viewport-lib 0.1.0

3D viewport rendering library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
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
//! `ViewportRenderer` — the main entry point for the viewport library.
//!
//! Wraps [`ViewportGpuResources`] and provides `prepare()` / `paint()` methods
//! that take raw `wgpu` types. GUI framework adapters (e.g. the egui
//! `CallbackTrait` impl in the application crate) delegate to these methods.

use crate::interaction::gizmo::{GizmoAxis, GizmoMode};
use crate::scene::material::Material;
use crate::resources::{CameraUniform, ColormapId};
use crate::interaction::snap::ConstraintOverlay;

/// Minimum scene item count to activate the instanced draw path.
/// Use instancing for any scene with more than 1 object. The per-object path
/// writes uniforms into a per-mesh buffer, so two scene nodes sharing the same
/// mesh would clobber each other. Instancing avoids this by keeping per-item
/// data in a separate instance buffer indexed by draw-call range.
pub(super) const INSTANCING_THRESHOLD: usize = 1;

/// A batch of instances sharing the same mesh and material textures, drawn in one call.
#[derive(Debug, Clone)]
pub(crate) struct InstancedBatch {
    pub mesh_index: usize,
    pub texture_id: Option<u64>,
    pub normal_map_id: Option<u64>,
    pub ao_map_id: Option<u64>,
    pub instance_offset: u32,
    pub instance_count: u32,
    pub is_transparent: bool,
}

// ---------------------------------------------------------------------------
// Section view / clip plane / clip volume
// ---------------------------------------------------------------------------

/// A world-space half-space clipping plane for section views.
///
/// A fragment at world position `p` is discarded if `dot(p, normal) + distance < 0`.
#[derive(Clone, Copy, Debug)]
pub struct ClipPlane {
    /// Unit normal of the clip plane (pointing into the preserved half-space).
    pub normal: [f32; 3],
    /// Signed distance from the origin along `normal`.
    pub distance: f32,
    /// Whether this plane is active. Inactive planes are ignored.
    pub enabled: bool,
    /// Cap fill color override. `None` = use the clipped object's material base_color.
    pub cap_color: Option<[f32; 4]>,
}

/// A volumetric clip region applied as an additional clipping test on top of any
/// existing [`ClipPlane`]s.  Fragments outside the volume are discarded.
///
/// The default value is [`ClipVolume::None`] which adds zero overhead.
///
/// This is a separate, independent mechanism from the half-space `clip_planes`
/// field on [`FrameData`].  When both are active a fragment must pass **both**
/// the clip-plane loop **and** the clip-volume test.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ClipVolume {
    /// No clip volume — all fragments pass (default, zero GPU overhead).
    None,
    /// Half-space plane: `dot(p, normal) + distance >= 0` is the kept region.
    ///
    /// This reproduces the existing `ClipPlane` behavior at the single-volume
    /// level and is useful when a caller wants to express both the plane and
    /// box/sphere regions through the same uniform path.
    Plane {
        /// Unit normal pointing into the preserved half-space.
        normal: [f32; 3],
        /// Signed distance from the origin along `normal`.
        distance: f32,
    },
    /// Axis-aligned or oriented box region: fragments inside the box are kept.
    ///
    /// `orientation` is a 3×3 rotation matrix stored as three column vectors
    /// (each `[f32; 3]`).  For an axis-aligned box use the identity.
    Box {
        /// Box center in world space.
        center: [f32; 3],
        /// Half-extents (per-axis radius) of the box.
        half_extents: [f32; 3],
        /// Rotation matrix columns: `orientation[0]` = local X axis in world
        /// space, `orientation[1]` = local Y, `orientation[2]` = local Z.
        orientation: [[f32; 3]; 3],
    },
    /// Sphere region: fragments inside the sphere are kept.
    Sphere {
        /// Sphere center in world space.
        center: [f32; 3],
        /// Sphere radius in world units.
        radius: f32,
    },
}

impl Default for ClipVolume {
    fn default() -> Self {
        ClipVolume::None
    }
}

// ---------------------------------------------------------------------------
// Post-processing settings
// ---------------------------------------------------------------------------

/// Tone mapping operator applied when HDR post-processing is enabled.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ToneMapping {
    /// Reinhard tone mapping (simple, good for scenes without extreme HDR).
    Reinhard,
    /// ACES filmic tone mapping (cinematic look, recommended).
    #[default]
    Aces,
    /// Khronos Neutral tone mapping (perceptually uniform).
    KhronosNeutral,
}

/// Optional post-processing effects applied after the main render pass.
///
/// All fields default to disabled/off for backward compatibility.
#[derive(Clone, Debug)]
pub struct PostProcessSettings {
    /// Enable the HDR render target and tone mapping pipeline.
    /// When `false`, the viewport renders directly to the output surface (LDR).
    pub enabled: bool,
    /// Tone mapping operator. Default: `Aces`.
    pub tone_mapping: ToneMapping,
    /// Pre-tone-mapping exposure multiplier. Default: `1.0`.
    pub exposure: f32,
    /// Enable screen-space ambient occlusion. Requires `enabled = true`.
    pub ssao: bool,
    /// Enable bloom. Requires `enabled = true`.
    pub bloom: bool,
    /// HDR luminance threshold for bloom extraction. Default: `1.0`.
    pub bloom_threshold: f32,
    /// Bloom contribution multiplier. Default: `0.1`.
    pub bloom_intensity: f32,
    /// Enable FXAA (Fast Approximate Anti-Aliasing) fullscreen pass. Requires `enabled = true`.
    pub fxaa: bool,
    /// Enable screen-space contact shadows (thin shadows at object-ground contact). Requires `enabled = true`.
    pub contact_shadows: bool,
    /// Maximum ray-march distance in view space. Default: 0.5.
    pub contact_shadow_max_distance: f32,
    /// Number of ray-march steps. Default: 16.
    pub contact_shadow_steps: u32,
    /// Depth thickness threshold for occlusion test. Default: 0.1.
    pub contact_shadow_thickness: f32,
}

impl Default for PostProcessSettings {
    fn default() -> Self {
        Self {
            enabled: false,
            tone_mapping: ToneMapping::Aces,
            exposure: 1.0,
            ssao: false,
            bloom: false,
            bloom_threshold: 1.0,
            bloom_intensity: 0.1,
            fxaa: false,
            contact_shadows: false,
            contact_shadow_max_distance: 0.5,
            contact_shadow_steps: 16,
            contact_shadow_thickness: 0.1,
        }
    }
}

// ---------------------------------------------------------------------------
// Lighting configuration types
// ---------------------------------------------------------------------------

