Skip to main content

ssruntime/context/
mod.rs

1//! [`Context`]: the playback state of one character, and the per-frame evaluation that turns it into frame data.
2
3use alloc::vec::Vec;
4
5use crate::mix::{LayerState, NO_EVENT_THRESHOLD, SourceState, TrackBlend, TrackFade, TrackState, count_attribute_capacities, reserve_total};
6use crate::resource::{AnimationMetadata, AnimationResource, fnv1a_hash_str};
7use crate::{error, eval};
8
9mod buffers;
10mod events;
11mod frame;
12mod overrides;
13mod playback;
14mod tracks;
15
16/// Per-instance global buffers — the output of `resolve_global_state`.
17/// World matrices, UVs, and shape vertices are composited from the resolved
18/// (post-mix) pose; they are not per-layer.
19pub(crate) struct GlobalBuffers {
20    world_matrices: Vec<crate::eval::SsMatrix4x4>,
21    inheritance_matrices: Vec<crate::eval::SsMatrix4x4>,
22    pub(crate) local_uvs: Vec<f32>,
23    shape_vertices: Vec<f32>,
24    shape_vertex_box_coords: Vec<f32>,
25    shape_vertex_counts: Vec<i32>,
26    /// Skinned mesh world-space vertex positions, concatenated across all parts.
27    /// Use `mesh_vertex_offsets` to slice per-part ranges:
28    ///   part `p` occupies `mesh_vertex_offsets[p]..mesh_vertex_offsets[p + 1]`.
29    /// Non-mesh parts contribute an empty range.
30    mesh_vertices_x: Vec<f32>,
31    mesh_vertices_y: Vec<f32>,
32    /// CSR-style prefix sum, length = `num_parts + 1`.
33    mesh_vertex_offsets: Vec<u32>,
34    /// The mesh layout (`AnimationMetadata::mesh_layout`) whose static UVs and
35    /// triangle indices the getters hand out, and that `mesh_vertex_offsets`
36    /// and the vertex buffers are sized for; [`NO_MESH_LAYOUT`] until
37    /// `compute_mesh_vertices` sets them up, and in SceneGraph mode. The buffers
38    /// themselves are the animation's, shared by every instance.
39    mesh_layout: usize,
40    /// Per-frame Nine-Slice grids, CSR-sliced per part. Written by
41    /// `compose_frame_data` (the draw plan needs the counts), not by
42    /// `resolve_global_state`.
43    nines: crate::eval::framedata::NinesBuffers,
44}
45
46impl GlobalBuffers {
47    fn new() -> Self {
48        Self {
49            world_matrices: Vec::new(),
50            inheritance_matrices: Vec::new(),
51            local_uvs: Vec::new(),
52            shape_vertices: Vec::new(),
53            shape_vertex_box_coords: Vec::new(),
54            shape_vertex_counts: Vec::new(),
55            mesh_vertices_x: Vec::new(),
56            mesh_vertices_y: Vec::new(),
57            mesh_vertex_offsets: Vec::new(),
58            mesh_layout: NO_MESH_LAYOUT,
59            nines: crate::eval::framedata::NinesBuffers::default(),
60        }
61    }
62}
63
64/// `GlobalBuffers::mesh_layout` before the static mesh buffers are set up.
65const NO_MESH_LAYOUT: usize = usize::MAX;
66
67/// Static / shareable evaluation context. The resource borrow and the
68/// FlatBufferBuilder workspace live here because they are what Animation
69/// Instancing (ROADMAP.md) would share: one resource and one fb workspace
70/// driving N instances serially.
71pub(crate) struct EvaluationContext<'a> {
72    resource: Option<&'a AnimationResource<'a>>,
73    fb: flatbuffers::FlatBufferBuilder<'a>,
74    /// Whether `fb` currently holds a finished frame-data buffer. Guards the
75    /// zero-copy accessors: `finished_data()` asserts on an unfinished builder,
76    /// and `panic = "abort"` makes that assert fatal.
77    frame_data_ready: bool,
78    /// The largest frame data `fb` has finished, and the capacity it was last
79    /// given. The builder grows by doubling, so a frame that outgrows the
80    /// capacity leaves up to half of it unused; the next frame starts on a
81    /// builder sized to the largest frame instead.
82    fb_need: usize,
83    pub(crate) fb_capacity: usize,
84
85    // Workspace buffers to avoid per-frame allocations
86    draw_order_workspace: Vec<u16>,
87    batches_workspace: Vec<crate::runtime::framedata::ss::runtime::DrawBatch>,
88    mask_indices_workspace: Vec<u16>,
89    deform_interpolation_start_workspace: Vec<f32>,
90    deform_interpolation_end_workspace: Vec<f32>,
91    deform_interpolation_out_workspace: Vec<f32>,
92    deform_result_coordinate_workspace: Vec<crate::runtime::framedata::ss::runtime::Vec2>,
93    deform_result_index_workspace: Vec<i16>,
94    inheritance_alphas_workspace: Vec<f32>,
95    /// Scratch for the Override Layer's force-hide cascade forward pass.
96    override_hide_workspace: Vec<bool>,
97    /// Scratch copy of the primary controller's traversed frames, so the seam
98    /// can read them while the override table is borrowed mutably.
99    override_passed_frames_workspace: Vec<i32>,
100}
101
102impl<'a> EvaluationContext<'a> {
103    fn new() -> Self {
104        Self {
105            resource: None,
106            fb: flatbuffers::FlatBufferBuilder::new(),
107            frame_data_ready: false,
108            fb_need: 0,
109            fb_capacity: 0,
110            draw_order_workspace: Vec::new(),
111            batches_workspace: Vec::new(),
112            mask_indices_workspace: Vec::new(),
113            deform_interpolation_start_workspace: Vec::new(),
114            deform_interpolation_end_workspace: Vec::new(),
115            deform_interpolation_out_workspace: Vec::new(),
116            deform_result_coordinate_workspace: Vec::new(),
117            deform_result_index_workspace: Vec::new(),
118            inheritance_alphas_workspace: Vec::new(),
119            override_hide_workspace: Vec::new(),
120            override_passed_frames_workspace: Vec::new(),
121        }
122    }
123}
124
125/// The transport of the whole character. A source's own controller keeps its
126/// playhead, speed, loop count and section, but whether it moves at all is
127/// decided here, so a source attached mid-playback moves with the rest and
128/// pause / stop reach every track. Track 0 finishing does not stop it: the
129/// other tracks and the fades carry on.
130#[derive(Debug, Clone, Copy, Default)]
131struct CharacterClock {
132    /// Set by `play`, cleared by `stop` and by a new setup.
133    playing: bool,
134    /// A hold on a playing clock. Never set while `playing` is false.
135    pausing: bool,
136}
137
138impl CharacterClock {
139    fn is_running(&self) -> bool {
140        self.playing && !self.pausing
141    }
142}
143
144/// Per-instance playback state. Owns one playback source per blend layer,
145/// the per-source pose buffers (`layers`), the post-mix pose
146/// (`resolved_layer`) that feeds global resolution, the resolved global
147/// buffers, and the configuration knobs that influence frame evaluation.
148/// Kept apart from `EvaluationContext` so that many of these can share one.
149///
150/// `sources` and `layers` are kept length-parallel and always contain at
151/// least one slot (the primary). The `primary` field designates the
152/// authoritative source for events and non-blendable discrete attributes.
153pub(crate) struct InstanceState<'a> {
154    /// Whether the character is playing, and held. Every source on every track
155    /// advances on this one clock, and every fade with it.
156    clock: CharacterClock,
157    pub(crate) sources: Vec<SourceState>,
158    /// The track stack, ascending. Always holds at least track 0, which carries
159    /// the structure (discrete attributes and events) for the whole instance.
160    pub(crate) tracks: Vec<TrackState>,
161    pub(crate) layers: Vec<LayerState<'a>>,
162    pub(crate) resolved_layer: LayerState<'a>,
163    pub(crate) primary: u32,
164    z_order: crate::eval::z_order::ZOrderTable,
165    pub(crate) globals: GlobalBuffers,
166    collected_event_indices: Vec<i32>,
167    /// Parallel to `collected_event_indices`: source handle that fired each
168    /// collected event. At the default event threshold every entry equals
169    /// `primary` — "track 0's animation fires events". When other sources
170    /// opt in (lower threshold), entries record the firing source.
171    collected_event_source_handles: Vec<u32>,
172    pub(crate) coordinate_system: crate::eval::SsCoordinateSystem,
173    pub(crate) origin: crate::eval::SsOrigin,
174    pub(crate) unit: crate::eval::SsUnit,
175    render_mode: crate::eval::RenderMode,
176    /// Per-part runtime Override Layer table. Dense by `part_index`,
177    /// `None` = no override. Created at the part count by the first override
178    /// set on the instance, and dropped again when a new animation leaves no
179    /// override in it, so an instance that overrides nothing never allocates it.
180    pub(crate) part_overrides: Vec<Option<crate::eval::override_layer::PartOverride>>,
181    /// Per-part resolved cell meta recorded by the seam when a cell override is
182    /// applied, so `compute_local_uvs` samples the overridden cell (not just the
183    /// geometry/texture channels). Empty when no override is active this frame.
184    override_cell_uv_meta: Vec<Option<crate::eval::framedata::ResolvedCellMeta>>,
185    /// How many times `Context::update` has run: the update an evaluation
186    /// belongs to, which an OverwriteOnNextKeyframe override's first evaluation records.
187    updates: u64,
188}
189
190impl<'a> InstanceState<'a> {
191    fn new() -> Self {
192        Self {
193            clock: CharacterClock::default(),
194            sources: alloc::vec![SourceState::new()],
195            tracks: alloc::vec![TrackState::new()],
196            layers: alloc::vec![LayerState::new()],
197            resolved_layer: LayerState::new(),
198            primary: 0,
199            z_order: crate::eval::z_order::ZOrderTable::new(),
200            globals: GlobalBuffers::new(),
201            collected_event_indices: Vec::new(),
202            collected_event_source_handles: Vec::new(),
203            coordinate_system: crate::eval::SsCoordinateSystem::default(),
204            origin: crate::eval::SsOrigin::default(),
205            unit: crate::eval::SsUnit::default(),
206            render_mode: crate::eval::RenderMode::default(),
207            part_overrides: Vec::new(),
208            override_cell_uv_meta: Vec::new(),
209            updates: 0,
210        }
211    }
212
213    /// `true` when at least one part carries an active override — gates the
214    /// per-frame seam work in `get_frame_data`.
215    pub(crate) fn has_any_override(&self) -> bool {
216        self.part_overrides.iter().any(|o| o.as_ref().is_some_and(|p| !p.is_empty()))
217    }
218
219    /// Drop the slot back to `None` if the entry no longer carries any override,
220    /// keeping [`has_any_override`](Self::has_any_override) cheap and the
221    /// lifecycle bookkeeping simple.
222    fn compact_override(&mut self, idx: usize) {
223        if let Some(entry) = self.part_overrides.get_mut(idx)
224            && entry.as_ref().is_some_and(|p| p.is_empty())
225        {
226            *entry = None;
227        }
228    }
229
230    /// On a new animation within the same SSAB: drop Visibility and OverwriteOnNextKeyframe and
231    /// HoldUntilNextAnimation Color/Cell overrides, keep Permanent ones, then resize to the
232    /// new part count (part identity is stable within an SSAB; parts beyond the
233    /// new count are dropped by the resize — the Permanent re-validation).
234    fn retain_permanent_overrides_on_setup(&mut self, num_parts: usize) {
235        use crate::eval::override_layer::PriorityMode;
236        if self.part_overrides.is_empty() {
237            return;
238        }
239        for entry in self.part_overrides.iter_mut() {
240            let Some(p) = entry.as_mut() else { continue };
241            p.visibility = None;
242            if p.color.as_ref().is_some_and(|c| c.priority != PriorityMode::Permanent) {
243                p.color = None;
244            }
245            if p.cell.as_ref().is_some_and(|c| c.priority != PriorityMode::Permanent) {
246                p.cell = None;
247            }
248            if p.is_empty() {
249                *entry = None;
250            }
251        }
252        if self.part_overrides.iter().all(Option::is_none) {
253            self.part_overrides = Vec::new();
254        } else {
255            self.part_overrides.resize(num_parts, None);
256        }
257    }
258
259    fn primary_idx(&self) -> usize {
260        self.primary as usize
261    }
262
263    /// Reset the stack to a single track carrying a single source. Called when a
264    /// new animation is set up: an instance's tracks belong to the animation that
265    /// established them, so they do not survive a re-setup.
266    fn collapse_to_track_zero(&mut self) {
267        // The collected events read against these sources, and their handles would
268        // name whatever the slots hold next.
269        self.collected_event_indices.clear();
270        self.collected_event_source_handles.clear();
271        self.sources.truncate(1);
272        self.layers.truncate(1);
273        // Rebuilding the slot must not read as a reset of the host's playback
274        // policy: this runs inside every `setup_animation`, and the speed /
275        // frame-skip / frame-rate override deliberately outlive an animation
276        // change. They are track 0's, not slot 0's: after a crossfade slot 0
277        // may be a released source at the defaults. `Context::reset` clears
278        // them explicitly afterwards, because that one really is a teardown.
279        let policy = self.tracks[0].policy;
280        let outgoing_event_threshold = self.tracks[0].outgoing_event_threshold;
281        self.sources[0] = SourceState::new();
282        self.sources[0].controller.adopt_policy(&policy);
283        self.tracks.truncate(1);
284        self.tracks[0] = TrackState::new();
285        self.tracks[0].policy = policy;
286        self.tracks[0].outgoing_event_threshold = outgoing_event_threshold;
287        self.tracks[0].main = 0;
288        self.primary = 0;
289    }
290
291    pub(crate) fn primary_source(&self) -> &SourceState {
292        &self.sources[self.primary_idx()]
293    }
294
295    fn primary_source_mut(&mut self) -> &mut SourceState {
296        let idx = self.primary_idx();
297        &mut self.sources[idx]
298    }
299
300    /// `true` when the primary alone decides the pose: it is active, its track
301    /// mixes at full alpha, and no other active source is on an audible track.
302    /// The mix would yield the primary's pose verbatim, so the pose is
303    /// extracted straight into the resolved layer instead, which skips the
304    /// per-part vec clone + 27 per-part PartState setter calls and the
305    /// primary's own layer.
306    fn is_single_full_track(&self) -> bool {
307        let primary_idx = self.primary_idx();
308        let primary = &self.sources[primary_idx];
309        if !primary.is_active() {
310            return false;
311        }
312        // Any second audible source, or a track that would lerp/offset rather than
313        // pass its source through, means the fold has real work to do.
314        let track = &self.tracks[primary.track as usize];
315        if track.alpha != 1.0 || track.blend != TrackBlend::Mix {
316            return false;
317        }
318        !self.sources.iter().enumerate().any(|(i, s)| i != primary_idx && s.is_active() && self.tracks[s.track as usize].is_audible())
319    }
320
321    /// Change one setting of `track`'s playback policy, and the same setting on
322    /// every source the track carries now (both sides of a crossfade included),
323    /// so the policy and what is playing never disagree. The caller has made
324    /// sure the track exists.
325    fn set_track_policy(&mut self, track: u32, policy: impl FnOnce(&mut eval::playback_controller::PlaybackPolicy), controller: impl Fn(&mut eval::playback_controller::PlaybackController)) {
326        policy(&mut self.tracks[track as usize].policy);
327        for source in self.sources.iter_mut() {
328            if source.track as u32 == track && source.has_real_animation() {
329                controller(&mut source.controller);
330            }
331        }
332    }
333
334    /// Whether source `i`, which is not the primary, fires the events it passes.
335    /// On the outgoing side of a crossfade it is the side's share of the track
336    /// that is measured, against the track's threshold, so a side of several
337    /// sources goes quiet at once; anywhere else, its own weight against its own
338    /// threshold.
339    fn source_fires_events(&self, i: usize) -> bool {
340        let source = &self.sources[i];
341        let track = &self.tracks[source.track as usize];
342        if let Some(fade @ TrackFade::Cross { to, .. }) = track.fade
343            && to as usize != i
344            && source.outgoing_share > 0.0
345        {
346            return 1.0 - fade.progress() >= track.outgoing_event_threshold;
347        }
348        source.weight >= source.event_threshold
349    }
350
351    /// The controller of the source carrying `track`'s animation.
352    fn track_main_controller(&self, track: u32) -> Option<&eval::playback_controller::PlaybackController> {
353        let main = self.tracks.get(track as usize)?.main;
354        let source = self.sources.get(main as usize)?;
355        source.has_real_animation().then_some(&source.controller)
356    }
357}
358
359/// The playback state of one animated object: a stack of tracks, each playing an
360/// animation of the bound resource, layered onto the setup pose. Bind a resource
361/// with [`Self::bind_resource`] and select an animation with
362/// [`Self::setup_animation`] before playing.
363pub struct Context<'a> {
364    eval: EvaluationContext<'a>,
365    instance: InstanceState<'a>,
366}
367
368impl<'a> Default for Context<'a> {
369    fn default() -> Self {
370        Self::new()
371    }
372}
373
374/// Read-only access to the internals, for the unit tests in `crate::tests`.
375#[cfg(all(test, feature = "std"))]
376impl<'a> Context<'a> {
377    pub(crate) fn eval(&self) -> &EvaluationContext<'a> {
378        &self.eval
379    }
380
381    pub(crate) fn instance(&self) -> &InstanceState<'a> {
382        &self.instance
383    }
384}
385
386impl<'a> Context<'a> {
387    /// An empty context.
388    pub fn new() -> Self {
389        Context { eval: EvaluationContext::new(), instance: InstanceState::new() }
390    }
391
392    /// Back to the just-created state: the resource is unbound, and the overrides
393    /// and the playback and coordinate settings are cleared.
394    pub fn reset(&mut self) {
395        self.eval.resource = None;
396        self.eval.fb.reset();
397        self.eval.frame_data_ready = false;
398        self.instance.collapse_to_track_zero();
399        // A teardown, not an animation change: the host's playback policy goes
400        // with it, which `collapse_to_track_zero` alone would have carried over.
401        self.instance.tracks[0].policy = eval::playback_controller::PlaybackPolicy::DEFAULT;
402        self.instance.tracks[0].outgoing_event_threshold = NO_EVENT_THRESHOLD;
403        self.instance.primary_source_mut().controller.reset_setup();
404        self.instance.layers[0].cursors.clear();
405        self.instance.resolved_layer.cursors.clear();
406        self.instance.coordinate_system = crate::eval::SsCoordinateSystem::default();
407        self.instance.origin = crate::eval::SsOrigin::default();
408        self.instance.unit = crate::eval::SsUnit::default();
409        self.instance.render_mode = crate::eval::RenderMode::default();
410        self.instance.z_order = crate::eval::z_order::ZOrderTable::new();
411        self.instance.part_overrides.clear();
412        self.instance.globals.mesh_layout = NO_MESH_LAYOUT;
413    }
414
415    /// What the frame computes; see [`RenderMode`](crate::eval::RenderMode).
416    pub fn set_render_mode(&mut self, mode: crate::eval::RenderMode) {
417        self.instance.render_mode = mode;
418    }
419
420    /// What [`Self::set_render_mode`] stored.
421    pub fn render_mode(&self) -> crate::eval::RenderMode {
422        self.instance.render_mode
423    }
424
425    /// Bind `resource`, dropping the tracks and the overrides. The coordinate
426    /// settings stay. [`Self::setup_animation`] comes next.
427    pub fn bind_resource(&mut self, resource: &'a AnimationResource<'a>) {
428        self.eval.resource = Some(resource);
429        self.eval.fb.reset();
430        self.eval.frame_data_ready = false;
431        self.instance.collapse_to_track_zero();
432        self.instance.clock = CharacterClock::default();
433        self.instance.layers[0].cursors.clear();
434        self.instance.resolved_layer.cursors.clear();
435        // A new SSAB invalidates part identity — drop all overrides.
436        self.instance.part_overrides.clear();
437        // The layout indexes the old pack's static mesh buffers.
438        self.instance.globals.mesh_layout = NO_MESH_LAYOUT;
439        // Configuration (coordinate_system, origin, unit) is preserved.
440    }
441
442    /// The bound resource's `.ssab` bytes.
443    pub fn get_ssab_data(&self) -> Option<&[u8]> {
444        self.eval.resource.map(|r| r.get_ssab_data())
445    }
446
447    /// Select the animation `name` and move to its first frame. This does not start
448    /// it; [`Self::play`] does. It drops every track but 0, the section and the loop
449    /// count, and keeps the speed, the frame rate, the frame skip and the direction.
450    pub fn setup_animation(&mut self, name: &str) -> Result<(), error::SSRuntimeError> {
451        let hash = fnv1a_hash_str(name);
452        self.setup_animation_by_hash(hash)
453    }
454
455    /// [`Self::setup_animation`] by the FNV-1a hash of the name.
456    pub fn setup_animation_by_hash(&mut self, hash: u32) -> Result<(), error::SSRuntimeError> {
457        let Some(resource) = self.eval.resource else {
458            return Err(error::SSRuntimeError::NotLoaded);
459        };
460
461        let Some(index) = resource.find_animation_index_by_hash(hash) else {
462            return Err(error::SSRuntimeError::AnimationNotFound);
463        };
464
465        let metadata = &resource.animations[index];
466        self.instance.collapse_to_track_zero();
467        // Selecting an animation does not start it; `play` does.
468        self.instance.clock = CharacterClock::default();
469        let primary = self.instance.primary_source_mut();
470        primary.controller.setup(metadata.start_frame, metadata.end_frame, metadata.fps);
471        primary.animation_idx = index as i32;
472        primary.weight = 1.0;
473
474        let num_parts = metadata.cached_parts().len();
475        let (cell_c, color_c, shader_c, deform_c) = count_attribute_capacities(metadata);
476        let cursor_c = crate::eval::framedata::cursor_count(metadata.cached_parts());
477
478        // A new setup plays one source alone, extracted straight into the
479        // resolved layer; the source's own layer is sized when a mix needs it.
480        for layer in self.instance.layers.iter_mut() {
481            *layer = LayerState::new();
482        }
483        self.instance.resolved_layer.resize_for_parts(num_parts, cursor_c, cell_c, color_c, shader_c, deform_c);
484
485        // Override Layer: a new animation clears Visibility and OverwriteOnNextKeyframe and
486        // HoldUntilNextAnimation Color/Cell overrides but keeps Permanent ones.
487        self.instance.retain_permanent_overrides_on_setup(num_parts);
488
489        let globals = &mut self.instance.globals;
490        globals.world_matrices.clear();
491        globals.world_matrices.resize(num_parts, crate::eval::SsMatrix4x4::IDENTITY);
492        globals.inheritance_matrices.clear();
493        globals.inheritance_matrices.resize(num_parts, crate::eval::SsMatrix4x4::IDENTITY);
494        globals.local_uvs.clear();
495        globals.local_uvs.resize(num_parts * 10, 0.0);
496        // Shape buffers keep their `part_index * SHAPE_VERTICES_STRIDE` layout, but
497        // only a pack with a shape part has anything to put in them.
498        let shape_len = if metadata.cached_parts().iter().any(|p| p.shape_kind.is_some()) { num_parts * crate::eval::framedata::SHAPE_VERTICES_STRIDE } else { 0 };
499        globals.shape_vertices = alloc::vec![0.0; shape_len];
500        globals.shape_vertex_box_coords = alloc::vec![0.0; shape_len];
501        globals.shape_vertex_counts.clear();
502        globals.shape_vertex_counts.resize(num_parts, 0);
503        // Have compute_mesh_vertices set up the newly selected animation's
504        // static mesh buffers.
505        globals.mesh_layout = NO_MESH_LAYOUT;
506
507        self.instance.z_order.setup(index as i32, metadata.cached_parts());
508        self.prepare_part_bases();
509        self.reserve_frame_workspaces(metadata);
510
511        Ok(())
512    }
513
514    /// Size up front what the first frame of `metadata`'s animation would
515    /// otherwise grow on its way: the buffers whose size the parts decide, by
516    /// their count or by their meshes' vertices. What a frame's contents decide
517    /// — the frame data, the draw batches, a deform, an effect's particles, the
518    /// frames an update passes — still grows on first use.
519    fn reserve_frame_workspaces(&mut self, metadata: &AnimationMetadata<'a>) {
520        let parts = metadata.cached_parts();
521        let num_parts = parts.len();
522
523        let resolved = &mut self.instance.resolved_layer;
524        // One vertex attribute per part that shows a cell, whether or not it
525        // keys a vertex deform.
526        resolved.vertex_vec.clear();
527        resolved.vertex_vec.reserve(parts.iter().filter(|p| p.run(crate::eval::framedata::IDX_ATTRIBUTECELL).is_some()).count());
528        if resolved.mesh_deform.len() != num_parts {
529            resolved.mesh_deform.resize_with(num_parts, || None);
530        }
531
532        let eval = &mut self.eval;
533        reserve_total(&mut eval.inheritance_alphas_workspace, num_parts);
534        reserve_total(&mut eval.draw_order_workspace, num_parts);
535        reserve_total(&mut eval.mask_indices_workspace, parts.iter().filter(|p| p.is_mask_contributor).count());
536
537        let globals = &mut self.instance.globals;
538        reserve_total(&mut globals.nines.vertex_offsets, num_parts + 1);
539        reserve_total(&mut globals.nines.index_offsets, num_parts + 1);
540        // Room only: the static mesh buffers are still handed out from the
541        // first frame on, and only a Direct instance positions mesh vertices.
542        reserve_total(&mut globals.mesh_vertex_offsets, num_parts + 1);
543        if self.instance.render_mode == crate::eval::RenderMode::Direct {
544            let total_vertices = parts.iter().map(|p| p.mesh_cell.as_ref().map_or(0, |m| m.num_vertices())).sum();
545            reserve_total(&mut globals.mesh_vertices_x, total_vertices);
546            reserve_total(&mut globals.mesh_vertices_y, total_vertices);
547        }
548    }
549}