viewport-lib 0.18.0

3D viewport rendering library
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
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
//! GPU particle systems.
//!
//! A particle system owns a persistent GPU buffer holding `capacity` particles.
//! Each particle stores its world-space position, velocity, lifetime remaining,
//! starting lifetime, colour, and size.
//!
//! The host calls [`ViewportGpuResources::create_gpu_particle_system`] once at
//! startup to allocate the buffer, then submits a
//! [`GpuParticleSystemItem`](crate::renderer::GpuParticleSystemItem) per frame.
//! The renderer dispatches an emit compute pass (recycling dead particles back
//! into live ones based on `EmitterConfig`), then a sim compute pass
//! (integrating `ForceField`s and decrementing lifetime), then draws the live
//! particles via the route picked in [`GpuParticleSystemConfig::render`].
//!
//! Dead particles are not compacted. The emit shader scans for slots with
//! `lifetime <= 0` and reuses them; the draw shader emits a degenerate clip
//! position for dead slots so they cost nothing in the rasteriser. Compaction
//! would require a prefix sum each frame and is not worth the cost at the
//! particle counts the API targets (1k - 200k).

use bytemuck::{Pod, Zeroable};
use wgpu::util::DeviceExt;

use crate::renderer::{ParticleMeshAlign, SpriteBlend, SpriteLitParams, SpriteSizeMode};

/// Handle to a persistent GPU particle system.
///
/// Returned by [`ViewportGpuResources::create_gpu_particle_system`]. Stable
/// until [`ViewportGpuResources::drop_gpu_particle_system`] is called.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct GpuParticleSystemId(pub(crate) usize);

impl GpuParticleSystemId {
    /// Raw slot index. Useful for debug overlays; do not synthesise these by hand.
    pub fn index(self) -> usize {
        self.0
    }
}

/// Persistent configuration for a particle system. Set at creation; the render
/// route and capacity are stable for the system's lifetime.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct GpuParticleSystemConfig {
    /// Maximum number of simultaneously live particles. Memory cost scales
    /// linearly with this value (currently 80 bytes per particle plus a small
    /// fixed overhead).
    pub capacity: u32,
    /// How the live particles are drawn each frame.
    pub render: ParticleRender,
}

impl Default for GpuParticleSystemConfig {
    fn default() -> Self {
        Self {
            capacity: 10_000,
            render: ParticleRender::default(),
        }
    }
}

/// How a particle system draws its live particles.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum ParticleRender {
    /// Draw each particle as a camera-facing billboard sprite.
    Sprite {
        /// Optional texture sampled per fragment. `None` renders solid quads
        /// tinted by the particle colour.
        texture_id: Option<u64>,
        /// GPU blend state.
        blend: SpriteBlend,
        /// Screen-space or world-space sizing for the per-particle `size`.
        size_mode: SpriteSizeMode,
        /// Whether the draw writes to depth.
        depth_write: bool,
        /// When `true`, the draw runs through the lit particle sprite pipeline
        /// and picks up the scene lighting environment. Default `false`
        /// preserves the emissive billboard look.
        lit: bool,
        /// Lighting parameters used when `lit` is `true`.
        lit_params: SpriteLitParams,
        /// Optional tangent-space normal map for the `NormalMap` mode.
        normal_texture_id: Option<u64>,
    },
    /// Draw each particle as an instance of an uploaded mesh. The vertex
    /// shader composes the per-instance transform from the live particle's
    /// position, velocity, `size`, and (for `Random` align) the spawn seed.
    /// Unlit; the particle colour multiplies an optional albedo sample.
    Mesh {
        /// Mesh handle returned by `ViewportGpuResources::upload_mesh_data`.
        mesh_id: u64,
        /// Optional albedo texture handle. `None` renders flat-tinted.
        texture_id: Option<u64>,
        /// GPU blend state.
        blend: SpriteBlend,
        /// How per-particle rotation is derived.
        align: ParticleMeshAlign,
    },
}

impl Default for ParticleRender {
    fn default() -> Self {
        ParticleRender::Sprite {
            texture_id: None,
            blend: SpriteBlend::AlphaBlend,
            size_mode: SpriteSizeMode::ScreenSpace,
            depth_write: false,
            lit: false,
            lit_params: SpriteLitParams {
                roughness: 0.9,
                normal_mode: crate::renderer::SpriteNormalMode::Spherical,
                receive_shadows: false,
                ambient_scale: 1.0,
            },
            normal_texture_id: None,
        }
    }
}

/// One particle as it lives on the GPU. Layout matches `Particle` in
/// `particle_emit.wgsl` and `particle_sim.wgsl`. Eighty bytes, naturally
/// 16-byte aligned.
#[repr(C)]
#[derive(Copy, Clone, Pod, Zeroable)]
pub(crate) struct GpuParticle {
    pub position: [f32; 3],
    pub lifetime: f32, // seconds remaining; <= 0 means dead
    pub velocity: [f32; 3],
    pub max_lifetime: f32, // initial lifetime, used for fade ramps
    pub colour: [f32; 4],
    pub size: f32,
    /// Stable per-spawn seed used by the mesh draw route for `Random` align
    /// rotation. Written by `particle_emit.wgsl`; left untouched by the sim.
    pub spawn_seed: f32,
    pub _pad: [f32; 2],
}