/// Light source type.
///
/// `Directional` emits parallel rays from a fixed direction (infinite distance).
/// `Point` emits rays from a position with distance-based falloff.
/// `Spot` emits a cone of light with inner (full-intensity) and outer (cutoff) angles.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub enum LightKind {
    /// Infinitely distant light with parallel rays (e.g. the sun).
    Directional {
        /// World-space direction the light travels toward (not the source direction).
        direction: [f32; 3],
    },
    /// Omnidirectional point light with distance falloff.
    Point {
        /// World-space position of the light source.
        position: [f32; 3],
        /// Maximum range (world units) beyond which the light contributes nothing.
        range: f32,
    },
    /// Cone-shaped spotlight.
    Spot {
        /// World-space position of the light source.
        position: [f32; 3],
        /// World-space direction the cone points toward.
        direction: [f32; 3],
        /// Maximum range (world units).
        range: f32,
        /// Inner cone half-angle (radians) — full intensity within this cone.
        inner_angle: f32,
        /// Outer cone half-angle (radians) — light fades to zero at this angle.
        outer_angle: f32,
    },
}

/// A single light source with color and intensity.
#[derive(Clone, Debug)]
pub struct LightSource {
    /// The type and geometric parameters of this light.
    pub kind: LightKind,
    /// RGB light color in linear 0..1. Default [1.0, 1.0, 1.0].
    pub color: [f32; 3],
    /// Intensity multiplier. Default 1.0.
    pub intensity: f32,
}

impl Default for LightSource {
    fn default() -> Self {
        Self {
            kind: LightKind::Directional {
                direction: [0.3, 1.0, 0.5],
            },
            color: [1.0, 1.0, 1.0],
            intensity: 1.0,
        }
    }
}

/// Shadow filtering mode.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ShadowFilter {
    /// Standard 3×3 PCF (fast).
    #[default]
    Pcf,
    /// Percentage-Closer Soft Shadows (variable penumbra width, higher cost).
    Pcss,
}

/// Per-frame lighting configuration for the viewport.
///
/// Supports up to 8 light sources. Only `lights[0]` casts shadows.
/// Blinn-Phong shading coefficients (ambient, diffuse, specular, shininess) have
/// moved to per-object [`Material`] structs.
#[derive(Clone, Debug)]
pub struct LightingSettings {
    /// Active light sources (max 8). Default: one directional light.
    pub lights: Vec<LightSource>,
    /// Shadow map depth bias to reduce shadow acne. Default: 0.0001.
    pub shadow_bias: f32,
    /// Whether shadow maps are computed and sampled. Default: true.
    pub shadows_enabled: bool,
    /// Sky color for hemisphere ambient. Default [0.8, 0.9, 1.0].
    pub sky_color: [f32; 3],
    /// Ground color for hemisphere ambient. Default [0.3, 0.2, 0.1].
    pub ground_color: [f32; 3],
    /// Hemisphere ambient intensity. 0.0 = disabled. Default 0.0.
    pub hemisphere_intensity: f32,
    /// Override the shadow frustum half-extent (world units). None = auto (20.0 or from domain_extents).
    /// Tighter values improve shadow map texel density and reduce contact-shadow penumbra.
    pub shadow_extent_override: Option<f32>,

    /// Number of cascaded shadow map splits (1–4). Default: 4.
    pub shadow_cascade_count: u32,
    /// Blend factor between logarithmic and linear cascade splits (0.0 = linear, 1.0 = log).
    /// Default: 0.75. Higher values allocate more resolution near the camera.
    pub cascade_split_lambda: f32,
    /// Shadow atlas resolution (width = height). Default: 4096.
    /// Each cascade tile is `atlas_resolution / 2`.
    pub shadow_atlas_resolution: u32,
    /// Shadow filtering mode. Default: PCF.
    pub shadow_filter: ShadowFilter,
    /// PCSS light source radius in shadow-map UV space. Controls penumbra width. Default: 0.02.
    pub pcss_light_radius: f32,
}

impl Default for LightingSettings {
    fn default() -> Self {
        Self {
            lights: vec![LightSource::default()],
            shadow_bias: 0.0001,
            shadows_enabled: true,
            sky_color: [0.8, 0.9, 1.0],
            ground_color: [0.3, 0.2, 0.1],
            hemisphere_intensity: 0.0,
            shadow_extent_override: None,
            shadow_cascade_count: 4,
            cascade_split_lambda: 0.75,
            shadow_atlas_resolution: 4096,
            shadow_filter: ShadowFilter::Pcf,
            pcss_light_radius: 0.02,
        }
    }
}

// ---------------------------------------------------------------------------
// Per-frame data types
// ---------------------------------------------------------------------------

/// Per-object render data for one frame.
#[derive(Clone)]
#[non_exhaustive]
pub struct SceneRenderItem {
    /// Index into `ViewportGpuResources::meshes` for this object's GPU buffers.
    pub mesh_index: usize,
    /// World-space model matrix (Translation * Rotation * Scale).
    pub model: [[f32; 4]; 4],
    /// Whether this object is selected (drives orange tint in WGSL).
    pub selected: bool,
    /// Whether this object is visible. Hidden objects are not drawn.
    pub visible: bool,
    /// Whether to render per-vertex normal visualization lines for this object.
    pub show_normals: bool,
    /// Per-object material (color, shading coefficients, opacity, texture).
    pub material: Material,
    /// Named scalar attribute to colour by. `None` = use material base colour.
    pub active_attribute: Option<crate::resources::AttributeRef>,
    /// Explicit scalar range `(min, max)`. `None` = use auto-range computed at upload time.
    pub scalar_range: Option<(f32, f32)>,
    /// Colormap to use for scalar colouring. Ignored when `active_attribute` is `None`.
    pub colormap_id: Option<crate::resources::ColormapId>,
    /// RGBA color for NaN scalar values. `None` = discard (fully transparent).
    pub nan_color: Option<[f32; 4]>,
    /// Render this mesh with no back-face culling (visible from both sides).
    ///
    /// Set this for analytical surfaces (plots, CFD isosurfaces) that the camera
    /// can orbit under. Opaque geometry with this flag uses the
    /// `solid_two_sided_pipeline` instead of `solid_pipeline`.
    pub two_sided: bool,
}

impl Default for SceneRenderItem {
    fn default() -> Self {
        Self {
            mesh_index: 0,
            model: glam::Mat4::IDENTITY.to_cols_array_2d(),
            selected: false,
            visible: true,
            show_normals: false,
            material: Material::default(),
            active_attribute: None,
            scalar_range: None,
            colormap_id: None,
            nan_color: None,
            two_sided: false,
        }
    }
}

/// Scalar bar (colour legend) overlay descriptor.
///
/// Not part of `FrameData` — the application draws scalar bars after `show_viewport()`
/// returns, using `egui::Painter` and the colormap data from
/// [`ViewportGpuResources::get_colormap_rgba`](crate::resources::ViewportGpuResources::get_colormap_rgba).
#[derive(Debug, Clone)]
pub struct ScalarBar {
    /// Colormap to display.
    pub colormap_id: crate::resources::ColormapId,
    /// Scalar value at the low end of the gradient.
    pub scalar_min: f32,
    /// Scalar value at the high end of the gradient.
    pub scalar_max: f32,
    /// Title label shown above the bar.
    pub title: String,
    /// Corner of the viewport rect to anchor the bar to.
    pub anchor: ScalarBarAnchor,
    /// Whether to draw the bar vertically or horizontally.
    pub orientation: ScalarBarOrientation,
}

