Draw the cubes using flat shading and fewer vertexes.
[mandelwow.git] / main.rs
1 extern crate mandelwow_lib;
2
3 extern crate cgmath;
4 #[macro_use(uniform)]
5 extern crate glium;
6 extern crate glutin;
7
8 use cgmath::{Euler, Matrix4, Rad, SquareMatrix, Vector3, Vector4, Zero};
9 use cgmath::conv::array4x4;
10 use glium::{DisplayBuild, Surface};
11 use glutin::ElementState::Pressed;
12 use glutin::Event::KeyboardInput;
13 use glutin::VirtualKeyCode;
14 use mandelwow_lib::*;
15 use std::f32::consts::PI;
16 use std::time::{Duration, Instant};
17
18 #[cfg(target_os = "emscripten")]
19 use std::os::raw::{c_int, c_void};
20
21 fn gl_info(display : &glium::Display) {
22     let version = *display.get_opengl_version();
23     let api = match version {
24         glium::Version(glium::Api::Gl, _, _) => "OpenGL",
25         glium::Version(glium::Api::GlEs, _, _) => "OpenGL ES"
26     };
27     println!("{} context verson: {}", api, display.get_opengl_version_string());
28 }
29
30 #[cfg(target_os = "emscripten")]
31 #[allow(non_camel_case_types)]
32 type em_callback_func = unsafe extern fn();
33 #[cfg(target_os = "emscripten")]
34 extern {
35     fn emscripten_set_main_loop(func : em_callback_func, fps : c_int, simulate_infinite_loop : c_int);
36 }
37
38 #[cfg(target_os = "emscripten")]
39 thread_local!(static MAIN_LOOP_CALLBACK: std::cell::RefCell<*mut c_void> =
40               std::cell::RefCell::new(std::ptr::null_mut()));
41
42 #[cfg(target_os = "emscripten")]
43 pub fn set_main_loop_callback<F>(callback : F) where F : FnMut() -> support::Action {
44     MAIN_LOOP_CALLBACK.with(|log| {
45             *log.borrow_mut() = &callback as *const _ as *mut c_void;
46             });
47
48     unsafe { emscripten_set_main_loop(wrapper::<F>, 0, 1); }
49
50     unsafe extern "C" fn wrapper<F>() where F : FnMut() -> support::Action {
51         MAIN_LOOP_CALLBACK.with(|z| {
52             let closure = *z.borrow_mut() as *mut F;
53             (*closure)();
54         });
55     }
56 }
57
58 #[cfg(not(target_os = "emscripten"))]
59 pub fn set_main_loop_callback<F>(callback : F) where F : FnMut() -> support::Action {
60     support::start_loop(callback);
61 }
62
63 fn main() {
64     let mut soundplayer = sound::start();
65
66     let display = glutin::WindowBuilder::new()
67         .with_dimensions(1280, 720)
68         .with_gl_profile(glutin::GlProfile::Core)
69         //.with_fullscreen(glutin::get_primary_monitor())
70         .with_depth_buffer(24)
71         .with_vsync()
72         .with_srgb(Some(true))
73         .with_title(format!("MandelWow"))
74         .build_glium()
75         //.build_glium_debug(glium::debug::DebugCallbackBehavior::PrintAll)
76         .unwrap();
77
78     gl_info(&display);
79
80     let text = text::Text::new(&display);
81     let mandelwow_program = mandelwow::program(&display);
82     let bounding_box_program = bounding_box::solid_fill_program(&display);
83     let shaded_program = shaded_cube::shaded_program(&display);
84
85     let mut camera = support::camera::CameraState::new();
86     let mut t: f32 = 0.0;
87     let mut pause = false;
88     let mut bounding_box_enabled = true;
89     let mut fullscreen = true;
90
91     // These are the bounds of the 3D Mandelwow section which we render in 3-space.
92     let bounds = Cube {
93         xmin: -2.0,
94         xmax:  0.7,
95         ymin: -1.0,
96         ymax:  1.0,
97         zmin: -1.1,
98         zmax:  1.1,
99     };
100     let mandelwow_bbox = bounding_box::BoundingBox::new(&display, &bounds, &bounding_box_program);
101     let shaded_cube = ShadedCube::new(&display, &shaded_program);
102
103     const SEA_XSIZE: usize = 24;
104     const SEA_ZSIZE: usize = 20;
105     let sea_xmin = -14.0f32;
106     let sea_xmax =  14.0f32;
107     let sea_y = -2.5;
108     let sea_zmin =  -2.0f32;
109     let sea_zmax = -26.0f32;
110     let sea_xstep = (sea_xmax - sea_xmin) / (SEA_XSIZE as f32);
111     let sea_zstep = (sea_zmax - sea_zmin) / (SEA_ZSIZE as f32);
112
113     let mut sea = [[Vector3::zero(); SEA_ZSIZE]; SEA_XSIZE];
114     for x in 0..SEA_XSIZE {
115         for z in 0..SEA_ZSIZE {
116             sea[x][z] = Vector3 {
117                 x: sea_xmin + (x as f32) * sea_xstep,
118                 y: sea_y,
119                 z: sea_zmin + (z as f32) * sea_zstep,
120             };
121         }
122     }
123
124     let mut frame_cnt = 0;
125     let mut last_report_time = Instant::now();
126     let mut last_report_frame_cnt = 0;
127     let mut accum_draw_time = Duration::new(0, 0);
128     let mut accum_idle_time = Duration::new(0, 0);
129
130     let mut last_hit = 0.0f32;
131     let mut hit_time = 0.0f32;
132     set_main_loop_callback(|| {
133         let new_hit = sound::hit_event(&mut soundplayer);
134         if new_hit != last_hit {
135             hit_time = t;
136         }
137         last_hit = new_hit;
138         let hit_delta = t - hit_time;
139         let hit_scale = 1. / (1. + hit_delta * hit_delta * 15.0) + 1.;
140
141         camera.update();
142         let perspview = camera.get_perspview();
143
144         // Vary the wow factor to slice the Mandelwow along its 4th dimension.
145         let wmin = -0.8;
146         let wmax =  0.8;
147         let wsize = wmax - wmin;
148         let wow = (((t * 0.7).sin() + 1.0) / 2.0) * wsize + wmin;
149
150         //println!("t={} w={:?} camera={:?}", t, w, camera.get_pos());
151
152         let time_before_swap = Instant::now();
153         let mut frame = display.draw();
154         frame.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);
155         let time_before_draw = Instant::now();
156
157         let rotation = Matrix4::from(
158             Euler { x: Rad(t.sin() / 3.), y: Rad(t.sin() / 2.), z: Rad(t / 1.5)});
159         let z_trans = -3.0;  // Send the model back a little bit so it fits the screen.
160         let scale =
161             Matrix4::from_diagonal(Vector4::new(hit_scale, hit_scale, hit_scale, 1.0));
162         let model2 =
163             Matrix4::from_translation(Vector3::unit_z() * z_trans) * rotation * scale;
164         let model = array4x4(model2);
165
166         // Draw the bounding box before the fractal, when the Z-buffer is still clear,
167         // so the lines behind the semi-translucent areas will be drawn.
168         if bounding_box_enabled {
169             let uniforms = uniform! {
170                 model: model,
171                 view:  camera.get_view(),
172                 perspective: camera.get_perspective(),
173             };
174             mandelwow_bbox.draw(&mut frame, &uniforms);
175         }
176
177         for x in 0..SEA_XSIZE {
178             for z in 0..SEA_ZSIZE {
179                 let wave = (((x as f32 / SEA_XSIZE as f32 * PI * 5.0 + t * 2.0)).sin() +
180                             ((z as f32 / SEA_ZSIZE as f32 * PI * 3.0 + t * 3.0)).sin()) * 0.3;
181                 let model = Matrix4::from_translation(sea[x][z] + Vector3 {x: 0., y: wave, z: 0.});
182                 let uniforms = uniform! {
183                     model: array4x4(model),
184                     perspview: perspview,
185                     col: [0., (1. - wave).abs() * 0.5,  wave.abs()],
186                 };
187                 shaded_cube.draw(&mut frame, &uniforms);
188             }
189         }
190
191         mandelwow::draw(&display, &mut frame, &mandelwow_program, model, &camera, &bounds, wow);
192
193         text.draw(&mut frame, &perspview);
194
195         frame.finish().unwrap();
196         let time_after_draw = Instant::now();
197
198         for ev in display.poll_events() {
199             match ev {
200                 glutin::Event::Closed |
201                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::Escape)) |
202                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::Q)) => {
203                     return support::Action::Stop
204                 },
205                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::B)) => {
206                     bounding_box_enabled ^= true;
207                 },
208                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::P)) => {
209                     pause ^= true;
210                 },
211                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::PageUp)) => {
212                     t += 0.01;
213                 },
214                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::PageDown)) => {
215                     t -= 0.01;
216                 },
217                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::F10)) => {
218                     screenshot(&display);
219                 },
220                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::F11)) => {
221                     fullscreen ^= true;
222                     if fullscreen {
223                         // Not implemented on Linux
224                         glutin::WindowBuilder::new()
225                             .with_fullscreen(glutin::get_primary_monitor())
226                             .with_depth_buffer(24)
227                             .rebuild_glium(&display).unwrap();
228                     } else {
229                         glutin::WindowBuilder::new()
230                             .rebuild_glium(&display).unwrap();
231                     }
232                 },
233                 ev => camera.process_input(&ev),
234             }
235         }
236
237         let now = Instant::now();
238         frame_cnt += 1;
239         accum_idle_time += time_before_draw - time_before_swap;
240         accum_draw_time += time_after_draw - time_before_draw;
241         if now - last_report_time > Duration::from_secs(5) {
242             fn millis(d : Duration) -> f32 {
243                 d.as_secs() as f32 * 1e3 + d.subsec_nanos() as f32 / 1e6
244             }
245             let frames_done = frame_cnt - last_report_frame_cnt;
246             let fps = frames_done as f32 / (now - last_report_time).as_secs() as f32;
247             let avg_draw_time = millis(accum_draw_time / frames_done);
248             let avg_idle_time = millis(accum_idle_time / frames_done);
249             println!("fps={:.1} draw={:.1}ms idle={:.1}ms", fps, avg_draw_time, avg_idle_time);
250
251             last_report_time = now;
252             last_report_frame_cnt = frame_cnt;
253             accum_draw_time = Duration::new(0, 0);
254             accum_idle_time = Duration::new(0, 0);
255         }
256
257         if !pause {
258             // Increment time
259             t += 0.01;
260         }
261
262         support::Action::Continue
263     });
264 }