oxigaf-render 0.1.2

Differentiable 3D Gaussian Splatting rasterizer (wgpu)
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
//! Physically-motivated lens post-processing for u8 RGBA images.
//!
//! This module implements chromatic aberration, barrel/pincushion distortion,
//! and vignetting effects on flat `Vec<u8>` RGBA images (row-major,
//! 4 bytes per pixel).  These effects complement the f32-RGB API in
//! [`chromatic_aberration`][crate::chromatic_aberration].
//!
//! # Quick start
//!
//! ```rust
//! use oxigaf_render::lens_effects::{
//!     LensEffectsConfig, ChromAberrationConfig, apply_lens_effects,
//! };
//!
//! let width  = 4u32;
//! let height = 4u32;
//! let image  = vec![128u8; (width * height * 4) as usize];
//! let config = LensEffectsConfig {
//!     chromatic_aberration: Some(ChromAberrationConfig::subtle()),
//!     distortion: None,
//!     vignette: None,
//! };
//! let out = apply_lens_effects(&image, width, height, &config).expect("lens effects failed");
//! assert_eq!(out.len(), image.len());
//! ```

use thiserror::Error;

// ─────────────────────────────────────────────────────────────────────────────
// Error type
// ─────────────────────────────────────────────────────────────────────────────

/// Errors produced by the RGBA lens-effects functions.
#[derive(Debug, Error, PartialEq)]
pub enum LensEffectError {
    /// Buffer supplied to the function was empty (or a dimension was zero).
    #[error("Empty image buffer")]
    EmptyImage,

    /// Buffer length does not match `width × height × 4`.
    #[error(
        "Image buffer {actual} bytes does not match {width}\u{d7}{height}\u{d7}4 = {expected}"
    )]
    InvalidDimensions {
        /// Actual buffer length in bytes.
        actual: usize,
        /// Expected buffer length in bytes.
        expected: usize,
        /// Declared image width.
        width: u32,
        /// Declared image height.
        height: u32,
    },

    /// `strength` was outside `[0, 1]`.
    #[error("Invalid aberration strength {strength}: must be in [0, 1]")]
    InvalidAberrationStrength {
        /// The offending value.
        strength: f32,
    },

    /// A radial distortion coefficient was outside `[-1, 1]`.
    #[error("Invalid distortion coefficient {k}: must be in [-1, 1]")]
    InvalidDistortionCoeff {
        /// The offending coefficient value.
        k: f32,
    },
}

// ─────────────────────────────────────────────────────────────────────────────
// Config structures
// ─────────────────────────────────────────────────────────────────────────────

/// Per-channel radial-shift chromatic aberration (RGBA u8 API).
///
/// Each channel is sampled from a slightly different radial offset from the
/// image centre.  `shift > 0` pushes the sample outward; `shift < 0` pulls it
/// inward.
#[derive(Debug, Clone, PartialEq)]
pub struct ChromAberrationConfig {
    /// Radial shift factor for the red channel (default `0.005`).
    pub red_shift: f32,
    /// Radial shift factor for the green channel (default `0.0`).
    pub green_shift: f32,
    /// Radial shift factor for the blue channel (default `-0.005`).
    pub blue_shift: f32,
    /// Overall effect strength in `[0, 1]` (default `1.0`).
    pub strength: f32,
}

impl Default for ChromAberrationConfig {
    fn default() -> Self {
        Self {
            red_shift: 0.005,
            green_shift: 0.0,
            blue_shift: -0.005,
            strength: 1.0,
        }
    }
}

impl ChromAberrationConfig {
    /// Validate the configuration.
    ///
    /// # Errors
    ///
    /// Returns [`LensEffectError::InvalidAberrationStrength`] if `strength ∉ [0, 1]`.
    pub fn validate(&self) -> Result<(), LensEffectError> {
        if !(0.0..=1.0).contains(&self.strength) {
            return Err(LensEffectError::InvalidAberrationStrength {
                strength: self.strength,
            });
        }
        Ok(())
    }

    /// Subtle aberration — barely noticeable.
    pub fn subtle() -> Self {
        Self {
            red_shift: 0.002,
            green_shift: 0.0,
            blue_shift: -0.002,
            strength: 1.0,
        }
    }

    /// Moderate aberration — visible colour fringing at edges.
    pub fn moderate() -> Self {
        Self {
            red_shift: 0.01,
            green_shift: 0.0,
            blue_shift: -0.01,
            strength: 1.0,
        }
    }

    /// Strong aberration — pronounced chromatic fringing.
    pub fn strong() -> Self {
        Self {
            red_shift: 0.03,
            green_shift: 0.0,
            blue_shift: -0.03,
            strength: 1.0,
        }
    }
}

/// Barrel/pincushion radial lens distortion (RGBA u8 API).
#[derive(Debug, Clone, PartialEq)]
pub struct DistortionConfig {
    /// First radial distortion coefficient `k1`
    /// (negative → barrel, positive → pincushion).
    /// Must be in `[-1, 1]` (default `0.0`).
    pub k1: f32,
    /// Second radial distortion coefficient `k2`.
    /// Must be in `[-1, 1]` (default `0.0`).
    pub k2: f32,
    /// Overall effect strength in `[0, 1]` (default `1.0`).
    pub strength: f32,
}

impl Default for DistortionConfig {
    fn default() -> Self {
        Self {
            k1: 0.0,
            k2: 0.0,
            strength: 1.0,
        }
    }
}

impl DistortionConfig {
    /// Validate the configuration.
    ///
    /// # Errors
    ///
    /// - [`LensEffectError::InvalidDistortionCoeff`] if `k1` or `k2 ∉ [-1, 1]`.
    /// - [`LensEffectError::InvalidAberrationStrength`] if `strength ∉ [0, 1]`.
    pub fn validate(&self) -> Result<(), LensEffectError> {
        if !(-1.0..=1.0).contains(&self.k1) {
            return Err(LensEffectError::InvalidDistortionCoeff { k: self.k1 });
        }
        if !(-1.0..=1.0).contains(&self.k2) {
            return Err(LensEffectError::InvalidDistortionCoeff { k: self.k2 });
        }
        if !(0.0..=1.0).contains(&self.strength) {
            return Err(LensEffectError::InvalidAberrationStrength {
                strength: self.strength,
            });
        }
        Ok(())
    }

    /// Slight barrel distortion — gently bowing outward.
    pub fn slight_barrel() -> Self {
        Self {
            k1: -0.1,
            k2: 0.0,
            strength: 1.0,
        }
    }

    /// Slight pincushion distortion — gently bowing inward.
    pub fn slight_pincushion() -> Self {
        Self {
            k1: 0.1,
            k2: 0.0,
            strength: 1.0,
        }
    }
}

