From fca01e05f4dd056cff0b47d4ebf5edfd94605dde Mon Sep 17 00:00:00 2001 From: numzero Date: Sat, 14 Sep 2024 15:14:15 +0300 Subject: [PATCH] Extract mesh tracing into the lib crate --- src/bin/mesh/main.rs | 46 ++------------------------------------------ src/lib.rs | 1 + src/mesh_tracer.rs | 40 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 44 deletions(-) diff --git a/src/bin/mesh/main.rs b/src/bin/mesh/main.rs index 37a8e45..50d78e8 100644 --- a/src/bin/mesh/main.rs +++ b/src/bin/mesh/main.rs @@ -1,5 +1,6 @@ use glam::*; -use refraction::mesh_loader::{load_mesh, Face}; +use refraction::mesh_loader::load_mesh; +use refraction::mesh_tracer::{trace_to_mesh, Mesh}; use show_image::{ImageInfo, ImageView, WindowOptions}; use std::env; use std::error::Error; @@ -59,44 +60,6 @@ fn ypr_to_mat(ypr: Vec3) -> Mat3 { m_roll * m_pitch * m_yaw } -type Mesh = [Face]; - -struct TraceResult { - distance: f32, - normal: Vec3, -} - -fn trace_to_mesh(mesh: &Mesh, base: Vec3, ray: Vec3) -> Option { - let mut ret: Option = None; - let mut dist = f32::INFINITY; - for f in mesh { - let fs = (0..3).map(|k| edge_dist(f.vertices[k], f.vertices[(k + 1) % 3], base, ray)); - if fs.into_iter().all(|f| f >= 0.0) { - let m = mat3( - f.vertices[1] - f.vertices[0], - f.vertices[2] - f.vertices[0], - -ray, - ); - let m = m.inverse(); - let rel = m * (base - f.vertices[0]); - if rel.z > dist { - continue; - } - dist = rel.z; - ret = Some(TraceResult { - distance: rel.z, - normal: f.normal, - }); - } - } - ret -} - -struct Location { - pos: Vec3, - rot: Vec4, -} - fn render(mesh: &Mesh, camera: impl Fn(Vec2) -> (Vec3, Vec3)) -> Image { let bkg = vec3(0.0, 0.0, 0.0); let mut img = Image { @@ -159,8 +122,3 @@ fn main() -> Result<(), Box> { } } } - -fn edge_dist(a: Vec3, b: Vec3, base: Vec3, dir: Vec3) -> f32 { - // Note: given that the input is not arbitrary but comes from a cartesian product of certain (a, b) pairs and certain (base, dir) pairs, this can be optimized from Cnm to an+bm+cnm with c Option { + let mut ret: Option = None; + let mut dist = f32::INFINITY; + for f in mesh { + let fs = (0..3).map(|k| edge_dist(f.vertices[k], f.vertices[(k + 1) % 3], base, ray)); + if fs.into_iter().all(|f| f >= 0.0) { + let m = mat3( + f.vertices[1] - f.vertices[0], + f.vertices[2] - f.vertices[0], + -ray, + ); + let m = m.inverse(); + let rel = m * (base - f.vertices[0]); + if rel.z > dist { + continue; + } + dist = rel.z; + ret = Some(TraceResult { + distance: rel.z, + normal: f.normal, + }); + } + } + ret +} + +fn edge_dist(a: Vec3, b: Vec3, base: Vec3, dir: Vec3) -> f32 { + // Note: given that the input is not arbitrary but comes from a cartesian product of certain (a, b) pairs and certain (base, dir) pairs, this can be optimized from Cnm to an+bm+cnm with c