grafo 0.15.0

A GPU-accelerated rendering library for Rust
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
//! Pipeline creation and management for the Grafo library.
//!
//! This module provides functions to create and manage rendering pipelines.
// TODO: This is needed to avoid false positives generated by the repr(C) expansion in compiler 1.89
#![allow(unused)]

use crate::vertex::{CustomVertex, InstanceColor, InstanceMetadata, InstanceTransform};
use wgpu::util::DeviceExt;
use wgpu::{
    BindGroup, BindGroupLayout, ComputePipeline, Device, RenderPass, RenderPipeline,
    StencilFaceState, StoreOp, Texture, TextureView,
};

/// A structure for coordinate normalization on the GPU. We pass pixel coordinates to the GPU,
///  but GPU needs coordinates to be normalized between 0 and 1.
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct Uniforms {
    pub canvas_size: [f32; 2],
    /// Display scale factor (e.g. 2.0 for Retina). Used by the AA fringe shader
    /// to offset by exactly 1 physical pixel.
    pub scale_factor: f32,
    /// AA fringe offset in physical pixels. Controls how far the anti-aliasing
    /// fringe extends outward from shape edges. Default is 0.75. Set to 0.0 to
    /// disable the AA fringe entirely.
    pub fringe_width: f32,
}

impl Uniforms {
    pub fn new(width: f32, height: f32, scale_factor: f32, fringe_width: f32) -> Self {
        Self {
            canvas_size: [width, height],
            scale_factor,
            fringe_width,
        }
    }
}

fn create_equal_increment_stencil_state() -> wgpu::StencilState {
    // In this stencil state we will only draw where the stencil value is equal to the reference value,
    //  and all outside areas are zeroed.
    let face_state = wgpu::StencilFaceState {
        compare: wgpu::CompareFunction::Equal,
        fail_op: wgpu::StencilOperation::Keep,
        depth_fail_op: wgpu::StencilOperation::Keep,
        pass_op: wgpu::StencilOperation::IncrementClamp,
    };

    wgpu::StencilState {
        front: face_state,
        back: face_state,
        read_mask: 0xff,
        write_mask: 0xff,
    }
}

fn create_equal_decrement_stencil_state() -> wgpu::StencilState {
    // In this stencil state we will only draw where the stencil value is equal to the reference value,
    //  and all outside areas are zeroed.
    let face_state = wgpu::StencilFaceState {
        compare: wgpu::CompareFunction::Equal,
        fail_op: wgpu::StencilOperation::Keep,
        depth_fail_op: wgpu::StencilOperation::Keep,
        pass_op: wgpu::StencilOperation::DecrementClamp,
    };

    wgpu::StencilState {
        front: face_state,
        back: face_state,
        read_mask: 0xff,
        write_mask: 0xff,
    }
}

/// Creates a bind group so uniforms can be processed. Look at Uniforms struct for more info.
pub fn create_uniform_bind_group_layout(device: &Device) -> BindGroupLayout {
    device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
        label: None,
        entries: &[wgpu::BindGroupLayoutEntry {
            binding: 0,
            visibility: wgpu::ShaderStages::VERTEX,
            ty: wgpu::BindingType::Buffer {
                ty: wgpu::BufferBindingType::Uniform,
                has_dynamic_offset: false,
                min_binding_size: None,
            },
            count: None,
        }],
    })
}

pub fn create_equal_increment_depth_state() -> wgpu::DepthStencilState {
    wgpu::DepthStencilState {
        format: wgpu::TextureFormat::Depth24PlusStencil8,
        depth_write_enabled: true,
        depth_compare: wgpu::CompareFunction::Always,
        stencil: create_equal_increment_stencil_state(),
        bias: wgpu::DepthBiasState::default(),
    }
}

