gled 2.28.5

gled is an application for creating animations and effects on artnet or dmx installations
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
pub mod scene_instance_path;

use super::{
    AssetTrait, animation::Animation, midi_controller::MidiController,
    output_device::routing::OutputRoutings, scene::instance::SceneInstance,
};
use crate::{
    app::{svg::Svg, timing::Timing},
    audio::sound_data::SoundData,
    input::{
        artnet::{ARTNET_CONFIG, ArtnetConfig},
        event::{GamepadEvent, InputEvent},
        external_control::ArtnetControlConfig,
        osc::OscConfig,
    },
    pipeline::{
        extract_output::ExtractOutput, group::Groups, output_clear::OutputClear, preview::Preview,
        preview_indices::PreviewIndices,
    },
    storage::{
        asset::{
            palette::Palette,
            project::scene_instance_path::SceneInstanceUnion,
            scene::{Scene, grid::GridLocation},
        },
        asset_id::AssetId,
        collections::Collections,
    },
    ui::windows::channel_overwrites::ChannelOverwrites,
    wgpu_render_state,
};
use cpal::DeviceId;
use serde::{Deserialize, Serialize};
use std::{
    collections::{BTreeSet, HashMap},
    sync::Arc,
};
use wgpu::CommandEncoderDescriptor;

#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum GridHighlight {
    Row,
    Column,
    None,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(default)]
pub struct Project {
    pub palette: Option<Palette>,
    pub groups: Groups,
    #[serde(default = "Project::default_grid_width")]
    pub grid_width: usize,
    #[serde(default = "Project::default_grid_height")]
    pub grid_height: usize,
    #[serde(default = "Project::default_grid_highlight")]
    pub grid_highlight: GridHighlight,
    pub scenes_instances_grid: HashMap<GridLocation, SceneInstance>,
    pub svg: Option<Svg>,
    pub channel_overwrites: ChannelOverwrites,
    pub output_routings: Arc<OutputRoutings>,
    pub artnet_config: ArtnetConfig,
    pub tap_input_events: BTreeSet<InputEvent>,
    pub blackout_input_events: BTreeSet<InputEvent>,
    pub blackout_hold_input_events: BTreeSet<InputEvent>,
    pub half_input_events: BTreeSet<InputEvent>,
    pub double_input_events: BTreeSet<InputEvent>,
    pub midi_active_mappings: HashMap<String, Option<AssetId<MidiController>>>,
    pub main_dimmer: f32,
    #[serde(
        serialize_with = "crate::audio::device_id_serde::serialize_device_id",
        deserialize_with = "crate::audio::device_id_serde::deserialize_scene_instances"
    )]
    pub audio_input_device: Option<DeviceId>,
    artnet_control_config: ArtnetControlConfig,
    pub osc_config: OscConfig,
}

impl Default for Project {
    fn default() -> Self {
        #[cfg(feature = "profiling")]
        puffin::profile_function!("Project::default");
        Self {
            palette: None,
            groups: Groups::default(),
            grid_width: Self::DEFAULT_GRID_WIDTH,
            grid_height: Self::DEFAULT_GRID_HEIGHT,
            grid_highlight: Self::DEFAULT_GRID_HIGHLIGHT,
            scenes_instances_grid: HashMap::new(),
            svg: Default::default(),
            channel_overwrites: Default::default(),
            output_routings: Default::default(),
            artnet_config: Default::default(),
            tap_input_events: std::iter::once(InputEvent::Key(egui::Key::T))
                .chain(std::iter::once(InputEvent::Gamepad(GamepadEvent::Mode(0))))
                .collect(),
            blackout_input_events: std::iter::once(InputEvent::Key(egui::Key::B)).collect(),
            blackout_hold_input_events: std::iter::once(InputEvent::Key(egui::Key::N))
                .chain(std::iter::once(InputEvent::Gamepad(GamepadEvent::Start(0))))
                .collect(),
            half_input_events: std::iter::once(InputEvent::Key(egui::Key::Minus)).collect(),
            double_input_events: std::iter::once(InputEvent::Key(egui::Key::Plus)).collect(),
            midi_active_mappings: HashMap::new(),
            main_dimmer: 1.0,
            audio_input_device: None,
            artnet_control_config: ArtnetControlConfig::default(),
            osc_config: OscConfig::default(),
        }
    }
}

impl Project {
    pub const MIN_GRID_WIDTH: usize = 2;
    pub const MIN_GRID_HEIGHT: usize = 2;
    pub const DEFAULT_GRID_WIDTH: usize = 8;
    pub const DEFAULT_GRID_HEIGHT: usize = 6;
    pub const DEFAULT_GRID_HIGHLIGHT: GridHighlight = GridHighlight::Row;

    fn default_grid_width() -> usize {
        Self::DEFAULT_GRID_WIDTH
    }

    fn default_grid_height() -> usize {
        Self::DEFAULT_GRID_HEIGHT
    }

