polyscope-rs 0.5.10

A Rust-native 3D visualization library for geometric data
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
//! polyscope-rs: A Rust-native 3D visualization library for geometric data.
//!
//! Polyscope is a viewer and user interface for 3D data such as meshes and point clouds.
//! It allows you to register your data and quickly generate informative visualizations.
//!
//! # Quick Start
//!
//! ```no_run
//! use polyscope_rs::*;
//!
//! fn main() -> Result<()> {
//!     // Initialize polyscope
//!     init()?;
//!
//!     // Register a point cloud
//!     let points = vec![
//!         Vec3::new(0.0, 0.0, 0.0),
//!         Vec3::new(1.0, 0.0, 0.0),
//!         Vec3::new(0.0, 1.0, 0.0),
//!     ];
//!     register_point_cloud("my points", points);
//!
//!     // Show the viewer
//!     show();
//!
//!     Ok(())
//! }
//! ```
//!
//! # Architecture
//!
//! Polyscope uses a paradigm of **structures** and **quantities**:
//!
//! - A **structure** is a geometric object in the scene (point cloud, mesh, etc.)
//! - A **quantity** is data associated with a structure (scalar field, vector field, colors)
//!
//! # Structures
//!
//! - [`PointCloud`] - A set of points in 3D space
//! - [`SurfaceMesh`] - A triangular or polygonal mesh
//! - [`CurveNetwork`] - A network of curves/edges
//! - [`VolumeMesh`] - A tetrahedral or hexahedral mesh
//! - [`VolumeGrid`] - A regular grid of values (for implicit surfaces)
//! - [`CameraView`] - A camera frustum visualization

// Type casts in visualization code: Conversions between coordinate types (f32, f64)
// and index types (u32, usize) are intentional. Values are bounded by practical
// limits (screen resolution, mesh sizes).
#![allow(clippy::cast_possible_truncation)]
#![allow(clippy::cast_sign_loss)]
#![allow(clippy::cast_precision_loss)]
// Documentation lints: Detailed error/panic docs will be added as the API stabilizes.
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::missing_panics_doc)]
// Function length: Event handling and application logic are legitimately complex.
#![allow(clippy::too_many_lines)]
// Code organization: Local types in event handlers improve readability.
#![allow(clippy::items_after_statements)]
// Function signatures: Some public API functions need many parameters for flexibility.
#![allow(clippy::too_many_arguments)]
// Method design: Some methods take &self for API consistency or future expansion.
#![allow(clippy::unused_self)]
// Argument design: Some functions take ownership for API consistency.
#![allow(clippy::needless_pass_by_value)]
// Variable naming: Short names (x, y, z) are clear in context.
#![allow(clippy::many_single_char_names)]
// Configuration structs may have many boolean fields.
#![allow(clippy::struct_excessive_bools)]
// #[must_use] design: Setter methods intentionally omit #[must_use] since
// the mutation happens in-place; the &Self return is just for chaining convenience.
#![allow(clippy::must_use_candidate)]
// Documentation formatting: Backtick linting is too strict for doc comments.
#![allow(clippy::doc_markdown)]

/// Generates `get_<prefix>`, `with_<prefix>`, and `with_<prefix>_ref` accessor functions
/// for a structure type registered in the global context.
macro_rules! impl_structure_accessors {
    (
        get_fn = $get_fn:ident,
        with_fn = $with_fn:ident,
        with_ref_fn = $with_ref_fn:ident,
        handle = $handle:ident,
        type_name = $type_name:expr,
        rust_type = $rust_type:ty,
        doc_name = $doc_name:expr
    ) => {
        #[doc = concat!("Gets a registered ", $doc_name, " by name.")]
        #[must_use]
        pub fn $get_fn(name: &str) -> Option<$handle> {
            crate::with_context(|ctx| {
                if ctx.registry.contains($type_name, name) {
                    Some($handle {
                        name: name.to_string(),
                    })
                } else {
                    None
                }
            })
        }

        #[doc = concat!("Executes a closure with mutable access to a registered ", $doc_name, ".\n\nReturns `None` if the ", $doc_name, " does not exist.")]
        pub fn $with_fn<F, R>(name: &str, f: F) -> Option<R>
        where
            F: FnOnce(&mut $rust_type) -> R,
        {
            crate::with_context_mut(|ctx| {
                ctx.registry
                    .get_mut($type_name, name)
                    .and_then(|s| s.as_any_mut().downcast_mut::<$rust_type>())
                    .map(f)
            })
        }

        #[doc = concat!("Executes a closure with immutable access to a registered ", $doc_name, ".\n\nReturns `None` if the ", $doc_name, " does not exist.")]
        pub fn $with_ref_fn<F, R>(name: &str, f: F) -> Option<R>
        where
            F: FnOnce(&$rust_type) -> R,
        {
            crate::with_context(|ctx| {
                ctx.registry
                    .get($type_name, name)
                    .and_then(|s| s.as_any().downcast_ref::<$rust_type>())
                    .map(f)
            })
        }
    };
}

