Switch to WebGL 2.
[mandelwow.git] / main.rs
1 extern crate cgmath;
2 #[macro_use(uniform,program,implement_vertex)]
3 extern crate glium;
4 extern crate glutin;
5 extern crate image;
6 #[cfg(not(target_os = "emscripten"))]
7 extern crate libxm;
8 #[cfg(not(target_os = "emscripten"))]
9 extern crate sdl2;
10
11 //use cgmath::prelude::*;
12 use cgmath::{Euler, Matrix4, Rad, Vector3};
13 use cube::Cube;
14 use glium::{DisplayBuild, Surface};
15 use glutin::ElementState::Pressed;
16 use glutin::Event::KeyboardInput;
17 use glutin::VirtualKeyCode;
18 use std::os::raw::{c_int, c_void};
19
20 mod bounding_box;
21 mod cube;
22 mod mandelwow;
23 #[cfg(not(target_os = "emscripten"))]
24 mod sound;
25 #[cfg(target_os = "emscripten")]
26 #[path = "sound_emscripten.rs"]
27 mod sound;
28 mod support;
29
30 fn screenshot(display : &glium::Display) {
31     let image: glium::texture::RawImage2d<u8> = display.read_front_buffer();
32     let image = image::ImageBuffer::from_raw(image.width, image.height, image.data.into_owned()).unwrap();
33     let image = image::DynamicImage::ImageRgba8(image).flipv();
34     let mut output = std::fs::File::create(&std::path::Path::new("screenshot.png")).unwrap();
35     image.save(&mut output, image::ImageFormat::PNG).unwrap();
36 }
37
38 fn gl_info(display : &glium::Display) {
39     let version = *display.get_opengl_version();
40     let api = match version {
41         glium::Version(glium::Api::Gl, _, _) => "OpenGL",
42         glium::Version(glium::Api::GlEs, _, _) => "OpenGL ES"
43     };
44     println!("{} context verson: {}", api, display.get_opengl_version_string());
45 }
46
47 #[allow(non_camel_case_types)]
48 type em_callback_func = unsafe extern fn();
49 extern {
50     fn emscripten_set_main_loop(func : em_callback_func, fps : c_int, simulate_infinite_loop : c_int);
51 }
52
53 thread_local!(static MAIN_LOOP_CALLBACK: std::cell::RefCell<*mut c_void> =
54               std::cell::RefCell::new(std::ptr::null_mut()));
55
56 pub fn set_main_loop_callback<F>(callback : F) where F : FnMut() {
57     MAIN_LOOP_CALLBACK.with(|log| {
58             *log.borrow_mut() = &callback as *const _ as *mut c_void;
59             });
60
61     unsafe { emscripten_set_main_loop(wrapper::<F>, 0, 1); }
62
63     unsafe extern "C" fn wrapper<F>() where F : FnMut() {
64         MAIN_LOOP_CALLBACK.with(|z| {
65             let closure = *z.borrow_mut() as *mut F;
66             (*closure)();
67         });
68     }
69 }
70
71 fn main() {
72     let _soundplayer = sound::start();
73
74     let display = glutin::WindowBuilder::new()
75         .with_dimensions(600, 600)
76         //.with_fullscreen(glutin::get_primary_monitor())
77         .with_depth_buffer(24)
78         .with_vsync()
79         .with_title(format!("MandelWow"))
80         .build_glium()
81         .unwrap();
82
83     gl_info(&display);
84
85     let mandelwow_program = mandelwow::program(&display);
86     let bounding_box_program = bounding_box::solid_fill_program(&display);
87
88     let mut camera = support::camera::CameraState::new();
89     let mut t: f32 = 0.0;
90     let mut pause = false;
91     let mut bounding_box_enabled = true;
92     let mut fullscreen = true;
93
94     // These are the bounds of the 3D Mandelwow section which we render in 3-space.
95     let bounds = Cube {
96         xmin: -2.0,
97         xmax:  0.7,
98         ymin: -1.0,
99         ymax:  1.0,
100         zmin: -1.1,
101         zmax:  1.1,
102     };
103
104     //support::start_loop(|| {
105     set_main_loop_callback(|| {
106         camera.update();
107
108         if !pause {
109             // Increment time
110             t += 0.01;
111         }
112
113         // Vary the wow factor to slice the Mandelwow along its 4th dimension.
114         let wmin = -0.8;
115         let wmax =  0.8;
116         let wsize = wmax - wmin;
117         let wow = (((t * 0.7).sin() + 1.0) / 2.0) * wsize + wmin;
118
119         //println!("t={} w={:?} camera={:?}", t, w, camera.get_pos());
120
121         let mut frame = display.draw();
122         frame.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);
123
124         let rotation = cgmath::Matrix4::from(
125             Euler { x: Rad(t.sin() / 3.), y: Rad(t.sin() / 2.), z: Rad(t)});
126         let z_trans = -2.0;  // Send the model back a little bit so it fits the screen.
127         let model2 =
128             Matrix4::from_translation(Vector3::unit_z() * z_trans) * rotation;
129         let model = cgmath::conv::array4x4(model2);
130
131         // Draw the bounding box before the fractal, when the Z-buffer is still clear,
132         // so the lines behind the semi-translucent areas will be drawn.
133         if bounding_box_enabled {
134             let uniforms = uniform! {
135                 model: model,
136                 view:  camera.get_view(),
137                 perspective: camera.get_perspective(),
138             };
139             bounding_box::draw(&display, &mut frame, &bounding_box_program, &uniforms, &bounds);
140         }
141
142         mandelwow::draw(&display, &mut frame, &mandelwow_program, model, &camera, &bounds, wow);
143         frame.finish().unwrap();
144
145         for ev in display.poll_events() {
146             match ev {
147                 glutin::Event::Closed |
148                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::Escape)) |
149                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::Q)) => {
150                     //return support::Action::Stop
151                 },
152                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::B)) => {
153                     bounding_box_enabled ^= true;
154                 },
155                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::P)) => {
156                     pause ^= true;
157                 },
158                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::PageUp)) => {
159                     t += 0.01;
160                 },
161                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::PageDown)) => {
162                     t -= 0.01;
163                 },
164                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::F10)) => {
165                     screenshot(&display);
166                 },
167                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::F11)) => {
168                     fullscreen ^= true;
169                     if fullscreen {
170                         // Not implemented on Linux
171                         glutin::WindowBuilder::new()
172                             .with_fullscreen(glutin::get_primary_monitor())
173                             .with_depth_buffer(24)
174                             .rebuild_glium(&display).unwrap();
175                     } else {
176                         //glutin::WindowBuilder::new()
177                         //    .rebuild_glium(&display).unwrap();
178                     }
179                 },
180                 ev => camera.process_input(&ev),
181             }
182         }
183
184         //support::Action::Continue
185     });
186 }