/// Vignetting configuration for the RGBA u8 lens pipeline.
///
/// For a more expressive multi-model API see the `vignetting` module's
/// [`VignettingConfig`][crate::VignettingConfig].
#[derive(Debug, Clone, PartialEq)]
pub struct LensVignetteConfig {
    /// Vignette strength in `[0, 1]` (default `0.5`).
    pub strength: f32,
    /// Normalised radius where vignetting begins (default `0.7`).
    pub radius: f32,
    /// Falloff steepness exponent (default `2.0`).
    pub falloff: f32,
    /// Vignette colour as linear RGB in `[0, 1]` (default `[0, 0, 0]` — black).
    pub color: [f32; 3],
}

impl Default for LensVignetteConfig {
    fn default() -> Self {
        Self {
            strength: 0.5,
            radius: 0.7,
            falloff: 2.0,
            color: [0.0, 0.0, 0.0],
        }
    }
}

impl LensVignetteConfig {
    /// Validate the configuration.
    ///
    /// # Errors
    ///
    /// Returns [`LensEffectError::InvalidAberrationStrength`] if `strength ∉ [0, 1]`.
    pub fn validate(&self) -> Result<(), LensEffectError> {
        if !(0.0..=1.0).contains(&self.strength) {
            return Err(LensEffectError::InvalidAberrationStrength {
                strength: self.strength,
            });
        }
        Ok(())
    }

    /// Subtle vignette — barely noticeable darkening.
    pub fn subtle() -> Self {
        Self {
            strength: 0.3,
            ..Self::default()
        }
    }

    /// Cinematic vignette — strong darkening for a filmic look.
    pub fn cinema() -> Self {
        Self {
            strength: 0.7,
            radius: 0.5,
            ..Self::default()
        }
    }
}

/// Combined lens effects configuration (RGBA u8 API).
#[derive(Debug, Clone, Default)]
pub struct LensEffectsConfig {
    /// Optional chromatic aberration step.
    pub chromatic_aberration: Option<ChromAberrationConfig>,
    /// Optional barrel/pincushion distortion step.
    pub distortion: Option<DistortionConfig>,
    /// Optional vignetting step.
    pub vignette: Option<LensVignetteConfig>,
}

/// Summary statistics for the lens effects applied to an image.
#[derive(Debug, Clone, PartialEq)]
pub struct LensEffectStats {
    /// Mean pixel displacement (in pixels) caused by chromatic aberration.
    pub mean_shift_pixels: f32,
    /// Maximum pixel displacement caused by chromatic aberration.
    pub max_shift_pixels: f32,
    /// Vignette factor at the image centre (≈ 1.0 with default settings).
    pub vignette_factor_center: f32,
    /// Vignette factor at the image corner `(1, 1)` in normalised coords.
    pub vignette_factor_corner: f32,
}

// ─────────────────────────────────────────────────────────────────────────────
// Private helpers
// ─────────────────────────────────────────────────────────────────────────────

/// Bilinear-sample the RGB channels of a u8 RGBA image at fractional pixel
/// coordinates, clamping to the image boundary.
///
/// Returns `[r, g, b]` as `f32` in `[0, 255]`.
fn bilinear_sample_f32(img: &[u8], width: u32, height: u32, fx: f32, fy: f32) -> [f32; 3] {
    if img.is_empty() || width == 0 || height == 0 {
        return [0.0; 3];
    }

    let xc = fx.clamp(0.0, (width - 1) as f32);
    let yc = fy.clamp(0.0, (height - 1) as f32);

    let x0 = xc.floor() as usize;
    let y0 = yc.floor() as usize;
    let x1 = (x0 + 1).min((width - 1) as usize);
    let y1 = (y0 + 1).min((height - 1) as usize);

    let tx = xc - x0 as f32;
    let ty = yc - y0 as f32;
    let w = width as usize;

    let sample = |row: usize, col: usize| -> [f32; 3] {
        let base = (row * w + col) * 4;
        [
            img.get(base).copied().unwrap_or(0) as f32,
            img.get(base + 1).copied().unwrap_or(0) as f32,
            img.get(base + 2).copied().unwrap_or(0) as f32,
        ]
    };

    let p00 = sample(y0, x0);
    let p10 = sample(y0, x1);
    let p01 = sample(y1, x0);
    let p11 = sample(y1, x1);

    let mut out = [0.0_f32; 3];
    for i in 0..3 {
        let top = p00[i] * (1.0 - tx) + p10[i] * tx;
        let bot = p01[i] * (1.0 - tx) + p11[i] * tx;
        out[i] = top * (1.0 - ty) + bot * ty;
    }
    out
}

/// Bilinear-sample a *single* channel of a u8 RGBA image at fractional
/// pixel coordinates, clamping to the image boundary.
///
/// Used by [`apply_chromatic_aberration_rgba`], which needs a different
/// source position per channel — sampling only the needed channel (instead
/// of all three via [`bilinear_sample_f32`] and discarding two) avoids
/// doing 3x the bilinear-fetch work.
#[inline]
fn bilinear_sample_channel_f32(
    img: &[u8],
    width: u32,
    height: u32,
    fx: f32,
    fy: f32,
    channel: usize,
) -> f32 {
    if img.is_empty() || width == 0 || height == 0 {
        return 0.0;
    }

    let xc = fx.clamp(0.0, (width - 1) as f32);
    let yc = fy.clamp(0.0, (height - 1) as f32);

    let x0 = xc.floor() as usize;
    let y0 = yc.floor() as usize;
    let x1 = (x0 + 1).min((width - 1) as usize);
    let y1 = (y0 + 1).min((height - 1) as usize);

    let tx = xc - x0 as f32;
    let ty = yc - y0 as f32;
    let w = width as usize;

    let sample = |row: usize, col: usize| -> f32 {
        let idx = (row * w + col) * 4 + channel;
        img.get(idx).copied().unwrap_or(0) as f32
    };

    let v00 = sample(y0, x0);
    let v10 = sample(y0, x1);
    let v01 = sample(y1, x0);
    let v11 = sample(y1, x1);
    let top = v00 * (1.0 - tx) + v10 * tx;
    let bot = v01 * (1.0 - tx) + v11 * tx;
    top * (1.0 - ty) + bot * ty
}