/// Uniform buffer matching `EmitParams` in `particle_emit.wgsl`. 96 bytes.
#[repr(C)]
#[derive(Copy, Clone, Pod, Zeroable)]
pub(crate) struct EmitParamsGpu {
    pub spawn_min: [f32; 3],
    pub spawn_kind: u32, // 0=Point, 1=Box, 2=Sphere
    pub spawn_max: [f32; 3],
    pub spawn_radius: f32, // sphere radius (Sphere only)
    pub vel_min: [f32; 3],
    pub vel_kind: u32, // 0=Fixed, 1=UniformBox, 2=UniformCone
    pub vel_max: [f32; 3],
    pub cone_half_angle: f32,
    pub vel_axis: [f32; 3],
    pub cone_min_speed: f32,
    pub colour: [f32; 4],
    pub spawn_count: u32,
    pub capacity: u32,
    pub rng_seed: u32,
    pub size: f32,
    pub lifetime_min: f32,
    pub lifetime_max: f32,
    pub cone_max_speed: f32,
    pub _pad: f32,
}

/// Maximum number of forces in a single sim dispatch. Forces are inlined into
/// the uniform buffer; bump this if it becomes a real limit (so far no game
/// effect uses more than 3-4 forces simultaneously).
pub(crate) const MAX_FORCES: usize = 8;

/// One force on the GPU. Tagged union; 32 bytes.
#[repr(C)]
#[derive(Copy, Clone, Pod, Zeroable)]
pub(crate) struct GpuForce {
    pub kind: u32, // 0=Gravity, 1=Drag, 2=PointAttractor
    pub _pad: [u32; 3],
    pub v0: [f32; 4], // Gravity: xyz=acceleration / Drag: x=coefficient / Attractor: xyz=position, w=strength
    pub v1: [f32; 4], // Attractor: x=falloff
}

/// Uniform buffer matching `SimParams` in `particle_sim.wgsl`. Forces are
/// inlined so the sim pipeline reads from a single uniform binding.
#[repr(C)]
#[derive(Copy, Clone, Pod, Zeroable)]
pub(crate) struct SimParamsGpu {
    pub dt: f32,
    pub capacity: u32,
    pub force_count: u32,
    pub _pad: u32,
    pub forces: [GpuForce; MAX_FORCES],
}

/// Per-system persistent GPU state.
pub(crate) struct ParticleSystem {
    pub capacity: u32,
    pub render: ParticleRender,
    /// `capacity` particles in `GpuParticle` layout. STORAGE + VERTEX usage so
    /// the draw pipeline can bind it directly.
    pub particle_buf: wgpu::Buffer,
    /// Single atomic u32 counter rewritten by the host before each emit
    /// dispatch and decremented by emit threads as they claim slots. Reused
    /// across frames; nothing is preserved between dispatches.
    pub emit_counter_buf: wgpu::Buffer,
    /// Bind group for the sim/emit compute pipelines (group 1).
    pub sim_bg: wgpu::BindGroup,
    /// Bind group for the sprite draw pipeline (group 1). `None` when the
    /// system's render route is not `Sprite`.
    pub draw_bg: Option<wgpu::BindGroup>,
    /// Bind group for the mesh draw pipeline (group 1). `None` when the
    /// system's render route is not `Mesh`.
    pub draw_bg_mesh: Option<wgpu::BindGroup>,
    /// Group 2 bind group for the lit draw pipeline (normal map + sampler).
    /// `None` when the system's render route is not lit.
    pub draw_lit_normal_bg: Option<wgpu::BindGroup>,
    /// Uniform buffers backing whichever draw bind group is populated.
    pub _draw_uniform_buf: Option<wgpu::Buffer>,
    /// Whether the slot is in use. The slot is reused lazily by future creates.
    pub alive: bool,
    /// Frame count since creation; used to seed the emit RNG so a freshly
    /// created system gets a different sequence from one that has been
    /// running for a while.
    pub frame_counter: u32,
    /// Fractional spawn accumulator. `rate * dt` rarely lands on an integer
    /// per frame; the fractional remainder rolls over to the next frame so
    /// the long-term average emission matches the configured rate.
    pub spawn_accumulator: f32,
}

/// Which draw family the render loop should dispatch for this system.
#[derive(Copy, Clone, Debug)]
pub(crate) enum ParticleDrawRoute {
    Sprite { lit: bool },
    Mesh { mesh_id: u64 },
}

/// Per-frame data for one particle system, populated in prepare and consumed
/// in render.
pub(crate) struct ParticleFrameData {
    /// Index into `particle_systems`.
    pub system_idx: usize,
    /// Picked at submit time; consumed by the draw pipeline router.
    pub blend: SpriteBlend,
    /// Whether to skip the draw (hidden item).
    pub hidden: bool,
    /// Which draw family to dispatch.
    pub route: ParticleDrawRoute,
}

