oxiphysics-gpu 0.1.0

GPU acceleration backends for the OxiPhysics engine
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
#![allow(clippy::ptr_arg)]
// Copyright 2026 COOLJAPAN OU (Team KitaSan)
// SPDX-License-Identifier: Apache-2.0

//! CPU-side simulation of a wgpu compute pipeline abstraction.
//!
//! Provides data layout and dispatch logic that mirrors a typical GPU compute
//! pipeline, with all computation running on the CPU.

// ── silence unused-item lints for the enum variants / fields used only in
//    tests or future GPU back-ends ──────────────────────────────────────────
#![allow(dead_code)]

// ─────────────────────────────────────────────────────────────────────────────
// BufferUsage
// ─────────────────────────────────────────────────────────────────────────────

/// Intended usage of a [`ComputeBuffer`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BufferUsage {
    /// Vertex data fed to the rasteriser.
    Vertex,
    /// Index data for indexed draw calls.
    Index,
    /// Small, frequently-updated uniform / constant data.
    Uniform,
    /// General-purpose read-write storage.
    Storage,
    /// CPU↔GPU transfer staging area.
    Staging,
}

// ─────────────────────────────────────────────────────────────────────────────
// ComputeBuffer
// ─────────────────────────────────────────────────────────────────────────────

/// A CPU-resident buffer that mirrors a GPU buffer.
#[derive(Debug, Clone)]
pub struct ComputeBuffer {
    /// Raw `f32` elements.
    pub data: Vec<f32>,
    /// Intended GPU usage hint.
    pub usage: BufferUsage,
    /// Human-readable label (useful for debugging).
    pub label: String,
}

impl ComputeBuffer {
    /// Allocate a zero-initialised buffer of `size` `f32` elements.
    pub fn new(size: usize, usage: BufferUsage, label: &str) -> Self {
        Self {
            data: vec![0.0_f32; size],
            usage,
            label: label.to_owned(),
        }
    }

    /// Write `values` into the buffer starting at element `offset`.
    ///
    /// # Panics
    /// Panics if `offset + values.len() > self.data.len()`.
    pub fn write_f32(&mut self, offset: usize, values: &[f32]) {
        let end = offset + values.len();
        assert!(
            end <= self.data.len(),
            "write_f32: out-of-bounds write (offset={offset}, len={}, capacity={})",
            values.len(),
            self.data.len()
        );
        self.data[offset..end].copy_from_slice(values);
    }

    /// Read `count` `f32` elements starting at element `offset`.
    ///
    /// # Panics
    /// Panics if `offset + count > self.data.len()`.
    pub fn read_f32(&self, offset: usize, count: usize) -> Vec<f32> {
        let end = offset + count;
        assert!(
            end <= self.data.len(),
            "read_f32: out-of-bounds read (offset={offset}, count={count}, capacity={})",
            self.data.len()
        );
        self.data[offset..end].to_vec()
    }

    /// Total size of the buffer in bytes (`len * 4`).
    pub fn byte_size(&self) -> usize {
        self.data.len() * std::mem::size_of::<f32>()
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// WorkgroupSize
// ─────────────────────────────────────────────────────────────────────────────

/// Workgroup dimensions for a compute dispatch.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WorkgroupSize {
    /// X dimension.
    pub x: u32,
    /// Y dimension.
    pub y: u32,
    /// Z dimension.
    pub z: u32,
}

impl WorkgroupSize {
    /// Compute the number of workgroups needed to cover `total` items when
    /// each workgroup handles `workgroup` items (ceiling division).
    pub fn dispatch_count(total: u32, workgroup: u32) -> u32 {
        assert!(workgroup > 0, "workgroup size must be > 0");
        total.div_ceil(workgroup)
    }
}

impl Default for WorkgroupSize {
    fn default() -> Self {
        Self { x: 64, y: 1, z: 1 }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// ComputeKernelKind
// ─────────────────────────────────────────────────────────────────────────────

/// The kind of compute kernel to dispatch.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ComputeKernelKind {
    /// Semi-implicit velocity / position integration.
    VelocityUpdate,
    /// Pressure Jacobi iteration.
    PressureJacobi,
    /// Lennard-Jones particle force evaluation.
    ParticleForce,
    /// Neighbour-search (spatial hashing).
    NeighborSearch,
    /// User-defined kernel identified by a string tag.
    Custom(String),
}

// ─────────────────────────────────────────────────────────────────────────────
// CpuComputeDispatch
// ─────────────────────────────────────────────────────────────────────────────

/// Dispatcher that executes compute kernels on the CPU.
pub struct CpuComputeDispatch {
    /// Which kernel this dispatcher is configured for.
    pub kernel: ComputeKernelKind,
    /// Workgroup size hint (informational on the CPU path).
    pub workgroup_size: WorkgroupSize,
}

impl CpuComputeDispatch {
    /// Create a new dispatcher.
    pub fn new(kernel: ComputeKernelKind, wg: WorkgroupSize) -> Self {
        Self {
            kernel,
            workgroup_size: wg,
        }
    }

    /// Semi-implicit Euler integration for `n` particles.
    ///
    /// `pos[i] += vel[i] * dt` then `vel[i] += force[i] / mass[i] * dt`.
    pub fn dispatch_velocity_update(
        &self,
        pos: &mut ComputeBuffer,
        vel: &mut ComputeBuffer,
        force: &ComputeBuffer,
        mass: &ComputeBuffer,
        dt: f32,
        n: usize,
    ) {
        for i in 0..n {
            pos.data[i] += vel.data[i] * dt;
            vel.data[i] += force.data[i] / mass.data[i] * dt;
        }
    }

    /// Single Jacobi pressure iteration over an `nx × ny` grid.
    ///
    /// Interior points only; boundary cells are left unchanged.
    ///
    /// `p[i,j] = (p_old[i+1,j] + p_old[i-1,j] + p_old[i,j+1] + p_old[i,j-1]
    ///            - dx² * rhs[i,j]) / 4`
    pub fn dispatch_pressure_jacobi(
        &self,
        p: &mut ComputeBuffer,
        p_old: &ComputeBuffer,
        rhs: &ComputeBuffer,
        nx: usize,
        ny: usize,
        dx: f32,
    ) {
        let dx2 = dx * dx;
        for j in 1..ny - 1 {
            for i in 1..nx - 1 {
                let idx = j * nx + i;
                p.data[idx] = (p_old.data[idx + 1]
                    + p_old.data[idx - 1]
                    + p_old.data[idx + nx]
                    + p_old.data[idx - nx]
                    - dx2 * rhs.data[idx])
                    / 4.0;
            }
        }
    }

