re_viewer_context 0.38.1

Rerun viewer state that is shared with the viewer's code components.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use arrow::array::ArrayRef;
use re_chunk::{ComponentIdentifier, LatestAtQuery, RowId, TimelineName};
use re_chunk_store::external::re_chunk::Chunk;
use re_entity_db::EntityDb;
use re_log_types::{EntityPath, StoreId, TimeInt, TimePoint, Timeline};
use re_sdk_types::{AsComponents, ComponentBatch, ComponentDescriptor, SerializedComponentBatch};

use crate::{
    ActiveStoreContext, CommandSender, SystemCommand, SystemCommandSender as _, ViewerContext,
};

#[inline]
pub fn blueprint_timeline() -> TimelineName {
    re_string_interner::intern_static!(TimelineName, "blueprint")
}

/// The timepoint to use when writing an update to the blueprint.
pub fn blueprint_timepoint_for_writes(blueprint: &re_entity_db::EntityDb) -> TimePoint {
    let timeline = Timeline::new_sequence(blueprint_timeline());

    let max_time = blueprint
        .time_range_for(timeline.name())
        .map(|range| range.max.as_i64())
        .unwrap_or(0)
        .saturating_add(1);

    TimePoint::from([(timeline, TimeInt::new_temporal(max_time))])
}

impl ActiveStoreContext<'_> {
    /// The timepoint to use when writing an update to the blueprint.
    #[inline]
    pub fn blueprint_timepoint_for_writes(&self) -> TimePoint {
        blueprint_timepoint_for_writes(self.blueprint)
    }
}

/// Helper trait for writing & reading blueprints.
pub trait BlueprintContext {
    fn command_sender(&self) -> &CommandSender;

    fn current_blueprint(&self) -> &EntityDb;

    fn default_blueprint(&self) -> Option<&EntityDb>;

    fn blueprint_query(&self) -> &LatestAtQuery;

    fn save_blueprint_archetype(&self, entity_path: EntityPath, components: &dyn AsComponents) {
        self.save_blueprint_archetypes(entity_path, std::iter::once(components));
    }

