euv-engine 0.31.3

A high-performance 2D game engine built on the euv framework, featuring ECS, fixed-timestep game loop, canvas rendering, physics, collision detection, sprite animation, and audio.
Documentation
use super::*;

/// Implements factory constructors and accessors for [`Ray`] and
/// [`Occluder`].
impl Ray {
    /// Creates a new ray starting at `origin` pointing in `direction`.
    ///
    /// `t_min` and `t_max` default to [`RAYTRACE_DEFAULT_T_MIN`] and
    /// [`RAYTRACE_DEFAULT_T_MAX`]. `depth` defaults to 0.
    ///
    /// # Arguments
    ///
    /// - `Vector3D` - The ray origin.
    /// - `Vector3D` - The unit direction.
    ///
    /// # Returns
    ///
    /// - `Ray` - The new ray.
    pub fn new(origin: Vector3D, direction: Vector3D) -> Ray {
        Ray {
            origin,
            direction,
            t_min: RAYTRACE_DEFAULT_T_MIN,
            t_max: RAYTRACE_DEFAULT_T_MAX,
            depth: 0,
        }
    }

    /// Computes the world-space point at distance `t` along this ray.
    ///
    /// # Arguments
    ///
    /// - `f64` - The ray parameter.
    ///
    /// # Returns
    ///
    /// - `Vector3D` - `origin + direction * t`.
    pub fn at(&self, t: f64) -> Vector3D {
        self.get_origin() + self.get_direction().scaled(t)
    }

    /// Returns a clone of this ray with `depth` replaced by `depth`.
    ///
    /// # Arguments
    ///
    /// - `u32` - The new recursion depth.
    ///
    /// # Returns
    ///
    /// - `Ray` - The cloned ray with updated depth.
    pub fn with_depth(&self, depth: u32) -> Ray {
        Ray {
            origin: self.get_origin(),
            direction: self.get_direction(),
            t_min: self.get_t_min(),
            t_max: self.get_t_max(),
            depth,
        }
    }

    /// Returns a clone of this ray with its parameter range replaced.
    ///
    /// The new bounds are taken as given, so an inverted or non-finite
    /// range is representable; both query entry points reject such a ray
    /// as untraceable rather than letting `NaN` comparisons decide the
    /// outcome.
    ///
    /// # Arguments
    ///
    /// - `f64` - The minimum accepted hit parameter.
    /// - `f64` - The maximum accepted hit parameter.
    ///
    /// # Returns
    ///
    /// - `Ray` - The cloned ray with the new range.
    pub fn with_range(&self, t_min: f64, t_max: f64) -> Ray {
        Ray {
            origin: self.get_origin(),
            direction: self.get_direction(),
            t_min,
            t_max,
            depth: self.get_depth(),
        }
    }

    /// Intersects this ray with a triangle using the Moller-Trumbore
    /// algorithm, keeping only hits inside this ray's `t_min`..=`t_max`
    /// range.
    ///
    /// The test is two-sided: a hit from either face counts, and the
    /// returned normal always faces against the ray direction. This is the
    /// range-clamped counterpart of the free
    /// [`intersect_triangle`](crate::intersect_triangle), which reports the
    /// raw distance however far away the triangle is.
    ///
    /// # Arguments
    ///
    /// - `[Vector3D; 3]` - The three triangle vertices in winding order.
    ///
    /// # Returns
    ///
    /// - `Option<(f64, Vector3D)>` - The hit distance along the ray and the
    ///   unit normal oriented against the ray direction, or `None` on miss.
    pub fn intersect_triangle(&self, vertices: [Vector3D; 3]) -> Option<(f64, Vector3D)> {
        let (t, normal): (f64, Vector3D) = intersect_triangle(self, vertices)?;
        if t < self.get_t_min() || t > self.get_t_max() {
            return None;
        }
        Some((t, normal))
    }
}

/// Implements factory constructors for [`Occluder`].
impl Occluder {
    /// Creates a spherical occluder centered at `center` with `radius`.
    ///
    /// # Arguments
    ///
    /// - `Vector3D` - The sphere center.
    /// - `f64` - The sphere radius.
    /// - `Material` - The surface material.
    ///
    /// # Returns
    ///
    /// - `Occluder` - The new sphere occluder.
    pub fn sphere(center: Vector3D, radius: f64, material: Material) -> Occluder {
        Occluder {
            kind: OccluderKind::Sphere,
            center,
            extent: Vector3D::new(radius, radius, radius),
            vertices: [center; 3],
            material,
        }
    }

    /// Creates an axis-aligned bounding-box occluder from `min` to `max`.
    ///
    /// # Arguments
    ///
    /// - `Vector3D` - The AABB minimum corner.
    /// - `Vector3D` - The AABB maximum corner.
    /// - `Material` - The surface material.
    ///
    /// # Returns
    ///
    /// - `Occluder` - The new AABB occluder.
    pub fn aabb(min: Vector3D, max: Vector3D, material: Material) -> Occluder {
        Occluder {
            kind: OccluderKind::Aabb,
            center: min,
            extent: max,
            vertices: [min; 3],
            material,
        }
    }

    /// Creates a triangular occluder from its three vertices.
    ///
    /// The vertex order fixes the geometric winding; because the
    /// intersection test is two-sided the winding does not affect which
    /// faces produce hits, only the raw cross-product normal before it is
    /// oriented against the incoming ray.
    ///
    /// # Arguments
    ///
    /// - `Vector3D` - The first triangle vertex.
    /// - `Vector3D` - The second triangle vertex.
    /// - `Vector3D` - The third triangle vertex.
    /// - `Material` - The surface material.
    ///
    /// # Returns
    ///
    /// - `Occluder` - The new triangle occluder.
    pub fn triangle(v0: Vector3D, v1: Vector3D, v2: Vector3D, material: Material) -> Occluder {
        Occluder {
            kind: OccluderKind::Triangle,
            center: Vector3D::zero(),
            extent: Vector3D::zero(),
            vertices: [v0, v1, v2],
            material,
        }
    }

