Skip to main content

sim_logic/rendering/three_d/
view.rs

1use std::{error::Error, fmt};
2
3use bevy_ecs::prelude::Resource;
4use sim_engine::{
5    Camera3d, Color, Fog3d, Lighting3d, LogicalViewport, Mesh3dStyleError, Projection3d,
6    Pseudo3dError, SurfaceStyle3d, UnitError, Vec3, WorldLength,
7};
8
9/// Filled-surface projection policy, available without a GPU dependency.
10#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
11pub enum ThreeDSurfacePolicy {
12    /// Require Engine's conservative cross-backend clipping/orientation proofs.
13    #[default]
14    StrictPortable,
15    /// Use hardware clipping for filled surfaces, retaining finite-arithmetic checks.
16    /// Mathematical display edges retain their independent strict validation.
17    Native,
18}
19
20/// Optional World resource enabling a 3D view beneath screen overlays.
21///
22/// The positive-y up axis is fixed; the perspective aspect follows the current
23/// logical viewport. Missing or disabled views publish no 3D content, even if
24/// the World retains visible cuboids. Switching views does not change gameplay
25/// or playback state. FrameUpdate may update this presentation resource.
26#[derive(Debug, Clone, Copy, PartialEq, Resource)]
27pub struct View3d {
28    position: Vec3,
29    target: Vec3,
30    vertical_fov_radians: f32,
31    near: WorldLength,
32    far: WorldLength,
33    background: Color,
34    orthographic_span: Option<WorldLength>,
35    surface_policy: ThreeDSurfacePolicy,
36    lighting: Lighting3d,
37    fog: Option<Fog3d>,
38    enabled: bool,
39}
40
41impl View3d {
42    /// Creates an enabled view with 60-degree vertical FOV and a 0.1..1000 range.
43    ///
44    /// Position and target must form a valid camera with positive-y up.
45    pub fn new(position: Vec3, target: Vec3) -> Result<Self, View3dError> {
46        let view = Self {
47            position,
48            target,
49            vertical_fov_radians: std::f32::consts::FRAC_PI_3,
50            near: WorldLength::new(0.1)?,
51            far: WorldLength::new(1000.0)?,
52            background: Color::BLACK,
53            orthographic_span: None,
54            surface_policy: ThreeDSurfacePolicy::StrictPortable,
55            lighting: Lighting3d::default(),
56            fog: None,
57            enabled: true,
58        };
59        view.validate()?;
60        Ok(view)
61    }
62
63    /// Returns the world-space eye position.
64    pub const fn position(self) -> Vec3 {
65        self.position
66    }
67
68    /// Returns the world-space look-at point.
69    pub const fn target(self) -> Vec3 {
70        self.target
71    }
72
73    /// Returns the last configured perspective field of view in radians.
74    /// Orthographic views retain this value but do not use it.
75    pub const fn vertical_fov_radians(self) -> f32 {
76        self.vertical_fov_radians
77    }
78
79    /// Returns the positive near clipping distance.
80    pub const fn near(self) -> WorldLength {
81        self.near
82    }
83
84    /// Returns the far clipping distance, greater than the near distance.
85    pub const fn far(self) -> WorldLength {
86        self.far
87    }
88
89    /// Returns the normalized straight-linear RGBA clear color.
90    /// Engine performs the target's premultiplied-alpha conversion.
91    pub const fn background(self) -> Color {
92        self.background
93    }
94
95    /// Reports whether the World participates in 3D extraction and rendering.
96    pub const fn enabled(self) -> bool {
97        self.enabled
98    }
99
100    /// Returns the orthographic vertical world span, or None for perspective.
101    pub const fn orthographic_span(self) -> Option<WorldLength> {
102        self.orthographic_span
103    }
104
105    /// Returns the filled-surface projection policy; strict by default.
106    pub const fn surface_policy(self) -> ThreeDSurfacePolicy {
107        self.surface_policy
108    }
109
110    /// Selects filled-surface validation without changing camera or world state.
111    pub fn set_surface_policy(&mut self, policy: ThreeDSurfacePolicy) {
112        self.surface_policy = policy;
113    }
114
115    /// Returns the ambient and optional directional illumination descriptor.
116    pub const fn lighting(self) -> Lighting3d {
117        self.lighting
118    }
119
120    /// Replaces validated lighting; only Lambert surfaces use it.
121    pub fn set_lighting(&mut self, lighting: Lighting3d) {
122        self.lighting = lighting;
123    }
124
125    /// Returns optional distance fog, disabled by default.
126    pub const fn fog(self) -> Option<Fog3d> {
127        self.fog
128    }
129
130    /// Replaces validated fog; each surface must independently opt in.
131    /// Fog never changes logical visibility, alpha or triangle budgets.
132    pub fn set_fog(&mut self, fog: Option<Fog3d>) {
133        self.fog = fog;
134    }
135
136    /// Replaces the eye and look-at point atomically after basis validation.
137    pub fn set_pose(&mut self, position: Vec3, target: Vec3) -> Result<(), View3dError> {
138        let proposed = Self {
139            position,
140            target,
141            ..*self
142        };
143        proposed.validate()?;
144        *self = proposed;
145        Ok(())
146    }
147
148    /// Replaces perspective parameters atomically, preserving automatic aspect.
149    pub fn set_perspective(
150        &mut self,
151        vertical_fov_radians: f32,
152        near: WorldLength,
153        far: WorldLength,
154    ) -> Result<(), View3dError> {
155        let proposed = Self {
156            vertical_fov_radians,
157            near,
158            far,
159            orthographic_span: None,
160            ..*self
161        };
162        proposed.validate()?;
163        *self = proposed;
164        Ok(())
165    }
166
167    /// Selects orthographic projection with a vertical world span and automatic aspect.
168    /// Invalid camera arithmetic leaves the entire previous view unchanged.
169    pub fn set_orthographic(
170        &mut self,
171        vertical_span: WorldLength,
172        near: WorldLength,
173        far: WorldLength,
174    ) -> Result<(), View3dError> {
175        let proposed = Self {
176            orthographic_span: Some(vertical_span),
177            near,
178            far,
179            ..*self
180        };
181        proposed.validate()?;
182        *self = proposed;
183        Ok(())
184    }
185
186    /// Replaces the normalized straight-linear RGBA clear color, or changes nothing.
187    pub fn set_background(&mut self, background: Color) -> Result<(), View3dError> {
188        SurfaceStyle3d::blend(background)?;
189        self.background = background;
190        Ok(())
191    }
192
193    /// Enables or suppresses the complete 3D snapshot without removing cuboids.
194    pub fn set_enabled(&mut self, enabled: bool) {
195        self.enabled = enabled;
196    }
197
198    /// Builds a CPU camera for the current logical viewport without allocation.
199    ///
200    /// An extreme aspect ratio can be unrepresentable and returns a typed error.
201    pub fn camera(self, viewport: LogicalViewport) -> Result<Camera3d, View3dError> {
202        self.camera_with_aspect(viewport.width() / viewport.height())
203    }
204
205    pub(crate) fn validate(self) -> Result<(), View3dError> {
206        SurfaceStyle3d::blend(self.background)?;
207        self.camera_with_aspect(1.0)?;
208        Ok(())
209    }
210
211    fn camera_with_aspect(self, aspect: f32) -> Result<Camera3d, View3dError> {
212        let projection = match self.orthographic_span {
213            Some(span) => Projection3d::orthographic(span, aspect, self.near, self.far)?,
214            None => {
215                Projection3d::perspective(self.vertical_fov_radians, aspect, self.near, self.far)?
216            }
217        };
218        Ok(Camera3d::look_at(
219            self.position,
220            self.target,
221            Vec3::Y,
222            projection,
223        )?)
224    }
225}
226
227/// Camera or clear-color validation failed without changing the previous view.
228#[derive(Debug, Clone, Copy, PartialEq)]
229pub enum View3dError {
230    /// Invalid camera basis, projection, or overflowing camera arithmetic.
231    Geometry(Pseudo3dError),
232    /// Invalid typed projection distance.
233    Units(UnitError),
234    /// The target clear color was not normalized straight-linear RGBA.
235    Background(Mesh3dStyleError),
236}
237
238impl From<Pseudo3dError> for View3dError {
239    fn from(error: Pseudo3dError) -> Self {
240        Self::Geometry(error)
241    }
242}
243
244impl From<UnitError> for View3dError {
245    fn from(error: UnitError) -> Self {
246        Self::Units(error)
247    }
248}
249
250impl From<Mesh3dStyleError> for View3dError {
251    fn from(error: Mesh3dStyleError) -> Self {
252        Self::Background(error)
253    }
254}
255
256impl fmt::Display for View3dError {
257    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
258        match self {
259            Self::Geometry(error) => write!(formatter, "invalid 3D view: {error}"),
260            Self::Units(error) => write!(formatter, "invalid 3D view units: {error}"),
261            Self::Background(error) => write!(formatter, "invalid 3D background: {error}"),
262        }
263    }
264}
265
266impl Error for View3dError {
267    fn source(&self) -> Option<&(dyn Error + 'static)> {
268        match self {
269            Self::Geometry(error) => Some(error),
270            Self::Units(error) => Some(error),
271            Self::Background(error) => Some(error),
272        }
273    }
274}