1use crate::{Color, Mat4, Vec3};
3pub const MAX_POINT_LIGHTS: usize = 8;
4#[repr(u32)]
5#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6pub enum Quality {
7 #[default]
8 Low = 0,
9 Medium = 1,
10 High = 2,
11}
12impl Quality {
13 pub fn shadow_size(self) -> u32 {
14 match self {
15 Self::Low => 0,
16 Self::Medium => 512,
17 Self::High => 1024,
18 }
19 }
20 pub fn point_limit(self) -> usize {
21 match self {
22 Self::Low => 2,
23 Self::Medium => 4,
24 Self::High => 8,
25 }
26 }
27 pub fn from_name(name: &str) -> Option<Self> {
28 match name {
29 "low" => Some(Self::Low),
30 "medium" => Some(Self::Medium),
31 "high" => Some(Self::High),
32 _ => None,
33 }
34 }
35}
36#[derive(Clone, Copy, Debug)]
37pub struct PointLight {
38 pub position: Vec3,
39 pub color: Color,
40 pub radius: f32,
41 pub intensity: f32,
42}
43impl PointLight {
44 pub fn valid(self) -> bool {
45 self.position.is_finite()
46 && self.position.abs().max_element() <= 1e6
47 && self.color.to_vec().is_finite()
48 && self.color.r >= 0.
49 && self.color.g >= 0.
50 && self.color.b >= 0.
51 && self.color.r <= 1.
52 && self.color.g <= 1.
53 && self.color.b <= 1.
54 && self.radius.is_finite()
55 && (0.01..=1000.).contains(&self.radius)
56 && self.intensity.is_finite()
57 && (0. ..=16.).contains(&self.intensity)
58 }
59}
60#[derive(Clone, Copy, Debug)]
61pub struct SunShadow {
62 pub center: Vec3,
63 pub direction: Vec3,
64 pub extent: f32,
65 pub depth: f32,
66 pub bias: f32,
67 pub normal_bias: f32,
68 pub strength: f32,
69}
70impl Default for SunShadow {
71 fn default() -> Self {
72 Self {
73 center: Vec3::ZERO,
74 direction: Vec3::new(-0.4, 0.85, 0.3),
75 extent: 30.,
76 depth: 80.,
77 bias: 0.001,
78 normal_bias: 0.025,
79 strength: 0.85,
80 }
81 }
82}
83impl SunShadow {
84 pub fn valid(self) -> bool {
85 self.center.is_finite()
86 && self.center.abs().max_element() <= 1e6
87 && self.direction.is_finite()
88 && self.direction.length_squared().is_finite()
89 && self.direction.length_squared() > 1e-8
90 && self.extent.is_finite()
91 && (0.1..=500.).contains(&self.extent)
92 && self.depth.is_finite()
93 && (1. ..=1000.).contains(&self.depth)
94 && self.bias.is_finite()
95 && (0. ..=0.1).contains(&self.bias)
96 && self.normal_bias.is_finite()
97 && (0. ..=1.).contains(&self.normal_bias)
98 && self.strength.is_finite()
99 && (0. ..=1.).contains(&self.strength)
100 }
101 pub fn matrix(self, size: u32) -> Mat4 {
102 let direction = self.direction.normalize();
103 let up = if direction.dot(Vec3::Y).abs() > 0.98 {
104 Vec3::Z
105 } else {
106 Vec3::Y
107 };
108 let view = Mat4::look_at_rh(self.center + direction * self.depth, self.center, up);
109 let mut projection = Mat4::orthographic_rh_gl(
110 -self.extent,
111 self.extent,
112 -self.extent,
113 self.extent,
114 0.1,
115 self.depth * 2.,
116 );
117 if size > 0 {
119 let origin = projection * view * Vec3::ZERO.extend(1.);
120 let texel = 2. / size as f32;
121 let mut values = projection.to_cols_array();
122 values[12] += (origin.x / texel).round() * texel - origin.x;
123 values[13] += (origin.y / texel).round() * texel - origin.y;
124 projection = Mat4::from_cols_array(&values);
125 }
126 projection * view
127 }
128}
129#[repr(C)]
131#[derive(Clone, Copy, Debug, PartialEq)]
132pub struct Environment {
133 pub points: [f32; 64],
134 pub shadow_matrix: [f32; 16],
135 pub shadow_options: [f32; 4],
136 pub shadow_extra: [f32; 4],
137 pub shadow_direction: [f32; 4],
138 pub light_count: u32,
139 pub shadow_size: u32,
140 pub pcf_radius: u32,
141 pub quality: u32,
142}
143impl Default for Environment {
144 fn default() -> Self {
145 Self {
146 points: [0.; 64],
147 shadow_matrix: Mat4::IDENTITY.to_cols_array(),
148 shadow_options: [0.; 4],
149 shadow_extra: [0.; 4],
150 shadow_direction: [0.; 4],
151 light_count: 0,
152 shadow_size: 0,
153 pcf_radius: 0,
154 quality: 0,
155 }
156 }
157}
158impl Environment {
159 #[cfg(test)]
160 pub(crate) fn update(
161 &mut self,
162 lights: &[PointLight],
163 sun: Option<SunShadow>,
164 quality: Quality,
165 eye: Option<Vec3>,
166 ) {
167 self.update_details(lights, sun, quality, eye, 0, 0);
168 }
169 pub(crate) fn update_details(
170 &mut self,
171 lights: &[PointLight],
172 sun: Option<SunShadow>,
173 quality: Quality,
174 eye: Option<Vec3>,
175 shadows: u8,
176 local_lights: u8,
177 ) {
178 self.quality = quality as u32;
179 self.points = [0.; 64];
180 self.light_count = lights.len().min(match local_lights {
181 1 => 0,
182 2 => 2,
183 3 => 4,
184 4 => 8,
185 _ => quality.point_limit(),
186 }) as u32;
187 let mut order = [0usize; MAX_POINT_LIGHTS];
188 for (i, index) in order.iter_mut().take(lights.len()).enumerate() {
189 *index = i;
190 }
191 if let Some(eye) = eye {
192 order[..lights.len()].sort_unstable_by(|a, b| {
193 lights[*a]
194 .position
195 .distance_squared(eye)
196 .total_cmp(&lights[*b].position.distance_squared(eye))
197 });
198 }
199 for (slot, &index) in order[..self.light_count as usize].iter().enumerate() {
200 let light = lights[index];
201 self.points[slot * 8..slot * 8 + 8].copy_from_slice(&[
202 light.position.x,
203 light.position.y,
204 light.position.z,
205 light.radius,
206 light.color.r,
207 light.color.g,
208 light.color.b,
209 light.intensity,
210 ]);
211 }
212 self.shadow_size = sun.map_or(0, |_| match shadows {
213 1 => 0,
214 2 => 512,
215 3 => 1024,
216 _ => quality.shadow_size(),
217 });
218 self.pcf_radius = u32::from(shadows == 3 || shadows == 0 && quality == Quality::High);
219 if let Some(sun) = sun {
220 self.shadow_matrix = sun.matrix(self.shadow_size).to_cols_array();
221 let d = sun.direction.normalize();
222 self.shadow_direction = [d.x, d.y, d.z, 0.];
223 self.shadow_options = [sun.bias, sun.strength, self.pcf_radius as f32, 0.];
224 self.shadow_extra = [
225 sun.normal_bias,
226 if self.shadow_size > 0 {
227 1. / self.shadow_size as f32
228 } else {
229 0.
230 },
231 0.,
232 0.,
233 ];
234 } else {
235 self.shadow_options = [0.; 4];
236 self.shadow_extra = [0.; 4];
237 self.shadow_direction = [0.; 4];
238 }
239 }
240 pub(crate) fn frustum(self) -> Option<ferravex_graphics::Frustum> {
241 if self.shadow_size == 0 {
242 None
243 } else {
244 ferravex_graphics::Frustum::from_matrix(
245 Mat4::from_cols_array(&self.shadow_matrix),
246 ferravex_graphics::ClipDepth::NegativeOneToOne,
247 )
248 }
249 }
250}
251#[cfg(test)]
252mod tests {
253 use super::*;
254 #[test]
255 fn quality_bounds_and_environment_layout() {
256 assert_eq!(std::mem::size_of::<Environment>(), 384);
257 assert_eq!(std::mem::offset_of!(Environment, light_count), 368);
258 assert_eq!(Quality::Low.shadow_size(), 0);
259 assert_eq!(Quality::High.point_limit(), 8);
260 assert!(
261 !SunShadow {
262 direction: Vec3::ZERO,
263 ..Default::default()
264 }
265 .valid()
266 );
267 }
268 #[test]
269 fn nearest_lights_and_vertical_shadow_direction_are_defined() {
270 assert!(
271 !SunShadow {
272 direction: Vec3::splat(1e30),
273 ..Default::default()
274 }
275 .valid()
276 );
277 let lights = [
278 PointLight {
279 position: Vec3::X * 20.,
280 color: crate::WHITE,
281 radius: 30.,
282 intensity: 1.,
283 },
284 PointLight {
285 position: Vec3::ZERO,
286 color: crate::RED,
287 radius: 3.,
288 intensity: 1.,
289 },
290 PointLight {
291 position: Vec3::Y,
292 color: crate::BLUE,
293 radius: 3.,
294 intensity: 1.,
295 },
296 ];
297 let mut env = Environment::default();
298 env.update(
299 &lights,
300 Some(SunShadow {
301 direction: Vec3::Y,
302 ..Default::default()
303 }),
304 Quality::Low,
305 Some(Vec3::ZERO),
306 );
307 assert_eq!(env.light_count, 2);
308 assert_eq!(env.points[0], 0.);
309 assert_eq!(env.shadow_size, 0);
310 assert!(Mat4::from_cols_array(&env.shadow_matrix).is_finite());
311 env.update(&lights, Some(Default::default()), Quality::High, None);
312 assert!(env.frustum().unwrap().contains_point(Vec3::ZERO));
313 }
314}