1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::mpsc::Receiver;
use std::time::{Duration, Instant};

use anyhow::{Context, Result};
use crevice::std430::{AsStd430, Std430};
use egui::{FontDefinitions, Style};
use egui_wgpu_backend::ScreenDescriptor;
use egui_winit_platform::{Platform, PlatformDescriptor};
use image::{ImageBuffer, ImageFormat, Rgba};
use log::{debug, error, info};
use mint::Vector2;
use notify::{watcher, DebouncedEvent, RecommendedWatcher, RecursiveMode, Watcher};
use rfd::FileDialog;
use wgpu::PowerPreference;
use winit::event::{Event, MouseScrollDelta, VirtualKeyCode, WindowEvent};
use winit::event_loop::{ControlFlow, EventLoop};
use winit::window::Window;

use crate::gui::Gui;
use crate::renderer::Renderer;
use crate::shader::Shader;
use crate::shader_loader::ShaderLoader;

mod gui;
pub mod preprocessor;
pub mod renderer;
pub mod shader;
pub mod shader_loader;

#[derive(Debug)]
pub enum Command {
    /// Open a pick file dialog and load a shader
    Load,
    /// Reload the shader from disk
    Reload,
    /// Watch the shader for fs changes
    Watch,
    /// Unwatch the shader
    Unwatch,
    /// Reset the globals to their default
    ResetGlobals,
    /// Reset the shader params to their default
    ResetParams,
    /// Export a render of the current shader
    ExportImage,
    Pause,
    Resume,
    /// Terminate the application
    Exit,
}

/// The globals we pass to the fragment shader
#[derive(AsStd430, Clone)]
pub struct Globals {
    /// Window resolution
    pub resolution: Vector2<u32>,
    /// Mouse pos
    pub mouse: Vector2<u32>,
    /// Mouse wheel
    pub mouse_wheel: f32,
    /// Draw area width/height ratio
    pub ratio: f32,
    /// Current running time in sec
    pub time: f32,
    /// Number of frame
    pub frame: u32,
}

impl Globals {
    pub fn reset(&mut self) {
        self.frame = 0;
        self.time = 0.0;
        self.mouse_wheel = 0.0;
    }
}

pub struct Settings {
    pub target_framerate: Duration,
    pub mouse_wheel_step: f32,
}

pub struct ExportData {
    pub size: Vector2<u32>,
    pub format: ImageFormat,
    pub path: PathBuf,
}

impl Default for ExportData {
    fn default() -> Self {
        Self {
            size: Vector2::from([2048, 2048]),
            format: ImageFormat::Png,
            path: PathBuf::from_str("render.png").unwrap(),
        }
    }
}

pub struct Nuance {
    /// The main window
    window: Window,
    gui: Gui,
    /// App settings
    settings: Settings,

    /// The current loaded shader
    shader: Option<Shader>,
    /// Shader compiler and transpiler
    shader_loader: ShaderLoader,
    watcher: RecommendedWatcher,
    /// Receiver for watcher events
    watcher_rx: Receiver<DebouncedEvent>,
    watching: bool,

    renderer: Renderer,
    /// Parameters passed to shaders
    globals: Globals,

    /// The instant at which the simulation started
    /// Reset on simulation restart and on unpause
    sim_start: Instant,
    /// Accumulated time since simulation start, to account for pauses
    /// Reset on simulation restart
    sim_duration: Duration,
    paused: bool,

    /// Export configuration
    export_data: ExportData,
}

