sim-logic 0.1.0

A code-first application and logic layer for Sim;Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! Managed presentation geometry in logical screen pixels.

use std::{error::Error, fmt};

use bevy_ecs::prelude::Component;
use sim_engine::{Color, Layer, LogicalScreenPosition, LogicalScreenVector};

use crate::input::PointerSample;

#[path = "screen/image.rs"]
mod image;
pub use image::{ImageFilter, ImageRegion, ImageVisualError, ScreenImageVisual};
#[path = "screen/clip.rs"]
mod clip;
#[path = "screen/rectangle.rs"]
mod rectangle;
pub use clip::ScreenClip;
#[path = "screen/vectors.rs"]
mod vectors;
pub use vectors::{ScreenCircleVisual, ScreenLineVisual};
#[path = "screen/polyline.rs"]
mod polyline;
pub use polyline::{ScreenPolylineError, ScreenPolylineVisual};

/// A filled rectangle with optional rounded corners and a decorative outline.
///
/// The origin is the content area's top-left, with x increasing rightward and
/// y downward. Finite negative and offscreen positions are allowed. World
/// camera movement, zoom, rotation, and fixed interpolation do not affect this
/// visual. It requires no world-space Transform and may coexist with a world
/// visual on the same entity without controlling that visual.
///
/// FrameUpdate may mutate this presentation-only component directly. Extraction
/// samples its current values, excludes disabled entities, and draws screen
/// rectangles after all world visuals. Within screen content, lower layer and
/// draw-order depth draw first; stable source identity breaks remaining ties.
/// Visibility does not automatically capture or route input. No window or GPU
/// is required to construct, update, or extract the component.
#[derive(Debug, Clone, Copy, PartialEq, Component)]
pub struct ScreenRectangleVisual {
    position: LogicalScreenPosition,
    size: LogicalScreenVector,
    color: Color,
    layer: Layer,
    draw_order_depth: f32,
    corner_radius: f32,
    stroke: Option<sim_engine::Stroke>,
    clip: ScreenClip,
}

impl ScreenRectangleVisual {
    /// Creates a rectangle on the default layer with draw-order depth zero.
    ///
    /// Position must be finite, size must be finite and strictly positive on
    /// both axes, and color must be normalized straight-linear RGBA. Adding
    /// size to position in f32 must produce finite, strictly greater far bounds.
    pub fn new(
        position: LogicalScreenPosition,
        size: LogicalScreenVector,
        color: Color,
    ) -> Result<Self, ScreenVisualError> {
        let visual = Self {
            position,
            size,
            color,
            layer: Layer::DEFAULT,
            draw_order_depth: 0.0,
            corner_radius: 0.0,
            stroke: None,
            clip: ScreenClip::Unclipped,
        };
        visual.validate()?;
        Ok(visual)
    }

    /// Returns the rectangle's top-left position in logical screen pixels.
    pub const fn position(&self) -> LogicalScreenPosition {
        self.position
    }

    /// Returns the full positive width and height in logical screen pixels.
    pub const fn size(&self) -> LogicalScreenVector {
        self.size
    }

    /// Tests the current rectangular geometry against an event-time pointer.
    ///
    /// Both the rectangle and the sample's stored viewport use half-open bounds:
    /// left/top edges are included, right/bottom excluded. Partially offscreen
    /// rectangles can be hit only inside that viewport. The supplied geometry
    /// is current; this does not reconstruct historical layout after a resize.
    ///
    /// This is allocation-free geometry, not automatic UI routing. Alpha, entity
    /// enablement and overlapping draw order are not inspected. The configured
    /// clip and rounded fill are respected; the decorative outline is excluded.
    /// The caller chooses eligibility and which overlapping target wins.
    pub fn contains_pointer(&self, sample: PointerSample) -> bool {
        if !self.clip.contains_pointer(sample) {
            return false;
        }
        let point = sample.position().to_vec2();
        let minimum = self.position.to_vec2();
        let maximum = minimum + self.size.to_vec2();
        let inside = point.x() >= minimum.x()
            && point.y() >= minimum.y()
            && point.x() < maximum.x()
            && point.y() < maximum.y();
        if !inside {
            return false;
        }
        let radius = f64::from(self.corner_radius)
            .min(f64::from(self.size.to_vec2().x()) * 0.5)
            .min(f64::from(self.size.to_vec2().y()) * 0.5);
        let x = f64::from(point.x()) - f64::from(minimum.x());
        let y = f64::from(point.y()) - f64::from(minimum.y());
        let dx = (x - x.clamp(radius, f64::from(self.size.to_vec2().x()) - radius)).abs();
        let dy = (y - y.clamp(radius, f64::from(self.size.to_vec2().y()) - radius)).abs();
        dx.hypot(dy) <= radius
    }

