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