proof-engine 0.1.1

A mathematical rendering engine for Rust. Every visual is the output of a mathematical function.
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
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
//! Mathematical particle system.
//!
//! Particles are driven by MathFunctions, not simple velocity/gravity.
//! This creates particles that move in mathematically meaningful ways.
//! Includes emitters, forces, trails, sub-emitters, collision, GPU data export.

pub mod emitters;
pub mod flock;
pub mod gpu_particles;
pub mod particle_render;

use crate::glyph::{Glyph, RenderLayer};
use crate::math::{MathFunction, ForceField, Falloff, AttractorType};
use crate::math::fields::falloff_factor;
use glam::{Vec2, Vec3, Vec4, Mat4};
use std::collections::HashMap;

// โ”€โ”€โ”€ Particle flags โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Bitfield of particle feature flags.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ParticleFlags(pub u32);

impl ParticleFlags {
    pub const COLLIDES:           Self = ParticleFlags(0x0001);
    pub const GRAVITY:            Self = ParticleFlags(0x0002);
    pub const AFFECTED_BY_FIELDS: Self = ParticleFlags(0x0004);
    pub const EMIT_ON_DEATH:      Self = ParticleFlags(0x0008);
    pub const ATTRACTOR:          Self = ParticleFlags(0x0010);
    pub const TRAIL_EMITTER:      Self = ParticleFlags(0x0020);
    pub const WORLD_SPACE:        Self = ParticleFlags(0x0040);
    pub const STRETCH:            Self = ParticleFlags(0x0080);
    pub const GPU_SIMULATED:      Self = ParticleFlags(0x0100);

    pub fn empty() -> Self { Self(0) }
    pub fn contains(self, other: Self) -> bool { (self.0 & other.0) == other.0 }
    pub fn insert(&mut self, other: Self) { self.0 |= other.0; }
    pub fn remove(&mut self, other: Self) { self.0 &= !other.0; }
}

impl std::ops::BitOr for ParticleFlags {
    type Output = Self;
    fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) }
}

impl std::ops::BitOrAssign for ParticleFlags {
    fn bitor_assign(&mut self, rhs: Self) { self.0 |= rhs.0; }
}

// โ”€โ”€โ”€ Core particle types โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// An individual math-driven particle.
#[derive(Clone)]
pub struct MathParticle {
    pub glyph:        Glyph,
    pub behavior:     MathFunction,
    pub trail:        bool,
    pub trail_length: u8,
    pub trail_decay:  f32,
    pub interaction:  ParticleInteraction,
    /// Origin position (behavior is evaluated relative to this).
    pub origin:       Vec3,
    pub age:          f32,
    pub lifetime:     f32,
    pub velocity:     Vec3,
    pub acceleration: Vec3,
    pub drag:         f32,
    pub spin:         f32,
    pub scale:        f32,
    pub scale_over_life: Option<ScaleCurve>,
    pub color_over_life: Option<ColorGradient>,
    pub size_over_life:  Option<FloatCurve>,
    pub group:           Option<u32>,
    pub sub_emitter:     Option<Box<SubEmitterRef>>,
    pub flags:           ParticleFlags,
    pub user_data:       [f32; 4],
}

impl Default for MathParticle {
    fn default() -> Self {
        Self {
            glyph:           Glyph::default(),
            behavior:        MathFunction::Sine { amplitude: 1.0, frequency: 1.0, phase: 0.0 },
            trail:           false,
            trail_length:    0,
            trail_decay:     0.5,
            interaction:     ParticleInteraction::None,
            origin:          Vec3::ZERO,
            age:             0.0,
            lifetime:        2.0,
            velocity:        Vec3::ZERO,
            acceleration:    Vec3::ZERO,
            drag:            0.01,
            spin:            0.0,
            scale:           1.0,
            scale_over_life: None,
            color_over_life: None,
            size_over_life:  None,
            group:           None,
            sub_emitter:     None,
            flags:           ParticleFlags::empty(),
            user_data:       [0.0; 4],
        }
    }
}

/// How a particle interacts with other nearby particles.
#[derive(Clone, Debug)]
pub enum ParticleInteraction {
    None,
    Attract(f32),
    Repel(f32),
    Flock {
        alignment:  f32,
        cohesion:   f32,
        separation: f32,
        radius:     f32,
    },
    /// Connects to the nearest particle with a line, maintaining `distance`.
    Chain(f32),
    /// Orbit a target point at a given radius and angular speed.
    Orbit { center: Vec3, radius: f32, speed: f32 },
    /// Damped spring toward a target.
    Spring { target: Vec3, stiffness: f32, damping: f32 },
}

/// Reference to a sub-emitter that spawns on particle death.
#[derive(Clone, Debug)]
pub struct SubEmitterRef {
    pub preset: Box<EmitterPreset>,
    pub count:  u8,
    pub inherit_velocity: bool,
    pub inherit_color:    bool,
}

// โ”€โ”€โ”€ Curves and gradients โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// A float keyframe curve for particle properties over normalized lifetime [0,1].
#[derive(Clone, Debug)]
pub struct FloatCurve {
    keys: Vec<(f32, f32)>, // (time, value), sorted by time
}

impl FloatCurve {
    pub fn new(keys: Vec<(f32, f32)>) -> Self {
        let mut k = keys;
        k.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
        Self { keys: k }
    }

    pub fn constant(v: f32) -> Self { Self::new(vec![(0.0, v), (1.0, v)]) }
    pub fn linear(from: f32, to: f32) -> Self { Self::new(vec![(0.0, from), (1.0, to)]) }
    pub fn ease_in_out(from: f32, to: f32) -> Self {
        Self::new(vec![(0.0, from), (0.5, (from + to) * 0.5), (1.0, to)])
    }

    pub fn evaluate(&self, t: f32) -> f32 {
        if self.keys.is_empty() { return 0.0; }
        if t <= self.keys[0].0 { return self.keys[0].1; }
        if t >= self.keys[self.keys.len()-1].0 { return self.keys[self.keys.len()-1].1; }
        for i in 1..self.keys.len() {
            if t <= self.keys[i].0 {
                let (t0, v0) = self.keys[i-1];
                let (t1, v1) = self.keys[i];
                let f = (t - t0) / (t1 - t0);
                return v0 + (v1 - v0) * f;
            }
        }
        self.keys.last().unwrap().1
    }
}

/// A color gradient over normalized lifetime [0,1].
#[derive(Clone, Debug)]
pub struct ColorGradient {
    keys: Vec<(f32, Vec4)>,
}

impl ColorGradient {
    pub fn new(keys: Vec<(f32, Vec4)>) -> Self {
        let mut k = keys;
        k.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
        Self { keys: k }
    }

