phosph-rs 0.4.0

Simple, pretty, multiplatform molecular viewer for chemists.
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
use bevy::prelude::*;
use bevy::render::mesh::{Indices, PrimitiveTopology, VertexAttributeValues};
use bevy::render::render_asset::RenderAssetUsages;

mod cube;
pub use cube::*;

mod marching_cubes_tri_table;
use marching_cubes_tri_table::MARCHING_CUBES_TRI_TABLE;

/// Edge connection table for marching cubes: which two cube corners each edge connects.
const EDGE_CONNECTIONS: [[usize; 2]; 12] = [
    [0, 1], // 0
    [1, 2], // 1
    [2, 3], // 2
    [3, 0], // 3
    [4, 5], // 4
    [5, 6], // 5
    [6, 7], // 6
    [7, 4], // 7
    [0, 4], // 8
    [1, 5], // 9
    [2, 6], // 10
    [3, 7], // 11
];

/// Fixed step size for isovalue increments
const ISOVALUE_STEP: f32 = 0.005;

/// Main plugin for volumetric isosurface rendering (marching cubes).
pub struct VolumetricPlugin;

impl Plugin for VolumetricPlugin {
    fn build(&self, app: &mut App) {
        app.add_plugins(CubePlugin);

        // UI state and isosurface resource
        app.insert_resource(VolumetricUiState::default());
        app.init_resource::<VolumetricIsosurfaceResources>();

        // Ensure an entity exists to drive the renderer
        app.add_systems(Startup, setup_volumetric_renderer);

        // Isosurface management systems
        app.add_systems(Update, create_or_update_isosurface);
        app.add_systems(Update, cleanup_isosurface_on_disable);

        // Input controls (J/K for isovalue, Y for normals, V for visibility)
        app.add_systems(Update, isosurface_controls_system);
        app.add_systems(Update, toggle_isosurface_visibility);
    }
}

/// Resource used to store isosurface mesh & entity handles for lifecycle management.
#[derive(Resource, Default)]
pub struct VolumetricIsosurfaceResources {
    /// True once at least one isosurface entity has been spawned.
    pub created: bool,

    /// Positive isosurface entity & assets (for +isovalue)
    pub pos_entity: Option<Entity>,
    pub pos_mesh_handle: Option<Handle<Mesh>>,
    pub pos_material_handle: Option<Handle<StandardMaterial>>,

    /// Negative isosurface entity & assets (for -isovalue)
    pub neg_entity: Option<Entity>,
    pub neg_mesh_handle: Option<Handle<Mesh>>,
    pub neg_material_handle: Option<Handle<StandardMaterial>>,

    /// Last isovalue magnitude used to generate the meshes (for change detection)
    pub last_isovalue: Option<f32>,

    /// Last smooth_normals state used to generate the meshes (for change detection)
    pub last_smooth_normals: Option<bool>,
}

/// Simple UI state resource for the volumetric renderer
#[derive(Resource)]
pub struct VolumetricUiState {
    /// Is volumetric rendering enabled?
    pub enabled: bool,
}

impl Default for VolumetricUiState {
    fn default() -> Self {
        VolumetricUiState { enabled: true }
    }
}

/// Spawn a marker entity to represent the volumetric renderer.
fn setup_volumetric_renderer(mut commands: Commands) {
    commands.spawn((
        Name::new("Volumetric Isosurface Renderer"),
        VolumetricRenderer::default(),
    ));
    info!("Volumetric renderer entity created (spawned at startup)");
}

