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