/// Convert a pixel coordinate to the normalised `[-1, 1]`-ish space (the
/// image's shorter dimension spans `[-1, 1]`; the longer one extends
/// beyond that symmetrically).
///
/// Both axes are scaled by the *same* factor (the shorter image
/// dimension) rather than independently by their own dimension, so equal
/// pixel distances from the centre map to equal radii regardless of
/// aspect ratio. The previous per-axis scaling made every radial effect
/// (vignette, chromatic aberration, barrel distortion) anisotropically
/// stretched on non-square images — e.g. ~1.8x stronger horizontally than
/// vertically on a 16:9 render. On a square image this is identical to
/// the old per-axis formula.
#[inline]
fn normalized_coords(px: u32, py: u32, width: u32, height: u32) -> (f32, f32) {
    let scale = 2.0 / (width.min(height).max(1) as f32);
    let cx = width as f32 * 0.5;
    let cy = height as f32 * 0.5;
    let nx = ((px as f32 + 0.5) - cx) * scale;
    let ny = ((py as f32 + 0.5) - cy) * scale;
    (nx, ny)
}

/// Inverse of [`normalized_coords`]: convert from normalised space back to
/// pixel space. Kept as the exact algebraic inverse of `normalized_coords`.
#[inline]
pub(crate) fn normalized_to_pixel(nx: f32, ny: f32, width: u32, height: u32) -> (f32, f32) {
    let scale = 2.0 / (width.min(height).max(1) as f32);
    let cx = width as f32 * 0.5;
    let cy = height as f32 * 0.5;
    let px = nx / scale + cx - 0.5;
    let py = ny / scale + cy - 0.5;
    (px, py)
}

/// Compute distorted source coordinates from normalised output coordinates.
///
/// Applies the Brown–Conrady radial model:
/// `radial_factor = 1 + k1·r² + k2·r⁴`.
#[inline]
pub(crate) fn apply_distortion_coords(nx: f32, ny: f32, k1: f32, k2: f32) -> (f32, f32) {
    let r2 = nx * nx + ny * ny;
    let rf = 1.0 + k1 * r2 + k2 * r2 * r2;
    (nx * rf, ny * rf)
}

/// Compute the vignette factor `∈ [0, 1]` for a normalised coordinate.
#[inline]
pub(crate) fn compute_vignette_factor(nx: f32, ny: f32, config: &LensVignetteConfig) -> f32 {
    let r = (nx * nx + ny * ny).sqrt();
    if r <= config.radius {
        return 1.0;
    }
    // Normalize by the actual maximum radius reachable in the [-1,1]^2
    // normalised space — the corners, at r = sqrt(2) — not 1.0. The
    // corners are farther than the edge midpoints, so normalizing by 1.0
    // made `t` exceed 1 well before the true image corner, driving the
    // vignette to full black there regardless of `strength`.
    let outer = (std::f32::consts::SQRT_2 - config.radius).max(1e-6);
    let t = ((r - config.radius) / outer).clamp(0.0, 1.0);
    (1.0 - config.strength * t.powf(config.falloff)).clamp(0.0, 1.0)
}

/// Validate that the RGBA buffer matches the declared dimensions.
fn validate_rgba_buffer(img: &[u8], width: u32, height: u32) -> Result<(), LensEffectError> {
    if img.is_empty() || width == 0 || height == 0 {
        return Err(LensEffectError::EmptyImage);
    }
    let expected = (width as usize) * (height as usize) * 4;
    if img.len() != expected {
        return Err(LensEffectError::InvalidDimensions {
            actual: img.len(),
            expected,
            width,
            height,
        });
    }
    Ok(())
}

// ─────────────────────────────────────────────────────────────────────────────
// Public functions
// ─────────────────────────────────────────────────────────────────────────────

/// Apply per-channel radial chromatic aberration to a u8 RGBA image.
///
/// # Errors
///
/// - [`LensEffectError::EmptyImage`] for zero-dimension images.
/// - [`LensEffectError::InvalidDimensions`] if the buffer length mismatches.
/// - [`LensEffectError::InvalidAberrationStrength`] if `config.strength ∉ [0, 1]`.
pub fn apply_chromatic_aberration_rgba(
    image_rgba: &[u8],
    width: u32,
    height: u32,
    config: &ChromAberrationConfig,
) -> Result<Vec<u8>, LensEffectError> {
    validate_rgba_buffer(image_rgba, width, height)?;
    config.validate()?;

    let eff_r = config.red_shift * config.strength;
    let eff_g = config.green_shift * config.strength;
    let eff_b = config.blue_shift * config.strength;

    let n = (width * height) as usize;
    let mut out = vec![0u8; n * 4];

    // Single pass over destination pixels: compute (nx, ny) once and
    // derive each channel's own shifted source position from the shared
    // r², sampling only that one channel. The previous implementation ran
    // `radial_shift_channel` three times, each re-deriving (nx, ny) / r²
    // from scratch and bilinear-sampling *all three* channels while
    // discarding two of them — 3x the pass count and 3x the bilinear work.
    for py in 0..height {
        for px in 0..width {
            let (nx, ny) = normalized_coords(px, py, width, height);
            let r2 = nx * nx + ny * ny;

            let idx = (py * width + px) as usize;
            let base = idx * 4;

            for (channel, shift) in [(0usize, eff_r), (1, eff_g), (2, eff_b)] {
                let scale = 1.0 + shift * r2;
                let src_nx = nx * scale;
                let src_ny = ny * scale;
                let (src_px, src_py) = normalized_to_pixel(src_nx, src_ny, width, height);
                let v =
                    bilinear_sample_channel_f32(image_rgba, width, height, src_px, src_py, channel);
                out[base + channel] = v.clamp(0.0, 255.0).round() as u8;
            }

            out[base + 3] = image_rgba.get(base + 3).copied().unwrap_or(255);
        }
    }

    Ok(out)
}

/// Apply barrel/pincushion distortion to a u8 RGBA image.
///
/// # Errors
///
/// - [`LensEffectError::EmptyImage`] for zero-dimension images.
/// - [`LensEffectError::InvalidDimensions`] if the buffer length mismatches.
/// - [`LensEffectError::InvalidDistortionCoeff`] /
///   [`LensEffectError::InvalidAberrationStrength`] for out-of-range config values.
pub fn apply_barrel_distortion(
    image_rgba: &[u8],
    width: u32,
    height: u32,
    config: &DistortionConfig,
) -> Result<Vec<u8>, LensEffectError> {
    validate_rgba_buffer(image_rgba, width, height)?;
    config.validate()?;

    let k1 = config.k1 * config.strength;
    let k2 = config.k2 * config.strength;

    let n = (width * height) as usize;
    let mut out = vec![0u8; n * 4];

    for py in 0..height {
        for px in 0..width {
            let (nx, ny) = normalized_coords(px, py, width, height);
            let (src_nx, src_ny) = apply_distortion_coords(nx, ny, k1, k2);
            let (src_px, src_py) = normalized_to_pixel(src_nx, src_ny, width, height);

            let rgb = bilinear_sample_f32(image_rgba, width, height, src_px, src_py);
            let a = {
                let ax = src_px.clamp(0.0, (width - 1) as f32) as usize;
                let ay = src_py.clamp(0.0, (height - 1) as f32) as usize;
                image_rgba
                    .get((ay * width as usize + ax) * 4 + 3)
                    .copied()
                    .unwrap_or(255)
            };

            let idx = (py * width + px) as usize;
            if let Some(dst) = out.get_mut(idx * 4..idx * 4 + 4) {
                dst[0] = rgb[0].clamp(0.0, 255.0).round() as u8;
                dst[1] = rgb[1].clamp(0.0, 255.0).round() as u8;
                dst[2] = rgb[2].clamp(0.0, 255.0).round() as u8;
                dst[3] = a;
            }
        }
    }

    Ok(out)
}