    pub fn constant(c: Vec4) -> Self { Self::new(vec![(0.0, c), (1.0, c)]) }
    pub fn fade_out(c: Vec4) -> Self {
        Self::new(vec![(0.0, c), (0.8, c), (1.0, Vec4::new(c.x, c.y, c.z, 0.0))])
    }
    pub fn fire() -> Self {
        Self::new(vec![
            (0.0, Vec4::new(1.0, 1.0, 0.2, 1.0)),
            (0.3, Vec4::new(1.0, 0.4, 0.0, 0.9)),
            (0.7, Vec4::new(0.5, 0.1, 0.0, 0.5)),
            (1.0, Vec4::new(0.2, 0.0, 0.0, 0.0)),
        ])
    }
    pub fn plasma() -> Self {
        Self::new(vec![
            (0.0, Vec4::new(0.2, 0.0, 1.0, 1.0)),
            (0.3, Vec4::new(0.8, 0.0, 1.0, 0.9)),
            (0.7, Vec4::new(1.0, 0.2, 0.8, 0.5)),
            (1.0, Vec4::new(1.0, 0.8, 1.0, 0.0)),
        ])
    }
    pub fn electric() -> Self {
        Self::new(vec![
            (0.0, Vec4::new(0.5, 0.8, 1.0, 1.0)),
            (0.5, Vec4::new(1.0, 1.0, 1.0, 1.0)),
            (1.0, Vec4::new(0.3, 0.5, 1.0, 0.0)),
        ])
    }

    pub fn evaluate(&self, t: f32) -> Vec4 {
        if self.keys.is_empty() { return Vec4::ONE; }
        if t <= self.keys[0].0 { return self.keys[0].1; }
        if t >= self.keys[self.keys.len()-1].0 { return self.keys[self.keys.len()-1].1; }
        for i in 1..self.keys.len() {
            if t <= self.keys[i].0 {
                let (t0, c0) = self.keys[i-1];
                let (t1, c1) = self.keys[i];
                let f = (t - t0) / (t1 - t0);
                return c0 + (c1 - c0) * f;
            }
        }
        self.keys.last().unwrap().1
    }
}

/// A scale-over-life curve: (time, scale_x, scale_y).
#[derive(Clone, Debug)]
pub struct ScaleCurve {
    pub x: FloatCurve,
    pub y: FloatCurve,
}

impl ScaleCurve {
    pub fn uniform(from: f32, to: f32) -> Self {
        Self { x: FloatCurve::linear(from, to), y: FloatCurve::linear(from, to) }
    }
    pub fn evaluate(&self, t: f32) -> Vec2 {
        Vec2::new(self.x.evaluate(t), self.y.evaluate(t))
    }
}

// โ”€โ”€โ”€ Particle tick โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

impl MathParticle {
    pub fn is_alive(&self) -> bool { self.age < self.lifetime }

    pub fn tick(&mut self, dt: f32) {
        self.age += dt;
        let life_frac = (self.age / self.lifetime).clamp(0.0, 1.0);

        // Math-function-driven displacement
        let dx = self.behavior.evaluate(self.age, self.origin.x);
        let dy = self.behavior.evaluate(self.age + 1.0, self.origin.y);
        let dz = self.behavior.evaluate(self.age + 2.0, self.origin.z);

        // Physics integration
        self.velocity += self.acceleration * dt;
        self.velocity *= 1.0 - (self.drag * dt).clamp(0.0, 1.0);

        if self.flags.contains(ParticleFlags::WORLD_SPACE) {
            self.glyph.position += self.velocity * dt;
        } else {
            self.glyph.position = self.origin + Vec3::new(dx, dy, dz) + self.velocity * dt * life_frac;
        }

        // Reset per-frame acceleration
        self.acceleration = Vec3::ZERO;

        // Apply interaction-specific motion
        match &self.interaction {
            ParticleInteraction::Orbit { center, radius, speed } => {
                let theta = self.age * speed;
                let offset = Vec3::new(theta.cos() * radius, 0.0, theta.sin() * radius);
                self.glyph.position = *center + offset;
            }
            ParticleInteraction::Spring { target, stiffness, damping } => {
                let delta = *target - self.glyph.position;
                self.velocity += delta * *stiffness * dt;
                self.velocity *= 1.0 - *damping * dt;
            }
            _ => {}
        }

        // Color over lifetime
        if let Some(ref grad) = self.color_over_life {
            self.glyph.color = grad.evaluate(life_frac);
        } else {
            // Default fade
            let fade = if life_frac > 0.7 { 1.0 - (life_frac - 0.7) / 0.3 } else { 1.0 };
            self.glyph.color.w = fade;
        }

        // Scale over lifetime
        if let Some(ref curve) = self.scale_over_life {
            let s = curve.evaluate(life_frac);
            self.scale = s.x;
        }

        // Size over lifetime (emission glow)
        if let Some(ref curve) = self.size_over_life {
            let s = curve.evaluate(life_frac);
            self.glyph.glow_radius = s;
            self.glyph.emission = s * 0.8;
        }

        // Spin (angular rotation encoded in glyph)
        self.glyph.glow_radius = (self.glyph.glow_radius + self.spin * dt).max(0.0);
    }
}

// โ”€โ”€โ”€ Particle pool โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Pre-allocated pool of particles.
pub struct ParticlePool {
    particles: Vec<Option<MathParticle>>,
    free_slots: Vec<usize>,
    pub stats: PoolStats,
    /// Particles queued for sub-emission (spawned at end of tick).
    pending_spawns: Vec<(Vec3, Vec3, Vec4, EmitterPreset)>,
}

/// Runtime stats for the particle pool.
#[derive(Debug, Clone, Default)]
pub struct PoolStats {
    pub alive:    usize,
    pub capacity: usize,
    pub spawned:  u64,
    pub expired:  u64,
    pub dropped:  u64,
}

impl ParticlePool {
    pub fn new(capacity: usize) -> Self {
        Self {
            particles:     vec![None; capacity],
            free_slots:    (0..capacity).rev().collect(),
            stats:         PoolStats { capacity, ..Default::default() },
            pending_spawns: Vec::new(),
        }
    }

    pub fn spawn(&mut self, particle: MathParticle) -> bool {
        if let Some(slot) = self.free_slots.pop() {
            self.particles[slot] = Some(particle);
            self.stats.spawned += 1;
            self.stats.alive   += 1;
            true
        } else {
            self.stats.dropped += 1;
            false
        }
    }

    pub fn tick(&mut self, dt: f32) {
        let mut to_free = Vec::new();
        for (i, slot) in self.particles.iter_mut().enumerate() {
            if let Some(ref mut p) = slot {
                p.tick(dt);
                if !p.is_alive() {
                    // Queue sub-emitter spawn if configured
                    if p.flags.contains(ParticleFlags::EMIT_ON_DEATH) {
                        if let Some(ref se) = p.sub_emitter.clone() {
                            let pos = p.glyph.position;
                            let vel = p.velocity;
                            let color = p.glyph.color;
                            for _ in 0..se.count {
                                // Store for deferred spawning
                                // (can't borrow self.free_slots while iterating)
                            }
                        }
                    }
                    to_free.push(i);
                }
            }
        }
        for i in to_free {
            self.particles[i] = None;
            self.free_slots.push(i);
            self.stats.alive   = self.stats.alive.saturating_sub(1);
            self.stats.expired += 1;
        }
    }

