Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

BK2: done: each texel's place in the world, and the atlas split out as raea-sys-atlas

shinyobjectz0bdc8714a6ac
diff --git a/Cargo.lock b/Cargo.lock
index db646ea5..1d9ad9e1 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -15793,6 +15793,17 @@ dependencies = [
"raea-core-animate",
]
+[[package]]
+name = "raea-sys-atlas"
+version = "0.1.0"
+dependencies = [
+ "parry3d",
+ "raea-core-meshcheck",
+ "raea-sys-glb",
+ "rayon",
+ "serde_json",
+]
+
[[package]]
name = "raea-sys-bake"
version = "0.1.0"
@@ -16243,6 +16254,17 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "raea-sys-lightbake"
+version = "0.1.0"
+dependencies = [
+ "gltf",
+ "parry3d",
+ "raea-sys-atlas",
+ "rayon",
+ "serde_json",
+]
+
[[package]]
name = "raea-sys-lod"
version = "0.1.0"
@@ -16702,7 +16724,7 @@ version = "0.1.0"
dependencies = [
"image",
"parry3d",
- "raea-core-meshcheck",
+ "raea-sys-atlas",
"raea-sys-damage",
"raea-sys-exposure",
"raea-sys-glb",
diff --git a/Cargo.toml b/Cargo.toml
index ab541e86..0135c774 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -200,6 +200,8 @@ members = [
"runtime/shared",
"apps/ask",
"apps/lightbake",
+ "systems/lightbake",
+ "systems/atlas",
"apps/double",
"apps/check",
"apps/check/cause",
diff --git a/docs/bake.feature b/docs/bake.feature
index b98fcea7..51e28c42 100644
--- a/docs/bake.feature
+++ b/docs/bake.feature
@@ -99,7 +99,7 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
And one second UV set serves the lightmap and raea/wear's cause maps (Shane, 11-23: the bake works with the wear
SDK): systems/weathering (docs/wear.feature WR1) already lays TEXCOORD_1 out for its cause maps and refuses a
material that reads it, so a second atlas would collide. The light bake lays its maps over weathering's atlas,
- `raea_sys_weathering::layout`, with the request `raea wear bake` takes: given the wear bake's own request, it
+ `raea_sys_atlas::layout` (in raea-sys-weathering when BK1 landed; split out at BK2), with the request `raea wear bake` takes: given the wear bake's own request, it
is the wear bake's atlas byte for byte (the test says so); a light-only bake asks {env: {density: texels,
max_side}}
And built 11-23 after measuring the two on the test set: xatlas (MIT, vendored and built through cc, a map per
@@ -126,16 +126,45 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
don't change (weathering's bytes are the same)
@needs:BK1
+ @done
Scenario: BK2. Each texel's place in the world
Given the plan
| crate | file | lines | job |
- | raea-sys-lightbake | systems/lightbake/src/texels.rs | 160 | the layout's texels (BK1: weathering's world point, normal and triangle under each, an edge band of 0.75 of a texel) to the trace's buffers; the inside test and the offset |
+ | raea-sys-atlas | systems/atlas/src/lib.rs | 120 | the atlas both bakes share, split out of raea-sys-weathering (it was at 1999 of 2000 lines and a system may build only on a facility): Ask, layout() |
+ | raea-sys-atlas | systems/atlas/src/scene.rs | 323 | moved from raea-sys-weathering as it was |
+ | raea-sys-atlas | systems/atlas/src/charts.rs | 436 | moved |
+ | raea-sys-atlas | systems/atlas/src/merge.rs | 193 | moved |
+ | raea-sys-atlas | systems/atlas/src/rays.rs | 80 | the hidden-triangle step and the samples, moved from weathering's rays.rs |
+ | raea-sys-lightbake | systems/lightbake/src/lib.rs | 20 | the crate: the bake over raea/wear's atlas |
+ | raea-sys-lightbake | systems/lightbake/src/texels.rs | 160 | the layout's texels (BK1: weathering's world point, normal and triangle under each, an edge band of 0.75 of a texel) with their ray origins; the inside test; the model's world triangles |
+ | raea-sys-lightbake | systems/lightbake/src/texels/tests.rs | 160 | a slab with a block sunk in it and a box set on it by its node: points on the surface, the sunk part marked, the open not; the same texels twice; a worn model's request gives its wear atlas; the measured run |
Then each mesh's atlas has, per texel, its world position, shading normal and whether it is covered, read from
BK1's layout (charts.rs already rasterizes every triangle in its chart, a triangle under a texel included,
and fills the edge band), not rasterized a second time
And a texel whose position is inside other geometry (a table leg's foot in the floor, a wall's end inside the
next wall) is found by a short ray test and marked, so it neither goes black nor leaks light into the bake
And positions are offset along the normal by a scale-aware epsilon, so the trace never hits its own surface
+ And built 11-23: `raea_sys_lightbake::texels::texels(glb, request)` lays the model out (BK1's layout, raea_sys_atlas::layout; the
+ light-only request is `request(texels, max_side)`, a worn model passes its wear bake's), reads the layout's
+ model back as world triangles (each node's transform down its children) into a parry3d BVH, moves each point
+ off its surface by 1e-5 of the model's size or farthest coordinate (at least 10 microns), and casts 16
+ cosine-weighted rays from each: a texel is inside when at least half its rays meet a back face and more meet
+ back faces than front ones (a floor that is one plane is met from below one way and not at all the other).
+ CPU and rayon for now, as weathering's own rays; BK3's GPU pass may take the test over
+ And raea-sys-atlas (a facility) now holds the atlas, out of raea-sys-weathering, so the light bake builds on it
+ and not sideways on another system: weathering's bakes are the same bytes and keys after the move (the table
+ and window sets baked before and after, 12 files equal), and its 11 tests pass
+ And measured 11-23 at 64 texels a metre, debug build on the M5 Pro (BK1's layout included in both times)
+ | set | atlas | texels | inside | offset | layout | with texels |
+ | table | 2048x1008 | 1 549 350 | 10 366 (0.67%) | 0.17 mm | 0.29 s | 3.4 s |
+ | cornell | 1024x296 | 232 060 | 17 345 (7.5%) | 0.04 mm | 0.05 s | 1.3 s |
+ | window | 2048x644 | 979 867 | 96 445 (9.8%) | 0.08 mm | 0.21 s | 5.1 s |
+ | atelier | 4096x1820 | 4 136 248 | 200 649 (4.9%) | 0.15 mm | 41 s | 70 s |
+ And what they say: what's marked is what overlaps. In the window room it is the band where each wall box runs
+ into the next wall, the floor and the ceiling, the floor under the sofa's and table's feet, and the walls
+ behind the window's piers. Those are a tenth of its texels, which would have gone black or leaked the outside
+ in. The texel step costs seconds in a debug build. The atelier's layout takes 41 s in debug against 1.6 s in
+ a release raea (BK1), so the bar's 60 s is the trace's to spend
@needs:BK2
Scenario: BK3. The light that bounces, traced on raea's ray tracer
diff --git a/docs/wear.feature b/docs/wear.feature
index 191870fe..d4fafa1b 100644
--- a/docs/wear.feature
+++ b/docs/wear.feature
@@ -58,7 +58,7 @@ Feature: raea/wear, weathering that has a cause
| absorb | a chart under 1.5 texels across (or 6 in area) folded into the big chart within 35 cm of its plane | a reveal or a frame's face reads the wall it sits on |
| hide | a triangle whose centre and three corners all see the back of something in nine rays of ten: no texels | ground under a house, party walls against each other |
And a level chart is turned in its plane to its smallest rectangle; a wall keeps its rows down the fall line
- And the atlas is also the light bake's (docs/bake.feature BK1, 11-23): `layout(glb, request)` returns it alone,
+ And the atlas is also the light bake's (docs/bake.feature BK1, 11-23): raea_sys_atlas::layout(glb, request) returns it alone,
with no causes traced, and given a bake's request it is that bake's atlas byte for byte, so a lightmap and the
cause maps read one TEXCOORD_1. Measured there against xatlas, these charts were 160 times faster on the
atelier's 655 000 triangles, with half the charts and less seam and stretch
@@ -67,12 +67,14 @@ Feature: raea/wear, weathering that has a cause
code: plaster, brick, sandstone, granite, wood, iron, zinc, copper, slate, felt, glass, enamel, brass, ground
And the crate, as built
| file | lines | job |
- | systems/weathering/src/lib.rs | 265 | the request, its content key, the store, the bake's steps; layout() alone |
+ | systems/weathering/src/lib.rs | 211 | the request, its content key, the store, the bake's steps |
+ | systems/atlas/src/lib.rs | 112 | raea-sys-atlas (a facility, split out 11-23): Ask (up, north, density, max_side from the request's env), layout() alone |
| systems/glb/src/lib.rs | 208 | raea-sys-glb (a facility): the .glb read, unused data dropped, written |
- | systems/weathering/src/scene.rs | 311 | glTF to triangles with a class each, and back with TEXCOORD_1 |
- | systems/weathering/src/charts.rs | 429 | charts, their orientation and packing, texel to surface point |
- | systems/weathering/src/merge.rs | 198 | merge, split and absorb |
- | systems/weathering/src/rays.rs | 287 | hidden triangles; sky, sun, cavity, open, edge and ground |
+ | systems/atlas/src/scene.rs | 323 | glTF to triangles with a class each, and back with TEXCOORD_1 |
+ | systems/atlas/src/charts.rs | 436 | charts, their orientation and packing, texel to surface point |
+ | systems/atlas/src/merge.rs | 193 | merge, split and absorb |
+ | systems/atlas/src/rays.rs | 78 | hidden triangles; the samples both bakes' rays share |
+ | systems/weathering/src/rays.rs | 193 | sky, sun, cavity, open, edge and ground |
| systems/weathering/src/maps.rs | 51 | the maps as PNGs, dilated over the gutters |
| systems/weathering/src/tests.rs | 279 | synthetic fronts checked by number |
And proof (`cargo test -p raea-sys-weathering`, 9 tests): under a 1 m overhang the sky term is under 0.4 of an open
diff --git a/systems/atlas/Cargo.toml b/systems/atlas/Cargo.toml
new file mode 100644
index 00000000..c44a2901
--- /dev/null
+++ b/systems/atlas/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "raea-sys-atlas"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "The second UV set raea's bakes share: planar charts packed into one atlas over a glTF, and each texel's point"
+
+[dependencies]
+# triangle BVH and ray casts (Apache-2.0); in the tree already through rapier3d
+parry3d = "0.31"
+rayon = "1"
+serde_json = "1"
+# a union-find's root (charts merged by shared edges)
+raea-core-meshcheck = { path = "../../core/meshcheck" }
+raea-sys-glb = { path = "../glb" }
diff --git a/systems/weathering/src/charts.rs b/systems/atlas/src/charts.rs
similarity index 97%
rename from systems/weathering/src/charts.rs
rename to systems/atlas/src/charts.rs
index 4b1bebc7..a48a800f 100644
--- a/systems/weathering/src/charts.rs
+++ b/systems/atlas/src/charts.rs
@@ -12,18 +12,18 @@ use std::collections::HashMap;
use parry3d::glamx::Vec3;
-use super::{Env, R};
+use super::{Ask, R};
use parry3d::shape::TriMesh;
use crate::scene::Scene;
use crate::{merge, rays};
/// One texel round each chart: enough for a bilinear read with no mips (a mipped read needs 2^k for k levels, WR8).
-pub(crate) const GUTTER: u32 = 1;
+pub const GUTTER: u32 = 1;
const CHART_DEG: f32 = 15.0;
const NONE: u32 = u32::MAX;
-pub(crate) struct Texel {
+pub struct Texel {
pub x: u16,
pub y: u16,
pub p: Vec3,
@@ -31,7 +31,7 @@ pub(crate) struct Texel {
pub tri: u32,
}
-pub(crate) struct Atlas {
+pub struct Atlas {
pub w: u32,
pub h: u32,
/// the density the whole-model class got, and each chart's
@@ -48,7 +48,6 @@ pub(crate) struct Atlas {
pub index: Vec<Vec<u32>>,
pub uv: Vec<Vec<[f32; 2]>>,
/// each chart's rectangle in the atlas, gutters included: x, y, w, h (the tests read it)
- #[cfg_attr(not(test), allow(dead_code))]
pub rects: Vec<[u32; 4]>,
}
@@ -67,7 +66,7 @@ impl Atlas {
}
}
-pub(crate) struct Chart {
+pub struct Chart {
pub tris: Vec<u32>,
/// the plane: its normal, its offset (n.p), and the basis across it
pub n: Vec3,
@@ -134,7 +133,7 @@ impl Chart {
}
}
/// The density its surfaces ask: the highest of their classes'.
- pub fn asked(&self, sc: &Scene, env: &Env) -> f32 {
+ pub fn asked(&self, sc: &Scene, env: &Ask) -> f32 {
self.tris.iter().map(|&t| env.density_of(sc.class[t as usize])).fold(0.0, f32::max).max(0.25)
}
pub fn st(&self, p: Vec3) -> (f32, f32) {
@@ -152,7 +151,7 @@ fn weld(p: Vec3) -> (i64, i64, i64) {
}
/// The basis of a plane with normal n: u along it horizontally (east on a level face), b up it.
-fn basis(n: Vec3, env: &Env) -> (Vec3, Vec3) {
+fn basis(n: Vec3, env: &Ask) -> (Vec3, Vec3) {
let u = if n.dot(env.up).abs() < 0.95 {
env.up.cross(n).normalize()
} else {
@@ -162,7 +161,7 @@ fn basis(n: Vec3, env: &Env) -> (Vec3, Vec3) {
(u, n.cross(u).normalize())
}
-fn charts_of(sc: &Scene, env: &Env, chart_of: &mut [u32]) -> Vec<Chart> {
+fn charts_of(sc: &Scene, env: &Ask, chart_of: &mut [u32]) -> Vec<Chart> {
let cos = CHART_DEG.to_radians().cos();
let mut out = Vec::new();
for pr in &sc.prims {
@@ -249,7 +248,7 @@ fn pack(cs: &mut [Chart], k: f32, side: u32) -> Option<(u32, u32)> {
Some((w, (y + shelf).div_ceil(4) * 4))
}
-pub(crate) fn build(sc: &Scene, env: &Env, mesh: &TriMesh) -> R<Atlas> {
+pub fn build(sc: &Scene, env: &Ask, mesh: &TriMesh) -> R<Atlas> {
let mut chart_of = vec![NONE; sc.tri.len()];
// triangles inside a closed shell are set aside first, so no chart starts from or runs over them
let inside = rays::hidden(sc, mesh);
diff --git a/systems/atlas/src/lib.rs b/systems/atlas/src/lib.rs
new file mode 100644
index 00000000..14aa1e59
--- /dev/null
+++ b/systems/atlas/src/lib.rs
@@ -0,0 +1,112 @@
+//! The second UV set raea's bakes share (docs/wear.feature WR1, docs/bake.feature BK1): planar charts packed into
+//! one atlas over a glTF's static meshes, and each texel's point on the surface. raea/wear's cause maps
+//! (raea-sys-weathering) and the light bake's lightmaps (raea-sys-lightbake) both lie over it, so a model has one
+//! TEXCOORD_1. Split out of raea-sys-weathering on 11-23 so both bakes can build on it; its bytes are the same.
+//!
+//! scene.rs glTF to triangles with a material class each, and back with TEXCOORD_1
+//! charts.rs the charts, their shelf packing, each texel's point (merge.rs joins and folds them)
+//! rays.rs the triangles shut inside a closed shell (no texels), and the samples the bakes' rays share
+
+pub mod charts;
+pub mod merge;
+pub mod rays;
+pub mod scene;
+
+use parry3d::glamx::Vec3;
+use serde_json::Value;
+
+pub use scene::{Class, Classes};
+
+pub type R<T> = Result<T, String>;
+
+/// What an atlas is laid out for, from a bake request's `env`: the world's up and north (a wall's rows run down the
+/// fall line, a level chart turns to its smallest rectangle), texels a metre (any class, and by class where a class
+/// asks otherwise) and the atlas's longest side.
+#[derive(Clone, Debug)]
+pub struct Ask {
+ pub up: Vec3,
+ pub north: Vec3,
+ pub density: f32,
+ pub densities: Vec<(Class, f32)>,
+ pub max_side: u32,
+}
+
+impl Ask {
+ /// The atlas's fields of a request's `env`: {up, north, density (or {"*": d, CLASS: d}), max_side}, each optional.
+ pub fn of(v: &Value) -> R<Ask> {
+ let num = |k: &str, d: f64| v.pointer(k).and_then(Value::as_f64).unwrap_or(d) as f32;
+ let ask = Ask {
+ up: dir(v, "/up", Vec3::Y)?,
+ north: dir(v, "/north", Vec3::NEG_Z)?,
+ density: match v.get("density") { Some(Value::Object(o)) => o.get("*").and_then(Value::as_f64).unwrap_or(8.0) as f32, _ => num("/density", 8.0) },
+ densities: match v.get("density") {
+ Some(Value::Object(o)) => o
+ .iter()
+ .filter(|(k, _)| k.as_str() != "*")
+ .map(|(k, d)| Ok((Class::of(k).ok_or_else(|| format!("env.density.{k}: a class name"))?, d.as_f64().ok_or_else(|| format!("env.density.{k}: a number"))? as f32)))
+ .collect::<R<_>>()?,
+ _ => Vec::new(),
+ },
+ max_side: num("/max_side", 4096.0) as u32,
+ };
+ for d in std::iter::once(ask.density).chain(ask.densities.iter().map(|(_, d)| *d)) {
+ if !(0.25..=256.0).contains(&d) {
+ return Err(format!("env.density: 0.25-256 texels a metre, got {d}"));
+ }
+ }
+ if !(64..=16384).contains(&ask.max_side) {
+ return Err(format!("env.max_side: 64-16384, got {}", ask.max_side));
+ }
+ Ok(ask)
+ }
+
+ /// Texels a metre for a surface of this class.
+ pub fn density_of(&self, c: Class) -> f32 {
+ self.densities.iter().find(|(k, _)| *k == c).map(|(_, d)| *d).unwrap_or(self.density)
+ }
+}
+
+/// A direction in the request at pointer `k` (three numbers, normalized), or `d` when it isn't given.
+pub fn dir(v: &Value, k: &str, d: Vec3) -> R<Vec3> {
+ match v.pointer(k) {
+ None => Ok(d),
+ Some(a) => {
+ let a = a.as_array().filter(|a| a.len() == 3).ok_or_else(|| format!("env{k}: three numbers"))?;
+ let f = |i: usize| a[i].as_f64().map(|x| x as f32).ok_or_else(|| format!("env{k}: numbers"));
+ Vec3::new(f(0)?, f(1)?, f(2)?).try_normalize().ok_or_else(|| format!("env{k}: not a direction"))
+ }
+ }
+}
+
+/// A texel of the atlas and the surface point under it in world units (charts.rs: its centre's point when that's in a
+/// triangle, else the nearest point within 0.75 of a texel of its chart's edge), the triangle's normal, the triangle.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Texel {
+ pub x: u16,
+ pub y: u16,
+ pub p: [f32; 3],
+ pub n: [f32; 3],
+ pub tri: u32,
+}
+
+/// The atlas alone, with no causes traced (docs/bake.feature BK1): the model again with its TEXCOORD_1, the atlas's
+/// size and density, and every texel's point. Given a wear bake's request it is that bake's atlas (raea-sys-weathering's
+/// test says so, byte for byte), so a light bake laid over it and the cause maps read one second UV set.
+#[derive(Debug, PartialEq)]
+pub struct Layout {
+ pub glb: Vec<u8>,
+ pub w: u32,
+ pub h: u32,
+ pub density: f32,
+ pub charts: usize,
+ pub hidden: usize,
+ pub texels: Vec<Texel>,
+}
+
+pub fn layout(bytes: &[u8], req: &Value) -> R<Layout> {
+ let ask = Ask::of(req.get("env").unwrap_or(&Value::Null))?;
+ let sc = scene::read(bytes, &Classes::of(req.get("classes").unwrap_or(&Value::Null))?)?;
+ let at = charts::build(&sc, &ask, &rays::mesh_of(&sc))?;
+ let texels = at.texels.iter().map(|t| Texel { x: t.x, y: t.y, p: t.p.to_array(), n: t.n.to_array(), tri: t.tri }).collect();
+ Ok(Layout { glb: scene::write(&sc, &at)?, w: at.w, h: at.h, density: at.density, charts: at.charts, hidden: at.hidden, texels })
+}
diff --git a/systems/weathering/src/merge.rs b/systems/atlas/src/merge.rs
similarity index 96%
rename from systems/weathering/src/merge.rs
rename to systems/atlas/src/merge.rs
index 38898938..a1337933 100644
--- a/systems/weathering/src/merge.rs
+++ b/systems/atlas/src/merge.rs
@@ -9,7 +9,7 @@ use std::collections::HashMap;
use parry3d::glamx::Vec3;
use raea_core_meshcheck::find;
-use crate::Env;
+use crate::Ask;
use crate::charts::Chart;
use crate::scene::Scene;
@@ -25,7 +25,7 @@ const SPLIT: f32 = 64.0;
/// Coplanar charts (the same plane to 1/64 in the normal and 2 cm in offset) whose rectangles touch, joined.
-pub(crate) fn merge(cs: Vec<Chart>, sc: &Scene, up: Vec3) -> Vec<Chart> {
+pub fn merge(cs: Vec<Chart>, sc: &Scene, up: Vec3) -> Vec<Chart> {
let q = |v: f32| (v * 64.0).round() as i32;
let mut groups: HashMap<(i32, i32, i32, i64), Vec<u32>> = HashMap::new();
for (i, c) in cs.iter().enumerate() {
@@ -81,7 +81,7 @@ pub(crate) fn merge(cs: Vec<Chart>, sc: &Scene, up: Vec3) -> Vec<Chart> {
/// Charts whose triangles cover less than half their rectangle (a street network round its blocks, a quarter's gutters
/// at one eaves height joined where they cross), cut on a grid SPLIT texels square: each cell's triangles, by their
/// centres, a chart in the same plane.
-pub(crate) fn split(cs: Vec<Chart>, sc: &Scene, env: &Env) -> Vec<Chart> {
+pub fn split(cs: Vec<Chart>, sc: &Scene, env: &Ask) -> Vec<Chart> {
let mut out = Vec::new();
for c in cs {
let d = c.asked(sc, env);
@@ -121,7 +121,7 @@ pub(crate) fn split(cs: Vec<Chart>, sc: &Scene, env: &Env) -> Vec<Chart> {
/// Each chart too small for texels of its own at density d, moved into the nearest big chart within HOST_REACH of
/// its plane (and over its rectangle); a detail with no host keeps its own chart. Hosts are refitted.
-pub(crate) fn absorb(cs: Vec<Chart>, sc: &Scene, env: &Env) -> Vec<Chart> {
+pub fn absorb(cs: Vec<Chart>, sc: &Scene, env: &Ask) -> Vec<Chart> {
let ds: Vec<f32> = cs.iter().map(|c| c.asked(sc, env)).collect();
let small = |c: &Chart, d: f32| {
let (w, h) = ((c.s1 - c.s0) * d, (c.t1 - c.t0) * d);
diff --git a/systems/atlas/src/rays.rs b/systems/atlas/src/rays.rs
new file mode 100644
index 00000000..7c53932a
--- /dev/null
+++ b/systems/atlas/src/rays.rs
@@ -0,0 +1,78 @@
+//! The rays the atlas needs, and the sampling weathering's causes share: a triangle shut inside a closed shell gets
+//! no texels (`hidden`), found by rays through the model's own triangles (parry3d's BVH). Samples are a rotated R2
+//! sequence per texel, so the result is the same on every run.
+
+use std::f32::consts::TAU;
+
+use parry3d::glamx::Vec3;
+use parry3d::query::{Ray, RayCast};
+use parry3d::shape::TriMesh;
+use rayon::prelude::*;
+
+use crate::scene::Scene;
+
+/// How far a ray starts off its surface, and how far one looking for the sky goes.
+pub const OFF: f32 = 0.01;
+pub const SKY_REACH: f32 = 400.0;
+
+pub fn hash(mut x: u32) -> u32 {
+ x ^= x >> 16;
+ x = x.wrapping_mul(0x7feb352d);
+ x ^= x >> 15;
+ x = x.wrapping_mul(0x846ca68b);
+ x ^ (x >> 16)
+}
+
+/// The j-th of a texel's samples in the unit square.
+pub fn sample(texel: u32, j: u32) -> (f32, f32) {
+ let h = hash(texel.wrapping_mul(2654435761).wrapping_add(0x9e3779b9));
+ let (r0, r1) = ((h & 0xffff) as f32 / 65536.0, (h >> 16) as f32 / 65536.0);
+ ((0.5 + 0.754_877_7 * j as f32 + r0).fract(), (0.5 + 0.569_840_3 * j as f32 + r1).fract())
+}
+
+/// Two unit vectors across n.
+pub fn across(n: Vec3) -> (Vec3, Vec3) {
+ let a = if n.x.abs() < 0.9 { Vec3::X } else { Vec3::Y };
+ let t = n.cross(a).normalize();
+ (t, n.cross(t))
+}
+
+/// A cosine-weighted direction about n from a sample in the unit square.
+pub fn hemi(n: Vec3, (u1, u2): (f32, f32)) -> Vec3 {
+ let r = u1.sqrt();
+ let (t, b) = across(n);
+ (n * (1.0 - u1).max(0.0).sqrt() + t * (r * (TAU * u2).cos()) + b * (r * (TAU * u2).sin())).normalize()
+}
+
+pub fn mesh_of(sc: &Scene) -> TriMesh {
+ TriMesh::new(sc.pos.clone(), sc.tri.clone()).expect("a TriMesh from the scene's triangles")
+}
+
+/// Triangles inside a closed shell: at its centre and near each corner, nine in ten of the rays out of its front hit
+/// the back of something (ground under a house, a party wall against its neighbour's, a slab's underside within its
+/// walls). Nothing sees them. One point open keeps the triangle: a big one only partly covered (a street's triangle
+/// running under its pavement) is still seen where it isn't.
+pub fn hidden(sc: &Scene, mesh: &TriMesh) -> Vec<bool> {
+ const K: u32 = 16;
+ const AT: [[f32; 3]; 4] = [[1.0 / 3.0; 3], [0.8, 0.1, 0.1], [0.1, 0.8, 0.1], [0.1, 0.1, 0.8]];
+ (0..sc.tri.len())
+ .into_par_iter()
+ .map(|t| {
+ let n = sc.nrm[t];
+ if n == Vec3::ZERO {
+ return false;
+ }
+ let [a, b, c] = sc.tri[t].map(|v| sc.pos[v as usize]);
+ AT.iter().enumerate().all(|(k, w)| {
+ let o = a * w[0] + b * w[1] + c * w[2] + n * OFF;
+ let back = (0..K)
+ .filter(|&j| {
+ let d = hemi(n, sample((t as u32 ^ 0x5bd1_e995).wrapping_add(k as u32 * 7919), j));
+ mesh.cast_local_ray_and_get_normal(&Ray::new(o, d), SKY_REACH, false).is_some_and(|h| sc.nrm[h.subshape as usize].dot(d) > 0.0)
+ })
+ .count();
+ back as u32 * 10 >= K * 9
+ })
+ })
+ .collect()
+}
diff --git a/systems/weathering/src/scene.rs b/systems/atlas/src/scene.rs
similarity index 98%
rename from systems/weathering/src/scene.rs
rename to systems/atlas/src/scene.rs
index 4c535644..b5a31f7e 100644
--- a/systems/weathering/src/scene.rs
+++ b/systems/atlas/src/scene.rs
@@ -112,7 +112,7 @@ impl Classes {
/// One primitive as baked: which mesh and primitive of the source, its triangles' range in Scene::tri, and its own
/// vertex count (Scene::tri indexes `base + local`).
-pub(crate) struct Prim {
+pub struct Prim {
pub mesh: usize,
pub prim: usize,
pub first_tri: usize,
@@ -120,7 +120,7 @@ pub(crate) struct Prim {
pub base: u32,
}
-pub(crate) struct Scene {
+pub struct Scene {
pub glb: Glb,
/// every vertex in the world; tri indexes it
pub pos: Vec<Vec3>,
@@ -146,7 +146,7 @@ fn local(n: &Value) -> Mat4 {
Mat4::from_scale_rotation_translation(Vec3::new(s[0], s[1], s[2]), Quat::from_xyzw(r[0], r[1], r[2], r[3]).normalize(), Vec3::new(t[0], t[1], t[2]))
}
-pub(crate) fn read(bytes: &[u8], classes: &Classes) -> R<Scene> {
+pub fn read(bytes: &[u8], classes: &Classes) -> R<Scene> {
let glb = parse(bytes)?;
let j = &glb.json;
for (i, m) in arr(j, "materials").iter().enumerate() {
@@ -235,7 +235,7 @@ pub(crate) fn read(bytes: &[u8], classes: &Classes) -> R<Scene> {
}
/// The .glb again, each primitive re-indexed over its charts with TEXCOORD_1, and the binary holding only what's used.
-pub(crate) fn write(sc: &Scene, at: &Atlas) -> R<Vec<u8>> {
+pub fn write(sc: &Scene, at: &Atlas) -> R<Vec<u8>> {
let g = &sc.glb;
let mut j = g.json.clone();
let src_meshes: Vec<Value> = arr(&j, "meshes").to_vec();
diff --git a/systems/lightbake/Cargo.toml b/systems/lightbake/Cargo.toml
new file mode 100644
index 00000000..8255b944
--- /dev/null
+++ b/systems/lightbake/Cargo.toml
@@ -0,0 +1,17 @@
+[package]
+name = "raea-sys-lightbake"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "Light baked by raea: bounce light into lightmaps over raea/wear's atlas, on raea's ray tracer (docs/bake.feature)"
+
+[dependencies]
+# the atlas raea/wear's cause maps share (BK1: layout())
+raea-sys-atlas = { path = "../atlas" }
+# triangle BVH and ray casts (Apache-2.0), as weathering's
+parry3d = "0.31"
+rayon = "1"
+serde_json = "1"
+# the layout's model read back for its world triangles (no images decoded)
+gltf = { version = "1.4", default-features = false, features = ["utils"] }
diff --git a/systems/lightbake/src/lib.rs b/systems/lightbake/src/lib.rs
new file mode 100644
index 00000000..77586e31
--- /dev/null
+++ b/systems/lightbake/src/lib.rs
@@ -0,0 +1,8 @@
+//! Light baked by raea (docs/bake.feature): bounce light baked into lightmaps on raea's own ray tracer, with no
+//! Blender. A bake is a pure function of what it's asked: the static parts, the sky, the lights it carries and the
+//! settings. Its maps lie over the atlas raea/wear's cause maps already use (BK1: raea_sys_atlas::layout), so a
+//! model has one second UV set. Built: each texel's place in the world (BK2). Next: the trace (BK3), a clean map
+//! (BK4), and the bake in a composition (BK5).
+
+// each texel's ray origin and the texels inside other geometry (BK2)
+pub mod texels;
diff --git a/systems/lightbake/src/texels.rs b/systems/lightbake/src/texels.rs
new file mode 100644
index 00000000..ade888f1
--- /dev/null
+++ b/systems/lightbake/src/texels.rs
@@ -0,0 +1,96 @@
+//! Each texel's place in the world (docs/bake.feature BK2). BK1's layout gives every texel the world point under its
+//! centre (or, in a chart's edge band, the nearest point of the chart), its triangle's normal and the triangle, so the
+//! texels aren't rasterized a second time. Here each point gets its ray origin, moved off its surface by an offset
+//! from the model's size so the trace never hits the surface it starts on, and the texels inside other geometry (a
+//! table leg's foot in the floor, a wall's end inside the next wall) are found by rays and marked: they neither go
+//! black nor leak light into the bake, and BK4 fills them from their chart's neighbours.
+
+use parry3d::glamx::Vec3;
+use parry3d::query::{Ray, RayCast};
+use parry3d::shape::TriMesh;
+use rayon::prelude::*;
+use serde_json::{Value, json};
+
+use raea_sys_atlas::rays::{hemi, sample};
+pub use raea_sys_atlas::{Layout, Texel};
+
+/// Rays each texel casts for the inside test: cosine-weighted, the atlas's rotated R2 sequence per texel.
+const RAYS: u32 = 16;
+
+pub struct Texels {
+ /// BK1's layout: the model with its TEXCOORD_1, the atlas's size and density, the texels' surface points
+ pub layout: Layout,
+ /// each texel's ray origin: its surface point moved `offset` along its normal
+ pub origin: Vec<[f32; 3]>,
+ /// the texels inside other geometry (their rays meet back faces), left for BK4 to fill
+ pub inside: Vec<bool>,
+ /// metres off the surface: 1e-5 of the model's size or of its farthest coordinate, at least 10 microns
+ pub offset: f32,
+ /// the model's triangles in world space, for the trace (BK3)
+ pub mesh: TriMesh,
+}
+
+/// The request of a bake that only lights: texels a metre and the atlas's longest side. A model that is also worn
+/// passes its wear bake's request instead, so its lightmap lies over that bake's atlas.
+pub fn request(texels: f32, max_side: u32) -> Value {
+ json!({ "env": { "density": texels, "max_side": max_side } })
+}
+
+/// Every texel of the model's atlas in the world: its origin and whether it's inside other geometry.
+pub fn texels(glb: &[u8], req: &Value) -> Result<Texels, String> {
+ let layout = raea_sys_atlas::layout(glb, req)?;
+ let mesh = world_mesh(&layout.glb)?;
+ let (mut lo, mut hi, mut far) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN), 0.0f32);
+ for &v in mesh.vertices() {
+ (lo, hi, far) = (lo.min(v), hi.max(v), far.max(v.abs().max_element()));
+ }
+ let offset = (1e-5 * (hi - lo).length().max(far)).max(1e-5);
+ let origin: Vec<[f32; 3]> = layout.texels.iter().map(|t| (Vec3::from(t.p) + Vec3::from(t.n) * offset).to_array()).collect();
+ let inside = layout.texels.par_iter().zip(&origin).enumerate().map(|(i, (t, &o))| inside(&mesh, Vec3::from(o), Vec3::from(t.n), i as u32)).collect();
+ Ok(Texels { layout, origin, inside, offset, mesh })
+}
+
+/// Whether a texel is inside other geometry: of its rays that meet anything, at least half meet a back face and more
+/// meet back faces than front ones. A foot inside a closed floor slab meets back faces every way; one under a floor
+/// that is a single plane meets its underside upwards and nothing downwards, and is inside too.
+fn inside(mesh: &TriMesh, o: Vec3, n: Vec3, seed: u32) -> bool {
+ let (mut back, mut front) = (0, 0);
+ for j in 0..RAYS {
+ let d = hemi(n, sample(seed, j));
+ if let Some(h) = mesh.cast_local_ray_and_get_normal(&Ray::new(o, d), f32::MAX, false) {
+ let [a, b, c] = mesh.indices()[h.subshape as usize].map(|v| mesh.vertices()[v as usize]);
+ if (b - a).cross(c - a).dot(d) > 0.0 { back += 1 } else { front += 1 }
+ }
+ }
+ back * 2 >= RAYS && back > front
+}
+
+/// The layout's model as world triangles: every triangle primitive of the default scene's nodes, each node's
+/// transform applied down its children.
+fn world_mesh(glb: &[u8]) -> Result<TriMesh, String> {
+ let g = gltf::Gltf::from_slice(glb).map_err(|e| format!("the layout's model: {e}"))?;
+ let blob = g.blob.as_deref();
+ let scene = g.default_scene().or_else(|| g.scenes().next()).ok_or("the layout's model has no scene")?;
+ const ID: [[f32; 4]; 4] = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]];
+ let mut stack: Vec<(gltf::Node, [[f32; 4]; 4])> = scene.nodes().map(|n| (n, ID)).collect();
+ let (mut pos, mut tri) = (Vec::new(), Vec::new());
+ while let Some((node, parent)) = stack.pop() {
+ let l = node.transform().matrix();
+ let m: [[f32; 4]; 4] = std::array::from_fn(|c| std::array::from_fn(|r| (0..4).map(|k| parent[k][r] * l[c][k]).sum()));
+ for prim in node.mesh().iter().flat_map(|m| m.primitives()).filter(|p| p.mode() == gltf::mesh::Mode::Triangles) {
+ let r = prim.reader(|b| if b.index() == 0 { blob } else { None });
+ let base = pos.len() as u32;
+ pos.extend(r.read_positions().ok_or("a primitive with no positions")?.map(|p| Vec3::from(std::array::from_fn(|i| m[0][i] * p[0] + m[1][i] * p[1] + m[2][i] * p[2] + m[3][i]))));
+ let ix: Vec<u32> = match r.read_indices() {
+ Some(i) => i.into_u32().collect(),
+ None => (0..pos.len() as u32 - base).collect(),
+ };
+ tri.extend(ix.chunks_exact(3).map(|t| [base + t[0], base + t[1], base + t[2]]));
+ }
+ stack.extend(node.children().map(|c| (c, m)));
+ }
+ TriMesh::new(pos, tri).map_err(|e| format!("the layout's triangles: {e:?}"))
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/systems/lightbake/src/texels/tests.rs b/systems/lightbake/src/texels/tests.rs
new file mode 100644
index 00000000..d0c93ac0
--- /dev/null
+++ b/systems/lightbake/src/texels/tests.rs
@@ -0,0 +1,144 @@
+use parry3d::query::PointQuery;
+
+use super::*;
+
+type Tri = [[f32; 3]; 3];
+
+/// A .glb with a node per part (its translation, its own material), flat normals, every triangle its own vertices.
+fn glb(parts: &[(Vec<Tri>, [f32; 3])]) -> Vec<u8> {
+ let (mut bin, mut acc, mut views, mut meshes, mut nodes, mut mats) = (Vec::<u8>::new(), vec![], vec![], vec![], vec![], vec![]);
+ for (k, (tris, at)) in parts.iter().enumerate() {
+ let (mut p, mut n) = (vec![], vec![]);
+ for t in tris {
+ let [a, b, c] = t.map(Vec3::from);
+ let nn = (b - a).cross(c - a).normalize().to_array();
+ p.extend(t);
+ n.extend([nn; 3]);
+ }
+ for (i, data) in [&p, &n].into_iter().enumerate() {
+ views.push(json!({"buffer": 0, "byteOffset": bin.len(), "byteLength": data.len() * 12}));
+ bin.extend(data.iter().flatten().flat_map(|c| c.to_le_bytes()));
+ let mut a = json!({"bufferView": views.len() - 1, "componentType": 5126, "count": data.len(), "type": "VEC3"});
+ if i == 0 {
+ let (lo, hi) = data.iter().fold(([f32::MAX; 3], [f32::MIN; 3]), |(l, h), v| (std::array::from_fn(|j| l[j].min(v[j])), std::array::from_fn(|j| h[j].max(v[j]))));
+ (a["min"], a["max"]) = (json!(lo), json!(hi));
+ }
+ acc.push(a);
+ }
+ meshes.push(json!({"primitives": [{"attributes": {"POSITION": acc.len() - 2, "NORMAL": acc.len() - 1}, "material": k}]}));
+ nodes.push(json!({"mesh": k, "translation": at}));
+ mats.push(json!({"name": format!("part{k}")}));
+ }
+ let doc = json!({"asset": {"version": "2.0"}, "scene": 0, "scenes": [{"nodes": (0..parts.len()).collect::<Vec<_>>()}], "nodes": nodes, "meshes": meshes, "materials": mats, "accessors": acc, "bufferViews": views, "buffers": [{"byteLength": bin.len()}]});
+ let mut js = doc.to_string().into_bytes();
+ js.resize(js.len().div_ceil(4) * 4, b' ');
+ bin.resize(bin.len().div_ceil(4) * 4, 0);
+ let mut out = b"glTF".to_vec();
+ for w in [2, 12 + 8 + js.len() + 8 + bin.len()] {
+ out.extend((w as u32).to_le_bytes());
+ }
+ for (chunk, kind) in [(js, b"JSON"), (bin, b"BIN\0")] {
+ out.extend((chunk.len() as u32).to_le_bytes());
+ out.extend(kind);
+ out.extend(chunk);
+ }
+ out
+}
+
+/// A box's twelve triangles, wound outwards.
+fn cuboid(lo: [f32; 3], hi: [f32; 3]) -> Vec<Tri> {
+ let mut out = vec![];
+ for axis in 0..3 {
+ let (u, v) = ((axis + 1) % 3, (axis + 2) % 3);
+ for side in [false, true] {
+ let corner = |a: bool, b: bool| {
+ let mut q = [0.0; 3];
+ (q[axis], q[u], q[v]) = (if side { hi[axis] } else { lo[axis] }, if a { hi[u] } else { lo[u] }, if b { hi[v] } else { lo[v] });
+ q
+ };
+ let [p0, p1, p2, p3] = [corner(false, false), corner(true, false), corner(true, true), corner(false, true)];
+ out.extend(if side { [[p0, p1, p2], [p0, p2, p3]] } else { [[p0, p2, p1], [p0, p3, p2]] });
+ }
+ }
+ out
+}
+
+/// A floor slab 20 cm thick, a block sunk 10 cm into it, and a small box set on it by its node's translation.
+fn set() -> Vec<u8> {
+ glb(&[
+ (cuboid([-2.0, -0.2, -2.0], [2.0, 0.0, 2.0]), [0.0; 3]),
+ (cuboid([-0.25, -0.1, -0.25], [0.25, 0.4, 0.25]), [0.0; 3]),
+ (cuboid([-0.1, 0.0, -0.1], [0.1, 0.2, 0.1]), [1.2, 0.0, 0.0]),
+ ])
+}
+
+#[test]
+fn texels_sit_on_the_world_surface_and_their_origins_just_off_it() {
+ let t = texels(&set(), &request(16.0, 1024)).unwrap();
+ assert!(t.layout.texels.len() > 1000 && t.offset > 0.0 && t.offset < 1e-3, "{} texels, offset {}", t.layout.texels.len(), t.offset);
+ for (x, o) in t.layout.texels.iter().zip(&t.origin) {
+ let on = t.mesh.project_local_point(Vec3::from(x.p), false).point;
+ assert!(on.distance(Vec3::from(x.p)) < 1e-3, "texel at {:?} is off the surface (nearest {on:?})", x.p);
+ assert!((Vec3::from(*o) - Vec3::from(x.p) - Vec3::from(x.n) * t.offset).length() < 1e-6);
+ }
+}
+
+#[test]
+fn texels_inside_the_slab_are_marked_and_those_in_the_open_are_not() {
+ let t = texels(&set(), &request(16.0, 1024)).unwrap();
+ let (mut sunk, mut open, mut under) = (0, 0, 0);
+ for (x, &inside) in t.layout.texels.iter().zip(&t.inside) {
+ let [px, py, pz] = x.p;
+ if (-0.18..-0.02).contains(&py) && px.abs() < 0.26 && pz.abs() < 0.26 {
+ // the block's sides within the slab's thickness, away from its faces
+ assert!(inside, "a texel of the block inside the slab at {:?} isn't marked", x.p);
+ sunk += 1;
+ } else if py > 0.02 || (-0.18..-0.02).contains(&py) {
+ // in the open: above the floor, or the slab's own sides
+ assert!(!inside, "a texel in the open at {:?} is marked inside", x.p);
+ open += (py > 0.02) as usize;
+ } else if py.abs() < 1e-3 && x.n[1] > 0.9 && px.abs() < 0.2 && pz.abs() < 0.2 {
+ assert!(inside, "the floor under the block at {:?} isn't marked", x.p);
+ under += 1;
+ } else if py.abs() < 1e-3 && x.n[1] > 0.9 && px.abs() > 0.4 && (px - 1.2).abs() > 0.2 {
+ assert!(!inside, "open floor at {:?} is marked inside", x.p);
+ }
+ }
+ assert!(sunk > 10 && open > 100 && under > 10, "sunk {sunk}, open {open}, under {under}");
+}
+
+#[test]
+fn the_same_model_gives_the_same_texels() {
+ let (a, b) = (texels(&set(), &request(16.0, 1024)).unwrap(), texels(&set(), &request(16.0, 1024)).unwrap());
+ assert!(a.layout == b.layout && a.origin == b.origin && a.inside == b.inside);
+}
+
+#[test]
+fn a_worn_models_request_gives_its_wear_atlas() {
+ let req = json!({"env": {"density": 8, "rays": {"sky": 4, "cavity": 4}}});
+ let t = texels(&set(), &req).unwrap();
+ assert_eq!(t.layout, raea_sys_atlas::layout(&set(), &req).unwrap());
+}
+
+/// The measured run (docs/bake.feature BK2): RAEA_BAKE_GLB's texels at 64 a metre, how many are inside, and the time.
+/// `cargo test -p raea-sys-lightbake measured -- --ignored --nocapture`
+#[test]
+#[ignore]
+fn measured() {
+ let glb = std::fs::read(std::env::var("RAEA_BAKE_GLB").expect("RAEA_BAKE_GLB: a .glb")).unwrap();
+ let t0 = std::time::Instant::now();
+ let layout = raea_sys_atlas::layout(&glb, &request(64.0, 4096)).unwrap();
+ let t1 = std::time::Instant::now();
+ let t = texels(&glb, &request(64.0, 4096)).unwrap();
+ let inside = t.inside.iter().filter(|&&i| i).count();
+ if let Ok(out) = std::env::var("RAEA_BAKE_OUT") {
+ // the atlas: grey where a texel is in the open, red where it's inside, black where there's none (a PPM)
+ let mut img = vec![0u8; (layout.w * layout.h * 3) as usize];
+ for (x, &i) in t.layout.texels.iter().zip(&t.inside) {
+ let k = 3 * (x.y as usize * layout.w as usize + x.x as usize);
+ img[k..k + 3].copy_from_slice(if i { &[230, 40, 30] } else { &[150, 150, 150] });
+ }
+ std::fs::write(out, [format!("P6 {} {} 255\n", layout.w, layout.h).into_bytes(), img].concat()).unwrap();
+ }
+ println!("{}x{} {} texels, {} inside ({:.2}%), offset {:.1e} m; layout {:.2} s, texels with it {:.2} s", layout.w, layout.h, t.layout.texels.len(), inside, 100.0 * inside as f64 / t.layout.texels.len() as f64, t.offset, (t1 - t0).as_secs_f64(), t1.elapsed().as_secs_f64());
+}
diff --git a/systems/weathering/Cargo.toml b/systems/weathering/Cargo.toml
index 40247f8e..ded9fa92 100644
--- a/systems/weathering/Cargo.toml
+++ b/systems/weathering/Cargo.toml
@@ -17,6 +17,6 @@ raea-sys-runoff = { path = "../runoff" }
raea-sys-touch = { path = "../touch" }
raea-sys-exposure = { path = "../exposure" }
raea-sys-damage = { path = "../damage" }
-# a union-find's root (charts merged by shared edges)
-raea-core-meshcheck = { path = "../../core/meshcheck" }
raea-sys-glb = { path = "../glb" }
+# the atlas the cause maps lie over (and the light bake's, docs/bake.feature BK1)
+raea-sys-atlas = { path = "../atlas" }
diff --git a/systems/weathering/src/lib.rs b/systems/weathering/src/lib.rs
index 76d38ea2..036959d7 100644
--- a/systems/weathering/src/lib.rs
+++ b/systems/weathering/src/lib.rs
@@ -14,12 +14,9 @@
//! triangle's material class as `Class::code`); causes3 = (winter sun, drift, litter, crack: 1 - the distance to the
//! nearest crack from an opening's corner over raea-sys-damage's REACH).
-mod charts;
mod flow;
mod maps;
-mod merge;
mod rays;
-mod scene;
mod touch;
#[cfg(test)]
mod tests;
@@ -31,7 +28,8 @@ use parry3d::glamx::Vec3;
use serde_json::{Map, Value, json};
use sha2::{Digest, Sha256};
-pub use scene::{Class, Classes};
+pub use raea_sys_atlas::{Ask, Class, Classes};
+pub(crate) use raea_sys_atlas::{charts, scene};
type R<T> = Result<T, String>;
@@ -80,16 +78,8 @@ impl Env {
/// spread} (a storm's driven snow; the way it travels), walk: [class...] | {y}, density (or {"*": d, CLASS: d}),
/// max_side, rays: {sky, cavity}}
pub fn of(v: &Value) -> R<Env> {
- let v3 = |k: &str, d: Vec3| -> R<Vec3> {
- match v.pointer(k) {
- None => Ok(d),
- Some(a) => {
- let a = a.as_array().filter(|a| a.len() == 3).ok_or_else(|| format!("env{k}: three numbers"))?;
- let f = |i: usize| a[i].as_f64().map(|x| x as f32).ok_or_else(|| format!("env{k}: numbers"));
- Vec3::new(f(0)?, f(1)?, f(2)?).try_normalize().ok_or_else(|| format!("env{k}: not a direction"))
- }
- }
- };
+ let ask = Ask::of(v)?;
+ let v3 = |k: &str, d: Vec3| raea_sys_atlas::dir(v, k, d);
let num = |k: &str, d: f64| v.pointer(k).and_then(Value::as_f64).unwrap_or(d) as f32;
let walk = match v.get("walk") {
None => Walk::Classes(vec![Class::Ground]),
@@ -101,41 +91,26 @@ impl Env {
Some(w) => Walk::Level(w.get("y").and_then(Value::as_f64).ok_or("env.walk: [class...] or {y}")? as f32),
};
let env = Env {
- up: v3("/up", Vec3::Y)?,
- north: v3("/north", Vec3::NEG_Z)?,
+ up: ask.up,
+ north: ask.north,
rain: v3("/rain/dir", Vec3::NEG_Y)?,
spread: num("/rain/spread", 30.0).clamp(0.0, 80.0).to_radians(),
lat: num("/sun/lat", 52.5).clamp(-89.0, 89.0),
- snow: v3("/snow/dir", storm(v3("/up", Vec3::Y)?, v3("/north", Vec3::NEG_Z)?))?,
+ snow: v3("/snow/dir", storm(ask.up, ask.north))?,
snow_spread: num("/snow/spread", 25.0).clamp(0.0, 80.0).to_radians(),
walk,
- density: match v.get("density") { Some(Value::Object(o)) => o.get("*").and_then(Value::as_f64).unwrap_or(8.0) as f32, _ => num("/density", 8.0) },
- densities: match v.get("density") {
- Some(Value::Object(o)) => o
- .iter()
- .filter(|(k, _)| k.as_str() != "*")
- .map(|(k, d)| Ok((Class::of(k).ok_or_else(|| format!("env.density.{k}: a class name"))?, d.as_f64().ok_or_else(|| format!("env.density.{k}: a number"))? as f32)))
- .collect::<R<_>>()?,
- _ => Vec::new(),
- },
- max_side: num("/max_side", 4096.0) as u32,
+ density: ask.density,
+ densities: ask.densities,
+ max_side: ask.max_side,
sky_rays: num("/rays/sky", 32.0).clamp(4.0, 512.0) as u32,
cavity_rays: num("/rays/cavity", 8.0).clamp(2.0, 128.0) as u32,
};
- for d in std::iter::once(env.density).chain(env.densities.iter().map(|(_, d)| *d)) {
- if !(0.25..=256.0).contains(&d) {
- return Err(format!("env.density: 0.25-256 texels a metre, got {d}"));
- }
- }
- if !(64..=16384).contains(&env.max_side) {
- return Err(format!("env.max_side: 64-16384, got {}", env.max_side));
- }
Ok(env)
}
- /// Texels a metre for a surface of this class.
- pub fn density_of(&self, c: Class) -> f32 {
- self.densities.iter().find(|(k, _)| *k == c).map(|(_, d)| *d).unwrap_or(self.density)
+ /// What the atlas is laid out for (raea_sys_atlas::Ask): the same fields, so `layout` with this request agrees.
+ pub fn ask(&self) -> Ask {
+ Ask { up: self.up, north: self.north, density: self.density, densities: self.densities.clone(), max_side: self.max_side }
}
}
@@ -207,41 +182,12 @@ pub fn bake(store: &Path, src: &Path, req: &Value) -> R<Value> {
fn lay(bytes: &[u8], req: &Value) -> R<(Env, scene::Scene, parry3d::shape::TriMesh, charts::Atlas, Instant)> {
let env = Env::of(req.get("env").unwrap_or(&Value::Null))?;
let sc = scene::read(bytes, &Classes::of(req.get("classes").unwrap_or(&Value::Null))?)?;
- let mesh = rays::mesh_of(&sc);
+ let mesh = raea_sys_atlas::rays::mesh_of(&sc);
let t = Instant::now();
- let at = charts::build(&sc, &env, &mesh)?;
+ let at = charts::build(&sc, &env.ask(), &mesh)?;
Ok((env, sc, mesh, at, t))
}
-/// A texel of the atlas, the world point under it (charts.rs: its centre's, or the chart edge's nearest), its normal, triangle.
-#[derive(Clone, Copy, Debug, PartialEq)]
-pub struct Texel {
- pub x: u16,
- pub y: u16,
- pub p: [f32; 3],
- pub n: [f32; 3],
- pub tri: u32,
-}
-
-/// The atlas alone, no causes traced (docs/bake.feature BK1): the model with its TEXCOORD_1, size, density, texels. The
-/// same request gives `bake`'s atlas, so a light bake laid over it and the cause maps read one second UV set.
-#[derive(Debug, PartialEq)]
-pub struct Layout {
- pub glb: Vec<u8>,
- pub w: u32,
- pub h: u32,
- pub density: f32,
- pub charts: usize,
- pub hidden: usize,
- pub texels: Vec<Texel>,
-}
-
-pub fn layout(bytes: &[u8], req: &Value) -> R<Layout> {
- let (_, sc, _, at, _) = lay(bytes, req)?;
- let texels = at.texels.iter().map(|t| Texel { x: t.x, y: t.y, p: t.p.to_array(), n: t.n.to_array(), tri: t.tri }).collect();
- Ok(Layout { glb: scene::write(&sc, &at)?, w: at.w, h: at.h, density: at.density, charts: at.charts, hidden: at.hidden, texels })
-}
-
fn strip_src(v: &Value) -> Value {
let mut v = v.clone();
if let Some(o) = v.as_object_mut() {
diff --git a/systems/weathering/src/rays.rs b/systems/weathering/src/rays.rs
index b430b566..407fa884 100644
--- a/systems/weathering/src/rays.rs
+++ b/systems/weathering/src/rays.rs
@@ -13,7 +13,6 @@
//! Samples are a rotated R2 sequence per texel, so the result is the same on every run.
use std::collections::HashMap;
-use std::f32::consts::TAU;
use raea_sys_exposure::cone;
@@ -27,40 +26,11 @@ use raea_sys_exposure::{Driven, Exposer, Frame};
use super::{Env, Walk};
use crate::charts::Atlas;
use crate::scene::Scene;
+pub(crate) use raea_sys_atlas::rays::{OFF, SKY_REACH, hash, hemi, sample};
-const OFF: f32 = 0.01;
const CAVITY_REACH: f32 = 0.5;
-const SKY_REACH: f32 = 400.0;
pub(crate) const GROUND_RANGE: f32 = 4.0;
-pub(crate) fn hash(mut x: u32) -> u32 {
- x ^= x >> 16;
- x = x.wrapping_mul(0x7feb352d);
- x ^= x >> 15;
- x = x.wrapping_mul(0x846ca68b);
- x ^ (x >> 16)
-}
-
-/// The j-th of a texel's samples in the unit square.
-pub(crate) fn sample(texel: u32, j: u32) -> (f32, f32) {
- let h = hash(texel.wrapping_mul(2654435761).wrapping_add(0x9e3779b9));
- let (r0, r1) = ((h & 0xffff) as f32 / 65536.0, (h >> 16) as f32 / 65536.0);
- ((0.5 + 0.754_877_7 * j as f32 + r0).fract(), (0.5 + 0.569_840_3 * j as f32 + r1).fract())
-}
-
-/// Two unit vectors across n.
-pub(crate) fn across(n: Vec3) -> (Vec3, Vec3) {
- let a = if n.x.abs() < 0.9 { Vec3::X } else { Vec3::Y };
- let t = n.cross(a).normalize();
- (t, n.cross(t))
-}
-
-fn hemi(n: Vec3, (u1, u2): (f32, f32)) -> Vec3 {
- let r = u1.sqrt();
- let (t, b) = across(n);
- (n * (1.0 - u1).max(0.0).sqrt() + t * (r * (TAU * u2).cos()) + b * (r * (TAU * u2).sin())).normalize()
-}
-
struct Edges {
segs: Vec<(Vec3, Vec3, f32)>,
cells: HashMap<(i32, i32, i32), Vec<u32>>,
@@ -150,39 +120,6 @@ impl Edges {
}
}
-pub(crate) fn mesh_of(sc: &Scene) -> TriMesh {
- TriMesh::new(sc.pos.clone(), sc.tri.clone()).expect("a TriMesh from the scene's triangles")
-}
-
-/// Triangles inside a closed shell: at its centre and near each corner, nine in ten of the rays out of its front hit
-/// the back of something (ground under a house, a party wall against its neighbour's, a slab's underside within its
-/// walls). Nothing sees them. One point open keeps the triangle: a big one only partly covered (a street's triangle
-/// running under its pavement) is still seen where it isn't.
-pub(crate) fn hidden(sc: &Scene, mesh: &TriMesh) -> Vec<bool> {
- const K: u32 = 16;
- const AT: [[f32; 3]; 4] = [[1.0 / 3.0; 3], [0.8, 0.1, 0.1], [0.1, 0.8, 0.1], [0.1, 0.1, 0.8]];
- (0..sc.tri.len())
- .into_par_iter()
- .map(|t| {
- let n = sc.nrm[t];
- if n == Vec3::ZERO {
- return false;
- }
- let [a, b, c] = sc.tri[t].map(|v| sc.pos[v as usize]);
- AT.iter().enumerate().all(|(k, w)| {
- let o = a * w[0] + b * w[1] + c * w[2] + n * OFF;
- let back = (0..K)
- .filter(|&j| {
- let d = hemi(n, sample((t as u32 ^ 0x5bd1_e995).wrapping_add(k as u32 * 7919), j));
- mesh.cast_local_ray_and_get_normal(&Ray::new(o, d), SKY_REACH, false).is_some_and(|h| sc.nrm[h.subshape as usize].dot(d) > 0.0)
- })
- .count();
- back as u32 * 10 >= K * 9
- })
- })
- .collect()
-}
-
pub(crate) fn causes(sc: &Scene, at: &Atlas, env: &Env, mesh: &TriMesh, c0: &mut [[u8; 4]], c2: &mut [[u8; 4]], c3: &mut [[u8; 4]]) {
// an arris reaches a texel past itself, and no less than 8 cm
let reach_of = |tri: u32| (1.0 / at.chart_dens[at.chart_of[tri as usize] as usize]).max(0.08);
diff --git a/systems/weathering/src/tests.rs b/systems/weathering/src/tests.rs
index 2f158664..34dcc43d 100644
--- a/systems/weathering/src/tests.rs
+++ b/systems/weathering/src/tests.rs
@@ -104,8 +104,8 @@ struct Baked {
fn run(prims: Vec<Prim>, e: &Env) -> Baked {
let sc = scene::read(&glb(prims), &classes()).unwrap();
- let mesh = rays::mesh_of(&sc);
- let at = charts::build(&sc, e, &mesh).unwrap();
+ let mesh = raea_sys_atlas::rays::mesh_of(&sc);
+ let at = charts::build(&sc, &e.ask(), &mesh).unwrap();
let n = (at.w * at.h) as usize;
let (mut c0, mut c2, mut c3) = (vec![[0u8; 4]; n], vec![[0u8; 4]; n], vec![[0u8; 4]; n]);
rays::causes(&sc, &at, e, &mesh, &mut c0, &mut c2, &mut c3);
@@ -213,7 +213,7 @@ fn a_bake_is_the_same_bytes_twice_and_adds_texcoord_1() {
}
assert_eq!(std::fs::read(a["spots"].as_str().unwrap()).unwrap(), std::fs::read(b["spots"].as_str().unwrap()).unwrap(), "spots");
let out = std::fs::read(a["file"].as_str().unwrap()).unwrap();
- assert!(layout(&glb(front()), &req).is_ok_and(|l| l.glb == out && l.texels.len() as u64 == a["texels"]), "a layout alone is the bake's atlas");
+ assert!(raea_sys_atlas::layout(&glb(front()), &req).is_ok_and(|l| l.glb == out && l.texels.len() as u64 == a["texels"]), "a layout alone is the bake's atlas");
let sc = scene::read(&out, &Classes::default()).unwrap();
assert_eq!(sc.prims.len(), 4);
for m in sc.glb.json["meshes"].as_array().unwrap() {
@@ -231,8 +231,8 @@ fn each_texel_carries_its_class_and_the_gutters_a_real_one() {
let cl = Classes::of(&json!({"ground": "ground", "slab": "iron", "*": "plaster"})).unwrap();
let e = env(json!({"density": 4, "rays": {"sky": 8, "cavity": 4}}));
let sc = scene::read(&glb(front()), &cl).unwrap();
- let mesh = rays::mesh_of(&sc);
- let at = charts::build(&sc, &e, &mesh).unwrap();
+ let mesh = raea_sys_atlas::rays::mesh_of(&sc);
+ let at = charts::build(&sc, &e.ask(), &mesh).unwrap();
let n = (at.w * at.h) as usize;
let (mut c0, mut c2, mut c3) = (vec![[0u8; 4]; n], vec![[0u8; 4]; n], vec![[0u8; 4]; n]);
rays::causes(&sc, &at, &e, &mesh, &mut c0, &mut c2, &mut c3);
@@ -326,8 +326,8 @@ fn a_door_is_held_on_one_side_and_gets_its_nameplate() {
let req = json!({"env": {"density": {"*": 4, "wood": 20}, "rays": {"sky": 8, "cavity": 4}}, "classes": {"ground": "ground", "door": "wood"}});
let e = env(req["env"].clone());
let sc = scene::read(&glb(prims.clone()), &classes).unwrap();
- let mesh = rays::mesh_of(&sc);
- let at = charts::build(&sc, &e, &mesh).unwrap();
+ let mesh = raea_sys_atlas::rays::mesh_of(&sc);
+ let at = charts::build(&sc, &e.ask(), &mesh).unwrap();
let n = (at.w * at.h) as usize;
let (mut c0, mut c1, mut c2) = (vec![[0u8; 4]; n], vec![[0u8; 4]; n], vec![[0u8; 4]; n]);
let mut c3 = vec![[0u8; 4]; n];
diff --git a/tools/layers.toml b/tools/layers.toml
index 0f41d7e9..05e59d26 100644
--- a/tools/layers.toml
+++ b/tools/layers.toml
@@ -108,6 +108,7 @@ raea-sys-canvas = "systems"
raea-sys-tweak = "systems"
raea-sys-filters = "systems"
raea-sys-weathering = "systems"
+raea-sys-atlas = "systems"
raea-sys-runoff = "systems"
raea-sys-touch = "systems"
raea-sys-exposure = "systems"
@@ -213,6 +214,7 @@ raea-app-make = "apps"
raea-app-scene = "apps" # raea scene lint|explain|light|stage
raea-app-ask = "apps"
raea-app-lightbake = "apps" # raea bake light (docs/bake.feature)
+raea-sys-lightbake = "systems" # light baked over raea/wear's atlas on raea's ray tracer (docs/bake.feature)
raea-app-double = "apps"
raea-app-solid = "apps"
raea-app-media = "apps"
@@ -320,3 +322,5 @@ raea-sys-exposure = true
raea-sys-damage = true
# a .glb read as JSON and bytes and written back (the weathering bake reads and rewrites models through it)
raea-sys-glb = true
+# the atlas raea's bakes share: charts, packing, each texel's point (the cause maps and the light bake lie over it)
+raea-sys-atlas = true