radiance 0.7.1

Video art software designed for live performance
Documentation
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
use nalgebra::Vector2;
use serde_json::json;
use std::collections::HashMap;
use std::iter;
use std::sync::Arc;
/// This module handles radiance output through winit
/// (e.g. actually displaying ScreenOutputNode to a screen)
use winit;
use winit::event_loop::ActiveEventLoop;
use winit::keyboard::{Key, NamedKey};
use winit::window::WindowId;
use winit::{
    event::*,
    window::{Fullscreen, Window},
};

const COMMON_RESOLUTIONS: &[[u32; 2]] = &[
    [4096, 2160],
    [3840, 2160],
    [2560, 2048],
    [3440, 1440],
    [2560, 1600],
    [2560, 1440],
    [2048, 1536],
    [2560, 1080],
    [1920, 1200],
    [2048, 1080],
    [1920, 1080],
    [1600, 1200],
    [1680, 1050],
    [1680, 1050],
    [1440, 1080],
    [1400, 1050],
    [1600, 900],
    [1440, 960],
    [1280, 1024],
    [1440, 900],
    [1280, 960],
    [1280, 854],
    [1366, 768],
    [1280, 800],
    [1152, 864],
    [1280, 768],
    [1280, 720],
    [1152, 768],
    [1024, 768],
    [1024, 600],
    [1024, 576],
    [800, 600],
    [768, 576],
    [854, 480],
    [800, 480],
    [640, 480],
    [480, 320],
    [384, 288],
    [352, 288],
    [320, 240],
    [320, 200],
];

const ALLOW_SQUISH: f32 = 1.1;

const EPSILON: f32 = 0.0001;

fn cross(a: Vector2<f32>, b: Vector2<f32>) -> f32 {
    a[0] * b[1] - a[1] * b[0]
}

#[derive(Debug)]
pub struct WinitOutput<'a> {
    screen_output_shader_module: wgpu::ShaderModule,
    screen_output_bind_group_layout: wgpu::BindGroupLayout,
    screen_output_render_pipeline_layout: wgpu::PipelineLayout,

    projection_mapped_output_shader_module: wgpu::ShaderModule,
    projection_mapped_output_bind_group_layout: wgpu::BindGroupLayout,
    projection_mapped_output_render_pipeline_layout: wgpu::PipelineLayout,
    projection_mapped_output_vertex_buffer_layout: wgpu::VertexBufferLayout<'a>,

    screen_outputs: HashMap<radiance::NodeId, Option<VisibleScreenOutput>>,
    projection_mapped_outputs: HashMap<radiance::NodeId, Option<VisibleProjectionMappedOutput>>,
}

#[derive(Debug)]
struct VisibleScreenOutput {
    // Resources
    window: Arc<winit::window::Window>,
    surface: wgpu::Surface<'static>,
    config: wgpu::SurfaceConfiguration,
    render_pipeline: wgpu::RenderPipeline,
    render_target_id: radiance::RenderTargetId,
    render_target: radiance::RenderTarget,

    // Internal
    initial_update: bool, // Initialized to false, set to true on first update.
    request_close: bool,  // If set to True, delete this window on the next update
    name: String,
    resolution: [u32; 2],
    can_draw: bool,
}

#[derive(Debug)]
struct VisibleProjectionMappedSingleOutput {
    window: Arc<winit::window::Window>,
    surface: wgpu::Surface<'static>,
    config: wgpu::SurfaceConfiguration,
    render_pipeline: wgpu::RenderPipeline,
    uniform_buffer: wgpu::Buffer,
    uniforms: ProjectionMapUniforms,
    vertex_buffer: wgpu::Buffer,
    index_buffer: wgpu::Buffer,
    vertices: Vec<ProjectionMapVertex>,
    indices: Vec<u16>,
    indices_count: u32,
    can_draw: bool,
}

#[derive(Debug)]
struct VisibleProjectionMappedOutput {
    // Resources
    screens: HashMap<String, VisibleProjectionMappedSingleOutput>,
    render_target_id: radiance::RenderTargetId,
    render_target: radiance::RenderTarget,
    resolution: [u32; 2],
    initial_update: bool, // Initialized to false, set to true on first update.
    request_close: bool,  // If set to True, delete this window on the next update
}

impl VisibleScreenOutput {
    fn resize(&mut self, device: &wgpu::Device, new_size: winit::dpi::PhysicalSize<u32>) {
        if new_size.width > 0 && new_size.height > 0 {
            self.config.width = new_size.width;
            self.config.height = new_size.height;
            self.surface.configure(device, &self.config);
        }
    }
}