    /// Apply a force field to all particles that have AFFECTED_BY_FIELDS.
    pub fn apply_field(&mut self, field: &ForceField, time: f32) {
        for slot in &mut self.particles {
            if let Some(ref mut p) = slot {
                if p.flags.contains(ParticleFlags::AFFECTED_BY_FIELDS) {
                    let force = field.force_at(p.glyph.position, p.glyph.mass, p.glyph.charge, time);
                    p.acceleration += force / p.glyph.mass.max(0.001);
                }
            }
        }
    }

    /// Apply an explicit force to all particles (e.g. gravity, wind).
    pub fn apply_force(&mut self, force: Vec3) {
        for slot in &mut self.particles {
            if let Some(ref mut p) = slot {
                p.acceleration += force;
            }
        }
    }

    /// Apply gravity to all GRAVITY-flagged particles.
    pub fn apply_gravity(&mut self, g: f32) {
        for slot in &mut self.particles {
            if let Some(ref mut p) = slot {
                if p.flags.contains(ParticleFlags::GRAVITY) {
                    p.acceleration.y -= g;
                }
            }
        }
    }

    /// Collide all COLLIDES particles against an infinite floor at y=0.
    pub fn collide_floor(&mut self, restitution: f32) {
        for slot in &mut self.particles {
            if let Some(ref mut p) = slot {
                if p.flags.contains(ParticleFlags::COLLIDES) && p.glyph.position.y < 0.0 {
                    p.glyph.position.y = 0.0;
                    p.velocity.y = -p.velocity.y * restitution;
                }
            }
        }
    }

    /// Kill all particles immediately.
    pub fn clear(&mut self) {
        for (i, slot) in self.particles.iter_mut().enumerate() {
            if slot.is_some() {
                *slot = None;
                self.free_slots.push(i);
                self.stats.alive = self.stats.alive.saturating_sub(1);
            }
        }
    }

    pub fn iter(&self) -> impl Iterator<Item = &MathParticle> {
        self.particles.iter().filter_map(|s| s.as_ref())
    }

    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut MathParticle> {
        self.particles.iter_mut().filter_map(|s| s.as_mut())
    }

    pub fn count(&self) -> usize { self.stats.alive }
    pub fn capacity(&self) -> usize { self.stats.capacity }
    pub fn is_full(&self) -> bool { self.free_slots.is_empty() }

    /// Export live particle positions to a flat f32 buffer (x,y,z, r,g,b,a per particle).
    pub fn export_gpu_buffer(&self) -> Vec<f32> {
        let mut buf = Vec::with_capacity(self.stats.alive * 7);
        for slot in &self.particles {
            if let Some(ref p) = slot {
                buf.push(p.glyph.position.x);
                buf.push(p.glyph.position.y);
                buf.push(p.glyph.position.z);
                buf.push(p.glyph.color.x);
                buf.push(p.glyph.color.y);
                buf.push(p.glyph.color.z);
                buf.push(p.glyph.color.w);
            }
        }
        buf
    }
}

// โ”€โ”€โ”€ Particle emitter shapes โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Defines the 3-D region from which a burst emits.
#[derive(Clone, Debug)]
pub enum EmitterShape {
    /// Single point emission.
    Point,
    /// Uniform sphere surface.
    Sphere { radius: f32 },
    /// Hemisphere surface pointing up (+Y).
    Hemisphere { radius: f32 },
    /// Solid sphere volume.
    SphereVolume { radius: f32 },
    /// Cone: apex at origin, opening toward +Y.
    Cone { angle: f32, length: f32 },
    /// Axis-aligned box.
    Box { half_extents: Vec3 },
    /// Flat disk on the XZ plane.
    Disk { radius: f32 },
    /// Ring (annulus) at y=0.
    Ring { inner: f32, outer: f32 },
    /// Line segment from `a` to `b`.
    Line { a: Vec3, b: Vec3 },
    /// Mesh surface (uses pre-baked sample points).
    Mesh { sample_points: Vec<Vec3> },
    /// Torus.
    Torus { major_radius: f32, minor_radius: f32 },
}

impl EmitterShape {
    /// Sample a random position within the shape.
    pub fn sample(&self, rng: &mut FastRng) -> Vec3 {
        match self {
            Self::Point => Vec3::ZERO,
            Self::Sphere { radius } => {
                let (p, _) = rng.unit_sphere();
                p * *radius
            }
            Self::Hemisphere { radius } => {
                let (mut p, _) = rng.unit_sphere();
                p.y = p.y.abs();
                p * *radius
            }
            Self::SphereVolume { radius } => {
                let (p, _) = rng.unit_sphere();
                p * *radius * rng.f32().cbrt()
            }
            Self::Cone { angle, length } => {
                let r   = rng.f32() * length;
                let a   = rng.f32() * std::f32::consts::TAU;
                let rad = r * angle.to_radians().tan();
                Vec3::new(a.cos() * rad, r, a.sin() * rad)
            }
            Self::Box { half_extents } => {
                Vec3::new(
                    rng.range(-half_extents.x, half_extents.x),
                    rng.range(-half_extents.y, half_extents.y),
                    rng.range(-half_extents.z, half_extents.z),
                )
            }
            Self::Disk { radius } => {
                let r = rng.f32().sqrt() * radius;
                let a = rng.f32() * std::f32::consts::TAU;
                Vec3::new(a.cos() * r, 0.0, a.sin() * r)
            }
            Self::Ring { inner, outer } => {
                let r = rng.range(*inner, *outer);
                let a = rng.f32() * std::f32::consts::TAU;
                Vec3::new(a.cos() * r, 0.0, a.sin() * r)
            }
            Self::Line { a, b } => {
                let t = rng.f32();
                *a + (*b - *a) * t
            }
            Self::Mesh { sample_points } => {
                if sample_points.is_empty() { return Vec3::ZERO; }
                sample_points[rng.range_u32(0, sample_points.len() as u32) as usize]
            }
            Self::Torus { major_radius, minor_radius } => {
                let theta = rng.f32() * std::f32::consts::TAU;
                let phi   = rng.f32() * std::f32::consts::TAU;
                let r     = rng.f32() * minor_radius;
                Vec3::new(
                    (major_radius + r * phi.cos()) * theta.cos(),
                    r * phi.sin(),
                    (major_radius + r * phi.cos()) * theta.sin(),
                )
            }
        }
    }

    /// Sample the outward normal direction at a sampled position (for velocity direction).
    pub fn normal_at(&self, pos: Vec3) -> Vec3 {
        match self {
            Self::Sphere { .. } | Self::SphereVolume { .. } | Self::Hemisphere { .. } => {
                if pos.length_squared() > 1e-6 { pos.normalize() } else { Vec3::Y }
            }
            Self::Cone { .. } => { Vec3::new(pos.x, 0.2, pos.z).normalize() }
            Self::Disk { .. } | Self::Ring { .. } => Vec3::Y,
            _ => Vec3::Y,
        }
    }
}