mod app;
mod camera_view;
mod curve_network;
mod floating;
mod gizmo;
mod groups;
mod headless;
mod init;
mod point_cloud;
mod screenshot;
mod slice_plane;
mod surface_mesh;
mod transform;
mod ui_sync;
mod volume_grid;
mod volume_mesh;

// Re-export core types
pub use polyscope_core::{
    Mat4, Vec2, Vec3, Vec4,
    error::{PolyscopeError, Result},
    gizmo::{GizmoAxis, GizmoConfig, GizmoMode, GizmoSpace, Transform},
    group::Group,
    options::Options,
    pick::{PickResult, Pickable},
    quantity::{ParamCoordsType, ParamVizStyle, Quantity, QuantityKind},
    registry::Registry,
    slice_plane::{MAX_SLICE_PLANES, SlicePlane, SlicePlaneUniforms},
    state::{Context, with_context, with_context_mut},
    structure::{HasQuantities, Structure},
};

// Re-export render types
pub use polyscope_render::{
    AxisDirection, Camera, ColorMap, ColorMapRegistry, Material, MaterialRegistry, NavigationStyle,
    PickElementType, ProjectionMode, RenderContext, RenderEngine, ScreenshotError,
    ScreenshotOptions,
};

// Re-export UI types
pub use polyscope_ui::{
    AppearanceSettings, CameraSettings, GizmoAction, GizmoSettings, GroupSettings, GroupsAction,
    SceneExtents, SelectionInfo, SlicePlaneGizmoAction, SlicePlaneSelectionInfo,
    SlicePlaneSettings, SlicePlanesAction, ViewAction,
};

// Re-export structures
pub use polyscope_structures::volume_grid::VolumeGridVizMode;
pub use polyscope_structures::{
    CameraExtrinsics, CameraIntrinsics, CameraParameters, CameraView, CurveNetwork, PointCloud,
    SurfaceMesh, VolumeCellType, VolumeGrid, VolumeMesh,
};

// Re-export module APIs
pub use camera_view::*;
pub use curve_network::*;
pub use floating::*;
pub use gizmo::*;
pub use groups::*;
pub use headless::*;
pub use init::*;
pub use point_cloud::*;
pub use screenshot::*;
pub use slice_plane::*;
pub use surface_mesh::*;
pub use transform::*;
pub use ui_sync::*;
pub use volume_grid::*;
pub use volume_mesh::*;

/// Removes a structure by name.
pub fn remove_structure(name: &str) {
    with_context_mut(|ctx| {
        // Try removing from each structure type
        ctx.registry.remove("PointCloud", name);
        ctx.registry.remove("SurfaceMesh", name);
        ctx.registry.remove("CurveNetwork", name);
        ctx.registry.remove("VolumeMesh", name);
        ctx.registry.remove("VolumeGrid", name);
        ctx.registry.remove("CameraView", name);
        ctx.update_extents();
    });
}

/// Removes all structures.
pub fn remove_all_structures() {
    with_context_mut(|ctx| {
        ctx.registry.clear();
        ctx.update_extents();
    });
}

/// Removes all structures, groups, slice planes, floating quantities,
/// and clears callbacks.
///
/// Unlike shutting down, this preserves render engine state and options.
/// Useful for resetting the scene while keeping the app running.
/// Matches C++ Polyscope's `removeEverything()` (commit f34f403).
pub fn remove_everything() {
    remove_all_structures();
    remove_all_groups();
    remove_all_slice_planes();
    remove_all_floating_quantities();
    clear_file_drop_callback();
}