/// Controls for isovalue magnitude using J/K keys and smooth/flat shading toggle with Y
fn isosurface_controls_system(
    keyboard: Res<ButtonInput<KeyCode>>,
    mut query: Query<&mut VolumetricRenderer>,
) {
    if query.is_empty() {
        return;
    }

    for mut r in query.iter_mut() {
        // Isovalue adjustments with fixed step
        if keyboard.just_pressed(KeyCode::KeyJ) {
            r.isovalue = (r.isovalue - ISOVALUE_STEP).max(0.0);
            info!("Isovalue decreased to {:.4}", r.isovalue);
        }
        if keyboard.just_pressed(KeyCode::KeyK) {
            r.isovalue += ISOVALUE_STEP;
            info!("Isovalue increased to {:.4}", r.isovalue);
        }

        // Toggle smooth/flat shading
        if keyboard.just_pressed(KeyCode::KeyY) {
            r.smooth_normals = !r.smooth_normals;
            info!(
                "Normal smoothing: {}",
                if r.smooth_normals { "smooth" } else { "flat" }
            );
        }

        // Keep isovalue non-negative
        if r.isovalue < 0.0 {
            r.isovalue = 0.0;
        }
    }
}

/// Toggle isosurface visibility with the V key
fn toggle_isosurface_visibility(
    keyboard: Res<ButtonInput<KeyCode>>,
    iso_res: Res<VolumetricIsosurfaceResources>,
    mut query: Query<&mut Visibility>,
) {
    if keyboard.just_pressed(KeyCode::KeyV) {
        let mut toggled = false;

        // Toggle positive isosurface
        if let Some(entity) = iso_res.pos_entity {
            if let Ok(mut visibility) = query.get_mut(entity) {
                *visibility = match *visibility {
                    Visibility::Visible => Visibility::Hidden,
                    _ => Visibility::Visible,
                };
                toggled = true;
            }
        }

        // Toggle negative isosurface
        if let Some(entity) = iso_res.neg_entity {
            if let Ok(mut visibility) = query.get_mut(entity) {
                *visibility = match *visibility {
                    Visibility::Visible => Visibility::Hidden,
                    _ => Visibility::Visible,
                };
            }
        }

        if toggled {
            // Check the state of the first entity to log the message
            if let Some(entity) = iso_res.pos_entity {
                if let Ok(visibility) = query.get(entity) {
                    match *visibility {
                        Visibility::Visible => info!("Isosurfaces visible"),
                        _ => info!("Isosurfaces hidden"),
                    }
                }
            }
        }
    }
}