    /// Returns the normalized straight-linear RGBA fill color.
    pub const fn color(&self) -> Color {
        self.color
    }

    /// Returns the primary ordering layer within screen content.
    pub const fn layer(&self) -> Layer {
        self.layer
    }

    /// Returns the finite ordering depth within the screen layer.
    ///
    /// This value controls draw order only; it is not camera projection depth.
    pub const fn draw_order_depth(&self) -> f32 {
        self.draw_order_depth
    }

    /// Replaces position and size together after validating their bounds.
    ///
    /// Failure leaves every component value unchanged. Finite offscreen
    /// geometry is accepted without clamping.
    pub fn set_geometry(
        &mut self,
        position: LogicalScreenPosition,
        size: LogicalScreenVector,
    ) -> Result<(), ScreenVisualError> {
        validate_geometry(position, size)?;
        self.position = position;
        self.size = size;
        Ok(())
    }

    /// Replaces the logical top-left position while retaining size.
    ///
    /// Invalid or unrepresentable bounds leave the component unchanged.
    pub fn set_position(
        &mut self,
        position: LogicalScreenPosition,
    ) -> Result<(), ScreenVisualError> {
        self.set_geometry(position, self.size)
    }

    /// Replaces logical width and height while retaining position.
    ///
    /// Non-positive size or invalid bounds leave the component unchanged.
    pub fn set_size(&mut self, size: LogicalScreenVector) -> Result<(), ScreenVisualError> {
        self.set_geometry(self.position, size)
    }

    /// Replaces normalized straight-linear RGBA color atomically.
    ///
    /// A non-finite channel or channel outside `0.0..=1.0` leaves it unchanged.
    pub fn set_color(&mut self, color: Color) -> Result<(), ScreenVisualError> {
        validate_color(color)?;
        self.color = color;
        Ok(())
    }

    /// Replaces the ordering layer within screen content.
    pub fn set_layer(&mut self, layer: Layer) {
        self.layer = layer;
    }

    /// Replaces within-layer ordering depth after finite-value validation.
    ///
    /// Negative values are allowed. Failure leaves the component unchanged.
    pub fn set_draw_order_depth(&mut self, depth: f32) -> Result<(), ScreenVisualError> {
        validate_draw_order_depth(depth)?;
        self.draw_order_depth = depth;
        Ok(())
    }

    pub(crate) fn validate(&self) -> Result<(), ScreenVisualError> {
        validate_geometry(self.position, self.size)?;
        validate_color(self.color)?;
        validate_draw_order_depth(self.draw_order_depth)
    }
}

/// Invalid value rejected by a screen visual's constructor or atomic setter.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum ScreenVisualError {
    /// Removing the stroke would leave an outline-only shape with no paint.
    MissingPaint,
    /// Image rotation was non-finite.
    InvalidRotation {
        /// Rejected clockwise angle in radians.
        value: f32,
    },
    /// Line endpoints coincide or their difference overflows.
    InvalidLine,
    /// A radius was negative or non-finite (circles additionally reject zero).
    InvalidRadius {
        /// Rejected radius in logical pixels.
        value: f32,
    },
    /// A stroke width was non-finite or not positive.
    InvalidStrokeWidth {
        /// Rejected width in logical pixels.
        value: f32,
    },
    /// A logical screen position contained a non-finite coordinate.
    InvalidPosition {
        /// Rejected logical top-left position.
        value: LogicalScreenPosition,
    },
    /// A logical width or height was non-finite or not strictly positive.
    InvalidSize {
        /// Rejected logical-pixel size.
        value: LogicalScreenVector,
    },
    /// Adding size overflowed or failed to advance either f32 coordinate.
    InvalidBounds {
        /// Logical top-left position of the rejected geometry.
        position: LogicalScreenPosition,
        /// Logical-pixel size of the rejected geometry.
        size: LogicalScreenVector,
    },
    /// A color channel was non-finite or outside `0.0..=1.0`.
    InvalidColor {
        /// Rejected straight-linear RGBA color.
        value: Color,
    },
    /// Draw-order depth was non-finite.
    InvalidDrawOrderDepth {
        /// Rejected ordering value.
        value: f32,
    },
}