/// This depth stencil state ignores stencil and draws only where the depth value is equal to the
/// reference value
pub fn create_depth_stencil_state_for_text() -> wgpu::DepthStencilState {
    wgpu::DepthStencilState {
        format: wgpu::TextureFormat::Depth24PlusStencil8,
        depth_write_enabled: true,
        // Draw only where depth value is equal to the reference value set by the shape when it
        //  was drawn. When the shape is drawn, it always replaces the depth value with the reference
        //  value for itself
        depth_compare: wgpu::CompareFunction::Equal,
        stencil: wgpu::StencilState {
            front: StencilFaceState::IGNORE,
            back: StencilFaceState::IGNORE,
            read_mask: 0,
            write_mask: 0,
        },
        bias: wgpu::DepthBiasState::default(),
    }
}

pub fn create_equal_decrement_depth_state() -> wgpu::DepthStencilState {
    wgpu::DepthStencilState {
        format: wgpu::TextureFormat::Depth24PlusStencil8,
        depth_write_enabled: false,
        depth_compare: wgpu::CompareFunction::Always,
        stencil: create_equal_decrement_stencil_state(),
        bias: wgpu::DepthBiasState::default(),
    }
}

pub fn write_on_equal_depth_stencil_state() -> wgpu::DepthStencilState {
    let face_state = wgpu::StencilFaceState {
        compare: wgpu::CompareFunction::Equal,
        fail_op: wgpu::StencilOperation::Keep,
        depth_fail_op: wgpu::StencilOperation::Keep,
        pass_op: wgpu::StencilOperation::Replace,
    };

    let stencil = wgpu::StencilState {
        front: face_state,
        back: face_state,
        read_mask: 0xff,
        write_mask: 0xff,
    };

    wgpu::DepthStencilState {
        format: wgpu::TextureFormat::Depth24PlusStencil8,
        depth_write_enabled: false,
        depth_compare: wgpu::CompareFunction::Always,
        stencil,
        bias: wgpu::DepthBiasState::default(),
    }
}

pub fn always_pass_and_keep_stencil_state() -> wgpu::DepthStencilState {
    let face_state = wgpu::StencilFaceState {
        compare: wgpu::CompareFunction::Always,
        fail_op: wgpu::StencilOperation::Keep,
        depth_fail_op: wgpu::StencilOperation::Keep,
        pass_op: wgpu::StencilOperation::Keep,
    };

    let stencil = wgpu::StencilState {
        front: face_state,
        back: face_state,
        read_mask: 0xff,
        write_mask: 0xff,
    };

    wgpu::DepthStencilState {
        format: wgpu::TextureFormat::Depth24PlusStencil8,
        depth_write_enabled: false,
        depth_compare: wgpu::CompareFunction::Always,
        stencil,
        bias: wgpu::DepthBiasState::default(),
    }
}

pub enum PipelineType {
    /// Keeps values where the stencil is equal to the reference value, zeros outside areas.
    /// I.e. keeps intersection between stencil buffer and what's being rendered.
    EqualIncrementStencil,
    /// Decrements the stencil value where the stencil is equal to the reference value.
    EqualDecrementStencil,
}

pub fn create_gradient_bind_group_layout(device: &Device) -> BindGroupLayout {
    device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
        entries: &[
            wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Uniform,
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            },
            wgpu::BindGroupLayoutEntry {
                binding: 1,
                visibility: wgpu::ShaderStages::FRAGMENT,
                ty: wgpu::BindingType::Texture {
                    multisampled: false,
                    view_dimension: wgpu::TextureViewDimension::D1,
                    sample_type: wgpu::TextureSampleType::Float { filterable: false },
                },
                count: None,
            },
            wgpu::BindGroupLayoutEntry {
                binding: 2,
                visibility: wgpu::ShaderStages::FRAGMENT,
                ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::NonFiltering),
                count: None,
            },
        ],
        label: Some("gradient_bind_group_layout"),
    })
}