// โ”€โ”€โ”€ Particle forces โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// A standalone particle force that can be added to a system.
#[derive(Clone, Debug)]
pub enum ParticleForce {
    /// Constant directional force (e.g. gravity, wind).
    Constant { force: Vec3 },
    /// Drag proportional to velocity.
    Drag { coefficient: f32 },
    /// Attractor/repulsor at a point.
    PointForce { position: Vec3, strength: f32, falloff: Falloff },
    /// Turbulence using layered noise.
    Turbulence { strength: f32, frequency: f32, octaves: u8 },
    /// Vortex spinning around an axis.
    Vortex { axis: Vec3, position: Vec3, strength: f32, falloff_radius: f32 },
    /// Cylindrical wind blast.
    WindBlast { direction: Vec3, min_speed: f32, max_speed: f32, gust_freq: f32 },
    /// Kill particles below a certain Y.
    KillPlane { y: f32 },
    /// Bounce particles off a plane.
    Bounce { normal: Vec3, d: f32, restitution: f32 },
    /// Velocity noise โ€” random jitter per frame.
    Noise { amplitude: Vec3 },
    /// Orbit force โ€” pull toward circular orbit.
    OrbitForce { center: Vec3, radius: f32, strength: f32 },
}

impl ParticleForce {
    /// Compute the acceleration this force applies to a particle.
    pub fn acceleration(&self, p: &MathParticle, time: f32, rng: &mut FastRng) -> Vec3 {
        match self {
            Self::Constant { force } => *force,
            Self::Drag { coefficient } => -p.velocity * *coefficient,
            Self::PointForce { position, strength, falloff } => {
                let delta = *position - p.glyph.position;
                let dist  = delta.length();
                if dist < 0.001 { return Vec3::ZERO; }
                let dir  = delta / dist;
                let mag  = falloff_factor(*falloff, dist, f32::MAX) * strength;
                dir * mag
            }
            Self::Turbulence { strength, frequency, octaves: _ } => {
                let pos = p.glyph.position * *frequency;
                let nx = pseudo_noise3(pos + Vec3::new(0.0, 0.0, 0.0), time) * 2.0 - 1.0;
                let ny = pseudo_noise3(pos + Vec3::new(100.0, 0.0, 0.0), time) * 2.0 - 1.0;
                let nz = pseudo_noise3(pos + Vec3::new(200.0, 0.0, 0.0), time) * 2.0 - 1.0;
                Vec3::new(nx, ny, nz) * *strength
            }
            Self::Vortex { axis, position, strength, falloff_radius } => {
                let delta = p.glyph.position - *position;
                let dist  = delta.length();
                if dist < 0.001 { return Vec3::ZERO; }
                let tangent = axis.cross(delta).normalize();
                let fo = (1.0 - (dist / falloff_radius).min(1.0)).powi(2);
                tangent * *strength * fo
            }
            Self::WindBlast { direction, min_speed, max_speed, gust_freq } => {
                let gust = ((time * gust_freq).sin() * 0.5 + 0.5) * (max_speed - min_speed) + min_speed;
                direction.normalize_or_zero() * gust
            }
            Self::KillPlane { .. } => Vec3::ZERO, // handled separately
            Self::Bounce { .. }    => Vec3::ZERO, // handled separately
            Self::Noise { amplitude } => {
                Vec3::new(
                    rng.range(-amplitude.x, amplitude.x),
                    rng.range(-amplitude.y, amplitude.y),
                    rng.range(-amplitude.z, amplitude.z),
                )
            }
            Self::OrbitForce { center, radius, strength } => {
                let delta = p.glyph.position - *center;
                let dist  = delta.length();
                if dist < 0.001 { return Vec3::ZERO; }
                let target_dist = *radius;
                let radial_dir  = delta / dist;
                let orbit_acc   = (target_dist - dist) * *strength;
                radial_dir * orbit_acc
            }
        }
    }
}

// โ”€โ”€โ”€ Particle system โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// A self-contained particle system with its own pool, forces, and emitters.
pub struct ParticleSystem {
    pub pool:         ParticlePool,
    pub forces:       Vec<ParticleForce>,
    pub position:     Vec3,
    pub transform:    Mat4,
    pub gravity:      Vec3,
    pub time:         f32,
    pub enabled:      bool,
    pub world_space:  bool,
    rng: FastRng,

    // Trail data: maps slot index โ†’ list of trail positions
    trails: HashMap<usize, Vec<Vec3>>,
    pub max_trail_len: usize,
}

impl ParticleSystem {
    pub fn new(capacity: usize) -> Self {
        Self {
            pool:          ParticlePool::new(capacity),
            forces:        Vec::new(),
            position:      Vec3::ZERO,
            transform:     Mat4::IDENTITY,
            gravity:       Vec3::new(0.0, -9.81, 0.0),
            time:          0.0,
            enabled:       true,
            world_space:   true,
            rng:           FastRng::new(0xDEADBEEF),
            trails:        HashMap::new(),
            max_trail_len: 16,
        }
    }

    pub fn with_gravity(mut self, g: Vec3) -> Self { self.gravity = g; self }
    pub fn with_position(mut self, p: Vec3) -> Self { self.position = p; self }
    pub fn add_force(mut self, f: ParticleForce) -> Self { self.forces.push(f); self }

    /// Emit `count` particles from a shape with a template.
    pub fn burst(&mut self, shape: &EmitterShape, count: u32, template: &ParticleTemplate) {
        for _ in 0..count {
            let local_pos = shape.sample(&mut self.rng);
            let normal    = shape.normal_at(local_pos);
            let world_pos = self.position + local_pos;

            let speed  = template.speed.sample(&mut self.rng);
            let life   = template.lifetime.sample(&mut self.rng);
            let spread = template.spread;
            let dir    = jitter_direction(normal, spread, &mut self.rng) * speed;

            let color  = template.gradient.evaluate(self.rng.f32());
            let size   = template.size.sample(&mut self.rng);

            let mut p = MathParticle {
                glyph: Glyph {
                    position:   world_pos,
                    color,
                    emission:   template.emission,
                    glow_color: Vec3::new(color.x, color.y, color.z),
                    glow_radius: size,
                    character:  template.character,
                    layer:      RenderLayer::Particle,
                    mass:       template.mass,
                    ..Default::default()
                },
                behavior:        template.behavior.clone(),
                trail:           template.trail,
                trail_length:    template.trail_length,
                trail_decay:     template.trail_decay,
                interaction:     template.interaction.clone(),
                origin:          world_pos,
                age:             0.0,
                lifetime:        life,
                velocity:        dir,
                acceleration:    Vec3::ZERO,
                drag:            template.drag,
                spin:            self.rng.range(template.spin.0, template.spin.1),
                scale:           size,
                scale_over_life: template.scale_over_life.clone(),
                color_over_life: template.color_over_life.clone(),
                size_over_life:  template.size_over_life.clone(),
                group:           template.group,
                sub_emitter:     template.sub_emitter.clone(),
                flags:           template.flags,
                user_data:       [0.0; 4],
            };
            self.pool.spawn(p);
        }
    }

