1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
use crate::;
use Vec3;
/// Builds the observer-PoV view basis (forward, right, up) from camera yaw/pitch.
///
/// Uses the exact same convention as `Camera::new` in `optics::raytracer` (same
/// `world_up` fallback threshold and axis), so that gemological metrics are evaluated
/// against the same frame that is actually rendered.
/// 19 tilt ELEVATION sample points (camera pitch, not tilt-from-table-up) in exact 5°
/// steps across 0° to 90°.
///
/// This is a different, independently-valid parameterisation from
/// [`TILT_ANGLES_DEG`]'s `-90..=+90°` tilt-away-from-table-up domain: `0°` here means
/// edge-on/profile (camera pitch 0), `90°` means table-up/face-up (camera pitch 90) --
/// the reverse of where those two poses sit in `TILT_ANGLES_DEG`. Kept exactly as it
/// is (unchanged by the full-axis sweep's ±90° widening) because
/// [`evaluate_angular_profile_at_azimuth`] is a real, independently-used elevation
/// sweep at a single fixed azimuth, not merely a coarser draft of the full-axis
/// function -- do not "unify" the two domains.
pub const PROFILE_ANGLES_DEG: = ;
/// Outcome of refracting an incident ray into the gemstone at a known entry point/normal
/// (for one specific refractive index) and following it through up to 10 internal bounces.
/// Factored out of the main grid loop so the exact same entry-refraction-then-bounce logic
/// can be replayed at the d-line index (for the windowing/extinction/brilliance
/// classification) and independently at the F-line and C-line indices (for the Fire
/// measurement below), from the identical physical entry point and incident direction.
/// The physical exit path of a ray that escaped upward through the crown: its exit
/// direction, the Fresnel entry*exit transmittance and exit-facet-normal cosine (see
/// `RayFate::ExitedUpward`'s doc), plus which facet it exited through and how many
/// internal TIR bounces it took to get there.
///
/// The facet index and bounce count exist purely so the Fire measurement can tell
/// whether a ray's F-line and C-line companion traces exited via the SAME physical
/// path. When a ray sits near a critical angle, F and C (whose refractive indices
/// differ) can straddle the TIR threshold at different bounces -- one refracts out
/// early, the other reflects on and exits several facets later through a completely
/// different part of the stone. `acos(dir_f . dir_c)` between two such unrelated exit
/// directions measures nothing physically meaningful (it is not "dispersion", it is two
/// different rays that happen to share an entry point), yet the raw angle can be tens of
/// degrees and dominate the weighted Fire sum. See the bifurcation gate in
/// `evaluate_gem_optical_metrics` for how this is used.
/// Unpolarized Fresnel transmittance at a dielectric interface, given the cosines of the
/// incident and transmitted angles on either side (`n1` -> `n2`). Averages the s- and
/// p-polarized reflectances (`Rs`, `Rp`) into a single scalar reflectance `R`, then
/// returns `T = 1 - R`, clamped to [0, 1]. Used to weight each ray's contribution to Fire
/// by the energy it actually delivers, rather than counting every surviving ray equally
/// regardless of how much of its light made it through the entry and exit interfaces.
/// Refracts `incoming_dir` into the gem at `entry_point`/`n_entry` using Snell's law for
/// `index`, then follows up to 10 internal bounces (TIR vs refract-out) exactly as the
/// original single-wavelength trace did. This is the physical core shared by the d-line,
/// F-line, and C-line traces -- identical control flow, parameterized only by which
/// refractive index the light is carrying.
/// Whether a ray that exited the gem in direction `exit_dir` is visibly returned to an
/// observer at `cam_forward` under the given key/fill/overhead-ring illumination -- i.e.
/// not lost to the observer's own head-shadow, AND actually collected by at least one of
/// the three light sources. This is the exact same "is this light visible" test used for
/// `brilliance_pct` / `extinction_pct` classification in the main loop below (Directional
/// Extinction Analysis), factored out here so the Scintillation temporal sub-poses (see
/// `cell_returned_at_yaw_offset` below) apply an identical definition of "returned" at
/// each rotated pose rather than a hand-rolled approximation of it.
/// Small camera-yaw offsets (degrees), sampled around the primary viewing azimuth, used
/// to measure Scintillation's TEMPORAL component: how much a given grid cell's light
/// return *changes* as the stone is gently rotated, as distinct from the static spatial
/// contrast measured across the grid at a single fixed pose. This is "a handful of
/// samples across a few degrees of rotation" -- five poses (odd count -- see
/// `cell_returned_at_yaw_offset`'s doc for why), spanning +/-3 deg, comparable in scale
/// to a hand gently tilting a stone for inspection, not a full turn.
const SCINT_TEMPORAL_YAW_OFFSETS_DEG: = ;
/// Weight of the spatial (per-pose, per-grid-cell contrast) term in the combined
/// `scintillation_pct`. See `combine_scintillation_pct` for the full weighting rationale.
const SCINT_SPATIAL_WEIGHT: f32 = 0.6;
/// Weight of the temporal (per-cell, across-pose flicker) term in the combined
/// `scintillation_pct`. See `combine_scintillation_pct` for the full weighting rationale.
const SCINT_TEMPORAL_WEIGHT: f32 = 0.4;
/// Per-evaluation context threaded through the Scintillation temporal sub-poses
/// (`cell_returned_at_yaw_offset`): everything needed to fire and classify one extra
/// ray at a rotated camera azimuth, bundled into one struct purely to keep that
/// function's argument count within clippy's `too_many_arguments` lint -- these six
/// values are otherwise identical across all `grid_size * grid_size *
/// SCINT_TEMPORAL_YAW_OFFSETS_DEG.len()` calls per `evaluate_gem_optical_metrics`
/// invocation.
/// Fires a single, non-jittered ray at grid cell `(u, v)` (same screen-space coordinates
/// as the main grid loop, in `[-1, 1]`) from the camera pose rotated by `yaw_offset_deg`
/// around `ctx.cam_yaw`, refracts it at the d-line only, and reports whether it is
/// visibly returned to an observer at that pose (`ray_is_visibly_returned` above).
/// Deliberately independent of the main grid loop's per-cell state: temporal modulation
/// is a distinct physical question (does the SAME screen-space cell's return status flip
/// as the viewpoint rotates) from the spatial sub-aperture contrast measured there, and
/// no fire (F-line/C-line) companion trace is needed since only whether light returns --
/// not its color separation -- is relevant to sparkle.
///
/// Odd offset counts (see [`SCINT_TEMPORAL_YAW_OFFSETS_DEG`]) avoid a subtle test hazard:
/// with an even sample count, a cell that flips exactly half the time lands at the
/// maximum possible Bernoulli variance (p=0.5, p*(1-p)=0.25) exactly, and if that
/// happened for literally every visited cell the temporal term would read exactly 100%
/// -- defeating the same "never let a percentage metric actually reach its ceiling"
/// property `scintillation_pct` already guards via the `cv / (1 + cv)` spatial squash
/// (see `no_built_in_material_saturates_scintillation_on_either_cut` in
/// `tests/metrics_tests.rs`). With 5 (odd) samples, the achievable discrete probabilities
/// are k/5 for k in 0..=5, whose variance k/5 * (1 - k/5) tops out at 0.24 (k=2 or 3),
/// strictly below the continuous maximum of 0.25 -- so the temporal term can approach but
/// never exactly reach 100% either, by the same construction as the spatial term, without
/// needing its own hyperbolic squash.
/// Scintillation TEMPORAL contribution of one grid cell `(u, v)`: does its return status
/// flip as the camera nudges through the few small azimuth offsets in
/// [`SCINT_TEMPORAL_YAW_OFFSETS_DEG`]? Computed via independent single-ray samples (see
/// `cell_returned_at_yaw_offset`), reduced to the Bernoulli variance `p * (1 - p)` of the
/// fraction `p` of offsets at which the cell returned light: 0 when the cell's return
/// status never flips across the sampled poses (always on, or always off -- bright or
/// dark, but not sparkling), up to 0.24 (see `cell_returned_at_yaw_offset`'s doc for why
/// not the continuous maximum 0.25) when it flips close to half the time.
/// Scintillation SPATIAL term: coefficient of variation (std-dev / mean) of per-cell
/// light-return fraction across the 18x18 grid (`cell_fraction_sum`, `cell_fraction_sum_sq`,
/// `cell_count` accumulated in the main grid loop), mapped into a 0-100 percentage.
/// CV = 0 means every visited cell returns light at the same rate (a uniformly bright or
/// uniformly dark stone -- no contrast, no sparkle). CV climbs as bright and dark cells
/// increasingly diverge, and for these per-facet-cell light-return distributions (sparse
/// bright cells against a mostly-dark field is the common case, not the exception) CV
/// routinely lands well above 1.0 -- a straight `(cv * 100.0).clamp(0.0, 100.0)` was
/// measured to saturate at exactly 100% for 19 of 26 material/cut combinations swept
/// across the built-ins, which collapses the metric's ability to discriminate among most
/// stones (see `fire_and_scintillation_are_finite_and_in_range_for_every_material_on_
/// both_cuts` and `no_built_in_material_saturates_scintillation_on_either_cut` in
/// `metrics_tests.rs`).
///
/// Instead, squash CV through `cv / (1 + cv)`, a monotone bijection from [0, inf) to
/// [0, 1): CV=0 -> 0%, CV=1 -> 50%, CV=2 -> 66.7%, CV=9 -> 90%, asymptotically
/// approaching but mathematically never reaching 100% however large CV gets. This keeps
/// the metric strictly ordered (higher CV always reads higher) and strictly below the
/// ceiling, so two stones with different spatial contrast always produce different
/// displayed values instead of both clipping to the same 100. A stone with no visited
/// cells (e.g. camera facing entirely outside the gem) reports 0: there is no light
/// return to contrast.
/// Scintillation TEMPORAL term: mean per-cell Bernoulli variance (`temporal_variance_sum`,
/// accumulated in the main grid loop via `cell_temporal_variance`) across the same
/// visited-cell set (`cell_count`) as the spatial term, normalized by its own achievable
/// maximum (0.24, not the continuous 0.25 -- see `cell_returned_at_yaw_offset`) into a
/// 0-100 percentage. This one needs no separate saturating squash: it is already bounded
/// by construction (mean of per-cell values that individually top out at 0.24 / 0.24 =
/// 100%), and averaging many cells' worth of samples makes the whole grid actually
/// landing on that per-cell ceiling simultaneously vanishingly unlikely in practice (see
/// `no_built_in_material_saturates_scintillation_on_either_cut`, which pins this for
/// every built-in material).
/// Combines the Scintillation spatial and temporal terms (both already 0-100
/// percentages) into the final displayed `scintillation_pct`.
///
/// The reference gemological definition of scintillation is spatial AND temporal
/// modulation together -- a static bright/dark pattern that does not change as the stone
/// moves is not "sparkle", and a stone that flickers everywhere uniformly (no spatial
/// contrast to begin with) has nothing to flicker between either. Weighted 60/40 toward
/// the spatial term: the spatial CV is measured from a much larger effective sample (5
/// sub-aperture rays x 18x18 grid, the same population every other metric here is
/// measured against) and is the term validated against all thirteen built-in materials
/// as non-saturating and broadly discriminating (see the module-level doc and
/// `no_built_in_material_saturates_scintillation_on_either_cut`); the temporal term is
/// measured far more coarsely (5 single-ray azimuth samples per cell, no sub-aperture
/// averaging) specifically to keep the added cost modest (see the task report for the
/// before/after measurement), so it is kept a substantial but minority contribution
/// rather than an equal partner. Note this weighting is NOT strong enough to make SRB
/// out-scintillate the emerald cut unconditionally: the spatial term's own much larger
/// dynamic range across cuts still dominates when the two cuts return very different
/// amounts of light (e.g. a low-brilliance emerald-cut reading with a few very bright,
/// very contrasty cells can out-score a brighter, more evenly-lit SRB reading). It IS
/// decisive specifically where the reference definition asks it to be: at roughly
/// comparable brilliance between the two cuts, the temporal term reliably tips SRB above
/// the emerald cut -- see
/// `srb_can_scintillate_more_than_emerald_cut_at_matched_brilliance` in
/// `tests/metrics_tests.rs` and the task report for the measured sweep and before/after
/// cost numbers.
/// Degrees-of-angular-separation -> display-scale multiplier for `fire_index`.
///
/// The measured quantity is the mean angle (in degrees) between a ray's F-line and
/// C-line exit directions, accumulated over the rays that are actually visibly
/// returned -- i.e. exit upward through the crown AND pass the same
/// `is_illuminated && !is_head_shadow` test used for `brilliance_pct` (see the main loop
/// below; rays that exit but are head-shadowed or unlit are physically invisible and are
/// intensity-weighted out of Fire, not just counted as "surviving"). Swept across every
/// built-in material, both `StandardGemCuts` cuts, and several camera pitches (see
/// `tests/metrics_tests.rs`), that mean separation typically lands somewhere in the
/// roughly 0.4-10 deg range depending on material dispersion, cut, and viewing/lighting
/// angle -- physically real (multiple TIR bounces each add their own chromatic
/// walk-off, so it is not surprising this is larger than a single-interface dispersion
/// angle), but not yet a legible UI number next to percentages like `brilliance_pct`.
///
/// This constant rescales that angle into a display range comparable to the old
/// closed-form `fire_index` values for ordinary gems (which topped out around 80 for
/// diamond), purely so the number stays legible in the existing UI widgets. It is a
/// *display* scale, not a fit: it was not tuned to reproduce old per-material numbers.
///
/// Re-derived twice so far. First (50 -> 175) after the exit-radiance-cosine weighting
/// was added to the Fire accumulation below (see the `radiance_weight` comment in the
/// main loop): that weighting multiplies in `exit_cos_f * exit_cos_c` on top of the
/// existing Fresnel transmittance product, suppressing every ray's contribution somewhat.
///
/// Second (175 -> 275) after the F/C bifurcation gate was added (see the gate's own
/// comment in the main loop below): requiring the F-line and C-line traces to exit
/// through the same facet after the same number of bounces discards the pairs whose raw
/// angle was dominated by disjoint, physically meaningless exit-direction divergence --
/// which, empirically, were also the pairs contributing the largest raw angles, so
/// discarding them shrinks the weighted sum more than it shrinks the ray count.
/// Recalibration method (same as the first pass): Diamond on the standard round
/// brilliant cut at the camera/light pose used throughout `tests/metrics_tests.rs`/
/// `tests/raytracer_tests.rs` (yaw 0.0, pitch 0.45, light yaw/pitch 0.85/0.95) measured a
/// raw weighted-mean separation of ~0.0716 deg post-gate (down from ~0.113 deg
/// pre-gate -- roughly a 37% drop, not quite the "halves" ballpark a cruder estimate
/// suggested, since the discarded pairs were disproportionately the largest-angle ones);
/// 275 was picked as the round multiplier landing that reference reading back at
/// `fire_index` ~= 19.7, matching the "tens" bucket the previous calibration pass
/// targeted. Sanity-checked afterward against the same pose's highest-dispersion
/// materials (Moissanite, Cubic Zirconia) and against
/// `fire_and_scintillation_are_finite_and_in_range_for_every_material_on_both_cuts`
/// (pitch 1.4): every built-in material on both cuts stays comfortably under 100 at this
/// scale, well inside that test's existing <1000 ceiling.
///
/// This scale, together with the bifurcation gate above it, DOES fix the emerald-cut
/// Fire ordering that the previous exit-radiance-cosine-only pass could not: see the
/// top-level comment on `evaluate_gem_optical_metrics` for the corrected measured tables
/// (Diamond now measures above Sapphire, Topaz, and Quartz on the emerald cut, as
/// dispersion predicts).
const FIRE_DEGREES_TO_DISPLAY_SCALE: f32 = 275.0;
/// Per-evaluation context threaded through [`classify_aperture_sample`]: everything
/// needed to fire and classify one grid-cell aperture-sample ray at the fixed camera
/// pose, bundled into one struct purely to keep that function's argument count within
/// clippy's `too_many_arguments` lint -- these ten values are otherwise identical
/// across all `grid_size * grid_size * aperture_samples.len()` calls per
/// `evaluate_gem_optical_metrics` invocation. Mirrors [`TemporalPoseContext`]'s reason
/// for existing, one level up (this context is built once per invocation at the fixed
/// pose; `TemporalPoseContext` is what the temporal sub-poses rebuild the view basis
/// from at each small yaw offset).
/// How one grid-cell aperture-sample ray was classified, mirroring the buckets the
/// pre-extraction main loop counted inline. `Returned` carries the qualifying Fire
/// sample's raw `(angle_deg, weight)` pair, if any -- deliberately NOT folded into the
/// Fire accumulator here, so the caller can apply the identical `f32::mul_add` chain
/// against its own running total, in the same grid-cell/aperture-sample iteration
/// order the pre-extraction code used. Folding it in here instead (e.g. via a `&mut
/// f32` accumulator parameter, or returning a partial sum to be added with `+`) would
/// change which intermediate values a fused multiply-add rounds against, silently
/// perturbing the bit-exact result -- see the module's task-level bit-exactness
/// requirement.
/// Fires a single grid-cell aperture-sample ray at screen-space coordinates `(u, v)`
/// (in `[-1, 1]`) with sub-aperture jitter `(dx_sub, dz_sub)`, refracts and traces it
/// through the stone at the d-line (and, if it qualifies, replays the same entry
/// point/direction at the F-line and C-line indices for the Fire measurement), and
/// classifies the result. Returns `None` if the ray misses the stone geometry entirely
/// (not counted in any bucket, matching the pre-extraction code's `continue` on a
/// miss).
///
/// This is a direct extraction of the pre-extraction main loop's per-sample body: it
/// performs exactly the same sequence of floating-point operations in exactly the same
/// order, just packaged as a function so `evaluate_gem_optical_metrics` itself does not
/// have to spell out the F/C bifurcation gate and Fire weighting inline. See
/// [`RayClassification`]'s doc for why the Fire accumulator itself is threaded through
/// the caller rather than updated in here.
/// Aggregate accumulators threaded through `evaluate_gem_optical_metrics`'s main grid
/// loop. Bundled into one `#[derive(Default)]` struct (every field starts at zero)
/// purely to collapse what used to be a dozen separate `let mut ... = 0` declarations
/// -- each with its own explanatory comment -- into a single
/// `MetricsAccumulators::default()` call in the function itself, keeping it under
/// clippy's line-count budget without losing any of the original per-field rationale,
/// which now lives on the fields below instead.
/// Prints the `DIAG_FIRE_DEBUG` Fire diagnostic line for one
/// `evaluate_gem_optical_metrics` invocation. Pure formatting over already-computed
/// values -- extracted purely to keep the `eprintln!`'s argument list out of the main
/// function's line count; touches no accumulator and performs no computation that
/// feeds back into any returned metric.
/// Bundles `MetricsAccumulators`' fields relevant to the Fire diagnostic line,
/// purely so [`log_fire_diagnostics`] takes `&MetricsAccumulators` directly instead of
/// unpacking each field into its own parameter (which pushed it over clippy's
/// `too_many_arguments` limit).
/// Prints the `DIAG_FIRE_DEBUG` Scintillation diagnostic line. Same rationale as
/// [`log_fire_diagnostics`].
/// Everything the main grid loop in [`evaluate_gem_optical_metrics`] needs that is
/// fixed across the whole evaluation: the sampling grid resolution, the sub-aperture
/// jitter bundle, and the two shared per-ray contexts ([`TemporalPoseContext`],
/// [`ApertureSampleContext`]).
/// Builds [`GridEvalSetup`]. A pure setup extraction: every value here is computed
/// exactly once, unconditionally, with no accumulator or loop state involved, so
/// moving it into its own function changes nothing about the floating-point operations
/// `evaluate_gem_optical_metrics` performs -- only where they are textually written.
/// Evaluates true GIA / AGSL optical gemological metrics by firing an analytical grid
/// of rays with viewing aperture cone from the observer's **Point of View (`PoV`)**.
///
/// Rays are fired from (`cam_yaw`, `cam_pitch`) through the 3D cutting schedule facet
/// geometry, dynamically accounting for:
/// 1. Gemstone refractive index n(λ) from Sellmeier / Cauchy equations
/// 2. Snell's law refraction at inclined crown & girdle facet entry points
/// 3. Total Internal Reflection (TIR) vs bottom leakage (Windowing) on pavilion facets
/// 4. Light source illumination alignment (`light_yaw`, `light_pitch`) vs head-shadow extinction
/// 5. Fire: the angular separation between the F-line and C-line images of each ray that
/// is actually visibly returned (same illumination test as brilliance), so a
/// high-leakage cut with a few stray near-critical-angle rays cannot outscore a
/// well-performing one on angle alone
/// 6. Scintillation: the spatial contrast (coefficient of variation) of light return
/// across the 18x18 sampling grid over the stone's face
///
/// ## Resolved: Fire ordering on step (emerald) cuts, and the F/C bifurcation artifact
///
/// It was long believed this metric systematically scored step cuts above brilliants.
/// That premise turned out to be wrong: at the canonical test poses, the round brilliant
/// correctly out-fires the emerald cut for Diamond/Quartz/Sapphire/Topaz (e.g. Diamond at
/// pitch 1.4: SRB ~20.0 vs. emerald ~9.2). Two real, separable defects remained:
///
/// 1. Material ordering could invert on step cuts (a low-dispersion material reading
/// higher Fire than Diamond on the emerald cut specifically).
/// 2. Isolated pose flips where a step cut beat the brilliant.
///
/// Root cause of both, isolated by measurement: Fire is computed by tracing the
/// Fraunhofer F and C lines and measuring the angular separation between their exit
/// directions (see point 5 above, and the `radiance_weight` comment in the main loop
/// below). When the F and C traces exit via *different facets, or after a different
/// number of internal bounces* -- their critical angles straddled a TIR threshold at
/// different points inside the stone -- the two lines have taken physically disjoint
/// paths, so `acos(dir_f . dir_c)` measures the angle between two unrelated exit
/// directions rather than true chromatic dispersion. These "bifurcated" pairs measured
/// up to 33.5 deg mean separation and up to ~27 fire-units from a single ray, and carried
/// 45-98% of the weighted Fire sum in every case where a step cut wrongly out-scored a
/// brilliant. Two earlier fix attempts (radiance-cosine weighting alone, and a saturating
/// perceptual-resolvability map on the raw angle) narrowed the distortion but could not
/// eliminate it, because neither targeted this mechanism specifically: both continued to
/// treat bifurcated pairs as if they were legitimate same-path dispersion samples, just
/// suppressed by a shrinking multiplier or a saturating cap. See prior revisions of this
/// comment (in version control) for those attempts' measured tables.
///
/// The fix, implemented in the F/C qualification gate in the main loop below: a Fire
/// pair contributes only when both `RayFate::ExitedUpward` traces report the SAME exit
/// facet index AND the same bounce count (`ExitPath::facet_idx` / `ExitPath::bounces`).
/// This mirrors the existing rule that a pair contributes nothing if F or C fails to
/// exit upward at all -- a bifurcated pair is, physically, exactly that same situation:
/// no shared exit path exists to measure a dispersion angle across. A capped-credit
/// alternative (crediting a bifurcated pair at a small fixed angle instead of discarding
/// it, since "different facets flashing different colours" is itself a fire-positive
/// perceptual event) was measured and rejected: it put Quartz above Sapphire on the
/// emerald cut at pitch 1.4, when Sapphire's true dispersion is clearly higher and
/// strict discard gets that pair right. See the F/C gate's own comment for the full
/// measured comparison.
///
/// This fix was verified against corrected step-cut geometry: `emerald_cut()` was
/// separately found to be over-constrained (11 of its 34 declared planes contributed no
/// facet to the actual solid, leaving a 23-facet solid missing most of its step
/// structure) and has since been re-derived so all 34 planes contribute
/// (`hull.untouched_planes()` is empty; see `tests/optics_geometry_tests.rs`). All Fire
/// numbers in this comment and in `tests/metrics_tests.rs` were re-measured against that
/// corrected 34-facet geometry together with the F/C bifurcation gate above.
///
/// ## Investigated and closed: Quartz vs. Topaz ordering on the emerald cut is noise, not a defect
///
/// At the single canonical pose (emerald cut, yaw=0.0, pitch=1.4, light 0.85/0.95),
/// Quartz measures a higher `fire_index` than Topaz, even though Topaz has the larger
/// F-C dispersion (`n_F - n_C`: Topaz ~0.00816 vs. Quartz ~0.00781, a Topaz/Quartz ratio
/// of only ~1.045). This was investigated empirically (grid-size and pose sweeps via a
/// throwaway example, deleted afterward) rather than "fixed" on suspicion, per this
/// module's history of failed physically-motivated Fire tuning attempts. Findings:
///
/// - Sweeping camera pitch 0.15-1.50 at the canonical yaw/light (28 poses, default
/// `grid_size` = 18): Topaz reads higher at 12 poses, Quartz at 16, with the gap swinging
/// from -2.48 to +5.45 fire-units (mean +0.21, stddev 1.71) -- a swing an order of
/// magnitude larger than the ~4.5% dispersion difference could produce on its own, and
/// with no consistent sign.
/// - Re-run with `grid_size` quadrupled to 72 (5184 rays vs. 324 per pose, before the
/// 5-point aperture bundle): the same sweep's mean gap collapsed to -0.0004 (stddev
/// 0.735) and the canonical pose itself flipped to a ~0.05-unit Topaz lead -- consistent
/// with a real signal this small being dominated by discrete-grid quantization noise at
/// the production resolution, not a systematic material-ordering bug.
/// - `DIAG_FIRE_DEBUG` at the canonical pose shows *why* the two materials are close
/// even before quantization: Quartz's raw `mean_angle_unweighted` (0.291 deg) is
/// actually slightly ABOVE Topaz's (0.286 deg) despite Topaz's higher dispersion,
/// because per-ray angular spread from refraction is not purely proportional to
/// `n_F - n_C` -- it also depends on the base index `n_d` (Topaz `n_d` ~1.627 vs.
/// Quartz ~1.544). That same higher `n_d` gives Topaz systematically lower Fresnel
/// transmittance (`mean_transmittance` 0.451 vs. Quartz's 0.509 at this pose), and Fire
/// is transmittance-weighted by design (see point 5 above) -- so Topaz's dispersion
/// edge is legitimately offset by its own index raising Fresnel losses, not just
/// swamped by noise. Both effects are real physics; neither is a defect, and together
/// they explain why "higher dispersion always wins" is not a safe assumption for two
/// materials this close (~4.5%) in `n_F - n_C`.
///
/// Conclusion: not fixed, because there is nothing here to fix -- `fire_index` is not
/// simply a resampling of `n_F - n_C`, and a materially larger gap for two materials
/// this close in true dispersion would need many more rays per pose than this metric's
/// production resolution provides to resolve reliably. If this needs to be revisited,
/// raise `grid_size` in `build_grid_eval_setup` (verified above to shrink the noise) --
/// don't retune the F/C gate or `FIRE_DEGREES_TO_DISPLAY_SCALE` against this pair, since
/// neither one is the actual source of the imprecision.
/// Camera azimuths the Tilt Performance dialog sweeps a full tilt-elevation profile at,
/// in degrees -- see [`evaluate_angular_profile_at_azimuth`].
///
/// `0.0` looks straight down whatever direction `RenderContext::yaw == 0.0` frames (for
/// a round outline this is an arbitrary reference; for an elongated one -- marquise,
/// emerald cut, pear -- it is a real, physically distinct direction, conventionally the
/// table's long axis). Each further entry rotates the viewpoint another 45° around the
/// table-normal axis, so `90.0` looks down the perpendicular ("width") axis and `45.0`/
/// `135.0` bisect the two. Tilting toward a non-round stone's long axis and tilting
/// toward its short axis window very differently, which is exactly the information a
/// single azimuth-0 sweep hides.
pub const PROFILE_AZIMUTHS_DEG: = ;
/// Calculates a 19-point angular profile of (Brilliance %, Extinction %, Windowing %)
/// at an explicit camera azimuth.
///
/// Sampled over `PoV` tilt elevation angles in exact 5° steps: [0°, 5°, 10°, 15°, 20°,
/// 25°, 30°, 35°, 40°, 45°, 50°, 55°, 60°, 65°, 70°, 75°, 80°, 85°, 90°]. `cam_yaw` is
/// in radians (matching `evaluate_gem_optical_metrics`'s own convention) -- see
/// [`PROFILE_AZIMUTHS_DEG`] for the four-azimuth convention the Tilt Performance
/// dialog's axis switcher uses. [`evaluate_angular_profile`] is just this function
/// called at `cam_yaw: 0.0`, so both share one code path.
/// Shared per-angle sampling loop behind [`evaluate_angular_profile_at_azimuth`] (called
/// with `&PROFILE_ANGLES_DEG`, 19 points / 5° steps) and
/// [`evaluate_full_axis_profile_at_azimuth`] (called with `&HALF_AXIS_PITCH_DEG`, 90
/// points / 1° steps, see that function's doc comment for why a *different* grid needs
/// its own const array rather than a finer `PROFILE_ANGLES_DEG`).
///
/// Factored out so both call sites run through the textually IDENTICAL sequence of
/// floating-point operations -- same `to_radians()`, same `evaluate_gem_optical_metrics`
/// call, same field reads in the same order -- rather than two hand-copies that could
/// silently drift apart. `evaluate_angular_profile_at_azimuth`'s own output is
/// byte-for-byte unchanged by this refactor (it was already exactly this loop body
/// before this function existed), so no existing golden/reference test needed
/// re-baselining for it.
///
/// Const-generic over the sample count `N` so one function body serves both the 19-point
/// and 90-point grids without a `Vec`-based dynamic-length version paying an allocation
/// per sweep -- this runs `N` times per axis and the whole full-axis profile runs it 4
/// times (see [`evaluate_full_axis_profile_at_azimuth`]'s cost doc comment), so keeping
/// it allocation-free matters.
/// Pitch (camera-elevation) values `0..=89` degrees, ascending -- the per-half grid
/// [`evaluate_full_axis_profile_at_azimuth`] sweeps at each of the two azimuths it
/// combines. Deliberately excludes `90.0`: pitch `90` (table-up/face-up, see that
/// function's doc comment for why it -- not pitch 0 -- is the shared point) is
/// evaluated exactly once by the caller and stitched into both halves, rather than
/// swept twice at two different azimuths only to throw one copy away. Private: nothing
/// outside this module has a legitimate reason to sample this exact grid on its own.
const
const HALF_AXIS_PITCH_DEG: = build_half_axis_pitch_deg;
const
/// 181 full-axis tilt sample points in exact 1° steps, `-90..=90` inclusive.
///
/// The VALUE is tilt AWAY FROM TABLE-UP, in degrees -- NOT camera elevation/pitch (that
/// is what [`PROFILE_ANGLES_DEG`] is). `TILT_ANGLES_DEG[90] == 0.0` is the shared
/// table-up/face-up pole (camera pitch 90°) every axis's curve passes through; `[0]`
/// and `[180]` are both edge-on/profile (camera pitch 0°), reached from the two
/// opposite azimuths of the axis pair -- see [`evaluate_full_axis_profile_at_azimuth`]'s
/// doc comment for the full geometry and the pose-to-index formula.
///
/// This is the inverse of what an earlier version of this sweep did (edge-on at the
/// centre, table-up at the ends) -- that mapping was a genuine defect, not just a
/// label: the "shared" centre point was edge-on approached from two DIFFERENT azimuths
/// (a real, physically distinct pose each side), which made the merged curve
/// discontinuous exactly where a point was supposed to be shared. Table-up, not
/// edge-on, is the one pose in this whole sweep that is actually azimuth-independent
/// (see the next function's doc comment), which is what makes sharing it correct.
///
/// # Why 1° and not 5° (measured, not a preference)
///
/// The original design for this sweep used 5° steps (37 points spanning the full axis).
/// Measuring one sample point at 1.875 ms (round brilliant / diamond, release,
/// single-threaded) made it possible to compute the TRUE 1°-resolution curve and check
/// how much error reconstructing it from coarser samples (linear interpolation between
/// measured points -- exactly what this dialog's curve and hover readout do) actually
/// costs:
///
/// | step | pts/axis | brilliance max/mean | extinction max/mean | windowing max/mean |
/// |---|---|---|---|---|
/// | 5 deg | 37 | 4.55 / 1.08 pp | 4.80 / 1.23 pp | 5.14 / 0.86 pp |
/// | 3 deg | 61 | 3.72 / 0.73 pp | 4.32 / 0.90 pp | 4.52 / 0.65 pp |
/// | 2 deg | 91 | 3.22 / 0.48 pp | 3.61 / 0.52 pp | 4.58 / 0.43 pp |
///
/// (Quartz was worse than diamond at 5°: 6.07 / 7.33 / 5.96 pp max.) There is no knee in
/// that table -- the error decays roughly linearly with step size, which means the curve
/// carries genuine high-frequency structure (individual facets flipping in and out of a
/// FIXED light as the stone tilts), not just interpolation slack that a slightly finer
/// grid would mop up. A 5-7 percentage-point error is disqualifying here specifically
/// because these curves back hard-threshold catalogue filters ("windowing never exceeds
/// 20% within ±45°"), where a few pp of reconstruction error directly flips a design in
/// or out of the result set.
///
/// 1° is also the natural ceiling rather than an arbitrary choice: the graph canvas this
/// gets drawn into is a few hundred pixels wide, so 181 points is roughly one point per
/// pixel -- sampling finer would resolve the metric's own grid-sampling noise floor
/// (`evaluate_gem_optical_metrics`'s aperture-sample grid, see that function's doc
/// comment), not new curve signal. Recorded here explicitly so nobody "improves" this to
/// 0.5° later on the assumption that finer is strictly better.
pub const TILT_ANGLES_DEG: = build_tilt_angles_deg;
/// Merges one axis's independently-swept positive-azimuth and negative-azimuth
/// (`positive_azimuth + 180°`) pitch-0..89 halves, plus the shared table-up (pitch-90)
/// pole evaluated once, into the single 181-point `TILT_ANGLES_DEG`-indexed output
/// array -- see [`evaluate_full_axis_profile_at_azimuth`]'s doc comment for the
/// geometry this implements and the tilt-to-pose formula. `positive_pitch_sweep`/
/// `negative_pitch_sweep` are each indexed by [`HALF_AXIS_PITCH_DEG`] (pitch `i` at
/// index `i`, i.e. ASCENDING pitch = DESCENDING `|tilt|`, since `pitch = 90 - |tilt|`).
/// Calculates a full-axis, 181-point angular profile spanning the ENTIRE `-90°..=+90°`
/// TILT range (tilt AWAY FROM TABLE-UP -- see [`TILT_ANGLES_DEG`]) for one axis of
/// [`PROFILE_AZIMUTHS_DEG`].
///
/// Returns (Brilliance %, Extinction %, Windowing %) at 1° resolution -- see
/// [`TILT_ANGLES_DEG`] for the sample grid and why it's 1° rather than the coarser 5°
/// [`PROFILE_ANGLES_DEG`] uses. **This is a different parameterisation of the same
/// underlying [`evaluate_gem_optical_metrics`] machinery, not a replacement for
/// [`evaluate_angular_profile_at_azimuth`]**: that function sweeps camera ELEVATION
/// (`0..=90°` of pitch, at a single fixed azimuth) and stays exactly as it is; this one
/// sweeps TILT AWAY FROM TABLE-UP (`-90..=+90°`, switching between two opposite
/// azimuths partway through). Do not "unify" the two -- they answer different
/// questions and are both independently correct for what they're each used for.
///
/// # The tilt-to-pose formula
///
/// For tilt `t` (this function's own `-90..=+90°` domain) on the axis whose positive
/// azimuth is `A = positive_azimuth_deg`:
///
/// ```text
/// cam_pitch = (90 - |t|).to_radians()
/// cam_yaw = A when t >= 0
/// A + 180 when t < 0
/// ```
///
/// `t = 0` -> `cam_pitch = 90°`: camera directly overhead, TABLE-UP. `t = ±90` ->
/// `cam_pitch = 0°`: edge-on/profile, approached from the two opposite azimuths. This
/// is the tilt-elevation relationship a "how far is this stone tilted off table-up"
/// question needs, and it is what the catalogue's own performance filters are phrased
/// against (e.g. "windowing never exceeds 20% within ±45° [of table-up]") -- under the
/// inverse mapping an earlier version of this sweep used, that same filter text would
/// have silently measured proximity to EDGE-ON instead.
///
/// # Why the negative half is a real sweep, not a mirror
///
/// [`evaluate_gem_optical_metrics`] takes a FIXED `light_yaw`/`light_pitch`. Tilting a
/// stone toward the light and tilting it away from the light give genuinely different
/// brilliance/extinction/windowing, even for a perfectly symmetric round brilliant --
/// and an asymmetric outline (pear, heart, half-moon) is not 2-fold symmetric
/// geometrically either. So `positive_azimuth_deg + 180°` below is independently
/// raytraced at every pitch, never derived by reflecting the positive half.
///
/// # Why table-up (not edge-on) is the point that's genuinely shared
///
/// `Camera::new` computes `origin = (d*cos(pitch)*sin(yaw), d*sin(pitch),
/// d*cos(pitch)*cos(yaw))`. At `pitch == 0°` (edge-on), `cos(pitch) == 1`, so `origin`
/// depends on `yaw` -- the two azimuths genuinely put the camera in two different
/// places. At `pitch == 90°` (table-up), `cos(pitch) ≈ 0`, so `origin ≈ (0, d, 0)` for
/// EVERY yaw -- one single pose. `Camera::new` also switches its `world_up` fallback
/// exactly where `cos(pitch).abs() < 1e-4` (i.e. right at this pole), which is what
/// keeps `right`/`up` from spinning with `yaw` there too -- `right` resolves to
/// `(1, 0, 0)` regardless of azimuth at the pole, confirmed against `Camera::new`'s own
/// formula. Table-up is therefore the one pose in this entire sweep that is actually
/// independent of which of the two azimuths it's evaluated at, which is what makes
/// evaluating it once and sharing it between both halves correct rather than merely
/// convenient. (An earlier version of this function shared the EDGE-ON point instead,
/// which does not have this property -- see [`TILT_ANGLES_DEG`]'s doc comment for why
/// that was a genuine bug, not just a mislabelled axis: it made the merged curve
/// discontinuous exactly at the point that was supposed to be shared.)
///
/// Net cost: `90 + 1 + 90 = 181` raytrace evaluations per axis (not 182 -- the shared
/// table-up point is genuinely evaluated once), matching [`TILT_ANGLES_DEG`]'s own
/// "181 x 4 x 1.875 ms" cost accounting used to justify the 1° step size.
///
/// `PROFILE_AZIMUTHS_DEG[k]` is the caller's own convention for this axis's canonical
/// (positive) azimuth; `positive_azimuth_deg + 180.0` is the negative half's azimuth --
/// callers do not need to compute or pass that second azimuth themselves.
/// Calculates a 19-point angular profile of (Brilliance %, Extinction %, Windowing %)
/// at the canonical (0°) camera azimuth.
///
/// See [`evaluate_angular_profile_at_azimuth`] for the general form this delegates to,
/// and [`PROFILE_AZIMUTHS_DEG`] for what the other three azimuths mean. Sampled over
/// `PoV` tilt elevation angles in exact 5° steps: [0°, 5°, 10°, 15°, 20°, 25°, 30°,
/// 35°, 40°, 45°, 50°, 55°, 60°, 65°, 70°, 75°, 80°, 85°, 90°].