pub fn create_pipeline(
    canvas_logical_size: (f32, f32),
    scale_factor: f64,
    fringe_width: f32,
    device: &Device,
    config: &wgpu::SurfaceConfiguration,
    pipeline_type: PipelineType,
    sample_count: u32,
) -> (
    Uniforms,
    wgpu::Buffer,
    BindGroup,
    BindGroupLayout,
    BindGroupLayout,
    RenderPipeline,
) {
    let (depth_stencil_state, targets) = match pipeline_type {
        PipelineType::EqualIncrementStencil => (
            create_equal_increment_depth_state(),
            [Some(wgpu::ColorTargetState {
                format: config.format,
                blend: Some(wgpu::BlendState {
                    // Premultiplied alpha blending
                    color: wgpu::BlendComponent {
                        src_factor: wgpu::BlendFactor::One,
                        dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
                        operation: wgpu::BlendOperation::Add,
                    },
                    alpha: wgpu::BlendComponent {
                        src_factor: wgpu::BlendFactor::One,
                        dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
                        operation: wgpu::BlendOperation::Add,
                    },
                }),
                write_mask: wgpu::ColorWrites::ALL,
            })],
        ),
        PipelineType::EqualDecrementStencil => (
            create_equal_decrement_depth_state(),
            [Some(wgpu::ColorTargetState {
                format: config.format,
                blend: Some(wgpu::BlendState {
                    // Premultiplied alpha blending
                    color: wgpu::BlendComponent {
                        src_factor: wgpu::BlendFactor::One,
                        dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
                        operation: wgpu::BlendOperation::Add,
                    },
                    alpha: wgpu::BlendComponent {
                        src_factor: wgpu::BlendFactor::One,
                        dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
                        operation: wgpu::BlendOperation::Add,
                    },
                }),
                write_mask: wgpu::ColorWrites::empty(),
            })],
        ),
    };
    let uniforms = Uniforms::new(
        canvas_logical_size.0,
        canvas_logical_size.1,
        scale_factor as f32,
        fringe_width,
    );

    let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
        label: None,
        contents: bytemuck::cast_slice(&[uniforms]),
        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
    });

    // Bind group for uniforms
    let bind_group_layout = create_uniform_bind_group_layout(device);
    // Bind group layouts for shape texturing layers (group(1) and group(2) in shader)
    let texture_bind_group_layout_layer0 =
        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("shape_texture_bind_group_layout_layer0"),
        });
    let texture_bind_group_layout_layer1 =
        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("shape_texture_bind_group_layout_layer1"),
        });
    let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
        layout: &bind_group_layout,
        entries: &[wgpu::BindGroupEntry {
            binding: 0,
            resource: uniform_buffer.as_entire_binding(),
        }],
        label: None,
    });

    // Create the render pipeline
    let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
        label: None,
        source: wgpu::ShaderSource::Wgsl(include_str!("shaders/shader.wgsl").into()),
    });

    let render_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: None,
        bind_group_layouts: &[
            &bind_group_layout,
            &texture_bind_group_layout_layer0,
            &texture_bind_group_layout_layer1,
        ],
        push_constant_ranges: &[],
    });

    let fragment_entry_point = match pipeline_type {
        PipelineType::EqualIncrementStencil => "fs_passthrough",
        PipelineType::EqualDecrementStencil => "fs_stencil_only",
    };

    let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: None,
        layout: Some(&render_pipeline_layout),
        vertex: wgpu::VertexState {
            module: &shader,
            entry_point: Some("vs_main"),
            compilation_options: Default::default(),
            buffers: &[
                CustomVertex::desc(),
                InstanceTransform::desc(),
                InstanceColor::desc(),
                InstanceMetadata::desc(),
            ],
        },
        fragment: Some(wgpu::FragmentState {
            module: &shader,
            entry_point: Some(fragment_entry_point),
            compilation_options: Default::default(),
            targets: &targets,
        }),
        primitive: wgpu::PrimitiveState::default(),
        depth_stencil: Some(depth_stencil_state),
        multisample: wgpu::MultisampleState {
            count: sample_count,
            mask: !0,
            alpha_to_coverage_enabled: false,
        },
        multiview: None,
        cache: None,
    });

    (
        uniforms,
        uniform_buffer,
        bind_group,
        texture_bind_group_layout_layer0,
        texture_bind_group_layout_layer1,
        render_pipeline,
    )
}