impl fmt::Display for ScreenVisualError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingPaint => formatter.write_str("an outline-only shape requires a stroke"),
            Self::InvalidRotation { value } => {
                write!(formatter, "non-finite screen rotation: {value}")
            }
            Self::InvalidLine => formatter
                .write_str("screen line endpoints must be distinct with finite displacement"),
            Self::InvalidRadius { value } => write!(formatter, "invalid screen radius: {value}"),
            Self::InvalidStrokeWidth { value } => {
                write!(formatter, "invalid screen stroke width: {value}")
            }
            Self::InvalidPosition { value } => {
                write!(
                    formatter,
                    "logical screen position must be finite, got {value:?}"
                )
            }
            Self::InvalidSize { value } => write!(
                formatter,
                "logical screen size must be positive and finite, got {value:?}"
            ),
            Self::InvalidBounds { position, size } => write!(
                formatter,
                "logical screen bounds must be finite and strictly increasing, got {position:?} plus {size:?}"
            ),
            Self::InvalidColor { value } => write!(
                formatter,
                "screen color must be normalized linear RGBA, got {value:?}"
            ),
            Self::InvalidDrawOrderDepth { value } => {
                write!(
                    formatter,
                    "screen draw-order depth must be finite, got {value}"
                )
            }
        }
    }
}

impl Error for ScreenVisualError {}

fn validate_geometry(
    position: LogicalScreenPosition,
    size: LogicalScreenVector,
) -> Result<(), ScreenVisualError> {
    if !position.is_finite() {
        return Err(ScreenVisualError::InvalidPosition { value: position });
    }
    let extent = size.to_vec2();
    if !size.is_finite() || extent.x() <= 0.0 || extent.y() <= 0.0 {
        return Err(ScreenVisualError::InvalidSize { value: size });
    }
    let minimum = position.to_vec2();
    let maximum = minimum + extent;
    if !maximum.is_finite() || maximum.x() <= minimum.x() || maximum.y() <= minimum.y() {
        return Err(ScreenVisualError::InvalidBounds { position, size });
    }
    Ok(())
}

fn validate_color(value: Color) -> Result<(), ScreenVisualError> {
    value
        .is_normalized()
        .then_some(())
        .ok_or(ScreenVisualError::InvalidColor { value })
}

fn validate_draw_order_depth(value: f32) -> Result<(), ScreenVisualError> {
    value
        .is_finite()
        .then_some(())
        .ok_or(ScreenVisualError::InvalidDrawOrderDepth { value })
}

#[cfg(test)]
mod tests {
    use super::*;

    fn state_bits(visual: ScreenRectangleVisual) -> [u32; 9] {
        let position = visual.position().to_vec2();
        let size = visual.size().to_vec2();
        [
            position.x(),
            position.y(),
            size.x(),
            size.y(),
            visual.color().red(),
            visual.color().green(),
            visual.color().blue(),
            visual.color().alpha(),
            visual.draw_order_depth(),
        ]
        .map(f32::to_bits)
    }

    #[test]
    fn finite_offscreen_and_small_representable_geometry_is_preserved()
    -> Result<(), ScreenVisualError> {
        let position = LogicalScreenPosition::new(-40.0, 9_000.0);
        let size = LogicalScreenVector::new(20.0, 10.0);
        let mut visual = ScreenRectangleVisual::new(position, size, Color::WHITE)?;
        assert_eq!(visual.position(), position);
        assert_eq!(visual.size(), size);
        assert_eq!(visual.layer(), Layer::DEFAULT);
        assert_eq!(visual.draw_order_depth(), 0.0);

        let subnormal = f32::from_bits(1);
        visual.set_geometry(
            LogicalScreenPosition::new(-0.0, 0.0),
            LogicalScreenVector::new(subnormal, subnormal),
        )?;
        assert_eq!(
            visual.position().to_vec2().x().to_bits(),
            (-0.0_f32).to_bits()
        );
        assert_eq!(visual.size().to_vec2().x().to_bits(), 1);
        visual.set_layer(Layer::new(-3));
        visual.set_draw_order_depth(-2.0)?;
        visual.set_color(Color::TRANSPARENT)?;
        assert_eq!(visual.layer(), Layer::new(-3));
        assert_eq!(visual.draw_order_depth(), -2.0);
        assert_eq!(visual.color(), Color::TRANSPARENT);
        Ok(())
    }