/// Create or update isosurfaces for both +isovalue and -isovalue.
/// Renders fully opaque isosurfaces only.
fn create_or_update_isosurface(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    mut iso_res: ResMut<VolumetricIsosurfaceResources>,
    vol_query: Query<&VolumetricRenderer>,
    maybe_data: Option<Res<VolumetricData>>,
    ui_state: Res<VolumetricUiState>,
) {
    if !ui_state.enabled {
        return;
    }

    let data = match maybe_data {
        Some(d) => d,
        None => return,
    };

    if vol_query.is_empty() {
        return;
    }

    // Use the first renderer
    let renderer = vol_query.iter().next().unwrap();

    // Magnitude of isovalue: we will generate both +iso and -iso
    let target_iso = renderer.isovalue.abs();
    let smooth = renderer.smooth_normals;

    // Check if we need to regenerate meshes
    let need_mesh_update = match (iso_res.last_isovalue, iso_res.last_smooth_normals) {
        (Some(prev_iso), Some(prev_smooth)) => {
            (prev_iso - target_iso).abs() > std::f32::EPSILON || prev_smooth != smooth
        }
        _ => true,
    };

    if !need_mesh_update && iso_res.created {
        // Nothing changed
        return;
    }

    // Generate meshes for +iso and -iso with chosen normal style
    let mesh_pos = if smooth {
        generate_isosurface_mesh_smooth(&data, target_iso)
    } else {
        generate_isosurface_mesh_flat(&data, target_iso)
    };
    let mesh_neg = if smooth {
        generate_isosurface_mesh_smooth(&data, -target_iso)
    } else {
        generate_isosurface_mesh_flat(&data, -target_iso)
    };

    // Create fully opaque materials for positive and negative isosurfaces
    let mat_pos = StandardMaterial {
        base_color: Color::srgba(
            renderer.positive_color.x,
            renderer.positive_color.y,
            renderer.positive_color.z,
            1.0, // Fully opaque
        ),
        unlit: false,
        perceptual_roughness: 0.3,
        metallic: 0.3,
        alpha_mode: AlphaMode::Opaque,
        cull_mode: None,
        double_sided: true,
        ..Default::default()
    };

    let mat_neg = StandardMaterial {
        base_color: Color::srgba(
            renderer.negative_color.x,
            renderer.negative_color.y,
            renderer.negative_color.z,
            1.0, // Fully opaque
        ),
        unlit: false,
        perceptual_roughness: 0.3,
        metallic: 0.3,
        alpha_mode: AlphaMode::Opaque,
        cull_mode: None,
        double_sided: true,
        ..Default::default()
    };

    if !iso_res.created {
        // Add mesh assets and create materials & entities for both lobes
        let mesh_handle_pos = meshes.add(mesh_pos);
        let mesh_handle_neg = meshes.add(mesh_neg);
        let mat_handle_pos = materials.add(mat_pos);
        let mat_handle_neg = materials.add(mat_neg);

        let pos_ent = commands
            .spawn((
                Mesh3d(mesh_handle_pos.clone()),
                MeshMaterial3d(mat_handle_pos.clone()),
                Name::new("Isosurface +"),
                Transform::from_translation(data.origin),
                Visibility::Visible,
            ))
            .id();
        let neg_ent = commands
            .spawn((
                Mesh3d(mesh_handle_neg.clone()),
                MeshMaterial3d(mat_handle_neg.clone()),
                Name::new("Isosurface -"),
                Transform::from_translation(data.origin),
                Visibility::Visible,
            ))
            .id();

        iso_res.created = true;
        iso_res.pos_entity = Some(pos_ent);
        iso_res.neg_entity = Some(neg_ent);
        iso_res.pos_mesh_handle = Some(mesh_handle_pos);
        iso_res.neg_mesh_handle = Some(mesh_handle_neg);
        iso_res.pos_material_handle = Some(mat_handle_pos);
        iso_res.neg_material_handle = Some(mat_handle_neg);
        iso_res.last_isovalue = Some(target_iso);
        iso_res.last_smooth_normals = Some(smooth);

        info!(
            "Spawned opaque ± isosurfaces for isovalue {:.4} ({})",
            target_iso,
            if smooth { "smooth" } else { "flat" }
        );
    } else {
        // Update positive lobe mesh
        if let Some(mesh_handle_pos) = &iso_res.pos_mesh_handle {
            if let Some(existing) = meshes.get_mut(mesh_handle_pos) {
                *existing = mesh_pos;
                info!(
                    "Updated positive isosurface mesh for isovalue {:.4}",
                    target_iso
                );
            } else {
                let new_handle = meshes.add(mesh_pos);
                iso_res.pos_mesh_handle = Some(new_handle.clone());
                if let Some(ent) = iso_res.pos_entity {
                    commands.entity(ent).insert(Mesh3d(new_handle));
                }
                info!("Replaced positive mesh asset handle");
            }
        } else {
            let new_handle = meshes.add(mesh_pos);
            iso_res.pos_mesh_handle = Some(new_handle.clone());
            if let Some(ent) = iso_res.pos_entity {
                commands.entity(ent).insert(Mesh3d(new_handle));
            }
            info!("Attached positive mesh handle to existing entity");
        }

        // Update negative lobe mesh
        if let Some(mesh_handle_neg) = &iso_res.neg_mesh_handle {
            if let Some(existing) = meshes.get_mut(mesh_handle_neg) {
                *existing = mesh_neg;
                info!(
                    "Updated negative isosurface mesh for isovalue {:.4}",
                    target_iso
                );
            } else {
                let new_handle = meshes.add(mesh_neg);
                iso_res.neg_mesh_handle = Some(new_handle.clone());
                if let Some(ent) = iso_res.neg_entity {
                    commands.entity(ent).insert(Mesh3d(new_handle));
                }
                info!("Replaced negative mesh asset handle");
            }
        } else {
            let new_handle = meshes.add(mesh_neg);
            iso_res.neg_mesh_handle = Some(new_handle.clone());
            if let Some(ent) = iso_res.neg_entity {
                commands.entity(ent).insert(Mesh3d(new_handle));
            }
            info!("Attached negative mesh handle to existing entity");
        }

        // Update materials to ensure they stay opaque
        let mat_handle_pos = materials.add(mat_pos);
        let mat_handle_neg = materials.add(mat_neg);
        iso_res.pos_material_handle = Some(mat_handle_pos.clone());
        iso_res.neg_material_handle = Some(mat_handle_neg.clone());
        if let Some(ent) = iso_res.pos_entity {
            commands.entity(ent).insert(MeshMaterial3d(mat_handle_pos));
        }
        if let Some(ent) = iso_res.neg_entity {
            commands.entity(ent).insert(MeshMaterial3d(mat_handle_neg));
        }

        iso_res.last_isovalue = Some(target_iso);
        iso_res.last_smooth_normals = Some(smooth);
    }
}