pub fn create_gradient_increment_pipeline(
    device: &Device,
    format: wgpu::TextureFormat,
    sample_count: u32,
    uniform_bgl: &wgpu::BindGroupLayout,
    texture_bgl_layer0: &wgpu::BindGroupLayout,
    texture_bgl_layer1: &wgpu::BindGroupLayout,
    gradient_bgl: &wgpu::BindGroupLayout,
) -> RenderPipeline {
    let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
        label: Some("gradient_increment_shader"),
        source: wgpu::ShaderSource::Wgsl(include_str!("shaders/shader.wgsl").into()),
    });

    let render_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: Some("gradient_increment_pipeline_layout"),
        bind_group_layouts: &[
            uniform_bgl,
            texture_bgl_layer0,
            texture_bgl_layer1,
            gradient_bgl,
        ],
        push_constant_ranges: &[],
    });

    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some("gradient_increment_pipeline"),
        layout: Some(&render_pipeline_layout),
        vertex: wgpu::VertexState {
            module: &shader,
            entry_point: Some("vs_main_gradient"),
            compilation_options: Default::default(),
            buffers: &[
                CustomVertex::desc(),
                InstanceTransform::desc(),
                InstanceColor::desc(),
                InstanceMetadata::desc(),
            ],
        },
        fragment: Some(wgpu::FragmentState {
            module: &shader,
            entry_point: Some("fs_passthrough_gradient"),
            compilation_options: Default::default(),
            targets: &[Some(wgpu::ColorTargetState {
                format,
                blend: Some(wgpu::BlendState {
                    color: wgpu::BlendComponent {
                        src_factor: wgpu::BlendFactor::One,
                        dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
                        operation: wgpu::BlendOperation::Add,
                    },
                    alpha: wgpu::BlendComponent {
                        src_factor: wgpu::BlendFactor::One,
                        dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
                        operation: wgpu::BlendOperation::Add,
                    },
                }),
                write_mask: wgpu::ColorWrites::ALL,
            })],
        }),
        primitive: wgpu::PrimitiveState::default(),
        depth_stencil: Some(create_equal_increment_depth_state()),
        multisample: wgpu::MultisampleState {
            count: sample_count,
            mask: !0,
            alpha_to_coverage_enabled: false,
        },
        multiview: None,
        cache: None,
    })
}

pub fn create_render_pass<'a, 'b: 'a>(
    encoder: &'a mut wgpu::CommandEncoder,
    msaa_texture_view: Option<&'b TextureView>,
    output_texture_view: &'b TextureView,
    depth_texture_view: &'b TextureView,
) -> RenderPass<'a> {
    let (view, resolve_target) = if let Some(msaa_view) = msaa_texture_view {
        (msaa_view, Some(output_texture_view))
    } else {
        (output_texture_view, None)
    };

    let render_pass = begin_render_pass_with_load_ops(
        encoder,
        None,
        view,
        resolve_target,
        depth_texture_view,
        RenderPassLoadOperations {
            color_load_op: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
            depth_load_op: wgpu::LoadOp::Clear(1.0),
            stencil_load_op: wgpu::LoadOp::Clear(0),
        },
    );

    render_pass
}

pub struct RenderPassLoadOperations {
    pub color_load_op: wgpu::LoadOp<wgpu::Color>,
    pub depth_load_op: wgpu::LoadOp<f32>,
    pub stencil_load_op: wgpu::LoadOp<u32>,
}

pub fn begin_render_pass_with_load_ops<'a, 'b: 'a>(
    encoder: &'a mut wgpu::CommandEncoder,
    label: Option<&'a str>,
    color_texture_view: &'b TextureView,
    resolve_target: Option<&'b TextureView>,
    depth_texture_view: &'b TextureView,
    load_operations: RenderPassLoadOperations,
) -> RenderPass<'a> {
    encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
        label,
        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
            view: color_texture_view,
            resolve_target,
            ops: wgpu::Operations {
                load: load_operations.color_load_op,
                store: StoreOp::Store,
            },
        })],
        depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
            view: depth_texture_view,
            depth_ops: Some(wgpu::Operations {
                load: load_operations.depth_load_op,
                store: StoreOp::Store,
            }),
            stencil_ops: Some(wgpu::Operations {
                load: load_operations.stencil_load_op,
                store: StoreOp::Store,
            }),
        }),
        timestamp_writes: None,
        occlusion_query_set: None,
    })
}