/// Sets a callback that is invoked when files are dropped onto the polyscope window.
///
/// The callback receives a slice of file paths that were dropped.
///
/// # Example
/// ```no_run
/// polyscope_rs::set_file_drop_callback(|paths| {
///     for path in paths {
///         println!("Dropped: {}", path.display());
///     }
/// });
/// ```
pub fn set_file_drop_callback(callback: impl FnMut(&[std::path::PathBuf]) + Send + Sync + 'static) {
    with_context_mut(|ctx| {
        ctx.file_drop_callback = Some(Box::new(callback));
    });
}

/// Clears the file drop callback.
pub fn clear_file_drop_callback() {
    with_context_mut(|ctx| {
        ctx.file_drop_callback = None;
    });
}

/// Loads a blendable (4-channel, RGB-tintable) matcap material from disk.
///
/// Takes a name and 4 image file paths for R, G, B, K matcap channels.
/// The material becomes available in the UI material selector on the next frame.
///
/// Supports HDR, JPEG, PNG, EXR, and other image formats.
///
/// # Example
/// ```no_run
/// polyscope_rs::load_blendable_material("metal", [
///     "assets/metal_r.hdr",
///     "assets/metal_g.hdr",
///     "assets/metal_b.hdr",
///     "assets/metal_k.hdr",
/// ]);
/// ```
pub fn load_blendable_material(name: &str, filenames: [&str; 4]) {
    with_context_mut(|ctx| {
        ctx.material_load_queue
            .push(polyscope_core::state::MaterialLoadRequest::Blendable {
                name: name.to_string(),
                filenames: [
                    filenames[0].to_string(),
                    filenames[1].to_string(),
                    filenames[2].to_string(),
                    filenames[3].to_string(),
                ],
            });
    });
}

/// Loads a blendable material using a base path and extension.
///
/// Automatically expands to 4 filenames by appending `_r`, `_g`, `_b`, `_k`
/// before the extension. For example:
/// `load_blendable_material_ext("metal", "assets/metal", ".hdr")`
/// loads `assets/metal_r.hdr`, `assets/metal_g.hdr`, `assets/metal_b.hdr`, `assets/metal_k.hdr`.
pub fn load_blendable_material_ext(name: &str, base: &str, ext: &str) {
    load_blendable_material(
        name,
        [
            &format!("{base}_r{ext}"),
            &format!("{base}_g{ext}"),
            &format!("{base}_b{ext}"),
            &format!("{base}_k{ext}"),
        ],
    );
}