/// Cleanup isosurfaces when UI disables volumetric rendering.
fn cleanup_isosurface_on_disable(
    mut commands: Commands,
    mut iso_res: ResMut<VolumetricIsosurfaceResources>,
    ui_state: Res<VolumetricUiState>,
) {
    if ui_state.enabled {
        return;
    }

    if !iso_res.created {
        return;
    }

    if let Some(ent) = iso_res.pos_entity.take() {
        commands.entity(ent).despawn_recursive();
    }
    if let Some(ent) = iso_res.neg_entity.take() {
        commands.entity(ent).despawn_recursive();
    }

    iso_res.pos_mesh_handle = None;
    iso_res.neg_mesh_handle = None;
    iso_res.pos_material_handle = None;
    iso_res.neg_material_handle = None;
    iso_res.last_isovalue = None;
    iso_res.last_smooth_normals = None;
    iso_res.created = false;

    info!("Cleaned up isosurfaces due to UI disable");
}

/// Fix triangle winding and normals to ensure proper front-facing surfaces for correct lighting.
///
/// Two things matter for proper specular/reflective lighting in Bevy:
/// 1. Triangle winding must be CCW for front faces.
/// 2. Vertex normals must point outward (consistent with that winding).
///
/// This function:
/// - Checks if the voxel basis is left-handed and flips winding if needed
/// - Flips normals only when winding is flipped to keep them consistent
fn fix_winding_and_normals(mesh: &mut Mesh, voxel_basis: [Vec3; 3]) {
    // Check if the voxel basis is left-handed
    let a = Mat3::from_cols(voxel_basis[0], voxel_basis[1], voxel_basis[2]);
    let is_left_handed = a.determinant() < 0.0;

    // The standard marching cubes table produces inside-out triangles for a right-handed system,
    // but for a left-handed system we need to handle it differently.
    // In either case, we need exactly one winding flip to get outward-facing triangles.

    // For right-handed systems: flip once (standard MC is inside-out)
    // For left-handed systems: don't flip (MC orientation happens to be correct)
    let should_flip_winding = !is_left_handed;

    if should_flip_winding {
        if let Some(Indices::U32(idx)) = mesh.indices_mut() {
            for tri in idx.chunks_exact_mut(3) {
                tri.swap(1, 2); // [a,b,c] -> [a,c,b]
            }
        }

        // Flip normals to match the flipped winding
        if let Some(VertexAttributeValues::Float32x3(nrm)) =
            mesh.attribute_mut(Mesh::ATTRIBUTE_NORMAL)
        {
            for v in nrm.iter_mut() {
                v[0] = -v[0];
                v[1] = -v[1];
                v[2] = -v[2];
            }
        }
    }
}