impl crate::resources::ViewportGpuResources {
    /// Allocate a persistent GPU particle system.
    ///
    /// The returned [`GpuParticleSystemId`] stays valid until
    /// [`drop_gpu_particle_system`](Self::drop_gpu_particle_system) is called
    /// or the renderer is dropped.
    pub fn create_gpu_particle_system(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        config: &GpuParticleSystemConfig,
    ) -> GpuParticleSystemId {
        self.ensure_particle_pipelines(device);

        let capacity = config.capacity.max(1);

        // Persistent particle buffer, initialised to all-dead.
        let particle_bytes_len = (capacity as usize) * std::mem::size_of::<GpuParticle>();
        let zero_particles = vec![0u8; particle_bytes_len];
        let particle_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("gpu_particle_buf"),
            contents: &zero_particles,
            usage: wgpu::BufferUsages::STORAGE
                | wgpu::BufferUsages::VERTEX
                | wgpu::BufferUsages::COPY_DST,
        });

        // Atomic counter rewritten per emit dispatch.
        let emit_counter_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("gpu_particle_emit_counter"),
            contents: bytemuck::bytes_of(&0u32),
            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
        });

        // Draw-side state. The sprite route uses the existing sprite-style
        // uniform; the mesh route uses a smaller uniform with the align mode
        // and a `has_texture` flag.
        enum DrawState {
            Sprite {
                texture_id: Option<u64>,
                size_mode: SpriteSizeMode,
                lit: bool,
                lit_params: SpriteLitParams,
                normal_texture_id: Option<u64>,
            },
            Mesh {
                texture_id: Option<u64>,
                align: ParticleMeshAlign,
            },
        }
        let draw_state = match &config.render {
            ParticleRender::Sprite {
                texture_id,
                blend: _,
                size_mode,
                depth_write: _,
                lit,
                lit_params,
                normal_texture_id,
            } => DrawState::Sprite {
                texture_id: *texture_id,
                size_mode: *size_mode,
                lit: *lit,
                lit_params: *lit_params,
                normal_texture_id: *normal_texture_id,
            },
            ParticleRender::Mesh {
                texture_id,
                blend: _,
                align,
                mesh_id: _,
            } => DrawState::Mesh {
                texture_id: *texture_id,
                align: *align,
            },
        };

        let _ = queue; // queue currently unused; reserved for textures upload paths

        let sim_bgl = self
            .particle_sim_bgl
            .as_ref()
            .expect("ensure_particle_pipelines failed to create sim BGL");
        let sim_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("gpu_particle_sim_bg"),
            layout: sim_bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: particle_buf.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: emit_counter_buf.as_entire_binding(),
                },
            ],
        });

        // Per-route draw resources. Exactly one of `sprite_draw_bg` and
        // `mesh_draw_bg` is populated; the other arm stays `None`.
        let mut sprite_draw_bg: Option<wgpu::BindGroup> = None;
        let mut mesh_draw_bg: Option<wgpu::BindGroup> = None;
        let mut sprite_lit_normal_bg: Option<wgpu::BindGroup> = None;
        let draw_uniform_buf: Option<wgpu::Buffer>;

        match draw_state {
            DrawState::Sprite {
                texture_id,
                size_mode,
                lit,
                lit_params,
                normal_texture_id,
            } => {
                #[repr(C)]
                #[derive(Copy, Clone, Pod, Zeroable)]
                struct SpriteDrawUniform {
                    model: [[f32; 4]; 4],
                    world_space: u32,
                    has_texture: u32,
                    normal_mode: u32,
                    has_normal_map: u32,
                    ambient_scale: f32,
                    roughness: f32,
                    _pad0: u32,
                    _pad1: u32,
                }
                let normal_mode_u32 = match lit_params.normal_mode {
                    crate::renderer::SpriteNormalMode::Spherical => 0u32,
                    crate::renderer::SpriteNormalMode::Flat => 1u32,
                    crate::renderer::SpriteNormalMode::NormalMap => 2u32,
                };
                let uniform = SpriteDrawUniform {
                    model: glam::Mat4::IDENTITY.to_cols_array_2d(),
                    world_space: matches!(size_mode, SpriteSizeMode::WorldSpace) as u32,
                    has_texture: texture_id.is_some() as u32,
                    normal_mode: normal_mode_u32,
                    has_normal_map: normal_texture_id.is_some() as u32,
                    ambient_scale: lit_params.ambient_scale,
                    roughness: lit_params.roughness,
                    _pad0: 0,
                    _pad1: 0,
                };
                let uniform_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                    label: Some("gpu_particle_sprite_draw_uniform"),
                    contents: bytemuck::bytes_of(&uniform),
                    usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                });
                let texture_view = match texture_id {
                    Some(id) if (id as usize) < self.textures.len() => {
                        &self.textures[id as usize].view
                    }
                    _ => &self.fallback_lut_view,
                };
                let draw_bgl = self
                    .particle_draw_bgl
                    .as_ref()
                    .expect("ensure_particle_pipelines failed to create draw BGL");
                sprite_draw_bg = Some(device.create_bind_group(&wgpu::BindGroupDescriptor {
                    label: Some("gpu_particle_draw_bg"),
                    layout: draw_bgl,
                    entries: &[
                        wgpu::BindGroupEntry {
                            binding: 0,
                            resource: uniform_buf.as_entire_binding(),
                        },
                        wgpu::BindGroupEntry {
                            binding: 1,
                            resource: wgpu::BindingResource::TextureView(texture_view),
                        },
                        wgpu::BindGroupEntry {
                            binding: 2,
                            resource: wgpu::BindingResource::Sampler(&self.material_sampler),
                        },
                        wgpu::BindGroupEntry {
                            binding: 3,
                            resource: particle_buf.as_entire_binding(),
                        },
                    ],
                }));
                if lit {
                    let lit_bgl = self
                        .particle_sprite_lit_bgl
                        .as_ref()
                        .expect("ensure_particle_pipelines failed to create lit BGL");
                    let normal_view = match normal_texture_id {
                        Some(id) if (id as usize) < self.textures.len() => {
                            &self.textures[id as usize].view
                        }
                        _ => &self.fallback_normal_map_view,
                    };
                    sprite_lit_normal_bg =
                        Some(device.create_bind_group(&wgpu::BindGroupDescriptor {
                            label: Some("gpu_particle_lit_normal_bg"),
                            layout: lit_bgl,
                            entries: &[
                                wgpu::BindGroupEntry {
                                    binding: 0,
                                    resource: wgpu::BindingResource::TextureView(normal_view),
                                },
                                wgpu::BindGroupEntry {
                                    binding: 1,
                                    resource: wgpu::BindingResource::Sampler(&self.material_sampler),
                                },
                            ],
                        }));
                }
                draw_uniform_buf = Some(uniform_buf);
            }
            DrawState::Mesh { texture_id, align } => {
                #[repr(C)]
                #[derive(Copy, Clone, Pod, Zeroable)]
                struct MeshDrawUniform {
                    align: u32,
                    has_texture: u32,
                    _pad0: u32,
                    _pad1: u32,
                }
                let align_u32 = match align {
                    ParticleMeshAlign::Identity => 0u32,
                    ParticleMeshAlign::Velocity => 1u32,
                    ParticleMeshAlign::Random => 2u32,
                };
                let uniform = MeshDrawUniform {
                    align: align_u32,
                    has_texture: texture_id.is_some() as u32,
                    _pad0: 0,
                    _pad1: 0,
                };
                let uniform_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                    label: Some("gpu_particle_mesh_draw_uniform"),
                    contents: bytemuck::bytes_of(&uniform),
                    usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                });
                let texture_view = match texture_id {
                    Some(id) if (id as usize) < self.textures.len() => {
                        &self.textures[id as usize].view
                    }
                    _ => &self.fallback_texture.view,
                };
                let mesh_bgl = self
                    .particle_mesh_draw_bgl
                    .as_ref()
                    .expect("ensure_particle_pipelines failed to create mesh draw BGL");
                mesh_draw_bg = Some(device.create_bind_group(&wgpu::BindGroupDescriptor {
                    label: Some("gpu_particle_mesh_draw_bg"),
                    layout: mesh_bgl,
                    entries: &[
                        wgpu::BindGroupEntry {
                            binding: 0,
                            resource: uniform_buf.as_entire_binding(),
                        },
                        wgpu::BindGroupEntry {
                            binding: 1,
                            resource: wgpu::BindingResource::TextureView(texture_view),
                        },
                        wgpu::BindGroupEntry {
                            binding: 2,
                            resource: wgpu::BindingResource::Sampler(&self.material_sampler),
                        },
                        wgpu::BindGroupEntry {
                            binding: 3,
                            resource: particle_buf.as_entire_binding(),
                        },
                    ],
                }));
                draw_uniform_buf = Some(uniform_buf);
            }
        }

        let system = ParticleSystem {
            capacity,
            render: config.render.clone(),
            particle_buf,
            emit_counter_buf,
            sim_bg,
            draw_bg: sprite_draw_bg,
            draw_bg_mesh: mesh_draw_bg,
            draw_lit_normal_bg: sprite_lit_normal_bg,
            _draw_uniform_buf: draw_uniform_buf,
            alive: true,
            frame_counter: 0,
            spawn_accumulator: 0.0,
        };

        if let Some(idx) = self
            .particle_systems
            .iter()
            .position(|slot: &Option<ParticleSystem>| slot.as_ref().is_none_or(|s| !s.alive))
        {
            self.particle_systems[idx] = Some(system);
            GpuParticleSystemId(idx)
        } else {
            self.particle_systems.push(Some(system));
            GpuParticleSystemId(self.particle_systems.len() - 1)
        }
    }

    /// Release a particle system. The handle becomes invalid; the slot is
    /// reused on the next `create_gpu_particle_system` call.
    pub fn drop_gpu_particle_system(&mut self, id: GpuParticleSystemId) {
        if let Some(Some(s)) = self.particle_systems.get_mut(id.0) {
            s.alive = false;
        }
    }

    #[allow(dead_code)]
    pub(crate) fn particle_system(&self, id: GpuParticleSystemId) -> Option<&ParticleSystem> {
        self.particle_systems
            .get(id.0)?
            .as_ref()
            .filter(|s| s.alive)
    }

    #[allow(dead_code)]
    pub(crate) fn particle_system_mut(
        &mut self,
        id: GpuParticleSystemId,
    ) -> Option<&mut ParticleSystem> {
        self.particle_systems
            .get_mut(id.0)?
            .as_mut()
            .filter(|s| s.alive)
    }

    /// Lazily create the compute + draw pipelines used by every particle
    /// system. No-op once the bind group layouts are present.
    pub(crate) fn ensure_particle_pipelines(&mut self, device: &wgpu::Device) {
        if self.particle_sim_bgl.is_some() {
            return;
        }

        // Group 0: emit/sim params (uniform).
        let params_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("gpu_particle_params_bgl"),
            entries: &[wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::COMPUTE,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Uniform,
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            }],
        });

        // Group 1 (sim/emit): particle buffer + atomic emit counter.
        let sim_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("gpu_particle_sim_bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    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: 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,
                },
            ],
        });

        // Group 1 (draw): sprite uniform + texture + sampler + particle buffer.
        let draw_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("gpu_particle_draw_bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::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 {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 3,
                    visibility: wgpu::ShaderStages::VERTEX,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: true },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
            ],
        });

        // Compute pipelines.
        let emit_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("particle_emit_shader"),
            source: wgpu::ShaderSource::Wgsl(
                include_str!(concat!(env!("OUT_DIR"), "/particle_emit.wgsl")).into(),
            ),
        });
        let sim_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("particle_sim_shader"),
            source: wgpu::ShaderSource::Wgsl(
                include_str!(concat!(env!("OUT_DIR"), "/particle_sim.wgsl")).into(),
            ),
        });

        let compute_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("particle_compute_layout"),
            bind_group_layouts: &[&params_bgl, &sim_bgl],
            push_constant_ranges: &[],
        });

        let emit_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: Some("particle_emit_pipeline"),
            layout: Some(&compute_layout),
            module: &emit_shader,
            entry_point: Some("emit_main"),
            compilation_options: wgpu::PipelineCompilationOptions::default(),
            cache: None,
        });

        let sim_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: Some("particle_sim_pipeline"),
            layout: Some(&compute_layout),
            module: &sim_shader,
            entry_point: Some("sim_main"),
            compilation_options: wgpu::PipelineCompilationOptions::default(),
            cache: None,
        });

        // Draw pipelines: three blend variants of the same shader.
        let sprite_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("particle_sprite_shader"),
            source: wgpu::ShaderSource::Wgsl(
                include_str!(concat!(env!("OUT_DIR"), "/particle_sprite.wgsl")).into(),
            ),
        });

        let draw_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("particle_draw_layout"),
            bind_group_layouts: &[&self.camera_bind_group_layout, &draw_bgl],
            push_constant_ranges: &[],
        });

        let sample_count = self.sample_count;
        let additive = wgpu::BlendState {
            color: wgpu::BlendComponent {
                src_factor: wgpu::BlendFactor::One,
                dst_factor: wgpu::BlendFactor::One,
                operation: wgpu::BlendOperation::Add,
            },
            alpha: wgpu::BlendComponent {
                src_factor: wgpu::BlendFactor::One,
                dst_factor: wgpu::BlendFactor::One,
                operation: wgpu::BlendOperation::Add,
            },
        };
        let premul = 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,
            },
        };

        let make_draw = |fmt: wgpu::TextureFormat, blend: wgpu::BlendState, label: &str| {
            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some(label),
                layout: Some(&draw_layout),
                vertex: wgpu::VertexState {
                    module: &sprite_shader,
                    entry_point: Some("vs_main"),
                    buffers: &[],
                    compilation_options: wgpu::PipelineCompilationOptions::default(),
                },
                fragment: Some(wgpu::FragmentState {
                    module: &sprite_shader,
                    entry_point: Some("fs_main"),
                    targets: &[Some(wgpu::ColorTargetState {
                        format: fmt,
                        blend: Some(blend),
                        write_mask: wgpu::ColorWrites::ALL,
                    })],
                    compilation_options: wgpu::PipelineCompilationOptions::default(),
                }),
                primitive: wgpu::PrimitiveState {
                    topology: wgpu::PrimitiveTopology::TriangleList,
                    cull_mode: None,
                    ..Default::default()
                },
                depth_stencil: Some(wgpu::DepthStencilState {
                    format: wgpu::TextureFormat::Depth24PlusStencil8,
                    depth_write_enabled: false,
                    depth_compare: wgpu::CompareFunction::Less,
                    stencil: wgpu::StencilState::default(),
                    bias: wgpu::DepthBiasState::default(),
                }),
                multisample: wgpu::MultisampleState {
                    count: sample_count,
                    ..Default::default()
                },
                multiview: None,
                cache: None,
            })
        };

        let ldr = self.target_format;
        let hdr = wgpu::TextureFormat::Rgba16Float;
        let alpha = wgpu::BlendState::ALPHA_BLENDING;
        self.particle_sprite_pipeline_alpha = Some(crate::resources::DualPipeline {
            ldr: make_draw(ldr, alpha, "particle_sprite_alpha"),
            hdr: make_draw(hdr, alpha, "particle_sprite_alpha"),
        });
        self.particle_sprite_pipeline_additive = Some(crate::resources::DualPipeline {
            ldr: make_draw(ldr, additive, "particle_sprite_additive"),
            hdr: make_draw(hdr, additive, "particle_sprite_additive"),
        });
        self.particle_sprite_pipeline_premultiplied = Some(crate::resources::DualPipeline {
            ldr: make_draw(ldr, premul, "particle_sprite_premultiplied"),
            hdr: make_draw(hdr, premul, "particle_sprite_premultiplied"),
        });

        // Lit GPU particle sprite pipelines. Same vertex inputs and draw BGL
        // as the emissive path; group 2 adds the optional normal-map binding
        // and the shader pulls scene lighting via the camera bind group.
        let lit_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("gpu_particle_lit_bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
            ],
        });

        let lit_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("particle_sprite_lit_shader"),
            source: wgpu::ShaderSource::Wgsl(
                include_str!(concat!(env!("OUT_DIR"), "/particle_sprite_lit.wgsl")).into(),
            ),
        });

        let lit_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("particle_draw_lit_layout"),
            bind_group_layouts: &[&self.camera_bind_group_layout, &draw_bgl, &lit_bgl],
            push_constant_ranges: &[],
        });

        let make_lit_draw = |fmt: wgpu::TextureFormat, blend: wgpu::BlendState, label: &str| {
            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some(label),
                layout: Some(&lit_layout),
                vertex: wgpu::VertexState {
                    module: &lit_shader,
                    entry_point: Some("vs_main"),
                    buffers: &[],
                    compilation_options: wgpu::PipelineCompilationOptions::default(),
                },
                fragment: Some(wgpu::FragmentState {
                    module: &lit_shader,
                    entry_point: Some("fs_main"),
                    targets: &[Some(wgpu::ColorTargetState {
                        format: fmt,
                        blend: Some(blend),
                        write_mask: wgpu::ColorWrites::ALL,
                    })],
                    compilation_options: wgpu::PipelineCompilationOptions::default(),
                }),
                primitive: wgpu::PrimitiveState {
                    topology: wgpu::PrimitiveTopology::TriangleList,
                    cull_mode: None,
                    ..Default::default()
                },
                depth_stencil: Some(wgpu::DepthStencilState {
                    format: wgpu::TextureFormat::Depth24PlusStencil8,
                    depth_write_enabled: false,
                    depth_compare: wgpu::CompareFunction::Less,
                    stencil: wgpu::StencilState::default(),
                    bias: wgpu::DepthBiasState::default(),
                }),
                multisample: wgpu::MultisampleState {
                    count: sample_count,
                    ..Default::default()
                },
                multiview: None,
                cache: None,
            })
        };

        self.particle_sprite_lit_pipeline_alpha = Some(crate::resources::DualPipeline {
            ldr: make_lit_draw(ldr, alpha, "particle_sprite_lit_alpha"),
            hdr: make_lit_draw(hdr, alpha, "particle_sprite_lit_alpha"),
        });
        self.particle_sprite_lit_pipeline_additive = Some(crate::resources::DualPipeline {
            ldr: make_lit_draw(ldr, additive, "particle_sprite_lit_additive"),
            hdr: make_lit_draw(hdr, additive, "particle_sprite_lit_additive"),
        });
        self.particle_sprite_lit_pipeline_premultiplied = Some(crate::resources::DualPipeline {
            ldr: make_lit_draw(ldr, premul, "particle_sprite_lit_premultiplied"),
            hdr: make_lit_draw(hdr, premul, "particle_sprite_lit_premultiplied"),
        });

        let lit_fallback_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("gpu_particle_lit_fallback_bg"),
            layout: &lit_bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&self.fallback_normal_map_view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&self.material_sampler),
                },
            ],
        });

        self.particle_sprite_lit_bgl = Some(lit_bgl);
        self.particle_sprite_lit_fallback_bg = Some(lit_fallback_bg);

        // Mesh-route draw pipelines. Same blend variants as the sprite route,
        // but the vertex stage consumes the mesh's standard `Vertex` layout
        // on slot 0 and composes the per-instance transform inline from the
        // bound particle storage buffer.
        let mesh_draw_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("gpu_particle_mesh_draw_bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::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 {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 3,
                    visibility: wgpu::ShaderStages::VERTEX,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: true },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
            ],
        });

        let mesh_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("particle_mesh_shader"),
            source: wgpu::ShaderSource::Wgsl(
                include_str!(concat!(env!("OUT_DIR"), "/particle_mesh.wgsl")).into(),
            ),
        });

        let mesh_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("particle_mesh_draw_layout"),
            bind_group_layouts: &[&self.camera_bind_group_layout, &mesh_draw_bgl],
            push_constant_ranges: &[],
        });

        let make_mesh_draw = |fmt: wgpu::TextureFormat, blend: wgpu::BlendState, label: &str| {
            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some(label),
                layout: Some(&mesh_layout),
                vertex: wgpu::VertexState {
                    module: &mesh_shader,
                    entry_point: Some("vs_main"),
                    buffers: &[crate::resources::types::Vertex::buffer_layout()],
                    compilation_options: wgpu::PipelineCompilationOptions::default(),
                },
                fragment: Some(wgpu::FragmentState {
                    module: &mesh_shader,
                    entry_point: Some("fs_main"),
                    targets: &[Some(wgpu::ColorTargetState {
                        format: fmt,
                        blend: Some(blend),
                        write_mask: wgpu::ColorWrites::ALL,
                    })],
                    compilation_options: wgpu::PipelineCompilationOptions::default(),
                }),
                primitive: wgpu::PrimitiveState {
                    topology: wgpu::PrimitiveTopology::TriangleList,
                    cull_mode: Some(wgpu::Face::Back),
                    ..Default::default()
                },
                depth_stencil: Some(wgpu::DepthStencilState {
                    format: wgpu::TextureFormat::Depth24PlusStencil8,
                    depth_write_enabled: false,
                    depth_compare: wgpu::CompareFunction::Less,
                    stencil: wgpu::StencilState::default(),
                    bias: wgpu::DepthBiasState::default(),
                }),
                multisample: wgpu::MultisampleState {
                    count: sample_count,
                    ..Default::default()
                },
                multiview: None,
                cache: None,
            })
        };

        self.particle_mesh_pipeline_alpha = Some(crate::resources::DualPipeline {
            ldr: make_mesh_draw(ldr, alpha, "particle_mesh_alpha"),
            hdr: make_mesh_draw(hdr, alpha, "particle_mesh_alpha"),
        });
        self.particle_mesh_pipeline_additive = Some(crate::resources::DualPipeline {
            ldr: make_mesh_draw(ldr, additive, "particle_mesh_additive"),
            hdr: make_mesh_draw(hdr, additive, "particle_mesh_additive"),
        });
        self.particle_mesh_pipeline_premultiplied = Some(crate::resources::DualPipeline {
            ldr: make_mesh_draw(ldr, premul, "particle_mesh_premultiplied"),
            hdr: make_mesh_draw(hdr, premul, "particle_mesh_premultiplied"),
        });
        self.particle_mesh_draw_bgl = Some(mesh_draw_bgl);

        self.particle_params_bgl = Some(params_bgl);
        self.particle_sim_bgl = Some(sim_bgl);
        self.particle_draw_bgl = Some(draw_bgl);
        self.particle_emit_pipeline = Some(emit_pipeline);
        self.particle_sim_pipeline = Some(sim_pipeline);
    }

    /// Run emit + sim compute passes for every particle system referenced this
    /// frame. Returns per-job draw metadata for the render phase.
    pub(crate) fn run_particle_jobs(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        items: &[crate::renderer::GpuParticleSystemItem],
    ) -> Vec<ParticleFrameData> {
        if items.is_empty() {
            return Vec::new();
        }
        self.ensure_particle_pipelines(device);

        let emit_pipeline = self
            .particle_emit_pipeline
            .as_ref()
            .expect("particle pipelines should exist after ensure")
            .clone();
        let sim_pipeline = self
            .particle_sim_pipeline
            .as_ref()
            .expect("particle pipelines should exist after ensure")
            .clone();
        let params_bgl = self
            .particle_params_bgl
            .as_ref()
            .expect("particle params BGL")
            .clone();

        let mut frame_data: Vec<ParticleFrameData> = Vec::with_capacity(items.len());
        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("particle_compute_encoder"),
        });

        for item in items {
            let idx = item.system_id.0;
            let (blend, route) = match self.particle_systems.get(idx).and_then(|s| s.as_ref()) {
                Some(s) if s.alive => match &s.render {
                    ParticleRender::Sprite { blend, lit, .. } => {
                        (*blend, ParticleDrawRoute::Sprite { lit: *lit })
                    }
                    ParticleRender::Mesh {
                        blend, mesh_id, ..
                    } => (*blend, ParticleDrawRoute::Mesh { mesh_id: *mesh_id }),
                },
                _ => continue,
            };

            let hidden = item.settings.hidden;

            // Pull mutable state out, build dispatch state outside the borrow.
            let (
                capacity,
                particle_buf_binding,
                emit_counter_binding,
                sim_bg,
                spawn_count,
                frame_counter,
            ) = {
                let system = self.particle_systems[idx].as_mut().unwrap();
                let dt = item.time_step.max(0.0);
                system.spawn_accumulator += item.emitter.rate * dt;
                let spawn_count = system.spawn_accumulator.floor() as u32;
                system.spawn_accumulator -= spawn_count as f32;
                system.frame_counter = system.frame_counter.wrapping_add(1);
                let frame_counter = system.frame_counter;
                (
                    system.capacity,
                    system.particle_buf.as_entire_binding(),
                    system.emit_counter_buf.as_entire_binding(),
                    // Need to clone the bind group; wgpu allows this cheaply (Arc inside).
                    system.sim_bg.clone(),
                    spawn_count,
                    frame_counter,
                )
            };
            let _ = (particle_buf_binding, emit_counter_binding); // bound through sim_bg

            let workgroups = capacity.div_ceil(64);

            // ----- Emit -----
            if spawn_count > 0 {
                queue.write_buffer(
                    &self.particle_systems[idx]
                        .as_ref()
                        .unwrap()
                        .emit_counter_buf,
                    0,
                    bytemuck::bytes_of(&spawn_count),
                );

                let emit_params =
                    build_emit_params(&item.emitter, capacity, spawn_count, frame_counter);
                let emit_uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                    label: Some("particle_emit_params"),
                    contents: bytemuck::bytes_of(&emit_params),
                    usage: wgpu::BufferUsages::UNIFORM,
                });
                let emit_params_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
                    label: Some("particle_emit_params_bg"),
                    layout: &params_bgl,
                    entries: &[wgpu::BindGroupEntry {
                        binding: 0,
                        resource: emit_uniform.as_entire_binding(),
                    }],
                });

                let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                    label: Some("particle_emit_pass"),
                    timestamp_writes: None,
                });
                pass.set_pipeline(&emit_pipeline);
                pass.set_bind_group(0, &emit_params_bg, &[]);
                pass.set_bind_group(1, &sim_bg, &[]);
                pass.dispatch_workgroups(workgroups, 1, 1);
            }

            // ----- Sim -----
            let sim_params = build_sim_params(item.time_step, capacity, &item.forces);
            let sim_uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("particle_sim_params"),
                contents: bytemuck::bytes_of(&sim_params),
                usage: wgpu::BufferUsages::UNIFORM,
            });
            let sim_params_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("particle_sim_params_bg"),
                layout: &params_bgl,
                entries: &[wgpu::BindGroupEntry {
                    binding: 0,
                    resource: sim_uniform.as_entire_binding(),
                }],
            });

            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("particle_sim_pass"),
                timestamp_writes: None,
            });
            pass.set_pipeline(&sim_pipeline);
            pass.set_bind_group(0, &sim_params_bg, &[]);
            pass.set_bind_group(1, &sim_bg, &[]);
            pass.dispatch_workgroups(workgroups, 1, 1);
            drop(pass);

            frame_data.push(ParticleFrameData {
                system_idx: idx,
                blend,
                hidden,
                route,
            });
        }

        queue.submit(std::iter::once(encoder.finish()));
        frame_data
    }
}