    /// Returns a list of `(center, radius)` sphere tuples approximating
    /// this occluder, suitable for [`soft_shadow_factor`].
    ///
    /// For sphere occluders this returns `(center, radius)`. For AABB
    /// occluders the bounding sphere is computed conservatively from the
    /// AABB extents.
    ///
    /// # Returns
    ///
    /// - `Vec<(Vector3D, f64)>` - One bounding sphere per occluder.
    pub fn occluder_points(&self) -> Vec<(Vector3D, f64)> {
        collect_occluder_points(from_ref(self))
    }
}

/// Implements the constructor and zero-allocation tracing entry points for
/// [`RayTraceScene`].
impl RayTraceScene {
    /// Creates a new scene taking ownership of `occluders` and precomputing
    /// both the bounding volume hierarchy and the `(center, radius)` shadow
    /// bounding spheres used by [`soft_shadow_factor`].
    ///
    /// The hierarchy is built once here; every later query reuses it, so
    /// the cost of the BVH never appears in a per-ray measurement. The
    /// public surface is unchanged from the pre-BVH constructor, which
    /// takes the occluder list by value.
    ///
    /// # Arguments
    ///
    /// - `Vec<Occluder>` - All occluding surfaces in the scene.
    ///
    /// # Returns
    ///
    /// - `RayTraceScene` - The new scene with precomputed shadow data.
    pub fn new(occluders: Vec<Occluder>) -> RayTraceScene {
        let shadow_points: Vec<(Vector3D, f64)> = collect_occluder_points(&occluders);
        let (nodes, indices): (Vec<RayTraceNode>, Vec<usize>) = build_bvh(&occluders);
        RayTraceScene {
            occluders,
            nodes,
            indices,
            shadow_points,
        }
    }

    /// Iteratively traces a ray through the scene and returns the final
    /// shaded color, using the [`RAYTRACE_DEFAULT_MAX_BOUNCES`] constant as
    /// the bounce limit.
    ///
    /// Performs no heap allocation per ray or per bounce: the shadow
    /// bounding spheres precomputed at construction are reused, and no
    /// [`Material`] is cloned. Use [`RayTraceScene::trace_with_bounces`] to
    /// override the bounce limit.
    ///
    /// # Arguments
    ///
    /// - `Ray` - The ray to trace.
    /// - `&LightingUniforms` - Lighting parameters used during shading.
    ///
    /// # Returns
    ///
    /// - `Vector3D` - The final traced color.
    pub fn trace(&self, ray: Ray, lights: &LightingUniforms) -> Vector3D {
        self.trace_with_bounces(ray, lights, RAYTRACE_DEFAULT_MAX_BOUNCES)
    }

    /// Iteratively traces a ray through the scene with an explicit bounce
    /// limit and returns the final shaded color.
    ///
    /// On a miss the ambient color scaled by the accumulated specular
    /// throughput is added. On a hit the surface material is evaluated with
    /// [`LightingUniforms::shade`] and, when the hit material has a
    /// non-zero specular component, the trace continues with a reflected
    /// ray up to `max_bounces` times (incrementing the ray's `depth` field
    /// per bounce).
    ///
    /// # Arguments
    ///
    /// - `Ray` - The ray to trace.
    /// - `&LightingUniforms` - Lighting parameters used during shading.
    /// - `u32` - The maximum number of bounces allowed for this ray.
    ///
    /// # Returns
    ///
    /// - `Vector3D` - The final traced color.
    pub fn trace_with_bounces(
        &self,
        ray: Ray,
        lights: &LightingUniforms,
        max_bounces: u32,
    ) -> Vector3D {
        trace_bounces(ray, self, lights, max_bounces)
    }

    /// Finds the closest intersection between a ray and the scene
    /// occluders.
    ///
    /// The winning occluder's [`Material`] is cloned exactly once, when the
    /// returned [`Hit`] is constructed; losing candidates are never cloned.
    /// Traversal itself resolves every candidate through the scene's
    /// bounding volume hierarchy, so the cost scales with the parts of the
    /// hierarchy the ray actually crosses rather than with the occluder
    /// count.
    ///
    /// # Arguments
    ///
    /// - `&Ray` - The ray to test.
    ///
    /// # Returns
    ///
    /// - `Option<Hit>` - The closest hit, or `None` if the ray misses.
    pub fn closest_hit(&self, ray: &Ray) -> Option<Hit> {
        let occluders: &[Occluder] = self.get_occluders();
        closest_hit_indexed(ray, self).map(
            |(index, t, position, normal): (usize, f64, Vector3D, Vector3D)| Hit {
                t,
                position,
                normal,
                material: occluders[index].get_material().clone(),
            },
        )
    }

    /// Reports whether anything in the scene blocks the ray's parameter
    /// range.
    ///
    /// This is the any-hit counterpart to [`RayTraceScene::closest_hit`],
    /// built for shadow segments: it stops at the first blocker instead of
    /// resolving the whole hierarchy, so a fully occluded light costs less
    /// than a fully visible one. An empty scene reports `false`, and a ray
    /// with an inverted or non-finite range reports `false` rather than
    /// inventing a hit.
    ///
    /// # Arguments
    ///
    /// - `&Ray` - The ray to test.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when at least one occluder intersects the range.
    pub fn occluded(&self, ray: &Ray) -> bool {
        occluded_indexed(ray, self)
    }
}