A pile of gross hacks, but works in a browser so it's all justified.
[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 #[allow(non_camel_case_types)]
39 type em_callback_func = unsafe extern fn();
40 extern {
41     fn emscripten_set_main_loop(func : em_callback_func, fps : c_int, simulate_infinite_loop : c_int);
42 }
43
44 thread_local!(static MAIN_LOOP_CALLBACK: std::cell::RefCell<*mut c_void> =
45               std::cell::RefCell::new(std::ptr::null_mut()));
46
47 pub fn set_main_loop_callback<F>(callback : F) where F : FnMut() {
48     MAIN_LOOP_CALLBACK.with(|log| {
49             *log.borrow_mut() = &callback as *const _ as *mut c_void;
50             });
51
52     unsafe { emscripten_set_main_loop(wrapper::<F>, 0, 1); }
53
54     unsafe extern "C" fn wrapper<F>() where F : FnMut() {
55         MAIN_LOOP_CALLBACK.with(|z| {
56             let closure = *z.borrow_mut() as *mut F;
57             (*closure)();
58         });
59     }
60 }
61
62 fn main() {
63     let _soundplayer = sound::start();
64
65     let display = glutin::WindowBuilder::new()
66         .with_dimensions(1024, 768)
67         //.with_fullscreen(glutin::get_primary_monitor())
68         .with_depth_buffer(24)
69         .with_vsync()
70         .with_title(format!("MandelWow"))
71         .build_glium()
72         .unwrap();
73
74     let mandelwow_program = mandelwow::program(&display);
75     let bounding_box_program = bounding_box::solid_fill_program(&display);
76
77     let mut camera = support::camera::CameraState::new();
78     let mut t: f32 = 0.0;
79     let mut pause = false;
80     let mut bounding_box_enabled = true;
81     let mut fullscreen = true;
82
83     // These are the bounds of the 3D Mandelwow section which we render in 3-space.
84     let bounds = Cube {
85         xmin: -2.0,
86         xmax:  0.7,
87         ymin: -1.0,
88         ymax:  1.0,
89         zmin: -1.1,
90         zmax:  1.1,
91     };
92
93     //support::start_loop(|| {
94     set_main_loop_callback(|| {
95         camera.update();
96
97         if !pause {
98             // Increment time
99             t += 0.01;
100         }
101
102         // Vary the wow factor to slice the Mandelwow along its 4th dimension.
103         let wmin = -0.8;
104         let wmax =  0.8;
105         let wsize = wmax - wmin;
106         let wow = (((t * 0.7).sin() + 1.0) / 2.0) * wsize + wmin;
107
108         //println!("t={} w={:?} camera={:?}", t, w, camera.get_pos());
109
110         let mut frame = display.draw();
111         frame.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);
112
113         let rotation = cgmath::Matrix4::from(
114             Euler { x: Rad(t.sin() / 3.), y: Rad(t.sin() / 2.), z: Rad(t)});
115         let z_trans = -2.0;  // Send the model back a little bit so it fits the screen.
116         let model2 =
117             Matrix4::from_translation(Vector3::unit_z() * z_trans) * rotation;
118         let model = cgmath::conv::array4x4(model2);
119
120         // Draw the bounding box before the fractal, when the Z-buffer is still clear,
121         // so the lines behind the semi-translucent areas will be drawn.
122         if bounding_box_enabled {
123             let uniforms = uniform! {
124                 model: model,
125                 view:  camera.get_view(),
126                 perspective: camera.get_perspective(),
127             };
128             bounding_box::draw(&display, &mut frame, &bounding_box_program, &uniforms, &bounds);
129         }
130
131         mandelwow::draw(&display, &mut frame, &mandelwow_program, model, &camera, &bounds, wow);
132         frame.finish().unwrap();
133
134         for ev in display.poll_events() {
135             match ev {
136                 glutin::Event::Closed |
137                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::Escape)) |
138                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::Q)) => {
139                     //return support::Action::Stop
140                 },
141                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::B)) => {
142                     bounding_box_enabled ^= true;
143                 },
144                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::P)) => {
145                     pause ^= true;
146                 },
147                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::PageUp)) => {
148                     t += 0.01;
149                 },
150                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::PageDown)) => {
151                     t -= 0.01;
152                 },
153                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::F10)) => {
154                     screenshot(&display);
155                 },
156                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::F11)) => {
157                     fullscreen ^= true;
158                     if fullscreen {
159                         // Not implemented on Linux
160                         glutin::WindowBuilder::new()
161                             .with_fullscreen(glutin::get_primary_monitor())
162                             .with_depth_buffer(24)
163                             .rebuild_glium(&display).unwrap();
164                     } else {
165                         //glutin::WindowBuilder::new()
166                         //    .rebuild_glium(&display).unwrap();
167                     }
168                 },
169                 ev => camera.process_input(&ev),
170             }
171         }
172
173         //support::Action::Continue
174     });
175 }