pub fn create_and_depth_texture(device: &Device, size: (u32, u32), sample_count: u32) -> Texture {
    let size = wgpu::Extent3d {
        width: size.0,
        height: size.1,
        depth_or_array_layers: 1,
    };

    device.create_texture(&wgpu::TextureDescriptor {
        label: None,
        size,
        mip_level_count: 1,
        sample_count,
        dimension: wgpu::TextureDimension::D2,
        format: wgpu::TextureFormat::Depth24PlusStencil8,
        usage: wgpu::TextureUsages::RENDER_ATTACHMENT
            | wgpu::TextureUsages::COPY_SRC
            | wgpu::TextureUsages::COPY_DST,
        view_formats: &[],
    })
}

// Renders buffer range to texture and increments stencil value where the buffer is drawn.
pub fn render_buffer_range_to_texture(
    index_range: (usize, usize), // (start_index, index_count)
    render_pass: &mut RenderPass<'_>,
    parent_stencil_reference: u32,
) {
    render_pass.set_stencil_reference(parent_stencil_reference);

    // The indices in the aggregated buffer are already offset, so we need to:
    // 1. Use the correct index range
    // 2. Set the vertex base to 0 since we're using the full vertex buffer
    let index_start = index_range.0 as u32;
    let index_end = (index_range.0 + index_range.1) as u32;

    render_pass.draw_indexed(index_start..index_end, 0, 0..1);
}

/// Creates an offscreen color texture for rendering and copying.
pub fn create_offscreen_color_texture(
    device: &Device,
    size: (u32, u32),
    format: wgpu::TextureFormat,
) -> Texture {
    device.create_texture(&wgpu::TextureDescriptor {
        label: Some("offscreen_render_texture_argb"),
        size: wgpu::Extent3d {
            width: size.0,
            height: size.1,
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format,
        usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
        view_formats: &[],
    })
}

/// Create compute bind group layout and pipeline for ARGB swizzle from BGRA bytes buffer to ARGB u32s.
pub fn create_argb_swizzle_pipeline(device: &Device) -> (BindGroupLayout, ComputePipeline) {
    let cs_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
        label: Some("argb_swizzle_cs"),
        source: wgpu::ShaderSource::Wgsl(include_str!("shaders/argb_swizzle.wgsl").into()),
    });

    let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
        label: Some("argb_swizzle_bgl"),
        entries: &[
            wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::COMPUTE,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Storage { read_only: true },
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            },
            wgpu::BindGroupLayoutEntry {
                binding: 1,
                visibility: wgpu::ShaderStages::COMPUTE,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Storage { read_only: false },
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            },
            wgpu::BindGroupLayoutEntry {
                binding: 2,
                visibility: wgpu::ShaderStages::COMPUTE,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Uniform,
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            },
        ],
    });

    let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: Some("argb_swizzle_pl"),
        bind_group_layouts: &[&bgl],
        push_constant_ranges: &[],
    });

    let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
        label: Some("argb_swizzle_pipeline"),
        layout: Some(&pipeline_layout),
        module: &cs_module,
        entry_point: Some("cs_main"),
        compilation_options: Default::default(),
        cache: None,
    });

    (bgl, pipeline)
}

/// Helper to create the ARGB swizzle bind group given buffers and params buffer.
pub fn create_argb_swizzle_bind_group(
    device: &Device,
    bgl: &BindGroupLayout,
    input_bytes: &wgpu::Buffer,
    output_words: &wgpu::Buffer,
    params: &wgpu::Buffer,
) -> BindGroup {
    device.create_bind_group(&wgpu::BindGroupDescriptor {
        label: Some("argb_swizzle_bg"),
        layout: bgl,
        entries: &[
            wgpu::BindGroupEntry {
                binding: 0,
                resource: input_bytes.as_entire_binding(),
            },
            wgpu::BindGroupEntry {
                binding: 1,
                resource: output_words.as_entire_binding(),
            },
            wgpu::BindGroupEntry {
                binding: 2,
                resource: params.as_entire_binding(),
            },
        ],
    })
}