/// Apply Laplacian smoothing to mesh vertex positions to reduce faceting artifacts.
///
/// This smooths the geometry to match the visual smoothness of interpolated normals.
/// Each vertex is moved toward the average position of its neighboring vertices.
fn smooth_mesh_positions(mesh: &mut Mesh, iterations: usize, lambda: f32) {
    // Extract positions and indices data without holding mutable references
    let positions_data = mesh.attribute(Mesh::ATTRIBUTE_POSITION).cloned();
    let indices_data = mesh.indices().cloned();

    let Some(VertexAttributeValues::Float32x3(positions_vec)) = positions_data else {
        return;
    };

    let Some(Indices::U32(indices_vec)) = indices_data else {
        return;
    };

    // Convert positions to Vec3 for easier math
    let mut verts: Vec<Vec3> = positions_vec
        .iter()
        .map(|p| Vec3::new(p[0], p[1], p[2]))
        .collect();

    // Build adjacency list
    let mut neighbors: Vec<Vec<usize>> = vec![Vec::new(); verts.len()];
    for tri in indices_vec.chunks(3) {
        let i0 = tri[0] as usize;
        let i1 = tri[1] as usize;
        let i2 = tri[2] as usize;

        // Add edges (undirected)
        neighbors[i0].push(i1);
        neighbors[i0].push(i2);
        neighbors[i1].push(i0);
        neighbors[i1].push(i2);
        neighbors[i2].push(i0);
        neighbors[i2].push(i1);
    }

    // Deduplicate neighbors
    for neighbor_list in neighbors.iter_mut() {
        neighbor_list.sort_unstable();
        neighbor_list.dedup();
    }

    // Apply Laplacian smoothing iterations
    for _ in 0..iterations {
        let mut new_verts = verts.clone();

        for (i, v) in verts.iter().enumerate() {
            if neighbors[i].is_empty() {
                continue; // Keep isolated vertices unchanged
            }

            // Compute average position of neighbors
            let avg_neighbor: Vec3 =
                neighbors[i].iter().map(|&j| verts[j]).sum::<Vec3>() / neighbors[i].len() as f32;

            // Move vertex toward average (lambda controls the amount)
            new_verts[i] = v.lerp(avg_neighbor, lambda);
        }

        verts = new_verts;
    }

    // Write smoothed positions back to mesh
    let smoothed_positions: Vec<[f32; 3]> = verts.into_iter().map(|v| [v.x, v.y, v.z]).collect();
    mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, smoothed_positions);
}

