Skip to main content

ssplayer_wgpu/
scene.rs

1//! The per-render-target half of rendering.
2//!
3//! Turns the runtime's FrameData / DrawBatch / SoA buffers into draw commands,
4//! and owns what belongs to one render target: the projection and the frame's
5//! geometry. One `SSScene` draws any number of players into one pass.
6//!
7//! It owns neither the `Device`/`Queue`, the render target, nor the
8//! device-scoped [`SSRenderer`] — all three are lent per frame.
9
10use crate::frame::FrameView;
11use crate::mask::{MaskOp, MaskWriter, ScopedWriter, StencilTest};
12use crate::metrics::{GpuTimer, SceneStats};
13use crate::player::CrowdMember;
14use crate::renderer::{
15    COVERAGE_FORMAT, CROWD_SHIFT, GeomClass, MESH_DRAW_PRIMS, MESH_FIRST_PRIMS, MESH_PRIM_SHIFT, PipelineKey, PipelineKind, QUAD_FAN_VERTS, SHADER_PARAM_STRIDE, SHADER_PARAM_STRIDE_F32, SHAPE_FAN_VERTS, SSRenderer, blend_index, ss_shader_entry,
16};
17
18use ssruntime::runtime::effect_draw_plan::ss::runtime::root_as_effect_draw_plan_unchecked;
19use ssruntime::runtime::framedata::ss::runtime::{BlendType, DrawBatchKind, PartAttributeShader, root_as_frame_data_unchecked};
20#[cfg(not(target_arch = "wasm32"))]
21use std::sync::Arc;
22#[cfg(not(target_arch = "wasm32"))]
23use std::sync::atomic::{AtomicBool, Ordering};
24
25/// PartsColor formula selector, matching `varg_of` in the WGSL. Only four exist,
26/// so the shader takes two bits per primitive rather than three floats per vertex.
27///
28/// Deliberately *not* four module-level `pub const`s: cbindgen sweeps those into
29/// the C header (see `cbindgen.toml`), and `#define MIX 0` in a public header is
30/// a collision waiting to happen.
31mod mode {
32    /// `mix(straight, colour, rate)` — also what a Shape fill and any unsupported
33    /// PartColor blend clamps to.
34    pub(super) const MIX: u32 = 0;
35    /// `straight * mix(1, colour, rate)`. With rate 1 this is the plain
36    /// `texture * colour` modulate the no-PartColor and effect paths use.
37    pub(super) const MUL: u32 = 1;
38    pub(super) const ADD: u32 = 2;
39    pub(super) const SUB: u32 = 3;
40}
41
42/// Opaque white, the colour a part without PartColor contributes (its alpha
43/// travels separately, at full precision).
44const WHITE: u32 = 0x00FF_FFFF;
45
46/// Pack a 0..1 RGB triple into the `unpack4x8unorm` byte order (x = byte 0).
47/// Sources are `u8 / 255`, so this round-trips exactly.
48fn pack_rgb(r: f32, g: f32, b: f32) -> u32 {
49    let q = |v: f32| ((v.clamp(0.0, 1.0) * 255.0).round() as u32) & 0xFF;
50    q(r) | (q(g) << 8) | (q(b) << 16)
51}
52
53/// The identity player tint: white multiplies nothing away. It shares [`WHITE`]'s
54/// value and not its meaning — that one is a part's missing PartColor, this one is
55/// a player nobody tinted — so the two are named apart.
56pub(crate) const NO_TINT: u32 = WHITE;
57
58/// Turn a public `0xRRGGBB` tint into the byte order the shader unpacks
59/// ([`pack_rgb`]'s, x = byte 0). Only the outer two bytes move; green is already
60/// where it belongs.
61pub(crate) fn pack_tint(rgb: u32) -> u32 {
62    ((rgb >> 16) & 0xFF) | (rgb & 0x00FF00) | ((rgb & 0xFF) << 16)
63}
64
65/// How a scene rasterises mask coverage.
66///
67/// The two working backends implement the same semantics from opposite ends:
68/// [`MaskBackend::Stencil`] is the hardware stencil, and
69/// [`MaskBackend::Coverage`] is written for engines that never lend one.
70/// Which is available is a property of the *host's render pass*, not of the
71/// animation — the same `.ssab` must look the same either way.
72#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
73pub enum MaskBackend {
74    /// No masking. Pure masks draw nothing and masked targets draw unclipped.
75    #[default]
76    None,
77    /// The host's stencil buffer. Needs
78    /// [`SceneConfig::stencil_format`] and a matching attachment on every pass.
79    Stencil,
80    /// A coverage bitmap the player rasterises for itself.
81    ///
82    /// Needs no stencil from the host, and so is the backend for a pass that has
83    /// none to give — Bevy's 2d depth is `Depth32Float`, and a WebGPU engine that
84    /// composes its own passes may expose no depth at all. The cost is one extra
85    /// pass per masking player per frame, which is why it is not the default.
86    ///
87    /// **The host must call [`SSScene::encode_offscreen`]** between `update`
88    /// and `draw`: the bitmap is rasterised into its own render pass, and under
89    /// the borrow model only the host has an encoder to open one with.
90    Coverage,
91}
92
93/// Construction config for SSScene, matched to the host's render target.
94#[derive(Clone, Copy, Debug)]
95pub struct SceneConfig {
96    /// Target color format. Pipelines are baked against this.
97    pub color_format: wgpu::TextureFormat,
98    /// Depth/stencil format of the host's render target, or `None` when it
99    /// attaches neither. When `Some`, the host must attach a matching
100    /// depth/stencil buffer to every render pass.
101    ///
102    /// Independent of [`SceneConfig::mask`]: this describes the *attachment*,
103    /// which a host may have for its own reasons whatever it masks with. The one
104    /// combination that cannot work is [`MaskBackend::Stencil`] without a format:
105    /// a debug build asserts, and a release build falls back to
106    /// [`MaskBackend::None`] and draws every mask target unclipped.
107    pub stencil_format: Option<wgpu::TextureFormat>,
108    /// How this scene draws masks.
109    pub mask: MaskBackend,
110}
111
112/// The fields of one `DrawBatch` the renderer needs, extracted by the caller so
113/// the operation layer keeps ownership of batch iteration.
114#[derive(Clone, Copy, Debug)]
115pub struct BatchInfo {
116    pub start_rank: usize,
117    pub count: usize,
118    pub texture_hash: u32,
119    pub blend_type: BlendType,
120    pub kind: DrawBatchKind,
121    /// Stencil test to apply (masked content). `None` for ordinary content.
122    pub stencil: StencilTest,
123    /// The part's place on its player's tree sequence — every part of the
124    /// instance tree numbered in drawing order, a sub-animation in its instance
125    /// part's place. What the coverage replay scopes writers against; read only
126    /// for a masked target (`count == 1`) under [`MaskBackend::Coverage`].
127    pub mask_seq: u32,
128    /// Player-level alpha, folded into every vertex's colour alpha.
129    /// The shader's final coverage is `tex.a * color.a` and the blend table is
130    /// premultiplied throughout, so a plain multiply here fades the part
131    /// correctly under every blend mode (including Add / Mul, which reach `dst`
132    /// unchanged at alpha 0). Mask writers are deliberately not faded — their
133    /// `color[0]` carries the cutout threshold, not a colour.
134    pub alpha: f32,
135    /// Player-level tint, multiplied into the fragment *after* the PartsColor
136    /// mix — the place `uColor` lands in the WebGL player, and the reason it
137    /// cannot fold into the vertex colour the formula blends towards. Packed in
138    /// the `unpack4x8unorm` byte order (red in byte 0); white, `0x00FF_FFFF`,
139    /// leaves the colour alone. Mask writers are untinted for the same reason
140    /// they are unfaded.
141    pub tint: u32,
142}
143
144#[derive(Clone, Debug, PartialEq)]
145struct BatchDrawCall {
146    key: PipelineKey,
147    texture_hash: u32,
148    /// The `vertex_index` range to issue. Which primitives that covers is the
149    /// class's own arithmetic — 12 per quad, 6 per particle, 30 per shape,
150    /// one stream entry per mesh vertex.
151    vertices: std::ops::Range<u32>,
152    /// The `instance_index` range to issue: one instance per member of the
153    /// player's crowd — one for a player that is none, and one for a coverage
154    /// bake, whose bitmap the members share. For Mesh the draw's first
155    /// primitive, which its stream entries count from, rides above
156    /// [`CROWD_SHIFT`].
157    instances: std::ops::Range<u32>,
158    /// Index of this part's block in the shader-params buffer, for
159    /// [`PipelineKind::Shader`] draws — the dynamic offset for bind group(2).
160    shader_slot: Option<u32>,
161    /// Which layer of the frame's coverage array this call rasterises into
162    /// (writer draws) or samples from (masked content). `None` when the call has
163    /// nothing to do with coverage.
164    cov_layer: Option<u32>,
165}
166
167/// One drawn primitive: where its geometry sits in the frame arena, and the
168/// handful of per-part values that are not in the runtime's buffers.
169///
170/// This is the record that stands in for a vertex buffer: the CPU does not
171/// transform corners, it copies each drawn part's slice of the runtime's SoA
172/// arrays into the arena and writes one of these per part.
173///
174/// Field meanings are per geometry class; see the `Prim` comment in the WGSL,
175/// which this must stay in step with.
176#[repr(C)]
177#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
178struct Prim {
179    /// Quad/Shape: world matrix base. Mesh: the part's Y vertices. Effect: unused.
180    aux_base: u32,
181    /// Local vertices (Quad), the part's X vertices (Mesh), shape vertices
182    /// (Shape), particle XY.
183    pos_base: u32,
184    /// Local UVs (Quad/Mesh, texture pixels), box coords (Shape), particle UVs.
185    uv_base: u32,
186    /// The owning node's placement record for the first member of its crowd;
187    /// see [`NODE_STRIDE_F32`].
188    node_base: u32,
189    /// Shape: live vertex count. A group-alpha composite: the layer it reads.
190    /// Unused elsewhere.
191    count: u32,
192    /// PartsColor formula (see [`mode`]).
193    mode: u32,
194    /// Player-level fade, applied in the vertex stage so it multiplies the corner
195    /// alphas before interpolation — the order the CPU path used.
196    alpha: f32,
197    /// Mesh: the part's Z. Unused elsewhere (local Z is zero).
198    z: f32,
199    /// Per-corner RGB, packed. Alpha is deliberately *not* in here.
200    colors: [u32; 4],
201    /// Per-corner alpha, kept as f32: a part without PartColor takes its alpha
202    /// straight from the runtime and quantising it would shift the output.
203    alphas: [f32; 4],
204    /// Per-corner PartsColor rate — or, for a mask writer, the cutout threshold
205    /// (`fs_mask` reads `varg.x`), which needs the full range including -1.
206    rates: [f32; 4],
207    /// Arena offset of the owning node's coverage block, meaningful only when
208    /// `mask_info` says this primitive takes part in coverage masking. Zero is a
209    /// real arena offset, so the flag is what gates it, never this value.
210    cov_base: u32,
211    /// Coverage masking, packed. Zero — the `Default` — is "no
212    /// coverage masking", which is every primitive under the stencil backend.
213    ///
214    /// | bits | meaning |
215    /// |---|---|
216    /// | 0 | set when this primitive takes part in coverage masking |
217    /// | 1 | 1 = writer (baking a bit), 0 = masked target (replaying) |
218    /// | 2 | target polarity: 1 = visible inside the coverage |
219    /// | 8..16 | writer: which bit of the bitmap it writes (0..95) |
220    /// | 8..32 | target: its place on the tree sequence, for the scope test |
221    mask_info: u32,
222    /// Player-level tint (see [`BatchInfo::tint`]), in [`pack_rgb`]'s byte order.
223    /// Unlike every other field, zero is not the neutral value here — it is
224    /// black — which is why [`Prim`] spells its `Default` out.
225    tint: u32,
226}
227
228impl Default for Prim {
229    /// Zero everywhere the shader reads a zero as "nothing", and [`NO_TINT`]
230    /// where it would read one as black. Written against `zeroed()` rather than
231    /// field by field so a new field keeps defaulting to zero on its own.
232    fn default() -> Self {
233        Self { tint: NO_TINT, ..bytemuck::Zeroable::zeroed() }
234    }
235}
236
237/// Which backend a mask writer is being appended for, and the one value each
238/// needs: the stencil op to apply, or the coverage bit to set.
239#[derive(Clone, Copy, Debug)]
240enum MaskWriterDest {
241    Stencil(MaskOp),
242    Coverage(usize),
243}
244
245/// Set on [`Prim::mask_info`] when the primitive takes part in coverage masking.
246const MASK_INFO_ACTIVE: u32 = 1 << 0;
247/// Set when the primitive is a coverage *writer* rather than a masked target.
248const MASK_INFO_WRITER: u32 = 1 << 1;
249/// Set when a masked target draws *inside* the coverage.
250const MASK_INFO_INSIDE: u32 = 1 << 2;
251
252/// Pack a writer's [`Prim::mask_info`].
253fn writer_mask_info(bit: usize) -> u32 {
254    MASK_INFO_ACTIVE | MASK_INFO_WRITER | ((bit as u32 & 0xFF) << 8)
255}
256
257/// Pack a masked target's [`Prim::mask_info`].
258///
259/// A target has no writer bit, so its sequence number takes all 24 bits above
260/// the flags — which is also as far as the replay's f32 comparison is exact.
261/// The stencil backend numbers the same tree without a limit, so the two only
262/// part ways past 2^24 parts in one tree. Clamped rather than wrapped so the
263/// failure, if it ever happened, is a mask that stops scoping rather than one
264/// that scopes backwards.
265fn target_mask_info(seq: u32, inside: bool) -> u32 {
266    let polarity = if inside { MASK_INFO_INSIDE } else { 0 };
267    MASK_INFO_ACTIVE | polarity | (seq.min(0xFF_FFFF) << 8)
268}
269
270/// Floats in one member's record of a node's placement: the 4x4 matrix the node
271/// draws at, then that member's alpha and its tint, the tint in [`pack_rgb`]'s
272/// byte order and stored as the number it is (exact, being below 2^24).
273///
274/// A node has one record per member of its player's crowd, back to back, and a
275/// player that is no crowd has one: alpha 1, [`NO_TINT`]. Both multiply in the
276/// vertex stage, so the one record changes nothing.
277pub(crate) const NODE_STRIDE_F32: usize = 18;
278
279/// Multiply two column-major 4x4 matrices: `a * b`.
280pub(crate) fn mat4_mul(a: &[f32; 16], b: &[f32; 16]) -> [f32; 16] {
281    let mut r = [0.0f32; 16];
282    for col in 0..4 {
283        for row in 0..4 {
284            let mut s = 0.0;
285            for k in 0..4 {
286                s += a[k * 4 + row] * b[col * 4 + k];
287            }
288            r[col * 4 + row] = s;
289        }
290    }
291    r
292}
293
294/// Where one node's placement and coverage block sit in the frame arena.
295///
296/// [`FrameChunk::push_transform`] copies the placement in. A node's parts copy
297/// their own geometry in as their primitives are recorded, so only what is
298/// drawn reaches the arena.
299#[derive(Clone, Copy, Debug)]
300pub struct NodeSlot {
301    /// The node's placement records, one per member (see [`NODE_STRIDE_F32`]).
302    transform: u32,
303    /// Arena offset of this node's coverage block, or [`NO_COVERAGE`].
304    ///
305    /// Written by [`FrameChunk::set_node_coverage`] *after* the writers are
306    /// planned, which is why it cannot be filled in by `push_transform`: the block
307    /// describes the writer group, and the group is not known until the walk has
308    /// looked at the frame.
309    coverage: u32,
310    /// Which layer of the frame's coverage array this node's bitmap occupies.
311    /// Meaningless while `coverage` is [`NO_COVERAGE`].
312    coverage_layer: u32,
313}
314
315/// One node's claim on the frame's coverage array. The layer index is this
316/// entry's position in [`FrameChunk::coverage_nodes`].
317#[derive(Clone, Copy, Debug)]
318struct CoverageNode {
319    /// Player-local width and height of the writer group, which is what decides
320    /// the bitmap's size class — a mask twice as wide wants twice the texels.
321    extent: (f32, f32),
322}
323
324/// [`NodeSlot::coverage`] for a node that writes no coverage this frame.
325const NO_COVERAGE: u32 = u32::MAX;
326
327// Written out rather than derived: every other field defaults to arena offset 0,
328// which is a real offset, but `coverage` has to default to "none" — and a derived
329// `Default` would quietly make every slot claim the first node's coverage block.
330impl Default for NodeSlot {
331    fn default() -> Self {
332        Self { transform: 0, coverage: NO_COVERAGE, coverage_layer: 0 }
333    }
334}
335
336/// Floats before the writer records in a node's coverage block: the six of the
337/// node-local -> coverage-UV affine, the array layer the bitmap lives in, and
338/// the writer count.
339pub(crate) const COVERAGE_HEADER_F32: usize = 8;
340
341/// Smallest coverage bitmap edge. Below this the quantisation costs more in
342/// reallocation than the texels are worth.
343const COVERAGE_MIN_SIZE: u32 = 128;
344/// Largest coverage bitmap edge — 4 MiB a layer at RGBA8.
345const COVERAGE_MAX_SIZE: u32 = 1024;
346/// How far below a size class the footprint must fall before the smaller class is
347/// taken. The reference Player's value.
348const COVERAGE_SHRINK_DEADBAND: f32 = 0.15;
349
350/// The frame's coverage bitmaps: one array texture, one layer per masking node.
351///
352/// An array rather than a texture apiece so the replay binds once for the whole
353/// pass — the layer a primitive reads travels in its coverage block, not in the
354/// binding.
355struct CoverageTargets {
356    /// Held only to keep the views alive; every access goes through one of them.
357    _texture: wgpu::Texture,
358    /// One single-layer view per layer, for the bake passes to attach to.
359    layer_views: Vec<wgpu::TextureView>,
360    /// The whole array, as the masked content samples it.
361    bind_group: wgpu::BindGroup,
362    size: u32,
363    layers: u32,
364}
365/// Floats per writer record in a coverage block: the open and close of its scope
366/// on the tree sequence, its bit, and op_invert.
367pub(crate) const COVERAGE_WRITER_F32: usize = 4;
368
369/// The frame's group-alpha layers: one array texture the size of the target and
370/// in its format, one layer per player drawn through one, so the target's own
371/// pipelines draw into them unchanged.
372///
373/// They are all alive at once, unlike the one offscreen a GL player reuses: each
374/// is folded back from inside the host's pass, which cannot be paused to draw
375/// the next.
376struct LayerTargets {
377    /// Held only to keep the views alive.
378    _texture: wgpu::Texture,
379    /// One view per layer, for its pass to attach to.
380    layer_views: Vec<wgpu::TextureView>,
381    /// The whole array, as the composite reads it.
382    bind_group: wgpu::BindGroup,
383    /// The target's depth-stencil, when it has one: every pipeline is built to
384    /// test against one, and a layer's masks write into it. One serves every
385    /// layer, cleared by each pass.
386    depth_stencil: Option<wgpu::TextureView>,
387    size: (u32, u32),
388    layers: u32,
389}
390
391/// The per-target, per-frame half — what one render target's worth of geometry
392/// looks like this frame.
393///
394/// Borrow model: owns neither the `Device`/`Queue`, the render target, nor the
395/// [`SSRenderer`]. It holds the projection (which is a property of the target)
396/// and the frame's arena, primitive table, mesh stream and draw calls.
397///
398/// One of these serves every player drawing into the same target.
399pub struct SSScene {
400    /// This frame's coverage bitmaps, kept across frames so a mask that holds its
401    /// size class does not reallocate.
402    coverage: Option<CoverageTargets>,
403    /// Whether a faded player is drawn as one layer (see
404    /// [`SSScene::set_group_alpha`]).
405    group_alpha: bool,
406    /// The group-alpha layers, kept across frames like `coverage`.
407    layers: Option<LayerTargets>,
408    /// Whether [`SSScene::encode_offscreen`] has been called since the last
409    /// update, which is what the next one takes to mean it will be called again.
410    /// Without it a faded player is drawn part by part, as it is with group alpha
411    /// off, rather than built opaque into a layer nobody draws.
412    offscreen_seen: bool,
413    /// Whether this frame's layers were drawn. `draw` composites them only then.
414    offscreen_encoded: bool,
415    /// How this target draws masks.
416    mask: MaskBackend,
417    /// The target's formats. Part of every [`PipelineKey`] this builds.
418    color_format: wgpu::TextureFormat,
419    stencil_format: Option<wgpu::TextureFormat>,
420
421    /// The projection matrix. Part of group(0) along with the frame buffers.
422    globals_buffer: wgpu::Buffer,
423    /// group(0), rebuilt whenever the frame buffer below is reallocated.
424    scene_bind_group: Option<wgpu::BindGroup>,
425    /// Last viewport passed to [`SSScene::set_viewport`], re-applied on restore
426    /// (the projection lives in a buffer that dies with the device).
427    viewport: Option<(f32, f32, bool)>,
428
429    /// The frame's arena, primitive table, mesh stream and shader params, in
430    /// that order, in one buffer: wgpu stages every write through a new buffer
431    /// of its own, and making one costs more than a frame's copy, so one write
432    /// it is — or natively, for a large frame, one copy out of `staging`.
433    frame_buffer: Option<wgpu::Buffer>,
434    /// The bytes each of group(0)'s three storage bindings covers, so the most
435    /// a frame may put in each, then the room for the shader params. They only
436    /// grow, and the buffer holds all four.
437    frame_capacity: [u64; 4],
438    /// Where this frame's primitive table and mesh stream start in the buffer:
439    /// group(0)'s dynamic offsets. The arena starts at zero.
440    frame_offsets: [u32; 2],
441    /// Where this frame's shader params start in the buffer. A shader part's
442    /// group(2) offset is this plus its slot's.
443    params_at: u32,
444    #[cfg(not(target_arch = "wasm32"))]
445    staging: FrameStaging,
446
447    /// This frame's geometry, every player's in `order`. This is what reaches
448    /// the GPU.
449    frame: FrameChunk,
450    /// The order the players are walked in, as `(order, index)` into the slice
451    /// `update_with` was handed. Kept across frames so that ordering a cast
452    /// allocates nothing; sorting the slice itself would, since the stable sort
453    /// takes a buffer of its own once a cast passes a few hundred.
454    draw_order: Vec<(i32, u32)>,
455    /// What `frame` was built from, `None` until a frame is — and so after a
456    /// restore, which starts the scene over. An update whose players are all
457    /// settled keeps the frame only while these still read the same.
458    built: Option<BuiltFrom>,
459    /// The players `frame` holds, as `(order, id)` in the order they were drawn:
460    /// a player added, removed, replaced or reordered changes the frame though
461    /// none of them moved. Refilled in place, like `draw_order`.
462    built_players: Vec<(i32, u32)>,
463
464    /// group(2) of an integration-shader (`ss-*`) part: the frame buffer, one
465    /// params slot wide. Built by the first frame with shader parts after the
466    /// buffer was (re)allocated; shader-free animations never build it.
467    ss_params_bind_group: Option<wgpu::BindGroup>,
468
469    /// This frame's counts. Free to keep, and the only way
470    /// to tell whether a change to how work is issued actually issued less.
471    stats: SceneStats,
472    /// GPU pass timing, present only when the device was created with
473    /// `Features::TIMESTAMP_QUERY`.
474    timer: Option<GpuTimer>,
475}
476
477/// The scene-wide inputs a frame was built from (see `SSScene::built`).
478#[derive(Clone, Copy, PartialEq)]
479struct BuiltFrom {
480    /// [`SSRenderer::texture_changes`]: the frame reads the texture sizes.
481    textures: u64,
482    /// Whether faded players were drawn into layers.
483    grouping: bool,
484}
485
486/// Column-major 4x4 identity. Used as the root transform (children compose their
487/// parent instance part's world matrix onto this).
488pub const IDENTITY_TRANSFORM: [f32; 16] = [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0];
489
490/// Min/max of a Normal part's 4 corner UVs (normalized by `tex_size`), as
491/// `[minU, minV, maxU, maxV]` — the cell UV rect an integration shader receives
492/// as `cell_rect` (ss-circle / ss-spot). Falls back to the full `[0,0,1,1]` when
493/// the part has no UV data.
494fn quad_uv_bounds(frame: &FrameView, part_idx: usize, tex_size: Option<(f32, f32)>) -> [f32; 4] {
495    let luv = &frame.local_uvs;
496    if (part_idx + 1) * 10 > luv.len() {
497        return [0.0, 0.0, 1.0, 1.0];
498    }
499    let l_uv = &luv[part_idx * 10..(part_idx + 1) * 10];
500    let (mut min_u, mut min_v, mut max_u, mut max_v) = (f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY);
501    for k in 0..4 {
502        let (u, v) = if let Some(s) = tex_size { (l_uv[k * 2] / s.0, l_uv[k * 2 + 1] / s.1) } else { (l_uv[k * 2], l_uv[k * 2 + 1]) };
503        min_u = min_u.min(u);
504        min_v = min_v.min(v);
505        max_u = max_u.max(u);
506        max_v = max_v.max(v);
507    }
508    [min_u, min_v, max_u, max_v]
509}
510
511/// PartsColor formula for a `BlendType`. Only Mix/Mul/Add/Sub select
512/// one; any other `BlendType` clamps to Mix (else no branch matches and the
513/// shader outputs black).
514fn parts_color_mode(blend: BlendType) -> u32 {
515    match blend {
516        BlendType::Mul => mode::MUL,
517        BlendType::Add => mode::ADD,
518        BlendType::Sub => mode::SUB,
519        _ => mode::MIX, // Mix (and clamp for all other blend types)
520    }
521}
522
523impl SSScene {
524    /// Build the target-scoped resources: the projection uniform. The rest of
525    /// group(0) is this frame's geometry, so its bind group is built in
526    /// `end_frame` — against whichever renderer is drawing the frame — once the
527    /// buffers are sized. That is why no `SSRenderer` is needed here.
528    pub fn new(device: &wgpu::Device, config: &SceneConfig) -> Self {
529        let globals_buffer = device.create_buffer(&wgpu::BufferDescriptor {
530            label: Some("SpriteStudio Globals UB"),
531            size: 64, // 16 * 4 bytes for mat4x4
532            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
533            mapped_at_creation: false,
534        });
535
536        // Stencil masking without an attachment to write into cannot work, and
537        // silently drawing every mask target unclipped is worse than saying so.
538        let mask = match config.mask {
539            MaskBackend::Stencil if config.stencil_format.is_none() => MaskBackend::None,
540            other => other,
541        };
542        debug_assert!(mask == config.mask, "MaskBackend::Stencil needs SceneConfig::stencil_format; masking is off for this scene");
543
544        Self {
545            coverage: None,
546            group_alpha: false,
547            layers: None,
548            offscreen_seen: false,
549            offscreen_encoded: false,
550            mask,
551            color_format: config.color_format,
552            stencil_format: config.stencil_format,
553            globals_buffer,
554            scene_bind_group: None,
555            viewport: None,
556            frame_buffer: None,
557            frame_capacity: [0; 4],
558            frame_offsets: [0; 2],
559            params_at: 0,
560            #[cfg(not(target_arch = "wasm32"))]
561            staging: FrameStaging::default(),
562            frame: FrameChunk::new(*config),
563            draw_order: Vec::new(),
564            built: None,
565            built_players: Vec::new(),
566            ss_params_bind_group: None,
567            stats: SceneStats::default(),
568            // Deferred to the first frame: `new` has no `Queue` to read the
569            // timestamp period from, and the borrow model does not lend one.
570            timer: None,
571        }
572    }
573
574    /// What the last frame cost.
575    ///
576    /// Counts are always populated. `gpu_pass_time_ns` needs the device to have
577    /// been created with `Features::TIMESTAMP_QUERY`, and the host to attach
578    /// [`SSScene::timestamp_writes`] to its render pass and call
579    /// [`SSScene::resolve_timestamps`] after it.
580    pub fn stats(&self) -> SceneStats {
581        SceneStats { gpu_pass_time_ns: self.timer.as_ref().and_then(|t| t.last_ns()), ..self.stats }
582    }
583
584    /// Timestamp writes for the host's `RenderPassDescriptor`, or `None` when the
585    /// device cannot time.
586    ///
587    /// The host opens the pass (borrow model), so it is the only place these
588    /// can be attached — the scene can only hand them over.
589    pub fn timestamp_writes(&self) -> Option<wgpu::RenderPassTimestampWrites<'_>> {
590        self.timer.as_ref().map(|t| t.writes())
591    }
592
593    /// Copy this frame's timestamps back toward the CPU. Call on the same
594    /// encoder as the pass, after it ends. No-op without the feature.
595    pub fn resolve_timestamps(&mut self, encoder: &mut wgpu::CommandEncoder) {
596        if let Some(timer) = self.timer.as_mut() {
597            timer.resolve(encoder);
598        }
599    }
600
601    /// Draw everything this frame draws outside the host's pass: the coverage
602    /// bitmaps, then one layer per player drawn with group alpha.
603    ///
604    /// Call between [`SSScene::update`] and [`SSScene::draw`], every frame, on
605    /// **the same encoder** the host will open its own pass with. Passes recorded
606    /// into one encoder execute in order, so what this draws is what the very
607    /// next pass reads — which is why this player has none of the one-frame lag
608    /// that engines whose offscreen targets are only readable next frame have to
609    /// work around. Do not split the two across encoders or frames.
610    ///
611    /// It opens passes of its own and never the host's, so the host's target is
612    /// still drawn in the one pass. Nothing to do — another backend than
613    /// [`MaskBackend::Coverage`] with group alpha off, or a frame where nothing
614    /// masks or fades — opens none.
615    pub fn encode_offscreen(&mut self, renderer: &mut SSRenderer, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder) {
616        self.offscreen_seen = true;
617        // Coverage first: masked content inside a layer reads this frame's bitmap.
618        self.bake_coverage(renderer, device, encoder);
619        self.offscreen_encoded = self.encode_layers(renderer, device, encoder);
620    }
621
622    /// Rasterise this frame's coverage bitmaps: a no-op under any backend but
623    /// [`MaskBackend::Coverage`], and on frames where nothing masks.
624    fn bake_coverage(&mut self, renderer: &mut SSRenderer, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder) {
625        if self.mask != MaskBackend::Coverage || self.frame.coverage_nodes.is_empty() {
626            return;
627        }
628        if self.scene_bind_group.is_none() {
629            return;
630        }
631
632        let layers = self.frame.coverage_nodes.len() as u32;
633        let size = self.coverage_size(&self.frame.coverage_nodes);
634        self.ensure_coverage(renderer, device, size, layers);
635        // Re-borrowed after `ensure_coverage`, which may have replaced the array.
636        let (Some(scene_bg), Some(targets)) = (self.scene_bind_group.as_ref(), self.coverage.as_ref()) else { return };
637
638        for layer in 0..layers {
639            // Cleared per layer: a bitmap is only ever read in the frame it was
640            // written, so there is nothing to preserve, and a stale bit left
641            // behind would clip content that no writer covers.
642            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
643                label: Some("SpriteStudio Mask Coverage"),
644                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
645                    view: &targets.layer_views[layer as usize],
646                    depth_slice: None,
647                    resolve_target: None,
648                    ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store },
649                })],
650                depth_stencil_attachment: None,
651                timestamp_writes: None,
652                occlusion_query_set: None,
653                multiview_mask: None,
654            });
655            pass.set_bind_group(0, scene_bg, &self.frame_offsets);
656            for call in self.frame.coverage_calls.iter().filter(|call| call.cov_layer == Some(layer)) {
657                let Some(pipeline) = renderer.pipelines.get(&call.key) else { continue };
658                pass.set_pipeline(pipeline);
659                pass.set_bind_group(1, renderer.texture_bind_group(call.texture_hash), &[]);
660                pass.draw(call.vertices.clone(), call.instances.clone());
661            }
662        }
663        self.stats.coverage_layers = layers;
664    }
665
666    /// Draw each group-alpha player into a layer of its own, and say whether
667    /// `draw` may composite them: false only when a layer was due and none could
668    /// be drawn.
669    ///
670    /// Each layer is cleared, then the player's own draws are replayed into it
671    /// against the frame's one upload, exactly as `draw` would have issued them.
672    fn encode_layers(&mut self, renderer: &mut SSRenderer, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder) -> bool {
673        let layers = self.frame.groups.iter().filter(|group| group.prim.is_some()).count() as u32;
674        if layers == 0 {
675            return true;
676        }
677        let Some((width, height, _)) = self.viewport else { return false };
678        self.ensure_layers(renderer, device, layer_extent(device, width, height), layers);
679        let this = &*self;
680        let (Some(scene_bg), Some(targets)) = (this.scene_bind_group.as_ref(), this.layers.as_ref()) else { return false };
681        let aspects = this.stencil_format.map(|format| (format.has_depth_aspect(), format.has_stencil_aspect()));
682
683        for (group, layer) in this.frame.groups.iter().filter(|group| group.prim.is_some()).zip(0..) {
684            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
685                label: Some("SpriteStudio Group Alpha"),
686                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
687                    view: &targets.layer_views[layer],
688                    depth_slice: None,
689                    resolve_target: None,
690                    ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store },
691                })],
692                // Cleared like the host's: a player leaves the stencil as it
693                // found it, so each layer starts from nothing written.
694                depth_stencil_attachment: targets.depth_stencil.as_ref().zip(aspects).map(|(view, (depth, stencil))| wgpu::RenderPassDepthStencilAttachment {
695                    view,
696                    depth_ops: depth.then_some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard }),
697                    stencil_ops: stencil.then_some(wgpu::Operations { load: wgpu::LoadOp::Clear(0), store: wgpu::StoreOp::Discard }),
698                }),
699                timestamp_writes: None,
700                occlusion_query_set: None,
701                multiview_mask: None,
702            });
703            pass.set_bind_group(0, scene_bg, &this.frame_offsets);
704            if this.stencil_enabled() {
705                pass.set_stencil_reference(0);
706            }
707            for call in &this.frame.draw_calls[group.calls.start as usize..group.calls.end as usize] {
708                this.record(renderer, &mut pass, call);
709            }
710        }
711        self.stats.group_layers = layers;
712        true
713    }
714
715    /// Build or rebuild the layer array when the frame needs more layers than it
716    /// has, or the target changed size. Layers only grow while the size holds; a
717    /// new size starts again from what this frame needs.
718    fn ensure_layers(&mut self, renderer: &SSRenderer, device: &wgpu::Device, size: (u32, u32), layers: u32) {
719        let current = self.layers.as_ref().filter(|targets| targets.size == size);
720        if current.is_some_and(|targets| targets.layers >= layers) {
721            return;
722        }
723        let layers = layers.max(current.map_or(0, |targets| targets.layers));
724        let extent = |depth_or_array_layers| wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers };
725        let texture = device.create_texture(&wgpu::TextureDescriptor {
726            label: Some("SpriteStudio Group Alpha"),
727            size: extent(layers),
728            mip_level_count: 1,
729            sample_count: 1,
730            dimension: wgpu::TextureDimension::D2,
731            format: self.color_format,
732            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
733            view_formats: &[],
734        });
735        let layer_views = (0..layers)
736            .map(|layer| texture.create_view(&wgpu::TextureViewDescriptor { label: Some("SpriteStudio Group Alpha Layer"), dimension: Some(wgpu::TextureViewDimension::D2), base_array_layer: layer, array_layer_count: Some(1), ..Default::default() }))
737            .collect();
738        let array_view = texture.create_view(&wgpu::TextureViewDescriptor { label: Some("SpriteStudio Group Alpha Array"), dimension: Some(wgpu::TextureViewDimension::D2Array), ..Default::default() });
739        let bind_group = renderer.coverage_bind_group(device, &array_view);
740        let depth_stencil = self.stencil_format.map(|format| {
741            device
742                .create_texture(&wgpu::TextureDescriptor {
743                    label: Some("SpriteStudio Group Alpha Stencil"),
744                    size: extent(1),
745                    mip_level_count: 1,
746                    sample_count: 1,
747                    dimension: wgpu::TextureDimension::D2,
748                    format,
749                    usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
750                    view_formats: &[],
751                })
752                .create_view(&wgpu::TextureViewDescriptor::default())
753        });
754        self.layers = Some(LayerTargets { _texture: texture, layer_views, bind_group, depth_stencil, size, layers });
755    }
756
757    /// Draw each player whose `alpha` is below 1 as one layer, composited at its
758    /// alpha, rather than fading each of its parts: where two parts overlap, half
759    /// a character then reads half, not three quarters. What the WebGL player
760    /// does for every faded player.
761    ///
762    /// Off by default, for what it costs: a render pass per faded player per
763    /// frame, a layer the size of the target for each faded at once — about 8
764    /// MiB at 1920x1080 — and one composite over the target apiece.
765    /// [`SceneStats::group_layers`] counts them. Turning it off frees them at the
766    /// next update; a frame already built with layers still draws them.
767    ///
768    /// The host calls [`SSScene::encode_offscreen`] every frame, which is what
769    /// draws the layers. Each update reads whether it was called since the one
770    /// before: a scene it is not called on draws its faded players part by part,
771    /// as with this off, and so does the first frame after a host starts calling
772    /// it. A host that stops draws one frame of them unfaded. Players past
773    /// `max_texture_array_layers` faded at once are drawn part by part too.
774    ///
775    /// Inside a layer the parts blend against transparency, not against what is
776    /// behind the player: an Add, Mul or Screen part composites with the player's
777    /// own parts alone, and a Mul part over nothing reads black. Its masks clip
778    /// within the player, as they always do. A crowd is one player, so it fades as
779    /// one layer; its members' own alphas still apply part by part.
780    pub fn set_group_alpha(&mut self, on: bool) {
781        self.group_alpha = on;
782    }
783
784    /// Whether faded players are drawn as one layer each; see
785    /// [`SSScene::set_group_alpha`].
786    pub fn group_alpha(&self) -> bool {
787        self.group_alpha
788    }
789
790    /// The edge length every coverage layer gets this frame.
791    ///
792    /// Quantised to a power of two so a mask that scales smoothly keeps the same
793    /// texture instead of reallocating every frame, and shared across layers
794    /// because each node's bbox is normalised onto its whole layer — a small mask
795    /// does not waste resolution by sharing a size with a large one, it just
796    /// spends more texels on itself than it needs.
797    fn coverage_size(&self, nodes: &[CoverageNode]) -> u32 {
798        let longest = nodes.iter().fold(0.0f32, |acc, node| acc.max(node.extent.0).max(node.extent.1));
799        let wanted = (longest.max(1.0).ceil() as u32).next_power_of_two().clamp(COVERAGE_MIN_SIZE, COVERAGE_MAX_SIZE);
800
801        // Shrinking waits for the footprint to fall well inside the smaller class;
802        // growing is immediate. The asymmetry is deliberate:
803        // holding a size too long costs VRAM nobody sees, while growing late
804        // costs visibly ragged mask edges.
805        match self.coverage.as_ref().map(|targets| targets.size) {
806            Some(current) if wanted < current && longest > (current as f32 / 2.0) * (1.0 - COVERAGE_SHRINK_DEADBAND) => current,
807            _ => wanted,
808        }
809    }
810
811    /// Build or rebuild the coverage array when the frame needs a shape the
812    /// current one cannot serve. Layers only ever grow within a frame's life, so
813    /// a frame with fewer masking players reuses the larger array.
814    fn ensure_coverage(&mut self, renderer: &mut SSRenderer, device: &wgpu::Device, size: u32, layers: u32) {
815        if self.coverage.as_ref().is_some_and(|targets| targets.size == size && targets.layers >= layers) {
816            return;
817        }
818        let layers = layers.max(self.coverage.as_ref().map_or(0, |targets| targets.layers));
819        let texture = device.create_texture(&wgpu::TextureDescriptor {
820            label: Some("SpriteStudio Mask Coverage"),
821            size: wgpu::Extent3d { width: size, height: size, depth_or_array_layers: layers },
822            mip_level_count: 1,
823            sample_count: 1,
824            dimension: wgpu::TextureDimension::D2,
825            format: COVERAGE_FORMAT,
826            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
827            view_formats: &[],
828        });
829        let layer_views = (0..layers)
830            .map(|layer| texture.create_view(&wgpu::TextureViewDescriptor { label: Some("SpriteStudio Mask Coverage Layer"), dimension: Some(wgpu::TextureViewDimension::D2), base_array_layer: layer, array_layer_count: Some(1), ..Default::default() }))
831            .collect();
832        let array_view = texture.create_view(&wgpu::TextureViewDescriptor { label: Some("SpriteStudio Mask Coverage Array"), dimension: Some(wgpu::TextureViewDimension::D2Array), ..Default::default() });
833        let bind_group = renderer.coverage_bind_group(device, &array_view);
834        self.coverage = Some(CoverageTargets { _texture: texture, layer_views, bind_group, size, layers });
835    }
836
837    /// Whether the hardware stencil is in use for this target. Also what decides
838    /// whether `draw` sets a stencil reference and whether pipelines carry a
839    /// depth-stencil state.
840    pub fn stencil_enabled(&self) -> bool {
841        self.mask == MaskBackend::Stencil
842    }
843
844    /// How this target draws masks.
845    pub fn mask_backend(&self) -> MaskBackend {
846        self.mask
847    }
848
849    /// The config this scene was built from. Retained so a lost device can be
850    /// replaced by a scene targeting the same formats without the caller having
851    /// to remember them.
852    pub fn config(&self) -> SceneConfig {
853        SceneConfig { color_format: self.color_format, stencil_format: self.stencil_format, mask: self.mask }
854    }
855
856    /// Set the projection to the render target's pixel dimensions. Remembered, so
857    /// [`SSScene::restore_device`] can re-apply it to a rebuilt buffer. The same
858    /// viewport again writes nothing, so a host may call this every frame.
859    pub fn set_viewport(&mut self, queue: &wgpu::Queue, width: f32, height: f32, y_down: bool) {
860        if self.viewport == Some((width, height, y_down)) {
861            return;
862        }
863        self.update_projection(queue, width, height, y_down);
864        self.viewport = Some((width, height, y_down));
865    }
866
867    /// Rebuild this target's GPU state against a freshly created `device` after
868    /// the previous one was lost. The host calls
869    /// [`SSRenderer::restore_device`] first — that covers pipelines and textures
870    /// for the whole device — then this once per render target, then
871    /// [`crate::SSPlayer::restore_textures`] once per player.
872    pub fn restore_device(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {
873        let (viewport, group_alpha) = (self.viewport, self.group_alpha);
874        *self = Self::new(device, &SceneConfig { color_format: self.color_format, stencil_format: self.stencil_format, mask: self.mask });
875        self.set_group_alpha(group_alpha);
876        if let Some((width, height, y_down)) = viewport {
877            self.set_viewport(queue, width, height, y_down);
878        }
879    }
880
881    /// Update the projection matrix to the target's pixel dimensions.
882    ///
883    /// `y_down` describes the **target**, not the geometry: the players hand up
884    /// Y-down world space (the Brain's coordinate system, set in `build_node`),
885    /// so a Y-down target passes it straight through and a Y-up one is where the
886    /// flip has to happen. That is why the sign reads inverted against the flag.
887    fn update_projection(&self, queue: &wgpu::Queue, width: f32, height: f32, y_down: bool) {
888        let scale_y = if y_down { 2.0 / height } else { -2.0 / height };
889        let matrix = [2.0 / width, 0.0, 0.0, 0.0, 0.0, scale_y, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0];
890        queue.write_buffer(&self.globals_buffer, 0, bytemuck::cast_slice(&matrix));
891    }
892
893    /// Advance every player and build this target's frame.
894    ///
895    /// This is the frame boundary: one `begin_frame` / `end_frame` pair spans
896    /// **all** the players sharing the target, so their geometry lands in one
897    /// frame buffer and their draws can be recorded back to back.
898    ///
899    /// Players are drawn in ascending [`crate::SSPlayer::order`], ties keeping the
900    /// order the caller passed them in; `players` itself is left as it was. The
901    /// scene borrows them rather than owning them, so they can live wherever the
902    /// host keeps them — a `Vec`, an ECS, an engine's scene graph — and a host
903    /// that keeps them in a collection of its own hands that over through
904    /// [`SSScene::update_with`] instead. Each player appends its geometry straight
905    /// to the frame, in that order.
906    pub fn update(&mut self, renderer: &mut SSRenderer, device: &wgpu::Device, queue: &wgpu::Queue, delta_secs: f32, players: &mut [&mut crate::SSPlayer]) {
907        self.update_with(renderer, device, queue, delta_secs, players, |player| Some(&mut **player));
908    }
909
910    /// [`SSScene::update`] over a collection of the host's own, each element's
911    /// player reached through `player`, which answers `None` for an element that
912    /// holds none — a free slot, say.
913    ///
914    /// For a host that keeps its cast from frame to frame: a `Vec<&mut SSPlayer>`
915    /// collected out of it cannot outlive the borrow it holds, so `update` would
916    /// cost a fresh one every frame. Ties in `order` keep the order of `players`.
917    ///
918    /// When every player is settled — stopped, finished or held with nothing of
919    /// its own still moving, and unchanged since the last frame — the frame that
920    /// frame built is kept: nothing is evaluated, rebuilt or uploaded, and
921    /// [`SSScene::draw`] draws it again. One player that moves rebuilds the
922    /// whole frame, the settled ones with it, since they share its buffer.
923    pub fn update_with<P>(&mut self, renderer: &mut SSRenderer, device: &wgpu::Device, queue: &wgpu::Queue, delta_secs: f32, players: &mut [P], player: impl Fn(&mut P) -> Option<&mut crate::SSPlayer>) {
924        self.draw_order.clear();
925        self.draw_order.extend(players.iter_mut().enumerate().filter_map(|(index, slot)| player(slot).map(|p| (p.order(), index as u32))));
926        // The index makes every key distinct, so the unstable sort, which needs
927        // no buffer, leaves ties in slice order just as a stable one would.
928        self.draw_order.sort_unstable();
929
930        // Before the walk: this is the one step that needs `&mut SSRenderer`. It
931        // does nothing at all except on the frames right after a pack is loaded.
932        for &(_, index) in &self.draw_order {
933            if let Some(p) = player(&mut players[index as usize]) {
934                p.flush_textures(renderer, device, queue);
935            }
936        }
937
938        // Faded players draw through layers only for a host that draws them, and
939        // only as many as one array holds.
940        // Taken every update, so what it says is always about the last frame.
941        let encoded = std::mem::take(&mut self.offscreen_seen);
942        let grouping = self.group_alpha && encoded && self.viewport.is_some();
943        // Freed here rather than when group alpha is turned off, so a frame built
944        // with layers before then still has them to draw.
945        if !self.group_alpha {
946            self.layers = None;
947        }
948        let from = BuiltFrom { textures: renderer.texture_changes(), grouping };
949        if self.built == Some(from) && self.cast_unchanged(players, &player) {
950            self.keep_frame();
951            for &(_, index) in &self.draw_order {
952                if let Some(p) = player(&mut players[index as usize]) {
953                    p.skip_tick();
954                }
955            }
956            return;
957        }
958
959        self.begin_frame();
960        let max_layers = if grouping { device.limits().max_texture_array_layers } else { 0 };
961        let mut drawing = 0;
962        self.built_players.clear();
963        for &(order, index) in &self.draw_order {
964            if let Some(p) = player(&mut players[index as usize]) {
965                let group = grouping && p.alpha() < 1.0 && self.frame.layered_groups() < max_layers;
966                let first = self.frame.draw_calls.len() as u32;
967                // A group player is drawn opaque into its layer, and faded once,
968                // as a whole, when the layer is folded back.
969                p.build_frame(&mut self.frame, renderer, delta_secs, if group { 1.0 } else { p.alpha() });
970                if group {
971                    self.frame.push_group(first, p.alpha());
972                }
973                drawing += u32::from(p.draws());
974                self.built_players.push((order, p.id()));
975            }
976        }
977        self.stats.players = drawing;
978        self.end_frame(renderer, device, queue);
979        self.built = Some(from);
980    }
981
982    /// Whether the players are the ones the kept frame was built from, in the
983    /// same order, and every one of them settled. Asked before any of them
984    /// updates, which is when a player can say whether its update would move it.
985    fn cast_unchanged<P>(&self, players: &mut [P], player: &impl Fn(&mut P) -> Option<&mut crate::SSPlayer>) -> bool {
986        self.draw_order.len() == self.built_players.len() && self.draw_order.iter().zip(&self.built_players).all(|(&(order, index), &built)| player(&mut players[index as usize]).is_some_and(|p| (order, p.id()) == built && p.settled()))
987    }
988
989    /// Draw the last frame again: [`SSScene::begin_frame`] without emptying it.
990    /// The counts still describe it, except that nothing was uploaded, and the
991    /// offscreen ones, which the next [`SSScene::encode_offscreen`] sets afresh.
992    fn keep_frame(&mut self) {
993        if let Some(timer) = self.timer.as_mut() {
994            timer.settle();
995            timer.poll();
996        }
997        self.stats = SceneStats { uploaded_bytes: 0, coverage_layers: 0, group_layers: 0, ..self.stats };
998        self.offscreen_encoded = false;
999    }
1000
1001    /// Reset per-frame accumulation. Call once before appending any batches.
1002    pub fn begin_frame(&mut self) {
1003        if let Some(timer) = self.timer.as_mut() {
1004            // Both halves of the readback handshake happen here, at the one point
1005            // in the frame where the previous frame is guaranteed submitted.
1006            timer.settle();
1007            timer.poll();
1008        }
1009        self.stats = SceneStats::default();
1010        self.offscreen_encoded = false;
1011        self.frame.reset(self.config());
1012        // Whatever goes into the frame now, `update_with` did not check it.
1013        self.built = None;
1014    }
1015
1016    /// Upload the accumulated frame to the GPU. Call once after all batches.
1017    pub fn end_frame(&mut self, renderer: &mut SSRenderer, device: &wgpu::Device, queue: &wgpu::Queue) {
1018        renderer.ensure_white(queue);
1019        if self.timer.is_none() {
1020            self.timer = GpuTimer::new(device, queue);
1021        }
1022
1023        self.stats.prims = self.frame.prims.len() as u32;
1024        self.stats.draw_calls = self.frame.draw_calls.len() as u32;
1025        self.stats.uploaded_bytes = (std::mem::size_of_val(self.frame.arena.as_slice()) + std::mem::size_of_val(self.frame.prims.as_slice()) + std::mem::size_of_val(self.frame.mesh_stream.as_slice())) as u64;
1026
1027        if self.frame.prims.is_empty() {
1028            return;
1029        }
1030
1031        // Each array starts at the first aligned offset past the one before it.
1032        let bytes =
1033            [std::mem::size_of_val(self.frame.arena.as_slice()), std::mem::size_of_val(self.frame.prims.as_slice()), std::mem::size_of_val(self.frame.mesh_stream.as_slice()), std::mem::size_of_val(self.frame.ss_params.as_slice())].map(|n| n as u64);
1034        let prims_at = bytes[0].next_multiple_of(FRAME_ALIGN);
1035        let stream_at = (prims_at + bytes[1]).next_multiple_of(FRAME_ALIGN);
1036        let params_at = (stream_at + bytes[2]).next_multiple_of(FRAME_ALIGN);
1037        self.frame_offsets = [prims_at as u32, stream_at as u32];
1038        self.params_at = params_at as u32;
1039
1040        // Growing any of the four invalidates group(0), so the buffer is sized
1041        // for all of them and the bind group rebuilt only when it actually moved.
1042        if self.ensure_frame_buffer(device, bytes) || self.scene_bind_group.is_none() {
1043            let buffer = self.frame_buffer.as_ref().expect("ensure_frame_buffer just built it");
1044            let binding = |binding, size| wgpu::BindGroupEntry { binding, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer, offset: 0, size: wgpu::BufferSize::new(size) }) };
1045            self.scene_bind_group = Some(device.create_bind_group(&wgpu::BindGroupDescriptor {
1046                label: Some("SpriteStudio Scene Bind Group"),
1047                layout: &renderer.scene_bind_group_layout,
1048                entries: &[wgpu::BindGroupEntry { binding: 0, resource: self.globals_buffer.as_entire_binding() }, binding(1, self.frame_capacity[0]), binding(2, self.frame_capacity[1]), binding(3, self.frame_capacity[2])],
1049            }));
1050            self.ss_params_bind_group = None;
1051        }
1052        if !self.frame.ss_params.is_empty() && self.ss_params_bind_group.is_none() {
1053            let buffer = self.frame_buffer.as_ref().expect("ensure_frame_buffer built it");
1054            // The binding window is one `SsParams` (64 B); the dynamic offset picks the slot.
1055            self.ss_params_bind_group = Some(device.create_bind_group(&wgpu::BindGroupDescriptor {
1056                label: Some("SpriteStudio SS Params Bind Group"),
1057                layout: &renderer.ss_params_bind_group_layout,
1058                entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer, offset: 0, size: wgpu::BufferSize::new(64) }) }],
1059            }));
1060        }
1061        if let Some(buffer) = self.frame_buffer.as_ref() {
1062            let parts = frame_parts(&self.frame, [prims_at, stream_at, params_at]);
1063            #[cfg(not(target_arch = "wasm32"))]
1064            let staged = frame_len(&parts) >= STAGED_UPLOAD_MIN && self.staging.upload(device, queue, buffer, &parts);
1065            #[cfg(target_arch = "wasm32")]
1066            let staged = false;
1067            if !staged {
1068                upload_frame(queue, buffer, &parts);
1069            }
1070        }
1071
1072        // Compile whatever this frame draws with and has not drawn with before. After the first few frames every key is a cache hit, so
1073        // this is a walk over the draw list and nothing more.
1074        //
1075        // The same walk counts what draw-call merging and bind-group dedup would
1076        // save.
1077        // The bake list is compiled here too. It is drawn from a different pass,
1078        // by which point there is no `&mut SSRenderer` to build a pipeline with —
1079        // a writer whose pipeline was missing would simply not rasterise, and an
1080        // empty bitmap reads as "no coverage", which draws masked content
1081        // unclipped rather than failing.
1082        for call in &self.frame.coverage_calls {
1083            renderer.ensure_pipeline(device, call.key);
1084        }
1085        if self.frame.layered_groups() > 0 {
1086            renderer.ensure_pipeline(device, self.frame.key(PipelineKind::Composite));
1087        }
1088
1089        for i in 0..self.frame.draw_calls.len() {
1090            let key = self.frame.draw_calls[i].key;
1091            renderer.ensure_pipeline(device, key);
1092
1093            let Some(previous) = i.checked_sub(1).map(|p| &self.frame.draw_calls[p]) else { continue };
1094            let call = &self.frame.draw_calls[i];
1095            if call.texture_hash == previous.texture_hash {
1096                self.stats.redundant_texture_binds += 1;
1097            }
1098            // A shader draw carries its own params offset, so two of them never
1099            // collapse into one however well their ranges line up.
1100            if call.key == previous.key && call.texture_hash == previous.texture_hash && call.shader_slot.is_none() && previous.shader_slot.is_none() && call.vertices.start == previous.vertices.end {
1101                self.stats.mergeable_draws += 1;
1102            }
1103        }
1104    }
1105
1106    /// Record draw commands into a RenderPass opened by the host.
1107    /// Returns the number of draw calls issued.
1108    ///
1109    /// Recorded fresh every frame. The draw list changes on most frames as parts
1110    /// appear and disappear, so a recording would be invalidated more often than
1111    /// it is replayed.
1112    ///
1113    /// A player drawn with group alpha is one draw here: its layer, folded back
1114    /// in its place in the order.
1115    pub fn draw<'a>(&'a self, renderer: &'a SSRenderer, rpass: &mut wgpu::RenderPass<'a>) -> usize {
1116        if self.frame.draw_calls.is_empty() {
1117            return 0;
1118        }
1119
1120        let Some(scene_bg) = self.scene_bind_group.as_ref() else { return 0 };
1121
1122        // No vertex or index buffer: group(0) *is* the geometry.
1123        rpass.set_bind_group(0, scene_bg, &self.frame_offsets);
1124        if self.stencil_enabled() {
1125            // Stencil ref is always 0; ops/compare are baked into the pipelines.
1126            rpass.set_stencil_reference(0);
1127        }
1128
1129        let calls = &self.frame.draw_calls;
1130        let mut groups = self.frame.groups.iter().peekable();
1131        let (mut issued, mut i) = (0usize, 0usize);
1132        while i < calls.len() {
1133            if let Some(group) = groups.next_if(|group| group.calls.start as usize == i) {
1134                match group.prim {
1135                    // Faded out altogether: none of it shows, whatever its parts
1136                    // blend with — an Invert part at alpha 0 would still darken.
1137                    None => {
1138                        i = group.calls.end as usize;
1139                        continue;
1140                    }
1141                    Some(prim) if self.offscreen_encoded => {
1142                        issued += usize::from(self.composite(renderer, rpass, prim));
1143                        i = group.calls.end as usize;
1144                        continue;
1145                    }
1146                    // Its layer was never drawn, so the player draws straight
1147                    // into the target instead.
1148                    Some(_) => {}
1149                }
1150            }
1151            issued += usize::from(self.record(renderer, rpass, &calls[i]));
1152            i += 1;
1153        }
1154
1155        issued
1156    }
1157
1158    /// Issue one recorded draw into `pass`, whose group(0) is already the
1159    /// frame's. Returns whether it was issued.
1160    fn record(&self, renderer: &SSRenderer, pass: &mut wgpu::RenderPass<'_>, call: &BatchDrawCall) -> bool {
1161        // Missing texture -> 1x1 white fallback.
1162        let texture = renderer.texture_bind_group(call.texture_hash);
1163
1164        // `end_frame` compiled every key this frame uses, so a miss here means
1165        // the key was an `ss-*` shader id `build_pipeline` declined to build.
1166        let (Some(pipeline), params_bg) = (renderer.pipelines.get(&call.key), self.ss_params_bind_group.as_ref()) else {
1167            return false;
1168        };
1169        // Integration-shader part: group(2) carries the part's
1170        // params at its dynamic offset.
1171        let params = match (call.shader_slot, params_bg) {
1172            (Some(slot), Some(bg)) => Some((slot, bg)),
1173            (Some(_), None) => return false, // params buffer missing — cannot draw
1174            (None, _) => None,
1175        };
1176
1177        pass.set_pipeline(pipeline);
1178        pass.set_bind_group(1, texture, &[]);
1179        if let Some((slot, bg)) = params {
1180            pass.set_bind_group(2, bg, &[self.params_at + slot * SHADER_PARAM_STRIDE as u32]);
1181        }
1182        // Set per draw rather than once: group(2) is the coverage array under
1183        // one pipeline layout and the shader params under another, so a shader
1184        // part drawn in between invalidates whichever was there.
1185        if matches!(call.key.kind, PipelineKind::ContentCoverage(..)) {
1186            let Some(coverage) = self.coverage.as_ref() else { return false };
1187            pass.set_bind_group(2, &coverage.bind_group, &[]);
1188        }
1189        pass.draw(call.vertices.clone(), call.instances.clone());
1190        true
1191    }
1192
1193    /// Fold one group-alpha layer back into the target, at the alpha its
1194    /// primitive carries. Returns whether it was drawn.
1195    fn composite(&self, renderer: &SSRenderer, pass: &mut wgpu::RenderPass<'_>, prim: u32) -> bool {
1196        let (Some(pipeline), Some(layers)) = (renderer.pipelines.get(&self.frame.key(PipelineKind::Composite)), self.layers.as_ref()) else { return false };
1197        pass.set_pipeline(pipeline);
1198        // The layout's texture group, which the composite does not sample.
1199        pass.set_bind_group(1, renderer.white_bind_group(), &[]);
1200        pass.set_bind_group(2, &layers.bind_group, &[]);
1201        pass.draw(prim * 3..prim * 3 + 3, 0..1);
1202        true
1203    }
1204}
1205
1206/// A group-alpha layer's size for a viewport of `width` x `height`: the target's
1207/// own pixels, brought inside what `device` can allocate.
1208fn layer_extent(device: &wgpu::Device, width: f32, height: f32) -> (u32, u32) {
1209    let max = device.limits().max_texture_dimension_2d;
1210    ((width.round() as u32).clamp(1, max), (height.round() as u32).clamp(1, max))
1211}
1212
1213/// Where each of the frame's four arrays may start in the frame buffer.
1214///
1215/// The largest `min_storage_buffer_offset_alignment` and
1216/// `min_uniform_buffer_offset_alignment` a device may ask for, so every device
1217/// takes it: each limit is a power of two no larger than this.
1218const FRAME_ALIGN: u64 = 256;
1219
1220impl SSScene {
1221    /// Make sure the buffer can hold `bytes` of each of the frame's arrays,
1222    /// reallocating it (with headroom) if not. Returns whether it was replaced —
1223    /// the bind groups are stale if so.
1224    fn ensure_frame_buffer(&mut self, device: &wgpu::Device, bytes: [u64; 4]) -> bool {
1225        if self.frame_buffer.is_some() && bytes.iter().zip(&self.frame_capacity).all(|(needed, held)| needed <= held) {
1226            return false;
1227        }
1228        for (held, &needed) in self.frame_capacity.iter_mut().zip(&bytes) {
1229            // A binding cannot be empty, hence the floor; an array with no
1230            // entries this frame still needs one to bind.
1231            if needed > *held || *held == 0 {
1232                *held = (needed * 2).max(1024).next_multiple_of(FRAME_ALIGN);
1233            }
1234        }
1235        // The binding past each start is a whole capacity long, and a start is
1236        // never later than the capacities before it add up to: the arena's
1237        // binding overlaps the arrays after it, and the stream's the params,
1238        // which bindings that only read may.
1239        let size = self.frame_capacity.iter().sum();
1240        self.frame_buffer = Some(device.create_buffer(&wgpu::BufferDescriptor { label: Some("SpriteStudio Frame"), size, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }));
1241        true
1242    }
1243}
1244
1245/// The `f32`s of a FlatBuffers vector's payload, which is little-endian and
1246/// not necessarily aligned for `f32`.
1247fn f32s(bytes: &[u8]) -> impl Iterator<Item = f32> + '_ {
1248    bytes.as_chunks::<4>().0.iter().map(|word| f32::from_le_bytes(*word))
1249}
1250
1251/// The frame's four arrays, each with where it starts in the frame buffer:
1252/// the arena, the primitive table, the mesh stream and the shader params.
1253type FrameParts<'a> = [(usize, &'a [u8]); 4];
1254
1255fn frame_parts(frame: &FrameChunk, [prims_at, stream_at, params_at]: [u64; 3]) -> FrameParts<'_> {
1256    [(0, bytemuck::cast_slice(&frame.arena)), (prims_at as usize, bytemuck::cast_slice(&frame.prims)), (stream_at as usize, bytemuck::cast_slice(&frame.mesh_stream)), (params_at as usize, bytemuck::cast_slice(&frame.ss_params))]
1257}
1258
1259/// How much of the frame buffer an upload covers: up to the end of the last array.
1260#[cfg(not(target_arch = "wasm32"))]
1261fn frame_len(parts: &FrameParts) -> usize {
1262    let (at, bytes) = parts[3];
1263    at + bytes.len()
1264}
1265
1266/// Copy the arrays into `view`, the frame buffer's first [`frame_len`] bytes,
1267/// zeroing the gaps between them.
1268#[cfg(not(target_arch = "wasm32"))]
1269fn fill_frame(mut view: wgpu::WriteOnly<'_, [u8]>, parts: &FrameParts) {
1270    let mut end = 0;
1271    for &(at, bytes) in parts {
1272        view.slice(end..at).fill(0);
1273        view.slice(at..at + bytes.len()).copy_from_slice(bytes);
1274        end = at + bytes.len();
1275    }
1276}
1277
1278/// Write the frame's arrays where `parts` puts them.
1279///
1280/// Natively in one `write_buffer_with`, so the frame goes up through one staging
1281/// buffer. The browser's `writeBuffer` stages for us and reads straight out of
1282/// wasm memory, while `write_buffer_with` there fills a zeroed copy on the heap
1283/// first, so on the web each array goes up as a write of its own.
1284fn upload_frame(queue: &wgpu::Queue, buffer: &wgpu::Buffer, parts: &FrameParts) {
1285    #[cfg(not(target_arch = "wasm32"))]
1286    {
1287        let Some(size) = wgpu::BufferSize::new(frame_len(parts) as u64) else { return };
1288        let Some(mut view) = queue.write_buffer_with(buffer, 0, size) else { return };
1289        fill_frame(view.slice(..), parts);
1290    }
1291    #[cfg(target_arch = "wasm32")]
1292    for &(at, bytes) in parts {
1293        if !bytes.is_empty() {
1294            queue.write_buffer(buffer, at as u64, bytes);
1295        }
1296    }
1297}
1298
1299/// Natively, a frame this large or larger goes up through [`FrameStaging`].
1300/// Below it, the copy's own submit costs about what the staging buffer
1301/// `write_buffer_with` does without saves.
1302#[cfg(not(target_arch = "wasm32"))]
1303const STAGED_UPLOAD_MIN: usize = 64 * 1024;
1304
1305/// Staging buffers of the scene's own that a large frame is copied through,
1306/// natively: `write_buffer_with` makes a new one for every write, which past
1307/// [`STAGED_UPLOAD_MIN`] costs more than writing into a mapped one that is
1308/// kept and submitting the copy. Each is mapped again once the GPU has copied
1309/// out of it.
1310#[cfg(not(target_arch = "wasm32"))]
1311#[derive(Default)]
1312struct FrameStaging {
1313    /// Three, so that a host with two frames in flight still finds one free.
1314    /// None free, the frame goes up through `write_buffer_with`.
1315    slots: [Option<StagingSlot>; 3],
1316}
1317
1318#[cfg(not(target_arch = "wasm32"))]
1319struct StagingSlot {
1320    buffer: wgpu::Buffer,
1321    /// Raised by the map callback, once the buffer may be written again.
1322    mapped: Arc<AtomicBool>,
1323}
1324
1325#[cfg(not(target_arch = "wasm32"))]
1326impl FrameStaging {
1327    /// Copy the frame into `target` through a free buffer, made as large as
1328    /// `target` when none is or the free one is too small. Returns false, having
1329    /// written nothing, when every one is still in flight.
1330    fn upload(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, target: &wgpu::Buffer, parts: &FrameParts) -> bool {
1331        let len = frame_len(parts) as u64;
1332        let free = self.slots.iter().position(|slot| slot.as_ref().is_some_and(|slot| slot.mapped.load(Ordering::Acquire)));
1333        let Some(index) = free.or_else(|| self.slots.iter().position(Option::is_none)) else { return false };
1334        let slot = match &mut self.slots[index] {
1335            Some(slot) if slot.buffer.size() >= len => slot,
1336            other => other.insert(StagingSlot::new(device, target.size())),
1337        };
1338        let mut view = slot.buffer.get_mapped_range_mut(..len).expect("a free staging buffer is mapped, and nothing else views it");
1339        fill_frame(view.slice(..), parts);
1340        drop(view);
1341        slot.buffer.unmap();
1342        slot.mapped.store(false, Ordering::Relaxed);
1343        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("SpriteStudio Frame Upload") });
1344        encoder.copy_buffer_to_buffer(&slot.buffer, 0, target, 0, len);
1345        queue.submit([encoder.finish()]);
1346        let mapped = Arc::clone(&slot.mapped);
1347        slot.buffer.map_async(wgpu::MapMode::Write, .., move |result| mapped.store(result.is_ok(), Ordering::Release));
1348        true
1349    }
1350}
1351
1352#[cfg(not(target_arch = "wasm32"))]
1353impl StagingSlot {
1354    fn new(device: &wgpu::Device, size: u64) -> Self {
1355        let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("SpriteStudio Frame Staging"), size, usage: wgpu::BufferUsages::MAP_WRITE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: true });
1356        Self { buffer, mapped: Arc::new(AtomicBool::new(true)) }
1357    }
1358}
1359
1360/// One frame of one render target: the arena, primitives, mesh stream and draw
1361/// calls every player sharing the target appends to, in its `order`.
1362pub struct FrameChunk {
1363    /// The target this frame is being built for — needed for pipeline keys.
1364    config: SceneConfig,
1365    /// Runtime SoA buffers and node transforms, copied verbatim.
1366    arena: Vec<f32>,
1367    prims: Vec<Prim>,
1368    /// One entry per mesh vertex drawn: the runtime's own index into its part's
1369    /// vertices, tagged with the part's primitive (see [`MESH_PRIM_SHIFT`]).
1370    mesh_stream: Vec<u32>,
1371    draw_calls: Vec<BatchDrawCall>,
1372    /// Writer draws for the coverage bitmap, kept apart from `draw_calls` because
1373    /// they are replayed into a different render pass — one
1374    /// [`SSScene::encode_offscreen`] opens before the host opens its own.
1375    /// Empty under every backend but [`MaskBackend::Coverage`].
1376    coverage_calls: Vec<BatchDrawCall>,
1377    /// One entry per node that writes coverage this frame, in layer order.
1378    coverage_nodes: Vec<CoverageNode>,
1379    /// Per-part integration-shader params, one `SHADER_PARAM_STRIDE_F32` slot each.
1380    ss_params: Vec<f32>,
1381    /// The players drawn with group alpha this frame, in draw order.
1382    groups: Vec<GroupLayer>,
1383    /// How many members the crowd being built has: every node pushes a record
1384    /// apiece, and every content draw is issued once for each. One for a player
1385    /// that is no crowd. Set by the player's top node.
1386    members: u32,
1387}
1388
1389/// One player drawn with group alpha: into a layer of its own, which takes its
1390/// draws' place in the target.
1391#[derive(Clone, Debug)]
1392struct GroupLayer {
1393    /// The player's draws in [`FrameChunk::draw_calls`]: replayed into the layer,
1394    /// skipped by [`SSScene::draw`]. Never empty.
1395    calls: std::ops::Range<u32>,
1396    /// The composite's primitive, whose `alpha` is the player's and whose
1397    /// `count` is its layer; `None` for a player faded out altogether, which
1398    /// takes no layer and draws nothing.
1399    prim: Option<u32>,
1400}
1401
1402impl FrameChunk {
1403    fn new(config: SceneConfig) -> Self {
1404        Self { config, arena: Vec::new(), prims: Vec::new(), mesh_stream: Vec::new(), draw_calls: Vec::new(), coverage_calls: Vec::new(), coverage_nodes: Vec::new(), ss_params: Vec::new(), groups: Vec::new(), members: 1 }
1405    }
1406
1407    /// Empty it for reuse, keeping the allocations — the frame is rebuilt every
1408    /// frame, so this is what stops a per-frame allocation storm.
1409    fn reset(&mut self, config: SceneConfig) {
1410        self.config = config;
1411        self.arena.clear();
1412        self.prims.clear();
1413        self.mesh_stream.clear();
1414        self.draw_calls.clear();
1415        self.coverage_calls.clear();
1416        self.coverage_nodes.clear();
1417        self.ss_params.clear();
1418        self.groups.clear();
1419        self.members = 1;
1420    }
1421
1422    /// The groups this frame that take a layer.
1423    fn layered_groups(&self) -> u32 {
1424        self.groups.iter().filter(|group| group.prim.is_some()).count() as u32
1425    }
1426
1427    /// Close the group a player at `alpha` opened at draw call `first`: its draws
1428    /// since then go into a layer, folded back at `alpha` by a primitive of its
1429    /// own. A player that drew nothing is no group at all.
1430    fn push_group(&mut self, first: u32, alpha: f32) {
1431        let calls = first..self.draw_calls.len() as u32;
1432        if calls.is_empty() {
1433            return;
1434        }
1435        let prim = (alpha > 0.0).then(|| {
1436            let layer = self.layered_groups();
1437            self.push_prim(Prim { alpha, count: layer, ..Default::default() })
1438        });
1439        self.groups.push(GroupLayer { calls, prim });
1440    }
1441
1442    /// Whether the hardware stencil is in use for the target this is built for.
1443    pub fn stencil_enabled(&self) -> bool {
1444        self.config.mask == MaskBackend::Stencil && self.config.stencil_format.is_some()
1445    }
1446
1447    /// How the target this is built for draws masks.
1448    ///
1449    /// [`crate::SSPlayer`]'s walk reads this rather than [`Self::stencil_enabled`]:
1450    /// planning writers, skipping a pure mask's colour and testing a masked
1451    /// target are the same work for both backends, and only what the batch is
1452    /// *appended as* differs.
1453    pub fn mask_backend(&self) -> MaskBackend {
1454        if self.config.mask == MaskBackend::Stencil && self.config.stencil_format.is_none() { MaskBackend::None } else { self.config.mask }
1455    }
1456
1457    /// Cache key for a content draw. Without a stencil buffer every draw uses the
1458    /// untested variant, so the test is normalised away rather than filling the
1459    /// cache with three identical pipelines.
1460    fn content_key(&self, blend: BlendType, stencil: StencilTest, class: GeomClass) -> PipelineKey {
1461        match self.mask_backend() {
1462            // The replay reads the polarity off the primitive, so a coverage-masked
1463            // part needs the coverage pipeline whichever way round it clips.
1464            MaskBackend::Coverage if stencil != StencilTest::None => self.key(PipelineKind::ContentCoverage(blend_index(blend), stencil, class)),
1465            MaskBackend::Stencil if self.config.stencil_format.is_some() => self.key(PipelineKind::Content(blend_index(blend), stencil, class)),
1466            _ => self.key(PipelineKind::Content(blend_index(blend), StencilTest::None, class)),
1467        }
1468    }
1469
1470    /// Attach this target's formats to a pipeline kind.
1471    fn key(&self, kind: PipelineKind) -> PipelineKey {
1472        PipelineKey { kind, color_format: self.config.color_format, stencil_format: self.config.stencil_format }
1473    }
1474
1475    /// Attach the player's coverage block to its top node, once the whole tree's
1476    /// writers are planned.
1477    ///
1478    /// `uv` is the affine that takes a **player-local** point to coverage UV
1479    /// `[0,1]` — the bbox normalisation, as
1480    /// `[a, b, c, d, tx, ty]` for `u = a*x + c*y + tx`, `v = b*x + d*y + ty`.
1481    /// Both the bake (which turns UV into clip space) and the replay (which
1482    /// samples with it) read this one transform, so the two cannot disagree about
1483    /// where the bitmap is.
1484    pub fn set_node_coverage(&mut self, node: &mut NodeSlot, uv: &[f32; 6], extent: (f32, f32), writers: &[ScopedWriter]) {
1485        let layer = self.coverage_nodes.len() as u32;
1486        let base = self.push_coverage_block(uv, layer, writers);
1487        self.coverage_nodes.push(CoverageNode { extent });
1488        // One more layer per `COVERAGE_LAYER_BITS` writers, consecutive, so a
1489        // writer's layer is the block's plus its bit's quotient.
1490        for _ in 1..writers.len().div_ceil(crate::mask::COVERAGE_LAYER_BITS) {
1491            self.coverage_nodes.push(CoverageNode { extent });
1492        }
1493        node.coverage = base;
1494        node.coverage_layer = layer;
1495    }
1496
1497    /// Point a sub-animation at its player's bitmap.
1498    ///
1499    /// No new layer: the child reads the one bitmap the top node baked, and the
1500    /// same writer records — their scopes are on the tree sequence, which the
1501    /// whole tree shares. Only the affine differs, composed with the chain of
1502    /// instance placements so the child's own local coordinates land in the top
1503    /// node's coverage.
1504    pub fn inherit_node_coverage(&mut self, node: &mut NodeSlot, uv: &[f32; 6], layer: u32, writers: &[ScopedWriter]) {
1505        node.coverage = self.push_coverage_block(uv, layer, writers);
1506        node.coverage_layer = layer;
1507    }
1508
1509    /// Which layer a node's coverage went to, for pointing the rest of its tree
1510    /// at it.
1511    pub fn node_coverage_layer(&self, node: &NodeSlot) -> u32 {
1512        node.coverage_layer
1513    }
1514
1515    /// Append a coverage block and return where it landed.
1516    fn push_coverage_block(&mut self, uv: &[f32; 6], layer: u32, writers: &[ScopedWriter]) -> u32 {
1517        let base = self.arena.len() as u32;
1518        self.arena.extend_from_slice(uv);
1519        self.arena.push(layer as f32);
1520        self.arena.push(writers.len() as f32);
1521        for (bit, w) in writers.iter().enumerate() {
1522            self.arena.push(w.open as f32);
1523            self.arena.push(w.close as f32);
1524            self.arena.push(bit as f32);
1525            self.arena.push(if w.writer.op_invert { 1.0 } else { 0.0 });
1526        }
1527        base
1528    }
1529
1530    /// Copy a placement matrix into the arena, for a top node that is no crowd:
1531    /// before any of its primitives, and the draws after it are issued once.
1532    pub fn push_transform(&mut self, transform: &[f32; 16]) -> NodeSlot {
1533        self.push_root_transform(transform, &[])
1534    }
1535
1536    /// The top node's placement: the player's own `transform`, once for each
1537    /// member of its `crowd` composed over that member's placement — or, for no
1538    /// crowd, once as it is. Sets how many members every draw after it is issued
1539    /// for.
1540    pub(crate) fn push_root_transform(&mut self, transform: &[f32; 16], crowd: &[CrowdMember]) -> NodeSlot {
1541        let base = self.arena.len() as u32;
1542        self.members = crowd.len().max(1) as u32;
1543        if crowd.is_empty() {
1544            self.push_record(transform, 1.0, NO_TINT);
1545        }
1546        for member in crowd {
1547            self.push_record(&mat4_mul(transform, &member.matrix()), member.alpha, pack_tint(member.tint));
1548        }
1549        NodeSlot { transform: base, ..Default::default() }
1550    }
1551
1552    /// A node placed under `parent`: each member's placement of the parent,
1553    /// composed with `local` — an instance part's world matrix for an instance's
1554    /// sub-animation, an effect part's for its particles, which the plan already
1555    /// placed relative to it. The members keep their alpha and tint.
1556    pub(crate) fn push_child_transform(&mut self, parent: &NodeSlot, local: &[f32; 16]) -> NodeSlot {
1557        let base = self.arena.len() as u32;
1558        for member in 0..self.members as usize {
1559            let at = parent.transform as usize + member * NODE_STRIDE_F32;
1560            let matrix: [f32; 16] = self.arena[at..at + 16].try_into().expect("a placement record holds a matrix");
1561            let (alpha, tint) = (self.arena[at + 16], self.arena[at + 17]);
1562            self.arena.extend_from_slice(&mat4_mul(&matrix, local));
1563            self.arena.extend_from_slice(&[alpha, tint]);
1564        }
1565        NodeSlot { transform: base, ..Default::default() }
1566    }
1567
1568    /// Append one member's placement record; see [`NODE_STRIDE_F32`].
1569    fn push_record(&mut self, matrix: &[f32; 16], alpha: f32, tint: u32) {
1570        self.arena.extend_from_slice(matrix);
1571        self.arena.extend_from_slice(&[alpha, tint as f32]);
1572    }
1573
1574    /// Append `prim`, returning its index in the frame's primitive table.
1575    fn push_prim(&mut self, prim: Prim) -> u32 {
1576        let index = self.prims.len() as u32;
1577        self.prims.push(prim);
1578        index
1579    }
1580
1581    /// Record a draw over the primitives `[first, self.prims.len())`.
1582    ///
1583    /// Primitive indices are global to the frame, and each class turns one into a
1584    /// fixed span of `vertex_index` values. Primitives of other
1585    /// classes in between simply leave gaps in a span nothing draws, which is why
1586    /// one primitive table serves all four.
1587    fn push_draw(&mut self, key: PipelineKey, class: GeomClass, texture_hash: u32, first: u32, shader_slot: Option<u32>) {
1588        let last = self.prims.len() as u32;
1589        if last == first {
1590            return;
1591        }
1592        let stride = match class {
1593            GeomClass::Quad => QUAD_FAN_VERTS,
1594            GeomClass::Effect => 6,
1595            GeomClass::Shape => SHAPE_FAN_VERTS,
1596            // Mesh draws are driven by the stream, not by primitive arithmetic.
1597            GeomClass::Mesh => return,
1598        };
1599        self.draw_calls.push(BatchDrawCall { key, texture_hash, vertices: first * stride..last * stride, instances: 0..self.members, shader_slot, cov_layer: None });
1600    }
1601
1602    /// Append one Normal, Mesh or Shape DrawBatch's geometry to the frame. The
1603    /// vertices are copied as the runtime laid them out; `node` names the
1604    /// placement the vertex stage applies to them (the root's, or an instance
1605    /// child's composed with its parents'). `frame` is re-parsed for its
1606    /// draw_order/parts/parts_color; the batch fields are passed in so the caller
1607    /// (SSPlayer) drives batch iteration and can interleave instance recursion at
1608    /// the right rank. `batch.stencil` selects the stencil-test content pipeline
1609    /// for masked parts.
1610    pub fn append_batch(&mut self, renderer: &SSRenderer, frame: &FrameView, node: &NodeSlot, batch: &BatchInfo) {
1611        let BatchInfo { start_rank, count, texture_hash, blend_type, kind, stencil, mask_seq, alpha, tint } = *batch;
1612        if frame.frame_data.is_empty() {
1613            return;
1614        }
1615        let frame_data = unsafe { root_as_frame_data_unchecked(frame.frame_data) };
1616        let draw_order = frame_data.draw_order();
1617        let parts = frame_data.parts();
1618        let parts_color = frame_data.parts_color();
1619
1620        if frame.world_matrices.is_empty() || frame.local_vertices.is_empty() || frame.local_uvs.is_empty() {
1621            return;
1622        }
1623
1624        // Under the coverage backend a masked target carries its own scope test:
1625        // which bitmap to read, its place on the tree sequence, and its polarity.
1626        // The stencil backend leaves this zero because the pipeline state does
1627        // the testing for it.
1628        //
1629        // `mask_seq` is the part's own — the walk splits masked batches to one
1630        // part each precisely so this is true.
1631        let (cov_base, mask_info) = match stencil {
1632            _ if self.mask_backend() != MaskBackend::Coverage || node.coverage == NO_COVERAGE => (0, 0),
1633            StencilTest::Inside => (node.coverage, target_mask_info(mask_seq, true)),
1634            StencilTest::Outside => (node.coverage, target_mask_info(mask_seq, false)),
1635            StencilTest::None => (0, 0),
1636        };
1637
1638        let first_prim = self.prims.len() as u32;
1639
1640        match kind {
1641            DrawBatchKind::Normal => {
1642                let key = self.content_key(blend_type, stencil, GeomClass::Quad);
1643                // Integration-shader dispatch: when the frame carries
1644                // `SHDR` attributes and this non-masked batch has ≥1 shader part,
1645                // draw per-part so each shader part gets its own pipeline + params.
1646                // Masked parts (stencil != None) use the plain path: shader and
1647                // mask are not combined, matching WebGL.
1648                let shaders = frame_data.shaders();
1649                let has_shader = |rank: usize| -> Option<PartAttributeShader> {
1650                    let si = parts.get(draw_order.get(rank) as usize).shader();
1651                    if si < 0 {
1652                        return None;
1653                    }
1654                    let attr = *shaders?.get(si as usize);
1655                    ss_shader_entry(attr.id_hash()).map(|_| attr)
1656                };
1657                let shader_dispatch = stencil == StencilTest::None && (start_rank..start_rank + count).any(|r| has_shader(r).is_some());
1658
1659                for rank in start_rank..start_rank + count {
1660                    let part_idx = draw_order.get(rank) as usize;
1661                    let part = parts.get(part_idx);
1662
1663                    let part_color_idx = part.part_color();
1664                    let (colors, alphas, rates, mode) = parts_color
1665                        .filter(|_| part_color_idx >= 0)
1666                        .map(|pc_vec| {
1667                            let pc = pc_vec.get(part_color_idx as usize);
1668                            let corners = [pc.lt(), pc.rt(), pc.lb(), pc.rb()];
1669                            let mut colors = [0u32; 4];
1670                            let mut alphas = [0.0f32; 4];
1671                            let mut rates = [0.0f32; 4];
1672                            for (i, corner) in corners.iter().enumerate() {
1673                                let c = corner.rgba();
1674                                colors[i] = pack_rgb(c.r() as f32 / 255.0, c.g() as f32 / 255.0, c.b() as f32 / 255.0);
1675                                alphas[i] = c.a() as f32 / 255.0;
1676                                rates[i] = corner.rate();
1677                            }
1678                            (colors, alphas, rates, parts_color_mode(pc.blend_type()))
1679                        })
1680                        // No PartColor: white modulated by the part's own alpha.
1681                        .unwrap_or(([WHITE; 4], [part.alpha(); 4], [1.0; 4], mode::MUL));
1682
1683                    let call_start = self.prims.len() as u32;
1684                    self.push_quad_prim(frame, node, part_idx, Prim { mode, alpha, tint, colors, alphas, rates, cov_base, mask_info, ..Default::default() });
1685                    if !shader_dispatch {
1686                        continue;
1687                    }
1688                    // Per-part draw call so shader / non-shader parts don't merge.
1689                    if self.prims.len() as u32 == call_start {
1690                        continue;
1691                    }
1692                    // A shader part gets its own pipeline and params slot; a plain
1693                    // part sharing the batch falls back to the content pipeline.
1694                    let (call_key, shader_slot) = match has_shader(rank) {
1695                        Some(attr) => {
1696                            let slot = self.push_shader_params(&attr, frame, part_idx, renderer.texture_size(texture_hash));
1697                            (self.key(PipelineKind::Shader(attr.id_hash(), blend_index(blend_type))), Some(slot))
1698                        }
1699                        None => (key, None),
1700                    };
1701                    self.push_draw(call_key, GeomClass::Quad, texture_hash, call_start, shader_slot);
1702                }
1703                if !shader_dispatch {
1704                    self.push_draw(key, GeomClass::Quad, texture_hash, first_prim, None);
1705                }
1706            }
1707            DrawBatchKind::Mesh => {
1708                let key = self.content_key(blend_type, stencil, GeomClass::Mesh);
1709                let (mut stream_start, mut draw_prim) = (self.mesh_stream.len() as u32, first_prim);
1710                for rank in start_rank..start_rank + count {
1711                    if self.prims.len() as u32 - draw_prim == MESH_DRAW_PRIMS {
1712                        let call = self.mesh_draw(key, texture_hash, stream_start, draw_prim, None);
1713                        self.draw_calls.extend(call);
1714                        (stream_start, draw_prim) = (self.mesh_stream.len() as u32, self.prims.len() as u32);
1715                    }
1716                    let part_idx = draw_order.get(rank) as usize;
1717                    let part = parts.get(part_idx);
1718
1719                    let part_color_idx = part.part_color();
1720                    let (color, part_alpha, rate, mode) = parts_color
1721                        .filter(|_| part_color_idx >= 0)
1722                        .map(|pc_vec| {
1723                            let pc = pc_vec.get(part_color_idx as usize);
1724                            let lt = pc.lt();
1725                            let c = lt.rgba();
1726                            // Mesh uses a single (corner-0) PartColor sample, like WebGL.
1727                            (pack_rgb(c.r() as f32 / 255.0, c.g() as f32 / 255.0, c.b() as f32 / 255.0), c.a() as f32 / 255.0, lt.rate(), parts_color_mode(pc.blend_type()))
1728                        })
1729                        .unwrap_or((WHITE, part.alpha(), 1.0, mode::MUL));
1730
1731                    self.push_mesh_prim(frame, part_idx, draw_prim, Prim { mode, alpha, tint, node_base: node.transform, z: part.position_z(), colors: [color; 4], alphas: [part_alpha; 4], rates: [rate; 4], cov_base, mask_info, ..Default::default() });
1732                }
1733                let call = self.mesh_draw(key, texture_hash, stream_start, draw_prim, None);
1734                self.draw_calls.extend(call);
1735            }
1736            DrawBatchKind::Shape => {
1737                let key = self.content_key(blend_type, stencil, GeomClass::Shape);
1738                for rank in start_rank..start_rank + count {
1739                    let part_idx = draw_order.get(rank) as usize;
1740                    let part = parts.get(part_idx);
1741
1742                    // Shape fill: the interpolated PartColor corners, or white *
1743                    // alpha when the part has no PartColor (matches WebGL). Shapes
1744                    // are textureless (white fallback), so this colour shows as-is.
1745                    // Shape bypasses the PartColor blend formula: it is forced to
1746                    // the Mix path with rate 1 (hasPc) / 0 (no PartColor), so the
1747                    // fill is the bilinear PartColor itself.
1748                    let part_color_idx = part.part_color();
1749                    let has_pc = part_color_idx >= 0 && parts_color.is_some();
1750                    let (colors, alphas) = parts_color
1751                        .filter(|_| part_color_idx >= 0)
1752                        .map(|pc_vec| {
1753                            let pc = pc_vec.get(part_color_idx as usize);
1754                            let corners = [pc.lt().rgba(), pc.rt().rgba(), pc.lb().rgba(), pc.rb().rgba()];
1755                            let mut colors = [0u32; 4];
1756                            let mut alphas = [0.0f32; 4];
1757                            for (i, c) in corners.iter().enumerate() {
1758                                colors[i] = pack_rgb(c.r() as f32 / 255.0, c.g() as f32 / 255.0, c.b() as f32 / 255.0);
1759                                alphas[i] = c.a() as f32 / 255.0;
1760                            }
1761                            (colors, alphas)
1762                        })
1763                        .unwrap_or(([WHITE; 4], [part.alpha(); 4]));
1764
1765                    self.push_shape_prim(frame, node, part_idx, Prim { mode: mode::MIX, alpha, tint, colors, alphas, rates: [if has_pc { 1.0 } else { 0.0 }; 4], cov_base, mask_info, ..Default::default() });
1766                }
1767                self.push_draw(key, GeomClass::Shape, texture_hash, first_prim, None);
1768            }
1769            _ => {}
1770        }
1771    }
1772
1773    /// Append one part's integration-shader (`ss-*`) params as a 256-byte slot in
1774    /// `ss_params` and return its slot index (the dynamic uniform offset unit).
1775    /// `cell_rect` is the min/max of the quad's 4 normalized corner UVs (for
1776    /// ss-circle / ss-spot); `pixel_size` is 1/texel (for the neighbour-sampling
1777    /// shaders). MUST be called after the part's quad is built.
1778    fn push_shader_params(&mut self, attr: &PartAttributeShader, frame: &FrameView, part_idx: usize, tex_size: Option<(f32, f32)>) -> u32 {
1779        let slot = (self.ss_params.len() / SHADER_PARAM_STRIDE_F32) as u32;
1780        let cell = quad_uv_bounds(frame, part_idx, tex_size);
1781        let (tw, th) = tex_size.unwrap_or((1.0, 1.0));
1782        let px = if tw > 0.0 { 1.0 / tw } else { 0.0 };
1783        let py = if th > 0.0 { 1.0 / th } else { 0.0 };
1784
1785        let mut block = [0.0f32; SHADER_PARAM_STRIDE_F32];
1786        block[0] = attr.param0();
1787        block[1] = attr.param1();
1788        block[2] = attr.param2();
1789        block[3] = attr.param3();
1790        block[4] = attr.param4();
1791        block[5] = attr.param5();
1792        block[6] = attr.param6();
1793        block[7] = attr.param7();
1794        block[8..12].copy_from_slice(&cell);
1795        block[12] = px;
1796        block[13] = py;
1797        self.ss_params.extend_from_slice(&block);
1798        slot
1799    }
1800
1801    /// Append one mask writer's geometry, routed to the mask-write pipeline for
1802    /// `op`. The cutout threshold rides in the primitive's rate slot, which
1803    /// `fs_mask` reads as `varg.x`: it needs the full f32 range,
1804    /// including the -1 that means "no cutout". No-op if masking is disabled.
1805    pub fn append_mask_writer(&mut self, frame: &FrameView, node: &NodeSlot, writer: &MaskWriter, op: MaskOp) {
1806        self.append_writer(frame, node, writer, MaskWriterDest::Stencil(op));
1807    }
1808
1809    /// Rasterise one writer's shape into the coverage bitmap, setting `bit`.
1810    ///
1811    /// Called once per writer per frame — there is no add/remove interleave here,
1812    /// because the coverage backend does not carry a running state through the
1813    /// draw walk. What the stencil path spends passes replaying, the replay
1814    /// shader recomputes per fragment from the writer's rank.
1815    pub fn append_coverage_writer(&mut self, frame: &FrameView, node: &NodeSlot, writer: &MaskWriter, bit: usize) {
1816        self.append_writer(frame, node, writer, MaskWriterDest::Coverage(bit));
1817    }
1818
1819    /// The geometry half both writer paths share. Only the primitive's coverage
1820    /// word and which list the draw call lands in differ.
1821    fn append_writer(&mut self, frame: &FrameView, node: &NodeSlot, writer: &MaskWriter, dest: MaskWriterDest) {
1822        use crate::mask::GeomKind;
1823        if self.mask_backend() == MaskBackend::None || frame.frame_data.is_empty() {
1824            return;
1825        }
1826        if frame.world_matrices.is_empty() {
1827            return;
1828        }
1829        // Colour output is masked off for the stencil pipelines and carries the
1830        // writer's bit for the coverage ones, so only the threshold in `rates`
1831        // matters to both.
1832        let mut prim = Prim { rates: [writer.threshold; 4], alpha: 1.0, ..Default::default() };
1833        let kind_of = |class| match dest {
1834            MaskWriterDest::Stencil(op) => PipelineKind::Mask(op, class),
1835            MaskWriterDest::Coverage(_) => PipelineKind::Coverage(class),
1836        };
1837        if let MaskWriterDest::Coverage(bit) = dest {
1838            if node.coverage == NO_COVERAGE {
1839                return;
1840            }
1841            prim.cov_base = node.coverage;
1842            prim.mask_info = writer_mask_info(bit);
1843        }
1844        // Only a bake call picks a layer; masked content reads the layer its
1845        // primitive's coverage block names, so one bind group serves them all.
1846        // Past the first layer's bits a writer lands in the next layer along.
1847        let cov_layer = match dest {
1848            MaskWriterDest::Coverage(bit) => Some(node.coverage_layer + (bit / crate::mask::COVERAGE_LAYER_BITS) as u32),
1849            MaskWriterDest::Stencil(_) => None,
1850        };
1851        let first_prim = self.prims.len() as u32;
1852
1853        let class = match writer.geom {
1854            GeomKind::Quad => {
1855                if frame.local_vertices.is_empty() || frame.local_uvs.is_empty() {
1856                    return;
1857                }
1858                self.push_quad_prim(frame, node, writer.part_idx, prim);
1859                GeomClass::Quad
1860            }
1861            GeomKind::Mesh => {
1862                let stream_start = self.mesh_stream.len() as u32;
1863                self.push_mesh_prim(frame, writer.part_idx, first_prim, Prim { node_base: node.transform, ..prim });
1864                let call = self.mesh_draw(self.key(kind_of(GeomClass::Mesh)), writer.texture_hash, stream_start, first_prim, cov_layer);
1865                self.writer_calls(dest).extend(call);
1866                return;
1867            }
1868            GeomKind::Shape => {
1869                self.push_shape_prim(frame, node, writer.part_idx, prim);
1870                GeomClass::Shape
1871            }
1872            GeomKind::Unsupported => return,
1873        };
1874
1875        self.push_writer_draw(self.key(kind_of(class)), class, writer.texture_hash, first_prim, dest, cov_layer);
1876    }
1877
1878    /// Which list a writer's draw call belongs in.
1879    fn writer_calls(&mut self, dest: MaskWriterDest) -> &mut Vec<BatchDrawCall> {
1880        match dest {
1881            MaskWriterDest::Stencil(_) => &mut self.draw_calls,
1882            MaskWriterDest::Coverage(_) => &mut self.coverage_calls,
1883        }
1884    }
1885
1886    /// [`FrameChunk::push_draw`] against whichever list `dest` names.
1887    fn push_writer_draw(&mut self, key: PipelineKey, class: GeomClass, texture_hash: u32, first: u32, dest: MaskWriterDest, cov_layer: Option<u32>) {
1888        let last = self.prims.len() as u32;
1889        if last == first {
1890            return;
1891        }
1892        let stride = match class {
1893            GeomClass::Quad => QUAD_FAN_VERTS,
1894            GeomClass::Effect => 6,
1895            GeomClass::Shape => SHAPE_FAN_VERTS,
1896            // Mesh draws are driven by the stream, not by primitive arithmetic.
1897            GeomClass::Mesh => return,
1898        };
1899        // A bake is the player's, shared by every member; a stencil writer is
1900        // drawn where each member stands.
1901        let members = if cov_layer.is_some() { 1 } else { self.members };
1902        let call = BatchDrawCall { key, texture_hash, vertices: first * stride..last * stride, instances: 0..members, shader_slot: None, cov_layer };
1903        self.writer_calls(dest).push(call);
1904    }
1905
1906    /// Record one sprite quad for `part_idx`: copy the part's world matrix, local
1907    /// vertices and local UVs into the arena, point `prim` at them and append it.
1908    /// `vs_quad` expands the four corners and the centre into a fan.
1909    fn push_quad_prim(&mut self, frame: &FrameView, node: &NodeSlot, part_idx: usize, prim: Prim) {
1910        // A part the runtime has no geometry for must not produce a primitive at
1911        // all: the vertex stage reads whatever its offsets point at.
1912        let (Some(matrix), Some(vertices), Some(uvs)) = (frame.world_matrices.get(part_idx * 16..part_idx * 16 + 16), frame.local_vertices.get(part_idx * 10..part_idx * 10 + 10), frame.local_uvs.get(part_idx * 10..part_idx * 10 + 10)) else {
1913            return;
1914        };
1915        let aux_base = self.arena.len() as u32;
1916        self.arena.extend_from_slice(matrix);
1917        self.arena.extend_from_slice(vertices);
1918        self.arena.extend_from_slice(uvs);
1919        self.push_prim(Prim { aux_base, pos_base: aux_base + 16, uv_base: aux_base + 26, node_base: node.transform, ..prim });
1920    }
1921
1922    /// Record one skinned-mesh part, the primitive after `draw_prim` in its draw.
1923    ///
1924    /// A mesh's vertex count varies by part, so its geometry is copied per drawn
1925    /// part rather than per node: its vertices into the arena as the runtime laid
1926    /// them out, and its triangle list into the mesh stream, each index tagged
1927    /// with the part's place in its draw.
1928    fn push_mesh_prim(&mut self, frame: &FrameView, part_idx: usize, draw_prim: u32, prim: Prim) {
1929        let (vertices, indices) = (&frame.mesh_vertex_offsets, &frame.mesh_index_offsets);
1930        if part_idx + 1 >= vertices.len() || part_idx + 1 >= indices.len() {
1931            return;
1932        }
1933        let (start, end) = (vertices[part_idx] as usize, vertices[part_idx + 1] as usize);
1934        let (Some(x), Some(y), Some(uvs), Some(triangles)) =
1935            (frame.mesh_vertices_x.get(start..end), frame.mesh_vertices_y.get(start..end), frame.mesh_uvs.get(start * 2..end * 2), frame.mesh_indices.get(indices[part_idx] as usize..indices[part_idx + 1] as usize))
1936        else {
1937            return;
1938        };
1939        if x.is_empty() || triangles.is_empty() {
1940            return;
1941        }
1942
1943        let pos_base = self.arena.len() as u32;
1944        self.arena.extend_from_slice(x);
1945        let aux_base = self.arena.len() as u32;
1946        self.arena.extend_from_slice(y);
1947        let uv_base = self.arena.len() as u32;
1948        self.arena.extend_from_slice(uvs);
1949        let tag = (self.prims.len() as u32 - draw_prim) << MESH_PRIM_SHIFT;
1950        self.mesh_stream.extend(triangles.iter().map(|&index| tag | index as u32));
1951        self.push_prim(Prim { aux_base, pos_base, uv_base, ..prim });
1952    }
1953
1954    /// The draw over the stream from `stream_start` to its end, whose first
1955    /// primitive is `draw_prim`, or `None` when that is empty — or when
1956    /// `draw_prim` is past what an `instance_index` can name above the member
1957    /// (see [`CROWD_SHIFT`]).
1958    fn mesh_draw(&self, key: PipelineKey, texture_hash: u32, stream_start: u32, draw_prim: u32, cov_layer: Option<u32>) -> Option<BatchDrawCall> {
1959        let stream_end = self.mesh_stream.len() as u32;
1960        let members = if cov_layer.is_some() { 1 } else { self.members };
1961        let first = draw_prim << CROWD_SHIFT;
1962        (stream_end > stream_start && draw_prim < MESH_FIRST_PRIMS).then(|| BatchDrawCall { key, texture_hash, vertices: stream_start..stream_end, instances: first..first + members, shader_slot: None, cov_layer })
1963    }
1964
1965    /// Record one Shape part, drawn as a fan from vertex 0 by `vs_shape`: copy
1966    /// its world matrix and its live vertices and box coordinates into the arena.
1967    /// No-op if the part is not a shape or has fewer than 3 live vertices.
1968    fn push_shape_prim(&mut self, frame: &FrameView, node: &NodeSlot, part_idx: usize, prim: Prim) {
1969        // Layout: `shape_vertices[part_idx * SHAPE_VERTICES_STRIDE + 2*v]` = local xy.
1970        let count = frame.shape_vertex_counts.get(part_idx).copied().unwrap_or(0).max(0) as usize;
1971        // The fan pattern is baked into the vertex stage at a fixed stride, so a
1972        // shape with more vertices than that would silently lose triangles.
1973        if count < 3 || count > (SHAPE_FAN_VERTS as usize / 3) + 2 {
1974            return;
1975        }
1976        let base = part_idx * crate::frame::SHAPE_VERTICES_STRIDE;
1977        let (Some(matrix), Some(vertices), Some(box_coords)) = (frame.world_matrices.get(part_idx * 16..part_idx * 16 + 16), frame.shape_vertices.get(base..base + count * 2), frame.shape_vertex_box_coords.get(base..base + count * 2)) else {
1978            return;
1979        };
1980        let aux_base = self.arena.len() as u32;
1981        self.arena.extend_from_slice(matrix);
1982        self.arena.extend_from_slice(vertices);
1983        self.arena.extend_from_slice(box_coords);
1984        self.push_prim(Prim { aux_base, pos_base: aux_base + 16, uv_base: aux_base + 16 + (count * 2) as u32, node_base: node.transform, count: count as u32, ..prim });
1985    }
1986
1987    /// Append an effect slot's `EffectDrawPlan` (a raw FlatBuffer) to the frame.
1988    /// `node` names the effect part's composed placement (the vertices are
1989    /// slot-relative), and `keys` translates the plan's cellmap hashes into
1990    /// renderer texture keys. Blend is per-command; color is taken
1991    /// from the plan and modulates the cellmap texture via the sprite shader.
1992    /// `stencil` selects the stencil test when the effect is a masked target
1993    /// (inherited from a parent mask); `None` for ordinary effects. `alpha` and
1994    /// `tint` are the player-level fade and colour (see [`BatchInfo::alpha`] and
1995    /// [`BatchInfo::tint`]).
1996    ///
1997    /// Under the coverage backend a masked effect tests like any other part:
1998    /// `node` carries the coverage block, pulled back to the effect's own local
1999    /// space, and `mask_seq` is the emitter's place on the tree sequence.
2000    #[allow(clippy::too_many_arguments)]
2001    pub fn append_effect(&mut self, plan_buf: &[u8], node: &NodeSlot, stencil: StencilTest, mask_seq: u32, alpha: f32, tint: u32, keys: &crate::AtlasKeys) {
2002        if plan_buf.is_empty() {
2003            return;
2004        }
2005        let (cov_base, mask_info) = match stencil {
2006            _ if self.mask_backend() != MaskBackend::Coverage || node.coverage == NO_COVERAGE => (0, 0),
2007            StencilTest::Inside => (node.coverage, target_mask_info(mask_seq, true)),
2008            StencilTest::Outside => (node.coverage, target_mask_info(mask_seq, false)),
2009            StencilTest::None => (0, 0),
2010        };
2011        let plan = unsafe { root_as_effect_draw_plan_unchecked(plan_buf) };
2012        // XY pairs, four to a particle: `step_effects` asks every slot for a
2013        // vertex stride of 2.
2014        let (verts, uvs) = (plan.verts().bytes(), plan.uvs().bytes());
2015        let colors = plan.colors();
2016
2017        for cmd in plan.commands().iter() {
2018            let quad_count = cmd.quad_count() as usize;
2019            if quad_count == 0 {
2020                continue;
2021            }
2022            // Cellmap-hash terms, like a draw batch's: translated to the key the
2023            // owning pack's atlas actually registered under.
2024            let texture_hash = keys.resolve(cmd.cellmap_hash());
2025            let particle_offset = cmd.particle_offset() as usize;
2026            // 0 = Mix pipeline, 1 = Add pipeline (per-command, not per-batch).
2027            let blend = if cmd.blend() == 1 { BlendType::Add } else { BlendType::Mix };
2028            let key = self.content_key(blend, stencil, GeomClass::Effect);
2029
2030            let vert_first = particle_offset * 4;
2031            let vert_last = (particle_offset + quad_count) * 4;
2032
2033            // The particle quads go into the arena as they are — the runtime
2034            // emits them in the effect part's own space, relative to the slot.
2035            // The effect part's placement is left, and the vertex stage
2036            // applies that.
2037            let pos_base = self.arena.len() as u32;
2038            self.arena.extend(f32s(&verts[vert_first * 8..vert_last * 8]));
2039            let uv_base = self.arena.len() as u32;
2040            self.arena.extend(f32s(&uvs[vert_first * 8..vert_last * 8]));
2041
2042            // One primitive per particle. The runtime emits every particle as a
2043            // quad in the corner order `quad_corner` expands, so no index list
2044            // has to travel with them.
2045            let first_prim = self.prims.len() as u32;
2046            for q in 0..quad_count {
2047                let vi = vert_first + q * 4;
2048                let color = pack_rgb(colors.get(vi * 4), colors.get(vi * 4 + 1), colors.get(vi * 4 + 2));
2049                self.push_prim(Prim {
2050                    pos_base: pos_base + (q * 8) as u32,
2051                    uv_base: uv_base + (q * 8) as u32,
2052                    node_base: node.transform,
2053                    // Effects carry no PartsColor overlay: plain texture*color modulate.
2054                    mode: mode::MUL,
2055                    alpha,
2056                    tint,
2057                    colors: [color; 4],
2058                    alphas: [colors.get(vi * 4 + 3); 4],
2059                    rates: [1.0; 4],
2060                    cov_base,
2061                    mask_info,
2062                    ..Default::default()
2063                });
2064            }
2065            self.push_draw(key, GeomClass::Effect, texture_hash, first_prim, None);
2066        }
2067    }
2068}
2069
2070/// A Normal part draws as a fan of four triangles around its centre vertex.
2071///
2072/// Each test draws one synthetic part over a 64 px square and reads back the
2073/// pixels whose values tell the fan apart from the two-triangle split and from a
2074/// bilinear fill. The square is placed so pixel centres land on whole quarters of
2075/// it: pixel `31 + 64 s` is the point `s` of the way across. Every test skips
2076/// cleanly when no GPU adapter is available.
2077#[cfg(test)]
2078mod tests {
2079    use super::*;
2080    use crate::renderer::Retention;
2081    use ssruntime::runtime::framedata::ss::runtime::{DrawBatch, FrameData, FrameDataArgs, PartAttributePartColor, PartState, SsAttributePartColorKeyValueColor, U8Color};
2082
2083    const SIZE: u32 = 128;
2084    /// The square's corners `lt, rt, lb, rb` and its centre, in target pixels
2085    /// about the target's middle.
2086    const SQUARE: [f32; 10] = [-32.5, -32.5, 31.5, -32.5, -32.5, 31.5, 31.5, 31.5, -0.5, -0.5];
2087    /// Local UVs that sample nothing in particular: the white fallback is 1x1.
2088    const NO_UVS: [f32; 10] = [0.0; 10];
2089    /// The pixel `s` of the way across the square.
2090    fn px(s: f32) -> u32 {
2091        (31.0 + 64.0 * s) as u32
2092    }
2093
2094    fn gpu() -> Option<(wgpu::Device, wgpu::Queue)> {
2095        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
2096        let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::default(), compatible_surface: None, force_fallback_adapter: false, apply_limit_buckets: false })).ok()?;
2097        pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).ok()
2098    }
2099
2100    /// One part, Mix-blended by `corners` (`lt, rt, lb, rb`, each a grey level
2101    /// and a rate), or carrying no PartsColor at all when `corners` is `None`.
2102    fn frame_data(corners: Option<[(u8, f32); 4]>) -> Vec<u8> {
2103        let mut fbb = flatbuffers::FlatBufferBuilder::new();
2104        let mut part = PartState::default();
2105        part.set_alpha(1.0);
2106        part.set_part_color(if corners.is_some() { 0 } else { -1 });
2107        part.set_shader(-1);
2108        let parts = fbb.create_vector(&[part]);
2109        let parts_color = corners.map(|c| {
2110            let corner = |(grey, rate): (u8, f32)| SsAttributePartColorKeyValueColor::new(&U8Color::new(255, grey, grey, grey), rate);
2111            fbb.create_vector(&[PartAttributePartColor::new(BlendType::Mix, &corner(c[0]), &corner(c[1]), &corner(c[2]), &corner(c[3]))])
2112        });
2113        let draw_order = fbb.create_vector(&[0u16]);
2114        let draw_batches = fbb.create_vector::<DrawBatch>(&[]);
2115        let mask_indices = fbb.create_vector::<u16>(&[]);
2116        let root = FrameData::create(&mut fbb, &FrameDataArgs { parts: Some(parts), parts_color, draw_order: Some(draw_order), draw_batches: Some(draw_batches), mask_indices: Some(mask_indices), ..Default::default() });
2117        fbb.finish(root, None);
2118        fbb.finished_data().to_vec()
2119    }
2120
2121    /// Draw the one part of `frame_data` with `vertices` / `uvs` over opaque
2122    /// black, and read the target back as RGBA8.
2123    fn draw(device: &wgpu::Device, queue: &wgpu::Queue, renderer: &mut SSRenderer, texture_hash: u32, frame_data: &[u8], vertices: &[f32; 10], uvs: &[f32; 10]) -> Vec<u8> {
2124        let format = wgpu::TextureFormat::Rgba8Unorm;
2125        let mut scene = SSScene::new(device, &SceneConfig { color_format: format, stencil_format: None, mask: MaskBackend::None });
2126        scene.set_viewport(queue, SIZE as f32, SIZE as f32, false);
2127        let frame = FrameView { frame_data, world_matrices: &IDENTITY_TRANSFORM, local_vertices: vertices, local_uvs: uvs, ..Default::default() };
2128        scene.begin_frame();
2129        let node = scene.frame.push_transform(&IDENTITY_TRANSFORM);
2130        let batch = BatchInfo { start_rank: 0, count: 1, texture_hash, blend_type: BlendType::Mix, kind: DrawBatchKind::Normal, stencil: StencilTest::None, mask_seq: 0, alpha: 1.0, tint: NO_TINT };
2131        scene.frame.append_batch(renderer, &frame, &node, &batch);
2132        scene.end_frame(renderer, device, queue);
2133
2134        let extent = wgpu::Extent3d { width: SIZE, height: SIZE, depth_or_array_layers: 1 };
2135        let target = device.create_texture(&wgpu::TextureDescriptor {
2136            label: None,
2137            size: extent,
2138            mip_level_count: 1,
2139            sample_count: 1,
2140            dimension: wgpu::TextureDimension::D2,
2141            format,
2142            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
2143            view_formats: &[],
2144        });
2145        let view = target.create_view(&wgpu::TextureViewDescriptor::default());
2146        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
2147        {
2148            let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
2149                label: None,
2150                color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &view, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store }, depth_slice: None })],
2151                depth_stencil_attachment: None,
2152                timestamp_writes: None,
2153                occlusion_query_set: None,
2154                multiview_mask: None,
2155            });
2156            assert_eq!(scene.draw(renderer, &mut rpass), 1, "the part was not drawn");
2157        }
2158        let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: None, size: (SIZE * SIZE * 4) as u64, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
2159        encoder.copy_texture_to_buffer(
2160            wgpu::TexelCopyTextureInfo { texture: &target, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
2161            wgpu::TexelCopyBufferInfo { buffer: &buffer, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(SIZE * 4), rows_per_image: Some(SIZE) } },
2162            extent,
2163        );
2164        queue.submit(std::iter::once(encoder.finish()));
2165        buffer.slice(..).map_async(wgpu::MapMode::Read, |r| r.unwrap());
2166        device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }).unwrap();
2167        let data = buffer.slice(..).get_mapped_range().unwrap().to_vec();
2168        buffer.unmap();
2169        data
2170    }
2171
2172    /// Assert the red channel at `(x, y)` is `expected` (0..1), give or take the
2173    /// rounding of an 8-bit target.
2174    fn assert_level(rgba: &[u8], (x, y): (u32, u32), expected: f32, what: &str) {
2175        let got = rgba[((y * SIZE + x) * 4) as usize];
2176        let want = expected * 255.0;
2177        assert!((got as f32 - want).abs() <= 2.0, "{what}: pixel ({x}, {y}) is {got}, expected {want:.1}");
2178    }
2179
2180    /// lt = rb = white and rt = lb = black: the centre takes the mean, grey, and
2181    /// a quarter of the way along a diagonal reads 0.75 towards a white corner
2182    /// and 0.25 towards a black one. Two triangles would put the centre on the
2183    /// black diagonal (0) and the quarter point at 0.5; a bilinear fill would
2184    /// read 0.625 there.
2185    #[test]
2186    fn a_four_corner_colour_shades_as_a_fan() {
2187        let Some((device, queue)) = gpu() else {
2188            eprintln!("no GPU adapter available, skipping headless render test");
2189            return;
2190        };
2191        let mut renderer = SSRenderer::new(&device);
2192        let data = frame_data(Some([(255, 1.0), (0, 1.0), (0, 1.0), (255, 1.0)]));
2193        let rgba = draw(&device, &queue, &mut renderer, 0, &data, &SQUARE, &NO_UVS);
2194        assert_level(&rgba, (px(0.5), px(0.5)), 0.5, "centre");
2195        assert_level(&rgba, (px(0.25), px(0.25)), 0.75, "towards lt");
2196        assert_level(&rgba, (px(0.75), px(0.75)), 0.75, "towards rb");
2197        assert_level(&rgba, (px(0.75), px(0.25)), 0.25, "towards rt");
2198        assert_level(&rgba, (px(0.25), px(0.75)), 0.25, "towards lb");
2199    }
2200
2201    /// The rate is averaged at the centre like the colour. Black blended over the
2202    /// white fallback reads `1 - rate`, so lt = rb = 1 and rt = lb = 0 put the
2203    /// centre at 0.5 — two triangles would leave it white.
2204    #[test]
2205    fn a_four_corner_rate_is_averaged_at_the_centre() {
2206        let Some((device, queue)) = gpu() else {
2207            eprintln!("no GPU adapter available, skipping headless render test");
2208            return;
2209        };
2210        let mut renderer = SSRenderer::new(&device);
2211        let data = frame_data(Some([(0, 1.0), (0, 0.0), (0, 0.0), (0, 1.0)]));
2212        let rgba = draw(&device, &queue, &mut renderer, 0, &data, &SQUARE, &NO_UVS);
2213        assert_level(&rgba, (px(0.5), px(0.5)), 0.5, "centre");
2214        assert_level(&rgba, (px(0.25), px(0.25)), 0.25, "towards lt");
2215        assert_level(&rgba, (px(0.75), px(0.25)), 0.75, "towards rt");
2216    }
2217
2218    /// The centre is the runtime's fifth local vertex, not the corners' mean
2219    /// recomputed here: moved to `(0.375, 0.375)`, the grey of the centre moves
2220    /// with it. Centred on the mean, that point would read 0.625.
2221    #[test]
2222    fn the_centre_is_the_fifth_local_vertex() {
2223        let Some((device, queue)) = gpu() else {
2224            eprintln!("no GPU adapter available, skipping headless render test");
2225            return;
2226        };
2227        let mut renderer = SSRenderer::new(&device);
2228        let data = frame_data(Some([(255, 1.0), (0, 1.0), (0, 1.0), (255, 1.0)]));
2229        let mut vertices = SQUARE;
2230        [vertices[8], vertices[9]] = [-8.5, -8.5];
2231        let rgba = draw(&device, &queue, &mut renderer, 0, &data, &vertices, &NO_UVS);
2232        assert_level(&rgba, (px(0.375), px(0.375)), 0.5, "moved centre");
2233    }
2234
2235    /// The centre samples the runtime's fifth local UV. A horizontal ramp, texel
2236    /// `i` at level `i`, drawn with the centre's U moved from the middle to a
2237    /// quarter: the middle pixel reads a quarter of the ramp, not half of it.
2238    #[test]
2239    fn the_centre_samples_the_fifth_local_uv() {
2240        let Some((device, queue)) = gpu() else {
2241            eprintln!("no GPU adapter available, skipping headless render test");
2242            return;
2243        };
2244        let mut renderer = SSRenderer::new(&device);
2245        let ramp: Vec<u8> = (0..=255u8).flat_map(|i| [i, i, i, 255]).collect();
2246        let hash = 1;
2247        renderer.upload_texture(&device, &queue, hash, &ramp, (256, 1), Retention::Retain);
2248        let uvs = [0.0, 0.0, 256.0, 0.0, 0.0, 1.0, 256.0, 1.0, 64.0, 0.5];
2249        let rgba = draw(&device, &queue, &mut renderer, hash, &frame_data(None), &SQUARE, &uvs);
2250        assert_level(&rgba, (px(0.5), px(0.5)), 63.5 / 255.0, "centre");
2251    }
2252
2253    /// Group alpha turned off between an update and the offscreen pass — a C host
2254    /// calling `ss_scene_set_group_alpha` between `ss_scene_update` and
2255    /// `ss_scene_render` — still draws the layer that frame was built with, and
2256    /// the next update frees it.
2257    #[test]
2258    fn group_alpha_turned_off_mid_frame_frees_the_layers_at_the_next_update() {
2259        let Some((device, queue)) = gpu() else {
2260            eprintln!("no GPU adapter available, skipping headless render test");
2261            return;
2262        };
2263        let mut renderer = SSRenderer::new(&device);
2264        let mut scene = SSScene::new(&device, &SceneConfig { color_format: wgpu::TextureFormat::Rgba8Unorm, stencil_format: None, mask: MaskBackend::None });
2265        scene.set_viewport(&queue, SIZE as f32, SIZE as f32, false);
2266        scene.set_group_alpha(true);
2267        let data = frame_data(None);
2268        let frame = FrameView { frame_data: &data, world_matrices: &IDENTITY_TRANSFORM, local_vertices: &SQUARE, local_uvs: &NO_UVS, ..Default::default() };
2269        scene.begin_frame();
2270        let node = scene.frame.push_transform(&IDENTITY_TRANSFORM);
2271        let batch = BatchInfo { start_rank: 0, count: 1, texture_hash: 0, blend_type: BlendType::Mix, kind: DrawBatchKind::Normal, stencil: StencilTest::None, mask_seq: 0, alpha: 1.0, tint: NO_TINT };
2272        scene.frame.append_batch(&renderer, &frame, &node, &batch);
2273        scene.frame.push_group(0, 0.5);
2274        scene.end_frame(&mut renderer, &device, &queue);
2275
2276        scene.set_group_alpha(false);
2277        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
2278        scene.encode_offscreen(&mut renderer, &device, &mut encoder);
2279        assert_eq!(scene.stats().group_layers, 1, "the frame built with a layer did not draw it");
2280        assert!(scene.layers.is_some(), "the layer the frame composites is gone before its draw");
2281
2282        scene.update(&mut renderer, &device, &queue, 0.0, &mut []);
2283        assert!(scene.layers.is_none(), "group alpha is off, and its layers outlived the next update");
2284    }
2285
2286    /// A frame copied up through the staging buffers lands in the frame buffer
2287    /// byte for byte as `write_buffer_with` puts it: through a new buffer, through
2288    /// one mapped again after a frame laid out differently — whose bytes would
2289    /// show in the gaps if they were not cleared — and through one replaced for a
2290    /// frame larger than it.
2291    #[cfg(not(target_arch = "wasm32"))]
2292    #[test]
2293    fn a_staged_frame_lands_as_a_written_one() {
2294        let Some((device, queue)) = gpu() else {
2295            eprintln!("no GPU adapter available, skipping headless render test");
2296            return;
2297        };
2298        let read = |buffer: &wgpu::Buffer| -> Vec<u8> {
2299            let readback = device.create_buffer(&wgpu::BufferDescriptor { label: None, size: buffer.size(), usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
2300            let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
2301            encoder.copy_buffer_to_buffer(buffer, 0, &readback, 0, buffer.size());
2302            queue.submit([encoder.finish()]);
2303            readback.slice(..).map_async(wgpu::MapMode::Read, |r| r.unwrap());
2304            device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }).unwrap();
2305            readback.slice(..).get_mapped_range().unwrap().to_vec()
2306        };
2307        let mut staging = FrameStaging::default();
2308        for (frame, lens) in [[9_004, 30_000, 12_008, 512], [8_004, 30_000, 12_008, 512], [27_004, 90_000, 36_008, 1_024]].into_iter().enumerate() {
2309            let arrays = lens.map(|len| (0..len).map(|i| (i as u8).wrapping_mul(31).wrapping_add(frame as u8 + 1)).collect::<Vec<u8>>());
2310            let mut end = 0usize;
2311            let parts: FrameParts = std::array::from_fn(|i| {
2312                let at = end.next_multiple_of(FRAME_ALIGN as usize);
2313                end = at + arrays[i].len();
2314                (at, arrays[i].as_slice())
2315            });
2316            let target = || device.create_buffer(&wgpu::BufferDescriptor { label: None, size: end as u64, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });
2317            let (written, staged) = (target(), target());
2318            upload_frame(&queue, &written, &parts);
2319            assert!(staging.upload(&device, &queue, &staged, &parts), "frame {frame}: no staging buffer was free, though the last frame was waited for");
2320            assert!(read(&written) == read(&staged), "frame {frame}: the staged frame differs from the written one");
2321        }
2322        assert_eq!(staging.slots.iter().flatten().count(), 1, "a staging buffer was made while one was free");
2323    }
2324}