Skip to main content

sim_engine/
scene.rs

1use std::{
2    error::Error,
3    fmt,
4    mem::size_of,
5    panic::{AssertUnwindSafe, catch_unwind, resume_unwind},
6};
7
8use crate::{
9    Color, Interpolate, LogicalPixels, LogicalScreenPosition, LogicalScreenVector, Rect, Vec2,
10    WorldLength,
11};
12
13pub(crate) const CIRCLE_SEGMENTS: usize = 64;
14pub(crate) const ROUND_CAP_SEGMENTS: usize = 16;
15pub(crate) const CORNER_SEGMENTS: usize = 12;
16pub(crate) const TESSELLATED_VERTEX_BYTES: usize = 20 * size_of::<f32>();
17const MAX_DASH_ELEMENTS: usize = 8;
18const MAX_MITER_LIMIT: f32 = 1_000.0;
19const MIN_STROKE_TURN_SINE: f64 = 0.000_1;
20/// Maximum visible dash pieces one command may request from tessellation.
21pub const MAX_STROKE_DASH_SUBSEGMENTS: usize = 1_000_000;
22
23/// Primitive category attached to structured scene validation errors.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum ScenePrimitive {
26    /// Circle geometry or style.
27    Circle,
28    /// Rectangle geometry or style.
29    Rect,
30    /// Single line geometry or stroke.
31    Line,
32    /// Connected polyline geometry or stroke.
33    Polyline,
34}
35
36/// Work category constrained by a [`SceneBudget`].
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38#[non_exhaustive]
39pub enum SceneBudgetResource {
40    /// Accepted scene commands.
41    Commands,
42    /// Points retained by polyline commands.
43    Points,
44    /// Conservative upper bound for generated triangle-list vertices.
45    TessellatedVertices,
46    /// Command payload bytes retained by the scene.
47    RetainedBytes,
48    /// Committed command-vector and owned polyline allocation bytes.
49    AllocationBytes,
50    /// Bytes uploaded for generated scene vertices.
51    UploadBytes,
52    /// Draw batches caused by ordering and clip changes.
53    DrawBatches,
54}
55
56/// Explicit upper bounds for engine-owned ordinary-scene work.
57///
58/// Limits may be zero to construct a background-only scene. Retained bytes
59/// count logical command values and owned polyline storage. Allocation bytes
60/// additionally bound committed spare command-vector capacity; allocator
61/// bookkeeping and transactional replacement overlap are excluded. Vertex and
62/// upload limits use the renderer's conservative
63/// triangle-list estimate, which is checked again after tessellation.
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub struct SceneBudget {
66    max_commands: usize,
67    max_points: usize,
68    max_tessellated_vertices: usize,
69    max_retained_bytes: usize,
70    max_allocation_bytes: usize,
71    max_upload_bytes: usize,
72    max_draw_batches: usize,
73}
74
75impl SceneBudget {
76    /// Builds a complete budget for ordinary scene construction and rendering.
77    pub const fn new(
78        max_commands: usize,
79        max_points: usize,
80        max_tessellated_vertices: usize,
81        max_retained_bytes: usize,
82        max_allocation_bytes: usize,
83        max_upload_bytes: usize,
84        max_draw_batches: usize,
85    ) -> Self {
86        Self {
87            max_commands,
88            max_points,
89            max_tessellated_vertices,
90            max_retained_bytes,
91            max_allocation_bytes,
92            max_upload_bytes,
93            max_draw_batches,
94        }
95    }
96
97    /// Returns the maximum accepted command count.
98    pub const fn max_commands(self) -> usize {
99        self.max_commands
100    }
101
102    /// Returns the maximum retained polyline point count.
103    pub const fn max_points(self) -> usize {
104        self.max_points
105    }
106
107    /// Returns the maximum conservatively estimated vertex count.
108    pub const fn max_tessellated_vertices(self) -> usize {
109        self.max_tessellated_vertices
110    }
111
112    /// Returns the maximum retained command payload bytes.
113    pub const fn max_retained_bytes(self) -> usize {
114        self.max_retained_bytes
115    }
116
117    /// Returns the maximum committed command and polyline allocation bytes.
118    pub const fn max_allocation_bytes(self) -> usize {
119        self.max_allocation_bytes
120    }
121
122    /// Returns the maximum generated vertex upload bytes.
123    pub const fn max_upload_bytes(self) -> usize {
124        self.max_upload_bytes
125    }
126
127    /// Returns the maximum draw-batch count.
128    pub const fn max_draw_batches(self) -> usize {
129        self.max_draw_batches
130    }
131}
132
133/// Construction and conservative rendering work accumulated by a scene.
134#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
135pub struct SceneStatistics {
136    requested_commands: usize,
137    accepted_commands: usize,
138    rejected_commands: usize,
139    requested_by_primitive: PrimitiveCommandCounts,
140    accepted_by_primitive: PrimitiveCommandCounts,
141    rejected_by_primitive: PrimitiveCommandCounts,
142    retained_points: usize,
143    estimated_tessellated_vertices: usize,
144    retained_bytes: usize,
145    estimated_upload_bytes: usize,
146    estimated_draw_batches: usize,
147}
148
149impl SceneStatistics {
150    /// Returns all insertion attempts, including invalid and over-budget work.
151    pub const fn requested_commands(self) -> usize {
152        self.requested_commands
153    }
154
155    /// Returns commands currently retained by the scene.
156    pub const fn accepted_commands(self) -> usize {
157        self.accepted_commands
158    }
159
160    /// Returns insertion attempts rejected by validation, budget, or allocation.
161    pub const fn rejected_commands(self) -> usize {
162        self.rejected_commands
163    }
164
165    /// Returns insertion attempts grouped by primitive category.
166    pub const fn requested_by_primitive(self) -> PrimitiveCommandCounts {
167        self.requested_by_primitive
168    }
169
170    /// Returns currently retained commands grouped by primitive category.
171    pub const fn accepted_by_primitive(self) -> PrimitiveCommandCounts {
172        self.accepted_by_primitive
173    }
174
175    /// Returns rejected insertion attempts grouped by primitive category.
176    pub const fn rejected_by_primitive(self) -> PrimitiveCommandCounts {
177        self.rejected_by_primitive
178    }
179
180    /// Returns points retained by accepted polyline commands.
181    pub const fn retained_points(self) -> usize {
182        self.retained_points
183    }
184
185    /// Returns the conservative upper bound for tessellated vertices.
186    pub const fn estimated_tessellated_vertices(self) -> usize {
187        self.estimated_tessellated_vertices
188    }
189
190    /// Returns tracked command and owned polyline payload bytes.
191    pub const fn retained_bytes(self) -> usize {
192        self.retained_bytes
193    }
194
195    /// Returns estimated bytes uploaded for generated vertices.
196    pub const fn estimated_upload_bytes(self) -> usize {
197        self.estimated_upload_bytes
198    }
199
200    /// Returns the conservative draw-batch upper bound.
201    pub const fn estimated_draw_batches(self) -> usize {
202        self.estimated_draw_batches
203    }
204
205    fn with_command(mut self, command: &DrawCommand) -> Self {
206        let vertices = command.estimated_tessellated_vertices();
207        self.accepted_commands = self.accepted_commands.saturating_add(1);
208        self.accepted_by_primitive.increment(command.primitive());
209        self.retained_points = self
210            .retained_points
211            .saturating_add(command.retained_point_count());
212        self.estimated_tessellated_vertices =
213            self.estimated_tessellated_vertices.saturating_add(vertices);
214        self.retained_bytes = self.retained_bytes.saturating_add(command.retained_bytes());
215        self.estimated_upload_bytes = self
216            .estimated_upload_bytes
217            .saturating_add(vertices.saturating_mul(TESSELLATED_VERTEX_BYTES));
218        self.estimated_draw_batches = self.estimated_draw_batches.saturating_add(1);
219        self
220    }
221}
222
223/// Command counters grouped by ordinary 2D primitive category.
224#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
225pub struct PrimitiveCommandCounts {
226    circles: usize,
227    rectangles: usize,
228    lines: usize,
229    polylines: usize,
230}
231
232impl PrimitiveCommandCounts {
233    /// Returns circle command count.
234    pub const fn circles(self) -> usize {
235        self.circles
236    }
237
238    /// Returns rectangle command count.
239    pub const fn rectangles(self) -> usize {
240        self.rectangles
241    }
242
243    /// Returns single-line command count.
244    pub const fn lines(self) -> usize {
245        self.lines
246    }
247
248    /// Returns connected-polyline command count.
249    pub const fn polylines(self) -> usize {
250        self.polylines
251    }
252
253    /// Returns all primitive commands represented by these counters.
254    pub const fn total(self) -> usize {
255        self.circles
256            .saturating_add(self.rectangles)
257            .saturating_add(self.lines)
258            .saturating_add(self.polylines)
259    }
260
261    pub(crate) fn increment(&mut self, primitive: ScenePrimitive) {
262        match primitive {
263            ScenePrimitive::Circle => self.circles = self.circles.saturating_add(1),
264            ScenePrimitive::Rect => self.rectangles = self.rectangles.saturating_add(1),
265            ScenePrimitive::Line => self.lines = self.lines.saturating_add(1),
266            ScenePrimitive::Polyline => self.polylines = self.polylines.saturating_add(1),
267        }
268    }
269
270    pub(crate) fn adding(mut self, other: Self) -> Self {
271        self.circles = self.circles.saturating_add(other.circles);
272        self.rectangles = self.rectangles.saturating_add(other.rectangles);
273        self.lines = self.lines.saturating_add(other.lines);
274        self.polylines = self.polylines.saturating_add(other.polylines);
275        self
276    }
277}
278
279/// Reason a command or temporary scene state was rejected.
280#[derive(Debug, Clone, Copy, PartialEq, Eq)]
281pub enum SceneError {
282    /// Clear color is non-finite or outside normalized RGBA.
283    InvalidBackground,
284    /// Primitive coordinates contain NaN or infinity.
285    NonFiniteGeometry(ScenePrimitive),
286    /// Radius, size, corner radius, or stroke width is outside its valid range.
287    InvalidDimension(ScenePrimitive),
288    /// A line segment, or at least one consecutive polyline segment, is not drawable.
289    DegenerateGeometry(ScenePrimitive),
290    /// Consecutive polyline segments form a numerically ambiguous continuation or reversal.
291    ///
292    /// An almost-collinear change of direction cannot select a stable shader
293    /// join branch; a retraced centerline also has no interior-disjoint
294    /// alpha-blended representation. `vertex_index` identifies the path point.
295    DegenerateStrokeTurn {
296        /// Primitive containing the ambiguous turn.
297        primitive: ScenePrimitive,
298        /// Zero-based index of the shared turn point.
299        vertex_index: usize,
300    },
301    /// Shape has no fill, stroke, or shadow.
302    MissingStyle(ScenePrimitive),
303    /// Fill color or gradient configuration is invalid.
304    InvalidFill(ScenePrimitive),
305    /// Stroke width or color is invalid.
306    InvalidStroke(ScenePrimitive),
307    /// A dash pattern would expand into more retained triangle pieces than its
308    /// explicit per-command limit.
309    StrokeExpansionLimitExceeded {
310        /// Primitive whose stroke exceeded the limit.
311        primitive: ScenePrimitive,
312        /// Configured maximum number of emitted visible subsegments.
313        limit: usize,
314        /// Minimum visible-subsegment count that proved the limit was exceeded.
315        required: usize,
316    },
317    /// Dash/gap boundaries collapse at the source path's `f32` coordinate scale.
318    UnrepresentableStrokePattern(ScenePrimitive),
319    /// Shadow offset, spread, or color is invalid.
320    InvalidShadow(ScenePrimitive),
321    /// Active logical screen clip is non-finite or empty.
322    InvalidScreenClip,
323    /// Pseudo-depth must be finite.
324    NonFiniteDepth,
325    /// An accepted command would exceed an explicit scene work limit.
326    BudgetExceeded {
327        /// Work category whose limit was exceeded.
328        resource: SceneBudgetResource,
329        /// Configured maximum for the category.
330        limit: usize,
331        /// Total category usage that the command requested.
332        requested: usize,
333    },
334    /// Engine-owned command storage could not be reserved without mutation.
335    AllocationFailed {
336        /// Conservative byte estimate associated with the failed reservation.
337        ///
338        /// Depending on the transactional path, this can describe one
339        /// command's retained payload or the total replacement/staging
340        /// allocation that could not be reserved. It is diagnostic context,
341        /// not a delta suitable for allocator accounting.
342        requested_bytes: usize,
343    },
344}
345
346impl fmt::Display for SceneError {
347    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
348        write!(formatter, "scene command rejected: {self:?}")
349    }
350}
351
352impl Error for SceneError {}
353
354/// Ordered list of visual draw commands for a single frame.
355///
356/// A scene contains renderable primitives only. It does not own simulation
357/// entities, domain rules, or time stepping.
358#[derive(Debug)]
359pub struct Scene {
360    background: Color,
361    /// Commands stored in draw order.
362    commands: Vec<SceneCommand>,
363    owned_payload_bytes: usize,
364    next_order: u64,
365    current_screen_clip: Option<ScreenClipRect>,
366    current_depth: f32,
367    budget: Option<SceneBudget>,
368    statistics: SceneStatistics,
369}
370
371impl Clone for Scene {
372    fn clone(&self) -> Self {
373        let commands = self.commands.clone();
374        let owned_payload_bytes = commands
375            .iter()
376            .map(|command| command.command.owned_allocation_bytes())
377            .fold(0usize, usize::saturating_add);
378        let mut statistics = self.statistics;
379        statistics.retained_bytes = commands
380            .len()
381            .saturating_mul(size_of::<SceneCommand>())
382            .saturating_add(owned_payload_bytes);
383        Self {
384            background: self.background,
385            commands,
386            owned_payload_bytes,
387            next_order: self.next_order,
388            current_screen_clip: self.current_screen_clip,
389            current_depth: self.current_depth,
390            budget: self.budget,
391            statistics,
392        }
393    }
394}
395
396impl Scene {
397    /// Creates an empty scene with a normalized linear-RGBA background color.
398    ///
399    /// This compatibility constructor is intentionally unbounded. Production
400    /// hosts handling externally sized visual state should prefer
401    /// [`Scene::with_budget`].
402    pub fn new(background: Color) -> Result<Self, SceneError> {
403        Self::create(background, None)
404    }
405
406    /// Creates an empty scene with explicit construction and rendering limits.
407    pub fn with_budget(background: Color, budget: SceneBudget) -> Result<Self, SceneError> {
408        Self::create(background, Some(budget))
409    }
410
411    fn create(background: Color, budget: Option<SceneBudget>) -> Result<Self, SceneError> {
412        if !background.is_normalized() {
413            return Err(SceneError::InvalidBackground);
414        }
415        Ok(Self {
416            background,
417            commands: Vec::new(),
418            owned_payload_bytes: 0,
419            next_order: 0,
420            current_screen_clip: None,
421            current_depth: 0.0,
422            budget,
423            statistics: SceneStatistics::default(),
424        })
425    }
426
427    /// Returns the normalized clear color used before drawing commands.
428    pub fn background(&self) -> Color {
429        self.background
430    }
431
432    /// Replaces the clear color used before drawing commands.
433    pub fn set_background(&mut self, background: Color) -> Result<(), SceneError> {
434        if !background.is_normalized() {
435            return Err(SceneError::InvalidBackground);
436        }
437        self.background = background;
438        Ok(())
439    }
440
441    /// Removes all draw commands and active clipping without changing the background color.
442    pub fn clear(&mut self) {
443        self.commands.clear();
444        self.owned_payload_bytes = 0;
445        self.next_order = 0;
446        self.current_screen_clip = None;
447        self.current_depth = 0.0;
448        self.statistics = SceneStatistics::default();
449    }
450
451    /// Returns accepted commands in stable layer and insertion order.
452    pub fn commands(&self) -> &[SceneCommand] {
453        &self.commands
454    }
455
456    /// Returns the number of accepted render commands.
457    pub fn command_count(&self) -> usize {
458        self.commands.len()
459    }
460
461    /// Returns CPU allocation bytes currently owned by command and polyline storage.
462    ///
463    /// Unlike [`SceneStatistics::retained_bytes`], which is the budgeted payload
464    /// of accepted commands, this includes spare `Vec` capacity retained for
465    /// reuse after insertion or [`Scene::clear`]. Allocator bookkeeping is not
466    /// included.
467    pub fn allocation_bytes(&self) -> usize {
468        self.commands
469            .capacity()
470            .saturating_mul(size_of::<SceneCommand>())
471            .saturating_add(self.owned_payload_bytes)
472    }
473
474    pub(crate) fn preflight_command_storage(
475        &self,
476        additional_commands: usize,
477        additional_owned_bytes: usize,
478    ) -> Result<(), SceneError> {
479        let Some(budget) = self.budget else {
480            return Ok(());
481        };
482        let retained_bytes = self
483            .statistics
484            .retained_bytes
485            .saturating_add(additional_commands.saturating_mul(size_of::<SceneCommand>()))
486            .saturating_add(additional_owned_bytes);
487        if retained_bytes > budget.max_retained_bytes {
488            return Err(SceneError::BudgetExceeded {
489                resource: SceneBudgetResource::RetainedBytes,
490                limit: budget.max_retained_bytes,
491                requested: retained_bytes,
492            });
493        }
494        let required_len = self.commands.len().saturating_add(additional_commands);
495        let owned_payload_bytes = self
496            .owned_payload_bytes
497            .saturating_add(additional_owned_bytes);
498        let capacity = if required_len <= self.commands.capacity() {
499            self.commands.capacity()
500        } else {
501            budgeted_command_capacity(
502                budget,
503                self.commands.capacity(),
504                required_len,
505                owned_payload_bytes,
506            )?
507        };
508        validate_scene_allocation_budget(budget, capacity, owned_payload_bytes)
509    }
510
511    /// Returns the explicit work budget, or `None` for an unbounded scene.
512    pub const fn budget(&self) -> Option<SceneBudget> {
513        self.budget
514    }
515
516    /// Returns requested, accepted, rejected, and estimated scene work.
517    pub const fn statistics(&self) -> SceneStatistics {
518        self.statistics
519    }
520
521    pub(crate) const fn current_screen_clip(&self) -> Option<ScreenClipRect> {
522        self.current_screen_clip
523    }
524
525    /// Replaces the screen-space clipping rectangle captured by new commands.
526    ///
527    /// The rectangle uses logical screen pixels with the origin at the top-left
528    /// of the render surface. Existing commands keep the clip they captured when
529    /// they were appended. `None` disables clipping for subsequent commands.
530    /// The previous clip is returned so callers can restore explicit drawing
531    /// state without tracking it separately. Invalid clips are rejected here,
532    /// before they can affect a later command insertion.
533    pub fn set_screen_clip(
534        &mut self,
535        screen_clip: Option<ScreenClipRect>,
536    ) -> Result<Option<ScreenClipRect>, SceneError> {
537        if screen_clip.is_some_and(|clip| !clip.is_valid()) {
538            return Err(SceneError::InvalidScreenClip);
539        }
540        Ok(std::mem::replace(
541            &mut self.current_screen_clip,
542            screen_clip,
543        ))
544    }
545
546    /// Appends commands from `draw` using a temporary screen-space clip.
547    ///
548    /// The rectangle uses logical screen pixels. Nested clips are intersected,
549    /// so inner drawing cannot escape an outer clip. The previous clip is
550    /// restored after `draw` returns.
551    pub fn with_screen_clip<R>(
552        &mut self,
553        screen_clip: ScreenClipRect,
554        draw: impl FnOnce(&mut Self) -> R,
555    ) -> Result<R, SceneError> {
556        if !screen_clip.is_valid() {
557            return Err(SceneError::InvalidScreenClip);
558        }
559        let previous = self.current_screen_clip;
560        let combined = match previous {
561            Some(outer) => outer.intersection(screen_clip)?,
562            None => screen_clip,
563        };
564        if !combined.is_valid() {
565            return Err(SceneError::InvalidScreenClip);
566        }
567        self.current_screen_clip = Some(combined);
568        let result = catch_unwind(AssertUnwindSafe(|| draw(self)));
569        self.current_screen_clip = previous;
570        match result {
571            Ok(result) => Ok(result),
572            Err(payload) => resume_unwind(payload),
573        }
574    }
575
576    /// Replaces the pseudo-depth captured by subsequently appended commands.
577    ///
578    /// Depth is measured in caller-defined units and converted through
579    /// [`crate::Projection2d::depth_scale`]. It affects projection only, not draw
580    /// order. Non-finite values return `false` and leave the current depth unchanged.
581    pub fn set_depth(&mut self, depth: f32) -> bool {
582        self.try_set_depth(depth).is_ok()
583    }
584
585    /// Replaces pseudo-depth and reports why invalid input was rejected.
586    pub fn try_set_depth(&mut self, depth: f32) -> Result<(), SceneError> {
587        if !depth.is_finite() {
588            return Err(SceneError::NonFiniteDepth);
589        }
590        self.current_depth = depth;
591        Ok(())
592    }
593
594    /// Appends commands with a temporary pseudo-depth value.
595    ///
596    /// The previous depth is restored after `draw` returns or unwinds. Non-finite
597    /// depth returns an error without calling `draw`.
598    pub fn with_depth<R>(
599        &mut self,
600        depth: f32,
601        draw: impl FnOnce(&mut Self) -> R,
602    ) -> Result<R, SceneError> {
603        if !depth.is_finite() {
604            return Err(SceneError::NonFiniteDepth);
605        }
606
607        let previous = self.current_depth;
608        self.current_depth = depth;
609        let result = catch_unwind(AssertUnwindSafe(|| draw(self)));
610        self.current_depth = previous;
611        match result {
612            Ok(result) => Ok(result),
613            Err(payload) => resume_unwind(payload),
614        }
615    }
616
617    /// Appends a valid command to the default layer.
618    ///
619    /// Returns `false` without changing commands, ordering, or retained
620    /// allocation when the primitive is invalid. Requested/rejected diagnostic
621    /// counters still advance for the attempted command.
622    pub fn push(&mut self, command: DrawCommand) -> bool {
623        self.try_push(command).is_ok()
624    }
625
626    /// Appends a command to the default layer with structured rejection diagnostics.
627    pub fn try_push(&mut self, command: DrawCommand) -> Result<(), SceneError> {
628        self.try_push_to_layer(Layer::DEFAULT, command)
629    }
630
631    /// Appends a command to a layer.
632    ///
633    /// Lower layer values are drawn first. Commands on the same layer preserve
634    /// insertion order.
635    /// Returns `false` without changing commands, ordering, or retained
636    /// allocation when `command` is invalid. Requested/rejected diagnostic
637    /// counters still advance for the attempted command.
638    pub fn push_to_layer(&mut self, layer: Layer, command: DrawCommand) -> bool {
639        self.try_push_to_layer(layer, command).is_ok()
640    }
641
642    /// Appends a command to a layer with structured rejection diagnostics.
643    pub fn try_push_to_layer(
644        &mut self,
645        layer: Layer,
646        command: DrawCommand,
647    ) -> Result<(), SceneError> {
648        let primitive = command.primitive();
649        self.statistics.requested_commands = self.statistics.requested_commands.saturating_add(1);
650        self.statistics.requested_by_primitive.increment(primitive);
651        let result = self.try_push_to_layer_inner(layer, command);
652        if result.is_err() {
653            self.statistics.rejected_commands = self.statistics.rejected_commands.saturating_add(1);
654            self.statistics.rejected_by_primitive.increment(primitive);
655        }
656        result
657    }
658
659    /// Atomically appends many commands and orders the combined scene once.
660    ///
661    /// This is the bounded high-volume construction path for adversarial or
662    /// frequently alternating layers. Validation and budget accounting happen
663    /// before the existing command list is changed. On failure, no command from
664    /// the batch is retained; request and rejection diagnostics still advance.
665    /// The resulting order is stable by layer and by batch insertion order.
666    pub fn try_extend_to_layers(
667        &mut self,
668        commands: impl IntoIterator<Item = (Layer, DrawCommand)>,
669    ) -> Result<(), SceneError> {
670        let mut staged = Vec::new();
671        let mut requested = self.statistics;
672        let mut attempted = 0usize;
673        let mut attempted_by_primitive = PrimitiveCommandCounts::default();
674        let mut next_order = self.next_order;
675        let existing_owned_payload_bytes = self.owned_payload_bytes;
676        let mut staged_owned_payload_bytes = 0usize;
677
678        for (layer, command) in commands {
679            let primitive = command.primitive();
680            attempted = attempted.saturating_add(1);
681            attempted_by_primitive.increment(primitive);
682            requested.requested_commands = requested.requested_commands.saturating_add(1);
683            requested.requested_by_primitive.increment(primitive);
684            if let Err(error) = command.validate() {
685                self.record_batch_rejection(attempted, attempted_by_primitive);
686                return Err(error);
687            }
688            if self
689                .current_screen_clip
690                .is_some_and(|screen_clip| !screen_clip.is_valid())
691            {
692                self.record_batch_rejection(attempted, attempted_by_primitive);
693                return Err(SceneError::InvalidScreenClip);
694            }
695
696            requested = requested.with_command(&command);
697            if let Some(budget) = self.budget
698                && let Err(error) = validate_scene_budget(budget, requested)
699            {
700                self.record_batch_rejection(attempted, attempted_by_primitive);
701                return Err(error);
702            }
703            let command_owned_payload_bytes = command.owned_allocation_bytes();
704            let prospective_owned_payload_bytes = existing_owned_payload_bytes
705                .saturating_add(staged_owned_payload_bytes)
706                .saturating_add(command_owned_payload_bytes);
707            if let Some(budget) = self.budget {
708                let required_total = self
709                    .commands
710                    .len()
711                    .saturating_add(staged.len())
712                    .saturating_add(1);
713                let final_capacity = if required_total <= self.commands.capacity() {
714                    self.commands.capacity()
715                } else {
716                    match budgeted_command_capacity(
717                        budget,
718                        self.commands.capacity(),
719                        required_total,
720                        prospective_owned_payload_bytes,
721                    ) {
722                        Ok(capacity) => capacity,
723                        Err(error) => {
724                            self.record_batch_rejection(attempted, attempted_by_primitive);
725                            return Err(error);
726                        }
727                    }
728                };
729                if let Err(error) = validate_scene_allocation_budget(
730                    budget,
731                    final_capacity,
732                    prospective_owned_payload_bytes,
733                ) {
734                    self.record_batch_rejection(attempted, attempted_by_primitive);
735                    return Err(error);
736                }
737
738                if staged.len() == staged.capacity() {
739                    let staging_capacity = match budgeted_command_capacity(
740                        budget,
741                        staged.capacity(),
742                        staged.len().saturating_add(1),
743                        prospective_owned_payload_bytes,
744                    ) {
745                        Ok(capacity) => capacity,
746                        Err(error) => {
747                            self.record_batch_rejection(attempted, attempted_by_primitive);
748                            return Err(error);
749                        }
750                    };
751                    let mut replacement = Vec::new();
752                    if replacement.try_reserve_exact(staging_capacity).is_err() {
753                        self.record_batch_rejection(attempted, attempted_by_primitive);
754                        return Err(SceneError::AllocationFailed {
755                            requested_bytes: scene_allocation_bytes(
756                                staging_capacity,
757                                prospective_owned_payload_bytes,
758                            ),
759                        });
760                    }
761                    if let Err(error) = validate_scene_allocation_budget(
762                        budget,
763                        replacement.capacity(),
764                        prospective_owned_payload_bytes,
765                    ) {
766                        self.record_batch_rejection(attempted, attempted_by_primitive);
767                        return Err(error);
768                    }
769                    replacement.append(&mut staged);
770                    staged = replacement;
771                } else if let Err(error) = validate_scene_allocation_budget(
772                    budget,
773                    staged.capacity(),
774                    prospective_owned_payload_bytes,
775                ) {
776                    self.record_batch_rejection(attempted, attempted_by_primitive);
777                    return Err(error);
778                }
779            } else if staged.try_reserve(1).is_err() {
780                self.record_batch_rejection(attempted, attempted_by_primitive);
781                return Err(SceneError::AllocationFailed {
782                    requested_bytes: command.retained_bytes(),
783                });
784            }
785            staged.push(SceneCommand {
786                layer,
787                order: next_order,
788                depth: self.current_depth,
789                screen_clip: self.current_screen_clip,
790                command,
791            });
792            staged_owned_payload_bytes =
793                staged_owned_payload_bytes.saturating_add(command_owned_payload_bytes);
794            next_order = next_order.saturating_add(1);
795        }
796
797        if staged.is_empty() {
798            return Ok(());
799        }
800        let total = self.commands.len().saturating_add(staged.len());
801        let owned_payload_bytes =
802            existing_owned_payload_bytes.saturating_add(staged_owned_payload_bytes);
803        let requested_capacity = if let Some(budget) = self.budget {
804            if total <= self.commands.capacity() {
805                self.commands.capacity()
806            } else {
807                match budgeted_command_capacity(
808                    budget,
809                    self.commands.capacity(),
810                    total,
811                    owned_payload_bytes,
812                ) {
813                    Ok(capacity) => capacity,
814                    Err(error) => {
815                        self.record_batch_rejection(attempted, attempted_by_primitive);
816                        return Err(error);
817                    }
818                }
819            }
820        } else {
821            total
822        };
823        if staged.capacity() < requested_capacity
824            && staged
825                .try_reserve_exact(requested_capacity.saturating_sub(staged.len()))
826                .is_err()
827        {
828            self.record_batch_rejection(attempted, attempted_by_primitive);
829            return Err(SceneError::AllocationFailed {
830                requested_bytes: scene_allocation_bytes(requested_capacity, owned_payload_bytes),
831            });
832        }
833        if let Some(budget) = self.budget
834            && let Err(error) =
835                validate_scene_allocation_budget(budget, staged.capacity(), owned_payload_bytes)
836        {
837            self.record_batch_rejection(attempted, attempted_by_primitive);
838            return Err(error);
839        }
840        staged.append(&mut self.commands);
841        staged.sort_unstable_by_key(|command| (command.layer, command.order));
842        self.commands = staged;
843        self.owned_payload_bytes = owned_payload_bytes;
844        self.next_order = next_order;
845        self.statistics = requested;
846        Ok(())
847    }
848
849    fn record_batch_rejection(
850        &mut self,
851        command_count: usize,
852        by_primitive: PrimitiveCommandCounts,
853    ) {
854        self.statistics.requested_commands = self
855            .statistics
856            .requested_commands
857            .saturating_add(command_count);
858        self.statistics.rejected_commands = self
859            .statistics
860            .rejected_commands
861            .saturating_add(command_count);
862        self.statistics.requested_by_primitive =
863            self.statistics.requested_by_primitive.adding(by_primitive);
864        self.statistics.rejected_by_primitive =
865            self.statistics.rejected_by_primitive.adding(by_primitive);
866    }
867
868    pub(crate) fn record_external_rejection(&mut self, primitive: ScenePrimitive) {
869        let mut counts = PrimitiveCommandCounts::default();
870        counts.increment(primitive);
871        self.record_batch_rejection(1, counts);
872    }
873
874    fn try_push_to_layer_inner(
875        &mut self,
876        layer: Layer,
877        command: DrawCommand,
878    ) -> Result<(), SceneError> {
879        command.validate()?;
880        if self
881            .current_screen_clip
882            .is_some_and(|screen_clip| !screen_clip.is_valid())
883        {
884            return Err(SceneError::InvalidScreenClip);
885        }
886
887        let command_retained_bytes = command.retained_bytes();
888        let owned_payload_bytes = self
889            .owned_payload_bytes
890            .saturating_add(command.owned_allocation_bytes());
891        let requested = self.statistics.with_command(&command);
892        if let Some(budget) = self.budget {
893            validate_scene_budget(budget, requested)?;
894        }
895
896        let replacement = if self.commands.len() == self.commands.capacity() {
897            if let Some(budget) = self.budget {
898                let required_len = self.commands.len().saturating_add(1);
899                let capacity = budgeted_command_capacity(
900                    budget,
901                    self.commands.capacity(),
902                    required_len,
903                    owned_payload_bytes,
904                )?;
905                let mut replacement = Vec::new();
906                replacement.try_reserve_exact(capacity).map_err(|_| {
907                    SceneError::AllocationFailed {
908                        requested_bytes: scene_allocation_bytes(capacity, owned_payload_bytes),
909                    }
910                })?;
911                validate_scene_allocation_budget(
912                    budget,
913                    replacement.capacity(),
914                    owned_payload_bytes,
915                )?;
916                Some(replacement)
917            } else {
918                self.commands
919                    .try_reserve(1)
920                    .map_err(|_| SceneError::AllocationFailed {
921                        requested_bytes: command_retained_bytes,
922                    })?;
923                None
924            }
925        } else {
926            if let Some(budget) = self.budget {
927                validate_scene_allocation_budget(
928                    budget,
929                    self.commands.capacity(),
930                    owned_payload_bytes,
931                )?;
932            }
933            None
934        };
935
936        if let Some(mut replacement) = replacement {
937            replacement.append(&mut self.commands);
938            self.commands = replacement;
939        }
940
941        let order = self.next_order;
942        let scene_command = SceneCommand {
943            layer,
944            order,
945            depth: self.current_depth,
946            screen_clip: self.current_screen_clip,
947            command,
948        };
949        let position = self.commands.partition_point(|existing| {
950            existing.layer < scene_command.layer
951                || (existing.layer == scene_command.layer && existing.order <= scene_command.order)
952        });
953        self.commands.insert(position, scene_command);
954        self.owned_payload_bytes = owned_payload_bytes;
955        self.next_order = self.next_order.saturating_add(1);
956        self.statistics = requested;
957        Ok(())
958    }
959
960    /// Appends a circle in world coordinates.
961    ///
962    /// `radius` is in world units. Returns `false` for non-positive or non-finite
963    /// radius, non-finite center, or invalid style values.
964    pub fn circle(&mut self, center: Vec2, radius: f32, style: ShapeStyle) -> bool {
965        self.try_circle(center, radius, style).is_ok()
966    }
967
968    /// Appends a circle and returns a structured validation error on rejection.
969    pub fn try_circle(
970        &mut self,
971        center: Vec2,
972        radius: f32,
973        style: ShapeStyle,
974    ) -> Result<(), SceneError> {
975        self.try_circle_on_layer(Layer::DEFAULT, center, radius, style)
976    }
977
978    /// Appends a circle in world coordinates to a layer.
979    ///
980    /// `radius` is in world units. Returns `false` for non-positive or non-finite
981    /// radius, non-finite center, or invalid style values.
982    pub fn circle_on_layer(
983        &mut self,
984        layer: Layer,
985        center: Vec2,
986        radius: f32,
987        style: ShapeStyle,
988    ) -> bool {
989        self.try_circle_on_layer(layer, center, radius, style)
990            .is_ok()
991    }
992
993    /// Appends a circle to a layer with structured rejection diagnostics.
994    pub fn try_circle_on_layer(
995        &mut self,
996        layer: Layer,
997        center: Vec2,
998        radius: f32,
999        style: ShapeStyle,
1000    ) -> Result<(), SceneError> {
1001        self.try_push_to_layer(
1002            layer,
1003            DrawCommand::Circle(Circle {
1004                center,
1005                radius,
1006                style,
1007            }),
1008        )
1009    }
1010
1011    /// Appends an axis-aligned rectangle in world coordinates.
1012    ///
1013    /// `corner_radius` is in world units and renderers clamp it to half the
1014    /// rectangle size. Invalid bounds, negative radius, and invalid styles return
1015    /// `false` without adding a command.
1016    pub fn rect(&mut self, rect: Rect, corner_radius: f32, style: ShapeStyle) -> bool {
1017        self.try_rect(rect, corner_radius, style).is_ok()
1018    }
1019
1020    /// Appends a rectangle and returns a structured validation error on rejection.
1021    pub fn try_rect(
1022        &mut self,
1023        rect: Rect,
1024        corner_radius: f32,
1025        style: ShapeStyle,
1026    ) -> Result<(), SceneError> {
1027        self.try_rect_on_layer(Layer::DEFAULT, rect, corner_radius, style)
1028    }
1029
1030    /// Appends an axis-aligned rectangle in world coordinates to a layer.
1031    ///
1032    /// `corner_radius` is in world units and renderers clamp it to half the
1033    /// rectangle size. Invalid bounds, negative radius, and invalid styles return
1034    /// `false` without adding a command.
1035    pub fn rect_on_layer(
1036        &mut self,
1037        layer: Layer,
1038        rect: Rect,
1039        corner_radius: f32,
1040        style: ShapeStyle,
1041    ) -> bool {
1042        self.try_rect_on_layer(layer, rect, corner_radius, style)
1043            .is_ok()
1044    }
1045
1046    /// Appends a rectangle to a layer with structured rejection diagnostics.
1047    pub fn try_rect_on_layer(
1048        &mut self,
1049        layer: Layer,
1050        rect: Rect,
1051        corner_radius: f32,
1052        style: ShapeStyle,
1053    ) -> Result<(), SceneError> {
1054        self.try_push_to_layer(
1055            layer,
1056            DrawCommand::Rect(RectShape {
1057                rect,
1058                corner_radius,
1059                style,
1060            }),
1061        )
1062    }
1063
1064    /// Appends a stroked line between world-space points.
1065    ///
1066    /// `width` is in logical screen pixels so line thickness stays readable while the
1067    /// camera zooms. Degenerate geometry and invalid width or color return
1068    /// `false`.
1069    pub fn line(&mut self, from: Vec2, to: Vec2, width: f32, color: Color) -> bool {
1070        self.try_line(from, to, width, color).is_ok()
1071    }
1072
1073    /// Appends a line and returns a structured validation error on rejection.
1074    pub fn try_line(
1075        &mut self,
1076        from: Vec2,
1077        to: Vec2,
1078        width: f32,
1079        color: Color,
1080    ) -> Result<(), SceneError> {
1081        self.try_styled_line(from, to, StrokeStyle2d::new(width, color))
1082    }
1083
1084    /// Appends a stroked line between world-space points to a layer.
1085    ///
1086    /// `width` is in logical screen pixels so line thickness stays readable while the
1087    /// camera zooms. Degenerate geometry and invalid width or color return
1088    /// `false`.
1089    pub fn line_on_layer(
1090        &mut self,
1091        layer: Layer,
1092        from: Vec2,
1093        to: Vec2,
1094        width: f32,
1095        color: Color,
1096    ) -> bool {
1097        self.try_line_on_layer(layer, from, to, width, color)
1098            .is_ok()
1099    }
1100
1101    /// Appends a line to a layer with structured rejection diagnostics.
1102    pub fn try_line_on_layer(
1103        &mut self,
1104        layer: Layer,
1105        from: Vec2,
1106        to: Vec2,
1107        width: f32,
1108        color: Color,
1109    ) -> Result<(), SceneError> {
1110        self.try_styled_line_on_layer(layer, from, to, StrokeStyle2d::new(width, color))
1111    }
1112
1113    /// Appends a line with explicit width units, caps, joins, dashes, and markers.
1114    pub fn styled_line(&mut self, from: Vec2, to: Vec2, style: StrokeStyle2d) -> bool {
1115        self.try_styled_line(from, to, style).is_ok()
1116    }
1117
1118    /// Appends an explicitly styled line with structured rejection diagnostics.
1119    pub fn try_styled_line(
1120        &mut self,
1121        from: Vec2,
1122        to: Vec2,
1123        style: StrokeStyle2d,
1124    ) -> Result<(), SceneError> {
1125        self.try_styled_line_on_layer(Layer::DEFAULT, from, to, style)
1126    }
1127
1128    /// Appends an explicitly styled line to a shared draw layer.
1129    pub fn styled_line_on_layer(
1130        &mut self,
1131        layer: Layer,
1132        from: Vec2,
1133        to: Vec2,
1134        style: StrokeStyle2d,
1135    ) -> bool {
1136        self.try_styled_line_on_layer(layer, from, to, style)
1137            .is_ok()
1138    }
1139
1140    /// Appends an explicitly styled line to a layer with structured rejection.
1141    pub fn try_styled_line_on_layer(
1142        &mut self,
1143        layer: Layer,
1144        from: Vec2,
1145        to: Vec2,
1146        style: StrokeStyle2d,
1147    ) -> Result<(), SceneError> {
1148        self.try_push_to_layer(layer, DrawCommand::Line(Line { from, to, style }))
1149    }
1150
1151    /// Appends connected stroked segments through world-space points.
1152    ///
1153    /// `width` is in logical screen pixels. Empty, single-point, non-finite,
1154    /// repeated-adjacent, or numerically ambiguous turn input returns `false`
1155    /// without adding a command; every consecutive segment must be drawable.
1156    pub fn polyline(&mut self, points: Vec<Vec2>, width: f32, color: Color) -> bool {
1157        self.try_polyline(points, width, color).is_ok()
1158    }
1159
1160    /// Appends a polyline and returns a structured validation error on rejection.
1161    pub fn try_polyline(
1162        &mut self,
1163        points: Vec<Vec2>,
1164        width: f32,
1165        color: Color,
1166    ) -> Result<(), SceneError> {
1167        self.try_styled_polyline(points, StrokeStyle2d::new(width, color))
1168    }
1169
1170    /// Appends connected stroked segments through world-space points to a layer.
1171    ///
1172    /// `width` is in logical screen pixels. Empty, single-point, non-finite,
1173    /// repeated-adjacent, or numerically ambiguous turn input returns `false`
1174    /// without adding a command; every consecutive segment must be drawable.
1175    pub fn polyline_on_layer(
1176        &mut self,
1177        layer: Layer,
1178        points: Vec<Vec2>,
1179        width: f32,
1180        color: Color,
1181    ) -> bool {
1182        self.try_polyline_on_layer(layer, points, width, color)
1183            .is_ok()
1184    }
1185
1186    /// Appends a polyline to a layer with structured rejection diagnostics.
1187    pub fn try_polyline_on_layer(
1188        &mut self,
1189        layer: Layer,
1190        points: Vec<Vec2>,
1191        width: f32,
1192        color: Color,
1193    ) -> Result<(), SceneError> {
1194        self.try_styled_polyline_on_layer(layer, points, StrokeStyle2d::new(width, color))
1195    }
1196
1197    /// Appends a connected path with explicit width, caps, joins, dashes, and markers.
1198    pub fn styled_polyline(&mut self, points: Vec<Vec2>, style: StrokeStyle2d) -> bool {
1199        self.try_styled_polyline(points, style).is_ok()
1200    }
1201
1202    /// Appends an explicitly styled path with structured rejection diagnostics.
1203    pub fn try_styled_polyline(
1204        &mut self,
1205        points: Vec<Vec2>,
1206        style: StrokeStyle2d,
1207    ) -> Result<(), SceneError> {
1208        self.try_styled_polyline_on_layer(Layer::DEFAULT, points, style)
1209    }
1210
1211    /// Appends an explicitly styled path to a shared draw layer.
1212    pub fn styled_polyline_on_layer(
1213        &mut self,
1214        layer: Layer,
1215        points: Vec<Vec2>,
1216        style: StrokeStyle2d,
1217    ) -> bool {
1218        self.try_styled_polyline_on_layer(layer, points, style)
1219            .is_ok()
1220    }
1221
1222    /// Appends an explicitly styled path to a layer with structured rejection.
1223    pub fn try_styled_polyline_on_layer(
1224        &mut self,
1225        layer: Layer,
1226        points: Vec<Vec2>,
1227        style: StrokeStyle2d,
1228    ) -> Result<(), SceneError> {
1229        self.try_push_to_layer(layer, DrawCommand::Polyline(Polyline { points, style }))
1230    }
1231}
1232
1233/// Draw layer used to order scene commands.
1234///
1235/// Lower values are drawn first. Higher values appear above lower layers.
1236#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1237pub struct Layer {
1238    order: i32,
1239}
1240
1241impl Layer {
1242    /// Default layer used by convenience drawing methods.
1243    pub const DEFAULT: Self = Self::new(0);
1244    /// Conventional layer for background guides or grids.
1245    pub const BACKGROUND: Self = Self::new(-100);
1246    /// Conventional layer for foreground annotations or overlays.
1247    pub const FOREGROUND: Self = Self::new(100);
1248
1249    /// Builds a layer from an order value.
1250    pub const fn new(order: i32) -> Self {
1251        Self { order }
1252    }
1253
1254    /// Returns the order value used for sorting.
1255    pub const fn order(self) -> i32 {
1256        self.order
1257    }
1258}
1259
1260/// Axis-aligned clipping rectangle in logical screen pixels.
1261///
1262/// The coordinate origin is the top-left of the render surface and positive y
1263/// points downward. Constructors reject empty and non-finite bounds.
1264/// Renderers clamp valid clips to the target viewport.
1265#[derive(Debug, Clone, Copy, PartialEq)]
1266pub struct ScreenClipRect {
1267    rect: Rect,
1268}
1269
1270impl ScreenClipRect {
1271    /// Builds a non-empty clip from two corners in logical screen pixels.
1272    pub fn new(min: LogicalScreenPosition, max: LogicalScreenPosition) -> Result<Self, SceneError> {
1273        Self::from_rect(Rect::new(min.to_vec2(), max.to_vec2()))
1274    }
1275
1276    /// Builds a clip from its top-left corner and size in logical screen pixels.
1277    ///
1278    /// Negative size components are accepted and normalized before validation.
1279    pub fn from_min_size(
1280        min: LogicalScreenPosition,
1281        size: LogicalScreenVector,
1282    ) -> Result<Self, SceneError> {
1283        Self::from_rect(Rect::from_min_size(min.to_vec2(), size.to_vec2()))
1284    }
1285
1286    fn from_rect(rect: Rect) -> Result<Self, SceneError> {
1287        let clip = Self { rect };
1288        clip.is_valid()
1289            .then_some(clip)
1290            .ok_or(SceneError::InvalidScreenClip)
1291    }
1292
1293    #[cfg(feature = "wgpu")]
1294    pub(crate) fn rect(self) -> Rect {
1295        self.rect
1296    }
1297
1298    /// Returns the normalized top-left corner in logical screen pixels.
1299    pub fn min(self) -> LogicalScreenPosition {
1300        LogicalScreenPosition::from_vec2(self.rect.normalized().min)
1301    }
1302
1303    /// Returns the normalized bottom-right corner in logical screen pixels.
1304    pub fn max(self) -> LogicalScreenPosition {
1305        LogicalScreenPosition::from_vec2(self.rect.normalized().max)
1306    }
1307
1308    /// Returns the overlap between two screen-space clips.
1309    ///
1310    /// Disjoint inputs return [`SceneError::InvalidScreenClip`].
1311    pub fn intersection(self, other: Self) -> Result<Self, SceneError> {
1312        let first = self.rect.normalized();
1313        let second = other.rect.normalized();
1314        let min = Vec2::new(first.min.x.max(second.min.x), first.min.y.max(second.min.y));
1315        let max = Vec2::new(first.max.x.min(second.max.x), first.max.y.min(second.max.y));
1316
1317        Self::new(
1318            LogicalScreenPosition::from_vec2(min),
1319            LogicalScreenPosition::from_vec2(Vec2::new(max.x.max(min.x), max.y.max(min.y))),
1320        )
1321    }
1322
1323    fn is_valid(self) -> bool {
1324        if !self.rect.min.is_finite() || !self.rect.max.is_finite() {
1325            return false;
1326        }
1327
1328        let rect = self.rect.normalized();
1329        rect.width() > 0.0 && rect.height() > 0.0
1330    }
1331}
1332
1333/// Draw command with layer and stable insertion order metadata.
1334#[derive(Debug, Clone)]
1335pub struct SceneCommand {
1336    /// Layer used to sort commands before rendering.
1337    layer: Layer,
1338    /// Monotonic insertion order within the scene.
1339    order: u64,
1340    /// Caller-defined pseudo-depth used by camera projection.
1341    depth: f32,
1342    /// Optional clipping rectangle in logical screen pixels.
1343    screen_clip: Option<ScreenClipRect>,
1344    /// Visual primitive to render.
1345    command: DrawCommand,
1346}
1347
1348impl SceneCommand {
1349    /// Returns the layer used for stable scene ordering.
1350    pub fn layer(&self) -> Layer {
1351        self.layer
1352    }
1353
1354    /// Returns the insertion order assigned by the scene.
1355    pub fn order(&self) -> u64 {
1356        self.order
1357    }
1358
1359    /// Returns caller-defined pseudo-depth captured by this command.
1360    ///
1361    /// Depth affects camera projection only. Commands on one layer retain their
1362    /// insertion order regardless of depth.
1363    pub fn depth(&self) -> f32 {
1364        self.depth
1365    }
1366
1367    /// Returns the optional clip captured when the command was appended.
1368    pub fn screen_clip(&self) -> Option<ScreenClipRect> {
1369        self.screen_clip
1370    }
1371
1372    /// Returns the visual primitive stored by this command.
1373    pub fn command(&self) -> &DrawCommand {
1374        &self.command
1375    }
1376}
1377
1378/// Renderable primitive command.
1379#[derive(Debug, Clone)]
1380#[non_exhaustive]
1381pub enum DrawCommand {
1382    /// Filled and/or stroked circle.
1383    Circle(Circle),
1384    /// Filled and/or stroked rectangle.
1385    Rect(RectShape),
1386    /// Single stroked segment.
1387    Line(Line),
1388    /// Connected stroked segments.
1389    Polyline(Polyline),
1390}
1391
1392impl DrawCommand {
1393    /// Returns the primitive category used by diagnostics and budgets.
1394    pub const fn primitive(&self) -> ScenePrimitive {
1395        match self {
1396            Self::Circle(_) => ScenePrimitive::Circle,
1397            Self::Rect(_) => ScenePrimitive::Rect,
1398            Self::Line(_) => ScenePrimitive::Line,
1399            Self::Polyline(_) => ScenePrimitive::Polyline,
1400        }
1401    }
1402
1403    /// Builds and validates a circle command for batch insertion.
1404    pub fn circle(center: Vec2, radius: f32, style: ShapeStyle) -> Result<Self, SceneError> {
1405        let command = Self::Circle(Circle {
1406            center,
1407            radius,
1408            style,
1409        });
1410        command.validate()?;
1411        Ok(command)
1412    }
1413
1414    /// Builds and validates a rectangle command for batch insertion.
1415    pub fn rect(rect: Rect, corner_radius: f32, style: ShapeStyle) -> Result<Self, SceneError> {
1416        let command = Self::Rect(RectShape {
1417            rect,
1418            corner_radius,
1419            style,
1420        });
1421        command.validate()?;
1422        Ok(command)
1423    }
1424
1425    /// Builds and validates a single line command for batch insertion.
1426    pub fn line(from: Vec2, to: Vec2, width: f32, color: Color) -> Result<Self, SceneError> {
1427        Self::styled_line(from, to, StrokeStyle2d::new(width, color))
1428    }
1429
1430    /// Builds and validates an explicitly styled line command.
1431    pub fn styled_line(from: Vec2, to: Vec2, style: StrokeStyle2d) -> Result<Self, SceneError> {
1432        let command = Self::Line(Line { from, to, style });
1433        command.validate()?;
1434        Ok(command)
1435    }
1436
1437    /// Builds and validates a connected polyline command for batch insertion.
1438    pub fn polyline(points: Vec<Vec2>, width: f32, color: Color) -> Result<Self, SceneError> {
1439        Self::styled_polyline(points, StrokeStyle2d::new(width, color))
1440    }
1441
1442    /// Builds and validates an explicitly styled polyline command.
1443    pub fn styled_polyline(points: Vec<Vec2>, style: StrokeStyle2d) -> Result<Self, SceneError> {
1444        let command = Self::Polyline(Polyline { points, style });
1445        command.validate()?;
1446        Ok(command)
1447    }
1448
1449    fn validate(&self) -> Result<(), SceneError> {
1450        match self {
1451            Self::Circle(circle) => {
1452                if !circle.center.is_finite() {
1453                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Circle));
1454                }
1455                if !circle.radius.is_finite() || circle.radius <= 0.0 {
1456                    return Err(SceneError::InvalidDimension(ScenePrimitive::Circle));
1457                }
1458                if !(circle.center + Vec2::splat(circle.radius)).is_finite()
1459                    || !(circle.center - Vec2::splat(circle.radius)).is_finite()
1460                {
1461                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Circle));
1462                }
1463                circle.style.validate(ScenePrimitive::Circle)
1464            }
1465            Self::Rect(rectangle) => {
1466                let rect = rectangle.rect.normalized();
1467                if !rect.min.is_finite() || !rect.max.is_finite() {
1468                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Rect));
1469                }
1470                let width = rect.width();
1471                let height = rect.height();
1472                if !width.is_finite() || !height.is_finite() {
1473                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Rect));
1474                }
1475                if width <= 0.0
1476                    || height <= 0.0
1477                    || !rectangle.corner_radius.is_finite()
1478                    || rectangle.corner_radius < 0.0
1479                {
1480                    return Err(SceneError::InvalidDimension(ScenePrimitive::Rect));
1481                }
1482                rectangle.style.validate(ScenePrimitive::Rect)
1483            }
1484            Self::Line(line) => {
1485                if !line.from.is_finite() || !line.to.is_finite() {
1486                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Line));
1487                }
1488                if !(line.to - line.from).is_finite() {
1489                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Line));
1490                }
1491                if !drawable_segment(line.from, line.to) {
1492                    return Err(SceneError::DegenerateGeometry(ScenePrimitive::Line));
1493                }
1494                if !line.style.is_valid() {
1495                    return Err(SceneError::InvalidStroke(ScenePrimitive::Line));
1496                }
1497                validate_stroke_path(&[line.from, line.to], line.style, ScenePrimitive::Line)?;
1498                Ok(())
1499            }
1500            Self::Polyline(polyline) => {
1501                validate_styled_polyline(polyline.points.iter().copied(), polyline.style)?;
1502                Ok(())
1503            }
1504        }
1505    }
1506
1507    fn retained_point_count(&self) -> usize {
1508        match self {
1509            Self::Polyline(polyline) => polyline.points.len(),
1510            Self::Circle(_) | Self::Rect(_) | Self::Line(_) => 0,
1511        }
1512    }
1513
1514    fn retained_bytes(&self) -> usize {
1515        size_of::<SceneCommand>().saturating_add(self.owned_allocation_bytes())
1516    }
1517
1518    fn owned_allocation_bytes(&self) -> usize {
1519        match self {
1520            Self::Polyline(polyline) => {
1521                polyline.points.capacity().saturating_mul(size_of::<Vec2>())
1522            }
1523            Self::Circle(_) | Self::Rect(_) | Self::Line(_) => 0,
1524        }
1525    }
1526
1527    fn estimated_tessellated_vertices(&self) -> usize {
1528        match self {
1529            Self::Circle(circle) => {
1530                let fill_vertices = CIRCLE_SEGMENTS * 3;
1531                let stroke_vertices = CIRCLE_SEGMENTS * 6;
1532                let style = circle.style;
1533                usize::from(style.fill.is_some()) * fill_vertices
1534                    + usize::from(style.stroke.is_some()) * stroke_vertices
1535                    + style.shadow.map_or(0, |shadow| {
1536                        fill_vertices + usize::from(shadow.spread > 0.0) * stroke_vertices
1537                    })
1538            }
1539            Self::Rect(rectangle) => {
1540                let rect = rectangle.rect.normalized();
1541                let radius = rectangle
1542                    .corner_radius
1543                    .max(0.0)
1544                    .min(rect.width().abs() * 0.5)
1545                    .min(rect.height().abs() * 0.5);
1546                let boundary_segments = if radius <= 0.0 {
1547                    4
1548                } else {
1549                    4 * (CORNER_SEGMENTS + 1)
1550                };
1551                let fill_vertices = boundary_segments * 3;
1552                let stroke_vertices = boundary_segments * 6;
1553                let style = rectangle.style;
1554                usize::from(style.fill.is_some()) * fill_vertices
1555                    + usize::from(style.stroke.is_some()) * stroke_vertices
1556                    + style.shadow.map_or(0, |shadow| {
1557                        fill_vertices + usize::from(shadow.spread > 0.0) * stroke_vertices
1558                    })
1559            }
1560            Self::Line(line) => estimate_stroke_vertices(&[line.from, line.to], line.style),
1561            Self::Polyline(polyline) => estimate_stroke_vertices(&polyline.points, polyline.style),
1562        }
1563    }
1564}
1565
1566fn validate_stroke_path(
1567    points: &[Vec2],
1568    style: StrokeStyle2d,
1569    primitive: ScenePrimitive,
1570) -> Result<(), SceneError> {
1571    validate_stroke_path_iter(points.iter().copied(), style, primitive)
1572}
1573
1574fn validate_stroke_path_iter<I>(
1575    points: I,
1576    style: StrokeStyle2d,
1577    primitive: ScenePrimitive,
1578) -> Result<(), SceneError>
1579where
1580    I: Iterator<Item = Vec2> + Clone,
1581{
1582    let maximum_offset = f64::from(style.stroke.width) * 0.5 * f64::from(style.miter_limit);
1583    if !maximum_offset.is_finite() || maximum_offset > f64::from(f32::MAX) {
1584        return Err(SceneError::InvalidStroke(primitive));
1585    }
1586    if style.width_mode == StrokeWidthMode2d::WorldUnits {
1587        let extent = Vec2::splat(maximum_offset as f32);
1588        if points
1589            .clone()
1590            .any(|point| !(point + extent).is_finite() || !(point - extent).is_finite())
1591        {
1592            return Err(SceneError::NonFiniteGeometry(primitive));
1593        }
1594    }
1595    if let Some(dash) = style.dash {
1596        let required = dash_subsegment_count_iter(points, dash, Some(dash.max_subsegments))
1597            .ok_or(SceneError::UnrepresentableStrokePattern(primitive))?;
1598        if required > dash.max_subsegments {
1599            return Err(SceneError::StrokeExpansionLimitExceeded {
1600                primitive,
1601                limit: dash.max_subsegments,
1602                required,
1603            });
1604        }
1605    }
1606    Ok(())
1607}
1608
1609/// Validates caller-owned polyline coordinates without allocating or copying them.
1610///
1611/// Screen-space adapters use this before reserving their converted point buffer,
1612/// so an invalid leading point or segment cannot force work proportional to the
1613/// rest of a caller-sized slice.
1614pub(crate) fn validate_polyline_geometry<I>(points: I) -> Result<(), SceneError>
1615where
1616    I: Iterator<Item = Vec2> + Clone,
1617{
1618    let primitive = ScenePrimitive::Polyline;
1619    if !points.clone().all(|point| point.is_finite()) {
1620        return Err(SceneError::NonFiniteGeometry(primitive));
1621    }
1622
1623    let mut deltas = points.clone();
1624    let Some(mut previous) = deltas.next() else {
1625        return Err(SceneError::DegenerateGeometry(primitive));
1626    };
1627    let mut segment_count = 0usize;
1628    for point in deltas {
1629        let delta = point - previous;
1630        if !delta.is_finite() {
1631            return Err(SceneError::NonFiniteGeometry(primitive));
1632        }
1633        previous = point;
1634        segment_count = segment_count.saturating_add(1);
1635    }
1636    if segment_count == 0 {
1637        return Err(SceneError::DegenerateGeometry(primitive));
1638    }
1639
1640    let mut segments = points.clone();
1641    let mut previous = segments
1642        .next()
1643        .expect("a non-empty path was established above");
1644    for point in segments {
1645        if !drawable_segment(previous, point) {
1646            return Err(SceneError::DegenerateGeometry(primitive));
1647        }
1648        previous = point;
1649    }
1650
1651    let mut turns = points;
1652    let mut first = turns
1653        .next()
1654        .expect("a drawable segment was established above");
1655    let mut second = turns
1656        .next()
1657        .expect("a drawable segment was established above");
1658    for (index, third) in turns.enumerate() {
1659        let incoming = second - first;
1660        let outgoing = third - second;
1661        let cross = f64::from(incoming.x) * f64::from(outgoing.y)
1662            - f64::from(incoming.y) * f64::from(outgoing.x);
1663        let dot = f64::from(incoming.x) * f64::from(outgoing.x)
1664            + f64::from(incoming.y) * f64::from(outgoing.y);
1665        let direction_product = f64::from(incoming.x).hypot(f64::from(incoming.y))
1666            * f64::from(outgoing.x).hypot(f64::from(outgoing.y));
1667        let normalized_cross = cross / direction_product;
1668        if normalized_cross.abs() <= MIN_STROKE_TURN_SINE && (dot < 0.0 || normalized_cross != 0.0)
1669        {
1670            return Err(SceneError::DegenerateStrokeTurn {
1671                primitive,
1672                vertex_index: index + 1,
1673            });
1674        }
1675        first = second;
1676        second = third;
1677    }
1678    Ok(())
1679}
1680
1681/// Validates a complete styled polyline without taking ownership of its points.
1682pub(crate) fn validate_styled_polyline<I>(points: I, style: StrokeStyle2d) -> Result<(), SceneError>
1683where
1684    I: Iterator<Item = Vec2> + Clone,
1685{
1686    validate_polyline_geometry(points.clone())?;
1687    if !style.is_valid() {
1688        return Err(SceneError::InvalidStroke(ScenePrimitive::Polyline));
1689    }
1690    validate_stroke_path_iter(points, style, ScenePrimitive::Polyline)
1691}
1692
1693fn estimate_stroke_vertices(points: &[Vec2], style: StrokeStyle2d) -> usize {
1694    let segment_count = points
1695        .windows(2)
1696        .filter(|pair| drawable_segment(pair[0], pair[1]))
1697        .count();
1698    if segment_count == 0 {
1699        return 0;
1700    }
1701    let body_count = style.dash.map_or(segment_count, |dash| {
1702        dash_subsegment_count(points, dash, None)
1703            .expect("accepted dash paths have representable subsegments")
1704    });
1705    // A visible dash may continue across every geometric vertex. Counting all
1706    // possible joins is conservative without expanding the pattern twice.
1707    let join_count = segment_count.saturating_sub(1);
1708    let cap_count = if style.dash.is_some() {
1709        body_count.saturating_mul(2)
1710    } else {
1711        2
1712    };
1713    let cap_vertices = match style.cap {
1714        StrokeCap2d::Round => cap_count.saturating_mul(ROUND_CAP_SEGMENTS * 3),
1715        StrokeCap2d::Butt | StrokeCap2d::Square => 0,
1716    };
1717    let join_vertices = match style.join {
1718        StrokeJoin2d::Bevel => join_count.saturating_mul(6),
1719        StrokeJoin2d::Miter => join_count.saturating_mul(12),
1720        // Logical round joins carry one candidate fan for each possible screen
1721        // orientation; the shader collapses the inactive fan to zero area.
1722        StrokeJoin2d::Round if style.width_mode == StrokeWidthMode2d::LogicalPixels => {
1723            join_count.saturating_mul(ROUND_CAP_SEGMENTS * 6)
1724        }
1725        StrokeJoin2d::Round => join_count.saturating_mul(ROUND_CAP_SEGMENTS * 3),
1726    };
1727    let marker_vertices = (usize::from(style.start_marker.is_some())
1728        + usize::from(style.end_marker.is_some()))
1729    .saturating_mul(3);
1730    body_count
1731        .saturating_mul(6)
1732        .saturating_add(cap_vertices)
1733        .saturating_add(join_vertices)
1734        .saturating_add(marker_vertices)
1735}
1736
1737fn dash_subsegment_count(
1738    points: &[Vec2],
1739    dash: StrokeDashPattern2d,
1740    stop_after: Option<usize>,
1741) -> Option<usize> {
1742    dash_subsegment_count_iter(points.iter().copied(), dash, stop_after)
1743}
1744
1745fn dash_subsegment_count_iter<I>(
1746    points: I,
1747    dash: StrokeDashPattern2d,
1748    stop_after: Option<usize>,
1749) -> Option<usize>
1750where
1751    I: Iterator<Item = Vec2>,
1752{
1753    let lengths = dash.lengths();
1754    let total: f64 = lengths.iter().map(|length| f64::from(*length)).sum();
1755    let mut phase = f64::from(dash.phase).rem_euclid(total);
1756    let mut pattern_index = 0usize;
1757    while phase >= f64::from(lengths[pattern_index]) {
1758        phase -= f64::from(lengths[pattern_index]);
1759        pattern_index = (pattern_index + 1) % lengths.len();
1760    }
1761    let mut pattern_remaining = f64::from(lengths[pattern_index]) - phase;
1762    let mut count = 0usize;
1763
1764    let mut points = points;
1765    let mut previous = points.next()?;
1766    for point in points {
1767        let delta = point - previous;
1768        let segment_length = f64::from(delta.x).hypot(f64::from(delta.y));
1769        let mut segment_remaining = segment_length;
1770        while segment_remaining > 0.0 {
1771            let consumed = segment_remaining.min(pattern_remaining);
1772            if pattern_index.is_multiple_of(2) && consumed > 0.0 {
1773                count = count.saturating_add(1);
1774                if stop_after.is_some_and(|limit| count > limit) {
1775                    return Some(count);
1776                }
1777            }
1778            let next_remaining = segment_remaining - consumed;
1779            if next_remaining >= segment_remaining {
1780                return None;
1781            }
1782            let amount_start = 1.0 - segment_remaining / segment_length;
1783            let amount_end = 1.0 - next_remaining / segment_length;
1784            if dash_segment_point(previous, point, amount_start)
1785                == dash_segment_point(previous, point, amount_end)
1786            {
1787                return None;
1788            }
1789            segment_remaining = next_remaining;
1790            pattern_remaining -= consumed;
1791            if pattern_remaining <= 0.0 {
1792                pattern_index = (pattern_index + 1) % lengths.len();
1793                pattern_remaining = f64::from(lengths[pattern_index]);
1794            }
1795        }
1796        previous = point;
1797    }
1798    Some(count)
1799}
1800
1801fn dash_segment_point(from: Vec2, to: Vec2, amount: f64) -> Vec2 {
1802    Vec2::new(
1803        (f64::from(from.x) * (1.0 - amount) + f64::from(to.x) * amount) as f32,
1804        (f64::from(from.y) * (1.0 - amount) + f64::from(to.y) * amount) as f32,
1805    )
1806}
1807
1808fn validate_scene_budget(
1809    budget: SceneBudget,
1810    requested: SceneStatistics,
1811) -> Result<(), SceneError> {
1812    let limits = [
1813        (
1814            SceneBudgetResource::Commands,
1815            budget.max_commands,
1816            requested.accepted_commands,
1817        ),
1818        (
1819            SceneBudgetResource::Points,
1820            budget.max_points,
1821            requested.retained_points,
1822        ),
1823        (
1824            SceneBudgetResource::TessellatedVertices,
1825            budget.max_tessellated_vertices,
1826            requested.estimated_tessellated_vertices,
1827        ),
1828        (
1829            SceneBudgetResource::RetainedBytes,
1830            budget.max_retained_bytes,
1831            requested.retained_bytes,
1832        ),
1833        // Actual allocation capacity is validated transactionally at the
1834        // insertion boundary, once the prospective Vec capacity is known.
1835        (
1836            SceneBudgetResource::UploadBytes,
1837            budget.max_upload_bytes,
1838            requested.estimated_upload_bytes,
1839        ),
1840        (
1841            SceneBudgetResource::DrawBatches,
1842            budget.max_draw_batches,
1843            requested.estimated_draw_batches,
1844        ),
1845    ];
1846    for (resource, limit, requested) in limits {
1847        if requested > limit {
1848            return Err(SceneError::BudgetExceeded {
1849                resource,
1850                limit,
1851                requested,
1852            });
1853        }
1854    }
1855    Ok(())
1856}
1857
1858fn scene_allocation_bytes(command_capacity: usize, owned_payload_bytes: usize) -> usize {
1859    command_capacity
1860        .saturating_mul(size_of::<SceneCommand>())
1861        .saturating_add(owned_payload_bytes)
1862}
1863
1864fn validate_scene_allocation_budget(
1865    budget: SceneBudget,
1866    command_capacity: usize,
1867    owned_payload_bytes: usize,
1868) -> Result<(), SceneError> {
1869    let requested = scene_allocation_bytes(command_capacity, owned_payload_bytes);
1870    if requested > budget.max_allocation_bytes {
1871        return Err(SceneError::BudgetExceeded {
1872            resource: SceneBudgetResource::AllocationBytes,
1873            limit: budget.max_allocation_bytes,
1874            requested,
1875        });
1876    }
1877    Ok(())
1878}
1879
1880fn budgeted_command_capacity(
1881    budget: SceneBudget,
1882    current_capacity: usize,
1883    required_len: usize,
1884    owned_payload_bytes: usize,
1885) -> Result<usize, SceneError> {
1886    let available = budget
1887        .max_allocation_bytes
1888        .saturating_sub(owned_payload_bytes);
1889    let maximum_capacity = available / size_of::<SceneCommand>();
1890    if required_len > maximum_capacity {
1891        return Err(SceneError::BudgetExceeded {
1892            resource: SceneBudgetResource::AllocationBytes,
1893            limit: budget.max_allocation_bytes,
1894            requested: scene_allocation_bytes(required_len, owned_payload_bytes),
1895        });
1896    }
1897    Ok(current_capacity
1898        .max(1)
1899        .saturating_mul(2)
1900        .max(required_len)
1901        .min(maximum_capacity))
1902}
1903
1904fn drawable_segment(from: Vec2, to: Vec2) -> bool {
1905    let delta = to - from;
1906    delta.is_finite() && (delta.x != 0.0 || delta.y != 0.0)
1907}
1908
1909/// Circle primitive in world coordinates.
1910#[derive(Debug, Clone)]
1911pub struct Circle {
1912    center: Vec2,
1913    radius: f32,
1914    style: ShapeStyle,
1915}
1916
1917impl Circle {
1918    /// Returns the center in world coordinates.
1919    pub const fn center(&self) -> Vec2 {
1920        self.center
1921    }
1922    /// Returns the radius in world units.
1923    pub const fn radius(&self) -> f32 {
1924        self.radius
1925    }
1926    /// Returns fill, stroke, and shadow styling.
1927    pub const fn style(&self) -> ShapeStyle {
1928        self.style
1929    }
1930}
1931
1932/// Axis-aligned rectangle primitive in world coordinates.
1933#[derive(Debug, Clone)]
1934pub struct RectShape {
1935    rect: Rect,
1936    corner_radius: f32,
1937    style: ShapeStyle,
1938}
1939
1940impl RectShape {
1941    /// Returns rectangle bounds in world coordinates.
1942    pub const fn rect(&self) -> Rect {
1943        self.rect
1944    }
1945    /// Returns corner radius in world units.
1946    pub const fn corner_radius(&self) -> f32 {
1947        self.corner_radius
1948    }
1949    /// Returns fill, stroke, and shadow styling.
1950    pub const fn style(&self) -> ShapeStyle {
1951        self.style
1952    }
1953}
1954
1955/// Stroked line primitive in world coordinates.
1956#[derive(Debug, Clone)]
1957pub struct Line {
1958    from: Vec2,
1959    to: Vec2,
1960    style: StrokeStyle2d,
1961}
1962
1963impl Line {
1964    /// Returns the start point in world coordinates.
1965    pub const fn from(&self) -> Vec2 {
1966        self.from
1967    }
1968    /// Returns the end point in world coordinates.
1969    pub const fn to(&self) -> Vec2 {
1970        self.to
1971    }
1972    /// Returns color and scalar width; inspect [`Self::stroke_style`] for units.
1973    pub const fn stroke(&self) -> Stroke {
1974        self.style.stroke
1975    }
1976    /// Returns the complete cap, join, dash, marker, and width-mode style.
1977    pub const fn stroke_style(&self) -> StrokeStyle2d {
1978        self.style
1979    }
1980}
1981
1982/// Connected line-strip primitive in world coordinates.
1983#[derive(Debug, Clone)]
1984pub struct Polyline {
1985    points: Vec<Vec2>,
1986    style: StrokeStyle2d,
1987}
1988
1989impl Polyline {
1990    /// Returns connected points in world coordinates.
1991    pub fn points(&self) -> &[Vec2] {
1992        &self.points
1993    }
1994    /// Returns color and scalar width; inspect [`Self::stroke_style`] for units.
1995    pub const fn stroke(&self) -> Stroke {
1996        self.style.stroke
1997    }
1998    /// Returns the complete cap, join, dash, marker, and width-mode style.
1999    pub const fn stroke_style(&self) -> StrokeStyle2d {
2000        self.style
2001    }
2002}
2003
2004/// Coordinate space used by a line or polyline stroke width.
2005#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2006pub enum StrokeWidthMode2d {
2007    /// Width remains constant in logical screen pixels while the camera zooms.
2008    LogicalPixels,
2009    /// Width is measured in the same world units as the path coordinates.
2010    WorldUnits,
2011}
2012
2013/// Presentation used at an open line or dash endpoint.
2014#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2015pub enum StrokeCap2d {
2016    /// Stop exactly at the endpoint.
2017    Butt,
2018    /// Extend by half the stroke width beyond the endpoint.
2019    Square,
2020    /// Add a semicircular endpoint.
2021    Round,
2022}
2023
2024/// Presentation used where two visible polyline segments meet.
2025#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2026pub enum StrokeJoin2d {
2027    /// Connect the two segment corners directly.
2028    Bevel,
2029    /// Fill the corner with a circular join.
2030    Round,
2031    /// Extend corner edges to their intersection, bounded by the style's
2032    /// miter limit and falling back to a bevel beyond it.
2033    Miter,
2034}
2035
2036/// Fixed-size, allocation-free dash pattern in source path-coordinate units.
2037///
2038/// Values alternate visible and hidden lengths, beginning with a visible
2039/// length. The element count must be even and at most eight. `phase` advances
2040/// into the repeating pattern in the same path units. `max_subsegments` is a
2041/// hard limit on visible pieces generated for one command.
2042#[derive(Debug, Clone, Copy, PartialEq)]
2043pub struct StrokeDashPattern2d {
2044    lengths: [f32; MAX_DASH_ELEMENTS],
2045    length_count: u8,
2046    phase: f32,
2047    max_subsegments: usize,
2048}
2049
2050impl StrokeDashPattern2d {
2051    /// Builds a bounded alternating visible/hidden dash pattern.
2052    pub fn new(
2053        lengths: &[f32],
2054        phase: f32,
2055        max_subsegments: usize,
2056    ) -> Result<Self, StrokeStyleError> {
2057        if lengths.len() < 2
2058            || lengths.len() > MAX_DASH_ELEMENTS
2059            || !lengths.len().is_multiple_of(2)
2060        {
2061            return Err(StrokeStyleError::InvalidDashElementCount);
2062        }
2063        if lengths
2064            .iter()
2065            .any(|length| !length.is_finite() || *length <= 0.0)
2066        {
2067            return Err(StrokeStyleError::InvalidDashLength);
2068        }
2069        if !phase.is_finite() {
2070            return Err(StrokeStyleError::InvalidDashPhase);
2071        }
2072        if max_subsegments == 0 || max_subsegments > MAX_STROKE_DASH_SUBSEGMENTS {
2073            return Err(StrokeStyleError::InvalidDashExpansionLimit);
2074        }
2075        let mut stored = [0.0; MAX_DASH_ELEMENTS];
2076        stored[..lengths.len()].copy_from_slice(lengths);
2077        Ok(Self {
2078            lengths: stored,
2079            length_count: lengths.len() as u8,
2080            phase,
2081            max_subsegments,
2082        })
2083    }
2084
2085    /// Returns the alternating visible/hidden lengths in path units.
2086    pub fn lengths(&self) -> &[f32] {
2087        &self.lengths[..usize::from(self.length_count)]
2088    }
2089
2090    /// Returns the repeating-pattern phase in path units.
2091    pub const fn phase(self) -> f32 {
2092        self.phase
2093    }
2094
2095    /// Returns the hard visible-subsegment expansion limit.
2096    pub const fn max_subsegments(self) -> usize {
2097        self.max_subsegments
2098    }
2099}
2100
2101/// Reusable arrow marker definition for a line endpoint.
2102///
2103/// Marker dimensions are logical pixels even when the line body uses a world
2104/// width, keeping scientific annotations readable under camera zoom. A marked
2105/// endpoint ignores the ordinary cap: the body ends with a butt boundary at
2106/// the path endpoint, which is also the marker base. The filled triangle grows
2107/// outward from the path, so markers remain interior-disjoint from arbitrarily
2108/// short, dashed, or camera-scaled terminal segments.
2109#[derive(Debug, Clone, Copy, PartialEq)]
2110pub struct StrokeMarker2d {
2111    length: LogicalPixels,
2112    width: LogicalPixels,
2113}
2114
2115impl StrokeMarker2d {
2116    /// Builds a filled triangular arrow marker.
2117    pub const fn arrow(length: LogicalPixels, width: LogicalPixels) -> Self {
2118        Self { length, width }
2119    }
2120
2121    /// Returns marker length along the endpoint tangent.
2122    pub const fn length(self) -> LogicalPixels {
2123        self.length
2124    }
2125
2126    /// Returns full marker width perpendicular to the endpoint tangent.
2127    pub const fn width(self) -> LogicalPixels {
2128        self.width
2129    }
2130}
2131
2132/// Complete bounded styling for open 2D lines and polylines.
2133#[derive(Debug, Clone, Copy, PartialEq)]
2134pub struct StrokeStyle2d {
2135    stroke: Stroke,
2136    width_mode: StrokeWidthMode2d,
2137    cap: StrokeCap2d,
2138    join: StrokeJoin2d,
2139    miter_limit: f32,
2140    dash: Option<StrokeDashPattern2d>,
2141    start_marker: Option<StrokeMarker2d>,
2142    end_marker: Option<StrokeMarker2d>,
2143}
2144
2145impl StrokeStyle2d {
2146    /// Builds the legacy logical-pixel round-cap joined-strip style.
2147    pub const fn new(width: f32, color: Color) -> Self {
2148        Self {
2149            stroke: Stroke::new(width, color),
2150            width_mode: StrokeWidthMode2d::LogicalPixels,
2151            cap: StrokeCap2d::Round,
2152            join: StrokeJoin2d::Miter,
2153            miter_limit: MAX_MITER_LIMIT,
2154            dash: None,
2155            start_marker: None,
2156            end_marker: None,
2157        }
2158    }
2159
2160    /// Builds a validated logical-pixel-width style.
2161    pub const fn logical(width: LogicalPixels, color: Color) -> Self {
2162        Self::new(width.get(), color)
2163    }
2164
2165    /// Builds a validated world-unit-width style.
2166    pub const fn world(width: WorldLength, color: Color) -> Self {
2167        let mut style = Self::new(width.get(), color);
2168        style.width_mode = StrokeWidthMode2d::WorldUnits;
2169        style
2170    }
2171
2172    /// Selects the open endpoint presentation.
2173    pub const fn with_cap(mut self, cap: StrokeCap2d) -> Self {
2174        self.cap = cap;
2175        self
2176    }
2177
2178    /// Selects the connected-segment presentation.
2179    pub const fn with_join(mut self, join: StrokeJoin2d) -> Self {
2180        self.join = join;
2181        self
2182    }
2183
2184    /// Sets the miter-length multiple in `1.0..=1000.0`.
2185    pub fn with_miter_limit(mut self, limit: f32) -> Result<Self, StrokeStyleError> {
2186        if !limit.is_finite() || !(1.0..=MAX_MITER_LIMIT).contains(&limit) {
2187            return Err(StrokeStyleError::InvalidMiterLimit);
2188        }
2189        self.miter_limit = limit;
2190        Ok(self)
2191    }
2192
2193    /// Applies an allocation-free bounded dash pattern.
2194    pub const fn with_dash_pattern(mut self, dash: StrokeDashPattern2d) -> Self {
2195        self.dash = Some(dash);
2196        self
2197    }
2198
2199    /// Adds an outward-pointing triangular marker based at the first path point.
2200    pub const fn with_start_marker(mut self, marker: StrokeMarker2d) -> Self {
2201        self.start_marker = Some(marker);
2202        self
2203    }
2204
2205    /// Adds an outward-pointing triangular marker based at the last path point.
2206    pub const fn with_end_marker(mut self, marker: StrokeMarker2d) -> Self {
2207        self.end_marker = Some(marker);
2208        self
2209    }
2210
2211    /// Returns color and scalar width.
2212    pub const fn stroke(self) -> Stroke {
2213        self.stroke
2214    }
2215
2216    /// Returns whether width is logical-screen or world-space.
2217    pub const fn width_mode(self) -> StrokeWidthMode2d {
2218        self.width_mode
2219    }
2220
2221    /// Returns endpoint presentation.
2222    pub const fn cap(self) -> StrokeCap2d {
2223        self.cap
2224    }
2225
2226    /// Returns connected-segment presentation.
2227    pub const fn join(self) -> StrokeJoin2d {
2228        self.join
2229    }
2230
2231    /// Returns the bounded miter multiple.
2232    pub const fn miter_limit(self) -> f32 {
2233        self.miter_limit
2234    }
2235
2236    /// Returns the optional bounded dash pattern.
2237    pub const fn dash_pattern(self) -> Option<StrokeDashPattern2d> {
2238        self.dash
2239    }
2240
2241    /// Returns the optional first-endpoint marker.
2242    pub const fn start_marker(self) -> Option<StrokeMarker2d> {
2243        self.start_marker
2244    }
2245
2246    /// Returns the optional last-endpoint marker.
2247    pub const fn end_marker(self) -> Option<StrokeMarker2d> {
2248        self.end_marker
2249    }
2250
2251    fn is_valid(self) -> bool {
2252        self.stroke.is_valid()
2253            && self.miter_limit.is_finite()
2254            && (1.0..=MAX_MITER_LIMIT).contains(&self.miter_limit)
2255    }
2256}
2257
2258/// Invalid bounded line-style configuration.
2259#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2260pub enum StrokeStyleError {
2261    /// Dash patterns require an even count from two through eight.
2262    InvalidDashElementCount,
2263    /// Every dash and gap length must be positive and finite.
2264    InvalidDashLength,
2265    /// Dash phase must be finite.
2266    InvalidDashPhase,
2267    /// Dash expansion limit must be in `1..=1_000_000`.
2268    InvalidDashExpansionLimit,
2269    /// Miter limit must be finite and in `1.0..=1000.0`.
2270    InvalidMiterLimit,
2271}
2272
2273impl fmt::Display for StrokeStyleError {
2274    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2275        write!(formatter, "invalid bounded 2D stroke style: {self:?}")
2276    }
2277}
2278
2279impl Error for StrokeStyleError {}
2280
2281/// Fill, stroke, and shadow styling for solid primitives.
2282#[derive(Debug, Clone, Copy, PartialEq)]
2283pub struct ShapeStyle {
2284    fill: Option<Fill>,
2285    stroke: Option<Stroke>,
2286    shadow: Option<Shadow>,
2287}
2288
2289impl ShapeStyle {
2290    /// Builds explicit fill, stroke, and shadow choices.
2291    pub const fn new(fill: Option<Fill>, stroke: Option<Stroke>, shadow: Option<Shadow>) -> Self {
2292        Self {
2293            fill,
2294            stroke,
2295            shadow,
2296        }
2297    }
2298
2299    /// Returns fill paint, if any.
2300    pub const fn fill(self) -> Option<Fill> {
2301        self.fill
2302    }
2303    /// Returns outline stroke, if any.
2304    pub const fn stroke(self) -> Option<Stroke> {
2305        self.stroke
2306    }
2307    /// Returns shadow styling, if any.
2308    pub const fn shadow(self) -> Option<Shadow> {
2309        self.shadow
2310    }
2311    /// Creates a style with fill color only.
2312    pub fn filled(color: Color) -> Self {
2313        Self::filled_with(Fill::Solid(color))
2314    }
2315
2316    /// Creates a style with fill paint only.
2317    pub fn filled_with(fill: Fill) -> Self {
2318        Self {
2319            fill: Some(fill),
2320            stroke: None,
2321            shadow: None,
2322        }
2323    }
2324
2325    /// Creates a style with stroke only.
2326    ///
2327    /// `width` is in logical screen pixels.
2328    pub fn stroked(width: f32, color: Color) -> Self {
2329        Self {
2330            fill: None,
2331            stroke: Some(Stroke { width, color }),
2332            shadow: None,
2333        }
2334    }
2335
2336    /// Creates a style with both fill and stroke.
2337    ///
2338    /// `stroke_width` is in logical screen pixels.
2339    pub fn fill_stroke(fill: Color, stroke_width: f32, stroke: Color) -> Self {
2340        Self::fill_stroke_with(Fill::Solid(fill), stroke_width, stroke)
2341    }
2342
2343    /// Creates a style with both fill paint and stroke.
2344    ///
2345    /// `stroke_width` is in logical screen pixels.
2346    pub fn fill_stroke_with(fill: Fill, stroke_width: f32, stroke: Color) -> Self {
2347        Self {
2348            fill: Some(fill),
2349            stroke: Some(Stroke {
2350                width: stroke_width,
2351                color: stroke,
2352            }),
2353            shadow: None,
2354        }
2355    }
2356
2357    /// Adds a shadow to the style.
2358    pub fn with_shadow(mut self, shadow: Shadow) -> Self {
2359        self.shadow = Some(shadow);
2360        self
2361    }
2362
2363    fn validate(self, primitive: ScenePrimitive) -> Result<(), SceneError> {
2364        if self.fill.is_none() && self.stroke.is_none() && self.shadow.is_none() {
2365            return Err(SceneError::MissingStyle(primitive));
2366        }
2367        if self.fill.is_some_and(|fill| !fill.is_valid()) {
2368            return Err(SceneError::InvalidFill(primitive));
2369        }
2370        if self.stroke.is_some_and(|stroke| !stroke.is_valid()) {
2371            return Err(SceneError::InvalidStroke(primitive));
2372        }
2373        if self.shadow.is_some_and(|shadow| !shadow.is_valid()) {
2374            return Err(SceneError::InvalidShadow(primitive));
2375        }
2376        Ok(())
2377    }
2378}
2379
2380/// Paint used to fill a shape.
2381///
2382/// Gradient coordinates are in world units. Renderers may approximate gradients
2383/// per vertex until a more advanced shader path exists.
2384#[derive(Debug, Clone, Copy, PartialEq)]
2385pub enum Fill {
2386    /// Single color over the whole shape.
2387    Solid(Color),
2388    /// Color interpolation along a world-space axis.
2389    LinearGradient(LinearGradient),
2390    /// Color interpolation outward from a world-space center.
2391    RadialGradient(RadialGradient),
2392}
2393
2394impl Fill {
2395    /// Returns the color at a world-space point.
2396    ///
2397    /// Degenerate gradients fall back to their end color rather than producing
2398    /// NaN.
2399    pub fn color_at(self, world: Vec2) -> Color {
2400        self.color_at_with_offset(world, Vec2::ZERO)
2401    }
2402
2403    pub(crate) fn color_at_with_offset(self, world_base: Vec2, world_offset: Vec2) -> Color {
2404        match self {
2405            Self::Solid(color) => color,
2406            Self::LinearGradient(gradient) => {
2407                gradient.color_at_with_offset(world_base, world_offset)
2408            }
2409            Self::RadialGradient(gradient) => {
2410                gradient.color_at_with_offset(world_base, world_offset)
2411            }
2412        }
2413    }
2414
2415    fn is_valid(self) -> bool {
2416        match self {
2417            Self::Solid(color) => color.is_normalized(),
2418            Self::LinearGradient(gradient) => gradient.is_valid(),
2419            Self::RadialGradient(gradient) => gradient.is_valid(),
2420        }
2421    }
2422}
2423
2424impl From<Color> for Fill {
2425    fn from(color: Color) -> Self {
2426        Self::Solid(color)
2427    }
2428}
2429
2430/// Linear color gradient in world coordinates.
2431#[derive(Debug, Clone, Copy, PartialEq)]
2432pub struct LinearGradient {
2433    start: Vec2,
2434    end: Vec2,
2435    start_color: Color,
2436    end_color: Color,
2437}
2438
2439impl LinearGradient {
2440    /// Builds a linear gradient between two world-space points.
2441    pub fn new(start: Vec2, end: Vec2, start_color: Color, end_color: Color) -> Self {
2442        Self {
2443            start,
2444            end,
2445            start_color,
2446            end_color,
2447        }
2448    }
2449
2450    /// Returns the world-space gradient start.
2451    pub const fn start(self) -> Vec2 {
2452        self.start
2453    }
2454    /// Returns the world-space gradient end.
2455    pub const fn end(self) -> Vec2 {
2456        self.end
2457    }
2458    /// Returns the color at the start.
2459    pub const fn start_color(self) -> Color {
2460        self.start_color
2461    }
2462    /// Returns the color at the end.
2463    pub const fn end_color(self) -> Color {
2464        self.end_color
2465    }
2466
2467    /// Samples the gradient at a world-space point.
2468    pub fn color_at(self, world: Vec2) -> Color {
2469        self.color_at_with_offset(world, Vec2::ZERO)
2470    }
2471
2472    fn color_at_with_offset(self, world_base: Vec2, world_offset: Vec2) -> Color {
2473        if !self.is_valid() || !world_base.is_finite() || !world_offset.is_finite() {
2474            return self.end_color.clamp();
2475        }
2476
2477        let axis_x = f64::from(self.end.x) - f64::from(self.start.x);
2478        let axis_y = f64::from(self.end.y) - f64::from(self.start.y);
2479        let relative_x =
2480            f64::from(world_base.x) - f64::from(self.start.x) + f64::from(world_offset.x);
2481        let relative_y =
2482            f64::from(world_base.y) - f64::from(self.start.y) + f64::from(world_offset.y);
2483        let axis_length_squared = axis_x * axis_x + axis_y * axis_y;
2484        let amount = ((relative_x * axis_x + relative_y * axis_y) / axis_length_squared)
2485            .clamp(0.0, 1.0) as f32;
2486        self.start_color.interpolate(self.end_color, amount)
2487    }
2488
2489    fn is_valid(self) -> bool {
2490        self.start.is_finite()
2491            && self.end.is_finite()
2492            && self.start_color.is_normalized()
2493            && self.end_color.is_normalized()
2494            && self.start != self.end
2495    }
2496}
2497
2498/// Radial color gradient in world coordinates.
2499#[derive(Debug, Clone, Copy, PartialEq)]
2500pub struct RadialGradient {
2501    /// Center point in world coordinates.
2502    center: Vec2,
2503    /// Radius where `inner_color` is reached, in world units.
2504    inner_radius: f32,
2505    /// Radius where `outer_color` is reached, in world units.
2506    outer_radius: f32,
2507    /// Color at or inside `inner_radius`.
2508    inner_color: Color,
2509    /// Color at or outside `outer_radius`.
2510    outer_color: Color,
2511}
2512
2513impl RadialGradient {
2514    /// Builds a radial gradient in world coordinates.
2515    ///
2516    /// Reversed finite radii are normalized together with their colors so the
2517    /// color attached to each radius remains stable.
2518    pub fn new(
2519        center: Vec2,
2520        inner_radius: f32,
2521        outer_radius: f32,
2522        inner_color: Color,
2523        outer_color: Color,
2524    ) -> Self {
2525        if inner_radius.is_finite() && outer_radius.is_finite() && inner_radius > outer_radius {
2526            Self {
2527                center,
2528                inner_radius: outer_radius,
2529                outer_radius: inner_radius,
2530                inner_color: outer_color,
2531                outer_color: inner_color,
2532            }
2533        } else {
2534            Self {
2535                center,
2536                inner_radius,
2537                outer_radius,
2538                inner_color,
2539                outer_color,
2540            }
2541        }
2542    }
2543
2544    /// Returns the world-space gradient center.
2545    pub const fn center(self) -> Vec2 {
2546        self.center
2547    }
2548
2549    /// Returns the inner radius in world units.
2550    pub const fn inner_radius(self) -> f32 {
2551        self.inner_radius
2552    }
2553
2554    /// Returns the outer radius in world units.
2555    pub const fn outer_radius(self) -> f32 {
2556        self.outer_radius
2557    }
2558
2559    /// Returns the inner linear color.
2560    pub const fn inner_color(self) -> Color {
2561        self.inner_color
2562    }
2563
2564    /// Returns the outer linear color.
2565    pub const fn outer_color(self) -> Color {
2566        self.outer_color
2567    }
2568
2569    /// Samples the gradient at a world-space point.
2570    pub fn color_at(self, world: Vec2) -> Color {
2571        self.color_at_with_offset(world, Vec2::ZERO)
2572    }
2573
2574    fn color_at_with_offset(self, world_base: Vec2, world_offset: Vec2) -> Color {
2575        if !self.is_valid() || !world_base.is_finite() || !world_offset.is_finite() {
2576            return self.outer_color.clamp();
2577        }
2578
2579        let radius_range = self.outer_radius - self.inner_radius;
2580        if radius_range == 0.0 {
2581            return self.outer_color;
2582        }
2583
2584        let horizontal =
2585            f64::from(world_base.x) - f64::from(self.center.x) + f64::from(world_offset.x);
2586        let vertical =
2587            f64::from(world_base.y) - f64::from(self.center.y) + f64::from(world_offset.y);
2588        let distance = horizontal.hypot(vertical);
2589        let amount = ((distance - f64::from(self.inner_radius)) / f64::from(radius_range))
2590            .clamp(0.0, 1.0) as f32;
2591        self.inner_color.interpolate(self.outer_color, amount)
2592    }
2593
2594    fn is_valid(self) -> bool {
2595        self.center.is_finite()
2596            && self.inner_radius.is_finite()
2597            && self.outer_radius.is_finite()
2598            && self.inner_radius >= 0.0
2599            && self.outer_radius >= self.inner_radius
2600            && self.inner_color.is_normalized()
2601            && self.outer_color.is_normalized()
2602    }
2603}
2604
2605/// Stroke color and width for lines and shape outlines.
2606#[derive(Debug, Clone, Copy, PartialEq)]
2607pub struct Stroke {
2608    width: f32,
2609    color: Color,
2610}
2611
2612impl Stroke {
2613    /// Builds a stroke used by shape outlines and legacy logical-width lines.
2614    ///
2615    /// [`StrokeStyle2d::world`] reuses the same scalar/color value while making
2616    /// the width's coordinate space explicit on the containing style.
2617    pub const fn new(width: f32, color: Color) -> Self {
2618        Self { width, color }
2619    }
2620    /// Returns scalar width in the coordinate space selected by its owner.
2621    pub const fn width(self) -> f32 {
2622        self.width
2623    }
2624    /// Returns the stroke color.
2625    pub const fn color(self) -> Color {
2626        self.color
2627    }
2628    fn is_valid(self) -> bool {
2629        self.width.is_finite() && self.width > 0.0 && self.color.is_normalized()
2630    }
2631}
2632
2633/// Simple screen-space shadow used by the first renderer slice.
2634#[derive(Debug, Clone, Copy, PartialEq)]
2635pub struct Shadow {
2636    offset: LogicalScreenVector,
2637    spread: f32,
2638    color: Color,
2639}
2640
2641impl Shadow {
2642    /// Builds a shadow from logical screen-space offset, spread, and color.
2643    pub fn new(offset: LogicalScreenVector, spread: f32, color: Color) -> Self {
2644        Self {
2645            offset,
2646            spread,
2647            color,
2648        }
2649    }
2650
2651    /// Returns the logical-pixel shadow offset.
2652    pub const fn offset(self) -> LogicalScreenVector {
2653        self.offset
2654    }
2655    /// Returns extra logical-pixel spread.
2656    pub const fn spread(self) -> f32 {
2657        self.spread
2658    }
2659    /// Returns the shadow color.
2660    pub const fn color(self) -> Color {
2661        self.color
2662    }
2663
2664    fn is_valid(self) -> bool {
2665        self.offset.is_finite()
2666            && self.spread.is_finite()
2667            && self.spread >= 0.0
2668            && (self.spread * 2.0).is_finite()
2669            && self.color.is_normalized()
2670    }
2671}
2672
2673#[cfg(test)]
2674mod tests {
2675    use std::panic::{AssertUnwindSafe, catch_unwind};
2676
2677    use super::MAX_STROKE_DASH_SUBSEGMENTS;
2678    use crate::{
2679        Color, DrawCommand, Fill, Layer, LinearGradient, LogicalScreenPosition,
2680        LogicalScreenVector, RadialGradient, Rect, Scene, SceneBudget, SceneBudgetResource,
2681        SceneCommand, SceneError, ScenePrimitive, ScreenClipRect, ShapeStyle, StrokeCap2d,
2682        StrokeDashPattern2d, StrokeJoin2d, StrokeMarker2d, StrokeStyle2d, StrokeStyleError, Vec2,
2683    };
2684    use crate::{LogicalPixels, WorldLength};
2685
2686    const UNLIMITED: usize = usize::MAX;
2687
2688    const fn budget_for(
2689        commands: usize,
2690        points: usize,
2691        vertices: usize,
2692        retained_bytes: usize,
2693        upload_bytes: usize,
2694        batches: usize,
2695    ) -> SceneBudget {
2696        SceneBudget::new(
2697            commands,
2698            points,
2699            vertices,
2700            retained_bytes,
2701            UNLIMITED,
2702            upload_bytes,
2703            batches,
2704        )
2705    }
2706
2707    #[test]
2708    fn scene_collects_visual_commands_only() {
2709        let mut scene = Scene::new(Color::BLACK).unwrap();
2710        scene.circle(Vec2::ZERO, 10.0, ShapeStyle::filled(Color::WHITE));
2711
2712        assert_eq!(scene.commands.len(), 1);
2713    }
2714
2715    #[test]
2716    fn scene_keeps_commands_sorted_by_layer() {
2717        let mut scene = Scene::new(Color::BLACK).unwrap();
2718        scene.circle_on_layer(
2719            Layer::FOREGROUND,
2720            Vec2::ZERO,
2721            10.0,
2722            ShapeStyle::filled(Color::WHITE),
2723        );
2724        scene.line_on_layer(Layer::BACKGROUND, Vec2::ZERO, Vec2::X, 1.0, Color::WHITE);
2725
2726        assert!(matches!(scene.commands[0].command, DrawCommand::Line(_)));
2727        assert!(matches!(scene.commands[1].command, DrawCommand::Circle(_)));
2728    }
2729
2730    #[test]
2731    fn scene_budget_rejection_is_atomic_and_counted() {
2732        let budget = budget_for(1, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED);
2733        let mut scene = Scene::with_budget(Color::BLACK, budget).unwrap();
2734        scene
2735            .try_circle(Vec2::new(1.0, 2.0), 3.0, ShapeStyle::filled(Color::WHITE))
2736            .unwrap();
2737
2738        let before_order = scene.commands()[0].order();
2739        let result = scene.try_circle(Vec2::new(4.0, 5.0), 6.0, ShapeStyle::filled(Color::WHITE));
2740
2741        assert_eq!(
2742            result,
2743            Err(SceneError::BudgetExceeded {
2744                resource: SceneBudgetResource::Commands,
2745                limit: 1,
2746                requested: 2,
2747            })
2748        );
2749        assert_eq!(scene.command_count(), 1);
2750        assert_eq!(scene.commands()[0].order(), before_order);
2751        assert_eq!(scene.statistics().requested_commands(), 2);
2752        assert_eq!(scene.statistics().accepted_commands(), 1);
2753        assert_eq!(scene.statistics().rejected_commands(), 1);
2754    }
2755
2756    #[test]
2757    fn scene_budget_enforces_every_resource_at_insertion() {
2758        let mut reference = Scene::new(Color::BLACK).unwrap();
2759        reference
2760            .try_polyline(
2761                vec![Vec2::ZERO, Vec2::X, Vec2::new(1.0, 1.0)],
2762                2.0,
2763                Color::WHITE,
2764            )
2765            .unwrap();
2766        let usage = reference.statistics();
2767        let cases = [
2768            (
2769                SceneBudgetResource::Points,
2770                budget_for(
2771                    UNLIMITED,
2772                    usage.retained_points() - 1,
2773                    UNLIMITED,
2774                    UNLIMITED,
2775                    UNLIMITED,
2776                    UNLIMITED,
2777                ),
2778                usage.retained_points(),
2779            ),
2780            (
2781                SceneBudgetResource::TessellatedVertices,
2782                budget_for(
2783                    UNLIMITED,
2784                    UNLIMITED,
2785                    usage.estimated_tessellated_vertices() - 1,
2786                    UNLIMITED,
2787                    UNLIMITED,
2788                    UNLIMITED,
2789                ),
2790                usage.estimated_tessellated_vertices(),
2791            ),
2792            (
2793                SceneBudgetResource::RetainedBytes,
2794                budget_for(
2795                    UNLIMITED,
2796                    UNLIMITED,
2797                    UNLIMITED,
2798                    usage.retained_bytes() - 1,
2799                    UNLIMITED,
2800                    UNLIMITED,
2801                ),
2802                usage.retained_bytes(),
2803            ),
2804            (
2805                SceneBudgetResource::UploadBytes,
2806                budget_for(
2807                    UNLIMITED,
2808                    UNLIMITED,
2809                    UNLIMITED,
2810                    UNLIMITED,
2811                    usage.estimated_upload_bytes() - 1,
2812                    UNLIMITED,
2813                ),
2814                usage.estimated_upload_bytes(),
2815            ),
2816            (
2817                SceneBudgetResource::DrawBatches,
2818                budget_for(
2819                    UNLIMITED,
2820                    UNLIMITED,
2821                    UNLIMITED,
2822                    UNLIMITED,
2823                    UNLIMITED,
2824                    usage.estimated_draw_batches() - 1,
2825                ),
2826                usage.estimated_draw_batches(),
2827            ),
2828        ];
2829
2830        for (resource, budget, requested) in cases {
2831            let mut scene = Scene::with_budget(Color::BLACK, budget).unwrap();
2832            let result = scene.try_polyline(
2833                vec![Vec2::ZERO, Vec2::X, Vec2::new(1.0, 1.0)],
2834                2.0,
2835                Color::WHITE,
2836            );
2837            assert_eq!(
2838                result,
2839                Err(SceneError::BudgetExceeded {
2840                    resource,
2841                    limit: requested - 1,
2842                    requested,
2843                })
2844            );
2845            assert_eq!(scene.command_count(), 0);
2846            assert_eq!(scene.statistics().accepted_commands(), 0);
2847            assert_eq!(scene.statistics().rejected_commands(), 1);
2848        }
2849    }
2850
2851    #[test]
2852    fn exact_scene_budget_is_accepted_and_clear_preserves_limits() {
2853        let mut reference = Scene::new(Color::BLACK).unwrap();
2854        reference
2855            .try_line(Vec2::ZERO, Vec2::X, 2.0, Color::WHITE)
2856            .unwrap();
2857        let usage = reference.statistics();
2858        let budget = budget_for(
2859            usage.accepted_commands(),
2860            usage.retained_points(),
2861            usage.estimated_tessellated_vertices(),
2862            usage.retained_bytes(),
2863            usage.estimated_upload_bytes(),
2864            usage.estimated_draw_batches(),
2865        );
2866        let mut scene = Scene::with_budget(Color::BLACK, budget).unwrap();
2867
2868        scene
2869            .try_line(Vec2::ZERO, Vec2::X, 2.0, Color::WHITE)
2870            .unwrap();
2871        assert_eq!(scene.statistics(), usage);
2872        scene.clear();
2873
2874        assert_eq!(scene.budget(), Some(budget));
2875        assert_eq!(scene.statistics(), Default::default());
2876        assert_eq!(scene.command_count(), 0);
2877    }
2878
2879    #[test]
2880    fn scene_allocation_budget_bounds_spare_command_capacity_atomically() {
2881        let command_bytes = size_of::<SceneCommand>();
2882        let too_small = SceneBudget::new(
2883            1,
2884            UNLIMITED,
2885            UNLIMITED,
2886            command_bytes,
2887            command_bytes - 1,
2888            UNLIMITED,
2889            UNLIMITED,
2890        );
2891        let mut rejected = Scene::with_budget(Color::BLACK, too_small).unwrap();
2892        let error = rejected
2893            .try_circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE))
2894            .unwrap_err();
2895        assert!(matches!(
2896            error,
2897            SceneError::BudgetExceeded {
2898                resource: SceneBudgetResource::AllocationBytes,
2899                limit,
2900                requested,
2901            } if limit == command_bytes - 1 && requested >= command_bytes
2902        ));
2903        assert_eq!(rejected.command_count(), 0);
2904        assert_eq!(rejected.allocation_bytes(), 0);
2905
2906        let bounded = SceneBudget::new(
2907            4,
2908            UNLIMITED,
2909            UNLIMITED,
2910            4 * command_bytes,
2911            4 * command_bytes,
2912            UNLIMITED,
2913            UNLIMITED,
2914        );
2915        let mut scene = Scene::with_budget(Color::BLACK, bounded).unwrap();
2916        scene
2917            .try_circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE))
2918            .unwrap();
2919        assert!(scene.allocation_bytes() <= bounded.max_allocation_bytes());
2920        scene.clear();
2921        assert!(scene.allocation_bytes() <= bounded.max_allocation_bytes());
2922    }
2923
2924    #[test]
2925    fn batch_allocation_budget_rejects_before_consuming_unbounded_input() {
2926        let budget = SceneBudget::new(
2927            usize::MAX,
2928            UNLIMITED,
2929            UNLIMITED,
2930            UNLIMITED,
2931            1,
2932            UNLIMITED,
2933            UNLIMITED,
2934        );
2935        let mut scene = Scene::with_budget(Color::BLACK, budget).unwrap();
2936        let consumed = std::cell::Cell::new(0usize);
2937        let command =
2938            DrawCommand::circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE)).unwrap();
2939        let commands = std::iter::from_fn(|| {
2940            consumed.set(consumed.get().saturating_add(1));
2941            Some((Layer::DEFAULT, command.clone()))
2942        });
2943
2944        assert!(matches!(
2945            scene.try_extend_to_layers(commands),
2946            Err(SceneError::BudgetExceeded {
2947                resource: SceneBudgetResource::AllocationBytes,
2948                limit: 1,
2949                ..
2950            })
2951        ));
2952        assert_eq!(consumed.get(), 1);
2953        assert_eq!(scene.command_count(), 0);
2954        assert_eq!(scene.allocation_bytes(), 0);
2955    }
2956
2957    #[test]
2958    fn batch_insertion_sorts_once_and_is_atomic_on_budget_failure() {
2959        let budget = budget_for(4, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED);
2960        let mut scene = Scene::with_budget(Color::BLACK, budget).unwrap();
2961        scene
2962            .try_extend_to_layers([
2963                (
2964                    Layer::FOREGROUND,
2965                    DrawCommand::circle(Vec2::new(1.0, 0.0), 1.0, ShapeStyle::filled(Color::WHITE))
2966                        .unwrap(),
2967                ),
2968                (
2969                    Layer::BACKGROUND,
2970                    DrawCommand::line(Vec2::ZERO, Vec2::X, 1.0, Color::WHITE).unwrap(),
2971                ),
2972                (
2973                    Layer::FOREGROUND,
2974                    DrawCommand::circle(Vec2::new(2.0, 0.0), 1.0, ShapeStyle::filled(Color::WHITE))
2975                        .unwrap(),
2976                ),
2977            ])
2978            .unwrap();
2979
2980        assert_eq!(scene.command_count(), 3);
2981        assert_eq!(scene.commands()[0].layer(), Layer::BACKGROUND);
2982        assert_eq!(scene.commands()[1].order(), 0);
2983        assert_eq!(scene.commands()[2].order(), 2);
2984
2985        let result = scene.try_extend_to_layers([
2986            (
2987                Layer::DEFAULT,
2988                DrawCommand::circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE)).unwrap(),
2989            ),
2990            (
2991                Layer::DEFAULT,
2992                DrawCommand::circle(Vec2::X, 1.0, ShapeStyle::filled(Color::WHITE)).unwrap(),
2993            ),
2994        ]);
2995        assert_eq!(
2996            result,
2997            Err(SceneError::BudgetExceeded {
2998                resource: SceneBudgetResource::Commands,
2999                limit: 4,
3000                requested: 5,
3001            })
3002        );
3003        assert_eq!(scene.command_count(), 3);
3004        assert_eq!(scene.statistics().requested_commands(), 5);
3005        assert_eq!(scene.statistics().accepted_commands(), 3);
3006        assert_eq!(scene.statistics().rejected_commands(), 2);
3007    }
3008
3009    #[test]
3010    fn linear_gradient_samples_along_axis() {
3011        let gradient = LinearGradient::new(Vec2::ZERO, Vec2::X, Color::BLACK, Color::WHITE);
3012
3013        let sampled = Fill::LinearGradient(gradient).color_at(Vec2::new(0.5, 4.0));
3014
3015        assert!((sampled.red() - 0.5).abs() < 0.001);
3016        assert!((sampled.green() - 0.5).abs() < 0.001);
3017        assert!((sampled.blue() - 0.5).abs() < 0.001);
3018    }
3019
3020    #[test]
3021    fn extreme_gradients_sample_without_f32_overflow() {
3022        let gradient = LinearGradient::new(
3023            Vec2::new(-f32::MAX, 0.0),
3024            Vec2::new(f32::MAX, 0.0),
3025            Color::BLACK,
3026            Color::WHITE,
3027        );
3028        let mut scene = Scene::new(Color::BLACK).unwrap();
3029
3030        assert!(
3031            scene
3032                .try_circle(
3033                    Vec2::ZERO,
3034                    1.0,
3035                    ShapeStyle::filled_with(Fill::LinearGradient(gradient)),
3036                )
3037                .is_ok()
3038        );
3039        assert_eq!(
3040            gradient.color_at(Vec2::ZERO),
3041            Color::rgba(0.5, 0.5, 0.5, 1.0)
3042        );
3043
3044        let radial = RadialGradient::new(
3045            Vec2::splat(f32::MAX),
3046            0.0,
3047            f32::MAX,
3048            Color::BLACK,
3049            Color::WHITE,
3050        );
3051        assert_eq!(radial.color_at(Vec2::splat(-f32::MAX)), Color::WHITE);
3052    }
3053
3054    #[test]
3055    fn overflowing_circle_and_shadow_are_rejected_at_scene_boundary() {
3056        let mut scene = Scene::new(Color::BLACK).unwrap();
3057        assert_eq!(
3058            scene.try_circle(
3059                Vec2::splat(f32::MAX),
3060                f32::MAX,
3061                ShapeStyle::filled(Color::WHITE),
3062            ),
3063            Err(SceneError::NonFiniteGeometry(ScenePrimitive::Circle))
3064        );
3065        assert_eq!(
3066            scene.try_circle(
3067                Vec2::ZERO,
3068                1.0,
3069                ShapeStyle::filled(Color::WHITE).with_shadow(super::Shadow::new(
3070                    LogicalScreenVector::new(0.0, 0.0),
3071                    f32::MAX,
3072                    Color::WHITE,
3073                )),
3074            ),
3075            Err(SceneError::InvalidShadow(ScenePrimitive::Circle))
3076        );
3077        assert_eq!(
3078            scene.try_line(
3079                Vec2::new(-f32::MAX, 0.0),
3080                Vec2::new(f32::MAX, 0.0),
3081                1.0,
3082                Color::WHITE,
3083            ),
3084            Err(SceneError::NonFiniteGeometry(ScenePrimitive::Line))
3085        );
3086        assert_eq!(
3087            scene.try_rect(
3088                Rect::new(Vec2::new(-f32::MAX, 0.0), Vec2::new(f32::MAX, 1.0),),
3089                0.0,
3090                ShapeStyle::filled(Color::WHITE),
3091            ),
3092            Err(SceneError::NonFiniteGeometry(ScenePrimitive::Rect))
3093        );
3094    }
3095
3096    #[test]
3097    fn commands_capture_temporary_screen_clip() {
3098        let mut scene = Scene::new(Color::BLACK).unwrap();
3099        let outer = ScreenClipRect::from_min_size(
3100            LogicalScreenPosition::new(10.0, 20.0),
3101            LogicalScreenVector::new(100.0, 80.0),
3102        )
3103        .unwrap();
3104        let inner = ScreenClipRect::from_min_size(
3105            LogicalScreenPosition::new(50.0, 0.0),
3106            LogicalScreenVector::new(100.0, 50.0),
3107        )
3108        .unwrap();
3109
3110        scene
3111            .with_screen_clip(outer, |scene| {
3112                scene
3113                    .with_screen_clip(inner, |scene| {
3114                        scene.circle(Vec2::ZERO, 10.0, ShapeStyle::filled(Color::WHITE));
3115                    })
3116                    .unwrap();
3117            })
3118            .unwrap();
3119        scene.circle(Vec2::ZERO, 10.0, ShapeStyle::filled(Color::WHITE));
3120
3121        assert_eq!(
3122            scene.commands[0].screen_clip,
3123            Some(
3124                ScreenClipRect::new(
3125                    LogicalScreenPosition::new(50.0, 20.0),
3126                    LogicalScreenPosition::new(110.0, 50.0),
3127                )
3128                .unwrap(),
3129            )
3130        );
3131        assert_eq!(scene.commands[1].screen_clip, None);
3132    }
3133
3134    #[test]
3135    fn scene_rejects_invalid_primitives_before_ordering() {
3136        let mut scene = Scene::new(Color::BLACK).unwrap();
3137
3138        assert!(!scene.circle(Vec2::ZERO, -1.0, ShapeStyle::filled(Color::WHITE)));
3139        assert!(!scene.line(Vec2::ZERO, Vec2::X, f32::NAN, Color::WHITE));
3140        assert!(!scene.polyline(vec![Vec2::ZERO], 1.0, Color::WHITE));
3141        assert_eq!(scene.command_count(), 0);
3142
3143        assert!(scene.circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE)));
3144        assert_eq!(scene.commands()[0].order(), 0);
3145    }
3146
3147    #[test]
3148    fn bounded_stroke_configuration_rejects_invalid_patterns_and_miters() {
3149        assert_eq!(
3150            StrokeDashPattern2d::new(&[1.0], 0.0, 4),
3151            Err(StrokeStyleError::InvalidDashElementCount)
3152        );
3153        assert_eq!(
3154            StrokeDashPattern2d::new(&[1.0, 0.0], 0.0, 4),
3155            Err(StrokeStyleError::InvalidDashLength)
3156        );
3157        assert_eq!(
3158            StrokeDashPattern2d::new(&[1.0, 1.0], f32::NAN, 4),
3159            Err(StrokeStyleError::InvalidDashPhase)
3160        );
3161        assert_eq!(
3162            StrokeDashPattern2d::new(&[1.0, 1.0], 0.0, 0),
3163            Err(StrokeStyleError::InvalidDashExpansionLimit)
3164        );
3165        assert_eq!(
3166            StrokeDashPattern2d::new(&[1.0, 1.0], 0.0, MAX_STROKE_DASH_SUBSEGMENTS + 1,),
3167            Err(StrokeStyleError::InvalidDashExpansionLimit)
3168        );
3169        assert_eq!(
3170            StrokeStyle2d::logical(LogicalPixels::new(2.0).unwrap(), Color::WHITE)
3171                .with_miter_limit(0.5),
3172            Err(StrokeStyleError::InvalidMiterLimit)
3173        );
3174    }
3175
3176    #[test]
3177    fn dash_boundaries_must_be_representable_at_the_source_coordinate_scale() {
3178        let dash =
3179            StrokeDashPattern2d::new(&[f32::MIN_POSITIVE, f32::MIN_POSITIVE], 0.0, 8).unwrap();
3180        let style = StrokeStyle2d::logical(LogicalPixels::new(1.0).unwrap(), Color::WHITE)
3181            .with_dash_pattern(dash);
3182
3183        assert!(matches!(
3184            DrawCommand::styled_line(Vec2::ZERO, Vec2::new(f32::MAX, 0.0), style),
3185            Err(SceneError::UnrepresentableStrokePattern(
3186                ScenePrimitive::Line,
3187            ))
3188        ));
3189    }
3190
3191    #[test]
3192    fn dash_expansion_is_rejected_atomically_at_the_scene_boundary() {
3193        let dash = StrokeDashPattern2d::new(&[2.0, 2.0], 0.0, 2).unwrap();
3194        let style = StrokeStyle2d::logical(LogicalPixels::new(2.0).unwrap(), Color::WHITE)
3195            .with_cap(StrokeCap2d::Butt)
3196            .with_dash_pattern(dash);
3197        let mut scene = Scene::new(Color::BLACK).unwrap();
3198
3199        assert_eq!(
3200            scene.try_styled_line(Vec2::ZERO, Vec2::new(10.0, 0.0), style),
3201            Err(SceneError::StrokeExpansionLimitExceeded {
3202                primitive: ScenePrimitive::Line,
3203                limit: 2,
3204                required: 3,
3205            })
3206        );
3207        assert_eq!(scene.command_count(), 0);
3208        assert_eq!(scene.statistics().requested_commands(), 1);
3209        assert_eq!(scene.statistics().rejected_commands(), 1);
3210    }
3211
3212    #[test]
3213    fn scene_statistics_group_requested_accepted_and_rejected_primitives() {
3214        let mut scene = Scene::new(Color::BLACK).unwrap();
3215        scene
3216            .try_circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE))
3217            .unwrap();
3218        assert_eq!(
3219            scene.try_line(Vec2::ZERO, Vec2::ZERO, 1.0, Color::WHITE),
3220            Err(SceneError::DegenerateGeometry(ScenePrimitive::Line))
3221        );
3222        scene
3223            .try_polyline(vec![Vec2::ZERO, Vec2::X], 1.0, Color::WHITE)
3224            .unwrap();
3225
3226        let statistics = scene.statistics();
3227        assert_eq!(statistics.requested_by_primitive().circles(), 1);
3228        assert_eq!(statistics.requested_by_primitive().lines(), 1);
3229        assert_eq!(statistics.requested_by_primitive().polylines(), 1);
3230        assert_eq!(statistics.requested_by_primitive().total(), 3);
3231        assert_eq!(statistics.accepted_by_primitive().circles(), 1);
3232        assert_eq!(statistics.accepted_by_primitive().polylines(), 1);
3233        assert_eq!(statistics.accepted_by_primitive().total(), 2);
3234        assert_eq!(statistics.rejected_by_primitive().lines(), 1);
3235        assert_eq!(statistics.rejected_by_primitive().total(), 1);
3236    }
3237
3238    #[test]
3239    fn rich_stroke_values_are_reusable_and_world_overflow_is_rejected() {
3240        let marker = StrokeMarker2d::arrow(
3241            LogicalPixels::new(8.0).unwrap(),
3242            LogicalPixels::new(6.0).unwrap(),
3243        );
3244        let style = StrokeStyle2d::logical(LogicalPixels::new(2.0).unwrap(), Color::WHITE)
3245            .with_cap(StrokeCap2d::Square)
3246            .with_join(StrokeJoin2d::Bevel)
3247            .with_start_marker(marker)
3248            .with_end_marker(marker);
3249        let command =
3250            DrawCommand::styled_polyline(vec![Vec2::ZERO, Vec2::X, Vec2::new(2.0, 1.0)], style)
3251                .unwrap();
3252        assert_eq!(command.estimated_tessellated_vertices(), 24);
3253
3254        let unsafe_world = StrokeStyle2d::world(WorldLength::new(f32::MAX).unwrap(), Color::WHITE);
3255        assert!(matches!(
3256            DrawCommand::styled_line(Vec2::ZERO, Vec2::X, unsafe_world),
3257            Err(SceneError::InvalidStroke(ScenePrimitive::Line))
3258        ));
3259
3260        let unsafe_logical =
3261            StrokeStyle2d::logical(LogicalPixels::new(f32::MAX).unwrap(), Color::WHITE);
3262        assert!(matches!(
3263            DrawCommand::styled_line(Vec2::ZERO, Vec2::X, unsafe_logical),
3264            Err(SceneError::InvalidStroke(ScenePrimitive::Line))
3265        ));
3266    }
3267
3268    #[test]
3269    fn polyline_rejects_zero_segments_and_numerically_ambiguous_turns() {
3270        let style = StrokeStyle2d::logical(LogicalPixels::new(2.0).unwrap(), Color::WHITE);
3271        assert!(matches!(
3272            DrawCommand::styled_polyline(vec![Vec2::ZERO, Vec2::ZERO, Vec2::X], style),
3273            Err(SceneError::DegenerateGeometry(ScenePrimitive::Polyline))
3274        ));
3275        assert!(matches!(
3276            DrawCommand::styled_polyline(vec![Vec2::ZERO, Vec2::X, Vec2::ZERO], style),
3277            Err(SceneError::DegenerateStrokeTurn {
3278                primitive: ScenePrimitive::Polyline,
3279                vertex_index: 1,
3280            })
3281        ));
3282        assert!(matches!(
3283            DrawCommand::styled_polyline(
3284                vec![Vec2::ZERO, Vec2::X, Vec2::new(0.0, 0.000_000_1)],
3285                style,
3286            ),
3287            Err(SceneError::DegenerateStrokeTurn {
3288                primitive: ScenePrimitive::Polyline,
3289                vertex_index: 1,
3290            })
3291        ));
3292        assert!(matches!(
3293            DrawCommand::styled_polyline(
3294                vec![Vec2::ZERO, Vec2::X, Vec2::new(2.0, 0.000_05)],
3295                style,
3296            ),
3297            Err(SceneError::DegenerateStrokeTurn {
3298                primitive: ScenePrimitive::Polyline,
3299                vertex_index: 1,
3300            })
3301        ));
3302    }
3303
3304    #[test]
3305    fn background_and_clip_are_validated_when_created() {
3306        assert!(matches!(
3307            Scene::new(Color::rgba(f32::NAN, 0.0, 0.0, 1.0)),
3308            Err(SceneError::InvalidBackground)
3309        ));
3310        assert!(matches!(
3311            Scene::new(Color::rgb(1.01, 0.0, 0.0)),
3312            Err(SceneError::InvalidBackground)
3313        ));
3314        assert_eq!(
3315            ScreenClipRect::new(
3316                LogicalScreenPosition::new(0.0, 0.0),
3317                LogicalScreenPosition::new(0.0, 10.0),
3318            ),
3319            Err(SceneError::InvalidScreenClip)
3320        );
3321        assert_eq!(
3322            ScreenClipRect::new(
3323                LogicalScreenPosition::new(f32::NAN, 0.0),
3324                LogicalScreenPosition::new(10.0, 10.0),
3325            ),
3326            Err(SceneError::InvalidScreenClip)
3327        );
3328    }
3329
3330    #[test]
3331    fn render_bound_scene_colors_must_be_normalized() {
3332        let mut scene = Scene::new(Color::BLACK).unwrap();
3333        assert_eq!(
3334            scene.try_circle(
3335                Vec2::ZERO,
3336                1.0,
3337                ShapeStyle::filled(Color::rgb(2.0, 0.0, 0.0)),
3338            ),
3339            Err(SceneError::InvalidFill(ScenePrimitive::Circle))
3340        );
3341        assert_eq!(
3342            scene.try_line(Vec2::ZERO, Vec2::X, 1.0, Color::rgba(0.0, 0.0, 0.0, -0.01),),
3343            Err(SceneError::InvalidStroke(ScenePrimitive::Line))
3344        );
3345        assert_eq!(scene.command_count(), 0);
3346    }
3347
3348    #[test]
3349    fn depth_does_not_reorder_commands_within_a_layer() {
3350        let mut scene = Scene::new(Color::BLACK).unwrap();
3351        scene
3352            .with_depth(4.0, |scene| {
3353                scene.circle(Vec2::X, 1.0, ShapeStyle::filled(Color::WHITE));
3354            })
3355            .unwrap();
3356        scene.circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE));
3357
3358        assert_eq!(scene.commands()[0].depth(), 4.0);
3359        assert_eq!(scene.commands()[1].depth(), 0.0);
3360    }
3361
3362    #[test]
3363    fn allocation_bytes_preserve_spare_command_capacity_after_clear() {
3364        let mut scene = Scene::new(Color::BLACK).unwrap();
3365        scene
3366            .try_polyline(
3367                vec![Vec2::ZERO, Vec2::X, Vec2::new(1.0, 1.0)],
3368                1.0,
3369                Color::WHITE,
3370            )
3371            .unwrap();
3372        let allocated = scene.allocation_bytes();
3373        assert!(allocated >= size_of::<SceneCommand>() + 3 * size_of::<Vec2>());
3374        scene.clear();
3375        assert_eq!(scene.statistics().retained_bytes(), 0);
3376        assert_eq!(
3377            scene.allocation_bytes(),
3378            scene.commands.capacity() * size_of::<SceneCommand>()
3379        );
3380        assert!(scene.allocation_bytes() > 0);
3381    }
3382
3383    #[test]
3384    fn clone_recomputes_capacity_based_polyline_accounting() {
3385        let mut points = Vec::with_capacity(1_024);
3386        points.extend([Vec2::ZERO, Vec2::X]);
3387        let mut scene = Scene::new(Color::BLACK).unwrap();
3388        scene.try_polyline(points, 1.0, Color::WHITE).unwrap();
3389
3390        let cloned = scene.clone();
3391        let actual_owned = cloned
3392            .commands
3393            .iter()
3394            .map(|command| command.command.owned_allocation_bytes())
3395            .fold(0usize, usize::saturating_add);
3396        assert_eq!(cloned.owned_payload_bytes, actual_owned);
3397        assert_eq!(
3398            cloned.statistics.retained_bytes(),
3399            cloned
3400                .commands
3401                .len()
3402                .saturating_mul(size_of::<SceneCommand>())
3403                .saturating_add(actual_owned)
3404        );
3405        assert_eq!(
3406            cloned.allocation_bytes(),
3407            cloned
3408                .commands
3409                .capacity()
3410                .saturating_mul(size_of::<SceneCommand>())
3411                .saturating_add(actual_owned)
3412        );
3413    }
3414
3415    #[test]
3416    fn structured_scene_errors_preserve_rejection_reason() {
3417        let mut scene = Scene::new(Color::BLACK).unwrap();
3418
3419        assert_eq!(
3420            scene.try_circle(Vec2::ZERO, -1.0, ShapeStyle::filled(Color::WHITE)),
3421            Err(SceneError::InvalidDimension(ScenePrimitive::Circle))
3422        );
3423        assert_eq!(
3424            scene.try_line(Vec2::ZERO, Vec2::ZERO, 1.0, Color::WHITE),
3425            Err(SceneError::DegenerateGeometry(ScenePrimitive::Line))
3426        );
3427        assert_eq!(
3428            scene.try_circle(
3429                Vec2::ZERO,
3430                1.0,
3431                ShapeStyle {
3432                    fill: None,
3433                    stroke: None,
3434                    shadow: None,
3435                },
3436            ),
3437            Err(SceneError::MissingStyle(ScenePrimitive::Circle))
3438        );
3439        assert_eq!(scene.command_count(), 0);
3440    }
3441
3442    #[test]
3443    fn commands_capture_depth_and_restore_it_after_unwind() {
3444        let mut scene = Scene::new(Color::BLACK).unwrap();
3445        let panic_result = catch_unwind(AssertUnwindSafe(|| {
3446            let _ = scene.with_depth(4.5, |scene| {
3447                scene.circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE));
3448                panic!("intentional depth unwind");
3449            });
3450        }));
3451        assert!(panic_result.is_err());
3452
3453        scene.circle(Vec2::X, 1.0, ShapeStyle::filled(Color::WHITE));
3454
3455        assert_eq!(scene.commands()[0].depth(), 4.5);
3456        assert_eq!(scene.commands()[1].depth(), 0.0);
3457        assert_eq!(
3458            scene.with_depth(f32::NAN, |_| {}),
3459            Err(SceneError::NonFiniteDepth)
3460        );
3461    }
3462
3463    #[test]
3464    fn gradients_sanitize_invalid_and_reversed_configuration() {
3465        let invalid_linear = LinearGradient::new(
3466            Vec2::new(f32::NAN, 0.0),
3467            Vec2::X,
3468            Color::BLACK,
3469            Color::WHITE,
3470        );
3471        assert_eq!(invalid_linear.color_at(Vec2::ZERO), Color::WHITE);
3472
3473        let reversed = RadialGradient::new(Vec2::ZERO, 10.0, 5.0, Color::WHITE, Color::BLACK);
3474        assert_eq!(reversed.inner_radius(), 5.0);
3475        assert_eq!(reversed.outer_radius(), 10.0);
3476        assert_eq!(reversed.color_at(Vec2::ZERO), Color::BLACK);
3477    }
3478
3479    #[test]
3480    fn tiny_nonzero_radial_range_preserves_both_color_endpoints() {
3481        let gradient =
3482            RadialGradient::new(Vec2::ZERO, 0.0, 0.000_000_01, Color::BLACK, Color::WHITE);
3483
3484        assert_eq!(gradient.color_at(Vec2::ZERO), Color::BLACK);
3485        assert_eq!(
3486            gradient.color_at(Vec2::new(0.000_000_01, 0.0)),
3487            Color::WHITE
3488        );
3489    }
3490
3491    #[test]
3492    fn temporary_screen_clip_restores_state_after_unwind() {
3493        let mut scene = Scene::new(Color::BLACK).unwrap();
3494        let clip = ScreenClipRect::from_min_size(
3495            LogicalScreenPosition::new(0.0, 0.0),
3496            LogicalScreenVector::new(100.0, 100.0),
3497        )
3498        .unwrap();
3499
3500        let panic_result = catch_unwind(AssertUnwindSafe(|| {
3501            let _ = scene.with_screen_clip(clip, |_| panic!("intentional test panic"));
3502        }));
3503        assert!(panic_result.is_err());
3504
3505        assert!(scene.circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE)));
3506        assert_eq!(scene.commands()[0].screen_clip(), None);
3507    }
3508}