/// Loads a static (single-texture, non-RGB-tintable) matcap material from disk.
///
/// The same texture is used for all 4 matcap channels. Static materials
/// cannot be tinted with per-surface RGB colors.
///
/// # Example
/// ```no_run
/// polyscope_rs::load_static_material("stone", "assets/stone.jpg");
/// ```
pub fn load_static_material(name: &str, filename: &str) {
    with_context_mut(|ctx| {
        ctx.material_load_queue
            .push(polyscope_core::state::MaterialLoadRequest::Static {
                name: name.to_string(),
                path: filename.to_string(),
            });
    });
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU32, Ordering};

    // Counter for unique test names to avoid race conditions
    static COUNTER: AtomicU32 = AtomicU32::new(0);

    fn unique_name(prefix: &str) -> String {
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        format!("{prefix}_{n}")
    }

    fn setup() {
        // Initialize context (only once)
        // Use ok() to handle race conditions in parallel tests
        let _ = init();
    }

    #[test]
    fn test_register_curve_network() {
        setup();
        let name = unique_name("test_cn");
        let nodes = vec![
            Vec3::new(0.0, 0.0, 0.0),
            Vec3::new(1.0, 0.0, 0.0),
            Vec3::new(1.0, 1.0, 0.0),
        ];
        let edges = vec![[0, 1], [1, 2]];

        let handle = register_curve_network(&name, nodes, edges);
        assert_eq!(handle.name(), name);

        // Verify it's retrievable
        let found = get_curve_network(&name);
        assert!(found.is_some());

        // Verify non-existent returns None
        let not_found = get_curve_network("nonexistent_xyz_123");
        assert!(not_found.is_none());
    }

    #[test]
    fn test_register_curve_network_line() {
        setup();
        let name = unique_name("line");
        let nodes = vec![
            Vec3::new(0.0, 0.0, 0.0),
            Vec3::new(1.0, 0.0, 0.0),
            Vec3::new(2.0, 0.0, 0.0),
            Vec3::new(3.0, 0.0, 0.0),
        ];

        register_curve_network_line(&name, nodes);

        let num_edges = with_curve_network_ref(&name, |cn| cn.num_edges());
        assert_eq!(num_edges, Some(3)); // 0-1, 1-2, 2-3
    }

    #[test]
    fn test_register_curve_network_loop() {
        setup();
        let name = unique_name("loop");
        let nodes = vec![
            Vec3::new(0.0, 0.0, 0.0),
            Vec3::new(1.0, 0.0, 0.0),
            Vec3::new(1.0, 1.0, 0.0),
        ];

        register_curve_network_loop(&name, nodes);

        let num_edges = with_curve_network_ref(&name, |cn| cn.num_edges());
        assert_eq!(num_edges, Some(3)); // 0-1, 1-2, 2-0
    }

    #[test]
    fn test_register_curve_network_segments() {
        setup();
        let name = unique_name("segs");
        let nodes = vec![
            Vec3::new(0.0, 0.0, 0.0),
            Vec3::new(1.0, 0.0, 0.0),
            Vec3::new(2.0, 0.0, 0.0),
            Vec3::new(3.0, 0.0, 0.0),
        ];

        register_curve_network_segments(&name, nodes);

        let num_edges = with_curve_network_ref(&name, |cn| cn.num_edges());
        assert_eq!(num_edges, Some(2)); // 0-1, 2-3
    }

    #[test]
    fn test_curve_network_handle_methods() {
        setup();
        let name = unique_name("handle_test");
        let nodes = vec![Vec3::ZERO, Vec3::X];
        let edges = vec![[0, 1]];

        let handle = register_curve_network(&name, nodes, edges);

        // Test chained setters
        handle
            .set_color(Vec3::new(1.0, 0.0, 0.0))
            .set_radius(0.1, false)
            .set_material("clay");

        // Verify values were set
        with_curve_network_ref(&name, |cn| {
            assert_eq!(cn.color(), Vec4::new(1.0, 0.0, 0.0, 1.0));
            assert_eq!(cn.radius(), 0.1);
            assert!(!cn.radius_is_relative());
            assert_eq!(cn.material(), "clay");
        });
    }

    #[test]
    fn test_with_curve_network() {
        setup();
        let name = unique_name("with_test");
        let nodes = vec![Vec3::ZERO, Vec3::X, Vec3::Y];
        let edges = vec![[0, 1], [1, 2]];

        register_curve_network(&name, nodes, edges);

        // Test mutable access
        let result = with_curve_network(&name, |cn| {
            cn.set_color(Vec3::new(0.5, 0.5, 0.5));
            cn.num_nodes()
        });
        assert_eq!(result, Some(3));

        // Verify mutation persisted
        let color = with_curve_network_ref(&name, |cn| cn.color());
        assert_eq!(color, Some(Vec4::new(0.5, 0.5, 0.5, 1.0)));
    }

    #[test]
    fn test_create_group() {
        setup();
        let name = unique_name("test_group");
        let handle = create_group(&name);
        assert_eq!(handle.name(), name);
        assert!(handle.is_enabled());
    }

    #[test]
    fn test_get_group() {
        setup();
        let name = unique_name("get_group");
        create_group(&name);

        let found = get_group(&name);
        assert!(found.is_some());
        assert_eq!(found.unwrap().name(), name);

        let not_found = get_group("nonexistent_group_xyz");
        assert!(not_found.is_none());
    }

    #[test]
    fn test_group_enable_disable() {
        setup();
        let name = unique_name("enable_group");
        let handle = create_group(&name);

        assert!(handle.is_enabled());
        handle.set_enabled(false);
        assert!(!handle.is_enabled());
        handle.set_enabled(true);
        assert!(handle.is_enabled());
    }

    #[test]
    fn test_group_add_structures() {
        setup();
        let group_name = unique_name("struct_group");
        let pc_name = unique_name("pc_in_group");

        // Create point cloud
        register_point_cloud(&pc_name, vec![Vec3::ZERO, Vec3::X]);

        // Create group and add point cloud
        let handle = create_group(&group_name);
        handle.add_point_cloud(&pc_name);

        assert_eq!(handle.num_structures(), 1);
    }

    #[test]
    fn test_group_hierarchy() {
        setup();
        let parent_name = unique_name("parent_group");
        let child_name = unique_name("child_group");

        let parent = create_group(&parent_name);
        let _child = create_group(&child_name);

        parent.add_child_group(&child_name);

        assert_eq!(parent.num_child_groups(), 1);
    }

    #[test]
    fn test_remove_group() {
        setup();
        let name = unique_name("remove_group");
        create_group(&name);

        assert!(get_group(&name).is_some());
        remove_group(&name);
        assert!(get_group(&name).is_none());
    }

    #[test]
    fn test_add_slice_plane() {
        setup();
        let name = unique_name("slice_plane");
        let handle = add_slice_plane(&name);
        assert_eq!(handle.name(), name);
        assert!(handle.is_enabled());
    }

    #[test]
    fn test_slice_plane_pose() {
        setup();
        let name = unique_name("slice_pose");
        let handle = add_slice_plane_with_pose(&name, Vec3::new(1.0, 2.0, 3.0), Vec3::X);

        assert_eq!(handle.origin(), Vec3::new(1.0, 2.0, 3.0));
        assert_eq!(handle.normal(), Vec3::X);
    }

    #[test]
    fn test_slice_plane_setters() {
        setup();
        let name = unique_name("slice_setters");
        let handle = add_slice_plane(&name);

        handle
            .set_origin(Vec3::new(1.0, 0.0, 0.0))
            .set_normal(Vec3::Z)
            .set_color(Vec3::new(1.0, 0.0, 0.0))
            .set_transparency(0.5);

        assert_eq!(handle.origin(), Vec3::new(1.0, 0.0, 0.0));
        assert_eq!(handle.normal(), Vec3::Z);
        assert_eq!(handle.color(), Vec4::new(1.0, 0.0, 0.0, 1.0));
        assert!((handle.transparency() - 0.5).abs() < 0.001);
    }

    #[test]
    fn test_slice_plane_enable_disable() {
        setup();
        let name = unique_name("slice_enable");
        let handle = add_slice_plane(&name);

        assert!(handle.is_enabled());
        handle.set_enabled(false);
        assert!(!handle.is_enabled());
        handle.set_enabled(true);
        assert!(handle.is_enabled());
    }

    #[test]
    fn test_remove_slice_plane() {
        setup();
        let name = unique_name("slice_remove");
        add_slice_plane(&name);

        assert!(get_slice_plane(&name).is_some());
        remove_slice_plane(&name);
        assert!(get_slice_plane(&name).is_none());
    }

    #[test]
    fn test_select_structure() {
        setup();
        let name = unique_name("select_pc");
        register_point_cloud(&name, vec![Vec3::ZERO]);

        assert!(!has_selection());

        select_structure("PointCloud", &name);
        assert!(has_selection());

        let selected = get_selected_structure();
        assert!(selected.is_some());
        let (type_name, struct_name) = selected.unwrap();
        assert_eq!(type_name, "PointCloud");
        assert_eq!(struct_name, name);

        deselect_structure();
        assert!(!has_selection());
    }

    #[test]
    fn test_slice_plane_gizmo_selection() {
        setup();
        let name = unique_name("slice_gizmo");
        add_slice_plane(&name);

        // Initially no slice plane selected
        let info = get_slice_plane_selection_info();
        assert!(!info.has_selection);

        // Select slice plane
        select_slice_plane_for_gizmo(&name);
        let info = get_slice_plane_selection_info();
        assert!(info.has_selection);
        assert_eq!(info.name, name);

        // Deselect slice plane
        deselect_slice_plane_gizmo();
        let info = get_slice_plane_selection_info();
        assert!(!info.has_selection);
    }

    #[test]
    fn test_slice_plane_structure_mutual_exclusion() {
        setup();
        let pc_name = unique_name("mutual_pc");
        let plane_name = unique_name("mutual_plane");

        register_point_cloud(&pc_name, vec![Vec3::ZERO]);
        add_slice_plane(&plane_name);

        // Select structure
        select_structure("PointCloud", &pc_name);
        assert!(has_selection());

        // Select slice plane - should deselect structure
        select_slice_plane_for_gizmo(&plane_name);
        assert!(!has_selection()); // Structure should be deselected
        let info = get_slice_plane_selection_info();
        assert!(info.has_selection);

        // Select structure again - should deselect slice plane
        select_structure("PointCloud", &pc_name);
        assert!(has_selection());
        let info = get_slice_plane_selection_info();
        assert!(!info.has_selection); // Slice plane should be deselected
    }

    #[test]
    fn test_structure_transform() {
        setup();
        let name = unique_name("transform_pc");
        register_point_cloud(&name, vec![Vec3::ZERO, Vec3::X]);

        // Default transform is identity
        let transform = get_point_cloud_transform(&name);
        assert!(transform.is_some());

        // Set a translation transform
        let new_transform = Mat4::from_translation(Vec3::new(1.0, 2.0, 3.0));
        set_point_cloud_transform(&name, new_transform);

        let transform = get_point_cloud_transform(&name).unwrap();
        let translation = transform.w_axis.truncate();
        assert!((translation - Vec3::new(1.0, 2.0, 3.0)).length() < 0.001);
    }

    #[test]
    fn test_get_slice_plane_settings() {
        setup();
        let name = unique_name("ui_slice_plane");

        // Add a slice plane
        add_slice_plane_with_pose(&name, Vec3::new(1.0, 2.0, 3.0), Vec3::X);

        // Get settings
        let settings = get_slice_plane_settings();
        let found = settings.iter().find(|s| s.name == name);
        assert!(found.is_some());

        let s = found.unwrap();
        assert_eq!(s.origin, [1.0, 2.0, 3.0]);
        assert_eq!(s.normal, [1.0, 0.0, 0.0]);
        assert!(s.enabled);
    }

    #[test]
    fn test_apply_slice_plane_settings() {
        setup();
        let name = unique_name("apply_slice_plane");

        // Add a slice plane
        add_slice_plane(&name);

        // Create modified settings
        let settings = polyscope_ui::SlicePlaneSettings {
            name: name.clone(),
            enabled: false,
            origin: [5.0, 6.0, 7.0],
            normal: [0.0, 0.0, 1.0],
            draw_plane: false,
            draw_widget: true,
            color: [1.0, 0.0, 0.0],
            transparency: 0.8,
            plane_size: 0.2,
            is_selected: false,
        };

        // Apply settings
        apply_slice_plane_settings(&settings);

        // Verify
        let handle = get_slice_plane(&name).unwrap();
        assert!(!handle.is_enabled());
        assert_eq!(handle.origin(), Vec3::new(5.0, 6.0, 7.0));
        assert_eq!(handle.normal(), Vec3::Z);
        assert!(!handle.draw_plane());
        assert!(handle.draw_widget());
        assert_eq!(handle.color(), Vec4::new(1.0, 0.0, 0.0, 1.0));
        assert!((handle.transparency() - 0.8).abs() < 0.001);
    }

    #[test]
    fn test_handle_slice_plane_action_add() {
        setup();
        let name = unique_name("action_add_plane");
        let mut settings = Vec::new();

        handle_slice_plane_action(
            polyscope_ui::SlicePlanesAction::Add(name.clone()),
            &mut settings,
        );

        assert_eq!(settings.len(), 1);
        assert_eq!(settings[0].name, name);
        assert!(get_slice_plane(&name).is_some());
    }

    #[test]
    fn test_handle_slice_plane_action_remove() {
        setup();
        let name = unique_name("action_remove_plane");

        // Add plane
        add_slice_plane(&name);
        let mut settings = vec![polyscope_ui::SlicePlaneSettings::with_name(&name)];

        // Remove via action
        handle_slice_plane_action(polyscope_ui::SlicePlanesAction::Remove(0), &mut settings);

        assert!(settings.is_empty());
        assert!(get_slice_plane(&name).is_none());
    }

    #[test]
    fn test_get_group_settings() {
        setup();
        let name = unique_name("ui_group");
        let pc_name = unique_name("pc_in_ui_group");

        // Create group and add a structure
        let handle = create_group(&name);
        register_point_cloud(&pc_name, vec![Vec3::ZERO]);
        handle.add_point_cloud(&pc_name);

        // Get settings
        let settings = get_group_settings();
        let found = settings.iter().find(|s| s.name == name);
        assert!(found.is_some());

        let s = found.unwrap();
        assert!(s.enabled);
        assert!(s.show_child_details);
        assert_eq!(s.child_structures.len(), 1);
        assert_eq!(s.child_structures[0], ("PointCloud".to_string(), pc_name));
    }

    #[test]
    fn test_apply_group_settings() {
        setup();
        let name = unique_name("apply_group");

        // Create group
        create_group(&name);

        // Create modified settings
        let settings = polyscope_ui::GroupSettings {
            name: name.clone(),
            enabled: false,
            show_child_details: false,
            parent_group: None,
            child_structures: Vec::new(),
            child_groups: Vec::new(),
        };

        // Apply settings
        apply_group_settings(&settings);

        // Verify
        let handle = get_group(&name).unwrap();
        assert!(!handle.is_enabled());
    }

    #[test]
    fn test_get_gizmo_settings() {
        setup();

        // Set known values
        set_gizmo_space(GizmoSpace::Local);
        set_gizmo_visible(false);
        set_gizmo_snap_translate(0.5);
        set_gizmo_snap_rotate(15.0);
        set_gizmo_snap_scale(0.1);

        let settings = get_gizmo_settings();
        assert!(settings.local_space); // Local
        assert!(!settings.visible);
        assert!((settings.snap_translate - 0.5).abs() < 0.001);
        assert!((settings.snap_rotate - 15.0).abs() < 0.001);
        assert!((settings.snap_scale - 0.1).abs() < 0.001);
    }

    #[test]
    fn test_apply_gizmo_settings() {
        setup();

        let settings = polyscope_ui::GizmoSettings {
            local_space: false, // World
            visible: true,
            snap_translate: 1.0,
            snap_rotate: 45.0,
            snap_scale: 0.25,
        };

        apply_gizmo_settings(&settings);

        assert_eq!(get_gizmo_space(), GizmoSpace::World);
        assert!(is_gizmo_visible());
    }

    #[test]
    fn test_get_selection_info_with_selection() {
        setup();
        let name = unique_name("gizmo_select_pc");

        register_point_cloud(&name, vec![Vec3::ZERO]);
        select_structure("PointCloud", &name);

        let info = get_selection_info();
        assert!(info.has_selection);
        assert_eq!(info.type_name, "PointCloud");
        assert_eq!(info.name, name);

        deselect_structure();
    }

    #[test]
    fn test_apply_selection_transform() {
        setup();
        let name = unique_name("gizmo_transform_pc");

        register_point_cloud(&name, vec![Vec3::ZERO]);
        select_structure("PointCloud", &name);

        let selection = polyscope_ui::SelectionInfo {
            has_selection: true,
            type_name: "PointCloud".to_string(),
            name: name.clone(),
            translation: [1.0, 2.0, 3.0],
            rotation_degrees: [0.0, 0.0, 0.0],
            scale: [1.0, 1.0, 1.0],
            centroid: [1.0, 2.0, 3.0],
        };

        apply_selection_transform(&selection);

        let transform = get_point_cloud_transform(&name).unwrap();
        let translation = transform.w_axis.truncate();
        assert!((translation - Vec3::new(1.0, 2.0, 3.0)).length() < 0.001);

        deselect_structure();
    }

    #[test]
    fn test_remove_all_groups() {
        setup();
        let g1 = unique_name("rag_group1");
        let g2 = unique_name("rag_group2");
        create_group(&g1);
        create_group(&g2);

        assert!(get_group(&g1).is_some());
        assert!(get_group(&g2).is_some());

        remove_all_groups();

        assert!(get_group(&g1).is_none());
        assert!(get_group(&g2).is_none());
    }

    #[test]
    fn test_remove_everything() {
        setup();
        let pc_name = unique_name("re_pc");
        let group_name = unique_name("re_group");
        let sp_name = unique_name("re_slice");

        register_point_cloud(&pc_name, vec![Vec3::ZERO]);
        create_group(&group_name);
        add_slice_plane(&sp_name);

        remove_everything();

        assert!(get_point_cloud(&pc_name).is_none());
        assert!(get_group(&group_name).is_none());
        assert!(get_all_slice_planes().is_empty());
    }

    #[test]
    fn test_degenerate_bounding_box() {
        setup();
        // Clear all structures so only our degenerate point cloud contributes
        remove_all_structures();
        let name = unique_name("degen_bbox");
        // Register a point cloud where all points are at the same location
        register_point_cloud(&name, vec![Vec3::ONE, Vec3::ONE, Vec3::ONE]);

        let (bb_min, bb_max) = with_context(|ctx| ctx.bounding_box);
        // Bounding box should be perturbed so min != max
        assert!(
            bb_max.x > bb_min.x,
            "degenerate bbox not perturbed: min={bb_min}, max={bb_max}"
        );
        assert!(bb_max.y > bb_min.y);
        assert!(bb_max.z > bb_min.z);
    }
}