Skip to main content

sim_logic/rendering/
extraction.rs

1//! Atomic CPU extraction into bounded Sim;Engine visual state.
2
3use crate::{
4    assets::ImageAssetId,
5    identity::{LogicEntity, WorldGeneration},
6    render::RenderLimits,
7    screen::{ImageVisualError, ScreenVisualError},
8    three_d::{
9        CuboidSource, MeshSource, ResolvedCuboid3d, ResolvedMesh3d, ThreeDExtractionBuffer,
10        ThreeDExtractionError, ThreeDRenderLimits, ThreeDSnapshot, View3d,
11    },
12    visual::{
13        ActiveCamera2d, CircleVisual, LineVisual, RectangleVisual, Transform2d, VisualValueError,
14        line_stroke_style,
15    },
16};
17use sim_engine::{
18    Camera2d, Color, Layer, Rect, Scene, SceneBudgetResource, SceneError, ShapeStyle, Vec2,
19};
20use std::{cmp::Ordering, error::Error, fmt, mem::size_of};
21
22#[path = "extraction/screen.rs"]
23mod screen;
24#[cfg(feature = "headless-text")]
25pub use screen::ResolvedScreenText;
26use screen::ScreenExtractionBuffer;
27#[cfg(feature = "headless-text")]
28pub(crate) use screen::ScreenTextSource;
29pub use screen::{
30    ResolvedScreenImage, ResolvedScreenPrimitive, ResolvedScreenRectangle, ScreenDraw,
31    ScreenExtractionUpdates,
32};
33pub(crate) use screen::{ScreenImageSource, ScreenRectangleSource, ScreenSource};
34
35/// One fully resolved circle retained for headless parity and diagnostics.
36///
37/// Records preserve their relative order from the single deterministic mixed
38/// Sim;Engine scene. The interpolated position is presentation state and is
39/// never written back to the ECS World.
40#[derive(Debug, Clone, Copy, PartialEq)]
41pub struct ResolvedCircle {
42    source: LogicEntity,
43    position: Vec2,
44    radius: f32,
45    color: Color,
46    layer: Layer,
47    draw_order_depth: f32,
48}
49
50/// One fully resolved rectangle retained for headless parity and diagnostics.
51///
52/// Records preserve their relative order from the single deterministic mixed
53/// Sim;Engine scene. Position is the interpolated world-space center; size and
54/// style are sampled directly from the canonical component.
55#[derive(Debug, Clone, Copy, PartialEq)]
56pub struct ResolvedRectangle {
57    source: LogicEntity,
58    position: Vec2,
59    size: Vec2,
60    corner_radius: f32,
61    color: Color,
62    layer: Layer,
63    draw_order_depth: f32,
64}
65
66/// One fully resolved anchored line retained for headless parity and diagnostics.
67///
68/// `from` and `to` are presentation-space world points after Transform
69/// interpolation. Vector and style are sampled from the current component and
70/// never written back to the ECS World.
71#[derive(Debug, Clone, Copy, PartialEq)]
72pub struct ResolvedLine {
73    source: LogicEntity,
74    from: Vec2,
75    to: Vec2,
76    stroke_width_logical_pixels: f32,
77    color: Color,
78    layer: Layer,
79    draw_order_depth: f32,
80}
81
82impl ResolvedLine {
83    /// Returns the managed entity that produced this visual.
84    pub const fn source(self) -> LogicEntity {
85        self.source
86    }
87
88    /// Returns the interpolated anchor in world coordinates.
89    pub const fn from(self) -> Vec2 {
90        self.from
91    }
92
93    /// Returns the resolved endpoint in world coordinates.
94    pub const fn to(self) -> Vec2 {
95        self.to
96    }
97
98    /// Returns stroke width in logical screen pixels.
99    pub const fn stroke_width_logical_pixels(self) -> f32 {
100        self.stroke_width_logical_pixels
101    }
102
103    /// Returns the normalized straight-linear RGBA stroke color.
104    pub const fn color(self) -> Color {
105        self.color
106    }
107
108    /// Returns the primary Sim;Engine draw layer.
109    pub const fn layer(self) -> Layer {
110        self.layer
111    }
112
113    /// Returns the within-layer ordering value used by Sim;Logic.
114    ///
115    /// This is not Sim;Engine projection depth.
116    pub const fn draw_order_depth(self) -> f32 {
117        self.draw_order_depth
118    }
119}
120
121impl ResolvedRectangle {
122    /// Returns the managed entity that produced this visual.
123    pub const fn source(self) -> LogicEntity {
124        self.source
125    }
126
127    /// Returns the interpolated world-space center.
128    pub const fn position(self) -> Vec2 {
129        self.position
130    }
131
132    /// Returns the full width and height in caller-defined world units.
133    pub const fn size(self) -> Vec2 {
134        self.size
135    }
136
137    /// Returns the requested corner radius before renderer-side clamping.
138    pub const fn corner_radius(self) -> f32 {
139        self.corner_radius
140    }
141
142    /// Returns the normalized straight-linear RGBA fill color.
143    pub const fn color(self) -> Color {
144        self.color
145    }
146
147    /// Returns the primary Sim;Engine draw layer.
148    pub const fn layer(self) -> Layer {
149        self.layer
150    }
151
152    /// Returns the within-layer ordering value used by Sim;Logic.
153    ///
154    /// This is not Sim;Engine projection depth.
155    pub const fn draw_order_depth(self) -> f32 {
156        self.draw_order_depth
157    }
158}
159
160impl ResolvedCircle {
161    /// Returns the managed entity that produced this visual.
162    pub const fn source(self) -> LogicEntity {
163        self.source
164    }
165
166    /// Returns the interpolated world-space center.
167    pub const fn position(self) -> Vec2 {
168        self.position
169    }
170
171    /// Returns the circle radius in caller-defined world units.
172    pub const fn radius(self) -> f32 {
173        self.radius
174    }
175
176    /// Returns the normalized straight-linear RGBA fill color.
177    pub const fn color(self) -> Color {
178        self.color
179    }
180
181    /// Returns the primary Sim;Engine draw layer.
182    pub const fn layer(self) -> Layer {
183        self.layer
184    }
185
186    /// Returns the within-layer ordering value used by Sim;Logic.
187    ///
188    /// This is not Sim;Engine projection depth.
189    pub const fn draw_order_depth(self) -> f32 {
190        self.draw_order_depth
191    }
192}
193
194/// Complete renderer-independent visual snapshot for one World generation.
195///
196/// A snapshot is published only after every required visual and its CPU/Scene
197/// limits have been validated. The desktop bridge must compare
198/// [`ExtractedFrame::world_generation`] with the active World immediately
199/// before submission so a retired generation is never rendered.
200pub struct ExtractedFrame {
201    world_generation: WorldGeneration,
202    background: Color,
203    camera: Camera2d,
204    storage: ExtractionBuffer,
205}
206
207struct ExtractionBuffer {
208    resolved_circles: Vec<ResolvedCircle>,
209    resolved_rectangles: Vec<ResolvedRectangle>,
210    resolved_lines: Vec<ResolvedLine>,
211    #[cfg_attr(
212        not(feature = "desktop"),
213        allow(dead_code, reason = "the headless build retains CPU parity data only")
214    )]
215    world_scene: Scene,
216    screen: ScreenExtractionBuffer,
217    three_d: ThreeDExtractionBuffer,
218}
219
220#[derive(Debug, Clone, Copy)]
221struct ExtractedMetadata {
222    world_generation: WorldGeneration,
223    background: Color,
224    camera: Camera2d,
225}
226
227#[derive(Debug, Clone, Copy)]
228pub(crate) struct ExtractionParameters {
229    world_generation: WorldGeneration,
230    background: Color,
231    alpha: f32,
232    limits: RenderLimits,
233}
234
235/// Application-owned published/work storage for atomic CPU extraction.
236pub(crate) struct ExtractionBuffers {
237    published: Option<ExtractedFrame>,
238    spare: Option<ExtractionBuffer>,
239    staged: Option<ExtractedMetadata>,
240}
241
242impl ExtractedFrame {
243    /// CPU screen work for this snapshot, independent of native GPU preparation.
244    /// Complete-frame publication uses two alternating buffers; each warms its
245    /// own exact-value cache. World geometry/interpolation are not cached here.
246    pub const fn screen_extraction_updates(&self) -> ScreenExtractionUpdates {
247        self.storage.screen.updates
248    }
249    /// Returns the World generation from which this snapshot was extracted.
250    pub const fn world_generation(&self) -> WorldGeneration {
251        self.world_generation
252    }
253
254    /// Returns the normalized clear color for the composed frame.
255    pub const fn background(&self) -> Color {
256        self.background
257    }
258
259    /// Returns the validated, interpolated presentation camera for this frame.
260    ///
261    /// This may differ from the active component's canonical camera during a
262    /// partial fixed interval.
263    pub const fn camera(&self) -> Camera2d {
264        self.camera
265    }
266
267    /// Returns value-comparable circles in their relative mixed-scene order.
268    pub fn resolved_circles(&self) -> &[ResolvedCircle] {
269        &self.storage.resolved_circles
270    }
271
272    /// Returns value-comparable rectangles in their relative mixed-scene order.
273    pub fn resolved_rectangles(&self) -> &[ResolvedRectangle] {
274        &self.storage.resolved_rectangles
275    }
276
277    /// Returns nonzero lines in their relative mixed-scene order.
278    pub fn resolved_lines(&self) -> &[ResolvedLine] {
279        &self.storage.resolved_lines
280    }
281
282    /// Returns screen rectangles in their deterministic screen-layer order.
283    ///
284    /// Positions and sizes are current logical pixels, not interpolated world
285    /// coordinates. All these records are composed above the world scene.
286    pub fn resolved_screen_rectangles(&self) -> &[ResolvedScreenRectangle] {
287        self.storage.screen.resolved()
288    }
289
290    /// Iterates over sorted screen rectangles, lines, circles and paths without allocating.
291    /// Path clones share their immutable CPU points.
292    /// Values are current FrameUpdate presentation, independent of fixed interpolation.
293    pub fn screen_primitives(&self) -> impl Iterator<Item = ResolvedScreenPrimitive> + '_ {
294        self.storage.screen.primitive_records()
295    }
296
297    /// Returns current screen images in their relative mixed-screen order.
298    ///
299    /// Records contain immutable asset IDs, not GPU resources. Use
300    /// `HeadlessRunner::image_asset` to inspect the registered source pixels.
301    pub fn resolved_screen_images(&self) -> &[ResolvedScreenImage] {
302        self.storage.screen.images()
303    }
304
305    /// Returns current prepared labels in their relative mixed-screen order.
306    ///
307    /// Strings, metrics, and fonts share their component's immutable CPU
308    /// preparation. No shaping, GPU allocation, or fixed interpolation occurs.
309    #[cfg(feature = "headless-text")]
310    pub fn resolved_screen_texts(&self) -> &[ResolvedScreenText] {
311        self.storage.screen.texts()
312    }
313
314    /// Returns the enabled 3D view and cuboids, or None when 3D is suppressed.
315    ///
316    /// Desktop composition places this opaque depth target above the 2D world
317    /// and below all screen draws. The snapshot contains no GPU resources.
318    pub fn three_d(&self) -> Option<ThreeDSnapshot<'_>> {
319        self.storage.three_d.snapshot()
320    }
321
322    /// Returns current visible cuboids in stable managed-identity order.
323    ///
324    /// Missing or disabled View3d resources produce an empty slice.
325    pub fn resolved_cuboids(&self) -> &[ResolvedCuboid3d] {
326        self.storage.three_d.resolved()
327    }
328
329    /// Returns current visible custom meshes in stable managed-identity order.
330    /// Missing or disabled View3d resources produce an empty slice.
331    pub fn resolved_meshes(&self) -> &[ResolvedMesh3d] {
332        self.storage
333            .three_d
334            .snapshot()
335            .map_or(&[], |snapshot| snapshot.meshes())
336    }
337
338    /// Returns the exact screen composition after the world scene.
339    ///
340    /// Contiguous primitive runs, images, and optional text share layer, depth,
341    /// and stable source order. Exact same-source ties put rectangles first,
342    /// then lines, circles, paths, images, and text. Empty screen content produces no
343    /// items. This plan does not replace desktop aggregate budget checks.
344    pub fn screen_draws(&self) -> &[ScreenDraw] {
345        self.storage.screen.draws()
346    }
347
348    /// Inspects one `ScreenDraw::Primitives` or `ScreenDraw::Rectangles` run.
349    /// Returns no iterator for an absent run; records borrow this snapshot and
350    /// retain exactly the order submitted to Engine, without allocation.
351    pub fn screen_primitive_run_records(
352        &self,
353        run: usize,
354    ) -> Option<impl Iterator<Item = ResolvedScreenPrimitive> + '_> {
355        self.storage.screen.primitive_run_records(run)
356    }
357
358    /// Returns just the rectangle records for one run in `screen_draws`.
359    /// A vector-only run returns an empty slice; an absent run returns None.
360    pub fn screen_rectangle_run_records(&self, run: usize) -> Option<&[ResolvedScreenRectangle]> {
361        self.storage.screen.run_records(run)
362    }
363
364    #[cfg(feature = "desktop")]
365    pub(crate) fn screen_rectangle_run(&self, run: usize) -> Option<&sim_engine::ScreenScene> {
366        self.storage.screen.run_scene(run)
367    }
368
369    /// Returns the camera-independent scene for the optional desktop bridge.
370    #[cfg(feature = "desktop")]
371    pub(crate) fn screen_scene(&self) -> &sim_engine::ScreenScene {
372        self.storage.screen.scene()
373    }
374
375    /// Returns the bounded world scene used by the desktop bridge.
376    #[cfg_attr(
377        not(feature = "desktop"),
378        allow(dead_code, reason = "used by the optional desktop bridge")
379    )]
380    pub(crate) const fn world_scene(&self) -> &Scene {
381        &self.storage.world_scene
382    }
383}
384
385impl ExtractionBuffer {
386    fn new(limits: RenderLimits) -> Result<Self, ExtractionError> {
387        let world_scene = Scene::with_budget(Color::BLACK, limits.world_scene_budget())
388            .map_err(ExtractionError::Scene)?;
389        Ok(Self {
390            resolved_circles: Vec::new(),
391            resolved_rectangles: Vec::new(),
392            resolved_lines: Vec::new(),
393            world_scene,
394            screen: ScreenExtractionBuffer::new(limits)?,
395            three_d: ThreeDExtractionBuffer::new(),
396        })
397    }
398}
399
400impl ExtractedMetadata {
401    fn with_storage(self, storage: ExtractionBuffer) -> ExtractedFrame {
402        ExtractedFrame {
403            world_generation: self.world_generation,
404            background: self.background,
405            camera: self.camera,
406            storage,
407        }
408    }
409}
410
411impl ExtractionParameters {
412    pub(crate) const fn new(
413        world_generation: WorldGeneration,
414        background: Color,
415        alpha: f32,
416        limits: RenderLimits,
417    ) -> Self {
418        Self {
419            world_generation,
420            background,
421            alpha,
422            limits,
423        }
424    }
425}
426
427impl ExtractionBuffers {
428    pub(crate) const fn new() -> Self {
429        Self {
430            published: None,
431            spare: None,
432            staged: None,
433        }
434    }
435
436    /// Invalidates metadata from an abandoned candidate before more fallible work.
437    pub(crate) fn discard_staged(&mut self) {
438        self.staged = None;
439    }
440
441    pub(crate) fn stage(
442        &mut self,
443        parameters: ExtractionParameters,
444        cameras: impl IntoIterator<Item = ActiveCamera2d>,
445        circles: impl IntoIterator<Item = CircleSource>,
446        rectangles: impl IntoIterator<Item = RectangleSource>,
447        lines: impl IntoIterator<Item = LineSource>,
448        screen_rectangles: impl IntoIterator<Item = ScreenSource>,
449    ) -> Result<(), ExtractionError> {
450        self.staged = None;
451        let mut spare = match self.spare.take() {
452            Some(spare) => spare,
453            None => ExtractionBuffer::new(parameters.limits)?,
454        };
455        let result = extract_frame_into(
456            &mut spare,
457            parameters,
458            cameras,
459            circles,
460            rectangles,
461            lines,
462            screen_rectangles,
463        );
464        self.spare = Some(spare);
465        let metadata = result?;
466        self.staged = Some(metadata);
467        Ok(())
468    }
469
470    #[cfg(test)]
471    fn stage_world_only(
472        &mut self,
473        parameters: ExtractionParameters,
474        cameras: impl IntoIterator<Item = ActiveCamera2d>,
475        circles: impl IntoIterator<Item = CircleSource>,
476        rectangles: impl IntoIterator<Item = RectangleSource>,
477        lines: impl IntoIterator<Item = LineSource>,
478    ) -> Result<(), ExtractionError> {
479        self.stage(parameters, cameras, circles, rectangles, lines, [])
480    }
481
482    pub(crate) fn stage_three_d(
483        &mut self,
484        generation: WorldGeneration,
485        limits: ThreeDRenderLimits,
486        view: Option<View3d>,
487        sources: impl IntoIterator<Item = CuboidSource>,
488        meshes: impl IntoIterator<Item = MeshSource>,
489    ) -> Result<(), ExtractionError> {
490        let Some(metadata) = self.staged.take() else {
491            return Err(ExtractionError::MissingStagedFrame);
492        };
493        let Some(spare) = self.spare.as_mut() else {
494            return Err(ExtractionError::MissingStagedFrame);
495        };
496        spare
497            .three_d
498            .extract(generation, limits, view, sources)
499            .map_err(ExtractionError::ThreeD)?;
500        spare
501            .three_d
502            .extract_meshes(generation, limits, meshes)
503            .map_err(ExtractionError::ThreeD)?;
504        self.staged = Some(metadata);
505        Ok(())
506    }
507
508    /// Publishes the complete staged buffer and recycles the previous one.
509    pub(crate) fn publish(&mut self) -> Option<WorldGeneration> {
510        let metadata = self.staged.take()?;
511        let Some(storage) = self.spare.take() else {
512            self.staged = Some(metadata);
513            return None;
514        };
515        let generation = metadata.world_generation;
516        let previous = self.published.replace(metadata.with_storage(storage));
517        self.spare = previous.map(|frame| frame.storage);
518        Some(generation)
519    }
520
521    pub(crate) const fn published(&self) -> Option<&ExtractedFrame> {
522        self.published.as_ref()
523    }
524}
525
526/// Structured reason why a new CPU visual snapshot was not published.
527#[derive(Debug)]
528#[non_exhaustive]
529pub enum ExtractionError {
530    /// A screen line/circle/path source count exceeded its explicit per-kind limit.
531    ScreenPrimitiveLimitExceeded {
532        /// First source that exceeded the limit.
533        entity: LogicEntity,
534        /// Configured maximum for this primitive kind.
535        limit: usize,
536    },
537    /// Enabled path points exceeded their aggregate CPU limit, including hidden clips.
538    ScreenPolylinePointsLimitExceeded {
539        /// Path that would exceed the limit.
540        entity: LogicEntity,
541        /// Configured aggregate path-point limit.
542        limit: usize,
543        /// Requested total, or usize::MAX on arithmetic overflow.
544        requested: usize,
545    },
546    /// A private staged snapshot was unavailable for completing 3D extraction.
547    MissingStagedFrame,
548    /// Independent bounded 3D snapshot preparation failed.
549    ThreeD(ThreeDExtractionError),
550    /// The active World did not contain a camera marked for extraction.
551    MissingActiveCamera,
552    /// The active World contained more than one marked camera.
553    MultipleActiveCameras,
554    /// Interpolation alpha was non-finite or outside the inclusive `0.0..=1.0` range.
555    InvalidInterpolationAlpha {
556        /// Rejected accumulator fraction.
557        alpha: f32,
558    },
559    /// A visual entity did not belong to the generation being extracted.
560    ForeignEntity {
561        /// Entity that carried stale or foreign provenance.
562        entity: LogicEntity,
563        /// Generation accepted by this extraction.
564        expected: WorldGeneration,
565    },
566    /// A component contained a value outside its public visual contract.
567    InvalidVisual {
568        /// Entity whose visual data was rejected.
569        entity: LogicEntity,
570        /// Exact invalid value category.
571        error: VisualValueError,
572    },
573    /// Interpolation of two finite translations did not produce a finite result.
574    InvalidInterpolatedTranslation {
575        /// Entity whose interpolation failed.
576        entity: LogicEntity,
577    },
578    /// A finite center and size produced collapsed or non-finite f32 bounds.
579    InvalidResolvedRectangle {
580        /// Entity whose derived bounds were not representable.
581        entity: LogicEntity,
582    },
583    /// An interpolated anchor and finite vector did not form a representable segment.
584    InvalidResolvedLine {
585        /// Entity whose resolved segment was rejected.
586        entity: LogicEntity,
587    },
588    /// The configured extracted-circle count was exceeded.
589    CircleLimitExceeded {
590        /// Configured maximum resolved circle count.
591        limit: usize,
592    },
593    /// The configured extracted-rectangle count was exceeded.
594    RectangleLimitExceeded {
595        /// Configured maximum resolved rectangle count.
596        limit: usize,
597    },
598    /// The configured enabled line-source count was exceeded.
599    LineLimitExceeded {
600        /// Configured maximum line-source count.
601        limit: usize,
602    },
603    /// The configured enabled screen-rectangle count was exceeded.
604    ScreenRectangleLimitExceeded {
605        /// Maximum number of screen rectangles accepted in one extraction.
606        limit: usize,
607    },
608    /// The opted-in enabled screen-image source count was exceeded.
609    ScreenImageLimitExceeded {
610        /// Configured image source limit (zero by default).
611        limit: usize,
612    },
613    /// The opted-in enabled screen-text source count was exceeded.
614    #[cfg(feature = "headless-text")]
615    ScreenTextLimitExceeded {
616        /// Configured label count limit, zero by default.
617        limit: usize,
618    },
619    /// Aggregate enabled label strings exceed the UTF-8 byte allowance.
620    #[cfg(feature = "headless-text")]
621    ScreenTextBytesLimitExceeded {
622        /// Configured inclusive UTF-8 byte limit.
623        limit: usize,
624        /// Requested aggregate bytes; usize::MAX also represents overflow.
625        requested: usize,
626    },
627    /// Aggregate enabled labels exceed the shaped-glyph allowance.
628    #[cfg(feature = "headless-text")]
629    ScreenTextGlyphLimitExceeded {
630        /// Configured inclusive shaped-glyph count limit.
631        limit: usize,
632        /// Requested aggregate glyphs; usize::MAX also represents overflow.
633        requested: usize,
634    },
635    /// A label uses a font not registered by this Application.
636    #[cfg(feature = "headless-text")]
637    UnregisteredTextFont {
638        /// Managed source of the foreign or unavailable font.
639        entity: LogicEntity,
640        /// Shared immutable font whose Application provenance was rejected.
641        font: crate::text::TextFont,
642    },
643    /// A label violated its prepared-text, position, or tint contract.
644    #[cfg(feature = "headless-text")]
645    InvalidScreenText {
646        /// Managed source whose text visual was rejected.
647        entity: LogicEntity,
648        /// Exact component validation failure.
649        error: crate::text::TextError,
650    },
651    /// An image handle was not registered by this Application.
652    UnregisteredImageAsset {
653        /// Managed source of the invalid reference.
654        entity: LogicEntity,
655        /// Rejected immutable image handle.
656        image: ImageAssetId,
657    },
658    /// An image component violated its geometry, tint, or source-region contract.
659    InvalidScreenImage {
660        /// Managed source whose visual was rejected.
661        entity: LogicEntity,
662        /// Exact component validation failure.
663        error: ImageVisualError,
664    },
665    /// A screen visual violated its validated logical-pixel contract.
666    InvalidScreenVisual {
667        /// Managed entity whose screen visual was rejected.
668        entity: LogicEntity,
669        /// Exact invalid value category.
670        error: ScreenVisualError,
671    },
672    /// CPU storage for a bounded fixed-size resolved record could not be reserved.
673    AllocationFailed {
674        /// Minimum bytes requested for the next fixed-size record.
675        requested_bytes: usize,
676    },
677    /// Sim;Engine rejected bounded scene construction.
678    Scene(SceneError),
679    /// Sim;Engine rejected bounded screen-scene construction.
680    ScreenScene(SceneError),
681}
682
683impl fmt::Display for ExtractionError {
684    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
685        match self {
686            Self::MissingStagedFrame => formatter.write_str("no staged CPU frame is available"),
687            Self::ThreeD(error) => write!(formatter, "3D extraction failed: {error}"),
688            Self::MissingActiveCamera => formatter.write_str("active World has no 2D camera"),
689            Self::MultipleActiveCameras => {
690                formatter.write_str("active World has more than one 2D camera")
691            }
692            Self::InvalidInterpolationAlpha { alpha } => write!(
693                formatter,
694                "interpolation alpha must be finite and within 0..=1, got {alpha}"
695            ),
696            Self::ForeignEntity { entity, expected } => write!(
697                formatter,
698                "visual entity {entity:?} does not belong to World generation {expected:?}"
699            ),
700            Self::InvalidVisual { entity, error } => {
701                write!(formatter, "visual entity {entity:?} is invalid: {error}")
702            }
703            Self::InvalidInterpolatedTranslation { entity } => write!(
704                formatter,
705                "visual entity {entity:?} produced a non-finite interpolated translation"
706            ),
707            Self::InvalidResolvedRectangle { entity } => write!(
708                formatter,
709                "visual entity {entity:?} produced collapsed or non-finite rectangle bounds"
710            ),
711            Self::InvalidResolvedLine { entity } => write!(
712                formatter,
713                "visual entity {entity:?} produced a collapsed or non-finite line"
714            ),
715            Self::CircleLimitExceeded { limit } => {
716                write!(
717                    formatter,
718                    "extracted circle count exceeds the limit of {limit}"
719                )
720            }
721            Self::RectangleLimitExceeded { limit } => write!(
722                formatter,
723                "extracted rectangle count exceeds the limit of {limit}"
724            ),
725            Self::LineLimitExceeded { limit } => write!(
726                formatter,
727                "enabled line-source count exceeds the limit of {limit}"
728            ),
729            Self::ScreenRectangleLimitExceeded { limit } => write!(
730                formatter,
731                "extracted screen rectangle count exceeds the limit of {limit}"
732            ),
733            Self::ScreenPolylinePointsLimitExceeded {
734                entity,
735                limit,
736                requested,
737            } => write!(
738                formatter,
739                "screen path {entity:?} exceeds point limit {limit}, requested {requested}"
740            ),
741            Self::ScreenPrimitiveLimitExceeded { entity, limit } => write!(
742                formatter,
743                "screen primitive {entity:?} exceeds its source limit {limit}"
744            ),
745            Self::ScreenImageLimitExceeded { limit } => write!(
746                formatter,
747                "extracted screen image count exceeds the limit of {limit}"
748            ),
749            #[cfg(feature = "headless-text")]
750            Self::ScreenTextLimitExceeded { limit } => write!(
751                formatter,
752                "extracted screen text count exceeds the limit of {limit}"
753            ),
754            #[cfg(feature = "headless-text")]
755            Self::ScreenTextBytesLimitExceeded { limit, requested } => write!(
756                formatter,
757                "screen text requests {requested} UTF-8 bytes, exceeding {limit}"
758            ),
759            #[cfg(feature = "headless-text")]
760            Self::ScreenTextGlyphLimitExceeded { limit, requested } => write!(
761                formatter,
762                "screen text requests {requested} shaped glyphs, exceeding {limit}"
763            ),
764            #[cfg(feature = "headless-text")]
765            Self::UnregisteredTextFont { entity, font } => write!(
766                formatter,
767                "screen text entity {entity:?} references unregistered font {font:?}"
768            ),
769            #[cfg(feature = "headless-text")]
770            Self::InvalidScreenText { entity, error } => write!(
771                formatter,
772                "screen text entity {entity:?} is invalid: {error}"
773            ),
774            Self::UnregisteredImageAsset { entity, image } => write!(
775                formatter,
776                "screen image entity {entity:?} references unregistered image {image:?}"
777            ),
778            Self::InvalidScreenImage { entity, error } => write!(
779                formatter,
780                "screen image entity {entity:?} is invalid: {error}"
781            ),
782            Self::InvalidScreenVisual { entity, error } => write!(
783                formatter,
784                "screen visual entity {entity:?} is invalid: {error}"
785            ),
786            Self::AllocationFailed { requested_bytes } => write!(
787                formatter,
788                "failed to reserve {requested_bytes} bytes for an extracted visual record"
789            ),
790            Self::Scene(error) => write!(formatter, "Sim;Engine scene extraction failed: {error}"),
791            Self::ScreenScene(error) => {
792                write!(formatter, "Sim;Engine screen extraction failed: {error}")
793            }
794        }
795    }
796}
797
798impl Error for ExtractionError {
799    fn source(&self) -> Option<&(dyn Error + 'static)> {
800        match self {
801            Self::ThreeD(error) => Some(error),
802            Self::InvalidVisual { error, .. } => Some(error),
803            Self::Scene(error) => Some(error),
804            Self::ScreenScene(error) => Some(error),
805            Self::InvalidScreenVisual { error, .. } => Some(error),
806            Self::InvalidScreenImage { error, .. } => Some(error),
807            #[cfg(feature = "headless-text")]
808            Self::InvalidScreenText { error, .. } => Some(error),
809            _ => None,
810        }
811    }
812}
813
814/// Copied ECS values consumed by the bounded extractor.
815///
816/// Keeping this adapter record private prevents raw Bevy identity from
817/// becoming public render API while allowing the ECS query to feed extraction
818/// without first allocating an unbounded intermediate collection.
819#[derive(Debug, Clone, Copy)]
820pub(crate) struct CircleSource {
821    entity: LogicEntity,
822    previous_translation: Vec2,
823    current_translation: Vec2,
824    radius: f32,
825    color: Color,
826    layer: Layer,
827    draw_order_depth: f32,
828}
829
830/// Copied rectangle values consumed by the bounded extractor.
831#[derive(Debug, Clone, Copy)]
832pub(crate) struct RectangleSource {
833    entity: LogicEntity,
834    previous_translation: Vec2,
835    current_translation: Vec2,
836    size: Vec2,
837    corner_radius: f32,
838    color: Color,
839    layer: Layer,
840    draw_order_depth: f32,
841}
842
843/// Copied anchored-line values consumed by the bounded extractor.
844#[derive(Debug, Clone, Copy)]
845pub(crate) struct LineSource {
846    entity: LogicEntity,
847    previous_translation: Vec2,
848    current_translation: Vec2,
849    vector: Vec2,
850    stroke_width_logical_pixels: f32,
851    color: Color,
852    layer: Layer,
853    draw_order_depth: f32,
854}
855
856impl LineSource {
857    pub(crate) fn new(entity: LogicEntity, transform: &Transform2d, visual: &LineVisual) -> Self {
858        Self {
859            entity,
860            previous_translation: transform.previous_translation(),
861            current_translation: transform.translation(),
862            vector: visual.vector(),
863            stroke_width_logical_pixels: visual.stroke_width_logical_pixels(),
864            color: visual.color(),
865            layer: visual.layer(),
866            draw_order_depth: visual.draw_order_depth(),
867        }
868    }
869}
870
871impl RectangleSource {
872    pub(crate) fn new(
873        entity: LogicEntity,
874        transform: &Transform2d,
875        visual: &RectangleVisual,
876    ) -> Self {
877        Self {
878            entity,
879            previous_translation: transform.previous_translation(),
880            current_translation: transform.translation(),
881            size: visual.size(),
882            corner_radius: visual.corner_radius(),
883            color: visual.color(),
884            layer: visual.layer(),
885            draw_order_depth: visual.draw_order_depth(),
886        }
887    }
888}
889
890impl CircleSource {
891    pub(crate) fn new(entity: LogicEntity, transform: &Transform2d, visual: &CircleVisual) -> Self {
892        Self {
893            entity,
894            previous_translation: transform.previous_translation(),
895            current_translation: transform.translation(),
896            radius: visual.radius(),
897            color: visual.color(),
898            layer: visual.layer(),
899            draw_order_depth: visual.draw_order_depth(),
900        }
901    }
902}
903
904/// Builds one complete bounded CPU visual snapshot for focused extractor tests.
905#[cfg(test)]
906pub(crate) fn extract_frame(
907    parameters: ExtractionParameters,
908    cameras: impl IntoIterator<Item = ActiveCamera2d>,
909    circles: impl IntoIterator<Item = CircleSource>,
910    rectangles: impl IntoIterator<Item = RectangleSource>,
911    lines: impl IntoIterator<Item = LineSource>,
912) -> Result<ExtractedFrame, ExtractionError> {
913    let mut storage = ExtractionBuffer::new(parameters.limits)?;
914    let metadata = extract_frame_into(
915        &mut storage,
916        parameters,
917        cameras,
918        circles,
919        rectangles,
920        lines,
921        [],
922    )?;
923    Ok(metadata.with_storage(storage))
924}
925
926fn extract_frame_into(
927    storage: &mut ExtractionBuffer,
928    parameters: ExtractionParameters,
929    cameras: impl IntoIterator<Item = ActiveCamera2d>,
930    circles: impl IntoIterator<Item = CircleSource>,
931    rectangles: impl IntoIterator<Item = RectangleSource>,
932    lines: impl IntoIterator<Item = LineSource>,
933    screen_rectangles: impl IntoIterator<Item = ScreenSource>,
934) -> Result<ExtractedMetadata, ExtractionError> {
935    let ExtractionParameters {
936        world_generation,
937        background,
938        alpha,
939        limits,
940    } = parameters;
941    debug_assert_eq!(
942        storage.world_scene.budget(),
943        Some(limits.world_scene_budget()),
944        "an extraction buffer cannot cross a frozen render-limit boundary"
945    );
946    storage.resolved_circles.clear();
947    storage.resolved_rectangles.clear();
948    storage.resolved_lines.clear();
949    storage.world_scene.clear();
950    storage.three_d.clear();
951
952    if !alpha.is_finite() || !(0.0..=1.0).contains(&alpha) {
953        return Err(ExtractionError::InvalidInterpolationAlpha { alpha });
954    }
955
956    let mut cameras = cameras.into_iter();
957    let camera = cameras.next().ok_or(ExtractionError::MissingActiveCamera)?;
958    if cameras.next().is_some() {
959        return Err(ExtractionError::MultipleActiveCameras);
960    }
961    let camera = camera.interpolated_camera(alpha);
962
963    for source in circles {
964        if source.entity.world_generation() != world_generation {
965            return Err(ExtractionError::ForeignEntity {
966                entity: source.entity,
967                expected: world_generation,
968            });
969        }
970        if storage.resolved_circles.len() == limits.max_world_circles() {
971            return Err(ExtractionError::CircleLimitExceeded {
972                limit: limits.max_world_circles(),
973            });
974        }
975        validate_aggregate_command_capacity(storage.resolved_circles.len(), limits)?;
976
977        validate_source(source)?;
978        let position = source
979            .previous_translation
980            .lerp(source.current_translation, alpha);
981        if !position.is_finite() {
982            return Err(ExtractionError::InvalidInterpolatedTranslation {
983                entity: source.entity,
984            });
985        }
986
987        storage
988            .resolved_circles
989            .try_reserve(1)
990            .map_err(|_| ExtractionError::AllocationFailed {
991                requested_bytes: size_of::<ResolvedCircle>(),
992            })?;
993        storage.resolved_circles.push(ResolvedCircle {
994            source: source.entity,
995            position,
996            radius: source.radius,
997            color: source.color,
998            layer: source.layer,
999            draw_order_depth: source.draw_order_depth,
1000        });
1001    }
1002
1003    for source in rectangles {
1004        if source.entity.world_generation() != world_generation {
1005            return Err(ExtractionError::ForeignEntity {
1006                entity: source.entity,
1007                expected: world_generation,
1008            });
1009        }
1010        if storage.resolved_rectangles.len() == limits.max_world_rectangles() {
1011            return Err(ExtractionError::RectangleLimitExceeded {
1012                limit: limits.max_world_rectangles(),
1013            });
1014        }
1015        validate_aggregate_command_capacity(
1016            storage
1017                .resolved_circles
1018                .len()
1019                .saturating_add(storage.resolved_rectangles.len()),
1020            limits,
1021        )?;
1022
1023        validate_rectangle_source(source)?;
1024        let position = source
1025            .previous_translation
1026            .lerp(source.current_translation, alpha);
1027        if !position.is_finite() {
1028            return Err(ExtractionError::InvalidInterpolatedTranslation {
1029                entity: source.entity,
1030            });
1031        }
1032        let bounds = Rect::from_center_size(position, source.size);
1033        if !rectangle_bounds_are_representable(bounds) {
1034            return Err(ExtractionError::InvalidResolvedRectangle {
1035                entity: source.entity,
1036            });
1037        }
1038
1039        storage.resolved_rectangles.try_reserve(1).map_err(|_| {
1040            ExtractionError::AllocationFailed {
1041                requested_bytes: size_of::<ResolvedRectangle>(),
1042            }
1043        })?;
1044        storage.resolved_rectangles.push(ResolvedRectangle {
1045            source: source.entity,
1046            position,
1047            size: source.size,
1048            corner_radius: source.corner_radius,
1049            color: source.color,
1050            layer: source.layer,
1051            draw_order_depth: source.draw_order_depth,
1052        });
1053    }
1054
1055    let mut line_sources_seen = 0usize;
1056    for source in lines {
1057        if source.entity.world_generation() != world_generation {
1058            return Err(ExtractionError::ForeignEntity {
1059                entity: source.entity,
1060                expected: world_generation,
1061            });
1062        }
1063        if line_sources_seen == limits.max_world_lines() {
1064            return Err(ExtractionError::LineLimitExceeded {
1065                limit: limits.max_world_lines(),
1066            });
1067        }
1068        line_sources_seen = line_sources_seen.saturating_add(1);
1069
1070        validate_line_source(source)?;
1071        if source.vector.x() == 0.0 && source.vector.y() == 0.0 {
1072            continue;
1073        }
1074        validate_aggregate_command_capacity(
1075            storage
1076                .resolved_circles
1077                .len()
1078                .saturating_add(storage.resolved_rectangles.len())
1079                .saturating_add(storage.resolved_lines.len()),
1080            limits,
1081        )?;
1082
1083        let from = source
1084            .previous_translation
1085            .lerp(source.current_translation, alpha);
1086        if !from.is_finite() {
1087            return Err(ExtractionError::InvalidInterpolatedTranslation {
1088                entity: source.entity,
1089            });
1090        }
1091        let to = from + source.vector;
1092        let delta = to - from;
1093        if !to.is_finite() || !delta.is_finite() || (delta.x() == 0.0 && delta.y() == 0.0) {
1094            return Err(ExtractionError::InvalidResolvedLine {
1095                entity: source.entity,
1096            });
1097        }
1098
1099        storage
1100            .resolved_lines
1101            .try_reserve(1)
1102            .map_err(|_| ExtractionError::AllocationFailed {
1103                requested_bytes: size_of::<ResolvedLine>(),
1104            })?;
1105        storage.resolved_lines.push(ResolvedLine {
1106            source: source.entity,
1107            from,
1108            to,
1109            stroke_width_logical_pixels: source.stroke_width_logical_pixels,
1110            color: source.color,
1111            layer: source.layer,
1112            draw_order_depth: source.draw_order_depth,
1113        });
1114    }
1115
1116    storage.resolved_circles.sort_unstable_by(|left, right| {
1117        compare_visual_order(
1118            left.layer,
1119            left.draw_order_depth,
1120            left.source,
1121            right.layer,
1122            right.draw_order_depth,
1123            right.source,
1124        )
1125    });
1126    storage.resolved_rectangles.sort_unstable_by(|left, right| {
1127        compare_visual_order(
1128            left.layer,
1129            left.draw_order_depth,
1130            left.source,
1131            right.layer,
1132            right.draw_order_depth,
1133            right.source,
1134        )
1135    });
1136    storage.resolved_lines.sort_unstable_by(|left, right| {
1137        compare_visual_order(
1138            left.layer,
1139            left.draw_order_depth,
1140            left.source,
1141            right.layer,
1142            right.draw_order_depth,
1143            right.source,
1144        )
1145    });
1146
1147    storage
1148        .world_scene
1149        .set_background(background)
1150        .map_err(ExtractionError::Scene)?;
1151    populate_scene(
1152        &mut storage.world_scene,
1153        &storage.resolved_circles,
1154        &storage.resolved_rectangles,
1155        &storage.resolved_lines,
1156    )?;
1157    storage
1158        .screen
1159        .extract(world_generation, limits, screen_rectangles)?;
1160
1161    Ok(ExtractedMetadata {
1162        world_generation,
1163        background,
1164        camera,
1165    })
1166}
1167
1168fn validate_aggregate_command_capacity(
1169    retained_visuals: usize,
1170    limits: RenderLimits,
1171) -> Result<(), ExtractionError> {
1172    let limit = limits.world_scene_budget().max_commands();
1173    if retained_visuals == limit {
1174        return Err(ExtractionError::Scene(SceneError::BudgetExceeded {
1175            resource: SceneBudgetResource::Commands,
1176            limit,
1177            requested: retained_visuals.saturating_add(1),
1178        }));
1179    }
1180    Ok(())
1181}
1182
1183fn rectangle_bounds_are_representable(bounds: Rect) -> bool {
1184    bounds.min().is_finite()
1185        && bounds.max().is_finite()
1186        && bounds.width().is_finite()
1187        && bounds.height().is_finite()
1188        && bounds.width() > 0.0
1189        && bounds.height() > 0.0
1190}
1191
1192fn compare_visual_order(
1193    left_layer: Layer,
1194    left_depth: f32,
1195    left_entity: LogicEntity,
1196    right_layer: Layer,
1197    right_depth: f32,
1198    right_entity: LogicEntity,
1199) -> Ordering {
1200    left_layer
1201        .cmp(&right_layer)
1202        .then_with(|| {
1203            if left_depth == right_depth {
1204                Ordering::Equal
1205            } else {
1206                left_depth.total_cmp(&right_depth)
1207            }
1208        })
1209        .then_with(|| left_entity.stable_bits().cmp(&right_entity.stable_bits()))
1210}
1211
1212fn populate_scene(
1213    scene: &mut Scene,
1214    circles: &[ResolvedCircle],
1215    rectangles: &[ResolvedRectangle],
1216    lines: &[ResolvedLine],
1217) -> Result<(), ExtractionError> {
1218    if lines.is_empty() && rectangles.is_empty() {
1219        for circle in circles {
1220            push_circle(scene, circle)?;
1221        }
1222        return Ok(());
1223    }
1224    if lines.is_empty() && circles.is_empty() {
1225        for rectangle in rectangles {
1226            push_rectangle(scene, rectangle)?;
1227        }
1228        return Ok(());
1229    }
1230    if lines.is_empty() {
1231        let mut circle_index = 0;
1232        let mut rectangle_index = 0;
1233        while circle_index < circles.len() && rectangle_index < rectangles.len() {
1234            let circle = &circles[circle_index];
1235            let rectangle = &rectangles[rectangle_index];
1236            let order = compare_visual_order(
1237                rectangle.layer,
1238                rectangle.draw_order_depth,
1239                rectangle.source,
1240                circle.layer,
1241                circle.draw_order_depth,
1242                circle.source,
1243            );
1244            if order != Ordering::Greater {
1245                // Rectangle has the lower primitive rank for an otherwise exact tie.
1246                push_rectangle(scene, rectangle)?;
1247                rectangle_index += 1;
1248            } else {
1249                push_circle(scene, circle)?;
1250                circle_index += 1;
1251            }
1252        }
1253        for circle in &circles[circle_index..] {
1254            push_circle(scene, circle)?;
1255        }
1256        for rectangle in &rectangles[rectangle_index..] {
1257            push_rectangle(scene, rectangle)?;
1258        }
1259        return Ok(());
1260    }
1261    if circles.is_empty() && rectangles.is_empty() {
1262        for line in lines {
1263            push_line(scene, line)?;
1264        }
1265        return Ok(());
1266    }
1267
1268    #[derive(Clone, Copy)]
1269    enum VisualKind {
1270        Rectangle,
1271        Circle,
1272        Line,
1273    }
1274
1275    let mut circle_index = 0;
1276    let mut rectangle_index = 0;
1277    let mut line_index = 0;
1278    while circle_index < circles.len()
1279        || rectangle_index < rectangles.len()
1280        || line_index < lines.len()
1281    {
1282        let next = [
1283            rectangles.get(rectangle_index).map(|visual| {
1284                (
1285                    VisualKind::Rectangle,
1286                    visual.layer,
1287                    visual.draw_order_depth,
1288                    visual.source,
1289                    0_u8,
1290                )
1291            }),
1292            circles.get(circle_index).map(|visual| {
1293                (
1294                    VisualKind::Circle,
1295                    visual.layer,
1296                    visual.draw_order_depth,
1297                    visual.source,
1298                    1_u8,
1299                )
1300            }),
1301            lines.get(line_index).map(|visual| {
1302                (
1303                    VisualKind::Line,
1304                    visual.layer,
1305                    visual.draw_order_depth,
1306                    visual.source,
1307                    2_u8,
1308                )
1309            }),
1310        ]
1311        .into_iter()
1312        .flatten()
1313        .min_by(|left, right| {
1314            compare_visual_order(left.1, left.2, left.3, right.1, right.2, right.3)
1315                .then_with(|| left.4.cmp(&right.4))
1316        });
1317        let Some(next) = next else {
1318            break;
1319        };
1320
1321        match next.0 {
1322            VisualKind::Rectangle => {
1323                push_rectangle(scene, &rectangles[rectangle_index])?;
1324                rectangle_index += 1;
1325            }
1326            VisualKind::Circle => {
1327                push_circle(scene, &circles[circle_index])?;
1328                circle_index += 1;
1329            }
1330            VisualKind::Line => {
1331                push_line(scene, &lines[line_index])?;
1332                line_index += 1;
1333            }
1334        }
1335    }
1336    Ok(())
1337}
1338
1339fn push_circle(scene: &mut Scene, circle: &ResolvedCircle) -> Result<(), ExtractionError> {
1340    scene
1341        .try_circle_on_layer(
1342            circle.layer,
1343            circle.position,
1344            circle.radius,
1345            ShapeStyle::filled(circle.color),
1346        )
1347        .map_err(ExtractionError::Scene)
1348}
1349
1350fn push_rectangle(scene: &mut Scene, rectangle: &ResolvedRectangle) -> Result<(), ExtractionError> {
1351    scene
1352        .try_rect_on_layer(
1353            rectangle.layer,
1354            Rect::from_center_size(rectangle.position, rectangle.size),
1355            rectangle.corner_radius,
1356            ShapeStyle::filled(rectangle.color),
1357        )
1358        .map_err(ExtractionError::Scene)
1359}
1360
1361fn push_line(scene: &mut Scene, line: &ResolvedLine) -> Result<(), ExtractionError> {
1362    scene
1363        .try_styled_line_on_layer(
1364            line.layer,
1365            line.from,
1366            line.to,
1367            line_stroke_style(line.stroke_width_logical_pixels, line.color),
1368        )
1369        .map_err(ExtractionError::Scene)
1370}
1371
1372fn validate_source(source: CircleSource) -> Result<(), ExtractionError> {
1373    crate::visual::validate_translation(source.previous_translation).map_err(|error| {
1374        ExtractionError::InvalidVisual {
1375            entity: source.entity,
1376            error,
1377        }
1378    })?;
1379    crate::visual::validate_translation(source.current_translation).map_err(|error| {
1380        ExtractionError::InvalidVisual {
1381            entity: source.entity,
1382            error,
1383        }
1384    })?;
1385    crate::visual::validate_radius(source.radius).map_err(|error| {
1386        ExtractionError::InvalidVisual {
1387            entity: source.entity,
1388            error,
1389        }
1390    })?;
1391    crate::visual::validate_color(source.color).map_err(|error| {
1392        ExtractionError::InvalidVisual {
1393            entity: source.entity,
1394            error,
1395        }
1396    })?;
1397    crate::visual::validate_draw_order_depth(source.draw_order_depth).map_err(|error| {
1398        ExtractionError::InvalidVisual {
1399            entity: source.entity,
1400            error,
1401        }
1402    })?;
1403    Ok(())
1404}
1405
1406fn validate_rectangle_source(source: RectangleSource) -> Result<(), ExtractionError> {
1407    crate::visual::validate_translation(source.previous_translation).map_err(|error| {
1408        ExtractionError::InvalidVisual {
1409            entity: source.entity,
1410            error,
1411        }
1412    })?;
1413    crate::visual::validate_translation(source.current_translation).map_err(|error| {
1414        ExtractionError::InvalidVisual {
1415            entity: source.entity,
1416            error,
1417        }
1418    })?;
1419    crate::visual::validate_size(source.size).map_err(|error| ExtractionError::InvalidVisual {
1420        entity: source.entity,
1421        error,
1422    })?;
1423    crate::visual::validate_corner_radius(source.corner_radius).map_err(|error| {
1424        ExtractionError::InvalidVisual {
1425            entity: source.entity,
1426            error,
1427        }
1428    })?;
1429    crate::visual::validate_color(source.color).map_err(|error| {
1430        ExtractionError::InvalidVisual {
1431            entity: source.entity,
1432            error,
1433        }
1434    })?;
1435    crate::visual::validate_draw_order_depth(source.draw_order_depth).map_err(|error| {
1436        ExtractionError::InvalidVisual {
1437            entity: source.entity,
1438            error,
1439        }
1440    })?;
1441    Ok(())
1442}
1443
1444fn validate_line_source(source: LineSource) -> Result<(), ExtractionError> {
1445    crate::visual::validate_translation(source.previous_translation).map_err(|error| {
1446        ExtractionError::InvalidVisual {
1447            entity: source.entity,
1448            error,
1449        }
1450    })?;
1451    crate::visual::validate_translation(source.current_translation).map_err(|error| {
1452        ExtractionError::InvalidVisual {
1453            entity: source.entity,
1454            error,
1455        }
1456    })?;
1457    crate::visual::validate_line_vector(source.vector).map_err(|error| {
1458        ExtractionError::InvalidVisual {
1459            entity: source.entity,
1460            error,
1461        }
1462    })?;
1463    crate::visual::validate_line_width(source.stroke_width_logical_pixels).map_err(|error| {
1464        ExtractionError::InvalidVisual {
1465            entity: source.entity,
1466            error,
1467        }
1468    })?;
1469    crate::visual::validate_color(source.color).map_err(|error| {
1470        ExtractionError::InvalidVisual {
1471            entity: source.entity,
1472            error,
1473        }
1474    })?;
1475    crate::visual::validate_draw_order_depth(source.draw_order_depth).map_err(|error| {
1476        ExtractionError::InvalidVisual {
1477            entity: source.entity,
1478            error,
1479        }
1480    })?;
1481    Ok(())
1482}
1483
1484#[cfg(test)]
1485mod tests {
1486    use super::*;
1487    use crate::{identity::ApplicationId, render::DEFAULT_WORLD_SCENE_BUDGET};
1488    use bevy_ecs::world::World;
1489    use sim_engine::{DrawCommand, StrokeCap2d, StrokeWidthMode2d};
1490
1491    fn generation(sequence: u64) -> WorldGeneration {
1492        WorldGeneration::new(ApplicationId::from_raw(1), sequence)
1493    }
1494
1495    fn entity(world: &mut World, generation: WorldGeneration) -> LogicEntity {
1496        let raw = world.spawn_empty().id();
1497        LogicEntity::new(ApplicationId::from_raw(1), generation, raw)
1498    }
1499
1500    fn camera() -> Result<ActiveCamera2d, sim_engine::Camera2dError> {
1501        Camera2d::new(Vec2::ZERO, 32.0).map(ActiveCamera2d::new)
1502    }
1503
1504    fn source(
1505        entity: LogicEntity,
1506        previous: Vec2,
1507        current: Vec2,
1508        layer: i32,
1509        depth: f32,
1510    ) -> CircleSource {
1511        CircleSource {
1512            entity,
1513            previous_translation: previous,
1514            current_translation: current,
1515            radius: 2.0,
1516            color: Color::WHITE,
1517            layer: Layer::new(layer),
1518            draw_order_depth: depth,
1519        }
1520    }
1521
1522    fn rectangle_source(
1523        entity: LogicEntity,
1524        previous: Vec2,
1525        current: Vec2,
1526        size: Vec2,
1527        layer: i32,
1528        depth: f32,
1529    ) -> RectangleSource {
1530        RectangleSource {
1531            entity,
1532            previous_translation: previous,
1533            current_translation: current,
1534            size,
1535            corner_radius: 0.25,
1536            color: Color::WHITE,
1537            layer: Layer::new(layer),
1538            draw_order_depth: depth,
1539        }
1540    }
1541
1542    fn line_source(
1543        entity: LogicEntity,
1544        previous: Vec2,
1545        current: Vec2,
1546        vector: Vec2,
1547        layer: i32,
1548        depth: f32,
1549    ) -> LineSource {
1550        LineSource {
1551            entity,
1552            previous_translation: previous,
1553            current_translation: current,
1554            vector,
1555            stroke_width_logical_pixels: 2.5,
1556            color: Color::rgb8(255, 160, 40),
1557            layer: Layer::new(layer),
1558            draw_order_depth: depth,
1559        }
1560    }
1561
1562    #[test]
1563    fn interpolation_covers_zero_middle_and_just_below_one() -> Result<(), Box<dyn Error>> {
1564        let generation = generation(1);
1565        let mut world = World::new();
1566        let entity = entity(&mut world, generation);
1567        let previous = Vec2::new(0.0, 4.0);
1568        let current = Vec2::new(8.0, 12.0);
1569        let just_below_one = f32::from_bits(1.0_f32.to_bits() - 1);
1570
1571        for (alpha, expected) in [
1572            (0.0, previous),
1573            (0.5, Vec2::new(4.0, 8.0)),
1574            (just_below_one, previous.lerp(current, just_below_one)),
1575        ] {
1576            let frame = extract_frame(
1577                ExtractionParameters::new(generation, Color::BLACK, alpha, RenderLimits::default()),
1578                [camera()?],
1579                [source(entity, previous, current, 0, 0.0)],
1580                [],
1581                [],
1582            )?;
1583
1584            assert_eq!(frame.resolved_circles()[0].position(), expected);
1585            assert_eq!(frame.world_scene().command_count(), 1);
1586        }
1587        Ok(())
1588    }
1589
1590    #[test]
1591    fn rectangle_interpolation_and_scene_bounds_match() -> Result<(), Box<dyn Error>> {
1592        let generation = generation(1);
1593        let mut world = World::new();
1594        let entity = entity(&mut world, generation);
1595        let previous = Vec2::new(-4.0, 2.0);
1596        let current = Vec2::new(8.0, 6.0);
1597        let size = Vec2::new(6.0, 2.0);
1598
1599        for (alpha, expected) in [(0.0, previous), (0.5, Vec2::new(2.0, 4.0)), (1.0, current)] {
1600            let frame = extract_frame(
1601                ExtractionParameters::new(generation, Color::BLACK, alpha, RenderLimits::default()),
1602                [camera()?],
1603                [],
1604                [rectangle_source(entity, previous, current, size, 0, 0.0)],
1605                [],
1606            )?;
1607            let [resolved] = frame.resolved_rectangles() else {
1608                return Err("expected one resolved rectangle".into());
1609            };
1610            assert_eq!(resolved.position(), expected);
1611            assert_eq!(resolved.size(), size);
1612            assert_eq!(resolved.corner_radius(), 0.25);
1613
1614            let [command] = frame.world_scene().commands() else {
1615                return Err("expected one rectangle command".into());
1616            };
1617            let DrawCommand::Rect(rectangle) = command.command() else {
1618                return Err("resolved rectangle produced another command kind".into());
1619            };
1620            assert_eq!(rectangle.rect().min(), expected - size * 0.5);
1621            assert_eq!(rectangle.rect().max(), expected + size * 0.5);
1622            assert_eq!(rectangle.corner_radius(), 0.25);
1623        }
1624        Ok(())
1625    }
1626
1627    #[test]
1628    fn line_interpolates_only_its_anchor_and_uses_an_exact_butt_stroke()
1629    -> Result<(), Box<dyn Error>> {
1630        let generation = generation(1);
1631        let mut world = World::new();
1632        let entity = entity(&mut world, generation);
1633        let previous = Vec2::new(-4.0, 2.0);
1634        let current = Vec2::new(8.0, 6.0);
1635        let vector = Vec2::new(3.0, -1.0);
1636        let color = Color::rgb8(255, 160, 40);
1637
1638        let frame = extract_frame(
1639            ExtractionParameters::new(generation, Color::BLACK, 0.5, RenderLimits::default()),
1640            [camera()?],
1641            [],
1642            [],
1643            [line_source(entity, previous, current, vector, 4, -2.0)],
1644        )?;
1645        let [resolved] = frame.resolved_lines() else {
1646            return Err("expected one resolved line".into());
1647        };
1648        assert_eq!(resolved.source(), entity);
1649        assert_eq!(resolved.from(), Vec2::new(2.0, 4.0));
1650        assert_eq!(resolved.to(), Vec2::new(5.0, 3.0));
1651        assert_eq!(resolved.stroke_width_logical_pixels(), 2.5);
1652        assert_eq!(resolved.color(), color);
1653        assert_eq!(resolved.layer(), Layer::new(4));
1654        assert_eq!(resolved.draw_order_depth(), -2.0);
1655
1656        let [command] = frame.world_scene().commands() else {
1657            return Err("expected one line command".into());
1658        };
1659        assert_eq!(command.layer(), Layer::new(4));
1660        let DrawCommand::Line(line) = command.command() else {
1661            return Err("resolved line produced another command kind".into());
1662        };
1663        assert_eq!(line.from(), resolved.from());
1664        assert_eq!(line.to(), resolved.to());
1665        assert_eq!(line.stroke().width(), 2.5);
1666        assert_eq!(line.stroke().color(), color);
1667        assert_eq!(
1668            line.stroke_style().width_mode(),
1669            StrokeWidthMode2d::LogicalPixels
1670        );
1671        assert_eq!(line.stroke_style().cap(), StrokeCap2d::Butt);
1672        assert_eq!(line.stroke_style().start_marker(), None);
1673        assert_eq!(line.stroke_style().end_marker(), None);
1674        Ok(())
1675    }
1676
1677    #[test]
1678    fn zero_lines_are_omitted_but_still_count_toward_the_source_limit() -> Result<(), Box<dyn Error>>
1679    {
1680        let generation = generation(1);
1681        let mut world = World::new();
1682        let first = entity(&mut world, generation);
1683        let second = entity(&mut world, generation);
1684        let limits = RenderLimits::default().with_max_world_lines(1);
1685
1686        let frame = extract_frame(
1687            ExtractionParameters::new(generation, Color::BLACK, 0.0, limits),
1688            [camera()?],
1689            [],
1690            [],
1691            [line_source(
1692                first,
1693                Vec2::ZERO,
1694                Vec2::ZERO,
1695                Vec2::ZERO,
1696                0,
1697                0.0,
1698            )],
1699        )?;
1700        assert!(frame.resolved_lines().is_empty());
1701        assert_eq!(frame.world_scene().command_count(), 0);
1702
1703        let result = extract_frame(
1704            ExtractionParameters::new(generation, Color::BLACK, 0.0, limits),
1705            [camera()?],
1706            [],
1707            [],
1708            [
1709                line_source(first, Vec2::ZERO, Vec2::ZERO, Vec2::ZERO, 0, 0.0),
1710                line_source(second, Vec2::ZERO, Vec2::ZERO, Vec2::ZERO, 0, 0.0),
1711            ],
1712        );
1713        assert!(matches!(
1714            result,
1715            Err(ExtractionError::LineLimitExceeded { limit: 1 })
1716        ));
1717        Ok(())
1718    }
1719
1720    #[test]
1721    fn line_resolution_keeps_representable_subnormal_and_maximum_vectors()
1722    -> Result<(), Box<dyn Error>> {
1723        let generation = generation(1);
1724        let mut world = World::new();
1725        let entity = entity(&mut world, generation);
1726
1727        for vector in [Vec2::new(f32::from_bits(1), 0.0), Vec2::new(f32::MAX, 0.0)] {
1728            let frame = extract_frame(
1729                ExtractionParameters::new(generation, Color::BLACK, 0.0, RenderLimits::default()),
1730                [camera()?],
1731                [],
1732                [],
1733                [line_source(entity, Vec2::ZERO, Vec2::ZERO, vector, 0, 0.0)],
1734            )?;
1735            let [line] = frame.resolved_lines() else {
1736                return Err("representable nonzero vector should resolve".into());
1737            };
1738            assert_eq!(line.from(), Vec2::ZERO);
1739            assert_eq!(line.to().x().to_bits(), vector.x().to_bits());
1740            assert_eq!(line.to().y().to_bits(), vector.y().to_bits());
1741        }
1742        Ok(())
1743    }
1744
1745    #[test]
1746    fn camera_center_uses_the_same_interpolation_alpha() -> Result<(), Box<dyn Error>> {
1747        let generation = generation(1);
1748        let previous = Vec2::new(-4.0, 2.0);
1749        let current = Vec2::new(8.0, 6.0);
1750        let mut configured = Camera2d::new(previous, 24.0)?;
1751        configured.set_rotation(0.75)?;
1752        configured.set_projection(sim_engine::Projection2d::new(0.25, 2.0)?);
1753        let mut camera = ActiveCamera2d::new(configured);
1754        camera.set_center(current)?;
1755
1756        for (alpha, expected) in [(0.0, previous), (0.5, Vec2::new(2.0, 4.0)), (1.0, current)] {
1757            let frame = extract_frame(
1758                ExtractionParameters::new(generation, Color::BLACK, alpha, RenderLimits::default()),
1759                [camera],
1760                [],
1761                [],
1762                [],
1763            )?;
1764
1765            assert_eq!(frame.camera().center(), expected);
1766            assert_eq!(frame.camera().zoom(), 24.0);
1767            assert_eq!(frame.camera().rotation(), 0.75);
1768            assert_eq!(
1769                frame.camera().projection(),
1770                sim_engine::Projection2d::new(0.25, 2.0)?
1771            );
1772            assert_eq!(camera.center(), current);
1773            assert_eq!(camera.previous_center(), previous);
1774        }
1775        Ok(())
1776    }
1777
1778    #[test]
1779    fn sorting_uses_layer_then_depth_then_stable_entity() -> Result<(), Box<dyn Error>> {
1780        let generation = generation(1);
1781        let mut world = World::new();
1782        let first = entity(&mut world, generation);
1783        let second = entity(&mut world, generation);
1784        let third = entity(&mut world, generation);
1785        let frame = extract_frame(
1786            ExtractionParameters::new(generation, Color::BLACK, 0.0, RenderLimits::default()),
1787            [camera()?],
1788            [
1789                source(third, Vec2::new(3.0, 0.0), Vec2::new(3.0, 0.0), 1, 0.0),
1790                source(second, Vec2::new(2.0, 0.0), Vec2::new(2.0, 0.0), 0, 1.0),
1791                source(first, Vec2::new(1.0, 0.0), Vec2::new(1.0, 0.0), 0, 1.0),
1792            ],
1793            [],
1794            [
1795                line_source(
1796                    third,
1797                    Vec2::new(3.0, 0.0),
1798                    Vec2::new(3.0, 0.0),
1799                    Vec2::ONE,
1800                    1,
1801                    0.0,
1802                ),
1803                line_source(
1804                    second,
1805                    Vec2::new(2.0, 0.0),
1806                    Vec2::new(2.0, 0.0),
1807                    Vec2::ONE,
1808                    0,
1809                    1.0,
1810                ),
1811                line_source(
1812                    first,
1813                    Vec2::new(1.0, 0.0),
1814                    Vec2::new(1.0, 0.0),
1815                    Vec2::ONE,
1816                    0,
1817                    1.0,
1818                ),
1819            ],
1820        )?;
1821
1822        let ordered_sources: Vec<_> = frame
1823            .resolved_circles()
1824            .iter()
1825            .map(|circle| circle.source())
1826            .collect();
1827        let mut same_layer = [first, second];
1828        same_layer.sort_by_key(|entity| entity.stable_bits());
1829        let expected_sources = vec![same_layer[0], same_layer[1], third];
1830        assert_eq!(ordered_sources, expected_sources);
1831        let ordered_lines: Vec<_> = frame
1832            .resolved_lines()
1833            .iter()
1834            .map(|line| line.source())
1835            .collect();
1836        assert_eq!(ordered_lines, expected_sources);
1837
1838        let scene_centers: Vec<_> = frame
1839            .world_scene()
1840            .commands()
1841            .iter()
1842            .filter_map(|command| match command.command() {
1843                DrawCommand::Circle(circle) => Some(circle.center()),
1844                _ => None,
1845            })
1846            .collect();
1847        let expected_center = |entity: LogicEntity| {
1848            if entity == first {
1849                Vec2::new(1.0, 0.0)
1850            } else {
1851                Vec2::new(2.0, 0.0)
1852            }
1853        };
1854        assert_eq!(
1855            scene_centers,
1856            vec![
1857                expected_center(same_layer[0]),
1858                expected_center(same_layer[1]),
1859                Vec2::new(3.0, 0.0)
1860            ]
1861        );
1862        Ok(())
1863    }
1864
1865    #[test]
1866    fn mixed_scene_uses_one_total_order_with_rectangle_circle_line_on_exact_tie()
1867    -> Result<(), Box<dyn Error>> {
1868        #[derive(Debug, PartialEq)]
1869        enum Observed {
1870            Circle(Vec2),
1871            Rectangle(Vec2),
1872            Line(Vec2, Vec2),
1873        }
1874
1875        let generation = generation(1);
1876        let mut world = World::new();
1877        let tied = entity(&mut world, generation);
1878        let early = entity(&mut world, generation);
1879        let late = entity(&mut world, generation);
1880        let frame = extract_frame(
1881            ExtractionParameters::new(generation, Color::BLACK, 0.0, RenderLimits::default()),
1882            [camera()?],
1883            [
1884                source(late, Vec2::new(30.0, 0.0), Vec2::new(30.0, 0.0), 1, 0.0),
1885                source(tied, Vec2::new(20.0, 0.0), Vec2::new(20.0, 0.0), 0, 1.0),
1886            ],
1887            [
1888                rectangle_source(
1889                    tied,
1890                    Vec2::new(20.0, 0.0),
1891                    Vec2::new(20.0, 0.0),
1892                    Vec2::ONE,
1893                    0,
1894                    1.0,
1895                ),
1896                rectangle_source(
1897                    early,
1898                    Vec2::new(10.0, 0.0),
1899                    Vec2::new(10.0, 0.0),
1900                    Vec2::ONE,
1901                    0,
1902                    0.0,
1903                ),
1904            ],
1905            [line_source(
1906                tied,
1907                Vec2::new(20.0, 0.0),
1908                Vec2::new(20.0, 0.0),
1909                Vec2::new(2.0, 0.0),
1910                0,
1911                1.0,
1912            )],
1913        )?;
1914
1915        let observed: Vec<_> = frame
1916            .world_scene()
1917            .commands()
1918            .iter()
1919            .map(|command| match command.command() {
1920                DrawCommand::Circle(circle) => Observed::Circle(circle.center()),
1921                DrawCommand::Rect(rectangle) => Observed::Rectangle(rectangle.rect().center()),
1922                DrawCommand::Line(line) => Observed::Line(line.from(), line.to()),
1923                _ => unreachable!("extractor emitted an unsupported command kind"),
1924            })
1925            .collect();
1926        assert_eq!(
1927            observed,
1928            [
1929                Observed::Rectangle(Vec2::new(10.0, 0.0)),
1930                Observed::Rectangle(Vec2::new(20.0, 0.0)),
1931                Observed::Circle(Vec2::new(20.0, 0.0)),
1932                Observed::Line(Vec2::new(20.0, 0.0), Vec2::new(22.0, 0.0)),
1933                Observed::Circle(Vec2::new(30.0, 0.0)),
1934            ]
1935        );
1936
1937        for (circle_depth, rectangle_depth) in [(-0.0, 0.0), (0.0, -0.0)] {
1938            let frame = extract_frame(
1939                ExtractionParameters::new(generation, Color::BLACK, 0.0, RenderLimits::default()),
1940                [camera()?],
1941                [source(tied, Vec2::ZERO, Vec2::ZERO, 0, circle_depth)],
1942                [rectangle_source(
1943                    tied,
1944                    Vec2::ZERO,
1945                    Vec2::ZERO,
1946                    Vec2::ONE,
1947                    0,
1948                    rectangle_depth,
1949                )],
1950                [line_source(
1951                    tied,
1952                    Vec2::ZERO,
1953                    Vec2::ZERO,
1954                    Vec2::ONE,
1955                    0,
1956                    circle_depth,
1957                )],
1958            )?;
1959            let [first, second, third] = frame.world_scene().commands() else {
1960                return Err("signed-zero tie should produce three commands".into());
1961            };
1962            assert!(matches!(first.command(), DrawCommand::Rect(_)));
1963            assert!(matches!(second.command(), DrawCommand::Circle(_)));
1964            assert!(matches!(third.command(), DrawCommand::Line(_)));
1965        }
1966        Ok(())
1967    }
1968
1969    #[test]
1970    fn circle_count_is_bounded_before_an_extra_record_is_retained() -> Result<(), Box<dyn Error>> {
1971        let generation = generation(1);
1972        let mut world = World::new();
1973        let first = entity(&mut world, generation);
1974        let second = entity(&mut world, generation);
1975        let limits = RenderLimits::new(1, DEFAULT_WORLD_SCENE_BUDGET, Default::default());
1976
1977        let result = extract_frame(
1978            ExtractionParameters::new(generation, Color::BLACK, 0.0, limits),
1979            [camera()?],
1980            [
1981                source(first, Vec2::ZERO, Vec2::ZERO, 0, 0.0),
1982                source(second, Vec2::ZERO, Vec2::ZERO, 0, 0.0),
1983            ],
1984            [],
1985            [],
1986        );
1987
1988        assert!(matches!(
1989            result,
1990            Err(ExtractionError::CircleLimitExceeded { limit: 1 })
1991        ));
1992        Ok(())
1993    }
1994
1995    #[test]
1996    fn rectangle_and_aggregate_command_limits_are_distinct() -> Result<(), Box<dyn Error>> {
1997        let generation = generation(1);
1998        let mut world = World::new();
1999        let first = entity(&mut world, generation);
2000        let second = entity(&mut world, generation);
2001        let rectangle_limit = RenderLimits::default().with_max_world_rectangles(1);
2002        let rectangles = [
2003            rectangle_source(first, Vec2::ZERO, Vec2::ZERO, Vec2::ONE, 0, 0.0),
2004            rectangle_source(second, Vec2::ZERO, Vec2::ZERO, Vec2::ONE, 0, 0.0),
2005        ];
2006        let result = extract_frame(
2007            ExtractionParameters::new(generation, Color::BLACK, 0.0, rectangle_limit),
2008            [camera()?],
2009            [],
2010            rectangles,
2011            [],
2012        );
2013        assert!(matches!(
2014            result,
2015            Err(ExtractionError::RectangleLimitExceeded { limit: 1 })
2016        ));
2017
2018        let standard = DEFAULT_WORLD_SCENE_BUDGET;
2019        let one_command = sim_engine::SceneBudget::new(
2020            1,
2021            standard.max_points(),
2022            standard.max_tessellated_vertices(),
2023            standard.max_retained_bytes(),
2024            standard.max_allocation_bytes(),
2025            standard.max_upload_bytes(),
2026            standard.max_draw_batches(),
2027        );
2028        let aggregate_limits =
2029            RenderLimits::new(1, one_command, Default::default()).with_max_world_rectangles(1);
2030        let result = extract_frame(
2031            ExtractionParameters::new(generation, Color::BLACK, 0.0, aggregate_limits),
2032            [camera()?],
2033            [source(first, Vec2::ZERO, Vec2::ZERO, 0, 0.0)],
2034            [rectangle_source(
2035                second,
2036                Vec2::ZERO,
2037                Vec2::ZERO,
2038                Vec2::ONE,
2039                0,
2040                0.0,
2041            )],
2042            [],
2043        );
2044        assert!(matches!(
2045            result,
2046            Err(ExtractionError::Scene(SceneError::BudgetExceeded {
2047                resource: SceneBudgetResource::Commands,
2048                limit: 1,
2049                requested: 2,
2050            }))
2051        ));
2052        Ok(())
2053    }
2054
2055    #[test]
2056    fn line_and_aggregate_command_limits_are_distinct() -> Result<(), Box<dyn Error>> {
2057        let generation = generation(1);
2058        let mut world = World::new();
2059        let first = entity(&mut world, generation);
2060        let second = entity(&mut world, generation);
2061        let line_limit = RenderLimits::default().with_max_world_lines(1);
2062        let lines = [
2063            line_source(first, Vec2::ZERO, Vec2::ZERO, Vec2::ONE, 0, 0.0),
2064            line_source(second, Vec2::ZERO, Vec2::ZERO, Vec2::ONE, 0, 0.0),
2065        ];
2066        let result = extract_frame(
2067            ExtractionParameters::new(generation, Color::BLACK, 0.0, line_limit),
2068            [camera()?],
2069            [],
2070            [],
2071            lines,
2072        );
2073        assert!(matches!(
2074            result,
2075            Err(ExtractionError::LineLimitExceeded { limit: 1 })
2076        ));
2077
2078        let standard = DEFAULT_WORLD_SCENE_BUDGET;
2079        let one_command = sim_engine::SceneBudget::new(
2080            1,
2081            standard.max_points(),
2082            standard.max_tessellated_vertices(),
2083            standard.max_retained_bytes(),
2084            standard.max_allocation_bytes(),
2085            standard.max_upload_bytes(),
2086            standard.max_draw_batches(),
2087        );
2088        let limits = RenderLimits::new(1, one_command, Default::default()).with_max_world_lines(1);
2089        let result = extract_frame(
2090            ExtractionParameters::new(generation, Color::BLACK, 0.0, limits),
2091            [camera()?],
2092            [source(first, Vec2::ZERO, Vec2::ZERO, 0, 0.0)],
2093            [],
2094            [line_source(
2095                second,
2096                Vec2::ZERO,
2097                Vec2::ZERO,
2098                Vec2::ONE,
2099                0,
2100                0.0,
2101            )],
2102        );
2103        assert!(matches!(
2104            result,
2105            Err(ExtractionError::Scene(SceneError::BudgetExceeded {
2106                resource: SceneBudgetResource::Commands,
2107                limit: 1,
2108                requested: 2,
2109            }))
2110        ));
2111        Ok(())
2112    }
2113
2114    #[test]
2115    fn collapsed_or_overflowed_rectangle_bounds_keep_entity_attribution()
2116    -> Result<(), Box<dyn Error>> {
2117        let generation = generation(1);
2118        let mut world = World::new();
2119        let collapsed = entity(&mut world, generation);
2120        let overflowed = entity(&mut world, generation);
2121
2122        for source in [
2123            rectangle_source(
2124                collapsed,
2125                Vec2::splat(f32::MAX),
2126                Vec2::splat(f32::MAX),
2127                Vec2::ONE,
2128                0,
2129                0.0,
2130            ),
2131            rectangle_source(
2132                overflowed,
2133                Vec2::splat(f32::MAX),
2134                Vec2::splat(f32::MAX),
2135                Vec2::splat(f32::MAX),
2136                0,
2137                0.0,
2138            ),
2139        ] {
2140            let result = extract_frame(
2141                ExtractionParameters::new(generation, Color::BLACK, 0.0, RenderLimits::default()),
2142                [camera()?],
2143                [],
2144                [source],
2145                [],
2146            );
2147            assert!(matches!(
2148                result,
2149                Err(ExtractionError::InvalidResolvedRectangle { entity })
2150                    if entity == source.entity
2151            ));
2152        }
2153        Ok(())
2154    }
2155
2156    #[test]
2157    fn collapsed_or_overflowed_line_endpoints_keep_entity_attribution() -> Result<(), Box<dyn Error>>
2158    {
2159        let generation = generation(1);
2160        let mut world = World::new();
2161        let collapsed = entity(&mut world, generation);
2162        let overflowed = entity(&mut world, generation);
2163
2164        for source in [
2165            line_source(
2166                collapsed,
2167                Vec2::splat(f32::MAX),
2168                Vec2::splat(f32::MAX),
2169                Vec2::ONE,
2170                0,
2171                0.0,
2172            ),
2173            line_source(
2174                overflowed,
2175                Vec2::splat(f32::MAX),
2176                Vec2::splat(f32::MAX),
2177                Vec2::splat(f32::MAX),
2178                0,
2179                0.0,
2180            ),
2181        ] {
2182            let result = extract_frame(
2183                ExtractionParameters::new(generation, Color::BLACK, 0.0, RenderLimits::default()),
2184                [camera()?],
2185                [],
2186                [],
2187                [source],
2188            );
2189            assert!(matches!(
2190                result,
2191                Err(ExtractionError::InvalidResolvedLine { entity })
2192                    if entity == source.entity
2193            ));
2194        }
2195        Ok(())
2196    }
2197
2198    #[test]
2199    fn foreign_generation_is_rejected() -> Result<(), Box<dyn Error>> {
2200        let active = generation(1);
2201        let stale = generation(2);
2202        let mut world = World::new();
2203        let stale_entity = entity(&mut world, stale);
2204
2205        let result = extract_frame(
2206            ExtractionParameters::new(active, Color::BLACK, 0.0, RenderLimits::default()),
2207            [camera()?],
2208            [source(stale_entity, Vec2::ZERO, Vec2::ZERO, 0, 0.0)],
2209            [],
2210            [],
2211        );
2212
2213        assert!(matches!(
2214            result,
2215            Err(ExtractionError::ForeignEntity { entity, expected })
2216                if entity == stale_entity && expected == active
2217        ));
2218        Ok(())
2219    }
2220
2221    #[test]
2222    fn defensive_visual_validation_precedes_scene_publication() -> Result<(), Box<dyn Error>> {
2223        let generation = generation(1);
2224        let mut world = World::new();
2225        let entity = entity(&mut world, generation);
2226        let invalid = CircleSource {
2227            radius: f32::NAN,
2228            ..source(entity, Vec2::ZERO, Vec2::ZERO, 0, 0.0)
2229        };
2230
2231        let result = extract_frame(
2232            ExtractionParameters::new(generation, Color::BLACK, 0.5, RenderLimits::default()),
2233            [camera()?],
2234            [invalid],
2235            [],
2236            [],
2237        );
2238
2239        assert!(matches!(
2240            result,
2241            Err(ExtractionError::InvalidVisual {
2242                error: VisualValueError::InvalidRadius { .. },
2243                ..
2244            })
2245        ));
2246        Ok(())
2247    }
2248
2249    #[test]
2250    fn defensive_line_validation_preserves_entity_attribution() -> Result<(), Box<dyn Error>> {
2251        let generation = generation(1);
2252        let mut world = World::new();
2253        let entity = entity(&mut world, generation);
2254
2255        for invalid in [
2256            LineSource {
2257                vector: Vec2::new(f32::NAN, 0.0),
2258                ..line_source(entity, Vec2::ZERO, Vec2::ZERO, Vec2::ONE, 0, 0.0)
2259            },
2260            LineSource {
2261                stroke_width_logical_pixels: f32::MAX,
2262                ..line_source(entity, Vec2::ZERO, Vec2::ZERO, Vec2::ONE, 0, 0.0)
2263            },
2264        ] {
2265            let result = extract_frame(
2266                ExtractionParameters::new(generation, Color::BLACK, 0.0, RenderLimits::default()),
2267                [camera()?],
2268                [],
2269                [],
2270                [invalid],
2271            );
2272            assert!(matches!(
2273                result,
2274                Err(ExtractionError::InvalidVisual {
2275                    entity: rejected,
2276                    error: VisualValueError::InvalidLineVector { .. }
2277                        | VisualValueError::InvalidLineWidth { .. },
2278                }) if rejected == entity
2279            ));
2280        }
2281        Ok(())
2282    }
2283
2284    #[test]
2285    fn camera_cardinality_is_checked() -> Result<(), Box<dyn Error>> {
2286        let generation = generation(1);
2287        let limits = RenderLimits::default();
2288        let missing = extract_frame(
2289            ExtractionParameters::new(generation, Color::BLACK, 0.0, limits),
2290            [],
2291            [],
2292            [],
2293            [],
2294        );
2295        assert!(matches!(missing, Err(ExtractionError::MissingActiveCamera)));
2296
2297        let multiple = extract_frame(
2298            ExtractionParameters::new(generation, Color::BLACK, 0.0, limits),
2299            [camera()?, camera()?],
2300            [],
2301            [],
2302            [],
2303        );
2304        assert!(matches!(
2305            multiple,
2306            Err(ExtractionError::MultipleActiveCameras)
2307        ));
2308
2309        Ok(())
2310    }
2311
2312    #[test]
2313    fn reusable_storage_clears_logical_state_without_losing_fixed_record_capacity()
2314    -> Result<(), Box<dyn Error>> {
2315        let generation = generation(1);
2316        let mut world = World::new();
2317        let first = entity(&mut world, generation);
2318        let second = entity(&mut world, generation);
2319        let third = entity(&mut world, generation);
2320        let fourth = entity(&mut world, generation);
2321        let fifth = entity(&mut world, generation);
2322        let limits = RenderLimits::default();
2323        let mut storage = ExtractionBuffer::new(limits)?;
2324
2325        let first_metadata = extract_frame_into(
2326            &mut storage,
2327            ExtractionParameters::new(generation, Color::BLACK, 0.0, limits),
2328            [camera()?],
2329            [
2330                source(first, Vec2::ZERO, Vec2::ZERO, 0, 0.0),
2331                source(second, Vec2::ONE, Vec2::ONE, 0, 1.0),
2332            ],
2333            [
2334                rectangle_source(third, Vec2::ZERO, Vec2::ZERO, Vec2::ONE, 0, 2.0),
2335                rectangle_source(fourth, Vec2::ONE, Vec2::ONE, Vec2::ONE, 0, 3.0),
2336            ],
2337            [line_source(
2338                fifth,
2339                Vec2::new(2.0, 4.0),
2340                Vec2::new(2.0, 4.0),
2341                Vec2::new(3.0, -1.0),
2342                0,
2343                4.0,
2344            )],
2345            [],
2346        )?;
2347        assert_eq!(first_metadata.background, Color::BLACK);
2348        let circle_capacity = storage.resolved_circles.capacity();
2349        let rectangle_capacity = storage.resolved_rectangles.capacity();
2350        let line_capacity = storage.resolved_lines.capacity();
2351        let circle_address = storage.resolved_circles.as_ptr();
2352        let rectangle_address = storage.resolved_rectangles.as_ptr();
2353        let line_address = storage.resolved_lines.as_ptr();
2354        let scene_address = storage.world_scene.commands().as_ptr();
2355        let scene_allocation = storage.world_scene.allocation_bytes();
2356
2357        let moved_camera = ActiveCamera2d::new(Camera2d::new(Vec2::new(7.0, -4.0), 20.0)?);
2358        let second_metadata = extract_frame_into(
2359            &mut storage,
2360            ExtractionParameters::new(generation, Color::WHITE, 0.0, limits),
2361            [moved_camera],
2362            [source(first, Vec2::ONE, Vec2::ONE, 0, 0.0)],
2363            [],
2364            [],
2365            [],
2366        )?;
2367        assert_eq!(second_metadata.background, Color::WHITE);
2368        assert_eq!(second_metadata.camera.center(), Vec2::new(7.0, -4.0));
2369        assert_eq!(storage.resolved_circles.len(), 1);
2370        assert!(storage.resolved_rectangles.is_empty());
2371        assert!(storage.resolved_lines.is_empty());
2372        assert_eq!(storage.world_scene.command_count(), 1);
2373        assert_eq!(storage.world_scene.background(), Color::WHITE);
2374        assert_eq!(storage.resolved_circles.capacity(), circle_capacity);
2375        assert_eq!(storage.resolved_rectangles.capacity(), rectangle_capacity);
2376        assert_eq!(storage.resolved_lines.capacity(), line_capacity);
2377        assert_eq!(storage.resolved_circles.as_ptr(), circle_address);
2378        assert_eq!(storage.resolved_rectangles.as_ptr(), rectangle_address);
2379        assert_eq!(storage.resolved_lines.as_ptr(), line_address);
2380        assert_eq!(storage.world_scene.commands().as_ptr(), scene_address);
2381        assert_eq!(storage.world_scene.allocation_bytes(), scene_allocation);
2382
2383        let empty_metadata = extract_frame_into(
2384            &mut storage,
2385            ExtractionParameters::new(generation, Color::BLACK, 0.0, limits),
2386            [camera()?],
2387            [],
2388            [],
2389            [],
2390            [],
2391        )?;
2392        assert_eq!(empty_metadata.background, Color::BLACK);
2393        assert!(storage.resolved_circles.is_empty());
2394        assert!(storage.resolved_rectangles.is_empty());
2395        assert!(storage.resolved_lines.is_empty());
2396        assert_eq!(storage.world_scene.command_count(), 0);
2397        assert_eq!(storage.world_scene.statistics().accepted_commands(), 0);
2398        assert_eq!(storage.world_scene.background(), Color::BLACK);
2399        assert_eq!(storage.resolved_circles.capacity(), circle_capacity);
2400        assert_eq!(storage.resolved_rectangles.capacity(), rectangle_capacity);
2401        assert_eq!(storage.resolved_lines.capacity(), line_capacity);
2402        assert_eq!(storage.resolved_circles.as_ptr(), circle_address);
2403        assert_eq!(storage.resolved_rectangles.as_ptr(), rectangle_address);
2404        assert_eq!(storage.resolved_lines.as_ptr(), line_address);
2405        assert_eq!(storage.world_scene.commands().as_ptr(), scene_address);
2406        assert_eq!(storage.world_scene.allocation_bytes(), scene_allocation);
2407        Ok(())
2408    }
2409
2410    #[test]
2411    fn invalid_line_staging_preserves_publication_and_retry_clears_partial_records()
2412    -> Result<(), Box<dyn Error>> {
2413        let first_generation = generation(1);
2414        let next_generation = generation(2);
2415        let mut world = World::new();
2416        let first = entity(&mut world, first_generation);
2417        let valid = entity(&mut world, next_generation);
2418        let invalid = entity(&mut world, next_generation);
2419        let limits = RenderLimits::default();
2420        let mut buffers = ExtractionBuffers::new();
2421
2422        buffers.stage_world_only(
2423            ExtractionParameters::new(first_generation, Color::BLACK, 0.0, limits),
2424            [camera()?],
2425            [source(first, Vec2::ZERO, Vec2::ZERO, 0, 0.0)],
2426            [],
2427            [],
2428        )?;
2429        assert_eq!(buffers.publish(), Some(first_generation));
2430
2431        let result = buffers.stage_world_only(
2432            ExtractionParameters::new(next_generation, Color::WHITE, 0.0, limits),
2433            [camera()?],
2434            [],
2435            [],
2436            [
2437                line_source(valid, Vec2::ZERO, Vec2::ZERO, Vec2::ONE, 0, 0.0),
2438                line_source(
2439                    invalid,
2440                    Vec2::splat(f32::MAX),
2441                    Vec2::splat(f32::MAX),
2442                    Vec2::ONE,
2443                    0,
2444                    1.0,
2445                ),
2446            ],
2447        );
2448        assert!(matches!(
2449            result,
2450            Err(ExtractionError::InvalidResolvedLine { entity }) if entity == invalid
2451        ));
2452        let partial = buffers
2453            .spare
2454            .as_ref()
2455            .ok_or("failed line staging should retain its private spare")?;
2456        assert_eq!(partial.resolved_lines.len(), 1);
2457        assert_eq!(partial.resolved_lines[0].source(), valid);
2458        assert_eq!(partial.world_scene.command_count(), 0);
2459
2460        let published = buffers
2461            .published()
2462            .ok_or("failed line staging should preserve the published frame")?;
2463        assert_eq!(published.world_generation(), first_generation);
2464        assert_eq!(published.resolved_circles().len(), 1);
2465        assert!(published.resolved_lines().is_empty());
2466
2467        buffers.stage_world_only(
2468            ExtractionParameters::new(next_generation, Color::WHITE, 0.0, limits),
2469            [camera()?],
2470            [],
2471            [],
2472            [line_source(
2473                valid,
2474                Vec2::new(2.0, 3.0),
2475                Vec2::new(2.0, 3.0),
2476                Vec2::new(-1.0, 4.0),
2477                0,
2478                0.0,
2479            )],
2480        )?;
2481        assert_eq!(buffers.publish(), Some(next_generation));
2482        let published = buffers
2483            .published()
2484            .ok_or("valid line retry should publish")?;
2485        assert!(published.resolved_circles().is_empty());
2486        let [line] = published.resolved_lines() else {
2487            return Err("valid line retry should contain one fresh line".into());
2488        };
2489        assert_eq!(line.source(), valid);
2490        assert_eq!(line.from(), Vec2::new(2.0, 3.0));
2491        assert_eq!(line.to(), Vec2::new(1.0, 7.0));
2492        assert_eq!(published.world_scene().command_count(), 1);
2493        Ok(())
2494    }
2495
2496    #[test]
2497    fn downstream_line_scene_failure_keeps_the_last_complete_snapshot() -> Result<(), Box<dyn Error>>
2498    {
2499        let first_generation = generation(1);
2500        let failed_generation = generation(2);
2501        let mut world = World::new();
2502        let first = entity(&mut world, first_generation);
2503        let failed_first = entity(&mut world, failed_generation);
2504        let failed_second = entity(&mut world, failed_generation);
2505        let defaults = RenderLimits::default();
2506        let scene = defaults.world_scene_budget();
2507        let one_draw_batch = sim_engine::SceneBudget::new(
2508            scene.max_commands(),
2509            scene.max_points(),
2510            scene.max_tessellated_vertices(),
2511            scene.max_retained_bytes(),
2512            scene.max_allocation_bytes(),
2513            scene.max_upload_bytes(),
2514            1,
2515        );
2516        let limits = RenderLimits::new(
2517            defaults.max_world_circles(),
2518            one_draw_batch,
2519            defaults.frame_limits(),
2520        )
2521        .with_max_world_rectangles(defaults.max_world_rectangles())
2522        .with_max_world_lines(defaults.max_world_lines());
2523        let mut buffers = ExtractionBuffers::new();
2524
2525        buffers.stage_world_only(
2526            ExtractionParameters::new(first_generation, Color::BLACK, 0.0, limits),
2527            [camera()?],
2528            [source(first, Vec2::ZERO, Vec2::ZERO, 0, 0.0)],
2529            [],
2530            [],
2531        )?;
2532        assert_eq!(buffers.publish(), Some(first_generation));
2533
2534        let result = buffers.stage_world_only(
2535            ExtractionParameters::new(failed_generation, Color::WHITE, 0.0, limits),
2536            [camera()?],
2537            [],
2538            [],
2539            [
2540                line_source(failed_first, Vec2::ZERO, Vec2::ZERO, Vec2::ONE, 0, 0.0),
2541                line_source(failed_second, Vec2::ZERO, Vec2::ZERO, Vec2::ONE, 1, 0.0),
2542            ],
2543        );
2544        assert!(matches!(result, Err(ExtractionError::Scene(_))));
2545        let partial = buffers
2546            .spare
2547            .as_ref()
2548            .ok_or("failed Scene staging should retain its private spare")?;
2549        assert_eq!(partial.resolved_lines.len(), 2);
2550        assert_eq!(partial.world_scene.command_count(), 1);
2551        assert_eq!(partial.world_scene.statistics().requested_commands(), 2);
2552        assert_eq!(partial.world_scene.statistics().accepted_commands(), 1);
2553        assert_eq!(partial.world_scene.statistics().rejected_commands(), 1);
2554        assert_eq!(partial.world_scene.statistics().estimated_draw_batches(), 1);
2555
2556        let published = buffers
2557            .published()
2558            .ok_or("failed Scene staging should preserve the published frame")?;
2559        assert_eq!(published.world_generation(), first_generation);
2560        assert_eq!(published.resolved_circles().len(), 1);
2561        assert!(published.resolved_lines().is_empty());
2562        Ok(())
2563    }
2564
2565    #[test]
2566    fn failed_staging_preserves_published_frame_and_retry_has_no_partial_records()
2567    -> Result<(), Box<dyn Error>> {
2568        let first_generation = generation(1);
2569        let failed_generation = generation(2);
2570        let recovered_generation = generation(3);
2571        let mut world = World::new();
2572        let first = entity(&mut world, first_generation);
2573        let failed_first = entity(&mut world, failed_generation);
2574        let failed_second = entity(&mut world, failed_generation);
2575        let recovered = entity(&mut world, recovered_generation);
2576        let defaults = RenderLimits::default();
2577        let scene = defaults.world_scene_budget();
2578        let one_draw_batch = sim_engine::SceneBudget::new(
2579            scene.max_commands(),
2580            scene.max_points(),
2581            scene.max_tessellated_vertices(),
2582            scene.max_retained_bytes(),
2583            scene.max_allocation_bytes(),
2584            scene.max_upload_bytes(),
2585            1,
2586        );
2587        let limits = RenderLimits::new(
2588            defaults.max_world_circles(),
2589            one_draw_batch,
2590            defaults.frame_limits(),
2591        )
2592        .with_max_world_rectangles(defaults.max_world_rectangles());
2593        let mut buffers = ExtractionBuffers::new();
2594
2595        buffers.stage_world_only(
2596            ExtractionParameters::new(first_generation, Color::BLACK, 0.0, limits),
2597            [camera()?],
2598            [source(first, Vec2::ONE, Vec2::ONE, 0, 0.0)],
2599            [],
2600            [],
2601        )?;
2602        assert_eq!(buffers.publish(), Some(first_generation));
2603
2604        let result = buffers.stage_world_only(
2605            ExtractionParameters::new(failed_generation, Color::WHITE, 0.0, limits),
2606            [ActiveCamera2d::new(Camera2d::new(Vec2::ONE, 20.0)?)],
2607            [
2608                source(failed_first, Vec2::ZERO, Vec2::ZERO, 0, 0.0),
2609                source(
2610                    failed_second,
2611                    Vec2::splat(f32::MAX),
2612                    Vec2::splat(f32::MAX),
2613                    1,
2614                    1.0,
2615                ),
2616            ],
2617            [],
2618            [],
2619        );
2620        assert!(matches!(result, Err(ExtractionError::Scene(_))));
2621        let partial = buffers
2622            .spare
2623            .as_ref()
2624            .ok_or("failed staging should retain its private spare")?;
2625        assert_eq!(partial.resolved_circles.len(), 2);
2626        assert_eq!(partial.world_scene.command_count(), 1);
2627        assert_eq!(partial.world_scene.statistics().requested_commands(), 2);
2628        assert_eq!(partial.world_scene.statistics().accepted_commands(), 1);
2629        let published = buffers
2630            .published()
2631            .ok_or("failed staging should preserve the published frame")?;
2632        assert_eq!(published.world_generation(), first_generation);
2633        assert_eq!(published.background(), Color::BLACK);
2634        assert_eq!(published.camera().center(), Vec2::ZERO);
2635        assert_eq!(published.resolved_circles().len(), 1);
2636        assert_eq!(published.resolved_circles()[0].source(), first);
2637        assert_eq!(published.world_scene().command_count(), 1);
2638
2639        buffers.stage_world_only(
2640            ExtractionParameters::new(failed_generation, Color::WHITE, 0.0, limits),
2641            [ActiveCamera2d::new(Camera2d::new(Vec2::ONE, 20.0)?)],
2642            [source(failed_first, Vec2::ZERO, Vec2::ZERO, 0, 0.0)],
2643            [],
2644            [],
2645        )?;
2646        buffers.discard_staged();
2647        assert_eq!(buffers.publish(), None);
2648        assert_eq!(
2649            buffers.published().map(ExtractedFrame::world_generation),
2650            Some(first_generation),
2651            "abandoning a validated candidate must not publish its work buffer"
2652        );
2653
2654        buffers.stage_world_only(
2655            ExtractionParameters::new(recovered_generation, Color::WHITE, 0.0, limits),
2656            [ActiveCamera2d::new(Camera2d::new(
2657                Vec2::new(-2.0, 3.0),
2658                20.0,
2659            )?)],
2660            [],
2661            [rectangle_source(
2662                recovered,
2663                Vec2::new(4.0, 5.0),
2664                Vec2::new(4.0, 5.0),
2665                Vec2::ONE,
2666                0,
2667                0.0,
2668            )],
2669            [],
2670        )?;
2671        assert_eq!(buffers.publish(), Some(recovered_generation));
2672        let published = buffers
2673            .published()
2674            .ok_or("valid retry should publish its complete frame")?;
2675        assert_eq!(published.world_generation(), recovered_generation);
2676        assert_eq!(published.background(), Color::WHITE);
2677        assert_eq!(published.camera().center(), Vec2::new(-2.0, 3.0));
2678        assert!(published.resolved_circles().is_empty());
2679        let [rectangle] = published.resolved_rectangles() else {
2680            return Err("valid retry should contain only its rectangle".into());
2681        };
2682        assert_eq!(rectangle.source(), recovered);
2683        assert_eq!(published.world_scene().command_count(), 1);
2684        assert_eq!(published.world_scene().statistics().accepted_commands(), 1);
2685        assert!(matches!(
2686            published.world_scene().commands()[0].command(),
2687            DrawCommand::Rect(_)
2688        ));
2689        Ok(())
2690    }
2691
2692    #[test]
2693    fn successful_publications_alternate_exactly_two_warmed_buffers() -> Result<(), Box<dyn Error>>
2694    {
2695        let first_generation = generation(1);
2696        let second_generation = generation(2);
2697        let third_generation = generation(3);
2698        let mut world = World::new();
2699        let first = entity(&mut world, first_generation);
2700        let second = entity(&mut world, second_generation);
2701        let third = entity(&mut world, third_generation);
2702        let limits = RenderLimits::default();
2703        let mut buffers = ExtractionBuffers::new();
2704
2705        buffers.stage_world_only(
2706            ExtractionParameters::new(first_generation, Color::BLACK, 0.0, limits),
2707            [camera()?],
2708            [source(first, Vec2::ZERO, Vec2::ZERO, 0, 0.0)],
2709            [],
2710            [],
2711        )?;
2712        assert_eq!(buffers.publish(), Some(first_generation));
2713        let published = buffers.published().ok_or("first frame was not published")?;
2714        let first_circle_address = published.storage.resolved_circles.as_ptr();
2715        let first_scene_address = published.storage.world_scene.commands().as_ptr();
2716
2717        buffers.stage_world_only(
2718            ExtractionParameters::new(second_generation, Color::WHITE, 0.0, limits),
2719            [camera()?],
2720            [source(second, Vec2::ONE, Vec2::ONE, 0, 0.0)],
2721            [],
2722            [],
2723        )?;
2724        assert_eq!(buffers.publish(), Some(second_generation));
2725        let published = buffers
2726            .published()
2727            .ok_or("second frame was not published")?;
2728        let second_circle_address = published.storage.resolved_circles.as_ptr();
2729        let second_scene_address = published.storage.world_scene.commands().as_ptr();
2730        assert_ne!(second_circle_address, first_circle_address);
2731        assert_ne!(second_scene_address, first_scene_address);
2732
2733        buffers.stage_world_only(
2734            ExtractionParameters::new(third_generation, Color::BLACK, 0.0, limits),
2735            [camera()?],
2736            [source(
2737                third,
2738                Vec2::new(2.0, 3.0),
2739                Vec2::new(2.0, 3.0),
2740                0,
2741                0.0,
2742            )],
2743            [],
2744            [],
2745        )?;
2746        assert_eq!(buffers.publish(), Some(third_generation));
2747        let published = buffers.published().ok_or("third frame was not published")?;
2748        assert_eq!(
2749            published.storage.resolved_circles.as_ptr(),
2750            first_circle_address
2751        );
2752        assert_eq!(
2753            published.storage.world_scene.commands().as_ptr(),
2754            first_scene_address
2755        );
2756        assert_eq!(published.resolved_circles()[0].source(), third);
2757        Ok(())
2758    }
2759}