impl VisibleProjectionMappedSingleOutput {
    fn resize(&mut self, device: &wgpu::Device, new_size: winit::dpi::PhysicalSize<u32>) {
        if new_size.width > 0 && new_size.height > 0 {
            self.config.width = new_size.width;
            self.config.height = new_size.height;
            self.surface.configure(device, &self.config);
        }
    }
}

// The uniform buffer associated with the projection mapped shader
#[repr(C)]
#[derive(Default, Debug, Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct ProjectionMapUniforms {
    inv_map: [f32; 12],
}

// The vertex data associated with the projection mapped shader
#[repr(C)]
#[derive(Default, Debug, Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct ProjectionMapVertex {
    uv: [f32; 2],
}

// Max vertices in a single crop polygon
const MAX_VERTICES: usize = 128;
const MAX_INDICES: usize = 128;

impl WinitOutput<'_> {
    pub fn new(device: &wgpu::Device) -> Self {
        let screen_output_shader_module =
            device.create_shader_module(wgpu::ShaderModuleDescriptor {
                label: Some("Screen output shader"),
                source: wgpu::ShaderSource::Wgsl(include_str!("output.wgsl").into()),
            });

        let projection_mapped_output_shader_module =
            device.create_shader_module(wgpu::ShaderModuleDescriptor {
                label: Some("Projection mapped output shader"),
                source: wgpu::ShaderSource::Wgsl(include_str!("projection_map.wgsl").into()),
            });

        let screen_output_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                entries: &[
                    wgpu::BindGroupLayoutEntry {
                        binding: 0,
                        visibility: wgpu::ShaderStages::FRAGMENT,
                        ty: wgpu::BindingType::Texture {
                            multisampled: false,
                            view_dimension: wgpu::TextureViewDimension::D2,
                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        },
                        count: None,
                    },
                    wgpu::BindGroupLayoutEntry {
                        binding: 1,
                        visibility: wgpu::ShaderStages::FRAGMENT,
                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                        count: None,
                    },
                ],
                label: Some("screen output texture bind group layout"),
            });

        let projection_mapped_output_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                entries: &[
                    wgpu::BindGroupLayoutEntry {
                        binding: 0,
                        visibility: wgpu::ShaderStages::FRAGMENT,
                        ty: wgpu::BindingType::Texture {
                            multisampled: false,
                            view_dimension: wgpu::TextureViewDimension::D2,
                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        },
                        count: None,
                    },
                    wgpu::BindGroupLayoutEntry {
                        binding: 1,
                        visibility: wgpu::ShaderStages::FRAGMENT,
                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                        count: None,
                    },
                    wgpu::BindGroupLayoutEntry {
                        binding: 2, // ProjectionMapUniforms
                        visibility: wgpu::ShaderStages::VERTEX,
                        ty: wgpu::BindingType::Buffer {
                            ty: wgpu::BufferBindingType::Uniform,
                            has_dynamic_offset: false,
                            min_binding_size: None,
                        },
                        count: None,
                    },
                ],
                label: Some("screen output texture bind group layout"),
            });

        let screen_output_render_pipeline_layout =
            device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("Screen output Render Pipeline Layout"),
                bind_group_layouts: &[&screen_output_bind_group_layout],
                push_constant_ranges: &[],
            });

        let projection_mapped_output_render_pipeline_layout =
            device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("Projection mapped output Render Pipeline Layout"),
                bind_group_layouts: &[&projection_mapped_output_bind_group_layout],
                push_constant_ranges: &[],
            });

        let projection_mapped_output_vertex_buffer_layout = wgpu::VertexBufferLayout {
            array_stride: std::mem::size_of::<ProjectionMapVertex>() as wgpu::BufferAddress,
            step_mode: wgpu::VertexStepMode::Vertex,
            attributes: &[wgpu::VertexAttribute {
                offset: 0,
                shader_location: 0,
                format: wgpu::VertexFormat::Float32x2,
            }],
        };

        WinitOutput {
            screen_output_shader_module,
            screen_output_bind_group_layout,
            screen_output_render_pipeline_layout,

            projection_mapped_output_shader_module,
            projection_mapped_output_bind_group_layout,
            projection_mapped_output_render_pipeline_layout,
            projection_mapped_output_vertex_buffer_layout,

            screen_outputs: HashMap::<radiance::NodeId, Option<VisibleScreenOutput>>::new(),
            projection_mapped_outputs: HashMap::<
                radiance::NodeId,
                Option<VisibleProjectionMappedOutput>,
            >::new(),
        }
    }

    pub fn render_targets_iter(
        &self,
    ) -> impl Iterator<Item = (&radiance::RenderTargetId, &radiance::RenderTarget)> {
        self.screen_outputs
            .values()
            .flatten()
            .map(|screen_output| {
                (
                    &screen_output.render_target_id,
                    &screen_output.render_target,
                )
            })
            .chain(self.projection_mapped_outputs.values().flatten().map(
                |projection_mapped_output| {
                    (
                        &projection_mapped_output.render_target_id,
                        &projection_mapped_output.render_target,
                    )
                },
            ))
    }

    // returns true if present() was called (forcing vsync)
    pub fn update(
        &mut self,
        event_loop: &ActiveEventLoop,
        ctx: &mut radiance::Context,
        props: &mut radiance::Props,
        instance: &wgpu::Instance,
        adapter: &wgpu::Adapter,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
    ) -> bool {
        // Prune screen_outputs and projection_mapped_outputs of any nodes that are no longer present in the given graph
        self.screen_outputs.retain(|id, _| {
            props
                .node_props
                .get(id)
                .map(|node_props| matches!(node_props, radiance::NodeProps::ScreenOutputNode(_)))
                .unwrap_or(false)
        });
        self.projection_mapped_outputs.retain(|id, _| {
            props
                .node_props
                .get(id)
                .map(|node_props| {
                    matches!(
                        node_props,
                        radiance::NodeProps::ProjectionMappedOutputNode(_)
                    )
                })
                .unwrap_or(false)
        });

        // Construct screen_outputs and projection_mapped_outputs for any ScreenOutputNodes we didn't know about
        for (node_id, node_props) in props.node_props.iter() {
            match node_props {
                radiance::NodeProps::ScreenOutputNode(_) => {
                    if !self.screen_outputs.contains_key(node_id) {
                        self.screen_outputs.insert(*node_id, None);
                    }
                }
                radiance::NodeProps::ProjectionMappedOutputNode(_) => {
                    if !self.projection_mapped_outputs.contains_key(node_id) {
                        self.projection_mapped_outputs.insert(*node_id, None);
                    }
                }
                _ => {}
            }
        }

        // See what screens are available for output
        let available_screens: Vec<radiance::AvailableOutputScreen> = event_loop
            .available_monitors()
            .filter_map(|mh| {
                let name = mh.name()?;
                let native_resolution = mh.size();
                if native_resolution.width * native_resolution.height == 0 {
                    return None;
                }
                let suggested_resolutions =
                    Some([native_resolution.width, native_resolution.height]).into_iter();
                let aspect = native_resolution.width as f32 / native_resolution.height as f32;
                let suggested_resolutions = suggested_resolutions.chain(
                    COMMON_RESOLUTIONS
                        .iter()
                        .filter(|resolution| {
                            if resolution[0] >= native_resolution.width
                                || resolution[1] >= native_resolution.height
                            {
                                return false; // Don't recommend higher resolutions than native resolution
                            }
                            let test_aspect = resolution[0] as f32 / resolution[1] as f32;
                            aspect / test_aspect < ALLOW_SQUISH
                                && test_aspect / aspect < ALLOW_SQUISH
                        })
                        .cloned(),
                );
                let suggested_resolutions: Vec<[u32; 2]> = suggested_resolutions.collect();
                if suggested_resolutions.is_empty() {
                    return None;
                }
                Some(radiance::AvailableOutputScreen {
                    name,
                    suggested_resolutions,
                })
            })
            .collect();

        // Update internal state of screen_outputs from props
        let node_ids: Vec<radiance::NodeId> = self.screen_outputs.keys().cloned().collect();
        for node_id in node_ids {
            let screen_output_props: &mut radiance::ScreenOutputNodeProps = props
                .node_props
                .get_mut(&node_id)
                .unwrap()
                .try_into()
                .unwrap();

            // If this node's screen list is totally empty, default it to the first screen
            if screen_output_props.available_screens.is_empty()
                && screen_output_props.screen.is_none()
                && available_screens
                    .first()
                    .map(|s| s.suggested_resolutions.first())
                    .is_some()
            {
                let screen = available_screens.first().unwrap();
                let name = screen.name.clone();
                let resolution = *screen.suggested_resolutions.first().unwrap();
                screen_output_props.screen =
                    Some(radiance::SelectedOutputScreen { name, resolution });
            }

            // Populate each screen output node props with a list of screens available on the system
            screen_output_props.available_screens = available_screens.clone();
            #[allow(clippy::if_same_then_else)]
            if screen_output_props.screen.is_none() {
                // Can't output if there's no screen selected
                screen_output_props.visible = false;
            } else if !available_screens.iter().any(|available_screen| {
                available_screen.name == screen_output_props.screen.as_ref().unwrap().name
            }) {
                // Hide any outputs that point to screens we don't know about
                screen_output_props.visible = false;
            }
            if self
                .screen_outputs
                .get(&node_id)
                .unwrap()
                .as_ref()
                .map(|visible_screen_output| visible_screen_output.request_close)
                .unwrap_or(false)
            {
                // Close was requested; set visible to false
                screen_output_props.visible = false;
            }

            if screen_output_props.visible {
                let screen = screen_output_props.screen.as_ref().unwrap(); // The selected screen, as per the props
                                                                           // (it is safe to unwrap it because the window would have been set to invisible had it been None)
                let needs_new_window = match self.screen_outputs.get(&node_id).unwrap() {
                    None => true, // Make a new window if we weren't visible last frame
                    Some(screen_output) => screen_output.resolution != screen.resolution, // Make a new window if the resolution changes TODO also make a new window if screen name changes
                };
                if needs_new_window {
                    let visible_screen_output = self.new_screen_output(
                        instance,
                        adapter,
                        device,
                        event_loop,
                        &screen.name,
                        &screen.resolution,
                    );
                    visible_screen_output.window.set_title("Radiance Output");
                    // Replace None with Some
                    self.screen_outputs
                        .insert(node_id, Some(visible_screen_output));
                }
            } else if self.screen_outputs.get(&node_id).unwrap().is_some() {
                // Replace Some with None if we aren't supposed to be visible
                self.screen_outputs.insert(node_id, None);
            }
        }

        // Update internal state of projection_mapped_outputs from props
        let node_ids: Vec<radiance::NodeId> =
            self.projection_mapped_outputs.keys().cloned().collect();
        for node_id in node_ids {
            let projection_mapped_output_props: &mut radiance::ProjectionMappedOutputNodeProps =
                props
                    .node_props
                    .get_mut(&node_id)
                    .unwrap()
                    .try_into()
                    .unwrap();

            // Populate each projection mapped output node props with a list of screens available on the system
            projection_mapped_output_props.available_screens = available_screens.clone();

            if self
                .projection_mapped_outputs
                .get(&node_id)
                .unwrap()
                .as_ref()
                .map(|visible_projection_mapped_output| {
                    visible_projection_mapped_output.request_close
                })
                .unwrap_or(false)
            {
                // Close was requested; set visible to false
                projection_mapped_output_props.visible = false;
            }

            if projection_mapped_output_props.visible {
                let needs_new_windows = match self.projection_mapped_outputs.get(&node_id).unwrap()
                {
                    None => true, // Make new resources if we weren't visible last frame
                    Some(projection_mapped_output) => {
                        projection_mapped_output.resolution
                            != projection_mapped_output_props.resolution
                    } // Make new resources if the resolution changes OR (TODO) screen list changes
                };
                if needs_new_windows {
                    let render_target_id = radiance::RenderTargetId::gen();
                    let render_target: radiance::RenderTarget = serde_json::from_value(json!({
                        "width": projection_mapped_output_props.resolution[0],
                        "height": projection_mapped_output_props.resolution[1],
                        "dt": 1. / 60.
                    }))
                    .unwrap();
                    let visible_projection_mapped_output = VisibleProjectionMappedOutput {
                        screens: projection_mapped_output_props
                            .screens
                            .iter()
                            .map(|single_screen_props| {
                                let single_output = self.new_projection_mapped_single_output(
                                    instance, adapter, device, event_loop,
                                );
                                single_output.window.set_title("Radiance Output");
                                (single_screen_props.name.clone(), single_output)
                            })
                            .collect(),
                        render_target_id,
                        render_target,
                        initial_update: false,
                        request_close: false,
                        resolution: projection_mapped_output_props.resolution,
                    };
                    self.projection_mapped_outputs
                        .insert(node_id, Some(visible_projection_mapped_output));
                }

                let output = self
                    .projection_mapped_outputs
                    .get_mut(&node_id)
                    .unwrap()
                    .as_mut()
                    .unwrap();
                for screen_props in projection_mapped_output_props.screens.iter() {
                    if let Some(single_output) = output.screens.get_mut(&screen_props.name) {
                        let inv_map = screen_props.map.try_inverse().unwrap();
                        let inv_map_padded = [
                            inv_map[(0, 0)],
                            inv_map[(1, 0)],
                            inv_map[(2, 0)],
                            0.,
                            inv_map[(0, 1)],
                            inv_map[(1, 1)],
                            inv_map[(2, 1)],
                            0.,
                            inv_map[(0, 2)],
                            inv_map[(1, 2)],
                            inv_map[(2, 2)],
                            0.,
                        ];
                        single_output.uniforms = ProjectionMapUniforms {
                            inv_map: inv_map_padded,
                        };

                        single_output.vertices = screen_props
                            .crop
                            .iter()
                            .map(|uv| ProjectionMapVertex { uv: [uv[0], uv[1]] })
                            .collect();
                        // Ear-clip polygon from props to get the index list

                        let mut indices: Vec<usize> = (0..screen_props.crop.len()).collect();
                        single_output.indices.clear();
                        while indices.len() > 2 {
                            // Find an ear
                            let mut found_ear = false;
                            for i in 0..indices.len() {
                                let ii1 = (indices.len() + i - 1) % indices.len();
                                let ii2 = i;
                                let ii3 = (i + 1) % indices.len();
                                let p1 = screen_props.crop[indices[ii1]];
                                let p2 = screen_props.crop[indices[ii2]];
                                let p3 = screen_props.crop[indices[ii3]];
                                let c = cross(p2 - p1, p3 - p2);
                                // CCW polygon winding produces negative cross products on interior edges
                                if c < -EPSILON {
                                    // This vertex is an ear tip if there all vertices are outside the ear
                                    let edge_inside_polygon = indices.iter().all(|&test_ix| {
                                        let test_vertex = screen_props.crop[test_ix];

                                        // Inside triangle test, from http://blackpawn.com/texts/pointinpoly/
                                        let v0 = p3 - p1;
                                        let v1 = p2 - p1;
                                        let v2 = test_vertex - p1;

                                        // Compute dot products
                                        let dot00 = v0.dot(&v0);
                                        let dot01 = v0.dot(&v1);
                                        let dot02 = v0.dot(&v2);
                                        let dot11 = v1.dot(&v1);
                                        let dot12 = v1.dot(&v2);

                                        // Compute barycentric coordinates
                                        let inv_denom = 1. / (dot00 * dot11 - dot01 * dot01);
                                        let u = (dot11 * dot02 - dot01 * dot12) * inv_denom;
                                        let v = (dot00 * dot12 - dot01 * dot02) * inv_denom;

                                        // Check if point is outside triangle
                                        !((u >= EPSILON)
                                            && (v >= EPSILON)
                                            && (u + v < 1. - EPSILON))
                                    });
                                    if edge_inside_polygon {
                                        found_ear = true;
                                        single_output.indices.push(indices[ii1] as u16);
                                        single_output.indices.push(indices[ii2] as u16);
                                        single_output.indices.push(indices[ii3] as u16);
                                        indices.remove(i); // Clip
                                        break;
                                    }
                                }
                            }
                            if !found_ear {
                                // We have clipped the polygon to the point that it has no ears
                                break;
                            }
                        }
                        single_output.indices_count = single_output.indices.len() as u32;
                        if single_output.indices_count % 2 == 1 {
                            single_output.indices.push(0); // Add padding to get to a multiple of 4 bytes
                        }
                    }
                }
            } else if self
                .projection_mapped_outputs
                .get(&node_id)
                .unwrap()
                .is_some()
            {
                // Replace Some with None if we aren't supposed to be visible
                self.projection_mapped_outputs.insert(node_id, None);
            }
        }

        let mut did_vsync = false;

        // Paint each screen output
        for (node_id, screen_output) in self
            .screen_outputs
            .iter_mut()
            .filter_map(|(k, v)| Some((k, v.as_mut()?)))
        {
            if !screen_output.initial_update {
                continue;
            }
            // Fullscreen
            let mh = event_loop.available_monitors().find(|mh| {
                mh.name()
                    .map(|n| &n == &screen_output.name)
                    .unwrap_or(false)
            });
            if let Some(monitor) = mh {
                screen_output
                    .window
                    .set_fullscreen(Some(Fullscreen::Borderless(Some(monitor))));
            }

            // Paint
            let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("Radiance output encoder"),
            });

            let results = ctx.paint(device, queue, &mut encoder, screen_output.render_target_id);
            queue.submit(iter::once(encoder.finish()));

            // See if we can present (window is not occluded)
            // (on Mac, we can always draw.) XXX test this
            // (on Windows, we can always draw, and in fact, the redraw signal doesn't fire as it should.)
            if cfg!(target_os = "linux") && !screen_output.can_draw {
                continue;
            }
            screen_output.can_draw = false;
            screen_output.window.request_redraw();

            let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("Surface output encoder"),
            });

            if let Some(texture) = results.get(node_id) {
                let output_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
                    layout: &self.screen_output_bind_group_layout,
                    entries: &[
                        wgpu::BindGroupEntry {
                            binding: 0,
                            resource: wgpu::BindingResource::TextureView(&texture.view),
                        },
                        wgpu::BindGroupEntry {
                            binding: 1,
                            resource: wgpu::BindingResource::Sampler(&texture.sampler),
                        },
                    ],
                    label: Some("output bind group"),
                });

                // Record output render pass.
                let output = screen_output.surface.get_current_texture().unwrap();
                let view = output
                    .texture
                    .create_view(&wgpu::TextureViewDescriptor::default());

                {
                    let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                        label: Some("Output window render pass"),
                        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                            view: &view,
                            resolve_target: None,
                            ops: wgpu::Operations {
                                load: wgpu::LoadOp::Clear(wgpu::Color {
                                    r: 0.,
                                    g: 0.,
                                    b: 0.,
                                    a: 0.,
                                }),
                                store: wgpu::StoreOp::Store,
                            },
                            depth_slice: None,
                        })],
                        depth_stencil_attachment: None,
                        timestamp_writes: None,
                        occlusion_query_set: None,
                    });

                    render_pass.set_pipeline(&screen_output.render_pipeline);
                    render_pass.set_bind_group(0, &output_bind_group, &[]);
                    render_pass.draw(0..6, 0..1);
                }

                // Submit the commands.
                queue.submit(iter::once(encoder.finish()));

                // Draw
                screen_output.window.pre_present_notify();
                output.present();
                did_vsync = true;
            }
        }
        // Paint each projection mapped output
        for (node_id, output) in self
            .projection_mapped_outputs
            .iter_mut()
            .filter_map(|(k, v)| Some((k, v.as_mut()?)))
        {
            if !output.initial_update {
                continue;
            }

            // Paint virtual
            let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("Radiance output encoder"),
            });

            let results = ctx.paint(device, queue, &mut encoder, output.render_target_id);
            queue.submit(iter::once(encoder.finish()));

            for (screen_name, single_output) in output.screens.iter_mut() {
                // Fullscreen
                let mh = event_loop
                    .available_monitors()
                    .find(|mh| mh.name().map(|n| &n == screen_name).unwrap_or(false));
                if let Some(monitor) = mh {
                    #[cfg(target_os = "linux")]
                    {
                        single_output
                            .window
                            .set_fullscreen(Some(Fullscreen::Borderless(Some(monitor))));
                    }
                    #[cfg(not(target_os = "linux"))]
                    {
                        if let Some(video_mode) = monitor.video_modes().next() {
                            single_output
                                .window
                                .set_fullscreen(Some(Fullscreen::Exclusive(video_mode)));
                        }
                    }
                }

                // Write uniforms
                queue.write_buffer(
                    &single_output.uniform_buffer,
                    0,
                    bytemuck::cast_slice(&[single_output.uniforms]),
                );

                // Write vertices
                queue.write_buffer(
                    &single_output.vertex_buffer,
                    0,
                    bytemuck::cast_slice(&single_output.vertices),
                );
                queue.write_buffer(
                    &single_output.index_buffer,
                    0,
                    bytemuck::cast_slice(&single_output.indices),
                );

                // See if we can present (window is not occluded)
                // (on Mac, we can always draw.) XXX test this
                // (on Windows, we can always draw, and in fact, the redraw signal doesn't fire as it should.)
                if cfg!(target_os = "linux") && !single_output.can_draw {
                    continue;
                }
                single_output.can_draw = false;
                single_output.window.request_redraw();

                // Paint physical
                let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
                    label: Some("Surface output encoder"),
                });

                if let Some(texture) = results.get(node_id) {
                    let output_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
                        layout: &self.projection_mapped_output_bind_group_layout,
                        entries: &[
                            wgpu::BindGroupEntry {
                                binding: 0,
                                resource: wgpu::BindingResource::TextureView(&texture.view),
                            },
                            wgpu::BindGroupEntry {
                                binding: 1,
                                resource: wgpu::BindingResource::Sampler(&texture.sampler),
                            },
                            wgpu::BindGroupEntry {
                                binding: 2,
                                resource: single_output.uniform_buffer.as_entire_binding(),
                            },
                        ],
                        label: Some("output bind group"),
                    });

                    // Record output render pass.
                    let output = single_output.surface.get_current_texture().unwrap();
                    let view = output
                        .texture
                        .create_view(&wgpu::TextureViewDescriptor::default());

                    {
                        let mut render_pass =
                            encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                                label: Some("Output window render pass"),
                                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                                    view: &view,
                                    resolve_target: None,
                                    ops: wgpu::Operations {
                                        load: wgpu::LoadOp::Clear(wgpu::Color {
                                            r: 0.,
                                            g: 0.,
                                            b: 0.,
                                            a: 0.,
                                        }),
                                        store: wgpu::StoreOp::Store,
                                    },
                                    depth_slice: None,
                                })],
                                depth_stencil_attachment: None,
                                timestamp_writes: None,
                                occlusion_query_set: None,
                            });

                        render_pass.set_pipeline(&single_output.render_pipeline);
                        render_pass.set_bind_group(0, &output_bind_group, &[]);
                        render_pass.set_vertex_buffer(0, single_output.vertex_buffer.slice(..));
                        render_pass.set_index_buffer(
                            single_output.index_buffer.slice(..),
                            wgpu::IndexFormat::Uint16,
                        );
                        render_pass.draw_indexed(0..single_output.indices_count, 0, 0..1);
                    }

                    // Submit the commands.
                    queue.submit(iter::once(encoder.finish()));

                    single_output.window.pre_present_notify();
                    output.present();
                    did_vsync = true;
                }
            }
        }

        // Mark all nodes that we know about as having received their initial update.
        // Painting is gated on this being true,
        // because otherwise, we might try to paint a render target that the radiance context doesn't know about.
        // After the initial update, the radiance context is guaranteed to know about this screen output's render target.
        for screen_output in self.screen_outputs.values_mut().flatten() {
            screen_output.initial_update = true;
        }
        for projection_mapped_output in self.projection_mapped_outputs.values_mut().flatten() {
            projection_mapped_output.initial_update = true;
        }

        did_vsync
    }

    fn new_screen_output(
        &self,
        instance: &wgpu::Instance,
        adapter: &wgpu::Adapter,
        device: &wgpu::Device,
        event_loop: &ActiveEventLoop,
        name: &str,
        resolution: &[u32; 2],
    ) -> VisibleScreenOutput {
        let window = Arc::new(
            event_loop
                .create_window(Window::default_attributes())
                .unwrap(),
        ); //TODO: assign proper screen, etc
        let size = window.inner_size();
        let surface = instance.create_surface(window.clone()).unwrap();

        let surface_caps = surface.get_capabilities(&adapter);
        let surface_format = surface_caps
            .formats
            .iter()
            .find(|f| f.is_srgb())
            .copied()
            .unwrap_or(surface_caps.formats[0]);

        let config = wgpu::SurfaceConfiguration {
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            format: surface_format,
            width: size.width,
            height: size.height,
            present_mode: wgpu::PresentMode::AutoVsync,
            alpha_mode: wgpu::CompositeAlphaMode::Auto,
            view_formats: vec![],
            desired_maximum_frame_latency: 2,
        };
        surface.configure(device, &config);

        let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("Output Render Pipeline"),
            layout: Some(&self.screen_output_render_pipeline_layout),
            vertex: wgpu::VertexState {
                module: &self.screen_output_shader_module,
                entry_point: Some("vs_main"),
                buffers: &[],
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &self.screen_output_shader_module,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: config.format,
                    blend: Some(wgpu::BlendState::REPLACE),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleStrip,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: Some(wgpu::Face::Back),
                polygon_mode: wgpu::PolygonMode::Fill,
                unclipped_depth: false,
                conservative: false,
            },
            depth_stencil: None,
            multisample: wgpu::MultisampleState {
                count: 1,
                mask: !0,
                alpha_to_coverage_enabled: false,
            },
            multiview: None,
            cache: None,
        });

        let render_target_id = radiance::RenderTargetId::gen();
        let render_target: radiance::RenderTarget = serde_json::from_value(json!({
            "width": resolution[0],
            "height": resolution[1],
            "dt": 1. / 60.
        }))
        .unwrap();

        VisibleScreenOutput {
            window,
            surface,
            config,
            render_pipeline,
            render_target_id,
            render_target,
            initial_update: false,
            request_close: false,
            name: name.to_owned(),
            resolution: *resolution,
            can_draw: false,
        }
    }

    fn new_projection_mapped_single_output(
        &self,
        instance: &wgpu::Instance,
        adapter: &wgpu::Adapter,
        device: &wgpu::Device,
        event_loop: &ActiveEventLoop,
    ) -> VisibleProjectionMappedSingleOutput {
        let window = Arc::new(
            event_loop
                .create_window(Window::default_attributes())
                .unwrap(),
        ); //TODO: assign proper screen, etc
        let size = window.inner_size();
        let surface = instance.create_surface(window.clone()).unwrap();

        let surface_caps = surface.get_capabilities(&adapter);
        let surface_format = surface_caps
            .formats
            .iter()
            .find(|f| f.is_srgb())
            .copied()
            .unwrap_or(surface_caps.formats[0]);

        let config = wgpu::SurfaceConfiguration {
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            format: surface_format,
            width: size.width,
            height: size.height,
            present_mode: wgpu::PresentMode::AutoVsync,
            alpha_mode: wgpu::CompositeAlphaMode::Auto,
            view_formats: vec![],
            desired_maximum_frame_latency: 2,
        };
        surface.configure(device, &config);

        let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("Output Render Pipeline"),
            layout: Some(&self.projection_mapped_output_render_pipeline_layout),
            vertex: wgpu::VertexState {
                module: &self.projection_mapped_output_shader_module,
                entry_point: Some("vs_main"),
                buffers: &[self.projection_mapped_output_vertex_buffer_layout.clone()],
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &self.projection_mapped_output_shader_module,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: config.format,
                    blend: Some(wgpu::BlendState::REPLACE),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: Some(wgpu::Face::Back),
                polygon_mode: wgpu::PolygonMode::Fill,
                unclipped_depth: false,
                conservative: false,
            },
            depth_stencil: None,
            multisample: wgpu::MultisampleState {
                count: 1,
                mask: !0,
                alpha_to_coverage_enabled: false,
            },
            multiview: None,
            cache: None,
        });

        let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Projection mapped output uniform buffer"),
            size: std::mem::size_of::<ProjectionMapUniforms>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let vertex_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Projection mapped output vertex buffer"),
            size: (std::mem::size_of::<ProjectionMapVertex>() * MAX_VERTICES) as u64,
            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let index_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Projection mapped output index buffer"),
            size: (std::mem::size_of::<u16>() * MAX_INDICES) as u64,
            usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        VisibleProjectionMappedSingleOutput {
            window,
            surface,
            config,
            render_pipeline,
            uniform_buffer,
            uniforms: ProjectionMapUniforms { inv_map: [0.; 12] },
            vertex_buffer,
            index_buffer,
            vertices: Vec::<_>::new(),
            indices: Vec::<_>::new(),
            indices_count: 0,
            can_draw: false,
        }
    }

    pub fn window_event(
        &mut self,
        window_id: WindowId,
        event: &WindowEvent,
        device: &wgpu::Device,
    ) -> bool {
        // Return true => event consumed
        // Return false => event continues to be processed

        for screen_output in self.screen_outputs.values_mut().flatten() {
            if screen_output.window.id() != window_id {
                continue;
            }
            match event {
                WindowEvent::CloseRequested
                | WindowEvent::KeyboardInput {
                    event:
                        KeyEvent {
                            state: ElementState::Pressed,
                            logical_key: Key::Named(NamedKey::Escape),
                            ..
                        },
                    ..
                } => {
                    screen_output.request_close = true;
                }
                WindowEvent::Resized(physical_size) => {
                    screen_output.resize(device, physical_size.clone());
                }
                WindowEvent::RedrawRequested => {
                    screen_output.can_draw = true;
                }
                _ => {}
            }
            return true;
        }
        for output in self.projection_mapped_outputs.values_mut().flatten() {
            for single_output in output.screens.values_mut() {
                if single_output.window.id() != window_id {
                    continue;
                }
                match event {
                    WindowEvent::CloseRequested
                    | WindowEvent::KeyboardInput {
                        event:
                            KeyEvent {
                                state: ElementState::Pressed,
                                logical_key: Key::Named(NamedKey::Escape),
                                ..
                            },
                        ..
                    } => {
                        output.request_close = true;
                    }
                    WindowEvent::Resized(physical_size) => {
                        single_output.resize(&device, physical_size.clone());
                    }
                    WindowEvent::RedrawRequested => {
                        single_output.can_draw = true;
                    }
                    _ => {}
                }
                return true;
            }
        }
        false
    }
}