/// Anchor corner for a [`ScalarBar`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScalarBarAnchor {
    /// Top-left corner of the viewport.
    TopLeft,
    /// Top-right corner of the viewport.
    TopRight,
    /// Bottom-left corner of the viewport.
    BottomLeft,
    /// Bottom-right corner of the viewport.
    BottomRight,
}

/// Orientation of a [`ScalarBar`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScalarBarOrientation {
    /// Gradient runs from bottom (min) to top (max).
    Vertical,
    /// Gradient runs from left (min) to right (max).
    Horizontal,
}

/// Generic overlay quad: pre-computed corners + RGBA color.
pub struct OverlayQuad {
    /// Four corner positions in world space (CCW winding when viewed from outside).
    pub corners: [[f32; 3]; 4],
    /// RGBA color (alpha for semi-transparency).
    pub color: [f32; 4],
}

// ---------------------------------------------------------------------------
// SciVis Phase B — point cloud and glyph renderers
// ---------------------------------------------------------------------------

/// Render mode for point cloud items.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PointRenderMode {
    /// GPU point primitives with `point_size` uniform (fastest, no shading).
    #[default]
    ScreenSpaceCircle,
    // Future: BillboardQuad, FixedSphere
}

/// A point cloud item to render in the viewport.
#[non_exhaustive]
pub struct PointCloudItem {
    /// World-space positions (one vec3 per point).
    pub positions: Vec<[f32; 3]>,
    /// Optional per-point RGBA colors in linear `[0,1]`. If empty, uses `default_color`.
    pub colors: Vec<[f32; 4]>,
    /// Optional per-point scalar values for LUT coloring. If non-empty, overrides `colors`.
    pub scalars: Vec<f32>,
    /// Scalar range for LUT mapping. None = auto from min/max of `scalars`.
    pub scalar_range: Option<(f32, f32)>,
    /// Colormap for scalar coloring. None = use default builtin (viridis).
    pub colormap_id: Option<ColormapId>,
    /// Screen-space point size in pixels. Default: 4.0.
    pub point_size: f32,
    /// Fallback color when neither `colors` nor `scalars` are provided.
    pub default_color: [f32; 4],
    /// World-space model matrix. Default: identity.
    pub model: [[f32; 4]; 4],
    /// Render mode. Default: ScreenSpaceCircle.
    pub render_mode: PointRenderMode,
    /// Unique ID for picking. 0 = not pickable.
    pub id: u64,
}

impl Default for PointCloudItem {
    fn default() -> Self {
        Self {
            positions: Vec::new(),
            colors: Vec::new(),
            scalars: Vec::new(),
            scalar_range: None,
            colormap_id: None,
            point_size: 4.0,
            default_color: [1.0, 1.0, 1.0, 1.0],
            model: glam::Mat4::IDENTITY.to_cols_array_2d(),
            render_mode: PointRenderMode::ScreenSpaceCircle,
            id: 0,
        }
    }
}

/// Glyph shape type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum GlyphType {
    /// Cone tip + cylinder shaft.
    #[default]
    Arrow,
    /// Icosphere.
    Sphere,
    /// Unit cube.
    Cube,
}

/// A set of instanced glyphs to render (e.g. velocity arrows).
#[non_exhaustive]
pub struct GlyphItem {
    /// World-space base positions (one per glyph instance).
    pub positions: Vec<[f32; 3]>,
    /// Per-instance direction vectors. Length = magnitude (used for orientation + optional scale).
    pub vectors: Vec<[f32; 3]>,
    /// Global scale factor applied to all glyph instances. Default: 1.0.
    pub scale: f32,
    /// Whether glyph size scales with vector magnitude. Default: true.
    pub scale_by_magnitude: bool,
    /// Clamp magnitude range for scaling. None = no clamping.
    pub magnitude_clamp: Option<(f32, f32)>,
    /// Optional per-instance scalar values for LUT coloring. Empty = color by magnitude.
    pub scalars: Vec<f32>,
    /// Scalar range for LUT mapping. None = auto from data.
    pub scalar_range: Option<(f32, f32)>,
    /// Colormap for scalar coloring. None = use default builtin (viridis).
    pub colormap_id: Option<ColormapId>,
    /// Glyph shape. Default: Arrow.
    pub glyph_type: GlyphType,
    /// World-space model matrix. Default: identity.
    pub model: [[f32; 4]; 4],
    /// Unique ID for picking. 0 = not pickable.
    pub id: u64,
}

impl Default for GlyphItem {
    fn default() -> Self {
        Self {
            positions: Vec::new(),
            vectors: Vec::new(),
            scale: 1.0,
            scale_by_magnitude: true,
            magnitude_clamp: None,
            scalars: Vec::new(),
            scalar_range: None,
            colormap_id: None,
            glyph_type: GlyphType::Arrow,
            model: glam::Mat4::IDENTITY.to_cols_array_2d(),
            id: 0,
        }
    }
}

/// A volume item to render via GPU ray-marching.
///
/// The caller uploads a 3D scalar field via [`ViewportGpuResources::upload_volume`](crate::resources::ViewportGpuResources::upload_volume) and
/// receives a [`VolumeId`](crate::resources::VolumeId). Each frame, submit a `VolumeItem` referencing that id plus
/// transfer function and display parameters.
#[non_exhaustive]
pub struct VolumeItem {
    /// Reference to a previously uploaded 3D texture.
    pub volume_id: crate::resources::VolumeId,
    /// Color transfer function LUT. `None` = use default builtin (viridis).
    pub color_lut: Option<ColormapId>,
    /// Opacity transfer function LUT. `None` = linear ramp (0 at min, 1 at max).
    pub opacity_lut: Option<ColormapId>,
    /// Scalar range for normalization [min, max].
    pub scalar_range: (f32, f32),
    /// World-space bounding box minimum corner.
    pub bbox_min: [f32; 3],
    /// World-space bounding box maximum corner.
    pub bbox_max: [f32; 3],
    /// Ray step multiplier. Lower = higher quality, slower. Default: 1.0.
    pub step_scale: f32,
    /// World-space transform. Default: identity.
    pub model: [[f32; 4]; 4],
    /// Whether to apply gradient-based Phong shading. Default: false.
    pub enable_shading: bool,
    /// Global opacity multiplier. Default: 1.0.
    pub opacity_scale: f32,
    /// Scalar threshold range [min, max]. Samples outside this range are discarded (opacity = 0).
    /// Default: same as scalar_range (no clipping).
    pub threshold_min: f32,
    /// Upper scalar threshold. Samples above this value are discarded.
    /// Default: same as scalar_range.1 (no clipping).
    pub threshold_max: f32,
    /// Color and opacity to use for NaN scalar samples. `None` = skip NaN samples entirely
    /// (same as current behaviour: discard). `Some([r, g, b, a])` = render NaN voxels with
    /// this fixed RGBA color instead of sampling the transfer function.
    pub nan_color: Option<[f32; 4]>,
}

