re_types/archetypes/
asset3d.rs

1// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/rust/api.rs
2// Based on "crates/store/re_types/definitions/rerun/archetypes/asset3d.fbs".
3
4#![allow(unused_imports)]
5#![allow(unused_parens)]
6#![allow(clippy::clone_on_copy)]
7#![allow(clippy::cloned_instead_of_copied)]
8#![allow(clippy::map_flatten)]
9#![allow(clippy::needless_question_mark)]
10#![allow(clippy::new_without_default)]
11#![allow(clippy::redundant_closure)]
12#![allow(clippy::too_many_arguments)]
13#![allow(clippy::too_many_lines)]
14
15use ::re_types_core::try_serialize_field;
16use ::re_types_core::SerializationResult;
17use ::re_types_core::{ComponentBatch as _, SerializedComponentBatch};
18use ::re_types_core::{ComponentDescriptor, ComponentName};
19use ::re_types_core::{DeserializationError, DeserializationResult};
20
21/// **Archetype**: A prepacked 3D asset (`.gltf`, `.glb`, `.obj`, `.stl`, etc.).
22///
23/// See also [`archetypes::Mesh3D`][crate::archetypes::Mesh3D].
24///
25/// If there are multiple [`archetypes::InstancePoses3D`][crate::archetypes::InstancePoses3D] instances logged to the same entity as a mesh,
26/// an instance of the mesh will be drawn for each transform.
27///
28/// ## Example
29///
30/// ### Simple 3D asset
31/// ```ignore
32/// use rerun::external::anyhow;
33///
34/// fn main() -> anyhow::Result<()> {
35///     let args = std::env::args().collect::<Vec<_>>();
36///     let Some(path) = args.get(1) else {
37///         anyhow::bail!("Usage: {} <path_to_asset.[gltf|glb|obj|stl]>", args[0]);
38///     };
39///
40///     let rec = rerun::RecordingStreamBuilder::new("rerun_example_asset3d").spawn()?;
41///
42///     rec.log_static("world", &rerun::ViewCoordinates::RIGHT_HAND_Z_UP())?; // Set an up-axis
43///     rec.log("world/asset", &rerun::Asset3D::from_file_path(path)?)?;
44///
45///     Ok(())
46/// }
47/// ```
48/// <center>
49/// <picture>
50///   <source media="(max-width: 480px)" srcset="https://static.rerun.io/asset3d_simple/af238578188d3fd0de3e330212120e2842a8ddb2/480w.png">
51///   <source media="(max-width: 768px)" srcset="https://static.rerun.io/asset3d_simple/af238578188d3fd0de3e330212120e2842a8ddb2/768w.png">
52///   <source media="(max-width: 1024px)" srcset="https://static.rerun.io/asset3d_simple/af238578188d3fd0de3e330212120e2842a8ddb2/1024w.png">
53///   <source media="(max-width: 1200px)" srcset="https://static.rerun.io/asset3d_simple/af238578188d3fd0de3e330212120e2842a8ddb2/1200w.png">
54///   <img src="https://static.rerun.io/asset3d_simple/af238578188d3fd0de3e330212120e2842a8ddb2/full.png" width="640">
55/// </picture>
56/// </center>
57#[derive(Clone, Debug, PartialEq, Default)]
58pub struct Asset3D {
59    /// The asset's bytes.
60    pub blob: Option<SerializedComponentBatch>,
61
62    /// The Media Type of the asset.
63    ///
64    /// Supported values:
65    /// * `model/gltf-binary`
66    /// * `model/gltf+json`
67    /// * `model/obj` (.mtl material files are not supported yet, references are silently ignored)
68    /// * `model/stl`
69    ///
70    /// If omitted, the viewer will try to guess from the data blob.
71    /// If it cannot guess, it won't be able to render the asset.
72    pub media_type: Option<SerializedComponentBatch>,
73
74    /// A color multiplier applied to the whole asset.
75    ///
76    /// For mesh who already have `albedo_factor` in materials,
77    /// it will be overwritten by actual `albedo_factor` of [`archetypes::Asset3D`][crate::archetypes::Asset3D] (if specified).
78    pub albedo_factor: Option<SerializedComponentBatch>,
79}
80
81impl Asset3D {
82    /// Returns the [`ComponentDescriptor`] for [`Self::blob`].
83    #[inline]
84    pub fn descriptor_blob() -> ComponentDescriptor {
85        ComponentDescriptor {
86            archetype_name: Some("rerun.archetypes.Asset3D".into()),
87            component_name: "rerun.components.Blob".into(),
88            archetype_field_name: Some("blob".into()),
89        }
90    }
91
92    /// Returns the [`ComponentDescriptor`] for [`Self::media_type`].
93    #[inline]
94    pub fn descriptor_media_type() -> ComponentDescriptor {
95        ComponentDescriptor {
96            archetype_name: Some("rerun.archetypes.Asset3D".into()),
97            component_name: "rerun.components.MediaType".into(),
98            archetype_field_name: Some("media_type".into()),
99        }
100    }
101
102    /// Returns the [`ComponentDescriptor`] for [`Self::albedo_factor`].
103    #[inline]
104    pub fn descriptor_albedo_factor() -> ComponentDescriptor {
105        ComponentDescriptor {
106            archetype_name: Some("rerun.archetypes.Asset3D".into()),
107            component_name: "rerun.components.AlbedoFactor".into(),
108            archetype_field_name: Some("albedo_factor".into()),
109        }
110    }
111
112    /// Returns the [`ComponentDescriptor`] for the associated indicator component.
113    #[inline]
114    pub fn descriptor_indicator() -> ComponentDescriptor {
115        ComponentDescriptor {
116            archetype_name: Some("rerun.archetypes.Asset3D".into()),
117            component_name: "rerun.components.Asset3DIndicator".into(),
118            archetype_field_name: None,
119        }
120    }
121}
122
123static REQUIRED_COMPONENTS: once_cell::sync::Lazy<[ComponentDescriptor; 1usize]> =
124    once_cell::sync::Lazy::new(|| [Asset3D::descriptor_blob()]);
125
126static RECOMMENDED_COMPONENTS: once_cell::sync::Lazy<[ComponentDescriptor; 2usize]> =
127    once_cell::sync::Lazy::new(|| {
128        [
129            Asset3D::descriptor_media_type(),
130            Asset3D::descriptor_indicator(),
131        ]
132    });
133
134static OPTIONAL_COMPONENTS: once_cell::sync::Lazy<[ComponentDescriptor; 1usize]> =
135    once_cell::sync::Lazy::new(|| [Asset3D::descriptor_albedo_factor()]);
136
137static ALL_COMPONENTS: once_cell::sync::Lazy<[ComponentDescriptor; 4usize]> =
138    once_cell::sync::Lazy::new(|| {
139        [
140            Asset3D::descriptor_blob(),
141            Asset3D::descriptor_media_type(),
142            Asset3D::descriptor_indicator(),
143            Asset3D::descriptor_albedo_factor(),
144        ]
145    });
146
147impl Asset3D {
148    /// The total number of components in the archetype: 1 required, 2 recommended, 1 optional
149    pub const NUM_COMPONENTS: usize = 4usize;
150}
151
152/// Indicator component for the [`Asset3D`] [`::re_types_core::Archetype`]
153pub type Asset3DIndicator = ::re_types_core::GenericIndicatorComponent<Asset3D>;
154
155impl ::re_types_core::Archetype for Asset3D {
156    type Indicator = Asset3DIndicator;
157
158    #[inline]
159    fn name() -> ::re_types_core::ArchetypeName {
160        "rerun.archetypes.Asset3D".into()
161    }
162
163    #[inline]
164    fn display_name() -> &'static str {
165        "Asset 3D"
166    }
167
168    #[inline]
169    fn indicator() -> SerializedComponentBatch {
170        #[allow(clippy::unwrap_used)]
171        Asset3DIndicator::DEFAULT.serialized().unwrap()
172    }
173
174    #[inline]
175    fn required_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
176        REQUIRED_COMPONENTS.as_slice().into()
177    }
178
179    #[inline]
180    fn recommended_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
181        RECOMMENDED_COMPONENTS.as_slice().into()
182    }
183
184    #[inline]
185    fn optional_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
186        OPTIONAL_COMPONENTS.as_slice().into()
187    }
188
189    #[inline]
190    fn all_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
191        ALL_COMPONENTS.as_slice().into()
192    }
193
194    #[inline]
195    fn from_arrow_components(
196        arrow_data: impl IntoIterator<Item = (ComponentDescriptor, arrow::array::ArrayRef)>,
197    ) -> DeserializationResult<Self> {
198        re_tracing::profile_function!();
199        use ::re_types_core::{Loggable as _, ResultExt as _};
200        let arrays_by_descr: ::nohash_hasher::IntMap<_, _> = arrow_data.into_iter().collect();
201        let blob = arrays_by_descr
202            .get(&Self::descriptor_blob())
203            .map(|array| SerializedComponentBatch::new(array.clone(), Self::descriptor_blob()));
204        let media_type = arrays_by_descr
205            .get(&Self::descriptor_media_type())
206            .map(|array| {
207                SerializedComponentBatch::new(array.clone(), Self::descriptor_media_type())
208            });
209        let albedo_factor = arrays_by_descr
210            .get(&Self::descriptor_albedo_factor())
211            .map(|array| {
212                SerializedComponentBatch::new(array.clone(), Self::descriptor_albedo_factor())
213            });
214        Ok(Self {
215            blob,
216            media_type,
217            albedo_factor,
218        })
219    }
220}
221
222impl ::re_types_core::AsComponents for Asset3D {
223    #[inline]
224    fn as_serialized_batches(&self) -> Vec<SerializedComponentBatch> {
225        use ::re_types_core::Archetype as _;
226        [
227            Some(Self::indicator()),
228            self.blob.clone(),
229            self.media_type.clone(),
230            self.albedo_factor.clone(),
231        ]
232        .into_iter()
233        .flatten()
234        .collect()
235    }
236}
237
238impl ::re_types_core::ArchetypeReflectionMarker for Asset3D {}
239
240impl Asset3D {
241    /// Create a new `Asset3D`.
242    #[inline]
243    pub fn new(blob: impl Into<crate::components::Blob>) -> Self {
244        Self {
245            blob: try_serialize_field(Self::descriptor_blob(), [blob]),
246            media_type: None,
247            albedo_factor: None,
248        }
249    }
250
251    /// Update only some specific fields of a `Asset3D`.
252    #[inline]
253    pub fn update_fields() -> Self {
254        Self::default()
255    }
256
257    /// Clear all the fields of a `Asset3D`.
258    #[inline]
259    pub fn clear_fields() -> Self {
260        use ::re_types_core::Loggable as _;
261        Self {
262            blob: Some(SerializedComponentBatch::new(
263                crate::components::Blob::arrow_empty(),
264                Self::descriptor_blob(),
265            )),
266            media_type: Some(SerializedComponentBatch::new(
267                crate::components::MediaType::arrow_empty(),
268                Self::descriptor_media_type(),
269            )),
270            albedo_factor: Some(SerializedComponentBatch::new(
271                crate::components::AlbedoFactor::arrow_empty(),
272                Self::descriptor_albedo_factor(),
273            )),
274        }
275    }
276
277    /// Partitions the component data into multiple sub-batches.
278    ///
279    /// Specifically, this transforms the existing [`SerializedComponentBatch`]es data into [`SerializedComponentColumn`]s
280    /// instead, via [`SerializedComponentBatch::partitioned`].
281    ///
282    /// This makes it possible to use `RecordingStream::send_columns` to send columnar data directly into Rerun.
283    ///
284    /// The specified `lengths` must sum to the total length of the component batch.
285    ///
286    /// [`SerializedComponentColumn`]: [::re_types_core::SerializedComponentColumn]
287    #[inline]
288    pub fn columns<I>(
289        self,
290        _lengths: I,
291    ) -> SerializationResult<impl Iterator<Item = ::re_types_core::SerializedComponentColumn>>
292    where
293        I: IntoIterator<Item = usize> + Clone,
294    {
295        let columns = [
296            self.blob
297                .map(|blob| blob.partitioned(_lengths.clone()))
298                .transpose()?,
299            self.media_type
300                .map(|media_type| media_type.partitioned(_lengths.clone()))
301                .transpose()?,
302            self.albedo_factor
303                .map(|albedo_factor| albedo_factor.partitioned(_lengths.clone()))
304                .transpose()?,
305        ];
306        Ok(columns
307            .into_iter()
308            .flatten()
309            .chain([::re_types_core::indicator_column::<Self>(
310                _lengths.into_iter().count(),
311            )?]))
312    }
313
314    /// Helper to partition the component data into unit-length sub-batches.
315    ///
316    /// This is semantically similar to calling [`Self::columns`] with `std::iter::take(1).repeat(n)`,
317    /// where `n` is automatically guessed.
318    #[inline]
319    pub fn columns_of_unit_batches(
320        self,
321    ) -> SerializationResult<impl Iterator<Item = ::re_types_core::SerializedComponentColumn>> {
322        let len_blob = self.blob.as_ref().map(|b| b.array.len());
323        let len_media_type = self.media_type.as_ref().map(|b| b.array.len());
324        let len_albedo_factor = self.albedo_factor.as_ref().map(|b| b.array.len());
325        let len = None
326            .or(len_blob)
327            .or(len_media_type)
328            .or(len_albedo_factor)
329            .unwrap_or(0);
330        self.columns(std::iter::repeat(1).take(len))
331    }
332
333    /// The asset's bytes.
334    #[inline]
335    pub fn with_blob(mut self, blob: impl Into<crate::components::Blob>) -> Self {
336        self.blob = try_serialize_field(Self::descriptor_blob(), [blob]);
337        self
338    }
339
340    /// This method makes it possible to pack multiple [`crate::components::Blob`] in a single component batch.
341    ///
342    /// This only makes sense when used in conjunction with [`Self::columns`]. [`Self::with_blob`] should
343    /// be used when logging a single row's worth of data.
344    #[inline]
345    pub fn with_many_blob(
346        mut self,
347        blob: impl IntoIterator<Item = impl Into<crate::components::Blob>>,
348    ) -> Self {
349        self.blob = try_serialize_field(Self::descriptor_blob(), blob);
350        self
351    }
352
353    /// The Media Type of the asset.
354    ///
355    /// Supported values:
356    /// * `model/gltf-binary`
357    /// * `model/gltf+json`
358    /// * `model/obj` (.mtl material files are not supported yet, references are silently ignored)
359    /// * `model/stl`
360    ///
361    /// If omitted, the viewer will try to guess from the data blob.
362    /// If it cannot guess, it won't be able to render the asset.
363    #[inline]
364    pub fn with_media_type(mut self, media_type: impl Into<crate::components::MediaType>) -> Self {
365        self.media_type = try_serialize_field(Self::descriptor_media_type(), [media_type]);
366        self
367    }
368
369    /// This method makes it possible to pack multiple [`crate::components::MediaType`] in a single component batch.
370    ///
371    /// This only makes sense when used in conjunction with [`Self::columns`]. [`Self::with_media_type`] should
372    /// be used when logging a single row's worth of data.
373    #[inline]
374    pub fn with_many_media_type(
375        mut self,
376        media_type: impl IntoIterator<Item = impl Into<crate::components::MediaType>>,
377    ) -> Self {
378        self.media_type = try_serialize_field(Self::descriptor_media_type(), media_type);
379        self
380    }
381
382    /// A color multiplier applied to the whole asset.
383    ///
384    /// For mesh who already have `albedo_factor` in materials,
385    /// it will be overwritten by actual `albedo_factor` of [`archetypes::Asset3D`][crate::archetypes::Asset3D] (if specified).
386    #[inline]
387    pub fn with_albedo_factor(
388        mut self,
389        albedo_factor: impl Into<crate::components::AlbedoFactor>,
390    ) -> Self {
391        self.albedo_factor = try_serialize_field(Self::descriptor_albedo_factor(), [albedo_factor]);
392        self
393    }
394
395    /// This method makes it possible to pack multiple [`crate::components::AlbedoFactor`] in a single component batch.
396    ///
397    /// This only makes sense when used in conjunction with [`Self::columns`]. [`Self::with_albedo_factor`] should
398    /// be used when logging a single row's worth of data.
399    #[inline]
400    pub fn with_many_albedo_factor(
401        mut self,
402        albedo_factor: impl IntoIterator<Item = impl Into<crate::components::AlbedoFactor>>,
403    ) -> Self {
404        self.albedo_factor = try_serialize_field(Self::descriptor_albedo_factor(), albedo_factor);
405        self
406    }
407}
408
409impl ::re_byte_size::SizeBytes for Asset3D {
410    #[inline]
411    fn heap_size_bytes(&self) -> u64 {
412        self.blob.heap_size_bytes()
413            + self.media_type.heap_size_bytes()
414            + self.albedo_factor.heap_size_bytes()
415    }
416}