    #[test]
    fn constructors_reject_nonfinite_nonpositive_and_unrepresentable_geometry() {
        let origin = LogicalScreenPosition::default();
        let unit = LogicalScreenVector::new(1.0, 1.0);
        for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
            for position in [
                LogicalScreenPosition::new(value, 0.0),
                LogicalScreenPosition::new(0.0, value),
            ] {
                assert!(matches!(
                    ScreenRectangleVisual::new(position, unit, Color::WHITE),
                    Err(ScreenVisualError::InvalidPosition { .. })
                ));
            }
        }
        for value in [0.0, -0.0, -1.0, f32::NAN, f32::INFINITY] {
            for size in [
                LogicalScreenVector::new(value, 1.0),
                LogicalScreenVector::new(1.0, value),
            ] {
                assert!(matches!(
                    ScreenRectangleVisual::new(origin, size, Color::WHITE),
                    Err(ScreenVisualError::InvalidSize { .. })
                ));
            }
        }
        for (position, size) in [
            (
                LogicalScreenPosition::new(f32::MAX, 0.0),
                LogicalScreenVector::new(f32::MAX, 1.0),
            ),
            (
                LogicalScreenPosition::new(0.0, f32::MAX),
                LogicalScreenVector::new(1.0, f32::MAX),
            ),
            (LogicalScreenPosition::new(16_777_216.0, 0.0), unit),
            (LogicalScreenPosition::new(0.0, 16_777_216.0), unit),
        ] {
            assert!(matches!(
                ScreenRectangleVisual::new(position, size, Color::WHITE),
                Err(ScreenVisualError::InvalidBounds { .. })
            ));
        }
        assert!(matches!(
            ScreenRectangleVisual::new(origin, unit, Color::rgb(2.0, 0.0, 0.0)),
            Err(ScreenVisualError::InvalidColor { .. })
        ));
    }

    #[test]
    fn failed_setters_preserve_every_prior_bit() -> Result<(), ScreenVisualError> {
        let mut visual = ScreenRectangleVisual::new(
            LogicalScreenPosition::new(-0.0, -0.0),
            LogicalScreenVector::new(16.0, 8.0),
            Color::rgba(-0.0, 0.25, 0.5, 1.0),
        )?;
        visual.set_draw_order_depth(-0.0)?;
        visual.set_layer(Layer::new(7));
        let before = state_bits(visual);
        assert!(
            visual
                .set_geometry(
                    LogicalScreenPosition::new(3.0, 4.0),
                    LogicalScreenVector::new(0.0, 1.0)
                )
                .is_err()
        );
        assert_eq!(state_bits(visual), before);
        assert!(
            visual
                .set_position(LogicalScreenPosition::new(f32::MAX, 0.0))
                .is_err()
        );
        assert_eq!(state_bits(visual), before);
        assert!(
            visual
                .set_size(LogicalScreenVector::new(1.0, f32::NAN))
                .is_err()
        );
        assert_eq!(state_bits(visual), before);
        for value in [f32::NAN, f32::INFINITY, -0.1, 1.1] {
            assert!(visual.set_color(Color::WHITE.with_alpha(value)).is_err());
            assert_eq!(state_bits(visual), before);
        }
        for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
            assert!(visual.set_draw_order_depth(value).is_err());
            assert_eq!(state_bits(visual), before);
        }
        assert_eq!(visual.layer(), Layer::new(7));
        Ok(())
    }

    #[test]
    fn geometry_setter_validates_the_requested_pair_together() -> Result<(), ScreenVisualError> {
        let mut visual = ScreenRectangleVisual::new(
            LogicalScreenPosition::default(),
            LogicalScreenVector::new(1.0, 1.0),
            Color::WHITE,
        )?;
        let position = LogicalScreenPosition::new(16_777_216.0, 16_777_216.0);
        let size = LogicalScreenVector::new(2.0, 2.0);
        assert!(visual.set_position(position).is_err());
        visual.set_geometry(position, size)?;
        assert_eq!(visual.position(), position);
        assert_eq!(visual.size(), size);
        assert!(visual.set_size(LogicalScreenVector::new(1.0, 1.0)).is_err());
        assert_eq!(visual.size(), size);
        Ok(())
    }
}