Lots of changes, first working version.
[mandelwow.git] / mandel.rs
1 #[macro_use]
2
3 extern crate glium;
4 extern crate glutin;
5
6 use glium::DisplayBuild;
7 use glium::Surface;
8 use glium::index::PrimitiveType;
9 use glium::index::IndexBuffer;
10
11 mod support;
12
13 #[derive(Copy, Clone)]
14 struct Vertex {
15     position: [f32; 3],
16     color: [f32; 3],
17 }
18 implement_vertex!(Vertex, position, color);
19
20 #[derive(Copy, Clone)]
21 struct Cube {
22     xmin: f32,
23     ymin: f32,
24     zmin: f32,
25     xmax: f32,
26     ymax: f32,
27     zmax: f32,
28 }
29
30 /*
31 fn mand(cx: f32, cy: f32) -> [f32; 3] {
32     let maxiter = 64;
33     let mut iter = maxiter;
34     let mut zx = cx;
35     let mut zy = cy;
36     while iter > 0 {
37         let zx2 = zx * zx;
38         let zy2 = zy * zy;
39         if zx2 + zy2 > 4.0 {
40             return [iter as f32 / maxiter as f32, 1.0, 1.0];
41         }
42         zy = zx * zy * 2.0 + cy;
43         zx = zx2 - zy2 + cx;
44         iter -= 1;
45     }
46
47     [0.0, 0.0, 0.0]
48 }
49 */
50
51 fn mandelwow_program(display: &glium::Display) -> glium::Program {
52     return program!(display,
53         140 => {
54             vertex: r#"
55                 #version 140
56                 uniform mat4 perspective;
57                 uniform mat4 view;
58                 uniform mat4 model;
59                 uniform vec2 z0;
60                 in vec3 position;
61                 out vec2 c;
62                 out vec2 z;
63
64                 void main() {
65                     mat4 modelview = view * model;
66                     gl_Position = perspective * modelview * vec4(position, 1.0);
67                     c = vec2(position.x, position.y);
68                     z = vec2(z0.x, z0.y);
69                 }
70             "#,
71
72             fragment: r#"
73                 #version 140
74                 precision highp float;
75                 in vec2 c;
76                 in vec2 z;
77                 out vec4 f_color;
78
79                 void main() {
80                     float zx = z.x;
81                     float zy = z.y;
82                     int maxiter = 64;
83                     int iter = maxiter;
84                     while (iter > 0) {
85                         float zx2 = zx * zx;
86                         float zy2 = zy * zy;
87                         if (zx2 * zy2 > 4.0) {
88                           float index = 1.0 - float(iter) / float(maxiter);
89                           f_color = vec4(index, index * 0.5, index, index * 0.5);
90                           return;
91                         }
92                         zy = zx * zy * 2.0 + c.y;
93                         zx = zx2 - zy2 + c.x;
94                         iter -= 1;
95                     }
96                     f_color = vec4((sin(z.y) + 1.0) / 2,
97                                    (sin(c.y) + 1.0) / 2,
98                                    (sin(c.x) + 1.0) / 2,
99                                    1.0);
100                 }
101             "#
102         }).unwrap();
103 }
104
105 fn solid_fill_program(display: &glium::Display) -> glium::Program {
106     let vertex_shader_src = r#"
107         #version 140
108         in vec3 position;
109         uniform mat4 perspective;
110         uniform mat4 view;
111         uniform mat4 model;
112
113         void main() {
114             mat4 modelview = view * model;
115             gl_Position = perspective * modelview * vec4(position, 1.0);
116         }
117     "#;
118
119     let fragment_shader_src = r#"
120         #version 140
121
122         out vec4 color;
123
124         void main() {
125             color = vec4(1.0, 1.0, 1.0, 1.0);
126         }
127     "#;
128
129     return glium::Program::from_source(display,
130                                        vertex_shader_src,
131                                        fragment_shader_src,
132                                        None).unwrap();
133 }
134
135 fn bounding_box<U>(display: &glium::Display,
136                    frame: &mut glium::Frame,
137                    program: &glium::Program,
138                    uniforms: &U,
139                    cube: &Cube) where U: glium::uniforms::Uniforms {
140     // Draw the bounding box
141
142     #[derive(Copy, Clone)]
143     struct Vertex { position: [f32; 3] }
144     implement_vertex!(Vertex, position);
145
146     let cube = [
147         Vertex { position: [cube.xmin, cube.ymin, cube.zmin] },
148         Vertex { position: [cube.xmax, cube.ymin, cube.zmin] },
149         Vertex { position: [cube.xmax, cube.ymax, cube.zmin] },
150         Vertex { position: [cube.xmin, cube.ymax, cube.zmin] },
151         Vertex { position: [cube.xmin, cube.ymin, cube.zmax] },
152         Vertex { position: [cube.xmax, cube.ymin, cube.zmax] },
153         Vertex { position: [cube.xmax, cube.ymax, cube.zmax] },
154         Vertex { position: [cube.xmin, cube.ymax, cube.zmax] },
155     ];
156     let vb = glium::VertexBuffer::new(display, &cube).unwrap();
157
158     let front_indices = IndexBuffer::new(display, PrimitiveType::LineLoop,
159                                          &[0, 1, 2, 3u16]).unwrap();
160     frame.draw(&vb, &front_indices, program, uniforms, &Default::default()).unwrap();
161
162     let back_indices = IndexBuffer::new(display, PrimitiveType::LineLoop,
163                                         &[4, 5, 6, 7u16]).unwrap();
164     frame.draw(&vb, &back_indices, program, uniforms, &Default::default()).unwrap();
165
166     let sides_indices = IndexBuffer::new(display, PrimitiveType::LinesList,
167                                          &[0, 4, 1, 5, 2, 6, 3, 7u16]).unwrap();
168     frame.draw(&vb, &sides_indices, program, uniforms, &Default::default()).unwrap();
169 }
170
171 fn mandel<U>(display: &glium::Display,
172           frame: &mut glium::Frame,
173           program: &glium::Program,
174           uniforms: &U,
175           z: [f32; 2]) where U: glium::uniforms::Uniforms {
176     let xmin = -2.0;
177     let xmax =  0.7;
178     let ymin = -1.0;
179     let ymax =  1.0;
180     let zmin = -1.2;
181     let zmax =  1.2;
182     let width = xmax - xmin;
183     let height = ymax - ymin;
184     let xres: usize = 1;
185     let yres: usize = 1;
186     let xstep = width / (xres as f32);
187     let ystep = height / (yres as f32);
188     let vb_size = (xres * 2 + 4) * yres;
189     let mut v : Vec<Vertex> = Vec::with_capacity(vb_size);
190     v.resize(vb_size, Vertex { position: [0.0, 0.0, -1.0], color: [0.0, 0.0, 0.0] });
191     let mut i: usize = 0;
192     let mut vy = ymin;
193     let vz = z[1];
194     for _ in 0..yres {
195         let mut vx = xmin;
196         let c = [0.0, 0.0, 1.0];
197         v[i] = Vertex { position: [vx, vy+ystep, vz], color: c }; i += 1;
198         v[i] = Vertex { position: [vx, vy,       vz], color: c }; i += 1;
199         for _ in 0..xres {
200             //let c = mand(vx, vy);
201             v[i] = Vertex { position: [vx+xstep, vy+ystep, vz], color: c }; i += 1;
202             v[i] = Vertex { position: [vx+xstep, vy,       vz], color: c }; i += 1;
203             vx += xstep;
204         }
205         v[i] = Vertex { position: [vx,   vy, vz], color: c }; i += 1;
206         v[i] = Vertex { position: [xmin, vy, vz], color: c }; i += 1;
207         vy += ystep;
208     }
209
210     //let vb = glium::VertexBuffer::empty_persistent(display, width*height*3).unwrap();
211     let vb = glium::VertexBuffer::new(display, &v).unwrap();
212
213     let indices = glium::index::NoIndices(glium::index::PrimitiveType::TriangleStrip);
214     //let indices = glium::index::NoIndices(glium::index::PrimitiveType::LineStrip);
215     //let indices = glium::IndexBuffer::new(display, PrimitiveType::TrianglesList,
216     //                                      &[0u16, 1, 2]).unwrap();
217
218     let params = glium::DrawParameters {
219         depth: glium::Depth {
220             test: glium::draw_parameters::DepthTest::IfLess,
221             write: true,
222             .. Default::default()
223         },
224         blend: glium::Blend::alpha_blending(),
225         .. Default::default()
226     };
227
228     frame.draw(&vb, &indices, program, uniforms, &params).unwrap();
229 }
230
231 fn mandelwow(display: &glium::Display,
232              mut frame: &mut glium::Frame,
233              program: &glium::Program,
234              model: [[f32; 4]; 4],
235              camera: &support::camera::CameraState,
236              cube: &Cube,
237              mandel_w: f32) {
238     let mut z0 = [mandel_w, 0f32];
239     let zres = 50;
240     let zmin = cube.zmin;
241     let zmax = cube.zmax;
242     let zstep = (zmax - zmin) / zres as f32;
243     let mut zy = zmin;
244     for _ in 0..zres {
245         z0[1] = zy;
246         zy += zstep;
247
248         let uniforms = uniform! {
249             z0: z0,
250             model: model,
251             view:  camera.get_view(),
252             perspective: camera.get_perspective(),
253         };
254
255         mandel(&display, &mut frame, &program, &uniforms, z0);
256     }
257 }
258
259 fn main() {
260     let display = glium::glutin::WindowBuilder::new()
261         .with_dimensions(1024, 768)
262         .with_depth_buffer(24)
263         .with_title(format!("MandelWow"))
264         .build_glium()
265         .unwrap();
266
267     let mut camera = support::camera::CameraState::new();
268     let mut t: f32 = 0.0;
269     let mut z = [ 0.0, 0.0f32 ];
270     let mut pause = false;
271
272     support::start_loop(|| {
273         camera.update();
274
275         if !pause {
276             // Increment time
277             t += 0.01;
278         }
279
280         // Compute a sine wave slicing the Mandelwow along its 4th dimension.
281         let wmin = -0.8;
282         let wmax =  0.8;
283         let wsize = wmax - wmin;
284         let mandel_w = ((t.sin() + 1.0) / 2.0) * wsize + wmin;
285
286         //println!("t={} z={:?} camera={:?}", t, z, camera.get_pos());
287
288         let mut frame = display.draw();
289         frame.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);
290
291         let z_trans = -2.0;  // How far back to move the model
292         let model = [
293             [ t.cos(),  t.sin(),  0.0,     0.0],
294             [-t.sin(),  t.cos(),  0.0,     0.0],
295             [     0.0,  0.0,      1.0,     0.0],
296             [     0.0,  0.0,      z_trans, 1.0f32]
297         ];
298
299         let program = mandelwow_program(&display);
300         let bounding_box_program = solid_fill_program(&display);
301
302         let bounds = Cube {
303             xmin: -2.0,
304             xmax:  0.7,
305             ymin: -1.0,
306             ymax:  1.0,
307             zmin: -1.2,
308             zmax:  1.2,
309         };
310
311         mandelwow(&display, &mut frame, &program, model, &camera, &bounds, mandel_w);
312
313         let uniforms = uniform! {
314             model: model,
315             view:  camera.get_view(),
316             perspective: camera.get_perspective(),
317         };
318         bounding_box(&display, &mut frame, &bounding_box_program, &uniforms, &bounds);
319
320         for ev in display.poll_events() {
321             match ev {
322                 glium::glutin::Event::Closed => {
323                     frame.finish().unwrap();
324                     return support::Action::Stop
325                 },
326                 glutin::Event::KeyboardInput(glutin::ElementState::Pressed, _, Some(glutin::VirtualKeyCode::PageUp)) => {
327                     t += 0.01;
328                 },
329                 glutin::Event::KeyboardInput(glutin::ElementState::Pressed, _, Some(glutin::VirtualKeyCode::PageDown)) => {
330                     t -= 0.01;
331                 },
332                 glutin::Event::KeyboardInput(glutin::ElementState::Pressed, _, Some(glutin::VirtualKeyCode::P)) => {
333                     pause ^= true;
334                 },
335                 ev => camera.process_input(&ev),
336             }
337         }
338
339         frame.finish().unwrap();
340         support::Action::Continue
341     });
342 }