fn build_emit_params(
    e: &crate::renderer::EmitterConfig,
    capacity: u32,
    spawn_count: u32,
    frame_counter: u32,
) -> EmitParamsGpu {
    use crate::renderer::{SpawnShape, VelocityDist};

    let mut out = EmitParamsGpu {
        spawn_min: [0.0; 3],
        spawn_kind: 0,
        spawn_max: [0.0; 3],
        spawn_radius: 0.0,
        vel_min: [0.0; 3],
        vel_kind: 0,
        vel_max: [0.0; 3],
        cone_half_angle: 0.0,
        vel_axis: [0.0; 3],
        cone_min_speed: 0.0,
        colour: e.colour,
        spawn_count,
        capacity,
        rng_seed: frame_counter.wrapping_mul(0x9E3779B1),
        size: e.size,
        lifetime_min: e.lifetime.0,
        lifetime_max: e.lifetime.1,
        cone_max_speed: 0.0,
        _pad: 0.0,
    };

    match e.spawn_shape {
        SpawnShape::Point(p) => {
            out.spawn_kind = 0;
            out.spawn_min = p;
        }
        SpawnShape::Box { min, max } => {
            out.spawn_kind = 1;
            out.spawn_min = min;
            out.spawn_max = max;
        }
        SpawnShape::Sphere { center, radius } => {
            out.spawn_kind = 2;
            out.spawn_min = center;
            out.spawn_radius = radius;
        }
    }

    match e.initial_velocity {
        VelocityDist::Fixed(v) => {
            out.vel_kind = 0;
            out.vel_min = v;
        }
        VelocityDist::UniformBox { min, max } => {
            out.vel_kind = 1;
            out.vel_min = min;
            out.vel_max = max;
        }
        VelocityDist::UniformCone {
            axis,
            half_angle,
            min_speed,
            max_speed,
        } => {
            out.vel_kind = 2;
            out.vel_axis = axis;
            out.cone_half_angle = half_angle;
            out.cone_min_speed = min_speed;
            out.cone_max_speed = max_speed;
        }
    }

    out
}