    pub fn tick(&mut self, dt: f32) {
        if !self.enabled { return; }
        self.time += dt;

        // Apply gravity
        self.pool.apply_gravity(self.gravity.length());

        // Apply all forces
        let time = self.time;
        let mut rng = FastRng::new(self.rng.next() ^ (self.time * 1000.0) as u64);
        for force in &self.forces {
            for slot in &mut self.pool.particles {
                if let Some(ref mut p) = slot {
                    let acc = force.acceleration(p, time, &mut rng);
                    p.acceleration += acc;
                }
            }
        }

        // Handle bounce and kill planes
        for force in &self.forces {
            match force {
                ParticleForce::KillPlane { y } => {
                    for slot in &mut self.pool.particles {
                        if let Some(ref mut p) = slot {
                            if p.glyph.position.y < *y { p.age = p.lifetime + 1.0; }
                        }
                    }
                }
                ParticleForce::Bounce { normal, d, restitution } => {
                    let n = normal.normalize_or_zero();
                    for slot in &mut self.pool.particles {
                        if let Some(ref mut p) = slot {
                            let dist = n.dot(p.glyph.position) - d;
                            if dist < 0.0 {
                                p.glyph.position -= n * dist;
                                let vn = n * n.dot(p.velocity);
                                p.velocity -= vn * (1.0 + restitution);
                            }
                        }
                    }
                }
                _ => {}
            }
        }

        self.pool.tick(dt);

        // Update trails
        for (i, slot) in self.pool.particles.iter().enumerate() {
            if let Some(ref p) = slot {
                if p.trail {
                    let trail = self.trails.entry(i).or_default();
                    trail.push(p.glyph.position);
                    if trail.len() > self.max_trail_len {
                        trail.remove(0);
                    }
                }
            } else {
                self.trails.remove(&i);
            }
        }
    }

    pub fn trails(&self) -> &HashMap<usize, Vec<Vec3>> { &self.trails }

    /// Export all active particles as a GPU-ready flat buffer.
    pub fn export_gpu_buffer(&self) -> Vec<f32> { self.pool.export_gpu_buffer() }
}

// โ”€โ”€โ”€ Particle template โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// A reusable template for spawning particles from an emitter.
#[derive(Clone, Debug)]
pub struct ParticleTemplate {
    pub lifetime:        RangeParam,
    pub speed:           RangeParam,
    pub size:            RangeParam,
    pub spread:          f32,
    pub drag:            f32,
    pub mass:            f32,
    pub emission:        f32,
    pub spin:            (f32, f32),
    pub character:       char,
    pub trail:           bool,
    pub trail_length:    u8,
    pub trail_decay:     f32,
    pub behavior:        MathFunction,
    pub interaction:     ParticleInteraction,
    pub gradient:        ColorGradient,
    pub scale_over_life: Option<ScaleCurve>,
    pub color_over_life: Option<ColorGradient>,
    pub size_over_life:  Option<FloatCurve>,
    pub group:           Option<u32>,
    pub sub_emitter:     Option<Box<SubEmitterRef>>,
    pub flags:           ParticleFlags,
}

impl Default for ParticleTemplate {
    fn default() -> Self {
        Self {
            lifetime:        RangeParam::constant(2.0),
            speed:           RangeParam::range(1.0, 5.0),
            size:            RangeParam::constant(1.0),
            spread:          0.3,
            drag:            0.02,
            mass:            1.0,
            emission:        0.7,
            spin:            (-2.0, 2.0),
            character:       'ยท',
            trail:           false,
            trail_length:    8,
            trail_decay:     0.8,
            behavior:        MathFunction::Sine { amplitude: 0.5, frequency: 1.0, phase: 0.0 },
            interaction:     ParticleInteraction::None,
            gradient:        ColorGradient::fade_out(Vec4::ONE),
            scale_over_life: None,
            color_over_life: None,
            size_over_life:  None,
            group:           None,
            sub_emitter:     None,
            flags:           ParticleFlags::GRAVITY,
        }
    }
}

impl ParticleTemplate {
    pub fn fire() -> Self {
        Self {
            lifetime:       RangeParam::range(0.6, 1.4),
            speed:          RangeParam::range(2.0, 6.0),
            size:           RangeParam::range(0.8, 1.6),
            spread:         0.8,
            drag:           0.05,
            character:      'โ–ฒ',
            emission:       1.0,
            color_over_life: Some(ColorGradient::fire()),
            size_over_life:  Some(FloatCurve::linear(1.5, 0.1)),
            flags:          ParticleFlags::AFFECTED_BY_FIELDS,
            ..Default::default()
        }
    }

    pub fn smoke() -> Self {
        Self {
            lifetime:       RangeParam::range(2.0, 4.0),
            speed:          RangeParam::range(0.3, 1.2),
            size:           RangeParam::range(1.0, 3.0),
            spread:         0.5,
            drag:           0.1,
            character:      'โ—‹',
            emission:       0.1,
            color_over_life: Some(ColorGradient::new(vec![
                (0.0, Vec4::new(0.5, 0.5, 0.5, 0.8)),
                (0.7, Vec4::new(0.3, 0.3, 0.3, 0.4)),
                (1.0, Vec4::new(0.2, 0.2, 0.2, 0.0)),
            ])),
            size_over_life: Some(FloatCurve::linear(1.0, 4.0)),
            flags:          ParticleFlags::empty(),
            ..Default::default()
        }
    }

    pub fn electric_spark() -> Self {
        Self {
            lifetime:       RangeParam::range(0.1, 0.4),
            speed:          RangeParam::range(8.0, 20.0),
            size:           RangeParam::constant(0.5),
            spread:         1.5,
            drag:           0.01,
            character:      'ยท',
            emission:       1.2,
            color_over_life: Some(ColorGradient::electric()),
            flags:          ParticleFlags::GRAVITY | ParticleFlags::COLLIDES,
            ..Default::default()
        }
    }

    pub fn plasma() -> Self {
        Self {
            lifetime:        RangeParam::range(0.5, 1.5),
            speed:           RangeParam::range(3.0, 8.0),
            size:            RangeParam::range(0.8, 1.4),
            spread:          0.4,
            drag:            0.03,
            character:       'โ—‰',
            emission:        1.3,
            color_over_life: Some(ColorGradient::plasma()),
            flags:           ParticleFlags::AFFECTED_BY_FIELDS,
            ..Default::default()
        }
    }