/// Compute unpadded and padded bytes-per-row given a width and bytes-per-pixel.
/// Padded value respects wgpu::COPY_BYTES_PER_ROW_ALIGNMENT (256 bytes).
pub fn compute_padded_bytes_per_row(width: u32, bytes_per_pixel: u32) -> (u32, u32) {
    let unpadded = width * bytes_per_pixel;
    let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
    let padded = unpadded.div_ceil(align) * align;
    (unpadded, padded)
}

/// Convenience wrapper to create a buffer with a label and usage.
pub fn create_buffer(
    device: &Device,
    label: Option<&str>,
    size: u64,
    usage: wgpu::BufferUsages,
) -> wgpu::Buffer {
    device.create_buffer(&wgpu::BufferDescriptor {
        label,
        size,
        usage,
        mapped_at_creation: false,
    })
}

/// Convenience wrapper to create and initialize a buffer from bytes.
pub fn create_buffer_init(
    device: &Device,
    label: Option<&str>,
    bytes: &[u8],
    usage: wgpu::BufferUsages,
) -> wgpu::Buffer {
    device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
        label,
        contents: bytes,
        usage,
    })
}

/// Encode a copy from a texture to a buffer with the provided padded bytes-per-row.
pub fn encode_copy_texture_to_buffer(
    encoder: &mut wgpu::CommandEncoder,
    texture: &wgpu::Texture,
    buffer: &wgpu::Buffer,
    width: u32,
    height: u32,
    padded_bytes_per_row: u32,
) {
    encoder.copy_texture_to_buffer(
        wgpu::TexelCopyTextureInfo {
            texture,
            mip_level: 0,
            origin: wgpu::Origin3d::ZERO,
            aspect: wgpu::TextureAspect::All,
        },
        wgpu::TexelCopyBufferInfo {
            buffer,
            layout: wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(padded_bytes_per_row),
                rows_per_image: Some(height),
            },
        },
        wgpu::Extent3d {
            width,
            height,
            depth_or_array_layers: 1,
        },
    );
}

/// Create a CPU readback buffer of given size.
pub fn create_readback_buffer(device: &Device, label: Option<&str>, size: u64) -> wgpu::Buffer {
    create_buffer(
        device,
        label,
        size,
        wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
    )
}

/// Create a storage input buffer (COPY_DST | STORAGE), typically for texture bytes input.
pub fn create_storage_input_buffer(
    device: &Device,
    label: Option<&str>,
    size: u64,
) -> wgpu::Buffer {
    create_buffer(
        device,
        label,
        size,
        wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::STORAGE,
    )
}

/// Create a storage output buffer (STORAGE | COPY_SRC), typically for compute outputs.
pub fn create_storage_output_buffer(
    device: &Device,
    label: Option<&str>,
    size: u64,
) -> wgpu::Buffer {
    create_buffer(
        device,
        label,
        size,
        wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
    )
}

/// Parameters for ARGB compute swizzle, shared between modules.
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
pub struct ArgbParams {
    pub width: u32,
    pub height: u32,
    pub padded_bpr: u32,
    pub _pad: u32,
}

/// Create or update a uniform buffer for ArgbParams.
pub fn create_argb_params_buffer(device: &Device, params: &ArgbParams) -> wgpu::Buffer {
    create_buffer_init(
        device,
        Some("argb_params"),
        bytemuck::bytes_of(params),
        wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
    )
}

