re_types/archetypes/
segmentation_image.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/segmentation_image.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**: An image made up of integer [`components::ClassId`][crate::components::ClassId]s.
22///
23/// Each pixel corresponds to a [`components::ClassId`][crate::components::ClassId] that will be mapped to a color based on [`archetypes::AnnotationContext`][crate::archetypes::AnnotationContext].
24///
25/// In the case of floating point images, the label will be looked up based on rounding to the nearest
26/// integer value.
27///
28/// Use [`archetypes::AnnotationContext`][crate::archetypes::AnnotationContext] to associate each class with a color and a label.
29///
30/// ## Example
31///
32/// ### Simple segmentation image
33/// ```ignore
34/// use ndarray::{s, Array, ShapeBuilder as _};
35///
36/// fn main() -> Result<(), Box<dyn std::error::Error>> {
37///     let rec = rerun::RecordingStreamBuilder::new("rerun_example_segmentation_image").spawn()?;
38///
39///     // create a segmentation image
40///     let mut image = Array::<u8, _>::zeros((8, 12).f());
41///     image.slice_mut(s![0..4, 0..6]).fill(1);
42///     image.slice_mut(s![4..8, 6..12]).fill(2);
43///
44///     // create an annotation context to describe the classes
45///     let annotation = rerun::AnnotationContext::new([
46///         (1, "red", rerun::Rgba32::from_rgb(255, 0, 0)),
47///         (2, "green", rerun::Rgba32::from_rgb(0, 255, 0)),
48///     ]);
49///
50///     // log the annotation and the image
51///     rec.log_static("/", &annotation)?;
52///
53///     rec.log("image", &rerun::SegmentationImage::try_from(image)?)?;
54///
55///     Ok(())
56/// }
57/// ```
58/// <center>
59/// <picture>
60///   <source media="(max-width: 480px)" srcset="https://static.rerun.io/segmentation_image_simple/f8aac62abcf4c59c5d62f9ebc2d86fd0285c1736/480w.png">
61///   <source media="(max-width: 768px)" srcset="https://static.rerun.io/segmentation_image_simple/f8aac62abcf4c59c5d62f9ebc2d86fd0285c1736/768w.png">
62///   <source media="(max-width: 1024px)" srcset="https://static.rerun.io/segmentation_image_simple/f8aac62abcf4c59c5d62f9ebc2d86fd0285c1736/1024w.png">
63///   <source media="(max-width: 1200px)" srcset="https://static.rerun.io/segmentation_image_simple/f8aac62abcf4c59c5d62f9ebc2d86fd0285c1736/1200w.png">
64///   <img src="https://static.rerun.io/segmentation_image_simple/f8aac62abcf4c59c5d62f9ebc2d86fd0285c1736/full.png" width="640">
65/// </picture>
66/// </center>
67#[derive(Clone, Debug, PartialEq, Default)]
68pub struct SegmentationImage {
69    /// The raw image data.
70    pub buffer: Option<SerializedComponentBatch>,
71
72    /// The format of the image.
73    pub format: Option<SerializedComponentBatch>,
74
75    /// Opacity of the image, useful for layering the segmentation image on top of another image.
76    ///
77    /// Defaults to 0.5 if there's any other images in the scene, otherwise 1.0.
78    pub opacity: Option<SerializedComponentBatch>,
79
80    /// An optional floating point value that specifies the 2D drawing order.
81    ///
82    /// Objects with higher values are drawn on top of those with lower values.
83    pub draw_order: Option<SerializedComponentBatch>,
84}
85
86impl SegmentationImage {
87    /// Returns the [`ComponentDescriptor`] for [`Self::buffer`].
88    #[inline]
89    pub fn descriptor_buffer() -> ComponentDescriptor {
90        ComponentDescriptor {
91            archetype_name: Some("rerun.archetypes.SegmentationImage".into()),
92            component_name: "rerun.components.ImageBuffer".into(),
93            archetype_field_name: Some("buffer".into()),
94        }
95    }
96
97    /// Returns the [`ComponentDescriptor`] for [`Self::format`].
98    #[inline]
99    pub fn descriptor_format() -> ComponentDescriptor {
100        ComponentDescriptor {
101            archetype_name: Some("rerun.archetypes.SegmentationImage".into()),
102            component_name: "rerun.components.ImageFormat".into(),
103            archetype_field_name: Some("format".into()),
104        }
105    }
106
107    /// Returns the [`ComponentDescriptor`] for [`Self::opacity`].
108    #[inline]
109    pub fn descriptor_opacity() -> ComponentDescriptor {
110        ComponentDescriptor {
111            archetype_name: Some("rerun.archetypes.SegmentationImage".into()),
112            component_name: "rerun.components.Opacity".into(),
113            archetype_field_name: Some("opacity".into()),
114        }
115    }
116
117    /// Returns the [`ComponentDescriptor`] for [`Self::draw_order`].
118    #[inline]
119    pub fn descriptor_draw_order() -> ComponentDescriptor {
120        ComponentDescriptor {
121            archetype_name: Some("rerun.archetypes.SegmentationImage".into()),
122            component_name: "rerun.components.DrawOrder".into(),
123            archetype_field_name: Some("draw_order".into()),
124        }
125    }
126
127    /// Returns the [`ComponentDescriptor`] for the associated indicator component.
128    #[inline]
129    pub fn descriptor_indicator() -> ComponentDescriptor {
130        ComponentDescriptor {
131            archetype_name: Some("rerun.archetypes.SegmentationImage".into()),
132            component_name: "rerun.components.SegmentationImageIndicator".into(),
133            archetype_field_name: None,
134        }
135    }
136}
137
138static REQUIRED_COMPONENTS: once_cell::sync::Lazy<[ComponentDescriptor; 2usize]> =
139    once_cell::sync::Lazy::new(|| {
140        [
141            SegmentationImage::descriptor_buffer(),
142            SegmentationImage::descriptor_format(),
143        ]
144    });
145
146static RECOMMENDED_COMPONENTS: once_cell::sync::Lazy<[ComponentDescriptor; 1usize]> =
147    once_cell::sync::Lazy::new(|| [SegmentationImage::descriptor_indicator()]);
148
149static OPTIONAL_COMPONENTS: once_cell::sync::Lazy<[ComponentDescriptor; 2usize]> =
150    once_cell::sync::Lazy::new(|| {
151        [
152            SegmentationImage::descriptor_opacity(),
153            SegmentationImage::descriptor_draw_order(),
154        ]
155    });
156
157static ALL_COMPONENTS: once_cell::sync::Lazy<[ComponentDescriptor; 5usize]> =
158    once_cell::sync::Lazy::new(|| {
159        [
160            SegmentationImage::descriptor_buffer(),
161            SegmentationImage::descriptor_format(),
162            SegmentationImage::descriptor_indicator(),
163            SegmentationImage::descriptor_opacity(),
164            SegmentationImage::descriptor_draw_order(),
165        ]
166    });
167
168impl SegmentationImage {
169    /// The total number of components in the archetype: 2 required, 1 recommended, 2 optional
170    pub const NUM_COMPONENTS: usize = 5usize;
171}
172
173/// Indicator component for the [`SegmentationImage`] [`::re_types_core::Archetype`]
174pub type SegmentationImageIndicator = ::re_types_core::GenericIndicatorComponent<SegmentationImage>;
175
176impl ::re_types_core::Archetype for SegmentationImage {
177    type Indicator = SegmentationImageIndicator;
178
179    #[inline]
180    fn name() -> ::re_types_core::ArchetypeName {
181        "rerun.archetypes.SegmentationImage".into()
182    }
183
184    #[inline]
185    fn display_name() -> &'static str {
186        "Segmentation image"
187    }
188
189    #[inline]
190    fn indicator() -> SerializedComponentBatch {
191        #[allow(clippy::unwrap_used)]
192        SegmentationImageIndicator::DEFAULT.serialized().unwrap()
193    }
194
195    #[inline]
196    fn required_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
197        REQUIRED_COMPONENTS.as_slice().into()
198    }
199
200    #[inline]
201    fn recommended_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
202        RECOMMENDED_COMPONENTS.as_slice().into()
203    }
204
205    #[inline]
206    fn optional_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
207        OPTIONAL_COMPONENTS.as_slice().into()
208    }
209
210    #[inline]
211    fn all_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
212        ALL_COMPONENTS.as_slice().into()
213    }
214
215    #[inline]
216    fn from_arrow_components(
217        arrow_data: impl IntoIterator<Item = (ComponentDescriptor, arrow::array::ArrayRef)>,
218    ) -> DeserializationResult<Self> {
219        re_tracing::profile_function!();
220        use ::re_types_core::{Loggable as _, ResultExt as _};
221        let arrays_by_descr: ::nohash_hasher::IntMap<_, _> = arrow_data.into_iter().collect();
222        let buffer = arrays_by_descr
223            .get(&Self::descriptor_buffer())
224            .map(|array| SerializedComponentBatch::new(array.clone(), Self::descriptor_buffer()));
225        let format = arrays_by_descr
226            .get(&Self::descriptor_format())
227            .map(|array| SerializedComponentBatch::new(array.clone(), Self::descriptor_format()));
228        let opacity = arrays_by_descr
229            .get(&Self::descriptor_opacity())
230            .map(|array| SerializedComponentBatch::new(array.clone(), Self::descriptor_opacity()));
231        let draw_order = arrays_by_descr
232            .get(&Self::descriptor_draw_order())
233            .map(|array| {
234                SerializedComponentBatch::new(array.clone(), Self::descriptor_draw_order())
235            });
236        Ok(Self {
237            buffer,
238            format,
239            opacity,
240            draw_order,
241        })
242    }
243}
244
245impl ::re_types_core::AsComponents for SegmentationImage {
246    #[inline]
247    fn as_serialized_batches(&self) -> Vec<SerializedComponentBatch> {
248        use ::re_types_core::Archetype as _;
249        [
250            Some(Self::indicator()),
251            self.buffer.clone(),
252            self.format.clone(),
253            self.opacity.clone(),
254            self.draw_order.clone(),
255        ]
256        .into_iter()
257        .flatten()
258        .collect()
259    }
260}
261
262impl ::re_types_core::ArchetypeReflectionMarker for SegmentationImage {}
263
264impl SegmentationImage {
265    /// Create a new `SegmentationImage`.
266    #[inline]
267    pub fn new(
268        buffer: impl Into<crate::components::ImageBuffer>,
269        format: impl Into<crate::components::ImageFormat>,
270    ) -> Self {
271        Self {
272            buffer: try_serialize_field(Self::descriptor_buffer(), [buffer]),
273            format: try_serialize_field(Self::descriptor_format(), [format]),
274            opacity: None,
275            draw_order: None,
276        }
277    }
278
279    /// Update only some specific fields of a `SegmentationImage`.
280    #[inline]
281    pub fn update_fields() -> Self {
282        Self::default()
283    }
284
285    /// Clear all the fields of a `SegmentationImage`.
286    #[inline]
287    pub fn clear_fields() -> Self {
288        use ::re_types_core::Loggable as _;
289        Self {
290            buffer: Some(SerializedComponentBatch::new(
291                crate::components::ImageBuffer::arrow_empty(),
292                Self::descriptor_buffer(),
293            )),
294            format: Some(SerializedComponentBatch::new(
295                crate::components::ImageFormat::arrow_empty(),
296                Self::descriptor_format(),
297            )),
298            opacity: Some(SerializedComponentBatch::new(
299                crate::components::Opacity::arrow_empty(),
300                Self::descriptor_opacity(),
301            )),
302            draw_order: Some(SerializedComponentBatch::new(
303                crate::components::DrawOrder::arrow_empty(),
304                Self::descriptor_draw_order(),
305            )),
306        }
307    }
308
309    /// Partitions the component data into multiple sub-batches.
310    ///
311    /// Specifically, this transforms the existing [`SerializedComponentBatch`]es data into [`SerializedComponentColumn`]s
312    /// instead, via [`SerializedComponentBatch::partitioned`].
313    ///
314    /// This makes it possible to use `RecordingStream::send_columns` to send columnar data directly into Rerun.
315    ///
316    /// The specified `lengths` must sum to the total length of the component batch.
317    ///
318    /// [`SerializedComponentColumn`]: [::re_types_core::SerializedComponentColumn]
319    #[inline]
320    pub fn columns<I>(
321        self,
322        _lengths: I,
323    ) -> SerializationResult<impl Iterator<Item = ::re_types_core::SerializedComponentColumn>>
324    where
325        I: IntoIterator<Item = usize> + Clone,
326    {
327        let columns = [
328            self.buffer
329                .map(|buffer| buffer.partitioned(_lengths.clone()))
330                .transpose()?,
331            self.format
332                .map(|format| format.partitioned(_lengths.clone()))
333                .transpose()?,
334            self.opacity
335                .map(|opacity| opacity.partitioned(_lengths.clone()))
336                .transpose()?,
337            self.draw_order
338                .map(|draw_order| draw_order.partitioned(_lengths.clone()))
339                .transpose()?,
340        ];
341        Ok(columns
342            .into_iter()
343            .flatten()
344            .chain([::re_types_core::indicator_column::<Self>(
345                _lengths.into_iter().count(),
346            )?]))
347    }
348
349    /// Helper to partition the component data into unit-length sub-batches.
350    ///
351    /// This is semantically similar to calling [`Self::columns`] with `std::iter::take(1).repeat(n)`,
352    /// where `n` is automatically guessed.
353    #[inline]
354    pub fn columns_of_unit_batches(
355        self,
356    ) -> SerializationResult<impl Iterator<Item = ::re_types_core::SerializedComponentColumn>> {
357        let len_buffer = self.buffer.as_ref().map(|b| b.array.len());
358        let len_format = self.format.as_ref().map(|b| b.array.len());
359        let len_opacity = self.opacity.as_ref().map(|b| b.array.len());
360        let len_draw_order = self.draw_order.as_ref().map(|b| b.array.len());
361        let len = None
362            .or(len_buffer)
363            .or(len_format)
364            .or(len_opacity)
365            .or(len_draw_order)
366            .unwrap_or(0);
367        self.columns(std::iter::repeat(1).take(len))
368    }
369
370    /// The raw image data.
371    #[inline]
372    pub fn with_buffer(mut self, buffer: impl Into<crate::components::ImageBuffer>) -> Self {
373        self.buffer = try_serialize_field(Self::descriptor_buffer(), [buffer]);
374        self
375    }
376
377    /// This method makes it possible to pack multiple [`crate::components::ImageBuffer`] in a single component batch.
378    ///
379    /// This only makes sense when used in conjunction with [`Self::columns`]. [`Self::with_buffer`] should
380    /// be used when logging a single row's worth of data.
381    #[inline]
382    pub fn with_many_buffer(
383        mut self,
384        buffer: impl IntoIterator<Item = impl Into<crate::components::ImageBuffer>>,
385    ) -> Self {
386        self.buffer = try_serialize_field(Self::descriptor_buffer(), buffer);
387        self
388    }
389
390    /// The format of the image.
391    #[inline]
392    pub fn with_format(mut self, format: impl Into<crate::components::ImageFormat>) -> Self {
393        self.format = try_serialize_field(Self::descriptor_format(), [format]);
394        self
395    }
396
397    /// This method makes it possible to pack multiple [`crate::components::ImageFormat`] in a single component batch.
398    ///
399    /// This only makes sense when used in conjunction with [`Self::columns`]. [`Self::with_format`] should
400    /// be used when logging a single row's worth of data.
401    #[inline]
402    pub fn with_many_format(
403        mut self,
404        format: impl IntoIterator<Item = impl Into<crate::components::ImageFormat>>,
405    ) -> Self {
406        self.format = try_serialize_field(Self::descriptor_format(), format);
407        self
408    }
409
410    /// Opacity of the image, useful for layering the segmentation image on top of another image.
411    ///
412    /// Defaults to 0.5 if there's any other images in the scene, otherwise 1.0.
413    #[inline]
414    pub fn with_opacity(mut self, opacity: impl Into<crate::components::Opacity>) -> Self {
415        self.opacity = try_serialize_field(Self::descriptor_opacity(), [opacity]);
416        self
417    }
418
419    /// This method makes it possible to pack multiple [`crate::components::Opacity`] in a single component batch.
420    ///
421    /// This only makes sense when used in conjunction with [`Self::columns`]. [`Self::with_opacity`] should
422    /// be used when logging a single row's worth of data.
423    #[inline]
424    pub fn with_many_opacity(
425        mut self,
426        opacity: impl IntoIterator<Item = impl Into<crate::components::Opacity>>,
427    ) -> Self {
428        self.opacity = try_serialize_field(Self::descriptor_opacity(), opacity);
429        self
430    }
431
432    /// An optional floating point value that specifies the 2D drawing order.
433    ///
434    /// Objects with higher values are drawn on top of those with lower values.
435    #[inline]
436    pub fn with_draw_order(mut self, draw_order: impl Into<crate::components::DrawOrder>) -> Self {
437        self.draw_order = try_serialize_field(Self::descriptor_draw_order(), [draw_order]);
438        self
439    }
440
441    /// This method makes it possible to pack multiple [`crate::components::DrawOrder`] in a single component batch.
442    ///
443    /// This only makes sense when used in conjunction with [`Self::columns`]. [`Self::with_draw_order`] should
444    /// be used when logging a single row's worth of data.
445    #[inline]
446    pub fn with_many_draw_order(
447        mut self,
448        draw_order: impl IntoIterator<Item = impl Into<crate::components::DrawOrder>>,
449    ) -> Self {
450        self.draw_order = try_serialize_field(Self::descriptor_draw_order(), draw_order);
451        self
452    }
453}
454
455impl ::re_byte_size::SizeBytes for SegmentationImage {
456    #[inline]
457    fn heap_size_bytes(&self) -> u64 {
458        self.buffer.heap_size_bytes()
459            + self.format.heap_size_bytes()
460            + self.opacity.heap_size_bytes()
461            + self.draw_order.heap_size_bytes()
462    }
463}