use glam::{Mat4, Vec3, Vec4}; use sdl2::event::Event; use sdl2::keyboard::{Keycode, Scancode}; use std::collections::HashMap; use std::convert::TryInto; use std::ffi::{c_void, CStr, CString}; use std::fs::File; use std::io::Read; use std::path::Path; use std::time::{Duration, Instant}; mod iqm; use iqm::Model; pub fn load_small_file

(name: P) -> Vec where P: AsRef { let mut f = File::open (name).unwrap (); let len = f.metadata ().unwrap ().len (); if len > 1024 * 1024 { panic! ("File is too big"); } let mut data = vec! [0u8; len.try_into ().unwrap ()]; f.read (&mut data [..]).unwrap (); data } pub fn ugly_load_texture

(name: P) -> u32 where P: AsRef { let decoder = png::Decoder::new (File::open (name).unwrap ()); let (info, mut reader) = decoder.read_info ().unwrap (); // Allocate the output buffer. let mut buf = vec! [0; info.buffer_size ()]; // Read the next frame. Currently this function should only called once. // The default options reader.next_frame (&mut buf).unwrap (); unsafe { gl::BindTexture (gl::TEXTURE_2D, 1); gl::TexImage2D (gl::TEXTURE_2D, 0, gl::RGBA.try_into ().unwrap (), 1024, 1024, 0, gl::RGBA, gl::UNSIGNED_BYTE, &buf [0] as *const u8 as *const c_void); gl::TexParameteri (gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::CLAMP_TO_EDGE as i32); gl::TexParameteri (gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::CLAMP_TO_EDGE as i32); gl::TexParameteri (gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::NEAREST as i32); gl::TexParameteri (gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::NEAREST as i32); } 1 } const VERT_SHADER_SRC: &str = " #define lowp #define mediump #define highp #line 0 uniform highp mat4 uni_mvp; attribute highp vec4 attr_pos; attribute mediump vec2 attr_uv; attribute lowp vec3 attr_normal; varying mediump vec2 vary_uv; varying lowp vec3 vary_normal; void main (void) { vary_uv = attr_uv; lowp vec4 light_color = vec4 (1.0); vary_normal = attr_normal; gl_Position = uni_mvp * attr_pos; }"; const FRAG_SHADER_SRC: &str = " #define lowp #define mediump #define highp #line 0 uniform lowp sampler2D uni_texture; uniform lowp vec3 uni_albedo; uniform lowp vec3 uni_object_space_light; uniform lowp vec3 uni_min_bright; uniform lowp vec3 uni_min_albedo; //varying lowp vec4 vary_color; varying lowp vec3 vary_normal; varying mediump vec2 vary_uv; void main (void) { lowp vec3 normal = normalize (vary_normal); lowp vec3 albedo = uni_albedo * max (uni_min_albedo, texture2D (uni_texture, vary_uv).rgb); //lowp vec3 albedo = vec3 (vary_uv, 0.0); lowp float diffuse_factor = dot (normal, uni_object_space_light); lowp vec3 sun = max (diffuse_factor, 0.0) * vec3 (0.95, 0.9, 0.85); lowp vec3 sky = (diffuse_factor * 0.45 + 0.55) * vec3 (0.05, 0.1, 0.15); lowp vec3 diffuse_color = albedo * max (uni_min_bright, (sun + sky)); gl_FragColor = vec4 (sqrt (diffuse_color), 1.0); } "; pub struct ShaderObject { id: u32, } impl ShaderObject { pub fn id (&self) -> u32 { self.id } pub fn new (shader_type: u32, source: &str) -> Result { let id = unsafe { gl::CreateShader (shader_type) }; let sources = [ source.as_ptr () as *const i8, ]; let lengths = [ source.len ().try_into ().unwrap (), ]; let success = unsafe { gl::ShaderSource (id, sources.len ().try_into ().unwrap (), sources.as_ptr (), lengths.as_ptr ()); gl::CompileShader (id); let mut success = 0; gl::GetShaderiv (id, gl::COMPILE_STATUS, &mut success); success == 1 }; if success { Ok (ShaderObject { id, }) } else { let mut info_log = vec! [0u8; 4096]; let mut log_length = 0; unsafe { gl::GetShaderInfoLog (id, (info_log.len () - 1).try_into ().unwrap (), &mut log_length, info_log.as_mut_ptr () as *mut i8); } info_log.truncate (log_length.try_into ().unwrap ()); let info = String::from_utf8 (info_log).unwrap (); Err (info) } } } impl Drop for ShaderObject { fn drop (&mut self) { unsafe { gl::DeleteShader (self.id); } } } pub struct ShaderProgram { id: u32, } impl ShaderProgram { pub fn new (vert: &ShaderObject, frag: &ShaderObject) -> Result { let id = unsafe { gl::CreateProgram () }; unsafe { gl::AttachShader (id, vert.id ()); gl::AttachShader (id, frag.id ()); gl::LinkProgram (id); } let success = unsafe { let mut success = 0; gl::GetProgramiv (id, gl::LINK_STATUS, &mut success); success == 1 }; if success { Ok (ShaderProgram { id, }) } else { let mut info_log = vec! [0u8; 4096]; let mut log_length = 0; unsafe { gl::GetProgramInfoLog (id, (info_log.len () - 1).try_into ().unwrap (), &mut log_length, info_log.as_mut_ptr () as *mut i8); } info_log.truncate (log_length.try_into ().unwrap ()); let info = String::from_utf8 (info_log).unwrap (); Err (info) } } pub fn get_uniform_location (&self, name: &CStr) -> i32 { unsafe { gl::UseProgram (self.id); gl::GetUniformLocation (self.id, name.as_ptr ()) } } pub fn get_attribute_location (&self, name: &CStr) -> i32 { unsafe { gl::UseProgram (self.id); gl::GetAttribLocation (self.id, name.as_ptr ()) } } } impl Drop for ShaderProgram { fn drop (&mut self) { unsafe { gl::DeleteProgram (self.id); } } } fn enable_vertex_attrib_array (id: Option ) { match id { Some (id) => unsafe { gl::EnableVertexAttribArray (id); }, _ => (), } } unsafe fn vertex_attrib_pointer (id: Option , num_coords: i32, slice: &[u8]) { const FALSE_U8: u8 = 0; const FLOAT_SIZE: i32 = 4; match id { Some (id) => { gl::VertexAttribPointer (id, num_coords, gl::FLOAT, FALSE_U8, FLOAT_SIZE * num_coords, &slice [0] as *const u8 as *const c_void); }, _ => (), } } unsafe fn point_to_model ( attrs: &HashMap >, model: &Model ) { vertex_attrib_pointer (attrs ["pos"], 3, model.get_vertex_slice (0)); vertex_attrib_pointer (attrs ["uv"], 2, model.get_vertex_slice (1)); vertex_attrib_pointer (attrs ["normal"], 3, model.get_vertex_slice (2)); } const KEY_LEFT: usize = 0; const KEY_RIGHT: usize = KEY_LEFT + 1; const KEY_UP: usize = KEY_RIGHT + 1; const KEY_DOWN: usize = KEY_UP + 1; const KEY_COUNT: usize = KEY_DOWN + 1; struct ControllerState { keys: Vec , } impl ControllerState { pub fn from_sdl_keyboard (k: &sdl2::keyboard::KeyboardState) -> Self { let f = |c| k.is_scancode_pressed (c); Self { keys: vec! [ f (Scancode::Left), f (Scancode::Right), f (Scancode::Up), f (Scancode::Down), ], } } pub fn is_pressed (&self, code: usize) -> bool { self.keys [code] } } struct WorldState { azimuth: f32, altitude: f32, spin_speed: i32, } impl WorldState { pub fn new () -> Self { Self { azimuth: 0.0, altitude: 0.0, spin_speed: 0, } } pub fn step (&mut self, controller: &ControllerState) { const SPIN_RAMP_TIME: i32 = 30; let spin_f = 4.0 * self.spin_speed as f32 / SPIN_RAMP_TIME as f32; if controller.is_pressed (KEY_LEFT) { self.spin_speed = std::cmp::min (self.spin_speed + 1, SPIN_RAMP_TIME); self.azimuth += spin_f; } else if controller.is_pressed (KEY_RIGHT) { self.spin_speed = std::cmp::min (self.spin_speed + 1, SPIN_RAMP_TIME); self.azimuth -= spin_f; } else if controller.is_pressed (KEY_UP) { self.spin_speed = std::cmp::min (self.spin_speed + 1, SPIN_RAMP_TIME); self.altitude = f32::min (90.0, self.altitude + spin_f); } else if controller.is_pressed (KEY_DOWN) { self.spin_speed = std::cmp::min (self.spin_speed + 1, SPIN_RAMP_TIME); self.altitude = f32::max (-90.0, self.altitude - spin_f); } else { self.spin_speed = 0; } } } struct TimeStep { last_frame_time: Instant, // Milliseconds accum: u128, fps_num: u16, fps_den: u16, } impl TimeStep { pub fn new (fps_num: u16, fps_den: u16) -> Self { Self { last_frame_time: Instant::now (), accum: 0, fps_num, fps_den, } } // Automatically gets monotonic system time from Instant // If you need something fancy just rewrite this. // Returns: How many logics steps to run. Typically 0 or 1. pub fn step (&mut self) -> u16 { let frame_time = Instant::now (); let fps_num_128: u128 = self.fps_num.into (); let fps_den_128: u128 = self.fps_den.into (); self.accum += (frame_time - self.last_frame_time).as_millis () * fps_num_128; let mut result = 0; const MAX_FRAMES: u16 = 4; for _ in 0..MAX_FRAMES { if self.accum > fps_den_128 { result += 1; self.accum -= fps_den_128; } else { break; } } self.last_frame_time = frame_time; result } } unsafe fn draw_world (world: &WorldState) { } fn main () { let sdl_context = sdl2::init ().unwrap (); let video_subsystem = sdl_context.video ().unwrap (); let window = video_subsystem.window ("OpenGL? In my Rust?", 1280, 720) .position_centered () .opengl () .build () .unwrap (); gl::load_with (|s| { let result = video_subsystem.gl_get_proc_address (s) as *const _; //println! ("{:?}", result); result }); assert! (gl::ClearColor::is_loaded ()); let gl_ctx = window.gl_create_context ().unwrap (); window.gl_make_current (&gl_ctx).unwrap (); // I love how with Rust I can throw unwrap ()s everywhere // It's safer than C / C++'s default behavior of unchecked errors // It's more programmer-friendly and explicit than C#'s unchecked // exceptions that can appear almost anywhere at runtime with no // compile-time warning // And I'm still not actually checking errors - Just checkmarking // that I know where they are. let vert_shader = ShaderObject::new (gl::VERTEX_SHADER, VERT_SHADER_SRC).unwrap (); let frag_shader = ShaderObject::new (gl::FRAGMENT_SHADER, FRAG_SHADER_SRC).unwrap (); let shader_program = ShaderProgram::new (&vert_shader, &frag_shader).unwrap (); let unis: HashMap <_, _> = vec! [ "mvp", "object_space_light", "albedo", "min_albedo", "min_bright", "texture", ].iter () .map (|name| { let mut s = String::from ("uni_"); s.push_str (name); let c_str = CString::new (s.as_bytes ()).unwrap (); let loc = shader_program.get_uniform_location (&c_str); println! ("Uni {} --> {}", name, loc); (String::from (*name), loc) }) .collect (); let attrs: HashMap <_, Option > = vec! [ "pos", "uv", "normal", ].iter () .map (|name| { let mut s = String::from ("attr_"); s.push_str (name); let c_str = CString::new (s.as_bytes ()).unwrap (); let loc = shader_program.get_attribute_location (&c_str); let loc = match loc.try_into () { Ok (i) => Some (i), _ => { println! ("Attribute {} not found - Optimized out?", name); None }, }; (String::from (*name), loc) }) .collect (); let texture = ugly_load_texture ("sky.png"); let model_data = load_small_file ("pumpking.iqm"); let model = Model::from_slice (&model_data [..]); let sky_data = load_small_file ("sky-sphere.iqm"); let sky_model = Model::from_slice (&sky_data [..]); const FALSE_U8: u8 = 0; unsafe { enable_vertex_attrib_array (attrs ["pos"]); enable_vertex_attrib_array (attrs ["uv"]); enable_vertex_attrib_array (attrs ["normal"]); gl::Enable (gl::DEPTH_TEST); gl::Enable (gl::TEXTURE); let num_coords = 3; let stride = 4 * num_coords; } let mut time_step = TimeStep::new (60, 1000); let mut state = WorldState::new (); let mut event_pump = sdl_context.event_pump ().unwrap (); 'running: loop { let frames_to_do = time_step.step (); let controller = ControllerState::from_sdl_keyboard (&event_pump.keyboard_state ()); for _ in 0..frames_to_do { state.step (&controller); } let _mouse = event_pump.mouse_state (); for event in event_pump.poll_iter() { match event { Event::Quit {..} | Event::KeyDown { keycode: Some (Keycode::Escape), .. } => { break 'running }, _ => (), } } window.gl_make_current (&gl_ctx).unwrap (); let longitude = state.azimuth.to_radians (); let latitude = (state.altitude - 90.0).to_radians (); let proj_mat = Mat4::perspective_rh_gl (30.0f32.to_radians (), 1280.0 / 720.0, 0.5, 500.0); let model_mat = Mat4::from_translation (Vec3::from ((0.0, 0.0, -2.7 * 0.5))) ; let view_mat = proj_mat * Mat4::from_translation (Vec3::from ((0.0, 0.0, -8.0))) * Mat4::from_rotation_x (latitude) * Mat4::from_rotation_z (longitude) ; let mvp_mat = view_mat * model_mat; let sky_mvp_mat = view_mat * Mat4::from_scale (Vec3::from ((16.0, 16.0, 16.0))); let light = Vec3::from ((2.0, 0.0, 5.0)).normalize (); let object_space_light = model_mat.inverse () * Vec4::from ((light.x (), light.y (), light.z (), 0.0)); let orange = Vec3::from ((255.0 / 255.0, 154.0 / 255.0, 0.0 / 255.0)); let green = Vec3::from ((14.0 / 255.0, 127.0 / 255.0, 24.0 / 255.0)); let white = Vec3::from ((1.0, 1.0, 1.0)); let black = Vec3::from ((0.0, 0.0, 0.0)); let orange = orange * orange; let green = green * green; unsafe { gl::ClearColor (1.0f32, 1.0f32, 1.0f32, 1.0f32); gl::Clear (gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); gl::Disable (gl::CULL_FACE); gl::Uniform3fv (unis ["min_bright"], 1, &black as *const Vec3 as *const f32); gl::Uniform3fv (unis ["min_albedo"], 1, &white as *const Vec3 as *const f32); gl::UniformMatrix4fv (unis ["mvp"], 1, FALSE_U8, &mvp_mat as *const Mat4 as *const f32); gl::Uniform3fv (unis ["object_space_light"], 1, &object_space_light as *const Vec4 as *const f32); gl::Uniform3fv (unis ["albedo"], 1, &orange as *const Vec3 as *const f32); point_to_model (&attrs, &model); gl::DrawElements (gl::TRIANGLES, (model.meshes [0].num_triangles * 3) as i32, gl::UNSIGNED_INT, &model.get_index_slice (0) [0] as *const u8 as *const c_void); if true { gl::Uniform3fv (unis ["albedo"], 1, &green as *const Vec3 as *const f32); gl::DrawElements (gl::TRIANGLES, (model.meshes [1].num_triangles * 3) as i32, gl::UNSIGNED_INT, &model.get_index_slice (1) [0] as *const u8 as *const c_void); } let draw_sky = true; if draw_sky { //println! ("Drawing sky"); gl::UniformMatrix4fv (unis ["mvp"], 1, FALSE_U8, &sky_mvp_mat as *const Mat4 as *const f32); gl::Uniform3fv (unis ["albedo"], 1, &white as *const Vec3 as *const f32); gl::Uniform3fv (unis ["min_bright"], 1, &white as *const Vec3 as *const f32); gl::Uniform3fv (unis ["min_albedo"], 1, &black as *const Vec3 as *const f32); gl::Uniform1i (unis ["texture"], 0); point_to_model (&attrs, &sky_model); gl::DrawElements (gl::TRIANGLES, (sky_model.meshes [0].num_triangles * 3) as i32, gl::UNSIGNED_INT, &sky_model.get_index_slice (0) [0] as *const u8 as *const c_void); } } window.gl_swap_window (); ::std::thread::sleep (Duration::from_millis (15)); } } #[cfg (test)] mod tests { use super::*; #[test] pub fn iqm () { let data = load_small_file ("pumpking.iqm"); { let model = eader::from_slice (&data [..]).unwrap ().1; assert_eq! (model.fields [1], 90368); assert_eq! (model.fields [2], 0); assert_eq! (model.fields [consts::VERSION], 2); } { let model = Model::from_slice (&data [..]); println! ("{:?}", model.meshes); println! ("{:?}", model.vertexarrays); } } }