impl Default for VolumeItem {
    fn default() -> Self {
        Self {
            volume_id: crate::resources::VolumeId(0),
            color_lut: None,
            opacity_lut: None,
            scalar_range: (0.0, 1.0),
            bbox_min: [0.0, 0.0, 0.0],
            bbox_max: [1.0, 1.0, 1.0],
            step_scale: 1.0,
            model: glam::Mat4::IDENTITY.to_cols_array_2d(),
            enable_shading: false,
            opacity_scale: 1.0,
            threshold_min: 0.0,
            threshold_max: 1.0,
            nan_color: None,
        }
    }
}

/// A polyline (stream tracer) item to render in the viewport.
///
/// All streamlines for one source are concatenated into a single vertex buffer.
/// `strip_lengths` records how many vertices belong to each individual streamline.
#[non_exhaustive]
pub struct PolylineItem {
    /// World-space positions for all streamlines, concatenated.
    pub positions: Vec<[f32; 3]>,
    /// Per-vertex scalar values (same length as `positions`). Empty = no scalar coloring.
    pub scalars: Vec<f32>,
    /// Number of vertices per individual streamline strip.
    pub strip_lengths: Vec<u32>,
    /// Scalar range for LUT mapping. None = auto from min/max of `scalars`.
    pub scalar_range: Option<(f32, f32)>,
    /// Colormap for scalar coloring. None = viridis.
    pub colormap_id: Option<ColormapId>,
    /// Fallback color when `scalars` is empty.
    pub default_color: [f32; 4],
    /// Hardware line width in pixels (may be clamped to 1 by some GPU drivers).
    pub line_width: f32,
    /// Unique ID for identification. 0 = not pickable.
    pub id: u64,
}

impl Default for PolylineItem {
    fn default() -> Self {
        Self {
            positions: Vec::new(),
            scalars: Vec::new(),
            strip_lengths: Vec::new(),
            scalar_range: None,
            colormap_id: None,
            default_color: [0.9, 0.92, 0.96, 1.0],
            line_width: 2.0,
            id: 0,
        }
    }
}

// ---------------------------------------------------------------------------
// SciVis Phase M — streamtube renderer
// ---------------------------------------------------------------------------

/// A streamtube item: polyline strips rendered as instanced 3D cylinder segments.
///
/// Each consecutive pair of positions within a strip becomes one cylinder instance,
/// oriented along the segment direction, scaled to the configured radius.  The
/// cylinder mesh is an 8-sided built-in uploaded once at pipeline creation time.
///
/// `StreamtubeItem` is `#[non_exhaustive]` so future fields (e.g. per-point radius
/// from a scalar attribute) can be added without breaking existing callers.
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct StreamtubeItem {
    /// World-space positions for all strips, concatenated.
    pub positions: Vec<[f32; 3]>,
    /// Number of vertices per individual strip.
    pub strip_lengths: Vec<u32>,
    /// Tube radius in world-space units.  Default: `0.05`.
    pub radius: f32,
    /// RGBA colour for all tube segments in this item.  Default: opaque white.
    pub color: [f32; 4],
    /// Unique ID (reserved for future picking support).  Default: `0`.
    pub id: u64,
}

impl Default for StreamtubeItem {
    fn default() -> Self {
        Self {
            positions: Vec::new(),
            strip_lengths: Vec::new(),
            radius: 0.05,
            color: [1.0, 1.0, 1.0, 1.0],
            id: 0,
        }
    }
}

// ---------------------------------------------------------------------------
// Phase G — GPU compute filter types
// ---------------------------------------------------------------------------

/// Whether a filter runs on CPU or GPU compute shader.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FilterMode {
    /// CPU-side index compaction (existing path, always works).
    #[default]
    Cpu,
    /// GPU compute shader index compaction (faster for large meshes).
    Gpu,
}

/// Kind of GPU compute filter operation.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ComputeFilterKind {
    /// Clip: discard triangles where all 3 vertices are on the negative side of a plane.
    /// Plane defined as (normal.xyz, distance) where dot(pos, normal) < distance => clipped.
    Clip {
        /// Unit normal of the clip plane.
        plane_normal: [f32; 3],
        /// Signed distance from origin along the plane normal.
        plane_dist: f32,
    },
    /// Box clip: discard triangles where all 3 vertices are outside an oriented box region.
    ClipBox {
        /// Box center in world space.
        center: [f32; 3],
        /// Half-extents (per-axis radius) of the box.
        half_extents: [f32; 3],
        /// Rotation matrix columns: local X, Y, Z axes in world space.
        orientation: [[f32; 3]; 3],
    },
    /// Sphere clip: discard triangles where all 3 vertices are outside a sphere region.
    ClipSphere {
        /// Sphere center in world space.
        center: [f32; 3],
        /// Sphere radius in world units.
        radius: f32,
    },
    /// Threshold: discard triangles where all 3 vertex scalars are outside [min, max].
    Threshold {
        /// Minimum scalar value (inclusive).
        min: f32,
        /// Maximum scalar value (inclusive).
        max: f32,
    },
}

/// A GPU compute filter item — references an existing uploaded mesh.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ComputeFilterItem {
    /// Index into `ViewportGpuResources` mesh store.
    pub mesh_index: usize,
    /// Which filter to apply.
    pub kind: ComputeFilterKind,
    /// Name of the scalar attribute buffer (for Threshold). Ignored for Clip.
    pub attribute_name: Option<String>,
}

impl Default for ComputeFilterItem {
    fn default() -> Self {
        Self {
            mesh_index: 0,
            kind: ComputeFilterKind::Clip {
                plane_normal: [0.0, 0.0, 1.0],
                plane_dist: 0.0,
            },
            attribute_name: None,
        }
    }
}

/// All data needed to render one frame of the viewport.
#[non_exhaustive]
pub struct FrameData {
    /// Per-frame camera uniform (view-proj matrix, eye position).
    pub camera_uniform: CameraUniform,
    /// Per-frame lighting configuration.
    pub lighting: LightingSettings,
    /// Camera eye position in world space (for Blinn-Phong specular lighting).
    pub eye_pos: [f32; 3],
    /// Per-object render items.
    pub scene_items: Vec<SceneRenderItem>,
    /// Whether to render in wireframe mode.
    pub wireframe_mode: bool,
    /// Gizmo model matrix (Some = selected object exists and gizmo should render).
    pub gizmo_model: Option<glam::Mat4>,
    /// Current gizmo interaction mode.
    pub gizmo_mode: GizmoMode,
    /// Current hovered gizmo axis.
    pub gizmo_hovered: GizmoAxis,
    /// Orientation for gizmo space (identity for world, object orientation for local).
    pub gizmo_space_orientation: glam::Quat,
    /// Domain extents for wireframe rendering. None if domain has zero extents.
    pub domain_extents: Option<[f32; 3]>,
    /// Overlay quads to render this frame.
    pub overlay_quads: Vec<OverlayQuad>,
    /// Constraint guide lines to render this frame.
    pub constraint_overlays: Vec<ConstraintOverlay>,
    /// Whether to render the ground-plane grid.
    pub show_grid: bool,
    /// Grid cell size in world units. Zero means use domain_extents-derived spacing.
    pub grid_cell_size: f32,
    /// Half-extent of the grid in world units (grid spans ±grid_half_extent). Zero = use domain_extents.
    pub grid_half_extent: f32,
    /// Whether to draw the 2D axes orientation indicator overlay.
    /// Defaults to `true`.
    pub show_axes_indicator: bool,
    /// Whether the simulation is 2D (affects grid plane orientation).
    pub is_2d: bool,
    /// Viewport size in physical pixels (width, height). Required for axes indicator.
    pub viewport_size: [f32; 2],
    /// Camera orientation quaternion (used for axes indicator projection).
    pub camera_orientation: glam::Quat,
    /// Optional background/clear color [r, g, b, a]. Adapters can use this as the
    /// render pass clear color. None = let the adapter choose its default.
    pub background_color: Option<[f32; 4]>,