/// Apply vignetting to a u8 RGBA image.
///
/// Alpha is preserved unchanged.
///
/// # Errors
///
/// - [`LensEffectError::EmptyImage`] for zero-dimension images.
/// - [`LensEffectError::InvalidDimensions`] if the buffer length mismatches.
/// - [`LensEffectError::InvalidAberrationStrength`] if `strength ∉ [0, 1]`.
pub fn apply_vignette_effect(
    image_rgba: &[u8],
    width: u32,
    height: u32,
    config: &LensVignetteConfig,
) -> Result<Vec<u8>, LensEffectError> {
    validate_rgba_buffer(image_rgba, width, height)?;
    config.validate()?;

    let n = (width * height) as usize;
    let mut out = vec![0u8; n * 4];

    for py in 0..height {
        for px in 0..width {
            let (nx, ny) = normalized_coords(px, py, width, height);
            let factor = compute_vignette_factor(nx, ny, config);
            let inv = 1.0 - factor;

            let idx = (py * width + px) as usize;
            let base = idx * 4;

            for ch in 0..3 {
                let src = image_rgba.get(base + ch).copied().unwrap_or(0) as f32;
                let color_val = config.color.get(ch).copied().unwrap_or(0.0) * 255.0;
                let blended = (factor * src + inv * color_val).clamp(0.0, 255.0).round() as u8;
                if let Some(dst) = out.get_mut(base + ch) {
                    *dst = blended;
                }
            }
            if let Some(dst) = out.get_mut(base + 3) {
                *dst = image_rgba.get(base + 3).copied().unwrap_or(255);
            }
        }
    }

    Ok(out)
}

/// Apply all configured lens effects in order: aberration → distortion → vignette.
///
/// Each step is optional.  If a step's `Option` is `None` the image passes
/// through unchanged for that step.
///
/// # Errors
///
/// Propagates errors from any of the individual effect functions.
pub fn apply_lens_effects(
    image_rgba: &[u8],
    width: u32,
    height: u32,
    config: &LensEffectsConfig,
) -> Result<Vec<u8>, LensEffectError> {
    validate_rgba_buffer(image_rgba, width, height)?;

    let mut current: Vec<u8> = image_rgba.to_vec();

    if let Some(ref ca) = config.chromatic_aberration {
        current = apply_chromatic_aberration_rgba(&current, width, height, ca)?;
    }
    if let Some(ref dist) = config.distortion {
        current = apply_barrel_distortion(&current, width, height, dist)?;
    }
    if let Some(ref vig) = config.vignette {
        current = apply_vignette_effect(&current, width, height, vig)?;
    }

    Ok(current)
}