    fn save_blueprint_archetypes<'a>(
        &self,
        entity_path: EntityPath,
        archetypes: impl IntoIterator<Item = &'a dyn AsComponents>,
    ) {
        let blueprint = self.current_blueprint();
        let timepoint = blueprint_timepoint_for_writes(blueprint);

        let mut chunk_builder = Chunk::builder(entity_path);
        for archetype in archetypes {
            chunk_builder = chunk_builder.with_archetype_auto_row(timepoint.clone(), archetype);
        }

        let chunk = match chunk_builder.build() {
            Ok(chunk) => chunk,
            Err(err) => {
                re_log::error_once!("Failed to create Chunk for blueprint components: {err}");
                return;
            }
        };

        self.command_sender()
            .send_system(SystemCommand::AppendToStore(
                blueprint.store_id().clone(),
                vec![chunk],
            ));
    }

    fn save_blueprint_component(
        &self,
        entity_path: EntityPath,
        component_descr: &ComponentDescriptor,
        component_batch: &dyn ComponentBatch,
    ) {
        let Some(serialized) = component_batch.serialized(component_descr.clone()) else {
            re_log::warn!("could not serialize components with descriptor `{component_descr}`");
            return;
        };

        self.save_serialized_blueprint_component(entity_path, serialized);
    }

    fn save_static_blueprint_component(
        &self,
        entity_path: EntityPath,
        component_descr: &ComponentDescriptor,
        component_batch: &dyn ComponentBatch,
    ) {
        let Some(serialized) = component_batch.serialized(component_descr.clone()) else {
            re_log::warn!("could not serialize components with descriptor `{component_descr}`");
            return;
        };

        self.save_serialized_static_blueprint_component(entity_path, serialized);
    }

    fn save_serialized_static_blueprint_component(
        &self,
        entity_path: EntityPath,
        component_batch: SerializedComponentBatch,
    ) {
        let blueprint = self.current_blueprint();

        let chunk = match Chunk::builder(entity_path)
            .with_serialized_batch(RowId::new(), TimePoint::STATIC, component_batch)
            .build()
        {
            Ok(chunk) => chunk,
            Err(err) => {
                re_log::error_once!("Failed to create Chunk for blueprint components: {err}");
                return;
            }
        };

        self.command_sender()
            .send_system(SystemCommand::AppendToStore(
                blueprint.store_id().clone(),
                vec![chunk],
            ));
    }

    fn save_serialized_blueprint_component(
        &self,
        entity_path: EntityPath,
        component_batch: SerializedComponentBatch,
    ) {
        self.save_blueprint_array(
            entity_path,
            component_batch.descriptor,
            component_batch.array,
        );
    }

    fn save_blueprint_array(
        &self,
        entity_path: EntityPath,
        component_descr: ComponentDescriptor,
        array: ArrayRef,
    ) {
        let blueprint = self.current_blueprint();
        let timepoint = blueprint_timepoint_for_writes(blueprint);
        self.append_array_to_store(
            blueprint.store_id().clone(),
            timepoint,
            entity_path,
            component_descr,
            array,
        );
    }

    /// Append an array to the given store.
    fn append_array_to_store(
        &self,
        store_id: StoreId,
        timepoint: TimePoint,
        entity_path: EntityPath,
        component_descr: ComponentDescriptor,
        array: ArrayRef,
    ) {
        let chunk = match Chunk::builder(entity_path)
            .with_row(RowId::new(), timepoint, [(component_descr, array)])
            .build()
        {
            Ok(chunk) => chunk,
            Err(err) => {
                re_log::error_once!("Failed to create Chunk: {err}");
                return;
            }
        };

        self.command_sender()
            .send_system(SystemCommand::AppendToStore(store_id, vec![chunk]));
    }

    fn save_static_blueprint_array(
        &self,
        entity_path: EntityPath,
        component_descr: ComponentDescriptor,
        array: ArrayRef,
    ) {
        let blueprint = self.current_blueprint();

        let chunk = match Chunk::builder(entity_path)
            .with_row(RowId::new(), TimePoint::STATIC, [(component_descr, array)])
            .build()
        {
            Ok(chunk) => chunk,
            Err(err) => {
                re_log::error_once!("Failed to create Chunk: {err}");
                return;
            }
        };

        self.command_sender()
            .send_system(SystemCommand::AppendToStore(
                blueprint.store_id().clone(),
                vec![chunk],
            ));
    }

    fn latest_at_in_current_blueprint(
        &self,
        entity_path: &EntityPath,
        components: impl IntoIterator<Item = ComponentIdentifier>,
    ) -> re_query::LatestAtResults {
        self.current_blueprint()
            .latest_at(self.blueprint_query(), entity_path, components)
    }

    /// Queries a raw component from the currently active blueprint.
    ///
    /// Returns `None` for empty arrays, which are written by
    /// [`Self::clear_blueprint_component`] to represent an unset value.
    fn raw_latest_at_in_current_blueprint(
        &self,
        entity_path: &EntityPath,
        component: ComponentIdentifier,
    ) -> Option<ArrayRef> {
        self.current_blueprint()
            .latest_at(self.blueprint_query(), entity_path, [component])
            .get(component)?
            .component_batch_raw(component)
            .filter(|a| !a.is_empty())
    }

    /// Queries a raw component from the default blueprint.
    ///
    /// Returns `None` for empty arrays, which are written by
    /// [`Self::clear_blueprint_component`] to represent an unset value.
    fn raw_latest_at_in_default_blueprint(
        &self,
        entity_path: &EntityPath,
        component: ComponentIdentifier,
    ) -> Option<ArrayRef> {
        self.default_blueprint()?
            .latest_at(self.blueprint_query(), entity_path, [component])
            .get(component)?
            .component_batch_raw(component)
            .filter(|a| !a.is_empty())
    }

    /// Resets a blueprint component to the value it had in the default blueprint.
    fn reset_blueprint_component(
        &self,
        entity_path: EntityPath,
        component_descr: ComponentDescriptor,
    ) {
        if let Some(default_value) =
            self.raw_latest_at_in_default_blueprint(&entity_path, component_descr.component)
        {
            self.save_blueprint_array(entity_path, component_descr, default_value);
        } else {
            self.clear_blueprint_component(entity_path, component_descr);
        }
    }

    /// Clears a component in the blueprint store by logging an empty array if it exists.
    fn clear_blueprint_component(
        &self,
        entity_path: EntityPath,
        component_descr: ComponentDescriptor,
    ) {
        let blueprint = self.current_blueprint();
        let component = component_descr.component;

        let Some(datatype) = blueprint
            .latest_at(self.blueprint_query(), &entity_path, [component])
            .get(component)
            .and_then(|unit| {
                unit.component_batch_raw(component)
                    .map(|array| array.data_type().clone())
            })
        else {
            // There's no component at this path yet, so there's nothing to clear.
            return;
        };

        let timepoint = blueprint_timepoint_for_writes(blueprint);
        let chunk = Chunk::builder(entity_path)
            .with_row(
                RowId::new(),
                timepoint,
                [(
                    component_descr,
                    re_chunk::external::arrow::array::new_empty_array(&datatype),
                )],
            )
            .build();

        match chunk {
            Ok(chunk) => self
                .command_sender()
                .send_system(SystemCommand::AppendToStore(
                    blueprint.store_id().clone(),
                    vec![chunk],
                )),
            Err(err) => {
                re_log::error_once!("Failed to create Chunk for blueprint component: {err}");
            }
        }
    }

    fn clear_static_blueprint_component(
        &self,
        entity_path: EntityPath,
        component_descr: ComponentDescriptor,
    ) {
        let blueprint = self.current_blueprint();
        let component = component_descr.component;

        let Some(datatype) = blueprint
            .latest_at(self.blueprint_query(), &entity_path, [component])
            .get(component)
            .and_then(|unit| {
                unit.component_batch_raw(component)
                    .map(|array| array.data_type().clone())
            })
        else {
            // There's no component at this path yet, so there's nothing to clear.
            return;
        };

        let chunk = Chunk::builder(entity_path)
            .with_row(
                RowId::new(),
                TimePoint::STATIC,
                [(
                    component_descr,
                    re_chunk::external::arrow::array::new_empty_array(&datatype),
                )],
            )
            .build();

        match chunk {
            Ok(chunk) => self
                .command_sender()
                .send_system(SystemCommand::AppendToStore(
                    blueprint.store_id().clone(),
                    vec![chunk],
                )),
            Err(err) => {
                re_log::error_once!("Failed to create Chunk for blueprint component: {err}");
            }
        }
    }
}

