Advertisement
Guest User

Untitled

a guest
Nov 18th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 8.80 KB | None | 0 0
  1. #![feature(duration_as_u128)]
  2.  
  3. #[macro_use]
  4. extern crate image;
  5. extern crate gl;
  6. extern crate winapi;
  7. extern crate glfw;
  8.  
  9. use std::ffi::CString;
  10. use std::ptr;
  11. use std::time::{SystemTime};
  12. use std::mem;
  13. use std::str;
  14. use std::sync::mpsc::Receiver;
  15.  
  16. use self::glfw::{Context, Key, Action};
  17.  
  18. use gl::types::{GLenum, GLuint, GLint, GLchar, GLboolean, GLfloat, GLsizeiptr};
  19.  
  20. //use ash::vk;
  21. //use ash::version::DeviceV1_0;
  22.  
  23. //bitbucket, sourcetree, trello
  24. //rustup default nightly
  25.  
  26. //gl_generator, khronos_api maybe not used
  27. //expand more things into several lines for readability
  28. //make some stuff inline
  29. //see if variables in fn are duplicated when returning or what and if there is a way to chane it if it is duplicating
  30.  
  31. //TODO make license
  32.  
  33. fn main() {
  34.  
  35.     println!("Ensuring safe installation:");
  36.     unsafe { ensure_safety(2 * 1024 * 1024, 4 * 1024 * 1024); }
  37.  
  38.     let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();
  39.     glfw.window_hint(glfw::WindowHint::ContextVersion(3, 3));
  40.     glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core));
  41.     #[cfg(target_os = "macos")]
  42.     glfw.window_hint(glfw::WindowHint::OpenGlForwardCompat(true));
  43.  
  44.     // glfw window creation
  45.     // --------------------
  46.     let (mut window, events) = glfw.create_window(800, 600, "Survival Game", glfw::WindowMode::Windowed)
  47.         .expect("Failed to create GLFW window");
  48.  
  49.     window.make_current();
  50.     window.set_key_polling(true);
  51.     window.set_framebuffer_size_polling(true);
  52.  
  53.     gl::load_with(|symbol| window.get_proc_address(symbol) as *const _);
  54.  
  55.     let vs = compile_shader(
  56.         "
  57.        #version 150
  58.        in vec2 position;
  59.  
  60.        void main() {
  61.            gl_Position = vec4(position, 0.0, 1.0);
  62.        }
  63.        ",
  64.         gl::VERTEX_SHADER
  65.     );
  66.     let fs = compile_shader(
  67.         "
  68.        #version 150
  69.        out vec4 out_color;
  70.  
  71.        void main() {
  72.            out_color = vec4(1.0, 1.0, 1.0, 1.0);
  73.        }
  74.        ",
  75.         gl::FRAGMENT_SHADER
  76.     );
  77.     let program = link_program(vs, fs);
  78.  
  79.     let mut vao = 0;
  80.     let mut vbo = 0;
  81.  
  82.     unsafe {
  83.         // Create Vertex Array Object
  84.         gl::GenVertexArrays(1, &mut vao);
  85.         gl::BindVertexArray(vao);
  86.  
  87.         // Create a Vertex Buffer Object and copy the vertex data to it
  88.         gl::GenBuffers(1, &mut vbo);
  89.         gl::BindBuffer(gl::ARRAY_BUFFER, vbo);
  90.         let vertex_data: [GLfloat; 6] = [0.0, 0.5, 0.5, -0.5, -0.5, -0.5];
  91.         gl::BufferData(
  92.             gl::ARRAY_BUFFER,
  93.             (vertex_data.len() * mem::size_of::<GLfloat>()) as GLsizeiptr,
  94.             mem::transmute(&vertex_data[0]),
  95.             gl::STATIC_DRAW,
  96.         );
  97.  
  98.         // Use shader program
  99.         gl::UseProgram(program);
  100.         gl::BindFragDataLocation(program, 0, CString::new("out_color").unwrap().as_ptr());
  101.  
  102.         // Specify the layout of the vertex data
  103.         let pos_attr = gl::GetAttribLocation(program, CString::new("position").unwrap().as_ptr());
  104.         gl::EnableVertexAttribArray(pos_attr as GLuint);
  105.         gl::VertexAttribPointer(
  106.             pos_attr as GLuint,
  107.             2,
  108.             gl::FLOAT,
  109.             gl::FALSE as GLboolean,
  110.             0,
  111.             ptr::null(),
  112.         );
  113.     }
  114.  
  115.     let mut frames = 0;
  116.     let mut start_time = SystemTime::now();
  117.     while !window.should_close() {
  118.         frames += 1;
  119.         if start_time.elapsed().unwrap().as_millis() >= 1000 {
  120.             println!("{}", frames);
  121.             frames = 0;
  122.             start_time = SystemTime::now();
  123.         }
  124.         //let start_time = SystemTime::now();
  125.  
  126.         process_events(&mut window, &events);
  127.  
  128.         unsafe {
  129.             gl::ClearColor(0.3, 0.3, 0.3, 1.0);
  130.             gl::Clear(gl::COLOR_BUFFER_BIT);
  131.  
  132.             for x in 0..10000 {
  133.                 gl::DrawArrays(gl::TRIANGLES, 0, 3);
  134.             }
  135.         }
  136.  
  137.         //println!("time: {}", start_time.elapsed().unwrap().as_nanos());
  138.         window.swap_buffers();
  139.         glfw.poll_events();
  140.     }
  141. }
  142.  
  143. fn process_events(window: &mut glfw::Window, events: &Receiver<(f64, glfw::WindowEvent)>) {
  144.     for (_, event) in glfw::flush_messages(events) {
  145.         match event {
  146.             glfw::WindowEvent::FramebufferSize(width, height) => {
  147.                 // make sure the viewport matches the new window dimensions; note that width and
  148.                 // height will be significantly larger than specified on retina displays.
  149.                 unsafe { gl::Viewport(0, 0, width, height) }
  150.             }
  151.             glfw::WindowEvent::Key(Key::Escape, _, Action::Press, _) => window.set_should_close(true),
  152.             _ => {}
  153.         }
  154.     }
  155. }
  156.  
  157. fn compile_shader(
  158.     src: &str,
  159.     ty: GLenum,
  160. ) -> GLuint {
  161.  
  162.     let shader;
  163.     unsafe {
  164.         shader = gl::CreateShader(ty);
  165.         // Attempt to compile the shader
  166.         let c_str = CString::new(src.as_bytes()).unwrap();
  167.         gl::ShaderSource(shader, 1, &c_str.as_ptr(), ptr::null());
  168.         gl::CompileShader(shader);
  169.  
  170.         // Get the compile status
  171.         let mut status = gl::FALSE as GLint;
  172.         gl::GetShaderiv(shader, gl::COMPILE_STATUS, &mut status);
  173.  
  174.         // Fail on error
  175.         if status != (gl::TRUE as GLint) {
  176.             let mut len = 0;
  177.             gl::GetShaderiv(shader, gl::INFO_LOG_LENGTH, &mut len);
  178.             let mut buf = Vec::with_capacity(len as usize);
  179.             buf.set_len((len as usize) - 1); // subtract 1 to skip the trailing null character
  180.             gl::GetShaderInfoLog(
  181.                 shader,
  182.                 len,
  183.                 ptr::null_mut(),
  184.                 buf.as_mut_ptr() as *mut GLchar,
  185.             );
  186.             panic!(
  187.                 "{}",
  188.                 str::from_utf8(&buf)
  189.                     .ok()
  190.                     .expect("ShaderInfoLog not valid utf8")
  191.             );
  192.         }
  193.     }
  194.     shader
  195. }
  196.  
  197. fn link_program(
  198.     vs: GLuint,
  199.     fs: GLuint,
  200. ) -> GLuint {
  201.     unsafe {
  202.         let program = gl::CreateProgram();
  203.         gl::AttachShader(program, vs);
  204.         gl::AttachShader(program, fs);
  205.         gl::LinkProgram(program);
  206.         // Get the link status
  207.         let mut status = gl::FALSE as GLint;
  208.         gl::GetProgramiv(program, gl::LINK_STATUS, &mut status);
  209.  
  210.         // Fail on error
  211.         if status != (gl::TRUE as GLint) {
  212.             let mut len: GLint = 0;
  213.             gl::GetProgramiv(program, gl::INFO_LOG_LENGTH, &mut len);
  214.             let mut buf = Vec::with_capacity(len as usize);
  215.             buf.set_len((len as usize) - 1); // subtract 1 to skip the trailing null character
  216.             gl::GetProgramInfoLog(
  217.                 program,
  218.                 len,
  219.                 ptr::null_mut(),
  220.                 buf.as_mut_ptr() as *mut GLchar,
  221.             );
  222.             panic!(
  223.                 "{}",
  224.                 str::from_utf8(&buf)
  225.                     .ok()
  226.                     .expect("ProgramInfoLog not valid utf8")
  227.             );
  228.         }
  229.         program
  230.     }
  231. }
  232.  
  233. unsafe fn ensure_safety(min_ram: u64,
  234.                         rec_ram: u64,
  235. ) {
  236.  
  237.     //DEPENDENCY CHECKS
  238.     //Check for OpenGL?
  239.  
  240.     //SPECIFICATION CHECKS7
  241.     let mut memory_kb: u64 = 0;
  242.     winapi::um::sysinfoapi::GetPhysicallyInstalledSystemMemory(&mut memory_kb as *mut u64);
  243.     if memory_kb < min_ram {
  244.         display_warning_with_box("Memory Warning", &format!("Your system RAM is well below the minimum requirements. It is recommended that you have at least {}GB of RAM. Your system only has {}GB. The game will either fail to run or you will experience severely degraded performance.", min_ram / (1024 * 1024), memory_kb / (1024 * 1024)));
  245.     } else if memory_kb < rec_ram {
  246.         display_warning_with_box("Memory Warning", &format!("Your system RAM meets the minimum requirements but is below the recommended specifications. {}GB of RAM is recommended but your system has {}GB. The game may not run at optimal performance.", rec_ram / (1024 * 1024), memory_kb / (1024 * 1024)));
  247.     } else {
  248.         println!("{}gb of RAM detected. Recommended requirements are met!", memory_kb / (1024 * 1024))
  249.     }
  250. }
  251.  
  252. unsafe fn display_error_with_box(title: &str,
  253.                                  message: &str,
  254. ) -> ! {
  255.  
  256.     //might be a problem with the warning thing
  257.     winapi::um::winuser::MessageBoxA(ptr::null_mut(), CString::new(message).unwrap().as_ptr(), CString::new(title).unwrap().as_ptr(), winapi::um::winuser::MB_OK | winapi::um::winuser::MB_ICONERROR);
  258.     panic!("Error: {}", message);
  259. }
  260.  
  261. unsafe fn display_warning_with_box(title: &str,
  262.                                    message: &str,
  263. ) {
  264.  
  265.     winapi::um::winuser::MessageBoxA(ptr::null_mut(), CString::new(message).unwrap().as_ptr(), CString::new(title).unwrap().as_ptr(), winapi::um::winuser::MB_OK | winapi::um::winuser::MB_ICONWARNING);
  266.     println!("Warning: {}", message);
  267. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement