A simple map viewer

context.rs 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. use glutin;
  2. pub(crate) mod gl {
  3. pub use self::Gles2 as Gl;
  4. include!(concat!(env!("OUT_DIR"), "/gles_bindings.rs"));
  5. }
  6. #[derive(Clone)]
  7. pub struct Context {
  8. pub(crate) gl: gl::Gl,
  9. }
  10. impl ::std::fmt::Debug for Context {
  11. fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
  12. let version = unsafe {
  13. let data = ::std::ffi::CStr::from_ptr(self.gl.GetString(gl::VERSION) as *const _).to_bytes().to_vec();
  14. String::from_utf8(data).unwrap_or_else(|_| "".into())
  15. };
  16. write!(f, "Context {{ version: {:?} }}", version)
  17. }
  18. }
  19. macro_rules! check_gl_errors {
  20. ($cx:expr) => (
  21. $cx.check_errors(file!(), line!());
  22. )
  23. }
  24. impl Context {
  25. pub fn from_window(window: &glutin::Window) -> Context {
  26. let gl = gl::Gl::load_with(|ptr| window.get_proc_address(ptr) as *const _);
  27. Context {gl: gl}
  28. }
  29. pub fn gl_version(&self) -> String {
  30. unsafe {
  31. let data = ::std::ffi::CStr::from_ptr(self.gl.GetString(gl::VERSION) as *const _).to_bytes().to_vec();
  32. String::from_utf8(data).unwrap_or_else(|_| "".into())
  33. }
  34. }
  35. pub fn max_texture_size(&self) -> i32 {
  36. unsafe {
  37. let mut size = 0;
  38. self.gl.GetIntegerv(gl::MAX_TEXTURE_SIZE, &mut size as *mut _);
  39. size
  40. }
  41. }
  42. pub unsafe fn check_errors(&self, file: &str, line: u32) {
  43. loop {
  44. match self.gl.GetError() {
  45. gl::NO_ERROR => break,
  46. gl::INVALID_VALUE => {
  47. println!("{}:{}, invalid value error", file, line);
  48. },
  49. gl::INVALID_ENUM => {
  50. println!("{}:{}, invalid enum error", file, line);
  51. },
  52. gl::INVALID_OPERATION => {
  53. println!("{}:{}, invalid operation error", file, line);
  54. },
  55. gl::INVALID_FRAMEBUFFER_OPERATION => {
  56. println!("{}:{}, invalid framebuffer operation error", file, line);
  57. },
  58. gl::OUT_OF_MEMORY => {
  59. println!("{}:{}, out of memory error", file, line);
  60. },
  61. x => {
  62. println!("{}:{}, unknown error {}", file, line, x);
  63. },
  64. }
  65. }
  66. }
  67. pub fn clear_color(&self, color: (f32, f32, f32, f32)) {
  68. unsafe {
  69. self.gl.ClearColor(color.0, color.1, color.2, color.3);
  70. self.gl.Clear(gl::COLOR_BUFFER_BIT);
  71. }
  72. }
  73. }