Skip to main content

euv_engine/lighting/
fn.rs

1use super::*;
2
3/// Computes the Lambertian (diffuse) contribution of a single light at a
4/// shaded surface point.
5///
6/// The returned color is computed as:
7///
8/// ```text
9/// color * intensity * max(0, dot(normal, light_dir)) * albedo
10/// ```
11///
12/// For directional lights, `light_dir` is the unit direction toward the
13/// light. For point and spot lights, `light_dir` is the unit direction from
14/// the surface position to the light position. The light's color and
15/// intensity are merged multiplicatively with the Lambertian cosine term
16/// and the material's albedo. The caller is expected to have already
17/// applied any falloff factor.
18///
19/// # Arguments
20///
21/// - `&Light` - The light source being evaluated.
22/// - `Vector3D` - The surface normal (expected to be unit length).
23/// - `&Material` - The material at the shaded point.
24///
25/// # Returns
26///
27/// - `Vector3D` - The diffuse contribution of this light.
28pub fn compute_lambert(light: &Light, normal: Vector3D, material: &Material) -> Vector3D {
29    let light_dir: Vector3D = light.get_direction();
30    let cos: f64 = normal.dot(light_dir).max(0.0);
31    let intensity: f64 = light.get_intensity();
32    let color: Vector3D = light.get_color();
33    let albedo: Vector3D = material.get_albedo();
34    let k: f64 = intensity * cos;
35    Vector3D::new(
36        color.get_x() * albedo.get_x() * k,
37        color.get_y() * albedo.get_y() * k,
38        color.get_z() * albedo.get_z() * k,
39    )
40}
41
42/// Computes the Blinn-Phong specular contribution of a single light.
43///
44/// Returns:
45///
46/// ```text
47/// light_color * intensity * pow(max(0, dot(reflect(-l, n), v)), shininess) * specular
48/// ```
49///
50/// where `reflect(-l, n)` is the mirror reflection of the light direction
51/// about the surface normal and `v` is the unit view direction from the
52/// shaded point toward the eye.
53///
54/// # Arguments
55///
56/// - `&Light` - The light source.
57/// - `Vector3D` - The surface normal (unit length).
58/// - `Vector3D` - The unit view direction (from the surface toward the eye).
59/// - `&Material` - The material at the shaded point.
60///
61/// # Returns
62///
63/// - `Vector3D` - The specular contribution of this light.
64pub fn compute_phong(
65    light: &Light,
66    normal: Vector3D,
67    view_dir: Vector3D,
68    material: &Material,
69) -> Vector3D {
70    let light_dir: Vector3D = light.get_direction();
71    let reflect: Vector3D = (light_dir - normal.scaled(2.0 * light_dir.dot(normal))).normalized();
72    let spec_factor: f64 = reflect
73        .dot(view_dir)
74        .max(0.0)
75        .powf(material.get_shininess());
76    let specular: f64 = material.get_specular();
77    let intensity: f64 = light.get_intensity();
78    let color: Vector3D = light.get_color();
79    let k: f64 = intensity * spec_factor * specular;
80    Vector3D::new(color.get_x() * k, color.get_y() * k, color.get_z() * k)
81}
82
83/// Applies the inverse-square falloff formula
84/// `1.0 / (1.0 + falloff * d²)`, clamped to a non-negative result.
85///
86/// # Arguments
87///
88/// - `f64` - The distance from the light source. Negative values are
89///   treated as zero.
90/// - `f64` - The falloff coefficient (0.0 disables falloff).
91///
92/// # Returns
93///
94/// - `f64` - A non-negative scalar in the range 0.0..=1.0.
95pub fn apply_falloff(distance: f64, falloff: f64) -> f64 {
96    let d: f64 = distance.abs();
97    let denom: f64 = 1.0 + falloff * d * d;
98    (1.0 / denom).max(0.0)
99}
100
101/// Intersects a ray with a sphere centered at `center` with radius `radius`.
102///
103/// Uses the standard quadratic-form ray-sphere test. Returns `Some((t, n))`
104/// where `t` is the nearest positive intersection distance along the ray
105/// and `n` is the outward unit normal at the hit point. Returns `None` if
106/// the ray misses.
107///
108/// # Arguments
109///
110/// - `Vector3D` - The ray origin.
111/// - `Vector3D` - The ray direction (expected to be unit length).
112/// - `Vector3D` - The sphere center.
113/// - `f64` - The sphere radius (must be positive).
114///
115/// # Returns
116///
117/// - `Option<(f64, Vector3D)>` - The hit distance and surface normal, or
118///   `None` on miss.
119pub fn ray_sphere_intersect(
120    origin: Vector3D,
121    dir: Vector3D,
122    center: Vector3D,
123    radius: f64,
124) -> Option<(f64, Vector3D)> {
125    let oc: Vector3D = origin - center;
126    let b: f64 = oc.dot(dir);
127    let c: f64 = oc.dot(oc) - radius * radius;
128    let disc: f64 = b * b - c;
129    if disc < 0.0 {
130        return None;
131    }
132    let sq: f64 = disc.sqrt();
133    let t1: f64 = -b - sq;
134    let t2: f64 = -b + sq;
135    let t: f64 = if t1 >= 0.0 {
136        t1
137    } else if t2 >= 0.0 {
138        t2
139    } else {
140        return None;
141    };
142    let hit: Vector3D = origin + dir.scaled(t);
143    let normal: Vector3D = (hit - center).normalized();
144    Some((t, normal))
145}
146
147/// Intersects a ray with an axis-aligned bounding box using the slab method.
148///
149/// # Arguments
150///
151/// - `Vector3D` - The ray origin.
152/// - `Vector3D` - The ray direction (expected to be unit length).
153/// - `Vector3D` - The AABB minimum corner.
154/// - `Vector3D` - The AABB maximum corner.
155///
156/// # Returns
157///
158/// - `Option<(f64, f64, Vector3D)>` - `(t_near, t_far, normal)` on hit, or
159///   `None` if the ray misses or is parallel to the slab.
160pub fn ray_aabb_intersect(
161    origin: Vector3D,
162    dir: Vector3D,
163    aabb_min: Vector3D,
164    aabb_max: Vector3D,
165) -> Option<(f64, f64, Vector3D)> {
166    let inv_dir: Vector3D = Vector3D::new(1.0 / dir.get_x(), 1.0 / dir.get_y(), 1.0 / dir.get_z());
167    let t1x: f64 = (aabb_min.get_x() - origin.get_x()) * inv_dir.get_x();
168    let t2x: f64 = (aabb_max.get_x() - origin.get_x()) * inv_dir.get_x();
169    let t1y: f64 = (aabb_min.get_y() - origin.get_y()) * inv_dir.get_y();
170    let t2y: f64 = (aabb_max.get_y() - origin.get_y()) * inv_dir.get_y();
171    let t1z: f64 = (aabb_min.get_z() - origin.get_z()) * inv_dir.get_z();
172    let t2z: f64 = (aabb_max.get_z() - origin.get_z()) * inv_dir.get_z();
173    let tmin_x: f64 = t1x.min(t2x);
174    let tmax_x: f64 = t1x.max(t2x);
175    let tmin_y: f64 = t1y.min(t2y);
176    let tmax_y: f64 = t1y.max(t2y);
177    let tmin_z: f64 = t1z.min(t2z);
178    let tmax_z: f64 = t1z.max(t2z);
179    let t_near: f64 = tmin_x.max(tmin_y).max(tmin_z);
180    let t_far: f64 = tmax_x.min(tmax_y).min(tmax_z);
181    if t_near > t_far || t_far < 0.0 {
182        return None;
183    }
184    let hit: Vector3D = origin + dir.scaled(t_near);
185    let cx: f64 = (aabb_min.get_x() + aabb_max.get_x()) * 0.5;
186    let cy: f64 = (aabb_min.get_y() + aabb_max.get_y()) * 0.5;
187    let cz: f64 = (aabb_min.get_z() + aabb_max.get_z()) * 0.5;
188    let dx: f64 = hit.get_x() - cx;
189    let dy: f64 = hit.get_y() - cy;
190    let dz: f64 = hit.get_z() - cz;
191    let ex: f64 = (aabb_max.get_x() - aabb_min.get_x()) * 0.5;
192    let ey: f64 = (aabb_max.get_y() - aabb_min.get_y()) * 0.5;
193    let ez: f64 = (aabb_max.get_z() - aabb_min.get_z()) * 0.5;
194    let ax: f64 = dx.abs() / ex.max(EPSILON);
195    let ay: f64 = dy.abs() / ey.max(EPSILON);
196    let az: f64 = dz.abs() / ez.max(EPSILON);
197    let normal: Vector3D = if ax >= ay && ax >= az {
198        Vector3D::new(dx.signum(), 0.0, 0.0)
199    } else if ay >= az {
200        Vector3D::new(0.0, dy.signum(), 0.0)
201    } else {
202        Vector3D::new(0.0, 0.0, dz.signum())
203    };
204    Some((t_near, t_far, normal))
205}
206
207/// Computes a soft-shadow visibility factor in the range 0.0..=1.0.
208///
209/// Casts a single ray from `origin` toward `light_pos` and checks whether
210/// any sphere in `occluders` blocks the path. Returns 1.0 when no occluder
211/// is intersected, otherwise returns 0.0 (binary shadow). A future
212/// refinement could sample multiple rays to approximate penumbra.
213///
214/// # Arguments
215///
216/// - `Vector3D` - The surface point casting the shadow ray.
217/// - `Vector3D` - The light position to test against.
218/// - `&[(Vector3D, f64)]` - A slice of `(center, radius)` occluder spheres.
219///
220/// # Returns
221///
222/// - `f64` - 1.0 if the light is visible, 0.0 if fully occluded.
223pub fn soft_shadow_factor(
224    origin: Vector3D,
225    light_pos: Vector3D,
226    occluders: &[(Vector3D, f64)],
227) -> f64 {
228    let to_light: Vector3D = light_pos - origin;
229    let dist: f64 = to_light.magnitude();
230    if dist < EPSILON {
231        return 1.0;
232    }
233    let dir: Vector3D = to_light.scaled(1.0 / dist);
234    for &(center, radius) in occluders.iter() {
235        if let Some((t, _)) = ray_sphere_intersect(origin, dir, center, radius)
236            && t > EPSILON
237            && t < dist - EPSILON
238        {
239            return 0.0;
240        }
241    }
242    1.0
243}