impl BlueprintContext for ViewerContext<'_> {
    fn command_sender(&self) -> &CommandSender {
        self.command_sender()
    }

    fn current_blueprint(&self) -> &EntityDb {
        self.store_context.blueprint
    }

    fn default_blueprint(&self) -> Option<&EntityDb> {
        self.store_context.default_blueprint
    }

    fn blueprint_query(&self) -> &LatestAtQuery {
        self.blueprint_query
    }
}

/// Lightweight [`BlueprintContext`] that can be constructed from individual references.
///
/// Useful when you need a [`BlueprintContext`] but don't have a full [`ViewerContext`].
pub struct AppBlueprintCtx<'a> {
    pub command_sender: &'a CommandSender,
    pub current_blueprint: &'a EntityDb,
    pub default_blueprint: Option<&'a EntityDb>,
    pub blueprint_query: LatestAtQuery,
}

impl BlueprintContext for AppBlueprintCtx<'_> {
    fn command_sender(&self) -> &CommandSender {
        self.command_sender
    }

    fn current_blueprint(&self) -> &EntityDb {
        self.current_blueprint
    }

    fn default_blueprint(&self) -> Option<&EntityDb> {
        self.default_blueprint
    }

    fn blueprint_query(&self) -> &LatestAtQuery {
        &self.blueprint_query
    }
}