    // -----------------------------------------------------------------------
    // Phase 6 additions (all opt-in; defaults preserve Phase 1–5 behavior)
    // -----------------------------------------------------------------------
    /// Active section-view clip planes. Max 6. Default: empty (no clipping).
    pub clip_planes: Vec<ClipPlane>,

    /// Whether to render filled caps at clip plane cross-sections. Default: `true`.
    pub cap_fill_enabled: bool,

    /// Draw a stencil-outline ring around selected objects. Default: `false`.
    pub outline_selected: bool,
    /// RGBA color of the selection outline ring. Default: orange `[1.0, 0.5, 0.0, 1.0]`.
    pub outline_color: [f32; 4],
    /// Width of the outline ring in pixels. Default: `2.0`.
    pub outline_width_px: f32,

    /// Render selected objects as a semi-transparent x-ray overlay. Default: `false`.
    pub xray_selected: bool,
    /// RGBA color of the x-ray tint (should have alpha < 1). Default: `[0.3, 0.7, 1.0, 0.25]`.
    pub xray_color: [f32; 4],

    /// Optional post-processing settings. Default: disabled.
    pub post_process: PostProcessSettings,

    /// Projection matrix (without view). Required for correct SSAO view-space reconstruction.
    /// Defaults to identity; set this when `post_process.ssao` is true.
    pub camera_proj: glam::Mat4,

    /// Camera view matrix (world → view). Required for CSM cascade computation.
    /// Defaults to identity; set this when using cascaded shadow maps.
    pub camera_view: glam::Mat4,
    /// Camera near clip plane. Default: 0.1.
    pub camera_near: f32,
    /// Camera far clip plane. Default: 1000.0.
    pub camera_far: f32,
    /// Camera vertical field of view in radians. Default: PI/4.
    pub camera_fov: f32,
    /// Camera aspect ratio (width / height). Default: 1.333.
    pub camera_aspect: f32,

    // -----------------------------------------------------------------------
    // Phase 6.6 additions — generation-based cache invalidation
    // -----------------------------------------------------------------------
    /// Scene version counter from `Scene::version()`. Used by the renderer to
    /// skip batch rebuild and GPU upload when the scene has not changed.
    /// Default: 0 (triggers rebuild on first frame).
    pub scene_generation: u64,

    /// Selection version counter from `Selection::version()`. Used by the renderer
    /// to skip batch rebuild when the selection has not changed.
    /// Default: 0 (triggers rebuild on first frame).
    pub selection_generation: u64,

    // -----------------------------------------------------------------------
    // SciVis Phase B — point cloud and glyph renderers
    // -----------------------------------------------------------------------
    /// Point cloud items to render this frame. Default: empty (zero-cost skip).
    pub point_clouds: Vec<PointCloudItem>,
    /// Instanced glyph items to render this frame. Default: empty (zero-cost skip).
    pub glyphs: Vec<GlyphItem>,

    // -----------------------------------------------------------------------
    // SciVis Phase M8 — polyline (stream tracer) renderer
    // -----------------------------------------------------------------------
    /// Polyline (streamline) items to render this frame. Default: empty (zero-cost skip).
    pub polylines: Vec<PolylineItem>,

    // -----------------------------------------------------------------------
    // SciVis Phase D -- volume rendering
    // -----------------------------------------------------------------------
    /// Volume items to render this frame via GPU ray-marching. Default: empty (zero-cost skip).
    pub volumes: Vec<VolumeItem>,

    // -----------------------------------------------------------------------
    // Multi-viewport support
    // -----------------------------------------------------------------------
    /// Which viewport slot this frame data belongs to (0-based).
    ///
    /// In single-viewport mode this is always 0.  In multi-viewport mode each
    /// sub-viewport sets a distinct index so the renderer can maintain
    /// independent per-viewport camera buffers and bind groups.  The renderer
    /// grows its internal per-viewport storage automatically as new indices are
    /// seen.  Default: `0`.
    pub viewport_index: usize,

    // -----------------------------------------------------------------------
    // Phase G — GPU compute filtering
    // -----------------------------------------------------------------------
    /// GPU compute filter items dispatched before the render pass.
    ///
    /// Default: empty — the compute pass is completely skipped (zero overhead).
    /// Each item references an uploaded mesh by index and specifies a Clip or
    /// Threshold filter. The renderer replaces the mesh's index buffer with the
    /// compacted output during `paint()`.
    pub compute_filter_items: Vec<ComputeFilterItem>,

    // -----------------------------------------------------------------------
    // SciVis Phase L — isoline / contour line renderer
    // -----------------------------------------------------------------------
    /// Isoline (contour line) items to render on mesh surfaces.
    ///
    /// Default: empty — zero overhead when no isolines are requested.
    /// Each [`crate::geometry::isoline::IsolineItem`] carries its own mesh geometry,
    /// per-vertex scalars, and a list of isovalues.  The renderer extracts
    /// the segments on the CPU and uploads them through the existing polyline
    /// pipeline (no new GPU pipeline or shader required).
    pub isoline_items: Vec<crate::geometry::isoline::IsolineItem>,

    // -----------------------------------------------------------------------
    // SciVis Phase M — streamtube renderer
    // -----------------------------------------------------------------------
    /// Streamtube items to render this frame.
    ///
    /// Default: empty — zero overhead when unused.  Each [`StreamtubeItem`]
    /// is converted to instanced cylinder segments during `prepare()`.
    pub streamtube_items: Vec<StreamtubeItem>,

    // -----------------------------------------------------------------------
    // SciVis Phase N — extended clip volumes
    // -----------------------------------------------------------------------
    /// Optional volumetric clip region.  Fragments outside the volume are discarded,
    /// in addition to any [`clip_planes`](Self::clip_planes) already active.
    ///
    /// Default: [`ClipVolume::None`] — zero GPU overhead.
    pub clip_volume: ClipVolume,
}