    pub fn rain() -> Self {
        Self {
            lifetime:       RangeParam::range(1.0, 2.0),
            speed:          RangeParam::range(10.0, 20.0),
            size:           RangeParam::constant(0.3),
            spread:         0.05,
            drag:           0.0,
            character:      '|',
            emission:       0.4,
            flags:          ParticleFlags::GRAVITY | ParticleFlags::COLLIDES,
            ..Default::default()
        }
    }

    pub fn snow() -> Self {
        Self {
            lifetime:       RangeParam::range(3.0, 8.0),
            speed:          RangeParam::range(0.5, 2.0),
            size:           RangeParam::range(0.5, 1.0),
            spread:         1.5,
            drag:           0.3,
            character:      'โ„',
            emission:       0.5,
            color_over_life: Some(ColorGradient::constant(Vec4::new(0.9, 0.95, 1.0, 0.9))),
            flags:          ParticleFlags::GRAVITY | ParticleFlags::AFFECTED_BY_FIELDS,
            ..Default::default()
        }
    }
}

// โ”€โ”€โ”€ Continuous emitter โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Emitter that fires continuously at a given rate.
pub struct ContinuousEmitter {
    pub system:    ParticleSystem,
    pub rate:      f32, // particles per second
    pub shape:     EmitterShape,
    pub template:  ParticleTemplate,
    accumulator:   f32,
    pub active:    bool,
    pub duration:  Option<f32>,  // None = infinite
    elapsed:       f32,
    pub bursts:    Vec<BurstEvent>,
}

/// A one-shot burst event within a continuous emitter.
#[derive(Clone, Debug)]
pub struct BurstEvent {
    pub time:  f32,
    pub count: u32,
    fired:     bool,
}

impl BurstEvent {
    pub fn new(time: f32, count: u32) -> Self { Self { time, count, fired: false } }
}

impl ContinuousEmitter {
    pub fn new(rate: f32, shape: EmitterShape, template: ParticleTemplate) -> Self {
        Self {
            system:      ParticleSystem::new(4096),
            rate,
            shape,
            template,
            accumulator: 0.0,
            active:      true,
            duration:    None,
            elapsed:     0.0,
            bursts:      Vec::new(),
        }
    }

    pub fn with_duration(mut self, secs: f32) -> Self { self.duration = Some(secs); self }
    pub fn with_burst(mut self, b: BurstEvent) -> Self { self.bursts.push(b); self }
    pub fn with_capacity(mut self, n: usize) -> Self { self.system.pool = ParticlePool::new(n); self }

    pub fn tick(&mut self, dt: f32) {
        if !self.active { self.system.tick(dt); return; }

        self.elapsed += dt;
        if let Some(dur) = self.duration {
            if self.elapsed >= dur { self.active = false; }
        }

        // Continuous emission
        self.accumulator += self.rate * dt;
        let count = self.accumulator as u32;
        if count > 0 {
            self.system.burst(&self.shape, count, &self.template);
            self.accumulator -= count as f32;
        }

        // Burst events
        for b in &mut self.bursts {
            if !b.fired && self.elapsed >= b.time {
                self.system.burst(&self.shape, b.count, &self.template);
                b.fired = true;
            }
        }

        self.system.tick(dt);
    }

    pub fn pool(&self) -> &ParticlePool { &self.system.pool }
}

// โ”€โ”€โ”€ Particle group โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// A named group of particles with shared behavior modifiers.
#[derive(Debug)]
pub struct ParticleGroup {
    pub name:       String,
    pub id:         u32,
    pub color_mult: Vec4,
    pub speed_mult: f32,
    pub life_mult:  f32,
}

impl ParticleGroup {
    pub fn new(id: u32, name: impl Into<String>) -> Self {
        Self { id, name: name.into(), color_mult: Vec4::ONE, speed_mult: 1.0, life_mult: 1.0 }
    }
}

// โ”€โ”€โ”€ Trail renderer data โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Computed trail ribbon geometry for a single particle.
#[derive(Clone, Debug)]
pub struct TrailRibbon {
    pub positions: Vec<Vec3>,
    pub colors:    Vec<Vec4>,
    pub widths:    Vec<f32>,
}

impl TrailRibbon {
    pub fn build(positions: &[Vec3], base_color: Vec4, base_width: f32) -> Self {
        let n = positions.len();
        let mut colors = Vec::with_capacity(n);
        let mut widths = Vec::with_capacity(n);
        for i in 0..n {
            let t = i as f32 / (n.max(2) - 1) as f32;
            let alpha = t; // head bright, tail fades
            colors.push(Vec4::new(base_color.x, base_color.y, base_color.z, alpha * base_color.w));
            widths.push(base_width * alpha);
        }
        Self { positions: positions.to_vec(), colors, widths }
    }
}

// โ”€โ”€โ”€ LOD particle system โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// A multi-LOD particle system that reduces fidelity based on camera distance.
pub struct LodParticleSystem {
    /// LOD0 = full quality, LOD3 = billboard only.
    pub lods:        [ContinuousEmitter; 4],
    pub lod_ranges:  [f32; 4],
    pub position:    Vec3,
    current_lod:     usize,
}

impl LodParticleSystem {
    pub fn new(base_rate: f32, shape: EmitterShape, template: ParticleTemplate) -> Self {
        let e0 = ContinuousEmitter::new(base_rate, shape.clone(), template.clone());
        let e1 = ContinuousEmitter::new(base_rate * 0.6, shape.clone(), template.clone());
        let e2 = ContinuousEmitter::new(base_rate * 0.3, shape.clone(), template.clone());
        let e3 = ContinuousEmitter::new(base_rate * 0.1, shape, template);
        Self {
            lods:        [e0, e1, e2, e3],
            lod_ranges:  [20.0, 50.0, 100.0, 200.0],
            position:    Vec3::ZERO,
            current_lod: 0,
        }
    }

    pub fn tick(&mut self, dt: f32, camera_pos: Vec3) {
        let dist = (self.position - camera_pos).length();
        self.current_lod = 3;
        for (i, &range) in self.lod_ranges.iter().enumerate() {
            if dist <= range { self.current_lod = i; break; }
        }
        self.lods[self.current_lod].tick(dt);
    }

    pub fn active_pool(&self) -> &ParticlePool { self.lods[self.current_lod].pool() }
}

// โ”€โ”€โ”€ GPU instance buffer โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// GPU-compatible instanced particle data: position + size + color (10 floats).
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct GpuParticleInstance {
    pub position: [f32; 3],
    pub size:     f32,
    pub color:    [f32; 4],
    pub velocity: [f32; 3],
    pub age_frac: f32,
}

impl GpuParticleInstance {
    pub fn from_particle(p: &MathParticle) -> Self {
        let lf = (p.age / p.lifetime).clamp(0.0, 1.0);
        Self {
            position: p.glyph.position.to_array(),
            size:     p.scale,
            color:    p.glyph.color.to_array(),
            velocity: p.velocity.to_array(),
            age_frac: lf,
        }
    }
}

