From 187189ec62ef14425ae6fd0a55fd0d58f24a4220 Mon Sep 17 00:00:00 2001 From: Andreas Reich Date: Wed, 10 Jul 2024 11:04:55 +0200 Subject: [PATCH] All components are now consistently implemented by a datatype (#6823) ### What Previously, we were a bit inconsistent with this: Most components were backed up by a single datatype but some weren't. This is now enforced everywhere. The expectation was that this saves a lot of code since we can forward to fewer serialized types. In reality this isn't _as_ good as expected since a bunch of new datatypes had to be introduced: * `Float64` * `Blob` used by `Blob` component - there should probably be no blob component but instead components with a deeper semantic * `Utf8List` for the sole purpose of implementing `VisualizerOverrides` * `ViewCoordinates` for the sole purpose of implementing `ViewCoordinates` ### Checklist * [x] I have read and agree to [Contributor Guide](https://github.com/rerun-io/rerun/blob/main/CONTRIBUTING.md) and the [Code of Conduct](https://github.com/rerun-io/rerun/blob/main/CODE_OF_CONDUCT.md) * [x] I've included a screenshot or gif (if applicable) * [x] I have tested the web demo (if applicable): * Using examples from latest `main` build: [rerun.io/viewer](https://rerun.io/viewer/pr/6823?manifest_url=https://app.rerun.io/version/main/examples_manifest.json) * Using full set of examples from `nightly` build: [rerun.io/viewer](https://rerun.io/viewer/pr/6823?manifest_url=https://app.rerun.io/version/nightly/examples_manifest.json) * [x] The PR title and labels are set such as to maximize their usefulness for the next release's CHANGELOG * [x] If applicable, add a new check to the [release checklist](https://github.com/rerun-io/rerun/blob/main/tests/python/release_checklist)! - [PR Build Summary](https://build.rerun.io/pr/6823) - [Recent benchmark results](https://build.rerun.io/graphs/crates.html) - [Wasm size tracking](https://build.rerun.io/graphs/sizes.html) To run all checks from `main`, comment on the PR with `@rerun-bot full-check`. --- .../src/build_examples/snippets.rs | 7 +- .../src/codegen/python/views.rs | 2 +- crates/build/re_types_builder/src/objects.rs | 9 +- .../store/re_chunk_store/tests/memory_test.rs | 2 +- .../re_entity_db/tests/time_histograms.rs | 2 +- crates/store/re_query/src/latest_at/query.rs | 2 +- .../re_types/definitions/rerun/blueprint.fbs | 1 + .../blueprint/components/auto_layout.fbs | 2 +- .../blueprint/components/auto_space_views.fbs | 2 +- .../blueprint/components/column_share.fbs | 2 +- .../blueprint/components/grid_columns.fbs | 2 +- .../rerun/blueprint/components/row_share.fbs | 2 +- .../rerun/blueprint/components/visible.fbs | 2 +- .../components/visualizer_overrides.fbs | 2 +- .../rerun/blueprint/datatypes/utf8_list.fbs | 17 ++ .../definitions/rerun/components/blob.fbs | 4 +- .../rerun/components/clear_is_recursive.fbs | 2 +- .../rerun/components/depth_meter.fbs | 2 +- .../rerun/components/disconnected_space.fbs | 2 +- .../rerun/components/draw_order.fbs | 2 +- .../rerun/components/marker_size.fbs | 2 +- .../definitions/rerun/components/radius.fbs | 2 +- .../definitions/rerun/components/scalar.fbs | 2 +- .../rerun/components/stroke_width.fbs | 2 +- .../rerun/components/view_coordinates.fbs | 5 +- .../re_types/definitions/rerun/datatypes.fbs | 3 + .../definitions/rerun/datatypes/blob.fbs | 24 ++ .../definitions/rerun/datatypes/bool.fbs | 1 + .../definitions/rerun/datatypes/float32.fbs | 3 +- .../definitions/rerun/datatypes/float64.fbs | 20 ++ .../definitions/rerun/datatypes/uint32.fbs | 3 +- .../definitions/rerun/datatypes/uint64.fbs | 2 +- .../rerun/datatypes/view_coordinates.fbs | 49 ++++ .../re_types/src/archetypes/points3d_ext.rs | 6 +- .../src/blueprint/components/column_share.rs | 102 ++----- .../src/blueprint/components/row_share.rs | 102 ++----- .../src/blueprint/components/visible.rs | 76 ++--- .../src/blueprint/components/visible_ext.rs | 4 +- crates/store/re_types/src/components/blob.rs | 148 ++-------- .../re_types/src/components/depth_meter.rs | 102 ++----- .../src/components/depth_meter_ext.rs | 8 +- .../src/components/disconnected_space.rs | 76 ++--- .../src/components/disconnected_space_ext.rs | 2 +- .../re_types/src/components/draw_order.rs | 102 ++----- .../re_types/src/components/draw_order_ext.rs | 16 +- .../re_types/src/components/marker_size.rs | 102 ++----- .../src/components/marker_size_ext.rs | 2 +- crates/store/re_types/src/components/mod.rs | 1 - .../store/re_types/src/components/radius.rs | 102 ++----- .../re_types/src/components/radius_ext.rs | 27 +- .../store/re_types/src/components/scalar.rs | 102 ++----- .../re_types/src/components/scalar_ext.rs | 4 +- .../re_types/src/components/stroke_width.rs | 102 ++----- .../src/components/stroke_width_ext.rs | 4 +- .../src/components/view_coordinates.rs | 196 ++----------- .../src/components/view_coordinates_ext.rs | 21 +- .../re_types/src/datatypes/.gitattributes | 3 +- crates/store/re_types/src/datatypes/blob.rs | 195 +++++++++++++ .../src/{components => datatypes}/blob_ext.rs | 9 + .../store/re_types/src/datatypes/bool_ext.rs | 12 - crates/store/re_types/src/datatypes/mod.rs | 9 +- .../re_types/src/datatypes/range2d_ext.rs | 7 +- .../re_types/src/datatypes/uvec4d_ext.rs | 2 +- .../store/re_types/src/datatypes/vec2d_ext.rs | 9 +- .../store/re_types/src/datatypes/vec3d_ext.rs | 2 +- .../store/re_types/src/datatypes/vec4d_ext.rs | 2 +- .../src/datatypes/view_coordinates.rs | 269 ++++++++++++++++++ .../src/datatypes/view_coordinates_ext.rs | 17 ++ crates/store/re_types/src/lib.rs | 6 +- crates/store/re_types/tests/arrows3d.rs | 4 +- crates/store/re_types/tests/box2d.rs | 6 +- crates/store/re_types/tests/box3d.rs | 4 +- crates/store/re_types/tests/clear.rs | 8 +- crates/store/re_types/tests/depth_image.rs | 2 +- .../re_types/tests/disconnected_space.rs | 6 +- crates/store/re_types/tests/line_strips2d.rs | 6 +- crates/store/re_types/tests/line_strips3d.rs | 4 +- crates/store/re_types/tests/points2d.rs | 6 +- crates/store/re_types/tests/points3d.rs | 4 +- .../src/blueprint/components/auto_layout.rs | 76 ++--- .../blueprint/components/auto_layout_ext.rs | 4 +- .../blueprint/components/auto_space_views.rs | 76 ++--- .../src/blueprint/components/grid_columns.rs | 102 ++----- .../components/visualizer_overrides.rs | 194 ++----------- .../src/blueprint/datatypes/.gitattributes | 5 + .../src/blueprint/datatypes/mod.rs | 6 + .../src/blueprint/datatypes/utf8list.rs | 241 ++++++++++++++++ .../src/blueprint/datatypes/utf8list_ext.rs | 8 + .../re_types_blueprint/src/blueprint/mod.rs | 2 + .../re_types_core/src/archetypes/clear_ext.rs | 4 +- .../src/components/clear_is_recursive.rs | 76 ++--- .../src/components/clear_is_recursive_ext.rs | 2 +- .../src/datatypes/.gitattributes | 2 + .../src/datatypes/bool.rs | 22 +- .../re_types_core/src/datatypes/bool_ext.rs | 17 ++ .../re_types_core/src/datatypes/float32.rs | 2 +- .../src/datatypes/float32_ext.rs | 7 + .../re_types_core/src/datatypes/float64.rs | 157 ++++++++++ .../src/datatypes/float64_ext.rs | 24 ++ .../store/re_types_core/src/datatypes/mod.rs | 8 + .../re_types_core/src/datatypes/uint32.rs | 2 +- .../re_types_core/src/datatypes/uint32_ext.rs | 17 ++ .../re_types_core/src/datatypes/uint64.rs | 2 +- .../re_types_core/src/datatypes/uint64_ext.rs | 17 ++ crates/store/re_types_core/src/lib.rs | 3 + .../re_blueprint_tree/src/blueprint_tree.rs | 2 +- .../re_context_menu/src/actions/show_hide.rs | 2 +- crates/viewer/re_data_ui/src/image.rs | 2 +- .../src/datatype_editors/bool_toggle.rs | 13 - .../src/datatype_editors/float_drag.rs | 21 +- .../re_edit_ui/src/datatype_editors/mod.rs | 7 +- crates/viewer/re_edit_ui/src/lib.rs | 18 +- .../re_selection_panel/src/selection_panel.rs | 2 +- .../src/space_view_class.rs | 2 +- .../src/contexts/transform_context.rs | 2 +- .../re_space_view_spatial/src/mesh_loader.rs | 4 +- crates/viewer/re_space_view_spatial/src/ui.rs | 4 +- .../viewer/re_space_view_spatial/src/ui_3d.rs | 2 +- .../src/visualizers/depth_images.rs | 2 +- .../src/visualizers/mod.rs | 6 +- .../src/line_visualizer_system.rs | 8 +- .../src/point_visualizer_system.rs | 8 +- .../src/space_view_class.rs | 2 +- .../src/space_view/view_query.rs | 3 +- .../re_viewport_blueprint/src/container.rs | 22 +- .../re_viewport_blueprint/src/space_view.rs | 4 +- .../src/space_view_contents.rs | 2 +- .../src/viewport_blueprint.rs | 8 +- .../reference/types/components/blob.md | 2 +- .../types/components/clear_is_recursive.md | 2 +- .../reference/types/components/depth_meter.md | 2 +- .../types/components/disconnected_space.md | 2 +- .../reference/types/components/draw_order.md | 2 +- .../reference/types/components/marker_size.md | 2 +- .../reference/types/components/radius.md | 2 +- .../reference/types/components/scalar.md | 2 +- .../types/components/stroke_width.md | 2 +- .../types/components/view_coordinates.md | 2 +- docs/content/reference/types/datatypes.md | 3 + .../reference/types/datatypes/.gitattributes | 3 + .../content/reference/types/datatypes/blob.md | 20 ++ .../content/reference/types/datatypes/bool.md | 4 + .../reference/types/datatypes/float32.md | 5 + .../reference/types/datatypes/float64.md | 20 ++ .../types/datatypes/view_coordinates.md | 35 +++ docs/snippets/all/tutorials/temporal_batch.rs | 2 +- examples/rust/incremental_logging/src/main.rs | 2 +- .../rerun/blueprint/components/.gitattributes | 7 - .../blueprint/components/auto_layout.cpp | 60 ---- .../blueprint/components/auto_layout.hpp | 45 +-- .../blueprint/components/auto_space_views.cpp | 62 ---- .../blueprint/components/auto_space_views.hpp | 46 +-- .../blueprint/components/column_share.cpp | 59 ---- .../blueprint/components/column_share.hpp | 47 ++- .../blueprint/components/grid_columns.cpp | 59 ---- .../blueprint/components/grid_columns.hpp | 47 ++- .../rerun/blueprint/components/row_share.cpp | 59 ---- .../rerun/blueprint/components/row_share.hpp | 47 ++- .../rerun/blueprint/components/visible.cpp | 60 ---- .../rerun/blueprint/components/visible.hpp | 42 +-- .../components/visualizer_overrides.hpp | 49 ++-- rerun_cpp/src/rerun/blueprint/datatypes.hpp | 1 + .../rerun/blueprint/datatypes/.gitattributes | 2 + .../utf8list.cpp} | 35 ++- .../rerun/blueprint/datatypes/utf8list.hpp | 60 ++++ rerun_cpp/src/rerun/components/.gitattributes | 10 - rerun_cpp/src/rerun/components/blob.hpp | 37 +-- .../rerun/components/clear_is_recursive.cpp | 60 ---- .../rerun/components/clear_is_recursive.hpp | 42 +-- .../src/rerun/components/depth_meter.cpp | 57 ---- .../src/rerun/components/depth_meter.hpp | 43 ++- .../rerun/components/disconnected_space.cpp | 60 ---- .../rerun/components/disconnected_space.hpp | 46 +-- rerun_cpp/src/rerun/components/draw_order.cpp | 57 ---- rerun_cpp/src/rerun/components/draw_order.hpp | 42 +-- .../src/rerun/components/marker_size.cpp | 57 ---- .../src/rerun/components/marker_size.hpp | 43 ++- rerun_cpp/src/rerun/components/radius.cpp | 57 ---- rerun_cpp/src/rerun/components/radius.hpp | 42 +-- rerun_cpp/src/rerun/components/scalar.hpp | 42 +-- .../src/rerun/components/stroke_width.cpp | 57 ---- .../src/rerun/components/stroke_width.hpp | 47 ++- .../src/rerun/components/view_coordinates.hpp | 44 ++- .../rerun/components/view_coordinates_ext.cpp | 6 +- rerun_cpp/src/rerun/datatypes.hpp | 3 + rerun_cpp/src/rerun/datatypes/.gitattributes | 6 + .../rerun/{components => datatypes}/blob.cpp | 16 +- rerun_cpp/src/rerun/datatypes/blob.hpp | 58 ++++ .../scalar.cpp => datatypes/float64.cpp} | 18 +- rerun_cpp/src/rerun/datatypes/float64.hpp | 61 ++++ .../view_coordinates.cpp | 17 +- .../src/rerun/datatypes/view_coordinates.hpp | 81 ++++++ .../rerun/datatypes/view_coordinates_ext.cpp | 24 ++ .../tests/archetypes/view_coordinates.cpp | 2 +- rerun_py/rerun_sdk/rerun/_image.py | 6 +- .../rerun/archetypes/arrows2d_ext.py | 4 +- .../rerun/archetypes/arrows3d_ext.py | 4 +- .../rerun_sdk/rerun/archetypes/asset3d_ext.py | 4 +- .../rerun_sdk/rerun/archetypes/boxes2d_ext.py | 6 +- .../rerun_sdk/rerun/archetypes/boxes3d_ext.py | 4 +- .../rerun_sdk/rerun/archetypes/depth_image.py | 4 +- .../archetypes/disconnected_space_ext.py | 4 +- rerun_py/rerun_sdk/rerun/archetypes/image.py | 2 +- .../rerun/archetypes/line_strips2d.py | 4 +- .../rerun/archetypes/line_strips3d.py | 2 +- .../rerun_sdk/rerun/archetypes/pinhole_ext.py | 4 +- .../rerun/archetypes/points2d_ext.py | 6 +- .../rerun/archetypes/points3d_ext.py | 4 +- rerun_py/rerun_sdk/rerun/archetypes/scalar.py | 4 +- .../rerun/archetypes/segmentation_image.py | 2 +- .../rerun_sdk/rerun/archetypes/series_line.py | 2 +- .../rerun/archetypes/series_point.py | 2 +- .../rerun/archetypes/view_coordinates.py | 4 +- rerun_py/rerun_sdk/rerun/blueprint/api.py | 10 +- .../archetypes/container_blueprint.py | 8 +- .../blueprint/archetypes/plot_legend_ext.py | 4 +- .../archetypes/space_view_blueprint.py | 2 +- .../archetypes/viewport_blueprint.py | 4 +- .../rerun/blueprint/components/__init__.py | 40 +-- .../rerun/blueprint/components/auto_layout.py | 50 +--- .../blueprint/components/auto_space_views.py | 56 +--- .../blueprint/components/column_share.py | 66 +---- .../blueprint/components/grid_columns.py | 69 +---- .../rerun/blueprint/components/row_share.py | 66 +---- .../rerun/blueprint/components/visible.py | 50 +--- .../components/visualizer_overrides.py | 114 +------- .../rerun_sdk/rerun/blueprint/containers.py | 11 +- .../rerun/blueprint/datatypes/.gitattributes | 1 + .../rerun/blueprint/datatypes/__init__.py | 6 + .../rerun/blueprint/datatypes/utf8list.py | 60 ++++ .../utf8list_ext.py} | 21 +- .../rerun/blueprint/views/bar_chart_view.py | 3 +- .../rerun/blueprint/views/spatial2d_view.py | 2 +- .../rerun/blueprint/views/spatial3d_view.py | 2 +- .../rerun/blueprint/views/tensor_view.py | 3 +- .../blueprint/views/text_document_view.py | 4 +- .../rerun/blueprint/views/text_log_view.py | 4 +- .../rerun/blueprint/views/time_series_view.py | 2 +- .../rerun_sdk/rerun/components/__init__.py | 58 +--- rerun_py/rerun_sdk/rerun/components/blob.py | 54 +--- .../rerun/components/clear_is_recursive.py | 66 +---- .../components/clear_is_recursive_ext.py | 22 ++ .../rerun_sdk/rerun/components/depth_meter.py | 55 +--- .../rerun/components/disconnected_space.py | 53 +--- .../components/disconnected_space_ext.py | 2 +- .../rerun_sdk/rerun/components/draw_order.py | 55 +--- .../rerun_sdk/rerun/components/marker_size.py | 55 +--- rerun_py/rerun_sdk/rerun/components/radius.py | 55 +--- .../rerun_sdk/rerun/components/radius_ext.py | 6 +- rerun_py/rerun_sdk/rerun/components/scalar.py | 55 +--- .../rerun/components/stroke_width.py | 55 +--- .../rerun/components/view_coordinates.py | 69 +---- .../rerun/components/view_coordinates_ext.py | 36 +-- .../rerun_sdk/rerun/datatypes/.gitattributes | 3 + .../rerun_sdk/rerun/datatypes/__init__.py | 24 ++ rerun_py/rerun_sdk/rerun/datatypes/blob.py | 66 +++++ .../{components => datatypes}/blob_ext.py | 4 +- rerun_py/rerun_sdk/rerun/datatypes/float32.py | 3 +- rerun_py/rerun_sdk/rerun/datatypes/float64.py | 69 +++++ .../rerun/datatypes/view_coordinates.py | 100 +++++++ .../rerun/datatypes/view_coordinates_ext.py | 46 +++ rerun_py/tests/unit/common_arrays.py | 19 +- rerun_py/tests/unit/test_arrows3d.py | 6 +- rerun_py/tests/unit/test_box2d.py | 8 +- rerun_py/tests/unit/test_box3d.py | 6 +- .../tests/unit/test_container_blueprint.py | 19 +- rerun_py/tests/unit/test_depth_image.py | 4 +- .../tests/unit/test_disconnected_space.py | 5 +- rerun_py/tests/unit/test_line_strips2d.py | 8 +- rerun_py/tests/unit/test_line_strips3d.py | 5 +- rerun_py/tests/unit/test_pinhole.py | 5 +- rerun_py/tests/unit/test_plot_legend.py | 3 +- rerun_py/tests/unit/test_points2d.py | 15 +- rerun_py/tests/unit/test_points3d.py | 12 +- .../tests/unit/test_space_view_blueprint.py | 5 +- rerun_py/tests/unit/test_view_coordinates.py | 3 +- .../tests/unit/test_viewport_blueprint.py | 9 +- .../tests/unit/test_visualizer_overrides.py | 3 +- tests/rust/test_api/src/main.rs | 2 +- tests/rust/test_temporal_batch/src/main.rs | 2 +- 280 files changed, 3229 insertions(+), 4094 deletions(-) create mode 100644 crates/store/re_types/definitions/rerun/blueprint/datatypes/utf8_list.fbs create mode 100644 crates/store/re_types/definitions/rerun/datatypes/blob.fbs create mode 100644 crates/store/re_types/definitions/rerun/datatypes/float64.fbs create mode 100644 crates/store/re_types/definitions/rerun/datatypes/view_coordinates.fbs create mode 100644 crates/store/re_types/src/datatypes/blob.rs rename crates/store/re_types/src/{components => datatypes}/blob_ext.rs (55%) delete mode 100644 crates/store/re_types/src/datatypes/bool_ext.rs create mode 100644 crates/store/re_types/src/datatypes/view_coordinates.rs create mode 100644 crates/store/re_types/src/datatypes/view_coordinates_ext.rs create mode 100644 crates/store/re_types_blueprint/src/blueprint/datatypes/.gitattributes create mode 100644 crates/store/re_types_blueprint/src/blueprint/datatypes/mod.rs create mode 100644 crates/store/re_types_blueprint/src/blueprint/datatypes/utf8list.rs create mode 100644 crates/store/re_types_blueprint/src/blueprint/datatypes/utf8list_ext.rs rename crates/store/{re_types => re_types_core}/src/datatypes/bool.rs (86%) create mode 100644 crates/store/re_types_core/src/datatypes/bool_ext.rs create mode 100644 crates/store/re_types_core/src/datatypes/float64.rs create mode 100644 crates/store/re_types_core/src/datatypes/float64_ext.rs create mode 100644 crates/store/re_types_core/src/datatypes/uint32_ext.rs create mode 100644 crates/store/re_types_core/src/datatypes/uint64_ext.rs create mode 100644 docs/content/reference/types/datatypes/blob.md create mode 100644 docs/content/reference/types/datatypes/float64.md create mode 100644 docs/content/reference/types/datatypes/view_coordinates.md delete mode 100644 rerun_cpp/src/rerun/blueprint/components/auto_layout.cpp delete mode 100644 rerun_cpp/src/rerun/blueprint/components/auto_space_views.cpp delete mode 100644 rerun_cpp/src/rerun/blueprint/components/column_share.cpp delete mode 100644 rerun_cpp/src/rerun/blueprint/components/grid_columns.cpp delete mode 100644 rerun_cpp/src/rerun/blueprint/components/row_share.cpp delete mode 100644 rerun_cpp/src/rerun/blueprint/components/visible.cpp rename rerun_cpp/src/rerun/blueprint/{components/visualizer_overrides.cpp => datatypes/utf8list.cpp} (61%) create mode 100644 rerun_cpp/src/rerun/blueprint/datatypes/utf8list.hpp delete mode 100644 rerun_cpp/src/rerun/components/clear_is_recursive.cpp delete mode 100644 rerun_cpp/src/rerun/components/depth_meter.cpp delete mode 100644 rerun_cpp/src/rerun/components/disconnected_space.cpp delete mode 100644 rerun_cpp/src/rerun/components/draw_order.cpp delete mode 100644 rerun_cpp/src/rerun/components/marker_size.cpp delete mode 100644 rerun_cpp/src/rerun/components/radius.cpp delete mode 100644 rerun_cpp/src/rerun/components/stroke_width.cpp rename rerun_cpp/src/rerun/{components => datatypes}/blob.cpp (77%) create mode 100644 rerun_cpp/src/rerun/datatypes/blob.hpp rename rerun_cpp/src/rerun/{components/scalar.cpp => datatypes/float64.cpp} (73%) create mode 100644 rerun_cpp/src/rerun/datatypes/float64.hpp rename rerun_cpp/src/rerun/{components => datatypes}/view_coordinates.cpp (73%) create mode 100644 rerun_cpp/src/rerun/datatypes/view_coordinates.hpp create mode 100644 rerun_cpp/src/rerun/datatypes/view_coordinates_ext.cpp create mode 100644 rerun_py/rerun_sdk/rerun/blueprint/datatypes/utf8list.py rename rerun_py/rerun_sdk/rerun/blueprint/{components/visualizer_overrides_ext.py => datatypes/utf8list_ext.py} (52%) create mode 100644 rerun_py/rerun_sdk/rerun/components/clear_is_recursive_ext.py create mode 100644 rerun_py/rerun_sdk/rerun/datatypes/blob.py rename rerun_py/rerun_sdk/rerun/{components => datatypes}/blob_ext.py (95%) create mode 100644 rerun_py/rerun_sdk/rerun/datatypes/float64.py create mode 100644 rerun_py/rerun_sdk/rerun/datatypes/view_coordinates.py create mode 100644 rerun_py/rerun_sdk/rerun/datatypes/view_coordinates_ext.py diff --git a/crates/build/re_dev_tools/src/build_examples/snippets.rs b/crates/build/re_dev_tools/src/build_examples/snippets.rs index a0e0c1908c44..02c0774f606d 100644 --- a/crates/build/re_dev_tools/src/build_examples/snippets.rs +++ b/crates/build/re_dev_tools/src/build_examples/snippets.rs @@ -91,13 +91,12 @@ fn collect_snippets_recursively( let name = path.file_stem().unwrap().to_str().unwrap().to_owned(); let config_key = path.strip_prefix(snippet_root_path)?.with_extension(""); - - let config_key = config_key.to_str().unwrap(); + let config_key = config_key.to_str().unwrap().replace('\\', "/"); let is_opted_out = config .opt_out .run - .get(config_key) + .get(&config_key) .is_some_and(|languages| languages.iter().any(|v| v == "py")); if is_opted_out { println!( @@ -130,7 +129,7 @@ fn collect_snippets_recursively( println!("Adding {}", path.display()); let extra_args: Vec = config .extra_args - .get(config_key) + .get(&config_key) .cloned() .unwrap_or_default() .into_iter() diff --git a/crates/build/re_types_builder/src/codegen/python/views.rs b/crates/build/re_types_builder/src/codegen/python/views.rs index 9fbe44c0d692..0d19d83e3d43 100644 --- a/crates/build/re_types_builder/src/codegen/python/views.rs +++ b/crates/build/re_types_builder/src/codegen/python/views.rs @@ -40,7 +40,7 @@ fn init_method(reporter: &Reporter, objects: &Objects, obj: &Object) -> String { origin: EntityPathLike = "/", contents: SpaceViewContentsLike = "$origin/**", name: Utf8Like | None = None, - visible: blueprint_components.VisibleLike | None = None, + visible: datatypes.BoolLike | None = None, defaults: list[Union[AsComponents, ComponentBatchLike]] = [], overrides: dict[EntityPathLike, list[ComponentBatchLike]] = {}, "# diff --git a/crates/build/re_types_builder/src/objects.rs b/crates/build/re_types_builder/src/objects.rs index 5be1fb74b234..962403308094 100644 --- a/crates/build/re_types_builder/src/objects.rs +++ b/crates/build/re_types_builder/src/objects.rs @@ -98,10 +98,11 @@ impl Objects { } } } - } else { - // Note that we *do* allow primitive fields on components for the moment. Not doing so creates a lot of bloat. - if obj.kind == ObjectKind::Archetype || obj.kind == ObjectKind::View { - reporter.error(virtpath, &obj.fqname, format!("Field {:?} s a primitive field of type {:?}. Primitive types are only allowed on DataTypes & Components.", field.fqname, field.typ)); + } else if obj.kind != ObjectKind::Datatype { + let is_enum_component = obj.kind == ObjectKind::Component && obj.is_enum(); // Enum components are allowed to have no datatype. + let is_test_component = obj.kind == ObjectKind::Component && obj.is_testing(); // Test components are allowed to have datatypes for the moment. TODO(andreas): Should clean this up as well! + if !is_enum_component && !is_test_component { + reporter.error(virtpath, &obj.fqname, format!("Field {:?} s a primitive field of type {:?}. Primitive types are only allowed on DataTypes.", field.fqname, field.typ)); } } diff --git a/crates/store/re_chunk_store/tests/memory_test.rs b/crates/store/re_chunk_store/tests/memory_test.rs index 040281af9b4a..1eef7c0592fc 100644 --- a/crates/store/re_chunk_store/tests/memory_test.rs +++ b/crates/store/re_chunk_store/tests/memory_test.rs @@ -100,7 +100,7 @@ fn scalar_memory_overhead() { let entity_path = re_log_types::entity_path!("scalar"); let timepoint = TimePoint::default().with(Timeline::new("log_time", TimeType::Time), i as i64); - let scalars = Scalar::to_arrow([Scalar(i as f64)]).unwrap(); + let scalars = Scalar::to_arrow([Scalar::from(i as f64)]).unwrap(); let row = PendingRow::new( timepoint, diff --git a/crates/store/re_entity_db/tests/time_histograms.rs b/crates/store/re_entity_db/tests/time_histograms.rs index 1712e627a7ed..a83fd10b8eec 100644 --- a/crates/store/re_entity_db/tests/time_histograms.rs +++ b/crates/store/re_entity_db/tests/time_histograms.rs @@ -465,7 +465,7 @@ fn time_histograms() -> anyhow::Result<()> { TimePoint::from_iter([ (timeline_frame, 1000), // ]), - [&[ClearIsRecursive(true)] as _], + [&[ClearIsRecursive(true.into())] as _], ) .build()? }; diff --git a/crates/store/re_query/src/latest_at/query.rs b/crates/store/re_query/src/latest_at/query.rs index 43fe7249639b..df5c90d1a3b4 100644 --- a/crates/store/re_query/src/latest_at/query.rs +++ b/crates/store/re_query/src/latest_at/query.rs @@ -98,7 +98,7 @@ impl Caches { #[allow(clippy::collapsible_if)] // readability if clear_entity_path == *entity_path || cached.mono::(&crate::PromiseResolver {}) - == Some(ClearIsRecursive(true)) + == Some(ClearIsRecursive(true.into())) { if compare_indices(*cached.index(), max_clear_index) == std::cmp::Ordering::Greater diff --git a/crates/store/re_types/definitions/rerun/blueprint.fbs b/crates/store/re_types/definitions/rerun/blueprint.fbs index 9e5f1b5eba1c..d6ddcb840da7 100644 --- a/crates/store/re_types/definitions/rerun/blueprint.fbs +++ b/crates/store/re_types/definitions/rerun/blueprint.fbs @@ -1,4 +1,5 @@ include "./blueprint/datatypes/tensor_dimension_index_slider.fbs"; +include "./blueprint/datatypes/utf8_list.fbs"; include "./blueprint/components/active_tab.fbs"; include "./blueprint/components/auto_layout.fbs"; diff --git a/crates/store/re_types/definitions/rerun/blueprint/components/auto_layout.fbs b/crates/store/re_types/definitions/rerun/blueprint/components/auto_layout.fbs index 83c2228fb3a4..14e6aa0ca8e8 100644 --- a/crates/store/re_types/definitions/rerun/blueprint/components/auto_layout.fbs +++ b/crates/store/re_types/definitions/rerun/blueprint/components/auto_layout.fbs @@ -19,5 +19,5 @@ struct AutoLayout ( "attr.rust.repr": "transparent", "attr.rust.tuple_struct" ) { - auto_layout: bool (order: 100); + auto_layout: rerun.datatypes.Bool (order: 100); } diff --git a/crates/store/re_types/definitions/rerun/blueprint/components/auto_space_views.fbs b/crates/store/re_types/definitions/rerun/blueprint/components/auto_space_views.fbs index d24b3804da6b..1b40eab00e40 100644 --- a/crates/store/re_types/definitions/rerun/blueprint/components/auto_space_views.fbs +++ b/crates/store/re_types/definitions/rerun/blueprint/components/auto_space_views.fbs @@ -19,5 +19,5 @@ struct AutoSpaceViews ( "attr.rust.repr": "transparent", "attr.rust.tuple_struct" ) { - auto_space_views: bool (order: 100); + auto_space_views: rerun.datatypes.Bool (order: 100); } diff --git a/crates/store/re_types/definitions/rerun/blueprint/components/column_share.fbs b/crates/store/re_types/definitions/rerun/blueprint/components/column_share.fbs index 7025b00974c0..b8d8feab0138 100644 --- a/crates/store/re_types/definitions/rerun/blueprint/components/column_share.fbs +++ b/crates/store/re_types/definitions/rerun/blueprint/components/column_share.fbs @@ -18,5 +18,5 @@ table ColumnShare ( "attr.rust.derive": "Default" ) { /// The layout shares of a column in the container. - share: float (order: 100); + share: rerun.datatypes.Float32 (order: 100); } diff --git a/crates/store/re_types/definitions/rerun/blueprint/components/grid_columns.fbs b/crates/store/re_types/definitions/rerun/blueprint/components/grid_columns.fbs index 0f3143a893f5..c3c6ac37a7d0 100644 --- a/crates/store/re_types/definitions/rerun/blueprint/components/grid_columns.fbs +++ b/crates/store/re_types/definitions/rerun/blueprint/components/grid_columns.fbs @@ -16,5 +16,5 @@ table GridColumns ( "attr.rust.override_crate": "re_types_blueprint" ) { /// The number of columns. - columns: uint (order: 100); + columns: rerun.datatypes.UInt32 (order: 100); } diff --git a/crates/store/re_types/definitions/rerun/blueprint/components/row_share.fbs b/crates/store/re_types/definitions/rerun/blueprint/components/row_share.fbs index 7f6930f13eee..8c75b0a11b5f 100644 --- a/crates/store/re_types/definitions/rerun/blueprint/components/row_share.fbs +++ b/crates/store/re_types/definitions/rerun/blueprint/components/row_share.fbs @@ -17,5 +17,5 @@ table RowShare ( "attr.rust.derive": "Default" ) { /// The layout share of a row in the container. - share: float (order: 100); + share: rerun.datatypes.Float32 (order: 100); } diff --git a/crates/store/re_types/definitions/rerun/blueprint/components/visible.fbs b/crates/store/re_types/definitions/rerun/blueprint/components/visible.fbs index 66c674e31f8f..65f5989b40b4 100644 --- a/crates/store/re_types/definitions/rerun/blueprint/components/visible.fbs +++ b/crates/store/re_types/definitions/rerun/blueprint/components/visible.fbs @@ -18,5 +18,5 @@ struct Visible ( "attr.rust.repr": "transparent", "attr.rust.tuple_struct" ) { - visible: bool (order: 100); + visible: rerun.datatypes.Bool (order: 100); } diff --git a/crates/store/re_types/definitions/rerun/blueprint/components/visualizer_overrides.fbs b/crates/store/re_types/definitions/rerun/blueprint/components/visualizer_overrides.fbs index 0de1bfa62154..af88c15eb6c2 100644 --- a/crates/store/re_types/definitions/rerun/blueprint/components/visualizer_overrides.fbs +++ b/crates/store/re_types/definitions/rerun/blueprint/components/visualizer_overrides.fbs @@ -51,5 +51,5 @@ table VisualizerOverrides ( /// - SegmentationImage /// - SeriesLine /// - SeriesPoint - visualizers: [string] (order: 100); + visualizers: rerun.blueprint.datatypes.Utf8List (order: 100); } diff --git a/crates/store/re_types/definitions/rerun/blueprint/datatypes/utf8_list.fbs b/crates/store/re_types/definitions/rerun/blueprint/datatypes/utf8_list.fbs new file mode 100644 index 000000000000..587abc03af76 --- /dev/null +++ b/crates/store/re_types/definitions/rerun/blueprint/datatypes/utf8_list.fbs @@ -0,0 +1,17 @@ +namespace rerun.blueprint.datatypes; + +/// A list of strings of text, encoded as UTF-8. +// +// NOTE: Apache Arrow uses UTF-8 encoding of its String type, as does Rust. +table Utf8List ( + "attr.docs.unreleased", + "attr.arrow.transparent", + "attr.python.aliases": "Sequence[str]", + "attr.rerun.scope": "blueprint", + "attr.rust.derive": "PartialEq, Eq, PartialOrd, Ord, Default", + "attr.rust.repr": "transparent", + "attr.rust.tuple_struct", + "attr.rust.override_crate": "re_types_blueprint" +) { + value: [string] (order: 100); +} diff --git a/crates/store/re_types/definitions/rerun/components/blob.fbs b/crates/store/re_types/definitions/rerun/components/blob.fbs index 12b10e775eb1..513c7e1cbcb6 100644 --- a/crates/store/re_types/definitions/rerun/components/blob.fbs +++ b/crates/store/re_types/definitions/rerun/components/blob.fbs @@ -14,8 +14,8 @@ table Blob ( "attr.arrow.transparent", "attr.python.aliases": "bytes, npt.NDArray[np.uint8]", "attr.python.array_aliases": "bytes, npt.NDArray[np.uint8]", - "attr.rust.derive": "PartialEq, Eq", + "attr.rust.derive": "Default, PartialEq, Eq", "attr.rust.repr": "transparent" ) { - data: [ubyte] (order: 100); + data: rerun.datatypes.Blob (order: 100); } diff --git a/crates/store/re_types/definitions/rerun/components/clear_is_recursive.fbs b/crates/store/re_types/definitions/rerun/components/clear_is_recursive.fbs index ca0a5bf49d3f..608597d35a9a 100644 --- a/crates/store/re_types/definitions/rerun/components/clear_is_recursive.fbs +++ b/crates/store/re_types/definitions/rerun/components/clear_is_recursive.fbs @@ -19,5 +19,5 @@ struct ClearIsRecursive ( "attr.rust.tuple_struct" ) { /// If true, also clears all recursive children entities. - recursive: bool (order: 100); + recursive: rerun.datatypes.Bool (order: 100); } diff --git a/crates/store/re_types/definitions/rerun/components/depth_meter.fbs b/crates/store/re_types/definitions/rerun/components/depth_meter.fbs index dc6500c065fe..1c2d6355f99b 100644 --- a/crates/store/re_types/definitions/rerun/components/depth_meter.fbs +++ b/crates/store/re_types/definitions/rerun/components/depth_meter.fbs @@ -23,5 +23,5 @@ struct DepthMeter ( "attr.rust.derive": "Copy, PartialEq, PartialOrd, bytemuck::Pod, bytemuck::Zeroable", "attr.rust.repr": "transparent" ) { - value: float (order: 100); + value: rerun.datatypes.Float32 (order: 100); } diff --git a/crates/store/re_types/definitions/rerun/components/disconnected_space.fbs b/crates/store/re_types/definitions/rerun/components/disconnected_space.fbs index 8138b358d7b2..ff444c75c4b3 100644 --- a/crates/store/re_types/definitions/rerun/components/disconnected_space.fbs +++ b/crates/store/re_types/definitions/rerun/components/disconnected_space.fbs @@ -24,5 +24,5 @@ struct DisconnectedSpace ( /// /// Set to true to disconnect the entity from its parent. /// Set to false to disable the effects of this component, (re-)connecting the entity to its parent again. - is_disconnected: bool (order: 100); + is_disconnected: rerun.datatypes.Bool (order: 100); } diff --git a/crates/store/re_types/definitions/rerun/components/draw_order.fbs b/crates/store/re_types/definitions/rerun/components/draw_order.fbs index 47abf64ed70c..edb64522a308 100644 --- a/crates/store/re_types/definitions/rerun/components/draw_order.fbs +++ b/crates/store/re_types/definitions/rerun/components/draw_order.fbs @@ -21,5 +21,5 @@ struct DrawOrder ( "attr.rust.derive": "Copy", "attr.rust.repr": "transparent" ) { - value: float (order: 100); + value: rerun.datatypes.Float32 (order: 100); } diff --git a/crates/store/re_types/definitions/rerun/components/marker_size.fbs b/crates/store/re_types/definitions/rerun/components/marker_size.fbs index 620b3411865d..7b42cc84627d 100644 --- a/crates/store/re_types/definitions/rerun/components/marker_size.fbs +++ b/crates/store/re_types/definitions/rerun/components/marker_size.fbs @@ -16,5 +16,5 @@ struct MarkerSize ( "attr.rust.derive": "Copy, PartialEq, PartialOrd, bytemuck::Pod, bytemuck::Zeroable", "attr.rust.repr": "transparent" ) { - value: float (order: 100); + value: rerun.datatypes.Float32 (order: 100); } diff --git a/crates/store/re_types/definitions/rerun/components/radius.fbs b/crates/store/re_types/definitions/rerun/components/radius.fbs index 597cd6d58d68..09512dce4405 100644 --- a/crates/store/re_types/definitions/rerun/components/radius.fbs +++ b/crates/store/re_types/definitions/rerun/components/radius.fbs @@ -23,5 +23,5 @@ struct Radius ( "attr.rust.derive": "Copy, PartialEq, PartialOrd, bytemuck::Pod, bytemuck::Zeroable", "attr.rust.repr": "transparent" ) { - value: float (order: 100); + value: rerun.datatypes.Float32 (order: 100); } diff --git a/crates/store/re_types/definitions/rerun/components/scalar.fbs b/crates/store/re_types/definitions/rerun/components/scalar.fbs index d171b202528b..0cb3231ca211 100644 --- a/crates/store/re_types/definitions/rerun/components/scalar.fbs +++ b/crates/store/re_types/definitions/rerun/components/scalar.fbs @@ -18,5 +18,5 @@ struct Scalar ( "attr.rust.derive": "Copy, PartialEq, PartialOrd, bytemuck::Pod, bytemuck::Zeroable", "attr.rust.repr": "transparent" ) { - value: double (order: 100); + value: rerun.datatypes.Float64 (order: 100); } diff --git a/crates/store/re_types/definitions/rerun/components/stroke_width.fbs b/crates/store/re_types/definitions/rerun/components/stroke_width.fbs index df747b7ccbfd..b380626f93db 100644 --- a/crates/store/re_types/definitions/rerun/components/stroke_width.fbs +++ b/crates/store/re_types/definitions/rerun/components/stroke_width.fbs @@ -16,5 +16,5 @@ struct StrokeWidth ( "attr.rust.derive": "Copy, PartialEq, PartialOrd, bytemuck::Pod, bytemuck::Zeroable", "attr.rust.repr": "transparent" ) { - width: float (order: 100); + width: rerun.datatypes.Float32 (order: 100); } diff --git a/crates/store/re_types/definitions/rerun/components/view_coordinates.fbs b/crates/store/re_types/definitions/rerun/components/view_coordinates.fbs index 8c52db46e6cf..bd83fcf80bfc 100644 --- a/crates/store/re_types/definitions/rerun/components/view_coordinates.fbs +++ b/crates/store/re_types/definitions/rerun/components/view_coordinates.fbs @@ -39,8 +39,9 @@ struct ViewCoordinates ( "attr.python.aliases": "npt.ArrayLike", "attr.python.array_aliases": "npt.ArrayLike", "attr.rust.derive": "Copy, PartialEq, Eq, bytemuck::Pod, bytemuck::Zeroable", - "attr.rust.repr": "transparent" + "attr.rust.repr": "transparent", + "attr.cpp.no_field_ctors" ) { /// The directions of the [x, y, z] axes. - coordinates: [ubyte: 3] (order: 100); + coordinates: rerun.datatypes.ViewCoordinates (order: 100); } diff --git a/crates/store/re_types/definitions/rerun/datatypes.fbs b/crates/store/re_types/definitions/rerun/datatypes.fbs index cff57723cc7b..4ca2def9345c 100644 --- a/crates/store/re_types/definitions/rerun/datatypes.fbs +++ b/crates/store/re_types/definitions/rerun/datatypes.fbs @@ -1,11 +1,13 @@ include "./datatypes/angle.fbs"; include "./datatypes/annotation_info.fbs"; +include "./datatypes/blob.fbs"; include "./datatypes/bool.fbs"; include "./datatypes/class_description_map_elem.fbs"; include "./datatypes/class_description.fbs"; include "./datatypes/class_id.fbs"; include "./datatypes/entity_path.fbs"; include "./datatypes/float32.fbs"; +include "./datatypes/float64.fbs"; include "./datatypes/keypoint_id.fbs"; include "./datatypes/keypoint_pair.fbs"; include "./datatypes/mat3x3.fbs"; @@ -36,6 +38,7 @@ include "./datatypes/uvec4d.fbs"; include "./datatypes/vec2d.fbs"; include "./datatypes/vec3d.fbs"; include "./datatypes/vec4d.fbs"; +include "./datatypes/view_coordinates.fbs"; include "./datatypes/visible_time_range.fbs"; namespace rerun.datatypes; diff --git a/crates/store/re_types/definitions/rerun/datatypes/blob.fbs b/crates/store/re_types/definitions/rerun/datatypes/blob.fbs new file mode 100644 index 000000000000..3cd162a97c0d --- /dev/null +++ b/crates/store/re_types/definitions/rerun/datatypes/blob.fbs @@ -0,0 +1,24 @@ +include "arrow/attributes.fbs"; +include "python/attributes.fbs"; +include "rust/attributes.fbs"; +include "docs/attributes.fbs"; +include "rerun/attributes.fbs"; + +include "rerun/datatypes.fbs"; + +namespace rerun.datatypes; + +// --- + +/// A binary blob of data. +table Blob ( + "attr.docs.unreleased", + "attr.arrow.transparent", + "attr.python.aliases": "bytes, npt.NDArray[np.uint8]", + "attr.python.array_aliases": "bytes, npt.NDArray[np.uint8]", + "attr.rust.derive": "PartialEq, Eq", + "attr.rust.repr": "transparent", + "attr.rust.tuple_struct" +) { + data: [ubyte] (order: 100); +} diff --git a/crates/store/re_types/definitions/rerun/datatypes/bool.fbs b/crates/store/re_types/definitions/rerun/datatypes/bool.fbs index 36cb57a0246b..1295551efc33 100644 --- a/crates/store/re_types/definitions/rerun/datatypes/bool.fbs +++ b/crates/store/re_types/definitions/rerun/datatypes/bool.fbs @@ -15,6 +15,7 @@ struct Bool ( "attr.arrow.transparent", "attr.python.aliases": "bool", "attr.rust.derive": "Copy, Default, PartialEq, Eq, PartialOrd, Ord", + "attr.rust.override_crate": "re_types_core", "attr.rust.repr": "transparent", "attr.rust.tuple_struct" ) { diff --git a/crates/store/re_types/definitions/rerun/datatypes/float32.fbs b/crates/store/re_types/definitions/rerun/datatypes/float32.fbs index bcd8e1590d44..03a2638073ab 100644 --- a/crates/store/re_types/definitions/rerun/datatypes/float32.fbs +++ b/crates/store/re_types/definitions/rerun/datatypes/float32.fbs @@ -9,7 +9,8 @@ namespace rerun.datatypes; struct Float32 ( "attr.arrow.transparent", "attr.python.aliases": "float", - "attr.rust.derive": "Copy, PartialEq, PartialOrd, bytemuck::Pod, bytemuck::Zeroable", + "attr.python.array_aliases": "npt.NDArray[Any], npt.ArrayLike, Sequence[Sequence[float]], Sequence[float]", + "attr.rust.derive": "Default, Copy, PartialEq, PartialOrd, bytemuck::Pod, bytemuck::Zeroable", "attr.rust.override_crate": "re_types_core", "attr.rust.repr": "transparent", "attr.rust.tuple_struct" diff --git a/crates/store/re_types/definitions/rerun/datatypes/float64.fbs b/crates/store/re_types/definitions/rerun/datatypes/float64.fbs new file mode 100644 index 000000000000..750137bc0a54 --- /dev/null +++ b/crates/store/re_types/definitions/rerun/datatypes/float64.fbs @@ -0,0 +1,20 @@ +include "arrow/attributes.fbs"; +include "python/attributes.fbs"; +include "fbs/attributes.fbs"; +include "rust/attributes.fbs"; + +namespace rerun.datatypes; + +/// A double-precision 64-bit IEEE 754 floating point number. +struct Float64 ( + "attr.docs.unreleased", + "attr.arrow.transparent", + "attr.python.aliases": "float", + "attr.python.array_aliases": "npt.NDArray[Any], npt.ArrayLike, Sequence[Sequence[float]], Sequence[float]", + "attr.rust.derive": "Default, Copy, PartialEq, PartialOrd, bytemuck::Pod, bytemuck::Zeroable", + "attr.rust.override_crate": "re_types_core", + "attr.rust.repr": "transparent", + "attr.rust.tuple_struct" +) { + value: double (order: 100); +} diff --git a/crates/store/re_types/definitions/rerun/datatypes/uint32.fbs b/crates/store/re_types/definitions/rerun/datatypes/uint32.fbs index fa3cd2d479b3..7e5dc8a18f56 100644 --- a/crates/store/re_types/definitions/rerun/datatypes/uint32.fbs +++ b/crates/store/re_types/definitions/rerun/datatypes/uint32.fbs @@ -11,7 +11,8 @@ struct UInt32 ( "attr.arrow.transparent", "attr.python.aliases": "int", "attr.python.array_aliases": "int, npt.NDArray[np.uint32]", - "attr.rust.derive": "Copy, PartialEq, Eq, PartialOrd, Ord", + "attr.rust.derive": "Default, Copy, PartialEq, Eq, PartialOrd, Ord", + "attr.rust.override_crate": "re_types_core", "attr.rust.override_crate": "re_types_core", "attr.rust.tuple_struct" ) { diff --git a/crates/store/re_types/definitions/rerun/datatypes/uint64.fbs b/crates/store/re_types/definitions/rerun/datatypes/uint64.fbs index 1fb55ad2abe0..b888328af2fc 100644 --- a/crates/store/re_types/definitions/rerun/datatypes/uint64.fbs +++ b/crates/store/re_types/definitions/rerun/datatypes/uint64.fbs @@ -11,7 +11,7 @@ struct UInt64 ( "attr.arrow.transparent", "attr.python.aliases": "int", "attr.python.array_aliases": "int, npt.NDArray[np.uint64]", - "attr.rust.derive": "Copy, PartialEq, Eq, PartialOrd, Ord", + "attr.rust.derive": "Default, Copy, PartialEq, Eq, PartialOrd, Ord", "attr.rust.override_crate": "re_types_core", "attr.rust.tuple_struct" ) { diff --git a/crates/store/re_types/definitions/rerun/datatypes/view_coordinates.fbs b/crates/store/re_types/definitions/rerun/datatypes/view_coordinates.fbs new file mode 100644 index 000000000000..82f014b889e7 --- /dev/null +++ b/crates/store/re_types/definitions/rerun/datatypes/view_coordinates.fbs @@ -0,0 +1,49 @@ +include "arrow/attributes.fbs"; +include "python/attributes.fbs"; +include "rust/attributes.fbs"; + +include "rerun/attributes.fbs"; + +namespace rerun.datatypes; + + +// TODO(#6320) +/* +enum ViewDir: byte { + Up = 1, + Down = 2, + Right = 3, + Left = 4, + Forward = 5, + Back = 6, +} +*/ + +/// How we interpret the coordinate system of an entity/space. +/// +/// For instance: What is "up"? What does the Z axis mean? Is this right-handed or left-handed? +/// +/// The three coordinates are always ordered as [x, y, z]. +/// +/// For example [Right, Down, Forward] means that the X axis points to the right, the Y axis points +/// down, and the Z axis points forward. +/// +/// The following constants are used to represent the different directions: +/// * Up = 1 +/// * Down = 2 +/// * Right = 3 +/// * Left = 4 +/// * Forward = 5 +/// * Back = 6 +struct ViewCoordinates ( + "attr.docs.unreleased", + "attr.arrow.transparent", + "attr.python.aliases": "npt.ArrayLike", + "attr.python.array_aliases": "npt.ArrayLike", + "attr.rust.derive": "Copy, PartialEq, Eq, bytemuck::Pod, bytemuck::Zeroable", + "attr.rust.repr": "transparent", + "attr.rust.tuple_struct" +) { + /// The directions of the [x, y, z] axes. + coordinates: [ubyte: 3] (order: 100); +} diff --git a/crates/store/re_types/src/archetypes/points3d_ext.rs b/crates/store/re_types/src/archetypes/points3d_ext.rs index 8e499c2fafce..d6fa94d13f84 100644 --- a/crates/store/re_types/src/archetypes/points3d_ext.rs +++ b/crates/store/re_types/src/archetypes/points3d_ext.rs @@ -185,7 +185,7 @@ fn from_ply(ply: ply_rs::ply::Ply) -> Points3D { if let Some(radius) = props.get(PROP_RADIUS).and_then(f32) { props.remove(PROP_RADIUS); - this.radius = Some(Radius(radius)); + this.radius = Some(Radius::from(radius)); } if let Some(label) = props.get(PROP_LABEL).and_then(string) { @@ -249,7 +249,9 @@ fn from_ply(ply: ply_rs::ply::Ply) -> Points3D { } if radii.iter().any(|opt| opt.is_some()) { // If some radii have been specified but not others, default the unspecified ones to 1.0. - let radii = radii.into_iter().map(|opt| opt.unwrap_or(Radius(1.0))); + let radii = radii + .into_iter() + .map(|opt| opt.unwrap_or(Radius::from(1.0))); arch = arch.with_radii(radii); } if labels.iter().any(|opt| opt.is_some()) { diff --git a/crates/store/re_types/src/blueprint/components/column_share.rs b/crates/store/re_types/src/blueprint/components/column_share.rs index 213867a30a13..33f5f40dcffa 100644 --- a/crates/store/re_types/src/blueprint/components/column_share.rs +++ b/crates/store/re_types/src/blueprint/components/column_share.rs @@ -22,7 +22,7 @@ use ::re_types_core::{DeserializationError, DeserializationResult}; #[derive(Clone, Debug, Default)] pub struct ColumnShare( /// The layout shares of a column in the container. - pub f32, + pub crate::datatypes::Float32, ); impl ::re_types_core::SizeBytes for ColumnShare { @@ -33,36 +33,35 @@ impl ::re_types_core::SizeBytes for ColumnShare { #[inline] fn is_pod() -> bool { - ::is_pod() + ::is_pod() } } -impl From for ColumnShare { - #[inline] - fn from(share: f32) -> Self { - Self(share) +impl> From for ColumnShare { + fn from(v: T) -> Self { + Self(v.into()) } } -impl From for f32 { +impl std::borrow::Borrow for ColumnShare { #[inline] - fn from(value: ColumnShare) -> Self { - value.0 + fn borrow(&self) -> &crate::datatypes::Float32 { + &self.0 } } impl std::ops::Deref for ColumnShare { - type Target = f32; + type Target = crate::datatypes::Float32; #[inline] - fn deref(&self) -> &f32 { + fn deref(&self) -> &crate::datatypes::Float32 { &self.0 } } impl std::ops::DerefMut for ColumnShare { #[inline] - fn deref_mut(&mut self) -> &mut f32 { + fn deref_mut(&mut self) -> &mut crate::datatypes::Float32 { &mut self.0 } } @@ -79,9 +78,7 @@ impl ::re_types_core::Loggable for ColumnShare { #[inline] fn arrow_datatype() -> arrow2::datatypes::DataType { - #![allow(clippy::wildcard_imports)] - use arrow2::datatypes::*; - DataType::Float32 + crate::datatypes::Float32::arrow_datatype() } fn to_arrow_opt<'a>( @@ -90,29 +87,12 @@ impl ::re_types_core::Loggable for ColumnShare { where Self: Clone + 'a, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, datatypes::*}; - Ok({ - let (somes, data0): (Vec<_>, Vec<_>) = data - .into_iter() - .map(|datum| { - let datum: Option<::std::borrow::Cow<'a, Self>> = datum.map(Into::into); - let datum = datum.map(|datum| datum.into_owned().0); - (datum.is_some(), datum) - }) - .unzip(); - let data0_bitmap: Option = { - let any_nones = somes.iter().any(|some| !*some); - any_nones.then(|| somes.into()) - }; - PrimitiveArray::new( - Self::arrow_datatype(), - data0.into_iter().map(|v| v.unwrap_or_default()).collect(), - data0_bitmap, - ) - .boxed() - }) + crate::datatypes::Float32::to_arrow_opt(data.into_iter().map(|datum| { + datum.map(|datum| match datum.into() { + ::std::borrow::Cow::Borrowed(datum) => ::std::borrow::Cow::Borrowed(&datum.0), + ::std::borrow::Cow::Owned(datum) => ::std::borrow::Cow::Owned(datum.0), + }) + })) } fn from_arrow_opt( @@ -121,25 +101,8 @@ impl ::re_types_core::Loggable for ColumnShare { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - Ok(arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = Self::arrow_datatype(); - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.blueprint.components.ColumnShare#share")? - .into_iter() - .map(|opt| opt.copied()) - .map(|v| v.ok_or_else(DeserializationError::missing_data)) - .map(|res| res.map(|v| Some(Self(v)))) - .collect::>>>() - .with_context("rerun.blueprint.components.ColumnShare#share") - .with_context("rerun.blueprint.components.ColumnShare")?) + crate::datatypes::Float32::from_arrow_opt(arrow_data) + .map(|v| v.into_iter().map(|v| v.map(Self)).collect()) } #[inline] @@ -147,29 +110,6 @@ impl ::re_types_core::Loggable for ColumnShare { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - if let Some(validity) = arrow_data.validity() { - if validity.unset_bits() != 0 { - return Err(DeserializationError::missing_data()); - } - } - Ok({ - let slice = arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = DataType::Float32; - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.blueprint.components.ColumnShare#share")? - .values() - .as_slice(); - { - slice.iter().copied().map(Self).collect::>() - } - }) + crate::datatypes::Float32::from_arrow(arrow_data).map(|v| v.into_iter().map(Self).collect()) } } diff --git a/crates/store/re_types/src/blueprint/components/row_share.rs b/crates/store/re_types/src/blueprint/components/row_share.rs index 19e94fae8059..79c7b788333c 100644 --- a/crates/store/re_types/src/blueprint/components/row_share.rs +++ b/crates/store/re_types/src/blueprint/components/row_share.rs @@ -22,7 +22,7 @@ use ::re_types_core::{DeserializationError, DeserializationResult}; #[derive(Clone, Debug, Default)] pub struct RowShare( /// The layout share of a row in the container. - pub f32, + pub crate::datatypes::Float32, ); impl ::re_types_core::SizeBytes for RowShare { @@ -33,36 +33,35 @@ impl ::re_types_core::SizeBytes for RowShare { #[inline] fn is_pod() -> bool { - ::is_pod() + ::is_pod() } } -impl From for RowShare { - #[inline] - fn from(share: f32) -> Self { - Self(share) +impl> From for RowShare { + fn from(v: T) -> Self { + Self(v.into()) } } -impl From for f32 { +impl std::borrow::Borrow for RowShare { #[inline] - fn from(value: RowShare) -> Self { - value.0 + fn borrow(&self) -> &crate::datatypes::Float32 { + &self.0 } } impl std::ops::Deref for RowShare { - type Target = f32; + type Target = crate::datatypes::Float32; #[inline] - fn deref(&self) -> &f32 { + fn deref(&self) -> &crate::datatypes::Float32 { &self.0 } } impl std::ops::DerefMut for RowShare { #[inline] - fn deref_mut(&mut self) -> &mut f32 { + fn deref_mut(&mut self) -> &mut crate::datatypes::Float32 { &mut self.0 } } @@ -79,9 +78,7 @@ impl ::re_types_core::Loggable for RowShare { #[inline] fn arrow_datatype() -> arrow2::datatypes::DataType { - #![allow(clippy::wildcard_imports)] - use arrow2::datatypes::*; - DataType::Float32 + crate::datatypes::Float32::arrow_datatype() } fn to_arrow_opt<'a>( @@ -90,29 +87,12 @@ impl ::re_types_core::Loggable for RowShare { where Self: Clone + 'a, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, datatypes::*}; - Ok({ - let (somes, data0): (Vec<_>, Vec<_>) = data - .into_iter() - .map(|datum| { - let datum: Option<::std::borrow::Cow<'a, Self>> = datum.map(Into::into); - let datum = datum.map(|datum| datum.into_owned().0); - (datum.is_some(), datum) - }) - .unzip(); - let data0_bitmap: Option = { - let any_nones = somes.iter().any(|some| !*some); - any_nones.then(|| somes.into()) - }; - PrimitiveArray::new( - Self::arrow_datatype(), - data0.into_iter().map(|v| v.unwrap_or_default()).collect(), - data0_bitmap, - ) - .boxed() - }) + crate::datatypes::Float32::to_arrow_opt(data.into_iter().map(|datum| { + datum.map(|datum| match datum.into() { + ::std::borrow::Cow::Borrowed(datum) => ::std::borrow::Cow::Borrowed(&datum.0), + ::std::borrow::Cow::Owned(datum) => ::std::borrow::Cow::Owned(datum.0), + }) + })) } fn from_arrow_opt( @@ -121,25 +101,8 @@ impl ::re_types_core::Loggable for RowShare { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - Ok(arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = Self::arrow_datatype(); - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.blueprint.components.RowShare#share")? - .into_iter() - .map(|opt| opt.copied()) - .map(|v| v.ok_or_else(DeserializationError::missing_data)) - .map(|res| res.map(|v| Some(Self(v)))) - .collect::>>>() - .with_context("rerun.blueprint.components.RowShare#share") - .with_context("rerun.blueprint.components.RowShare")?) + crate::datatypes::Float32::from_arrow_opt(arrow_data) + .map(|v| v.into_iter().map(|v| v.map(Self)).collect()) } #[inline] @@ -147,29 +110,6 @@ impl ::re_types_core::Loggable for RowShare { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - if let Some(validity) = arrow_data.validity() { - if validity.unset_bits() != 0 { - return Err(DeserializationError::missing_data()); - } - } - Ok({ - let slice = arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = DataType::Float32; - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.blueprint.components.RowShare#share")? - .values() - .as_slice(); - { - slice.iter().copied().map(Self).collect::>() - } - }) + crate::datatypes::Float32::from_arrow(arrow_data).map(|v| v.into_iter().map(Self).collect()) } } diff --git a/crates/store/re_types/src/blueprint/components/visible.rs b/crates/store/re_types/src/blueprint/components/visible.rs index 838e046b9257..f91bd0cf62da 100644 --- a/crates/store/re_types/src/blueprint/components/visible.rs +++ b/crates/store/re_types/src/blueprint/components/visible.rs @@ -21,7 +21,7 @@ use ::re_types_core::{DeserializationError, DeserializationResult}; /// **Component**: Whether the container, view, entity or instance is currently visible. #[derive(Clone, Debug, Copy, PartialEq, Eq, PartialOrd, Ord)] #[repr(transparent)] -pub struct Visible(pub bool); +pub struct Visible(pub crate::datatypes::Bool); impl ::re_types_core::SizeBytes for Visible { #[inline] @@ -31,36 +31,35 @@ impl ::re_types_core::SizeBytes for Visible { #[inline] fn is_pod() -> bool { - ::is_pod() + ::is_pod() } } -impl From for Visible { - #[inline] - fn from(visible: bool) -> Self { - Self(visible) +impl> From for Visible { + fn from(v: T) -> Self { + Self(v.into()) } } -impl From for bool { +impl std::borrow::Borrow for Visible { #[inline] - fn from(value: Visible) -> Self { - value.0 + fn borrow(&self) -> &crate::datatypes::Bool { + &self.0 } } impl std::ops::Deref for Visible { - type Target = bool; + type Target = crate::datatypes::Bool; #[inline] - fn deref(&self) -> &bool { + fn deref(&self) -> &crate::datatypes::Bool { &self.0 } } impl std::ops::DerefMut for Visible { #[inline] - fn deref_mut(&mut self) -> &mut bool { + fn deref_mut(&mut self) -> &mut crate::datatypes::Bool { &mut self.0 } } @@ -77,9 +76,7 @@ impl ::re_types_core::Loggable for Visible { #[inline] fn arrow_datatype() -> arrow2::datatypes::DataType { - #![allow(clippy::wildcard_imports)] - use arrow2::datatypes::*; - DataType::Boolean + crate::datatypes::Bool::arrow_datatype() } fn to_arrow_opt<'a>( @@ -88,29 +85,12 @@ impl ::re_types_core::Loggable for Visible { where Self: Clone + 'a, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, datatypes::*}; - Ok({ - let (somes, data0): (Vec<_>, Vec<_>) = data - .into_iter() - .map(|datum| { - let datum: Option<::std::borrow::Cow<'a, Self>> = datum.map(Into::into); - let datum = datum.map(|datum| datum.into_owned().0); - (datum.is_some(), datum) - }) - .unzip(); - let data0_bitmap: Option = { - let any_nones = somes.iter().any(|some| !*some); - any_nones.then(|| somes.into()) - }; - BooleanArray::new( - Self::arrow_datatype(), - data0.into_iter().map(|v| v.unwrap_or_default()).collect(), - data0_bitmap, - ) - .boxed() - }) + crate::datatypes::Bool::to_arrow_opt(data.into_iter().map(|datum| { + datum.map(|datum| match datum.into() { + ::std::borrow::Cow::Borrowed(datum) => ::std::borrow::Cow::Borrowed(&datum.0), + ::std::borrow::Cow::Owned(datum) => ::std::borrow::Cow::Owned(datum.0), + }) + })) } fn from_arrow_opt( @@ -119,23 +99,7 @@ impl ::re_types_core::Loggable for Visible { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - Ok(arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = Self::arrow_datatype(); - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.blueprint.components.Visible#visible")? - .into_iter() - .map(|v| v.ok_or_else(DeserializationError::missing_data)) - .map(|res| res.map(|v| Some(Self(v)))) - .collect::>>>() - .with_context("rerun.blueprint.components.Visible#visible") - .with_context("rerun.blueprint.components.Visible")?) + crate::datatypes::Bool::from_arrow_opt(arrow_data) + .map(|v| v.into_iter().map(|v| v.map(Self)).collect()) } } diff --git a/crates/store/re_types/src/blueprint/components/visible_ext.rs b/crates/store/re_types/src/blueprint/components/visible_ext.rs index 76cb903fa5e9..e43b167449fa 100644 --- a/crates/store/re_types/src/blueprint/components/visible_ext.rs +++ b/crates/store/re_types/src/blueprint/components/visible_ext.rs @@ -1,8 +1,10 @@ +use re_types_core::datatypes::Bool; + use super::Visible; impl Default for Visible { #[inline] fn default() -> Self { - Self(true) + Self(Bool(true)) } } diff --git a/crates/store/re_types/src/components/blob.rs b/crates/store/re_types/src/components/blob.rs index 618d4a29a78d..fe336e8bb169 100644 --- a/crates/store/re_types/src/components/blob.rs +++ b/crates/store/re_types/src/components/blob.rs @@ -19,9 +19,9 @@ use ::re_types_core::{ComponentBatch, MaybeOwnedComponentBatch}; use ::re_types_core::{DeserializationError, DeserializationResult}; /// **Component**: A binary blob of data. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq)] #[repr(transparent)] -pub struct Blob(pub ::re_types_core::ArrowBuffer); +pub struct Blob(pub crate::datatypes::Blob); impl ::re_types_core::SizeBytes for Blob { #[inline] @@ -31,36 +31,35 @@ impl ::re_types_core::SizeBytes for Blob { #[inline] fn is_pod() -> bool { - <::re_types_core::ArrowBuffer>::is_pod() + ::is_pod() } } -impl From<::re_types_core::ArrowBuffer> for Blob { - #[inline] - fn from(data: ::re_types_core::ArrowBuffer) -> Self { - Self(data) +impl> From for Blob { + fn from(v: T) -> Self { + Self(v.into()) } } -impl From for ::re_types_core::ArrowBuffer { +impl std::borrow::Borrow for Blob { #[inline] - fn from(value: Blob) -> Self { - value.0 + fn borrow(&self) -> &crate::datatypes::Blob { + &self.0 } } impl std::ops::Deref for Blob { - type Target = ::re_types_core::ArrowBuffer; + type Target = crate::datatypes::Blob; #[inline] - fn deref(&self) -> &::re_types_core::ArrowBuffer { + fn deref(&self) -> &crate::datatypes::Blob { &self.0 } } impl std::ops::DerefMut for Blob { #[inline] - fn deref_mut(&mut self) -> &mut ::re_types_core::ArrowBuffer { + fn deref_mut(&mut self) -> &mut crate::datatypes::Blob { &mut self.0 } } @@ -77,13 +76,7 @@ impl ::re_types_core::Loggable for Blob { #[inline] fn arrow_datatype() -> arrow2::datatypes::DataType { - #![allow(clippy::wildcard_imports)] - use arrow2::datatypes::*; - DataType::List(std::sync::Arc::new(Field::new( - "item", - DataType::UInt8, - false, - ))) + crate::datatypes::Blob::arrow_datatype() } fn to_arrow_opt<'a>( @@ -92,48 +85,12 @@ impl ::re_types_core::Loggable for Blob { where Self: Clone + 'a, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, datatypes::*}; - Ok({ - let (somes, data0): (Vec<_>, Vec<_>) = data - .into_iter() - .map(|datum| { - let datum: Option<::std::borrow::Cow<'a, Self>> = datum.map(Into::into); - let datum = datum.map(|datum| datum.into_owned().0); - (datum.is_some(), datum) - }) - .unzip(); - let data0_bitmap: Option = { - let any_nones = somes.iter().any(|some| !*some); - any_nones.then(|| somes.into()) - }; - { - use arrow2::{buffer::Buffer, offset::OffsetsBuffer}; - let offsets = arrow2::offset::Offsets::::try_from_lengths( - data0 - .iter() - .map(|opt| opt.as_ref().map_or(0, |datum| datum.num_instances())), - )? - .into(); - let data0_inner_data: Buffer<_> = data0 - .iter() - .flatten() - .map(|b| b.as_slice()) - .collect::>() - .concat() - .into(); - let data0_inner_bitmap: Option = None; - ListArray::try_new( - Self::arrow_datatype(), - offsets, - PrimitiveArray::new(DataType::UInt8, data0_inner_data, data0_inner_bitmap) - .boxed(), - data0_bitmap, - )? - .boxed() - } - }) + crate::datatypes::Blob::to_arrow_opt(data.into_iter().map(|datum| { + datum.map(|datum| match datum.into() { + ::std::borrow::Cow::Borrowed(datum) => ::std::borrow::Cow::Borrowed(&datum.0), + ::std::borrow::Cow::Owned(datum) => ::std::borrow::Cow::Owned(datum.0), + }) + })) } fn from_arrow_opt( @@ -142,70 +99,7 @@ impl ::re_types_core::Loggable for Blob { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - Ok({ - let arrow_data = arrow_data - .as_any() - .downcast_ref::>() - .ok_or_else(|| { - let expected = Self::arrow_datatype(); - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.components.Blob#data")?; - if arrow_data.is_empty() { - Vec::new() - } else { - let arrow_data_inner = { - let arrow_data_inner = &**arrow_data.values(); - arrow_data_inner - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = DataType::UInt8; - let actual = arrow_data_inner.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.components.Blob#data")? - .values() - }; - let offsets = arrow_data.offsets(); - arrow2::bitmap::utils::ZipValidity::new_with_validity( - offsets.iter().zip(offsets.lengths()), - arrow_data.validity(), - ) - .map(|elem| { - elem.map(|(start, len)| { - let start = *start as usize; - let end = start + len; - if end > arrow_data_inner.len() { - return Err(DeserializationError::offset_slice_oob( - (start, end), - arrow_data_inner.len(), - )); - } - - #[allow(unsafe_code, clippy::undocumented_unsafe_blocks)] - let data = unsafe { - arrow_data_inner - .clone() - .sliced_unchecked(start, end - start) - }; - let data = ::re_types_core::ArrowBuffer::from(data); - Ok(data) - }) - .transpose() - }) - .collect::>>>()? - } - .into_iter() - } - .map(|v| v.ok_or_else(DeserializationError::missing_data)) - .map(|res| res.map(|v| Some(Self(v)))) - .collect::>>>() - .with_context("rerun.components.Blob#data") - .with_context("rerun.components.Blob")?) + crate::datatypes::Blob::from_arrow_opt(arrow_data) + .map(|v| v.into_iter().map(|v| v.map(Self)).collect()) } } diff --git a/crates/store/re_types/src/components/depth_meter.rs b/crates/store/re_types/src/components/depth_meter.rs index 88739534a14a..65783a841f44 100644 --- a/crates/store/re_types/src/components/depth_meter.rs +++ b/crates/store/re_types/src/components/depth_meter.rs @@ -28,7 +28,7 @@ use ::re_types_core::{DeserializationError, DeserializationResult}; /// In 3D views on the other hand, this affects where the points of the point cloud are placed. #[derive(Clone, Debug, Copy, PartialEq, PartialOrd, bytemuck::Pod, bytemuck::Zeroable)] #[repr(transparent)] -pub struct DepthMeter(pub f32); +pub struct DepthMeter(pub crate::datatypes::Float32); impl ::re_types_core::SizeBytes for DepthMeter { #[inline] @@ -38,36 +38,35 @@ impl ::re_types_core::SizeBytes for DepthMeter { #[inline] fn is_pod() -> bool { - ::is_pod() + ::is_pod() } } -impl From for DepthMeter { - #[inline] - fn from(value: f32) -> Self { - Self(value) +impl> From for DepthMeter { + fn from(v: T) -> Self { + Self(v.into()) } } -impl From for f32 { +impl std::borrow::Borrow for DepthMeter { #[inline] - fn from(value: DepthMeter) -> Self { - value.0 + fn borrow(&self) -> &crate::datatypes::Float32 { + &self.0 } } impl std::ops::Deref for DepthMeter { - type Target = f32; + type Target = crate::datatypes::Float32; #[inline] - fn deref(&self) -> &f32 { + fn deref(&self) -> &crate::datatypes::Float32 { &self.0 } } impl std::ops::DerefMut for DepthMeter { #[inline] - fn deref_mut(&mut self) -> &mut f32 { + fn deref_mut(&mut self) -> &mut crate::datatypes::Float32 { &mut self.0 } } @@ -84,9 +83,7 @@ impl ::re_types_core::Loggable for DepthMeter { #[inline] fn arrow_datatype() -> arrow2::datatypes::DataType { - #![allow(clippy::wildcard_imports)] - use arrow2::datatypes::*; - DataType::Float32 + crate::datatypes::Float32::arrow_datatype() } fn to_arrow_opt<'a>( @@ -95,29 +92,12 @@ impl ::re_types_core::Loggable for DepthMeter { where Self: Clone + 'a, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, datatypes::*}; - Ok({ - let (somes, data0): (Vec<_>, Vec<_>) = data - .into_iter() - .map(|datum| { - let datum: Option<::std::borrow::Cow<'a, Self>> = datum.map(Into::into); - let datum = datum.map(|datum| datum.into_owned().0); - (datum.is_some(), datum) - }) - .unzip(); - let data0_bitmap: Option = { - let any_nones = somes.iter().any(|some| !*some); - any_nones.then(|| somes.into()) - }; - PrimitiveArray::new( - Self::arrow_datatype(), - data0.into_iter().map(|v| v.unwrap_or_default()).collect(), - data0_bitmap, - ) - .boxed() - }) + crate::datatypes::Float32::to_arrow_opt(data.into_iter().map(|datum| { + datum.map(|datum| match datum.into() { + ::std::borrow::Cow::Borrowed(datum) => ::std::borrow::Cow::Borrowed(&datum.0), + ::std::borrow::Cow::Owned(datum) => ::std::borrow::Cow::Owned(datum.0), + }) + })) } fn from_arrow_opt( @@ -126,25 +106,8 @@ impl ::re_types_core::Loggable for DepthMeter { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - Ok(arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = Self::arrow_datatype(); - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.components.DepthMeter#value")? - .into_iter() - .map(|opt| opt.copied()) - .map(|v| v.ok_or_else(DeserializationError::missing_data)) - .map(|res| res.map(|v| Some(Self(v)))) - .collect::>>>() - .with_context("rerun.components.DepthMeter#value") - .with_context("rerun.components.DepthMeter")?) + crate::datatypes::Float32::from_arrow_opt(arrow_data) + .map(|v| v.into_iter().map(|v| v.map(Self)).collect()) } #[inline] @@ -152,29 +115,6 @@ impl ::re_types_core::Loggable for DepthMeter { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - if let Some(validity) = arrow_data.validity() { - if validity.unset_bits() != 0 { - return Err(DeserializationError::missing_data()); - } - } - Ok({ - let slice = arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = DataType::Float32; - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.components.DepthMeter#value")? - .values() - .as_slice(); - { - slice.iter().copied().map(Self).collect::>() - } - }) + crate::datatypes::Float32::from_arrow(arrow_data).map(bytemuck::cast_vec) } } diff --git a/crates/store/re_types/src/components/depth_meter_ext.rs b/crates/store/re_types/src/components/depth_meter_ext.rs index eea53259d599..7e22ab397cd2 100644 --- a/crates/store/re_types/src/components/depth_meter_ext.rs +++ b/crates/store/re_types/src/components/depth_meter_ext.rs @@ -1,14 +1,8 @@ use super::DepthMeter; -impl std::fmt::Display for DepthMeter { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:.prec$}", self.0, prec = crate::DISPLAY_PRECISION) - } -} - impl Default for DepthMeter { #[inline] fn default() -> Self { - Self(1.0) // 1 unit == 1 meter. + Self(1.0.into()) // 1 unit == 1 meter. } } diff --git a/crates/store/re_types/src/components/disconnected_space.rs b/crates/store/re_types/src/components/disconnected_space.rs index 347736f105d4..17f7c42f2c6f 100644 --- a/crates/store/re_types/src/components/disconnected_space.rs +++ b/crates/store/re_types/src/components/disconnected_space.rs @@ -30,7 +30,7 @@ pub struct DisconnectedSpace( /// /// Set to true to disconnect the entity from its parent. /// Set to false to disable the effects of this component, (re-)connecting the entity to its parent again. - pub bool, + pub crate::datatypes::Bool, ); impl ::re_types_core::SizeBytes for DisconnectedSpace { @@ -41,36 +41,35 @@ impl ::re_types_core::SizeBytes for DisconnectedSpace { #[inline] fn is_pod() -> bool { - ::is_pod() + ::is_pod() } } -impl From for DisconnectedSpace { - #[inline] - fn from(is_disconnected: bool) -> Self { - Self(is_disconnected) +impl> From for DisconnectedSpace { + fn from(v: T) -> Self { + Self(v.into()) } } -impl From for bool { +impl std::borrow::Borrow for DisconnectedSpace { #[inline] - fn from(value: DisconnectedSpace) -> Self { - value.0 + fn borrow(&self) -> &crate::datatypes::Bool { + &self.0 } } impl std::ops::Deref for DisconnectedSpace { - type Target = bool; + type Target = crate::datatypes::Bool; #[inline] - fn deref(&self) -> &bool { + fn deref(&self) -> &crate::datatypes::Bool { &self.0 } } impl std::ops::DerefMut for DisconnectedSpace { #[inline] - fn deref_mut(&mut self) -> &mut bool { + fn deref_mut(&mut self) -> &mut crate::datatypes::Bool { &mut self.0 } } @@ -87,9 +86,7 @@ impl ::re_types_core::Loggable for DisconnectedSpace { #[inline] fn arrow_datatype() -> arrow2::datatypes::DataType { - #![allow(clippy::wildcard_imports)] - use arrow2::datatypes::*; - DataType::Boolean + crate::datatypes::Bool::arrow_datatype() } fn to_arrow_opt<'a>( @@ -98,29 +95,12 @@ impl ::re_types_core::Loggable for DisconnectedSpace { where Self: Clone + 'a, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, datatypes::*}; - Ok({ - let (somes, data0): (Vec<_>, Vec<_>) = data - .into_iter() - .map(|datum| { - let datum: Option<::std::borrow::Cow<'a, Self>> = datum.map(Into::into); - let datum = datum.map(|datum| datum.into_owned().0); - (datum.is_some(), datum) - }) - .unzip(); - let data0_bitmap: Option = { - let any_nones = somes.iter().any(|some| !*some); - any_nones.then(|| somes.into()) - }; - BooleanArray::new( - Self::arrow_datatype(), - data0.into_iter().map(|v| v.unwrap_or_default()).collect(), - data0_bitmap, - ) - .boxed() - }) + crate::datatypes::Bool::to_arrow_opt(data.into_iter().map(|datum| { + datum.map(|datum| match datum.into() { + ::std::borrow::Cow::Borrowed(datum) => ::std::borrow::Cow::Borrowed(&datum.0), + ::std::borrow::Cow::Owned(datum) => ::std::borrow::Cow::Owned(datum.0), + }) + })) } fn from_arrow_opt( @@ -129,23 +109,7 @@ impl ::re_types_core::Loggable for DisconnectedSpace { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - Ok(arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = Self::arrow_datatype(); - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.components.DisconnectedSpace#is_disconnected")? - .into_iter() - .map(|v| v.ok_or_else(DeserializationError::missing_data)) - .map(|res| res.map(|v| Some(Self(v)))) - .collect::>>>() - .with_context("rerun.components.DisconnectedSpace#is_disconnected") - .with_context("rerun.components.DisconnectedSpace")?) + crate::datatypes::Bool::from_arrow_opt(arrow_data) + .map(|v| v.into_iter().map(|v| v.map(Self)).collect()) } } diff --git a/crates/store/re_types/src/components/disconnected_space_ext.rs b/crates/store/re_types/src/components/disconnected_space_ext.rs index da0ad4defb74..aa60226ac9a4 100644 --- a/crates/store/re_types/src/components/disconnected_space_ext.rs +++ b/crates/store/re_types/src/components/disconnected_space_ext.rs @@ -3,6 +3,6 @@ use super::DisconnectedSpace; impl Default for DisconnectedSpace { #[inline] fn default() -> Self { - Self(true) + Self(true.into()) } } diff --git a/crates/store/re_types/src/components/draw_order.rs b/crates/store/re_types/src/components/draw_order.rs index f4b11acc25e4..4e8f06ae33d1 100644 --- a/crates/store/re_types/src/components/draw_order.rs +++ b/crates/store/re_types/src/components/draw_order.rs @@ -26,7 +26,7 @@ use ::re_types_core::{DeserializationError, DeserializationResult}; /// Draw order for entities with the same draw order is generally undefined. #[derive(Clone, Debug, Copy)] #[repr(transparent)] -pub struct DrawOrder(pub f32); +pub struct DrawOrder(pub crate::datatypes::Float32); impl ::re_types_core::SizeBytes for DrawOrder { #[inline] @@ -36,36 +36,35 @@ impl ::re_types_core::SizeBytes for DrawOrder { #[inline] fn is_pod() -> bool { - ::is_pod() + ::is_pod() } } -impl From for DrawOrder { - #[inline] - fn from(value: f32) -> Self { - Self(value) +impl> From for DrawOrder { + fn from(v: T) -> Self { + Self(v.into()) } } -impl From for f32 { +impl std::borrow::Borrow for DrawOrder { #[inline] - fn from(value: DrawOrder) -> Self { - value.0 + fn borrow(&self) -> &crate::datatypes::Float32 { + &self.0 } } impl std::ops::Deref for DrawOrder { - type Target = f32; + type Target = crate::datatypes::Float32; #[inline] - fn deref(&self) -> &f32 { + fn deref(&self) -> &crate::datatypes::Float32 { &self.0 } } impl std::ops::DerefMut for DrawOrder { #[inline] - fn deref_mut(&mut self) -> &mut f32 { + fn deref_mut(&mut self) -> &mut crate::datatypes::Float32 { &mut self.0 } } @@ -82,9 +81,7 @@ impl ::re_types_core::Loggable for DrawOrder { #[inline] fn arrow_datatype() -> arrow2::datatypes::DataType { - #![allow(clippy::wildcard_imports)] - use arrow2::datatypes::*; - DataType::Float32 + crate::datatypes::Float32::arrow_datatype() } fn to_arrow_opt<'a>( @@ -93,29 +90,12 @@ impl ::re_types_core::Loggable for DrawOrder { where Self: Clone + 'a, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, datatypes::*}; - Ok({ - let (somes, data0): (Vec<_>, Vec<_>) = data - .into_iter() - .map(|datum| { - let datum: Option<::std::borrow::Cow<'a, Self>> = datum.map(Into::into); - let datum = datum.map(|datum| datum.into_owned().0); - (datum.is_some(), datum) - }) - .unzip(); - let data0_bitmap: Option = { - let any_nones = somes.iter().any(|some| !*some); - any_nones.then(|| somes.into()) - }; - PrimitiveArray::new( - Self::arrow_datatype(), - data0.into_iter().map(|v| v.unwrap_or_default()).collect(), - data0_bitmap, - ) - .boxed() - }) + crate::datatypes::Float32::to_arrow_opt(data.into_iter().map(|datum| { + datum.map(|datum| match datum.into() { + ::std::borrow::Cow::Borrowed(datum) => ::std::borrow::Cow::Borrowed(&datum.0), + ::std::borrow::Cow::Owned(datum) => ::std::borrow::Cow::Owned(datum.0), + }) + })) } fn from_arrow_opt( @@ -124,25 +104,8 @@ impl ::re_types_core::Loggable for DrawOrder { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - Ok(arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = Self::arrow_datatype(); - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.components.DrawOrder#value")? - .into_iter() - .map(|opt| opt.copied()) - .map(|v| v.ok_or_else(DeserializationError::missing_data)) - .map(|res| res.map(|v| Some(Self(v)))) - .collect::>>>() - .with_context("rerun.components.DrawOrder#value") - .with_context("rerun.components.DrawOrder")?) + crate::datatypes::Float32::from_arrow_opt(arrow_data) + .map(|v| v.into_iter().map(|v| v.map(Self)).collect()) } #[inline] @@ -150,29 +113,6 @@ impl ::re_types_core::Loggable for DrawOrder { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - if let Some(validity) = arrow_data.validity() { - if validity.unset_bits() != 0 { - return Err(DeserializationError::missing_data()); - } - } - Ok({ - let slice = arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = DataType::Float32; - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.components.DrawOrder#value")? - .values() - .as_slice(); - { - slice.iter().copied().map(Self).collect::>() - } - }) + crate::datatypes::Float32::from_arrow(arrow_data).map(|v| v.into_iter().map(Self).collect()) } } diff --git a/crates/store/re_types/src/components/draw_order_ext.rs b/crates/store/re_types/src/components/draw_order_ext.rs index 00cd8d038007..7a5c958df337 100644 --- a/crates/store/re_types/src/components/draw_order_ext.rs +++ b/crates/store/re_types/src/components/draw_order_ext.rs @@ -1,25 +1,27 @@ +use re_types_core::datatypes::Float32; + use super::DrawOrder; // TODO(cmc): come up with some DSL in our flatbuffers definitions so that we can declare these // constants directly in there. impl DrawOrder { /// Draw order used for depth image when they're not shown as a 3D point cloud and no draw order was specified. - pub const DEFAULT_DEPTH_IMAGE: Self = Self(-20.0); + pub const DEFAULT_DEPTH_IMAGE: Self = Self(Float32(-20.0)); /// Draw order used for images if no draw order was specified. - pub const DEFAULT_IMAGE: Self = Self(-10.0); + pub const DEFAULT_IMAGE: Self = Self(Float32(-10.0)); /// Draw order used for segmentation images if no draw order was specified. - pub const DEFAULT_SEGMENTATION_IMAGE: Self = Self(0.0); + pub const DEFAULT_SEGMENTATION_IMAGE: Self = Self(Float32(0.0)); /// Draw order used for 2D boxes if no draw order was specified. - pub const DEFAULT_BOX2D: Self = Self(10.0); + pub const DEFAULT_BOX2D: Self = Self(Float32(10.0)); /// Draw order used for 2D lines if no draw order was specified. - pub const DEFAULT_LINES2D: Self = Self(20.0); + pub const DEFAULT_LINES2D: Self = Self(Float32(20.0)); /// Draw order used for 2D points if no draw order was specified. - pub const DEFAULT_POINTS2D: Self = Self(30.0); + pub const DEFAULT_POINTS2D: Self = Self(Float32(30.0)); } impl std::cmp::PartialEq for DrawOrder { @@ -55,6 +57,6 @@ impl Default for DrawOrder { #[inline] fn default() -> Self { // Pick zero as default which happens to be neither at the bottom nor the top. - Self(0.0) + Self(Float32(0.0)) } } diff --git a/crates/store/re_types/src/components/marker_size.rs b/crates/store/re_types/src/components/marker_size.rs index c8da39c6aa77..afbf17681e4f 100644 --- a/crates/store/re_types/src/components/marker_size.rs +++ b/crates/store/re_types/src/components/marker_size.rs @@ -21,7 +21,7 @@ use ::re_types_core::{DeserializationError, DeserializationResult}; /// **Component**: Radius of a marker of a point in e.g. a 2D plot, measured in UI points. #[derive(Clone, Debug, Copy, PartialEq, PartialOrd, bytemuck::Pod, bytemuck::Zeroable)] #[repr(transparent)] -pub struct MarkerSize(pub f32); +pub struct MarkerSize(pub crate::datatypes::Float32); impl ::re_types_core::SizeBytes for MarkerSize { #[inline] @@ -31,36 +31,35 @@ impl ::re_types_core::SizeBytes for MarkerSize { #[inline] fn is_pod() -> bool { - ::is_pod() + ::is_pod() } } -impl From for MarkerSize { - #[inline] - fn from(value: f32) -> Self { - Self(value) +impl> From for MarkerSize { + fn from(v: T) -> Self { + Self(v.into()) } } -impl From for f32 { +impl std::borrow::Borrow for MarkerSize { #[inline] - fn from(value: MarkerSize) -> Self { - value.0 + fn borrow(&self) -> &crate::datatypes::Float32 { + &self.0 } } impl std::ops::Deref for MarkerSize { - type Target = f32; + type Target = crate::datatypes::Float32; #[inline] - fn deref(&self) -> &f32 { + fn deref(&self) -> &crate::datatypes::Float32 { &self.0 } } impl std::ops::DerefMut for MarkerSize { #[inline] - fn deref_mut(&mut self) -> &mut f32 { + fn deref_mut(&mut self) -> &mut crate::datatypes::Float32 { &mut self.0 } } @@ -77,9 +76,7 @@ impl ::re_types_core::Loggable for MarkerSize { #[inline] fn arrow_datatype() -> arrow2::datatypes::DataType { - #![allow(clippy::wildcard_imports)] - use arrow2::datatypes::*; - DataType::Float32 + crate::datatypes::Float32::arrow_datatype() } fn to_arrow_opt<'a>( @@ -88,29 +85,12 @@ impl ::re_types_core::Loggable for MarkerSize { where Self: Clone + 'a, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, datatypes::*}; - Ok({ - let (somes, data0): (Vec<_>, Vec<_>) = data - .into_iter() - .map(|datum| { - let datum: Option<::std::borrow::Cow<'a, Self>> = datum.map(Into::into); - let datum = datum.map(|datum| datum.into_owned().0); - (datum.is_some(), datum) - }) - .unzip(); - let data0_bitmap: Option = { - let any_nones = somes.iter().any(|some| !*some); - any_nones.then(|| somes.into()) - }; - PrimitiveArray::new( - Self::arrow_datatype(), - data0.into_iter().map(|v| v.unwrap_or_default()).collect(), - data0_bitmap, - ) - .boxed() - }) + crate::datatypes::Float32::to_arrow_opt(data.into_iter().map(|datum| { + datum.map(|datum| match datum.into() { + ::std::borrow::Cow::Borrowed(datum) => ::std::borrow::Cow::Borrowed(&datum.0), + ::std::borrow::Cow::Owned(datum) => ::std::borrow::Cow::Owned(datum.0), + }) + })) } fn from_arrow_opt( @@ -119,25 +99,8 @@ impl ::re_types_core::Loggable for MarkerSize { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - Ok(arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = Self::arrow_datatype(); - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.components.MarkerSize#value")? - .into_iter() - .map(|opt| opt.copied()) - .map(|v| v.ok_or_else(DeserializationError::missing_data)) - .map(|res| res.map(|v| Some(Self(v)))) - .collect::>>>() - .with_context("rerun.components.MarkerSize#value") - .with_context("rerun.components.MarkerSize")?) + crate::datatypes::Float32::from_arrow_opt(arrow_data) + .map(|v| v.into_iter().map(|v| v.map(Self)).collect()) } #[inline] @@ -145,29 +108,6 @@ impl ::re_types_core::Loggable for MarkerSize { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - if let Some(validity) = arrow_data.validity() { - if validity.unset_bits() != 0 { - return Err(DeserializationError::missing_data()); - } - } - Ok({ - let slice = arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = DataType::Float32; - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.components.MarkerSize#value")? - .values() - .as_slice(); - { - slice.iter().copied().map(Self).collect::>() - } - }) + crate::datatypes::Float32::from_arrow(arrow_data).map(bytemuck::cast_vec) } } diff --git a/crates/store/re_types/src/components/marker_size_ext.rs b/crates/store/re_types/src/components/marker_size_ext.rs index f6ecfcaea173..344c118695a0 100644 --- a/crates/store/re_types/src/components/marker_size_ext.rs +++ b/crates/store/re_types/src/components/marker_size_ext.rs @@ -3,6 +3,6 @@ use super::MarkerSize; impl Default for MarkerSize { #[inline] fn default() -> Self { - Self(8.0) // Reminder: these are ui points. Picking 1.0 is too small, 0.0 is invisible. + Self(8.0.into()) // Reminder: these are ui points. Picking 1.0 is too small, 0.0 is invisible. } } diff --git a/crates/store/re_types/src/components/mod.rs b/crates/store/re_types/src/components/mod.rs index da7bdac526fa..681aa584be15 100644 --- a/crates/store/re_types/src/components/mod.rs +++ b/crates/store/re_types/src/components/mod.rs @@ -5,7 +5,6 @@ mod annotation_context; mod axis_length; mod axis_length_ext; mod blob; -mod blob_ext; mod class_id; mod class_id_ext; mod color; diff --git a/crates/store/re_types/src/components/radius.rs b/crates/store/re_types/src/components/radius.rs index 742e5786156b..b9e799191a76 100644 --- a/crates/store/re_types/src/components/radius.rs +++ b/crates/store/re_types/src/components/radius.rs @@ -28,7 +28,7 @@ use ::re_types_core::{DeserializationError, DeserializationResult}; /// The Viewer's UI scaling defaults to the OS scaling which typically is 100% for full HD screens and 200% for 4k screens. #[derive(Clone, Debug, Copy, PartialEq, PartialOrd, bytemuck::Pod, bytemuck::Zeroable)] #[repr(transparent)] -pub struct Radius(pub f32); +pub struct Radius(pub crate::datatypes::Float32); impl ::re_types_core::SizeBytes for Radius { #[inline] @@ -38,36 +38,35 @@ impl ::re_types_core::SizeBytes for Radius { #[inline] fn is_pod() -> bool { - ::is_pod() + ::is_pod() } } -impl From for Radius { - #[inline] - fn from(value: f32) -> Self { - Self(value) +impl> From for Radius { + fn from(v: T) -> Self { + Self(v.into()) } } -impl From for f32 { +impl std::borrow::Borrow for Radius { #[inline] - fn from(value: Radius) -> Self { - value.0 + fn borrow(&self) -> &crate::datatypes::Float32 { + &self.0 } } impl std::ops::Deref for Radius { - type Target = f32; + type Target = crate::datatypes::Float32; #[inline] - fn deref(&self) -> &f32 { + fn deref(&self) -> &crate::datatypes::Float32 { &self.0 } } impl std::ops::DerefMut for Radius { #[inline] - fn deref_mut(&mut self) -> &mut f32 { + fn deref_mut(&mut self) -> &mut crate::datatypes::Float32 { &mut self.0 } } @@ -84,9 +83,7 @@ impl ::re_types_core::Loggable for Radius { #[inline] fn arrow_datatype() -> arrow2::datatypes::DataType { - #![allow(clippy::wildcard_imports)] - use arrow2::datatypes::*; - DataType::Float32 + crate::datatypes::Float32::arrow_datatype() } fn to_arrow_opt<'a>( @@ -95,29 +92,12 @@ impl ::re_types_core::Loggable for Radius { where Self: Clone + 'a, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, datatypes::*}; - Ok({ - let (somes, data0): (Vec<_>, Vec<_>) = data - .into_iter() - .map(|datum| { - let datum: Option<::std::borrow::Cow<'a, Self>> = datum.map(Into::into); - let datum = datum.map(|datum| datum.into_owned().0); - (datum.is_some(), datum) - }) - .unzip(); - let data0_bitmap: Option = { - let any_nones = somes.iter().any(|some| !*some); - any_nones.then(|| somes.into()) - }; - PrimitiveArray::new( - Self::arrow_datatype(), - data0.into_iter().map(|v| v.unwrap_or_default()).collect(), - data0_bitmap, - ) - .boxed() - }) + crate::datatypes::Float32::to_arrow_opt(data.into_iter().map(|datum| { + datum.map(|datum| match datum.into() { + ::std::borrow::Cow::Borrowed(datum) => ::std::borrow::Cow::Borrowed(&datum.0), + ::std::borrow::Cow::Owned(datum) => ::std::borrow::Cow::Owned(datum.0), + }) + })) } fn from_arrow_opt( @@ -126,25 +106,8 @@ impl ::re_types_core::Loggable for Radius { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - Ok(arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = Self::arrow_datatype(); - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.components.Radius#value")? - .into_iter() - .map(|opt| opt.copied()) - .map(|v| v.ok_or_else(DeserializationError::missing_data)) - .map(|res| res.map(|v| Some(Self(v)))) - .collect::>>>() - .with_context("rerun.components.Radius#value") - .with_context("rerun.components.Radius")?) + crate::datatypes::Float32::from_arrow_opt(arrow_data) + .map(|v| v.into_iter().map(|v| v.map(Self)).collect()) } #[inline] @@ -152,29 +115,6 @@ impl ::re_types_core::Loggable for Radius { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - if let Some(validity) = arrow_data.validity() { - if validity.unset_bits() != 0 { - return Err(DeserializationError::missing_data()); - } - } - Ok({ - let slice = arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = DataType::Float32; - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.components.Radius#value")? - .values() - .as_slice(); - { - slice.iter().copied().map(Self).collect::>() - } - }) + crate::datatypes::Float32::from_arrow(arrow_data).map(bytemuck::cast_vec) } } diff --git a/crates/store/re_types/src/components/radius_ext.rs b/crates/store/re_types/src/components/radius_ext.rs index 6bf920283bf3..474d2af65a45 100644 --- a/crates/store/re_types/src/components/radius_ext.rs +++ b/crates/store/re_types/src/components/radius_ext.rs @@ -1,11 +1,13 @@ +use re_types_core::datatypes::Float32; + use super::Radius; impl Radius { /// Zero radius. - pub const ZERO: Self = Self(0.0); + pub const ZERO: Self = Self(Float32(0.0)); /// Radius of length 1 in ui points. - pub const ONE_UI_POINTS: Self = Self(-1.0); + pub const ONE_UI_POINTS: Self = Self(Float32(-1.0)); } impl Default for Radius { @@ -25,7 +27,7 @@ impl Radius { 0.0 <= radius_in_scene_units, "Bad radius: {radius_in_scene_units}" ); - Self(radius_in_scene_units) + Self(Float32(radius_in_scene_units)) } /// Creates a new radius in ui points. @@ -37,51 +39,52 @@ impl Radius { 0.0 <= radius_in_ui_points, "Bad radius: {radius_in_ui_points}" ); - Self(-radius_in_ui_points) + Self(Float32(-radius_in_ui_points)) } /// If this radius is in scene units, returns the radius in scene units. #[inline] pub fn scene_units(&self) -> Option { // Ensure negative zero is treated as a point size. - self.0.is_sign_positive().then_some(self.0) + self.0.is_sign_positive().then_some(*self.0) } /// If this radius is in ui points, returns the radius in ui points. #[inline] pub fn ui_points(&self) -> Option { // Ensure negative zero is treated as a point size. - self.0.is_sign_negative().then_some(-self.0) + self.0.is_sign_negative().then_some(-*self.0) } } #[cfg(test)] mod tests { use super::Radius; + use re_types_core::datatypes::Float32; #[test] fn scene_point_distinction() { - let radius = Radius(1.0); + let radius = Radius(Float32(1.0)); assert_eq!(radius.scene_units(), Some(1.0)); assert_eq!(radius.ui_points(), None); - let radius = Radius(-1.0); + let radius = Radius(Float32(-1.0)); assert_eq!(radius.scene_units(), None); assert_eq!(radius.ui_points(), Some(1.0)); - let radius = Radius(f32::INFINITY); + let radius = Radius(Float32(f32::INFINITY)); assert_eq!(radius.scene_units(), Some(f32::INFINITY)); assert_eq!(radius.ui_points(), None); - let radius = Radius(f32::NEG_INFINITY); + let radius = Radius(Float32(f32::NEG_INFINITY)); assert_eq!(radius.scene_units(), None); assert_eq!(radius.ui_points(), Some(f32::INFINITY)); - let radius = Radius(0.0); + let radius = Radius(Float32(0.0)); assert_eq!(radius.scene_units(), Some(0.0)); assert_eq!(radius.ui_points(), None); - let radius = Radius(-0.0); + let radius = Radius(Float32(-0.0)); assert_eq!(radius.scene_units(), None); assert_eq!(radius.ui_points(), Some(0.0)); } diff --git a/crates/store/re_types/src/components/scalar.rs b/crates/store/re_types/src/components/scalar.rs index e47e1aa9a90e..f98bdae0300c 100644 --- a/crates/store/re_types/src/components/scalar.rs +++ b/crates/store/re_types/src/components/scalar.rs @@ -23,7 +23,7 @@ use ::re_types_core::{DeserializationError, DeserializationResult}; /// Used for time series plots. #[derive(Clone, Debug, Copy, PartialEq, PartialOrd, bytemuck::Pod, bytemuck::Zeroable)] #[repr(transparent)] -pub struct Scalar(pub f64); +pub struct Scalar(pub crate::datatypes::Float64); impl ::re_types_core::SizeBytes for Scalar { #[inline] @@ -33,36 +33,35 @@ impl ::re_types_core::SizeBytes for Scalar { #[inline] fn is_pod() -> bool { - ::is_pod() + ::is_pod() } } -impl From for Scalar { - #[inline] - fn from(value: f64) -> Self { - Self(value) +impl> From for Scalar { + fn from(v: T) -> Self { + Self(v.into()) } } -impl From for f64 { +impl std::borrow::Borrow for Scalar { #[inline] - fn from(value: Scalar) -> Self { - value.0 + fn borrow(&self) -> &crate::datatypes::Float64 { + &self.0 } } impl std::ops::Deref for Scalar { - type Target = f64; + type Target = crate::datatypes::Float64; #[inline] - fn deref(&self) -> &f64 { + fn deref(&self) -> &crate::datatypes::Float64 { &self.0 } } impl std::ops::DerefMut for Scalar { #[inline] - fn deref_mut(&mut self) -> &mut f64 { + fn deref_mut(&mut self) -> &mut crate::datatypes::Float64 { &mut self.0 } } @@ -79,9 +78,7 @@ impl ::re_types_core::Loggable for Scalar { #[inline] fn arrow_datatype() -> arrow2::datatypes::DataType { - #![allow(clippy::wildcard_imports)] - use arrow2::datatypes::*; - DataType::Float64 + crate::datatypes::Float64::arrow_datatype() } fn to_arrow_opt<'a>( @@ -90,29 +87,12 @@ impl ::re_types_core::Loggable for Scalar { where Self: Clone + 'a, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, datatypes::*}; - Ok({ - let (somes, data0): (Vec<_>, Vec<_>) = data - .into_iter() - .map(|datum| { - let datum: Option<::std::borrow::Cow<'a, Self>> = datum.map(Into::into); - let datum = datum.map(|datum| datum.into_owned().0); - (datum.is_some(), datum) - }) - .unzip(); - let data0_bitmap: Option = { - let any_nones = somes.iter().any(|some| !*some); - any_nones.then(|| somes.into()) - }; - PrimitiveArray::new( - Self::arrow_datatype(), - data0.into_iter().map(|v| v.unwrap_or_default()).collect(), - data0_bitmap, - ) - .boxed() - }) + crate::datatypes::Float64::to_arrow_opt(data.into_iter().map(|datum| { + datum.map(|datum| match datum.into() { + ::std::borrow::Cow::Borrowed(datum) => ::std::borrow::Cow::Borrowed(&datum.0), + ::std::borrow::Cow::Owned(datum) => ::std::borrow::Cow::Owned(datum.0), + }) + })) } fn from_arrow_opt( @@ -121,25 +101,8 @@ impl ::re_types_core::Loggable for Scalar { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - Ok(arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = Self::arrow_datatype(); - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.components.Scalar#value")? - .into_iter() - .map(|opt| opt.copied()) - .map(|v| v.ok_or_else(DeserializationError::missing_data)) - .map(|res| res.map(|v| Some(Self(v)))) - .collect::>>>() - .with_context("rerun.components.Scalar#value") - .with_context("rerun.components.Scalar")?) + crate::datatypes::Float64::from_arrow_opt(arrow_data) + .map(|v| v.into_iter().map(|v| v.map(Self)).collect()) } #[inline] @@ -147,29 +110,6 @@ impl ::re_types_core::Loggable for Scalar { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - if let Some(validity) = arrow_data.validity() { - if validity.unset_bits() != 0 { - return Err(DeserializationError::missing_data()); - } - } - Ok({ - let slice = arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = DataType::Float64; - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.components.Scalar#value")? - .values() - .as_slice(); - { - slice.iter().copied().map(Self).collect::>() - } - }) + crate::datatypes::Float64::from_arrow(arrow_data).map(bytemuck::cast_vec) } } diff --git a/crates/store/re_types/src/components/scalar_ext.rs b/crates/store/re_types/src/components/scalar_ext.rs index 51a30354f82f..20a432b926cf 100644 --- a/crates/store/re_types/src/components/scalar_ext.rs +++ b/crates/store/re_types/src/components/scalar_ext.rs @@ -1,3 +1,5 @@ +use re_types_core::datatypes::Float64; + use super::Scalar; impl std::fmt::Display for Scalar { @@ -9,6 +11,6 @@ impl std::fmt::Display for Scalar { impl Default for Scalar { #[inline] fn default() -> Self { - Self(0.0) + Self(Float64(0.0)) } } diff --git a/crates/store/re_types/src/components/stroke_width.rs b/crates/store/re_types/src/components/stroke_width.rs index d9e8f77571e4..a2b1d8540d13 100644 --- a/crates/store/re_types/src/components/stroke_width.rs +++ b/crates/store/re_types/src/components/stroke_width.rs @@ -21,7 +21,7 @@ use ::re_types_core::{DeserializationError, DeserializationResult}; /// **Component**: The width of a stroke specified in UI points. #[derive(Clone, Debug, Copy, PartialEq, PartialOrd, bytemuck::Pod, bytemuck::Zeroable)] #[repr(transparent)] -pub struct StrokeWidth(pub f32); +pub struct StrokeWidth(pub crate::datatypes::Float32); impl ::re_types_core::SizeBytes for StrokeWidth { #[inline] @@ -31,36 +31,35 @@ impl ::re_types_core::SizeBytes for StrokeWidth { #[inline] fn is_pod() -> bool { - ::is_pod() + ::is_pod() } } -impl From for StrokeWidth { - #[inline] - fn from(width: f32) -> Self { - Self(width) +impl> From for StrokeWidth { + fn from(v: T) -> Self { + Self(v.into()) } } -impl From for f32 { +impl std::borrow::Borrow for StrokeWidth { #[inline] - fn from(value: StrokeWidth) -> Self { - value.0 + fn borrow(&self) -> &crate::datatypes::Float32 { + &self.0 } } impl std::ops::Deref for StrokeWidth { - type Target = f32; + type Target = crate::datatypes::Float32; #[inline] - fn deref(&self) -> &f32 { + fn deref(&self) -> &crate::datatypes::Float32 { &self.0 } } impl std::ops::DerefMut for StrokeWidth { #[inline] - fn deref_mut(&mut self) -> &mut f32 { + fn deref_mut(&mut self) -> &mut crate::datatypes::Float32 { &mut self.0 } } @@ -77,9 +76,7 @@ impl ::re_types_core::Loggable for StrokeWidth { #[inline] fn arrow_datatype() -> arrow2::datatypes::DataType { - #![allow(clippy::wildcard_imports)] - use arrow2::datatypes::*; - DataType::Float32 + crate::datatypes::Float32::arrow_datatype() } fn to_arrow_opt<'a>( @@ -88,29 +85,12 @@ impl ::re_types_core::Loggable for StrokeWidth { where Self: Clone + 'a, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, datatypes::*}; - Ok({ - let (somes, data0): (Vec<_>, Vec<_>) = data - .into_iter() - .map(|datum| { - let datum: Option<::std::borrow::Cow<'a, Self>> = datum.map(Into::into); - let datum = datum.map(|datum| datum.into_owned().0); - (datum.is_some(), datum) - }) - .unzip(); - let data0_bitmap: Option = { - let any_nones = somes.iter().any(|some| !*some); - any_nones.then(|| somes.into()) - }; - PrimitiveArray::new( - Self::arrow_datatype(), - data0.into_iter().map(|v| v.unwrap_or_default()).collect(), - data0_bitmap, - ) - .boxed() - }) + crate::datatypes::Float32::to_arrow_opt(data.into_iter().map(|datum| { + datum.map(|datum| match datum.into() { + ::std::borrow::Cow::Borrowed(datum) => ::std::borrow::Cow::Borrowed(&datum.0), + ::std::borrow::Cow::Owned(datum) => ::std::borrow::Cow::Owned(datum.0), + }) + })) } fn from_arrow_opt( @@ -119,25 +99,8 @@ impl ::re_types_core::Loggable for StrokeWidth { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - Ok(arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = Self::arrow_datatype(); - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.components.StrokeWidth#width")? - .into_iter() - .map(|opt| opt.copied()) - .map(|v| v.ok_or_else(DeserializationError::missing_data)) - .map(|res| res.map(|v| Some(Self(v)))) - .collect::>>>() - .with_context("rerun.components.StrokeWidth#width") - .with_context("rerun.components.StrokeWidth")?) + crate::datatypes::Float32::from_arrow_opt(arrow_data) + .map(|v| v.into_iter().map(|v| v.map(Self)).collect()) } #[inline] @@ -145,29 +108,6 @@ impl ::re_types_core::Loggable for StrokeWidth { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - if let Some(validity) = arrow_data.validity() { - if validity.unset_bits() != 0 { - return Err(DeserializationError::missing_data()); - } - } - Ok({ - let slice = arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = DataType::Float32; - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.components.StrokeWidth#width")? - .values() - .as_slice(); - { - slice.iter().copied().map(Self).collect::>() - } - }) + crate::datatypes::Float32::from_arrow(arrow_data).map(bytemuck::cast_vec) } } diff --git a/crates/store/re_types/src/components/stroke_width_ext.rs b/crates/store/re_types/src/components/stroke_width_ext.rs index 28dabce213c7..7bc98a4f0391 100644 --- a/crates/store/re_types/src/components/stroke_width_ext.rs +++ b/crates/store/re_types/src/components/stroke_width_ext.rs @@ -1,8 +1,10 @@ +use re_types_core::datatypes::Float32; + use super::StrokeWidth; impl Default for StrokeWidth { #[inline] fn default() -> Self { - Self(8.0) // Reminder: these are ui points. Picking 1.0 is too small, 0.0 is invisible. + Self(Float32(8.0)) // Reminder: these are ui points. Picking 1.0 is too small, 0.0 is invisible. } } diff --git a/crates/store/re_types/src/components/view_coordinates.rs b/crates/store/re_types/src/components/view_coordinates.rs index b81efe09d25b..e2e19b78de3e 100644 --- a/crates/store/re_types/src/components/view_coordinates.rs +++ b/crates/store/re_types/src/components/view_coordinates.rs @@ -38,7 +38,7 @@ use ::re_types_core::{DeserializationError, DeserializationResult}; #[repr(transparent)] pub struct ViewCoordinates( /// The directions of the [x, y, z] axes. - pub [u8; 3usize], + pub crate::datatypes::ViewCoordinates, ); impl ::re_types_core::SizeBytes for ViewCoordinates { @@ -49,36 +49,35 @@ impl ::re_types_core::SizeBytes for ViewCoordinates { #[inline] fn is_pod() -> bool { - <[u8; 3usize]>::is_pod() + ::is_pod() } } -impl From<[u8; 3usize]> for ViewCoordinates { - #[inline] - fn from(coordinates: [u8; 3usize]) -> Self { - Self(coordinates) +impl> From for ViewCoordinates { + fn from(v: T) -> Self { + Self(v.into()) } } -impl From for [u8; 3usize] { +impl std::borrow::Borrow for ViewCoordinates { #[inline] - fn from(value: ViewCoordinates) -> Self { - value.0 + fn borrow(&self) -> &crate::datatypes::ViewCoordinates { + &self.0 } } impl std::ops::Deref for ViewCoordinates { - type Target = [u8; 3usize]; + type Target = crate::datatypes::ViewCoordinates; #[inline] - fn deref(&self) -> &[u8; 3usize] { + fn deref(&self) -> &crate::datatypes::ViewCoordinates { &self.0 } } impl std::ops::DerefMut for ViewCoordinates { #[inline] - fn deref_mut(&mut self) -> &mut [u8; 3usize] { + fn deref_mut(&mut self) -> &mut crate::datatypes::ViewCoordinates { &mut self.0 } } @@ -95,12 +94,7 @@ impl ::re_types_core::Loggable for ViewCoordinates { #[inline] fn arrow_datatype() -> arrow2::datatypes::DataType { - #![allow(clippy::wildcard_imports)] - use arrow2::datatypes::*; - DataType::FixedSizeList( - std::sync::Arc::new(Field::new("item", DataType::UInt8, false)), - 3usize, - ) + crate::datatypes::ViewCoordinates::arrow_datatype() } fn to_arrow_opt<'a>( @@ -109,55 +103,12 @@ impl ::re_types_core::Loggable for ViewCoordinates { where Self: Clone + 'a, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, datatypes::*}; - Ok({ - let (somes, data0): (Vec<_>, Vec<_>) = data - .into_iter() - .map(|datum| { - let datum: Option<::std::borrow::Cow<'a, Self>> = datum.map(Into::into); - let datum = datum.map(|datum| datum.into_owned().0); - (datum.is_some(), datum) - }) - .unzip(); - let data0_bitmap: Option = { - let any_nones = somes.iter().any(|some| !*some); - any_nones.then(|| somes.into()) - }; - { - use arrow2::{buffer::Buffer, offset::OffsetsBuffer}; - let data0_inner_data: Vec<_> = data0 - .into_iter() - .flat_map(|v| match v { - Some(v) => itertools::Either::Left(v.into_iter()), - None => itertools::Either::Right( - std::iter::repeat(Default::default()).take(3usize), - ), - }) - .collect(); - let data0_inner_bitmap: Option = - data0_bitmap.as_ref().map(|bitmap| { - bitmap - .iter() - .map(|b| std::iter::repeat(b).take(3usize)) - .flatten() - .collect::>() - .into() - }); - FixedSizeListArray::new( - Self::arrow_datatype(), - PrimitiveArray::new( - DataType::UInt8, - data0_inner_data.into_iter().collect(), - data0_inner_bitmap, - ) - .boxed(), - data0_bitmap, - ) - .boxed() - } - }) + crate::datatypes::ViewCoordinates::to_arrow_opt(data.into_iter().map(|datum| { + datum.map(|datum| match datum.into() { + ::std::borrow::Cow::Borrowed(datum) => ::std::borrow::Cow::Borrowed(&datum.0), + ::std::borrow::Cow::Owned(datum) => ::std::borrow::Cow::Owned(datum.0), + }) + })) } fn from_arrow_opt( @@ -166,73 +117,8 @@ impl ::re_types_core::Loggable for ViewCoordinates { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - Ok({ - let arrow_data = arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = Self::arrow_datatype(); - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.components.ViewCoordinates#coordinates")?; - if arrow_data.is_empty() { - Vec::new() - } else { - let offsets = (0..) - .step_by(3usize) - .zip((3usize..).step_by(3usize).take(arrow_data.len())); - let arrow_data_inner = { - let arrow_data_inner = &**arrow_data.values(); - arrow_data_inner - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = DataType::UInt8; - let actual = arrow_data_inner.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.components.ViewCoordinates#coordinates")? - .into_iter() - .map(|opt| opt.copied()) - .collect::>() - }; - arrow2::bitmap::utils::ZipValidity::new_with_validity( - offsets, - arrow_data.validity(), - ) - .map(|elem| { - elem.map(|(start, end): (usize, usize)| { - debug_assert!(end - start == 3usize); - if end > arrow_data_inner.len() { - return Err(DeserializationError::offset_slice_oob( - (start, end), - arrow_data_inner.len(), - )); - } - - #[allow(unsafe_code, clippy::undocumented_unsafe_blocks)] - let data = unsafe { arrow_data_inner.get_unchecked(start..end) }; - let data = data.iter().cloned().map(Option::unwrap_or_default); - - // NOTE: Unwrapping cannot fail: the length must be correct. - #[allow(clippy::unwrap_used)] - Ok(array_init::from_iter(data).unwrap()) - }) - .transpose() - }) - .collect::>>>()? - } - .into_iter() - } - .map(|v| v.ok_or_else(DeserializationError::missing_data)) - .map(|res| res.map(|v| Some(Self(v)))) - .collect::>>>() - .with_context("rerun.components.ViewCoordinates#coordinates") - .with_context("rerun.components.ViewCoordinates")?) + crate::datatypes::ViewCoordinates::from_arrow_opt(arrow_data) + .map(|v| v.into_iter().map(|v| v.map(Self)).collect()) } #[inline] @@ -240,46 +126,6 @@ impl ::re_types_core::Loggable for ViewCoordinates { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - if let Some(validity) = arrow_data.validity() { - if validity.unset_bits() != 0 { - return Err(DeserializationError::missing_data()); - } - } - Ok({ - let slice = { - let arrow_data = arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = DataType::FixedSizeList( - std::sync::Arc::new(Field::new("item", DataType::UInt8, false)), - 3usize, - ); - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.components.ViewCoordinates#coordinates")?; - let arrow_data_inner = &**arrow_data.values(); - bytemuck::cast_slice::<_, [_; 3usize]>( - arrow_data_inner - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = DataType::UInt8; - let actual = arrow_data_inner.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.components.ViewCoordinates#coordinates")? - .values() - .as_slice(), - ) - }; - { - slice.iter().copied().map(Self).collect::>() - } - }) + crate::datatypes::ViewCoordinates::from_arrow(arrow_data).map(bytemuck::cast_vec) } } diff --git a/crates/store/re_types/src/components/view_coordinates_ext.rs b/crates/store/re_types/src/components/view_coordinates_ext.rs index 40e2c82fa921..3d4342816c21 100644 --- a/crates/store/re_types/src/components/view_coordinates_ext.rs +++ b/crates/store/re_types/src/components/view_coordinates_ext.rs @@ -2,6 +2,7 @@ // ---------------------------------------------------------------------------- +use crate::datatypes; use crate::view_coordinates::{Axis3, Handedness, Sign, SignedAxis3, ViewDir}; use super::ViewCoordinates; @@ -9,7 +10,7 @@ use super::ViewCoordinates; impl ViewCoordinates { /// Construct a new `ViewCoordinates` from an array of [`ViewDir`]s. pub const fn new(x: ViewDir, y: ViewDir, z: ViewDir) -> Self { - Self([x as u8, y as u8, z as u8]) + Self(datatypes::ViewCoordinates([x as u8, y as u8, z as u8])) } /// Chooses a coordinate system based on just an up-axis. @@ -38,7 +39,7 @@ impl ViewCoordinates { /// Returns an error if this does not span all three dimensions. pub fn sanity_check(&self) -> Result<(), String> { let mut dims = [false; 3]; - for dir in self.0 { + for dir in *self.0 { let dim = match ViewDir::try_from(dir)? { ViewDir::Up | ViewDir::Down => 0, ViewDir::Right | ViewDir::Left => 1, @@ -59,7 +60,7 @@ impl ViewCoordinates { /// The up-axis. #[inline] pub fn up(&self) -> Option { - for (dim, &dir) in self.0.iter().enumerate() { + for (dim, &dir) in self.iter().enumerate() { if dir == ViewDir::Up as u8 { return Some(SignedAxis3::new(Sign::Positive, Axis3::from_dim(dim))); } else if dir == ViewDir::Down as u8 { @@ -72,7 +73,7 @@ impl ViewCoordinates { /// The right-axis. #[inline] pub fn right(&self) -> Option { - for (dim, &dir) in self.0.iter().enumerate() { + for (dim, &dir) in self.iter().enumerate() { if dir == ViewDir::Right as u8 { return Some(SignedAxis3::new(Sign::Positive, Axis3::from_dim(dim))); } else if dir == ViewDir::Left as u8 { @@ -85,7 +86,7 @@ impl ViewCoordinates { /// The forward-axis. #[inline] pub fn forward(&self) -> Option { - for (dim, &dir) in self.0.iter().enumerate() { + for (dim, &dir) in self.iter().enumerate() { if dir == ViewDir::Forward as u8 { return Some(SignedAxis3::new(Sign::Positive, Axis3::from_dim(dim))); } else if dir == ViewDir::Back as u8 { @@ -97,7 +98,7 @@ impl ViewCoordinates { /// Describe using three letters, e.g. `RDF` for X=Right, Y=Down, Z=Forward. pub fn describe_short(&self) -> String { - let [x, y, z] = self.0; + let [x, y, z] = *self.0; let x = ViewDir::try_from(x).map(|x| x.short()).unwrap_or("?"); let y = ViewDir::try_from(y).map(|y| y.short()).unwrap_or("?"); let z = ViewDir::try_from(z).map(|z| z.short()).unwrap_or("?"); @@ -106,7 +107,7 @@ impl ViewCoordinates { /// A long description of the coordinate system, explicitly writing out all directions. pub fn describe(&self) -> String { - let [x, y, z] = self.0; + let [x, y, z] = *self.0; let x_short = ViewDir::try_from(x).map(|x| x.short()).unwrap_or("?"); let y_short = ViewDir::try_from(y).map(|y| y.short()).unwrap_or("?"); let z_short = ViewDir::try_from(z).map(|z| z.short()).unwrap_or("?"); @@ -272,7 +273,11 @@ impl Default for ViewCoordinates { macro_rules! define_coordinates { ($docstring:literal, $name:ident => ($x:ident, $y:ident, $z:ident) ) => { #[doc = $docstring] - pub const $name: Self = Self([ViewDir::$x as u8, ViewDir::$y as u8, ViewDir::$z as u8]); + pub const $name: Self = Self(datatypes::ViewCoordinates([ + ViewDir::$x as u8, + ViewDir::$y as u8, + ViewDir::$z as u8, + ])); }; } diff --git a/crates/store/re_types/src/datatypes/.gitattributes b/crates/store/re_types/src/datatypes/.gitattributes index afabb7a21d9c..d2d2a1195e5d 100644 --- a/crates/store/re_types/src/datatypes/.gitattributes +++ b/crates/store/re_types/src/datatypes/.gitattributes @@ -3,7 +3,7 @@ .gitattributes linguist-generated=true angle.rs linguist-generated=true annotation_info.rs linguist-generated=true -bool.rs linguist-generated=true +blob.rs linguist-generated=true class_description.rs linguist-generated=true class_description_map_elem.rs linguist-generated=true class_id.rs linguist-generated=true @@ -35,3 +35,4 @@ uvec4d.rs linguist-generated=true vec2d.rs linguist-generated=true vec3d.rs linguist-generated=true vec4d.rs linguist-generated=true +view_coordinates.rs linguist-generated=true diff --git a/crates/store/re_types/src/datatypes/blob.rs b/crates/store/re_types/src/datatypes/blob.rs new file mode 100644 index 000000000000..82984cae3444 --- /dev/null +++ b/crates/store/re_types/src/datatypes/blob.rs @@ -0,0 +1,195 @@ +// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/rust/api.rs +// Based on "crates/store/re_types/definitions/rerun/datatypes/blob.fbs". + +#![allow(unused_imports)] +#![allow(unused_parens)] +#![allow(clippy::clone_on_copy)] +#![allow(clippy::cloned_instead_of_copied)] +#![allow(clippy::map_flatten)] +#![allow(clippy::needless_question_mark)] +#![allow(clippy::new_without_default)] +#![allow(clippy::redundant_closure)] +#![allow(clippy::too_many_arguments)] +#![allow(clippy::too_many_lines)] + +use ::re_types_core::external::arrow2; +use ::re_types_core::ComponentName; +use ::re_types_core::SerializationResult; +use ::re_types_core::{ComponentBatch, MaybeOwnedComponentBatch}; +use ::re_types_core::{DeserializationError, DeserializationResult}; + +/// **Datatype**: A binary blob of data. +#[derive(Clone, Debug, PartialEq, Eq)] +#[repr(transparent)] +pub struct Blob(pub ::re_types_core::ArrowBuffer); + +impl ::re_types_core::SizeBytes for Blob { + #[inline] + fn heap_size_bytes(&self) -> u64 { + self.0.heap_size_bytes() + } + + #[inline] + fn is_pod() -> bool { + <::re_types_core::ArrowBuffer>::is_pod() + } +} + +impl From<::re_types_core::ArrowBuffer> for Blob { + #[inline] + fn from(data: ::re_types_core::ArrowBuffer) -> Self { + Self(data) + } +} + +impl From for ::re_types_core::ArrowBuffer { + #[inline] + fn from(value: Blob) -> Self { + value.0 + } +} + +::re_types_core::macros::impl_into_cow!(Blob); + +impl ::re_types_core::Loggable for Blob { + type Name = ::re_types_core::DatatypeName; + + #[inline] + fn name() -> Self::Name { + "rerun.datatypes.Blob".into() + } + + #[inline] + fn arrow_datatype() -> arrow2::datatypes::DataType { + #![allow(clippy::wildcard_imports)] + use arrow2::datatypes::*; + DataType::List(std::sync::Arc::new(Field::new( + "item", + DataType::UInt8, + false, + ))) + } + + fn to_arrow_opt<'a>( + data: impl IntoIterator>>>, + ) -> SerializationResult> + where + Self: Clone + 'a, + { + #![allow(clippy::wildcard_imports)] + use ::re_types_core::{Loggable as _, ResultExt as _}; + use arrow2::{array::*, datatypes::*}; + Ok({ + let (somes, data0): (Vec<_>, Vec<_>) = data + .into_iter() + .map(|datum| { + let datum: Option<::std::borrow::Cow<'a, Self>> = datum.map(Into::into); + let datum = datum.map(|datum| datum.into_owned().0); + (datum.is_some(), datum) + }) + .unzip(); + let data0_bitmap: Option = { + let any_nones = somes.iter().any(|some| !*some); + any_nones.then(|| somes.into()) + }; + { + use arrow2::{buffer::Buffer, offset::OffsetsBuffer}; + let offsets = arrow2::offset::Offsets::::try_from_lengths( + data0 + .iter() + .map(|opt| opt.as_ref().map_or(0, |datum| datum.num_instances())), + )? + .into(); + let data0_inner_data: Buffer<_> = data0 + .iter() + .flatten() + .map(|b| b.as_slice()) + .collect::>() + .concat() + .into(); + let data0_inner_bitmap: Option = None; + ListArray::try_new( + Self::arrow_datatype(), + offsets, + PrimitiveArray::new(DataType::UInt8, data0_inner_data, data0_inner_bitmap) + .boxed(), + data0_bitmap, + )? + .boxed() + } + }) + } + + fn from_arrow_opt( + arrow_data: &dyn arrow2::array::Array, + ) -> DeserializationResult>> + where + Self: Sized, + { + #![allow(clippy::wildcard_imports)] + use ::re_types_core::{Loggable as _, ResultExt as _}; + use arrow2::{array::*, buffer::*, datatypes::*}; + Ok({ + let arrow_data = arrow_data + .as_any() + .downcast_ref::>() + .ok_or_else(|| { + let expected = Self::arrow_datatype(); + let actual = arrow_data.data_type().clone(); + DeserializationError::datatype_mismatch(expected, actual) + }) + .with_context("rerun.datatypes.Blob#data")?; + if arrow_data.is_empty() { + Vec::new() + } else { + let arrow_data_inner = { + let arrow_data_inner = &**arrow_data.values(); + arrow_data_inner + .as_any() + .downcast_ref::() + .ok_or_else(|| { + let expected = DataType::UInt8; + let actual = arrow_data_inner.data_type().clone(); + DeserializationError::datatype_mismatch(expected, actual) + }) + .with_context("rerun.datatypes.Blob#data")? + .values() + }; + let offsets = arrow_data.offsets(); + arrow2::bitmap::utils::ZipValidity::new_with_validity( + offsets.iter().zip(offsets.lengths()), + arrow_data.validity(), + ) + .map(|elem| { + elem.map(|(start, len)| { + let start = *start as usize; + let end = start + len; + if end > arrow_data_inner.len() { + return Err(DeserializationError::offset_slice_oob( + (start, end), + arrow_data_inner.len(), + )); + } + + #[allow(unsafe_code, clippy::undocumented_unsafe_blocks)] + let data = unsafe { + arrow_data_inner + .clone() + .sliced_unchecked(start, end - start) + }; + let data = ::re_types_core::ArrowBuffer::from(data); + Ok(data) + }) + .transpose() + }) + .collect::>>>()? + } + .into_iter() + } + .map(|v| v.ok_or_else(DeserializationError::missing_data)) + .map(|res| res.map(|v| Some(Self(v)))) + .collect::>>>() + .with_context("rerun.datatypes.Blob#data") + .with_context("rerun.datatypes.Blob")?) + } +} diff --git a/crates/store/re_types/src/components/blob_ext.rs b/crates/store/re_types/src/datatypes/blob_ext.rs similarity index 55% rename from crates/store/re_types/src/components/blob_ext.rs rename to crates/store/re_types/src/datatypes/blob_ext.rs index 09a9cdaf5366..eb580325d0e6 100644 --- a/crates/store/re_types/src/components/blob_ext.rs +++ b/crates/store/re_types/src/datatypes/blob_ext.rs @@ -12,3 +12,12 @@ impl Default for Blob { Self(Vec::new().into()) } } + +impl std::ops::Deref for Blob { + type Target = re_types_core::ArrowBuffer; + + #[inline] + fn deref(&self) -> &re_types_core::ArrowBuffer { + &self.0 + } +} diff --git a/crates/store/re_types/src/datatypes/bool_ext.rs b/crates/store/re_types/src/datatypes/bool_ext.rs deleted file mode 100644 index e69408b1d06a..000000000000 --- a/crates/store/re_types/src/datatypes/bool_ext.rs +++ /dev/null @@ -1,12 +0,0 @@ -use std::ops::Deref; - -use super::Bool; - -impl Deref for Bool { - type Target = bool; - - #[inline] - fn deref(&self) -> &Self::Target { - &self.0 - } -} diff --git a/crates/store/re_types/src/datatypes/mod.rs b/crates/store/re_types/src/datatypes/mod.rs index c67ff92517e5..355b74feb7ff 100644 --- a/crates/store/re_types/src/datatypes/mod.rs +++ b/crates/store/re_types/src/datatypes/mod.rs @@ -4,8 +4,8 @@ mod angle; mod angle_ext; mod annotation_info; mod annotation_info_ext; -mod bool; -mod bool_ext; +mod blob; +mod blob_ext; mod class_description; mod class_description_ext; mod class_description_map_elem; @@ -65,10 +65,12 @@ mod vec3d; mod vec3d_ext; mod vec4d; mod vec4d_ext; +mod view_coordinates; +mod view_coordinates_ext; pub use self::angle::Angle; pub use self::annotation_info::AnnotationInfo; -pub use self::bool::Bool; +pub use self::blob::Blob; pub use self::class_description::ClassDescription; pub use self::class_description_map_elem::ClassDescriptionMapElem; pub use self::class_id::ClassId; @@ -99,3 +101,4 @@ pub use self::uvec4d::UVec4D; pub use self::vec2d::Vec2D; pub use self::vec3d::Vec3D; pub use self::vec4d::Vec4D; +pub use self::view_coordinates::ViewCoordinates; diff --git a/crates/store/re_types/src/datatypes/range2d_ext.rs b/crates/store/re_types/src/datatypes/range2d_ext.rs index cf233f61222b..49267ea795db 100644 --- a/crates/store/re_types/src/datatypes/range2d_ext.rs +++ b/crates/store/re_types/src/datatypes/range2d_ext.rs @@ -27,14 +27,11 @@ impl From for emath::Rect { impl std::fmt::Display for Range2D { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let prec = f.precision().unwrap_or(crate::DEFAULT_DISPLAY_DECIMALS); write!( f, "[{:.prec$}, {:.prec$}]×[{:.prec$}, {:.prec$}]", - self.x_range.0[0], - self.x_range.0[1], - self.y_range.0[0], - self.y_range.0[1], - prec = crate::DISPLAY_PRECISION, + self.x_range.0[0], self.x_range.0[1], self.y_range.0[0], self.y_range.0[1], ) } } diff --git a/crates/store/re_types/src/datatypes/uvec4d_ext.rs b/crates/store/re_types/src/datatypes/uvec4d_ext.rs index ff97921bd9c6..462dce9faadd 100644 --- a/crates/store/re_types/src/datatypes/uvec4d_ext.rs +++ b/crates/store/re_types/src/datatypes/uvec4d_ext.rs @@ -99,6 +99,7 @@ impl From for UVec4D { impl std::fmt::Display for UVec4D { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let prec = f.precision().unwrap_or(crate::DEFAULT_DISPLAY_DECIMALS); write!( f, "[{:.prec$}, {:.prec$}, {:.prec$}, {:.prec$}]", @@ -106,7 +107,6 @@ impl std::fmt::Display for UVec4D { self.y(), self.z(), self.w(), - prec = crate::DISPLAY_PRECISION, ) } } diff --git a/crates/store/re_types/src/datatypes/vec2d_ext.rs b/crates/store/re_types/src/datatypes/vec2d_ext.rs index 722788487d4d..de480aef70cc 100644 --- a/crates/store/re_types/src/datatypes/vec2d_ext.rs +++ b/crates/store/re_types/src/datatypes/vec2d_ext.rs @@ -101,12 +101,7 @@ impl From> for Vec2D { impl std::fmt::Display for Vec2D { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - f, - "[{:.prec$}, {:.prec$}]", - self.x(), - self.y(), - prec = crate::DISPLAY_PRECISION, - ) + let prec = f.precision().unwrap_or(crate::DEFAULT_DISPLAY_DECIMALS); + write!(f, "[{:.prec$}, {:.prec$}]", self.x(), self.y(),) } } diff --git a/crates/store/re_types/src/datatypes/vec3d_ext.rs b/crates/store/re_types/src/datatypes/vec3d_ext.rs index 7a4418ae57d1..4a2471284c9c 100644 --- a/crates/store/re_types/src/datatypes/vec3d_ext.rs +++ b/crates/store/re_types/src/datatypes/vec3d_ext.rs @@ -113,13 +113,13 @@ impl From> for Vec3D { impl std::fmt::Display for Vec3D { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let prec = f.precision().unwrap_or(crate::DEFAULT_DISPLAY_DECIMALS); write!( f, "[{:.prec$}, {:.prec$}, {:.prec$}]", self.x(), self.y(), self.z(), - prec = crate::DISPLAY_PRECISION, ) } } diff --git a/crates/store/re_types/src/datatypes/vec4d_ext.rs b/crates/store/re_types/src/datatypes/vec4d_ext.rs index f52cc0f2f036..6bd3dc234742 100644 --- a/crates/store/re_types/src/datatypes/vec4d_ext.rs +++ b/crates/store/re_types/src/datatypes/vec4d_ext.rs @@ -117,6 +117,7 @@ impl From> for Vec4D { impl std::fmt::Display for Vec4D { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let prec = f.precision().unwrap_or(crate::DEFAULT_DISPLAY_DECIMALS); write!( f, "[{:.prec$}, {:.prec$}, {:.prec$}, {:.prec$}]", @@ -124,7 +125,6 @@ impl std::fmt::Display for Vec4D { self.y(), self.z(), self.w(), - prec = crate::DISPLAY_PRECISION, ) } } diff --git a/crates/store/re_types/src/datatypes/view_coordinates.rs b/crates/store/re_types/src/datatypes/view_coordinates.rs new file mode 100644 index 000000000000..c2b019d252cc --- /dev/null +++ b/crates/store/re_types/src/datatypes/view_coordinates.rs @@ -0,0 +1,269 @@ +// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/rust/api.rs +// Based on "crates/store/re_types/definitions/rerun/datatypes/view_coordinates.fbs". + +#![allow(unused_imports)] +#![allow(unused_parens)] +#![allow(clippy::clone_on_copy)] +#![allow(clippy::cloned_instead_of_copied)] +#![allow(clippy::map_flatten)] +#![allow(clippy::needless_question_mark)] +#![allow(clippy::new_without_default)] +#![allow(clippy::redundant_closure)] +#![allow(clippy::too_many_arguments)] +#![allow(clippy::too_many_lines)] + +use ::re_types_core::external::arrow2; +use ::re_types_core::ComponentName; +use ::re_types_core::SerializationResult; +use ::re_types_core::{ComponentBatch, MaybeOwnedComponentBatch}; +use ::re_types_core::{DeserializationError, DeserializationResult}; + +/// **Datatype**: How we interpret the coordinate system of an entity/space. +/// +/// For instance: What is "up"? What does the Z axis mean? Is this right-handed or left-handed? +/// +/// The three coordinates are always ordered as [x, y, z]. +/// +/// For example [Right, Down, Forward] means that the X axis points to the right, the Y axis points +/// down, and the Z axis points forward. +/// +/// The following constants are used to represent the different directions: +/// * Up = 1 +/// * Down = 2 +/// * Right = 3 +/// * Left = 4 +/// * Forward = 5 +/// * Back = 6 +#[derive(Clone, Debug, Copy, PartialEq, Eq, bytemuck::Pod, bytemuck::Zeroable)] +#[repr(transparent)] +pub struct ViewCoordinates( + /// The directions of the [x, y, z] axes. + pub [u8; 3usize], +); + +impl ::re_types_core::SizeBytes for ViewCoordinates { + #[inline] + fn heap_size_bytes(&self) -> u64 { + self.0.heap_size_bytes() + } + + #[inline] + fn is_pod() -> bool { + <[u8; 3usize]>::is_pod() + } +} + +impl From<[u8; 3usize]> for ViewCoordinates { + #[inline] + fn from(coordinates: [u8; 3usize]) -> Self { + Self(coordinates) + } +} + +impl From for [u8; 3usize] { + #[inline] + fn from(value: ViewCoordinates) -> Self { + value.0 + } +} + +::re_types_core::macros::impl_into_cow!(ViewCoordinates); + +impl ::re_types_core::Loggable for ViewCoordinates { + type Name = ::re_types_core::DatatypeName; + + #[inline] + fn name() -> Self::Name { + "rerun.datatypes.ViewCoordinates".into() + } + + #[inline] + fn arrow_datatype() -> arrow2::datatypes::DataType { + #![allow(clippy::wildcard_imports)] + use arrow2::datatypes::*; + DataType::FixedSizeList( + std::sync::Arc::new(Field::new("item", DataType::UInt8, false)), + 3usize, + ) + } + + fn to_arrow_opt<'a>( + data: impl IntoIterator>>>, + ) -> SerializationResult> + where + Self: Clone + 'a, + { + #![allow(clippy::wildcard_imports)] + use ::re_types_core::{Loggable as _, ResultExt as _}; + use arrow2::{array::*, datatypes::*}; + Ok({ + let (somes, data0): (Vec<_>, Vec<_>) = data + .into_iter() + .map(|datum| { + let datum: Option<::std::borrow::Cow<'a, Self>> = datum.map(Into::into); + let datum = datum.map(|datum| datum.into_owned().0); + (datum.is_some(), datum) + }) + .unzip(); + let data0_bitmap: Option = { + let any_nones = somes.iter().any(|some| !*some); + any_nones.then(|| somes.into()) + }; + { + use arrow2::{buffer::Buffer, offset::OffsetsBuffer}; + let data0_inner_data: Vec<_> = data0 + .into_iter() + .flat_map(|v| match v { + Some(v) => itertools::Either::Left(v.into_iter()), + None => itertools::Either::Right( + std::iter::repeat(Default::default()).take(3usize), + ), + }) + .collect(); + let data0_inner_bitmap: Option = + data0_bitmap.as_ref().map(|bitmap| { + bitmap + .iter() + .map(|b| std::iter::repeat(b).take(3usize)) + .flatten() + .collect::>() + .into() + }); + FixedSizeListArray::new( + Self::arrow_datatype(), + PrimitiveArray::new( + DataType::UInt8, + data0_inner_data.into_iter().collect(), + data0_inner_bitmap, + ) + .boxed(), + data0_bitmap, + ) + .boxed() + } + }) + } + + fn from_arrow_opt( + arrow_data: &dyn arrow2::array::Array, + ) -> DeserializationResult>> + where + Self: Sized, + { + #![allow(clippy::wildcard_imports)] + use ::re_types_core::{Loggable as _, ResultExt as _}; + use arrow2::{array::*, buffer::*, datatypes::*}; + Ok({ + let arrow_data = arrow_data + .as_any() + .downcast_ref::() + .ok_or_else(|| { + let expected = Self::arrow_datatype(); + let actual = arrow_data.data_type().clone(); + DeserializationError::datatype_mismatch(expected, actual) + }) + .with_context("rerun.datatypes.ViewCoordinates#coordinates")?; + if arrow_data.is_empty() { + Vec::new() + } else { + let offsets = (0..) + .step_by(3usize) + .zip((3usize..).step_by(3usize).take(arrow_data.len())); + let arrow_data_inner = { + let arrow_data_inner = &**arrow_data.values(); + arrow_data_inner + .as_any() + .downcast_ref::() + .ok_or_else(|| { + let expected = DataType::UInt8; + let actual = arrow_data_inner.data_type().clone(); + DeserializationError::datatype_mismatch(expected, actual) + }) + .with_context("rerun.datatypes.ViewCoordinates#coordinates")? + .into_iter() + .map(|opt| opt.copied()) + .collect::>() + }; + arrow2::bitmap::utils::ZipValidity::new_with_validity( + offsets, + arrow_data.validity(), + ) + .map(|elem| { + elem.map(|(start, end): (usize, usize)| { + debug_assert!(end - start == 3usize); + if end > arrow_data_inner.len() { + return Err(DeserializationError::offset_slice_oob( + (start, end), + arrow_data_inner.len(), + )); + } + + #[allow(unsafe_code, clippy::undocumented_unsafe_blocks)] + let data = unsafe { arrow_data_inner.get_unchecked(start..end) }; + let data = data.iter().cloned().map(Option::unwrap_or_default); + + // NOTE: Unwrapping cannot fail: the length must be correct. + #[allow(clippy::unwrap_used)] + Ok(array_init::from_iter(data).unwrap()) + }) + .transpose() + }) + .collect::>>>()? + } + .into_iter() + } + .map(|v| v.ok_or_else(DeserializationError::missing_data)) + .map(|res| res.map(|v| Some(Self(v)))) + .collect::>>>() + .with_context("rerun.datatypes.ViewCoordinates#coordinates") + .with_context("rerun.datatypes.ViewCoordinates")?) + } + + #[inline] + fn from_arrow(arrow_data: &dyn arrow2::array::Array) -> DeserializationResult> + where + Self: Sized, + { + #![allow(clippy::wildcard_imports)] + use ::re_types_core::{Loggable as _, ResultExt as _}; + use arrow2::{array::*, buffer::*, datatypes::*}; + if let Some(validity) = arrow_data.validity() { + if validity.unset_bits() != 0 { + return Err(DeserializationError::missing_data()); + } + } + Ok({ + let slice = { + let arrow_data = arrow_data + .as_any() + .downcast_ref::() + .ok_or_else(|| { + let expected = DataType::FixedSizeList( + std::sync::Arc::new(Field::new("item", DataType::UInt8, false)), + 3usize, + ); + let actual = arrow_data.data_type().clone(); + DeserializationError::datatype_mismatch(expected, actual) + }) + .with_context("rerun.datatypes.ViewCoordinates#coordinates")?; + let arrow_data_inner = &**arrow_data.values(); + bytemuck::cast_slice::<_, [_; 3usize]>( + arrow_data_inner + .as_any() + .downcast_ref::() + .ok_or_else(|| { + let expected = DataType::UInt8; + let actual = arrow_data_inner.data_type().clone(); + DeserializationError::datatype_mismatch(expected, actual) + }) + .with_context("rerun.datatypes.ViewCoordinates#coordinates")? + .values() + .as_slice(), + ) + }; + { + slice.iter().copied().map(Self).collect::>() + } + }) + } +} diff --git a/crates/store/re_types/src/datatypes/view_coordinates_ext.rs b/crates/store/re_types/src/datatypes/view_coordinates_ext.rs new file mode 100644 index 000000000000..298f271dbe8e --- /dev/null +++ b/crates/store/re_types/src/datatypes/view_coordinates_ext.rs @@ -0,0 +1,17 @@ +use super::ViewCoordinates; + +impl std::ops::Deref for ViewCoordinates { + type Target = [u8; 3]; + + #[inline] + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl std::ops::DerefMut for ViewCoordinates { + #[inline] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} diff --git a/crates/store/re_types/src/lib.rs b/crates/store/re_types/src/lib.rs index 655d42b0a3ff..6ac3162e82c1 100644 --- a/crates/store/re_types/src/lib.rs +++ b/crates/store/re_types/src/lib.rs @@ -175,10 +175,10 @@ // --- -/// Number of decimals shown for all vector display methods. -pub const DISPLAY_PRECISION: usize = 3; +/// Number of decimals shown for all float display methods. +pub use re_types_core::DEFAULT_DISPLAY_DECIMALS; -/// Acrchetype are the high-level things you can log, like [`Image`][archetypes::Image], [`Points3D`][archetypes::Points3D], etc. +/// Archetype are the high-level things you can log, like [`Image`][archetypes::Image], [`Points3D`][archetypes::Points3D], etc. /// /// All archetypes implement the [`Archetype`] trait. /// diff --git a/crates/store/re_types/tests/arrows3d.rs b/crates/store/re_types/tests/arrows3d.rs index f7d68a60a1ff..35e98a725bfd 100644 --- a/crates/store/re_types/tests/arrows3d.rs +++ b/crates/store/re_types/tests/arrows3d.rs @@ -19,8 +19,8 @@ fn roundtrip() { Position3D(Vec3D([40.0, 50.0, 60.0])), // ]), radii: Some(vec![ - Radius(1.0), // - Radius(10.0), + Radius::from(1.0), // + Radius::from(10.0), ]), colors: Some(vec![ Color::from_unmultiplied_rgba(0xAA, 0x00, 0x00, 0xCC), // diff --git a/crates/store/re_types/tests/box2d.rs b/crates/store/re_types/tests/box2d.rs index 7b3ba81ee680..6f3dbfd2474f 100644 --- a/crates/store/re_types/tests/box2d.rs +++ b/crates/store/re_types/tests/box2d.rs @@ -18,14 +18,14 @@ fn roundtrip() { components::Color::from_unmultiplied_rgba(0x00, 0xBB, 0x00, 0xDD), ]), radii: Some(vec![ - components::Radius(42.0), // - components::Radius(43.0), + components::Radius::from(42.0), // + components::Radius::from(43.0), ]), labels: Some(vec![ "hello".into(), // "friend".into(), // ]), - draw_order: Some(components::DrawOrder(300.0)), + draw_order: Some(components::DrawOrder(300.0.into())), class_ids: Some(vec![ components::ClassId::from(126), // components::ClassId::from(127), // diff --git a/crates/store/re_types/tests/box3d.rs b/crates/store/re_types/tests/box3d.rs index 8ed924766280..b9bd61b53f6d 100644 --- a/crates/store/re_types/tests/box3d.rs +++ b/crates/store/re_types/tests/box3d.rs @@ -25,8 +25,8 @@ fn roundtrip() { components::Color::from_unmultiplied_rgba(0x00, 0xBB, 0x00, 0xDD), ]), radii: Some(vec![ - components::Radius(42.0), // - components::Radius(43.0), + components::Radius::from(42.0), // + components::Radius::from(43.0), ]), labels: Some(vec![ "hello".into(), // diff --git a/crates/store/re_types/tests/clear.rs b/crates/store/re_types/tests/clear.rs index a83b146663d1..099e27fb46e1 100644 --- a/crates/store/re_types/tests/clear.rs +++ b/crates/store/re_types/tests/clear.rs @@ -1,17 +1,15 @@ use std::collections::HashMap; -use re_types::{ - archetypes::Clear, components::ClearIsRecursive, Archetype as _, AsComponents as _, -}; +use re_types::{archetypes::Clear, Archetype as _, AsComponents as _}; #[test] fn roundtrip() { let all_expected = [ Clear { - is_recursive: ClearIsRecursive(true), + is_recursive: true.into(), }, // Clear { - is_recursive: ClearIsRecursive(false), + is_recursive: false.into(), }, ]; diff --git a/crates/store/re_types/tests/depth_image.rs b/crates/store/re_types/tests/depth_image.rs index 98bae602712e..16b1e07bd383 100644 --- a/crates/store/re_types/tests/depth_image.rs +++ b/crates/store/re_types/tests/depth_image.rs @@ -26,7 +26,7 @@ fn depth_image_roundtrip() { buffer: TensorBuffer::U8(vec![1, 2, 3, 4, 5, 6].into()), } .into(), - meter: Some(DepthMeter(1000.0)), + meter: Some(DepthMeter::from(1000.0)), draw_order: None, colormap: None, point_fill_ratio: None, diff --git a/crates/store/re_types/tests/disconnected_space.rs b/crates/store/re_types/tests/disconnected_space.rs index 2412e9910c2b..dd3239db2b2d 100644 --- a/crates/store/re_types/tests/disconnected_space.rs +++ b/crates/store/re_types/tests/disconnected_space.rs @@ -1,15 +1,15 @@ use std::collections::HashMap; -use re_types::{archetypes::DisconnectedSpace, components, Archetype as _, AsComponents as _}; +use re_types::{archetypes::DisconnectedSpace, Archetype as _, AsComponents as _}; #[test] fn roundtrip() { let all_expected = [ DisconnectedSpace { - disconnected_space: components::DisconnectedSpace(true), + disconnected_space: true.into(), }, // DisconnectedSpace { - disconnected_space: components::DisconnectedSpace(false), + disconnected_space: false.into(), }, ]; diff --git a/crates/store/re_types/tests/line_strips2d.rs b/crates/store/re_types/tests/line_strips2d.rs index 8f65f0a00df2..8cd3139ae190 100644 --- a/crates/store/re_types/tests/line_strips2d.rs +++ b/crates/store/re_types/tests/line_strips2d.rs @@ -15,8 +15,8 @@ fn roundtrip() { LineStrip2D::from_iter([[0., 3.], [1., 4.], [2., 2.], [3., 4.], [4., 2.], [5., 4.], [6., 3.]]), // ], radii: Some(vec![ - Radius(42.0), // - Radius(43.0), + Radius::from(42.0), // + Radius::from(43.0), ]), colors: Some(vec![ Color::from_unmultiplied_rgba(0xAA, 0x00, 0x00, 0xCC), // @@ -26,7 +26,7 @@ fn roundtrip() { "hello".into(), // "friend".into(), // ]), - draw_order: Some(DrawOrder(300.0)), + draw_order: Some(DrawOrder(300.0.into())), class_ids: Some(vec![ ClassId::from(126), // ClassId::from(127), // diff --git a/crates/store/re_types/tests/line_strips3d.rs b/crates/store/re_types/tests/line_strips3d.rs index 7cad3a6e2c0a..69f92dfed1fb 100644 --- a/crates/store/re_types/tests/line_strips3d.rs +++ b/crates/store/re_types/tests/line_strips3d.rs @@ -15,8 +15,8 @@ fn roundtrip() { LineStrip3D::from_iter([[0., 3., 1.], [1., 4., 2.], [2., 2., 3.], [3., 4., 4.], [4., 2., 5.], [5., 4., 6.], [6., 3., 7.]]), ], radii: Some(vec![ - Radius(42.0), // - Radius(43.0), + Radius::from(42.0), // + Radius::from(43.0), ]), colors: Some(vec![ Color::from_unmultiplied_rgba(0xAA, 0x00, 0x00, 0xCC), // diff --git a/crates/store/re_types/tests/points2d.rs b/crates/store/re_types/tests/points2d.rs index 2c11a47ee875..61c55b809d93 100644 --- a/crates/store/re_types/tests/points2d.rs +++ b/crates/store/re_types/tests/points2d.rs @@ -10,8 +10,8 @@ fn roundtrip() { components::Position2D::new(3.0, 4.0), ], radii: Some(vec![ - components::Radius(42.0), // - components::Radius(43.0), + components::Radius::from(42.0), // + components::Radius::from(43.0), ]), colors: Some(vec![ components::Color::from_unmultiplied_rgba(0xAA, 0x00, 0x00, 0xCC), // @@ -21,7 +21,7 @@ fn roundtrip() { "hello".into(), // "friend".into(), // ]), - draw_order: Some(components::DrawOrder(300.0)), + draw_order: Some(components::DrawOrder(300.0.into())), class_ids: Some(vec![ components::ClassId::from(126), // components::ClassId::from(127), // diff --git a/crates/store/re_types/tests/points3d.rs b/crates/store/re_types/tests/points3d.rs index fe06fe99b69e..146d31db23e1 100644 --- a/crates/store/re_types/tests/points3d.rs +++ b/crates/store/re_types/tests/points3d.rs @@ -10,8 +10,8 @@ fn roundtrip() { components::Position3D::new(4.0, 5.0, 6.0), ], radii: Some(vec![ - components::Radius(42.0), // - components::Radius(43.0), + components::Radius::from(42.0), // + components::Radius::from(43.0), ]), colors: Some(vec![ components::Color::from_unmultiplied_rgba(0xAA, 0x00, 0x00, 0xCC), // diff --git a/crates/store/re_types_blueprint/src/blueprint/components/auto_layout.rs b/crates/store/re_types_blueprint/src/blueprint/components/auto_layout.rs index 53499ec5cd63..5ba1c344f50a 100644 --- a/crates/store/re_types_blueprint/src/blueprint/components/auto_layout.rs +++ b/crates/store/re_types_blueprint/src/blueprint/components/auto_layout.rs @@ -21,7 +21,7 @@ use ::re_types_core::{DeserializationError, DeserializationResult}; /// **Component**: Whether the viewport layout is determined automatically. #[derive(Clone, Debug, Copy)] #[repr(transparent)] -pub struct AutoLayout(pub bool); +pub struct AutoLayout(pub crate::datatypes::Bool); impl ::re_types_core::SizeBytes for AutoLayout { #[inline] @@ -31,36 +31,35 @@ impl ::re_types_core::SizeBytes for AutoLayout { #[inline] fn is_pod() -> bool { - ::is_pod() + ::is_pod() } } -impl From for AutoLayout { - #[inline] - fn from(auto_layout: bool) -> Self { - Self(auto_layout) +impl> From for AutoLayout { + fn from(v: T) -> Self { + Self(v.into()) } } -impl From for bool { +impl std::borrow::Borrow for AutoLayout { #[inline] - fn from(value: AutoLayout) -> Self { - value.0 + fn borrow(&self) -> &crate::datatypes::Bool { + &self.0 } } impl std::ops::Deref for AutoLayout { - type Target = bool; + type Target = crate::datatypes::Bool; #[inline] - fn deref(&self) -> &bool { + fn deref(&self) -> &crate::datatypes::Bool { &self.0 } } impl std::ops::DerefMut for AutoLayout { #[inline] - fn deref_mut(&mut self) -> &mut bool { + fn deref_mut(&mut self) -> &mut crate::datatypes::Bool { &mut self.0 } } @@ -77,9 +76,7 @@ impl ::re_types_core::Loggable for AutoLayout { #[inline] fn arrow_datatype() -> arrow2::datatypes::DataType { - #![allow(clippy::wildcard_imports)] - use arrow2::datatypes::*; - DataType::Boolean + crate::datatypes::Bool::arrow_datatype() } fn to_arrow_opt<'a>( @@ -88,29 +85,12 @@ impl ::re_types_core::Loggable for AutoLayout { where Self: Clone + 'a, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, datatypes::*}; - Ok({ - let (somes, data0): (Vec<_>, Vec<_>) = data - .into_iter() - .map(|datum| { - let datum: Option<::std::borrow::Cow<'a, Self>> = datum.map(Into::into); - let datum = datum.map(|datum| datum.into_owned().0); - (datum.is_some(), datum) - }) - .unzip(); - let data0_bitmap: Option = { - let any_nones = somes.iter().any(|some| !*some); - any_nones.then(|| somes.into()) - }; - BooleanArray::new( - Self::arrow_datatype(), - data0.into_iter().map(|v| v.unwrap_or_default()).collect(), - data0_bitmap, - ) - .boxed() - }) + crate::datatypes::Bool::to_arrow_opt(data.into_iter().map(|datum| { + datum.map(|datum| match datum.into() { + ::std::borrow::Cow::Borrowed(datum) => ::std::borrow::Cow::Borrowed(&datum.0), + ::std::borrow::Cow::Owned(datum) => ::std::borrow::Cow::Owned(datum.0), + }) + })) } fn from_arrow_opt( @@ -119,23 +99,7 @@ impl ::re_types_core::Loggable for AutoLayout { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - Ok(arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = Self::arrow_datatype(); - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.blueprint.components.AutoLayout#auto_layout")? - .into_iter() - .map(|v| v.ok_or_else(DeserializationError::missing_data)) - .map(|res| res.map(|v| Some(Self(v)))) - .collect::>>>() - .with_context("rerun.blueprint.components.AutoLayout#auto_layout") - .with_context("rerun.blueprint.components.AutoLayout")?) + crate::datatypes::Bool::from_arrow_opt(arrow_data) + .map(|v| v.into_iter().map(|v| v.map(Self)).collect()) } } diff --git a/crates/store/re_types_blueprint/src/blueprint/components/auto_layout_ext.rs b/crates/store/re_types_blueprint/src/blueprint/components/auto_layout_ext.rs index 0a7501582765..4113abafc344 100644 --- a/crates/store/re_types_blueprint/src/blueprint/components/auto_layout_ext.rs +++ b/crates/store/re_types_blueprint/src/blueprint/components/auto_layout_ext.rs @@ -1,8 +1,10 @@ +use re_types::datatypes::Bool; + use super::AutoLayout; impl Default for AutoLayout { #[inline] fn default() -> Self { - Self(true) + Self(Bool(true)) } } diff --git a/crates/store/re_types_blueprint/src/blueprint/components/auto_space_views.rs b/crates/store/re_types_blueprint/src/blueprint/components/auto_space_views.rs index e05b05f6d150..fa9ffd245e1d 100644 --- a/crates/store/re_types_blueprint/src/blueprint/components/auto_space_views.rs +++ b/crates/store/re_types_blueprint/src/blueprint/components/auto_space_views.rs @@ -21,7 +21,7 @@ use ::re_types_core::{DeserializationError, DeserializationResult}; /// **Component**: Whether or not space views should be created automatically. #[derive(Clone, Debug, Copy, Default, PartialEq, Eq, PartialOrd, Ord)] #[repr(transparent)] -pub struct AutoSpaceViews(pub bool); +pub struct AutoSpaceViews(pub crate::datatypes::Bool); impl ::re_types_core::SizeBytes for AutoSpaceViews { #[inline] @@ -31,36 +31,35 @@ impl ::re_types_core::SizeBytes for AutoSpaceViews { #[inline] fn is_pod() -> bool { - ::is_pod() + ::is_pod() } } -impl From for AutoSpaceViews { - #[inline] - fn from(auto_space_views: bool) -> Self { - Self(auto_space_views) +impl> From for AutoSpaceViews { + fn from(v: T) -> Self { + Self(v.into()) } } -impl From for bool { +impl std::borrow::Borrow for AutoSpaceViews { #[inline] - fn from(value: AutoSpaceViews) -> Self { - value.0 + fn borrow(&self) -> &crate::datatypes::Bool { + &self.0 } } impl std::ops::Deref for AutoSpaceViews { - type Target = bool; + type Target = crate::datatypes::Bool; #[inline] - fn deref(&self) -> &bool { + fn deref(&self) -> &crate::datatypes::Bool { &self.0 } } impl std::ops::DerefMut for AutoSpaceViews { #[inline] - fn deref_mut(&mut self) -> &mut bool { + fn deref_mut(&mut self) -> &mut crate::datatypes::Bool { &mut self.0 } } @@ -77,9 +76,7 @@ impl ::re_types_core::Loggable for AutoSpaceViews { #[inline] fn arrow_datatype() -> arrow2::datatypes::DataType { - #![allow(clippy::wildcard_imports)] - use arrow2::datatypes::*; - DataType::Boolean + crate::datatypes::Bool::arrow_datatype() } fn to_arrow_opt<'a>( @@ -88,29 +85,12 @@ impl ::re_types_core::Loggable for AutoSpaceViews { where Self: Clone + 'a, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, datatypes::*}; - Ok({ - let (somes, data0): (Vec<_>, Vec<_>) = data - .into_iter() - .map(|datum| { - let datum: Option<::std::borrow::Cow<'a, Self>> = datum.map(Into::into); - let datum = datum.map(|datum| datum.into_owned().0); - (datum.is_some(), datum) - }) - .unzip(); - let data0_bitmap: Option = { - let any_nones = somes.iter().any(|some| !*some); - any_nones.then(|| somes.into()) - }; - BooleanArray::new( - Self::arrow_datatype(), - data0.into_iter().map(|v| v.unwrap_or_default()).collect(), - data0_bitmap, - ) - .boxed() - }) + crate::datatypes::Bool::to_arrow_opt(data.into_iter().map(|datum| { + datum.map(|datum| match datum.into() { + ::std::borrow::Cow::Borrowed(datum) => ::std::borrow::Cow::Borrowed(&datum.0), + ::std::borrow::Cow::Owned(datum) => ::std::borrow::Cow::Owned(datum.0), + }) + })) } fn from_arrow_opt( @@ -119,23 +99,7 @@ impl ::re_types_core::Loggable for AutoSpaceViews { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - Ok(arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = Self::arrow_datatype(); - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.blueprint.components.AutoSpaceViews#auto_space_views")? - .into_iter() - .map(|v| v.ok_or_else(DeserializationError::missing_data)) - .map(|res| res.map(|v| Some(Self(v)))) - .collect::>>>() - .with_context("rerun.blueprint.components.AutoSpaceViews#auto_space_views") - .with_context("rerun.blueprint.components.AutoSpaceViews")?) + crate::datatypes::Bool::from_arrow_opt(arrow_data) + .map(|v| v.into_iter().map(|v| v.map(Self)).collect()) } } diff --git a/crates/store/re_types_blueprint/src/blueprint/components/grid_columns.rs b/crates/store/re_types_blueprint/src/blueprint/components/grid_columns.rs index 0090401086bb..2f430c2eabcf 100644 --- a/crates/store/re_types_blueprint/src/blueprint/components/grid_columns.rs +++ b/crates/store/re_types_blueprint/src/blueprint/components/grid_columns.rs @@ -22,7 +22,7 @@ use ::re_types_core::{DeserializationError, DeserializationResult}; #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] pub struct GridColumns( /// The number of columns. - pub u32, + pub crate::datatypes::UInt32, ); impl ::re_types_core::SizeBytes for GridColumns { @@ -33,36 +33,35 @@ impl ::re_types_core::SizeBytes for GridColumns { #[inline] fn is_pod() -> bool { - ::is_pod() + ::is_pod() } } -impl From for GridColumns { - #[inline] - fn from(columns: u32) -> Self { - Self(columns) +impl> From for GridColumns { + fn from(v: T) -> Self { + Self(v.into()) } } -impl From for u32 { +impl std::borrow::Borrow for GridColumns { #[inline] - fn from(value: GridColumns) -> Self { - value.0 + fn borrow(&self) -> &crate::datatypes::UInt32 { + &self.0 } } impl std::ops::Deref for GridColumns { - type Target = u32; + type Target = crate::datatypes::UInt32; #[inline] - fn deref(&self) -> &u32 { + fn deref(&self) -> &crate::datatypes::UInt32 { &self.0 } } impl std::ops::DerefMut for GridColumns { #[inline] - fn deref_mut(&mut self) -> &mut u32 { + fn deref_mut(&mut self) -> &mut crate::datatypes::UInt32 { &mut self.0 } } @@ -79,9 +78,7 @@ impl ::re_types_core::Loggable for GridColumns { #[inline] fn arrow_datatype() -> arrow2::datatypes::DataType { - #![allow(clippy::wildcard_imports)] - use arrow2::datatypes::*; - DataType::UInt32 + crate::datatypes::UInt32::arrow_datatype() } fn to_arrow_opt<'a>( @@ -90,29 +87,12 @@ impl ::re_types_core::Loggable for GridColumns { where Self: Clone + 'a, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, datatypes::*}; - Ok({ - let (somes, data0): (Vec<_>, Vec<_>) = data - .into_iter() - .map(|datum| { - let datum: Option<::std::borrow::Cow<'a, Self>> = datum.map(Into::into); - let datum = datum.map(|datum| datum.into_owned().0); - (datum.is_some(), datum) - }) - .unzip(); - let data0_bitmap: Option = { - let any_nones = somes.iter().any(|some| !*some); - any_nones.then(|| somes.into()) - }; - PrimitiveArray::new( - Self::arrow_datatype(), - data0.into_iter().map(|v| v.unwrap_or_default()).collect(), - data0_bitmap, - ) - .boxed() - }) + crate::datatypes::UInt32::to_arrow_opt(data.into_iter().map(|datum| { + datum.map(|datum| match datum.into() { + ::std::borrow::Cow::Borrowed(datum) => ::std::borrow::Cow::Borrowed(&datum.0), + ::std::borrow::Cow::Owned(datum) => ::std::borrow::Cow::Owned(datum.0), + }) + })) } fn from_arrow_opt( @@ -121,25 +101,8 @@ impl ::re_types_core::Loggable for GridColumns { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - Ok(arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = Self::arrow_datatype(); - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.blueprint.components.GridColumns#columns")? - .into_iter() - .map(|opt| opt.copied()) - .map(|v| v.ok_or_else(DeserializationError::missing_data)) - .map(|res| res.map(|v| Some(Self(v)))) - .collect::>>>() - .with_context("rerun.blueprint.components.GridColumns#columns") - .with_context("rerun.blueprint.components.GridColumns")?) + crate::datatypes::UInt32::from_arrow_opt(arrow_data) + .map(|v| v.into_iter().map(|v| v.map(Self)).collect()) } #[inline] @@ -147,29 +110,6 @@ impl ::re_types_core::Loggable for GridColumns { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - if let Some(validity) = arrow_data.validity() { - if validity.unset_bits() != 0 { - return Err(DeserializationError::missing_data()); - } - } - Ok({ - let slice = arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = DataType::UInt32; - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.blueprint.components.GridColumns#columns")? - .values() - .as_slice(); - { - slice.iter().copied().map(Self).collect::>() - } - }) + crate::datatypes::UInt32::from_arrow(arrow_data).map(|v| v.into_iter().map(Self).collect()) } } diff --git a/crates/store/re_types_blueprint/src/blueprint/components/visualizer_overrides.rs b/crates/store/re_types_blueprint/src/blueprint/components/visualizer_overrides.rs index 0a1cbb347a8f..b7d732e8f7d8 100644 --- a/crates/store/re_types_blueprint/src/blueprint/components/visualizer_overrides.rs +++ b/crates/store/re_types_blueprint/src/blueprint/components/visualizer_overrides.rs @@ -55,7 +55,7 @@ pub struct VisualizerOverrides( /// - SegmentationImage /// - SeriesLine /// - SeriesPoint - pub Vec<::re_types_core::ArrowString>, + pub crate::blueprint::datatypes::Utf8List, ); impl ::re_types_core::SizeBytes for VisualizerOverrides { @@ -66,36 +66,35 @@ impl ::re_types_core::SizeBytes for VisualizerOverrides { #[inline] fn is_pod() -> bool { - >::is_pod() + ::is_pod() } } -impl From> for VisualizerOverrides { - #[inline] - fn from(visualizers: Vec<::re_types_core::ArrowString>) -> Self { - Self(visualizers) +impl> From for VisualizerOverrides { + fn from(v: T) -> Self { + Self(v.into()) } } -impl From for Vec<::re_types_core::ArrowString> { +impl std::borrow::Borrow for VisualizerOverrides { #[inline] - fn from(value: VisualizerOverrides) -> Self { - value.0 + fn borrow(&self) -> &crate::blueprint::datatypes::Utf8List { + &self.0 } } impl std::ops::Deref for VisualizerOverrides { - type Target = Vec<::re_types_core::ArrowString>; + type Target = crate::blueprint::datatypes::Utf8List; #[inline] - fn deref(&self) -> &Vec<::re_types_core::ArrowString> { + fn deref(&self) -> &crate::blueprint::datatypes::Utf8List { &self.0 } } impl std::ops::DerefMut for VisualizerOverrides { #[inline] - fn deref_mut(&mut self) -> &mut Vec<::re_types_core::ArrowString> { + fn deref_mut(&mut self) -> &mut crate::blueprint::datatypes::Utf8List { &mut self.0 } } @@ -112,13 +111,7 @@ impl ::re_types_core::Loggable for VisualizerOverrides { #[inline] fn arrow_datatype() -> arrow2::datatypes::DataType { - #![allow(clippy::wildcard_imports)] - use arrow2::datatypes::*; - DataType::List(std::sync::Arc::new(Field::new( - "item", - DataType::Utf8, - false, - ))) + crate::blueprint::datatypes::Utf8List::arrow_datatype() } fn to_arrow_opt<'a>( @@ -127,59 +120,12 @@ impl ::re_types_core::Loggable for VisualizerOverrides { where Self: Clone + 'a, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, datatypes::*}; - Ok({ - let (somes, data0): (Vec<_>, Vec<_>) = data - .into_iter() - .map(|datum| { - let datum: Option<::std::borrow::Cow<'a, Self>> = datum.map(Into::into); - let datum = datum.map(|datum| datum.into_owned().0); - (datum.is_some(), datum) - }) - .unzip(); - let data0_bitmap: Option = { - let any_nones = somes.iter().any(|some| !*some); - any_nones.then(|| somes.into()) - }; - { - use arrow2::{buffer::Buffer, offset::OffsetsBuffer}; - let offsets = arrow2::offset::Offsets::::try_from_lengths( - data0 - .iter() - .map(|opt| opt.as_ref().map_or(0, |datum| datum.len())), - )? - .into(); - let data0_inner_data: Vec<_> = data0.into_iter().flatten().flatten().collect(); - let data0_inner_bitmap: Option = None; - ListArray::try_new( - Self::arrow_datatype(), - offsets, - { - let offsets = arrow2::offset::Offsets::::try_from_lengths( - data0_inner_data.iter().map(|datum| datum.len()), - )? - .into(); - let inner_data: arrow2::buffer::Buffer = - data0_inner_data.into_iter().flat_map(|s| s.0).collect(); - - #[allow(unsafe_code, clippy::undocumented_unsafe_blocks)] - unsafe { - Utf8Array::::new_unchecked( - DataType::Utf8, - offsets, - inner_data, - data0_inner_bitmap, - ) - } - .boxed() - }, - data0_bitmap, - )? - .boxed() - } - }) + crate::blueprint::datatypes::Utf8List::to_arrow_opt(data.into_iter().map(|datum| { + datum.map(|datum| match datum.into() { + ::std::borrow::Cow::Borrowed(datum) => ::std::borrow::Cow::Borrowed(&datum.0), + ::std::borrow::Cow::Owned(datum) => ::std::borrow::Cow::Owned(datum.0), + }) + })) } fn from_arrow_opt( @@ -188,107 +134,7 @@ impl ::re_types_core::Loggable for VisualizerOverrides { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - Ok({ - let arrow_data = arrow_data - .as_any() - .downcast_ref::>() - .ok_or_else(|| { - let expected = Self::arrow_datatype(); - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.blueprint.components.VisualizerOverrides#visualizers")?; - if arrow_data.is_empty() { - Vec::new() - } else { - let arrow_data_inner = { - let arrow_data_inner = &**arrow_data.values(); - { - let arrow_data_inner = arrow_data_inner - .as_any() - .downcast_ref::>() - .ok_or_else(|| { - let expected = DataType::Utf8; - let actual = arrow_data_inner.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context( - "rerun.blueprint.components.VisualizerOverrides#visualizers", - )?; - let arrow_data_inner_buf = arrow_data_inner.values(); - let offsets = arrow_data_inner.offsets(); - arrow2::bitmap::utils::ZipValidity::new_with_validity( - offsets.iter().zip(offsets.lengths()), - arrow_data_inner.validity(), - ) - .map(|elem| { - elem.map(|(start, len)| { - let start = *start as usize; - let end = start + len; - if end > arrow_data_inner_buf.len() { - return Err(DeserializationError::offset_slice_oob( - (start, end), - arrow_data_inner_buf.len(), - )); - } - - #[allow(unsafe_code, clippy::undocumented_unsafe_blocks)] - let data = unsafe { - arrow_data_inner_buf.clone().sliced_unchecked(start, len) - }; - Ok(data) - }) - .transpose() - }) - .map(|res_or_opt| { - res_or_opt.map(|res_or_opt| { - res_or_opt.map(|v| ::re_types_core::ArrowString(v)) - }) - }) - .collect::>>>() - .with_context("rerun.blueprint.components.VisualizerOverrides#visualizers")? - .into_iter() - } - .collect::>() - }; - let offsets = arrow_data.offsets(); - arrow2::bitmap::utils::ZipValidity::new_with_validity( - offsets.iter().zip(offsets.lengths()), - arrow_data.validity(), - ) - .map(|elem| { - elem.map(|(start, len)| { - let start = *start as usize; - let end = start + len; - if end > arrow_data_inner.len() { - return Err(DeserializationError::offset_slice_oob( - (start, end), - arrow_data_inner.len(), - )); - } - - #[allow(unsafe_code, clippy::undocumented_unsafe_blocks)] - let data = unsafe { arrow_data_inner.get_unchecked(start..end) }; - let data = data - .iter() - .cloned() - .map(Option::unwrap_or_default) - .collect(); - Ok(data) - }) - .transpose() - }) - .collect::>>>()? - } - .into_iter() - } - .map(|v| v.ok_or_else(DeserializationError::missing_data)) - .map(|res| res.map(|v| Some(Self(v)))) - .collect::>>>() - .with_context("rerun.blueprint.components.VisualizerOverrides#visualizers") - .with_context("rerun.blueprint.components.VisualizerOverrides")?) + crate::blueprint::datatypes::Utf8List::from_arrow_opt(arrow_data) + .map(|v| v.into_iter().map(|v| v.map(Self)).collect()) } } diff --git a/crates/store/re_types_blueprint/src/blueprint/datatypes/.gitattributes b/crates/store/re_types_blueprint/src/blueprint/datatypes/.gitattributes new file mode 100644 index 000000000000..c3dfab32d1bc --- /dev/null +++ b/crates/store/re_types_blueprint/src/blueprint/datatypes/.gitattributes @@ -0,0 +1,5 @@ +# DO NOT EDIT! This file is generated by crates/build/re_types_builder/src/lib.rs + +.gitattributes linguist-generated=true +mod.rs linguist-generated=true +utf8list.rs linguist-generated=true diff --git a/crates/store/re_types_blueprint/src/blueprint/datatypes/mod.rs b/crates/store/re_types_blueprint/src/blueprint/datatypes/mod.rs new file mode 100644 index 000000000000..faad0f80b2d2 --- /dev/null +++ b/crates/store/re_types_blueprint/src/blueprint/datatypes/mod.rs @@ -0,0 +1,6 @@ +// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/rust/api.rs + +mod utf8list; +mod utf8list_ext; + +pub use self::utf8list::Utf8List; diff --git a/crates/store/re_types_blueprint/src/blueprint/datatypes/utf8list.rs b/crates/store/re_types_blueprint/src/blueprint/datatypes/utf8list.rs new file mode 100644 index 000000000000..92d3ffe6cd9f --- /dev/null +++ b/crates/store/re_types_blueprint/src/blueprint/datatypes/utf8list.rs @@ -0,0 +1,241 @@ +// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/rust/api.rs +// Based on "crates/store/re_types/definitions/rerun/blueprint/datatypes/utf8_list.fbs". + +#![allow(unused_imports)] +#![allow(unused_parens)] +#![allow(clippy::clone_on_copy)] +#![allow(clippy::cloned_instead_of_copied)] +#![allow(clippy::map_flatten)] +#![allow(clippy::needless_question_mark)] +#![allow(clippy::new_without_default)] +#![allow(clippy::redundant_closure)] +#![allow(clippy::too_many_arguments)] +#![allow(clippy::too_many_lines)] + +use ::re_types_core::external::arrow2; +use ::re_types_core::ComponentName; +use ::re_types_core::SerializationResult; +use ::re_types_core::{ComponentBatch, MaybeOwnedComponentBatch}; +use ::re_types_core::{DeserializationError, DeserializationResult}; + +/// **Datatype**: A list of strings of text, encoded as UTF-8. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Default)] +#[repr(transparent)] +pub struct Utf8List(pub Vec<::re_types_core::ArrowString>); + +impl ::re_types_core::SizeBytes for Utf8List { + #[inline] + fn heap_size_bytes(&self) -> u64 { + self.0.heap_size_bytes() + } + + #[inline] + fn is_pod() -> bool { + >::is_pod() + } +} + +impl From> for Utf8List { + #[inline] + fn from(value: Vec<::re_types_core::ArrowString>) -> Self { + Self(value) + } +} + +impl From for Vec<::re_types_core::ArrowString> { + #[inline] + fn from(value: Utf8List) -> Self { + value.0 + } +} + +::re_types_core::macros::impl_into_cow!(Utf8List); + +impl ::re_types_core::Loggable for Utf8List { + type Name = ::re_types_core::DatatypeName; + + #[inline] + fn name() -> Self::Name { + "rerun.blueprint.datatypes.Utf8List".into() + } + + #[inline] + fn arrow_datatype() -> arrow2::datatypes::DataType { + #![allow(clippy::wildcard_imports)] + use arrow2::datatypes::*; + DataType::List(std::sync::Arc::new(Field::new( + "item", + DataType::Utf8, + false, + ))) + } + + fn to_arrow_opt<'a>( + data: impl IntoIterator>>>, + ) -> SerializationResult> + where + Self: Clone + 'a, + { + #![allow(clippy::wildcard_imports)] + use ::re_types_core::{Loggable as _, ResultExt as _}; + use arrow2::{array::*, datatypes::*}; + Ok({ + let (somes, data0): (Vec<_>, Vec<_>) = data + .into_iter() + .map(|datum| { + let datum: Option<::std::borrow::Cow<'a, Self>> = datum.map(Into::into); + let datum = datum.map(|datum| datum.into_owned().0); + (datum.is_some(), datum) + }) + .unzip(); + let data0_bitmap: Option = { + let any_nones = somes.iter().any(|some| !*some); + any_nones.then(|| somes.into()) + }; + { + use arrow2::{buffer::Buffer, offset::OffsetsBuffer}; + let offsets = arrow2::offset::Offsets::::try_from_lengths( + data0 + .iter() + .map(|opt| opt.as_ref().map_or(0, |datum| datum.len())), + )? + .into(); + let data0_inner_data: Vec<_> = data0.into_iter().flatten().flatten().collect(); + let data0_inner_bitmap: Option = None; + ListArray::try_new( + Self::arrow_datatype(), + offsets, + { + let offsets = arrow2::offset::Offsets::::try_from_lengths( + data0_inner_data.iter().map(|datum| datum.len()), + )? + .into(); + let inner_data: arrow2::buffer::Buffer = + data0_inner_data.into_iter().flat_map(|s| s.0).collect(); + + #[allow(unsafe_code, clippy::undocumented_unsafe_blocks)] + unsafe { + Utf8Array::::new_unchecked( + DataType::Utf8, + offsets, + inner_data, + data0_inner_bitmap, + ) + } + .boxed() + }, + data0_bitmap, + )? + .boxed() + } + }) + } + + fn from_arrow_opt( + arrow_data: &dyn arrow2::array::Array, + ) -> DeserializationResult>> + where + Self: Sized, + { + #![allow(clippy::wildcard_imports)] + use ::re_types_core::{Loggable as _, ResultExt as _}; + use arrow2::{array::*, buffer::*, datatypes::*}; + Ok({ + let arrow_data = arrow_data + .as_any() + .downcast_ref::>() + .ok_or_else(|| { + let expected = Self::arrow_datatype(); + let actual = arrow_data.data_type().clone(); + DeserializationError::datatype_mismatch(expected, actual) + }) + .with_context("rerun.blueprint.datatypes.Utf8List#value")?; + if arrow_data.is_empty() { + Vec::new() + } else { + let arrow_data_inner = { + let arrow_data_inner = &**arrow_data.values(); + { + let arrow_data_inner = arrow_data_inner + .as_any() + .downcast_ref::>() + .ok_or_else(|| { + let expected = DataType::Utf8; + let actual = arrow_data_inner.data_type().clone(); + DeserializationError::datatype_mismatch(expected, actual) + }) + .with_context("rerun.blueprint.datatypes.Utf8List#value")?; + let arrow_data_inner_buf = arrow_data_inner.values(); + let offsets = arrow_data_inner.offsets(); + arrow2::bitmap::utils::ZipValidity::new_with_validity( + offsets.iter().zip(offsets.lengths()), + arrow_data_inner.validity(), + ) + .map(|elem| { + elem.map(|(start, len)| { + let start = *start as usize; + let end = start + len; + if end > arrow_data_inner_buf.len() { + return Err(DeserializationError::offset_slice_oob( + (start, end), + arrow_data_inner_buf.len(), + )); + } + + #[allow(unsafe_code, clippy::undocumented_unsafe_blocks)] + let data = unsafe { + arrow_data_inner_buf.clone().sliced_unchecked(start, len) + }; + Ok(data) + }) + .transpose() + }) + .map(|res_or_opt| { + res_or_opt.map(|res_or_opt| { + res_or_opt.map(|v| ::re_types_core::ArrowString(v)) + }) + }) + .collect::>>>() + .with_context("rerun.blueprint.datatypes.Utf8List#value")? + .into_iter() + } + .collect::>() + }; + let offsets = arrow_data.offsets(); + arrow2::bitmap::utils::ZipValidity::new_with_validity( + offsets.iter().zip(offsets.lengths()), + arrow_data.validity(), + ) + .map(|elem| { + elem.map(|(start, len)| { + let start = *start as usize; + let end = start + len; + if end > arrow_data_inner.len() { + return Err(DeserializationError::offset_slice_oob( + (start, end), + arrow_data_inner.len(), + )); + } + + #[allow(unsafe_code, clippy::undocumented_unsafe_blocks)] + let data = unsafe { arrow_data_inner.get_unchecked(start..end) }; + let data = data + .iter() + .cloned() + .map(Option::unwrap_or_default) + .collect(); + Ok(data) + }) + .transpose() + }) + .collect::>>>()? + } + .into_iter() + } + .map(|v| v.ok_or_else(DeserializationError::missing_data)) + .map(|res| res.map(|v| Some(Self(v)))) + .collect::>>>() + .with_context("rerun.blueprint.datatypes.Utf8List#value") + .with_context("rerun.blueprint.datatypes.Utf8List")?) + } +} diff --git a/crates/store/re_types_blueprint/src/blueprint/datatypes/utf8list_ext.rs b/crates/store/re_types_blueprint/src/blueprint/datatypes/utf8list_ext.rs new file mode 100644 index 000000000000..1b6082caaa61 --- /dev/null +++ b/crates/store/re_types_blueprint/src/blueprint/datatypes/utf8list_ext.rs @@ -0,0 +1,8 @@ +use super::Utf8List; + +impl Utf8List { + /// Iterates through the list of strings as Rust `str` references. + pub fn iter(&self) -> impl Iterator { + self.0.iter().map(|s| s.as_str()) + } +} diff --git a/crates/store/re_types_blueprint/src/blueprint/mod.rs b/crates/store/re_types_blueprint/src/blueprint/mod.rs index dc972753c970..e67e9c5c4658 100644 --- a/crates/store/re_types_blueprint/src/blueprint/mod.rs +++ b/crates/store/re_types_blueprint/src/blueprint/mod.rs @@ -8,3 +8,5 @@ pub mod components { pub use self::_components::*; pub use re_types::blueprint::components::*; } + +pub mod datatypes; diff --git a/crates/store/re_types_core/src/archetypes/clear_ext.rs b/crates/store/re_types_core/src/archetypes/clear_ext.rs index a242613aa424..50b7a581b095 100644 --- a/crates/store/re_types_core/src/archetypes/clear_ext.rs +++ b/crates/store/re_types_core/src/archetypes/clear_ext.rs @@ -8,7 +8,7 @@ impl Clear { #[inline] pub fn flat() -> Self { Self { - is_recursive: crate::components::ClearIsRecursive(false), + is_recursive: false.into(), } } @@ -18,7 +18,7 @@ impl Clear { /// all components of all its recursive children. pub fn recursive() -> Self { Self { - is_recursive: crate::components::ClearIsRecursive(true), + is_recursive: true.into(), } } } diff --git a/crates/store/re_types_core/src/components/clear_is_recursive.rs b/crates/store/re_types_core/src/components/clear_is_recursive.rs index e0c359e15514..b491e51eec71 100644 --- a/crates/store/re_types_core/src/components/clear_is_recursive.rs +++ b/crates/store/re_types_core/src/components/clear_is_recursive.rs @@ -22,7 +22,7 @@ use crate::{DeserializationError, DeserializationResult}; #[derive(Clone, Debug, Copy, PartialEq, Eq)] pub struct ClearIsRecursive( /// If true, also clears all recursive children entities. - pub bool, + pub crate::datatypes::Bool, ); impl crate::SizeBytes for ClearIsRecursive { @@ -33,36 +33,35 @@ impl crate::SizeBytes for ClearIsRecursive { #[inline] fn is_pod() -> bool { - ::is_pod() + ::is_pod() } } -impl From for ClearIsRecursive { - #[inline] - fn from(recursive: bool) -> Self { - Self(recursive) +impl> From for ClearIsRecursive { + fn from(v: T) -> Self { + Self(v.into()) } } -impl From for bool { +impl std::borrow::Borrow for ClearIsRecursive { #[inline] - fn from(value: ClearIsRecursive) -> Self { - value.0 + fn borrow(&self) -> &crate::datatypes::Bool { + &self.0 } } impl std::ops::Deref for ClearIsRecursive { - type Target = bool; + type Target = crate::datatypes::Bool; #[inline] - fn deref(&self) -> &bool { + fn deref(&self) -> &crate::datatypes::Bool { &self.0 } } impl std::ops::DerefMut for ClearIsRecursive { #[inline] - fn deref_mut(&mut self) -> &mut bool { + fn deref_mut(&mut self) -> &mut crate::datatypes::Bool { &mut self.0 } } @@ -79,9 +78,7 @@ impl crate::Loggable for ClearIsRecursive { #[inline] fn arrow_datatype() -> arrow2::datatypes::DataType { - #![allow(clippy::wildcard_imports)] - use arrow2::datatypes::*; - DataType::Boolean + crate::datatypes::Bool::arrow_datatype() } fn to_arrow_opt<'a>( @@ -90,29 +87,12 @@ impl crate::Loggable for ClearIsRecursive { where Self: Clone + 'a, { - #![allow(clippy::wildcard_imports)] - use crate::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, datatypes::*}; - Ok({ - let (somes, data0): (Vec<_>, Vec<_>) = data - .into_iter() - .map(|datum| { - let datum: Option<::std::borrow::Cow<'a, Self>> = datum.map(Into::into); - let datum = datum.map(|datum| datum.into_owned().0); - (datum.is_some(), datum) - }) - .unzip(); - let data0_bitmap: Option = { - let any_nones = somes.iter().any(|some| !*some); - any_nones.then(|| somes.into()) - }; - BooleanArray::new( - Self::arrow_datatype(), - data0.into_iter().map(|v| v.unwrap_or_default()).collect(), - data0_bitmap, - ) - .boxed() - }) + crate::datatypes::Bool::to_arrow_opt(data.into_iter().map(|datum| { + datum.map(|datum| match datum.into() { + ::std::borrow::Cow::Borrowed(datum) => ::std::borrow::Cow::Borrowed(&datum.0), + ::std::borrow::Cow::Owned(datum) => ::std::borrow::Cow::Owned(datum.0), + }) + })) } fn from_arrow_opt( @@ -121,23 +101,7 @@ impl crate::Loggable for ClearIsRecursive { where Self: Sized, { - #![allow(clippy::wildcard_imports)] - use crate::{Loggable as _, ResultExt as _}; - use arrow2::{array::*, buffer::*, datatypes::*}; - Ok(arrow_data - .as_any() - .downcast_ref::() - .ok_or_else(|| { - let expected = Self::arrow_datatype(); - let actual = arrow_data.data_type().clone(); - DeserializationError::datatype_mismatch(expected, actual) - }) - .with_context("rerun.components.ClearIsRecursive#recursive")? - .into_iter() - .map(|v| v.ok_or_else(DeserializationError::missing_data)) - .map(|res| res.map(|v| Some(Self(v)))) - .collect::>>>() - .with_context("rerun.components.ClearIsRecursive#recursive") - .with_context("rerun.components.ClearIsRecursive")?) + crate::datatypes::Bool::from_arrow_opt(arrow_data) + .map(|v| v.into_iter().map(|v| v.map(Self)).collect()) } } diff --git a/crates/store/re_types_core/src/components/clear_is_recursive_ext.rs b/crates/store/re_types_core/src/components/clear_is_recursive_ext.rs index 42fa52a010e0..1b4f03ae8181 100644 --- a/crates/store/re_types_core/src/components/clear_is_recursive_ext.rs +++ b/crates/store/re_types_core/src/components/clear_is_recursive_ext.rs @@ -5,6 +5,6 @@ impl Default for ClearIsRecursive { fn default() -> Self { // Clear only the element itself by default since this is less intrusive. // (Clearing recursively can be emulated with many clears, but the reverse is not true.) - Self(false) + Self(false.into()) } } diff --git a/crates/store/re_types_core/src/datatypes/.gitattributes b/crates/store/re_types_core/src/datatypes/.gitattributes index 14fd4a8e6590..bca9a672bf3a 100644 --- a/crates/store/re_types_core/src/datatypes/.gitattributes +++ b/crates/store/re_types_core/src/datatypes/.gitattributes @@ -1,8 +1,10 @@ # DO NOT EDIT! This file is generated by crates/build/re_types_builder/src/lib.rs .gitattributes linguist-generated=true +bool.rs linguist-generated=true entity_path.rs linguist-generated=true float32.rs linguist-generated=true +float64.rs linguist-generated=true mod.rs linguist-generated=true time_int.rs linguist-generated=true time_range.rs linguist-generated=true diff --git a/crates/store/re_types/src/datatypes/bool.rs b/crates/store/re_types_core/src/datatypes/bool.rs similarity index 86% rename from crates/store/re_types/src/datatypes/bool.rs rename to crates/store/re_types_core/src/datatypes/bool.rs index bd3d45a08dde..cfd4d21ef7d4 100644 --- a/crates/store/re_types/src/datatypes/bool.rs +++ b/crates/store/re_types_core/src/datatypes/bool.rs @@ -12,18 +12,18 @@ #![allow(clippy::too_many_arguments)] #![allow(clippy::too_many_lines)] -use ::re_types_core::external::arrow2; -use ::re_types_core::ComponentName; -use ::re_types_core::SerializationResult; -use ::re_types_core::{ComponentBatch, MaybeOwnedComponentBatch}; -use ::re_types_core::{DeserializationError, DeserializationResult}; +use crate::external::arrow2; +use crate::ComponentName; +use crate::SerializationResult; +use crate::{ComponentBatch, MaybeOwnedComponentBatch}; +use crate::{DeserializationError, DeserializationResult}; /// **Datatype**: A single boolean. #[derive(Clone, Debug, Copy, Default, PartialEq, Eq, PartialOrd, Ord)] #[repr(transparent)] pub struct Bool(pub bool); -impl ::re_types_core::SizeBytes for Bool { +impl crate::SizeBytes for Bool { #[inline] fn heap_size_bytes(&self) -> u64 { self.0.heap_size_bytes() @@ -49,10 +49,10 @@ impl From for bool { } } -::re_types_core::macros::impl_into_cow!(Bool); +crate::macros::impl_into_cow!(Bool); -impl ::re_types_core::Loggable for Bool { - type Name = ::re_types_core::DatatypeName; +impl crate::Loggable for Bool { + type Name = crate::DatatypeName; #[inline] fn name() -> Self::Name { @@ -73,7 +73,7 @@ impl ::re_types_core::Loggable for Bool { Self: Clone + 'a, { #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; + use crate::{Loggable as _, ResultExt as _}; use arrow2::{array::*, datatypes::*}; Ok({ let (somes, data0): (Vec<_>, Vec<_>) = data @@ -104,7 +104,7 @@ impl ::re_types_core::Loggable for Bool { Self: Sized, { #![allow(clippy::wildcard_imports)] - use ::re_types_core::{Loggable as _, ResultExt as _}; + use crate::{Loggable as _, ResultExt as _}; use arrow2::{array::*, buffer::*, datatypes::*}; Ok(arrow_data .as_any() diff --git a/crates/store/re_types_core/src/datatypes/bool_ext.rs b/crates/store/re_types_core/src/datatypes/bool_ext.rs new file mode 100644 index 000000000000..1c3c41aed673 --- /dev/null +++ b/crates/store/re_types_core/src/datatypes/bool_ext.rs @@ -0,0 +1,17 @@ +use super::Bool; + +impl std::ops::Deref for Bool { + type Target = bool; + + #[inline] + fn deref(&self) -> &bool { + &self.0 + } +} + +impl std::ops::DerefMut for Bool { + #[inline] + fn deref_mut(&mut self) -> &mut bool { + &mut self.0 + } +} diff --git a/crates/store/re_types_core/src/datatypes/float32.rs b/crates/store/re_types_core/src/datatypes/float32.rs index d1ac1f0520c5..06fbc69491d9 100644 --- a/crates/store/re_types_core/src/datatypes/float32.rs +++ b/crates/store/re_types_core/src/datatypes/float32.rs @@ -19,7 +19,7 @@ use crate::{ComponentBatch, MaybeOwnedComponentBatch}; use crate::{DeserializationError, DeserializationResult}; /// **Datatype**: A single-precision 32-bit IEEE 754 floating point number. -#[derive(Clone, Debug, Copy, PartialEq, PartialOrd, bytemuck::Pod, bytemuck::Zeroable)] +#[derive(Clone, Debug, Default, Copy, PartialEq, PartialOrd, bytemuck::Pod, bytemuck::Zeroable)] #[repr(transparent)] pub struct Float32(pub f32); diff --git a/crates/store/re_types_core/src/datatypes/float32_ext.rs b/crates/store/re_types_core/src/datatypes/float32_ext.rs index 9f8c6f0f97e3..99d681b51dae 100644 --- a/crates/store/re_types_core/src/datatypes/float32_ext.rs +++ b/crates/store/re_types_core/src/datatypes/float32_ext.rs @@ -1,5 +1,12 @@ use super::Float32; +impl std::fmt::Display for Float32 { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let prec = f.precision().unwrap_or(crate::DEFAULT_DISPLAY_DECIMALS); + write!(f, "{:.prec$}", self.0) + } +} + impl std::ops::Deref for Float32 { type Target = f32; diff --git a/crates/store/re_types_core/src/datatypes/float64.rs b/crates/store/re_types_core/src/datatypes/float64.rs new file mode 100644 index 000000000000..11dc6357d225 --- /dev/null +++ b/crates/store/re_types_core/src/datatypes/float64.rs @@ -0,0 +1,157 @@ +// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/rust/api.rs +// Based on "crates/store/re_types/definitions/rerun/datatypes/float64.fbs". + +#![allow(unused_imports)] +#![allow(unused_parens)] +#![allow(clippy::clone_on_copy)] +#![allow(clippy::cloned_instead_of_copied)] +#![allow(clippy::map_flatten)] +#![allow(clippy::needless_question_mark)] +#![allow(clippy::new_without_default)] +#![allow(clippy::redundant_closure)] +#![allow(clippy::too_many_arguments)] +#![allow(clippy::too_many_lines)] + +use crate::external::arrow2; +use crate::ComponentName; +use crate::SerializationResult; +use crate::{ComponentBatch, MaybeOwnedComponentBatch}; +use crate::{DeserializationError, DeserializationResult}; + +/// **Datatype**: A double-precision 64-bit IEEE 754 floating point number. +#[derive(Clone, Debug, Default, Copy, PartialEq, PartialOrd, bytemuck::Pod, bytemuck::Zeroable)] +#[repr(transparent)] +pub struct Float64(pub f64); + +impl crate::SizeBytes for Float64 { + #[inline] + fn heap_size_bytes(&self) -> u64 { + self.0.heap_size_bytes() + } + + #[inline] + fn is_pod() -> bool { + ::is_pod() + } +} + +impl From for Float64 { + #[inline] + fn from(value: f64) -> Self { + Self(value) + } +} + +impl From for f64 { + #[inline] + fn from(value: Float64) -> Self { + value.0 + } +} + +crate::macros::impl_into_cow!(Float64); + +impl crate::Loggable for Float64 { + type Name = crate::DatatypeName; + + #[inline] + fn name() -> Self::Name { + "rerun.datatypes.Float64".into() + } + + #[inline] + fn arrow_datatype() -> arrow2::datatypes::DataType { + #![allow(clippy::wildcard_imports)] + use arrow2::datatypes::*; + DataType::Float64 + } + + fn to_arrow_opt<'a>( + data: impl IntoIterator>>>, + ) -> SerializationResult> + where + Self: Clone + 'a, + { + #![allow(clippy::wildcard_imports)] + use crate::{Loggable as _, ResultExt as _}; + use arrow2::{array::*, datatypes::*}; + Ok({ + let (somes, data0): (Vec<_>, Vec<_>) = data + .into_iter() + .map(|datum| { + let datum: Option<::std::borrow::Cow<'a, Self>> = datum.map(Into::into); + let datum = datum.map(|datum| datum.into_owned().0); + (datum.is_some(), datum) + }) + .unzip(); + let data0_bitmap: Option = { + let any_nones = somes.iter().any(|some| !*some); + any_nones.then(|| somes.into()) + }; + PrimitiveArray::new( + Self::arrow_datatype(), + data0.into_iter().map(|v| v.unwrap_or_default()).collect(), + data0_bitmap, + ) + .boxed() + }) + } + + fn from_arrow_opt( + arrow_data: &dyn arrow2::array::Array, + ) -> DeserializationResult>> + where + Self: Sized, + { + #![allow(clippy::wildcard_imports)] + use crate::{Loggable as _, ResultExt as _}; + use arrow2::{array::*, buffer::*, datatypes::*}; + Ok(arrow_data + .as_any() + .downcast_ref::() + .ok_or_else(|| { + let expected = Self::arrow_datatype(); + let actual = arrow_data.data_type().clone(); + DeserializationError::datatype_mismatch(expected, actual) + }) + .with_context("rerun.datatypes.Float64#value")? + .into_iter() + .map(|opt| opt.copied()) + .map(|v| v.ok_or_else(DeserializationError::missing_data)) + .map(|res| res.map(|v| Some(Self(v)))) + .collect::>>>() + .with_context("rerun.datatypes.Float64#value") + .with_context("rerun.datatypes.Float64")?) + } + + #[inline] + fn from_arrow(arrow_data: &dyn arrow2::array::Array) -> DeserializationResult> + where + Self: Sized, + { + #![allow(clippy::wildcard_imports)] + use crate::{Loggable as _, ResultExt as _}; + use arrow2::{array::*, buffer::*, datatypes::*}; + if let Some(validity) = arrow_data.validity() { + if validity.unset_bits() != 0 { + return Err(DeserializationError::missing_data()); + } + } + Ok({ + let slice = arrow_data + .as_any() + .downcast_ref::() + .ok_or_else(|| { + let expected = DataType::Float64; + let actual = arrow_data.data_type().clone(); + DeserializationError::datatype_mismatch(expected, actual) + }) + .with_context("rerun.datatypes.Float64#value")? + .values() + .as_slice(); + { + slice.iter().copied().map(Self).collect::>() + } + }) + } +} diff --git a/crates/store/re_types_core/src/datatypes/float64_ext.rs b/crates/store/re_types_core/src/datatypes/float64_ext.rs new file mode 100644 index 000000000000..7013584e444d --- /dev/null +++ b/crates/store/re_types_core/src/datatypes/float64_ext.rs @@ -0,0 +1,24 @@ +use super::Float64; + +impl std::fmt::Display for Float64 { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let prec = f.precision().unwrap_or(crate::DEFAULT_DISPLAY_DECIMALS); + write!(f, "{:.prec$}", self.0) + } +} + +impl std::ops::Deref for Float64 { + type Target = f64; + + #[inline] + fn deref(&self) -> &f64 { + &self.0 + } +} + +impl std::ops::DerefMut for Float64 { + #[inline] + fn deref_mut(&mut self) -> &mut f64 { + &mut self.0 + } +} diff --git a/crates/store/re_types_core/src/datatypes/mod.rs b/crates/store/re_types_core/src/datatypes/mod.rs index de11b1b9e81d..9120787c2819 100644 --- a/crates/store/re_types_core/src/datatypes/mod.rs +++ b/crates/store/re_types_core/src/datatypes/mod.rs @@ -1,8 +1,12 @@ // DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/rust/api.rs +mod bool; +mod bool_ext; mod entity_path; mod float32; mod float32_ext; +mod float64; +mod float64_ext; mod time_int; mod time_int_ext; mod time_range; @@ -10,14 +14,18 @@ mod time_range_boundary; mod time_range_boundary_ext; mod time_range_ext; mod uint32; +mod uint32_ext; mod uint64; +mod uint64_ext; mod utf8; mod utf8_ext; mod visible_time_range; mod visible_time_range_ext; +pub use self::bool::Bool; pub use self::entity_path::EntityPath; pub use self::float32::Float32; +pub use self::float64::Float64; pub use self::time_int::TimeInt; pub use self::time_range::TimeRange; pub use self::time_range_boundary::TimeRangeBoundary; diff --git a/crates/store/re_types_core/src/datatypes/uint32.rs b/crates/store/re_types_core/src/datatypes/uint32.rs index 828c867a3344..b348042d7a4e 100644 --- a/crates/store/re_types_core/src/datatypes/uint32.rs +++ b/crates/store/re_types_core/src/datatypes/uint32.rs @@ -19,7 +19,7 @@ use crate::{ComponentBatch, MaybeOwnedComponentBatch}; use crate::{DeserializationError, DeserializationResult}; /// **Datatype**: A 32bit unsigned integer. -#[derive(Clone, Debug, Copy, PartialEq, Eq, PartialOrd, Ord)] +#[derive(Clone, Debug, Default, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct UInt32(pub u32); impl crate::SizeBytes for UInt32 { diff --git a/crates/store/re_types_core/src/datatypes/uint32_ext.rs b/crates/store/re_types_core/src/datatypes/uint32_ext.rs new file mode 100644 index 000000000000..a2aeb10cee13 --- /dev/null +++ b/crates/store/re_types_core/src/datatypes/uint32_ext.rs @@ -0,0 +1,17 @@ +use super::UInt32; + +impl std::ops::Deref for UInt32 { + type Target = u32; + + #[inline] + fn deref(&self) -> &u32 { + &self.0 + } +} + +impl std::ops::DerefMut for UInt32 { + #[inline] + fn deref_mut(&mut self) -> &mut u32 { + &mut self.0 + } +} diff --git a/crates/store/re_types_core/src/datatypes/uint64.rs b/crates/store/re_types_core/src/datatypes/uint64.rs index 20ed4cb10c3e..9358b3aaedda 100644 --- a/crates/store/re_types_core/src/datatypes/uint64.rs +++ b/crates/store/re_types_core/src/datatypes/uint64.rs @@ -19,7 +19,7 @@ use crate::{ComponentBatch, MaybeOwnedComponentBatch}; use crate::{DeserializationError, DeserializationResult}; /// **Datatype**: A 64bit unsigned integer. -#[derive(Clone, Debug, Copy, PartialEq, Eq, PartialOrd, Ord)] +#[derive(Clone, Debug, Default, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct UInt64(pub u64); impl crate::SizeBytes for UInt64 { diff --git a/crates/store/re_types_core/src/datatypes/uint64_ext.rs b/crates/store/re_types_core/src/datatypes/uint64_ext.rs new file mode 100644 index 000000000000..4b95a7ae72b6 --- /dev/null +++ b/crates/store/re_types_core/src/datatypes/uint64_ext.rs @@ -0,0 +1,17 @@ +use super::UInt64; + +impl std::ops::Deref for UInt64 { + type Target = u64; + + #[inline] + fn deref(&self) -> &u64 { + &self.0 + } +} + +impl std::ops::DerefMut for UInt64 { + #[inline] + fn deref_mut(&mut self) -> &mut u64 { + &mut self.0 + } +} diff --git a/crates/store/re_types_core/src/lib.rs b/crates/store/re_types_core/src/lib.rs index 09aa34c307bd..51455b08a3de 100644 --- a/crates/store/re_types_core/src/lib.rs +++ b/crates/store/re_types_core/src/lib.rs @@ -20,6 +20,9 @@ // --- +/// Number of decimals shown for all float display methods. +pub const DEFAULT_DISPLAY_DECIMALS: usize = 3; + /// Describes the interface for interpreting an object as a bundle of [`Component`]s. /// /// ## Custom bundles diff --git a/crates/viewer/re_blueprint_tree/src/blueprint_tree.rs b/crates/viewer/re_blueprint_tree/src/blueprint_tree.rs index f751977ecc8c..1a707b534e73 100644 --- a/crates/viewer/re_blueprint_tree/src/blueprint_tree.rs +++ b/crates/viewer/re_blueprint_tree/src/blueprint_tree.rs @@ -546,7 +546,7 @@ impl BlueprintTree { .save_recursive_override_or_clear_if_redundant( ctx, &query_result.tree, - &Visible(visible_after), + &Visible::from(visible_after), ); } } diff --git a/crates/viewer/re_context_menu/src/actions/show_hide.rs b/crates/viewer/re_context_menu/src/actions/show_hide.rs index da42a2bdae64..89049fc00c4c 100644 --- a/crates/viewer/re_context_menu/src/actions/show_hide.rs +++ b/crates/viewer/re_context_menu/src/actions/show_hide.rs @@ -143,7 +143,7 @@ fn set_data_result_visible( data_result.save_recursive_override_or_clear_if_redundant( ctx.viewer_context, &query_result.tree, - &re_types::blueprint::components::Visible(visible), + &re_types::blueprint::components::Visible::from(visible), ); } } else { diff --git a/crates/viewer/re_data_ui/src/image.rs b/crates/viewer/re_data_ui/src/image.rs index 6a585686a5b6..ec86548f7609 100644 --- a/crates/viewer/re_data_ui/src/image.rs +++ b/crates/viewer/re_data_ui/src/image.rs @@ -119,7 +119,7 @@ pub fn tensor_ui( ( ctx.recording() .latest_at_component::(entity_path, query) - .map(|meter| meter.value.0), + .map(|meter| *meter.value.0), ctx.recording() .latest_at_component::(entity_path, query) .map(|colormap| colormap.value), diff --git a/crates/viewer/re_edit_ui/src/datatype_editors/bool_toggle.rs b/crates/viewer/re_edit_ui/src/datatype_editors/bool_toggle.rs index 7a88ffdae3b5..bdfd56ea55e8 100644 --- a/crates/viewer/re_edit_ui/src/datatype_editors/bool_toggle.rs +++ b/crates/viewer/re_edit_ui/src/datatype_editors/bool_toggle.rs @@ -14,19 +14,6 @@ pub fn edit_bool( edit_bool_impl(ui, &mut value) } -/// Generic editor for a boolean value that is not wrapped into [`re_types::datatypes::Bool`]. -pub fn edit_bool_raw( - _ctx: &re_viewer_context::ViewerContext<'_>, - ui: &mut egui::Ui, - value: &mut MaybeMutRef<'_, impl std::ops::DerefMut>, -) -> egui::Response { - let mut value: MaybeMutRef<'_, bool> = match value { - MaybeMutRef::Ref(value) => MaybeMutRef::Ref(value), - MaybeMutRef::MutRef(value) => MaybeMutRef::MutRef(value), - }; - edit_bool_impl(ui, &mut value) -} - /// Non monomorphized implementation of [`edit_bool`]. fn edit_bool_impl(ui: &mut egui::Ui, value: &mut MaybeMutRef<'_, bool>) -> egui::Response { match value { diff --git a/crates/viewer/re_edit_ui/src/datatype_editors/float_drag.rs b/crates/viewer/re_edit_ui/src/datatype_editors/float_drag.rs index fa4bc0df475c..04b2a3193bd4 100644 --- a/crates/viewer/re_edit_ui/src/datatype_editors/float_drag.rs +++ b/crates/viewer/re_edit_ui/src/datatype_editors/float_drag.rs @@ -17,28 +17,15 @@ pub fn edit_f32_zero_to_max( edit_f32_float_raw_impl(ui, &mut value, 0.0..=f32::MAX) } -/// Generic editor for a raw f32 value from zero to max float. -pub fn edit_f32_zero_to_max_float_raw( +/// Generic editor for a [`re_types::datatypes::Float32`] value from min to max float. +pub fn edit_f32_min_to_max_float( _ctx: &re_viewer_context::ViewerContext<'_>, ui: &mut egui::Ui, - value: &mut MaybeMutRef<'_, impl std::ops::DerefMut>, -) -> egui::Response { - let mut value: MaybeMutRef<'_, f32> = match value { - MaybeMutRef::Ref(value) => MaybeMutRef::Ref(value), - MaybeMutRef::MutRef(value) => MaybeMutRef::MutRef(value), - }; - edit_f32_float_raw_impl(ui, &mut value, 0.0..=f32::MAX) -} - -/// Generic editor for a raw f32 value from min to max float. -pub fn edit_f32_min_to_max_float_raw( - _ctx: &re_viewer_context::ViewerContext<'_>, - ui: &mut egui::Ui, - value: &mut MaybeMutRef<'_, impl std::ops::DerefMut>, + value: &mut MaybeMutRef<'_, impl std::ops::DerefMut>, ) -> egui::Response { let mut value: MaybeMutRef<'_, f32> = match value { MaybeMutRef::Ref(value) => MaybeMutRef::Ref(value), - MaybeMutRef::MutRef(value) => MaybeMutRef::MutRef(value), + MaybeMutRef::MutRef(value) => MaybeMutRef::MutRef(&mut value.deref_mut().0), }; edit_f32_float_raw_impl(ui, &mut value, f32::MIN..=f32::MAX) } diff --git a/crates/viewer/re_edit_ui/src/datatype_editors/mod.rs b/crates/viewer/re_edit_ui/src/datatype_editors/mod.rs index 75999fcad66c..ab03716ba27c 100644 --- a/crates/viewer/re_edit_ui/src/datatype_editors/mod.rs +++ b/crates/viewer/re_edit_ui/src/datatype_editors/mod.rs @@ -3,12 +3,9 @@ mod enum_combobox; mod float_drag; mod singleline_string; -pub use bool_toggle::{edit_bool, edit_bool_raw}; +pub use bool_toggle::edit_bool; pub use enum_combobox::edit_view_enum; -pub use float_drag::{ - edit_f32_min_to_max_float_raw, edit_f32_zero_to_max, edit_f32_zero_to_max_float_raw, - edit_f32_zero_to_one, -}; +pub use float_drag::{edit_f32_min_to_max_float, edit_f32_zero_to_max, edit_f32_zero_to_one}; pub use singleline_string::{ display_name_ui, display_text_ui, edit_multiline_string, edit_singleline_string, }; diff --git a/crates/viewer/re_edit_ui/src/lib.rs b/crates/viewer/re_edit_ui/src/lib.rs index 802e8e6c3b72..ca19c3b463ca 100644 --- a/crates/viewer/re_edit_ui/src/lib.rs +++ b/crates/viewer/re_edit_ui/src/lib.rs @@ -13,9 +13,8 @@ mod response_utils; mod visual_bounds2d; use datatype_editors::{ - display_name_ui, display_text_ui, edit_bool, edit_bool_raw, edit_f32_min_to_max_float_raw, - edit_f32_zero_to_max, edit_f32_zero_to_max_float_raw, edit_f32_zero_to_one, - edit_multiline_string, edit_singleline_string, edit_view_enum, + display_name_ui, display_text_ui, edit_bool, edit_f32_min_to_max_float, edit_f32_zero_to_max, + edit_f32_zero_to_one, edit_multiline_string, edit_singleline_string, edit_view_enum, }; use re_types::{ blueprint::components::{BackgroundKind, Corner2D, LockRangeDuringZoom, ViewFit, Visible}, @@ -42,19 +41,18 @@ pub fn register_editors(registry: &mut re_viewer_context::ComponentUiRegistry) { registry.add_singleline_edit_or_view(range1d::edit_range1d); registry.add_singleline_edit_or_view::(edit_f32_zero_to_max); + registry.add_singleline_edit_or_view::(edit_f32_zero_to_max); registry.add_singleline_edit_or_view::(edit_f32_zero_to_max); - registry.add_singleline_edit_or_view::(edit_f32_zero_to_max); registry.add_singleline_edit_or_view::(edit_f32_zero_to_max); + registry.add_singleline_edit_or_view::(edit_f32_zero_to_max); + registry.add_singleline_edit_or_view::(edit_f32_zero_to_max); + registry.add_singleline_edit_or_view::(edit_f32_zero_to_max); - registry.add_singleline_edit_or_view::(edit_f32_min_to_max_float_raw); - - registry.add_singleline_edit_or_view::(edit_f32_zero_to_max_float_raw); - registry.add_singleline_edit_or_view::(edit_f32_zero_to_max_float_raw); - registry.add_singleline_edit_or_view::(edit_f32_zero_to_max_float_raw); + registry.add_singleline_edit_or_view::(edit_f32_min_to_max_float); registry.add_singleline_edit_or_view::(edit_f32_zero_to_one); - registry.add_singleline_edit_or_view::(edit_bool_raw); + registry.add_singleline_edit_or_view::(edit_bool); registry.add_singleline_edit_or_view::(edit_bool); registry.add_display_ui(Text::name(), Box::new(display_text_ui)); diff --git a/crates/viewer/re_selection_panel/src/selection_panel.rs b/crates/viewer/re_selection_panel/src/selection_panel.rs index 54071d1a80dd..4f7c5c6f22f0 100644 --- a/crates/viewer/re_selection_panel/src/selection_panel.rs +++ b/crates/viewer/re_selection_panel/src/selection_panel.rs @@ -1155,7 +1155,7 @@ fn visible_interactive_toggle_ui( data_result.save_recursive_override_or_clear_if_redundant( ctx.viewer_ctx, &query_result.tree, - &Visible(visible), + &Visible::from(visible), ); } } diff --git a/crates/viewer/re_space_view_bar_chart/src/space_view_class.rs b/crates/viewer/re_space_view_bar_chart/src/space_view_class.rs index bdfdf6f81dc1..1e32240989ba 100644 --- a/crates/viewer/re_space_view_bar_chart/src/space_view_class.rs +++ b/crates/viewer/re_space_view_bar_chart/src/space_view_class.rs @@ -156,7 +156,7 @@ impl SpaceViewClass for BarChartSpaceView { .clamp_grid(true) .allow_zoom([true, zoom_both_axis]); - if *legend_visible { + if *legend_visible.0 { plot = plot.legend(Legend::default().position(legend_corner.into())); } diff --git a/crates/viewer/re_space_view_spatial/src/contexts/transform_context.rs b/crates/viewer/re_space_view_spatial/src/contexts/transform_context.rs index e0fff1aa15be..7e5d5484d176 100644 --- a/crates/viewer/re_space_view_spatial/src/contexts/transform_context.rs +++ b/crates/viewer/re_space_view_spatial/src/contexts/transform_context.rs @@ -392,7 +392,7 @@ fn transform_at( let is_disconnect_space = || { entity_db .latest_at_component::(entity_path, query) - .map_or(false, |res| res.value.0) + .map_or(false, |res| **res.value) }; // If there is any other transform, we ignore `DisconnectedSpace`. diff --git a/crates/viewer/re_space_view_spatial/src/mesh_loader.rs b/crates/viewer/re_space_view_spatial/src/mesh_loader.rs index 108516c1ad07..1ef30c9e371e 100644 --- a/crates/viewer/re_space_view_spatial/src/mesh_loader.rs +++ b/crates/viewer/re_space_view_spatial/src/mesh_loader.rs @@ -79,9 +79,9 @@ impl LoadedMesh { transform: _, } = asset3d; - let media_type = MediaType::or_guess_from_data(media_type.clone(), blob.0.as_slice()) + let media_type = MediaType::or_guess_from_data(media_type.clone(), blob.as_slice()) .ok_or_else(|| anyhow::anyhow!("couldn't guess media type"))?; - let slf = Self::load_asset3d_parts(name, &media_type, blob.0.as_slice(), render_ctx)?; + let slf = Self::load_asset3d_parts(name, &media_type, blob.as_slice(), render_ctx)?; Ok(slf) } diff --git a/crates/viewer/re_space_view_spatial/src/ui.rs b/crates/viewer/re_space_view_spatial/src/ui.rs index fdb14900199b..858941c79394 100644 --- a/crates/viewer/re_space_view_spatial/src/ui.rs +++ b/crates/viewer/re_space_view_spatial/src/ui.rs @@ -524,7 +524,7 @@ pub fn picking( let [x, y] = image_info.coordinates; if let Some(raw_value) = image_info.tensor.get(&[y as _, x as _]) { let raw_value = raw_value.as_f64(); - let depth_in_meters = raw_value / meter.0 as f64; + let depth_in_meters = raw_value / *meter.0 as f64; depth_at_pointer = Some(depth_in_meters as f32); } } @@ -547,7 +547,7 @@ pub fn picking( image_info.row_id, annotations, image_info.meaning, - image_info.depth_meter.map(|d| d.0), + image_info.depth_meter.map(|d| *d.0), Some(image_info.colormap), ); }); diff --git a/crates/viewer/re_space_view_spatial/src/ui_3d.rs b/crates/viewer/re_space_view_spatial/src/ui_3d.rs index 28448b1156ca..ee8f351b163b 100644 --- a/crates/viewer/re_space_view_spatial/src/ui_3d.rs +++ b/crates/viewer/re_space_view_spatial/src/ui_3d.rs @@ -648,7 +648,7 @@ impl SpatialSpaceView3D { } // TODO(andreas): Make configurable. Could pick up default radius for this view? - let box_line_radius = Size(re_types::components::Radius::default().0); + let box_line_radius = Size(*re_types::components::Radius::default().0); if state.state_3d.show_bbox { line_builder diff --git a/crates/viewer/re_space_view_spatial/src/visualizers/depth_images.rs b/crates/viewer/re_space_view_spatial/src/visualizers/depth_images.rs index 59385898c818..60dcc8fad75d 100644 --- a/crates/viewer/re_space_view_spatial/src/visualizers/depth_images.rs +++ b/crates/viewer/re_space_view_spatial/src/visualizers/depth_images.rs @@ -227,7 +227,7 @@ impl DepthImageVisualizer { Some(colormap), )?; - let world_depth_from_texture_depth = 1.0 / depth_meter.0; + let world_depth_from_texture_depth = 1.0 / *depth_meter.0; // We want point radius to be defined in a scale where the radius of a point // is a factor of the diameter of a pixel projected at that distance. diff --git a/crates/viewer/re_space_view_spatial/src/visualizers/mod.rs b/crates/viewer/re_space_view_spatial/src/visualizers/mod.rs index 48b6829aa2b2..9df2935a88cd 100644 --- a/crates/viewer/re_space_view_spatial/src/visualizers/mod.rs +++ b/crates/viewer/re_space_view_spatial/src/visualizers/mod.rs @@ -184,7 +184,7 @@ pub fn process_radius_slice( re_tracing::profile_function!(); if radii.is_empty() { - vec![re_renderer::Size(fallback_radius.0); num_instances] + vec![re_renderer::Size(*fallback_radius.0); num_instances] } else { entity_iterator::clamped(radii, num_instances) .map(|radius| process_radius(entity_path, *radius)) @@ -202,7 +202,7 @@ fn process_radius( re_log::warn_once!("Found NaN radius in entity {entity_path}"); } - re_renderer::Size(radius.0) + re_renderer::Size(*radius.0) } /// Resolves all annotations and keypoints for the given entity view. @@ -296,7 +296,7 @@ pub fn load_keypoint_connections( .picking_object_id(re_renderer::PickingLayerObjectId(ent_path.hash64())); // TODO(andreas): Make configurable. Should we pick up the point's radius and make this proportional? - let line_radius = re_renderer::Size(re_types::components::Radius::default().0); + let line_radius = re_renderer::Size(*re_types::components::Radius::default().0); for ((class_id, _time), keypoints_in_class) in keypoints { let resolved_class_description = ent_context diff --git a/crates/viewer/re_space_view_time_series/src/line_visualizer_system.rs b/crates/viewer/re_space_view_time_series/src/line_visualizer_system.rs index b84d17b43c58..75bf86bd91e8 100644 --- a/crates/viewer/re_space_view_time_series/src/line_visualizer_system.rs +++ b/crates/viewer/re_space_view_time_series/src/line_visualizer_system.rs @@ -73,7 +73,7 @@ impl TypedComponentFallbackProvider for SeriesLineSystem { impl TypedComponentFallbackProvider for SeriesLineSystem { fn fallback_for(&self, _ctx: &QueryContext<'_>) -> StrokeWidth { - StrokeWidth(DEFAULT_STROKE_WIDTH) + StrokeWidth(DEFAULT_STROKE_WIDTH.into()) } } @@ -169,7 +169,7 @@ impl SeriesLineSystem { value: 0.0, attrs: PlotPointAttrs { color: fallback_color.into(), - radius_ui: 0.5 * fallback_stroke_width.0, + radius_ui: 0.5 * *fallback_stroke_width.0, kind: PlotSeriesKind::Continuous, }, }; @@ -252,7 +252,7 @@ impl SeriesLineSystem { } else if scalars.is_empty() { points[i].attrs.kind = PlotSeriesKind::Clear; } else { - points[i].value = scalars.first().map_or(0.0, |s| s.0); + points[i].value = scalars.first().map_or(0.0, |s| *s.0); } } @@ -311,7 +311,7 @@ impl SeriesLineSystem { for (i, (_index, _scalars, stroke_widths)) in all_frames { if let Some(stroke_width) = - stroke_widths.and_then(|stroke_widths| stroke_widths.first().map(|r| r.0)) + stroke_widths.and_then(|stroke_widths| stroke_widths.first().map(|r| *r.0)) { points[i].attrs.radius_ui = 0.5 * stroke_width; } diff --git a/crates/viewer/re_space_view_time_series/src/point_visualizer_system.rs b/crates/viewer/re_space_view_time_series/src/point_visualizer_system.rs index 96f4daa0339d..0f3031ce0a9d 100644 --- a/crates/viewer/re_space_view_time_series/src/point_visualizer_system.rs +++ b/crates/viewer/re_space_view_time_series/src/point_visualizer_system.rs @@ -75,7 +75,7 @@ impl TypedComponentFallbackProvider for SeriesPointSystem { impl TypedComponentFallbackProvider for SeriesPointSystem { fn fallback_for(&self, _ctx: &QueryContext<'_>) -> MarkerSize { - MarkerSize(DEFAULT_MARKER_SIZE) + MarkerSize::from(DEFAULT_MARKER_SIZE) } } @@ -127,7 +127,7 @@ impl SeriesPointSystem { value: 0.0, attrs: PlotPointAttrs { color: fallback_color.into(), - radius_ui: fallback_size.into(), + radius_ui: **fallback_size, kind: PlotSeriesKind::Scatter(ScatterAttrs { marker: fallback_shape, }), @@ -214,7 +214,7 @@ impl SeriesPointSystem { } else if scalars.is_empty() { points[i].attrs.kind = PlotSeriesKind::Clear; } else { - points[i].value = scalars.first().map_or(0.0, |s| s.0); + points[i].value = scalars.first().map_or(0.0, |s| *s.0); } } @@ -280,7 +280,7 @@ impl SeriesPointSystem { if let Some(marker_size) = marker_sizes.and_then(|marker_sizes| marker_sizes.first().copied()) { - points[i].attrs.radius_ui = marker_size.0; + points[i].attrs.radius_ui = *marker_size.0; } } } diff --git a/crates/viewer/re_space_view_time_series/src/space_view_class.rs b/crates/viewer/re_space_view_time_series/src/space_view_class.rs index 1b338e986ca7..0fe96f0f6451 100644 --- a/crates/viewer/re_space_view_time_series/src/space_view_class.rs +++ b/crates/viewer/re_space_view_time_series/src/space_view_class.rs @@ -374,7 +374,7 @@ impl SpaceViewClass for TimeSeriesSpaceView { } }); - if *legend_visible { + if *legend_visible.0 { plot = plot.legend(Legend::default().position(legend_corner.into())); } diff --git a/crates/viewer/re_viewer_context/src/space_view/view_query.rs b/crates/viewer/re_viewer_context/src/space_view/view_query.rs index 6c92b5fb76e5..b15137a43490 100644 --- a/crates/viewer/re_viewer_context/src/space_view/view_query.rs +++ b/crates/viewer/re_viewer_context/src/space_view/view_query.rs @@ -222,7 +222,8 @@ impl DataResult { // TODO(#6541): Check the datastore. #[inline] pub fn is_visible(&self, ctx: &ViewerContext<'_>) -> bool { - self.lookup_override::(ctx) + *self + .lookup_override::(ctx) .unwrap_or_default() .0 } diff --git a/crates/viewer/re_viewport_blueprint/src/container.rs b/crates/viewer/re_viewport_blueprint/src/container.rs index 08745901d3ae..e2df151a5911 100644 --- a/crates/viewer/re_viewport_blueprint/src/container.rs +++ b/crates/viewer/re_viewport_blueprint/src/container.rs @@ -93,15 +93,21 @@ impl ContainerBlueprint { .filter_map(|id| Contents::try_from(&id.0.clone().into())) .collect(); - let col_shares = col_shares.unwrap_or_default().iter().map(|v| v.0).collect(); - - let row_shares = row_shares.unwrap_or_default().iter().map(|v| v.0).collect(); + let col_shares = col_shares + .unwrap_or_default() + .iter() + .map(|v| *v.0) + .collect(); + let row_shares = row_shares + .unwrap_or_default() + .iter() + .map(|v| *v.0) + .collect(); let active_tab = active_tab.and_then(|id| Contents::try_from(&id.0.into())); - let visible = visible.map_or(true, |v| v.0); - - let grid_columns = grid_columns.map(|v| v.0); + let visible = visible.map_or(true, |v| **v); + let grid_columns = grid_columns.map(|v| **v); Some(Self { id, @@ -312,7 +318,7 @@ impl ContainerBlueprint { #[inline] pub fn set_visible(&self, ctx: &ViewerContext<'_>, visible: bool) { if visible != self.visible { - let component = Visible(visible); + let component = Visible::from(visible); ctx.save_blueprint_component(&self.entity_path(), &component); } } @@ -321,7 +327,7 @@ impl ContainerBlueprint { pub fn set_grid_columns(&self, ctx: &ViewerContext<'_>, grid_columns: Option) { if grid_columns != self.grid_columns { if let Some(grid_columns) = grid_columns { - let component = GridColumns(grid_columns); + let component = GridColumns(grid_columns.into()); ctx.save_blueprint_component(&self.entity_path(), &component); } else { ctx.save_empty_blueprint_component::(&self.entity_path()); diff --git a/crates/viewer/re_viewport_blueprint/src/space_view.rs b/crates/viewer/re_viewport_blueprint/src/space_view.rs index 4a299c5001ba..cd0be712a1fa 100644 --- a/crates/viewer/re_viewport_blueprint/src/space_view.rs +++ b/crates/viewer/re_viewport_blueprint/src/space_view.rs @@ -173,7 +173,7 @@ impl SpaceViewBlueprint { class_identifier, &space_env, ); - let visible = visible.map_or(true, |v| v.0); + let visible = visible.map_or(true, |v| *v.0); let defaults_path = id.as_entity_path().join(&"defaults".into()); Some(Self { @@ -342,7 +342,7 @@ impl SpaceViewBlueprint { #[inline] pub fn set_visible(&self, ctx: &ViewerContext<'_>, visible: bool) { if visible != self.visible { - let component = Visible(visible); + let component = Visible::from(visible); ctx.save_blueprint_component(&self.entity_path(), &component); } } diff --git a/crates/viewer/re_viewport_blueprint/src/space_view_contents.rs b/crates/viewer/re_viewport_blueprint/src/space_view_contents.rs index 2460296a12ae..baf94491d09a 100644 --- a/crates/viewer/re_viewport_blueprint/src/space_view_contents.rs +++ b/crates/viewer/re_viewport_blueprint/src/space_view_contents.rs @@ -406,7 +406,7 @@ impl DataQueryPropertyResolver<'_> { .map(|c| c.value) { node.data_result.visualizers = - viz_override.0.iter().map(|v| v.as_str().into()).collect(); + viz_override.0.iter().map(Into::into).collect(); } else { // Otherwise ask the `SpaceViewClass` to choose. node.data_result.visualizers = self diff --git a/crates/viewer/re_viewport_blueprint/src/viewport_blueprint.rs b/crates/viewer/re_viewport_blueprint/src/viewport_blueprint.rs index 93afa4352511..2360c0504482 100644 --- a/crates/viewer/re_viewport_blueprint/src/viewport_blueprint.rs +++ b/crates/viewer/re_viewport_blueprint/src/viewport_blueprint.rs @@ -138,9 +138,9 @@ impl ViewportBlueprint { .store_info() .map_or(false, |ri| ri.is_app_default_blueprint()); let auto_layout = - AtomicBool::new(auto_layout.map_or(is_app_default_blueprint, |auto| auto.0)); + AtomicBool::new(auto_layout.map_or(is_app_default_blueprint, |auto| *auto.0)); let auto_space_views = - AtomicBool::new(auto_space_views.map_or(is_app_default_blueprint, |auto| auto.0)); + AtomicBool::new(auto_space_views.map_or(is_app_default_blueprint, |auto| *auto.0)); let tree = build_tree_from_space_views_and_containers( space_views.values(), @@ -778,7 +778,7 @@ impl ViewportBlueprint { let old_value = self.auto_layout.swap(value, Ordering::SeqCst); if old_value != value { - let component = AutoLayout(value); + let component = AutoLayout::from(value); ctx.save_blueprint_component(&VIEWPORT_PATH.into(), &component); } } @@ -793,7 +793,7 @@ impl ViewportBlueprint { let old_value = self.auto_space_views.swap(value, Ordering::SeqCst); if old_value != value { - let component = AutoSpaceViews(value); + let component = AutoSpaceViews::from(value); ctx.save_blueprint_component(&VIEWPORT_PATH.into(), &component); } } diff --git a/docs/content/reference/types/components/blob.md b/docs/content/reference/types/components/blob.md index 2a8c2851288a..d1d50af1974d 100644 --- a/docs/content/reference/types/components/blob.md +++ b/docs/content/reference/types/components/blob.md @@ -7,7 +7,7 @@ A binary blob of data. ## Fields -* data: list of `u8` +* data: [`Blob`](../datatypes/blob.md) ## API reference links * 🌊 [C++ API docs for `Blob`](https://ref.rerun.io/docs/cpp/stable/structrerun_1_1components_1_1Blob.html) diff --git a/docs/content/reference/types/components/clear_is_recursive.md b/docs/content/reference/types/components/clear_is_recursive.md index e9276e2cdc29..4987c79c1676 100644 --- a/docs/content/reference/types/components/clear_is_recursive.md +++ b/docs/content/reference/types/components/clear_is_recursive.md @@ -7,7 +7,7 @@ Configures how a clear operation should behave - recursive or not. ## Fields -* recursive: `bool` +* recursive: [`Bool`](../datatypes/bool.md) ## API reference links * 🌊 [C++ API docs for `ClearIsRecursive`](https://ref.rerun.io/docs/cpp/stable/structrerun_1_1components_1_1ClearIsRecursive.html) diff --git a/docs/content/reference/types/components/depth_meter.md b/docs/content/reference/types/components/depth_meter.md index 1ad7341ebf71..889700508147 100644 --- a/docs/content/reference/types/components/depth_meter.md +++ b/docs/content/reference/types/components/depth_meter.md @@ -14,7 +14,7 @@ In 3D views on the other hand, this affects where the points of the point cloud ## Fields -* value: `f32` +* value: [`Float32`](../datatypes/float32.md) ## API reference links * 🌊 [C++ API docs for `DepthMeter`](https://ref.rerun.io/docs/cpp/stable/structrerun_1_1components_1_1DepthMeter.html) diff --git a/docs/content/reference/types/components/disconnected_space.md b/docs/content/reference/types/components/disconnected_space.md index 766aeba9bc02..7e56f28b171f 100644 --- a/docs/content/reference/types/components/disconnected_space.md +++ b/docs/content/reference/types/components/disconnected_space.md @@ -12,7 +12,7 @@ This is useful for specifying that a subgraph is independent of the rest of the ## Fields -* is_disconnected: `bool` +* is_disconnected: [`Bool`](../datatypes/bool.md) ## API reference links * 🌊 [C++ API docs for `DisconnectedSpace`](https://ref.rerun.io/docs/cpp/stable/structrerun_1_1components_1_1DisconnectedSpace.html) diff --git a/docs/content/reference/types/components/draw_order.md b/docs/content/reference/types/components/draw_order.md index 07507a41990a..d184b91b56eb 100644 --- a/docs/content/reference/types/components/draw_order.md +++ b/docs/content/reference/types/components/draw_order.md @@ -12,7 +12,7 @@ Draw order for entities with the same draw order is generally undefined. ## Fields -* value: `f32` +* value: [`Float32`](../datatypes/float32.md) ## API reference links * 🌊 [C++ API docs for `DrawOrder`](https://ref.rerun.io/docs/cpp/stable/structrerun_1_1components_1_1DrawOrder.html) diff --git a/docs/content/reference/types/components/marker_size.md b/docs/content/reference/types/components/marker_size.md index 416d5cfda764..20a70f9f2167 100644 --- a/docs/content/reference/types/components/marker_size.md +++ b/docs/content/reference/types/components/marker_size.md @@ -7,7 +7,7 @@ Radius of a marker of a point in e.g. a 2D plot, measured in UI points. ## Fields -* value: `f32` +* value: [`Float32`](../datatypes/float32.md) ## API reference links * 🌊 [C++ API docs for `MarkerSize`](https://ref.rerun.io/docs/cpp/stable/structrerun_1_1components_1_1MarkerSize.html) diff --git a/docs/content/reference/types/components/radius.md b/docs/content/reference/types/components/radius.md index 51094afdb5fa..1e903fb0a93a 100644 --- a/docs/content/reference/types/components/radius.md +++ b/docs/content/reference/types/components/radius.md @@ -14,7 +14,7 @@ The Viewer's UI scaling defaults to the OS scaling which typically is 100% for f ## Fields -* value: `f32` +* value: [`Float32`](../datatypes/float32.md) ## API reference links * 🌊 [C++ API docs for `Radius`](https://ref.rerun.io/docs/cpp/stable/structrerun_1_1components_1_1Radius.html) diff --git a/docs/content/reference/types/components/scalar.md b/docs/content/reference/types/components/scalar.md index a8a7b8d8ccd0..6e966a9be716 100644 --- a/docs/content/reference/types/components/scalar.md +++ b/docs/content/reference/types/components/scalar.md @@ -9,7 +9,7 @@ Used for time series plots. ## Fields -* value: `f64` +* value: [`Float64`](../datatypes/float64.md) ## API reference links * 🌊 [C++ API docs for `Scalar`](https://ref.rerun.io/docs/cpp/stable/structrerun_1_1components_1_1Scalar.html) diff --git a/docs/content/reference/types/components/stroke_width.md b/docs/content/reference/types/components/stroke_width.md index b7a92ae03a07..02494ce8307c 100644 --- a/docs/content/reference/types/components/stroke_width.md +++ b/docs/content/reference/types/components/stroke_width.md @@ -7,7 +7,7 @@ The width of a stroke specified in UI points. ## Fields -* width: `f32` +* width: [`Float32`](../datatypes/float32.md) ## API reference links * 🌊 [C++ API docs for `StrokeWidth`](https://ref.rerun.io/docs/cpp/stable/structrerun_1_1components_1_1StrokeWidth.html) diff --git a/docs/content/reference/types/components/view_coordinates.md b/docs/content/reference/types/components/view_coordinates.md index 4bf3e55ea693..ad993b0098ac 100644 --- a/docs/content/reference/types/components/view_coordinates.md +++ b/docs/content/reference/types/components/view_coordinates.md @@ -22,7 +22,7 @@ The following constants are used to represent the different directions: ## Fields -* coordinates: 3x `u8` +* coordinates: [`ViewCoordinates`](../datatypes/view_coordinates.md) ## API reference links * 🌊 [C++ API docs for `ViewCoordinates`](https://ref.rerun.io/docs/cpp/stable/structrerun_1_1components_1_1ViewCoordinates.html) diff --git a/docs/content/reference/types/datatypes.md b/docs/content/reference/types/datatypes.md index 84100ceacbea..d448c2e9ebfe 100644 --- a/docs/content/reference/types/datatypes.md +++ b/docs/content/reference/types/datatypes.md @@ -9,12 +9,14 @@ Data types are the lowest layer of the data model hierarchy. They are re-usable * [`Angle`](datatypes/angle.md): Angle in either radians or degrees. * [`AnnotationInfo`](datatypes/annotation_info.md): Annotation info annotating a class id or key-point id. +* [`Blob`](datatypes/blob.md): A binary blob of data. * [`Bool`](datatypes/bool.md): A single boolean. * [`ClassDescription`](datatypes/class_description.md): The description of a semantic Class. * [`ClassDescriptionMapElem`](datatypes/class_description_map_elem.md): A helper type for mapping class IDs to class descriptions. * [`ClassId`](datatypes/class_id.md): A 16-bit ID representing a type of semantic class. * [`EntityPath`](datatypes/entity_path.md): A path to an entity in the `ChunkStore`. * [`Float32`](datatypes/float32.md): A single-precision 32-bit IEEE 754 floating point number. +* [`Float64`](datatypes/float64.md): A double-precision 64-bit IEEE 754 floating point number. * [`KeypointId`](datatypes/keypoint_id.md): A 16-bit ID representing a type of semantic keypoint within a class. * [`KeypointPair`](datatypes/keypoint_pair.md): A connection between two `Keypoints`. * [`Mat3x3`](datatypes/mat3x3.md): A 3x3 Matrix. @@ -48,5 +50,6 @@ Data types are the lowest layer of the data model hierarchy. They are re-usable * [`Vec2D`](datatypes/vec2d.md): A vector in 2D space. * [`Vec3D`](datatypes/vec3d.md): A vector in 3D space. * [`Vec4D`](datatypes/vec4d.md): A vector in 4D space. +* [`ViewCoordinates`](datatypes/view_coordinates.md): How we interpret the coordinate system of an entity/space. * [`VisibleTimeRange`](datatypes/visible_time_range.md): Visible time range bounds for a specific timeline. diff --git a/docs/content/reference/types/datatypes/.gitattributes b/docs/content/reference/types/datatypes/.gitattributes index 7d1b1d3b2927..1dc294049dc2 100644 --- a/docs/content/reference/types/datatypes/.gitattributes +++ b/docs/content/reference/types/datatypes/.gitattributes @@ -3,12 +3,14 @@ .gitattributes linguist-generated=true angle.md linguist-generated=true annotation_info.md linguist-generated=true +blob.md linguist-generated=true bool.md linguist-generated=true class_description.md linguist-generated=true class_description_map_elem.md linguist-generated=true class_id.md linguist-generated=true entity_path.md linguist-generated=true float32.md linguist-generated=true +float64.md linguist-generated=true keypoint_id.md linguist-generated=true keypoint_pair.md linguist-generated=true mat3x3.md linguist-generated=true @@ -42,4 +44,5 @@ uvec4d.md linguist-generated=true vec2d.md linguist-generated=true vec3d.md linguist-generated=true vec4d.md linguist-generated=true +view_coordinates.md linguist-generated=true visible_time_range.md linguist-generated=true diff --git a/docs/content/reference/types/datatypes/blob.md b/docs/content/reference/types/datatypes/blob.md new file mode 100644 index 000000000000..b903cf6de722 --- /dev/null +++ b/docs/content/reference/types/datatypes/blob.md @@ -0,0 +1,20 @@ +--- +title: "Blob" +--- + + +A binary blob of data. + +## Fields + +* data: list of `u8` + +## API reference links + * 🌊 [C++ API docs for `Blob`](https://ref.rerun.io/docs/cpp/stable/structrerun_1_1datatypes_1_1Blob.html?speculative-link) + * 🐍 [Python API docs for `Blob`](https://ref.rerun.io/docs/python/stable/common/datatypes?speculative-link#rerun.datatypes.Blob) + * 🦀 [Rust API docs for `Blob`](https://docs.rs/rerun/latest/rerun/datatypes/struct.Blob.html?speculative-link) + + +## Used by + +* [`Blob`](../components/blob.md) diff --git a/docs/content/reference/types/datatypes/bool.md b/docs/content/reference/types/datatypes/bool.md index 44de3536d6dd..c1edda7aa2a3 100644 --- a/docs/content/reference/types/datatypes/bool.md +++ b/docs/content/reference/types/datatypes/bool.md @@ -15,3 +15,7 @@ A single boolean. * 🦀 [Rust API docs for `Bool`](https://docs.rs/rerun/latest/rerun/datatypes/struct.Bool.html) +## Used by + +* [`ClearIsRecursive`](../components/clear_is_recursive.md) +* [`DisconnectedSpace`](../components/disconnected_space.md) diff --git a/docs/content/reference/types/datatypes/float32.md b/docs/content/reference/types/datatypes/float32.md index 2a7ce61ec16f..8b751c47b662 100644 --- a/docs/content/reference/types/datatypes/float32.md +++ b/docs/content/reference/types/datatypes/float32.md @@ -18,7 +18,12 @@ A single-precision 32-bit IEEE 754 floating point number. ## Used by * [`AxisLength`](../components/axis_length.md) +* [`DepthMeter`](../components/depth_meter.md) +* [`DrawOrder`](../components/draw_order.md) * [`FillRatio`](../components/fill_ratio.md) * [`GammaCorrection`](../components/gamma_correction.md) * [`ImagePlaneDistance`](../components/image_plane_distance.md) +* [`MarkerSize`](../components/marker_size.md) * [`Opacity`](../components/opacity.md) +* [`Radius`](../components/radius.md) +* [`StrokeWidth`](../components/stroke_width.md) diff --git a/docs/content/reference/types/datatypes/float64.md b/docs/content/reference/types/datatypes/float64.md new file mode 100644 index 000000000000..691ebc959335 --- /dev/null +++ b/docs/content/reference/types/datatypes/float64.md @@ -0,0 +1,20 @@ +--- +title: "Float64" +--- + + +A double-precision 64-bit IEEE 754 floating point number. + +## Fields + +* value: `f64` + +## API reference links + * 🌊 [C++ API docs for `Float64`](https://ref.rerun.io/docs/cpp/stable/structrerun_1_1datatypes_1_1Float64.html?speculative-link) + * 🐍 [Python API docs for `Float64`](https://ref.rerun.io/docs/python/stable/common/datatypes?speculative-link#rerun.datatypes.Float64) + * 🦀 [Rust API docs for `Float64`](https://docs.rs/rerun/latest/rerun/datatypes/struct.Float64.html?speculative-link) + + +## Used by + +* [`Scalar`](../components/scalar.md) diff --git a/docs/content/reference/types/datatypes/view_coordinates.md b/docs/content/reference/types/datatypes/view_coordinates.md new file mode 100644 index 000000000000..81675b2ab213 --- /dev/null +++ b/docs/content/reference/types/datatypes/view_coordinates.md @@ -0,0 +1,35 @@ +--- +title: "ViewCoordinates" +--- + + +How we interpret the coordinate system of an entity/space. + +For instance: What is "up"? What does the Z axis mean? Is this right-handed or left-handed? + +The three coordinates are always ordered as [x, y, z]. + +For example [Right, Down, Forward] means that the X axis points to the right, the Y axis points +down, and the Z axis points forward. + +The following constants are used to represent the different directions: + * Up = 1 + * Down = 2 + * Right = 3 + * Left = 4 + * Forward = 5 + * Back = 6 + +## Fields + +* coordinates: 3x `u8` + +## API reference links + * 🌊 [C++ API docs for `ViewCoordinates`](https://ref.rerun.io/docs/cpp/stable/structrerun_1_1datatypes_1_1ViewCoordinates.html?speculative-link) + * 🐍 [Python API docs for `ViewCoordinates`](https://ref.rerun.io/docs/python/stable/common/datatypes?speculative-link#rerun.datatypes.ViewCoordinates) + * 🦀 [Rust API docs for `ViewCoordinates`](https://docs.rs/rerun/latest/rerun/datatypes/struct.ViewCoordinates.html?speculative-link) + + +## Used by + +* [`ViewCoordinates`](../components/view_coordinates.md) diff --git a/docs/snippets/all/tutorials/temporal_batch.rs b/docs/snippets/all/tutorials/temporal_batch.rs index ab8b4d81d192..684a452e6c53 100644 --- a/docs/snippets/all/tutorials/temporal_batch.rs +++ b/docs/snippets/all/tutorials/temporal_batch.rs @@ -16,7 +16,7 @@ fn main() -> Result<(), Box> { // Convert to rerun time / scalars let timeline_values = ChunkTimeline::new_sequence("step", timeline_values); - let scalar_data = scalar_data.into_iter().map(Scalar).collect::>(); + let scalar_data: Vec = scalar_data.into_iter().map(Into::into).collect(); rec.log_temporal_batch("scalars", [timeline_values], [&scalar_data as _])?; diff --git a/examples/rust/incremental_logging/src/main.rs b/examples/rust/incremental_logging/src/main.rs index e5ba8f616bc3..799e5754c26a 100644 --- a/examples/rust/incremental_logging/src/main.rs +++ b/examples/rust/incremental_logging/src/main.rs @@ -59,7 +59,7 @@ fn run(rec: &rerun::RecordingStream) -> anyhow::Result<()> { rec.log_static("readme", &rerun::TextDocument::from_markdown(README))?; let colors = [rerun::Color::from_rgb(255, 0, 0)]; - let radii = [rerun::Radius(0.1)]; + let radii = [rerun::Radius::from(0.1)]; // Only log colors and radii once. rec.set_time_sequence("frame_nr", 0); diff --git a/rerun_cpp/src/rerun/blueprint/components/.gitattributes b/rerun_cpp/src/rerun/blueprint/components/.gitattributes index a402cc3d6294..11d00c3d1875 100644 --- a/rerun_cpp/src/rerun/blueprint/components/.gitattributes +++ b/rerun_cpp/src/rerun/blueprint/components/.gitattributes @@ -2,19 +2,15 @@ .gitattributes linguist-generated=true active_tab.hpp linguist-generated=true -auto_layout.cpp linguist-generated=true auto_layout.hpp linguist-generated=true -auto_space_views.cpp linguist-generated=true auto_space_views.hpp linguist-generated=true background_kind.cpp linguist-generated=true background_kind.hpp linguist-generated=true -column_share.cpp linguist-generated=true column_share.hpp linguist-generated=true container_kind.cpp linguist-generated=true container_kind.hpp linguist-generated=true corner2d.cpp linguist-generated=true corner2d.hpp linguist-generated=true -grid_columns.cpp linguist-generated=true grid_columns.hpp linguist-generated=true included_content.hpp linguist-generated=true included_space_view.hpp linguist-generated=true @@ -24,7 +20,6 @@ panel_state.cpp linguist-generated=true panel_state.hpp linguist-generated=true query_expression.hpp linguist-generated=true root_container.hpp linguist-generated=true -row_share.cpp linguist-generated=true row_share.hpp linguist-generated=true space_view_class.hpp linguist-generated=true space_view_maximized.hpp linguist-generated=true @@ -33,9 +28,7 @@ tensor_dimension_index_slider.hpp linguist-generated=true view_fit.cpp linguist-generated=true view_fit.hpp linguist-generated=true viewer_recommendation_hash.hpp linguist-generated=true -visible.cpp linguist-generated=true visible.hpp linguist-generated=true visible_time_range.hpp linguist-generated=true visual_bounds2d.hpp linguist-generated=true -visualizer_overrides.cpp linguist-generated=true visualizer_overrides.hpp linguist-generated=true diff --git a/rerun_cpp/src/rerun/blueprint/components/auto_layout.cpp b/rerun_cpp/src/rerun/blueprint/components/auto_layout.cpp deleted file mode 100644 index 6f1413f69527..000000000000 --- a/rerun_cpp/src/rerun/blueprint/components/auto_layout.cpp +++ /dev/null @@ -1,60 +0,0 @@ -// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/cpp/mod.rs -// Based on "crates/store/re_types/definitions/rerun/blueprint/components/auto_layout.fbs". - -#include "auto_layout.hpp" - -#include -#include - -namespace rerun::blueprint::components {} - -namespace rerun { - const std::shared_ptr& - Loggable::arrow_datatype() { - static const auto datatype = arrow::boolean(); - return datatype; - } - - Result> Loggable::to_arrow( - const blueprint::components::AutoLayout* instances, size_t num_instances - ) { - // TODO(andreas): Allow configuring the memory pool. - arrow::MemoryPool* pool = arrow::default_memory_pool(); - auto datatype = arrow_datatype(); - - ARROW_ASSIGN_OR_RAISE(auto builder, arrow::MakeBuilder(datatype, pool)) - if (instances && num_instances > 0) { - RR_RETURN_NOT_OK(Loggable::fill_arrow_array_builder( - static_cast(builder.get()), - instances, - num_instances - )); - } - std::shared_ptr array; - ARROW_RETURN_NOT_OK(builder->Finish(&array)); - return array; - } - - rerun::Error Loggable::fill_arrow_array_builder( - arrow::BooleanBuilder* builder, const blueprint::components::AutoLayout* elements, - size_t num_elements - ) { - if (builder == nullptr) { - return rerun::Error(ErrorCode::UnexpectedNullArgument, "Passed array builder is null."); - } - if (elements == nullptr) { - return rerun::Error( - ErrorCode::UnexpectedNullArgument, - "Cannot serialize null pointer to arrow array." - ); - } - - static_assert(sizeof(*elements) == sizeof(elements->auto_layout)); - ARROW_RETURN_NOT_OK(builder->AppendValues( - reinterpret_cast(&elements->auto_layout), - static_cast(num_elements) - )); - - return Error::ok(); - } -} // namespace rerun diff --git a/rerun_cpp/src/rerun/blueprint/components/auto_layout.hpp b/rerun_cpp/src/rerun/blueprint/components/auto_layout.hpp index a1406f66c58b..5d82808947b9 100644 --- a/rerun_cpp/src/rerun/blueprint/components/auto_layout.hpp +++ b/rerun_cpp/src/rerun/blueprint/components/auto_layout.hpp @@ -3,37 +3,43 @@ #pragma once +#include "../../datatypes/bool.hpp" #include "../../result.hpp" #include #include -namespace arrow { - class Array; - class BooleanBuilder; - class DataType; -} // namespace arrow - namespace rerun::blueprint::components { /// **Component**: Whether the viewport layout is determined automatically. struct AutoLayout { - bool auto_layout; + rerun::datatypes::Bool auto_layout; public: AutoLayout() = default; - AutoLayout(bool auto_layout_) : auto_layout(auto_layout_) {} + AutoLayout(rerun::datatypes::Bool auto_layout_) : auto_layout(auto_layout_) {} - AutoLayout& operator=(bool auto_layout_) { + AutoLayout& operator=(rerun::datatypes::Bool auto_layout_) { auto_layout = auto_layout_; return *this; } + + AutoLayout(bool value_) : auto_layout(value_) {} + + AutoLayout& operator=(bool value_) { + auto_layout = value_; + return *this; + } + + /// Cast to the underlying Bool datatype + operator rerun::datatypes::Bool() const { + return auto_layout; + } }; } // namespace rerun::blueprint::components namespace rerun { - template - struct Loggable; + static_assert(sizeof(rerun::datatypes::Bool) == sizeof(blueprint::components::AutoLayout)); /// \private template <> @@ -41,17 +47,18 @@ namespace rerun { static constexpr const char Name[] = "rerun.blueprint.components.AutoLayout"; /// Returns the arrow data type this type corresponds to. - static const std::shared_ptr& arrow_datatype(); + static const std::shared_ptr& arrow_datatype() { + return Loggable::arrow_datatype(); + } /// Serializes an array of `rerun::blueprint:: components::AutoLayout` into an arrow array. static Result> to_arrow( const blueprint::components::AutoLayout* instances, size_t num_instances - ); - - /// Fills an arrow array builder with an array of this type. - static rerun::Error fill_arrow_array_builder( - arrow::BooleanBuilder* builder, const blueprint::components::AutoLayout* elements, - size_t num_elements - ); + ) { + return Loggable::to_arrow( + &instances->auto_layout, + num_instances + ); + } }; } // namespace rerun diff --git a/rerun_cpp/src/rerun/blueprint/components/auto_space_views.cpp b/rerun_cpp/src/rerun/blueprint/components/auto_space_views.cpp deleted file mode 100644 index 1d051a09f99d..000000000000 --- a/rerun_cpp/src/rerun/blueprint/components/auto_space_views.cpp +++ /dev/null @@ -1,62 +0,0 @@ -// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/cpp/mod.rs -// Based on "crates/store/re_types/definitions/rerun/blueprint/components/auto_space_views.fbs". - -#include "auto_space_views.hpp" - -#include -#include - -namespace rerun::blueprint::components {} - -namespace rerun { - const std::shared_ptr& - Loggable::arrow_datatype() { - static const auto datatype = arrow::boolean(); - return datatype; - } - - Result> Loggable::to_arrow( - const blueprint::components::AutoSpaceViews* instances, size_t num_instances - ) { - // TODO(andreas): Allow configuring the memory pool. - arrow::MemoryPool* pool = arrow::default_memory_pool(); - auto datatype = arrow_datatype(); - - ARROW_ASSIGN_OR_RAISE(auto builder, arrow::MakeBuilder(datatype, pool)) - if (instances && num_instances > 0) { - RR_RETURN_NOT_OK( - Loggable::fill_arrow_array_builder( - static_cast(builder.get()), - instances, - num_instances - ) - ); - } - std::shared_ptr array; - ARROW_RETURN_NOT_OK(builder->Finish(&array)); - return array; - } - - rerun::Error Loggable::fill_arrow_array_builder( - arrow::BooleanBuilder* builder, const blueprint::components::AutoSpaceViews* elements, - size_t num_elements - ) { - if (builder == nullptr) { - return rerun::Error(ErrorCode::UnexpectedNullArgument, "Passed array builder is null."); - } - if (elements == nullptr) { - return rerun::Error( - ErrorCode::UnexpectedNullArgument, - "Cannot serialize null pointer to arrow array." - ); - } - - static_assert(sizeof(*elements) == sizeof(elements->auto_space_views)); - ARROW_RETURN_NOT_OK(builder->AppendValues( - reinterpret_cast(&elements->auto_space_views), - static_cast(num_elements) - )); - - return Error::ok(); - } -} // namespace rerun diff --git a/rerun_cpp/src/rerun/blueprint/components/auto_space_views.hpp b/rerun_cpp/src/rerun/blueprint/components/auto_space_views.hpp index 1e95c53496c7..4783a44579de 100644 --- a/rerun_cpp/src/rerun/blueprint/components/auto_space_views.hpp +++ b/rerun_cpp/src/rerun/blueprint/components/auto_space_views.hpp @@ -3,37 +3,44 @@ #pragma once +#include "../../datatypes/bool.hpp" #include "../../result.hpp" #include #include -namespace arrow { - class Array; - class BooleanBuilder; - class DataType; -} // namespace arrow - namespace rerun::blueprint::components { /// **Component**: Whether or not space views should be created automatically. struct AutoSpaceViews { - bool auto_space_views; + rerun::datatypes::Bool auto_space_views; public: AutoSpaceViews() = default; - AutoSpaceViews(bool auto_space_views_) : auto_space_views(auto_space_views_) {} + AutoSpaceViews(rerun::datatypes::Bool auto_space_views_) + : auto_space_views(auto_space_views_) {} - AutoSpaceViews& operator=(bool auto_space_views_) { + AutoSpaceViews& operator=(rerun::datatypes::Bool auto_space_views_) { auto_space_views = auto_space_views_; return *this; } + + AutoSpaceViews(bool value_) : auto_space_views(value_) {} + + AutoSpaceViews& operator=(bool value_) { + auto_space_views = value_; + return *this; + } + + /// Cast to the underlying Bool datatype + operator rerun::datatypes::Bool() const { + return auto_space_views; + } }; } // namespace rerun::blueprint::components namespace rerun { - template - struct Loggable; + static_assert(sizeof(rerun::datatypes::Bool) == sizeof(blueprint::components::AutoSpaceViews)); /// \private template <> @@ -41,17 +48,18 @@ namespace rerun { static constexpr const char Name[] = "rerun.blueprint.components.AutoSpaceViews"; /// Returns the arrow data type this type corresponds to. - static const std::shared_ptr& arrow_datatype(); + static const std::shared_ptr& arrow_datatype() { + return Loggable::arrow_datatype(); + } /// Serializes an array of `rerun::blueprint:: components::AutoSpaceViews` into an arrow array. static Result> to_arrow( const blueprint::components::AutoSpaceViews* instances, size_t num_instances - ); - - /// Fills an arrow array builder with an array of this type. - static rerun::Error fill_arrow_array_builder( - arrow::BooleanBuilder* builder, const blueprint::components::AutoSpaceViews* elements, - size_t num_elements - ); + ) { + return Loggable::to_arrow( + &instances->auto_space_views, + num_instances + ); + } }; } // namespace rerun diff --git a/rerun_cpp/src/rerun/blueprint/components/column_share.cpp b/rerun_cpp/src/rerun/blueprint/components/column_share.cpp deleted file mode 100644 index 8abc32361053..000000000000 --- a/rerun_cpp/src/rerun/blueprint/components/column_share.cpp +++ /dev/null @@ -1,59 +0,0 @@ -// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/cpp/mod.rs -// Based on "crates/store/re_types/definitions/rerun/blueprint/components/column_share.fbs". - -#include "column_share.hpp" - -#include -#include - -namespace rerun::blueprint::components {} - -namespace rerun { - const std::shared_ptr& - Loggable::arrow_datatype() { - static const auto datatype = arrow::float32(); - return datatype; - } - - Result> Loggable::to_arrow( - const blueprint::components::ColumnShare* instances, size_t num_instances - ) { - // TODO(andreas): Allow configuring the memory pool. - arrow::MemoryPool* pool = arrow::default_memory_pool(); - auto datatype = arrow_datatype(); - - ARROW_ASSIGN_OR_RAISE(auto builder, arrow::MakeBuilder(datatype, pool)) - if (instances && num_instances > 0) { - RR_RETURN_NOT_OK(Loggable::fill_arrow_array_builder( - static_cast(builder.get()), - instances, - num_instances - )); - } - std::shared_ptr array; - ARROW_RETURN_NOT_OK(builder->Finish(&array)); - return array; - } - - rerun::Error Loggable::fill_arrow_array_builder( - arrow::FloatBuilder* builder, const blueprint::components::ColumnShare* elements, - size_t num_elements - ) { - if (builder == nullptr) { - return rerun::Error(ErrorCode::UnexpectedNullArgument, "Passed array builder is null."); - } - if (elements == nullptr) { - return rerun::Error( - ErrorCode::UnexpectedNullArgument, - "Cannot serialize null pointer to arrow array." - ); - } - - static_assert(sizeof(*elements) == sizeof(elements->share)); - ARROW_RETURN_NOT_OK( - builder->AppendValues(&elements->share, static_cast(num_elements)) - ); - - return Error::ok(); - } -} // namespace rerun diff --git a/rerun_cpp/src/rerun/blueprint/components/column_share.hpp b/rerun_cpp/src/rerun/blueprint/components/column_share.hpp index e75da76398a7..6f88c69deb1b 100644 --- a/rerun_cpp/src/rerun/blueprint/components/column_share.hpp +++ b/rerun_cpp/src/rerun/blueprint/components/column_share.hpp @@ -3,43 +3,44 @@ #pragma once +#include "../../datatypes/float32.hpp" #include "../../result.hpp" #include #include -namespace arrow { - /// \private - template - class NumericBuilder; - - class Array; - class DataType; - class FloatType; - using FloatBuilder = NumericBuilder; -} // namespace arrow - namespace rerun::blueprint::components { /// **Component**: The layout share of a column in the container. struct ColumnShare { /// The layout shares of a column in the container. - float share; + rerun::datatypes::Float32 share; public: ColumnShare() = default; - ColumnShare(float share_) : share(share_) {} + ColumnShare(rerun::datatypes::Float32 share_) : share(share_) {} - ColumnShare& operator=(float share_) { + ColumnShare& operator=(rerun::datatypes::Float32 share_) { share = share_; return *this; } + + ColumnShare(float value_) : share(value_) {} + + ColumnShare& operator=(float value_) { + share = value_; + return *this; + } + + /// Cast to the underlying Float32 datatype + operator rerun::datatypes::Float32() const { + return share; + } }; } // namespace rerun::blueprint::components namespace rerun { - template - struct Loggable; + static_assert(sizeof(rerun::datatypes::Float32) == sizeof(blueprint::components::ColumnShare)); /// \private template <> @@ -47,17 +48,15 @@ namespace rerun { static constexpr const char Name[] = "rerun.blueprint.components.ColumnShare"; /// Returns the arrow data type this type corresponds to. - static const std::shared_ptr& arrow_datatype(); + static const std::shared_ptr& arrow_datatype() { + return Loggable::arrow_datatype(); + } /// Serializes an array of `rerun::blueprint:: components::ColumnShare` into an arrow array. static Result> to_arrow( const blueprint::components::ColumnShare* instances, size_t num_instances - ); - - /// Fills an arrow array builder with an array of this type. - static rerun::Error fill_arrow_array_builder( - arrow::FloatBuilder* builder, const blueprint::components::ColumnShare* elements, - size_t num_elements - ); + ) { + return Loggable::to_arrow(&instances->share, num_instances); + } }; } // namespace rerun diff --git a/rerun_cpp/src/rerun/blueprint/components/grid_columns.cpp b/rerun_cpp/src/rerun/blueprint/components/grid_columns.cpp deleted file mode 100644 index 47bb8857a2b3..000000000000 --- a/rerun_cpp/src/rerun/blueprint/components/grid_columns.cpp +++ /dev/null @@ -1,59 +0,0 @@ -// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/cpp/mod.rs -// Based on "crates/store/re_types/definitions/rerun/blueprint/components/grid_columns.fbs". - -#include "grid_columns.hpp" - -#include -#include - -namespace rerun::blueprint::components {} - -namespace rerun { - const std::shared_ptr& - Loggable::arrow_datatype() { - static const auto datatype = arrow::uint32(); - return datatype; - } - - Result> Loggable::to_arrow( - const blueprint::components::GridColumns* instances, size_t num_instances - ) { - // TODO(andreas): Allow configuring the memory pool. - arrow::MemoryPool* pool = arrow::default_memory_pool(); - auto datatype = arrow_datatype(); - - ARROW_ASSIGN_OR_RAISE(auto builder, arrow::MakeBuilder(datatype, pool)) - if (instances && num_instances > 0) { - RR_RETURN_NOT_OK(Loggable::fill_arrow_array_builder( - static_cast(builder.get()), - instances, - num_instances - )); - } - std::shared_ptr array; - ARROW_RETURN_NOT_OK(builder->Finish(&array)); - return array; - } - - rerun::Error Loggable::fill_arrow_array_builder( - arrow::UInt32Builder* builder, const blueprint::components::GridColumns* elements, - size_t num_elements - ) { - if (builder == nullptr) { - return rerun::Error(ErrorCode::UnexpectedNullArgument, "Passed array builder is null."); - } - if (elements == nullptr) { - return rerun::Error( - ErrorCode::UnexpectedNullArgument, - "Cannot serialize null pointer to arrow array." - ); - } - - static_assert(sizeof(*elements) == sizeof(elements->columns)); - ARROW_RETURN_NOT_OK( - builder->AppendValues(&elements->columns, static_cast(num_elements)) - ); - - return Error::ok(); - } -} // namespace rerun diff --git a/rerun_cpp/src/rerun/blueprint/components/grid_columns.hpp b/rerun_cpp/src/rerun/blueprint/components/grid_columns.hpp index 3f2dcd58ffc9..6f89d19ebdd2 100644 --- a/rerun_cpp/src/rerun/blueprint/components/grid_columns.hpp +++ b/rerun_cpp/src/rerun/blueprint/components/grid_columns.hpp @@ -3,43 +3,44 @@ #pragma once +#include "../../datatypes/uint32.hpp" #include "../../result.hpp" #include #include -namespace arrow { - /// \private - template - class NumericBuilder; - - class Array; - class DataType; - class UInt32Type; - using UInt32Builder = NumericBuilder; -} // namespace arrow - namespace rerun::blueprint::components { /// **Component**: How many columns a grid container should have. struct GridColumns { /// The number of columns. - uint32_t columns; + rerun::datatypes::UInt32 columns; public: GridColumns() = default; - GridColumns(uint32_t columns_) : columns(columns_) {} + GridColumns(rerun::datatypes::UInt32 columns_) : columns(columns_) {} - GridColumns& operator=(uint32_t columns_) { + GridColumns& operator=(rerun::datatypes::UInt32 columns_) { columns = columns_; return *this; } + + GridColumns(uint32_t value_) : columns(value_) {} + + GridColumns& operator=(uint32_t value_) { + columns = value_; + return *this; + } + + /// Cast to the underlying UInt32 datatype + operator rerun::datatypes::UInt32() const { + return columns; + } }; } // namespace rerun::blueprint::components namespace rerun { - template - struct Loggable; + static_assert(sizeof(rerun::datatypes::UInt32) == sizeof(blueprint::components::GridColumns)); /// \private template <> @@ -47,17 +48,15 @@ namespace rerun { static constexpr const char Name[] = "rerun.blueprint.components.GridColumns"; /// Returns the arrow data type this type corresponds to. - static const std::shared_ptr& arrow_datatype(); + static const std::shared_ptr& arrow_datatype() { + return Loggable::arrow_datatype(); + } /// Serializes an array of `rerun::blueprint:: components::GridColumns` into an arrow array. static Result> to_arrow( const blueprint::components::GridColumns* instances, size_t num_instances - ); - - /// Fills an arrow array builder with an array of this type. - static rerun::Error fill_arrow_array_builder( - arrow::UInt32Builder* builder, const blueprint::components::GridColumns* elements, - size_t num_elements - ); + ) { + return Loggable::to_arrow(&instances->columns, num_instances); + } }; } // namespace rerun diff --git a/rerun_cpp/src/rerun/blueprint/components/row_share.cpp b/rerun_cpp/src/rerun/blueprint/components/row_share.cpp deleted file mode 100644 index 93cdf3f1b4e4..000000000000 --- a/rerun_cpp/src/rerun/blueprint/components/row_share.cpp +++ /dev/null @@ -1,59 +0,0 @@ -// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/cpp/mod.rs -// Based on "crates/store/re_types/definitions/rerun/blueprint/components/row_share.fbs". - -#include "row_share.hpp" - -#include -#include - -namespace rerun::blueprint::components {} - -namespace rerun { - const std::shared_ptr& - Loggable::arrow_datatype() { - static const auto datatype = arrow::float32(); - return datatype; - } - - Result> Loggable::to_arrow( - const blueprint::components::RowShare* instances, size_t num_instances - ) { - // TODO(andreas): Allow configuring the memory pool. - arrow::MemoryPool* pool = arrow::default_memory_pool(); - auto datatype = arrow_datatype(); - - ARROW_ASSIGN_OR_RAISE(auto builder, arrow::MakeBuilder(datatype, pool)) - if (instances && num_instances > 0) { - RR_RETURN_NOT_OK(Loggable::fill_arrow_array_builder( - static_cast(builder.get()), - instances, - num_instances - )); - } - std::shared_ptr array; - ARROW_RETURN_NOT_OK(builder->Finish(&array)); - return array; - } - - rerun::Error Loggable::fill_arrow_array_builder( - arrow::FloatBuilder* builder, const blueprint::components::RowShare* elements, - size_t num_elements - ) { - if (builder == nullptr) { - return rerun::Error(ErrorCode::UnexpectedNullArgument, "Passed array builder is null."); - } - if (elements == nullptr) { - return rerun::Error( - ErrorCode::UnexpectedNullArgument, - "Cannot serialize null pointer to arrow array." - ); - } - - static_assert(sizeof(*elements) == sizeof(elements->share)); - ARROW_RETURN_NOT_OK( - builder->AppendValues(&elements->share, static_cast(num_elements)) - ); - - return Error::ok(); - } -} // namespace rerun diff --git a/rerun_cpp/src/rerun/blueprint/components/row_share.hpp b/rerun_cpp/src/rerun/blueprint/components/row_share.hpp index a2c43d3969b1..2ed34a35cdab 100644 --- a/rerun_cpp/src/rerun/blueprint/components/row_share.hpp +++ b/rerun_cpp/src/rerun/blueprint/components/row_share.hpp @@ -3,43 +3,44 @@ #pragma once +#include "../../datatypes/float32.hpp" #include "../../result.hpp" #include #include -namespace arrow { - /// \private - template - class NumericBuilder; - - class Array; - class DataType; - class FloatType; - using FloatBuilder = NumericBuilder; -} // namespace arrow - namespace rerun::blueprint::components { /// **Component**: The layout share of a row in the container. struct RowShare { /// The layout share of a row in the container. - float share; + rerun::datatypes::Float32 share; public: RowShare() = default; - RowShare(float share_) : share(share_) {} + RowShare(rerun::datatypes::Float32 share_) : share(share_) {} - RowShare& operator=(float share_) { + RowShare& operator=(rerun::datatypes::Float32 share_) { share = share_; return *this; } + + RowShare(float value_) : share(value_) {} + + RowShare& operator=(float value_) { + share = value_; + return *this; + } + + /// Cast to the underlying Float32 datatype + operator rerun::datatypes::Float32() const { + return share; + } }; } // namespace rerun::blueprint::components namespace rerun { - template - struct Loggable; + static_assert(sizeof(rerun::datatypes::Float32) == sizeof(blueprint::components::RowShare)); /// \private template <> @@ -47,17 +48,15 @@ namespace rerun { static constexpr const char Name[] = "rerun.blueprint.components.RowShare"; /// Returns the arrow data type this type corresponds to. - static const std::shared_ptr& arrow_datatype(); + static const std::shared_ptr& arrow_datatype() { + return Loggable::arrow_datatype(); + } /// Serializes an array of `rerun::blueprint:: components::RowShare` into an arrow array. static Result> to_arrow( const blueprint::components::RowShare* instances, size_t num_instances - ); - - /// Fills an arrow array builder with an array of this type. - static rerun::Error fill_arrow_array_builder( - arrow::FloatBuilder* builder, const blueprint::components::RowShare* elements, - size_t num_elements - ); + ) { + return Loggable::to_arrow(&instances->share, num_instances); + } }; } // namespace rerun diff --git a/rerun_cpp/src/rerun/blueprint/components/visible.cpp b/rerun_cpp/src/rerun/blueprint/components/visible.cpp deleted file mode 100644 index faf219386b28..000000000000 --- a/rerun_cpp/src/rerun/blueprint/components/visible.cpp +++ /dev/null @@ -1,60 +0,0 @@ -// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/cpp/mod.rs -// Based on "crates/store/re_types/definitions/rerun/blueprint/components/visible.fbs". - -#include "visible.hpp" - -#include -#include - -namespace rerun::blueprint::components {} - -namespace rerun { - const std::shared_ptr& - Loggable::arrow_datatype() { - static const auto datatype = arrow::boolean(); - return datatype; - } - - Result> Loggable::to_arrow( - const blueprint::components::Visible* instances, size_t num_instances - ) { - // TODO(andreas): Allow configuring the memory pool. - arrow::MemoryPool* pool = arrow::default_memory_pool(); - auto datatype = arrow_datatype(); - - ARROW_ASSIGN_OR_RAISE(auto builder, arrow::MakeBuilder(datatype, pool)) - if (instances && num_instances > 0) { - RR_RETURN_NOT_OK(Loggable::fill_arrow_array_builder( - static_cast(builder.get()), - instances, - num_instances - )); - } - std::shared_ptr array; - ARROW_RETURN_NOT_OK(builder->Finish(&array)); - return array; - } - - rerun::Error Loggable::fill_arrow_array_builder( - arrow::BooleanBuilder* builder, const blueprint::components::Visible* elements, - size_t num_elements - ) { - if (builder == nullptr) { - return rerun::Error(ErrorCode::UnexpectedNullArgument, "Passed array builder is null."); - } - if (elements == nullptr) { - return rerun::Error( - ErrorCode::UnexpectedNullArgument, - "Cannot serialize null pointer to arrow array." - ); - } - - static_assert(sizeof(*elements) == sizeof(elements->visible)); - ARROW_RETURN_NOT_OK(builder->AppendValues( - reinterpret_cast(&elements->visible), - static_cast(num_elements) - )); - - return Error::ok(); - } -} // namespace rerun diff --git a/rerun_cpp/src/rerun/blueprint/components/visible.hpp b/rerun_cpp/src/rerun/blueprint/components/visible.hpp index a9886934051e..5cfe80fddd7b 100644 --- a/rerun_cpp/src/rerun/blueprint/components/visible.hpp +++ b/rerun_cpp/src/rerun/blueprint/components/visible.hpp @@ -3,37 +3,43 @@ #pragma once +#include "../../datatypes/bool.hpp" #include "../../result.hpp" #include #include -namespace arrow { - class Array; - class BooleanBuilder; - class DataType; -} // namespace arrow - namespace rerun::blueprint::components { /// **Component**: Whether the container, view, entity or instance is currently visible. struct Visible { - bool visible; + rerun::datatypes::Bool visible; public: Visible() = default; - Visible(bool visible_) : visible(visible_) {} + Visible(rerun::datatypes::Bool visible_) : visible(visible_) {} - Visible& operator=(bool visible_) { + Visible& operator=(rerun::datatypes::Bool visible_) { visible = visible_; return *this; } + + Visible(bool value_) : visible(value_) {} + + Visible& operator=(bool value_) { + visible = value_; + return *this; + } + + /// Cast to the underlying Bool datatype + operator rerun::datatypes::Bool() const { + return visible; + } }; } // namespace rerun::blueprint::components namespace rerun { - template - struct Loggable; + static_assert(sizeof(rerun::datatypes::Bool) == sizeof(blueprint::components::Visible)); /// \private template <> @@ -41,17 +47,15 @@ namespace rerun { static constexpr const char Name[] = "rerun.blueprint.components.Visible"; /// Returns the arrow data type this type corresponds to. - static const std::shared_ptr& arrow_datatype(); + static const std::shared_ptr& arrow_datatype() { + return Loggable::arrow_datatype(); + } /// Serializes an array of `rerun::blueprint:: components::Visible` into an arrow array. static Result> to_arrow( const blueprint::components::Visible* instances, size_t num_instances - ); - - /// Fills an arrow array builder with an array of this type. - static rerun::Error fill_arrow_array_builder( - arrow::BooleanBuilder* builder, const blueprint::components::Visible* elements, - size_t num_elements - ); + ) { + return Loggable::to_arrow(&instances->visible, num_instances); + } }; } // namespace rerun diff --git a/rerun_cpp/src/rerun/blueprint/components/visualizer_overrides.hpp b/rerun_cpp/src/rerun/blueprint/components/visualizer_overrides.hpp index fda228935232..353bed2a627b 100644 --- a/rerun_cpp/src/rerun/blueprint/components/visualizer_overrides.hpp +++ b/rerun_cpp/src/rerun/blueprint/components/visualizer_overrides.hpp @@ -3,6 +3,7 @@ #pragma once +#include "../../blueprint/datatypes/utf8list.hpp" #include "../../collection.hpp" #include "../../result.hpp" @@ -11,12 +12,6 @@ #include #include -namespace arrow { - class Array; - class DataType; - class ListBuilder; -} // namespace arrow - namespace rerun::blueprint::components { /// **Component**: Override the visualizers for an entity. /// @@ -53,24 +48,39 @@ namespace rerun::blueprint::components { /// - SegmentationImage /// - SeriesLine /// - SeriesPoint - rerun::Collection visualizers; + rerun::blueprint::datatypes::Utf8List visualizers; public: VisualizerOverrides() = default; - VisualizerOverrides(rerun::Collection visualizers_) + VisualizerOverrides(rerun::blueprint::datatypes::Utf8List visualizers_) : visualizers(std::move(visualizers_)) {} - VisualizerOverrides& operator=(rerun::Collection visualizers_) { + VisualizerOverrides& operator=(rerun::blueprint::datatypes::Utf8List visualizers_) { visualizers = std::move(visualizers_); return *this; } + + VisualizerOverrides(rerun::Collection value_) + : visualizers(std::move(value_)) {} + + VisualizerOverrides& operator=(rerun::Collection value_) { + visualizers = std::move(value_); + return *this; + } + + /// Cast to the underlying Utf8List datatype + operator rerun::blueprint::datatypes::Utf8List() const { + return visualizers; + } }; } // namespace rerun::blueprint::components namespace rerun { - template - struct Loggable; + static_assert( + sizeof(rerun::blueprint::datatypes::Utf8List) == + sizeof(blueprint::components::VisualizerOverrides) + ); /// \private template <> @@ -78,17 +88,18 @@ namespace rerun { static constexpr const char Name[] = "rerun.blueprint.components.VisualizerOverrides"; /// Returns the arrow data type this type corresponds to. - static const std::shared_ptr& arrow_datatype(); + static const std::shared_ptr& arrow_datatype() { + return Loggable::arrow_datatype(); + } /// Serializes an array of `rerun::blueprint:: components::VisualizerOverrides` into an arrow array. static Result> to_arrow( const blueprint::components::VisualizerOverrides* instances, size_t num_instances - ); - - /// Fills an arrow array builder with an array of this type. - static rerun::Error fill_arrow_array_builder( - arrow::ListBuilder* builder, const blueprint::components::VisualizerOverrides* elements, - size_t num_elements - ); + ) { + return Loggable::to_arrow( + &instances->visualizers, + num_instances + ); + } }; } // namespace rerun diff --git a/rerun_cpp/src/rerun/blueprint/datatypes.hpp b/rerun_cpp/src/rerun/blueprint/datatypes.hpp index 322adb232a90..429e06dea010 100644 --- a/rerun_cpp/src/rerun/blueprint/datatypes.hpp +++ b/rerun_cpp/src/rerun/blueprint/datatypes.hpp @@ -3,3 +3,4 @@ #pragma once #include "blueprint/datatypes/tensor_dimension_index_slider.hpp" +#include "blueprint/datatypes/utf8list.hpp" diff --git a/rerun_cpp/src/rerun/blueprint/datatypes/.gitattributes b/rerun_cpp/src/rerun/blueprint/datatypes/.gitattributes index 6b00a9a08be3..914f011d695c 100644 --- a/rerun_cpp/src/rerun/blueprint/datatypes/.gitattributes +++ b/rerun_cpp/src/rerun/blueprint/datatypes/.gitattributes @@ -3,3 +3,5 @@ .gitattributes linguist-generated=true tensor_dimension_index_slider.cpp linguist-generated=true tensor_dimension_index_slider.hpp linguist-generated=true +utf8list.cpp linguist-generated=true +utf8list.hpp linguist-generated=true diff --git a/rerun_cpp/src/rerun/blueprint/components/visualizer_overrides.cpp b/rerun_cpp/src/rerun/blueprint/datatypes/utf8list.cpp similarity index 61% rename from rerun_cpp/src/rerun/blueprint/components/visualizer_overrides.cpp rename to rerun_cpp/src/rerun/blueprint/datatypes/utf8list.cpp index 712997019185..aaf95b3bd3b2 100644 --- a/rerun_cpp/src/rerun/blueprint/components/visualizer_overrides.cpp +++ b/rerun_cpp/src/rerun/blueprint/datatypes/utf8list.cpp @@ -1,45 +1,42 @@ // DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/cpp/mod.rs -// Based on "crates/store/re_types/definitions/rerun/blueprint/components/visualizer_overrides.fbs". +// Based on "crates/store/re_types/definitions/rerun/blueprint/datatypes/utf8_list.fbs". -#include "visualizer_overrides.hpp" +#include "utf8list.hpp" #include #include -namespace rerun::blueprint::components {} +namespace rerun::blueprint::datatypes {} namespace rerun { const std::shared_ptr& - Loggable::arrow_datatype() { + Loggable::arrow_datatype() { static const auto datatype = arrow::list(arrow::field("item", arrow::utf8(), false)); return datatype; } - Result> - Loggable::to_arrow( - const blueprint::components::VisualizerOverrides* instances, size_t num_instances - ) { + Result> Loggable::to_arrow( + const blueprint::datatypes::Utf8List* instances, size_t num_instances + ) { // TODO(andreas): Allow configuring the memory pool. arrow::MemoryPool* pool = arrow::default_memory_pool(); auto datatype = arrow_datatype(); ARROW_ASSIGN_OR_RAISE(auto builder, arrow::MakeBuilder(datatype, pool)) if (instances && num_instances > 0) { - RR_RETURN_NOT_OK( - Loggable::fill_arrow_array_builder( - static_cast(builder.get()), - instances, - num_instances - ) - ); + RR_RETURN_NOT_OK(Loggable::fill_arrow_array_builder( + static_cast(builder.get()), + instances, + num_instances + )); } std::shared_ptr array; ARROW_RETURN_NOT_OK(builder->Finish(&array)); return array; } - rerun::Error Loggable::fill_arrow_array_builder( - arrow::ListBuilder* builder, const blueprint::components::VisualizerOverrides* elements, + rerun::Error Loggable::fill_arrow_array_builder( + arrow::ListBuilder* builder, const blueprint::datatypes::Utf8List* elements, size_t num_elements ) { if (builder == nullptr) { @@ -59,8 +56,8 @@ namespace rerun { for (size_t elem_idx = 0; elem_idx < num_elements; elem_idx += 1) { const auto& element = elements[elem_idx]; ARROW_RETURN_NOT_OK(builder->Append()); - for (size_t item_idx = 0; item_idx < element.visualizers.size(); item_idx += 1) { - ARROW_RETURN_NOT_OK(value_builder->Append(element.visualizers[item_idx])); + for (size_t item_idx = 0; item_idx < element.value.size(); item_idx += 1) { + ARROW_RETURN_NOT_OK(value_builder->Append(element.value[item_idx])); } } diff --git a/rerun_cpp/src/rerun/blueprint/datatypes/utf8list.hpp b/rerun_cpp/src/rerun/blueprint/datatypes/utf8list.hpp new file mode 100644 index 000000000000..c9749bb7b92b --- /dev/null +++ b/rerun_cpp/src/rerun/blueprint/datatypes/utf8list.hpp @@ -0,0 +1,60 @@ +// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/cpp/mod.rs +// Based on "crates/store/re_types/definitions/rerun/blueprint/datatypes/utf8_list.fbs". + +#pragma once + +#include "../../collection.hpp" +#include "../../result.hpp" + +#include +#include +#include +#include + +namespace arrow { + class Array; + class DataType; + class ListBuilder; +} // namespace arrow + +namespace rerun::blueprint::datatypes { + /// **Datatype**: A list of strings of text, encoded as UTF-8. + struct Utf8List { + rerun::Collection value; + + public: + Utf8List() = default; + + Utf8List(rerun::Collection value_) : value(std::move(value_)) {} + + Utf8List& operator=(rerun::Collection value_) { + value = std::move(value_); + return *this; + } + }; +} // namespace rerun::blueprint::datatypes + +namespace rerun { + template + struct Loggable; + + /// \private + template <> + struct Loggable { + static constexpr const char Name[] = "rerun.blueprint.datatypes.Utf8List"; + + /// Returns the arrow data type this type corresponds to. + static const std::shared_ptr& arrow_datatype(); + + /// Serializes an array of `rerun::blueprint:: datatypes::Utf8List` into an arrow array. + static Result> to_arrow( + const blueprint::datatypes::Utf8List* instances, size_t num_instances + ); + + /// Fills an arrow array builder with an array of this type. + static rerun::Error fill_arrow_array_builder( + arrow::ListBuilder* builder, const blueprint::datatypes::Utf8List* elements, + size_t num_elements + ); + }; +} // namespace rerun diff --git a/rerun_cpp/src/rerun/components/.gitattributes b/rerun_cpp/src/rerun/components/.gitattributes index 86cdb7e361ec..a2bd42936be1 100644 --- a/rerun_cpp/src/rerun/components/.gitattributes +++ b/rerun_cpp/src/rerun/components/.gitattributes @@ -6,19 +6,14 @@ aggregation_policy.hpp linguist-generated=true annotation_context.cpp linguist-generated=true annotation_context.hpp linguist-generated=true axis_length.hpp linguist-generated=true -blob.cpp linguist-generated=true blob.hpp linguist-generated=true class_id.hpp linguist-generated=true -clear_is_recursive.cpp linguist-generated=true clear_is_recursive.hpp linguist-generated=true color.hpp linguist-generated=true colormap.cpp linguist-generated=true colormap.hpp linguist-generated=true -depth_meter.cpp linguist-generated=true depth_meter.hpp linguist-generated=true -disconnected_space.cpp linguist-generated=true disconnected_space.hpp linguist-generated=true -draw_order.cpp linguist-generated=true draw_order.hpp linguist-generated=true fill_ratio.hpp linguist-generated=true gamma_correction.hpp linguist-generated=true @@ -34,7 +29,6 @@ magnification_filter.cpp linguist-generated=true magnification_filter.hpp linguist-generated=true marker_shape.cpp linguist-generated=true marker_shape.hpp linguist-generated=true -marker_size.cpp linguist-generated=true marker_size.hpp linguist-generated=true material.hpp linguist-generated=true media_type.hpp linguist-generated=true @@ -44,14 +38,11 @@ out_of_tree_transform3d.hpp linguist-generated=true pinhole_projection.hpp linguist-generated=true position2d.hpp linguist-generated=true position3d.hpp linguist-generated=true -radius.cpp linguist-generated=true radius.hpp linguist-generated=true range1d.hpp linguist-generated=true resolution.hpp linguist-generated=true rotation3d.hpp linguist-generated=true -scalar.cpp linguist-generated=true scalar.hpp linguist-generated=true -stroke_width.cpp linguist-generated=true stroke_width.hpp linguist-generated=true tensor_data.hpp linguist-generated=true tensor_dimension_index_selection.hpp linguist-generated=true @@ -64,5 +55,4 @@ transform3d.hpp linguist-generated=true triangle_indices.hpp linguist-generated=true vector2d.hpp linguist-generated=true vector3d.hpp linguist-generated=true -view_coordinates.cpp linguist-generated=true view_coordinates.hpp linguist-generated=true diff --git a/rerun_cpp/src/rerun/components/blob.hpp b/rerun_cpp/src/rerun/components/blob.hpp index 8c3337be1eb2..a662aee8a405 100644 --- a/rerun_cpp/src/rerun/components/blob.hpp +++ b/rerun_cpp/src/rerun/components/blob.hpp @@ -4,38 +4,44 @@ #pragma once #include "../collection.hpp" +#include "../datatypes/blob.hpp" #include "../result.hpp" #include #include #include -namespace arrow { - class Array; - class DataType; - class ListBuilder; -} // namespace arrow - namespace rerun::components { /// **Component**: A binary blob of data. struct Blob { - rerun::Collection data; + rerun::datatypes::Blob data; public: Blob() = default; + Blob(rerun::datatypes::Blob data_) : data(std::move(data_)) {} + + Blob& operator=(rerun::datatypes::Blob data_) { + data = std::move(data_); + return *this; + } + Blob(rerun::Collection data_) : data(std::move(data_)) {} Blob& operator=(rerun::Collection data_) { data = std::move(data_); return *this; } + + /// Cast to the underlying Blob datatype + operator rerun::datatypes::Blob() const { + return data; + } }; } // namespace rerun::components namespace rerun { - template - struct Loggable; + static_assert(sizeof(rerun::datatypes::Blob) == sizeof(components::Blob)); /// \private template <> @@ -43,16 +49,15 @@ namespace rerun { static constexpr const char Name[] = "rerun.components.Blob"; /// Returns the arrow data type this type corresponds to. - static const std::shared_ptr& arrow_datatype(); + static const std::shared_ptr& arrow_datatype() { + return Loggable::arrow_datatype(); + } /// Serializes an array of `rerun::components::Blob` into an arrow array. static Result> to_arrow( const components::Blob* instances, size_t num_instances - ); - - /// Fills an arrow array builder with an array of this type. - static rerun::Error fill_arrow_array_builder( - arrow::ListBuilder* builder, const components::Blob* elements, size_t num_elements - ); + ) { + return Loggable::to_arrow(&instances->data, num_instances); + } }; } // namespace rerun diff --git a/rerun_cpp/src/rerun/components/clear_is_recursive.cpp b/rerun_cpp/src/rerun/components/clear_is_recursive.cpp deleted file mode 100644 index 97f1354990a7..000000000000 --- a/rerun_cpp/src/rerun/components/clear_is_recursive.cpp +++ /dev/null @@ -1,60 +0,0 @@ -// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/cpp/mod.rs -// Based on "crates/store/re_types/definitions/rerun/components/clear_is_recursive.fbs". - -#include "clear_is_recursive.hpp" - -#include -#include - -namespace rerun::components {} - -namespace rerun { - const std::shared_ptr& Loggable::arrow_datatype( - ) { - static const auto datatype = arrow::boolean(); - return datatype; - } - - Result> Loggable::to_arrow( - const components::ClearIsRecursive* instances, size_t num_instances - ) { - // TODO(andreas): Allow configuring the memory pool. - arrow::MemoryPool* pool = arrow::default_memory_pool(); - auto datatype = arrow_datatype(); - - ARROW_ASSIGN_OR_RAISE(auto builder, arrow::MakeBuilder(datatype, pool)) - if (instances && num_instances > 0) { - RR_RETURN_NOT_OK(Loggable::fill_arrow_array_builder( - static_cast(builder.get()), - instances, - num_instances - )); - } - std::shared_ptr array; - ARROW_RETURN_NOT_OK(builder->Finish(&array)); - return array; - } - - rerun::Error Loggable::fill_arrow_array_builder( - arrow::BooleanBuilder* builder, const components::ClearIsRecursive* elements, - size_t num_elements - ) { - if (builder == nullptr) { - return rerun::Error(ErrorCode::UnexpectedNullArgument, "Passed array builder is null."); - } - if (elements == nullptr) { - return rerun::Error( - ErrorCode::UnexpectedNullArgument, - "Cannot serialize null pointer to arrow array." - ); - } - - static_assert(sizeof(*elements) == sizeof(elements->recursive)); - ARROW_RETURN_NOT_OK(builder->AppendValues( - reinterpret_cast(&elements->recursive), - static_cast(num_elements) - )); - - return Error::ok(); - } -} // namespace rerun diff --git a/rerun_cpp/src/rerun/components/clear_is_recursive.hpp b/rerun_cpp/src/rerun/components/clear_is_recursive.hpp index f6f81054a180..9eadea654ea7 100644 --- a/rerun_cpp/src/rerun/components/clear_is_recursive.hpp +++ b/rerun_cpp/src/rerun/components/clear_is_recursive.hpp @@ -3,38 +3,44 @@ #pragma once +#include "../datatypes/bool.hpp" #include "../result.hpp" #include #include -namespace arrow { - class Array; - class BooleanBuilder; - class DataType; -} // namespace arrow - namespace rerun::components { /// **Component**: Configures how a clear operation should behave - recursive or not. struct ClearIsRecursive { /// If true, also clears all recursive children entities. - bool recursive; + rerun::datatypes::Bool recursive; public: ClearIsRecursive() = default; - ClearIsRecursive(bool recursive_) : recursive(recursive_) {} + ClearIsRecursive(rerun::datatypes::Bool recursive_) : recursive(recursive_) {} - ClearIsRecursive& operator=(bool recursive_) { + ClearIsRecursive& operator=(rerun::datatypes::Bool recursive_) { recursive = recursive_; return *this; } + + ClearIsRecursive(bool value_) : recursive(value_) {} + + ClearIsRecursive& operator=(bool value_) { + recursive = value_; + return *this; + } + + /// Cast to the underlying Bool datatype + operator rerun::datatypes::Bool() const { + return recursive; + } }; } // namespace rerun::components namespace rerun { - template - struct Loggable; + static_assert(sizeof(rerun::datatypes::Bool) == sizeof(components::ClearIsRecursive)); /// \private template <> @@ -42,17 +48,15 @@ namespace rerun { static constexpr const char Name[] = "rerun.components.ClearIsRecursive"; /// Returns the arrow data type this type corresponds to. - static const std::shared_ptr& arrow_datatype(); + static const std::shared_ptr& arrow_datatype() { + return Loggable::arrow_datatype(); + } /// Serializes an array of `rerun::components::ClearIsRecursive` into an arrow array. static Result> to_arrow( const components::ClearIsRecursive* instances, size_t num_instances - ); - - /// Fills an arrow array builder with an array of this type. - static rerun::Error fill_arrow_array_builder( - arrow::BooleanBuilder* builder, const components::ClearIsRecursive* elements, - size_t num_elements - ); + ) { + return Loggable::to_arrow(&instances->recursive, num_instances); + } }; } // namespace rerun diff --git a/rerun_cpp/src/rerun/components/depth_meter.cpp b/rerun_cpp/src/rerun/components/depth_meter.cpp deleted file mode 100644 index 3b791a751dc0..000000000000 --- a/rerun_cpp/src/rerun/components/depth_meter.cpp +++ /dev/null @@ -1,57 +0,0 @@ -// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/cpp/mod.rs -// Based on "crates/store/re_types/definitions/rerun/components/depth_meter.fbs". - -#include "depth_meter.hpp" - -#include -#include - -namespace rerun::components {} - -namespace rerun { - const std::shared_ptr& Loggable::arrow_datatype() { - static const auto datatype = arrow::float32(); - return datatype; - } - - Result> Loggable::to_arrow( - const components::DepthMeter* instances, size_t num_instances - ) { - // TODO(andreas): Allow configuring the memory pool. - arrow::MemoryPool* pool = arrow::default_memory_pool(); - auto datatype = arrow_datatype(); - - ARROW_ASSIGN_OR_RAISE(auto builder, arrow::MakeBuilder(datatype, pool)) - if (instances && num_instances > 0) { - RR_RETURN_NOT_OK(Loggable::fill_arrow_array_builder( - static_cast(builder.get()), - instances, - num_instances - )); - } - std::shared_ptr array; - ARROW_RETURN_NOT_OK(builder->Finish(&array)); - return array; - } - - rerun::Error Loggable::fill_arrow_array_builder( - arrow::FloatBuilder* builder, const components::DepthMeter* elements, size_t num_elements - ) { - if (builder == nullptr) { - return rerun::Error(ErrorCode::UnexpectedNullArgument, "Passed array builder is null."); - } - if (elements == nullptr) { - return rerun::Error( - ErrorCode::UnexpectedNullArgument, - "Cannot serialize null pointer to arrow array." - ); - } - - static_assert(sizeof(*elements) == sizeof(elements->value)); - ARROW_RETURN_NOT_OK( - builder->AppendValues(&elements->value, static_cast(num_elements)) - ); - - return Error::ok(); - } -} // namespace rerun diff --git a/rerun_cpp/src/rerun/components/depth_meter.hpp b/rerun_cpp/src/rerun/components/depth_meter.hpp index 27970a36187b..3e4a95a00f3a 100644 --- a/rerun_cpp/src/rerun/components/depth_meter.hpp +++ b/rerun_cpp/src/rerun/components/depth_meter.hpp @@ -3,22 +3,12 @@ #pragma once +#include "../datatypes/float32.hpp" #include "../result.hpp" #include #include -namespace arrow { - /// \private - template - class NumericBuilder; - - class Array; - class DataType; - class FloatType; - using FloatBuilder = NumericBuilder; -} // namespace arrow - namespace rerun::components { /// **Component**: The world->depth map scaling factor. /// @@ -29,23 +19,34 @@ namespace rerun::components { /// Note that the only effect on 2D views is the physical depth values shown when hovering the image. /// In 3D views on the other hand, this affects where the points of the point cloud are placed. struct DepthMeter { - float value; + rerun::datatypes::Float32 value; public: DepthMeter() = default; + DepthMeter(rerun::datatypes::Float32 value_) : value(value_) {} + + DepthMeter& operator=(rerun::datatypes::Float32 value_) { + value = value_; + return *this; + } + DepthMeter(float value_) : value(value_) {} DepthMeter& operator=(float value_) { value = value_; return *this; } + + /// Cast to the underlying Float32 datatype + operator rerun::datatypes::Float32() const { + return value; + } }; } // namespace rerun::components namespace rerun { - template - struct Loggable; + static_assert(sizeof(rerun::datatypes::Float32) == sizeof(components::DepthMeter)); /// \private template <> @@ -53,17 +54,15 @@ namespace rerun { static constexpr const char Name[] = "rerun.components.DepthMeter"; /// Returns the arrow data type this type corresponds to. - static const std::shared_ptr& arrow_datatype(); + static const std::shared_ptr& arrow_datatype() { + return Loggable::arrow_datatype(); + } /// Serializes an array of `rerun::components::DepthMeter` into an arrow array. static Result> to_arrow( const components::DepthMeter* instances, size_t num_instances - ); - - /// Fills an arrow array builder with an array of this type. - static rerun::Error fill_arrow_array_builder( - arrow::FloatBuilder* builder, const components::DepthMeter* elements, - size_t num_elements - ); + ) { + return Loggable::to_arrow(&instances->value, num_instances); + } }; } // namespace rerun diff --git a/rerun_cpp/src/rerun/components/disconnected_space.cpp b/rerun_cpp/src/rerun/components/disconnected_space.cpp deleted file mode 100644 index 7c20d74b8478..000000000000 --- a/rerun_cpp/src/rerun/components/disconnected_space.cpp +++ /dev/null @@ -1,60 +0,0 @@ -// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/cpp/mod.rs -// Based on "crates/store/re_types/definitions/rerun/components/disconnected_space.fbs". - -#include "disconnected_space.hpp" - -#include -#include - -namespace rerun::components {} - -namespace rerun { - const std::shared_ptr& Loggable::arrow_datatype( - ) { - static const auto datatype = arrow::boolean(); - return datatype; - } - - Result> Loggable::to_arrow( - const components::DisconnectedSpace* instances, size_t num_instances - ) { - // TODO(andreas): Allow configuring the memory pool. - arrow::MemoryPool* pool = arrow::default_memory_pool(); - auto datatype = arrow_datatype(); - - ARROW_ASSIGN_OR_RAISE(auto builder, arrow::MakeBuilder(datatype, pool)) - if (instances && num_instances > 0) { - RR_RETURN_NOT_OK(Loggable::fill_arrow_array_builder( - static_cast(builder.get()), - instances, - num_instances - )); - } - std::shared_ptr array; - ARROW_RETURN_NOT_OK(builder->Finish(&array)); - return array; - } - - rerun::Error Loggable::fill_arrow_array_builder( - arrow::BooleanBuilder* builder, const components::DisconnectedSpace* elements, - size_t num_elements - ) { - if (builder == nullptr) { - return rerun::Error(ErrorCode::UnexpectedNullArgument, "Passed array builder is null."); - } - if (elements == nullptr) { - return rerun::Error( - ErrorCode::UnexpectedNullArgument, - "Cannot serialize null pointer to arrow array." - ); - } - - static_assert(sizeof(*elements) == sizeof(elements->is_disconnected)); - ARROW_RETURN_NOT_OK(builder->AppendValues( - reinterpret_cast(&elements->is_disconnected), - static_cast(num_elements) - )); - - return Error::ok(); - } -} // namespace rerun diff --git a/rerun_cpp/src/rerun/components/disconnected_space.hpp b/rerun_cpp/src/rerun/components/disconnected_space.hpp index c3b93cc354f5..aa1ecf2dbf81 100644 --- a/rerun_cpp/src/rerun/components/disconnected_space.hpp +++ b/rerun_cpp/src/rerun/components/disconnected_space.hpp @@ -3,17 +3,12 @@ #pragma once +#include "../datatypes/bool.hpp" #include "../result.hpp" #include #include -namespace arrow { - class Array; - class BooleanBuilder; - class DataType; -} // namespace arrow - namespace rerun::components { /// **Component**: Spatially disconnect this entity from its parent. /// @@ -26,23 +21,35 @@ namespace rerun::components { /// /// Set to true to disconnect the entity from its parent. /// Set to false to disable the effects of this component, (re-)connecting the entity to its parent again. - bool is_disconnected; + rerun::datatypes::Bool is_disconnected; public: DisconnectedSpace() = default; - DisconnectedSpace(bool is_disconnected_) : is_disconnected(is_disconnected_) {} + DisconnectedSpace(rerun::datatypes::Bool is_disconnected_) + : is_disconnected(is_disconnected_) {} - DisconnectedSpace& operator=(bool is_disconnected_) { + DisconnectedSpace& operator=(rerun::datatypes::Bool is_disconnected_) { is_disconnected = is_disconnected_; return *this; } + + DisconnectedSpace(bool value_) : is_disconnected(value_) {} + + DisconnectedSpace& operator=(bool value_) { + is_disconnected = value_; + return *this; + } + + /// Cast to the underlying Bool datatype + operator rerun::datatypes::Bool() const { + return is_disconnected; + } }; } // namespace rerun::components namespace rerun { - template - struct Loggable; + static_assert(sizeof(rerun::datatypes::Bool) == sizeof(components::DisconnectedSpace)); /// \private template <> @@ -50,17 +57,18 @@ namespace rerun { static constexpr const char Name[] = "rerun.components.DisconnectedSpace"; /// Returns the arrow data type this type corresponds to. - static const std::shared_ptr& arrow_datatype(); + static const std::shared_ptr& arrow_datatype() { + return Loggable::arrow_datatype(); + } /// Serializes an array of `rerun::components::DisconnectedSpace` into an arrow array. static Result> to_arrow( const components::DisconnectedSpace* instances, size_t num_instances - ); - - /// Fills an arrow array builder with an array of this type. - static rerun::Error fill_arrow_array_builder( - arrow::BooleanBuilder* builder, const components::DisconnectedSpace* elements, - size_t num_elements - ); + ) { + return Loggable::to_arrow( + &instances->is_disconnected, + num_instances + ); + } }; } // namespace rerun diff --git a/rerun_cpp/src/rerun/components/draw_order.cpp b/rerun_cpp/src/rerun/components/draw_order.cpp deleted file mode 100644 index e0778f987594..000000000000 --- a/rerun_cpp/src/rerun/components/draw_order.cpp +++ /dev/null @@ -1,57 +0,0 @@ -// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/cpp/mod.rs -// Based on "crates/store/re_types/definitions/rerun/components/draw_order.fbs". - -#include "draw_order.hpp" - -#include -#include - -namespace rerun::components {} - -namespace rerun { - const std::shared_ptr& Loggable::arrow_datatype() { - static const auto datatype = arrow::float32(); - return datatype; - } - - Result> Loggable::to_arrow( - const components::DrawOrder* instances, size_t num_instances - ) { - // TODO(andreas): Allow configuring the memory pool. - arrow::MemoryPool* pool = arrow::default_memory_pool(); - auto datatype = arrow_datatype(); - - ARROW_ASSIGN_OR_RAISE(auto builder, arrow::MakeBuilder(datatype, pool)) - if (instances && num_instances > 0) { - RR_RETURN_NOT_OK(Loggable::fill_arrow_array_builder( - static_cast(builder.get()), - instances, - num_instances - )); - } - std::shared_ptr array; - ARROW_RETURN_NOT_OK(builder->Finish(&array)); - return array; - } - - rerun::Error Loggable::fill_arrow_array_builder( - arrow::FloatBuilder* builder, const components::DrawOrder* elements, size_t num_elements - ) { - if (builder == nullptr) { - return rerun::Error(ErrorCode::UnexpectedNullArgument, "Passed array builder is null."); - } - if (elements == nullptr) { - return rerun::Error( - ErrorCode::UnexpectedNullArgument, - "Cannot serialize null pointer to arrow array." - ); - } - - static_assert(sizeof(*elements) == sizeof(elements->value)); - ARROW_RETURN_NOT_OK( - builder->AppendValues(&elements->value, static_cast(num_elements)) - ); - - return Error::ok(); - } -} // namespace rerun diff --git a/rerun_cpp/src/rerun/components/draw_order.hpp b/rerun_cpp/src/rerun/components/draw_order.hpp index d04aabf65a0c..558ca8250d86 100644 --- a/rerun_cpp/src/rerun/components/draw_order.hpp +++ b/rerun_cpp/src/rerun/components/draw_order.hpp @@ -3,22 +3,12 @@ #pragma once +#include "../datatypes/float32.hpp" #include "../result.hpp" #include #include -namespace arrow { - /// \private - template - class NumericBuilder; - - class Array; - class DataType; - class FloatType; - using FloatBuilder = NumericBuilder; -} // namespace arrow - namespace rerun::components { /// **Component**: Draw order of 2D elements. Higher values are drawn on top of lower values. /// @@ -27,23 +17,34 @@ namespace rerun::components { /// /// Draw order for entities with the same draw order is generally undefined. struct DrawOrder { - float value; + rerun::datatypes::Float32 value; public: DrawOrder() = default; + DrawOrder(rerun::datatypes::Float32 value_) : value(value_) {} + + DrawOrder& operator=(rerun::datatypes::Float32 value_) { + value = value_; + return *this; + } + DrawOrder(float value_) : value(value_) {} DrawOrder& operator=(float value_) { value = value_; return *this; } + + /// Cast to the underlying Float32 datatype + operator rerun::datatypes::Float32() const { + return value; + } }; } // namespace rerun::components namespace rerun { - template - struct Loggable; + static_assert(sizeof(rerun::datatypes::Float32) == sizeof(components::DrawOrder)); /// \private template <> @@ -51,16 +52,15 @@ namespace rerun { static constexpr const char Name[] = "rerun.components.DrawOrder"; /// Returns the arrow data type this type corresponds to. - static const std::shared_ptr& arrow_datatype(); + static const std::shared_ptr& arrow_datatype() { + return Loggable::arrow_datatype(); + } /// Serializes an array of `rerun::components::DrawOrder` into an arrow array. static Result> to_arrow( const components::DrawOrder* instances, size_t num_instances - ); - - /// Fills an arrow array builder with an array of this type. - static rerun::Error fill_arrow_array_builder( - arrow::FloatBuilder* builder, const components::DrawOrder* elements, size_t num_elements - ); + ) { + return Loggable::to_arrow(&instances->value, num_instances); + } }; } // namespace rerun diff --git a/rerun_cpp/src/rerun/components/marker_size.cpp b/rerun_cpp/src/rerun/components/marker_size.cpp deleted file mode 100644 index 9bcd08431b6f..000000000000 --- a/rerun_cpp/src/rerun/components/marker_size.cpp +++ /dev/null @@ -1,57 +0,0 @@ -// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/cpp/mod.rs -// Based on "crates/store/re_types/definitions/rerun/components/marker_size.fbs". - -#include "marker_size.hpp" - -#include -#include - -namespace rerun::components {} - -namespace rerun { - const std::shared_ptr& Loggable::arrow_datatype() { - static const auto datatype = arrow::float32(); - return datatype; - } - - Result> Loggable::to_arrow( - const components::MarkerSize* instances, size_t num_instances - ) { - // TODO(andreas): Allow configuring the memory pool. - arrow::MemoryPool* pool = arrow::default_memory_pool(); - auto datatype = arrow_datatype(); - - ARROW_ASSIGN_OR_RAISE(auto builder, arrow::MakeBuilder(datatype, pool)) - if (instances && num_instances > 0) { - RR_RETURN_NOT_OK(Loggable::fill_arrow_array_builder( - static_cast(builder.get()), - instances, - num_instances - )); - } - std::shared_ptr array; - ARROW_RETURN_NOT_OK(builder->Finish(&array)); - return array; - } - - rerun::Error Loggable::fill_arrow_array_builder( - arrow::FloatBuilder* builder, const components::MarkerSize* elements, size_t num_elements - ) { - if (builder == nullptr) { - return rerun::Error(ErrorCode::UnexpectedNullArgument, "Passed array builder is null."); - } - if (elements == nullptr) { - return rerun::Error( - ErrorCode::UnexpectedNullArgument, - "Cannot serialize null pointer to arrow array." - ); - } - - static_assert(sizeof(*elements) == sizeof(elements->value)); - ARROW_RETURN_NOT_OK( - builder->AppendValues(&elements->value, static_cast(num_elements)) - ); - - return Error::ok(); - } -} // namespace rerun diff --git a/rerun_cpp/src/rerun/components/marker_size.hpp b/rerun_cpp/src/rerun/components/marker_size.hpp index 8ffe080a3329..a3e3208c97b8 100644 --- a/rerun_cpp/src/rerun/components/marker_size.hpp +++ b/rerun_cpp/src/rerun/components/marker_size.hpp @@ -3,42 +3,43 @@ #pragma once +#include "../datatypes/float32.hpp" #include "../result.hpp" #include #include -namespace arrow { - /// \private - template - class NumericBuilder; - - class Array; - class DataType; - class FloatType; - using FloatBuilder = NumericBuilder; -} // namespace arrow - namespace rerun::components { /// **Component**: Radius of a marker of a point in e.g. a 2D plot, measured in UI points. struct MarkerSize { - float value; + rerun::datatypes::Float32 value; public: MarkerSize() = default; + MarkerSize(rerun::datatypes::Float32 value_) : value(value_) {} + + MarkerSize& operator=(rerun::datatypes::Float32 value_) { + value = value_; + return *this; + } + MarkerSize(float value_) : value(value_) {} MarkerSize& operator=(float value_) { value = value_; return *this; } + + /// Cast to the underlying Float32 datatype + operator rerun::datatypes::Float32() const { + return value; + } }; } // namespace rerun::components namespace rerun { - template - struct Loggable; + static_assert(sizeof(rerun::datatypes::Float32) == sizeof(components::MarkerSize)); /// \private template <> @@ -46,17 +47,15 @@ namespace rerun { static constexpr const char Name[] = "rerun.components.MarkerSize"; /// Returns the arrow data type this type corresponds to. - static const std::shared_ptr& arrow_datatype(); + static const std::shared_ptr& arrow_datatype() { + return Loggable::arrow_datatype(); + } /// Serializes an array of `rerun::components::MarkerSize` into an arrow array. static Result> to_arrow( const components::MarkerSize* instances, size_t num_instances - ); - - /// Fills an arrow array builder with an array of this type. - static rerun::Error fill_arrow_array_builder( - arrow::FloatBuilder* builder, const components::MarkerSize* elements, - size_t num_elements - ); + ) { + return Loggable::to_arrow(&instances->value, num_instances); + } }; } // namespace rerun diff --git a/rerun_cpp/src/rerun/components/radius.cpp b/rerun_cpp/src/rerun/components/radius.cpp deleted file mode 100644 index e8904878f48c..000000000000 --- a/rerun_cpp/src/rerun/components/radius.cpp +++ /dev/null @@ -1,57 +0,0 @@ -// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/cpp/mod.rs -// Based on "crates/store/re_types/definitions/rerun/components/radius.fbs". - -#include "radius.hpp" - -#include -#include - -namespace rerun::components {} - -namespace rerun { - const std::shared_ptr& Loggable::arrow_datatype() { - static const auto datatype = arrow::float32(); - return datatype; - } - - Result> Loggable::to_arrow( - const components::Radius* instances, size_t num_instances - ) { - // TODO(andreas): Allow configuring the memory pool. - arrow::MemoryPool* pool = arrow::default_memory_pool(); - auto datatype = arrow_datatype(); - - ARROW_ASSIGN_OR_RAISE(auto builder, arrow::MakeBuilder(datatype, pool)) - if (instances && num_instances > 0) { - RR_RETURN_NOT_OK(Loggable::fill_arrow_array_builder( - static_cast(builder.get()), - instances, - num_instances - )); - } - std::shared_ptr array; - ARROW_RETURN_NOT_OK(builder->Finish(&array)); - return array; - } - - rerun::Error Loggable::fill_arrow_array_builder( - arrow::FloatBuilder* builder, const components::Radius* elements, size_t num_elements - ) { - if (builder == nullptr) { - return rerun::Error(ErrorCode::UnexpectedNullArgument, "Passed array builder is null."); - } - if (elements == nullptr) { - return rerun::Error( - ErrorCode::UnexpectedNullArgument, - "Cannot serialize null pointer to arrow array." - ); - } - - static_assert(sizeof(*elements) == sizeof(elements->value)); - ARROW_RETURN_NOT_OK( - builder->AppendValues(&elements->value, static_cast(num_elements)) - ); - - return Error::ok(); - } -} // namespace rerun diff --git a/rerun_cpp/src/rerun/components/radius.hpp b/rerun_cpp/src/rerun/components/radius.hpp index 52bf4d715c25..af28e02fb17d 100644 --- a/rerun_cpp/src/rerun/components/radius.hpp +++ b/rerun_cpp/src/rerun/components/radius.hpp @@ -3,22 +3,12 @@ #pragma once +#include "../datatypes/float32.hpp" #include "../result.hpp" #include #include -namespace arrow { - /// \private - template - class NumericBuilder; - - class Array; - class DataType; - class FloatType; - using FloatBuilder = NumericBuilder; -} // namespace arrow - namespace rerun::components { /// **Component**: The radius of something, e.g. a point. /// @@ -29,7 +19,7 @@ namespace rerun::components { /// at 100% UI scaling, UI points are equal to pixels /// The Viewer's UI scaling defaults to the OS scaling which typically is 100% for full HD screens and 200% for 4k screens. struct Radius { - float value; + rerun::datatypes::Float32 value; public: // Extensions to generated type defined in 'radius_ext.cpp' @@ -51,18 +41,29 @@ namespace rerun::components { public: Radius() = default; + Radius(rerun::datatypes::Float32 value_) : value(value_) {} + + Radius& operator=(rerun::datatypes::Float32 value_) { + value = value_; + return *this; + } + Radius(float value_) : value(value_) {} Radius& operator=(float value_) { value = value_; return *this; } + + /// Cast to the underlying Float32 datatype + operator rerun::datatypes::Float32() const { + return value; + } }; } // namespace rerun::components namespace rerun { - template - struct Loggable; + static_assert(sizeof(rerun::datatypes::Float32) == sizeof(components::Radius)); /// \private template <> @@ -70,16 +71,15 @@ namespace rerun { static constexpr const char Name[] = "rerun.components.Radius"; /// Returns the arrow data type this type corresponds to. - static const std::shared_ptr& arrow_datatype(); + static const std::shared_ptr& arrow_datatype() { + return Loggable::arrow_datatype(); + } /// Serializes an array of `rerun::components::Radius` into an arrow array. static Result> to_arrow( const components::Radius* instances, size_t num_instances - ); - - /// Fills an arrow array builder with an array of this type. - static rerun::Error fill_arrow_array_builder( - arrow::FloatBuilder* builder, const components::Radius* elements, size_t num_elements - ); + ) { + return Loggable::to_arrow(&instances->value, num_instances); + } }; } // namespace rerun diff --git a/rerun_cpp/src/rerun/components/scalar.hpp b/rerun_cpp/src/rerun/components/scalar.hpp index b68022cbdc68..9c811333c69c 100644 --- a/rerun_cpp/src/rerun/components/scalar.hpp +++ b/rerun_cpp/src/rerun/components/scalar.hpp @@ -3,44 +3,45 @@ #pragma once +#include "../datatypes/float64.hpp" #include "../result.hpp" #include #include -namespace arrow { - /// \private - template - class NumericBuilder; - - class Array; - class DataType; - class DoubleType; - using DoubleBuilder = NumericBuilder; -} // namespace arrow - namespace rerun::components { /// **Component**: A scalar value, encoded as a 64-bit floating point. /// /// Used for time series plots. struct Scalar { - double value; + rerun::datatypes::Float64 value; public: Scalar() = default; + Scalar(rerun::datatypes::Float64 value_) : value(value_) {} + + Scalar& operator=(rerun::datatypes::Float64 value_) { + value = value_; + return *this; + } + Scalar(double value_) : value(value_) {} Scalar& operator=(double value_) { value = value_; return *this; } + + /// Cast to the underlying Float64 datatype + operator rerun::datatypes::Float64() const { + return value; + } }; } // namespace rerun::components namespace rerun { - template - struct Loggable; + static_assert(sizeof(rerun::datatypes::Float64) == sizeof(components::Scalar)); /// \private template <> @@ -48,16 +49,15 @@ namespace rerun { static constexpr const char Name[] = "rerun.components.Scalar"; /// Returns the arrow data type this type corresponds to. - static const std::shared_ptr& arrow_datatype(); + static const std::shared_ptr& arrow_datatype() { + return Loggable::arrow_datatype(); + } /// Serializes an array of `rerun::components::Scalar` into an arrow array. static Result> to_arrow( const components::Scalar* instances, size_t num_instances - ); - - /// Fills an arrow array builder with an array of this type. - static rerun::Error fill_arrow_array_builder( - arrow::DoubleBuilder* builder, const components::Scalar* elements, size_t num_elements - ); + ) { + return Loggable::to_arrow(&instances->value, num_instances); + } }; } // namespace rerun diff --git a/rerun_cpp/src/rerun/components/stroke_width.cpp b/rerun_cpp/src/rerun/components/stroke_width.cpp deleted file mode 100644 index 7f2896b755ba..000000000000 --- a/rerun_cpp/src/rerun/components/stroke_width.cpp +++ /dev/null @@ -1,57 +0,0 @@ -// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/cpp/mod.rs -// Based on "crates/store/re_types/definitions/rerun/components/stroke_width.fbs". - -#include "stroke_width.hpp" - -#include -#include - -namespace rerun::components {} - -namespace rerun { - const std::shared_ptr& Loggable::arrow_datatype() { - static const auto datatype = arrow::float32(); - return datatype; - } - - Result> Loggable::to_arrow( - const components::StrokeWidth* instances, size_t num_instances - ) { - // TODO(andreas): Allow configuring the memory pool. - arrow::MemoryPool* pool = arrow::default_memory_pool(); - auto datatype = arrow_datatype(); - - ARROW_ASSIGN_OR_RAISE(auto builder, arrow::MakeBuilder(datatype, pool)) - if (instances && num_instances > 0) { - RR_RETURN_NOT_OK(Loggable::fill_arrow_array_builder( - static_cast(builder.get()), - instances, - num_instances - )); - } - std::shared_ptr array; - ARROW_RETURN_NOT_OK(builder->Finish(&array)); - return array; - } - - rerun::Error Loggable::fill_arrow_array_builder( - arrow::FloatBuilder* builder, const components::StrokeWidth* elements, size_t num_elements - ) { - if (builder == nullptr) { - return rerun::Error(ErrorCode::UnexpectedNullArgument, "Passed array builder is null."); - } - if (elements == nullptr) { - return rerun::Error( - ErrorCode::UnexpectedNullArgument, - "Cannot serialize null pointer to arrow array." - ); - } - - static_assert(sizeof(*elements) == sizeof(elements->width)); - ARROW_RETURN_NOT_OK( - builder->AppendValues(&elements->width, static_cast(num_elements)) - ); - - return Error::ok(); - } -} // namespace rerun diff --git a/rerun_cpp/src/rerun/components/stroke_width.hpp b/rerun_cpp/src/rerun/components/stroke_width.hpp index 1e598dd1602e..c78a515da1c9 100644 --- a/rerun_cpp/src/rerun/components/stroke_width.hpp +++ b/rerun_cpp/src/rerun/components/stroke_width.hpp @@ -3,42 +3,43 @@ #pragma once +#include "../datatypes/float32.hpp" #include "../result.hpp" #include #include -namespace arrow { - /// \private - template - class NumericBuilder; - - class Array; - class DataType; - class FloatType; - using FloatBuilder = NumericBuilder; -} // namespace arrow - namespace rerun::components { /// **Component**: The width of a stroke specified in UI points. struct StrokeWidth { - float width; + rerun::datatypes::Float32 width; public: StrokeWidth() = default; - StrokeWidth(float width_) : width(width_) {} + StrokeWidth(rerun::datatypes::Float32 width_) : width(width_) {} - StrokeWidth& operator=(float width_) { + StrokeWidth& operator=(rerun::datatypes::Float32 width_) { width = width_; return *this; } + + StrokeWidth(float value_) : width(value_) {} + + StrokeWidth& operator=(float value_) { + width = value_; + return *this; + } + + /// Cast to the underlying Float32 datatype + operator rerun::datatypes::Float32() const { + return width; + } }; } // namespace rerun::components namespace rerun { - template - struct Loggable; + static_assert(sizeof(rerun::datatypes::Float32) == sizeof(components::StrokeWidth)); /// \private template <> @@ -46,17 +47,15 @@ namespace rerun { static constexpr const char Name[] = "rerun.components.StrokeWidth"; /// Returns the arrow data type this type corresponds to. - static const std::shared_ptr& arrow_datatype(); + static const std::shared_ptr& arrow_datatype() { + return Loggable::arrow_datatype(); + } /// Serializes an array of `rerun::components::StrokeWidth` into an arrow array. static Result> to_arrow( const components::StrokeWidth* instances, size_t num_instances - ); - - /// Fills an arrow array builder with an array of this type. - static rerun::Error fill_arrow_array_builder( - arrow::FloatBuilder* builder, const components::StrokeWidth* elements, - size_t num_elements - ); + ) { + return Loggable::to_arrow(&instances->width, num_instances); + } }; } // namespace rerun diff --git a/rerun_cpp/src/rerun/components/view_coordinates.hpp b/rerun_cpp/src/rerun/components/view_coordinates.hpp index 3b62bd784e55..c828022e5b59 100644 --- a/rerun_cpp/src/rerun/components/view_coordinates.hpp +++ b/rerun_cpp/src/rerun/components/view_coordinates.hpp @@ -3,19 +3,13 @@ #pragma once +#include "../datatypes/view_coordinates.hpp" #include "../rerun_sdk_export.hpp" #include "../result.hpp" -#include #include #include -namespace arrow { - class Array; - class DataType; - class FixedSizeListBuilder; -} // namespace arrow - namespace rerun::components { /// **Component**: How we interpret the coordinate system of an entity/space. /// @@ -35,7 +29,7 @@ namespace rerun::components { /// * Back = 6 struct ViewCoordinates { /// The directions of the [x, y, z] axes. - std::array coordinates; + rerun::datatypes::ViewCoordinates coordinates; public: // Extensions to generated type defined in 'view_coordinates_ext.cpp' @@ -51,11 +45,11 @@ namespace rerun::components { /// Construct Vec3D from x/y/z values. constexpr ViewCoordinates(uint8_t axis0, uint8_t axis1, uint8_t axis2) - : coordinates{axis0, axis1, axis2} {} + : coordinates(axis0, axis1, axis2) {} - /// Construct Vec3D from x/y/z values. + /// Construct Vec3D from x/y/z enum values. constexpr ViewCoordinates(ViewDir axis0, ViewDir axis1, ViewDir axis2) - : coordinates{axis0, axis1, axis2} {} + : coordinates(axis0, axis1, axis2) {} // // This section is generated by running `scripts/generate_view_coordinate_defs.py --cpp` @@ -244,18 +238,15 @@ namespace rerun::components { public: ViewCoordinates() = default; - ViewCoordinates(std::array coordinates_) : coordinates(coordinates_) {} - - ViewCoordinates& operator=(std::array coordinates_) { - coordinates = coordinates_; - return *this; + /// Cast to the underlying ViewCoordinates datatype + operator rerun::datatypes::ViewCoordinates() const { + return coordinates; } }; } // namespace rerun::components namespace rerun { - template - struct Loggable; + static_assert(sizeof(rerun::datatypes::ViewCoordinates) == sizeof(components::ViewCoordinates)); /// \private template <> @@ -263,17 +254,18 @@ namespace rerun { static constexpr const char Name[] = "rerun.components.ViewCoordinates"; /// Returns the arrow data type this type corresponds to. - static const std::shared_ptr& arrow_datatype(); + static const std::shared_ptr& arrow_datatype() { + return Loggable::arrow_datatype(); + } /// Serializes an array of `rerun::components::ViewCoordinates` into an arrow array. static Result> to_arrow( const components::ViewCoordinates* instances, size_t num_instances - ); - - /// Fills an arrow array builder with an array of this type. - static rerun::Error fill_arrow_array_builder( - arrow::FixedSizeListBuilder* builder, const components::ViewCoordinates* elements, - size_t num_elements - ); + ) { + return Loggable::to_arrow( + &instances->coordinates, + num_instances + ); + } }; } // namespace rerun diff --git a/rerun_cpp/src/rerun/components/view_coordinates_ext.cpp b/rerun_cpp/src/rerun/components/view_coordinates_ext.cpp index 17b88072237a..c36d1f6f487d 100644 --- a/rerun_cpp/src/rerun/components/view_coordinates_ext.cpp +++ b/rerun_cpp/src/rerun/components/view_coordinates_ext.cpp @@ -29,11 +29,11 @@ namespace rerun { /// Construct Vec3D from x/y/z values. constexpr ViewCoordinates(uint8_t axis0, uint8_t axis1, uint8_t axis2) - : coordinates{axis0, axis1, axis2} {} + : coordinates(axis0, axis1, axis2) {} - /// Construct Vec3D from x/y/z values. + /// Construct Vec3D from x/y/z enum values. constexpr ViewCoordinates(ViewDir axis0, ViewDir axis1, ViewDir axis2) - : coordinates{axis0, axis1, axis2} {} + : coordinates(axis0, axis1, axis2) {} // // This section is generated by running `scripts/generate_view_coordinate_defs.py --cpp` diff --git a/rerun_cpp/src/rerun/datatypes.hpp b/rerun_cpp/src/rerun/datatypes.hpp index 9c7e07bc4598..e90571375309 100644 --- a/rerun_cpp/src/rerun/datatypes.hpp +++ b/rerun_cpp/src/rerun/datatypes.hpp @@ -4,12 +4,14 @@ #include "datatypes/angle.hpp" #include "datatypes/annotation_info.hpp" +#include "datatypes/blob.hpp" #include "datatypes/bool.hpp" #include "datatypes/class_description.hpp" #include "datatypes/class_description_map_elem.hpp" #include "datatypes/class_id.hpp" #include "datatypes/entity_path.hpp" #include "datatypes/float32.hpp" +#include "datatypes/float64.hpp" #include "datatypes/keypoint_id.hpp" #include "datatypes/keypoint_pair.hpp" #include "datatypes/mat3x3.hpp" @@ -43,4 +45,5 @@ #include "datatypes/vec2d.hpp" #include "datatypes/vec3d.hpp" #include "datatypes/vec4d.hpp" +#include "datatypes/view_coordinates.hpp" #include "datatypes/visible_time_range.hpp" diff --git a/rerun_cpp/src/rerun/datatypes/.gitattributes b/rerun_cpp/src/rerun/datatypes/.gitattributes index bf5f7a01f10d..605ffd6572a3 100644 --- a/rerun_cpp/src/rerun/datatypes/.gitattributes +++ b/rerun_cpp/src/rerun/datatypes/.gitattributes @@ -5,6 +5,8 @@ angle.cpp linguist-generated=true angle.hpp linguist-generated=true annotation_info.cpp linguist-generated=true annotation_info.hpp linguist-generated=true +blob.cpp linguist-generated=true +blob.hpp linguist-generated=true bool.cpp linguist-generated=true bool.hpp linguist-generated=true class_description.cpp linguist-generated=true @@ -17,6 +19,8 @@ entity_path.cpp linguist-generated=true entity_path.hpp linguist-generated=true float32.cpp linguist-generated=true float32.hpp linguist-generated=true +float64.cpp linguist-generated=true +float64.hpp linguist-generated=true keypoint_id.cpp linguist-generated=true keypoint_id.hpp linguist-generated=true keypoint_pair.cpp linguist-generated=true @@ -83,5 +87,7 @@ vec3d.cpp linguist-generated=true vec3d.hpp linguist-generated=true vec4d.cpp linguist-generated=true vec4d.hpp linguist-generated=true +view_coordinates.cpp linguist-generated=true +view_coordinates.hpp linguist-generated=true visible_time_range.cpp linguist-generated=true visible_time_range.hpp linguist-generated=true diff --git a/rerun_cpp/src/rerun/components/blob.cpp b/rerun_cpp/src/rerun/datatypes/blob.cpp similarity index 77% rename from rerun_cpp/src/rerun/components/blob.cpp rename to rerun_cpp/src/rerun/datatypes/blob.cpp index ee9c195241ae..10b05e46fcdf 100644 --- a/rerun_cpp/src/rerun/components/blob.cpp +++ b/rerun_cpp/src/rerun/datatypes/blob.cpp @@ -1,21 +1,21 @@ // DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/cpp/mod.rs -// Based on "crates/store/re_types/definitions/rerun/components/blob.fbs". +// Based on "crates/store/re_types/definitions/rerun/datatypes/blob.fbs". #include "blob.hpp" #include #include -namespace rerun::components {} +namespace rerun::datatypes {} namespace rerun { - const std::shared_ptr& Loggable::arrow_datatype() { + const std::shared_ptr& Loggable::arrow_datatype() { static const auto datatype = arrow::list(arrow::field("item", arrow::uint8(), false)); return datatype; } - Result> Loggable::to_arrow( - const components::Blob* instances, size_t num_instances + Result> Loggable::to_arrow( + const datatypes::Blob* instances, size_t num_instances ) { // TODO(andreas): Allow configuring the memory pool. arrow::MemoryPool* pool = arrow::default_memory_pool(); @@ -23,7 +23,7 @@ namespace rerun { ARROW_ASSIGN_OR_RAISE(auto builder, arrow::MakeBuilder(datatype, pool)) if (instances && num_instances > 0) { - RR_RETURN_NOT_OK(Loggable::fill_arrow_array_builder( + RR_RETURN_NOT_OK(Loggable::fill_arrow_array_builder( static_cast(builder.get()), instances, num_instances @@ -34,8 +34,8 @@ namespace rerun { return array; } - rerun::Error Loggable::fill_arrow_array_builder( - arrow::ListBuilder* builder, const components::Blob* elements, size_t num_elements + rerun::Error Loggable::fill_arrow_array_builder( + arrow::ListBuilder* builder, const datatypes::Blob* elements, size_t num_elements ) { if (builder == nullptr) { return rerun::Error(ErrorCode::UnexpectedNullArgument, "Passed array builder is null."); diff --git a/rerun_cpp/src/rerun/datatypes/blob.hpp b/rerun_cpp/src/rerun/datatypes/blob.hpp new file mode 100644 index 000000000000..e0a14fab3a9d --- /dev/null +++ b/rerun_cpp/src/rerun/datatypes/blob.hpp @@ -0,0 +1,58 @@ +// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/cpp/mod.rs +// Based on "crates/store/re_types/definitions/rerun/datatypes/blob.fbs". + +#pragma once + +#include "../collection.hpp" +#include "../result.hpp" + +#include +#include +#include + +namespace arrow { + class Array; + class DataType; + class ListBuilder; +} // namespace arrow + +namespace rerun::datatypes { + /// **Datatype**: A binary blob of data. + struct Blob { + rerun::Collection data; + + public: + Blob() = default; + + Blob(rerun::Collection data_) : data(std::move(data_)) {} + + Blob& operator=(rerun::Collection data_) { + data = std::move(data_); + return *this; + } + }; +} // namespace rerun::datatypes + +namespace rerun { + template + struct Loggable; + + /// \private + template <> + struct Loggable { + static constexpr const char Name[] = "rerun.datatypes.Blob"; + + /// Returns the arrow data type this type corresponds to. + static const std::shared_ptr& arrow_datatype(); + + /// Serializes an array of `rerun::datatypes::Blob` into an arrow array. + static Result> to_arrow( + const datatypes::Blob* instances, size_t num_instances + ); + + /// Fills an arrow array builder with an array of this type. + static rerun::Error fill_arrow_array_builder( + arrow::ListBuilder* builder, const datatypes::Blob* elements, size_t num_elements + ); + }; +} // namespace rerun diff --git a/rerun_cpp/src/rerun/components/scalar.cpp b/rerun_cpp/src/rerun/datatypes/float64.cpp similarity index 73% rename from rerun_cpp/src/rerun/components/scalar.cpp rename to rerun_cpp/src/rerun/datatypes/float64.cpp index d3284035971d..f45c8e6beddd 100644 --- a/rerun_cpp/src/rerun/components/scalar.cpp +++ b/rerun_cpp/src/rerun/datatypes/float64.cpp @@ -1,21 +1,21 @@ // DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/cpp/mod.rs -// Based on "crates/store/re_types/definitions/rerun/components/scalar.fbs". +// Based on "crates/store/re_types/definitions/rerun/datatypes/float64.fbs". -#include "scalar.hpp" +#include "float64.hpp" #include #include -namespace rerun::components {} +namespace rerun::datatypes {} namespace rerun { - const std::shared_ptr& Loggable::arrow_datatype() { + const std::shared_ptr& Loggable::arrow_datatype() { static const auto datatype = arrow::float64(); return datatype; } - Result> Loggable::to_arrow( - const components::Scalar* instances, size_t num_instances + Result> Loggable::to_arrow( + const datatypes::Float64* instances, size_t num_instances ) { // TODO(andreas): Allow configuring the memory pool. arrow::MemoryPool* pool = arrow::default_memory_pool(); @@ -23,7 +23,7 @@ namespace rerun { ARROW_ASSIGN_OR_RAISE(auto builder, arrow::MakeBuilder(datatype, pool)) if (instances && num_instances > 0) { - RR_RETURN_NOT_OK(Loggable::fill_arrow_array_builder( + RR_RETURN_NOT_OK(Loggable::fill_arrow_array_builder( static_cast(builder.get()), instances, num_instances @@ -34,8 +34,8 @@ namespace rerun { return array; } - rerun::Error Loggable::fill_arrow_array_builder( - arrow::DoubleBuilder* builder, const components::Scalar* elements, size_t num_elements + rerun::Error Loggable::fill_arrow_array_builder( + arrow::DoubleBuilder* builder, const datatypes::Float64* elements, size_t num_elements ) { if (builder == nullptr) { return rerun::Error(ErrorCode::UnexpectedNullArgument, "Passed array builder is null."); diff --git a/rerun_cpp/src/rerun/datatypes/float64.hpp b/rerun_cpp/src/rerun/datatypes/float64.hpp new file mode 100644 index 000000000000..1c0158b23936 --- /dev/null +++ b/rerun_cpp/src/rerun/datatypes/float64.hpp @@ -0,0 +1,61 @@ +// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/cpp/mod.rs +// Based on "crates/store/re_types/definitions/rerun/datatypes/float64.fbs". + +#pragma once + +#include "../result.hpp" + +#include +#include + +namespace arrow { + /// \private + template + class NumericBuilder; + + class Array; + class DataType; + class DoubleType; + using DoubleBuilder = NumericBuilder; +} // namespace arrow + +namespace rerun::datatypes { + /// **Datatype**: A double-precision 64-bit IEEE 754 floating point number. + struct Float64 { + double value; + + public: + Float64() = default; + + Float64(double value_) : value(value_) {} + + Float64& operator=(double value_) { + value = value_; + return *this; + } + }; +} // namespace rerun::datatypes + +namespace rerun { + template + struct Loggable; + + /// \private + template <> + struct Loggable { + static constexpr const char Name[] = "rerun.datatypes.Float64"; + + /// Returns the arrow data type this type corresponds to. + static const std::shared_ptr& arrow_datatype(); + + /// Serializes an array of `rerun::datatypes::Float64` into an arrow array. + static Result> to_arrow( + const datatypes::Float64* instances, size_t num_instances + ); + + /// Fills an arrow array builder with an array of this type. + static rerun::Error fill_arrow_array_builder( + arrow::DoubleBuilder* builder, const datatypes::Float64* elements, size_t num_elements + ); + }; +} // namespace rerun diff --git a/rerun_cpp/src/rerun/components/view_coordinates.cpp b/rerun_cpp/src/rerun/datatypes/view_coordinates.cpp similarity index 73% rename from rerun_cpp/src/rerun/components/view_coordinates.cpp rename to rerun_cpp/src/rerun/datatypes/view_coordinates.cpp index 8ea84dc136dd..6ba1e32b4401 100644 --- a/rerun_cpp/src/rerun/components/view_coordinates.cpp +++ b/rerun_cpp/src/rerun/datatypes/view_coordinates.cpp @@ -1,23 +1,22 @@ // DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/cpp/mod.rs -// Based on "crates/store/re_types/definitions/rerun/components/view_coordinates.fbs". +// Based on "crates/store/re_types/definitions/rerun/datatypes/view_coordinates.fbs". #include "view_coordinates.hpp" #include #include -namespace rerun::components {} +namespace rerun::datatypes {} namespace rerun { - const std::shared_ptr& Loggable::arrow_datatype( - ) { + const std::shared_ptr& Loggable::arrow_datatype() { static const auto datatype = arrow::fixed_size_list(arrow::field("item", arrow::uint8(), false), 3); return datatype; } - Result> Loggable::to_arrow( - const components::ViewCoordinates* instances, size_t num_instances + Result> Loggable::to_arrow( + const datatypes::ViewCoordinates* instances, size_t num_instances ) { // TODO(andreas): Allow configuring the memory pool. arrow::MemoryPool* pool = arrow::default_memory_pool(); @@ -25,7 +24,7 @@ namespace rerun { ARROW_ASSIGN_OR_RAISE(auto builder, arrow::MakeBuilder(datatype, pool)) if (instances && num_instances > 0) { - RR_RETURN_NOT_OK(Loggable::fill_arrow_array_builder( + RR_RETURN_NOT_OK(Loggable::fill_arrow_array_builder( static_cast(builder.get()), instances, num_instances @@ -36,8 +35,8 @@ namespace rerun { return array; } - rerun::Error Loggable::fill_arrow_array_builder( - arrow::FixedSizeListBuilder* builder, const components::ViewCoordinates* elements, + rerun::Error Loggable::fill_arrow_array_builder( + arrow::FixedSizeListBuilder* builder, const datatypes::ViewCoordinates* elements, size_t num_elements ) { if (builder == nullptr) { diff --git a/rerun_cpp/src/rerun/datatypes/view_coordinates.hpp b/rerun_cpp/src/rerun/datatypes/view_coordinates.hpp new file mode 100644 index 000000000000..9ef73d4f16da --- /dev/null +++ b/rerun_cpp/src/rerun/datatypes/view_coordinates.hpp @@ -0,0 +1,81 @@ +// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/cpp/mod.rs +// Based on "crates/store/re_types/definitions/rerun/datatypes/view_coordinates.fbs". + +#pragma once + +#include "../result.hpp" + +#include +#include +#include + +namespace arrow { + class Array; + class DataType; + class FixedSizeListBuilder; +} // namespace arrow + +namespace rerun::datatypes { + /// **Datatype**: How we interpret the coordinate system of an entity/space. + /// + /// For instance: What is "up"? What does the Z axis mean? Is this right-handed or left-handed? + /// + /// The three coordinates are always ordered as [x, y, z]. + /// + /// For example [Right, Down, Forward] means that the X axis points to the right, the Y axis points + /// down, and the Z axis points forward. + /// + /// The following constants are used to represent the different directions: + /// * Up = 1 + /// * Down = 2 + /// * Right = 3 + /// * Left = 4 + /// * Forward = 5 + /// * Back = 6 + struct ViewCoordinates { + /// The directions of the [x, y, z] axes. + std::array coordinates; + + public: + // Extensions to generated type defined in 'view_coordinates_ext.cpp' + + /// Construct Vec3D from x/y/z values. + explicit constexpr ViewCoordinates(uint8_t axis0, uint8_t axis1, uint8_t axis2) + : coordinates{axis0, axis1, axis2} {} + + public: + ViewCoordinates() = default; + + ViewCoordinates(std::array coordinates_) : coordinates(coordinates_) {} + + ViewCoordinates& operator=(std::array coordinates_) { + coordinates = coordinates_; + return *this; + } + }; +} // namespace rerun::datatypes + +namespace rerun { + template + struct Loggable; + + /// \private + template <> + struct Loggable { + static constexpr const char Name[] = "rerun.datatypes.ViewCoordinates"; + + /// Returns the arrow data type this type corresponds to. + static const std::shared_ptr& arrow_datatype(); + + /// Serializes an array of `rerun::datatypes::ViewCoordinates` into an arrow array. + static Result> to_arrow( + const datatypes::ViewCoordinates* instances, size_t num_instances + ); + + /// Fills an arrow array builder with an array of this type. + static rerun::Error fill_arrow_array_builder( + arrow::FixedSizeListBuilder* builder, const datatypes::ViewCoordinates* elements, + size_t num_elements + ); + }; +} // namespace rerun diff --git a/rerun_cpp/src/rerun/datatypes/view_coordinates_ext.cpp b/rerun_cpp/src/rerun/datatypes/view_coordinates_ext.cpp new file mode 100644 index 000000000000..5095c6a17dc4 --- /dev/null +++ b/rerun_cpp/src/rerun/datatypes/view_coordinates_ext.cpp @@ -0,0 +1,24 @@ +#include "view_coordinates.hpp" + +// Uncomment for better auto-complete while editing the extension. +// #define EDIT_EXTENSION + +namespace rerun { + namespace datatypes { + +#ifdef EDIT_EXTENSION + struct ViewCoordinatesExt { + uint8_t coordinates[3]; +#define ViewCoordinates ViewCoordinatesExt + + // + + /// Construct Vec3D from x/y/z values. + explicit constexpr ViewCoordinates(uint8_t axis0, uint8_t axis1, uint8_t axis2) + : coordinates{axis0, axis1, axis2} {} + + // + }; +#endif + } // namespace datatypes +} // namespace rerun diff --git a/rerun_cpp/tests/archetypes/view_coordinates.cpp b/rerun_cpp/tests/archetypes/view_coordinates.cpp index d7fb31ac7fe9..2d1a8daa5d96 100644 --- a/rerun_cpp/tests/archetypes/view_coordinates.cpp +++ b/rerun_cpp/tests/archetypes/view_coordinates.cpp @@ -20,7 +20,7 @@ SCENARIO( ); ViewCoordinates from_manual; - from_manual.xyz.coordinates = { + from_manual.xyz = { rerun::components::ViewCoordinates::Right, rerun::components::ViewCoordinates::Down, rerun::components::ViewCoordinates::Forward, diff --git a/rerun_py/rerun_sdk/rerun/_image.py b/rerun_py/rerun_sdk/rerun/_image.py index 0ba490015606..e214236d3d2a 100644 --- a/rerun_py/rerun_sdk/rerun/_image.py +++ b/rerun_py/rerun_sdk/rerun/_image.py @@ -9,8 +9,8 @@ from ._log import AsComponents, ComponentBatchLike from .archetypes import Image -from .components import DrawOrderLike, TensorData -from .datatypes import TensorBuffer, TensorDimension +from .components import TensorData +from .datatypes import Float32Like, TensorBuffer, TensorDimension class ImageFormat: @@ -135,7 +135,7 @@ def __init__( path: str | pathlib.Path | None = None, contents: bytes | IO[bytes] | None = None, format: ImageFormat | None = None, - draw_order: DrawOrderLike | None = None, + draw_order: Float32Like | None = None, ) -> None: """ Create a new image with a given format. diff --git a/rerun_py/rerun_sdk/rerun/archetypes/arrows2d_ext.py b/rerun_py/rerun_sdk/rerun/archetypes/arrows2d_ext.py index 8b14e5323094..e207fd22d3b5 100644 --- a/rerun_py/rerun_sdk/rerun/archetypes/arrows2d_ext.py +++ b/rerun_py/rerun_sdk/rerun/archetypes/arrows2d_ext.py @@ -2,7 +2,7 @@ from typing import Any -from .. import components, datatypes +from .. import datatypes from ..error_utils import catch_and_log_exceptions @@ -14,7 +14,7 @@ def __init__( *, vectors: datatypes.Vec2DArrayLike, origins: datatypes.Vec2DArrayLike | None = None, - radii: components.RadiusArrayLike | None = None, + radii: datatypes.Float32ArrayLike | None = None, colors: datatypes.Rgba32ArrayLike | None = None, labels: datatypes.Utf8ArrayLike | None = None, class_ids: datatypes.ClassIdArrayLike | None = None, diff --git a/rerun_py/rerun_sdk/rerun/archetypes/arrows3d_ext.py b/rerun_py/rerun_sdk/rerun/archetypes/arrows3d_ext.py index 224c6e028fae..43e3f66bd122 100644 --- a/rerun_py/rerun_sdk/rerun/archetypes/arrows3d_ext.py +++ b/rerun_py/rerun_sdk/rerun/archetypes/arrows3d_ext.py @@ -2,7 +2,7 @@ from typing import Any -from .. import components, datatypes +from .. import datatypes from ..error_utils import catch_and_log_exceptions @@ -14,7 +14,7 @@ def __init__( *, vectors: datatypes.Vec3DArrayLike, origins: datatypes.Vec3DArrayLike | None = None, - radii: components.RadiusArrayLike | None = None, + radii: datatypes.Float32ArrayLike | None = None, colors: datatypes.Rgba32ArrayLike | None = None, labels: datatypes.Utf8ArrayLike | None = None, class_ids: datatypes.ClassIdArrayLike | None = None, diff --git a/rerun_py/rerun_sdk/rerun/archetypes/asset3d_ext.py b/rerun_py/rerun_sdk/rerun/archetypes/asset3d_ext.py index 1207810aadd2..92e7882d510d 100644 --- a/rerun_py/rerun_sdk/rerun/archetypes/asset3d_ext.py +++ b/rerun_py/rerun_sdk/rerun/archetypes/asset3d_ext.py @@ -3,7 +3,7 @@ import pathlib from typing import TYPE_CHECKING, Any -from .. import components, datatypes +from .. import datatypes from ..error_utils import catch_and_log_exceptions if TYPE_CHECKING: @@ -33,7 +33,7 @@ def __init__( self: Any, *, path: str | pathlib.Path | None = None, - contents: components.BlobLike | None = None, + contents: datatypes.BlobLike | None = None, media_type: datatypes.Utf8Like | None = None, transform: datatypes.Transform3DLike | None = None, ): diff --git a/rerun_py/rerun_sdk/rerun/archetypes/boxes2d_ext.py b/rerun_py/rerun_sdk/rerun/archetypes/boxes2d_ext.py index 560d656a508a..1c6bffd78588 100644 --- a/rerun_py/rerun_sdk/rerun/archetypes/boxes2d_ext.py +++ b/rerun_py/rerun_sdk/rerun/archetypes/boxes2d_ext.py @@ -6,7 +6,7 @@ import numpy as np import numpy.typing as npt -from .. import components, datatypes +from .. import datatypes from ..error_utils import catch_and_log_exceptions @@ -44,10 +44,10 @@ def __init__( centers: datatypes.Vec2DArrayLike | None = None, array: npt.ArrayLike | None = None, array_format: Box2DFormat | None = None, - radii: components.RadiusArrayLike | None = None, + radii: datatypes.Float32ArrayLike | None = None, colors: datatypes.Rgba32ArrayLike | None = None, labels: datatypes.Utf8ArrayLike | None = None, - draw_order: components.DrawOrderLike | None = None, + draw_order: datatypes.Float32ArrayLike | None = None, class_ids: datatypes.ClassIdArrayLike | None = None, ) -> None: """ diff --git a/rerun_py/rerun_sdk/rerun/archetypes/boxes3d_ext.py b/rerun_py/rerun_sdk/rerun/archetypes/boxes3d_ext.py index cb571669572a..7048ce103dbf 100644 --- a/rerun_py/rerun_sdk/rerun/archetypes/boxes3d_ext.py +++ b/rerun_py/rerun_sdk/rerun/archetypes/boxes3d_ext.py @@ -4,7 +4,7 @@ import numpy as np -from .. import components, datatypes +from .. import datatypes from ..error_utils import _send_warning_or_raise, catch_and_log_exceptions @@ -20,7 +20,7 @@ def __init__( centers: datatypes.Vec3DArrayLike | None = None, rotations: datatypes.Rotation3DArrayLike | None = None, colors: datatypes.Rgba32ArrayLike | None = None, - radii: components.RadiusArrayLike | None = None, + radii: datatypes.Float32ArrayLike | None = None, labels: datatypes.Utf8ArrayLike | None = None, class_ids: datatypes.ClassIdArrayLike | None = None, ) -> None: diff --git a/rerun_py/rerun_sdk/rerun/archetypes/depth_image.py b/rerun_py/rerun_sdk/rerun/archetypes/depth_image.py index e3f2d6e291ba..c25441d2c3d3 100644 --- a/rerun_py/rerun_sdk/rerun/archetypes/depth_image.py +++ b/rerun_py/rerun_sdk/rerun/archetypes/depth_image.py @@ -69,10 +69,10 @@ def __init__( self: Any, data: datatypes.TensorDataLike, *, - meter: components.DepthMeterLike | None = None, + meter: datatypes.Float32Like | None = None, colormap: components.ColormapLike | None = None, point_fill_ratio: datatypes.Float32Like | None = None, - draw_order: components.DrawOrderLike | None = None, + draw_order: datatypes.Float32Like | None = None, ): """ Create a new instance of the DepthImage archetype. diff --git a/rerun_py/rerun_sdk/rerun/archetypes/disconnected_space_ext.py b/rerun_py/rerun_sdk/rerun/archetypes/disconnected_space_ext.py index de898c4e7abd..c72a30c019a1 100644 --- a/rerun_py/rerun_sdk/rerun/archetypes/disconnected_space_ext.py +++ b/rerun_py/rerun_sdk/rerun/archetypes/disconnected_space_ext.py @@ -3,7 +3,7 @@ from typing import TYPE_CHECKING, Any if TYPE_CHECKING: - from ..components import DisconnectedSpaceLike + from ..datatypes import BoolLike class DisconnectedSpaceExt: @@ -11,7 +11,7 @@ class DisconnectedSpaceExt: def __init__( self: Any, - is_disconnected: DisconnectedSpaceLike = True, + is_disconnected: BoolLike = True, ): """ Disconnect an entity from its parent. diff --git a/rerun_py/rerun_sdk/rerun/archetypes/image.py b/rerun_py/rerun_sdk/rerun/archetypes/image.py index e78be6201a85..277910da4ae2 100644 --- a/rerun_py/rerun_sdk/rerun/archetypes/image.py +++ b/rerun_py/rerun_sdk/rerun/archetypes/image.py @@ -74,7 +74,7 @@ def __init__( data: datatypes.TensorDataLike, *, opacity: datatypes.Float32Like | None = None, - draw_order: components.DrawOrderLike | None = None, + draw_order: datatypes.Float32Like | None = None, ): """ Create a new instance of the Image archetype. diff --git a/rerun_py/rerun_sdk/rerun/archetypes/line_strips2d.py b/rerun_py/rerun_sdk/rerun/archetypes/line_strips2d.py index 681c74dddf08..46b4f71d2ed7 100644 --- a/rerun_py/rerun_sdk/rerun/archetypes/line_strips2d.py +++ b/rerun_py/rerun_sdk/rerun/archetypes/line_strips2d.py @@ -97,10 +97,10 @@ def __init__( self: Any, strips: components.LineStrip2DArrayLike, *, - radii: components.RadiusArrayLike | None = None, + radii: datatypes.Float32ArrayLike | None = None, colors: datatypes.Rgba32ArrayLike | None = None, labels: datatypes.Utf8ArrayLike | None = None, - draw_order: components.DrawOrderLike | None = None, + draw_order: datatypes.Float32Like | None = None, class_ids: datatypes.ClassIdArrayLike | None = None, ): """ diff --git a/rerun_py/rerun_sdk/rerun/archetypes/line_strips3d.py b/rerun_py/rerun_sdk/rerun/archetypes/line_strips3d.py index 1a81048a5613..74dadfffc8f2 100644 --- a/rerun_py/rerun_sdk/rerun/archetypes/line_strips3d.py +++ b/rerun_py/rerun_sdk/rerun/archetypes/line_strips3d.py @@ -116,7 +116,7 @@ def __init__( self: Any, strips: components.LineStrip3DArrayLike, *, - radii: components.RadiusArrayLike | None = None, + radii: datatypes.Float32ArrayLike | None = None, colors: datatypes.Rgba32ArrayLike | None = None, labels: datatypes.Utf8ArrayLike | None = None, class_ids: datatypes.ClassIdArrayLike | None = None, diff --git a/rerun_py/rerun_sdk/rerun/archetypes/pinhole_ext.py b/rerun_py/rerun_sdk/rerun/archetypes/pinhole_ext.py index fd34431d3a99..424552b8fbc6 100644 --- a/rerun_py/rerun_sdk/rerun/archetypes/pinhole_ext.py +++ b/rerun_py/rerun_sdk/rerun/archetypes/pinhole_ext.py @@ -5,9 +5,7 @@ import numpy.typing as npt -from ..components import ViewCoordinatesLike -from ..datatypes.mat3x3 import Mat3x3Like -from ..datatypes.vec2d import Vec2D, Vec2DLike +from ..datatypes import Mat3x3Like, Vec2D, Vec2DLike, ViewCoordinatesLike from ..error_utils import _send_warning_or_raise, catch_and_log_exceptions diff --git a/rerun_py/rerun_sdk/rerun/archetypes/points2d_ext.py b/rerun_py/rerun_sdk/rerun/archetypes/points2d_ext.py index 4fee18414bd6..2735291215cf 100644 --- a/rerun_py/rerun_sdk/rerun/archetypes/points2d_ext.py +++ b/rerun_py/rerun_sdk/rerun/archetypes/points2d_ext.py @@ -2,7 +2,7 @@ from typing import Any -from .. import components, datatypes +from .. import datatypes from ..error_utils import catch_and_log_exceptions @@ -13,10 +13,10 @@ def __init__( self: Any, positions: datatypes.Vec2DArrayLike, *, - radii: components.RadiusArrayLike | None = None, + radii: datatypes.Float32ArrayLike | None = None, colors: datatypes.Rgba32ArrayLike | None = None, labels: datatypes.Utf8ArrayLike | None = None, - draw_order: components.DrawOrderLike | None = None, + draw_order: datatypes.Float32ArrayLike | None = None, class_ids: datatypes.ClassIdArrayLike | None = None, keypoint_ids: datatypes.KeypointIdArrayLike | None = None, ): diff --git a/rerun_py/rerun_sdk/rerun/archetypes/points3d_ext.py b/rerun_py/rerun_sdk/rerun/archetypes/points3d_ext.py index 06523fe39b43..985b5430d5ab 100644 --- a/rerun_py/rerun_sdk/rerun/archetypes/points3d_ext.py +++ b/rerun_py/rerun_sdk/rerun/archetypes/points3d_ext.py @@ -2,7 +2,7 @@ from typing import Any -from .. import components, datatypes +from .. import datatypes from ..error_utils import catch_and_log_exceptions @@ -13,7 +13,7 @@ def __init__( self: Any, positions: datatypes.Vec3DArrayLike, *, - radii: components.RadiusArrayLike | None = None, + radii: datatypes.Float32ArrayLike | None = None, colors: datatypes.Rgba32ArrayLike | None = None, labels: datatypes.Utf8ArrayLike | None = None, class_ids: datatypes.ClassIdArrayLike | None = None, diff --git a/rerun_py/rerun_sdk/rerun/archetypes/scalar.py b/rerun_py/rerun_sdk/rerun/archetypes/scalar.py index baad0d59e445..7cb187e37b8a 100644 --- a/rerun_py/rerun_sdk/rerun/archetypes/scalar.py +++ b/rerun_py/rerun_sdk/rerun/archetypes/scalar.py @@ -9,7 +9,7 @@ from attrs import define, field -from .. import components +from .. import components, datatypes from .._baseclasses import ( Archetype, ) @@ -60,7 +60,7 @@ class Scalar(Archetype): """ - def __init__(self: Any, scalar: components.ScalarLike): + def __init__(self: Any, scalar: datatypes.Float64Like): """ Create a new instance of the Scalar archetype. diff --git a/rerun_py/rerun_sdk/rerun/archetypes/segmentation_image.py b/rerun_py/rerun_sdk/rerun/archetypes/segmentation_image.py index e93febab9b92..380772409c41 100644 --- a/rerun_py/rerun_sdk/rerun/archetypes/segmentation_image.py +++ b/rerun_py/rerun_sdk/rerun/archetypes/segmentation_image.py @@ -71,7 +71,7 @@ def __init__( data: datatypes.TensorDataLike, *, opacity: datatypes.Float32Like | None = None, - draw_order: components.DrawOrderLike | None = None, + draw_order: datatypes.Float32Like | None = None, ): """ Create a new instance of the SegmentationImage archetype. diff --git a/rerun_py/rerun_sdk/rerun/archetypes/series_line.py b/rerun_py/rerun_sdk/rerun/archetypes/series_line.py index 5d0490354ce6..32e74bc854c9 100644 --- a/rerun_py/rerun_sdk/rerun/archetypes/series_line.py +++ b/rerun_py/rerun_sdk/rerun/archetypes/series_line.py @@ -68,7 +68,7 @@ def __init__( self: Any, *, color: datatypes.Rgba32Like | None = None, - width: components.StrokeWidthLike | None = None, + width: datatypes.Float32Like | None = None, name: datatypes.Utf8Like | None = None, aggregation_policy: components.AggregationPolicyLike | None = None, ): diff --git a/rerun_py/rerun_sdk/rerun/archetypes/series_point.py b/rerun_py/rerun_sdk/rerun/archetypes/series_point.py index 8839d4bf038a..d289d65dd48e 100644 --- a/rerun_py/rerun_sdk/rerun/archetypes/series_point.py +++ b/rerun_py/rerun_sdk/rerun/archetypes/series_point.py @@ -88,7 +88,7 @@ def __init__( color: datatypes.Rgba32Like | None = None, marker: components.MarkerShapeLike | None = None, name: datatypes.Utf8Like | None = None, - marker_size: components.MarkerSizeLike | None = None, + marker_size: datatypes.Float32Like | None = None, ): """ Create a new instance of the SeriesPoint archetype. diff --git a/rerun_py/rerun_sdk/rerun/archetypes/view_coordinates.py b/rerun_py/rerun_sdk/rerun/archetypes/view_coordinates.py index 34e5538b0159..2bc98bc518d6 100644 --- a/rerun_py/rerun_sdk/rerun/archetypes/view_coordinates.py +++ b/rerun_py/rerun_sdk/rerun/archetypes/view_coordinates.py @@ -9,7 +9,7 @@ from attrs import define, field -from .. import components +from .. import components, datatypes from .._baseclasses import ( Archetype, ) @@ -60,7 +60,7 @@ class ViewCoordinates(ViewCoordinatesExt, Archetype): """ - def __init__(self: Any, xyz: components.ViewCoordinatesLike): + def __init__(self: Any, xyz: datatypes.ViewCoordinatesLike): """ Create a new instance of the ViewCoordinates archetype. diff --git a/rerun_py/rerun_sdk/rerun/blueprint/api.py b/rerun_py/rerun_sdk/rerun/blueprint/api.py index 9859bf8368f2..2979cb42d190 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/api.py +++ b/rerun_py/rerun_sdk/rerun/blueprint/api.py @@ -7,11 +7,11 @@ from .._baseclasses import AsComponents, ComponentBatchLike from .._spawn import _spawn_viewer -from ..datatypes import EntityPathLike, Utf8ArrayLike, Utf8Like +from ..datatypes import BoolLike, EntityPathLike, Float32ArrayLike, Utf8ArrayLike, Utf8Like from ..memory import MemoryRecording from ..recording_stream import RecordingStream from .archetypes import ContainerBlueprint, PanelBlueprint, SpaceViewBlueprint, SpaceViewContents, ViewportBlueprint -from .components import ColumnShareArrayLike, PanelState, PanelStateLike, RowShareArrayLike, VisibleLike +from .components import PanelState, PanelStateLike from .components.container_kind import ContainerKindLike SpaceViewContentsLike = Union[Utf8ArrayLike, SpaceViewContents] @@ -41,7 +41,7 @@ def __init__( origin: EntityPathLike, contents: SpaceViewContentsLike, name: Utf8Like | None, - visible: VisibleLike | None = None, + visible: BoolLike | None = None, properties: dict[str, AsComponents] = {}, defaults: list[Union[AsComponents, ComponentBatchLike]] = [], overrides: dict[EntityPathLike, list[ComponentBatchLike]] = {}, @@ -171,8 +171,8 @@ def __init__( *args: Container | SpaceView, contents: Optional[Iterable[Container | SpaceView]] = None, kind: ContainerKindLike, - column_shares: Optional[ColumnShareArrayLike] = None, - row_shares: Optional[RowShareArrayLike] = None, + column_shares: Optional[Float32ArrayLike] = None, + row_shares: Optional[Float32ArrayLike] = None, grid_columns: Optional[int] = None, active_tab: Optional[int | str] = None, name: Utf8Like | None, diff --git a/rerun_py/rerun_sdk/rerun/blueprint/archetypes/container_blueprint.py b/rerun_py/rerun_sdk/rerun/blueprint/archetypes/container_blueprint.py index d568a92fd1ab..84135d1ca638 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/archetypes/container_blueprint.py +++ b/rerun_py/rerun_sdk/rerun/blueprint/archetypes/container_blueprint.py @@ -29,11 +29,11 @@ def __init__( *, display_name: datatypes.Utf8Like | None = None, contents: datatypes.EntityPathArrayLike | None = None, - col_shares: blueprint_components.ColumnShareArrayLike | None = None, - row_shares: blueprint_components.RowShareArrayLike | None = None, + col_shares: datatypes.Float32ArrayLike | None = None, + row_shares: datatypes.Float32ArrayLike | None = None, active_tab: datatypes.EntityPathLike | None = None, - visible: blueprint_components.VisibleLike | None = None, - grid_columns: blueprint_components.GridColumnsLike | None = None, + visible: datatypes.BoolLike | None = None, + grid_columns: datatypes.UInt32Like | None = None, ): """ Create a new instance of the ContainerBlueprint archetype. diff --git a/rerun_py/rerun_sdk/rerun/blueprint/archetypes/plot_legend_ext.py b/rerun_py/rerun_sdk/rerun/blueprint/archetypes/plot_legend_ext.py index e955aab70751..eba8f8b23e35 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/archetypes/plot_legend_ext.py +++ b/rerun_py/rerun_sdk/rerun/blueprint/archetypes/plot_legend_ext.py @@ -2,6 +2,8 @@ from typing import Any +from rerun.datatypes.bool import BoolLike + from ...blueprint import components as blueprint_components from ...error_utils import catch_and_log_exceptions @@ -13,7 +15,7 @@ def __init__( self: Any, corner: blueprint_components.Corner2DLike | None = None, *, - visible: blueprint_components.VisibleLike | None = None, + visible: BoolLike | None = None, ): """ Create a new instance of the PlotLegend archetype. diff --git a/rerun_py/rerun_sdk/rerun/blueprint/archetypes/space_view_blueprint.py b/rerun_py/rerun_sdk/rerun/blueprint/archetypes/space_view_blueprint.py index ac37f7b52acf..906c28072507 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/archetypes/space_view_blueprint.py +++ b/rerun_py/rerun_sdk/rerun/blueprint/archetypes/space_view_blueprint.py @@ -29,7 +29,7 @@ def __init__( *, display_name: datatypes.Utf8Like | None = None, space_origin: datatypes.EntityPathLike | None = None, - visible: blueprint_components.VisibleLike | None = None, + visible: datatypes.BoolLike | None = None, ): """ Create a new instance of the SpaceViewBlueprint archetype. diff --git a/rerun_py/rerun_sdk/rerun/blueprint/archetypes/viewport_blueprint.py b/rerun_py/rerun_sdk/rerun/blueprint/archetypes/viewport_blueprint.py index 09dde9a707dc..fe93ef5dc118 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/archetypes/viewport_blueprint.py +++ b/rerun_py/rerun_sdk/rerun/blueprint/archetypes/viewport_blueprint.py @@ -28,8 +28,8 @@ def __init__( *, root_container: datatypes.UuidLike | None = None, maximized: datatypes.UuidLike | None = None, - auto_layout: blueprint_components.AutoLayoutLike | None = None, - auto_space_views: blueprint_components.AutoSpaceViewsLike | None = None, + auto_layout: datatypes.BoolLike | None = None, + auto_space_views: datatypes.BoolLike | None = None, past_viewer_recommendations: datatypes.UInt64ArrayLike | None = None, ): """ diff --git a/rerun_py/rerun_sdk/rerun/blueprint/components/__init__.py b/rerun_py/rerun_sdk/rerun/blueprint/components/__init__.py index 14b26d8af6d7..10f98717719d 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/components/__init__.py +++ b/rerun_py/rerun_sdk/rerun/blueprint/components/__init__.py @@ -3,14 +3,8 @@ from __future__ import annotations from .active_tab import ActiveTab, ActiveTabBatch, ActiveTabType -from .auto_layout import AutoLayout, AutoLayoutArrayLike, AutoLayoutBatch, AutoLayoutLike, AutoLayoutType -from .auto_space_views import ( - AutoSpaceViews, - AutoSpaceViewsArrayLike, - AutoSpaceViewsBatch, - AutoSpaceViewsLike, - AutoSpaceViewsType, -) +from .auto_layout import AutoLayout, AutoLayoutBatch, AutoLayoutType +from .auto_space_views import AutoSpaceViews, AutoSpaceViewsBatch, AutoSpaceViewsType from .background_kind import ( BackgroundKind, BackgroundKindArrayLike, @@ -18,7 +12,7 @@ BackgroundKindLike, BackgroundKindType, ) -from .column_share import ColumnShare, ColumnShareArrayLike, ColumnShareBatch, ColumnShareLike, ColumnShareType +from .column_share import ColumnShare, ColumnShareBatch, ColumnShareType from .container_kind import ( ContainerKind, ContainerKindArrayLike, @@ -27,7 +21,7 @@ ContainerKindType, ) from .corner2d import Corner2D, Corner2DArrayLike, Corner2DBatch, Corner2DLike, Corner2DType -from .grid_columns import GridColumns, GridColumnsArrayLike, GridColumnsBatch, GridColumnsLike, GridColumnsType +from .grid_columns import GridColumns, GridColumnsBatch, GridColumnsType from .included_content import IncludedContent, IncludedContentBatch, IncludedContentType from .included_space_view import IncludedSpaceView, IncludedSpaceViewBatch, IncludedSpaceViewType from .interactive import Interactive, InteractiveBatch, InteractiveType @@ -35,7 +29,7 @@ from .panel_state import PanelState, PanelStateArrayLike, PanelStateBatch, PanelStateLike, PanelStateType from .query_expression import QueryExpression, QueryExpressionBatch, QueryExpressionType from .root_container import RootContainer, RootContainerBatch, RootContainerType -from .row_share import RowShare, RowShareArrayLike, RowShareBatch, RowShareLike, RowShareType +from .row_share import RowShare, RowShareBatch, RowShareType from .space_view_class import SpaceViewClass, SpaceViewClassBatch, SpaceViewClassType from .space_view_maximized import SpaceViewMaximized, SpaceViewMaximizedBatch, SpaceViewMaximizedType from .space_view_origin import SpaceViewOrigin, SpaceViewOriginBatch, SpaceViewOriginType @@ -50,30 +44,20 @@ ViewerRecommendationHashBatch, ViewerRecommendationHashType, ) -from .visible import Visible, VisibleArrayLike, VisibleBatch, VisibleLike, VisibleType +from .visible import Visible, VisibleBatch, VisibleType from .visible_time_range import VisibleTimeRange, VisibleTimeRangeBatch, VisibleTimeRangeType from .visual_bounds2d import VisualBounds2D, VisualBounds2DBatch, VisualBounds2DType -from .visualizer_overrides import ( - VisualizerOverrides, - VisualizerOverridesArrayLike, - VisualizerOverridesBatch, - VisualizerOverridesLike, - VisualizerOverridesType, -) +from .visualizer_overrides import VisualizerOverrides, VisualizerOverridesBatch, VisualizerOverridesType __all__ = [ "ActiveTab", "ActiveTabBatch", "ActiveTabType", "AutoLayout", - "AutoLayoutArrayLike", "AutoLayoutBatch", - "AutoLayoutLike", "AutoLayoutType", "AutoSpaceViews", - "AutoSpaceViewsArrayLike", "AutoSpaceViewsBatch", - "AutoSpaceViewsLike", "AutoSpaceViewsType", "BackgroundKind", "BackgroundKindArrayLike", @@ -81,9 +65,7 @@ "BackgroundKindLike", "BackgroundKindType", "ColumnShare", - "ColumnShareArrayLike", "ColumnShareBatch", - "ColumnShareLike", "ColumnShareType", "ContainerKind", "ContainerKindArrayLike", @@ -96,9 +78,7 @@ "Corner2DLike", "Corner2DType", "GridColumns", - "GridColumnsArrayLike", "GridColumnsBatch", - "GridColumnsLike", "GridColumnsType", "IncludedContent", "IncludedContentBatch", @@ -124,9 +104,7 @@ "RootContainerBatch", "RootContainerType", "RowShare", - "RowShareArrayLike", "RowShareBatch", - "RowShareLike", "RowShareType", "SpaceViewClass", "SpaceViewClassBatch", @@ -149,9 +127,7 @@ "ViewerRecommendationHashBatch", "ViewerRecommendationHashType", "Visible", - "VisibleArrayLike", "VisibleBatch", - "VisibleLike", "VisibleTimeRange", "VisibleTimeRangeBatch", "VisibleTimeRangeType", @@ -160,8 +136,6 @@ "VisualBounds2DBatch", "VisualBounds2DType", "VisualizerOverrides", - "VisualizerOverridesArrayLike", "VisualizerOverridesBatch", - "VisualizerOverridesLike", "VisualizerOverridesType", ] diff --git a/rerun_py/rerun_sdk/rerun/blueprint/components/auto_layout.py b/rerun_py/rerun_sdk/rerun/blueprint/components/auto_layout.py index 9d28dd2ca925..ca09af6e7921 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/components/auto_layout.py +++ b/rerun_py/rerun_sdk/rerun/blueprint/components/auto_layout.py @@ -5,66 +5,32 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Sequence, Union - -import numpy as np -import pyarrow as pa -from attrs import define, field - +from ... import datatypes from ..._baseclasses import ( - BaseBatch, - BaseExtensionType, ComponentBatchMixin, ComponentMixin, ) -__all__ = ["AutoLayout", "AutoLayoutArrayLike", "AutoLayoutBatch", "AutoLayoutLike", "AutoLayoutType"] +__all__ = ["AutoLayout", "AutoLayoutBatch", "AutoLayoutType"] -@define(init=False) -class AutoLayout(ComponentMixin): +class AutoLayout(datatypes.Bool, ComponentMixin): """**Component**: Whether the viewport layout is determined automatically.""" _BATCH_TYPE = None + # You can define your own __init__ function as a member of AutoLayoutExt in auto_layout_ext.py - def __init__(self: Any, auto_layout: AutoLayoutLike): - """Create a new instance of the AutoLayout component.""" - - # You can define your own __init__ function as a member of AutoLayoutExt in auto_layout_ext.py - self.__attrs_init__(auto_layout=auto_layout) - - def __bool__(self) -> bool: - return self.auto_layout - - auto_layout: bool = field(converter=bool) + # Note: there are no fields here because AutoLayout delegates to datatypes.Bool + pass -if TYPE_CHECKING: - AutoLayoutLike = Union[AutoLayout, bool] -else: - AutoLayoutLike = Any - -AutoLayoutArrayLike = Union[ - AutoLayout, - Sequence[AutoLayoutLike], -] - - -class AutoLayoutType(BaseExtensionType): +class AutoLayoutType(datatypes.BoolType): _TYPE_NAME: str = "rerun.blueprint.components.AutoLayout" - def __init__(self) -> None: - pa.ExtensionType.__init__(self, pa.bool_(), self._TYPE_NAME) - -class AutoLayoutBatch(BaseBatch[AutoLayoutArrayLike], ComponentBatchMixin): +class AutoLayoutBatch(datatypes.BoolBatch, ComponentBatchMixin): _ARROW_TYPE = AutoLayoutType() - @staticmethod - def _native_to_pa_array(data: AutoLayoutArrayLike, data_type: pa.DataType) -> pa.Array: - array = np.asarray(data, dtype=np.bool_).flatten() - return pa.array(array, type=data_type) - # This is patched in late to avoid circular dependencies. AutoLayout._BATCH_TYPE = AutoLayoutBatch # type: ignore[assignment] diff --git a/rerun_py/rerun_sdk/rerun/blueprint/components/auto_space_views.py b/rerun_py/rerun_sdk/rerun/blueprint/components/auto_space_views.py index e676ecf508e5..239c5f510b28 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/components/auto_space_views.py +++ b/rerun_py/rerun_sdk/rerun/blueprint/components/auto_space_views.py @@ -5,72 +5,32 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Sequence, Union - -import numpy as np -import pyarrow as pa -from attrs import define, field - +from ... import datatypes from ..._baseclasses import ( - BaseBatch, - BaseExtensionType, ComponentBatchMixin, ComponentMixin, ) -__all__ = [ - "AutoSpaceViews", - "AutoSpaceViewsArrayLike", - "AutoSpaceViewsBatch", - "AutoSpaceViewsLike", - "AutoSpaceViewsType", -] +__all__ = ["AutoSpaceViews", "AutoSpaceViewsBatch", "AutoSpaceViewsType"] -@define(init=False) -class AutoSpaceViews(ComponentMixin): +class AutoSpaceViews(datatypes.Bool, ComponentMixin): """**Component**: Whether or not space views should be created automatically.""" _BATCH_TYPE = None + # You can define your own __init__ function as a member of AutoSpaceViewsExt in auto_space_views_ext.py - def __init__(self: Any, auto_space_views: AutoSpaceViewsLike): - """Create a new instance of the AutoSpaceViews component.""" - - # You can define your own __init__ function as a member of AutoSpaceViewsExt in auto_space_views_ext.py - self.__attrs_init__(auto_space_views=auto_space_views) - - def __bool__(self) -> bool: - return self.auto_space_views - - auto_space_views: bool = field(converter=bool) + # Note: there are no fields here because AutoSpaceViews delegates to datatypes.Bool + pass -if TYPE_CHECKING: - AutoSpaceViewsLike = Union[AutoSpaceViews, bool] -else: - AutoSpaceViewsLike = Any - -AutoSpaceViewsArrayLike = Union[ - AutoSpaceViews, - Sequence[AutoSpaceViewsLike], -] - - -class AutoSpaceViewsType(BaseExtensionType): +class AutoSpaceViewsType(datatypes.BoolType): _TYPE_NAME: str = "rerun.blueprint.components.AutoSpaceViews" - def __init__(self) -> None: - pa.ExtensionType.__init__(self, pa.bool_(), self._TYPE_NAME) - -class AutoSpaceViewsBatch(BaseBatch[AutoSpaceViewsArrayLike], ComponentBatchMixin): +class AutoSpaceViewsBatch(datatypes.BoolBatch, ComponentBatchMixin): _ARROW_TYPE = AutoSpaceViewsType() - @staticmethod - def _native_to_pa_array(data: AutoSpaceViewsArrayLike, data_type: pa.DataType) -> pa.Array: - array = np.asarray(data, dtype=np.bool_).flatten() - return pa.array(array, type=data_type) - # This is patched in late to avoid circular dependencies. AutoSpaceViews._BATCH_TYPE = AutoSpaceViewsBatch # type: ignore[assignment] diff --git a/rerun_py/rerun_sdk/rerun/blueprint/components/column_share.py b/rerun_py/rerun_sdk/rerun/blueprint/components/column_share.py index 7e410b77ebe6..48988da5a7d9 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/components/column_share.py +++ b/rerun_py/rerun_sdk/rerun/blueprint/components/column_share.py @@ -5,82 +5,32 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Sequence, Union - -import numpy as np -import numpy.typing as npt -import pyarrow as pa -from attrs import define, field - +from ... import datatypes from ..._baseclasses import ( - BaseBatch, - BaseExtensionType, ComponentBatchMixin, ComponentMixin, ) -__all__ = ["ColumnShare", "ColumnShareArrayLike", "ColumnShareBatch", "ColumnShareLike", "ColumnShareType"] +__all__ = ["ColumnShare", "ColumnShareBatch", "ColumnShareType"] -@define(init=False) -class ColumnShare(ComponentMixin): +class ColumnShare(datatypes.Float32, ComponentMixin): """**Component**: The layout share of a column in the container.""" _BATCH_TYPE = None + # You can define your own __init__ function as a member of ColumnShareExt in column_share_ext.py - def __init__(self: Any, share: ColumnShareLike): - """ - Create a new instance of the ColumnShare component. - - Parameters - ---------- - share: - The layout shares of a column in the container. - - """ - - # You can define your own __init__ function as a member of ColumnShareExt in column_share_ext.py - self.__attrs_init__(share=share) - - share: float = field(converter=float) - # The layout shares of a column in the container. - # - # (Docstring intentionally commented out to hide this field from the docs) - - def __array__(self, dtype: npt.DTypeLike = None) -> npt.NDArray[Any]: - # You can define your own __array__ function as a member of ColumnShareExt in column_share_ext.py - return np.asarray(self.share, dtype=dtype) + # Note: there are no fields here because ColumnShare delegates to datatypes.Float32 + pass - def __float__(self) -> float: - return float(self.share) - def __hash__(self) -> int: - return hash(self.share) - - -if TYPE_CHECKING: - ColumnShareLike = Union[ColumnShare, float] -else: - ColumnShareLike = Any - -ColumnShareArrayLike = Union[ColumnShare, Sequence[ColumnShareLike], npt.ArrayLike] - - -class ColumnShareType(BaseExtensionType): +class ColumnShareType(datatypes.Float32Type): _TYPE_NAME: str = "rerun.blueprint.components.ColumnShare" - def __init__(self) -> None: - pa.ExtensionType.__init__(self, pa.float32(), self._TYPE_NAME) - -class ColumnShareBatch(BaseBatch[ColumnShareArrayLike], ComponentBatchMixin): +class ColumnShareBatch(datatypes.Float32Batch, ComponentBatchMixin): _ARROW_TYPE = ColumnShareType() - @staticmethod - def _native_to_pa_array(data: ColumnShareArrayLike, data_type: pa.DataType) -> pa.Array: - array = np.asarray(data, dtype=np.float32).flatten() - return pa.array(array, type=data_type) - # This is patched in late to avoid circular dependencies. ColumnShare._BATCH_TYPE = ColumnShareBatch # type: ignore[assignment] diff --git a/rerun_py/rerun_sdk/rerun/blueprint/components/grid_columns.py b/rerun_py/rerun_sdk/rerun/blueprint/components/grid_columns.py index fb3b182d7d6a..7656a0859264 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/components/grid_columns.py +++ b/rerun_py/rerun_sdk/rerun/blueprint/components/grid_columns.py @@ -5,85 +5,32 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Sequence, Union - -import numpy as np -import numpy.typing as npt -import pyarrow as pa -from attrs import define, field - +from ... import datatypes from ..._baseclasses import ( - BaseBatch, - BaseExtensionType, ComponentBatchMixin, ComponentMixin, ) -__all__ = ["GridColumns", "GridColumnsArrayLike", "GridColumnsBatch", "GridColumnsLike", "GridColumnsType"] +__all__ = ["GridColumns", "GridColumnsBatch", "GridColumnsType"] -@define(init=False) -class GridColumns(ComponentMixin): +class GridColumns(datatypes.UInt32, ComponentMixin): """**Component**: How many columns a grid container should have.""" _BATCH_TYPE = None + # You can define your own __init__ function as a member of GridColumnsExt in grid_columns_ext.py - def __init__(self: Any, columns: GridColumnsLike): - """ - Create a new instance of the GridColumns component. - - Parameters - ---------- - columns: - The number of columns. - - """ - - # You can define your own __init__ function as a member of GridColumnsExt in grid_columns_ext.py - self.__attrs_init__(columns=columns) - - columns: int = field(converter=int) - # The number of columns. - # - # (Docstring intentionally commented out to hide this field from the docs) - - def __array__(self, dtype: npt.DTypeLike = None) -> npt.NDArray[Any]: - # You can define your own __array__ function as a member of GridColumnsExt in grid_columns_ext.py - return np.asarray(self.columns, dtype=dtype) + # Note: there are no fields here because GridColumns delegates to datatypes.UInt32 + pass - def __int__(self) -> int: - return int(self.columns) - def __hash__(self) -> int: - return hash(self.columns) - - -if TYPE_CHECKING: - GridColumnsLike = Union[GridColumns, int] -else: - GridColumnsLike = Any - -GridColumnsArrayLike = Union[ - GridColumns, - Sequence[GridColumnsLike], -] - - -class GridColumnsType(BaseExtensionType): +class GridColumnsType(datatypes.UInt32Type): _TYPE_NAME: str = "rerun.blueprint.components.GridColumns" - def __init__(self) -> None: - pa.ExtensionType.__init__(self, pa.uint32(), self._TYPE_NAME) - -class GridColumnsBatch(BaseBatch[GridColumnsArrayLike], ComponentBatchMixin): +class GridColumnsBatch(datatypes.UInt32Batch, ComponentBatchMixin): _ARROW_TYPE = GridColumnsType() - @staticmethod - def _native_to_pa_array(data: GridColumnsArrayLike, data_type: pa.DataType) -> pa.Array: - array = np.asarray(data, dtype=np.uint32).flatten() - return pa.array(array, type=data_type) - # This is patched in late to avoid circular dependencies. GridColumns._BATCH_TYPE = GridColumnsBatch # type: ignore[assignment] diff --git a/rerun_py/rerun_sdk/rerun/blueprint/components/row_share.py b/rerun_py/rerun_sdk/rerun/blueprint/components/row_share.py index 7d1bdb8ebbeb..f1cdde98f0e6 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/components/row_share.py +++ b/rerun_py/rerun_sdk/rerun/blueprint/components/row_share.py @@ -5,82 +5,32 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Sequence, Union - -import numpy as np -import numpy.typing as npt -import pyarrow as pa -from attrs import define, field - +from ... import datatypes from ..._baseclasses import ( - BaseBatch, - BaseExtensionType, ComponentBatchMixin, ComponentMixin, ) -__all__ = ["RowShare", "RowShareArrayLike", "RowShareBatch", "RowShareLike", "RowShareType"] +__all__ = ["RowShare", "RowShareBatch", "RowShareType"] -@define(init=False) -class RowShare(ComponentMixin): +class RowShare(datatypes.Float32, ComponentMixin): """**Component**: The layout share of a row in the container.""" _BATCH_TYPE = None + # You can define your own __init__ function as a member of RowShareExt in row_share_ext.py - def __init__(self: Any, share: RowShareLike): - """ - Create a new instance of the RowShare component. - - Parameters - ---------- - share: - The layout share of a row in the container. - - """ - - # You can define your own __init__ function as a member of RowShareExt in row_share_ext.py - self.__attrs_init__(share=share) - - share: float = field(converter=float) - # The layout share of a row in the container. - # - # (Docstring intentionally commented out to hide this field from the docs) - - def __array__(self, dtype: npt.DTypeLike = None) -> npt.NDArray[Any]: - # You can define your own __array__ function as a member of RowShareExt in row_share_ext.py - return np.asarray(self.share, dtype=dtype) + # Note: there are no fields here because RowShare delegates to datatypes.Float32 + pass - def __float__(self) -> float: - return float(self.share) - def __hash__(self) -> int: - return hash(self.share) - - -if TYPE_CHECKING: - RowShareLike = Union[RowShare, float] -else: - RowShareLike = Any - -RowShareArrayLike = Union[RowShare, Sequence[RowShareLike], npt.ArrayLike] - - -class RowShareType(BaseExtensionType): +class RowShareType(datatypes.Float32Type): _TYPE_NAME: str = "rerun.blueprint.components.RowShare" - def __init__(self) -> None: - pa.ExtensionType.__init__(self, pa.float32(), self._TYPE_NAME) - -class RowShareBatch(BaseBatch[RowShareArrayLike], ComponentBatchMixin): +class RowShareBatch(datatypes.Float32Batch, ComponentBatchMixin): _ARROW_TYPE = RowShareType() - @staticmethod - def _native_to_pa_array(data: RowShareArrayLike, data_type: pa.DataType) -> pa.Array: - array = np.asarray(data, dtype=np.float32).flatten() - return pa.array(array, type=data_type) - # This is patched in late to avoid circular dependencies. RowShare._BATCH_TYPE = RowShareBatch # type: ignore[assignment] diff --git a/rerun_py/rerun_sdk/rerun/blueprint/components/visible.py b/rerun_py/rerun_sdk/rerun/blueprint/components/visible.py index b223beaa09c9..95d858e5c998 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/components/visible.py +++ b/rerun_py/rerun_sdk/rerun/blueprint/components/visible.py @@ -5,66 +5,32 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Sequence, Union - -import numpy as np -import pyarrow as pa -from attrs import define, field - +from ... import datatypes from ..._baseclasses import ( - BaseBatch, - BaseExtensionType, ComponentBatchMixin, ComponentMixin, ) -__all__ = ["Visible", "VisibleArrayLike", "VisibleBatch", "VisibleLike", "VisibleType"] +__all__ = ["Visible", "VisibleBatch", "VisibleType"] -@define(init=False) -class Visible(ComponentMixin): +class Visible(datatypes.Bool, ComponentMixin): """**Component**: Whether the container, view, entity or instance is currently visible.""" _BATCH_TYPE = None + # You can define your own __init__ function as a member of VisibleExt in visible_ext.py - def __init__(self: Any, visible: VisibleLike): - """Create a new instance of the Visible component.""" - - # You can define your own __init__ function as a member of VisibleExt in visible_ext.py - self.__attrs_init__(visible=visible) - - def __bool__(self) -> bool: - return self.visible - - visible: bool = field(converter=bool) + # Note: there are no fields here because Visible delegates to datatypes.Bool + pass -if TYPE_CHECKING: - VisibleLike = Union[Visible, bool] -else: - VisibleLike = Any - -VisibleArrayLike = Union[ - Visible, - Sequence[VisibleLike], -] - - -class VisibleType(BaseExtensionType): +class VisibleType(datatypes.BoolType): _TYPE_NAME: str = "rerun.blueprint.components.Visible" - def __init__(self) -> None: - pa.ExtensionType.__init__(self, pa.bool_(), self._TYPE_NAME) - -class VisibleBatch(BaseBatch[VisibleArrayLike], ComponentBatchMixin): +class VisibleBatch(datatypes.BoolBatch, ComponentBatchMixin): _ARROW_TYPE = VisibleType() - @staticmethod - def _native_to_pa_array(data: VisibleArrayLike, data_type: pa.DataType) -> pa.Array: - array = np.asarray(data, dtype=np.bool_).flatten() - return pa.array(array, type=data_type) - # This is patched in late to avoid circular dependencies. Visible._BATCH_TYPE = VisibleBatch # type: ignore[assignment] diff --git a/rerun_py/rerun_sdk/rerun/blueprint/components/visualizer_overrides.py b/rerun_py/rerun_sdk/rerun/blueprint/components/visualizer_overrides.py index 6b4e9ef76855..af736e787361 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/components/visualizer_overrides.py +++ b/rerun_py/rerun_sdk/rerun/blueprint/components/visualizer_overrides.py @@ -5,30 +5,16 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Sequence, Union - -import pyarrow as pa -from attrs import define, field - from ..._baseclasses import ( - BaseBatch, - BaseExtensionType, ComponentBatchMixin, ComponentMixin, ) -from .visualizer_overrides_ext import VisualizerOverridesExt +from ...blueprint import datatypes as blueprint_datatypes -__all__ = [ - "VisualizerOverrides", - "VisualizerOverridesArrayLike", - "VisualizerOverridesBatch", - "VisualizerOverridesLike", - "VisualizerOverridesType", -] +__all__ = ["VisualizerOverrides", "VisualizerOverridesBatch", "VisualizerOverridesType"] -@define(init=False) -class VisualizerOverrides(VisualizerOverridesExt, ComponentMixin): +class VisualizerOverrides(blueprint_datatypes.Utf8List, ComponentMixin): """ **Component**: Override the visualizers for an entity. @@ -43,98 +29,18 @@ class VisualizerOverrides(VisualizerOverridesExt, ComponentMixin): """ _BATCH_TYPE = None + # You can define your own __init__ function as a member of VisualizerOverridesExt in visualizer_overrides_ext.py - def __init__(self: Any, visualizers: VisualizerOverridesLike): - """ - Create a new instance of the VisualizerOverrides component. - - Parameters - ---------- - visualizers: - Names of the visualizers that should be active. - - The built-in visualizers are: - - BarChart - - Arrows2D - - Arrows3D - - Asset3D - - Boxes2D - - Boxes3D - - Cameras - - DepthImage - - Image - - Lines2D - - Lines3D - - Mesh3D - - Points2D - - Points3D - - Transform3DArrows - - Tensor - - TextDocument - - TextLog - - SegmentationImage - - SeriesLine - - SeriesPoint - - """ - - # You can define your own __init__ function as a member of VisualizerOverridesExt in visualizer_overrides_ext.py - self.__attrs_init__(visualizers=visualizers) - - visualizers: list[str] = field( - converter=VisualizerOverridesExt.visualizers__field_converter_override, # type: ignore[misc] - ) - # Names of the visualizers that should be active. - # - # The built-in visualizers are: - # - BarChart - # - Arrows2D - # - Arrows3D - # - Asset3D - # - Boxes2D - # - Boxes3D - # - Cameras - # - DepthImage - # - Image - # - Lines2D - # - Lines3D - # - Mesh3D - # - Points2D - # - Points3D - # - Transform3DArrows - # - Tensor - # - TextDocument - # - TextLog - # - SegmentationImage - # - SeriesLine - # - SeriesPoint - # - # (Docstring intentionally commented out to hide this field from the docs) - - -if TYPE_CHECKING: - VisualizerOverridesLike = Union[VisualizerOverrides, str, list[str]] -else: - VisualizerOverridesLike = Any - -VisualizerOverridesArrayLike = Union[VisualizerOverrides, Sequence[VisualizerOverridesLike], str] - - -class VisualizerOverridesType(BaseExtensionType): - _TYPE_NAME: str = "rerun.blueprint.components.VisualizerOverrides" + # Note: there are no fields here because VisualizerOverrides delegates to datatypes.Utf8List + pass - def __init__(self) -> None: - pa.ExtensionType.__init__( - self, pa.list_(pa.field("item", pa.utf8(), nullable=False, metadata={})), self._TYPE_NAME - ) +class VisualizerOverridesType(blueprint_datatypes.Utf8ListType): + _TYPE_NAME: str = "rerun.blueprint.components.VisualizerOverrides" -class VisualizerOverridesBatch(BaseBatch[VisualizerOverridesArrayLike], ComponentBatchMixin): - _ARROW_TYPE = VisualizerOverridesType() - @staticmethod - def _native_to_pa_array(data: VisualizerOverridesArrayLike, data_type: pa.DataType) -> pa.Array: - return VisualizerOverridesExt.native_to_pa_array_override(data, data_type) +class VisualizerOverridesBatch(blueprint_datatypes.Utf8ListBatch, ComponentBatchMixin): + _ARROW_TYPE = VisualizerOverridesType() # This is patched in late to avoid circular dependencies. diff --git a/rerun_py/rerun_sdk/rerun/blueprint/containers.py b/rerun_py/rerun_sdk/rerun/blueprint/containers.py index dc0f14b4ac31..4ca94b223e34 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/containers.py +++ b/rerun_py/rerun_sdk/rerun/blueprint/containers.py @@ -2,9 +2,8 @@ from typing import Iterable, Optional -from ..datatypes import Utf8Like +from ..datatypes import Float32ArrayLike, Utf8Like from .api import Container, SpaceView -from .components import ColumnShareArrayLike, RowShareArrayLike from .components.container_kind import ContainerKind @@ -15,7 +14,7 @@ def __init__( self, *args: Container | SpaceView, contents: Optional[Iterable[Container | SpaceView]] = None, - column_shares: Optional[ColumnShareArrayLike] = None, + column_shares: Optional[Float32ArrayLike] = None, name: Utf8Like | None = None, ): """ @@ -47,7 +46,7 @@ def __init__( self, *args: Container | SpaceView, contents: Optional[Iterable[Container | SpaceView]] = None, - row_shares: Optional[RowShareArrayLike] = None, + row_shares: Optional[Float32ArrayLike] = None, name: Utf8Like | None = None, ): """ @@ -77,8 +76,8 @@ def __init__( self, *args: Container | SpaceView, contents: Optional[Iterable[Container | SpaceView]] = None, - column_shares: Optional[ColumnShareArrayLike] = None, - row_shares: Optional[RowShareArrayLike] = None, + column_shares: Optional[Float32ArrayLike] = None, + row_shares: Optional[Float32ArrayLike] = None, grid_columns: Optional[int] = None, name: Utf8Like | None = None, ): diff --git a/rerun_py/rerun_sdk/rerun/blueprint/datatypes/.gitattributes b/rerun_py/rerun_sdk/rerun/blueprint/datatypes/.gitattributes index 7c8bc6f4d93a..8ae92d95c142 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/datatypes/.gitattributes +++ b/rerun_py/rerun_sdk/rerun/blueprint/datatypes/.gitattributes @@ -3,3 +3,4 @@ .gitattributes linguist-generated=true __init__.py linguist-generated=true tensor_dimension_index_slider.py linguist-generated=true +utf8list.py linguist-generated=true diff --git a/rerun_py/rerun_sdk/rerun/blueprint/datatypes/__init__.py b/rerun_py/rerun_sdk/rerun/blueprint/datatypes/__init__.py index b811e0b19047..929fa1b8089b 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/datatypes/__init__.py +++ b/rerun_py/rerun_sdk/rerun/blueprint/datatypes/__init__.py @@ -9,6 +9,7 @@ TensorDimensionIndexSliderLike, TensorDimensionIndexSliderType, ) +from .utf8list import Utf8List, Utf8ListArrayLike, Utf8ListBatch, Utf8ListLike, Utf8ListType __all__ = [ "TensorDimensionIndexSlider", @@ -16,4 +17,9 @@ "TensorDimensionIndexSliderBatch", "TensorDimensionIndexSliderLike", "TensorDimensionIndexSliderType", + "Utf8List", + "Utf8ListArrayLike", + "Utf8ListBatch", + "Utf8ListLike", + "Utf8ListType", ] diff --git a/rerun_py/rerun_sdk/rerun/blueprint/datatypes/utf8list.py b/rerun_py/rerun_sdk/rerun/blueprint/datatypes/utf8list.py new file mode 100644 index 000000000000..c19b42158b43 --- /dev/null +++ b/rerun_py/rerun_sdk/rerun/blueprint/datatypes/utf8list.py @@ -0,0 +1,60 @@ +# DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/python/mod.rs +# Based on "crates/store/re_types/definitions/rerun/blueprint/datatypes/utf8_list.fbs". + +# You can extend this class by creating a "Utf8ListExt" class in "utf8list_ext.py". + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Sequence, Union + +import pyarrow as pa +from attrs import define, field + +from ..._baseclasses import ( + BaseBatch, + BaseExtensionType, +) +from .utf8list_ext import Utf8ListExt + +__all__ = ["Utf8List", "Utf8ListArrayLike", "Utf8ListBatch", "Utf8ListLike", "Utf8ListType"] + + +@define(init=False) +class Utf8List(Utf8ListExt): + """**Datatype**: A list of strings of text, encoded as UTF-8.""" + + def __init__(self: Any, value: Utf8ListLike): + """Create a new instance of the Utf8List datatype.""" + + # You can define your own __init__ function as a member of Utf8ListExt in utf8list_ext.py + self.__attrs_init__(value=value) + + value: list[str] = field() + + +if TYPE_CHECKING: + Utf8ListLike = Union[Utf8List, Sequence[str]] +else: + Utf8ListLike = Any + +Utf8ListArrayLike = Union[ + Utf8List, + Sequence[Utf8ListLike], +] + + +class Utf8ListType(BaseExtensionType): + _TYPE_NAME: str = "rerun.blueprint.datatypes.Utf8List" + + def __init__(self) -> None: + pa.ExtensionType.__init__( + self, pa.list_(pa.field("item", pa.utf8(), nullable=False, metadata={})), self._TYPE_NAME + ) + + +class Utf8ListBatch(BaseBatch[Utf8ListArrayLike]): + _ARROW_TYPE = Utf8ListType() + + @staticmethod + def _native_to_pa_array(data: Utf8ListArrayLike, data_type: pa.DataType) -> pa.Array: + return Utf8ListExt.native_to_pa_array_override(data, data_type) diff --git a/rerun_py/rerun_sdk/rerun/blueprint/components/visualizer_overrides_ext.py b/rerun_py/rerun_sdk/rerun/blueprint/datatypes/utf8list_ext.py similarity index 52% rename from rerun_py/rerun_sdk/rerun/blueprint/components/visualizer_overrides_ext.py rename to rerun_py/rerun_sdk/rerun/blueprint/datatypes/utf8list_ext.py index 17e5d0201625..785e00acd7fd 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/components/visualizer_overrides_ext.py +++ b/rerun_py/rerun_sdk/rerun/blueprint/datatypes/utf8list_ext.py @@ -5,11 +5,11 @@ import pyarrow as pa if TYPE_CHECKING: - from . import VisualizerOverridesArrayLike + from . import Utf8ListArrayLike -class VisualizerOverridesExt: - """Extension for [VisualizerOverrides][rerun.blueprint.components.VisualizerOverrides].""" +class Utf8ListExt: + """Extension for [Utf8List][rerun.blueprint.datatypes.Utf8List].""" @staticmethod def visualizers__field_converter_override(value: str | list[str]) -> list[str]: @@ -18,19 +18,20 @@ def visualizers__field_converter_override(value: str | list[str]) -> list[str]: return value @staticmethod - def native_to_pa_array_override(data: VisualizerOverridesArrayLike, data_type: pa.DataType) -> pa.Array: - from . import VisualizerOverrides + def native_to_pa_array_override(data: Utf8ListArrayLike, data_type: pa.DataType) -> pa.Array: + from ..datatypes import Utf8List - if isinstance(data, VisualizerOverrides): - array = [data.visualizers] - elif isinstance(data, str): + if isinstance(data, Utf8List): + data = data.value + + if isinstance(data, str): array = [[data]] elif isinstance(data, Sequence): data = list(data) if len(data) == 0: array = [] - elif isinstance(data[0], VisualizerOverrides): - array = [datum.visualizers for datum in data] # type: ignore[union-attr] + elif isinstance(data[0], Utf8List): + array = [datum.value for datum in data] # type: ignore[union-attr] else: array = [[str(datum) for datum in data]] else: diff --git a/rerun_py/rerun_sdk/rerun/blueprint/views/bar_chart_view.py b/rerun_py/rerun_sdk/rerun/blueprint/views/bar_chart_view.py index b654288fefdf..406a1efe6ae0 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/views/bar_chart_view.py +++ b/rerun_py/rerun_sdk/rerun/blueprint/views/bar_chart_view.py @@ -8,6 +8,7 @@ __all__ = ["BarChartView"] +from ... import datatypes from ..._baseclasses import AsComponents, ComponentBatchLike from ...datatypes import EntityPathLike, Utf8Like from .. import archetypes as blueprint_archetypes, components as blueprint_components @@ -53,7 +54,7 @@ def __init__( origin: EntityPathLike = "/", contents: SpaceViewContentsLike = "$origin/**", name: Utf8Like | None = None, - visible: blueprint_components.VisibleLike | None = None, + visible: datatypes.BoolLike | None = None, defaults: list[Union[AsComponents, ComponentBatchLike]] = [], overrides: dict[EntityPathLike, list[ComponentBatchLike]] = {}, plot_legend: blueprint_archetypes.PlotLegend | blueprint_components.Corner2D | None = None, diff --git a/rerun_py/rerun_sdk/rerun/blueprint/views/spatial2d_view.py b/rerun_py/rerun_sdk/rerun/blueprint/views/spatial2d_view.py index e7c94eba9228..7da0cecfed0b 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/views/spatial2d_view.py +++ b/rerun_py/rerun_sdk/rerun/blueprint/views/spatial2d_view.py @@ -73,7 +73,7 @@ def __init__( origin: EntityPathLike = "/", contents: SpaceViewContentsLike = "$origin/**", name: Utf8Like | None = None, - visible: blueprint_components.VisibleLike | None = None, + visible: datatypes.BoolLike | None = None, defaults: list[Union[AsComponents, ComponentBatchLike]] = [], overrides: dict[EntityPathLike, list[ComponentBatchLike]] = {}, background: blueprint_archetypes.Background diff --git a/rerun_py/rerun_sdk/rerun/blueprint/views/spatial3d_view.py b/rerun_py/rerun_sdk/rerun/blueprint/views/spatial3d_view.py index 284f70286d44..f4d506f0c2a0 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/views/spatial3d_view.py +++ b/rerun_py/rerun_sdk/rerun/blueprint/views/spatial3d_view.py @@ -69,7 +69,7 @@ def __init__( origin: EntityPathLike = "/", contents: SpaceViewContentsLike = "$origin/**", name: Utf8Like | None = None, - visible: blueprint_components.VisibleLike | None = None, + visible: datatypes.BoolLike | None = None, defaults: list[Union[AsComponents, ComponentBatchLike]] = [], overrides: dict[EntityPathLike, list[ComponentBatchLike]] = {}, background: blueprint_archetypes.Background diff --git a/rerun_py/rerun_sdk/rerun/blueprint/views/tensor_view.py b/rerun_py/rerun_sdk/rerun/blueprint/views/tensor_view.py index a8f7478b37f2..60e2003af99c 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/views/tensor_view.py +++ b/rerun_py/rerun_sdk/rerun/blueprint/views/tensor_view.py @@ -8,6 +8,7 @@ __all__ = ["TensorView"] +from ... import datatypes from ..._baseclasses import AsComponents, ComponentBatchLike from ...datatypes import EntityPathLike, Utf8Like from .. import archetypes as blueprint_archetypes, components as blueprint_components @@ -76,7 +77,7 @@ def __init__( origin: EntityPathLike = "/", contents: SpaceViewContentsLike = "$origin/**", name: Utf8Like | None = None, - visible: blueprint_components.VisibleLike | None = None, + visible: datatypes.BoolLike | None = None, defaults: list[Union[AsComponents, ComponentBatchLike]] = [], overrides: dict[EntityPathLike, list[ComponentBatchLike]] = {}, slice_selection: blueprint_archetypes.TensorSliceSelection | None = None, diff --git a/rerun_py/rerun_sdk/rerun/blueprint/views/text_document_view.py b/rerun_py/rerun_sdk/rerun/blueprint/views/text_document_view.py index 2a8f2a1caa44..9ea0fc08217e 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/views/text_document_view.py +++ b/rerun_py/rerun_sdk/rerun/blueprint/views/text_document_view.py @@ -8,9 +8,9 @@ __all__ = ["TextDocumentView"] +from ... import datatypes from ..._baseclasses import AsComponents, ComponentBatchLike from ...datatypes import EntityPathLike, Utf8Like -from .. import components as blueprint_components from ..api import SpaceView, SpaceViewContentsLike @@ -92,7 +92,7 @@ def __init__( origin: EntityPathLike = "/", contents: SpaceViewContentsLike = "$origin/**", name: Utf8Like | None = None, - visible: blueprint_components.VisibleLike | None = None, + visible: datatypes.BoolLike | None = None, defaults: list[Union[AsComponents, ComponentBatchLike]] = [], overrides: dict[EntityPathLike, list[ComponentBatchLike]] = {}, ) -> None: diff --git a/rerun_py/rerun_sdk/rerun/blueprint/views/text_log_view.py b/rerun_py/rerun_sdk/rerun/blueprint/views/text_log_view.py index be95cf0e58d1..08d8fe4cc71a 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/views/text_log_view.py +++ b/rerun_py/rerun_sdk/rerun/blueprint/views/text_log_view.py @@ -8,9 +8,9 @@ __all__ = ["TextLogView"] +from ... import datatypes from ..._baseclasses import AsComponents, ComponentBatchLike from ...datatypes import EntityPathLike, Utf8Like -from .. import components as blueprint_components from ..api import SpaceView, SpaceViewContentsLike @@ -58,7 +58,7 @@ def __init__( origin: EntityPathLike = "/", contents: SpaceViewContentsLike = "$origin/**", name: Utf8Like | None = None, - visible: blueprint_components.VisibleLike | None = None, + visible: datatypes.BoolLike | None = None, defaults: list[Union[AsComponents, ComponentBatchLike]] = [], overrides: dict[EntityPathLike, list[ComponentBatchLike]] = {}, ) -> None: diff --git a/rerun_py/rerun_sdk/rerun/blueprint/views/time_series_view.py b/rerun_py/rerun_sdk/rerun/blueprint/views/time_series_view.py index 05877eae3e98..e7de0a9383ae 100644 --- a/rerun_py/rerun_sdk/rerun/blueprint/views/time_series_view.py +++ b/rerun_py/rerun_sdk/rerun/blueprint/views/time_series_view.py @@ -88,7 +88,7 @@ def __init__( origin: EntityPathLike = "/", contents: SpaceViewContentsLike = "$origin/**", name: Utf8Like | None = None, - visible: blueprint_components.VisibleLike | None = None, + visible: datatypes.BoolLike | None = None, defaults: list[Union[AsComponents, ComponentBatchLike]] = [], overrides: dict[EntityPathLike, list[ComponentBatchLike]] = {}, axis_y: blueprint_archetypes.ScalarAxis | None = None, diff --git a/rerun_py/rerun_sdk/rerun/components/__init__.py b/rerun_py/rerun_sdk/rerun/components/__init__.py index 54e493b75d7a..726bd0c09c7a 100644 --- a/rerun_py/rerun_sdk/rerun/components/__init__.py +++ b/rerun_py/rerun_sdk/rerun/components/__init__.py @@ -17,26 +17,14 @@ AnnotationContextType, ) from .axis_length import AxisLength, AxisLengthBatch, AxisLengthType -from .blob import Blob, BlobArrayLike, BlobBatch, BlobLike, BlobType +from .blob import Blob, BlobBatch, BlobType from .class_id import ClassId, ClassIdBatch, ClassIdType -from .clear_is_recursive import ( - ClearIsRecursive, - ClearIsRecursiveArrayLike, - ClearIsRecursiveBatch, - ClearIsRecursiveLike, - ClearIsRecursiveType, -) +from .clear_is_recursive import ClearIsRecursive, ClearIsRecursiveBatch, ClearIsRecursiveType from .color import Color, ColorBatch, ColorType from .colormap import Colormap, ColormapArrayLike, ColormapBatch, ColormapLike, ColormapType -from .depth_meter import DepthMeter, DepthMeterArrayLike, DepthMeterBatch, DepthMeterLike, DepthMeterType -from .disconnected_space import ( - DisconnectedSpace, - DisconnectedSpaceArrayLike, - DisconnectedSpaceBatch, - DisconnectedSpaceLike, - DisconnectedSpaceType, -) -from .draw_order import DrawOrder, DrawOrderArrayLike, DrawOrderBatch, DrawOrderLike, DrawOrderType +from .depth_meter import DepthMeter, DepthMeterBatch, DepthMeterType +from .disconnected_space import DisconnectedSpace, DisconnectedSpaceBatch, DisconnectedSpaceType +from .draw_order import DrawOrder, DrawOrderBatch, DrawOrderType from .fill_ratio import FillRatio, FillRatioBatch, FillRatioType from .gamma_correction import GammaCorrection, GammaCorrectionBatch, GammaCorrectionType from .half_size2d import HalfSize2D, HalfSize2DBatch, HalfSize2DType @@ -53,7 +41,7 @@ MagnificationFilterType, ) from .marker_shape import MarkerShape, MarkerShapeArrayLike, MarkerShapeBatch, MarkerShapeLike, MarkerShapeType -from .marker_size import MarkerSize, MarkerSizeArrayLike, MarkerSizeBatch, MarkerSizeLike, MarkerSizeType +from .marker_size import MarkerSize, MarkerSizeBatch, MarkerSizeType from .material import Material, MaterialBatch, MaterialType from .media_type import MediaType, MediaTypeBatch, MediaTypeType from .name import Name, NameBatch, NameType @@ -62,12 +50,12 @@ from .pinhole_projection import PinholeProjection, PinholeProjectionBatch, PinholeProjectionType from .position2d import Position2D, Position2DBatch, Position2DType from .position3d import Position3D, Position3DBatch, Position3DType -from .radius import Radius, RadiusArrayLike, RadiusBatch, RadiusLike, RadiusType +from .radius import Radius, RadiusBatch, RadiusType from .range1d import Range1D, Range1DBatch, Range1DType from .resolution import Resolution, ResolutionBatch, ResolutionType from .rotation3d import Rotation3D, Rotation3DBatch, Rotation3DType -from .scalar import Scalar, ScalarArrayLike, ScalarBatch, ScalarLike, ScalarType -from .stroke_width import StrokeWidth, StrokeWidthArrayLike, StrokeWidthBatch, StrokeWidthLike, StrokeWidthType +from .scalar import Scalar, ScalarBatch, ScalarType +from .stroke_width import StrokeWidth, StrokeWidthBatch, StrokeWidthType from .tensor_data import TensorData, TensorDataBatch, TensorDataType from .tensor_dimension_index_selection import ( TensorDimensionIndexSelection, @@ -83,13 +71,7 @@ from .triangle_indices import TriangleIndices, TriangleIndicesBatch, TriangleIndicesType from .vector2d import Vector2D, Vector2DBatch, Vector2DType from .vector3d import Vector3D, Vector3DBatch, Vector3DType -from .view_coordinates import ( - ViewCoordinates, - ViewCoordinatesArrayLike, - ViewCoordinatesBatch, - ViewCoordinatesLike, - ViewCoordinatesType, -) +from .view_coordinates import ViewCoordinates, ViewCoordinatesBatch, ViewCoordinatesType __all__ = [ "AggregationPolicy", @@ -106,17 +88,13 @@ "AxisLengthBatch", "AxisLengthType", "Blob", - "BlobArrayLike", "BlobBatch", - "BlobLike", "BlobType", "ClassId", "ClassIdBatch", "ClassIdType", "ClearIsRecursive", - "ClearIsRecursiveArrayLike", "ClearIsRecursiveBatch", - "ClearIsRecursiveLike", "ClearIsRecursiveType", "Color", "ColorBatch", @@ -127,19 +105,13 @@ "ColormapLike", "ColormapType", "DepthMeter", - "DepthMeterArrayLike", "DepthMeterBatch", - "DepthMeterLike", "DepthMeterType", "DisconnectedSpace", - "DisconnectedSpaceArrayLike", "DisconnectedSpaceBatch", - "DisconnectedSpaceLike", "DisconnectedSpaceType", "DrawOrder", - "DrawOrderArrayLike", "DrawOrderBatch", - "DrawOrderLike", "DrawOrderType", "FillRatio", "FillRatioBatch", @@ -180,9 +152,7 @@ "MarkerShapeLike", "MarkerShapeType", "MarkerSize", - "MarkerSizeArrayLike", "MarkerSizeBatch", - "MarkerSizeLike", "MarkerSizeType", "Material", "MaterialBatch", @@ -209,9 +179,7 @@ "Position3DBatch", "Position3DType", "Radius", - "RadiusArrayLike", "RadiusBatch", - "RadiusLike", "RadiusType", "Range1D", "Range1DBatch", @@ -223,14 +191,10 @@ "Rotation3DBatch", "Rotation3DType", "Scalar", - "ScalarArrayLike", "ScalarBatch", - "ScalarLike", "ScalarType", "StrokeWidth", - "StrokeWidthArrayLike", "StrokeWidthBatch", - "StrokeWidthLike", "StrokeWidthType", "TensorData", "TensorDataBatch", @@ -266,8 +230,6 @@ "Vector3DBatch", "Vector3DType", "ViewCoordinates", - "ViewCoordinatesArrayLike", "ViewCoordinatesBatch", - "ViewCoordinatesLike", "ViewCoordinatesType", ] diff --git a/rerun_py/rerun_sdk/rerun/components/blob.py b/rerun_py/rerun_sdk/rerun/components/blob.py index 1a94ee467162..6d5409cf06f5 100644 --- a/rerun_py/rerun_sdk/rerun/components/blob.py +++ b/rerun_py/rerun_sdk/rerun/components/blob.py @@ -5,70 +5,32 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Sequence, Union - -import numpy as np -import numpy.typing as npt -import pyarrow as pa -from attrs import define, field - +from .. import datatypes from .._baseclasses import ( - BaseBatch, - BaseExtensionType, ComponentBatchMixin, ComponentMixin, ) -from .._converters import ( - to_np_uint8, -) -from .blob_ext import BlobExt -__all__ = ["Blob", "BlobArrayLike", "BlobBatch", "BlobLike", "BlobType"] +__all__ = ["Blob", "BlobBatch", "BlobType"] -@define(init=False) -class Blob(BlobExt, ComponentMixin): +class Blob(datatypes.Blob, ComponentMixin): """**Component**: A binary blob of data.""" _BATCH_TYPE = None + # You can define your own __init__ function as a member of BlobExt in blob_ext.py - def __init__(self: Any, data: BlobLike): - """Create a new instance of the Blob component.""" - - # You can define your own __init__ function as a member of BlobExt in blob_ext.py - self.__attrs_init__(data=data) - - data: npt.NDArray[np.uint8] = field(converter=to_np_uint8) - - def __array__(self, dtype: npt.DTypeLike = None) -> npt.NDArray[Any]: - # You can define your own __array__ function as a member of BlobExt in blob_ext.py - return np.asarray(self.data, dtype=dtype) + # Note: there are no fields here because Blob delegates to datatypes.Blob + pass -if TYPE_CHECKING: - BlobLike = Union[Blob, bytes, npt.NDArray[np.uint8]] -else: - BlobLike = Any - -BlobArrayLike = Union[Blob, Sequence[BlobLike], bytes, npt.NDArray[np.uint8]] - - -class BlobType(BaseExtensionType): +class BlobType(datatypes.BlobType): _TYPE_NAME: str = "rerun.components.Blob" - def __init__(self) -> None: - pa.ExtensionType.__init__( - self, pa.list_(pa.field("item", pa.uint8(), nullable=False, metadata={})), self._TYPE_NAME - ) - -class BlobBatch(BaseBatch[BlobArrayLike], ComponentBatchMixin): +class BlobBatch(datatypes.BlobBatch, ComponentBatchMixin): _ARROW_TYPE = BlobType() - @staticmethod - def _native_to_pa_array(data: BlobArrayLike, data_type: pa.DataType) -> pa.Array: - return BlobExt.native_to_pa_array_override(data, data_type) - # This is patched in late to avoid circular dependencies. Blob._BATCH_TYPE = BlobBatch # type: ignore[assignment] diff --git a/rerun_py/rerun_sdk/rerun/components/clear_is_recursive.py b/rerun_py/rerun_sdk/rerun/components/clear_is_recursive.py index adfd98abb2f6..300bf73b76d7 100644 --- a/rerun_py/rerun_sdk/rerun/components/clear_is_recursive.py +++ b/rerun_py/rerun_sdk/rerun/components/clear_is_recursive.py @@ -5,81 +5,33 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Sequence, Union - -import numpy as np -import numpy.typing as npt -import pyarrow as pa -from attrs import define, field - +from .. import datatypes from .._baseclasses import ( - BaseBatch, - BaseExtensionType, ComponentBatchMixin, ComponentMixin, ) +from .clear_is_recursive_ext import ClearIsRecursiveExt -__all__ = [ - "ClearIsRecursive", - "ClearIsRecursiveArrayLike", - "ClearIsRecursiveBatch", - "ClearIsRecursiveLike", - "ClearIsRecursiveType", -] +__all__ = ["ClearIsRecursive", "ClearIsRecursiveBatch", "ClearIsRecursiveType"] -@define(init=False) -class ClearIsRecursive(ComponentMixin): +class ClearIsRecursive(ClearIsRecursiveExt, datatypes.Bool, ComponentMixin): """**Component**: Configures how a clear operation should behave - recursive or not.""" _BATCH_TYPE = None + # __init__ can be found in clear_is_recursive_ext.py - def __init__(self: Any, recursive: ClearIsRecursiveLike): - """ - Create a new instance of the ClearIsRecursive component. - - Parameters - ---------- - recursive: - If true, also clears all recursive children entities. - - """ - - # You can define your own __init__ function as a member of ClearIsRecursiveExt in clear_is_recursive_ext.py - self.__attrs_init__(recursive=recursive) - - def __bool__(self) -> bool: - return self.recursive + # Note: there are no fields here because ClearIsRecursive delegates to datatypes.Bool + pass - recursive: bool = field(converter=bool) - # If true, also clears all recursive children entities. - # - # (Docstring intentionally commented out to hide this field from the docs) - -if TYPE_CHECKING: - ClearIsRecursiveLike = Union[ClearIsRecursive, bool] -else: - ClearIsRecursiveLike = Any - -ClearIsRecursiveArrayLike = Union[ClearIsRecursive, Sequence[ClearIsRecursiveLike], bool, npt.NDArray[np.bool_]] - - -class ClearIsRecursiveType(BaseExtensionType): +class ClearIsRecursiveType(datatypes.BoolType): _TYPE_NAME: str = "rerun.components.ClearIsRecursive" - def __init__(self) -> None: - pa.ExtensionType.__init__(self, pa.bool_(), self._TYPE_NAME) - -class ClearIsRecursiveBatch(BaseBatch[ClearIsRecursiveArrayLike], ComponentBatchMixin): +class ClearIsRecursiveBatch(datatypes.BoolBatch, ComponentBatchMixin): _ARROW_TYPE = ClearIsRecursiveType() - @staticmethod - def _native_to_pa_array(data: ClearIsRecursiveArrayLike, data_type: pa.DataType) -> pa.Array: - array = np.asarray(data, dtype=np.bool_).flatten() - return pa.array(array, type=data_type) - # This is patched in late to avoid circular dependencies. ClearIsRecursive._BATCH_TYPE = ClearIsRecursiveBatch # type: ignore[assignment] diff --git a/rerun_py/rerun_sdk/rerun/components/clear_is_recursive_ext.py b/rerun_py/rerun_sdk/rerun/components/clear_is_recursive_ext.py new file mode 100644 index 000000000000..737aeab539f1 --- /dev/null +++ b/rerun_py/rerun_sdk/rerun/components/clear_is_recursive_ext.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +from typing import Any + + +class ClearIsRecursiveExt: + """Extension for [ClearIsRecursive][rerun.components.ClearIsRecursive].""" + + def __init__( + self: Any, + recursive: bool = True, + ): + """ + Disconnect an entity from its parent. + + Parameters + ---------- + recursive: + If true, also clears all recursive children entities. + + """ + self.__attrs_init__(recursive) diff --git a/rerun_py/rerun_sdk/rerun/components/depth_meter.py b/rerun_py/rerun_sdk/rerun/components/depth_meter.py index fe931f6719c1..91c65fe21604 100644 --- a/rerun_py/rerun_sdk/rerun/components/depth_meter.py +++ b/rerun_py/rerun_sdk/rerun/components/depth_meter.py @@ -5,25 +5,16 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Sequence, Union - -import numpy as np -import numpy.typing as npt -import pyarrow as pa -from attrs import define, field - +from .. import datatypes from .._baseclasses import ( - BaseBatch, - BaseExtensionType, ComponentBatchMixin, ComponentMixin, ) -__all__ = ["DepthMeter", "DepthMeterArrayLike", "DepthMeterBatch", "DepthMeterLike", "DepthMeterType"] +__all__ = ["DepthMeter", "DepthMeterBatch", "DepthMeterType"] -@define(init=False) -class DepthMeter(ComponentMixin): +class DepthMeter(datatypes.Float32, ComponentMixin): """ **Component**: The world->depth map scaling factor. @@ -36,49 +27,19 @@ class DepthMeter(ComponentMixin): """ _BATCH_TYPE = None + # You can define your own __init__ function as a member of DepthMeterExt in depth_meter_ext.py - def __init__(self: Any, value: DepthMeterLike): - """Create a new instance of the DepthMeter component.""" - - # You can define your own __init__ function as a member of DepthMeterExt in depth_meter_ext.py - self.__attrs_init__(value=value) - - value: float = field(converter=float) - - def __array__(self, dtype: npt.DTypeLike = None) -> npt.NDArray[Any]: - # You can define your own __array__ function as a member of DepthMeterExt in depth_meter_ext.py - return np.asarray(self.value, dtype=dtype) - - def __float__(self) -> float: - return float(self.value) + # Note: there are no fields here because DepthMeter delegates to datatypes.Float32 + pass - def __hash__(self) -> int: - return hash(self.value) - -if TYPE_CHECKING: - DepthMeterLike = Union[DepthMeter, float] -else: - DepthMeterLike = Any - -DepthMeterArrayLike = Union[DepthMeter, Sequence[DepthMeterLike], float, npt.NDArray[np.float32]] - - -class DepthMeterType(BaseExtensionType): +class DepthMeterType(datatypes.Float32Type): _TYPE_NAME: str = "rerun.components.DepthMeter" - def __init__(self) -> None: - pa.ExtensionType.__init__(self, pa.float32(), self._TYPE_NAME) - -class DepthMeterBatch(BaseBatch[DepthMeterArrayLike], ComponentBatchMixin): +class DepthMeterBatch(datatypes.Float32Batch, ComponentBatchMixin): _ARROW_TYPE = DepthMeterType() - @staticmethod - def _native_to_pa_array(data: DepthMeterArrayLike, data_type: pa.DataType) -> pa.Array: - array = np.asarray(data, dtype=np.float32).flatten() - return pa.array(array, type=data_type) - # This is patched in late to avoid circular dependencies. DepthMeter._BATCH_TYPE = DepthMeterBatch # type: ignore[assignment] diff --git a/rerun_py/rerun_sdk/rerun/components/disconnected_space.py b/rerun_py/rerun_sdk/rerun/components/disconnected_space.py index 1cf2c35dd730..0c7a7003b6ab 100644 --- a/rerun_py/rerun_sdk/rerun/components/disconnected_space.py +++ b/rerun_py/rerun_sdk/rerun/components/disconnected_space.py @@ -5,32 +5,17 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Sequence, Union - -import numpy as np -import numpy.typing as npt -import pyarrow as pa -from attrs import define, field - +from .. import datatypes from .._baseclasses import ( - BaseBatch, - BaseExtensionType, ComponentBatchMixin, ComponentMixin, ) from .disconnected_space_ext import DisconnectedSpaceExt -__all__ = [ - "DisconnectedSpace", - "DisconnectedSpaceArrayLike", - "DisconnectedSpaceBatch", - "DisconnectedSpaceLike", - "DisconnectedSpaceType", -] +__all__ = ["DisconnectedSpace", "DisconnectedSpaceBatch", "DisconnectedSpaceType"] -@define(init=False) -class DisconnectedSpace(DisconnectedSpaceExt, ComponentMixin): +class DisconnectedSpace(DisconnectedSpaceExt, datatypes.Bool, ComponentMixin): """ **Component**: Spatially disconnect this entity from its parent. @@ -43,41 +28,17 @@ class DisconnectedSpace(DisconnectedSpaceExt, ComponentMixin): _BATCH_TYPE = None # __init__ can be found in disconnected_space_ext.py - def __bool__(self) -> bool: - return self.is_disconnected - - is_disconnected: bool = field(converter=bool) - # Whether the entity path at which this is logged is disconnected from its parent. - # - # Set to true to disconnect the entity from its parent. - # Set to false to disable the effects of this component, (re-)connecting the entity to its parent again. - # - # (Docstring intentionally commented out to hide this field from the docs) - + # Note: there are no fields here because DisconnectedSpace delegates to datatypes.Bool + pass -if TYPE_CHECKING: - DisconnectedSpaceLike = Union[DisconnectedSpace, bool] -else: - DisconnectedSpaceLike = Any -DisconnectedSpaceArrayLike = Union[DisconnectedSpace, Sequence[DisconnectedSpaceLike], bool, npt.NDArray[np.bool_]] - - -class DisconnectedSpaceType(BaseExtensionType): +class DisconnectedSpaceType(datatypes.BoolType): _TYPE_NAME: str = "rerun.components.DisconnectedSpace" - def __init__(self) -> None: - pa.ExtensionType.__init__(self, pa.bool_(), self._TYPE_NAME) - -class DisconnectedSpaceBatch(BaseBatch[DisconnectedSpaceArrayLike], ComponentBatchMixin): +class DisconnectedSpaceBatch(datatypes.BoolBatch, ComponentBatchMixin): _ARROW_TYPE = DisconnectedSpaceType() - @staticmethod - def _native_to_pa_array(data: DisconnectedSpaceArrayLike, data_type: pa.DataType) -> pa.Array: - array = np.asarray(data, dtype=np.bool_).flatten() - return pa.array(array, type=data_type) - # This is patched in late to avoid circular dependencies. DisconnectedSpace._BATCH_TYPE = DisconnectedSpaceBatch # type: ignore[assignment] diff --git a/rerun_py/rerun_sdk/rerun/components/disconnected_space_ext.py b/rerun_py/rerun_sdk/rerun/components/disconnected_space_ext.py index e18efb13f32a..4ac4066a3ca1 100644 --- a/rerun_py/rerun_sdk/rerun/components/disconnected_space_ext.py +++ b/rerun_py/rerun_sdk/rerun/components/disconnected_space_ext.py @@ -21,4 +21,4 @@ def __init__( Set to `False` to disable the effects of this component, (re-)connecting the entity to its parent again. """ - self.__attrs_init__(is_disconnected=is_disconnected) + self.__attrs_init__(is_disconnected) diff --git a/rerun_py/rerun_sdk/rerun/components/draw_order.py b/rerun_py/rerun_sdk/rerun/components/draw_order.py index 7b75321eb2be..a004804772cf 100644 --- a/rerun_py/rerun_sdk/rerun/components/draw_order.py +++ b/rerun_py/rerun_sdk/rerun/components/draw_order.py @@ -5,25 +5,16 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Sequence, Union - -import numpy as np -import numpy.typing as npt -import pyarrow as pa -from attrs import define, field - +from .. import datatypes from .._baseclasses import ( - BaseBatch, - BaseExtensionType, ComponentBatchMixin, ComponentMixin, ) -__all__ = ["DrawOrder", "DrawOrderArrayLike", "DrawOrderBatch", "DrawOrderLike", "DrawOrderType"] +__all__ = ["DrawOrder", "DrawOrderBatch", "DrawOrderType"] -@define(init=False) -class DrawOrder(ComponentMixin): +class DrawOrder(datatypes.Float32, ComponentMixin): """ **Component**: Draw order of 2D elements. Higher values are drawn on top of lower values. @@ -34,49 +25,19 @@ class DrawOrder(ComponentMixin): """ _BATCH_TYPE = None + # You can define your own __init__ function as a member of DrawOrderExt in draw_order_ext.py - def __init__(self: Any, value: DrawOrderLike): - """Create a new instance of the DrawOrder component.""" - - # You can define your own __init__ function as a member of DrawOrderExt in draw_order_ext.py - self.__attrs_init__(value=value) - - value: float = field(converter=float) - - def __array__(self, dtype: npt.DTypeLike = None) -> npt.NDArray[Any]: - # You can define your own __array__ function as a member of DrawOrderExt in draw_order_ext.py - return np.asarray(self.value, dtype=dtype) - - def __float__(self) -> float: - return float(self.value) + # Note: there are no fields here because DrawOrder delegates to datatypes.Float32 + pass - def __hash__(self) -> int: - return hash(self.value) - -if TYPE_CHECKING: - DrawOrderLike = Union[DrawOrder, float] -else: - DrawOrderLike = Any - -DrawOrderArrayLike = Union[DrawOrder, Sequence[DrawOrderLike], float, npt.NDArray[np.float32]] - - -class DrawOrderType(BaseExtensionType): +class DrawOrderType(datatypes.Float32Type): _TYPE_NAME: str = "rerun.components.DrawOrder" - def __init__(self) -> None: - pa.ExtensionType.__init__(self, pa.float32(), self._TYPE_NAME) - -class DrawOrderBatch(BaseBatch[DrawOrderArrayLike], ComponentBatchMixin): +class DrawOrderBatch(datatypes.Float32Batch, ComponentBatchMixin): _ARROW_TYPE = DrawOrderType() - @staticmethod - def _native_to_pa_array(data: DrawOrderArrayLike, data_type: pa.DataType) -> pa.Array: - array = np.asarray(data, dtype=np.float32).flatten() - return pa.array(array, type=data_type) - # This is patched in late to avoid circular dependencies. DrawOrder._BATCH_TYPE = DrawOrderBatch # type: ignore[assignment] diff --git a/rerun_py/rerun_sdk/rerun/components/marker_size.py b/rerun_py/rerun_sdk/rerun/components/marker_size.py index 9f07f4739bcb..71bce79ee7a8 100644 --- a/rerun_py/rerun_sdk/rerun/components/marker_size.py +++ b/rerun_py/rerun_sdk/rerun/components/marker_size.py @@ -5,71 +5,32 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Sequence, Union - -import numpy as np -import numpy.typing as npt -import pyarrow as pa -from attrs import define, field - +from .. import datatypes from .._baseclasses import ( - BaseBatch, - BaseExtensionType, ComponentBatchMixin, ComponentMixin, ) -__all__ = ["MarkerSize", "MarkerSizeArrayLike", "MarkerSizeBatch", "MarkerSizeLike", "MarkerSizeType"] +__all__ = ["MarkerSize", "MarkerSizeBatch", "MarkerSizeType"] -@define(init=False) -class MarkerSize(ComponentMixin): +class MarkerSize(datatypes.Float32, ComponentMixin): """**Component**: Radius of a marker of a point in e.g. a 2D plot, measured in UI points.""" _BATCH_TYPE = None + # You can define your own __init__ function as a member of MarkerSizeExt in marker_size_ext.py - def __init__(self: Any, value: MarkerSizeLike): - """Create a new instance of the MarkerSize component.""" - - # You can define your own __init__ function as a member of MarkerSizeExt in marker_size_ext.py - self.__attrs_init__(value=value) - - value: float = field(converter=float) - - def __array__(self, dtype: npt.DTypeLike = None) -> npt.NDArray[Any]: - # You can define your own __array__ function as a member of MarkerSizeExt in marker_size_ext.py - return np.asarray(self.value, dtype=dtype) - - def __float__(self) -> float: - return float(self.value) + # Note: there are no fields here because MarkerSize delegates to datatypes.Float32 + pass - def __hash__(self) -> int: - return hash(self.value) - -if TYPE_CHECKING: - MarkerSizeLike = Union[MarkerSize, float] -else: - MarkerSizeLike = Any - -MarkerSizeArrayLike = Union[MarkerSize, Sequence[MarkerSizeLike], float, npt.ArrayLike] - - -class MarkerSizeType(BaseExtensionType): +class MarkerSizeType(datatypes.Float32Type): _TYPE_NAME: str = "rerun.components.MarkerSize" - def __init__(self) -> None: - pa.ExtensionType.__init__(self, pa.float32(), self._TYPE_NAME) - -class MarkerSizeBatch(BaseBatch[MarkerSizeArrayLike], ComponentBatchMixin): +class MarkerSizeBatch(datatypes.Float32Batch, ComponentBatchMixin): _ARROW_TYPE = MarkerSizeType() - @staticmethod - def _native_to_pa_array(data: MarkerSizeArrayLike, data_type: pa.DataType) -> pa.Array: - array = np.asarray(data, dtype=np.float32).flatten() - return pa.array(array, type=data_type) - # This is patched in late to avoid circular dependencies. MarkerSize._BATCH_TYPE = MarkerSizeBatch # type: ignore[assignment] diff --git a/rerun_py/rerun_sdk/rerun/components/radius.py b/rerun_py/rerun_sdk/rerun/components/radius.py index 0a0738d89423..461f8e2c8087 100644 --- a/rerun_py/rerun_sdk/rerun/components/radius.py +++ b/rerun_py/rerun_sdk/rerun/components/radius.py @@ -5,26 +5,17 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Sequence, Union - -import numpy as np -import numpy.typing as npt -import pyarrow as pa -from attrs import define, field - +from .. import datatypes from .._baseclasses import ( - BaseBatch, - BaseExtensionType, ComponentBatchMixin, ComponentMixin, ) from .radius_ext import RadiusExt -__all__ = ["Radius", "RadiusArrayLike", "RadiusBatch", "RadiusLike", "RadiusType"] +__all__ = ["Radius", "RadiusBatch", "RadiusType"] -@define(init=False) -class Radius(RadiusExt, ComponentMixin): +class Radius(RadiusExt, datatypes.Float32, ComponentMixin): """ **Component**: The radius of something, e.g. a point. @@ -37,49 +28,19 @@ class Radius(RadiusExt, ComponentMixin): """ _BATCH_TYPE = None + # You can define your own __init__ function as a member of RadiusExt in radius_ext.py - def __init__(self: Any, value: RadiusLike): - """Create a new instance of the Radius component.""" - - # You can define your own __init__ function as a member of RadiusExt in radius_ext.py - self.__attrs_init__(value=value) - - value: float = field(converter=float) - - def __array__(self, dtype: npt.DTypeLike = None) -> npt.NDArray[Any]: - # You can define your own __array__ function as a member of RadiusExt in radius_ext.py - return np.asarray(self.value, dtype=dtype) - - def __float__(self) -> float: - return float(self.value) + # Note: there are no fields here because Radius delegates to datatypes.Float32 + pass - def __hash__(self) -> int: - return hash(self.value) - -if TYPE_CHECKING: - RadiusLike = Union[Radius, float] -else: - RadiusLike = Any - -RadiusArrayLike = Union[Radius, Sequence[RadiusLike], float, npt.ArrayLike] - - -class RadiusType(BaseExtensionType): +class RadiusType(datatypes.Float32Type): _TYPE_NAME: str = "rerun.components.Radius" - def __init__(self) -> None: - pa.ExtensionType.__init__(self, pa.float32(), self._TYPE_NAME) - -class RadiusBatch(BaseBatch[RadiusArrayLike], ComponentBatchMixin): +class RadiusBatch(datatypes.Float32Batch, ComponentBatchMixin): _ARROW_TYPE = RadiusType() - @staticmethod - def _native_to_pa_array(data: RadiusArrayLike, data_type: pa.DataType) -> pa.Array: - array = np.asarray(data, dtype=np.float32).flatten() - return pa.array(array, type=data_type) - # This is patched in late to avoid circular dependencies. Radius._BATCH_TYPE = RadiusBatch # type: ignore[assignment] diff --git a/rerun_py/rerun_sdk/rerun/components/radius_ext.py b/rerun_py/rerun_sdk/rerun/components/radius_ext.py index 1d4ebad1ffc7..20173a7b796a 100644 --- a/rerun_py/rerun_sdk/rerun/components/radius_ext.py +++ b/rerun_py/rerun_sdk/rerun/components/radius_ext.py @@ -1,20 +1,16 @@ from __future__ import annotations import numbers -from typing import TYPE_CHECKING import numpy as np import numpy.typing as npt -if TYPE_CHECKING: - from . import RadiusArrayLike - class RadiusExt: """Extension for [Radius][rerun.components.Radius].""" @staticmethod - def ui_points(radii: numbers.Number | npt.ArrayLike) -> RadiusArrayLike: + def ui_points(radii: numbers.Number | npt.ArrayLike) -> npt.ArrayLike: """ Create a radius or list of radii in UI points. diff --git a/rerun_py/rerun_sdk/rerun/components/scalar.py b/rerun_py/rerun_sdk/rerun/components/scalar.py index 56b18ab4f265..c7f3f62c27a0 100644 --- a/rerun_py/rerun_sdk/rerun/components/scalar.py +++ b/rerun_py/rerun_sdk/rerun/components/scalar.py @@ -5,25 +5,16 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Sequence, Union - -import numpy as np -import numpy.typing as npt -import pyarrow as pa -from attrs import define, field - +from .. import datatypes from .._baseclasses import ( - BaseBatch, - BaseExtensionType, ComponentBatchMixin, ComponentMixin, ) -__all__ = ["Scalar", "ScalarArrayLike", "ScalarBatch", "ScalarLike", "ScalarType"] +__all__ = ["Scalar", "ScalarBatch", "ScalarType"] -@define(init=False) -class Scalar(ComponentMixin): +class Scalar(datatypes.Float64, ComponentMixin): """ **Component**: A scalar value, encoded as a 64-bit floating point. @@ -31,49 +22,19 @@ class Scalar(ComponentMixin): """ _BATCH_TYPE = None + # You can define your own __init__ function as a member of ScalarExt in scalar_ext.py - def __init__(self: Any, value: ScalarLike): - """Create a new instance of the Scalar component.""" - - # You can define your own __init__ function as a member of ScalarExt in scalar_ext.py - self.__attrs_init__(value=value) - - value: float = field(converter=float) - - def __array__(self, dtype: npt.DTypeLike = None) -> npt.NDArray[Any]: - # You can define your own __array__ function as a member of ScalarExt in scalar_ext.py - return np.asarray(self.value, dtype=dtype) - - def __float__(self) -> float: - return float(self.value) + # Note: there are no fields here because Scalar delegates to datatypes.Float64 + pass - def __hash__(self) -> int: - return hash(self.value) - -if TYPE_CHECKING: - ScalarLike = Union[Scalar, float] -else: - ScalarLike = Any - -ScalarArrayLike = Union[Scalar, Sequence[ScalarLike], float, npt.NDArray[np.float64]] - - -class ScalarType(BaseExtensionType): +class ScalarType(datatypes.Float64Type): _TYPE_NAME: str = "rerun.components.Scalar" - def __init__(self) -> None: - pa.ExtensionType.__init__(self, pa.float64(), self._TYPE_NAME) - -class ScalarBatch(BaseBatch[ScalarArrayLike], ComponentBatchMixin): +class ScalarBatch(datatypes.Float64Batch, ComponentBatchMixin): _ARROW_TYPE = ScalarType() - @staticmethod - def _native_to_pa_array(data: ScalarArrayLike, data_type: pa.DataType) -> pa.Array: - array = np.asarray(data, dtype=np.float64).flatten() - return pa.array(array, type=data_type) - # This is patched in late to avoid circular dependencies. Scalar._BATCH_TYPE = ScalarBatch # type: ignore[assignment] diff --git a/rerun_py/rerun_sdk/rerun/components/stroke_width.py b/rerun_py/rerun_sdk/rerun/components/stroke_width.py index b2bbe5c1bacc..5d7e7d7d3a6c 100644 --- a/rerun_py/rerun_sdk/rerun/components/stroke_width.py +++ b/rerun_py/rerun_sdk/rerun/components/stroke_width.py @@ -5,71 +5,32 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Sequence, Union - -import numpy as np -import numpy.typing as npt -import pyarrow as pa -from attrs import define, field - +from .. import datatypes from .._baseclasses import ( - BaseBatch, - BaseExtensionType, ComponentBatchMixin, ComponentMixin, ) -__all__ = ["StrokeWidth", "StrokeWidthArrayLike", "StrokeWidthBatch", "StrokeWidthLike", "StrokeWidthType"] +__all__ = ["StrokeWidth", "StrokeWidthBatch", "StrokeWidthType"] -@define(init=False) -class StrokeWidth(ComponentMixin): +class StrokeWidth(datatypes.Float32, ComponentMixin): """**Component**: The width of a stroke specified in UI points.""" _BATCH_TYPE = None + # You can define your own __init__ function as a member of StrokeWidthExt in stroke_width_ext.py - def __init__(self: Any, width: StrokeWidthLike): - """Create a new instance of the StrokeWidth component.""" - - # You can define your own __init__ function as a member of StrokeWidthExt in stroke_width_ext.py - self.__attrs_init__(width=width) - - width: float = field(converter=float) - - def __array__(self, dtype: npt.DTypeLike = None) -> npt.NDArray[Any]: - # You can define your own __array__ function as a member of StrokeWidthExt in stroke_width_ext.py - return np.asarray(self.width, dtype=dtype) - - def __float__(self) -> float: - return float(self.width) + # Note: there are no fields here because StrokeWidth delegates to datatypes.Float32 + pass - def __hash__(self) -> int: - return hash(self.width) - -if TYPE_CHECKING: - StrokeWidthLike = Union[StrokeWidth, float] -else: - StrokeWidthLike = Any - -StrokeWidthArrayLike = Union[StrokeWidth, Sequence[StrokeWidthLike], float, npt.ArrayLike] - - -class StrokeWidthType(BaseExtensionType): +class StrokeWidthType(datatypes.Float32Type): _TYPE_NAME: str = "rerun.components.StrokeWidth" - def __init__(self) -> None: - pa.ExtensionType.__init__(self, pa.float32(), self._TYPE_NAME) - -class StrokeWidthBatch(BaseBatch[StrokeWidthArrayLike], ComponentBatchMixin): +class StrokeWidthBatch(datatypes.Float32Batch, ComponentBatchMixin): _ARROW_TYPE = StrokeWidthType() - @staticmethod - def _native_to_pa_array(data: StrokeWidthArrayLike, data_type: pa.DataType) -> pa.Array: - array = np.asarray(data, dtype=np.float32).flatten() - return pa.array(array, type=data_type) - # This is patched in late to avoid circular dependencies. StrokeWidth._BATCH_TYPE = StrokeWidthBatch # type: ignore[assignment] diff --git a/rerun_py/rerun_sdk/rerun/components/view_coordinates.py b/rerun_py/rerun_sdk/rerun/components/view_coordinates.py index 2f7a6d75cee8..9824eb7506e6 100644 --- a/rerun_py/rerun_sdk/rerun/components/view_coordinates.py +++ b/rerun_py/rerun_sdk/rerun/components/view_coordinates.py @@ -5,32 +5,17 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Sequence, Union - -import numpy as np -import numpy.typing as npt -import pyarrow as pa -from attrs import define, field - +from .. import datatypes from .._baseclasses import ( - BaseBatch, - BaseExtensionType, ComponentBatchMixin, ComponentMixin, ) from .view_coordinates_ext import ViewCoordinatesExt -__all__ = [ - "ViewCoordinates", - "ViewCoordinatesArrayLike", - "ViewCoordinatesBatch", - "ViewCoordinatesLike", - "ViewCoordinatesType", -] +__all__ = ["ViewCoordinates", "ViewCoordinatesBatch", "ViewCoordinatesType"] -@define(init=False) -class ViewCoordinates(ViewCoordinatesExt, ComponentMixin): +class ViewCoordinates(ViewCoordinatesExt, datatypes.ViewCoordinates, ComponentMixin): """ **Component**: How we interpret the coordinate system of an entity/space. @@ -51,57 +36,19 @@ class ViewCoordinates(ViewCoordinatesExt, ComponentMixin): """ _BATCH_TYPE = None + # You can define your own __init__ function as a member of ViewCoordinatesExt in view_coordinates_ext.py - def __init__(self: Any, coordinates: ViewCoordinatesLike): - """ - Create a new instance of the ViewCoordinates component. - - Parameters - ---------- - coordinates: - The directions of the [x, y, z] axes. - - """ - - # You can define your own __init__ function as a member of ViewCoordinatesExt in view_coordinates_ext.py - self.__attrs_init__(coordinates=coordinates) - - coordinates: npt.NDArray[np.uint8] = field( - converter=ViewCoordinatesExt.coordinates__field_converter_override, # type: ignore[misc] - ) - # The directions of the [x, y, z] axes. - # - # (Docstring intentionally commented out to hide this field from the docs) + # Note: there are no fields here because ViewCoordinates delegates to datatypes.ViewCoordinates + pass - def __array__(self, dtype: npt.DTypeLike = None) -> npt.NDArray[Any]: - # You can define your own __array__ function as a member of ViewCoordinatesExt in view_coordinates_ext.py - return np.asarray(self.coordinates, dtype=dtype) - -if TYPE_CHECKING: - ViewCoordinatesLike = Union[ViewCoordinates, npt.ArrayLike] -else: - ViewCoordinatesLike = Any - -ViewCoordinatesArrayLike = Union[ViewCoordinates, Sequence[ViewCoordinatesLike], npt.ArrayLike] - - -class ViewCoordinatesType(BaseExtensionType): +class ViewCoordinatesType(datatypes.ViewCoordinatesType): _TYPE_NAME: str = "rerun.components.ViewCoordinates" - def __init__(self) -> None: - pa.ExtensionType.__init__( - self, pa.list_(pa.field("item", pa.uint8(), nullable=False, metadata={}), 3), self._TYPE_NAME - ) - -class ViewCoordinatesBatch(BaseBatch[ViewCoordinatesArrayLike], ComponentBatchMixin): +class ViewCoordinatesBatch(datatypes.ViewCoordinatesBatch, ComponentBatchMixin): _ARROW_TYPE = ViewCoordinatesType() - @staticmethod - def _native_to_pa_array(data: ViewCoordinatesArrayLike, data_type: pa.DataType) -> pa.Array: - return ViewCoordinatesExt.native_to_pa_array_override(data, data_type) - # This is patched in late to avoid circular dependencies. ViewCoordinates._BATCH_TYPE = ViewCoordinatesBatch # type: ignore[assignment] diff --git a/rerun_py/rerun_sdk/rerun/components/view_coordinates_ext.py b/rerun_py/rerun_sdk/rerun/components/view_coordinates_ext.py index e889fa680cb5..6a699de6611e 100644 --- a/rerun_py/rerun_sdk/rerun/components/view_coordinates_ext.py +++ b/rerun_py/rerun_sdk/rerun/components/view_coordinates_ext.py @@ -5,11 +5,10 @@ import numpy as np import numpy.typing as npt -import pyarrow as pa if TYPE_CHECKING: from .._log import ComponentBatchLike - from . import ViewCoordinates, ViewCoordinatesArrayLike + from . import ViewCoordinates class ViewCoordinatesExt: @@ -30,39 +29,6 @@ def coordinates__field_converter_override(data: npt.ArrayLike) -> npt.NDArray[np raise ValueError(f"ViewCoordinates must be a 3-element array. Got: {coordinates.shape}") return coordinates - @staticmethod - def native_to_pa_array_override(data: ViewCoordinatesArrayLike, data_type: pa.DataType) -> pa.Array: - from . import ViewCoordinates, ViewCoordinatesLike - - if isinstance(data, ViewCoordinates): - # ViewCoordinates - data = [data.coordinates] - elif hasattr(data, "__len__") and len(data) > 0 and isinstance(data[0], ViewCoordinates): # type: ignore[arg-type, index] - # [ViewCoordinates] - data = [d.coordinates for d in data] # type: ignore[union-attr] - else: - data = cast(ViewCoordinatesLike, data) - try: - # [x, y, z] - data = [ViewCoordinates(data).coordinates] - except ValueError: - # [[x, y, z], ...] - data = [ViewCoordinates(d).coordinates for d in data] # type: ignore[union-attr] - - data = np.asarray(data, dtype=np.uint8) - - if len(data.shape) != 2 or data.shape[1] != 3: - raise ValueError(f"ViewCoordinates must be a 3-element array. Got: {data.shape}") - - data = data.flatten() - - for value in data: - # TODO(jleibs): Enforce this validation based on ViewDir - if value not in range(1, 7): - raise ValueError("ViewCoordinates must contain only values in the range [1,6].") - - return pa.FixedSizeListArray.from_arrays(data, type=data_type) - # Implement the AsComponents protocol def as_component_batches(self) -> Iterable[ComponentBatchLike]: from ..archetypes import ViewCoordinates diff --git a/rerun_py/rerun_sdk/rerun/datatypes/.gitattributes b/rerun_py/rerun_sdk/rerun/datatypes/.gitattributes index 5785b817bb75..b2da34ccc71e 100644 --- a/rerun_py/rerun_sdk/rerun/datatypes/.gitattributes +++ b/rerun_py/rerun_sdk/rerun/datatypes/.gitattributes @@ -4,12 +4,14 @@ __init__.py linguist-generated=true angle.py linguist-generated=true annotation_info.py linguist-generated=true +blob.py linguist-generated=true bool.py linguist-generated=true class_description.py linguist-generated=true class_description_map_elem.py linguist-generated=true class_id.py linguist-generated=true entity_path.py linguist-generated=true float32.py linguist-generated=true +float64.py linguist-generated=true keypoint_id.py linguist-generated=true keypoint_pair.py linguist-generated=true mat3x3.py linguist-generated=true @@ -43,4 +45,5 @@ uvec4d.py linguist-generated=true vec2d.py linguist-generated=true vec3d.py linguist-generated=true vec4d.py linguist-generated=true +view_coordinates.py linguist-generated=true visible_time_range.py linguist-generated=true diff --git a/rerun_py/rerun_sdk/rerun/datatypes/__init__.py b/rerun_py/rerun_sdk/rerun/datatypes/__init__.py index 9b6bb1f148a5..4c7678ece044 100644 --- a/rerun_py/rerun_sdk/rerun/datatypes/__init__.py +++ b/rerun_py/rerun_sdk/rerun/datatypes/__init__.py @@ -10,6 +10,7 @@ AnnotationInfoLike, AnnotationInfoType, ) +from .blob import Blob, BlobArrayLike, BlobBatch, BlobLike, BlobType from .bool import Bool, BoolArrayLike, BoolBatch, BoolLike, BoolType from .class_description import ( ClassDescription, @@ -28,6 +29,7 @@ from .class_id import ClassId, ClassIdArrayLike, ClassIdBatch, ClassIdLike, ClassIdType from .entity_path import EntityPath, EntityPathArrayLike, EntityPathBatch, EntityPathLike, EntityPathType from .float32 import Float32, Float32ArrayLike, Float32Batch, Float32Like, Float32Type +from .float64 import Float64, Float64ArrayLike, Float64Batch, Float64Like, Float64Type from .keypoint_id import KeypointId, KeypointIdArrayLike, KeypointIdBatch, KeypointIdLike, KeypointIdType from .keypoint_pair import KeypointPair, KeypointPairArrayLike, KeypointPairBatch, KeypointPairLike, KeypointPairType from .mat3x3 import Mat3x3, Mat3x3ArrayLike, Mat3x3Batch, Mat3x3Like, Mat3x3Type @@ -103,6 +105,13 @@ from .vec2d import Vec2D, Vec2DArrayLike, Vec2DBatch, Vec2DLike, Vec2DType from .vec3d import Vec3D, Vec3DArrayLike, Vec3DBatch, Vec3DLike, Vec3DType from .vec4d import Vec4D, Vec4DArrayLike, Vec4DBatch, Vec4DLike, Vec4DType +from .view_coordinates import ( + ViewCoordinates, + ViewCoordinatesArrayLike, + ViewCoordinatesBatch, + ViewCoordinatesLike, + ViewCoordinatesType, +) from .visible_time_range import ( VisibleTimeRange, VisibleTimeRangeArrayLike, @@ -122,6 +131,11 @@ "AnnotationInfoBatch", "AnnotationInfoLike", "AnnotationInfoType", + "Blob", + "BlobArrayLike", + "BlobBatch", + "BlobLike", + "BlobType", "Bool", "BoolArrayLike", "BoolBatch", @@ -152,6 +166,11 @@ "Float32Batch", "Float32Like", "Float32Type", + "Float64", + "Float64ArrayLike", + "Float64Batch", + "Float64Like", + "Float64Type", "KeypointId", "KeypointIdArrayLike", "KeypointIdBatch", @@ -317,6 +336,11 @@ "Vec4DBatch", "Vec4DLike", "Vec4DType", + "ViewCoordinates", + "ViewCoordinatesArrayLike", + "ViewCoordinatesBatch", + "ViewCoordinatesLike", + "ViewCoordinatesType", "VisibleTimeRange", "VisibleTimeRangeArrayLike", "VisibleTimeRangeBatch", diff --git a/rerun_py/rerun_sdk/rerun/datatypes/blob.py b/rerun_py/rerun_sdk/rerun/datatypes/blob.py new file mode 100644 index 000000000000..d1675746774d --- /dev/null +++ b/rerun_py/rerun_sdk/rerun/datatypes/blob.py @@ -0,0 +1,66 @@ +# DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/python/mod.rs +# Based on "crates/store/re_types/definitions/rerun/datatypes/blob.fbs". + +# You can extend this class by creating a "BlobExt" class in "blob_ext.py". + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Sequence, Union + +import numpy as np +import numpy.typing as npt +import pyarrow as pa +from attrs import define, field + +from .._baseclasses import ( + BaseBatch, + BaseExtensionType, +) +from .._converters import ( + to_np_uint8, +) +from .blob_ext import BlobExt + +__all__ = ["Blob", "BlobArrayLike", "BlobBatch", "BlobLike", "BlobType"] + + +@define(init=False) +class Blob(BlobExt): + """**Datatype**: A binary blob of data.""" + + def __init__(self: Any, data: BlobLike): + """Create a new instance of the Blob datatype.""" + + # You can define your own __init__ function as a member of BlobExt in blob_ext.py + self.__attrs_init__(data=data) + + data: npt.NDArray[np.uint8] = field(converter=to_np_uint8) + + def __array__(self, dtype: npt.DTypeLike = None) -> npt.NDArray[Any]: + # You can define your own __array__ function as a member of BlobExt in blob_ext.py + return np.asarray(self.data, dtype=dtype) + + +if TYPE_CHECKING: + BlobLike = Union[Blob, bytes, npt.NDArray[np.uint8]] +else: + BlobLike = Any + +BlobArrayLike = Union[Blob, Sequence[BlobLike], bytes, npt.NDArray[np.uint8]] + + +class BlobType(BaseExtensionType): + _TYPE_NAME: str = "rerun.datatypes.Blob" + + def __init__(self) -> None: + pa.ExtensionType.__init__( + self, pa.list_(pa.field("item", pa.uint8(), nullable=False, metadata={})), self._TYPE_NAME + ) + + +class BlobBatch(BaseBatch[BlobArrayLike]): + _ARROW_TYPE = BlobType() + + @staticmethod + def _native_to_pa_array(data: BlobArrayLike, data_type: pa.DataType) -> pa.Array: + return BlobExt.native_to_pa_array_override(data, data_type) diff --git a/rerun_py/rerun_sdk/rerun/components/blob_ext.py b/rerun_py/rerun_sdk/rerun/datatypes/blob_ext.py similarity index 95% rename from rerun_py/rerun_sdk/rerun/components/blob_ext.py rename to rerun_py/rerun_sdk/rerun/datatypes/blob_ext.py index 373adae58081..74249180c50f 100644 --- a/rerun_py/rerun_sdk/rerun/components/blob_ext.py +++ b/rerun_py/rerun_sdk/rerun/datatypes/blob_ext.py @@ -15,11 +15,11 @@ def next_offset(acc: int, arr: Sized) -> int: class BlobExt: - """Extension for [Blob][rerun.components.Blob].""" + """Extension for [Blob][rerun.datatypes.Blob].""" @staticmethod def native_to_pa_array_override(data: BlobArrayLike, data_type: pa.DataType) -> pa.Array: - from . import Blob, BlobBatch + from ..datatypes import Blob, BlobBatch # someone or something is building things manually, let them! if isinstance(data, BlobBatch): diff --git a/rerun_py/rerun_sdk/rerun/datatypes/float32.py b/rerun_py/rerun_sdk/rerun/datatypes/float32.py index a84483b00b3c..f197fa6eaadc 100644 --- a/rerun_py/rerun_sdk/rerun/datatypes/float32.py +++ b/rerun_py/rerun_sdk/rerun/datatypes/float32.py @@ -49,8 +49,7 @@ def __hash__(self) -> int: Float32Like = Any Float32ArrayLike = Union[ - Float32, - Sequence[Float32Like], + Float32, Sequence[Float32Like], npt.NDArray[Any], npt.ArrayLike, Sequence[Sequence[float]], Sequence[float] ] diff --git a/rerun_py/rerun_sdk/rerun/datatypes/float64.py b/rerun_py/rerun_sdk/rerun/datatypes/float64.py new file mode 100644 index 000000000000..71d801fb61fa --- /dev/null +++ b/rerun_py/rerun_sdk/rerun/datatypes/float64.py @@ -0,0 +1,69 @@ +# DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/python/mod.rs +# Based on "crates/store/re_types/definitions/rerun/datatypes/float64.fbs". + +# You can extend this class by creating a "Float64Ext" class in "float64_ext.py". + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Sequence, Union + +import numpy as np +import numpy.typing as npt +import pyarrow as pa +from attrs import define, field + +from .._baseclasses import ( + BaseBatch, + BaseExtensionType, +) + +__all__ = ["Float64", "Float64ArrayLike", "Float64Batch", "Float64Like", "Float64Type"] + + +@define(init=False) +class Float64: + """**Datatype**: A double-precision 64-bit IEEE 754 floating point number.""" + + def __init__(self: Any, value: Float64Like): + """Create a new instance of the Float64 datatype.""" + + # You can define your own __init__ function as a member of Float64Ext in float64_ext.py + self.__attrs_init__(value=value) + + value: float = field(converter=float) + + def __array__(self, dtype: npt.DTypeLike = None) -> npt.NDArray[Any]: + # You can define your own __array__ function as a member of Float64Ext in float64_ext.py + return np.asarray(self.value, dtype=dtype) + + def __float__(self) -> float: + return float(self.value) + + def __hash__(self) -> int: + return hash(self.value) + + +if TYPE_CHECKING: + Float64Like = Union[Float64, float] +else: + Float64Like = Any + +Float64ArrayLike = Union[ + Float64, Sequence[Float64Like], npt.NDArray[Any], npt.ArrayLike, Sequence[Sequence[float]], Sequence[float] +] + + +class Float64Type(BaseExtensionType): + _TYPE_NAME: str = "rerun.datatypes.Float64" + + def __init__(self) -> None: + pa.ExtensionType.__init__(self, pa.float64(), self._TYPE_NAME) + + +class Float64Batch(BaseBatch[Float64ArrayLike]): + _ARROW_TYPE = Float64Type() + + @staticmethod + def _native_to_pa_array(data: Float64ArrayLike, data_type: pa.DataType) -> pa.Array: + array = np.asarray(data, dtype=np.float64).flatten() + return pa.array(array, type=data_type) diff --git a/rerun_py/rerun_sdk/rerun/datatypes/view_coordinates.py b/rerun_py/rerun_sdk/rerun/datatypes/view_coordinates.py new file mode 100644 index 000000000000..f694e3bb5395 --- /dev/null +++ b/rerun_py/rerun_sdk/rerun/datatypes/view_coordinates.py @@ -0,0 +1,100 @@ +# DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/python/mod.rs +# Based on "crates/store/re_types/definitions/rerun/datatypes/view_coordinates.fbs". + +# You can extend this class by creating a "ViewCoordinatesExt" class in "view_coordinates_ext.py". + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Sequence, Union + +import numpy as np +import numpy.typing as npt +import pyarrow as pa +from attrs import define, field + +from .._baseclasses import ( + BaseBatch, + BaseExtensionType, +) +from .._converters import ( + to_np_uint8, +) +from .view_coordinates_ext import ViewCoordinatesExt + +__all__ = [ + "ViewCoordinates", + "ViewCoordinatesArrayLike", + "ViewCoordinatesBatch", + "ViewCoordinatesLike", + "ViewCoordinatesType", +] + + +@define(init=False) +class ViewCoordinates(ViewCoordinatesExt): + """ + **Datatype**: How we interpret the coordinate system of an entity/space. + + For instance: What is "up"? What does the Z axis mean? Is this right-handed or left-handed? + + The three coordinates are always ordered as [x, y, z]. + + For example [Right, Down, Forward] means that the X axis points to the right, the Y axis points + down, and the Z axis points forward. + + The following constants are used to represent the different directions: + * Up = 1 + * Down = 2 + * Right = 3 + * Left = 4 + * Forward = 5 + * Back = 6 + """ + + def __init__(self: Any, coordinates: ViewCoordinatesLike): + """ + Create a new instance of the ViewCoordinates datatype. + + Parameters + ---------- + coordinates: + The directions of the [x, y, z] axes. + + """ + + # You can define your own __init__ function as a member of ViewCoordinatesExt in view_coordinates_ext.py + self.__attrs_init__(coordinates=coordinates) + + coordinates: npt.NDArray[np.uint8] = field(converter=to_np_uint8) + # The directions of the [x, y, z] axes. + # + # (Docstring intentionally commented out to hide this field from the docs) + + def __array__(self, dtype: npt.DTypeLike = None) -> npt.NDArray[Any]: + # You can define your own __array__ function as a member of ViewCoordinatesExt in view_coordinates_ext.py + return np.asarray(self.coordinates, dtype=dtype) + + +if TYPE_CHECKING: + ViewCoordinatesLike = Union[ViewCoordinates, npt.ArrayLike] +else: + ViewCoordinatesLike = Any + +ViewCoordinatesArrayLike = Union[ViewCoordinates, Sequence[ViewCoordinatesLike], npt.ArrayLike] + + +class ViewCoordinatesType(BaseExtensionType): + _TYPE_NAME: str = "rerun.datatypes.ViewCoordinates" + + def __init__(self) -> None: + pa.ExtensionType.__init__( + self, pa.list_(pa.field("item", pa.uint8(), nullable=False, metadata={}), 3), self._TYPE_NAME + ) + + +class ViewCoordinatesBatch(BaseBatch[ViewCoordinatesArrayLike]): + _ARROW_TYPE = ViewCoordinatesType() + + @staticmethod + def _native_to_pa_array(data: ViewCoordinatesArrayLike, data_type: pa.DataType) -> pa.Array: + return ViewCoordinatesExt.native_to_pa_array_override(data, data_type) diff --git a/rerun_py/rerun_sdk/rerun/datatypes/view_coordinates_ext.py b/rerun_py/rerun_sdk/rerun/datatypes/view_coordinates_ext.py new file mode 100644 index 000000000000..1a8cae24785e --- /dev/null +++ b/rerun_py/rerun_sdk/rerun/datatypes/view_coordinates_ext.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, cast + +import numpy as np +import pyarrow as pa + +if TYPE_CHECKING: + from . import ViewCoordinatesArrayLike + + +class ViewCoordinatesExt: + """Extension for [ViewCoordinates][rerun.datatypes.ViewCoordinates].""" + + @staticmethod + def native_to_pa_array_override(data: ViewCoordinatesArrayLike, data_type: pa.DataType) -> pa.Array: + from . import ViewCoordinates, ViewCoordinatesLike + + if isinstance(data, ViewCoordinates): + # ViewCoordinates + data = [data.coordinates] + elif hasattr(data, "__len__") and len(data) > 0 and isinstance(data[0], ViewCoordinates): # type: ignore[arg-type, index] + # [ViewCoordinates] + data = [d.coordinates for d in data] # type: ignore[union-attr] + else: + data = cast(ViewCoordinatesLike, data) + try: + # [x, y, z] + data = [ViewCoordinates(data).coordinates] + except ValueError: + # [[x, y, z], ...] + data = [ViewCoordinates(d).coordinates for d in data] # type: ignore[union-attr] + + data = np.asarray(data, dtype=np.uint8) + + if len(data.shape) != 2 or data.shape[1] != 3: + raise ValueError(f"ViewCoordinates must be a 3-element array. Got: {data.shape}") + + data = data.flatten() + + for value in data: + # TODO(jleibs): Enforce this validation based on ViewDir + if value not in range(1, 7): + raise ValueError("ViewCoordinates must contain only values in the range [1,6].") + + return pa.FixedSizeListArray.from_arrays(data, type=data_type) diff --git a/rerun_py/tests/unit/common_arrays.py b/rerun_py/tests/unit/common_arrays.py index 715bfd833cc8..90d096f3870a 100644 --- a/rerun_py/tests/unit/common_arrays.py +++ b/rerun_py/tests/unit/common_arrays.py @@ -11,16 +11,15 @@ ColorBatch, DrawOrder, DrawOrderBatch, - DrawOrderLike, KeypointId, KeypointIdBatch, Radius, - RadiusArrayLike, RadiusBatch, TextBatch, ) from rerun.datatypes import ( Angle, + Float32ArrayLike, Quaternion, Rgba32ArrayLike, Rotation3D, @@ -258,18 +257,18 @@ def expected_rotations(rotations: Rotation3DArrayLike, type_: Any) -> Any: return type_._optional([Quaternion(xyzw=[1, 2, 3, 4])] * 3 + [RotationAxisAngle([1, 2, 3], 4)]) -radii_arrays: list[RadiusArrayLike | None] = [ +radii_arrays: list[Float32ArrayLike | None] = [ None, [], np.array([]), - # RadiusArrayLike: Sequence[RadiusLike]: float + # Float32ArrayLike: Sequence[RadiusLike]: float [1, 10], - # RadiusArrayLike: Sequence[RadiusLike]: Radius + # Float32ArrayLike: Sequence[RadiusLike]: Radius [ Radius(1), Radius(10), ], - # RadiusArrayLike: npt.NDArray[np.float32] + # Float32ArrayLike: npt.NDArray[np.float32] np.array([1, 10], dtype=np.float32), ] @@ -410,11 +409,11 @@ def labels_expected(obj: Any) -> Any: return TextBatch._optional(expected) -draw_orders: list[DrawOrderLike | None] = [ +draw_orders: list[Float32ArrayLike | None] = [ None, - # DrawOrderLike: float - 300, - # DrawOrderLike: DrawOrder + # Float32ArrayLike: float + 300.0, + # Float32ArrayLike: DrawOrder DrawOrder(300), ] diff --git a/rerun_py/tests/unit/test_arrows3d.py b/rerun_py/tests/unit/test_arrows3d.py index 34b86bb41e16..f5aa91f8a05e 100644 --- a/rerun_py/tests/unit/test_arrows3d.py +++ b/rerun_py/tests/unit/test_arrows3d.py @@ -4,8 +4,8 @@ from typing import Optional, cast import rerun as rr -from rerun.components import Position3DBatch, RadiusArrayLike, Vector3DBatch -from rerun.datatypes import ClassIdArrayLike, Rgba32ArrayLike, Utf8ArrayLike, Vec3DArrayLike +from rerun.components import Position3DBatch, Vector3DBatch +from rerun.datatypes import ClassIdArrayLike, Float32ArrayLike, Rgba32ArrayLike, Utf8ArrayLike, Vec3DArrayLike from .common_arrays import ( class_ids_arrays, @@ -41,7 +41,7 @@ def test_arrows3d() -> None: # make Pyright happy as it's apparently not able to track typing info trough zip_longest vectors = cast(Vec3DArrayLike, vectors) origins = cast(Optional[Vec3DArrayLike], origins) - radii = cast(Optional[RadiusArrayLike], radii) + radii = cast(Optional[Float32ArrayLike], radii) colors = cast(Optional[Rgba32ArrayLike], colors) labels = cast(Optional[Utf8ArrayLike], labels) class_ids = cast(Optional[ClassIdArrayLike], class_ids) diff --git a/rerun_py/tests/unit/test_box2d.py b/rerun_py/tests/unit/test_box2d.py index f9d60a6882f1..57bed1172ed3 100644 --- a/rerun_py/tests/unit/test_box2d.py +++ b/rerun_py/tests/unit/test_box2d.py @@ -9,12 +9,10 @@ import rerun as rr import torch from rerun.components import ( - DrawOrderLike, HalfSize2DBatch, Position2DBatch, - RadiusArrayLike, ) -from rerun.datatypes import ClassIdArrayLike, Rgba32ArrayLike, Utf8ArrayLike, Vec2DArrayLike +from rerun.datatypes import ClassIdArrayLike, Float32ArrayLike, Rgba32ArrayLike, Utf8ArrayLike, Vec2DArrayLike from .common_arrays import ( class_ids_arrays, @@ -51,10 +49,10 @@ def test_boxes2d() -> None: # make Pyright happy as it's apparently not able to track typing info trough zip_longest half_sizes = cast(Vec2DArrayLike, half_sizes) centers = cast(Vec2DArrayLike, centers) - radii = cast(Optional[RadiusArrayLike], radii) + radii = cast(Optional[Float32ArrayLike], radii) colors = cast(Optional[Rgba32ArrayLike], colors) labels = cast(Optional[Utf8ArrayLike], labels) - draw_order = cast(Optional[DrawOrderLike], draw_order) + draw_order = cast(Optional[Float32ArrayLike], draw_order) class_ids = cast(Optional[ClassIdArrayLike], class_ids) print( diff --git a/rerun_py/tests/unit/test_box3d.py b/rerun_py/tests/unit/test_box3d.py index a04fe0cebc8a..f988c71afb17 100644 --- a/rerun_py/tests/unit/test_box3d.py +++ b/rerun_py/tests/unit/test_box3d.py @@ -4,8 +4,8 @@ from typing import Optional, cast import rerun as rr -from rerun.components import HalfSize3DBatch, Position3DBatch, RadiusArrayLike, Rotation3DBatch -from rerun.datatypes import ClassIdArrayLike, Rgba32ArrayLike, Rotation3DArrayLike, Utf8ArrayLike +from rerun.components import HalfSize3DBatch, Position3DBatch, Rotation3DBatch +from rerun.datatypes import ClassIdArrayLike, Float32ArrayLike, Rgba32ArrayLike, Rotation3DArrayLike, Utf8ArrayLike from rerun.datatypes.vec3d import Vec3DArrayLike from .common_arrays import ( @@ -44,7 +44,7 @@ def test_boxes3d() -> None: half_sizes = cast(Vec3DArrayLike, half_sizes) centers = cast(Vec3DArrayLike, centers) rotations = cast(Rotation3DArrayLike, rotations) - radii = cast(Optional[RadiusArrayLike], radii) + radii = cast(Optional[Float32ArrayLike], radii) colors = cast(Optional[Rgba32ArrayLike], colors) labels = cast(Optional[Utf8ArrayLike], labels) class_ids = cast(Optional[ClassIdArrayLike], class_ids) diff --git a/rerun_py/tests/unit/test_container_blueprint.py b/rerun_py/tests/unit/test_container_blueprint.py index a16c762bc13a..c034ce7b5a99 100644 --- a/rerun_py/tests/unit/test_container_blueprint.py +++ b/rerun_py/tests/unit/test_container_blueprint.py @@ -5,14 +5,17 @@ from rerun.blueprint.archetypes.container_blueprint import ContainerBlueprint from rerun.blueprint.components.active_tab import ActiveTab, ActiveTabBatch -from rerun.blueprint.components.column_share import ColumnShare, ColumnShareArrayLike, ColumnShareBatch +from rerun.blueprint.components.column_share import ColumnShare, ColumnShareBatch from rerun.blueprint.components.container_kind import ContainerKind, ContainerKindBatch, ContainerKindLike -from rerun.blueprint.components.grid_columns import GridColumns, GridColumnsBatch, GridColumnsLike +from rerun.blueprint.components.grid_columns import GridColumns, GridColumnsBatch from rerun.blueprint.components.included_content import IncludedContentBatch -from rerun.blueprint.components.row_share import RowShare, RowShareArrayLike, RowShareBatch -from rerun.blueprint.components.visible import Visible, VisibleBatch, VisibleLike +from rerun.blueprint.components.row_share import RowShare, RowShareBatch +from rerun.blueprint.components.visible import Visible, VisibleBatch from rerun.components.name import Name, NameBatch +from rerun.datatypes.bool import BoolLike from rerun.datatypes.entity_path import EntityPath, EntityPathArrayLike, EntityPathLike +from rerun.datatypes.float32 import Float32ArrayLike +from rerun.datatypes.uint32 import UInt32ArrayLike from rerun.datatypes.utf8 import Utf8Like from .common_arrays import none_empty_or_value @@ -94,11 +97,11 @@ def test_container_blueprint() -> None: container_kind = cast(ContainerKindLike, container_kind) display_name = cast(Optional[Utf8Like], display_name) contents = cast(Optional[EntityPathArrayLike], contents) - col_shares = cast(Optional[ColumnShareArrayLike], col_shares) - row_shares = cast(Optional[RowShareArrayLike], row_shares) + col_shares = cast(Optional[Float32ArrayLike], col_shares) + row_shares = cast(Optional[Float32ArrayLike], row_shares) active_tab = cast(Optional[EntityPathLike], active_tab) - visible = cast(Optional[VisibleLike], visible) - grid_columns = cast(Optional[GridColumnsLike], grid_columns) + visible = cast(Optional[BoolLike], visible) + grid_columns = cast(Optional[UInt32ArrayLike], grid_columns) print( "rr.ContainerBlueprint(\n", diff --git a/rerun_py/tests/unit/test_depth_image.py b/rerun_py/tests/unit/test_depth_image.py index 9a531b14a27e..79266e87b39b 100644 --- a/rerun_py/tests/unit/test_depth_image.py +++ b/rerun_py/tests/unit/test_depth_image.py @@ -7,7 +7,7 @@ import rerun as rr import torch from rerun.components import DepthMeter -from rerun.datatypes import TensorBuffer, TensorData, TensorDataLike, TensorDimension +from rerun.datatypes import Float32Like, TensorBuffer, TensorData, TensorDataLike, TensorDimension rng = np.random.default_rng(12345) RANDOM_IMAGE_SOURCE = rng.uniform(0.0, 1.0, (10, 20)) @@ -26,7 +26,7 @@ RANDOM_IMAGE_SOURCE, ] -METER_INPUTS: list[rr.components.DepthMeterLike] = [1000, DepthMeter(1000)] +METER_INPUTS: list[Float32Like] = [1000, DepthMeter(1000)] def depth_image_expected() -> Any: diff --git a/rerun_py/tests/unit/test_disconnected_space.py b/rerun_py/tests/unit/test_disconnected_space.py index 555f3f2662b6..d66730f0d136 100644 --- a/rerun_py/tests/unit/test_disconnected_space.py +++ b/rerun_py/tests/unit/test_disconnected_space.py @@ -1,11 +1,12 @@ from __future__ import annotations import rerun as rr -from rerun.components import DisconnectedSpace, DisconnectedSpaceBatch, DisconnectedSpaceLike +from rerun.components import DisconnectedSpace, DisconnectedSpaceBatch +from rerun.datatypes.bool import BoolLike def test_disconnected_space() -> None: - disconnected_spaces: list[DisconnectedSpaceLike] = [ + disconnected_spaces: list[BoolLike] = [ # DisconnectedSpaceLike: bool True, # DisconnectedSpaceLike: DisconnectedSpace diff --git a/rerun_py/tests/unit/test_line_strips2d.py b/rerun_py/tests/unit/test_line_strips2d.py index 979a038480fb..6dab70773765 100644 --- a/rerun_py/tests/unit/test_line_strips2d.py +++ b/rerun_py/tests/unit/test_line_strips2d.py @@ -8,12 +8,10 @@ import rerun as rr import torch from rerun.components import ( - DrawOrderLike, LineStrip2DArrayLike, LineStrip2DBatch, - RadiusArrayLike, ) -from rerun.datatypes import ClassIdArrayLike, Rgba32ArrayLike, Utf8ArrayLike, Vec2D +from rerun.datatypes import ClassIdArrayLike, Float32ArrayLike, Rgba32ArrayLike, Utf8ArrayLike, Vec2D from .common_arrays import ( class_ids_arrays, @@ -83,10 +81,10 @@ def test_line_strips2d() -> None: # make Pyright happy as it's apparently not able to track typing info trough zip_longest strips = cast(LineStrip2DArrayLike, strips) - radii = cast(Optional[RadiusArrayLike], radii) + radii = cast(Optional[Float32ArrayLike], radii) colors = cast(Optional[Rgba32ArrayLike], colors) labels = cast(Optional[Utf8ArrayLike], labels) - draw_order = cast(Optional[DrawOrderLike], draw_order) + draw_order = cast(Optional[Float32ArrayLike], draw_order) class_ids = cast(Optional[ClassIdArrayLike], class_ids) print( diff --git a/rerun_py/tests/unit/test_line_strips3d.py b/rerun_py/tests/unit/test_line_strips3d.py index fc8e3a628dc8..97d82cd6c8c5 100644 --- a/rerun_py/tests/unit/test_line_strips3d.py +++ b/rerun_py/tests/unit/test_line_strips3d.py @@ -8,8 +8,7 @@ import rerun as rr import torch from rerun.components.line_strip3d import LineStrip3DArrayLike, LineStrip3DBatch -from rerun.components.radius import RadiusArrayLike -from rerun.datatypes import Vec3D +from rerun.datatypes import Float32ArrayLike, Vec3D from rerun.datatypes.class_id import ClassIdArrayLike from rerun.datatypes.rgba32 import Rgba32ArrayLike from rerun.datatypes.utf8 import Utf8ArrayLike @@ -82,7 +81,7 @@ def test_line_strips3d() -> None: # make Pyright happy as it's apparently not able to track typing info trough zip_longest strips = cast(LineStrip3DArrayLike, strips) - radii = cast(Optional[RadiusArrayLike], radii) + radii = cast(Optional[Float32ArrayLike], radii) colors = cast(Optional[Rgba32ArrayLike], colors) labels = cast(Optional[Utf8ArrayLike], labels) class_ids = cast(Optional[ClassIdArrayLike], class_ids) diff --git a/rerun_py/tests/unit/test_pinhole.py b/rerun_py/tests/unit/test_pinhole.py index e5ba56bdd397..94a29ecdc074 100644 --- a/rerun_py/tests/unit/test_pinhole.py +++ b/rerun_py/tests/unit/test_pinhole.py @@ -4,9 +4,8 @@ import numpy as np import rerun as rr -from rerun.components import PinholeProjectionBatch, ResolutionBatch, ViewCoordinatesBatch, ViewCoordinatesLike -from rerun.datatypes.mat3x3 import Mat3x3Like -from rerun.datatypes.vec2d import Vec2DLike +from rerun.components import PinholeProjectionBatch, ResolutionBatch, ViewCoordinatesBatch +from rerun.datatypes import Mat3x3Like, Vec2DLike, ViewCoordinatesLike def test_pinhole() -> None: diff --git a/rerun_py/tests/unit/test_plot_legend.py b/rerun_py/tests/unit/test_plot_legend.py index 78c0fb6f3238..13ea87868abb 100644 --- a/rerun_py/tests/unit/test_plot_legend.py +++ b/rerun_py/tests/unit/test_plot_legend.py @@ -6,6 +6,7 @@ import rerun as rr import rerun.blueprint as rrb from rerun.blueprint import components as blueprint_components +from rerun.datatypes.bool import BoolLike from .common_arrays import none_empty_or_value @@ -30,7 +31,7 @@ def test_scalar_axis() -> None: for corner, visible in all_arrays: corner = cast(Optional[blueprint_components.Corner2DLike], corner) - visible = cast(Optional[blueprint_components.VisibleLike], visible) + visible = cast(Optional[BoolLike], visible) print( f"rr.PlotLegend(\n" diff --git a/rerun_py/tests/unit/test_points2d.py b/rerun_py/tests/unit/test_points2d.py index ca15f0f1bdf5..d1b2e2abfaed 100644 --- a/rerun_py/tests/unit/test_points2d.py +++ b/rerun_py/tests/unit/test_points2d.py @@ -9,11 +9,16 @@ from rerun.components import ( Color, ColorBatch, - DrawOrderLike, Position2DBatch, - RadiusArrayLike, ) -from rerun.datatypes import ClassIdArrayLike, KeypointIdArrayLike, Rgba32ArrayLike, Utf8ArrayLike, Vec2DArrayLike +from rerun.datatypes import ( + ClassIdArrayLike, + Float32ArrayLike, + KeypointIdArrayLike, + Rgba32ArrayLike, + Utf8ArrayLike, + Vec2DArrayLike, +) from .common_arrays import ( class_ids_arrays, @@ -49,10 +54,10 @@ def test_points2d() -> None: # make Pyright happy as it's apparently not able to track typing info trough zip_longest positions = cast(Vec2DArrayLike, positions) - radii = cast(Optional[RadiusArrayLike], radii) + radii = cast(Optional[Float32ArrayLike], radii) colors = cast(Optional[Rgba32ArrayLike], colors) labels = cast(Optional[Utf8ArrayLike], labels) - draw_order = cast(Optional[DrawOrderLike], draw_order) + draw_order = cast(Optional[Float32ArrayLike], draw_order) class_ids = cast(Optional[ClassIdArrayLike], class_ids) keypoint_ids = cast(Optional[KeypointIdArrayLike], keypoint_ids) diff --git a/rerun_py/tests/unit/test_points3d.py b/rerun_py/tests/unit/test_points3d.py index be4a76cd8f11..2b76095ff1a6 100644 --- a/rerun_py/tests/unit/test_points3d.py +++ b/rerun_py/tests/unit/test_points3d.py @@ -10,9 +10,15 @@ Color, ColorBatch, Position3DBatch, - RadiusArrayLike, ) -from rerun.datatypes import ClassIdArrayLike, KeypointIdArrayLike, Rgba32ArrayLike, Utf8ArrayLike, Vec3DArrayLike +from rerun.datatypes import ( + ClassIdArrayLike, + Float32ArrayLike, + KeypointIdArrayLike, + Rgba32ArrayLike, + Utf8ArrayLike, + Vec3DArrayLike, +) from .common_arrays import ( class_ids_arrays, @@ -45,7 +51,7 @@ def test_points3d() -> None: # make Pyright happy as it's apparently not able to track typing info trough zip_longest positions = cast(Vec3DArrayLike, positions) - radii = cast(Optional[RadiusArrayLike], radii) + radii = cast(Optional[Float32ArrayLike], radii) colors = cast(Optional[Rgba32ArrayLike], colors) labels = cast(Optional[Utf8ArrayLike], labels) class_ids = cast(Optional[ClassIdArrayLike], class_ids) diff --git a/rerun_py/tests/unit/test_space_view_blueprint.py b/rerun_py/tests/unit/test_space_view_blueprint.py index 90728b39aa66..4b4c228b75fe 100644 --- a/rerun_py/tests/unit/test_space_view_blueprint.py +++ b/rerun_py/tests/unit/test_space_view_blueprint.py @@ -6,8 +6,9 @@ from rerun.blueprint.archetypes.space_view_blueprint import SpaceViewBlueprint from rerun.blueprint.components.space_view_class import SpaceViewClass, SpaceViewClassBatch from rerun.blueprint.components.space_view_origin import SpaceViewOrigin, SpaceViewOriginBatch -from rerun.blueprint.components.visible import Visible, VisibleBatch, VisibleLike +from rerun.blueprint.components.visible import Visible, VisibleBatch from rerun.components.name import Name, NameBatch +from rerun.datatypes.bool import BoolLike from rerun.datatypes.entity_path import EntityPathLike from rerun.datatypes.utf8 import Utf8Like @@ -34,7 +35,7 @@ def test_space_view_blueprint() -> None: class_identifier = cast(Utf8Like, class_identifier) display_name = cast(Optional[Utf8Like], display_name) space_origin = cast(Optional[EntityPathLike], space_origin) - visible = cast(Optional[VisibleLike], visible) + visible = cast(Optional[BoolLike], visible) print( "rr.SpaceViewBlueprint(\n", diff --git a/rerun_py/tests/unit/test_view_coordinates.py b/rerun_py/tests/unit/test_view_coordinates.py index 9f084469723c..d8788276c4a3 100644 --- a/rerun_py/tests/unit/test_view_coordinates.py +++ b/rerun_py/tests/unit/test_view_coordinates.py @@ -4,6 +4,7 @@ import rerun.components as rrc from rerun.archetypes import ViewCoordinates +from rerun.datatypes.view_coordinates import ViewCoordinatesArrayLike from .common_arrays import none_empty_or_value @@ -16,7 +17,7 @@ def view_coordinates_expected(obj: Any) -> rrc.ViewCoordinatesBatch: return rrc.ViewCoordinatesBatch(expected) -VIEW_COORDINATES_INPUTS: list[rrc.ViewCoordinatesArrayLike | None] = [ +VIEW_COORDINATES_INPUTS: list[ViewCoordinatesArrayLike | None] = [ None, rrc.ViewCoordinates([ rrc.ViewCoordinates.ViewDir.Right, diff --git a/rerun_py/tests/unit/test_viewport_blueprint.py b/rerun_py/tests/unit/test_viewport_blueprint.py index fcd606fbf1b9..29e6691cca48 100644 --- a/rerun_py/tests/unit/test_viewport_blueprint.py +++ b/rerun_py/tests/unit/test_viewport_blueprint.py @@ -4,14 +4,15 @@ from typing import Optional, cast from rerun.blueprint.archetypes.viewport_blueprint import ViewportBlueprint -from rerun.blueprint.components.auto_layout import AutoLayoutBatch, AutoLayoutLike -from rerun.blueprint.components.auto_space_views import AutoSpaceViewsBatch, AutoSpaceViewsLike +from rerun.blueprint.components.auto_layout import AutoLayoutBatch +from rerun.blueprint.components.auto_space_views import AutoSpaceViewsBatch from rerun.blueprint.components.root_container import RootContainerBatch from rerun.blueprint.components.space_view_maximized import SpaceViewMaximizedBatch from rerun.blueprint.components.viewer_recommendation_hash import ( ViewerRecommendationHash, ViewerRecommendationHashBatch, ) +from rerun.datatypes.bool import BoolLike from rerun.datatypes.uint64 import UInt64ArrayLike from rerun.datatypes.uuid import UuidLike @@ -53,8 +54,8 @@ def test_viewport_blueprint() -> None: # mypy can't track types properly through itertools zip so re-cast root_container = cast(Optional[UuidLike], root_container) maximized = cast(Optional[UuidLike], maximized) - auto_layout = cast(Optional[AutoLayoutLike], auto_layout) - auto_space_views = cast(Optional[AutoSpaceViewsLike], auto_space_views) + auto_layout = cast(Optional[BoolLike], auto_layout) + auto_space_views = cast(Optional[BoolLike], auto_space_views) past_viewer_recommendations = cast(Optional[UInt64ArrayLike], past_viewer_recommendations) print( diff --git a/rerun_py/tests/unit/test_visualizer_overrides.py b/rerun_py/tests/unit/test_visualizer_overrides.py index fb779f431156..09c0533fee6c 100644 --- a/rerun_py/tests/unit/test_visualizer_overrides.py +++ b/rerun_py/tests/unit/test_visualizer_overrides.py @@ -3,6 +3,7 @@ from typing import Any import rerun.blueprint.components as rrbc +from rerun.blueprint.datatypes.utf8list import Utf8ListArrayLike from .common_arrays import none_empty_or_value @@ -13,7 +14,7 @@ def visualizer_overrides_expected(obj: Any) -> rrbc.VisualizerOverridesBatch: return rrbc.VisualizerOverridesBatch(expected) -VISUALIZER_OVERRIDES_INPUT: list[rrbc.VisualizerOverridesArrayLike | None] = [ +VISUALIZER_OVERRIDES_INPUT: list[Utf8ListArrayLike | None] = [ None, [], "boxes3d", diff --git a/tests/rust/test_api/src/main.rs b/tests/rust/test_api/src/main.rs index b5c7acfc895e..bb0b1fd1e534 100644 --- a/tests/rust/test_api/src/main.rs +++ b/tests/rust/test_api/src/main.rs @@ -129,7 +129,7 @@ fn test_3d_points(rec: &RecordingStream) -> anyhow::Result<()> { ( Text(i.to_string().into()), Position3D::new(x((i * 0.2).sin()), y((i * 0.2).cos()), z(i)), - Radius(t * 0.1 + (1.0 - t) * 2.0), // lerp(0.1, 2.0, t) + Radius::from(t * 0.1 + (1.0 - t) * 2.0), // lerp(0.1, 2.0, t) Color::from_rgb(rng.gen(), rng.gen(), rng.gen()), ) })) diff --git a/tests/rust/test_temporal_batch/src/main.rs b/tests/rust/test_temporal_batch/src/main.rs index 24fae62ff3dc..0b283257f6cf 100644 --- a/tests/rust/test_temporal_batch/src/main.rs +++ b/tests/rust/test_temporal_batch/src/main.rs @@ -16,7 +16,7 @@ fn main() -> Result<(), Box> { // Convert to rerun time / scalars let timeline_values = ChunkTimeline::new_sequence("step", timeline_values); - let scalar_data = scalar_data.into_iter().map(Scalar).collect::>(); + let scalar_data: Vec = scalar_data.into_iter().map(Into::into).collect(); rec.log_temporal_batch("scalar", [timeline_values], [&scalar_data as _])?;