impl Default for FrameData {
    fn default() -> Self {
        Self {
            camera_uniform: CameraUniform {
                view_proj: glam::Mat4::IDENTITY.to_cols_array_2d(),
                eye_pos: [0.0, 0.0, 5.0],
                _pad: 0.0,
            },
            lighting: LightingSettings::default(),
            eye_pos: [0.0, 0.0, 5.0],
            scene_items: Vec::new(),
            wireframe_mode: false,
            gizmo_model: None,
            gizmo_mode: GizmoMode::Translate,
            gizmo_hovered: GizmoAxis::None,
            gizmo_space_orientation: glam::Quat::IDENTITY,
            domain_extents: None,
            overlay_quads: Vec::new(),
            constraint_overlays: Vec::new(),
            show_grid: false,
            grid_cell_size: 0.0,
            grid_half_extent: 0.0,
            show_axes_indicator: true,
            is_2d: false,
            viewport_size: [800.0, 600.0],
            camera_orientation: glam::Quat::IDENTITY,
            background_color: None,
            clip_planes: Vec::new(),
            cap_fill_enabled: true,
            outline_selected: false,
            outline_color: [1.0, 0.5, 0.0, 1.0],
            outline_width_px: 2.0,
            xray_selected: false,
            xray_color: [0.3, 0.7, 1.0, 0.25],
            post_process: PostProcessSettings::default(),
            camera_proj: glam::Mat4::IDENTITY,
            camera_view: glam::Mat4::IDENTITY,
            camera_near: 0.1,
            camera_far: 1000.0,
            camera_fov: std::f32::consts::FRAC_PI_4,
            camera_aspect: 1.333,
            scene_generation: 0,
            selection_generation: 0,
            point_clouds: Vec::new(),
            glyphs: Vec::new(),
            polylines: Vec::new(),
            volumes: Vec::new(),
            viewport_index: 0,
            compute_filter_items: Vec::new(),
            isoline_items: Vec::new(),
            streamtube_items: Vec::new(),
            clip_volume: ClipVolume::None,
        }
    }
}

// ---------------------------------------------------------------------------
// Draw-call macro (must be defined before use in impl block)
// ---------------------------------------------------------------------------

