Skip to main content

dream_soft_render/
geometry.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3use crate::Color;
4
5/// A mesh vertex: a position in surface pixels, a normalized texture coordinate, and a
6/// premultiplied color that multiplies the sampled texel.
7///
8/// The layout is fixed at 20 bytes (`#[repr(C)]`: four `f32` then four color bytes), so
9/// vertex data can be produced in bulk by other code without conversion.
10#[derive(Clone, Copy, Debug, Default, PartialEq)]
11#[repr(C)]
12pub struct Vertex {
13    /// Position in surface pixels; see the crate docs for the coordinate conventions.
14    pub pos: [f32; 2],
15    /// Texture coordinate, `0.0..=1.0` across the texture. Untextured meshes sample white
16    /// wherever it points, but it must still be finite.
17    pub uv: [f32; 2],
18    /// Premultiplied color, multiplied with the sampled texel.
19    pub color: Color,
20}
21
22const _: () = assert!(size_of::<Vertex>() == 20);
23
24impl Vertex {
25    /// A vertex from its parts.
26    #[must_use]
27    pub const fn new(pos: [f32; 2], uv: [f32; 2], color: Color) -> Self {
28        Self { pos, uv, color }
29    }
30
31    /// The first coordinate that is NaN or infinite, if any. The color cannot be invalid:
32    /// every bit pattern is a color.
33    pub(crate) fn non_finite_field(self) -> Option<crate::VertexField> {
34        if !self.pos.iter().all(|value| value.is_finite()) {
35            Some(crate::VertexField::Position)
36        } else if !self.uv.iter().all(|value| value.is_finite()) {
37            Some(crate::VertexField::Uv)
38        } else {
39            None
40        }
41    }
42
43    pub(crate) const fn pos2(&self) -> Pos2 {
44        pos2(self.pos[0], self.pos[1])
45    }
46
47    pub(crate) const fn uv2(&self) -> Pos2 {
48        pos2(self.uv[0], self.uv[1])
49    }
50
51    #[cfg(all(test, feature = "egui"))]
52    pub(crate) const fn to_egui(self) -> egui::epaint::Vertex {
53        egui::epaint::Vertex {
54            pos: egui::pos2(self.pos[0], self.pos[1]),
55            uv: egui::pos2(self.uv[0], self.uv[1]),
56            color: self.color.to_egui(),
57        }
58    }
59}
60
61/// A point inside the rasterizer: surface pixels for positions, normalized for texture
62/// coordinates. Public vertices use `[f32; 2]`; this is the named-field view the raster code
63/// computes with.
64#[derive(Clone, Copy, Debug, Default, PartialEq)]
65pub(crate) struct Pos2 {
66    pub(crate) x: f32,
67    pub(crate) y: f32,
68}
69
70impl Pos2 {
71    pub(crate) const ZERO: Self = pos2(0.0, 0.0);
72}
73
74pub(crate) const fn pos2(x: f32, y: f32) -> Pos2 {
75    Pos2 { x, y }
76}
77
78/// A per-pixel step through texture space.
79#[derive(Clone, Copy, Debug, Default, PartialEq)]
80pub(crate) struct Vec2 {
81    pub(crate) x: f32,
82    pub(crate) y: f32,
83}
84
85pub(crate) const fn vec2(x: f32, y: f32) -> Vec2 {
86    Vec2 { x, y }
87}
88
89/// The triangles the raster core draws: borrowed vertices and indices, three per triangle.
90/// [`Frame::mesh`](crate::Frame::mesh) hands over the caller's slices as they are, and the
91/// egui adapter reinterprets egui's vertex buffer in place, so neither path copies geometry.
92#[derive(Clone, Copy, Debug)]
93pub(crate) struct RasterMesh<'a> {
94    pub(crate) vertices: &'a [Vertex],
95    pub(crate) indices: &'a [u32],
96}
97
98/// An axis-aligned rectangle in floating-point surface pixels (for positions) or normalized
99/// texture coordinates (for UV ranges).
100#[derive(Clone, Copy, Debug, Default, PartialEq)]
101pub struct Rect {
102    /// Top-left corner.
103    pub min: [f32; 2],
104    /// Bottom-right corner.
105    pub max: [f32; 2],
106}
107
108impl Rect {
109    /// The whole texture, as a UV range.
110    pub const FULL_UV: Self = Self::from_min_max([0.0, 0.0], [1.0, 1.0]);
111
112    /// A rectangle from its top-left and bottom-right corners.
113    #[must_use]
114    pub const fn from_min_max(min: [f32; 2], max: [f32; 2]) -> Self {
115        Self { min, max }
116    }
117
118    /// A rectangle from its top-left corner and size.
119    #[must_use]
120    pub fn from_min_size(min: [f32; 2], size: [f32; 2]) -> Self {
121        Self::from_min_max(min, [min[0] + size[0], min[1] + size[1]])
122    }
123
124    pub(crate) fn is_finite(self) -> bool {
125        self.min
126            .iter()
127            .chain(&self.max)
128            .all(|value| value.is_finite())
129    }
130}
131
132/// A clip rectangle in integer surface pixels, half-open: it keeps pixels with
133/// `min_x <= x < max_x` and `min_y <= y < max_y`.
134///
135/// Bounds past the surface are clamped to it, and a rectangle with `min >= max` on either axis
136/// is empty, so drawing through it writes nothing.
137#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
138pub struct ClipRect {
139    /// First column kept.
140    pub min_x: u32,
141    /// First row kept.
142    pub min_y: u32,
143    /// One past the last column kept.
144    pub max_x: u32,
145    /// One past the last row kept.
146    pub max_y: u32,
147}
148
149impl ClipRect {
150    /// No clipping beyond the surface itself.
151    pub const ALL: Self = Self::new(0, 0, u32::MAX, u32::MAX);
152
153    /// A clip rectangle from its bounds.
154    #[must_use]
155    pub const fn new(min_x: u32, min_y: u32, max_x: u32, max_y: u32) -> Self {
156        Self {
157            min_x,
158            min_y,
159            max_x,
160            max_y,
161        }
162    }
163
164    pub(crate) fn to_bounds(self, width: usize, height: usize) -> crate::raster::ClipBounds {
165        let clamp = |value: u32, max: usize| usize::try_from(value).map_or(max, |v| v.min(max));
166        crate::raster::ClipBounds {
167            min_x: clamp(self.min_x, width),
168            min_y: clamp(self.min_y, height),
169            max_x: clamp(self.max_x, width),
170            max_y: clamp(self.max_y, height),
171        }
172    }
173}