/// Generate an isosurface mesh with smooth normals from volumetric scalar data using marching cubes.
///
/// Single-threaded marching cubes that deduplicates vertices and computes smooth vertex normals
/// by averaging adjacent triangle normals. This reduces visible "voxel seams" and improves
/// lighting consistency.
fn generate_isosurface_mesh_smooth(data: &VolumetricData, isovalue: f32) -> Mesh {
    let nx = data.dimensions.x as usize;
    let ny = data.dimensions.y as usize;
    let nz = data.dimensions.z as usize;

    // Need at least one cube in each axis
    if nx < 2 || ny < 2 || nz < 2 {
        return Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        );
    }

    // Working structures for indexed mesh construction
    let mut positions: Vec<[f32; 3]> = Vec::new();
    let mut normals_accum: Vec<Vec3> = Vec::new(); // accumulate triangle normals per-vertex
    let mut uvs: Vec<[f32; 2]> = Vec::new();
    let mut indices: Vec<u32> = Vec::new();

    // Map quantized positions to vertex indices for deduplication
    let mut vert_map: std::collections::HashMap<(i64, i64, i64), u32> =
        std::collections::HashMap::new();

    // Helper closure: retrieve voxel value at integer coords
    let get_val = |x: usize, y: usize, z: usize| -> f32 { data.get_voxel_unchecked(x, y, z) };

    // Small helper to quantize a world position to integer key
    let quantize = |v: Vec3, tol: f32| -> (i64, i64, i64) {
        let qx = (v.x / tol).round() as i64;
        let qy = (v.y / tol).round() as i64;
        let qz = (v.z / tol).round() as i64;
        (qx, qy, qz)
    };

    // Determine a quantization tolerance relative to voxel spacing to avoid splitting vertices
    let min_voxel_len = data
        .voxel_vectors
        .iter()
        .map(|v| v.length())
        .fold(f32::INFINITY, f32::min)
        .max(1e-6);
    // Tolerance slightly smaller than voxel spacing to merge identical edge vertices
    let tol = (min_voxel_len * 1e-3).max(1e-6);

    for z in 0..(nz - 1) {
        for y in 0..(ny - 1) {
            for x in 0..(nx - 1) {
                // corners (standard ordering)
                let corners = [
                    (x, y, z),
                    (x + 1, y, z),
                    (x + 1, y + 1, z),
                    (x, y + 1, z),
                    (x, y, z + 1),
                    (x + 1, y, z + 1),
                    (x + 1, y + 1, z + 1),
                    (x, y + 1, z + 1),
                ];

                let mut corner_vals = [0.0f32; 8];
                let mut corner_pos = [Vec3::ZERO; 8];

                for (i, &(cx, cy, cz)) in corners.iter().enumerate() {
                    corner_vals[i] = get_val(cx, cy, cz);
                    corner_pos[i] = data.voxel_to_world(cx, cy, cz);
                }

                // compute cube index (inside if value < isovalue)
                let mut cube_index: usize = 0;
                for i in 0..8 {
                    if corner_vals[i] < isovalue {
                        cube_index |= 1 << i;
                    }
                }

                let tri_entry = &MARCHING_CUBES_TRI_TABLE[cube_index];
                if tri_entry[0] == -1 {
                    continue;
                }

                let mut idx_table = 0;
                while idx_table < 16 {
                    let e0 = tri_entry[idx_table];
                    if e0 == -1 {
                        break;
                    }
                    let e1 = tri_entry[idx_table + 1];
                    let e2 = tri_entry[idx_table + 2];
                    if e1 == -1 || e2 == -1 {
                        break;
                    }

                    let v0 = interpolate_edge(&corner_pos, &corner_vals, e0 as usize, isovalue);
                    let v1 = interpolate_edge(&corner_pos, &corner_vals, e1 as usize, isovalue);
                    let v2 = interpolate_edge(&corner_pos, &corner_vals, e2 as usize, isovalue);

                    // Compute triangle normal from the marching cubes winding
                    let tri_n = (v1 - v0).cross(v2 - v0).normalize_or_zero();

                    // Use vertices and normal as-is from marching cubes table
                    // The fix_winding_and_normals function will handle orientation
                    let (a, b, c, n_final) = (v0, v1, v2, tri_n);

                    // For each vertex of the triangle, deduplicate and accumulate normals
                    let verts = [a, b, c];
                    for v in verts.iter() {
                        // Convert to mesh-local coordinates (relative to data.origin)
                        let local = Vec3::new(
                            v.x - data.origin.x,
                            v.y - data.origin.y,
                            v.z - data.origin.z,
                        );
                        let key = quantize(local, tol);

                        let vi = if let Some(&existing_idx) = vert_map.get(&key) {
                            existing_idx
                        } else {
                            let new_idx = positions.len() as u32;
                            positions.push([local.x, local.y, local.z]);
                            normals_accum.push(Vec3::ZERO);
                            uvs.push([0.0, 0.0]); // placeholder UV
                            vert_map.insert(key, new_idx);
                            new_idx
                        };

                        // record index for triangle element
                        indices.push(vi);
                        // accumulate triangle normal for smoothing using the chosen final normal
                        if let Some(acc) = normals_accum.get_mut(vi as usize) {
                            *acc += n_final;
                        }
                    }

                    idx_table += 3;
                }
            }
        }
    }

    // Compute averaged (smooth) normals
    let mut final_normals: Vec<[f32; 3]> = Vec::with_capacity(normals_accum.len());
    for acc in normals_accum.iter() {
        let n = acc.normalize_or_zero();
        final_normals.push([n.x, n.y, n.z]);
    }

    // Build an indexed mesh
    let mut mesh = Mesh::new(
        PrimitiveTopology::TriangleList,
        RenderAssetUsages::default(),
    );

    if !positions.is_empty() && !indices.is_empty() {
        mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, positions);
        mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, final_normals);
        mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, uvs);
        mesh.insert_indices(Indices::U32(indices));
    }

    // Fix winding and normals to ensure proper lighting
    fix_winding_and_normals(&mut mesh, data.voxel_vectors);

    // Smooth vertex positions to match the smooth normals
    // This reduces faceting artifacts and makes reflections match the visual smoothness
    smooth_mesh_positions(&mut mesh, 3, 0.5);

    mesh
}