    fn default_grid_highlight() -> GridHighlight {
        Self::DEFAULT_GRID_HIGHLIGHT
    }

    pub fn grid_width(&self) -> usize {
        self.grid_width.max(Self::MIN_GRID_WIDTH)
    }

    pub fn grid_height(&self) -> usize {
        self.grid_height.max(Self::MIN_GRID_HEIGHT)
    }

    pub fn quick_row_index(&self) -> usize {
        self.grid_height() - 1
    }

    pub fn quick_col_index(&self) -> usize {
        self.grid_width() - 1
    }

    pub fn set_grid_size(&mut self, width: usize, height: usize) {
        self.grid_width = width.max(Self::MIN_GRID_WIDTH);
        self.grid_height = height.max(Self::MIN_GRID_HEIGHT);

        let max_width = self.grid_width();
        let max_height = self.grid_height();
        self.scenes_instances_grid
            .retain(|location, _| location.col < max_width && location.row < max_height);
    }

    pub fn next_empty_grid_location(&self, start: GridLocation) -> GridLocation {
        let grid_height = self.grid_height();
        let grid_width = self.grid_width();
        for row in 0..grid_height {
            let row = (start.row + row) % grid_height;
            for col in 0..grid_width {
                let col = (start.col + col) % grid_width;
                let location = GridLocation { row, col };
                if !self.scenes_instances_grid.contains_key(&location) {
                    return location;
                }
            }
        }
        start
    }

    pub fn get_scenes_instance(&mut self, pos: &GridLocation) -> Option<&mut SceneInstance> {
        self.scenes_instances_grid.get_mut(pos)
    }
    pub fn scenes_instances_grid_len(&self) -> usize {
        self.scenes_instances_grid.len()
    }

    pub fn scene_instance_by_location_or_quick_index(
        &mut self,
        index_or_grid: SceneInstanceUnion,
    ) -> Option<&mut SceneInstance> {
        let pos = &self.location_by_location_or_quick_index(index_or_grid)?;
        self.get_scenes_instance(pos)
    }
    pub fn location_by_location_or_quick_index(
        &mut self,
        index_or_grid: SceneInstanceUnion,
    ) -> Option<GridLocation> {
        match index_or_grid {
            SceneInstanceUnion::Selected => None,
            SceneInstanceUnion::Grid(location) => Some(location),
            SceneInstanceUnion::Quick(quick_scene_instance_index) => match self.grid_highlight {
                GridHighlight::Row => {
                    if quick_scene_instance_index.index >= self.grid_width() {
                        return None;
                    }
                    Some(GridLocation {
                        row: self.quick_row_index(),
                        col: quick_scene_instance_index.index,
                    })
                }
                GridHighlight::Column => {
                    if quick_scene_instance_index.index >= self.grid_height() {
                        return None;
                    }
                    Some(GridLocation {
                        row: quick_scene_instance_index.index,
                        col: self.quick_col_index(),
                    })
                }
                GridHighlight::None => None,
            },
        }
    }

    pub fn all_scene_instance_locations(&self) -> impl Iterator<Item = &GridLocation> {
        self.scenes_instances_grid.keys()
    }

    pub fn scenes_instances_quick(&self) -> impl Iterator<Item = (&GridLocation, &SceneInstance)> {
        self.scenes_instances_grid
            .iter()
            .filter(move |(location, _)| match self.grid_highlight {
                GridHighlight::Row => location.row == self.quick_row_index(),
                GridHighlight::Column => location.col == self.quick_col_index(),
                GridHighlight::None => false,
            })
    }

    /// Reload shader code for all effects using the given animation, should be called after an animation is edited
    /// If the given animation is None, reloads all effects
    pub fn reload_shader_code(
        &mut self,
        animation: Option<AssetId<Animation>>,
        collections: &Collections,
    ) {
        self.scenes_instances_grid
            .values_mut()
            .for_each(|scene_instance| {
                scene_instance.reload_shader_code(animation, collections);
            });
    }

    pub fn send_positions(&mut self) {
        self.scenes_instances_grid
            .values_mut()
            .for_each(|scene_instance| {
                scene_instance.send_positions();
            });
    }

    /// Remove scene instance at path and update path to the next scene instance
    pub fn remove_scene_instance(&mut self, pos: GridLocation) -> Option<SceneInstance> {
        self.scenes_instances_grid.remove(&pos)
    }