fn build_sim_params(
    dt: f32,
    capacity: u32,
    forces: &[crate::renderer::ForceField],
) -> SimParamsGpu {
    use crate::renderer::ForceField;

    let mut gpu_forces = [GpuForce {
        kind: 0,
        _pad: [0; 3],
        v0: [0.0; 4],
        v1: [0.0; 4],
    }; MAX_FORCES];

    let n = forces.len().min(MAX_FORCES);
    for (i, f) in forces.iter().take(n).enumerate() {
        match *f {
            ForceField::Gravity(a) => {
                gpu_forces[i].kind = 0;
                gpu_forces[i].v0 = [a[0], a[1], a[2], 0.0];
            }
            ForceField::Drag(k) => {
                gpu_forces[i].kind = 1;
                gpu_forces[i].v0 = [k, 0.0, 0.0, 0.0];
            }
            ForceField::PointAttractor {
                position,
                strength,
                falloff,
            } => {
                gpu_forces[i].kind = 2;
                gpu_forces[i].v0 = [position[0], position[1], position[2], strength];
                gpu_forces[i].v1 = [falloff, 0.0, 0.0, 0.0];
            }
        }
    }

    SimParamsGpu {
        dt,
        capacity,
        force_count: n as u32,
        _pad: 0,
        forces: gpu_forces,
    }
}