impl Nuance {
    pub async fn init(window: Window, power_preference: PowerPreference) -> Result<Self> {
        let window_size = window.inner_size();
        let scale_factor = window.scale_factor();

        let ui_width = 280.0;
        let mut canvas_size = window_size;
        canvas_size.width -= (ui_width * scale_factor) as u32;

        debug!(
            "window physical size : {:?}, scale factor : {}",
            window_size, scale_factor
        );
        debug!("canvas size : {:?}", canvas_size);

        let renderer = Renderer::new(
            &window,
            power_preference,
            canvas_size.into(),
            Globals::std430_size_static() as u32,
        )
        .await?;

        let (tx, rx) = std::sync::mpsc::channel();

        Ok(Self {
            window,
            gui: Gui::new(
                Platform::new(PlatformDescriptor {
                    physical_width: window_size.width,
                    physical_height: window_size.height,
                    scale_factor,
                    font_definitions: FontDefinitions::default(),
                    style: Style::default(),
                }),
                ui_width as u32,
            ),
            settings: Settings {
                target_framerate: Duration::from_secs_f32(1.0 / 60.0),
                mouse_wheel_step: 0.1,
            },
            shader: None,
            shader_loader: ShaderLoader::new(),
            watcher: watcher(tx, Duration::from_millis(200))?,
            watcher_rx: rx,
            renderer,
            watching: false,
            globals: Globals {
                resolution: Vector2::from([canvas_size.width, canvas_size.height]),
                mouse: Vector2::from([0, 0]),
                mouse_wheel: 0.0,
                ratio: (canvas_size.width) as f32 / canvas_size.height as f32,
                time: 0.0,
                frame: 0,
            },
            sim_start: Instant::now(),
            sim_duration: Duration::from_nanos(0),
            paused: false,
            export_data: Default::default(),
        })
    }
    /// Runs the window, will block the thread until completion
    pub fn run(mut self, event_loop: EventLoop<Command>) -> Result<()> {
        // To send events to this event loop
        let proxy = event_loop.create_proxy();

        // Time since start
        let start_time = Instant::now();
        // Time since last draw
        let mut last_draw = Instant::now();

        event_loop.run(move |event, _, control_flow| {
            if let Ok(DebouncedEvent::Write(_)) = self.watcher_rx.try_recv() {
                proxy.send_event(Command::Reload).unwrap();
            }

            // Let egui update with the window events
            self.gui.handle_event(&event);

            match event {
                // Commands allow running code on the next loop
                // This is needed because the UI code triggers some functionalities
                // we can't execute immediately
                Event::UserEvent(cmd) => match cmd {
                    Command::Load => {
                        if let Some(path) = FileDialog::new()
                            .set_parent(&self.window)
                            .add_filter("Shaders", &["glsl", "frag", "spv"])
                            .pick_file()
                        {
                            self.unwatch();
                            self.load(&path);
                        }
                    }
                    Command::Reload => {
                        info!("Reloading !");
                        self.load(self.shader.as_ref().unwrap().main.clone());
                    }
                    Command::Watch => {
                        self.watch();
                    }
                    Command::Unwatch => {
                        self.unwatch();
                    }
                    Command::ResetGlobals => {
                        info!("Resetting globals !");
                        // Reset the running globals
                        self.globals.reset();
                        self.sim_start = Instant::now();
                        self.sim_duration = Duration::from_nanos(0);
                    }
                    Command::ResetParams => {
                        info!("Resetting params !");
                        if let Some(Some(metadata)) =
                            self.shader.as_mut().map(|it| it.metadata.as_mut())
                        {
                            metadata.reset_params();
                        }
                    }
                    Command::ExportImage => {
                        if let Some(path) = FileDialog::new()
                            .set_parent(&self.window)
                            .add_filter("Image", self.export_data.format.extensions_str())
                            .save_file()
                        {
                            self.export_data.path.push(&path);
                            self.export_image();
                        }
                    }
                    Command::Pause => {
                        self.pause();
                    }
                    Command::Resume => {
                        self.resume();
                    }
                    Command::Exit => {
                        *control_flow = ControlFlow::Exit;
                    }
                },
                Event::WindowEvent { event, .. } => match event {
                    WindowEvent::CursorMoved {
                        device_id: _device_id,
                        position,
                        ..
                    } => {
                        let scale_factor = self.window.scale_factor();
                        if position.x > self.gui.ui_width as f64 * scale_factor {
                            self.globals.mouse = Vector2::from([
                                (position.x - self.gui.ui_width as f64 * scale_factor) as u32,
                                position.y as u32,
                            ]);
                        }
                    }
                    WindowEvent::MouseWheel {
                        device_id: _device_id,
                        delta,
                        ..
                    } => match delta {
                        MouseScrollDelta::LineDelta(_, value) => {
                            self.globals.mouse_wheel += value * self.settings.mouse_wheel_step;
                        }
                        MouseScrollDelta::PixelDelta(pos) => {
                            info!("{:?}", pos);
                        }
                    },
                    WindowEvent::KeyboardInput { input, .. } => match input.virtual_keycode {
                        Some(VirtualKeyCode::F1) => {
                            self.gui.profiling_window = true;
                        }
                        _ => {}
                    },
                    WindowEvent::CloseRequested => {
                        *control_flow = ControlFlow::Exit;
                    }
                    _ => {}
                },
                Event::MainEventsCleared => {
                    // Do not poll events, wait until next frame based on target fps
                    let since_last_draw = last_draw.elapsed();
                    if since_last_draw >= self.settings.target_framerate {
                        self.window.request_redraw();
                    } else {
                        // Sleep til next frame
                        *control_flow = ControlFlow::WaitUntil(
                            Instant::now() + self.settings.target_framerate - since_last_draw,
                        );
                    }

                    // Update shader timem
                    if !self.is_paused() {
                        self.globals.time =
                            (self.sim_start.elapsed() + self.sim_duration).as_secs_f32();
                    }
                }
                Event::RedrawRequested(_) => {
                    // Tell the profiler we're running a new frame
                    puffin::GlobalProfiler::lock().new_frame();

                    // Update egui frame time from app start time
                    self.gui.update_time(start_time.elapsed().as_secs_f64());

                    // Query window properties
                    let window_size = self.window.inner_size();
                    let screen_desc = ScreenDescriptor {
                        physical_width: window_size.width,
                        physical_height: window_size.height,
                        scale_factor: self.window.scale_factor() as f32,
                    };

                    // Generate the GUI
                    let paint_jobs = Gui::render(&proxy, &screen_desc, &mut self);

                    // Render the UI
                    self.renderer
                        .render(
                            &screen_desc,
                            (&self.gui.texture(), &paint_jobs),
                            &self
                                .shader
                                .as_ref()
                                .map(|it| it.metadata.as_ref().map(|it| it.params_buffer()))
                                .unwrap_or_default()
                                .unwrap_or_default(),
                            self.globals.as_std430().as_bytes(),
                            !self.is_paused(),
                        )
                        .unwrap();

                    if !self.is_paused() {
                        self.globals.frame += 1;
                        last_draw = Instant::now();
                    }
                }
                _ => {}
            }
        });
    }