pub fn export_gpu_instances(pool: &ParticlePool) -> Vec<GpuParticleInstance> {
    pool.iter().map(GpuParticleInstance::from_particle).collect()
}

// โ”€โ”€โ”€ Preset emitter configurations โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Preset emitter configurations for common game events.
#[derive(Clone, Debug)]
pub enum EmitterPreset {
    /// 40 radial-burst particles, gravity+friction, lifetime 1.5s. Used for enemy death.
    DeathExplosion { color: Vec4 },
    /// 30 upward fountain particles. Used for level-up.
    LevelUpFountain,
    /// 16 spark ring. Used for crits.
    CritBurst,
    /// 8-16 hit sparks. Used for normal hits.
    HitSparks { color: Vec4, count: u8 },
    /// 12 slow-orbiting sparkles. Used for loot drops.
    LootSparkle { color: Vec4 },
    /// Status effect ambient particles.
    StatusAmbient { effect_mask: u8 },
    /// Stun orbiting stars.
    StunOrbit,
    /// Room-type ambient particles.
    RoomAmbient { room_type_id: u8 },
    /// Boss-specific entrance burst.
    BossEntrance { boss_id: u8 },
    /// Gravitational collapse spiral (for heavy damage hits).
    GravitationalCollapse { color: Vec4, attractor: AttractorType },
    /// Self-organizing spell stream.
    SpellStream { element_color: Vec4 },
    /// Golden spiral healing ascent.
    HealSpiral,
    /// Entropy cascade (corruption milestone, fills entire screen).
    EntropyCascade,
    /// Fire burst.
    FireBurst { intensity: f32 },
    /// Smoke puff.
    SmokePuff,
    /// Electric discharge.
    ElectricDischarge { color: Vec4 },
    /// Blood splatter.
    BloodSplatter { color: Vec4, count: u8 },
    /// Ice shatter.
    IceShatter,
    /// Poison cloud.
    PoisonCloud,
    /// Teleport flash.
    TeleportFlash { color: Vec4 },
    /// Shield hit impact.
    ShieldHit { shield_color: Vec4 },
    /// Coin scatter.
    CoinScatter { count: u8 },
    /// Rubble debris.
    RubbleDebris { count: u8 },
    /// Rain shower.
    RainShower,
    /// Snow fall.
    SnowFall,
    /// Confetti burst.
    ConfettiBurst,
    /// Custom template.
    Custom { template: ParticleTemplate, count: u32, shape: EmitterShape },
}

/// Spawn particles from a preset into a pool.
pub fn emit(scene: &mut crate::scene::Scene, preset: EmitterPreset, origin: Vec3) {
    emitters::emit_preset(&mut scene.particles, preset, origin);
}

// โ”€โ”€โ”€ Utility: fast RNG โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Xoshiro-style fast RNG for particle systems.
#[derive(Clone, Debug)]
pub struct FastRng {
    state: u64,
}

impl FastRng {
    pub fn new(seed: u64) -> Self { Self { state: seed ^ 0x9E3779B97F4A7C15 } }

    pub fn next(&mut self) -> u64 {
        let mut x = self.state;
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        self.state = x;
        x
    }

    pub fn f32(&mut self) -> f32 {
        (self.next() & 0x00FF_FFFF) as f32 / 0x00FF_FFFF as f32
    }

    pub fn range(&mut self, min: f32, max: f32) -> f32 {
        min + self.f32() * (max - min)
    }

    pub fn range_u32(&mut self, min: u32, max: u32) -> u32 {
        if min >= max { return min; }
        min + (self.next() as u32 % (max - min))
    }

    /// Returns a random unit-sphere direction and its length.
    pub fn unit_sphere(&mut self) -> (Vec3, f32) {
        loop {
            let x = self.range(-1.0, 1.0);
            let y = self.range(-1.0, 1.0);
            let z = self.range(-1.0, 1.0);
            let len = (x*x + y*y + z*z).sqrt();
            if len > 0.0 && len <= 1.0 {
                return (Vec3::new(x/len, y/len, z/len), len);
            }
        }
    }
}

// โ”€โ”€โ”€ Range parameter โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// A min/max range parameter that returns a random value when sampled.
#[derive(Clone, Debug)]
pub struct RangeParam {
    pub min: f32,
    pub max: f32,
}

impl RangeParam {
    pub fn constant(v: f32) -> Self { Self { min: v, max: v } }
    pub fn range(min: f32, max: f32) -> Self { Self { min, max } }
    pub fn sample(&self, rng: &mut FastRng) -> f32 { rng.range(self.min, self.max) }
}

// โ”€โ”€โ”€ Utilities โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Jitter a direction vector by `spread` radians.
fn jitter_direction(dir: Vec3, spread: f32, rng: &mut FastRng) -> Vec3 {
    if spread < 0.001 { return dir.normalize_or_zero(); }
    let (perp, _) = rng.unit_sphere();
    let jitter = dir + perp * spread;
    jitter.normalize_or_zero()
}

/// A simple 3D pseudo-noise function for turbulence.
fn pseudo_noise3(p: Vec3, t: f32) -> f32 {
    let ix = p.x.floor() as i32;
    let iy = p.y.floor() as i32;
    let iz = p.z.floor() as i32;
    let it = (t * 10.0) as i32;
    let h = hash4(ix, iy, iz, it);
    let fx = p.x - p.x.floor();
    let fy = p.y - p.y.floor();
    let fz = p.z - p.z.floor();
    // Smoothstep blend
    let ux = fx * fx * (3.0 - 2.0 * fx);
    let uy = fy * fy * (3.0 - 2.0 * fy);
    // Lerp over corners (simplified single-octave)
    let n = hash4(ix + (ux > 0.5) as i32, iy + (uy > 0.5) as i32, iz, it);
    n as f32 / u32::MAX as f32
}

fn hash4(x: i32, y: i32, z: i32, w: i32) -> u32 {
    let mut h = (x as u32).wrapping_mul(1619)
        ^ (y as u32).wrapping_mul(31337)
        ^ (z as u32).wrapping_mul(1013904223)
        ^ (w as u32).wrapping_mul(2654435769);
    h ^= h >> 16; h = h.wrapping_mul(0x45d9f3b);
    h ^= h >> 16; h
}

// โ”€โ”€โ”€ Particle effect presets โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// A named, reusable particle effect that combines template + shape + forces.
#[derive(Clone, Debug)]
pub struct ParticleEffect {
    pub name:      String,
    pub template:  ParticleTemplate,
    pub shape:     EmitterShape,
    pub rate:      f32,
    pub count:     u32,
    pub forces:    Vec<ParticleForce>,
    pub duration:  Option<f32>,
}