/// Creates a multisampled color texture for MSAA rendering.
/// When sample_count == 1, this should not be called (no MSAA texture needed).
pub fn create_msaa_color_texture(
    device: &Device,
    size: (u32, u32),
    format: wgpu::TextureFormat,
    sample_count: u32,
) -> Texture {
    device.create_texture(&wgpu::TextureDescriptor {
        label: Some("msaa_color_texture"),
        size: wgpu::Extent3d {
            width: size.0,
            height: size.1,
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count,
        dimension: wgpu::TextureDimension::D2,
        format,
        usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
        view_formats: &[],
    })
}

/// Creates a stencil-only pipeline: writes to the stencil buffer (IncrementClamp)
/// but produces no color output (ColorWrites::empty()).
/// Used for Step 1 of the three-step backdrop draw.
pub fn create_stencil_only_pipeline(
    device: &Device,
    format: wgpu::TextureFormat,
    sample_count: u32,
    uniform_bgl: &wgpu::BindGroupLayout,
    texture_bgl_layer0: &wgpu::BindGroupLayout,
    texture_bgl_layer1: &wgpu::BindGroupLayout,
) -> RenderPipeline {
    let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
        label: Some("stencil_only_shader"),
        source: wgpu::ShaderSource::Wgsl(include_str!("shaders/shader.wgsl").into()),
    });

    let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: Some("stencil_only_pipeline_layout"),
        bind_group_layouts: &[uniform_bgl, texture_bgl_layer0, texture_bgl_layer1],
        push_constant_ranges: &[],
    });

    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some("stencil_only_pipeline"),
        layout: Some(&pipeline_layout),
        vertex: wgpu::VertexState {
            module: &shader,
            entry_point: Some("vs_main"),
            compilation_options: Default::default(),
            buffers: &[
                CustomVertex::desc(),
                InstanceTransform::desc(),
                InstanceColor::desc(),
                InstanceMetadata::desc(),
            ],
        },
        fragment: Some(wgpu::FragmentState {
            module: &shader,
            entry_point: Some("fs_stencil_only"),
            compilation_options: Default::default(),
            targets: &[Some(wgpu::ColorTargetState {
                format,
                blend: None,
                write_mask: wgpu::ColorWrites::empty(),
            })],
        }),
        primitive: wgpu::PrimitiveState::default(),
        depth_stencil: Some(create_equal_increment_depth_state()),
        multisample: wgpu::MultisampleState {
            count: sample_count,
            mask: !0,
            alpha_to_coverage_enabled: false,
        },
        multiview: None,
        cache: None,
    })
}

/// Creates a shape color pipeline with stencil Equal + Keep (no stencil modification).
/// Same as the StencilIncrement pipeline but with pass_op = Keep.
/// Used for Step 3 of the three-step backdrop draw to avoid double stencil increment.
pub fn create_stencil_keep_color_pipeline(
    device: &Device,
    format: wgpu::TextureFormat,
    sample_count: u32,
    uniform_bgl: &wgpu::BindGroupLayout,
    texture_bgl_layer0: &wgpu::BindGroupLayout,
    texture_bgl_layer1: &wgpu::BindGroupLayout,
) -> RenderPipeline {
    let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
        label: Some("stencil_keep_color_shader"),
        source: wgpu::ShaderSource::Wgsl(include_str!("shaders/shader.wgsl").into()),
    });

    let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: Some("stencil_keep_color_pipeline_layout"),
        bind_group_layouts: &[uniform_bgl, texture_bgl_layer0, texture_bgl_layer1],
        push_constant_ranges: &[],
    });

    // Stencil: Equal + Keep (reads stencil for clipping but doesn't modify it)
    let stencil_face = wgpu::StencilFaceState {
        compare: wgpu::CompareFunction::Equal,
        fail_op: wgpu::StencilOperation::Keep,
        depth_fail_op: wgpu::StencilOperation::Keep,
        pass_op: wgpu::StencilOperation::Keep,
    };

    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some("stencil_keep_color_pipeline"),
        layout: Some(&pipeline_layout),
        vertex: wgpu::VertexState {
            module: &shader,
            entry_point: Some("vs_main"),
            compilation_options: Default::default(),
            buffers: &[
                CustomVertex::desc(),
                InstanceTransform::desc(),
                InstanceColor::desc(),
                InstanceMetadata::desc(),
            ],
        },
        fragment: Some(wgpu::FragmentState {
            module: &shader,
            entry_point: Some("fs_main"),
            compilation_options: Default::default(),
            targets: &[Some(wgpu::ColorTargetState {
                format,
                blend: Some(wgpu::BlendState {
                    color: wgpu::BlendComponent {
                        src_factor: wgpu::BlendFactor::One,
                        dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
                        operation: wgpu::BlendOperation::Add,
                    },
                    alpha: wgpu::BlendComponent {
                        src_factor: wgpu::BlendFactor::One,
                        dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
                        operation: wgpu::BlendOperation::Add,
                    },
                }),
                write_mask: wgpu::ColorWrites::ALL,
            })],
        }),
        primitive: wgpu::PrimitiveState::default(),
        depth_stencil: Some(wgpu::DepthStencilState {
            format: wgpu::TextureFormat::Depth24PlusStencil8,
            depth_write_enabled: true,
            depth_compare: wgpu::CompareFunction::Always,
            stencil: wgpu::StencilState {
                front: stencil_face,
                back: stencil_face,
                read_mask: 0xff,
                write_mask: 0x00,
            },
            bias: wgpu::DepthBiasState::default(),
        }),
        multisample: wgpu::MultisampleState {
            count: sample_count,
            mask: !0,
            alpha_to_coverage_enabled: false,
        },
        multiview: None,
        cache: None,
    })
}