/// Internal macro that emits all draw calls. Used by both `paint` (egui /
/// `'static`) and `paint_to` (iced / any lifetime) to avoid duplicating
/// ~90 lines of rendering code while satisfying Rust's lifetime invariance
/// on `&mut RenderPass<'a>`.
macro_rules! emit_draw_calls {
    ($resources:expr, $render_pass:expr, $frame:expr, $use_instancing:expr, $batches:expr, $camera_bg:expr, $compute_filter_results:expr) => {{
        let resources = $resources;
        let render_pass = $render_pass;
        let frame = $frame;
        let use_instancing: bool = $use_instancing;
        // Phase G compute filter results: used by per-object path to override index buffers.
        let compute_filter_results: &[crate::resources::ComputeFilterResult] = $compute_filter_results;
        let batches: &[InstancedBatch] = $batches;
        let camera_bg: &wgpu::BindGroup = $camera_bg;

        render_pass.set_bind_group(0, camera_bg, &[]);

        // Grid pass — rendered first so scene geometry always paints over it.
        if let (Some(vbuf), Some(ibuf)) = (
            &resources.grid_vertex_buffer,
            &resources.grid_index_buffer,
        ) {
            if resources.grid_index_count > 0 {
                render_pass.set_pipeline(&resources.overlay_line_pipeline);
                render_pass.set_bind_group(0, camera_bg, &[]);
                render_pass.set_bind_group(1, &resources.grid_bind_group, &[]);
                render_pass.set_vertex_buffer(0, vbuf.slice(..));
                render_pass.set_index_buffer(ibuf.slice(..), wgpu::IndexFormat::Uint32);
                render_pass.draw_indexed(0..resources.grid_index_count, 0, 0..1);
            }
        }

            if !frame.scene_items.is_empty() {
                if use_instancing && !batches.is_empty() {
                    let excluded_items: Vec<&SceneRenderItem> = frame
                        .scene_items
                        .iter()
                        .filter(|item| {
                            item.visible
                                && (item.active_attribute.is_some() || item.two_sided)
                                && resources
                                    .mesh_store
                                    .get(crate::resources::mesh_store::MeshId(item.mesh_index))
                                    .is_some()
                        })
                        .collect();

                // --- Instanced draw path ---
                // Separate opaque and transparent batches.
                let mut opaque_batches: Vec<&InstancedBatch> = Vec::new();
                let mut transparent_batches: Vec<&InstancedBatch> = Vec::new();
                for batch in batches {
                    if batch.is_transparent {
                        transparent_batches.push(batch);
                    } else {
                        opaque_batches.push(batch);
                    }
                }

                    // Draw opaque instanced batches.
                    if !opaque_batches.is_empty() && !frame.wireframe_mode {
                        if let Some(ref pipeline) = resources.solid_instanced_pipeline {
                            render_pass.set_pipeline(pipeline);
                            for batch in &opaque_batches {
                                let Some(mesh) = resources.mesh_store.get(crate::resources::mesh_store::MeshId(batch.mesh_index)) else { continue };
                                let mat_key = (
                                    batch.texture_id.unwrap_or(u64::MAX),
                                    batch.normal_map_id.unwrap_or(u64::MAX),
                                    batch.ao_map_id.unwrap_or(u64::MAX),
                                );
                                // Combined (instance storage + texture) bind group, primed in prepare().
                                let Some(inst_tex_bg) = resources.instance_bind_groups.get(&mat_key) else { continue };
                                render_pass.set_bind_group(1, inst_tex_bg, &[]);
                                render_pass.set_vertex_buffer(0, mesh.vertex_buffer.slice(..));
                                render_pass.set_index_buffer(mesh.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
                                render_pass.draw_indexed(
                                    0..mesh.index_count,
                                    0,
                                    batch.instance_offset..batch.instance_offset + batch.instance_count,
                                );
                            }
                        }
                    }

                    // Draw transparent instanced batches.
                    if !transparent_batches.is_empty() && !frame.wireframe_mode {
                        if let Some(ref pipeline) = resources.transparent_instanced_pipeline {
                            render_pass.set_pipeline(pipeline);
                            for batch in &transparent_batches {
                                let Some(mesh) = resources.mesh_store.get(crate::resources::mesh_store::MeshId(batch.mesh_index)) else { continue };
                                let mat_key = (
                                    batch.texture_id.unwrap_or(u64::MAX),
                                    batch.normal_map_id.unwrap_or(u64::MAX),
                                    batch.ao_map_id.unwrap_or(u64::MAX),
                                );
                                let Some(inst_tex_bg) = resources.instance_bind_groups.get(&mat_key) else { continue };
                                render_pass.set_bind_group(1, inst_tex_bg, &[]);
                                render_pass.set_vertex_buffer(0, mesh.vertex_buffer.slice(..));
                                render_pass.set_index_buffer(mesh.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
                                render_pass.draw_indexed(
                                    0..mesh.index_count,
                                    0,
                                    batch.instance_offset..batch.instance_offset + batch.instance_count,
                                );
                            }
                        }
                    }

                    // Wireframe mode fallback: draw per-object.
                    // mesh.object_bind_group (group 1) already contains the object uniform
                    // and fallback textures — no separate group 2 needed.
                    if frame.wireframe_mode {
                        for item in &frame.scene_items {
                            if !item.visible { continue; }
                            let Some(mesh) = resources.mesh_store.get(crate::resources::mesh_store::MeshId(item.mesh_index)) else { continue };
                            render_pass.set_pipeline(&resources.wireframe_pipeline);
                            render_pass.set_bind_group(1, &mesh.object_bind_group, &[]);
                            render_pass.set_vertex_buffer(0, mesh.vertex_buffer.slice(..));
                            render_pass.set_index_buffer(mesh.edge_index_buffer.slice(..), wgpu::IndexFormat::Uint32);
                            render_pass.draw_indexed(0..mesh.edge_index_count, 0, 0..1);
                        }
                    } else {
                        for item in &excluded_items {
                            let Some(mesh) = resources
                                .mesh_store
                                .get(crate::resources::mesh_store::MeshId(item.mesh_index))
                            else {
                                continue;
                            };
                            let pipeline = if item.material.opacity < 1.0 {
                                &resources.transparent_pipeline
                            } else if item.two_sided {
                                &resources.solid_two_sided_pipeline
                            } else {
                                &resources.solid_pipeline
                            };
                            render_pass.set_pipeline(pipeline);
                            render_pass.set_bind_group(1, &mesh.object_bind_group, &[]);
                            render_pass.set_vertex_buffer(0, mesh.vertex_buffer.slice(..));
                            render_pass.set_index_buffer(
                                mesh.index_buffer.slice(..),
                                wgpu::IndexFormat::Uint32,
                            );
                            render_pass.draw_indexed(0..mesh.index_count, 0, 0..1);
                        }
                    }
            } else {
                // --- Per-object draw path (original) ---
                let eye = glam::Vec3::from(frame.eye_pos);

                let dist_from_eye = |item: &&SceneRenderItem| -> f32 {
                    let pos = glam::Vec3::new(
                        item.model[3][0],
                        item.model[3][1],
                        item.model[3][2],
                    );
                    (pos - eye).length()
                };

                let mut opaque: Vec<&SceneRenderItem> = Vec::new();
                let mut transparent: Vec<&SceneRenderItem> = Vec::new();
                for item in &frame.scene_items {
                    if !item.visible || resources.mesh_store.get(crate::resources::mesh_store::MeshId(item.mesh_index)).is_none() {
                        continue;
                    }
                    if item.material.opacity < 1.0 {
                        transparent.push(item);
                    } else {
                        opaque.push(item);
                    }
                }
                opaque.sort_by(|a, b| dist_from_eye(a).partial_cmp(&dist_from_eye(b)).unwrap_or(std::cmp::Ordering::Equal));
                transparent.sort_by(|a, b| dist_from_eye(b).partial_cmp(&dist_from_eye(a)).unwrap_or(std::cmp::Ordering::Equal));

                macro_rules! draw_item {
                    ($item:expr, $pipeline:expr) => {{
                        let item = $item;
                        let mesh = resources.mesh_store.get(crate::resources::mesh_store::MeshId(item.mesh_index)).unwrap();
                        render_pass.set_bind_group(1, &mesh.object_bind_group, &[]);

                        // mesh.object_bind_group (group 1) already carries the object uniform
                        // and the correct texture views — updated in prepare() if material changed.
                        render_pass.set_vertex_buffer(0, mesh.vertex_buffer.slice(..));

                        if frame.wireframe_mode {
                            render_pass.set_pipeline(&resources.wireframe_pipeline);
                            render_pass.set_index_buffer(
                                mesh.edge_index_buffer.slice(..),
                                wgpu::IndexFormat::Uint32,
                            );
                            render_pass.draw_indexed(0..mesh.edge_index_count, 0, 0..1);
                        } else {
                            // Phase G: check for a compute-filtered index buffer override.
                            let filter_result = compute_filter_results
                                .iter()
                                .find(|r| r.mesh_index == item.mesh_index);
                            render_pass.set_pipeline($pipeline);
                            if let Some(fr) = filter_result {
                                render_pass.set_index_buffer(
                                    fr.index_buffer.slice(..),
                                    wgpu::IndexFormat::Uint32,
                                );
                                render_pass.draw_indexed(0..fr.index_count, 0, 0..1);
                            } else {
                                render_pass.set_index_buffer(
                                    mesh.index_buffer.slice(..),
                                    wgpu::IndexFormat::Uint32,
                                );
                                render_pass.draw_indexed(0..mesh.index_count, 0, 0..1);
                            }
                        }

                        if item.show_normals {
                            if let Some(ref nl_buf) = mesh.normal_line_buffer {
                                if mesh.normal_line_count > 0 {
                                    render_pass.set_pipeline(&resources.wireframe_pipeline);
                                    render_pass.set_bind_group(1, &mesh.normal_bind_group, &[]);
                                    render_pass.set_vertex_buffer(0, nl_buf.slice(..));
                                    render_pass.draw(0..mesh.normal_line_count, 0..1);
                                }
                            }
                        }
                    }};
                }

                for item in &opaque {
                    let pl = if item.two_sided {
                        &resources.solid_two_sided_pipeline
                    } else {
                        &resources.solid_pipeline
                    };
                    draw_item!(item, pl);
                }
                for item in &transparent {
                    draw_item!(item, &resources.transparent_pipeline);
                }
            }
        }

        // Gizmo pass.
        if frame.gizmo_model.is_some() && resources.gizmo_index_count > 0 {
            render_pass.set_pipeline(&resources.gizmo_pipeline);
            render_pass.set_bind_group(0, camera_bg, &[]);
            render_pass.set_bind_group(1, &resources.gizmo_bind_group, &[]);
            render_pass.set_vertex_buffer(0, resources.gizmo_vertex_buffer.slice(..));
            render_pass.set_index_buffer(
                resources.gizmo_index_buffer.slice(..),
                wgpu::IndexFormat::Uint32,
            );
            render_pass.draw_indexed(0..resources.gizmo_index_count, 0, 0..1);
        }

        // Domain wireframe pass.
        if let (Some(vbuf), Some(ibuf)) = (
            &resources.domain_vertex_buffer,
            &resources.domain_index_buffer,
        ) {
            if resources.domain_index_count > 0 {
                render_pass.set_pipeline(&resources.overlay_line_pipeline);
                render_pass.set_bind_group(0, camera_bg, &[]);
                render_pass.set_bind_group(1, &resources.domain_bind_group, &[]);
                render_pass.set_vertex_buffer(0, vbuf.slice(..));
                render_pass.set_index_buffer(ibuf.slice(..), wgpu::IndexFormat::Uint32);
                render_pass.draw_indexed(0..resources.domain_index_count, 0, 0..1);
            }
        }

        // Overlay quad pass.
        if !resources.bc_quad_buffers.is_empty() {
            render_pass.set_pipeline(&resources.overlay_pipeline);
            render_pass.set_bind_group(0, camera_bg, &[]);
            for (vbuf, ibuf, _ubuf, bg) in &resources.bc_quad_buffers {
                render_pass.set_bind_group(1, bg, &[]);
                render_pass.set_vertex_buffer(0, vbuf.slice(..));
                render_pass.set_index_buffer(ibuf.slice(..), wgpu::IndexFormat::Uint32);
                render_pass.draw_indexed(0..6, 0, 0..1);
            }
        }

        // Constraint guide line pass.
        if !resources.constraint_line_buffers.is_empty() {
            render_pass.set_pipeline(&resources.overlay_line_pipeline);
            render_pass.set_bind_group(0, camera_bg, &[]);
            for (vbuf, ibuf, index_count, _ubuf, bg) in &resources.constraint_line_buffers {
                render_pass.set_bind_group(1, bg, &[]);
                render_pass.set_vertex_buffer(0, vbuf.slice(..));
                render_pass.set_index_buffer(ibuf.slice(..), wgpu::IndexFormat::Uint32);
                render_pass.draw_indexed(0..*index_count, 0, 0..1);
            }
        }

        // Cap fill pass (section view cross-section fill).
        if !resources.cap_buffers.is_empty() {
            render_pass.set_pipeline(&resources.overlay_pipeline);
            render_pass.set_bind_group(0, camera_bg, &[]);
            for (vbuf, ibuf, idx_count, _ubuf, bg) in &resources.cap_buffers {
                render_pass.set_bind_group(1, bg, &[]);
                render_pass.set_vertex_buffer(0, vbuf.slice(..));
                render_pass.set_index_buffer(ibuf.slice(..), wgpu::IndexFormat::Uint32);
                render_pass.draw_indexed(0..*idx_count, 0, 0..1);
            }
        }

        // X-ray pass: render selected objects as semi-transparent overlay through geometry.
        if !resources.xray_object_buffers.is_empty() {
            render_pass.set_pipeline(&resources.xray_pipeline);
            render_pass.set_bind_group(0, camera_bg, &[]);
            for (mesh_idx, _buf, bg) in &resources.xray_object_buffers {
                let Some(mesh) = resources.mesh_store.get(crate::resources::mesh_store::MeshId(*mesh_idx)) else { continue };
                render_pass.set_bind_group(1, bg, &[]);
                render_pass.set_vertex_buffer(0, mesh.vertex_buffer.slice(..));
                render_pass.set_index_buffer(mesh.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
                render_pass.draw_indexed(0..mesh.index_count, 0, 0..1);
            }
        }

        // Outline composite: blit the offscreen outline texture (rendered in prepare()).
        if !resources.outline_object_buffers.is_empty() {
            if let (Some(pipeline), Some(bg)) = (
                &resources.outline_composite_pipeline_msaa,
                &resources.outline_composite_bind_group,
            ) {
                render_pass.set_pipeline(pipeline);
                render_pass.set_bind_group(0, bg, &[]);
                render_pass.draw(0..3, 0..1);
            }
        }

        // Axes indicator pass (screen-space, last so it draws on top).
        if frame.show_axes_indicator && resources.axes_vertex_count > 0 {
            render_pass.set_pipeline(&resources.axes_pipeline);
            render_pass.set_vertex_buffer(0, resources.axes_vertex_buffer.slice(..));
            render_pass.draw(0..resources.axes_vertex_count, 0..1);
        }
    }};
}

/// Draw point cloud and glyph items from per-frame GPU data prepared in `prepare()`.
///
/// Called by both `paint` and `paint_to` after `emit_draw_calls!` to render scivis layers.
macro_rules! emit_scivis_draw_calls {
    ($resources:expr, $render_pass:expr, $pc_gpu_data:expr, $glyph_gpu_data:expr, $polyline_gpu_data:expr, $volume_gpu_data:expr, $streamtube_gpu_data:expr, $camera_bg:expr) => {{
        let resources = $resources;
        let render_pass = $render_pass;
        let camera_bg: &wgpu::BindGroup = $camera_bg;

        // Point cloud pass.
        if !$pc_gpu_data.is_empty() {
            if let Some(ref pipeline) = resources.point_cloud_pipeline {
                render_pass.set_pipeline(pipeline);
                render_pass.set_bind_group(0, camera_bg, &[]);
                for pc in $pc_gpu_data.iter() {
                    render_pass.set_bind_group(1, &pc.bind_group, &[]);
                    render_pass.set_vertex_buffer(0, pc.vertex_buffer.slice(..));
                    // 6 vertices per point (billboard quad = 2 triangles), point_count instances.
                    render_pass.draw(0..6, 0..pc.point_count);
                }
            }
        }

        // Glyph pass.
        if !$glyph_gpu_data.is_empty() {
            if let Some(ref pipeline) = resources.glyph_pipeline {
                render_pass.set_pipeline(pipeline);
                render_pass.set_bind_group(0, camera_bg, &[]);
                for glyph in $glyph_gpu_data.iter() {
                    render_pass.set_bind_group(1, &glyph.uniform_bind_group, &[]);
                    render_pass.set_bind_group(2, &glyph.instance_bind_group, &[]);
                    render_pass.set_vertex_buffer(0, glyph.mesh_vertex_buffer.slice(..));
                    render_pass.set_index_buffer(
                        glyph.mesh_index_buffer.slice(..),
                        wgpu::IndexFormat::Uint32,
                    );
                    render_pass.draw_indexed(0..glyph.mesh_index_count, 0, 0..glyph.instance_count);
                }
            }
        }

        // Polyline pass (stream tracers — rendered after point clouds and glyphs).
        if !$polyline_gpu_data.is_empty() {
            if let Some(ref pipeline) = resources.polyline_pipeline {
                render_pass.set_pipeline(pipeline);
                render_pass.set_bind_group(0, camera_bg, &[]);
                for pl in $polyline_gpu_data.iter() {
                    render_pass.set_bind_group(1, &pl.bind_group, &[]);
                    render_pass.set_vertex_buffer(0, pl.vertex_buffer.slice(..));
                    // Draw each individual streamline strip separately.
                    for range in &pl.strip_ranges {
                        render_pass.draw(range.clone(), 0..1);
                    }
                }
            }
        }

        // Volume pass (after glyphs — volumes are translucent, rendered last).
        if !$volume_gpu_data.is_empty() {
            if let Some(ref pipeline) = resources.volume_pipeline {
                render_pass.set_pipeline(pipeline);
                render_pass.set_bind_group(0, camera_bg, &[]);
                for vol in $volume_gpu_data.iter() {
                    render_pass.set_bind_group(1, &vol.bind_group, &[]);
                    render_pass.set_vertex_buffer(0, vol.vertex_buffer.slice(..));
                    render_pass
                        .set_index_buffer(vol.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
                    render_pass.draw_indexed(0..36, 0, 0..1);
                }
            }
        }

        // Streamtube pass (SciVis Phase M — instanced cylinders along polyline strips).
        if !$streamtube_gpu_data.is_empty() {
            if let Some(ref pipeline) = resources.streamtube_pipeline {
                render_pass.set_pipeline(pipeline);
                render_pass.set_bind_group(0, camera_bg, &[]);
                for tube in $streamtube_gpu_data.iter() {
                    render_pass.set_bind_group(1, &tube.uniform_bind_group, &[]);
                    render_pass.set_bind_group(2, &tube.instance_bind_group, &[]);
                    render_pass.set_vertex_buffer(0, tube.mesh_vertex_buffer.slice(..));
                    render_pass.set_index_buffer(
                        tube.mesh_index_buffer.slice(..),
                        wgpu::IndexFormat::Uint32,
                    );
                    render_pass.draw_indexed(0..tube.mesh_index_count, 0, 0..tube.instance_count);
                }
            }
        }
    }};
}