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.

wear WR6: crumbling, from the same causes (raea-sys-damage, raea/wear); WR9's weather during a shot

shinyobjectz80cc01f11de7
diff --git a/Cargo.lock b/Cargo.lock
index 5d21833f..38ad9a82 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -15805,6 +15805,15 @@ dependencies = [
"raea-sys-shader",
]
+[[package]]
+name = "raea-sys-damage"
+version = "0.1.0"
+dependencies = [
+ "parry3d",
+ "raea-sys-touch",
+ "rayon",
+]
+
[[package]]
name = "raea-sys-environment"
version = "0.1.0"
@@ -16539,6 +16548,7 @@ dependencies = [
"image",
"parry3d",
"raea-core-meshcheck",
+ "raea-sys-damage",
"raea-sys-exposure",
"raea-sys-glb",
"raea-sys-runoff",
diff --git a/Cargo.toml b/Cargo.toml
index d9c4aa93..e867c061 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -107,6 +107,7 @@ members = [
"systems/runoff",
"systems/touch",
"systems/exposure",
+ "systems/damage",
"systems/glb",
"systems/procmat",
"systems/page",
diff --git a/sdk/wear/src/causes.ts b/sdk/wear/src/causes.ts
index 0d0bef06..f42975f4 100644
--- a/sdk/wear/src/causes.ts
+++ b/sdk/wear/src/causes.ts
@@ -3,10 +3,25 @@
// causes0 = sky (rain's reach), sun (the year's sun), cavity, edge (convex arris)
// causes1 = flow (run-off passing), deposit (what it left), deposit kind (60 x: 1 grime, 2 rust, 3 copper, 4 zinc), touch
// causes2 = ground (height over the walk, 0-4 m), element (the chart's number), open (the whole sky seen), class
-// causes3 = winter sun (December's), drift (driven snow), litter (where blown leaves and snow settle)
+// causes3 = winter sun (December's), drift (driven snow), litter (where blown leaves and snow settle), crack (1 - the
+// distance to the nearest crack from an opening's corner over CRACK_REACH; raea-sys-damage, WR6)
// The maps load as colour (sRGB) textures, so a colour channel is re-encoded to read the byte the bake wrote; alpha is
// stored linear. Element and class are numbers, read with textureLoad so a filtered read never blends two into a third.
+/** How far the bake keeps a texel's distance to a crack, metres (raea-sys-damage's REACH). */
+export const CRACK_REACH = 0.25;
+/** The loss potential's edges and weights, as raea-sys-damage's LOSS has them (its test compares the two): how readily
+ * a coat comes off at the damp foot (ground 0.7-1.3 m), where run-off soaks what the rain doesn't wash (flow 0.5-0.9,
+ * the rain's reach 0.35-0.85), at a knocked arris low down (edge 0.75-0.9, below 1.4-2.2 m) and along a crack
+ * (within 0.12 m); then the soak's, the arris's and (CRACK_WEIGHT) the crack's weight against the foot's 1. */
+export const LOSS = [0.7, 1.3, 0.5, 0.9, 0.35, 0.85, 0.75, 0.9, 1.4, 2.2, 0.12, 0.8, 0.7] as const;
+export const CRACK_WEIGHT = 0.6;
+/** Neglect past this is a house left empty (its panes broken and boarded, its slates gone, fallen render left on the
+ * walk), full at 1: a lived-in house mends and sweeps these however poorly it is kept. */
+export const ABANDON_FROM = 0.85;
+const f = (x: number) => (Number.isInteger(x) ? `${x}.0` : `${x}`);
+const L = LOSS.map(f);
+
/** The uniforms the module reads: `up` (the bake's up), `age` (years since the last repair, soot, upkeep, the bake's
* texels a metre), `wx` (wet, snow, storm, ice) and `season` (damp, dust, leaves, melt). */
export const CAUSES = /* wgsl */ `
@@ -16,7 +31,7 @@ struct WearCauses {
sky: f32, sun: f32, cav: f32, edge: f32,
flow: f32, dep: f32, kind: i32, touch: f32,
ground: f32, elem: f32, open: f32, cls: i32,
- dec: f32, drift: f32, litter: f32
+ dec: f32, drift: f32, litter: f32, crack: f32
}
fn wear_causes(uv: vec2<f32>) -> WearCauses {
@@ -33,10 +48,19 @@ fn wear_causes(uv: vec2<f32>) -> WearCauses {
wear_enc(a.r), wear_enc(a.g), wear_enc(a.b), a.a,
wear_enc(f.r), wear_enc(f.g), kind, f.a,
wear_enc(b.r) * 4.0, round(wear_enc(x.g) * 255.0), wear_enc(b.b), cls,
- wear_enc(d.r), wear_enc(d.g), wear_enc(d.b)
+ wear_enc(d.r), wear_enc(d.g), wear_enc(d.b), (1.0 - d.a) * ${f(CRACK_REACH)}
);
}
+// how readily the coat here comes off (WR6): raea-sys-damage's loss, so the debris the bake put down lies under it
+fn wear_loss(c: WearCauses) -> f32 {
+ let foot = 1.0 - smoothstep(${L[0]}, ${L[1]}, c.ground);
+ let soak = smoothstep(${L[2]}, ${L[3]}, c.flow) * (1.0 - smoothstep(${L[4]}, ${L[5]}, c.sky));
+ let arris = smoothstep(${L[6]}, ${L[7]}, c.edge) * (1.0 - smoothstep(${L[8]}, ${L[9]}, c.ground));
+ let near = 1.0 - smoothstep(0.0, ${L[10]}, c.crack);
+ return max(max(foot, ${L[11]} * soak), max(${L[12]} * arris, ${f(CRACK_WEIGHT)} * near));
+}
+
// value noise over the face, in metres
fn wear_h21(p: vec2<f32>) -> f32 {
var q = fract(p * vec2<f32>(123.34, 456.21));
@@ -62,24 +86,28 @@ fn wear_fbm2(p: vec2<f32>) -> f32 {
}
// where the point is: how far its face looks up, its place on the face in metres (along a wall and up it; two
-// horizontal axes on a level face), its height over the walk, and how upright the face is
-struct WearGeo { up: f32, p: vec2<f32>, h: f32, wall: f32 }
+// horizontal axes on a level face), its height over the walk, how upright the face is, a pixel's size in metres
+// (from the caller, before any branch: derivatives need uniform control flow) and the parallax: how far a point a
+// metre behind the face shifts in its place as the eye sees it (what's behind lost render is drawn there)
+struct WearGeo { up: f32, p: vec2<f32>, h: f32, wall: f32, px: f32, par: vec2<f32> }
-fn wear_geo(wp: vec3<f32>, nrm: vec3<f32>, c: WearCauses) -> WearGeo {
+fn wear_geo(wp: vec3<f32>, nrm: vec3<f32>, c: WearCauses, eye: vec3<f32>, px: f32) -> WearGeo {
let U = normalize(u_up());
let n = normalize(nrm);
let up = dot(n, U);
let side = n - U * up;
- var p: vec2<f32>;
+ var ax = U;
+ var ay = U;
if (length(side) > 0.3) {
- let t = normalize(cross(U, side));
- p = vec2<f32>(dot(wp, t), dot(wp, U));
+ ax = normalize(cross(U, side));
} else {
let r = select(vec3<f32>(1.0, 0.0, 0.0), vec3<f32>(0.0, 0.0, 1.0), abs(U.x) > 0.9);
- let e1 = normalize(cross(U, r));
- p = vec2<f32>(dot(wp, e1), dot(wp, cross(U, e1)));
+ ax = normalize(cross(U, r));
+ ay = cross(U, ax);
}
- return WearGeo(up, p, c.ground, 1.0 - smoothstep(0.5, 0.8, abs(up)));
+ let v = normalize(eye);
+ let par = -vec2<f32>(dot(v, ax), dot(v, ay)) / max(dot(v, n), 0.25);
+ return WearGeo(up, vec2<f32>(dot(wp, ax), dot(wp, ay)), c.ground, 1.0 - smoothstep(0.5, 0.8, abs(up)), px, par);
}
// what years of weather left, by cause: the same in every season
@@ -87,7 +115,7 @@ struct WearMarks {
age: f32, upkeep: f32, wear: f32,
wash: f32, shelter: f32, tuck: f32, crust: f32,
tear: f32, stain: f32, damp: f32, salt: f32, splash: f32,
- low: f32, chip: f32
+ low: f32, chip: f32, loss: f32, neglect: f32, abandon: f32
}
fn wear_marks(c: WearCauses, g: WearGeo) -> WearMarks {
@@ -117,7 +145,13 @@ fn wear_marks(c: WearCauses, g: WearGeo) -> WearMarks {
// chips need a real arris, so a bake of 12 texels a metre or finer (at 4 an edge spreads 25 cm); people and carts
// reach below 2.2 m
let chip = step(12.0, u_age().w) * smoothstep(0.75, 0.9, c.edge) * low * step(0.68 - 0.2 * (1.0 - upkeep), wear_vn2(g.p * 16.0 + vec2<f32>(c.elem * 9.0, 0.0))) * step(0.05, age);
- return WearMarks(age, upkeep, wear, wash, shelter, tuck, crust, tear, stain, damp, salt, splash, low, chip);
+ // WR6: how readily the coat comes off here, and how far neglect has let things go (little while kept up)
+ let loss = wear_loss(c) * g.wall;
+ let neglect = clamp(age * (1.15 - upkeep), 0.0, 1.0);
+ // left empty: neglect past what a lived-in house lets go (broken panes, slates and fallen render are mended or
+ // swept while anyone lives there), the whole house's, so by its own upkeep and not each element's draw
+ let abandon = smoothstep(${f(ABANDON_FROM)}, 1.0, age * (1.15 - clamp(u_age().z, 0.0, 1.0)));
+ return WearMarks(age, upkeep, wear, wash, shelter, tuck, crust, tear, stain, damp, salt, splash, low, chip, loss, neglect, abandon);
}
// a surface's own colour, roughness and metalness as the recipes change them
diff --git a/sdk/wear/src/debug.ts b/sdk/wear/src/debug.ts
index 462afba1..408235a6 100644
--- a/sdk/wear/src/debug.ts
+++ b/sdk/wear/src/debug.ts
@@ -32,6 +32,10 @@ export const DEBUG_CAUSES = {
litter: "vec3<f32>(1.0, 0.5, 0.1) * c.litter",
/** the material class, by WEAR_CLASSES' colour; magenta where the bake found none */
class: "wear_class_colour(c.cls)",
+ /** nearness to a crack from an opening's corner (WR6), in red */
+ crack: "vec3<f32>(1.0, 0.25, 0.1) * (1.0 - c.crack / 0.25)",
+ /** how readily the coat comes off (WR6): the damp foot, soaked faces, knocked arrises, cracks */
+ loss: "vec3<f32>(wear_loss(c))",
} as const;
export type WearCause = keyof typeof DEBUG_CAUSES;
diff --git a/sdk/wear/src/index.ts b/sdk/wear/src/index.ts
index 405585cd..7fdf4d0a 100644
--- a/sdk/wear/src/index.ts
+++ b/sdk/wear/src/index.ts
@@ -10,29 +10,33 @@
//
// The same spec goes on one glTF material (<StandardMaterial material="facade"/> as the base), a
// <MeshStandardMaterial shader={wear}>, or a <SurfaceShader {...wear}> over the whole scene. A surface without the
-// bake's second UV set is drawn as it was.
+// bake's second UV set is drawn as it was. Crumbling (WR6) follows the same age: render lost to the brick, paint to
+// the primer and the wood, enamel to the iron, cracks from the openings' corners, panes broken or boarded, slates
+// gone; `wearDebris(baked, age)` is the debris that age has brought down, where the bake put it.
import { hasNative, native, type NativeCalls } from "@raea/app/native";
-import { CAUSES } from "./causes";
+import { ABANDON_FROM, CAUSES } from "./causes";
import { debugHook, DEBUG_CAUSES, type WearCause } from "./debug";
import { HELPERS, RECIPES, SHARED, WEATHER } from "./recipes";
export { DEBUG_CAUSES, type WearCause } from "./debug";
+export { ABANDON_FROM, CRACK_REACH, CRACK_WEIGHT, LOSS } from "./causes";
+export { WEAR_CONDITIONS, WEATHER_RATES, weatherAt, type WearCondition, type WearSpell } from "./weather";
/** The material classes, in the bake's order (causes2's alpha is 16 x (the place + 1)), each with its colour in the
* debug view and what the causes do to it. */
export const WEAR_CLASSES = [
- { name: "plaster", colour: [0.95, 0.9, 0.75], marks: "washed clean and chalky; soot grey where sheltered, darkest under cornices; dark tears from sill ends; splash to 0.4 m and a damp tide at 0.6-1.2 m; blown at the foot; chipped arrises low down; a grease band" },
- { name: "brick", colour: [0.75, 0.3, 0.2], marks: "mortar washed out; soot black where sheltered; efflorescence under ledges; a tide line, green on north faces; spalled faces" },
+ { name: "plaster", colour: [0.95, 0.9, 0.75], marks: "washed clean and chalky; soot grey where sheltered, darkest under cornices; dark tears from sill ends; splash to 0.4 m and a damp tide at 0.6-1.2 m; by neglect blown to the brick behind at the damp foot, under sills, at knocked arrises and along cracks, and cracked from the openings' corners; chipped arrises low down; a grease band" },
+ { name: "brick", colour: [0.75, 0.3, 0.2], marks: "mortar washed out; soot black where sheltered; efflorescence under ledges; a tide line, green on north faces; spalled faces; cracks stepping along the joints from the openings' corners" },
{ name: "sandstone", colour: [0.9, 0.75, 0.45], marks: "washed light; a black crust where sheltered; black and white streaks under ledges; rounded arrises" },
{ name: "granite", colour: [0.6, 0.6, 0.62], marks: "little: soot where sheltered" },
- { name: "wood", colour: [0.55, 0.35, 0.15], marks: "sun-faded and alligatored on the faces the sun reaches; peeling at bottom rails; rot at the foot; worn to the wood where held and kicked" },
+ { name: "wood", colour: [0.55, 0.35, 0.15], marks: "sun-faded and alligatored on the faces the sun reaches; peeling to the primer and the wood at bottom rails, and by neglect wherever the coat's loosened; rot at the foot; worn to the wood where held and kicked" },
{ name: "iron", colour: [0.25, 0.3, 0.4], marks: "paint flaking at joints and arrises; rust at the foot and on the stone below; bright where held" },
{ name: "zinc", colour: [0.7, 0.8, 0.85], marks: "a pale patina where rain-washed; white streaks below" },
{ name: "copper", colour: [0.3, 0.7, 0.55], marks: "verdigris where rain-washed, brown-black where sheltered; green streaks below" },
- { name: "slate", colour: [0.35, 0.35, 0.45], marks: "lichen where the sun misses; soot in the laps" },
+ { name: "slate", colour: [0.35, 0.35, 0.45], marks: "lichen where the sun misses; soot in the laps; slates gone by neglect, most along ridges, verges and eaves" },
{ name: "felt", colour: [0.15, 0.15, 0.15], marks: "greyed by the sun; washed where the rain runs" },
- { name: "glass", colour: [0.5, 0.85, 1.0], marks: "a grime film where sheltered, thickest at the bottom and corners" },
- { name: "enamel", colour: [0.2, 0.3, 0.9], marks: "rust bled from its screws; chipped to black iron at holes and edges" },
+ { name: "glass", colour: [0.5, 0.85, 1.0], marks: "a grime film where sheltered, thickest at the bottom and corners; panes broken or boarded by neglect" },
+ { name: "enamel", colour: [0.2, 0.3, 0.9], marks: "rust bled from its screws; chipped to black iron at holes and edges, and by neglect flaking in sheets to rusting iron" },
{ name: "brass", colour: [0.9, 0.7, 0.2], marks: "dull brown, more where rain-washed; bright where touched" },
{ name: "ground", colour: [0.4, 0.55, 0.3], marks: "dirt in corners and at the wall's foot; moss where the sun misses; polished where feet pass" },
] as const satisfies readonly { name: string; colour: [number, number, number]; marks: string }[];
@@ -90,6 +94,59 @@ export interface WearWeather {
melt?: number;
}
+/** A thing the bake's rules put on the model (spots.json, docs/wear.feature WR3, WR6): what, who put it there, its
+ * middle, the face it's on and its size (across, up); debris also carries the loss potential of the plaster above it. */
+export interface WearSpot {
+ what: "bill" | "street plate" | "nameplate" | "debris";
+ by: string;
+ at: [number, number, number];
+ n: [number, number, number];
+ size: [number, number];
+ loss?: number;
+}
+
+const spotsOf = new Map<string, WearSpot[]>();
+
+/** The spots the bake put down (bills, street plates, nameplates, debris), read once from its spots.json. */
+export function wearSpots(baked: Pick<WearBaked, "spots">): WearSpot[] {
+ const path = baked?.spots;
+ if (typeof path !== "string") throw new TypeError("wearSpots: baked is wearBake's answer, with its spots");
+ let s = spotsOf.get(path);
+ if (!s) {
+ if (!hasNative()) throw new Error("wearSpots: reading the bake's spots needs the raea engine (raea render)");
+ const got = native("asset.read", { path });
+ // spots.json is ASCII (the rules' names and numbers), so atob's binary string is its text
+ s = JSON.parse(atob(got.base64)) as WearSpot[];
+ spotsOf.set(path, s);
+ }
+ return s;
+}
+
+/** How far neglect has let things go at an age (wearShader's own: the marks' age, less what upkeep keeps up). */
+export function neglectOf(age: WearAge = {}): number {
+ const years = age.years ?? 30;
+ const upkeep = age.upkeep ?? 0.5;
+ return Math.min(1, Math.max(0, (1 - Math.exp(-Math.max(years, 0) / 25)) * (1.15 - upkeep)));
+}
+
+/** How far a house is left empty at an age, 0..1 (wearShader's own): neglect past ABANDON_FROM. A lived-in house
+ * mends its panes and slates and sweeps its walk however poorly it is kept. */
+export function abandonOf(age: WearAge = {}): number {
+ const t = Math.min(1, Math.max(0, (neglectOf(age) - ABANDON_FROM) / (1 - ABANDON_FROM)));
+ return t * t * (3 - 2 * t);
+}
+
+/** A heap shows where the plaster above it has come off and nobody sweeps: loss potential x abandonment past this. */
+export const DEBRIS_AT = 0.3;
+
+/** The debris an age has left lying (WR6): the bake's debris under plaster whose loss potential has let it go, on
+ * the walk of a house left empty. `spots` is wearSpots' answer, or wearBake's to read it. */
+export function wearDebris(spots: readonly WearSpot[] | Pick<WearBaked, "spots">, age: WearAge = {}): WearSpot[] {
+ const all = Array.isArray(spots) ? (spots as readonly WearSpot[]) : wearSpots(spots as Pick<WearBaked, "spots">);
+ const a = abandonOf(age);
+ return all.filter((s) => s.what === "debris" && (s.loss ?? 0) * a >= DEBRIS_AT);
+}
+
export interface WearShaderOptions {
/** wearBake's answer: its maps are the shader's textures, its density decides whether edges can chip */
baked: Pick<WearBaked, "maps" | "density">;
@@ -179,8 +236,9 @@ ${cases.join("\n")}
const SURFACE = /* wgsl */ `
fn wear_surface(uv: vec2<f32>, pbr: ptr<function, PbrInput>) {
+ let px = length(fwidth((*pbr).world_position.xyz));
let c = wear_causes(uv);
- let g = wear_geo((*pbr).world_position.xyz, (*pbr).world_normal, c);
+ let g = wear_geo((*pbr).world_position.xyz, (*pbr).world_normal, c, (*pbr).V, px);
let m = wear_marks(c, g);
var s = WearSurf((*pbr).material.base_color.rgb, (*pbr).material.perceptual_roughness, (*pbr).material.metallic);
if (!wear_class(&s, c, g, m)) { return; }
diff --git a/sdk/wear/src/recipes.ts b/sdk/wear/src/recipes.ts
index 5b041869..f0a3f0d0 100644
--- a/sdk/wear/src/recipes.ts
+++ b/sdk/wear/src/recipes.ts
@@ -14,16 +14,21 @@ export const RECIPES: Record<string, string> = {
(*s).rough = mix((*s).rough, 0.95, m.wash * 0.4 * m.age);
// sheltered: soot grey, darkest tucked under cornices
(*s).col = mix((*s).col, (*s).col * vec3<f32>(0.3, 0.29, 0.27), m.crust);
- // the foot: render blown where the damp and the frost work, the brick behind it showing (worst where let go)
- let blowN = wear_fbm2(g.p * vec2<f32>(0.9, 1.4) + vec2<f32>(c.elem * 0.31, 5.0));
- let blowAt = 0.74 - 0.2 * (1.0 - m.upkeep) - 0.12 * (1.0 - smoothstep(0.15, 0.9, g.h));
- let foot = (1.0 - smoothstep(0.7, 1.3, g.h)) * g.wall * step(0.2, m.wear);
- let blown = smoothstep(blowAt, blowAt + 0.015, blowN) * foot;
- let lip = smoothstep(blowAt - 0.04, blowAt, blowN) * (1.0 - blown) * foot;
- (*s).col = mix((*s).col, wear_bond(g.p) * mix(1.0, 0.55, m.crust), blown);
- (*s).col = (*s).col * (1.0 - 0.45 * lip);
+ // WR6: the render lost where the causes loosen it (the damp foot, soaked faces, knocked arrises, along a crack) and
+ // neglect lets it go, to the brick 2 cm behind it; the broken edge's lip shades the hole under it
+ let lost = m.loss * m.neglect;
+ let lossAt = 0.8 - 0.34 * lost;
+ let q = g.p * vec2<f32>(0.9, 1.4) + vec2<f32>(c.elem * 0.31, 5.0);
+ let blowN = wear_fbm2(q);
+ let gone = smoothstep(lossAt, lossAt + 0.012, blowN) * step(0.03, lost);
+ let over = smoothstep(lossAt, lossAt + 0.012, wear_fbm2(q + vec2<f32>(0.0, 0.042)));
+ let lip = smoothstep(lossAt - 0.035, lossAt, blowN) * (1.0 - gone) * step(0.03, lost);
+ let behind = wear_bond(g.p + g.par * 0.02) * mix(1.0, 0.55, m.crust);
+ (*s).col = mix((*s).col, behind * (1.0 - 0.55 * (1.0 - over)), gone);
+ (*s).col = (*s).col * (1.0 - 0.4 * lip);
+ (*s).rough = mix((*s).rough, 0.95, gone);
// chipped arrises low down: the lime coat knocked off to the brick
- (*s).col = mix((*s).col, mix(vec3<f32>(0.78, 0.76, 0.7), wear_bond(g.p), 0.5), m.chip * (1.0 - blown));
+ (*s).col = mix((*s).col, mix(vec3<f32>(0.78, 0.76, 0.7), wear_bond(g.p), 0.5), m.chip * (1.0 - gone));
// a grease band where shoulders and hubs rub
(*s).col = mix((*s).col, (*s).col * vec3<f32>(0.5, 0.48, 0.45), c.touch * 0.6 * g.wall);
(*s).rough = mix((*s).rough, 0.55, c.touch * 0.5);`,
@@ -66,9 +71,14 @@ export const RECIPES: Record<string, string> = {
(*s).col = mix((*s).col, vec3<f32>(dot((*s).col, vec3<f32>(0.33))) * 1.25 + vec3<f32>(0.04), c.sun * 0.45 * m.wear);
let cells = abs(wear_vn2(g.p * vec2<f32>(14.0, 9.0)) - 0.5);
(*s).col = (*s).col * (1.0 - 0.45 * (1.0 - smoothstep(0.015, 0.05, cells)) * smoothstep(0.3, 0.8, c.sun) * m.wear);
- // under a ledge and at the bottom rails: peeling where the run-off soaks the timber, the grey wood showing
+ // under a ledge and at the bottom rails: peeling where the run-off soaks the timber, and by neglect (WR6) wherever
+ // the coat's loosened: the top coat off to the red-lead primer, then to the grey wood
let wetWood = clamp(c.flow + (1.0 - smoothstep(0.04, 0.5, g.h)) * g.wall, 0.0, 1.0);
- let peel = smoothstep(0.5, 0.56, wear_fbm2(g.p * vec2<f32>(9.0, 4.0)) + 0.2 * wetWood * m.wear) * wetWood * step(0.1, m.wear);
+ let bare = wear_fbm2(g.p * vec2<f32>(9.0, 4.0)) + 0.2 * wetWood * m.wear + 0.25 * m.loss * m.neglect;
+ let reach = max(wetWood, m.loss * smoothstep(0.1, 0.5, m.neglect)) * step(0.1, m.wear);
+ let primer = smoothstep(0.46, 0.49, bare) * reach;
+ let peel = smoothstep(0.53, 0.56, bare) * reach;
+ (*s).col = mix((*s).col, vec3<f32>(0.58, 0.34, 0.25) * (0.9 + 0.2 * wear_vn2(g.p * 25.0)), primer * (1.0 - peel));
(*s).col = mix((*s).col, vec3<f32>(0.3, 0.27, 0.22) * (0.8 + 0.3 * wear_vn2(vec2<f32>(g.p.x * 30.0, g.p.y * 2.0))), max(peel, m.chip));
// rot at the foot
let rot = (1.0 - smoothstep(0.02, 0.25, g.h)) * m.wear * g.wall;
@@ -114,7 +124,16 @@ export const RECIPES: Record<string, string> = {
// lichen on the faces the sun misses, soot in the laps
let lichen = (1.0 - c.sun) * smoothstep(0.55, 0.75, wear_fbm2(g.p * 2.5 + vec2<f32>(c.elem * 0.13, 1.0))) * m.age;
(*s).col = mix((*s).col, vec3<f32>(0.2, 0.22, 0.13), lichen * 0.6);
- (*s).col = mix((*s).col, vec3<f32>(0.03), m.crust * 0.5);`,
+ (*s).col = mix((*s).col, vec3<f32>(0.03), m.crust * 0.5);
+ // WR6: slates slipped and gone, the odd one by neglect and many once the house is empty, more along the ridge, the
+ // verges and the eaves, the battens and the
+ // felt under them showing (courses 11 cm up the slope's height, slates 25 cm across, broken bond)
+ let course = floor(g.p.y / 0.11);
+ let across = g.p.x / 0.25 + select(0.0, 0.5, i32(course) % 2 == 1);
+ let missing = step(wear_h21(vec2<f32>(floor(across) + c.elem * 17.0, course)), 0.1 * (0.15 * m.neglect + 0.85 * m.abandon) * (1.0 + 2.0 * c.edge));
+ let batten = 1.0 - smoothstep(0.0, 0.18, abs(fract(g.p.y / 0.11) - 0.5) * 2.0 - 0.6);
+ (*s).col = mix((*s).col, mix(vec3<f32>(0.04, 0.035, 0.03), vec3<f32>(0.3, 0.21, 0.12), batten), missing);
+ (*s).rough = mix((*s).rough, 0.95, missing);`,
felt: /* wgsl */ `
// roofing felt: greyed by the sun, its grit washed off where the rain runs
@@ -125,7 +144,23 @@ export const RECIPES: Record<string, string> = {
// sheltered: a grime film, thickest in the corners and at the bottom where the frame holds the dirt
let film = clamp(m.shelter * 0.5 + c.cav * 0.8 + (1.0 - m.wash) * 0.2, 0.0, 1.0) * m.age * (1.0 - 0.6 * m.upkeep);
(*s).col = mix((*s).col, (*s).col * vec3<f32>(0.62, 0.6, 0.55), film * 0.7);
- (*s).rough = mix((*s).rough, 0.55, film * 0.6);`,
+ (*s).rough = mix((*s).rough, 0.55, film * 0.6);
+ // WR6: a house left empty has its panes broken and boarded over, one fate per pane
+ let fate = wear_h21(vec2<f32>(c.elem, 11.0));
+ if (fate < 0.16 * m.abandon) {
+ // boarded: planks of grey, weathered deal across the opening
+ let row = fract(g.p.y / 0.15);
+ let tone = 0.75 + 0.4 * wear_h21(vec2<f32>(floor(g.p.y / 0.15), c.elem));
+ let gap = 1.0 - smoothstep(0.0, 0.06, min(row, 1.0 - row));
+ (*s).col = vec3<f32>(0.36, 0.32, 0.26) * tone * (0.85 + 0.3 * wear_vn2(vec2<f32>(g.p.x * 30.0, g.p.y * 3.0))) * (1.0 - 0.7 * gap);
+ (*s).rough = 0.9;
+ (*s).metal = 0.0;
+ } else if (fate < 0.38 * m.abandon) {
+ // broken: the dark room behind, shards left in the putty at the frame
+ let shard = smoothstep(0.52, 0.56, wear_fbm2(g.p * 7.0 + vec2<f32>(c.elem, 0.0)) * 0.6 + 0.7 * c.cav);
+ (*s).col = mix(vec3<f32>(0.012, 0.011, 0.01), (*s).col, shard);
+ (*s).rough = mix(1.0, (*s).rough, shard);
+ }`,
enamel: /* wgsl */ `
// rust bled from its screws, in short tails below them
@@ -133,10 +168,17 @@ export const RECIPES: Record<string, string> = {
let screw = step(0.8, wear_h21(vec2<f32>(col, c.elem)));
let tail = screw * (1.0 - smoothstep(0.0, 0.04, abs(fract(g.p.x * 6.0) - 0.5) / 6.0)) * smoothstep(0.3, 0.9, wear_vn2(vec2<f32>(col, g.p.y * 3.0)));
(*s).col = mix((*s).col, vec3<f32>(0.3, 0.12, 0.04), tail * m.wear * 0.8);
- // chipped to black iron at its holes and edges
+ // chipped to black iron at its holes and edges, and by neglect (WR6) flaking off in sheets from them to the iron,
+ // which rusts, and rust creeping under the enamel's broken edge
let chipped = smoothstep(0.65, 0.9, c.edge) * step(0.62 - 0.3 * m.wear, wear_vn2(g.p * 30.0)) * step(0.05, m.wear);
- (*s).col = mix((*s).col, vec3<f32>(0.03, 0.03, 0.035), chipped);
- (*s).rough = mix((*s).rough, 0.7, chipped);`,
+ let flakeN = wear_fbm2(g.p * 14.0 + vec2<f32>(c.elem * 3.1, 0.0));
+ let flakeAt = 0.82 - 0.38 * m.neglect * max(smoothstep(0.5, 0.9, c.edge), 0.5 * m.loss + 0.3);
+ let flake = smoothstep(flakeAt, flakeAt + 0.01, flakeN) * step(0.05, m.neglect);
+ let creep = smoothstep(flakeAt - 0.03, flakeAt, flakeN) * (1.0 - flake) * step(0.05, m.neglect);
+ let iron = mix(vec3<f32>(0.03, 0.03, 0.035), vec3<f32>(0.2, 0.08, 0.03), smoothstep(0.3, 0.7, wear_vn2(g.p * 40.0)) * flake);
+ (*s).col = mix((*s).col, iron, max(chipped, flake));
+ (*s).col = mix((*s).col, vec3<f32>(0.25, 0.1, 0.04), creep * 0.7);
+ (*s).rough = mix((*s).rough, 0.75, max(chipped, flake));`,
brass: /* wgsl */ `
// tarnished dull brown, more where the rain reaches; bright where hands touch it
@@ -195,6 +237,16 @@ fn wear_shared(s: ptr<function, WearSurf>, c: WearCauses, g: WearGeo, m: WearMar
(*s).col = mix((*s).col, vec3<f32>(0.8, 0.79, 0.74), m.salt * 0.3 * porous * smoothstep(0.4, 0.75, wear_vn2(vec2<f32>(g.p.x * 1.3, g.p.y * 3.0))));
if (c.cls != 13 && c.cls != 10) { (*s).col = mix((*s).col, (*s).col * 0.62, m.splash * 0.7); }
(*s).rough = mix((*s).rough, 0.97, m.crust * 0.5);
+ // WR6: cracks from the openings' corners, opening as neglect grows and gathering dirt along them; in brick a crack
+ // steps along the joints. Drawn no thinner than a pixel, fading as it gets thinner than one
+ let opened = smoothstep(0.1, 0.7, m.neglect) * porous;
+ let wide = 0.0035 * opened;
+ let dd = max(c.crack + (wear_vn2(g.p * 38.0) - 0.5) * 0.006, 0.0);
+ let line = (1.0 - smoothstep(0.5 * wide, 0.5 * wide + g.px, dd)) * min(1.0, wide / max(g.px, 0.0001) + 0.25) * step(0.0001, wide);
+ let stepped = (1.0 - smoothstep(0.02, 0.05, c.crack)) * wear_bond_joint(g.p) * opened;
+ let crack = select(line, stepped, c.cls == 1);
+ let halo = (1.0 - smoothstep(0.0, 0.03, dd)) * opened;
+ (*s).col = (*s).col * (1.0 - 0.8 * crack) * (1.0 - 0.15 * halo);
}
`;
diff --git a/sdk/wear/src/weather.ts b/sdk/wear/src/weather.ts
new file mode 100644
index 00000000..fa0e0438
--- /dev/null
+++ b/sdk/wear/src/weather.ts
@@ -0,0 +1,79 @@
+// Weather that changes during a shot (docs/wear.feature WR9): rain starting, snow settling, frost forming. What lies
+// on the surfaces (wet, snow, driven snow, frost) follows what the sky does at its own rate, so a shot that starts
+// dry darkens over the minutes rain takes to soak a front and dries over the hour it takes to dry. `weatherAt` gives
+// the surfaces' weather at a moment, for wearShader each frame.
+//
+// const spells = [{ at: 0 }, { at: 2, rain: 1 }, { at: 40 }]; // dry, raining from minute 2 to 40
+// const minutes = (frame / fps) * 60; // a timelapse: a second a minute
+// wearShader({ baked, weather: weatherAt({ day: 120 }, spells, minutes) })
+import type { WearWeather } from "./index";
+
+/** What the sky does from minute `at` of the shot on: rain, snow falling, a storm driving it, frost (each 0..1;
+ * what a spell leaves out is 0). */
+export interface WearSpell {
+ at: number;
+ rain?: number;
+ snow?: number;
+ storm?: number;
+ ice?: number;
+}
+
+/** How fast the surfaces follow the sky, the share of the way left covered per minute (ASSUMED until measured):
+ * wetting in about 3 minutes of steady rain, drying over about an hour; snow settling over about 20 minutes and
+ * melting over about two hours; driven snow plastering in about 10 and falling off over 30; frost forming over half
+ * an hour and going in 20. */
+export const WEATHER_RATES = { wet: 1 / 3, dry: 1 / 60, settle: 1 / 20, melt: 1 / 120, plaster: 1 / 10, shed: 1 / 30, freeze: 1 / 30, thaw: 1 / 20 } as const;
+
+type Lying = { wet: number; snow: number; storm: number; ice: number };
+const KEYS = [
+ ["wet", "rain", "wet", "dry"],
+ ["snow", "snow", "settle", "melt"],
+ ["storm", "storm", "plaster", "shed"],
+ ["ice", "ice", "freeze", "thaw"],
+] as const;
+
+/** The surfaces' weather `minutes` into the shot: `base` is how they lie when it starts (its day, and its wet, snow,
+ * storm and ice), `spells` what the sky does from when (in order). Each value eases toward the sky's at its rate,
+ * exactly (an exponential over each spell), so any frame can be drawn alone. */
+export function weatherAt(base: WearWeather, spells: readonly WearSpell[], minutes: number): WearWeather {
+ if (!Number.isFinite(minutes)) throw new RangeError(`weatherAt: minutes is a number, got ${minutes}`);
+ for (let i = 1; i < spells.length; i++) if (!(spells[i].at >= spells[i - 1].at)) throw new RangeError("weatherAt: spells are in order of `at`");
+ const v: Lying = { wet: base.wet ?? 0, snow: base.snow ?? 0, storm: base.storm ?? 0, ice: base.ice ?? 0 };
+ let t = spells.length ? Math.min(spells[0].at, minutes) : minutes;
+ for (let i = 0; i < spells.length && spells[i].at <= minutes; i++) {
+ const s = spells[i];
+ const end = Math.min(i + 1 < spells.length ? spells[i + 1].at : minutes, minutes);
+ const dt = Math.max(0, end - Math.max(t, s.at));
+ for (const [k, sky, up, down] of KEYS) {
+ const target = s[sky] ?? 0;
+ if (!(target >= 0 && target <= 1)) throw new RangeError(`weatherAt: a spell's ${sky} is 0..1, got ${target}`);
+ const rate = WEATHER_RATES[target > v[k] ? up : down];
+ v[k] = target + (v[k] - target) * Math.exp(-rate * dt);
+ }
+ t = end;
+ }
+ const r = (x: number) => Math.round(x * 1e4) / 1e4;
+ return { ...base, wet: r(v.wet), snow: r(v.snow), storm: r(v.storm), ice: r(v.ice) };
+}
+
+/** WR9's eight conditions as weather on the surfaces: a day of the year in its season and what lies on them. The
+ * light that goes with each (overcast for rain, a flash for thunder) is the scene's. */
+export const WEAR_CONDITIONS = {
+ /** damp lingering on north faces and plinths, algae where the run-off and the shade meet */
+ spring: { day: 105, damp: 0.85 },
+ /** dry: dust on ledges and treads */
+ summer: { day: 205 },
+ /** leaves where blown things settle, wet and dark after a shower */
+ autumn: { day: 300, wet: 0.35, leaves: 1 },
+ /** frost on the faces the winter sun misses */
+ winter: { day: 20, ice: 0.8 },
+ /** snow lying on what is open above, deeper in the lee */
+ snow: { day: 30, snow: 0.85, ice: 0.4 },
+ /** snow, and driven snow plastered on the faces the storm reaches */
+ blizzard: { day: 40, snow: 1, storm: 0.9, ice: 0.6 },
+ /** wet where the rain reaches, rivulets down the run-off's paths, puddles in the walk's hollows */
+ rain: { day: 130, wet: 0.8 },
+ /** heavy rain: wet through */
+ thunder: { day: 200, wet: 1 },
+} as const satisfies Record<string, WearWeather>;
+export type WearCondition = keyof typeof WEAR_CONDITIONS;
diff --git a/sdk/wear/test/wear.test.ts b/sdk/wear/test/wear.test.ts
index 1d78dc6c..379293c4 100644
--- a/sdk/wear/test/wear.test.ts
+++ b/sdk/wear/test/wear.test.ts
@@ -1,8 +1,10 @@
import { describe, expect, test } from "bun:test";
import { readFileSync } from "node:fs";
import { surfaceShader } from "@raea/render/3d/materials";
-import { DEBUG_CAUSES, seasonOf, WEAR_CLASSES, wearShader, type WearCause } from "../src/index";
+import { ABANDON_FROM, abandonOf, CRACK_REACH, CRACK_WEIGHT, DEBRIS_AT, DEBUG_CAUSES, LOSS, neglectOf, seasonOf, WEAR_CLASSES, wearDebris, wearShader, type WearCause, type WearSpot } from "../src/index";
import { RECIPES } from "../src/recipes";
+import { CAUSES } from "../src/causes";
+import { WEAR_CONDITIONS, weatherAt } from "../src/weather";
const baked = { maps: { causes0: "/s/causes0.png", causes1: "/s/causes1.png", causes2: "/s/causes2.png", causes3: "/s/causes3.png" }, density: 16 };
const ROOT = new URL("../../..", import.meta.url).pathname;
@@ -73,6 +75,61 @@ describe("the shader", () => {
});
});
+describe("crumbling (WR6)", () => {
+ const rs = readFileSync(`${ROOT}systems/damage/src/lib.rs`, "utf8");
+ const num = (name: string) => Number(rs.match(new RegExp(`const ${name}: f32 = ([0-9.]+);`))?.[1]);
+ test("the loss potential is raea-sys-damage's, so the debris it put down lies under the losses", () => {
+ const list = rs.match(/pub const LOSS: \[f32; (\d+)\] = \[([^\]]*)\]/);
+ expect(list).not.toBeNull();
+ expect(list![2].split(",").map(Number)).toEqual([...LOSS]);
+ expect(num("CRACK_WEIGHT")).toBe(CRACK_WEIGHT);
+ expect(num("REACH")).toBe(CRACK_REACH);
+ const sh = wearShader({ baked }).wesl;
+ expect(sh).toContain("fn wear_loss(c: WearCauses) -> f32");
+ expect(sh.includes(`let foot = 1.0 - smoothstep(${LOSS[0]}, ${LOSS[1]}, c.ground);`)).toBe(true);
+ expect(sh.includes("(1.0 - d.a) * 0.25")).toBe(true);
+ });
+ test("each class crumbles its own way", () => {
+ const sh = wearShader({ baked }).wesl;
+ const body = (c: string) => sh.slice(sh.indexOf(`fn wear_${c}(`), sh.indexOf("\n}\n", sh.indexOf(`fn wear_${c}(`)));
+ expect(body("plaster")).toContain("wear_bond(g.p + g.par * 0.02)");
+ expect(body("wood")).toContain("primer");
+ expect(body("enamel")).toContain("flake");
+ expect(body("glass")).toContain("boarded");
+ expect(body("glass")).toContain("broken");
+ expect(body("slate")).toContain("missing");
+ // cracks for the masonry and render, stepping along brick's joints, from a pixel size taken before any branch
+ expect(sh).toContain("let crack = select(line, stepped, c.cls == 1);");
+ const surf = sh.slice(sh.indexOf("fn wear_surface("));
+ expect(surf.indexOf("fwidth(")).toBeLessThan(surf.indexOf("if ("));
+ });
+ test("neglect grows with the years and falls with upkeep", () => {
+ expect(neglectOf({ years: 0 })).toBe(0);
+ expect(neglectOf({ years: 80, upkeep: 0.1 })).toBeGreaterThan(0.9);
+ expect(neglectOf({ years: 80, upkeep: 1 })).toBeLessThan(0.2);
+ expect(neglectOf({ years: 30, upkeep: 0.5 })).toBeGreaterThan(neglectOf({ years: 10, upkeep: 0.5 }));
+ });
+ test("a house is left empty only past what a lived-in one lets go", () => {
+ expect(abandonOf({ years: 80, upkeep: 0.35 })).toBe(0);
+ expect(abandonOf({ years: 30, upkeep: 0.5 })).toBe(0);
+ expect(abandonOf({ years: 90, upkeep: 0.05 })).toBeGreaterThan(0.95);
+ expect(abandonOf({ years: 80, upkeep: 0.2 })).toBeGreaterThan(0);
+ expect(neglectOf({ years: 80, upkeep: 0.35 })).toBeLessThan(ABANDON_FROM);
+ // the shader's own threshold is the same number
+ expect(CAUSES).toContain(`smoothstep(${ABANDON_FROM}, 1.0, age * (1.15 - clamp(u_age().z, 0.0, 1.0)))`);
+ });
+ test("debris lies where its plaster has come off and nobody sweeps", () => {
+ const heap = (loss: number): WearSpot => ({ what: "debris", by: "weather", at: [0, 0, 0], n: [0, 1, 0], size: [0.5, 0.3], loss });
+ const spots: WearSpot[] = [heap(1), heap(0.55), { what: "bill", by: "bill poster", at: [0, 1.5, 0], n: [0, 0, 1], size: [0.6, 0.85] }];
+ expect(wearDebris(spots, { years: 0 })).toEqual([]);
+ expect(wearDebris(spots, { years: 80, upkeep: 0.35 })).toEqual([]);
+ expect(wearDebris(spots, { years: 90, upkeep: 0.05 })).toHaveLength(2);
+ const some = wearDebris(spots, { years: 80, upkeep: 0.2 });
+ expect(some.every((s) => s.what === "debris" && s.loss! * abandonOf({ years: 80, upkeep: 0.2 }) >= DEBRIS_AT)).toBe(true);
+ expect(some.length).toBeLessThan(2);
+ });
+});
+
describe("the uniforms", () => {
test("carry age, the day's weather and the season's own share", () => {
const sh = wearShader({ baked, age: { years: 60, soot: 0.9, upkeep: 0.3 }, weather: { day: 300, wet: 0.4, snow: 0.2 }, up: [0, 0, 1] });
@@ -114,3 +171,46 @@ describe("the debug mode", () => {
expect(() => wearShader({ baked, debug: "rain" as never })).toThrow(/debug is one of/);
});
});
+
+describe("weather during a shot (WR9)", () => {
+ const rain = [{ at: 0 }, { at: 2, rain: 1 }, { at: 40 }];
+ test("rain soaks a dry front in minutes and it dries over the hour", () => {
+ expect(weatherAt({ day: 120 }, rain, 1).wet).toBe(0);
+ expect(weatherAt({ day: 120 }, rain, 3).wet).toBeGreaterThan(0.2);
+ expect(weatherAt({ day: 120 }, rain, 12).wet).toBeGreaterThan(0.95);
+ const stop = weatherAt({ day: 120 }, rain, 40).wet!;
+ expect(weatherAt({ day: 120 }, rain, 50).wet).toBeLessThan(stop);
+ expect(weatherAt({ day: 120 }, rain, 50).wet).toBeGreaterThan(0.75);
+ expect(weatherAt({ day: 120 }, rain, 300).wet).toBeLessThan(0.05);
+ expect(weatherAt({ day: 120 }, rain, 3).day).toBe(120);
+ });
+ test("each frame stands alone, and the values run on without a jump at a spell", () => {
+ const at = (m: number) => weatherAt({}, rain, m).wet!;
+ expect(Math.abs(at(40.001) - at(39.999))).toBeLessThan(1e-3);
+ for (let m = 0; m < 60; m += 1.7) expect(at(m)).toBeGreaterThanOrEqual(0);
+ });
+ test("snow settles, a storm plasters faster than it settles, frost forms", () => {
+ const w = weatherAt({ day: 20 }, [{ at: 0, snow: 1, storm: 1, ice: 1 }], 10);
+ expect(w.storm!).toBeGreaterThan(w.snow!);
+ expect(w.snow!).toBeGreaterThan(0.3);
+ expect(w.ice!).toBeGreaterThan(0.2);
+ expect(weatherAt({ day: 20, snow: 0.8 }, [{ at: 0 }], 60).snow).toBeGreaterThan(0.4);
+ });
+ test("refuses spells out of order or out of range", () => {
+ expect(() => weatherAt({}, [{ at: 5 }, { at: 1 }], 3)).toThrow(/in order/);
+ expect(() => weatherAt({}, [{ at: 0, rain: 2 }], 3)).toThrow(/0..1/);
+ });
+});
+
+describe("the eight conditions (WR9)", () => {
+ test("each is a weather wearShader takes, in its season", () => {
+ expect(Object.keys(WEAR_CONDITIONS)).toEqual(["spring", "summer", "autumn", "winter", "snow", "blizzard", "rain", "thunder"]);
+ for (const w of Object.values(WEAR_CONDITIONS)) {
+ expect(w.day >= 1 && w.day <= 366).toBe(true);
+ for (const v of Object.values(w)) expect(Number.isFinite(v)).toBe(true);
+ }
+ expect(seasonOf(WEAR_CONDITIONS.summer).dust).toBeGreaterThan(0.6);
+ expect(seasonOf(WEAR_CONDITIONS.spring).damp).toBeGreaterThan(0.6);
+ expect(seasonOf(WEAR_CONDITIONS.winter).leaves).toBe(0);
+ });
+});
diff --git a/systems/damage/Cargo.toml b/systems/damage/Cargo.toml
new file mode 100644
index 00000000..314c6f0b
--- /dev/null
+++ b/systems/damage/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "raea-sys-damage"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "Where a building breaks: cracks from the corners of its openings, how readily each point loses its coat, and debris under the losses (raea/wear's crumbling)"
+
+[dependencies]
+parry3d = "0.31"
+rayon = "1"
+raea-sys-touch = { path = "../touch" }
diff --git a/systems/damage/src/lib.rs b/systems/damage/src/lib.rs
new file mode 100644
index 00000000..82d115d0
--- /dev/null
+++ b/systems/damage/src/lib.rs
@@ -0,0 +1,241 @@
+//! Where a building breaks (docs/wear.feature WR6), by rules over the weathering bake's texels:
+//! - cracks run from the re-entrant corners of a wall's openings (a window's, a door's), where a wall's stresses
+//! gather, away from the opening and steeper than 45 degrees, 0.35-1.25 m, wandering as they go; each texel gets
+//! its distance to the nearest crack on its own wall (to REACH), which raea/wear draws, wider as neglect grows;
+//! - the loss potential (`loss`): how readily a point's coat (render, paint, enamel) comes off, from what loosens
+//! it: the damp foot of a wall, run-off soaking where the rain doesn't wash it, a knocked arris low down, a crack.
+//! raea/wear's recipes lose the coat where noise passes a threshold that potential and neglect lower, by the same
+//! formula (its test reads LOSS here);
+//! - debris on the walking surface under plaster with a high loss potential, each with that potential, so a scene
+//! puts down only what its neglect has brought down (raea/wear's wearDebris).
+//! Sizes and weights are ASSUMED until measured.
+
+#[cfg(test)]
+mod tests;
+
+use parry3d::glamx::Vec3;
+use parry3d::query::{Ray, RayCast};
+use rayon::prelude::*;
+
+use raea_sys_touch::{Mat, Point, Spot, Surface};
+
+/// A cache key's part: a change to the rules changes every bake that used them.
+pub const VERSION: &str = "raea-sys-damage 3";
+
+/// How far a texel's distance to a crack is kept (metres): the cause map holds 1 - d / REACH.
+pub const REACH: f32 = 0.25;
+
+/// The loss potential's edges and weights, in the order `loss` uses them (raea/wear's causes.ts has the same list,
+/// and its test compares them): the foot band (ground 0.7-1.3 m), the soak (flow 0.5-0.9, the rain's reach washing
+/// it from 0.35-0.85), the arris (edge 0.75-0.9, below 1.4-2.2 m), the crack (within 0.12 m), then the weights of
+/// the soak, the arris and the crack against the foot's 1.
+pub const LOSS: [f32; 13] = [0.7, 1.3, 0.5, 0.9, 0.35, 0.85, 0.75, 0.9, 1.4, 2.2, 0.12, 0.8, 0.7];
+const CRACK_WEIGHT: f32 = 0.6;
+
+/// a probe's reach across the wall either way when looking for an opening's corner
+const PROBE: f32 = 0.12;
+/// a probe meets the wall when it lands within this of the texel's plane
+const PLANE: f32 = 0.04;
+/// corner texels this near with the same opening are one corner
+const CORNER: f32 = 0.3;
+/// the share of re-entrant corners that crack (ASSUMED: about half; which ones by the corner's place, so a house
+/// cracks the same way every bake)
+const CRACKED: u64 = 50;
+const STEP: f32 = 0.04;
+const DEBRIS: [f32; 2] = [0.5, 0.3];
+const GAP_DEBRIS: f32 = 1.5;
+/// debris only under plaster this ready to come off
+const DEBRIS_LOSS: f32 = 0.5;
+/// how far out from the wall a heap lies (metres), and how far below the wall's foot the walk may be
+const DEBRIS_OUT: f32 = 0.2;
+const DROP: f32 = 0.5;
+/// a wall the rain reaches less than this is indoors (a room's wall, the back of a hollow model): nothing falls on a
+/// walk from it
+const OUTDOORS: f32 = 0.02;
+
+fn smooth(a: f32, b: f32, x: f32) -> f32 {
+ let t = ((x - a) / (b - a)).clamp(0.0, 1.0);
+ t * t * (3.0 - 2.0 * t)
+}
+
+/// How readily the coat at `q` comes off (0-1), with `crack` its distance to the nearest crack (metres).
+pub fn loss(q: &Point, crack: f32) -> f32 {
+ let l = &LOSS;
+ let foot = 1.0 - smooth(l[0], l[1], q.ground);
+ let soak = smooth(l[2], l[3], q.flow) * (1.0 - smooth(l[4], l[5], q.rain));
+ let arris = smooth(l[6], l[7], q.edge) * (1.0 - smooth(l[8], l[9], q.ground));
+ let near = 1.0 - smooth(0.0, l[10], crack);
+ foot.max(l[11] * soak).max(l[12] * arris).max(CRACK_WEIGHT * near)
+}
+
+fn wallish(m: Mat) -> bool {
+ matches!(m, Mat::Plaster | Mat::Masonry)
+}
+
+fn standing(s: &Surface, q: &Point) -> bool {
+ q.n.dot(s.up).abs() < 0.2 && wallish(s.mat[q.tri as usize])
+}
+
+/// The wall of the face at `p` (normal `n`) goes on at `at`: a ray into it from 0.3 m out meets plaster or masonry
+/// facing the same way within PLANE of p's plane (a reveal, a recess, a sill in front or nothing at all is no wall).
+fn wall_at(s: &Surface, p: Vec3, n: Vec3, at: Vec3) -> bool {
+ let o = at + n * 0.3;
+ s.mesh.cast_local_ray_and_get_normal(&Ray::new(o, -n), 0.6, false).is_some_and(|h| {
+ let t = h.subshape as usize;
+ wallish(s.mat[t]) && s.nrm[t].dot(n) > 0.9 && ((o - n * h.time_of_impact - p).dot(n)).abs() < PLANE
+ })
+}
+
+/// An opening's corner: where it is, its wall's normal, and the way a crack leaves it (in the wall's plane, away
+/// from the opening).
+#[derive(Clone, Debug, PartialEq)]
+pub struct Corner {
+ pub at: Vec3,
+ pub n: Vec3,
+ pub away: Vec3,
+}
+
+/// The re-entrant corners of the walls' openings. A wall texel is beside one when, of the eight probes PROBE away
+/// across and up the wall, only one diagonal misses the wall: the opening is that way, and the wall goes on along
+/// both its edges. A building's outer corner (an edge missing too) or a pier between two openings isn't one.
+pub fn corners(s: &Surface, pts: &[Point]) -> Vec<Corner> {
+ let found: Vec<(Vec3, Vec3, Vec3)> = pts
+ .par_iter()
+ .filter(|q| standing(s, q))
+ .filter_map(|q| {
+ let t = s.up.cross(q.n).normalize_or_zero();
+ let on = |d: Vec3| wall_at(s, q.p, q.n, q.p + d);
+ let (x, y) = (t * PROBE, s.up * PROBE);
+ if !(on(x) && on(-x) && on(y) && on(-y)) {
+ return None;
+ }
+ let open: Vec<Vec3> = [x + y, x - y, -x + y, -x - y].into_iter().filter(|&d| !on(d)).collect();
+ (open.len() == 1).then(|| (q.p, q.n, -open[0].normalize()))
+ })
+ .collect();
+ // one corner per cluster: the texels nearest it see it alike; keep their middle
+ let mut out: Vec<(Corner, u32)> = Vec::new();
+ let mut found = found;
+ found.sort_by_key(|f| raea_sys_touch::seed(f.0));
+ for (p, n, away) in found {
+ match out.iter_mut().find(|(c, _)| c.away.dot(away) > 0.99 && c.n.dot(n) > 0.95 && c.at.distance(p) < CORNER) {
+ Some((c, k)) => {
+ c.at = (c.at * *k as f32 + p) / (*k + 1) as f32;
+ *k += 1;
+ }
+ None => out.push((Corner { at: p, n, away }, 1)),
+ }
+ }
+ let mut out: Vec<Corner> = out.into_iter().map(|(c, _)| c).collect();
+ out.sort_by(|a, b| a.at.x.total_cmp(&b.at.x).then(a.at.y.total_cmp(&b.at.y)).then(a.at.z.total_cmp(&b.at.z)));
+ out
+}
+
+fn unit(h: u64) -> f32 {
+ (h >> 40) as f32 / (1u64 << 24) as f32
+}
+
+fn mix(h: u64, k: u64) -> u64 {
+ let mut x = h ^ k.wrapping_mul(0x9e37_79b9_7f4a_7c15);
+ x ^= x >> 31;
+ x = x.wrapping_mul(0xbf58_476d_1ce4_e5b9);
+ x ^ (x >> 29)
+}
+
+/// A crack's path from a corner: steeper than its diagonal (a wall settles), each step turned up to 20 degrees
+/// about that heading, stopping where the wall ends (another opening, the wall's edge) or at its length.
+pub fn crack(s: &Surface, c: &Corner) -> Vec<Vec3> {
+ let h = raea_sys_touch::seed(c.at);
+ let len = 0.35 + 0.9 * unit(mix(h, 1));
+ let side = c.away.dot(s.up).signum();
+ let heading = (c.away + s.up * side * 0.45).normalize_or_zero();
+ let across = c.n.cross(heading);
+ let (mut p, mut run, mut k) = (c.at, 0.0, 0u64);
+ let mut path = vec![p];
+ while run < len {
+ let a = (unit(mix(h, 10 + k)) - 0.5) * 0.7;
+ let q = p + (heading * a.cos() + across * a.sin()) * STEP;
+ if !wall_at(s, c.at, c.n, q) {
+ break;
+ }
+ path.push(q);
+ p = q;
+ run += STEP;
+ k += 1;
+ }
+ path
+}
+
+fn to_segment(p: Vec3, a: Vec3, b: Vec3) -> f32 {
+ let ab = b - a;
+ let t = ((p - a).dot(ab) / ab.length_squared().max(1e-12)).clamp(0.0, 1.0);
+ p.distance(a + ab * t)
+}
+
+/// Whether the corner at `at` cracks (CRACKED in a hundred do).
+fn cracked(at: Vec3) -> bool {
+ raea_sys_touch::seed(at).rotate_right(29) % 100 < CRACKED
+}
+
+/// Each point's distance to the nearest crack on its own wall (same facing, within 5 cm of its plane), at most REACH;
+/// with the corners the cracks start from.
+pub fn cracks(s: &Surface, pts: &[Point]) -> (Vec<f32>, Vec<Corner>) {
+ let cs: Vec<Corner> = corners(s, pts).into_iter().filter(|c| cracked(c.at)).collect();
+ let paths: Vec<(Vec3, Vec<Vec3>, Vec3, Vec3)> = cs
+ .iter()
+ .map(|c| {
+ let path = crack(s, c);
+ let (lo, hi) = path.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(l, h), &p| (l.min(p), h.max(p)));
+ (c.n, path, lo - Vec3::splat(REACH), hi + Vec3::splat(REACH))
+ })
+ .collect();
+ let d = pts
+ .par_iter()
+ .map(|q| {
+ if !standing(s, q) {
+ return REACH;
+ }
+ let mut best = REACH;
+ for (n, path, lo, hi) in &paths {
+ if n.dot(q.n) < 0.95 || (q.p - path[0]).dot(*n).abs() > 0.05 || q.p.cmplt(*lo).any() || q.p.cmpgt(*hi).any() {
+ continue;
+ }
+ for w in path.windows(2) {
+ best = best.min(to_segment(q.p, w[0], w[1]));
+ }
+ }
+ best
+ })
+ .collect();
+ (d, cs)
+}
+
+/// Where a heap from the foot of `q` lands: straight down from DEBRIS_OUT in front of it onto the walk, or nowhere
+/// when the first thing below is something else (a step, a plinth, a sill).
+fn landing(s: &Surface, q: &Point) -> Option<Vec3> {
+ let from = q.p + q.n * DEBRIS_OUT;
+ let h = s.mesh.cast_local_ray_and_get_normal(&Ray::new(from, -s.up), q.ground + DROP, false)?;
+ s.walk[h.subshape as usize].then(|| from - s.up * h.time_of_impact)
+}
+
+/// Debris on the walking surface in front of outdoor plaster whose loss potential is high, one a GAP_DEBRIS apart,
+/// each with the potential of the plaster above it.
+pub fn debris(s: &Surface, pts: &[Point], crack: &[f32]) -> Vec<(Spot, f32)> {
+ let mut c: Vec<(Spot, f32)> = pts
+ .iter()
+ .zip(crack)
+ .filter(|(q, _)| standing(s, q) && s.mat[q.tri as usize] == Mat::Plaster && q.ground <= LOSS[1] && q.rain >= OUTDOORS)
+ .map(|(q, &d)| (q, loss(q, d)))
+ .filter(|(_, l)| *l >= DEBRIS_LOSS)
+ .filter_map(|(q, l)| Some((Spot { what: "debris", by: "weather", at: landing(s, q)?, n: s.up, size: DEBRIS }, l)))
+ .collect();
+ c.sort_by_key(|(sp, _)| raea_sys_touch::seed(sp.at));
+ let mut kept: Vec<(Spot, f32)> = Vec::new();
+ for x in c {
+ if !kept.iter().any(|k| k.0.at.distance(x.0.at) < GAP_DEBRIS) {
+ kept.push(x);
+ }
+ }
+ kept.sort_by(|a, b| a.0.at.x.total_cmp(&b.0.at.x).then(a.0.at.z.total_cmp(&b.0.at.z)));
+ kept
+}
diff --git a/systems/damage/src/tests.rs b/systems/damage/src/tests.rs
new file mode 100644
index 00000000..87543bed
--- /dev/null
+++ b/systems/damage/src/tests.rs
@@ -0,0 +1,190 @@
+//! A plastered front with a window opening 1.2 m wide and 1.6 m high, recessed 0.25 m to its glass, and the wall's
+//! end at x = 6 (a building's outer corner). Points are sampled every 5 cm on the front as an atlas's texels would be;
+//! the ground is the plane y = 0.
+
+use parry3d::glamx::Vec3;
+use parry3d::query::{Ray, RayCast};
+use parry3d::shape::TriMesh;
+
+use raea_sys_touch::{Mat, Point, Surface};
+
+use crate::{CRACKED, REACH, corners, cracked, cracks, debris, loss};
+
+#[derive(Default)]
+struct B {
+ pos: Vec<Vec3>,
+ tri: Vec<[u32; 3]>,
+ nrm: Vec<Vec3>,
+ mat: Vec<Mat>,
+ walk: Vec<bool>,
+}
+
+impl B {
+ fn quad(&mut self, c: [Vec3; 4], out: Vec3, m: Mat, walk: bool) {
+ let n = (c[1] - c[0]).cross(c[2] - c[0]).normalize();
+ let c = if n.dot(out) < 0.0 { [c[0], c[3], c[2], c[1]] } else { c };
+ let i = self.pos.len() as u32;
+ self.pos.extend(c);
+ for t in [[i, i + 1, i + 2], [i, i + 2, i + 3]] {
+ self.tri.push(t);
+ self.nrm.push(out);
+ self.mat.push(m);
+ self.walk.push(walk);
+ }
+ }
+ fn cube(&mut self, a: [f32; 3], b: [f32; 3], m: Mat) {
+ let v = |x: f32, y: f32, z: f32| Vec3::new(x, y, z);
+ let ([x0, y0, z0], [x1, y1, z1]) = (a, b);
+ self.quad([v(x0, y0, z0), v(x0, y0, z1), v(x0, y1, z1), v(x0, y1, z0)], -Vec3::X, m, false);
+ self.quad([v(x1, y0, z0), v(x1, y0, z1), v(x1, y1, z1), v(x1, y1, z0)], Vec3::X, m, false);
+ self.quad([v(x0, y0, z0), v(x1, y0, z0), v(x1, y0, z1), v(x0, y0, z1)], -Vec3::Y, m, false);
+ self.quad([v(x0, y1, z0), v(x1, y1, z0), v(x1, y1, z1), v(x0, y1, z1)], Vec3::Y, m, false);
+ self.quad([v(x0, y0, z0), v(x1, y0, z0), v(x1, y1, z0), v(x0, y1, z0)], -Vec3::Z, m, false);
+ self.quad([v(x0, y0, z1), v(x1, y0, z1), v(x1, y1, z1), v(x0, y1, z1)], Vec3::Z, m, false);
+ }
+ fn mesh(&self) -> TriMesh {
+ TriMesh::new(self.pos.clone(), self.tri.clone()).unwrap()
+ }
+ fn surface<'a>(&'a self, mesh: &'a TriMesh) -> Surface<'a> {
+ Surface { pos: &self.pos, tri: &self.tri, nrm: &self.nrm, mat: &self.mat, walk: &self.walk, mesh, up: Vec3::Y }
+ }
+}
+
+const WIN: [f32; 4] = [-0.6, 0.6, 3.0, 4.6];
+
+/// The front at z = 0 from x = -6 to 6 and 8 m up, of `m`, with the window cut through it, its glass 0.25 m in.
+fn front(m: Mat) -> B {
+ let mut b = B::default();
+ let [x0, x1, y0, y1] = WIN;
+ b.cube([-6.0, 0.0, -0.5], [x0, 8.0, 0.0], m);
+ b.cube([x1, 0.0, -0.5], [6.0, 8.0, 0.0], m);
+ b.cube([x0, 0.0, -0.5], [x1, y0, 0.0], m);
+ b.cube([x0, y1, -0.5], [x1, 8.0, 0.0], m);
+ b.cube([x0, y0, -0.5], [x1, y1, -0.25], Mat::Other);
+ let v = |x: f32, z: f32| Vec3::new(x, 0.0, z);
+ b.quad([v(-20.0, -20.0), v(20.0, -20.0), v(20.0, 20.0), v(-20.0, 20.0)], Vec3::Y, Mat::Other, true);
+ b
+}
+
+/// The front's texels every 5 cm, outside the opening; `flow` and `rain` as the other maps would say.
+fn texels(mesh: &TriMesh, flow: f32, rain: f32) -> Vec<Point> {
+ let mut out = Vec::new();
+ for i in 0..239 {
+ for j in 0..159 {
+ let p = Vec3::new(-5.95 + i as f32 * 0.05, 0.025 + j as f32 * 0.05, 0.0);
+ let [x0, x1, y0, y1] = WIN;
+ if p.x > x0 && p.x < x1 && p.y > y0 && p.y < y1 {
+ continue;
+ }
+ let h = mesh.cast_local_ray_and_get_normal(&Ray::new(p + Vec3::Z * 0.02, -Vec3::Z), 0.05, false).expect("the front");
+ out.push(Point { p, n: Vec3::Z, tri: h.subshape, ground: p.y, rain, flow, edge: 0.0 });
+ }
+ }
+ out
+}
+
+// the four corners of the opening, each leaving away from it; the wall's end at x = 6 isn't one
+#[test]
+fn an_openings_four_corners_and_no_others() {
+ let b = front(Mat::Plaster);
+ let mesh = b.mesh();
+ let s = b.surface(&mesh);
+ let cs = corners(&s, &texels(&mesh, 0.0, 1.0));
+ assert_eq!(cs.len(), 4, "{cs:?}");
+ let [x0, x1, y0, y1] = WIN;
+ for (cx, cy) in [(x0, y0), (x0, y1), (x1, y0), (x1, y1)] {
+ let c = cs.iter().find(|c| c.at.distance(Vec3::new(cx, cy, 0.0)) < 0.2).unwrap_or_else(|| panic!("no corner at {cx}, {cy}: {cs:?}"));
+ let out = Vec3::new(cx.signum(), if cy == y1 { 1.0 } else { -1.0 }, 0.0).normalize();
+ assert!(c.away.dot(out) > 0.95, "corner {cx}, {cy} leaves along {:?}", c.away);
+ assert!(c.n.dot(Vec3::Z) > 0.99);
+ }
+}
+
+// each crack runs on the wall away from its corner, steeper than 45 degrees; texels on it are 0 from it, far ones
+// REACH; the same front gives the same cracks
+#[test]
+fn cracks_leave_the_corners_along_the_wall() {
+ let b = front(Mat::Plaster);
+ let mesh = b.mesh();
+ let s = b.surface(&mesh);
+ let pts = texels(&mesh, 0.0, 1.0);
+ let (d, cs) = cracks(&s, &pts);
+ assert_eq!(d.len(), pts.len());
+ let [x0, x1, y0, y1] = WIN;
+ for c in &cs {
+ let path = crate::crack(&s, c);
+ assert!(path.len() >= 8, "a crack of {} steps from {:?}", path.len(), c.at);
+ let end = *path.last().unwrap();
+ let run = end - c.at;
+ assert!(run.y.abs() > run.x.abs(), "steeper than 45: {run:?}");
+ assert_eq!(run.y.signum(), c.away.y.signum(), "up from the head's corners, down from the sill's");
+ assert_eq!(run.x.signum(), c.away.x.signum(), "away from the opening");
+ for p in &path {
+ assert!(!(p.x > x0 && p.x < x1 && p.y > y0 && p.y < y1), "into the opening at {p:?}");
+ assert!(p.z.abs() < 1e-4);
+ }
+ }
+ let near = pts.iter().zip(&d).filter(|(_, d)| **d < 0.03).count();
+ assert!(near > 20, "{near} texels on the cracks");
+ let far = pts.iter().zip(&d).find(|(q, _)| q.p.distance(Vec3::new(-4.0, 1.0, 0.0)) < 0.05).unwrap();
+ assert_eq!(*far.1, REACH);
+ assert_eq!(cracks(&s, &pts).0, d);
+}
+
+// the loss potential: the damp foot, a soaked face the rain doesn't wash, a knocked arris low down, a crack; nothing
+// on a dry, rain-washed face up the wall
+#[test]
+fn what_loosens_a_coat() {
+ let q = |ground: f32, rain: f32, flow: f32, edge: f32| Point { p: Vec3::ZERO, n: Vec3::Z, tri: 0, ground, rain, flow, edge };
+ assert!((loss(&q(0.2, 1.0, 0.0, 0.0), REACH) - 1.0).abs() < 1e-6, "the foot");
+ assert_eq!(loss(&q(3.0, 1.0, 0.0, 0.0), REACH), 0.0, "a plain face up the wall");
+ assert!((loss(&q(3.0, 0.1, 0.95, 0.0), REACH) - 0.8).abs() < 1e-6, "soaked under a sill");
+ assert_eq!(loss(&q(3.0, 0.95, 0.95, 0.0), REACH), 0.0, "run-off the rain washes");
+ assert!((loss(&q(1.0, 1.0, 0.0, 1.0), REACH) - 0.7).abs() < 0.2, "an arris low down");
+ assert_eq!(loss(&q(3.0, 1.0, 0.0, 1.0), REACH), 0.0, "an arris out of reach");
+ assert!((loss(&q(3.0, 1.0, 0.0, 0.0), 0.0) - 0.6).abs() < 1e-6, "on a crack");
+}
+
+// debris on the walk in front of the plaster's foot, 1.5 m apart, each with the potential above it; none in front of
+// stone, whose face doesn't come off in sheets
+#[test]
+fn debris_under_the_plasters_foot() {
+ let b = front(Mat::Plaster);
+ let mesh = b.mesh();
+ let s = b.surface(&mesh);
+ let pts = texels(&mesh, 0.0, 1.0);
+ let (d, _) = cracks(&s, &pts);
+ let spots = debris(&s, &pts, &d);
+ assert!(spots.len() >= 5, "{} heaps along 12 m", spots.len());
+ for (sp, l) in &spots {
+ assert!(sp.at.y.abs() < 1e-4 && (sp.at.z - 0.2).abs() < 1e-4, "on the walk in front: {:?}", sp.at);
+ assert!(*l >= 0.5 && *l <= 1.0);
+ assert_eq!(sp.what, "debris");
+ }
+ for (i, a) in spots.iter().enumerate() {
+ assert!(spots[i + 1..].iter().all(|b| a.0.at.distance(b.0.at) >= 1.5));
+ }
+ // a wall the rain doesn't reach is indoors; a plinth's top under the foot is no walk
+ assert!(debris(&s, &texels(&mesh, 0.0, 0.0), &d).is_empty(), "indoors");
+ let mut b = front(Mat::Plaster);
+ b.cube([-6.0, 0.0, 0.0], [6.0, 0.6, 0.3], Mat::Masonry);
+ let mesh = b.mesh();
+ let s = b.surface(&mesh);
+ let pts: Vec<Point> = texels(&mesh, 0.0, 1.0).into_iter().filter(|q| q.p.y > 0.6).map(|q| Point { ground: q.p.y, ..q }).collect();
+ let (d, _) = cracks(&s, &pts);
+ assert!(debris(&s, &pts, &d).is_empty(), "on a plinth 0.3 m out, a heap 0.2 m out lands on its top");
+ let stone = front(Mat::Masonry);
+ let mesh = stone.mesh();
+ let s = stone.surface(&mesh);
+ let pts = texels(&mesh, 0.0, 1.0);
+ assert!(debris(&s, &pts, &vec![REACH; pts.len()]).is_empty());
+}
+
+// about CRACKED in a hundred corners crack, the same ones every time: a front of 20 x 20 windows' corners
+#[test]
+fn about_half_the_corners_crack() {
+ let at: Vec<Vec3> = (0..400).map(|i| Vec3::new((i % 20) as f32 * 2.5 - 0.6, (i / 20) as f32 * 3.4 + 1.5, 0.0)).collect();
+ let n = at.iter().filter(|&&p| cracked(p)).count();
+ assert!((n as i64 - CRACKED as i64 * 4).abs() < 60, "{n} of 400 crack");
+ assert!(at.iter().all(|&p| cracked(p) == cracked(p)));
+}
diff --git a/systems/touch/src/lib.rs b/systems/touch/src/lib.rs
index 49f12e57..7f1a414b 100644
--- a/systems/touch/src/lib.rs
+++ b/systems/touch/src/lib.rs
@@ -24,7 +24,7 @@ use parry3d::shape::TriMesh;
pub use spots::Spot;
/// Bumped when the output would change for the same input (a bake that uses it keys on it).
-pub const VERSION: &str = "raea-sys-touch 4";
+pub const VERSION: &str = "raea-sys-touch 5";
/// What a triangle is made of, as far as touch goes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
@@ -120,8 +120,8 @@ impl Parts {
}
}
-/// A seed from a place, the same on every machine (the lock side of a single leaf).
-pub(crate) fn seed(p: Vec3) -> u64 {
+/// A seed from a place, the same on every machine (the lock side of a single leaf; raea-sys-damage's cracks).
+pub fn seed(p: Vec3) -> u64 {
let q = |v: f32| (v * 100.0).round() as i64 as u64;
let mut h = 0xcbf2_9ce4_8422_2325u64;
for v in [q(p.x), q(p.y), q(p.z)] {
diff --git a/systems/touch/src/spots.rs b/systems/touch/src/spots.rs
index 736a3d82..eba178a4 100644
--- a/systems/touch/src/spots.rs
+++ b/systems/touch/src/spots.rs
@@ -4,9 +4,8 @@
//! facing open ground, GAP_BILL apart;
//! - street plates (the city): on a building's corner, 2.5-3 m up, one on each face, where the arris runs from the
//! walking surface to 3.5 m and both faces look onto open ground;
-//! - nameplates (the tenant): beside a single door's lock side, 1.5 m up, on the wall;
-//! - debris (the weather): on the ground under plaster that run-off and rain soak at its foot (blown plaster's
-//! place, until WR6 decides where plaster is lost).
+//! - nameplates (the tenant): beside a single door's lock side, 1.5 m up, on the wall.
+//! Debris under lost plaster is raea-sys-damage's (WR6), by the loss potential raea/wear's recipes use.
//! Candidates are taken in the order of a seed from their place, each kept if none kept is nearer than its gap.
use std::collections::BTreeMap;
@@ -36,8 +35,6 @@ const PLATE: [f32; 2] = [0.6, 0.18];
const CORNER: f32 = 0.4;
const GAP_PLATE: f32 = 2.0;
const NAMEPLATE: [f32; 2] = [0.3, 0.12];
-const DEBRIS: [f32; 2] = [0.5, 0.3];
-const GAP_DEBRIS: f32 = 1.5;
/// open ground in front: a ray out of the face runs this far free
const OPEN: f32 = 2.0;
/// a ray that runs this far free reaches the sky
@@ -158,11 +155,6 @@ pub(crate) fn spots(s: &Surface, doors: &[Door], pts: &[Point]) -> Vec<Spot> {
}
}
- // debris: under plaster soaked at its foot, on the walking surface in front
- let soaked = pts.iter().filter(|q| s.mat[q.tri as usize] == Mat::Plaster && standing(s, q) && q.ground <= 1.2 && q.flow > 0.5 && q.rain > 0.5);
- let debris = soaked.map(|q| Spot { what: "debris", by: "weather", at: q.p - s.up * q.ground + q.n * 0.2, n: s.up, size: DEBRIS }).collect();
- out.extend(thin(debris, GAP_DEBRIS));
-
out.sort_by(|a, b| a.what.cmp(b.what).then(a.at.x.total_cmp(&b.at.x)).then(a.at.y.total_cmp(&b.at.y)).then(a.at.z.total_cmp(&b.at.z)));
out
}
diff --git a/systems/weathering/Cargo.toml b/systems/weathering/Cargo.toml
index 96861cf8..40247f8e 100644
--- a/systems/weathering/Cargo.toml
+++ b/systems/weathering/Cargo.toml
@@ -16,6 +16,7 @@ image = { version = "0.25", default-features = false, features = ["png"] }
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" }
diff --git a/systems/weathering/src/lib.rs b/systems/weathering/src/lib.rs
index 41892c0e..e55aed6e 100644
--- a/systems/weathering/src/lib.rs
+++ b/systems/weathering/src/lib.rs
@@ -11,7 +11,8 @@
//! causes0 = (sky: rain reach, sun: share of the sun's path seen, cavity: occlusion within CAVITY_REACH, edge:
//! nearness to a convex arris); causes1 = (flow, deposit, deposit kind, touch); causes2 = (ground: height over the
//! walking surface, 0-4 m; element: the chart's own number; open: the share of the whole sky seen; class: the
-//! triangle's material class as `Class::code`); causes3 = (winter sun, drift, litter, spare).
+//! 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;
@@ -35,7 +36,7 @@ pub use scene::{Class, Classes};
type R<T> = Result<T, String>;
/// Bumped when a bake's bytes would change for the same request.
-const VERSION: &str = "raea-sys-weathering 6";
+const VERSION: &str = "raea-sys-weathering 7";
/// The world the bake's causes come from.
#[derive(Clone, Debug)]
@@ -146,6 +147,7 @@ pub fn bake(store: &Path, src: &Path, req: &Value) -> R<Value> {
key.update(raea_sys_runoff::VERSION.as_bytes());
key.update(raea_sys_touch::VERSION.as_bytes());
key.update(raea_sys_exposure::VERSION.as_bytes());
+ key.update(raea_sys_damage::VERSION.as_bytes());
key.update(canonical(&strip_src(req)).as_bytes());
key.update(&bytes);
let key: String = key.finalize().iter().take(12).map(|b| format!("{b:02x}")).collect();
@@ -168,7 +170,10 @@ pub fn bake(store: &Path, src: &Path, req: &Value) -> R<Value> {
let (mut c0, mut c1, mut c2, mut c3) = (vec![[0u8; 4]; n], vec![[0u8; 4]; n], vec![[0u8; 4]; n], vec![[0u8; 4]; n]);
rays::causes(&sc, &at, &env, &mesh, &mut c0, &mut c2, &mut c3);
flow::flow(&sc, &at, &env, &mesh, &c0, &mut c1);
- let spots = touch::touch(&sc, &at, &env, &mesh, &c0, &mut c1, &c2);
+ let (spots, crack) = touch::touch(&sc, &at, &env, &mesh, &c0, &mut c1, &c2);
+ for (tx, b) in at.texels.iter().zip(crack) {
+ c3[at.px(tx.x, tx.y)][3] = b;
+ }
let t3 = Instant::now();
std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let model = dir.join("model.glb");
diff --git a/systems/weathering/src/rays.rs b/systems/weathering/src/rays.rs
index d6bac3e1..b430b566 100644
--- a/systems/weathering/src/rays.rs
+++ b/systems/weathering/src/rays.rs
@@ -220,7 +220,8 @@ pub(crate) fn causes(sc: &Scene, at: &Atlas, env: &Env, mesh: &TriMesh, c0: &mut
let edge = edges.near(p, reach_of(t.tri));
let ground = ground(sc, mesh, env, t.tri, p, n);
let element = (crate::rays::hash(at.chart_of[t.tri as usize].wrapping_add(17)) & 0xff) as u8;
- let c3 = [byte(x.december), byte(x.drift), byte(x.litter), 255];
+ // a: the crack, raea-sys-damage's (touch.rs)
+ let c3 = [byte(x.december), byte(x.drift), byte(x.litter), 0];
([byte(sky), byte(x.sun), byte(occl), byte(edge)], [byte(ground / GROUND_RANGE), element, byte(open), sc.class[t.tri as usize].code()], c3)
})
.collect();
diff --git a/systems/weathering/src/tests.rs b/systems/weathering/src/tests.rs
index 28afd8c4..46d30ca7 100644
--- a/systems/weathering/src/tests.rs
+++ b/systems/weathering/src/tests.rs
@@ -332,7 +332,8 @@ fn a_door_is_held_on_one_side_and_gets_its_nameplate() {
let mut c3 = vec![[0u8; 4]; n];
rays::causes(&sc, &at, &e, &mesh, &mut c0, &mut c2, &mut c3);
flow::flow(&sc, &at, &e, &mesh, &c0, &mut c1);
- touch::touch(&sc, &at, &e, &mesh, &c0, &mut c1, &c2);
+ let (_, crack) = touch::touch(&sc, &at, &e, &mesh, &c0, &mut c1, &c2);
+ assert_eq!(crack.len(), at.texels.len());
let touched = |keep: &dyn Fn(Vec3, Vec3) -> bool| at.texels.iter().any(|t| keep(t.p, t.n) && c1[t.y as usize * at.w as usize + t.x as usize][3] > 128);
let held = |side: f32| touched(&|p, n| n.z > 0.99 && (p.z + 0.25).abs() < 0.01 && (0.97..1.08).contains(&p.y) && p.x * side > 0.25);
assert!(held(1.0) != held(-1.0), "the handle band on one side of the leaf only");
@@ -343,5 +344,7 @@ fn a_door_is_held_on_one_side_and_gets_its_nameplate() {
let out = bake(&tmp.join("store"), &tmp.join("door.glb"), &req).unwrap();
let spots: Value = serde_json::from_str(&std::fs::read_to_string(out["spots"].as_str().unwrap()).unwrap()).unwrap();
assert_eq!(spots.as_array().unwrap().iter().filter(|s| s["what"] == "nameplate").count(), 1, "{spots}");
+ // the plaster's foot sheds: debris in front of it, each with its loss potential (raea-sys-damage)
+ assert!(spots.as_array().unwrap().iter().any(|s| s["what"] == "debris" && s["loss"].as_f64().is_some_and(|l| l >= 0.5)), "{spots}");
let _ = std::fs::remove_dir_all(&tmp);
}
diff --git a/systems/weathering/src/touch.rs b/systems/weathering/src/touch.rs
index bcae5e24..2f24cc63 100644
--- a/systems/weathering/src/touch.rs
+++ b/systems/weathering/src/touch.rs
@@ -1,9 +1,11 @@
//! causes1's touch and spots.json (WR3): the model handed to raea-sys-touch with each triangle's material and whether
//! it is walked on, and each texel with what the other maps already say there (its height over the walk, the rain's
-//! reach, the run-off passing, the nearness to an arris).
+//! reach, the run-off passing, the nearness to an arris). The same texels go to raea-sys-damage (WR6): causes3's a
+//! is each one's nearness to a crack from an opening's corner, and debris joins the spots with its loss potential.
use parry3d::glamx::Vec3;
use parry3d::shape::TriMesh;
+use raea_sys_damage as damage;
use raea_sys_touch::{Mat, Point, Spot, Surface, mark};
use serde_json::{Value, json};
@@ -23,8 +25,8 @@ fn mat(c: Class) -> Mat {
}
}
-/// Touch into causes1's a; the spots, as JSON.
-pub(crate) fn touch(sc: &Scene, at: &Atlas, env: &Env, mesh: &TriMesh, c0: &[[u8; 4]], c1: &mut [[u8; 4]], c2: &[[u8; 4]]) -> Value {
+/// Touch into causes1's a; the spots, as JSON, and each texel's crack byte (causes3's a).
+pub(crate) fn touch(sc: &Scene, at: &Atlas, env: &Env, mesh: &TriMesh, c0: &[[u8; 4]], c1: &mut [[u8; 4]], c2: &[[u8; 4]]) -> (Value, Vec<u8>) {
let mats: Vec<Mat> = sc.class.iter().map(|&c| mat(c)).collect();
let walk: Vec<bool> = (0..sc.tri.len()).map(|t| walks(sc, env, t)).collect();
let s = Surface { pos: &sc.pos, tri: &sc.tri, nrm: &sc.nrm, mat: &mats, walk: &walk, mesh, up: env.up };
@@ -34,11 +36,20 @@ pub(crate) fn touch(sc: &Scene, at: &Atlas, env: &Env, mesh: &TriMesh, c0: &[[u8
Point { p: tx.p, n: tx.n, tri: tx.tri, ground: f(c2[i][0]) * GROUND_RANGE, rain: f(c0[i][0]), flow: f(c1[i][0]), edge: f(c0[i][3]) }
}).collect();
let (touch, spots) = mark(&s, &pts);
+ let (cracks, _) = damage::cracks(&s, &pts);
for (tx, v) in at.texels.iter().zip(touch) {
c1[at.px(tx.x, tx.y)][3] = (v.clamp(0.0, 1.0) * 255.0).round() as u8;
}
+ let crack = cracks.iter().map(|d| ((1.0 - d / damage::REACH).clamp(0.0, 1.0) * 255.0).round() as u8).collect();
let v3 = |v: Vec3| json!([round(v.x), round(v.y), round(v.z)]);
- json!(spots.iter().map(|s: &Spot| json!({ "what": s.what, "by": s.by, "at": v3(s.at), "n": v3(s.n), "size": s.size })).collect::<Vec<_>>())
+ let spot = |s: &Spot| json!({ "what": s.what, "by": s.by, "at": v3(s.at), "n": v3(s.n), "size": s.size });
+ let mut out: Vec<Value> = spots.iter().map(spot).collect();
+ out.extend(damage::debris(&s, &pts, &cracks).iter().map(|(s, l)| {
+ let mut v = spot(s);
+ v["loss"] = json!(round(*l));
+ v
+ }));
+ (json!(out), crack)
}
fn round(v: f32) -> f64 {
diff --git a/tools/layers.toml b/tools/layers.toml
index a8e1fea8..83145beb 100644
--- a/tools/layers.toml
+++ b/tools/layers.toml
@@ -103,6 +103,7 @@ raea-sys-weathering = "systems"
raea-sys-runoff = "systems"
raea-sys-touch = "systems"
raea-sys-exposure = "systems"
+raea-sys-damage = "systems"
raea-sys-glb = "systems"
raea-sys-procmat = "systems"
raea-sys-grass = "systems"
@@ -293,5 +294,7 @@ raea-sys-runoff = true
raea-sys-touch = true
# what a model is exposed to through the year: the sun by date, driven snow, where blown things settle (the weathering bake's causes3)
raea-sys-exposure = true
+# where a building breaks: cracks from its openings' corners, how readily a coat comes off, debris under the losses (the weathering bake's causes3 a and debris)
+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