pub fn create_gradient_stencil_keep_color_pipeline(
    device: &Device,
    format: wgpu::TextureFormat,
    sample_count: u32,
    uniform_bgl: &wgpu::BindGroupLayout,
    texture_bgl_layer0: &wgpu::BindGroupLayout,
    texture_bgl_layer1: &wgpu::BindGroupLayout,
    gradient_bgl: &wgpu::BindGroupLayout,
) -> RenderPipeline {
    let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
        label: Some("gradient_stencil_keep_color_shader"),
        source: wgpu::ShaderSource::Wgsl(include_str!("shaders/shader.wgsl").into()),
    });

    let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: Some("gradient_stencil_keep_color_pipeline_layout"),
        bind_group_layouts: &[
            uniform_bgl,
            texture_bgl_layer0,
            texture_bgl_layer1,
            gradient_bgl,
        ],
        push_constant_ranges: &[],
    });

    let stencil_face = wgpu::StencilFaceState {
        compare: wgpu::CompareFunction::Equal,
        fail_op: wgpu::StencilOperation::Keep,
        depth_fail_op: wgpu::StencilOperation::Keep,
        pass_op: wgpu::StencilOperation::Keep,
    };

    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some("gradient_stencil_keep_color_pipeline"),
        layout: Some(&pipeline_layout),
        vertex: wgpu::VertexState {
            module: &shader,
            entry_point: Some("vs_main_gradient"),
            compilation_options: Default::default(),
            buffers: &[
                CustomVertex::desc(),
                InstanceTransform::desc(),
                InstanceColor::desc(),
                InstanceMetadata::desc(),
            ],
        },
        fragment: Some(wgpu::FragmentState {
            module: &shader,
            entry_point: Some("fs_main_gradient"),
            compilation_options: Default::default(),
            targets: &[Some(wgpu::ColorTargetState {
                format,
                blend: Some(wgpu::BlendState {
                    color: wgpu::BlendComponent {
                        src_factor: wgpu::BlendFactor::One,
                        dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
                        operation: wgpu::BlendOperation::Add,
                    },
                    alpha: wgpu::BlendComponent {
                        src_factor: wgpu::BlendFactor::One,
                        dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
                        operation: wgpu::BlendOperation::Add,
                    },
                }),
                write_mask: wgpu::ColorWrites::ALL,
            })],
        }),
        primitive: wgpu::PrimitiveState::default(),
        depth_stencil: Some(wgpu::DepthStencilState {
            format: wgpu::TextureFormat::Depth24PlusStencil8,
            depth_write_enabled: true,
            depth_compare: wgpu::CompareFunction::Always,
            stencil: wgpu::StencilState {
                front: stencil_face,
                back: stencil_face,
                read_mask: 0xff,
                write_mask: 0x00,
            },
            bias: wgpu::DepthBiasState::default(),
        }),
        multisample: wgpu::MultisampleState {
            count: sample_count,
            mask: !0,
            alpha_to_coverage_enabled: false,
        },
        multiview: None,
        cache: None,
    })
}