/// Generate an isosurface mesh with flat normals (one normal per triangle).
///
/// This produces a faceted appearance where each triangle has its own flat normal,
/// making the voxel structure more visible.
fn generate_isosurface_mesh_flat(data: &VolumetricData, isovalue: f32) -> Mesh {
    let nx = data.dimensions.x as usize;
    let ny = data.dimensions.y as usize;
    let nz = data.dimensions.z as usize;

    // Need at least one cube in each axis
    if nx < 2 || ny < 2 || nz < 2 {
        return Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        );
    }

    let mut positions: Vec<[f32; 3]> = Vec::new();
    let mut normals: Vec<[f32; 3]> = Vec::new();
    let mut uvs: Vec<[f32; 2]> = Vec::new();
    let mut indices: Vec<u32> = Vec::new();

    // Helper closure: retrieve voxel value at integer coords
    let get_val = |x: usize, y: usize, z: usize| -> f32 { data.get_voxel_unchecked(x, y, z) };

    // Determine voxel spacing for gradient calculation
    let _min_voxel_len = data
        .voxel_vectors
        .iter()
        .map(|v| v.length())
        .fold(f32::INFINITY, f32::min)
        .max(1e-6);

    for z in 0..(nz - 1) {
        for y in 0..(ny - 1) {
            for x in 0..(nx - 1) {
                let corners = [
                    (x, y, z),
                    (x + 1, y, z),
                    (x + 1, y + 1, z),
                    (x, y + 1, z),
                    (x, y, z + 1),
                    (x + 1, y, z + 1),
                    (x + 1, y + 1, z + 1),
                    (x, y + 1, z + 1),
                ];

                let mut corner_vals = [0.0f32; 8];
                let mut corner_pos = [Vec3::ZERO; 8];

                for (i, &(cx, cy, cz)) in corners.iter().enumerate() {
                    corner_vals[i] = get_val(cx, cy, cz);
                    corner_pos[i] = data.voxel_to_world(cx, cy, cz);
                }

                // compute cube index (inside if value < isovalue)
                let mut cube_index: usize = 0;
                for i in 0..8 {
                    if corner_vals[i] < isovalue {
                        cube_index |= 1 << i;
                    }
                }

                let tri_entry = &MARCHING_CUBES_TRI_TABLE[cube_index];
                if tri_entry[0] == -1 {
                    continue;
                }

                let mut idx = 0;
                while idx < 16 {
                    let e0 = tri_entry[idx];
                    if e0 == -1 {
                        break;
                    }
                    let e1 = tri_entry[idx + 1];
                    let e2 = tri_entry[idx + 2];
                    if e1 == -1 || e2 == -1 {
                        break;
                    }

                    let v0 = interpolate_edge(&corner_pos, &corner_vals, e0 as usize, isovalue);
                    let v1 = interpolate_edge(&corner_pos, &corner_vals, e1 as usize, isovalue);
                    let v2 = interpolate_edge(&corner_pos, &corner_vals, e2 as usize, isovalue);

                    // Compute flat geometric normal from the marching cubes winding
                    let tri_n = (v1 - v0).cross(v2 - v0).normalize_or_zero();

                    // Use vertices and normal as-is from marching cubes table
                    // The fix_winding_and_normals function will handle orientation
                    let (a, b, c, n_final) = (v0, v1, v2, tri_n);

                    // For flat shading, we create separate vertices for each triangle
                    // (no sharing between triangles)
                    let base_idx = positions.len() as u32;

                    // Store mesh-local coordinates
                    positions.push([
                        a.x - data.origin.x,
                        a.y - data.origin.y,
                        a.z - data.origin.z,
                    ]);
                    positions.push([
                        b.x - data.origin.x,
                        b.y - data.origin.y,
                        b.z - data.origin.z,
                    ]);
                    positions.push([
                        c.x - data.origin.x,
                        c.y - data.origin.y,
                        c.z - data.origin.z,
                    ]);

                    // Use the same flat normal for all three vertices
                    normals.push([n_final.x, n_final.y, n_final.z]);
                    normals.push([n_final.x, n_final.y, n_final.z]);
                    normals.push([n_final.x, n_final.y, n_final.z]);

                    // placeholder UVs
                    uvs.push([0.0, 0.0]);
                    uvs.push([0.5, 0.0]);
                    uvs.push([1.0, 1.0]);

                    // Add indices for this triangle
                    indices.push(base_idx);
                    indices.push(base_idx + 1);
                    indices.push(base_idx + 2);

                    idx += 3;
                }
            }
        }
    }

    let mut mesh = Mesh::new(
        PrimitiveTopology::TriangleList,
        RenderAssetUsages::default(),
    );
    if !positions.is_empty() && !indices.is_empty() {
        mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, positions);
        mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normals);
        mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, uvs);
        mesh.insert_indices(Indices::U32(indices));
    }

    // Fix winding and normals to ensure proper lighting
    fix_winding_and_normals(&mut mesh, data.voxel_vectors);

    mesh
}