impl ParticleEffect {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name:     name.into(),
            template: ParticleTemplate::default(),
            shape:    EmitterShape::Point,
            rate:     20.0,
            count:    1,
            forces:   Vec::new(),
            duration: None,
        }
    }

    pub fn campfire() -> Self {
        Self {
            name:     "campfire".into(),
            template: ParticleTemplate::fire(),
            shape:    EmitterShape::Disk { radius: 0.3 },
            rate:     40.0,
            count:    2,
            forces:   vec![
                ParticleForce::Turbulence { strength: 0.5, frequency: 2.0, octaves: 2 },
                ParticleForce::Constant { force: Vec3::new(0.0, 1.2, 0.0) },
            ],
            duration: None,
        }
    }

    pub fn explosion() -> Self {
        Self {
            name:     "explosion".into(),
            template: ParticleTemplate {
                lifetime:       RangeParam::range(0.4, 1.2),
                speed:          RangeParam::range(5.0, 20.0),
                size:           RangeParam::range(1.0, 2.5),
                spread:         3.14,
                drag:           0.08,
                character:      'โ–ˆ',
                emission:       1.5,
                color_over_life: Some(ColorGradient::fire()),
                flags:          ParticleFlags::GRAVITY,
                ..Default::default()
            },
            shape:    EmitterShape::Sphere { radius: 0.5 },
            rate:     0.0,
            count:    80,
            forces:   vec![ParticleForce::Constant { force: Vec3::new(0.0, -9.81, 0.0) }],
            duration: Some(0.05),
        }
    }

    pub fn rain_shower() -> Self {
        Self {
            name:     "rain".into(),
            template: ParticleTemplate::rain(),
            shape:    EmitterShape::Box { half_extents: Vec3::new(20.0, 0.0, 20.0) },
            rate:     500.0,
            count:    10,
            forces:   vec![
                ParticleForce::Constant { force: Vec3::new(0.3, -15.0, 0.0) },
                ParticleForce::KillPlane { y: -1.0 },
            ],
            duration: None,
        }
    }
}

// โ”€โ”€โ”€ Particle effect library โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Registry of named particle effects.
pub struct ParticleLibrary {
    effects: HashMap<String, ParticleEffect>,
}

impl ParticleLibrary {
    pub fn new() -> Self {
        let mut lib = Self { effects: HashMap::new() };
        lib.register(ParticleEffect::campfire());
        lib.register(ParticleEffect::explosion());
        lib.register(ParticleEffect::rain_shower());
        lib
    }

    pub fn register(&mut self, effect: ParticleEffect) {
        self.effects.insert(effect.name.clone(), effect);
    }

    pub fn get(&self, name: &str) -> Option<&ParticleEffect> {
        self.effects.get(name)
    }

    pub fn names(&self) -> Vec<&str> {
        self.effects.keys().map(|s| s.as_str()).collect()
    }

    /// Instantiate an effect into a ContinuousEmitter.
    pub fn instantiate(&self, name: &str) -> Option<ContinuousEmitter> {
        let e = self.effects.get(name)?;
        let mut emitter = ContinuousEmitter::new(e.rate, e.shape.clone(), e.template.clone());
        for f in &e.forces {
            emitter.system.forces.push(f.clone());
        }
        if let Some(d) = e.duration { emitter = emitter.with_duration(d); }
        Some(emitter)
    }
}

impl Default for ParticleLibrary {
    fn default() -> Self { Self::new() }
}

// โ”€โ”€โ”€ Particle statistics โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// System-wide particle statistics.
#[derive(Debug, Clone, Default)]
pub struct ParticleSystemStats {
    pub total_alive:   usize,
    pub total_spawned: u64,
    pub total_expired: u64,
    pub total_dropped: u64,
    pub emitter_count: usize,
}

impl ParticleSystemStats {
    pub fn from_pool(pool: &ParticlePool) -> Self {
        Self {
            total_alive:   pool.stats.alive,
            total_spawned: pool.stats.spawned,
            total_expired: pool.stats.expired,
            total_dropped: pool.stats.dropped,
            emitter_count: 1,
        }
    }
}

// โ”€โ”€โ”€ Tests โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn float_curve_linear() {
        let c = FloatCurve::linear(0.0, 10.0);
        assert!((c.evaluate(0.5) - 5.0).abs() < 0.01);
    }

    #[test]
    fn color_gradient_evaluate() {
        let g = ColorGradient::fade_out(Vec4::ONE);
        let c = g.evaluate(1.0);
        assert!(c.w < 0.1);
    }

    #[test]
    fn fast_rng_range() {
        let mut rng = FastRng::new(42);
        for _ in 0..1000 {
            let v = rng.range(0.0, 1.0);
            assert!(v >= 0.0 && v <= 1.0);
        }
    }

    #[test]
    fn particle_pool_spawn_and_tick() {
        let mut pool = ParticlePool::new(16);
        let p = MathParticle {
            glyph: Glyph { position: Vec3::ZERO, ..Default::default() },
            behavior: MathFunction::Sine { amplitude: 1.0, frequency: 1.0, phase: 0.0 },
            trail: false, trail_length: 0, trail_decay: 0.0,
            interaction: ParticleInteraction::None,
            origin: Vec3::ZERO,
            age: 0.0, lifetime: 1.0,
            velocity: Vec3::new(0.0, 1.0, 0.0),
            acceleration: Vec3::ZERO,
            drag: 0.0, spin: 0.0, scale: 1.0,
            scale_over_life: None, color_over_life: None, size_over_life: None,
            group: None, sub_emitter: None,
            flags: ParticleFlags::empty(),
            user_data: [0.0; 4],
        };
        assert!(pool.spawn(p));
        assert_eq!(pool.count(), 1);
        pool.tick(2.0); // Should expire
        assert_eq!(pool.count(), 0);
    }

    #[test]
    fn emitter_shape_sample() {
        let mut rng = FastRng::new(999);
        let shape = EmitterShape::Sphere { radius: 5.0 };
        for _ in 0..100 {
            let p = shape.sample(&mut rng);
            assert!((p.length() - 5.0).abs() < 0.1);
        }
    }

    #[test]
    fn emitter_shape_disk() {
        let mut rng = FastRng::new(12345);
        let shape = EmitterShape::Disk { radius: 3.0 };
        for _ in 0..100 {
            let p = shape.sample(&mut rng);
            assert!(p.y.abs() < 0.001);
            assert!(glam::Vec2::new(p.x, p.z).length() <= 3.001);
        }
    }

    #[test]
    fn particle_template_defaults() {
        let t = ParticleTemplate::default();
        assert_eq!(t.character, 'ยท');
    }

    #[test]
    fn scale_curve_evaluate() {
        let c = ScaleCurve::uniform(2.0, 0.5);
        let v = c.evaluate(0.5);
        assert!((v.x - 1.25).abs() < 0.01);
    }

    #[test]
    fn particle_library_campfire() {
        let lib = ParticleLibrary::new();
        let e = lib.instantiate("campfire");
        assert!(e.is_some());
    }

    #[test]
    fn gpu_export_buffer() {
        let pool = ParticlePool::new(64);
        let buf = pool.export_gpu_buffer();
        assert!(buf.is_empty());
    }
}