    /// Immediate load
    fn load<P: AsRef<Path>>(&mut self, path: P) {
        info!("Loading {}", path.as_ref().to_str().unwrap());
        let reload_start = Instant::now();

        match self.shader_loader.load_shader(&path) {
            Ok((shader, source)) => {
                let buffer_size = if let Some(metadata) = shader.metadata.as_ref() {
                    metadata.params_buffer_size()
                } else {
                    0
                };

                self.renderer
                    .set_shader(source, Globals::std430_size_static() as u32, buffer_size);

                self.shader = Some(shader);
                // Reset the running globals
                self.globals.reset();
                self.sim_start = Instant::now();
                self.sim_duration = Duration::from_nanos(0);

                info!(
                    "Loaded and ready ! (took {} ms)",
                    reload_start.elapsed().as_millis()
                );
            }
            Err(e) => {
                error!("{}", e);
                error!("Can't load {}", path.as_ref().to_str().unwrap());
            }
        }
    }

    /// Immediate watch
    fn watch(&mut self) {
        // TODO should watch for every file that is part of compilation
        if let Some(path) = self.shader.as_ref().map(|it| &it.main) {
            self.watcher
                .watch(path, RecursiveMode::NonRecursive)
                .unwrap();
            info!("Watching loaded shader for changes.");
        }
    }

    /// Immediate unwatch
    fn unwatch(&mut self) {
        // TODO should unwatch for every file that is part of compilation
        if let Some(shader) = self.shader.as_ref() {
            self.watcher
                .unwatch(&shader.main)
                .expect("Unexpected state");
            info!("Not watching for changes anymore.");
        }
    }

    fn export_image(&self) {
        let export_start = Instant::now();

        let ExportData {
            size, path, format, ..
        } = &self.export_data;

        let mut globals = self.globals.clone();
        globals.resolution = *size;
        globals.ratio = globals.resolution.x as f32 / globals.resolution.y as f32;

        self.renderer
            .render_to_buffer(
                *size,
                &self
                    .shader
                    .as_ref()
                    .map(|it| it.metadata.as_ref().map(|it| it.params_buffer()))
                    .unwrap_or_default()
                    .unwrap_or_default(),
                globals.as_std430().as_bytes(),
                |buf| {
                    let image = ImageBuffer::<Rgba<_>, _>::from_raw(size.x, size.y, &buf[..])
                        .context("Can't create image from buffer")?;
                    image.save_with_format(path, *format)?;

                    Ok(())
                },
            )
            .unwrap();

        info!(
            "Exported image ! (took {} ms)",
            export_start.elapsed().as_millis()
        );
    }

    fn pause(&mut self) {
        self.sim_duration += self.sim_start.elapsed();
        self.paused = true;
    }

    fn is_paused(&self) -> bool {
        self.paused
    }

    fn resume(&mut self) {
        self.sim_start = Instant::now();
        self.paused = false;
    }

    fn shader_loaded(&self) -> bool {
        self.shader.is_some()
    }
}