    /// O(n²) Lennard-Jones force accumulation.
    ///
    /// Positions are stored as interleaved `[x0, y0, x1, y1, …]`.
    /// Forces are accumulated in-place (`force` is zeroed first).
    pub fn dispatch_particle_force(
        &self,
        pos: &ComputeBuffer,
        force: &mut ComputeBuffer,
        eps: f32,
        sigma: f32,
        n: usize,
    ) {
        // Zero forces first.
        for v in force.data[..2 * n].iter_mut() {
            *v = 0.0;
        }

        for i in 0..n {
            for j in (i + 1)..n {
                let dx = pos.data[2 * j] - pos.data[2 * i];
                let dy = pos.data[2 * j + 1] - pos.data[2 * i + 1];
                let r2 = dx * dx + dy * dy;
                if r2 < 1e-12 {
                    continue;
                }
                let sr2 = (sigma * sigma) / r2;
                let sr6 = sr2 * sr2 * sr2;
                let sr12 = sr6 * sr6;
                // F = 24ε/r² * (2(σ/r)^12 - (σ/r)^6)
                let fmag = 24.0 * eps / r2 * (2.0 * sr12 - sr6);
                force.data[2 * i] -= fmag * dx;
                force.data[2 * i + 1] -= fmag * dy;
                force.data[2 * j] += fmag * dx;
                force.data[2 * j + 1] += fmag * dy;
            }
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// GpuStats
// ─────────────────────────────────────────────────────────────────────────────

/// Accumulated statistics for compute dispatches.
#[derive(Debug, Clone, Default)]
pub struct GpuStats {
    /// Total number of dispatches recorded.
    pub dispatch_count: u64,
    /// Total bytes transferred (reads + writes).
    pub bytes_transferred: u64,
    /// Total kernel wall-clock time in milliseconds.
    pub kernel_time_ms: f64,
}

impl GpuStats {
    /// Create zeroed stats.
    pub fn new() -> Self {
        Self::default()
    }

    /// Record a single dispatch event.
    pub fn record_dispatch(&mut self, bytes: u64, time_ms: f64) {
        self.dispatch_count += 1;
        self.bytes_transferred += bytes;
        self.kernel_time_ms += time_ms;
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Free-standing solver helpers
// ─────────────────────────────────────────────────────────────────────────────

/// Single Jacobi sweep over an `nx × ny` pressure grid.
///
/// Updates every interior cell of `p_new` using `p_old` and `rhs`.
pub fn jacobi_step_2d(
    p_new: &mut Vec<f32>,
    p_old: &[f32],
    rhs: &[f32],
    nx: usize,
    ny: usize,
    dx: f32,
) {
    let dx2 = dx * dx;
    for j in 1..ny - 1 {
        for i in 1..nx - 1 {
            let idx = j * nx + i;
            p_new[idx] = (p_old[idx + 1] + p_old[idx - 1] + p_old[idx + nx] + p_old[idx - nx]
                - dx2 * rhs[idx])
                / 4.0;
        }
    }
}

/// Iterative Jacobi pressure-Poisson solver.
///
/// Runs `n_iter` Jacobi sweeps and returns the final L∞ residual.
pub fn pressure_poisson_solve(
    p: &mut Vec<f32>,
    rhs: &[f32],
    nx: usize,
    ny: usize,
    dx: f32,
    n_iter: usize,
) -> f32 {
    let size = nx * ny;
    let mut p_old = p.clone();

    for _ in 0..n_iter {
        jacobi_step_2d(p, &p_old, rhs, nx, ny, dx);
        p_old.copy_from_slice(&p[..size]);
    }

    // Compute L∞ residual on interior cells.
    let dx2 = dx * dx;
    let mut residual = 0.0_f32;
    for j in 1..ny - 1 {
        for i in 1..nx - 1 {
            let idx = j * nx + i;
            let lap = (p[idx + 1] + p[idx - 1] + p[idx + nx] + p[idx - nx] - 4.0 * p[idx]) / dx2;
            let r = (lap - rhs[idx]).abs();
            if r > residual {
                residual = r;
            }
        }
    }
    residual
}

// ─────────────────────────────────────────────────────────────────────────────
// PipelineCache – LRU-style pipeline caching
// ─────────────────────────────────────────────────────────────────────────────

/// A simple LRU-eviction cache for compiled compute pipelines.
///
/// Keyed by a string label; evicts the oldest entry when the capacity is reached.
pub struct PipelineCache {
    /// Maximum number of entries.
    capacity: usize,
    /// Entries in insertion order (oldest first).
    entries: Vec<(String, CpuComputeDispatch)>,
}

impl PipelineCache {
    /// Create a new cache with the given capacity.
    pub fn new(capacity: usize) -> Self {
        Self {
            capacity,
            entries: Vec::new(),
        }
    }

    /// Insert (or replace) a pipeline under `key`.
    pub fn insert(&mut self, key: &str, pipeline: CpuComputeDispatch) {
        // Remove existing entry with the same key
        self.entries.retain(|(k, _)| k != key);
        // Evict oldest if at capacity
        while self.entries.len() >= self.capacity {
            self.entries.remove(0);
        }
        self.entries.push((key.to_owned(), pipeline));
    }

    /// Look up a cached pipeline by key.
    pub fn get(&self, key: &str) -> Option<&CpuComputeDispatch> {
        self.entries.iter().find(|(k, _)| k == key).map(|(_, v)| v)
    }

    /// Number of cached entries.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the cache is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Clear all cached pipelines.
    pub fn clear(&mut self) {
        self.entries.clear();
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// PipelineStats – dispatch-level statistics
// ─────────────────────────────────────────────────────────────────────────────

/// Fine-grained statistics for compute pipeline usage.
#[derive(Debug, Clone, Default)]
pub struct PipelineStats {
    /// Total number of dispatches.
    pub total_dispatches: u64,
    /// Total number of workgroups launched.
    pub total_workgroups: u64,
    /// Total number of invocations (workgroups × workgroup_size).
    pub total_invocations: u64,
    /// Number of times a cached pipeline was re-used.
    pub cache_hits: u64,
    /// Number of times a pipeline had to be compiled (or was not in cache).
    pub cache_misses: u64,
}

impl PipelineStats {
    /// Record a single dispatch event.
    pub fn record_dispatch(&mut self, num_workgroups: u64, wg_size: WorkgroupSize) {
        self.total_dispatches += 1;
        self.total_workgroups += num_workgroups;
        self.total_invocations +=
            num_workgroups * (wg_size.x as u64) * (wg_size.y as u64) * (wg_size.z as u64);
    }

    /// Cache hit ratio (0.0–1.0). Returns NaN when no lookups occurred.
    pub fn cache_hit_ratio(&self) -> f64 {
        let total = self.cache_hits + self.cache_misses;
        if total == 0 {
            return f64::NAN;
        }
        self.cache_hits as f64 / total as f64
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// MultiPassPipeline – chained compute passes
// ─────────────────────────────────────────────────────────────────────────────

/// A single compute pass in a multi-pass pipeline.
#[derive(Debug, Clone)]
pub struct ComputePass {
    /// Human-readable label.
    pub label: String,
    /// The kernel to dispatch.
    pub kernel: ComputeKernelKind,
    /// Workgroup size for this pass.
    pub workgroup_size: WorkgroupSize,
    /// Indices of buffers bound to this pass.
    pub buffer_bindings: Vec<usize>,
}

/// A sequence of compute passes that execute in order.
#[derive(Debug)]
pub struct MultiPassPipeline {
    /// Human-readable label.
    pub label: String,
    /// Ordered list of passes.
    pub passes: Vec<ComputePass>,
}

impl MultiPassPipeline {
    /// Create a new empty multi-pass pipeline.
    pub fn new(label: &str) -> Self {
        Self {
            label: label.to_owned(),
            passes: Vec::new(),
        }
    }

    /// Append a compute pass.
    pub fn add_pass(&mut self, pass: ComputePass) {
        self.passes.push(pass);
    }

    /// Number of passes.
    pub fn num_passes(&self) -> usize {
        self.passes.len()
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Pipeline validation
// ─────────────────────────────────────────────────────────────────────────────

/// Validate resource bindings for a single compute pass.
///
/// Returns a list of error messages (empty if valid).
pub fn validate_resource_bindings(pass: &ComputePass, buffers: &[ComputeBuffer]) -> Vec<String> {
    let mut errors = Vec::new();
    let mut seen = std::collections::HashSet::new();
    for &idx in &pass.buffer_bindings {
        if idx >= buffers.len() {
            errors.push(format!(
                "Pass '{}': buffer binding {} is out of range (have {} buffers)",
                pass.label,
                idx,
                buffers.len()
            ));
        }
        if !seen.insert(idx) {
            errors.push(format!(
                "Pass '{}': Duplicate buffer binding {}",
                pass.label, idx
            ));
        }
    }
    errors
}

/// Validate all passes in a multi-pass pipeline.
pub fn validate_pipeline(pipeline: &MultiPassPipeline, buffers: &[ComputeBuffer]) -> Vec<String> {
    let mut errors = Vec::new();
    for pass in &pipeline.passes {
        errors.extend(validate_resource_bindings(pass, buffers));
    }
    errors
}

// ─────────────────────────────────────────────────────────────────────────────
// Additional solver helpers
// ─────────────────────────────────────────────────────────────────────────────

/// Single SOR (Successive Over-Relaxation) sweep over an `nx × ny` grid.
///
/// `omega = 1.0` gives standard Gauss-Seidel; `omega ∈ (1, 2)` gives SOR.
pub fn sor_step_2d(
    p: &mut Vec<f32>,
    p_old: &[f32],
    rhs: &[f32],
    nx: usize,
    ny: usize,
    dx: f32,
    omega: f32,
) {
    let dx2 = dx * dx;
    for j in 1..ny - 1 {
        for i in 1..nx - 1 {
            let idx = j * nx + i;
            let gs = (p_old[idx + 1] + p_old[idx - 1] + p_old[idx + nx] + p_old[idx - nx]
                - dx2 * rhs[idx])
                / 4.0;
            p[idx] = (1.0 - omega) * p_old[idx] + omega * gs;
        }
    }
}

/// Red-black Gauss-Seidel sweep (in-place) on an `nx × ny` grid.
///
/// Updates "red" cells (i+j even) first, then "black" cells (i+j odd).
pub fn red_black_gauss_seidel_step(p: &mut Vec<f32>, rhs: &[f32], nx: usize, ny: usize, dx: f32) {
    let dx2 = dx * dx;
    // Red sweep (i + j even)
    for j in 1..ny - 1 {
        for i in 1..nx - 1 {
            if (i + j) % 2 == 0 {
                let idx = j * nx + i;
                p[idx] =
                    (p[idx + 1] + p[idx - 1] + p[idx + nx] + p[idx - nx] - dx2 * rhs[idx]) / 4.0;
            }
        }
    }
    // Black sweep (i + j odd)
    for j in 1..ny - 1 {
        for i in 1..nx - 1 {
            if (i + j) % 2 == 1 {
                let idx = j * nx + i;
                p[idx] =
                    (p[idx + 1] + p[idx - 1] + p[idx + nx] + p[idx - nx] - dx2 * rhs[idx]) / 4.0;
            }
        }
    }
}

/// Compute the L∞ residual of a 2D Poisson discretisation.
pub fn compute_linf_residual(p: &[f32], rhs: &[f32], nx: usize, ny: usize, dx: f32) -> f32 {
    let dx2 = dx * dx;
    let mut residual = 0.0_f32;
    for j in 1..ny - 1 {
        for i in 1..nx - 1 {
            let idx = j * nx + i;
            let lap = (p[idx + 1] + p[idx - 1] + p[idx + nx] + p[idx - nx] - 4.0 * p[idx]) / dx2;
            let r = (lap - rhs[idx]).abs();
            if r > residual {
                residual = r;
            }
        }
    }
    residual
}

/// O(n²) neighbor search for 2D interleaved positions `[x0, y0, x1, y1, …]`.
///
/// Returns a `Vec<Vec`usize`>` where `result[i]` contains the indices of
/// particles within `cutoff` distance of particle `i`.
pub fn dispatch_neighbor_search(positions: &[f32], n: usize, cutoff: f32) -> Vec<Vec<usize>> {
    let cutoff2 = cutoff * cutoff;
    let mut neighbors = vec![Vec::new(); n];
    for i in 0..n {
        for j in (i + 1)..n {
            let dx = positions[2 * j] - positions[2 * i];
            let dy = positions[2 * j + 1] - positions[2 * i + 1];
            let r2 = dx * dx + dy * dy;
            if r2 < cutoff2 {
                neighbors[i].push(j);
                neighbors[j].push(i);
            }
        }
    }
    neighbors
}

// ─────────────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────────────

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

    // ── BufferUsage ──────────────────────────────────────────────────────────

    #[test]
    fn buffer_usage_eq() {
        assert_eq!(BufferUsage::Storage, BufferUsage::Storage);
        assert_ne!(BufferUsage::Vertex, BufferUsage::Index);
    }

    #[test]
    fn buffer_usage_clone() {
        let u = BufferUsage::Uniform;
        assert_eq!(u.clone(), BufferUsage::Uniform);
    }

    // ── ComputeBuffer ────────────────────────────────────────────────────────

    #[test]
    fn compute_buffer_new_zeroed() {
        let buf = ComputeBuffer::new(8, BufferUsage::Storage, "test");
        assert_eq!(buf.data.len(), 8);
        assert!(buf.data.iter().all(|&v| v == 0.0));
        assert_eq!(buf.label, "test");
    }

    #[test]
    fn compute_buffer_byte_size() {
        let buf = ComputeBuffer::new(4, BufferUsage::Uniform, "u");
        assert_eq!(buf.byte_size(), 16);
    }

    #[test]
    fn compute_buffer_write_read_roundtrip() {
        let mut buf = ComputeBuffer::new(8, BufferUsage::Storage, "rw");
        buf.write_f32(2, &[1.0, 2.0, 3.0]);
        let out = buf.read_f32(2, 3);
        assert_eq!(out, vec![1.0, 2.0, 3.0]);
    }

    #[test]
    fn compute_buffer_write_at_offset_zero() {
        let mut buf = ComputeBuffer::new(4, BufferUsage::Storage, "s");
        buf.write_f32(0, &[9.0, 8.0, 7.0, 6.0]);
        assert_eq!(buf.data, vec![9.0, 8.0, 7.0, 6.0]);
    }

    #[test]
    #[should_panic(expected = "out-of-bounds write")]
    fn compute_buffer_write_oob_panics() {
        let mut buf = ComputeBuffer::new(4, BufferUsage::Storage, "oob");
        buf.write_f32(3, &[1.0, 2.0]); // 3+2 > 4
    }

    #[test]
    #[should_panic(expected = "out-of-bounds read")]
    fn compute_buffer_read_oob_panics() {
        let buf = ComputeBuffer::new(4, BufferUsage::Storage, "oob");
        let _ = buf.read_f32(3, 2);
    }

    // ── WorkgroupSize ────────────────────────────────────────────────────────

    #[test]
    fn workgroup_dispatch_count_exact() {
        assert_eq!(WorkgroupSize::dispatch_count(64, 64), 1);
    }

    #[test]
    fn workgroup_dispatch_count_ceil() {
        assert_eq!(WorkgroupSize::dispatch_count(65, 64), 2);
        assert_eq!(WorkgroupSize::dispatch_count(1, 64), 1);
    }

    #[test]
    fn workgroup_dispatch_count_zero_total() {
        assert_eq!(WorkgroupSize::dispatch_count(0, 64), 0);
    }

    #[test]
    fn workgroup_default() {
        let wg = WorkgroupSize::default();
        assert_eq!(wg.x, 64);
        assert_eq!(wg.y, 1);
        assert_eq!(wg.z, 1);
    }

    // ── ComputeKernelKind ────────────────────────────────────────────────────

    #[test]
    fn kernel_kind_custom_eq() {
        let a = ComputeKernelKind::Custom("foo".into());
        let b = ComputeKernelKind::Custom("foo".into());
        assert_eq!(a, b);
    }

    #[test]
    fn kernel_kind_variants_neq() {
        assert_ne!(
            ComputeKernelKind::VelocityUpdate,
            ComputeKernelKind::PressureJacobi
        );
    }

    // ── CpuComputeDispatch – velocity update ─────────────────────────────────

    #[test]
    fn velocity_update_basic() {
        let disp =
            CpuComputeDispatch::new(ComputeKernelKind::VelocityUpdate, WorkgroupSize::default());
        let n = 3;
        let mut pos = ComputeBuffer::new(n, BufferUsage::Storage, "pos");
        let mut vel = ComputeBuffer::new(n, BufferUsage::Storage, "vel");
        let mut force = ComputeBuffer::new(n, BufferUsage::Storage, "force");
        let mut mass = ComputeBuffer::new(n, BufferUsage::Storage, "mass");

        pos.write_f32(0, &[0.0, 1.0, 2.0]);
        vel.write_f32(0, &[1.0, 0.5, -1.0]);
        force.write_f32(0, &[0.0, 1.0, 0.0]);
        mass.write_f32(0, &[1.0, 2.0, 1.0]);

        let dt = 0.1_f32;
        disp.dispatch_velocity_update(&mut pos, &mut vel, &force, &mass, dt, n);

        // pos[0] = 0.0 + 1.0*0.1 = 0.1,  vel[0] = 1.0 + 0/1*0.1 = 1.0
        assert!((pos.data[0] - 0.1).abs() < 1e-6);
        assert!((vel.data[0] - 1.0).abs() < 1e-6);
        // pos[1] = 1.0 + 0.5*0.1 = 1.05, vel[1] = 0.5 + 1/2*0.1 = 0.55
        assert!((pos.data[1] - 1.05).abs() < 1e-6);
        assert!((vel.data[1] - 0.55).abs() < 1e-6);
    }

    #[test]
    fn velocity_update_zero_force() {
        let disp =
            CpuComputeDispatch::new(ComputeKernelKind::VelocityUpdate, WorkgroupSize::default());
        let n = 2;
        let mut pos = ComputeBuffer::new(n, BufferUsage::Storage, "pos");
        let mut vel = ComputeBuffer::new(n, BufferUsage::Storage, "vel");
        let force = ComputeBuffer::new(n, BufferUsage::Storage, "force");
        let mut mass = ComputeBuffer::new(n, BufferUsage::Storage, "mass");

        pos.write_f32(0, &[0.0, 0.0]);
        vel.write_f32(0, &[2.0, -3.0]);
        mass.write_f32(0, &[1.0, 1.0]);

        disp.dispatch_velocity_update(&mut pos, &mut vel, &force, &mass, 0.5, n);

        assert!((pos.data[0] - 1.0).abs() < 1e-6);
        assert!((pos.data[1] - (-1.5)).abs() < 1e-6);
        // velocities unchanged (zero force)
        assert!((vel.data[0] - 2.0).abs() < 1e-6);
        assert!((vel.data[1] - (-3.0)).abs() < 1e-6);
    }

    // ── CpuComputeDispatch – pressure Jacobi ─────────────────────────────────

    #[test]
    fn pressure_jacobi_interior_update() {
        let disp =
            CpuComputeDispatch::new(ComputeKernelKind::PressureJacobi, WorkgroupSize::default());
        let nx = 4;
        let ny = 4;
        let mut p = ComputeBuffer::new(nx * ny, BufferUsage::Storage, "p");
        let mut p_old = ComputeBuffer::new(nx * ny, BufferUsage::Storage, "p_old");
        let rhs = ComputeBuffer::new(nx * ny, BufferUsage::Storage, "rhs");

        // Set p_old to known values; neighbours of (1,1) are all 1.0
        for v in p_old.data.iter_mut() {
            *v = 1.0;
        }

        disp.dispatch_pressure_jacobi(&mut p, &p_old, &rhs, nx, ny, 1.0);

        // p[1*4+1] = (1+1+1+1 - 0)/4 = 1.0
        let idx = nx + 1;
        assert!((p.data[idx] - 1.0).abs() < 1e-6);
    }

    #[test]
    fn pressure_jacobi_boundary_unchanged() {
        let disp =
            CpuComputeDispatch::new(ComputeKernelKind::PressureJacobi, WorkgroupSize::default());
        let nx = 5;
        let ny = 5;
        let mut p = ComputeBuffer::new(nx * ny, BufferUsage::Storage, "p");
        let p_old = ComputeBuffer::new(nx * ny, BufferUsage::Storage, "p_old");
        let rhs = ComputeBuffer::new(nx * ny, BufferUsage::Storage, "rhs");

        // Boundary should remain zero.
        disp.dispatch_pressure_jacobi(&mut p, &p_old, &rhs, nx, ny, 1.0);
        assert_eq!(p.data[0], 0.0); // corner
        assert_eq!(p.data[4], 0.0); // top-right corner
    }

    // ── CpuComputeDispatch – LJ particle force ───────────────────────────────

    #[test]
    fn particle_force_zero_at_large_sep() {
        let disp =
            CpuComputeDispatch::new(ComputeKernelKind::ParticleForce, WorkgroupSize::default());
        let n = 2;
        // Two particles very far apart → tiny force.
        let mut pos = ComputeBuffer::new(2 * n, BufferUsage::Storage, "pos");
        let mut force = ComputeBuffer::new(2 * n, BufferUsage::Storage, "force");
        pos.write_f32(0, &[0.0, 0.0, 1000.0, 0.0]);

        disp.dispatch_particle_force(&pos, &mut force, 1.0, 1.0, n);
        // Force should be negligible at r=1000σ
        assert!(force.data[0].abs() < 1e-10);
    }

    #[test]
    fn particle_force_newton3() {
        let disp =
            CpuComputeDispatch::new(ComputeKernelKind::ParticleForce, WorkgroupSize::default());
        let n = 2;
        let mut pos = ComputeBuffer::new(2 * n, BufferUsage::Storage, "pos");
        let mut force = ComputeBuffer::new(2 * n, BufferUsage::Storage, "force");
        pos.write_f32(0, &[0.0, 0.0, 1.5, 0.0]);

        disp.dispatch_particle_force(&pos, &mut force, 1.0, 1.0, n);
        // Newton's third law: f0 + f1 == 0
        assert!((force.data[0] + force.data[2]).abs() < 1e-5);
        assert!((force.data[1] + force.data[3]).abs() < 1e-5);
    }

    // ── GpuStats ─────────────────────────────────────────────────────────────

    #[test]
    fn gpu_stats_initial_zero() {
        let s = GpuStats::new();
        assert_eq!(s.dispatch_count, 0);
        assert_eq!(s.bytes_transferred, 0);
        assert_eq!(s.kernel_time_ms, 0.0);
    }

    #[test]
    fn gpu_stats_accumulate() {
        let mut s = GpuStats::new();
        s.record_dispatch(128, 0.5);
        s.record_dispatch(256, 1.0);
        assert_eq!(s.dispatch_count, 2);
        assert_eq!(s.bytes_transferred, 384);
        assert!((s.kernel_time_ms - 1.5).abs() < 1e-9);
    }

    // ── jacobi_step_2d ───────────────────────────────────────────────────────

    #[test]
    fn jacobi_step_2d_uniform_field() {
        let nx = 4;
        let ny = 4;
        let size = nx * ny;
        let mut p_new = vec![0.0_f32; size];
        let p_old = vec![1.0_f32; size];
        let rhs = vec![0.0_f32; size];

        jacobi_step_2d(&mut p_new, &p_old, &rhs, nx, ny, 1.0);

        // Uniform field → interior stays 1.0.
        for j in 1..ny - 1 {
            for i in 1..nx - 1 {
                assert!((p_new[j * nx + i] - 1.0).abs() < 1e-6);
            }
        }
    }

    #[test]
    fn jacobi_step_2d_rhs_effect() {
        let nx = 4;
        let ny = 4;
        let size = nx * ny;
        let mut p_new = vec![0.0_f32; size];
        let p_old = vec![4.0_f32; size];
        // rhs = 4 at every interior point
        let rhs = vec![4.0_f32; size];

        jacobi_step_2d(&mut p_new, &p_old, &rhs, nx, ny, 1.0);
        // p[i,j] = (4+4+4+4 - 1²*4)/4 = (16-4)/4 = 3
        for j in 1..ny - 1 {
            for i in 1..nx - 1 {
                assert!((p_new[j * nx + i] - 3.0).abs() < 1e-6);
            }
        }
    }

    // ── pressure_poisson_solve ───────────────────────────────────────────────

    #[test]
    fn pressure_poisson_zero_rhs_zero_bc() {
        // Zero RHS + zero BCs → solution stays zero → zero residual.
        let nx = 5;
        let ny = 5;
        let mut p = vec![0.0_f32; nx * ny];
        let rhs = vec![0.0_f32; nx * ny];
        let residual = pressure_poisson_solve(&mut p, &rhs, nx, ny, 0.1, 50);
        assert!(residual < 1e-6, "residual={residual}");
    }

    #[test]
    fn pressure_poisson_residual_decreases() {
        let nx = 6;
        let ny = 6;
        let mut p1 = vec![0.0_f32; nx * ny];
        let mut p2 = p1.clone();
        let rhs: Vec<f32> = (0..(nx * ny)).map(|k| (k as f32).sin()).collect();
        let dx = 0.1;

        let r1 = pressure_poisson_solve(&mut p1, &rhs, nx, ny, dx, 10);
        let r2 = pressure_poisson_solve(&mut p2, &rhs, nx, ny, dx, 200);
        assert!(
            r2 <= r1 + 1e-4,
            "more iterations should not increase residual (r1={r1}, r2={r2})"
        );
    }

    // ── PipelineCache ──────────────────────────────────────────────────────

    #[test]
    fn pipeline_cache_insert_and_get() {
        let mut cache = PipelineCache::new(4);
        let disp =
            CpuComputeDispatch::new(ComputeKernelKind::VelocityUpdate, WorkgroupSize::default());
        cache.insert("vel_update", disp);
        assert!(cache.get("vel_update").is_some());
        assert!(cache.get("nonexistent").is_none());
    }

    #[test]
    fn pipeline_cache_eviction() {
        let mut cache = PipelineCache::new(2);
        let d1 =
            CpuComputeDispatch::new(ComputeKernelKind::VelocityUpdate, WorkgroupSize::default());
        let d2 =
            CpuComputeDispatch::new(ComputeKernelKind::PressureJacobi, WorkgroupSize::default());
        let d3 =
            CpuComputeDispatch::new(ComputeKernelKind::ParticleForce, WorkgroupSize::default());
        cache.insert("a", d1);
        cache.insert("b", d2);
        cache.insert("c", d3); // should evict "a"
        assert!(cache.get("a").is_none());
        assert!(cache.get("b").is_some());
        assert!(cache.get("c").is_some());
    }

    #[test]
    fn pipeline_cache_replace() {
        let mut cache = PipelineCache::new(4);
        let d1 =
            CpuComputeDispatch::new(ComputeKernelKind::VelocityUpdate, WorkgroupSize::default());
        let d2 = CpuComputeDispatch::new(
            ComputeKernelKind::ParticleForce,
            WorkgroupSize { x: 128, y: 1, z: 1 },
        );
        cache.insert("key", d1);
        cache.insert("key", d2);
        let entry = cache.get("key").unwrap();
        assert_eq!(entry.kernel, ComputeKernelKind::ParticleForce);
    }

    // ── PipelineStats ──────────────────────────────────────────────────────

    #[test]
    fn pipeline_stats_default() {
        let stats = PipelineStats::default();
        assert_eq!(stats.total_dispatches, 0);
        assert_eq!(stats.total_workgroups, 0);
        assert_eq!(stats.total_invocations, 0);
        assert_eq!(stats.cache_hits, 0);
        assert_eq!(stats.cache_misses, 0);
    }

    #[test]
    fn pipeline_stats_record() {
        let mut stats = PipelineStats::default();
        stats.record_dispatch(4, WorkgroupSize { x: 64, y: 1, z: 1 });
        assert_eq!(stats.total_dispatches, 1);
        assert_eq!(stats.total_workgroups, 4);
        assert_eq!(stats.total_invocations, 4 * 64);
    }

    #[test]
    fn pipeline_stats_record_3d_workgroup() {
        let mut stats = PipelineStats::default();
        stats.record_dispatch(2, WorkgroupSize { x: 8, y: 8, z: 4 });
        assert_eq!(stats.total_dispatches, 1);
        assert_eq!(stats.total_workgroups, 2);
        assert_eq!(stats.total_invocations, 2 * 8 * 8 * 4);
    }

    #[test]
    fn pipeline_stats_cache_ratio() {
        let mut stats = PipelineStats::default();
        assert!(stats.cache_hit_ratio().is_nan() || stats.cache_hit_ratio() == 0.0);
        stats.cache_hits = 3;
        stats.cache_misses = 1;
        assert!((stats.cache_hit_ratio() - 0.75).abs() < 1e-6);
    }

    // ── MultiPassPipeline ──────────────────────────────────────────────────

    #[test]
    fn multi_pass_empty() {
        let mp = MultiPassPipeline::new("empty");
        assert_eq!(mp.passes.len(), 0);
        assert_eq!(mp.label, "empty");
    }

    #[test]
    fn multi_pass_execute_add_scale() {
        // pass 0: fill buffer with [1, 2, 3, 4]
        // pass 1: scale by 2 → [2, 4, 6, 8]
        let mut mp = MultiPassPipeline::new("add_scale");
        mp.add_pass(ComputePass {
            label: "fill".into(),
            kernel: ComputeKernelKind::Custom("fill".into()),
            workgroup_size: WorkgroupSize::default(),
            buffer_bindings: vec![0],
        });
        mp.add_pass(ComputePass {
            label: "scale".into(),
            kernel: ComputeKernelKind::Custom("scale".into()),
            workgroup_size: WorkgroupSize::default(),
            buffer_bindings: vec![0],
        });
        assert_eq!(mp.passes.len(), 2);
        assert_eq!(mp.passes[0].label, "fill");
        assert_eq!(mp.passes[1].label, "scale");
    }

    #[test]
    fn multi_pass_dispatch_velocity_chain() {
        // Test chaining two velocity update passes
        let mut mp = MultiPassPipeline::new("vel_chain");
        mp.add_pass(ComputePass {
            label: "step1".into(),
            kernel: ComputeKernelKind::VelocityUpdate,
            workgroup_size: WorkgroupSize::default(),
            buffer_bindings: vec![0, 1, 2, 3],
        });
        mp.add_pass(ComputePass {
            label: "step2".into(),
            kernel: ComputeKernelKind::VelocityUpdate,
            workgroup_size: WorkgroupSize::default(),
            buffer_bindings: vec![0, 1, 2, 3],
        });

        let n = 2;
        let mut pos = ComputeBuffer::new(n, BufferUsage::Storage, "pos");
        let mut vel = ComputeBuffer::new(n, BufferUsage::Storage, "vel");
        let force = ComputeBuffer::new(n, BufferUsage::Storage, "force");
        let mut mass = ComputeBuffer::new(n, BufferUsage::Storage, "mass");

        pos.write_f32(0, &[0.0, 0.0]);
        vel.write_f32(0, &[1.0, 2.0]);
        mass.write_f32(0, &[1.0, 1.0]);

        let dt = 0.1_f32;

        // Execute passes manually (since we simulate CPU-side)
        for pass in &mp.passes {
            if pass.kernel == ComputeKernelKind::VelocityUpdate {
                let disp =
                    CpuComputeDispatch::new(ComputeKernelKind::VelocityUpdate, pass.workgroup_size);
                disp.dispatch_velocity_update(&mut pos, &mut vel, &force, &mass, dt, n);
            }
        }
        // After 2 steps with zero force: pos = vel*dt*2
        assert!((pos.data[0] - 0.2).abs() < 1e-5);
        assert!((pos.data[1] - 0.4).abs() < 1e-5);
    }

    // ── Pipeline validation ────────────────────────────────────────────────

    #[test]
    fn validate_binding_valid() {
        let buffers = vec![
            ComputeBuffer::new(16, BufferUsage::Storage, "buf0"),
            ComputeBuffer::new(16, BufferUsage::Uniform, "buf1"),
        ];
        let pass = ComputePass {
            label: "test".into(),
            kernel: ComputeKernelKind::VelocityUpdate,
            workgroup_size: WorkgroupSize::default(),
            buffer_bindings: vec![0, 1],
        };
        let errors = validate_resource_bindings(&pass, &buffers);
        assert!(errors.is_empty());
    }

    #[test]
    fn validate_binding_out_of_range() {
        let buffers = vec![ComputeBuffer::new(16, BufferUsage::Storage, "buf0")];
        let pass = ComputePass {
            label: "test".into(),
            kernel: ComputeKernelKind::VelocityUpdate,
            workgroup_size: WorkgroupSize::default(),
            buffer_bindings: vec![0, 5],
        };
        let errors = validate_resource_bindings(&pass, &buffers);
        assert_eq!(errors.len(), 1);
        assert!(errors[0].contains("out of range"));
    }

    #[test]
    fn validate_binding_duplicate() {
        let buffers = vec![ComputeBuffer::new(16, BufferUsage::Storage, "buf0")];
        let pass = ComputePass {
            label: "test".into(),
            kernel: ComputeKernelKind::VelocityUpdate,
            workgroup_size: WorkgroupSize::default(),
            buffer_bindings: vec![0, 0],
        };
        let errors = validate_resource_bindings(&pass, &buffers);
        assert_eq!(errors.len(), 1);
        assert!(errors[0].contains("Duplicate"));
    }

    #[test]
    fn validate_pipeline_all_passes() {
        let buffers = vec![ComputeBuffer::new(16, BufferUsage::Storage, "buf0")];
        let mut mp = MultiPassPipeline::new("test");
        mp.add_pass(ComputePass {
            label: "good".into(),
            kernel: ComputeKernelKind::VelocityUpdate,
            workgroup_size: WorkgroupSize::default(),
            buffer_bindings: vec![0],
        });
        mp.add_pass(ComputePass {
            label: "bad".into(),
            kernel: ComputeKernelKind::PressureJacobi,
            workgroup_size: WorkgroupSize::default(),
            buffer_bindings: vec![0, 3],
        });
        let errors = validate_pipeline(&mp, &buffers);
        assert_eq!(errors.len(), 1); // only the bad pass has errors
    }

    // ── ComputeBuffer additional tests ─────────────────────────────────────

    #[test]
    fn compute_buffer_clone() {
        let mut buf = ComputeBuffer::new(4, BufferUsage::Storage, "orig");
        buf.write_f32(0, &[1.0, 2.0, 3.0, 4.0]);
        let cloned = buf.clone();
        assert_eq!(buf.data, cloned.data);
        assert_eq!(buf.label, cloned.label);
    }

    #[test]
    fn compute_buffer_staging_usage() {
        let buf = ComputeBuffer::new(8, BufferUsage::Staging, "staging");
        assert_eq!(buf.usage, BufferUsage::Staging);
        assert_eq!(buf.byte_size(), 32);
    }

    // ── Workgroup additional tests ─────────────────────────────────────────

    #[test]
    fn workgroup_dispatch_count_large() {
        assert_eq!(WorkgroupSize::dispatch_count(1024, 256), 4);
        assert_eq!(WorkgroupSize::dispatch_count(1025, 256), 5);
    }

    // ── GpuStats additional tests ──────────────────────────────────────────

    #[test]
    fn gpu_stats_clone() {
        let mut s = GpuStats::new();
        s.record_dispatch(100, 1.5);
        let s2 = s.clone();
        assert_eq!(s.dispatch_count, s2.dispatch_count);
        assert_eq!(s.bytes_transferred, s2.bytes_transferred);
        assert!((s.kernel_time_ms - s2.kernel_time_ms).abs() < 1e-12);
    }

    // ── dispatch_particle_force additional tests ──────────────────────────

    #[test]
    fn particle_force_repulsive_at_close_range() {
        let disp =
            CpuComputeDispatch::new(ComputeKernelKind::ParticleForce, WorkgroupSize::default());
        let n = 2;
        let mut pos = ComputeBuffer::new(2 * n, BufferUsage::Storage, "pos");
        let mut force = ComputeBuffer::new(2 * n, BufferUsage::Storage, "force");
        // Two particles at distance 0.9σ (< σ → repulsive region)
        pos.write_f32(0, &[0.0, 0.0, 0.9, 0.0]);
        disp.dispatch_particle_force(&pos, &mut force, 1.0, 1.0, n);
        // Force on particle 0 should push it away from particle 1 (negative x)
        assert!(
            force.data[0] < 0.0,
            "expected repulsive force, got {}",
            force.data[0]
        );
    }

    #[test]
    fn particle_force_three_particles() {
        let disp =
            CpuComputeDispatch::new(ComputeKernelKind::ParticleForce, WorkgroupSize::default());
        let n = 3;
        let mut pos = ComputeBuffer::new(2 * n, BufferUsage::Storage, "pos");
        let mut force = ComputeBuffer::new(2 * n, BufferUsage::Storage, "force");
        // Triangle arrangement
        pos.write_f32(0, &[0.0, 0.0, 2.0, 0.0, 1.0, 1.732]);
        disp.dispatch_particle_force(&pos, &mut force, 1.0, 1.0, n);

        // Total momentum conservation: sum of all forces should be zero
        let fx_total = force.data[0] + force.data[2] + force.data[4];
        let fy_total = force.data[1] + force.data[3] + force.data[5];
        assert!(fx_total.abs() < 1e-5, "fx_total={fx_total}");
        assert!(fy_total.abs() < 1e-5, "fy_total={fy_total}");
    }

    // ── pressure_poisson_solve additional tests ───────────────────────────

    #[test]
    fn pressure_poisson_uniform_rhs() {
        let nx = 8;
        let ny = 8;
        let mut p = vec![0.0_f32; nx * ny];
        let rhs = vec![1.0_f32; nx * ny];
        let residual = pressure_poisson_solve(&mut p, &rhs, nx, ny, 0.1, 500);
        // After many iterations residual should decrease significantly
        assert!(residual < 10.0, "residual={residual}");
    }

    // ── SOR solver ────────────────────────────────────────────────────────

    #[test]
    fn sor_step_uniform_field() {
        let nx = 4;
        let ny = 4;
        let mut p = vec![0.0_f32; nx * ny];
        let rhs = vec![0.0_f32; nx * ny];
        let p_ref = vec![1.0_f32; nx * ny];
        sor_step_2d(&mut p, &p_ref, &rhs, nx, ny, 1.0, 1.0);
        // With omega=1.0 this is the same as Jacobi
        for j in 1..ny - 1 {
            for i in 1..nx - 1 {
                assert!((p[j * nx + i] - 1.0).abs() < 1e-6);
            }
        }
    }

    #[test]
    fn sor_step_over_relaxation() {
        // SOR with omega > 1 should differ from standard Jacobi (omega=1)
        let nx = 6;
        let ny = 6;
        let rhs = vec![0.0_f32; nx * ny];

        // Non-uniform reference: set boundary to 1, interior p_old to 0
        let mut p_ref = vec![0.0_f32; nx * ny];
        for i in 0..nx {
            p_ref[i] = 1.0;
            p_ref[(ny - 1) * nx + i] = 1.0;
        }
        for j in 0..ny {
            p_ref[j * nx] = 1.0;
            p_ref[j * nx + nx - 1] = 1.0;
        }

        let mut p_jac = vec![0.0_f32; nx * ny];
        let mut p_sor = vec![0.0_f32; nx * ny];
        sor_step_2d(&mut p_jac, &p_ref, &rhs, nx, ny, 1.0, 1.0);
        sor_step_2d(&mut p_sor, &p_ref, &rhs, nx, ny, 1.0, 1.5);

        // SOR result should differ from Jacobi for interior nodes next to boundary
        let idx = nx + 1; // has 2 boundary neighbors
        // Jacobi: (1+0+1+0)/4 = 0.5, SOR: (1-1.5)*0 + 1.5*0.5 = 0.75
        assert!(
            (p_sor[idx] - p_jac[idx]).abs() > 0.01,
            "SOR and Jacobi should differ: SOR={}, Jac={}",
            p_sor[idx],
            p_jac[idx]
        );
    }

    // ── Red-black Gauss-Seidel ────────────────────────────────────────────

    #[test]
    fn red_black_gs_uniform() {
        let nx = 6;
        let ny = 6;
        let mut p = vec![1.0_f32; nx * ny];
        let rhs = vec![0.0_f32; nx * ny];
        red_black_gauss_seidel_step(&mut p, &rhs, nx, ny, 1.0);
        // Uniform field is a fixed point with zero rhs
        for j in 1..ny - 1 {
            for i in 1..nx - 1 {
                assert!((p[j * nx + i] - 1.0).abs() < 1e-6);
            }
        }
    }

    #[test]
    fn red_black_gs_converges() {
        let nx = 8;
        let ny = 8;
        let mut p = vec![0.0_f32; nx * ny];
        let rhs = vec![0.0_f32; nx * ny];
        // Set boundary to 1
        for i in 0..nx {
            p[i] = 1.0;
            p[(ny - 1) * nx + i] = 1.0;
        }
        for j in 0..ny {
            p[j * nx] = 1.0;
            p[j * nx + nx - 1] = 1.0;
        }
        // Multiple sweeps should converge interior toward 1.0
        for _ in 0..200 {
            red_black_gauss_seidel_step(&mut p, &rhs, nx, ny, 1.0);
        }
        let center = p[(ny / 2) * nx + nx / 2];
        assert!((center - 1.0).abs() < 0.01, "center={center}");
    }

    // ── compute_linf_residual ─────────────────────────────────────────────

    #[test]
    fn linf_residual_zero_for_exact() {
        // Uniform field with zero rhs is an exact solution
        let nx = 4;
        let ny = 4;
        let p = vec![1.0_f32; nx * ny];
        let rhs = vec![0.0_f32; nx * ny];
        let res = compute_linf_residual(&p, &rhs, nx, ny, 1.0);
        assert!(res < 1e-6, "res={res}");
    }

    #[test]
    fn linf_residual_nonzero_for_wrong() {
        let nx = 4;
        let ny = 4;
        let mut p = vec![0.0_f32; nx * ny];
        p[nx + 1] = 100.0; // big spike
        let rhs = vec![0.0_f32; nx * ny];
        let res = compute_linf_residual(&p, &rhs, nx, ny, 1.0);
        assert!(res > 1.0, "expected large residual, got {res}");
    }

    // ── Dispatch neighbor search ──────────────────────────────────────────

    #[test]
    fn dispatch_neighbor_search_basic() {
        let n = 4;
        let positions = vec![
            0.0_f32, 0.0, // particle 0
            0.5, 0.0, // particle 1 (close to 0)
            5.0, 5.0, // particle 2 (far)
            0.3, 0.3, // particle 3 (close to 0 and 1)
        ];
        let neighbors = dispatch_neighbor_search(&positions, n, 1.0);
        // particle 0 should have neighbors 1 and 3
        assert!(neighbors[0].contains(&1));
        assert!(neighbors[0].contains(&3));
        // particle 2 should have no neighbors
        assert!(neighbors[2].is_empty());
    }

    #[test]
    fn dispatch_neighbor_search_all_close() {
        let n = 3;
        let positions = vec![0.0_f32, 0.0, 0.1, 0.0, 0.0, 0.1];
        let neighbors = dispatch_neighbor_search(&positions, n, 1.0);
        // All particles within cutoff of each other
        assert_eq!(neighbors[0].len(), 2);
        assert_eq!(neighbors[1].len(), 2);
        assert_eq!(neighbors[2].len(), 2);
    }

    #[test]
    fn dispatch_neighbor_search_none() {
        let n = 2;
        let positions = vec![0.0_f32, 0.0, 100.0, 100.0];
        let neighbors = dispatch_neighbor_search(&positions, n, 1.0);
        assert!(neighbors[0].is_empty());
        assert!(neighbors[1].is_empty());
    }
}