/// Interpolate a vertex position along a cube edge given the corner positions & values.
fn interpolate_edge(
    corner_pos: &[Vec3; 8],
    corner_val: &[f32; 8],
    edge_idx: usize,
    iso: f32,
) -> Vec3 {
    let pair = EDGE_CONNECTIONS[edge_idx];
    let a = pair[0];
    let b = pair[1];
    let va = corner_val[a];
    let vb = corner_val[b];
    let pa = corner_pos[a];
    let pb = corner_pos[b];

    if (iso - va).abs() < std::f32::EPSILON {
        return pa;
    }
    if (iso - vb).abs() < std::f32::EPSILON {
        return pb;
    }
    if (va - vb).abs() < std::f32::EPSILON {
        return pa;
    }

    let t = (iso - va) / (vb - va);
    pa + (pb - pa) * t
}

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

    #[test]
    fn test_interpolate_edge_midpoint() {
        let p0 = Vec3::new(0.0, 0.0, 0.0);
        let p1 = Vec3::new(1.0, 0.0, 0.0);
        let mut corner_pos = [Vec3::ZERO; 8];
        corner_pos[0] = p0;
        corner_pos[1] = p1;
        let mut corner_val = [0.0f32; 8];
        corner_val[0] = -1.0;
        corner_val[1] = 1.0;
        let v = interpolate_edge(&corner_pos, &corner_val, 0, 0.0);
        assert!((v - Vec3::new(0.5, 0.0, 0.0)).length() < 1e-6);
    }
}