    #[allow(clippy::too_many_arguments)]
    #[cfg_attr(feature = "profiling", profiling::function)]
    pub fn render(
        &mut self,
        timing: &Timing,
        blackout: bool,
        always_render: bool,
        collections: &Collections,
        extract_output: &mut ExtractOutput,
        sound_data: &SoundData,
    ) {
        let wgpu_render_state = wgpu_render_state();
        let device = wgpu_render_state.device;
        let queue = &wgpu_render_state.queue;

        let palette = self.palette.clone();
        let deck_groups = self.groups.clone();
        let main_dimmer = self.main_dimmer;
        for scene_instance in self.scenes_instances_grid.values_mut() {
            scene_instance.prepare(
                queue,
                palette.clone(),
                always_render,
                &deck_groups,
                timing,
                main_dimmer,
                collections,
                sound_data,
            );
        }

        PreviewIndices::get().prepare(queue);

        #[allow(unused_mut)]
        let mut encoder = device.create_command_encoder(&CommandEncoderDescriptor {
            label: Some("Render animations"),
        });

        #[cfg(feature = "profiling")]
        {
            let mut wgpu_profiler = crate::WGPU_PROFILER.lock();
            OutputClear::get().run(&mut wgpu_profiler.scope("OutputClear", &mut encoder));
            for scene_instance in self.scenes_instances_grid.values_mut() {
                scene_instance.render(
                    &mut wgpu_profiler.scope(
                        format!("Render scene \"{}\"", scene_instance.name),
                        &mut encoder,
                    ),
                    blackout,
                    always_render,
                );
            }
            extract_output.run(&mut wgpu_profiler.scope("ExtractOutput", &mut encoder));
            PreviewIndices::get().run(&mut wgpu_profiler.scope("PreviewIndices", &mut encoder));
            Preview::run(&mut wgpu_profiler.scope("Preview", &mut encoder));
            wgpu_profiler.resolve_queries(&mut encoder);
        }

        #[cfg(not(feature = "profiling"))]
        {
            OutputClear::get().run(&mut encoder);
            for scene_instance in self.scenes_instances_grid.values_mut() {
                scene_instance.render(&mut encoder, blackout, always_render);
            }
            extract_output.run(&mut encoder);
            PreviewIndices::get().run(&mut encoder);
            Preview::run(&mut encoder);
        }

        // Submit the animation/output work directly instead of deferring it to
        // egui's paint callback. This decouples the GPU->CPU readback (and the
        // resulting Art-Net/DMX output) from the surface-present path, so the
        // output for this frame is dispatched at the start of the frame and no
        // longer waits behind `Surface::get_current_texture` (which can stall
        // for whole vblank intervals when we render faster than the compositor
        // presents). The preview/output textures are written before egui samples
        // them later in the same frame, so ordering is preserved.
        let submission = queue.submit([encoder.finish()]);
        // Let the output poll thread deliver this frame's readback as soon as
        // the GPU finishes it, independently of any other frame submitted in the
        // same displayed frame (e.g. the second `double_render` pass).
        extract_output.notify_submitted(submission);
    }

    pub fn tap_input_is_new(&self) -> bool {
        self.tap_input_events.iter().any(|event| event.is_new())
    }

    pub fn blackout_input_is_new(&self) -> bool {
        self.blackout_input_events
            .iter()
            .any(|event| event.is_new())
    }

    pub fn blackout_hold_input_is_live(&self) -> bool {
        self.blackout_hold_input_events
            .iter()
            .any(|event| event.is_live())
    }

    pub fn half_input_is_new(&self) -> bool {
        self.half_input_events.iter().any(|event| event.is_new())
    }

    pub fn double_input_is_new(&self) -> bool {
        self.double_input_events.iter().any(|event| event.is_new())
    }

    pub fn add_scene(
        &mut self,
        pos: GridLocation,
        scene_id: AssetId<Scene>,
        collections: &Collections,
    ) {
        let scene_instance = SceneInstance::from_scene_id(scene_id, collections);
        self.add_scene_instance(pos, scene_instance);
    }

    pub fn add_scene_instance(&mut self, pos: GridLocation, scene_instance: SceneInstance) {
        if pos.col >= self.grid_width() || pos.row >= self.grid_height() {
            return;
        }
        let scene_instances = &mut self.scenes_instances_grid;
        scene_instances.insert(pos, scene_instance);
    }

    pub fn remove_nonexistant_groups(&mut self) {
        self.groups.remove_nonexistant_groups();
        for scene_instance in self.scenes_instances_grid.values_mut() {
            scene_instance.remove_nonexistant_groups();
        }
    }

    pub fn artnet_control_config(&mut self, apply: impl FnOnce(&mut ArtnetControlConfig)) {
        apply(&mut self.artnet_control_config);
        ARTNET_CONFIG.lock().artnet_control_config = self.artnet_control_config;
    }

    pub fn artnet_control_config_value(&self) -> ArtnetControlConfig {
        self.artnet_control_config
    }

    pub fn grid_location_from_continuous_index(
        &self,
        index: usize,
        start: &GridLocation,
    ) -> GridLocation {
        let grid_width = self.grid_width();
        let grid_height = self.grid_height();
        let span = grid_width * grid_height;
        let index = (index + start.col + start.row * grid_width) % span;
        let row = index / grid_width;
        let col = index % grid_width;
        GridLocation { row, col }
    }
}

impl AssetTrait for Project {
    const DIR_NAME: &'static str = "projects";
    const NAME: &'static str = "Project";
    const SHOW_NAME_IF_SELECTED: bool = true;
}