/// Compute summary statistics for the requested lens effects without modifying
/// an image.
///
/// Pass `None` for any effect whose statistics should be skipped; those fields
/// will be zero or one as appropriate.
pub fn compute_lens_effect_stats(
    width: u32,
    height: u32,
    ca_config: Option<&ChromAberrationConfig>,
    vignette_config: Option<&LensVignetteConfig>,
) -> LensEffectStats {
    let (mean_shift, max_shift) = if let Some(ca) = ca_config {
        let max_sf = ca.red_shift.abs().max(ca.blue_shift.abs()) * ca.strength;
        let half_diag = ((width * width + height * height) as f32).sqrt() * 0.5;
        let mut sum = 0.0f32;
        let mut max_s = 0.0f32;
        let n = width * height;

        for py in 0..height {
            for px in 0..width {
                let (nx, ny) = normalized_coords(px, py, width, height);
                let r2 = nx * nx + ny * ny;
                let shift_px = max_sf * r2 * half_diag;
                sum += shift_px;
                if shift_px > max_s {
                    max_s = shift_px;
                }
            }
        }

        let mean = if n > 0 { sum / n as f32 } else { 0.0 };
        (mean, max_s)
    } else {
        (0.0, 0.0)
    };

    let (vf_center, vf_corner) = if let Some(vc) = vignette_config {
        (
            compute_vignette_factor(0.0, 0.0, vc),
            compute_vignette_factor(1.0, 1.0, vc),
        )
    } else {
        (1.0, 1.0)
    };

    LensEffectStats {
        mean_shift_pixels: mean_shift,
        max_shift_pixels: max_shift,
        vignette_factor_center: vf_center,
        vignette_factor_corner: vf_corner,
    }
}

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

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

    fn solid_rgba(w: u32, h: u32, r: u8, g: u8, b: u8, a: u8) -> Vec<u8> {
        let n = (w * h) as usize;
        let mut img = vec![0u8; n * 4];
        for i in 0..n {
            img[i * 4] = r;
            img[i * 4 + 1] = g;
            img[i * 4 + 2] = b;
            img[i * 4 + 3] = a;
        }
        img
    }

    // ── 1. ChromAberrationConfig default values ────────────────────────────────

    #[test]
    fn test_chrom_aberration_config_defaults() {
        let cfg = ChromAberrationConfig::default();
        assert!((cfg.red_shift - 0.005).abs() < 1e-6);
        assert!((cfg.green_shift - 0.0).abs() < 1e-6);
        assert!((cfg.blue_shift + 0.005).abs() < 1e-6);
        assert!((cfg.strength - 1.0).abs() < 1e-6);
    }

    // ── 2. ChromAberrationConfig::validate: strength out of range ─────────────

    #[test]
    fn test_chrom_aberration_config_validate_bad_strength() {
        let cfg = ChromAberrationConfig {
            strength: 1.1,
            ..Default::default()
        };
        assert!(matches!(
            cfg.validate(),
            Err(LensEffectError::InvalidAberrationStrength { .. })
        ));
        let cfg2 = ChromAberrationConfig {
            strength: -0.1,
            ..Default::default()
        };
        assert!(cfg2.validate().is_err());
    }

    // ── 3. ChromAberrationConfig::validate: valid strength ────────────────────

    #[test]
    fn test_chrom_aberration_config_validate_ok() {
        assert!(ChromAberrationConfig::default().validate().is_ok());
    }

    // ── 4. DistortionConfig default values ────────────────────────────────────

    #[test]
    fn test_distortion_config_defaults() {
        let cfg = DistortionConfig::default();
        assert!((cfg.k1 - 0.0).abs() < 1e-6);
        assert!((cfg.k2 - 0.0).abs() < 1e-6);
        assert!((cfg.strength - 1.0).abs() < 1e-6);
    }

    // ── 5. DistortionConfig::validate: k1 out of range → error ───────────────

    #[test]
    fn test_distortion_config_validate_bad_k1() {
        let cfg = DistortionConfig {
            k1: -1.5,
            ..DistortionConfig::default()
        };
        assert!(matches!(
            cfg.validate(),
            Err(LensEffectError::InvalidDistortionCoeff { .. })
        ));
    }

    // ── 6. DistortionConfig::validate: k2 out of range → error ───────────────

    #[test]
    fn test_distortion_config_validate_bad_k2() {
        let cfg = DistortionConfig {
            k2: 1.5,
            ..DistortionConfig::default()
        };
        assert!(matches!(
            cfg.validate(),
            Err(LensEffectError::InvalidDistortionCoeff { .. })
        ));
    }

    // ── 7. DistortionConfig::validate: strength out of range → error ──────────

    #[test]
    fn test_distortion_config_validate_bad_strength() {
        let cfg = DistortionConfig {
            strength: 2.0,
            ..DistortionConfig::default()
        };
        assert!(cfg.validate().is_err());
    }

    // ── 8. LensVignetteConfig default values ──────────────────────────────────

    #[test]
    fn test_lens_vignette_config_defaults() {
        let cfg = LensVignetteConfig::default();
        assert!((cfg.strength - 0.5).abs() < 1e-6);
        assert!((cfg.radius - 0.7).abs() < 1e-6);
        assert!((cfg.falloff - 2.0).abs() < 1e-6);
        assert_eq!(cfg.color, [0.0, 0.0, 0.0]);
    }

    // ── 9. LensVignetteConfig::validate: invalid strength → error ─────────────

    #[test]
    fn test_lens_vignette_config_validate_bad_strength() {
        let cfg = LensVignetteConfig {
            strength: -0.1,
            ..LensVignetteConfig::default()
        };
        assert!(cfg.validate().is_err());
        let cfg2 = LensVignetteConfig {
            strength: 1.5,
            ..LensVignetteConfig::default()
        };
        assert!(cfg2.validate().is_err());
    }

    // ── 10. normalized_coords: centre of 256×256 → near (0, 0) ───────────────

    #[test]
    fn test_normalized_coords_center() {
        let (nx, ny) = normalized_coords(127, 127, 256, 256);
        assert!(nx.abs() < 0.01, "Expected nx ≈ 0, got {nx}");
        assert!(ny.abs() < 0.01, "Expected ny ≈ 0, got {ny}");
    }

    // ── 11. normalized_to_pixel: inverse of normalized_coords ─────────────────

    #[test]
    fn test_normalized_to_pixel_inverse() {
        for &(px, py, w, h) in &[(3u32, 5u32, 16u32, 16u32), (0, 0, 8, 8), (7, 3, 10, 10)] {
            let (nx, ny) = normalized_coords(px, py, w, h);
            let (rx, ry) = normalized_to_pixel(nx, ny, w, h);
            assert!(
                (rx - px as f32).abs() < 1e-4,
                "px round-trip: {px} → {nx} → {rx}"
            );
            assert!(
                (ry - py as f32).abs() < 1e-4,
                "py round-trip: {py} → {ny} → {ry}"
            );
        }
    }

    // ── 11b. normalized_coords: isotropic (aspect-ratio independent) radius ──

    #[test]
    fn test_normalized_coords_isotropic_on_wide_image() {
        // Regression: previously each axis was normalized independently by
        // its own dimension, so on a non-square image, a horizontal pixel
        // offset and an equal *pixel* vertical offset produced very
        // different radii (anisotropic / elliptical radial effects). Equal
        // pixel distances from the centre must now give equal radii.
        let w = 16u32;
        let h = 4u32;
        let (nx_h, ny_h) = normalized_coords(w / 2 + 2, h / 2, w, h);
        let (nx_v, ny_v) = normalized_coords(w / 2, h / 2 + 2, w, h);
        let r_h = (nx_h * nx_h + ny_h * ny_h).sqrt();
        let r_v = (nx_v * nx_v + ny_v * ny_v).sqrt();
        assert!(
            (r_h - r_v).abs() < 1e-4,
            "radii should match for equal pixel offsets: r_h={r_h} r_v={r_v}"
        );
    }

    #[test]
    fn test_vignette_factor_equal_at_equal_pixel_radius_wide_image() {
        // Same isotropy property, exercised through `compute_vignette_factor`
        // on a 16:4 image.
        let w = 16u32;
        let h = 4u32;
        let cfg = LensVignetteConfig {
            strength: 0.6,
            radius: 0.1,
            ..LensVignetteConfig::default()
        };
        let (nx_h, ny_h) = normalized_coords(w / 2 + 2, h / 2, w, h);
        let (nx_v, ny_v) = normalized_coords(w / 2, h / 2 + 2, w, h);
        let f_h = compute_vignette_factor(nx_h, ny_h, &cfg);
        let f_v = compute_vignette_factor(nx_v, ny_v, &cfg);
        assert!(
            (f_h - f_v).abs() < 1e-4,
            "vignette factor should be equal at equal pixel radius: f_h={f_h} f_v={f_v}"
        );
    }

    // ── 12. apply_distortion_coords: k1=0, k2=0 → identity ───────────────────

    #[test]
    fn test_apply_distortion_coords_identity() {
        let (ox, oy) = apply_distortion_coords(0.3, -0.4, 0.0, 0.0);
        assert!((ox - 0.3).abs() < 1e-6);
        assert!((oy + 0.4).abs() < 1e-6);
    }

    // ── 13. apply_distortion_coords: negative k1 → barrel ────────────────────

    #[test]
    fn test_apply_distortion_coords_barrel() {
        let (ox, _) = apply_distortion_coords(0.5, 0.0, -0.5, 0.0);
        assert!(
            ox < 0.5,
            "Barrel: distorted x should be less than original: {ox}"
        );
    }

    // ── 14. compute_vignette_factor: centre → 1.0 ─────────────────────────────

    #[test]
    fn test_compute_vignette_factor_center() {
        let cfg = LensVignetteConfig::default();
        let f = compute_vignette_factor(0.0, 0.0, &cfg);
        assert!((f - 1.0).abs() < 1e-6, "Expected 1.0 at centre, got {f}");
    }

    // ── 15. compute_vignette_factor: far corner → reduced ─────────────────────

    #[test]
    fn test_compute_vignette_factor_corner_reduced() {
        let cfg = LensVignetteConfig::default();
        let corner = compute_vignette_factor(1.0, 1.0, &cfg);
        assert!(
            corner < 1.0,
            "Vignette at corner should be < 1.0, got {corner}"
        );
        assert!(corner >= 0.0);
    }

    // ── 15b. compute_vignette_factor: corner bounded by 1.0 - strength ───────

    #[test]
    fn test_compute_vignette_factor_corner_bounded_by_strength() {
        // Regression: the falloff was previously normalized against r=1.0
        // instead of the true maximum radius sqrt(2), so the actual image
        // corner (nx=ny=1.0) always clamped to a factor of exactly 0.0
        // (fully black) regardless of `strength`. The corner factor must
        // never drop below `1.0 - strength`.
        let cfg = LensVignetteConfig::default(); // strength = 0.5
        let corner = compute_vignette_factor(1.0, 1.0, &cfg);
        assert!(
            corner >= 1.0 - cfg.strength - 1e-5,
            "corner factor {corner} should be >= 1.0 - strength ({})",
            1.0 - cfg.strength
        );
    }

    // ── 16. bilinear_sample_f32: in-bounds → correct value ────────────────────

    #[test]
    fn test_bilinear_sample_f32_in_bounds() {
        let mut img = vec![0u8; 4 * 4]; // 2×2 RGBA
        img[0] = 200;
        img[1] = 100;
        img[2] = 50;
        img[3] = 255;
        let rgb = bilinear_sample_f32(&img, 2, 2, 0.0, 0.0);
        assert!((rgb[0] - 200.0).abs() < 1.0);
        assert!((rgb[1] - 100.0).abs() < 1.0);
        assert!((rgb[2] - 50.0).abs() < 1.0);
    }

    // ── 17. bilinear_sample_f32: out-of-bounds clamped ────────────────────────

    #[test]
    fn test_bilinear_sample_f32_clamped() {
        let img = solid_rgba(4, 4, 128, 200, 60, 255);
        let rgb = bilinear_sample_f32(&img, 4, 4, 100.0, 100.0);
        assert!((rgb[0] - 128.0).abs() < 1.0);
    }

    // ── 18. bilinear_sample_channel_f32: agrees with bilinear_sample_f32 ─────

    #[test]
    fn test_bilinear_sample_channel_matches_full_sample() {
        // `apply_chromatic_aberration_rgba` was rewritten to sample one
        // channel at a time (avoiding 3x redundant bilinear work); the
        // single-channel sampler must agree with the all-channel sampler
        // (still used by `apply_barrel_distortion`) on every channel, for
        // a non-solid-colour image (so genuine interpolation occurs).
        let img = solid_rgba(6, 5, 37, 91, 214, 255);
        // Overwrite a few pixels so the image isn't uniform.
        let mut img = img;
        img[0] = 250;
        img[1] = 10;
        img[2] = 5;
        for &(fx, fy) in &[(0.0f32, 0.0f32), (2.7, 1.3), (5.0, 4.0), (3.5, 2.5)] {
            let full = bilinear_sample_f32(&img, 6, 5, fx, fy);
            for ch in 0..3 {
                let single = bilinear_sample_channel_f32(&img, 6, 5, fx, fy, ch);
                assert!(
                    (single - full[ch]).abs() < 1e-3,
                    "channel {ch} mismatch at ({fx},{fy}): single={single} full={full:?}"
                );
            }
        }
    }

    // ── 19. apply_chromatic_aberration_rgba: output size correct ──────────────

    #[test]
    fn test_apply_chromatic_aberration_rgba_output_size() {
        let img = solid_rgba(8, 6, 100, 120, 80, 255);
        let cfg = ChromAberrationConfig::default();
        let out =
            apply_chromatic_aberration_rgba(&img, 8, 6, &cfg).expect("chromatic aberration failed");
        assert_eq!(out.len(), 8 * 6 * 4);
    }

    // ── 20. apply_chromatic_aberration_rgba: zero shifts → identical ──────────

    #[test]
    fn test_apply_chromatic_aberration_rgba_zero_shifts_identity() {
        let img = solid_rgba(8, 8, 120, 80, 200, 255);
        let cfg = ChromAberrationConfig {
            red_shift: 0.0,
            green_shift: 0.0,
            blue_shift: 0.0,
            strength: 1.0,
        };
        let out = apply_chromatic_aberration_rgba(&img, 8, 8, &cfg).expect("CA failed");
        for i in 0..(8 * 8) {
            assert_eq!(img[i * 4], out[i * 4]);
            assert_eq!(img[i * 4 + 1], out[i * 4 + 1]);
            assert_eq!(img[i * 4 + 2], out[i * 4 + 2]);
        }
    }

    // ── 21. apply_chromatic_aberration_rgba: empty image → error ─────────────

    #[test]
    fn test_apply_chromatic_aberration_rgba_empty_error() {
        let cfg = ChromAberrationConfig::default();
        let result = apply_chromatic_aberration_rgba(&[], 0, 0, &cfg);
        assert!(matches!(result, Err(LensEffectError::EmptyImage)));
    }

    // ── 22. apply_chromatic_aberration_rgba: alpha channel preserved ──────────

    #[test]
    fn test_chromatic_aberration_rgba_alpha_preserved() {
        let img = solid_rgba(8, 8, 100, 150, 200, 77);
        let cfg = ChromAberrationConfig::moderate();
        let out = apply_chromatic_aberration_rgba(&img, 8, 8, &cfg).expect("CA failed");
        for i in 0..(8 * 8) {
            assert_eq!(out[i * 4 + 3], 77, "Alpha must equal 77 at pixel {i}");
        }
    }

    // ── 23. apply_barrel_distortion: output size correct ─────────────────────

    #[test]
    fn test_apply_barrel_distortion_output_size() {
        let img = solid_rgba(6, 4, 100, 100, 100, 255);
        let cfg = DistortionConfig::default();
        let out = apply_barrel_distortion(&img, 6, 4, &cfg).expect("barrel distortion failed");
        assert_eq!(out.len(), 6 * 4 * 4);
    }

    // ── 24. apply_barrel_distortion: k1=0 → near-identity ────────────────────

    #[test]
    fn test_apply_barrel_distortion_identity() {
        let img = solid_rgba(8, 8, 100, 150, 200, 255);
        let cfg = DistortionConfig::default();
        let out = apply_barrel_distortion(&img, 8, 8, &cfg).expect("barrel distortion failed");
        for i in 0..(8 * 8) {
            assert!((img[i * 4] as i32 - out[i * 4] as i32).abs() <= 1);
        }
    }

    // ── 25. apply_barrel_distortion: invalid buffer → error ──────────────────

    #[test]
    fn test_apply_barrel_distortion_invalid_buffer() {
        let bad = vec![0u8; 5];
        let cfg = DistortionConfig::default();
        let result = apply_barrel_distortion(&bad, 2, 2, &cfg);
        assert!(matches!(
            result,
            Err(LensEffectError::InvalidDimensions { .. })
        ));
    }

    // ── 26. apply_vignette_effect: output size correct ────────────────────────

    #[test]
    fn test_apply_vignette_effect_output_size() {
        let img = solid_rgba(10, 8, 200, 200, 200, 255);
        let cfg = LensVignetteConfig::default();
        let out = apply_vignette_effect(&img, 10, 8, &cfg).expect("vignette failed");
        assert_eq!(out.len(), 10 * 8 * 4);
    }

    // ── 27. apply_vignette_effect: strength=0 → identical output ─────────────

    #[test]
    fn test_apply_vignette_effect_zero_strength_identity() {
        let img = solid_rgba(8, 8, 200, 100, 50, 255);
        let cfg = LensVignetteConfig {
            strength: 0.0,
            ..LensVignetteConfig::default()
        };
        let out = apply_vignette_effect(&img, 8, 8, &cfg).expect("vignette failed");
        assert_eq!(img, out);
    }

    // ── 28. apply_vignette_effect: centre brighter than corner ───────────────

    #[test]
    fn test_apply_vignette_effect_center_vs_corner() {
        let w = 16u32;
        let h = 16u32;
        let img = solid_rgba(w, h, 200, 200, 200, 255);
        let cfg = LensVignetteConfig {
            strength: 0.8,
            radius: 0.3,
            ..LensVignetteConfig::default()
        };
        let out = apply_vignette_effect(&img, w, h, &cfg).expect("vignette failed");
        let cx = (h / 2 * w + w / 2) as usize;
        let center_r = out[cx * 4] as f32;
        let corner_r = out[0] as f32;
        assert!(
            center_r >= corner_r,
            "Centre ({center_r}) should be >= corner ({corner_r})"
        );
    }

    // ── 29. apply_vignette_effect: alpha preserved ────────────────────────────

    #[test]
    fn test_apply_vignette_effect_alpha_preserved() {
        let img = solid_rgba(4, 4, 128, 128, 128, 200);
        let cfg = LensVignetteConfig::default();
        let out = apply_vignette_effect(&img, 4, 4, &cfg).expect("vignette failed");
        for i in 0..(4 * 4) {
            assert_eq!(out[i * 4 + 3], 200, "Alpha must be preserved at pixel {i}");
        }
    }

    // ── 30. apply_vignette_effect: invalid buffer → error ────────────────────

    #[test]
    fn test_apply_vignette_effect_invalid_buffer() {
        let bad = vec![0u8; 3];
        let cfg = LensVignetteConfig::default();
        let result = apply_vignette_effect(&bad, 1, 1, &cfg);
        assert!(matches!(
            result,
            Err(LensEffectError::InvalidDimensions { .. })
        ));
    }

    // ── 31. apply_lens_effects: all None → pass-through ──────────────────────

    #[test]
    fn test_apply_lens_effects_all_none_passthrough() {
        let img = solid_rgba(8, 8, 100, 150, 200, 255);
        let cfg = LensEffectsConfig::default();
        let out = apply_lens_effects(&img, 8, 8, &cfg).expect("lens effects failed");
        assert_eq!(img, out);
    }

    // ── 32. apply_lens_effects: all Some → applies effects ───────────────────

    #[test]
    fn test_apply_lens_effects_all_some_applies() {
        let img = solid_rgba(8, 8, 100, 150, 200, 255);
        let cfg = LensEffectsConfig {
            chromatic_aberration: Some(ChromAberrationConfig::default()),
            distortion: Some(DistortionConfig::default()),
            vignette: Some(LensVignetteConfig::default()),
        };
        let out = apply_lens_effects(&img, 8, 8, &cfg).expect("lens effects failed");
        assert_eq!(out.len(), 8 * 8 * 4);
    }

    // ── 33. apply_lens_effects: empty buffer → error ──────────────────────────

    #[test]
    fn test_apply_lens_effects_empty_buffer_error() {
        let cfg = LensEffectsConfig::default();
        let result = apply_lens_effects(&[], 0, 0, &cfg);
        assert!(matches!(result, Err(LensEffectError::EmptyImage)));
    }

    // ── 34. compute_lens_effect_stats: vignette centre = 1.0 ─────────────────

    #[test]
    fn test_compute_lens_effect_stats_vignette_center() {
        let vc = LensVignetteConfig::default();
        let stats = compute_lens_effect_stats(128, 128, None, Some(&vc));
        assert!(
            (stats.vignette_factor_center - 1.0).abs() < 1e-5,
            "Centre factor should be 1.0: {}",
            stats.vignette_factor_center
        );
    }

    // ── 35. compute_lens_effect_stats: vignette corner < centre ──────────────

    #[test]
    fn test_compute_lens_effect_stats_vignette_corner_less_than_center() {
        let vc = LensVignetteConfig {
            strength: 0.8,
            radius: 0.3,
            ..LensVignetteConfig::default()
        };
        let stats = compute_lens_effect_stats(64, 64, None, Some(&vc));
        assert!(
            stats.vignette_factor_corner < stats.vignette_factor_center,
            "Corner ({}) should be < centre ({})",
            stats.vignette_factor_corner,
            stats.vignette_factor_center
        );
    }

    // ── 36. compute_lens_effect_stats: no effects → zeros/ones ───────────────

    #[test]
    fn test_compute_lens_effect_stats_none_effects() {
        let stats = compute_lens_effect_stats(64, 64, None, None);
        assert!((stats.mean_shift_pixels - 0.0).abs() < 1e-6);
        assert!((stats.max_shift_pixels - 0.0).abs() < 1e-6);
        assert!((stats.vignette_factor_center - 1.0).abs() < 1e-6);
        assert!((stats.vignette_factor_corner - 1.0).abs() < 1e-6);
    }

    // ── 37. compute_lens_effect_stats: CA gives positive shift ────────────────

    #[test]
    fn test_compute_lens_effect_stats_ca_positive_shift() {
        let ca = ChromAberrationConfig::strong();
        let stats = compute_lens_effect_stats(128, 128, Some(&ca), None);
        assert!(
            stats.mean_shift_pixels > 0.0,
            "Mean shift should be positive: {}",
            stats.mean_shift_pixels
        );
        assert!(stats.max_shift_pixels >= stats.mean_shift_pixels);
    }

    // ── 38. ChromAberrationConfig presets: ordering ───────────────────────────

    #[test]
    fn test_chrom_aberration_presets_ordering() {
        let subtle = ChromAberrationConfig::subtle();
        let moderate = ChromAberrationConfig::moderate();
        let strong = ChromAberrationConfig::strong();
        assert!(subtle.red_shift < moderate.red_shift);
        assert!(moderate.red_shift < strong.red_shift);
        assert!(subtle.blue_shift > moderate.blue_shift);
        assert!(moderate.blue_shift > strong.blue_shift);
    }

    // ── 39. DistortionConfig presets: barrel vs pincushion signs ─────────────

    #[test]
    fn test_distortion_presets_signs() {
        let barrel = DistortionConfig::slight_barrel();
        let pincushion = DistortionConfig::slight_pincushion();
        assert!(barrel.k1 < 0.0, "Barrel k1 should be negative");
        assert!(pincushion.k1 > 0.0, "Pincushion k1 should be positive");
    }

    // ── 40. LensVignetteConfig presets: strength ordering ────────────────────

    #[test]
    fn test_lens_vignette_presets_strength_ordering() {
        let subtle = LensVignetteConfig::subtle();
        let cinema = LensVignetteConfig::cinema();
        assert!(subtle.strength < cinema.strength);
    }

    // ── 41. LensEffectError variants: display messages ────────────────────────

    #[test]
    fn test_lens_effect_error_display() {
        let e1 = LensEffectError::EmptyImage;
        assert!(!e1.to_string().is_empty());

        let e2 = LensEffectError::InvalidDimensions {
            actual: 10,
            expected: 16,
            width: 2,
            height: 2,
        };
        assert!(e2.to_string().contains("10"));

        let e3 = LensEffectError::InvalidAberrationStrength { strength: 1.5 };
        assert!(e3.to_string().contains("1.5"));

        let e4 = LensEffectError::InvalidDistortionCoeff { k: -2.0 };
        assert!(e4.to_string().contains("-2"));
    }

    // ── 42. LensEffectsConfig fields accessible ───────────────────────────────

    #[test]
    fn test_lens_effects_config_fields() {
        let cfg = LensEffectsConfig {
            chromatic_aberration: Some(ChromAberrationConfig::default()),
            distortion: None,
            vignette: None,
        };
        assert!(cfg.chromatic_aberration.is_some());
        assert!(cfg.distortion.is_none());
    }

    // ── 43. 4×4 chromatic aberration smoke test ───────────────────────────────

    #[test]
    fn test_4x4_chromatic_aberration_smoke() {
        let img = solid_rgba(4, 4, 200, 100, 50, 255);
        let cfg = ChromAberrationConfig {
            strength: 0.5,
            ..ChromAberrationConfig::default()
        };
        let out = apply_chromatic_aberration_rgba(&img, 4, 4, &cfg).expect("4×4 CA failed");
        assert_eq!(out.len(), 4 * 4 * 4);
        for i in 0..(4 * 4) {
            assert_eq!(out[i * 4 + 3], 255);
        }
    }

    // ── 44. 4×4 barrel distortion smoke test ─────────────────────────────────

    #[test]
    fn test_4x4_barrel_distortion_smoke() {
        let img = solid_rgba(4, 4, 128, 64, 32, 128);
        let cfg = DistortionConfig::slight_barrel();
        let out = apply_barrel_distortion(&img, 4, 4, &cfg).expect("4×4 barrel failed");
        assert_eq!(out.len(), 4 * 4 * 4);
    }

    // ── 45. 4×4 vignette smoke test ───────────────────────────────────────────

    #[test]
    fn test_4x4_vignette_smoke() {
        let img = solid_rgba(4, 4, 200, 200, 200, 255);
        let cfg = LensVignetteConfig::cinema();
        let out = apply_vignette_effect(&img, 4, 4, &cfg).expect("4×4 vignette failed");
        assert_eq!(out.len(), 4 * 4 * 4);
    }

    // ── 46. LensEffectStats fields accessible ─────────────────────────────────

    #[test]
    fn test_lens_effect_stats_fields() {
        let stats = LensEffectStats {
            mean_shift_pixels: 1.5,
            max_shift_pixels: 3.0,
            vignette_factor_center: 1.0,
            vignette_factor_corner: 0.6,
        };
        assert!((stats.mean_shift_pixels - 1.5).abs() < 1e-6);
        assert!((stats.max_shift_pixels - 3.0).abs() < 1e-6);
        assert!((stats.vignette_factor_center - 1.0).abs() < 1e-6);
        assert!((stats.vignette_factor_corner - 0.6).abs() < 1e-5);
    }

    // ── 47. LensVignetteConfig::validate: valid strength ─────────────────────

    #[test]
    fn test_lens_vignette_config_validate_ok() {
        assert!(LensVignetteConfig::default().validate().is_ok());
        assert!(LensVignetteConfig::subtle().validate().is_ok());
        assert!(LensVignetteConfig::cinema().validate().is_ok());
    }

    // ── 48. DistortionConfig::validate: all valid → ok ────────────────────────

    #[test]
    fn test_distortion_config_validate_ok() {
        assert!(DistortionConfig::default().validate().is_ok());
        assert!(DistortionConfig::slight_barrel().validate().is_ok());
        assert!(DistortionConfig::slight_pincushion().validate().is_ok());
    }

    // ── 49. ChromAberrationConfig: presets validate successfully ─────────────

    #[test]
    fn test_chrom_aberration_presets_validate_ok() {
        assert!(ChromAberrationConfig::subtle().validate().is_ok());
        assert!(ChromAberrationConfig::moderate().validate().is_ok());
        assert!(ChromAberrationConfig::strong().validate().is_ok());
    }

    // ── 50. apply_lens_effects: only vignette applied ────────────────────────

    #[test]
    fn test_apply_lens_effects_only_vignette() {
        let img = solid_rgba(8, 8, 200, 200, 200, 255);
        let cfg = LensEffectsConfig {
            chromatic_aberration: None,
            distortion: None,
            vignette: Some(LensVignetteConfig {
                strength: 1.0,
                radius: 0.0,
                ..LensVignetteConfig::default()
            }),
        };
        let out = apply_lens_effects(&img, 8, 8, &cfg).expect("lens effects failed");
        // Corner pixel should be fully darkened.
        assert!(
            out[0] < 200,
            "Corner should be darkened by vignette, got {}",
            out[0]
        );
    }
}