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.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
WR4: raea wear bake and the native call wear.bake, on the weathering bake [WR1] [WR2] [WR3]
shinyobjectzea77b0dbb156
diff --git a/Cargo.lock b/Cargo.lockindex 0e6720a9..c526d00e 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -14258,6 +14258,7 @@ dependencies = ["raea-runtime-plugins","raea-runtime-react","raea-runtime-sound",+ "raea-runtime-wear","raea-sys-index","regex","serde",@@ -15112,6 +15113,7 @@ dependencies = ["raea-io-net","raea-native","raea-runtime-plugins",+ "raea-runtime-wear","raea-sys-fonts","raea-sys-grab","raea-sys-mix",@@ -15564,6 +15566,18 @@ dependencies = ["wgpu",]+[[package]]+name = "raea-runtime-wear"+version = "0.1.0"+dependencies = [+ "raea-io-assets",+ "raea-native",+ "raea-sys-bake",+ "raea-sys-glb",+ "raea-sys-weathering",+ "serde_json",+]+[[package]]name = "raea-runtime-world"version = "0.1.0"@@ -15730,6 +15744,13 @@ dependencies = ["serde_json",]+[[package]]+name = "raea-sys-exposure"+version = "0.1.0"+dependencies = [+ "parry3d",+]+[[package]]name = "raea-sys-filters"version = "0.1.0"@@ -15861,6 +15882,13 @@ dependencies = ["serde_json",]+[[package]]+name = "raea-sys-glb"+version = "0.1.0"+dependencies = [+ "serde_json",+]+[[package]]name = "raea-sys-grab"version = "0.1.0"@@ -16215,6 +16243,14 @@ dependencies = ["wgpu",]+[[package]]+name = "raea-sys-runoff"+version = "0.1.0"+dependencies = [+ "parry3d",+ "rayon",+]+[[package]]name = "raea-sys-sampler"version = "0.1.0"@@ -16343,6 +16379,13 @@ dependencies = ["serde_json",]+[[package]]+name = "raea-sys-touch"+version = "0.1.0"+dependencies = [+ "parry3d",+]+[[package]]name = "raea-sys-tweak"version = "0.1.0"@@ -16397,6 +16440,21 @@ dependencies = ["serde_json",]+[[package]]+name = "raea-sys-weathering"+version = "0.1.0"+dependencies = [+ "image",+ "parry3d",+ "raea-sys-exposure",+ "raea-sys-glb",+ "raea-sys-runoff",+ "raea-sys-touch",+ "rayon",+ "serde_json",+ "sha2 0.10.9",+]+[[package]]name = "raea-web"version = "0.1.0"diff --git a/Cargo.toml b/Cargo.tomlindex 25ad0230..1af05eb3 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -103,6 +103,11 @@ members = ["systems/tweak","systems/filters","systems/wear",+ "systems/weathering",+ "systems/runoff",+ "systems/touch",+ "systems/exposure",+ "systems/glb","systems/procmat","systems/page","systems/page-net",@@ -166,6 +171,7 @@ members = ["engine/shape-web","runtime/calls","runtime/shots",+ "runtime/wear","runtime/canvas","runtime/export","runtime/live",diff --git a/docs/manual/reference/cli/blender.md b/docs/manual/reference/cli/blender.mdindex a32f1730..60272cdb 100644--- a/docs/manual/reference/cli/blender.md+++ b/docs/manual/reference/cli/blender.md@@ -1,7 +1,7 @@---title: "raea blender"summary: "Run a Blender Python script headless, with raea's library of mesh scripts: convert, decimate, repair, split, bake, rig, cloth."-order: 106+order: 107sources: ["apps/tools/src/blender.rs", "apps/engines/src/blender_ts.rs"]---diff --git a/docs/manual/reference/cli/clothes.md b/docs/manual/reference/cli/clothes.mdindex 8182b6c9..4935ddd7 100644--- a/docs/manual/reference/cli/clothes.md+++ b/docs/manual/reference/cli/clothes.md@@ -1,7 +1,7 @@---title: "raea clothes"summary: "Clothes for SOMA's body from words: make sews a garment from a sewing pattern (GarmentCode, MIT), cut to SOMA's measurements and draped by raea's own cloth, as assets/clothes/NAME.json and its .glb; cover lays one on the skin by procedure; wear puts garments on a body."-order: 104+order: 105sources: ["engine/cli/src/cli.rs"]---diff --git a/docs/manual/reference/cli/godot.md b/docs/manual/reference/cli/godot.mdindex 5d499a47..91826342 100644--- a/docs/manual/reference/cli/godot.md+++ b/docs/manual/reference/cli/godot.md@@ -1,7 +1,7 @@---title: "raea godot"summary: "Run a TypeScript script against Godot's whole API in a headless Godot with GodotJS, record what it draws as frames, or open the editor on the project."-order: 107+order: 108sources: ["apps/engines/src/godot.rs", "apps/engines/src/godot_run.rs"]---diff --git a/docs/manual/reference/cli/index.md b/docs/manual/reference/cli/index.mdindex 0728e153..c4e151da 100644--- a/docs/manual/reference/cli/index.md+++ b/docs/manual/reference/cli/index.md@@ -14,7 +14,7 @@ they match the version they were made from; the prose around them is written by- **Help.** `raea help` (or `raea` alone) lists every verb's forms. `raea help --json` gives the same as data: eachverb's forms, its flags, how many values each flag takes, how many arguments it takes and where it runs.- **Strict arguments.** A verb refuses a flag or an argument its forms don't name, rather than ignoring it, so a- typo is caught. The four verbs with parsers of their own (`media`, `gen`, `physics`, `blender`) list their own forms.+ typo is caught. The five verbs with parsers of their own (`media`, `gen`, `physics`, `blender`, `godot`) list their own forms.- **Output.** A verb prints its result on stdout and exits 0. When it can't do what it was asked, it prints a linestarting with `REFUSED` that says why and what to do instead, and exits 1. A file refused again is told whatchanged since the last refusal.@@ -105,12 +105,13 @@ Music read, foley and instruments made on this machine.## Generate and 3D tools-Generated media, physics bakes, clothes and motion for SOMA's body, Blender and Godot.+Generated media, physics and weathering bakes, clothes and motion for SOMA's body, Blender and Godot.| Verb | What it does || --- | --- || [`raea gen`](gen.md) | Generate images, video, music, sound, speech, 3D models and text through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI. || [`raea physics`](physics.md) | Make the bakes <Physics> and <Goo> play: rigid bodies, soft goo, and parts cut out of a .glb. |+| [`raea wear`](wear.md) | Bake what weathers a model: where rain reaches and runs, what the sun sees, edges, hollows and touch, as maps raea/wear reads. || [`raea clothes`](clothes.md) | Clothes for SOMA's body from words: make sews a garment from a sewing pattern (GarmentCode, MIT), cut to SOMA's measurements and draped by raea's own cloth, as assets/clothes/NAME.json and its .glb; cover lays one on the skin by procedure; wear puts garments on a body. || [`raea motion`](motion.md) | Body motion made on this machine by Kimodo (NVIDIA), on MLX on a Mac and on PyTorch on Linux and Windows: a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads. || [`raea blender`](blender.md) | Run a Blender Python script headless, with raea's library of mesh scripts: convert, decimate, repair, split, bake, rig, cloth. |diff --git a/docs/manual/reference/cli/motion.md b/docs/manual/reference/cli/motion.mdindex ba1b2925..1d292478 100644--- a/docs/manual/reference/cli/motion.md+++ b/docs/manual/reference/cli/motion.md@@ -1,7 +1,7 @@---title: "raea motion"summary: "Body motion made on this machine by Kimodo (NVIDIA), on MLX on a Mac and on PyTorch on Linux and Windows: a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads."-order: 105+order: 106sources: ["engine/cli/src/cli.rs"]---diff --git a/docs/manual/reference/cli/wear.md b/docs/manual/reference/cli/wear.mdnew file mode 100644index 00000000..12ff30c5--- /dev/null+++ b/docs/manual/reference/cli/wear.md@@ -0,0 +1,49 @@+---+title: "raea wear bake"+summary: "Bake what weathers a model: where rain reaches and runs, what the sun sees, edges, hollows and touch, as maps raea/wear reads."+order: 104+sources: ["runtime/wear/src/lib.rs", "systems/weathering/src"]+---++Weathering in raea has causes. A bake traces them through a `.glb`'s own geometry once: rain and the sky, the sun's+path over the year, edges and hollows, the height over the ground, where hands and feet touch, and where run-off+carries soot, rust or copper and leaves it. It returns the model with a second UV set and four maps over it, which+raea/wear's recipes read. A composition gets the same bake from the native call `wear.bake`; `raea wear bake` makes+it from a shell, in the current folder's asset store. The same request gives the same files, and a second run reads+the first's.++```sh+raea wear bake corner.json -o corner.bake.json+```++A request names the model and, optionally, the world it stands in and the class of each of its materials:++```json+{+ "src": "/media/corner.glb",+ "env": { "density": 8, "walk": ["ground"], "sun": { "lat": 52.5 } },+ "classes": { "facade": "plaster", "plinth": "sandstone", "ground": "ground" }+}+```++<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->++## Usage++```sh+raea wear bake REQUEST.json [-o OUT.json] (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)+```++Headless: it needs nothing running and opens no window. Takes up to 2 arguments besides its flags.++## Flags++| Flag | Takes | What it does |+| --- | --- | --- |+| `-o` | `OUT.json` | Also write the result to this file, in place of printing it. |++<!-- generated:end -->++## See also++- [raea physics](physics.md) makes the other bakes a composition plays.diff --git a/docs/wear.feature b/docs/wear.featurenew file mode 100644index 00000000..3a8a5ae2--- /dev/null+++ b/docs/wear.feature@@ -0,0 +1,293 @@+@spec+Feature: raea/wear, weathering that has a cause+ Shane, 2026-11-17, pointing at a geometry-nodes damage kit (grunge masks by AO or rules, edge wear, streaks,+ rule-based scatter, broken windows, cracked roads) and at a leaf made from stacks of procedural masks: a raea-native+ version, "realistic procedural and highly intelligent seeding ... for what makes sense on wear, wear by material,+ crumbling infrastructure, doors, walls, plates", and the same for how textures are built and made cheap.++ raea's wear so far is shader-only (systems/wear: noise, screen-space curvature, grime on faces turned down;+ systems/procmat: a pattern with dust, dirt and edges). Nothing in it knows where water runs, what is sheltered, where+ hands touch or what a surface is made of, so the marks are scattered evenly rather than caused. The fix is the+ method of the literature: the agents of wear are traced through the geometry from their sources, and they leave+ their marks where the physics puts them. Dorsey, Pedersen and Hanrahan, "Flow and Changes in Appearance" (1996):+ drops of water flowing over surfaces, absorbing, dissolving and depositing. Chen et al., "Visual Simulation of+ Weathering by gamma-ton Tracing" (2005): aging particles from rain, sun, sky and leaks, picking up and depositing+ ("stain bleeding"). Each material then answers each cause its own way: black gypsum crust forms on carbonate stone+ where rain does not wash it, and rain-washed faces recede and stay light (Bonazza, NABU MedShip 2019).++ Three parts, each a standard of its own:+ 1. A bake (raea-sys-weathering): a glTF and an environment in, its cause maps out (where rain reaches and runs,+ what the sun and sky see, edges and hollows, height over the ground, where hands, feet and wheels touch, what+ the water carries and leaves), on a second UV set it adds, with the spots where the rules say a thing belongs.+ A pure function of its request, kept by content as raea-sys-bake's bakes are.+ 2. Recipes (raea/wear): one WESL surface hook per material class (docs/shaders.feature SH1, SH2, SH4) reading the+ same maps, so plaster, brick, sandstone, painted wood, iron, zinc, copper, slate, glass, enamel and brass each+ answer rain, shelter, run-off, damp, sun, touch and age as that material does.+ 3. Damage from the same maps: plaster blown off to the brick behind it, paint to the wood, enamel to the iron;+ cracks from the corners of openings; broken panes; debris where the damage is.+ Decided with Shane the same day: the recipes ship as an SDK part (raea/wear, not only an example to copy);+ examples/materials/wear/ is its demo, which closes docs/examples.feature EX9 (raea-sys-wear deleted); detail+ textures baked from mask stacks, mips on texture arrays and BC compression wait until the look is proven (WR8).+ Shane, later that day: every season and weather, not winter only (spring, summer, autumn, winter, snow, blizzard,+ rain, thunder; docs/realism.feature D17, LT16). So a bake holds only causes, which hold all year, and what a season+ or a day's weather does (lying snow, wet, ice, rivulets, puddles, driven snow, fallen leaves, algae) is drawn from+ uniforms over those causes, never baked in (WR9).++ Rule: 1. The causes++ @done+ Scenario: WR1. Cause maps baked from the geometry+ Given a .glb (static meshes; skins, morph targets, sparse accessors and a material already reading TEXCOORD_1+ are refused) and an environment: up, north, the rain's direction and cone, the driving snow's direction and+ cone, the latitude, the walking surfaces as material classes or a height, texels a metre (one number, or by+ class)+ When `wear.bake` runs+ Then it returns the .glb with TEXCOORD_1 and four RGBA8 maps over that atlas, kept by content in the store+ | map | r | g | b | a |+ | causes0 | sky: rain's reach, n.d over the rain's cone | sun: share of the year's sun path in sight | cavity: occlusion within 0.5 m | edge: nearness to a convex arris |+ | causes1 | flow: run-off passing (WR2) | deposit: what it left (WR2) | deposit kind (WR2) | touch (WR3) |+ | causes2 | ground: height over the walk below, 0-4 m | element: the chart's own number | open: share of the whole sky seen | spare |+ | causes3 | winter sun: share of the December path in sight (where snow lingers) | drift: driven snow's reach, n.d over its cone | litter: where blown leaves and snow settle (concave, at the walk, in the lee) | spare |+ And the year's sun is what fades and dries (it acts all year); the winter sun only decides where snow and ice+ outlast a thaw, so it has its own channel rather than a season in the request+ And the atlas is planar charts, packed on shelves with a 1-texel gutter, built in five steps+ | step | what | why |+ | flood | a primitive's triangles joined over shared (welded) edges while within 15 degrees of the first's plane | a curved bay or a draped street stays one chart |+ | merge | coplanar charts (1/64 in the normal, 2 cm in offset) whose rectangles touch, joined | a wall cut in strips by its openings shares no edges |+ | split | a chart filling under half its rectangle cut on a 64-texel grid | a street network round its blocks, gutters at one eaves height |+ | 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 rays are parry3d's TriMesh BVH (in the tree through rapier3d); samples are a rotated R2 sequence per texel+ And each triangle has a material class from the request's table, by glTF material name or by COLOR_0's alpha+ 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 | 217 | the request, its content key, the store, the bake's steps |+ | 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/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+ wall's; a south wall sees the winter sun and a north one doesn't; the ground channel reads the height to 0.1 m,+ through a slab to the ground under it; a slab's arris wears and a wall's foot doesn't; a 4 x 4 m court 12 m+ deep sees under 0.35 of the sky; a floor shut in a house gets no texels; charts never overlap and keep their+ density within 5%, by class where asked; the same request gives the same bytes, TEXCOORD_1 on every primitive+ And measured on a 250 m city tile (214,869 triangles, 6 materials) on an M5 Pro Mac (the last two rows with roofs+ at 1-2 texels a metre and the ground at 2, the rest 4 throughout)+ | step | atlas | texels covered | charts | rays |+ | flood only, 2-texel gutter | 4096 x 3928 | 6.70 M | 80,726 | 7.8 s |+ | merge and absorb, 1-texel gutter | 4096 x 2868 | 5.67 M | 17,658 | 6.8 s |+ | hide and split | 4096 x 2252 | 4.90 M | 18,786 | 4.5 s |+ | level charts turned | 4096 x 1828 | 4.81 M | 16,024 | 5.0 s |+ | density by class (roofs 1-2, ground 2) | 4096 x 1400 | 3.81 M | 15,743 | 4.1 s |+ | hidden by four points, open channel | 4096 x 1364 | 4.06 M | 16,213 | 4.9 s |+ And what the maps then cost uncompressed is 22 MB each a tile (BC compression and dropping causes2 where a+ model's own uv already says the height are WR8's)++ @done+ Scenario: WR2. Water: run-off, drips and what it carries+ Given causes0's sky term+ Then drops land where rain reaches, in proportion to it, and run down their surface (gravity projected onto it);+ on a ledge (a face within 30 degrees of level) they run to its lower edge and gather toward its ends, and leave+ at an overhang's edge, fall straight down (a ray) and run on over the surface they land on+ And a drop takes up what the surface it crosses gives (copper green, iron rust, zinc white, lime, and soot from+ a sheltered ledge) and leaves it downstream, so a stain bleeds from its cause: flow counts the water passing,+ deposit what it left, kind the most of it+ And as built (11-17), in its own crate, raea-sys-runoff, a facility the bake builds on: plain data in (positions,+ triangles, normals, a role each, each corner's texel in the atlas, the BVH), sums out, so other bakes can use it+ | crate | file | lines | job |+ | raea-sys-runoff | systems/runoff/src/lib.rs | 141 | the input, the sums (fixed point, 64-bit), the map's bytes |+ | raea-sys-runoff | systems/runoff/src/walk.rs | 253 | one drop's walk: faces, edges, corners, drips, what it carries |+ | raea-sys-runoff | systems/runoff/src/tests.rs | 148 | a wall with a sill and an iron bracket, checked by number |+ | raea-sys-weathering | systems/weathering/src/flow.rs | 54 | a drop per texel the rain reaches; roles by class; causes1 |+ And the walk's rules:+ | where the drop is | what it does |+ | on a face | runs down it (gravity projected), each drop up to 4 degrees off the fall line (ASSUMED), so a tear widens |+ | on a level face | keeps one heading, drawn per drop, so a ledge sheds off each edge by its share |+ | a face carries on behind what stands on it | the run stops at whatever it meets head on just off the face (a sill on the wall it runs down) |+ | at an edge into a face that climbs away | runs along the corner (a ledge's back, against the wall) |+ | at an edge onto an underside, or a free edge | looks along the edge 0.25 m for a wall met head on and clings into that corner (a sill's end), else drips: a ray straight down, 70% kept |+ | on a walking surface or a roof (slate, felt) | ends (the roof drains to its gutter) |+ And iron gives rust, zinc white, copper green, and every other face that looks up gives the dust that lies on it;+ what a drop carries it leaves over the next metres (half in 1.2 m), and it soaks away (1/e in 8 m)+ And causes1 r = water passing a texel per metre across (log, 0.02-20), g = what was left per square metre (log,+ 1e-4 to 0.1), b = the kind left most (0, 60, 120, 180, 240: none, grime, rust, copper, zinc); a wall's own+ driven rain counts in r, so the streaks a recipe draws come from g+ And a bake keys on raea-sys-runoff's VERSION as well as its own, so a change to the walk is never served stale+ And proof (`cargo test -p raea-sys-runoff`, 4 tests): under a 1.6 m sill the wall below its ends gets over 5x the+ water below its middle and over 3x the wall's beside it; an iron bracket leaves rust on the wall below it and+ nothing beside it; the same rain gives the same sums; a face that drains ends a drop there+ And measured: on the city tile it adds about 0.4 s to the bake (4.9 to 5.3 s); a 32 texel-a-metre test bed+ (tools/wear/testbed.ts in the game project: a front, a firewall, a rubble heap, a kerb) shows the tears under+ sill ends and the railing's rust+ And still open: a deposit's kind is filtered with its neighbours in the shader (a kind map wants nearest+ sampling, which the shared sampler doesn't give); a stain on the ground (drops end on it)++ @done+ Scenario: WR3. Touch, and where things belong+ Given the classes and the ground channel+ Then touch is written by rules, never by hand: a door leaf (wood, standing on the walking surface, 0.7-1.6 m+ wide, 1.9 m or more tall) gets a handle band at 0.95-1.1 m on its lock side and a kick band at 0-0.3 m; a+ tread is worn at its middle; a rail's top where hands slide; a gateway's jambs at hub height, 0.4-0.9 m; a+ passage's walls at the shoulder, 1.2-1.6 m, where two walls stand under 3 m apart+ And spots.json lists where the rules say a thing belongs, each with who put it there: bills on sheltered plinth+ faces at 0.5-2.5 m (a bill poster), a plate on a corner at 2.5-3 m (the city), a nameplate beside a door (the+ tenant), debris under damaged plaster (the weather)+ And as built (11-17), in its own crate, raea-sys-touch, a facility the bake builds on as it does on run-off:+ plain data in (triangles, a material each, which are walked on, the BVH, and each texel's point with what the+ other maps say there), touch and spots out+ | crate | file | lines | job |+ | raea-sys-touch | systems/touch/src/lib.rs | 137 | the input, parts (one material, welded at 1 mm), the output |+ | raea-sys-touch | systems/touch/src/bands.rs | 296 | doors, treads, rails, passages and gateways, and the bands |+ | raea-sys-touch | systems/touch/src/spots.rs | 167 | the spot rules |+ | raea-sys-touch | systems/touch/src/tests.rs | 248 | synthetic fronts checked by number |+ | raea-sys-weathering | systems/weathering/src/touch.rs | 47 | the scene and texels handed over; causes1 a and spots.json |+ And the rules as built (every number ASSUMED until a source is read, except where a note names one)+ | what | found by | marks |+ | a door leaf | a wood part 0.7-1.6 m across, 1.9 m or more tall, at most 0.12 m thick, with a floor in front or behind within 0.2 m of its foot, looked for from 0.3 m over it (a leaf set into a step stands on the step) | handle band 0.95-1.1 m over that floor within 0.3 m of the lock edge; kick band 0-0.3 m, full at the lock edge and 0.35 at the hinge |+ | the lock edge | two leaves in one plane whose edges meet within 8 cm: the meeting edge; else one edge, by a seed from the leaf's place | |+ | a tread | an up face of masonry or wood, not walked on, 0.2-0.45 m deep and 0.6-4 m wide, in a flight (another tread 0.1-0.23 m up or down beside it) or a first step at most 0.26 m up | dished: 1 - x^2 across its width |+ | a rail | a metal or wood part, long and thin, its top 0.75-1.2 m over the walk | its top |+ | a passage | a wall facing another under 3 m off, both at least 0.6 m deep, the floor between them walked | 0.8 at the shoulder, 1.2-1.6 m |+ | a gateway | walls 2.2-4.5 m apart, the floor between walked, a ceiling within 6 m | the hub band, 0.4-0.9 m |+ And the spots as built+ | what | by | where |+ | bill | bill poster | a plain wall (no opening within 3 m across, none from 0.5 m below to 2.5 m above), out of the rain, 0.95-2.05 m up, open ground in front, 3 m apart; Berlin's columns (Litfaß, from 1855) were brought in to keep bills off house fronts |+ | street plate | city | each face of a corner whose arris runs from the walk past 3.5 m, 2.5-3 m up, both faces open for 4 m |+ | nameplate | tenant | beside a single leaf's lock edge, 1.5 m over its floor, on whichever side sees more sky (a hall sees none; a balcony over a street door hides only part) |+ | debris | weather | on the ground in front of plaster soaked at its foot (run-off and rain), 1.5 m apart |+ And a bake keys on raea-sys-touch's VERSION as well, and writes spots.json beside the maps (its path in meta.json)+ And proof (`cargo test -p raea-sys-touch`, 9 tests; `-p raea-sys-weathering`, 10): on a test front the handle+ band lands on one side of the leaf, never on the wall, and the nameplate beside that side; a pair of leaves is+ held where they meet; a leaf set into a step is held from the step's top; treads are worn at the middle and a+ window sill isn't one; two walls 2.5 m apart wear at the shoulder, and at the hub only under a ceiling; a+ window's reveals are no passage; bills go on a plain wall and never beside a door; a corner gets one plate a+ face; the same input gives the same spots; through the bake, a door's band and its nameplate+ And measured: on the 32 texel-a-metre test bed (i-acp-mwlah7s6-107) the door is held on its lock side, kicked in+ patches, its nameplate beside it, a plate on each corner and one bill, on the firewall; on a 4 texel-a-metre+ city tile (5.2 M texels) the rules take 0.45 s and find 1,398 leaves, 246 treads, 1,140 nameplates, 303 street+ plates and 63 bills+ And still open: plates land on court corners and steps in a frontage too (which faces are on a street is the+ map's to say, a hand-off); at 4 texels a metre a 15 cm handle band is under one texel, so the city's doors+ want their own density class; no rails were found on the tile (its balconies' railings aren't modelled there)++ @needs:WR1 @done+ Scenario: WR4. `wear.bake` and `raea wear bake`+ Then a composition calls `wear.bake` (a native call, as physics.bake is) and gets the glTF and maps by file, and+ `raea wear bake REQUEST.json [-o OUT.json]` runs the same bake from a shell+ And the plan+ | crate | file | lines | job |+ | raea-runtime-wear | runtime/wear/src/lib.rs | 60 | the native call in the composition's folder (registered from thread.rs as raea-runtime-shots is; raea-runtime-react is at 1,965 lines) |+ | docs | docs/manual/reference/cli/wear.md | 40 | the verb's reference |+ And as built (11-17)+ | crate | file | lines | job |+ | raea-runtime-wear | runtime/wear/src/lib.rs | 67 | `wear.bake` and `raea wear bake`: the src found by the runtime's media rule, the bake kept in the composition's asset store, timed as made on first use |+ | raea-runtime-wear | runtime/wear/src/tests.rs | 97 | a wall and floor baked once into a project's store, a missing src, the verb's -o |+ | raea-runtime-react | src/thread.rs | +5 | registers it with the composition's folder and media rule (the crate needs no engine) |+ | raea-cli | src/cli.rs, src/tests.rs | +3 | the verb, its help line, its usage in the tests' list |+ | docs | docs/manual/reference/cli/wear.md, index.md; tools/manual-ref/cli.ts | 49 | the page, its row, its section |+ And proof: `cargo test -p raea-runtime-wear` passes (3 tests), and the verb's help and manual page pass L1's+ manual reference check++ Rule: 2. The materials++ @needs:WR4+ Scenario: WR5. raea/wear: a recipe per material+ Given `wearShader({ classes, weather, age })` from raea/wear+ Then it gives `{ wesl, uniforms, textures }` for a <Model>'s <Recover>, a <MeshStandardMaterial shader> or a+ <SurfaceShader>: the three maps as its textures, a `surface` hook that reads them and the material's class,+ and one function per class answering each cause+ | class | rain-washed | sheltered | under a ledge | ground band | edge, touch |+ | plaster | clean, paint chalky | soot grey, darkest under cornices | dark tears from sill ends | splash to 0.4 m, damp tide 0.6-1.2 m | chipped arrises low down, grease band |+ | brick | mortar washed out | soot black | efflorescence | tide line, green on north faces | spalled faces |+ | sandstone | washed light | black crust | black and white streaks | | rounded arrises |+ | wood | sun-faded on south and west, alligatored | | peeling at bottom rails | rot at the foot | worn to the wood where held and kicked |+ | iron | | | rust on the stone below | rust at the foot | paint flaking at joints, bright where held |+ | zinc, copper | patina | | white or green streaks | | |+ | glass | | a grime film at the bottom and corners | | | |+ | enamel | | | rust bled from its screws | | chipped to black iron at holes and edges |+ | brass | dull brown | | | | bright where touched |+ And the season and the weather (WR9), soot, years since the last repair and an upkeep that varies by element are+ uniforms; what years of weather left (soot, crust, fading, peeling, rust, touch) is the same in every season+ And a debug mode shows one cause in false colour+ And the plan+ | crate | file | lines | job |+ | raea/wear | sdk/wear/src/index.ts | 200 | wearBake, wearShader, the class table |+ | raea/wear | sdk/wear/src/causes.ts | 120 | the WESL that reads the maps |+ | raea/wear | sdk/wear/src/recipes.ts | 420 | one WESL function per class |+ | raea/wear | sdk/wear/src/debug.ts | 60 | a cause in false colour |+ | raea/wear | sdk/wear/test/wear.test.ts | 120 | the table, the shader's text, the uniforms |++ @needs:WR5,WR3+ Scenario: WR6. Crumbling+ Then where damage is high (ground band, edges, sheltered damp, neglect), plaster is gone to the brick 2 cm behind+ it under a shadowed lip, paint to primer and wood, enamel to iron; cracks run from the corners of openings;+ panes are broken or boarded by neglect; slates are missing; and spots.json puts debris under the losses+ And the cracked-road fracture of the kit waits for a piece that needs it++ @needs:WR5+ Scenario: WR9. Every season and weather, from uniforms over the causes+ Given the look's date and weather, the values the realism lane's sets carry: `day` (the day of the year, 1-366)+ and `hour`, from which the season's phase (day / 365.25) and the sun follow; snow, wet and ice as weather of+ their own (a December day can be dry and a March day snowed); `leaf` (the trees' cover, 0-1) where the trees+ need it; the wind; and the time for what runs+ Then each condition is drawn from the causes, and nothing of it is baked+ | condition | what it does on the surfaces | causes it reads |+ | spring | damp lingers on north faces and plinths; green algae where flow and shade meet; dust washed off | sun, flow, ground, sky |+ | summer | dry: dust lies on ledges and treads, run-off stains read pale, wood at its most faded | sun, deposit, sky |+ | autumn | fallen leaves on the walk where litter is high, wet and dark after rain; leaves in gutters | litter, ground, flow |+ | winter | frost on faces the winter sun misses; old snow greyed by soot in the lee | winter sun, litter, open |+ | snow | snow lying on faces open above (ledges, sills, cornices, roofs, treads), deeper in the lee, gone where the winter sun reaches and where feet pass | open, winter sun, litter, touch |+ | blizzard | snow as above, and driven snow plastered on faces the wind reaches, drifts against walls | drift, litter, open |+ | rain | darkened where the rain reaches; rivulets running down the flow map's paths; puddles on the walk where it is hollow | sky, flow, cavity, ground |+ | thunder | heavy rain (wet full, rivulets full, puddles splashed); the flash and the sky are the light's (docs/realism.feature) | as rain |+ And a condition can change during a shot (rain starting, snow settling): the uniforms take a value per frame and+ the look follows, with wetting and drying eased over the minutes they take (the rates ASSUMED until measured)+ And the wind's direction for driven snow is a bake input (causes3 g), ASSUMED east to north-east for Berlin's+ winter storms until the DWD's records are read; the rain's stays west+ And the bake's half as built (11-17), in its own crate, raea-sys-exposure, which also took the sun's path out+ of the bake (raea-sys-weathering 4 keys on it; the request's sun.season is gone)+ | crate | file | lines | job |+ | raea-sys-exposure | systems/exposure/src/lib.rs | 199 | the sun by date, driven weather, litter |+ | raea-sys-exposure | systems/exposure/src/tests.rs | 91 | synthetic fronts checked by number |+ | raea-sys-weathering | systems/weathering/src/rays.rs | 260 | causes0 g the year's sun; causes3 per texel |+ And its rules: the year's sun is the middle day of each month, every 2 hours the sun stands 3 degrees up;+ December's is days 335, 355 and 15, every hour; drift is the sky term's measure up a storm's cone (from the+ east-north-east, 60 degrees off the vertical, 25 wide, all ASSUMED); litter on faces looking up is 0.7 x the+ share of eight low rays (10 degrees up) meeting something within 1.5 m, plus 0.3 x the share of five rays+ toward the wind meeting something within 3 m (weights and reaches ASSUMED)+ And proof (`cargo test -p raea-sys-exposure`, 4 tests): the noon sun stands 14.1 degrees at the December+ solstice and 60.9 in June at 52.5 N; a south wall sees December's sun and a north one none, though it sees+ some of the year's; a wall facing the storm takes as much drift as a level roof and its lee none; litter+ gathers in a kerb's gutter and in a wall's lee, never on open road or a face that doesn't look up; through+ the bake (`-p raea-sys-weathering`), the same for December and the year on causes3 r and causes0 g+ And measured: the 32 texel-a-metre test bed bakes in 2.0 s of rays (1.5 s before causes3); the 4 texel-a-metre+ city tile in 13.8 s under another lane's load; a prototype of the eight conditions over the causes, in the+ game project's own wear recipe (components/wear/look.ts: snow lying on what looks up and is open, banked where+ litter settles, thinned by December's sun, trodden off by touch, plastered by a storm by drift; rain wetting+ what the sky term reaches, streaming down the run-off paths, puddling in hollows; leaves by litter; dust),+ posted as i-acp-mwlb9fb4-110+ And still open: the mapping from the look's `day` and weather to these values is WR5's (the prototype takes+ storm, leaves, dust and melt as values of their own); frost and algae; the flash of thunder is the light's++ Rule: 3. Shown, then cheap++ @needs:WR5+ Scenario: WR7. The demo, and EX9+ Then examples/materials/wear/ is a corner house made in code (plinth, rusticated ground floor, plastered storeys,+ sills, string course, cornice on consoles, door, iron balcony, zinc gutter and downpipe, an enamel street+ plate, a sandstone surround, steps, a cellar hatch), baked and shaded, with stills of every cause in false+ colour and the house under each of WR9's eight conditions, by day and at dusk+ And `wear` on MeshStandardMaterial and <WearExtension> are raea/wear's, and systems/wear, its spawn branch and+ its row columns are deleted in the same landing (docs/examples.feature EX9)++ @needs:WR7+ Scenario: WR8. Detail textures from mask stacks, and what they cost+ Then each class's detail (brick bond, plaster grain, stone tooling, wood grain) is a stack of procedural masks+ rendered by raea once into tiling layers, instead of noise evaluated per pixel per frame+ And texture arrays get mips (SH9 arrays have none, so a tiling layer shimmers far off) and maps can be BC+ compressed into KTX2, with the memory and frame time each saves measureddiff --git a/engine/cli/Cargo.toml b/engine/cli/Cargo.tomlindex 7cee4147..3e3aa6a7 100644--- a/engine/cli/Cargo.toml+++ b/engine/cli/Cargo.toml@@ -29,6 +29,8 @@ raea-core-brief = { path = "../../core/brief" }raea-app-workspace = { path = "../../apps/workspace" }# raea-runtime-react's defaultsraea-runtime-react = { path = "../../runtime/react", default-features = false, features = ["h264", "av1", "scripts", "modules", "network", "ml"] }+# `raea wear bake`: raea/wear's bake from a shell (docs/wear.feature WR4)+raea-runtime-wear = { path = "../../runtime/wear" }# the sound of its renders and plays: <Seedling> samples and speech (raea-runtime-sound's features)raea-runtime-sound = { path = "../../runtime/sound", features = ["seedling", "ml"] }raea-runtime-export = { path = "../../runtime/export" }diff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rsindex def57121..8d14199d 100644--- a/engine/cli/src/cli.rs+++ b/engine/cli/src/cli.rs@@ -144,9 +144,9 @@ pub fn run(args: &[String]) -> R<String> {let usage = format!("{usage}\n raea bug TITLE... --text TEXT [--command CMD] [--error TEXT] [--agent NAME] [--dry-run] (a bug in raea itself, not in your own composition, sent to raea's server with raea's version and the OS, no account needed: words only, paths, emails and keys taken out before it goes; five a day from a machine, the same bug again counted on the first report; --dry-run prints what would go and sends nothing)");// a workspace's files and specs (docs/projects.feature), listed under render's usage like librarylet usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|plan|controller] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, plan.ts, controllers/ID.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects and controllers under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; split and join keep its history)\n raea controller ls [--json] | raea controller get PATH [--json] | raea controller set PATH VALUE [--project] [--by NAME] | raea controller write FILE.ts [--by NAME] | raea controller rm ID [--by NAME] (the workspace's controllers, controllers/ID.ts; PATH is controller.group.field; every change a commit)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {} ({})\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, tools::motion::SETUP_USAGE, tools::motion::SETUP_ABOUT, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);- let (export_game, capcut, scene, physics, splat) = (raea_app_game::USAGE, raea_app_capcut::USAGE, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE);+ let (export_game, capcut, scene, physics, splat, wear) = (raea_app_game::USAGE, raea_app_capcut::USAGE, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE, raea_runtime_wear::USAGE);let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE, raea_app_fingerprint::USAGE, raea_sys_index::cli::USAGE);- return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea component list | raea component add NAME ... [--shared] [--force] | raea part list | raea part add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; raea part is its old name)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {capcut}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)"));+ return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea component list | raea component add NAME ... [--shared] [--force] | raea part list | raea part add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; raea part is its old name)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {capcut}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)"));}// `--version`: the release's version, which a skill's front matter names (docs/skills.feature SK6)if args.len() == 1 && matches!(args[0].as_str(), "--version" | "-V") {@@ -262,6 +262,8 @@ pub fn run(args: &[String]) -> R<String> {Some("splat") => return tools::splat::splat(args),// `physics bake|goo|part ...`: the bakes <Physics> and <Goo> make (systems/bake, registered in motion/physics.rs)Some("physics") => return motion::physics::cli(args),+ // `wear bake REQUEST.json [-o OUT.json]`: raea/wear's cause maps of a .glb (raea-runtime-wear, registered in thread.rs)+ Some("wear") => return raea_runtime_wear::cli(args, motion::media_path),// `scene lint|explain EDIT.tsx`: what each 3D part rests on; floating, sunk and clipping parts (raea-sys-contact, through motion/contact.rs)Some("scene") => return export::scene_cli(args),// `song FILE [-o OUT.song.json] [--plot OUT.png]`: the song's energy map for pacing (apps/tools/src/song.rs)diff --git a/engine/cli/src/tests.rs b/engine/cli/src/tests.rsindex e0643e35..48cf1de5 100644--- a/engine/cli/src/tests.rs+++ b/engine/cli/src/tests.rs@@ -32,7 +32,7 @@ fn help_lists_every_verb() {let listed = |v: &str| [format!("raea {v} "), format!("raea {v}\n"), format!("| {v} ")].iter().any(|l| help.contains(l.as_str()));let missing: Vec<_> = verbs.iter().filter(|v| !listed(v) && !unlisted.contains(&v.as_str())).collect();assert!(missing.is_empty(), "not in raea help: {missing:?}");- for usage in [raea_app_check::USAGE, raea_app_direction::check::USAGE, raea_app_direction::USAGE, raea_app_notes::USAGE, raea_app_game::USAGE, raea_runtime_export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, tools::blender::USAGE] {+ for usage in [raea_app_check::USAGE, raea_app_direction::check::USAGE, raea_app_direction::USAGE, raea_app_notes::USAGE, raea_app_game::USAGE, raea_runtime_export::SCENE_USAGE, motion::physics::USAGE, raea_runtime_wear::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, tools::blender::USAGE] {assert!(help.contains(usage), "{usage}");}}diff --git a/runtime/calls/Cargo.toml b/runtime/calls/Cargo.tomlindex 6db0ee4a..7e9b4b76 100644--- a/runtime/calls/Cargo.toml+++ b/runtime/calls/Cargo.toml@@ -12,6 +12,8 @@ ml = ["dep:raea-sys-ml", "dep:raea-sys-speech"][dependencies]raea-runtime-plugins = { path = "../plugins" }+# raea/wear's bake as the native call wear.bake, registered with these (docs/wear.feature WR4)+raea-runtime-wear = { path = "../wear" }raea-native = { path = "../../engine/native", default-features = false }raea-core-shape = { path = "../../core/shape" }raea-core-place = { path = "../../core/place" }diff --git a/runtime/calls/src/lib.rs b/runtime/calls/src/lib.rsindex 8f510505..1e78e18b 100644--- a/runtime/calls/src/lib.rs+++ b/runtime/calls/src/lib.rs@@ -201,6 +201,7 @@ pub fn call(name: &str, v: &Value) -> R<Value> {pub fn register() {static ONCE: std::sync::Once = std::sync::Once::new();ONCE.call_once(|| {+ raea_runtime_wear::register(raea_runtime_wear::Place { dir: composition_dir, media: raea_core_scene::media_path });const BOUNDS: &str = "{ min: [number, number, number]; max: [number, number, number] }";const SOLID: &str = "{ id: number; expr: string }";const SECTION: &str = "{ polygons: [number, number][][]; area: number; contours: number; bounds: { min: [number, number]; max: [number, number] } }";diff --git a/runtime/wear/Cargo.toml b/runtime/wear/Cargo.tomlnew file mode 100644index 00000000..8148f7ba--- /dev/null+++ b/runtime/wear/Cargo.toml@@ -0,0 +1,22 @@+[package]+name = "raea-runtime-wear"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "raea/wear's bake as a native call (wear.bake) and a verb (raea wear bake): a .glb's cause maps made once in the composition's asset store"++[dependencies]+# the native-call registry+raea-native = { path = "../../engine/native", default-features = false }+# the composition's asset store, where a bake is kept+raea-io-assets = { path = "../../io/assets" }+# a bake's time counted as made on first use, not as settling+raea-sys-bake = { path = "../../systems/bake" }+# the bake itself (docs/wear.feature WR1-WR3, WR9)+raea-sys-weathering = { path = "../../systems/weathering" }+serde_json = "1"++[dev-dependencies]+# a small wall and floor written as a .glb for the tests+raea-sys-glb = { path = "../../systems/glb" }diff --git a/runtime/wear/src/lib.rs b/runtime/wear/src/lib.rsnew file mode 100644index 00000000..e72b8bde--- /dev/null+++ b/runtime/wear/src/lib.rs@@ -0,0 +1,67 @@+//! raea/wear's bake as a native call and a verb (docs/wear.feature WR4): `wear.bake` from a composition and+//! `raea wear bake REQUEST.json [-o OUT.json]` from a shell both run raea-sys-weathering's bake of a .glb found from+//! the composition's folder, and keep it in that folder's asset store under the request's content key: made once,+//! and the same request gives the same files. The runtime hands in where the composition is and how a media path+//! (staticFile's /media/...) resolves, so this crate needs no engine.++use std::path::{Path, PathBuf};++use serde_json::Value;++type R<T> = Result<T, String>;++/// Where the composition is, and how its media paths resolve (the runtime's own).+#[derive(Clone, Copy)]+pub struct Place {+ pub dir: fn() -> Option<PathBuf>,+ pub media: fn(&Path, &str) -> PathBuf,+}++pub const TAKES: &str = "{ src: string; env?: { up?: [number, number, number]; north?: [number, number, number]; rain?: { dir?: [number, number, number]; spread?: number }; sun?: { lat?: number }; snow?: { dir?: [number, number, number]; spread?: number }; walk?: string[] | { y: number }; density?: number | Record<string, number>; max_side?: number; rays?: { sky?: number; cavity?: number } }; classes?: Record<string, string | { alpha: Record<string, string>; default?: string }> }";+pub const GIVES: &str = "{ key: string; file: string; maps: { causes0: string; causes1: string; causes2: string; causes3: string }; spots: string; size: [number, number]; density: number; charts: number; tris: number; ms: Record<string, number> }";+const ABOUT: &str = "a .glb's weathering causes baked once and kept (raea/wear): the model with a second UV set, and four maps over it (sky, sun, cavity, edge; run-off, deposit, touch; height over the ground, element, open sky; December's sun, driven snow, litter)";++pub const USAGE: &str = "raea wear bake REQUEST.json [-o OUT.json]";++pub fn register(place: Place) {+ // the registry takes a plain function, so the place is kept beside it (the first runtime's)+ let _ = PLACE.set(place);+ raea_native::register("wear.bake", TAKES, GIVES, ABOUT, |v| {+ let p = *PLACE.get().ok_or("wear.bake: the runtime didn't say where the composition is")?;+ bake_in(&(p.dir)().unwrap_or_else(|| PathBuf::from(".")), p.media, v)+ });+}++static PLACE: std::sync::OnceLock<Place> = std::sync::OnceLock::new();++/// The bake of `v.src` (resolved from `dir`) under `v`'s env and classes, kept in `dir`'s asset store.+pub fn bake_in(dir: &Path, media: fn(&Path, &str) -> PathBuf, v: &Value) -> R<Value> {+ let src = v.get("src").and_then(Value::as_str).filter(|s| !s.is_empty()).ok_or("wear.bake: src is the .glb to bake (staticFile(\"model.glb\") or a path)")?;+ let file = media(dir, src);+ if !file.is_file() {+ return Err(format!("wear.bake: no file at {} (src {src:?}, from {})", file.display(), dir.display()));+ }+ let store = raea_io_assets::Store::beside(&dir.join("edit.tsx")).dir;+ raea_sys_bake::making(|| raea_sys_weathering::bake(&store, &file, v))+}++/// `raea wear bake REQUEST.json [-o OUT.json]`: the bake from a shell, in the current folder (the composition's).+/// Prints the model's path, or writes the whole answer to OUT.json and prints its path.+pub fn cli(args: &[String], media: fn(&Path, &str) -> PathBuf) -> R<String> {+ if args.get(1).map(String::as_str) != Some("bake") {+ return Err(USAGE.into());+ }+ let req = args.get(2).filter(|a| !a.starts_with('-')).ok_or(USAGE)?;+ let v: Value = serde_json::from_slice(&std::fs::read(req).map_err(|e| format!("{req}: {e}"))?).map_err(|e| format!("{req}: {e}"))?;+ let out = bake_in(Path::new("."), media, &v)?;+ match args.iter().position(|a| a == "-o").map(|i| args.get(i + 1).ok_or(USAGE)).transpose()? {+ Some(o) => {+ std::fs::write(o, serde_json::to_string_pretty(&out).map_err(|e| e.to_string())?).map_err(|e| format!("{o}: {e}"))?;+ Ok(o.clone())+ }+ None => Ok(out.get("file").and_then(Value::as_str).map(String::from).unwrap_or_else(|| out.to_string())),+ }+}++#[cfg(test)]+mod tests;diff --git a/runtime/wear/src/tests.rs b/runtime/wear/src/tests.rsnew file mode 100644index 00000000..df2b0c20--- /dev/null+++ b/runtime/wear/src/tests.rs@@ -0,0 +1,97 @@+//! The call on a small scene: a 3 m wall standing on a 6 m floor in a project's assets/, found by its media path,+//! baked into the project's store; the same request comes back from the store; a missing src says where it looked;+//! the verb writes its answer where -o says.++use std::path::{Path, PathBuf};++use serde_json::{Value, json};++use super::{bake_in, cli};++/// The runtime's rule for /media/x, cut down: the project's assets/x.+fn media(dir: &Path, src: &str) -> PathBuf {+ match src.strip_prefix("/media/") {+ Some(rest) => dir.join("assets").join(rest),+ None => dir.join(src),+ }+}++fn project(name: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!("raea-wear-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(dir.join("assets")).unwrap();+ std::fs::write(dir.join("assets/corner.glb"), corner()).unwrap();+ dir+}++/// A wall (x 0-6, y 0-3 at z 0, facing +z) of "facade" and a floor (z 0-4) of "ground".+fn corner() -> Vec<u8> {+ let quads: [([f32; 3], [f32; 3], [f32; 3], [f32; 3]); 2] = [([0.0, 0.0, 0.0], [6.0, 0.0, 0.0], [6.0, 3.0, 0.0], [0.0, 3.0, 0.0]), ([0.0, 0.0, 4.0], [6.0, 0.0, 4.0], [6.0, 0.0, 0.0], [0.0, 0.0, 0.0])];+ let mut bin = Vec::new();+ let (mut views, mut accessors, mut prims) = (Vec::new(), Vec::new(), Vec::new());+ for (k, (a, b, c, d)) in quads.iter().enumerate() {+ let pos: Vec<f32> = [a, b, c, d].iter().flat_map(|p| p.iter().copied()).collect();+ let off = bin.len();+ bin.extend(pos.iter().flat_map(|f| f.to_le_bytes()));+ views.push(json!({ "buffer": 0, "byteOffset": off, "byteLength": 48 }));+ let lo: Vec<f32> = (0..3).map(|i| [a[i], b[i], c[i], d[i]].into_iter().fold(f32::INFINITY, f32::min)).collect();+ let hi: Vec<f32> = (0..3).map(|i| [a[i], b[i], c[i], d[i]].into_iter().fold(f32::NEG_INFINITY, f32::max)).collect();+ accessors.push(json!({ "bufferView": views.len() - 1, "componentType": 5126, "count": 4, "type": "VEC3", "min": lo, "max": hi }));+ let off = bin.len();+ bin.extend([0u16, 1, 2, 0, 2, 3].iter().flat_map(|i| i.to_le_bytes()));+ bin.extend([0u8; 4]);+ views.push(json!({ "buffer": 0, "byteOffset": off, "byteLength": 12 }));+ accessors.push(json!({ "bufferView": views.len() - 1, "componentType": 5123, "count": 6, "type": "SCALAR" }));+ prims.push(json!({ "attributes": { "POSITION": 2 * k }, "indices": 2 * k + 1, "material": k }));+ }+ let j = json!({+ "asset": { "version": "2.0" }, "scene": 0, "scenes": [{ "nodes": [0] }], "nodes": [{ "mesh": 0 }],+ "meshes": [{ "primitives": prims }], "materials": [{ "name": "facade" }, { "name": "ground" }],+ "buffers": [{ "byteLength": bin.len() }], "bufferViews": views, "accessors": accessors,+ });+ raea_sys_glb::glb_bytes(&j, &bin)+}++fn request() -> Value {+ json!({ "src": "/media/corner.glb", "env": { "density": 4, "walk": ["ground"], "rays": { "sky": 8, "cavity": 4 } }, "classes": { "facade": "plaster", "ground": "ground" } })+}++#[test]+fn a_bake_is_made_once_in_the_projects_store() {+ let dir = project("once");+ let a = bake_in(&dir, media, &request()).unwrap();+ let store = dir.join("assets").join("wear");+ let file = PathBuf::from(a["file"].as_str().unwrap());+ assert!(file.starts_with(&store) && file.is_file(), "the model in the project's store: {file:?}");+ for m in ["causes0", "causes1", "causes2", "causes3"] {+ assert!(Path::new(a["maps"][m].as_str().unwrap()).is_file(), "{m}");+ }+ let b = bake_in(&dir, media, &request()).unwrap();+ assert_eq!(a["key"], b["key"]);+ assert_eq!(a, b, "the second call reads the first's answer");+ let _ = std::fs::remove_dir_all(&dir);+}++#[test]+fn a_missing_src_says_where_it_looked() {+ let dir = project("missing");+ let e = bake_in(&dir, media, &json!({ "src": "/media/nope.glb" })).unwrap_err();+ assert!(e.contains("nope.glb") && e.contains("no file"), "{e}");+ assert!(bake_in(&dir, media, &json!({})).unwrap_err().contains("src"));+ let _ = std::fs::remove_dir_all(&dir);+}++#[test]+fn the_verb_writes_its_answer() {+ let dir = project("verb");+ std::fs::write(dir.join("req.json"), request().to_string()).unwrap();+ let here = std::env::current_dir().unwrap();+ std::env::set_current_dir(&dir).unwrap();+ let got = cli(&["wear".into(), "bake".into(), "req.json".into(), "-o".into(), "out.json".into()], media);+ std::env::set_current_dir(here).unwrap();+ assert_eq!(got.unwrap(), "out.json");+ let out: Value = serde_json::from_slice(&std::fs::read(dir.join("out.json")).unwrap()).unwrap();+ assert!(out["file"].as_str().unwrap().ends_with("model.glb"));+ assert!(cli(&["wear".into(), "bake".into()], media).unwrap_err().contains("raea wear bake"));+ let _ = std::fs::remove_dir_all(&dir);+}diff --git a/systems/exposure/Cargo.toml b/systems/exposure/Cargo.tomlnew file mode 100644index 00000000..a4544b7d--- /dev/null+++ b/systems/exposure/Cargo.toml@@ -0,0 +1,10 @@+[package]+name = "raea-sys-exposure"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "What a point on a model is exposed to through the year: the sun on chosen days, driven snow, and where blown things settle (the weathering bake's sun and causes3)"++[dependencies]+parry3d = "0.31"diff --git a/systems/exposure/src/lib.rs b/systems/exposure/src/lib.rsnew file mode 100644index 00000000..e2c7972f--- /dev/null+++ b/systems/exposure/src/lib.rs@@ -0,0 +1,199 @@+//! What a point on a model is exposed to through the year (docs/wear.feature WR9): the sun on chosen days, weather+//! driven along a cone, and how sheltered it is where blown things settle. The weathering bake builds causes0's sun+//! and causes3 on it, so a season or a day's weather is drawn over them at render time and never baked:+//! sun the share of the sun's path on the days asked (every `step` hours it stands 3 degrees up) the point+//! sees, weighted by n.s: the whole year's for what fades and dries, December's for where snow outlasts a thaw+//! drift driven snow's reach: rays up its cone (its axis the way the snow comes from), each seen one counting+//! n.d, over what an open level roof gets; a wall facing a storm gets as much as a roof, one in its lee none+//! litter where blown leaves and snow settle, on faces looking up: hemmed in close by (low rays out across the+//! face meeting something within LITTER_REACH: a kerb's gutter, a step's corner, a sill against its window)+//! and in the lee (rays toward the wind meeting something within LEE_REACH)+//! The weights of litter's two parts are ASSUMED until a snow or leaf count against a photograph says otherwise.+//! Samples are a rotated R2 sequence per point, 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;++#[cfg(test)]+mod tests;++pub const VERSION: &str = "raea-sys-exposure 2";++/// Days of the year (1-366) for the whole year's sun: the middle of each month.+pub const YEAR: [f32; 12] = [15.0, 46.0, 74.0, 105.0, 135.0, 166.0, 196.0, 227.0, 258.0, 288.0, 319.0, 349.0];+/// Days for December's sun, either side of the solstice: where snow and frost outlast a thaw.+pub const DECEMBER: [f32; 3] = [335.0, 355.0, 15.0];++const OFF: f32 = 0.01;+const FAR: f32 = 400.0;+const LITTER_REACH: f32 = 1.5;+const LEE_REACH: f32 = 3.0;+/// litter = ENCLOSED x hemmed in + LEE x in the lee (ASSUMED)+const ENCLOSED: f32 = 0.7;+const LEE: f32 = 0.3;++/// The model's frame: up, north, and its latitude in degrees.+#[derive(Clone, Copy, Debug)]+pub struct Frame {+ pub up: Vec3,+ pub north: Vec3,+ pub lat: f32,+}++/// Weather driven along a cone: the way it travels (a unit vector, down and with the wind) and the cone's half-angle+/// in radians.+#[derive(Clone, Copy, Debug)]+pub struct Driven {+ pub dir: Vec3,+ pub spread: f32,+}++/// What one point is exposed to, each 0-1.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct Exposure {+ pub sun: f32,+ pub december: f32,+ pub drift: f32,+ pub litter: f32,+}++/// The sun's directions on `days`, every `step` hours it stands 3 degrees up.+pub fn sun_path(f: &Frame, days: &[f32], step: f32) -> Vec<Vec3> {+ let east = f.north.cross(f.up).normalize();+ let phi = f.lat.to_radians();+ let mut out = Vec::new();+ for &n in days {+ let dec = (23.44f32).to_radians() * (TAU * (284.0 + n) / 365.0).sin();+ let mut t: f32 = 0.0;+ while t < 24.0 {+ let ha = (15.0 * (t - 12.0)).to_radians();+ let alt = (phi.sin() * dec.sin() + phi.cos() * dec.cos() * ha.cos()).asin();+ if alt > 3f32.to_radians() {+ let az = (-ha.sin()).atan2(dec.tan() * phi.cos() - phi.sin() * ha.cos());+ out.push((alt.cos() * (az.cos() * f.north + az.sin() * east) + alt.sin() * f.up).normalize());+ }+ t += step;+ }+ }+ out+}++/// Everything a point's exposure needs, worked out once for a model.+pub struct Exposer<'a> {+ mesh: &'a TriMesh,+ up: Vec3,+ year: Vec<Vec3>,+ december: Vec<Vec3>,+ snow: Driven,+ /// the snow's rays and what a level open roof gets of them+ rays: u32,+ level: f32,+}++impl<'a> Exposer<'a> {+ pub fn new(mesh: &'a TriMesh, f: &Frame, snow: Driven, rays: u32) -> Exposer<'a> {+ let rays = rays.max(1);+ let from = -snow.dir;+ let level = (0..rays).map(|j| cone(from, snow.spread, sample(0, j)).dot(f.up).max(0.0)).sum::<f32>() / rays as f32;+ Exposer { mesh, up: f.up, year: sun_path(f, &YEAR, 2.0), december: sun_path(f, &DECEMBER, 1.0), snow, rays, level }+ }++ fn hit(&self, o: Vec3, d: Vec3, far: f32) -> bool {+ self.mesh.cast_local_ray(&Ray::new(o, d), far, false).is_some()+ }++ fn lit(&self, o: Vec3, n: Vec3, path: &[Vec3]) -> f32 {+ if path.is_empty() {+ return 0.0;+ }+ path.iter().map(|&s| if n.dot(s) > 0.0 && !self.hit(o, s, FAR) { n.dot(s) } else { 0.0 }).sum::<f32>() / path.len() as f32+ }++ /// Point `i` (its index seeds its samples) at p, facing n.+ pub fn at(&self, i: u32, p: Vec3, n: Vec3) -> Exposure {+ let o = p + n * OFF;+ let from = -self.snow.dir;+ let mut drift = 0.0;+ for j in 0..self.rays {+ let d = cone(from, self.snow.spread, sample(i, j));+ if n.dot(d) > 0.0 && !self.hit(o, d, FAR) {+ drift += n.dot(d);+ }+ }+ let drift = if self.level > 0.0 { drift / self.rays as f32 / self.level } else { 0.0 };+ Exposure { sun: self.lit(o, n, &self.year), december: self.lit(o, n, &self.december), drift: drift.min(1.0), litter: self.litter(o, n) }+ }++ /// On a face looking up: low rays out across it every 45 degrees, and toward the wind, meeting something near.+ fn litter(&self, o: Vec3, n: Vec3) -> f32 {+ let facing = n.dot(self.up);+ if facing < 0.5 {+ return 0.0;+ }+ let (t, b) = across(self.up);+ let low = (10f32).to_radians();+ let hemmed = (0..8)+ .filter(|&k| {+ let a = TAU * k as f32 / 8.0;+ let d = (t * a.cos() + b * a.sin()) * low.cos() + self.up * low.sin();+ self.hit(o, d, LITTER_REACH)+ })+ .count() as f32+ / 8.0;+ let wind = -self.snow.dir;+ let level = (wind - self.up * wind.dot(self.up)).normalize_or_zero();+ let lee = if level == Vec3::ZERO {+ 0.0+ } else {+ let side = self.up.cross(level);+ let fan = [(-20f32, 5f32), (0.0, 5.0), (20.0, 5.0), (0.0, 15.0), (0.0, 25.0)];+ fan.iter()+ .filter(|&&(az, el)| {+ let (az, el) = (az.to_radians(), el.to_radians());+ let d = (level * az.cos() + side * az.sin()) * el.cos() + self.up * el.sin();+ self.hit(o, d, LEE_REACH)+ })+ .count() as f32+ / fan.len() as f32+ };+ ((ENCLOSED * hemmed + LEE * lee) * smooth((facing - 0.5) / 0.3)).clamp(0.0, 1.0)+ }+}++fn smooth(x: f32) -> f32 {+ let x = x.clamp(0.0, 1.0);+ x * x * (3.0 - 2.0 * x)+}++fn hash(mut x: u32) -> u32 {+ x ^= x >> 16;+ x = x.wrapping_mul(0x7feb_352d);+ x ^= x >> 15;+ x = x.wrapping_mul(0x846c_a68b);+ x ^ (x >> 16)+}++/// The j-th of point i's samples: an R2 sequence rotated by a hash of i.+fn sample(i: u32, j: u32) -> (f32, f32) {+ const A1: f32 = 0.754_877_7;+ const A2: f32 = 0.569_840_3;+ let h = hash(i.wrapping_add(0x9e37_79b9));+ let (o1, o2) = ((h & 0xffff) as f32 / 65536.0, (h >> 16) as f32 / 65536.0);+ ((o1 + A1 * j as f32).fract(), (o2 + A2 * j as f32).fract())+}++fn across(n: Vec3) -> (Vec3, Vec3) {+ let t = if n.x.abs() < 0.9 { Vec3::X } else { Vec3::Y };+ let t = (t - n * t.dot(n)).normalize();+ (t, n.cross(t))+}++fn cone(axis: Vec3, half: f32, (u1, u2): (f32, f32)) -> Vec3 {+ let c = 1.0 - u1 * (1.0 - half.cos());+ let s = (1.0 - c * c).max(0.0).sqrt();+ let (t, b) = across(axis);+ (axis * c + t * (s * (TAU * u2).cos()) + b * (s * (TAU * u2).sin())).normalize()+}diff --git a/systems/exposure/src/tests.rs b/systems/exposure/src/tests.rsnew file mode 100644index 00000000..ec3f8415--- /dev/null+++ b/systems/exposure/src/tests.rs@@ -0,0 +1,91 @@+//! Synthetic fronts checked by number: a wall facing south and one facing north, a wall facing a storm and one in+//! its lee, a gutter against a kerb, and the sun's height on the solstices.++use parry3d::glamx::Vec3;+use parry3d::shape::TriMesh;++use crate::{DECEMBER, Driven, Exposer, Frame, YEAR, sun_path};++const BERLIN: Frame = Frame { up: Vec3::Y, north: Vec3::NEG_Z, lat: 52.5 };++#[derive(Default)]+struct B {+ pos: Vec<Vec3>,+ tri: Vec<[u32; 3]>,+}++impl B {+ fn cube(&mut self, a: [f32; 3], b: [f32; 3]) {+ let i = self.pos.len() as u32;+ for k in 0..8 {+ self.pos.push(Vec3::new(if k & 1 == 0 { a[0] } else { b[0] }, if k & 2 == 0 { a[1] } else { b[1] }, if k & 4 == 0 { a[2] } else { b[2] }));+ }+ for q in [[0, 2, 3, 1], [4, 5, 7, 6], [0, 1, 5, 4], [2, 6, 7, 3], [0, 4, 6, 2], [1, 3, 7, 5]] {+ self.tri.push([i + q[0], i + q[1], i + q[2]]);+ self.tri.push([i + q[0], i + q[2], i + q[3]]);+ }+ }+ fn mesh(self) -> TriMesh {+ TriMesh::new(self.pos, self.tri).unwrap()+ }+}++/// Snow on a storm from the east-north-east, falling 60 degrees off the vertical.+fn storm() -> Driven {+ let east = BERLIN.north.cross(BERLIN.up).normalize();+ let from = (east * 22.5f32.to_radians().cos() + BERLIN.north * 22.5f32.to_radians().sin()).normalize();+ let (tilt, spread) = (60f32.to_radians(), 25f32.to_radians());+ Driven { dir: (-from * tilt.sin() - BERLIN.up * tilt.cos()).normalize(), spread }+}++#[test]+fn the_sun_stands_14_degrees_at_the_december_solstice_and_61_in_june() {+ let top = |day: f32| sun_path(&BERLIN, &[day], 0.25).iter().map(|s| s.y.asin().to_degrees()).fold(0.0, f32::max);+ assert!((top(355.0) - 14.1).abs() < 0.3, "{}", top(355.0));+ assert!((top(172.0) - 60.9).abs() < 0.3, "{}", top(172.0));+ assert!(sun_path(&BERLIN, &DECEMBER, 1.0).len() < sun_path(&BERLIN, &YEAR, 2.0).len());+}++#[test]+fn a_south_wall_sees_the_december_sun_and_a_north_one_does_not() {+ let mut b = B::default();+ b.cube([-5.0, 0.0, -1.0], [5.0, 10.0, 0.0]);+ let mesh = b.mesh();+ let e = Exposer::new(&mesh, &BERLIN, storm(), 32);+ let south = e.at(1, Vec3::new(0.0, 5.0, 0.0), Vec3::Z);+ let north = e.at(2, Vec3::new(0.0, 5.0, -1.0), Vec3::NEG_Z);+ assert!(south.december > 0.3 && north.december == 0.0, "{south:?} {north:?}");+ assert!(north.sun > 0.0, "a north wall sees the summer's early and late sun: {north:?}");+ assert!(south.sun > 3.0 * north.sun);+}++#[test]+fn a_wall_facing_the_storm_takes_the_drift_and_its_lee_none() {+ let mut b = B::default();+ b.cube([-0.5, 0.0, -5.0], [0.0, 10.0, 5.0]);+ let mesh = b.mesh();+ let e = Exposer::new(&mesh, &BERLIN, storm(), 64);+ let east = e.at(1, Vec3::new(0.0, 5.0, 0.0), Vec3::X);+ let west = e.at(2, Vec3::new(-0.5, 5.0, 0.0), Vec3::NEG_X);+ let roof = e.at(3, Vec3::new(-0.25, 10.0, 0.0), Vec3::Y);+ assert!(east.drift > 0.8 && west.drift < 0.05, "{east:?} {west:?}");+ assert!((roof.drift - 1.0).abs() < 0.1, "a level roof is the measure: {roof:?}");+}++#[test]+fn litter_gathers_in_the_gutter_against_a_kerb_and_in_a_walls_lee() {+ let mut b = B::default();+ b.cube([-20.0, -0.15, -20.0], [20.0, 0.0, 20.0]);+ b.cube([-20.0, 0.0, 0.0], [20.0, 0.15, 0.3]);+ b.cube([-10.0, 0.0, 10.0], [-9.7, 3.0, 14.0]);+ let mesh = b.mesh();+ let e = Exposer::new(&mesh, &BERLIN, storm(), 16);+ let gutter = e.at(1, Vec3::new(0.0, 0.0, -0.05), Vec3::Y);+ let road = e.at(2, Vec3::new(0.0, 0.0, -6.0), Vec3::Y);+ let lee = e.at(3, Vec3::new(-10.6, 0.0, 12.0), Vec3::Y);+ let wall = e.at(4, Vec3::new(5.0, 0.07, 0.0), Vec3::NEG_Z);+ assert!(gutter.litter > 0.1 && road.litter == 0.0, "{gutter:?} {road:?}");+ assert!(lee.litter > road.litter, "the lee of a wall against the wind: {lee:?}");+ assert_eq!(wall.litter, 0.0, "nothing settles on a face that doesn't look up");+ assert_eq!(e.at(1, Vec3::new(0.0, 0.0, -0.05), Vec3::Y), gutter, "the same point, the same exposure");+}diff --git a/systems/glb/Cargo.toml b/systems/glb/Cargo.tomlnew file mode 100644index 00000000..8bf8e706--- /dev/null+++ b/systems/glb/Cargo.toml@@ -0,0 +1,10 @@+[package]+name = "raea-sys-glb"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "A .glb read as its JSON and bytes, its accessors as floats or indices, and written back with only what's used"++[dependencies]+serde_json = "1"diff --git a/systems/glb/src/lib.rs b/systems/glb/src/lib.rsnew file mode 100644index 00000000..032ab67b--- /dev/null+++ b/systems/glb/src/lib.rs@@ -0,0 +1,208 @@+//! The .glb container: its JSON and binary chunks, accessors read as bytes, floats or indices (strides, component+//! types and normalized integers handled; sparse accessors refused), and the file written back with only the+//! accessors and buffer views still in use.++use serde_json::{Value, json};++/// An error is a line for the person.+type R<T> = Result<T, String>;++pub struct Glb {+ pub json: Value,+ pub bin: Vec<u8>,+}+pub fn parse(b: &[u8]) -> R<Glb> {+ if b.len() < 20 || &b[0..4] != b"glTF" {+ return Err("not a .glb (a .gltf with outside files isn't taken: pack it to .glb first)".into());+ }+ let jl = u32::from_le_bytes(b[12..16].try_into().unwrap()) as usize;+ let json: Value = serde_json::from_slice(b.get(20..20 + jl).ok_or("truncated JSON chunk")?).map_err(|e| e.to_string())?;+ let at = 20 + jl;+ let bin = if b.len() >= at + 8 {+ let bl = u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) as usize;+ b.get(at + 8..at + 8 + bl).ok_or("truncated BIN chunk")?.to_vec()+ } else {+ Vec::new()+ };+ Ok(Glb { json, bin })+}++pub fn arr<'a>(j: &'a Value, k: &str) -> &'a [Value] {+ j.get(k).and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[])+}++/// An accessor's elements as tight bytes, and its layout (components a vertex, bytes a component).+pub fn raw(g: &Glb, i: usize) -> R<(Vec<u8>, usize, usize, &Value)> {+ let a = arr(&g.json, "accessors").get(i).ok_or_else(|| format!("accessor {i} missing"))?;+ if a.get("sparse").is_some() {+ return Err(format!("accessor {i}: sparse accessors aren't taken"));+ }+ let comps = match a["type"].as_str().unwrap_or("") {+ "SCALAR" => 1,+ "VEC2" => 2,+ "VEC3" => 3,+ "VEC4" => 4,+ "MAT4" => 16,+ t => return Err(format!("accessor {i}: type {t}")),+ };+ let csize = match a["componentType"].as_u64().unwrap_or(0) {+ 5120 | 5121 => 1,+ 5122 | 5123 => 2,+ 5125 | 5126 => 4,+ c => return Err(format!("accessor {i}: component type {c}")),+ };+ let count = a["count"].as_u64().unwrap_or(0) as usize;+ let el = comps * csize;+ let Some(v) = a.get("bufferView").and_then(Value::as_u64) else { return Ok((vec![0; count * el], comps, csize, a)) };+ let bv = &arr(&g.json, "bufferViews")[v as usize];+ if bv["buffer"].as_u64().unwrap_or(0) != 0 {+ return Err(format!("accessor {i}: only the .glb's own buffer is read"));+ }+ let start = bv["byteOffset"].as_u64().unwrap_or(0) as usize + a["byteOffset"].as_u64().unwrap_or(0) as usize;+ let stride = bv["byteStride"].as_u64().map(|s| s as usize).unwrap_or(el);+ let mut out = Vec::with_capacity(count * el);+ for k in 0..count {+ let s = start + k * stride;+ out.extend_from_slice(g.bin.get(s..s + el).ok_or_else(|| format!("accessor {i} runs past the buffer"))?);+ }+ Ok((out, comps, csize, a))+}++/// An accessor as floats (normalized integers scaled to 0-1 or -1-1, others as they are).+pub fn floats(g: &Glb, i: usize) -> R<(Vec<f32>, usize)> {+ let (b, comps, csize, a) = raw(g, i)?;+ let norm = a["normalized"].as_bool().unwrap_or(false);+ let ct = a["componentType"].as_u64().unwrap_or(0);+ let out = b+ .chunks_exact(csize)+ .map(|c| match ct {+ 5126 => f32::from_le_bytes(c.try_into().unwrap()),+ 5121 => c[0] as f32 / if norm { 255.0 } else { 1.0 },+ 5120 => (c[0] as i8) as f32 / if norm { 127.0 } else { 1.0 },+ 5123 => u16::from_le_bytes(c.try_into().unwrap()) as f32 / if norm { 65535.0 } else { 1.0 },+ 5122 => i16::from_le_bytes(c.try_into().unwrap()) as f32 / if norm { 32767.0 } else { 1.0 },+ _ => u32::from_le_bytes(c.try_into().unwrap()) as f32,+ })+ .collect();+ Ok((out, comps))+}++pub fn indices(g: &Glb, i: usize) -> R<Vec<u32>> {+ let (b, _, csize, _) = raw(g, i)?;+ Ok(match csize {+ 1 => b.iter().map(|&x| x as u32).collect(),+ 2 => b.chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]]) as u32).collect(),+ _ => b.chunks_exact(4).map(|c| u32::from_le_bytes(c.try_into().unwrap())).collect(),+ })+}+/// Drop the accessors and views nothing uses any more (the primitives' old data), renumbering what's kept.+pub fn compact(j: &mut Value, bin: &[u8]) -> R<Vec<u8>> {+ let mut acc_used = vec![false; arr(j, "accessors").len()];+ let mark = |v: &Value, used: &mut Vec<bool>| {+ if let Some(i) = v.as_u64() {+ used[i as usize] = true;+ }+ };+ for m in arr(j, "meshes") {+ for p in arr(m, "primitives") {+ for a in p["attributes"].as_object().into_iter().flat_map(|o| o.values()) {+ mark(a, &mut acc_used);+ }+ mark(&p["indices"], &mut acc_used);+ }+ }+ for an in arr(j, "animations") {+ for s in arr(an, "samplers") {+ mark(&s["input"], &mut acc_used);+ mark(&s["output"], &mut acc_used);+ }+ }+ let acc_new: Vec<Option<usize>> = acc_used.iter().scan(0, |n, &u| Some(if u { *n += 1; Some(*n - 1) } else { None })).collect();+ let mut view_used = vec![false; arr(j, "bufferViews").len()];+ for (i, a) in arr(j, "accessors").iter().enumerate() {+ if acc_used[i] {+ mark(&a["bufferView"], &mut view_used);+ }+ }+ for im in arr(j, "images") {+ mark(&im["bufferView"], &mut view_used);+ }+ let mut nbin = Vec::new();+ let mut view_new = vec![None; view_used.len()];+ let mut views = Vec::new();+ for (i, v) in arr(j, "bufferViews").iter().enumerate() {+ if !view_used[i] {+ continue;+ }+ while nbin.len() % 4 != 0 {+ nbin.push(0);+ }+ let (o, l) = (v["byteOffset"].as_u64().unwrap_or(0) as usize, v["byteLength"].as_u64().unwrap_or(0) as usize);+ let mut nv = v.clone();+ nv["byteOffset"] = json!(nbin.len());+ nbin.extend_from_slice(bin.get(o..o + l).ok_or("a buffer view runs past the buffer")?);+ view_new[i] = Some(views.len());+ views.push(nv);+ }+ let remap = |v: &mut Value, table: &[Option<usize>]| {+ if let Some(i) = v.as_u64() {+ *v = json!(table[i as usize]);+ }+ };+ let accs: Vec<Value> = arr(j, "accessors")+ .iter()+ .enumerate()+ .filter(|(i, _)| acc_used[*i])+ .map(|(_, a)| {+ let mut a = a.clone();+ remap(&mut a["bufferView"], &view_new);+ a+ })+ .collect();+ for m in j.get_mut("meshes").and_then(Value::as_array_mut).into_iter().flatten() {+ for p in m.get_mut("primitives").and_then(Value::as_array_mut).into_iter().flatten() {+ for a in p["attributes"].as_object_mut().into_iter().flat_map(|o| o.values_mut()) {+ remap(a, &acc_new);+ }+ remap(&mut p["indices"], &acc_new);+ }+ }+ for an in j.get_mut("animations").and_then(Value::as_array_mut).into_iter().flatten() {+ for s in an.get_mut("samplers").and_then(Value::as_array_mut).into_iter().flatten() {+ remap(&mut s["input"], &acc_new);+ remap(&mut s["output"], &acc_new);+ }+ }+ for im in j.get_mut("images").and_then(Value::as_array_mut).into_iter().flatten() {+ if im.get("bufferView").is_some() {+ remap(&mut im["bufferView"], &view_new);+ }+ }+ j["accessors"] = json!(accs);+ j["bufferViews"] = json!(views);+ j["buffers"] = json!([{"byteLength": nbin.len()}]);+ Ok(glb_bytes(j, &nbin))+}++pub fn glb_bytes(j: &Value, bin: &[u8]) -> Vec<u8> {+ let mut js = j.to_string().into_bytes();+ while js.len() % 4 != 0 {+ js.push(b' ');+ }+ let mut b = bin.to_vec();+ while b.len() % 4 != 0 {+ b.push(0);+ }+ let total = 12 + 8 + js.len() + 8 + b.len();+ let mut out = Vec::with_capacity(total);+ out.extend_from_slice(b"glTF");+ out.extend_from_slice(&2u32.to_le_bytes());+ out.extend_from_slice(&(total as u32).to_le_bytes());+ out.extend_from_slice(&(js.len() as u32).to_le_bytes());+ out.extend_from_slice(b"JSON");+ out.extend_from_slice(&js);+ out.extend_from_slice(&(b.len() as u32).to_le_bytes());+ out.extend_from_slice(b"BIN\0");+ out.extend_from_slice(&b);+ out+}diff --git a/systems/runoff/Cargo.toml b/systems/runoff/Cargo.tomlnew file mode 100644index 00000000..e5bb10c8--- /dev/null+++ b/systems/runoff/Cargo.toml@@ -0,0 +1,11 @@+[package]+name = "raea-sys-runoff"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "Rain's run-off over a model's surfaces: drops walked down faces, dripping, clinging and carrying stains (raea/wear's flow)"++[dependencies]+parry3d = "0.31"+rayon = "1"diff --git a/systems/runoff/src/lib.rs b/systems/runoff/src/lib.rsnew file mode 100644index 00000000..269e690e--- /dev/null+++ b/systems/runoff/src/lib.rs@@ -0,0 +1,141 @@+//! Rain's run-off over a model's surfaces, after Dorsey, Pedersen and Hanrahan (1996, "Flow and Changes in+//! Appearance"): drops land where the rain reaches, run down each face along gravity, cross onto the next face over+//! shared edges, drip from the edges of undersides and fall to what's below, and carry what they pick up (dust off+//! a ledge's top, rust off iron, green off copper, white off zinc) down to where they leave it, as Chen et al.'s+//! gamma-tons (2005) do. Three rules from how fronts weather:+//! - a drop at the bottom of a vertical face about to drip first looks along that edge for a wall it meets head+//! on within CAPTURE (a ledge's end face meets the wall behind it): it clings into that corner and runs on down+//! the wall. So a sill sheds most of its water clear off its front and streaks the wall under its two ends.+//! - a face that drains (a roof, to its gutter) ends a drop at once; so does a walking surface (the ground).+//! - a drop on a level face keeps one heading (from its seed) till it leaves the face: a sill's top sends some of+//! its drops off the front and some off the ends, by the lengths of those edges.+//! Every drop is its own seeded walk and the sums are integer, so a run gives the same maps every time.++mod walk;+#[cfg(test)]+mod tests;++use std::sync::atomic::{AtomicU64, Ordering};++use parry3d::glamx::Vec3;+use parry3d::shape::TriMesh;+use rayon::prelude::*;++/// Bumped when a run's sums would change for the same input (a bake that uses them keys on it).+pub const VERSION: &str = "raea-sys-runoff 2";++/// What a drop picks up crossing a face, and leaves below it.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[repr(u8)]+pub enum Kind {+ None = 0,+ Grime = 1,+ Rust = 2,+ Copper = 3,+ Zinc = 4,+}++const KINDS: usize = 5;++/// Per triangle: what water picks up from it, and whether a drop ends on it.+#[derive(Clone, Copy, Debug)]+pub struct Role {+ pub gives: Kind,+ pub walk: bool,+ pub drains: bool,+}++/// The model: positions, triangles, their planes' normals and roles, and each triangle's corners in the atlas (texel+/// coordinates, texel i covering [i, i+1)).+pub struct Surface<'a> {+ pub pos: &'a [Vec3],+ pub tri: &'a [[u32; 3]],+ pub nrm: &'a [Vec3],+ pub role: &'a [Role],+ pub uv: &'a [[[f32; 2]; 3]],+ pub mesh: &'a TriMesh,+}++/// Where the rain lands: a point on a triangle, and how much water (square metres of rain caught).+#[derive(Clone, Copy, Debug)]+pub struct Drop {+ pub p: Vec3,+ pub tri: u32,+ pub water: f32,+}++/// The atlas: water passing each texel (square metres of rain caught upstream, per metre across), what it left there,+/// and the kind it left most of.+pub struct Out {+ pub flow: Vec<f32>,+ pub deposit: Vec<f32>,+ pub kind: Vec<Kind>,+}++impl Out {+ /// Texel i as bytes for a map, at `d` texels a metre: flow (water passing per metre across, log scale from 0.02 to+ /// 20 square metres a metre), deposit (left per square metre, log scale from 1e-4 to 0.1) and the kind (0, 60, 120,+ /// 180, 240 for none, grime, rust, copper, zinc).+ pub fn bytes(&self, i: usize, d: f32) -> [u8; 3] {+ let log = |v: f32, lo: f32, hi: f32| ((1.0 + v / lo).ln() / (1.0 + hi / lo).ln()).clamp(0.0, 1.0);+ let b = |v: f32| (v * 255.0).round() as u8;+ [b(log(self.flow[i] * d, 0.02, 20.0)), b(log(self.deposit[i] * d * d, 1e-4, 0.1)), self.kind[i] as u8 * 60]+ }+}++/// Fixed point for the sums: a billionth of a square metre (a drop's stain spread over a wall is that small).+const UNIT: f64 = 1e9;++pub(crate) struct Acc {+ w: u32,+ h: u32,+ flow: Vec<AtomicU64>,+ dep: Vec<[AtomicU64; KINDS]>,+}++impl Acc {+ fn new(w: u32, h: u32) -> Acc {+ let n = (w * h) as usize;+ Acc { w, h, flow: (0..n).map(|_| AtomicU64::new(0)).collect(), dep: (0..n).map(|_| std::array::from_fn(|_| AtomicU64::new(0))).collect() }+ }+ fn at(&self, uv: [f32; 2]) -> usize {+ let x = (uv[0].floor() as i64).clamp(0, self.w as i64 - 1) as usize;+ let y = (uv[1].floor() as i64).clamp(0, self.h as i64 - 1) as usize;+ y * self.w as usize + x+ }+ /// Water w over a segment from a to b (atlas coordinates): all of it passes each texel the segment crosses, and+ /// what it left is spread over them.+ pub(crate) fn line(&self, a: [f32; 2], b: [f32; 2], w: f32, left: &[f32; KINDS]) {+ let n = ((b[0] - a[0]).hypot(b[1] - a[1]) * 1.5).ceil().max(1.0) as usize;+ let mut last = usize::MAX;+ for i in 0..n {+ let t = (i as f32 + 0.5) / n as f32;+ let k = self.at([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]);+ if k != last {+ self.flow[k].fetch_add((w as f64 * UNIT).round() as u64, Ordering::Relaxed);+ last = k;+ }+ for (j, &l) in left.iter().enumerate() {+ if l > 0.0 {+ self.dep[k][j].fetch_add((l as f64 / n as f64 * UNIT).round() as u64, Ordering::Relaxed);+ }+ }+ }+ }+}++/// Every drop walked; the atlas's sums.+pub fn run(s: &Surface, drops: &[Drop], up: Vec3, w: u32, h: u32) -> Out {+ let adj = walk::Adjacency::of(s);+ let acc = Acc::new(w, h);+ drops.par_iter().enumerate().for_each(|(i, d)| walk::drop(s, &adj, &acc, up, d, i as u32));+ let flow = acc.flow.iter().map(|v| (v.load(Ordering::Relaxed) as f64 / UNIT) as f32).collect();+ let (mut deposit, mut kind) = (Vec::with_capacity(acc.dep.len()), Vec::with_capacity(acc.dep.len()));+ for d in &acc.dep {+ let v: [f32; KINDS] = std::array::from_fn(|j| (d[j].load(Ordering::Relaxed) as f64 / UNIT) as f32);+ deposit.push(v.iter().sum());+ let best = (1..KINDS).max_by(|&a, &b| v[a].total_cmp(&v[b]).then(b.cmp(&a))).unwrap();+ kind.push(if v[best] > 0.0 { [Kind::None, Kind::Grime, Kind::Rust, Kind::Copper, Kind::Zinc][best] } else { Kind::None });+ }+ Out { flow, deposit, kind }+}diff --git a/systems/runoff/src/tests.rs b/systems/runoff/src/tests.rsnew file mode 100644index 00000000..e72314cb--- /dev/null+++ b/systems/runoff/src/tests.rs@@ -0,0 +1,148 @@+//! A wall 4 m wide and 6 m high facing +z, standing on the ground, with a stone sill and an iron bracket on it. The+//! wall alone is in the atlas (D texels a metre, row 0 at its top); every other face sends its texels to one junk+//! texel past the wall's columns.++use parry3d::glamx::Vec3;+use parry3d::shape::TriMesh;++use crate::{Drop, Kind, Out, Role, Surface, run};++const D: f32 = 10.0;+const W: f32 = 4.0;+const H: f32 = 6.0;+const AW: u32 = (W * D) as u32 + 1;+const AH: u32 = (H * D) as u32;++struct Model {+ pos: Vec<Vec3>,+ tri: Vec<[u32; 3]>,+ nrm: Vec<Vec3>,+ role: Vec<Role>,+ uv: Vec<[[f32; 2]; 3]>,+}++const PLAIN: Role = Role { gives: Kind::None, walk: false, drains: false };++impl Model {+ fn quad(&mut self, c: [Vec3; 4], role: Role, wall: bool) {+ let at = self.pos.len() as u32;+ self.pos.extend(c);+ let n = (c[1] - c[0]).cross(c[2] - c[0]).normalize();+ let uv = |p: Vec3| if wall { [p.x * D, (H - p.y) * D] } else { [AW as f32 - 0.5, 0.5] };+ for t in [[at, at + 1, at + 2], [at, at + 2, at + 3]] {+ self.tri.push(t);+ self.nrm.push(n);+ self.role.push(role);+ self.uv.push(t.map(|i| uv(self.pos[i as usize])));+ }+ }+ /// An axis-aligned box's six faces, each wound outward.+ fn cuboid(&mut self, lo: Vec3, hi: Vec3, role: Role) {+ let v = |x: f32, y: f32, z: f32| Vec3::new(x, y, z);+ let (a, b) = (lo, hi);+ self.quad([v(a.x, a.y, b.z), v(b.x, a.y, b.z), v(b.x, b.y, b.z), v(a.x, b.y, b.z)], role, false); // +z+ self.quad([v(b.x, a.y, a.z), v(a.x, a.y, a.z), v(a.x, b.y, a.z), v(b.x, b.y, a.z)], role, false); // -z+ self.quad([v(b.x, a.y, b.z), v(b.x, a.y, a.z), v(b.x, b.y, a.z), v(b.x, b.y, b.z)], role, false); // +x+ self.quad([v(a.x, a.y, a.z), v(a.x, a.y, b.z), v(a.x, b.y, b.z), v(a.x, b.y, a.z)], role, false); // -x+ self.quad([v(a.x, b.y, b.z), v(b.x, b.y, b.z), v(b.x, b.y, a.z), v(a.x, b.y, a.z)], role, false); // +y+ self.quad([v(a.x, a.y, a.z), v(b.x, a.y, a.z), v(b.x, a.y, b.z), v(a.x, a.y, b.z)], role, false); // -y+ }+}++fn front() -> Model {+ let mut m = Model { pos: vec![], tri: vec![], nrm: vec![], role: vec![], uv: vec![] };+ let v = Vec3::new;+ m.quad([v(0.0, 0.0, 0.0), v(W, 0.0, 0.0), v(W, H, 0.0), v(0.0, H, 0.0)], PLAIN, true);+ m.quad([v(-2.0, 0.0, 4.0), v(6.0, 0.0, 4.0), v(6.0, 0.0, -2.0), v(-2.0, 0.0, -2.0)], Role { walk: true, ..PLAIN }, false);+ // a sill 1.6 m long, 0.18 deep, its top dusty; an iron bracket further along+ m.cuboid(v(1.0, 3.0, 0.0), v(2.6, 3.1, 0.18), Role { gives: Kind::Grime, ..PLAIN });+ m.cuboid(v(3.0, 4.0, 0.0), v(3.4, 4.4, 0.1), Role { gives: Kind::Rust, ..PLAIN });+ m+}++/// Rain on every level top and on the wall above the sill: a drop every 2 cm.+fn rain(m: &Model, mesh: &TriMesh) -> Vec<Drop> {+ let _ = mesh;+ let mut out = vec![];+ for (t, c) in m.tri.iter().enumerate() {+ let n = m.nrm[t];+ let up_top = n.y > 0.9 && !m.role[t].walk;+ let wall_above = m.uv[t][0][0] < AW as f32 - 1.0 && n.z > 0.9;+ if !(up_top || wall_above) {+ continue;+ }+ let [a, b, cc] = c.map(|i| m.pos[i as usize]);+ for i in 0..60 {+ for j in 0..60 - i {+ let (u, w) = ((i as f32 + 0.33) / 60.0, (j as f32 + 0.33) / 60.0);+ let p = a + (b - a) * u + (cc - a) * w;+ if wall_above && p.y < 3.1 {+ continue;+ }+ out.push(Drop { p: p + n * 0.001, tri: t as u32, water: if up_top { 1e-3 } else { 2e-4 } });+ }+ }+ }+ out+}++fn bake(m: &Model) -> Out {+ let mesh = TriMesh::new(m.pos.clone(), m.tri.clone()).unwrap();+ let s = Surface { pos: &m.pos, tri: &m.tri, nrm: &m.nrm, role: &m.role, uv: &m.uv, mesh: &mesh };+ run(&s, &rain(m, &mesh), Vec3::Y, AW, AH)+}++/// The sum over wall texels with x in [x0, x1) metres and height in [y0, y1).+fn sum(v: &[f32], x0: f32, x1: f32, y0: f32, y1: f32) -> f32 {+ let mut s = 0.0;+ for ty in ((H - y1) * D) as u32..((H - y0) * D) as u32 {+ for tx in (x0 * D) as u32..(x1 * D) as u32 {+ s += v[(ty * AW + tx) as usize];+ }+ }+ s+}++#[test]+fn a_sill_streaks_the_wall_under_its_ends_not_its_middle() {+ let o = bake(&front());+ let ends = sum(&o.flow, 0.85, 1.05, 1.0, 2.8) + sum(&o.flow, 2.55, 2.75, 1.0, 2.8);+ let middle = sum(&o.flow, 1.5, 2.1, 1.0, 2.8);+ assert!(ends > 0.0, "nothing ran down from the sill's ends");+ assert!(ends > 5.0 * middle, "ends {ends} middle {middle}");+ // and the wall beside the sill, clear of it, gets only the rain on itself above+ let beside = sum(&o.flow, 0.2, 0.6, 1.0, 2.8);+ assert!(ends > 3.0 * beside, "ends {ends} beside {beside}");+}++#[test]+fn iron_bleeds_rust_onto_the_wall_below_it_and_not_beside_it() {+ let o = bake(&front());+ let kinds_below: Vec<Kind> = (((H - 3.9) * D) as u32..((H - 2.0) * D) as u32)+ .flat_map(|ty| ((2.85 * D) as u32..(3.55 * D) as u32).map(move |tx| (ty * AW + tx) as usize))+ .filter(|&i| o.deposit[i] > 0.0)+ .map(|i| o.kind[i])+ .collect();+ assert!(!kinds_below.is_empty(), "nothing left under the bracket");+ assert!(kinds_below.iter().all(|k| *k == Kind::Rust), "{kinds_below:?}");+ assert_eq!(sum(&o.deposit, 0.1, 0.8, 0.5, 5.5), 0.0, "rust beside the bracket");+}++#[test]+fn the_same_rain_gives_the_same_sums() {+ let (a, b) = (bake(&front()), bake(&front()));+ assert_eq!(a.flow, b.flow);+ assert_eq!(a.deposit, b.deposit);+}++#[test]+fn a_drop_on_a_face_that_drains_ends_there() {+ let mut m = front();+ for r in m.role.iter_mut() {+ if !r.walk {+ r.drains = true;+ }+ }+ let o = bake(&m);+ assert_eq!(sum(&o.flow, 0.0, W, 0.0, H), 0.0);+}diff --git a/systems/runoff/src/walk.rs b/systems/runoff/src/walk.rsnew file mode 100644index 00000000..1ea6963e--- /dev/null+++ b/systems/runoff/src/walk.rs@@ -0,0 +1,253 @@+//! One drop's walk: down a face along gravity (or along its heading on a level face), over the edge into the next+//! face, along a corner where the next face rises, off an underside or a free edge to whatever is below. What the drop+//! picks up and leaves is summed into the atlas as it goes (Acc::line).++use std::collections::HashMap;++use parry3d::glamx::Vec3;+use parry3d::query::{Ray, RayCast};++use crate::{Acc, Drop, Kind, Surface, KINDS};++const NONE: u32 = u32::MAX;+/// How far a drop at the foot of an end face looks along the edge for the wall it meets (a sill's depth and more).+pub(crate) const CAPTURE: f32 = 0.25;+/// A face whose normal points down more than this sheds what reaches it.+const UNDERSIDE: f32 = -0.2;+/// Dirt picked up a metre run, per square metre of water; the run over which half of what's carried is left.+const PICK: f32 = 0.05;+const LEAVE: f32 = 1.2;+/// Water soaked into the surface: the run over which a drop keeps 1/e of itself.+const SOAK: f32 = 8.0;+/// What a drip keeps of itself when it lands.+const SPLASH: f32 = 0.7;+const STEPS: usize = 256;+/// How far a drop strays from the fall line, either side (ASSUMED: tears under sill ends widen about 1 in 7).+const MEANDER: f32 = 0.07;+/// A run is summed in pieces this long.+const PIECE: f32 = 0.25;+const EPS: f32 = 1e-4;++/// Across each triangle's edge k (corner k to k+1): the triangle that shares it, or NONE.+pub(crate) struct Adjacency(Vec<[u32; 3]>);++impl Adjacency {+ pub(crate) fn of(s: &Surface) -> Adjacency {+ // corners within a millimetre are one point, so primitives and boxes that touch edge to edge join+ let key = |v: Vec3| ((v.x * 1e3).round() as i64, (v.y * 1e3).round() as i64, (v.z * 1e3).round() as i64);+ let mut edges: HashMap<_, Vec<(u32, usize)>> = HashMap::new();+ for (t, c) in s.tri.iter().enumerate() {+ for k in 0..3 {+ let (a, b) = (key(s.pos[c[k] as usize]), key(s.pos[c[(k + 1) % 3] as usize]));+ edges.entry(if a < b { (a, b) } else { (b, a) }).or_default().push((t as u32, k));+ }+ }+ let mut adj = vec![[NONE; 3]; s.tri.len()];+ for list in edges.values() {+ // more than two on one edge (a fin, boxes meeting): each goes on to the one that bends it least+ for &(t, k) in list {+ let n = s.nrm[t as usize];+ let best = list.iter().filter(|(o, _)| *o != t).max_by(|a, b| n.dot(s.nrm[a.0 as usize]).total_cmp(&n.dot(s.nrm[b.0 as usize])).then(b.0.cmp(&a.0)));+ if let Some(&(o, _)) = best {+ adj[t as usize][k] = o;+ }+ }+ }+ Adjacency(adj)+ }+}++fn hash(a: u32, b: u32) -> f32 {+ let mut h = a.wrapping_mul(0x9e37_79b9) ^ b.wrapping_mul(0x85eb_ca6b);+ h ^= h >> 15;+ h = h.wrapping_mul(0x2c1b_3c6d);+ h ^= h >> 12;+ (h & 0x00ff_ffff) as f32 / 16_777_216.0+}++fn corners(s: &Surface, t: u32) -> [Vec3; 3] {+ let c = s.tri[t as usize];+ [s.pos[c[0] as usize], s.pos[c[1] as usize], s.pos[c[2] as usize]]+}++/// Barycentric weights of p in t (p on its plane), and the rate each changes per metre along d.+fn bary(s: &Surface, t: u32, p: Vec3, d: Vec3) -> ([f32; 3], [f32; 3]) {+ let [a, b, c] = corners(s, t);+ let (v0, v1) = (b - a, c - a);+ let (d00, d01, d11) = (v0.dot(v0), v0.dot(v1), v1.dot(v1));+ let den = (d00 * d11 - d01 * d01).max(1e-12);+ let w = |v2: Vec3| {+ let (d20, d21) = (v2.dot(v0), v2.dot(v1));+ let (l1, l2) = ((d11 * d20 - d01 * d21) / den, (d00 * d21 - d01 * d20) / den);+ [l1, l2]+ };+ let [l1, l2] = w(p - a);+ let [r1, r2] = w(d);+ ([1.0 - l1 - l2, l1, l2], [-r1 - r2, r1, r2])+}++fn uv_at(s: &Surface, t: u32, l: [f32; 3]) -> [f32; 2] {+ let u = &s.uv[t as usize];+ [l[0] * u[0][0] + l[1] * u[1][0] + l[2] * u[2][0], l[0] * u[0][1] + l[1] * u[1][1] + l[2] * u[2][1]]+}++/// The way a drop goes on t: down the face, or along `heading` on a level one (None when it has nowhere to go).+fn downhill(s: &Surface, t: u32, up: Vec3, heading: Vec3) -> Option<Vec3> {+ let n = s.nrm[t as usize];+ let g = -up - n * n.dot(-up);+ if g.length() > 0.05 {+ return Some(g.normalize());+ }+ (heading - n * n.dot(heading)).try_normalize()+}++/// The first surface along a ray, its triangle and point, past `skip` metres.+fn cast(s: &Surface, o: Vec3, d: Vec3, far: f32) -> Option<(u32, Vec3)> {+ let h = s.mesh.cast_local_ray_and_get_normal(&Ray::new(o, d), far, false)?;+ Some((h.subshape, o + d * h.time_of_impact))+}++/// One drop, walked till it ends; its water and dirt summed into `acc`.+pub(crate) fn drop(s: &Surface, adj: &Adjacency, acc: &Acc, up: Vec3, d0: &Drop, seed: u32) {+ let (mut t, mut p, mut water) = (d0.tri, d0.p, d0.water);+ let mut load = [0f32; KINDS];+ // a level face's heading, drawn once a drop: a sill's top sends its drops off every edge by the edges' share+ let a = hash(seed, 1) * std::f32::consts::TAU;+ let side = if up.y.abs() < 0.9 { Vec3::Y } else { Vec3::X };+ let (e1, e2) = (up.cross(side).normalize(), up.cross(up.cross(side)).normalize());+ let mut heading = e1 * a.cos() + e2 * a.sin();+ let mut along: Option<Vec3> = None;+ let wander = (hash(seed, 7) * 2.0 - 1.0) * MEANDER.tan();+ for _ in 0..STEPS {+ let r = s.role[t as usize];+ if r.walk || r.drains || water < 1e-7 {+ return;+ }+ let n = s.nrm[t as usize];+ if n.dot(up) < UNDERSIDE {+ match fall(s, p + n * 0.003, up) {+ Some((t2, q)) => (t, p, water, along) = (t2, q, water * SPLASH, None),+ None => return,+ }+ continue;+ }+ let Some(dir) = along.or_else(|| downhill(s, t, up, heading)) else { return };+ // drops wander off the fall line, each its own way, so a tear widens as it runs down (MEANDER either side)+ let dir = if along.is_none() && !level(s, t, up) { (dir + n.cross(dir) * wander).normalize() } else { dir };+ // the exit: the first edge the line p + s dir crosses+ let (l, dl) = bary(s, t, p, dir);+ let mut exit: Option<(f32, usize)> = None;+ for i in 0..3 {+ if dl[i] < -EPS {+ let sd = (-l[i] / dl[i]).max(0.0);+ if exit.is_none_or(|(b, _)| sd < b) {+ exit = Some((sd, (i + 1) % 3));+ }+ }+ }+ let Some((len, edge)) = exit else { return };+ // a face carries on behind what stands on it (a wall behind its sills and string courses): what the run meets+ // head on first, just off the face, stops it there+ let o = p + n * 0.003;+ let met = cast(s, o, dir, len + 0.003).filter(|(t2, _)| *t2 != t && s.nrm[*t2 as usize].dot(dir) < -0.3);+ let (len, met) = match met {+ Some((t2, h)) => ((h - o).length().min(len), Some((t2, h + s.nrm[t2 as usize] * 0.001))),+ None => (len, None),+ };+ let q = p + dir * len;+ // what this run picks up, and what it leaves of what it carries+ // in pieces of PIECE, so a stain fades down the run rather than lying even along it+ let pieces = (len / PIECE).ceil().max(1.0) as usize;+ let at = |f: f32| [l[0] + dl[0] * len * f, l[1] + dl[1] * len * f, l[2] + dl[2] * len * f];+ for j in 0..pieces {+ let (f0, f1) = (j as f32 / pieces as f32, (j + 1) as f32 / pieces as f32);+ let step = len / pieces as f32;+ let mut left = [0f32; KINDS];+ if r.gives != Kind::None {+ load[r.gives as usize] += PICK * step * water;+ }+ let keep = (-step / LEAVE).exp();+ for k in 0..KINDS {+ left[k] = load[k] * (1.0 - keep);+ load[k] *= keep;+ }+ acc.line(uv_at(s, t, at(f0)), uv_at(s, t, at(f1)), water, &left);+ water *= (-step / SOAK).exp();+ }+ // over the edge+ let c = corners(s, t);+ let ev = (c[(edge + 1) % 3] - c[edge]).normalize_or_zero();+ let across = adj.0[t as usize][edge];+ let (next, head_on) = match met {+ Some(m) => (Some(m), true),+ None if across != NONE => (Some((across, q)), false),+ None => (probe(s, t, q, dir), true),+ };+ match next {+ Some((t2, q2)) => {+ let n2 = s.nrm[t2 as usize];+ if level(s, t2, up) && rises(s, t2, q2, up, heading) && !rises(s, t2, q2, up, -heading) {+ heading = -heading; // a ledge met from the wall above it: the drop goes off its front, not back in+ }+ if n2.dot(up) < UNDERSIDE {+ // about to drip: a wall met head on along this edge takes it into the corner, else it falls+ match capture(s, t, q, n, ev).or_else(|| fall(s, q + dir * 0.003 + n * 0.003, up)) {+ Some((t3, q3)) => (t, p, water, along) = (t3, q3, water * SPLASH, None),+ None => return,+ }+ } else if (head_on && n.dot(up) > 0.3) || rises(s, t2, q2, up, heading) {+ // the next face climbs away (a ledge meeting the wall above it): along the corner instead+ let j = n.cross(n2).normalize_or_zero();+ let sign = if j.dot(-up).abs() > 0.05 { j.dot(-up).signum() } else if j.dot(dir).abs() > 0.05 { j.dot(dir).signum() } else { 1.0 };+ if along.is_some() {+ return; // a corner's end in a corner: it pools there+ }+ along = Some(j * sign);+ p = q - dir * 0.002;+ } else {+ if along.is_some() && n.dot(n2) < 0.99 {+ along = None;+ }+ (t, p) = (t2, q2 + downhill(s, t2, up, heading).unwrap_or(dir) * 0.001);+ }+ }+ None => match capture(s, t, q, n, ev).or_else(|| fall(s, q + dir * 0.003 + n * 0.003, up)) {+ Some((t3, q3)) => (t, p, water, along) = (t3, q3, water * SPLASH, None),+ None => return,+ },+ }+ }+}++fn level(s: &Surface, t: u32, up: Vec3) -> bool {+ s.nrm[t as usize].dot(up) > 0.97+}++/// Whether a drop put on t at q would go straight back over the edge it came by (the face rises from it).+fn rises(s: &Surface, t: u32, q: Vec3, up: Vec3, heading: Vec3) -> bool {+ let Some(d) = downhill(s, t, up, heading) else { return true };+ let (l, dl) = bary(s, t, q, d);+ (0..3).any(|i| l[i] + dl[i] * 0.01 < -1e-3)+}++/// A free edge: a surface just past it, met head on (a sill's back edge against the wall behind it).+fn probe(s: &Surface, t: u32, q: Vec3, dir: Vec3) -> Option<(u32, Vec3)> {+ let n = s.nrm[t as usize];+ let (t2, h) = cast(s, q - dir * 0.01 + n * 0.002, dir, 0.04)?;+ (t2 != t && s.nrm[t2 as usize].dot(dir) < -0.3).then_some((t2, h + s.nrm[t2 as usize] * 0.001))+}++/// The foot of an end face about to drip: a wall along the edge within CAPTURE, met head on, takes the drop.+fn capture(s: &Surface, t: u32, q: Vec3, n: Vec3, ev: Vec3) -> Option<(u32, Vec3)> {+ [ev, -ev].into_iter().filter_map(|e| {+ let (t2, h) = cast(s, q + n * 0.004, e, CAPTURE)?;+ let n2 = s.nrm[t2 as usize];+ (t2 != t && n2.dot(e) < -0.5).then(|| ((h - q).length(), t2, h + n2 * 0.002))+ }).min_by(|a, b| a.0.total_cmp(&b.0)).map(|(_, t2, h)| (t2, h))+}++/// A drip falling straight down from o: what it lands on.+fn fall(s: &Surface, o: Vec3, up: Vec3) -> Option<(u32, Vec3)> {+ let (t, h) = cast(s, o, -up, 200.0)?;+ Some((t, h + up * 0.001))+}diff --git a/systems/touch/Cargo.toml b/systems/touch/Cargo.tomlnew file mode 100644index 00000000..8104e3c8--- /dev/null+++ b/systems/touch/Cargo.toml@@ -0,0 +1,10 @@+[package]+name = "raea-sys-touch"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "Where hands, feet and wheels wear a model, and where things belong on it, by rules over its materials and heights (raea/wear's touch and spots)"++[dependencies]+parry3d = "0.31"diff --git a/systems/touch/src/bands.rs b/systems/touch/src/bands.rsnew file mode 100644index 00000000..27fcb982--- /dev/null+++ b/systems/touch/src/bands.rs@@ -0,0 +1,296 @@+//! The touch rules: door leaves, treads, rails, passages and gateways (heights from docs/wear.feature WR3, ASSUMED+//! there until a measured source is read).++use std::collections::{HashMap, HashSet};++use parry3d::glamx::Vec3;+use parry3d::query::{Ray, RayCast};++use crate::{Mat, Parts, Point, Surface, band, seed};++const LEAF_W: (f32, f32) = (0.7, 1.6);+const LEAF_H: f32 = 1.9;+const LEAF_T: f32 = 0.12;+/// a leaf stands on a floor (anything level) within this under its foot+const STAND: f32 = 0.2;+/// how far a leaf may be set into a step or threshold below the floor it opens onto+const SET_IN: f32 = 0.3;+/// two leaves whose edges are this close in one plane are a pair+const PAIR_GAP: f32 = 0.08;+const HANDLE: (f32, f32) = (0.95, 1.1);+/// the handle band reaches this far in from the lock edge+const HAND_REACH: f32 = 0.3;+const KICK: f32 = 0.3;+/// the kick band's strength at the hinge edge, against 1 at the lock edge (a foot pushes beside the hand; ASSUMED)+const KICK_HINGE: f32 = 0.35;+/// a passage's faces run at least this far each way from a point on them+const DEEP: f32 = 0.3;+const TREAD_D: (f32, f32) = (0.2, 0.45);+const TREAD_W: (f32, f32) = (0.6, 4.0);+/// one step's rise, between treads of a flight+const RISE: (f32, f32) = (0.1, 0.23);+/// a single step's tread at most this over the walking surface+const FIRST_STEP: f32 = 0.26;+const RAIL_L: f32 = 0.5;+const RAIL_X: f32 = 0.12;+const RAIL_Y: (f32, f32) = (0.75, 1.2);+const SHOULDER: (f32, f32) = (1.2, 1.6);+const PASSAGE: f32 = 3.0;+const HUB: (f32, f32) = (0.4, 0.9);+const GATE: (f32, f32) = (2.2, 4.5);+/// a gateway's ceiling within this over its floor+const CEILING: f32 = 6.0;++/// A door leaf: its part, the way across it (horizontal), its span along that way and its lock edge, its facing,+/// the middle of its foot.+#[derive(Clone, Copy, Debug)]+pub(crate) struct Door {+ pub part: u32,+ pub across: Vec3,+ pub lo: f32,+ pub hi: f32,+ pub lock: f32,+ pub paired: bool,+ pub facing: Vec3,+ pub foot: Vec3,+}++fn area(s: &Surface, t: u32) -> f32 {+ let [a, b, c] = s.tri[t as usize].map(|v| s.pos[v as usize]);+ (b - a).cross(c - a).length() / 2.0+}++/// The span of a part's corners along a direction.+fn span(s: &Surface, tris: &[u32], d: Vec3) -> (f32, f32) {+ let mut r = (f32::MAX, f32::MIN);+ for &t in tris {+ for &v in &s.tri[t as usize] {+ let x = s.pos[v as usize].dot(d);+ r = (r.0.min(x), r.1.max(x));+ }+ }+ r+}++/// The drop from o to the walking surface below, through anything that isn't one.+fn drop_to_walk(s: &Surface, mut o: Vec3) -> Option<f32> {+ let start = o;+ for _ in 0..8 {+ let h = s.mesh.cast_local_ray_and_get_normal(&Ray::new(o, -s.up), 100.0, false)?;+ let q = o - s.up * h.time_of_impact;+ if s.walk[h.subshape as usize] {+ return Some((start - q).dot(s.up));+ }+ o = q - s.up * 0.01;+ }+ None+}++/// The horizontal way a set of corners runs longest, by their spread (principal axis in the level plane).+fn longest(s: &Surface, tris: &[u32]) -> Vec3 {+ let (e1, e2) = s.up.any_orthonormal_pair();+ let pts: Vec<(f32, f32)> = tris.iter().flat_map(|&t| s.tri[t as usize]).map(|v| (s.pos[v as usize].dot(e1), s.pos[v as usize].dot(e2))).collect();+ let n = pts.len().max(1) as f32;+ let (ma, mb) = pts.iter().fold((0.0, 0.0), |(a, b), p| (a + p.0 / n, b + p.1 / n));+ let (mut caa, mut cbb, mut cab) = (0.0, 0.0, 0.0);+ for (a, b) in &pts {+ caa += (a - ma) * (a - ma);+ cbb += (b - mb) * (b - mb);+ cab += (a - ma) * (b - mb);+ }+ let th = 0.5 * (2.0 * cab).atan2(caa - cbb);+ e1 * th.cos() + e2 * th.sin()+}++pub(crate) fn doors(s: &Surface, parts: &Parts) -> Vec<Door> {+ let mut out: Vec<Door> = Vec::new();+ for (k, tris) in parts.tris().iter().enumerate() {+ if tris.is_empty() || s.mat[tris[0] as usize] != Mat::Wood {+ continue;+ }+ let Some(&big) = tris.iter().filter(|&&t| s.nrm[t as usize].dot(s.up).abs() < 0.2).max_by(|&&a, &&b| area(s, a).total_cmp(&area(s, b))) else { continue };+ let n = s.nrm[big as usize];+ let facing = (n - s.up * n.dot(s.up)).normalize_or_zero();+ if facing == Vec3::ZERO {+ continue;+ }+ let across = s.up.cross(facing).normalize();+ let ((lo, hi), (y0, y1), (t0, t1)) = (span(s, tris, across), span(s, tris, s.up), span(s, tris, facing));+ if !(LEAF_W.0..=LEAF_W.1).contains(&(hi - lo)) || y1 - y0 < LEAF_H || t1 - t0 > LEAF_T {+ continue;+ }+ // it stands on a floor in front or behind, within STAND of its foot: the leaf may start under a step or a+ // threshold it is set into, so the floor is looked for from SET_IN over the foot, and the higher floor+ // found is the foot the handle's height is taken from+ let foot = across * ((lo + hi) / 2.0) + s.up * y0 + facing * ((t0 + t1) / 2.0);+ let floor = [1.0f32, -1.0]+ .iter()+ .filter_map(|&side| {+ let o = foot + facing * (side * ((t1 - t0) / 2.0 + 0.05)) + s.up * SET_IN;+ let h = s.mesh.cast_local_ray_and_get_normal(&Ray::new(o, -s.up), SET_IN + STAND + 0.05, false)?;+ (s.nrm[h.subshape as usize].dot(s.up) > 0.7).then_some(SET_IN - h.time_of_impact)+ })+ .max_by(f32::total_cmp);+ if let Some(rise) = floor {+ out.push(Door { part: k as u32, across, lo, hi, lock: f32::NAN, paired: false, facing, foot: foot + s.up * rise });+ }+ }+ // a pair: two leaves in one plane whose edges meet; their lock sides are where they meet+ let meets = |a: &Door| {+ out.iter().filter(|b| b.part != a.part).find_map(|b| {+ if a.facing.dot(b.facing).abs() < 0.95 || (b.foot - a.foot).dot(a.facing).abs() > 0.15 {+ return None;+ }+ let (c, hw) = (b.foot.dot(a.across), (b.hi - b.lo) / 2.0);+ if (c - hw - a.hi).abs() < PAIR_GAP {+ Some(a.hi)+ } else if (a.lo - (c + hw)).abs() < PAIR_GAP {+ Some(a.lo)+ } else {+ None+ }+ })+ };+ let locks: Vec<Option<f32>> = out.iter().map(meets).collect();+ for (d, m) in out.iter_mut().zip(locks) {+ (d.lock, d.paired) = match m {+ Some(l) => (l, true),+ None => (if seed(d.foot) & 1 == 0 { d.lo } else { d.hi }, false),+ };+ }+ out+}++/// A tread: a point on its middle line, the way across it and half its width.+struct Tread {+ mid: Vec3,+ along: Vec3,+ half: f32,+}++/// The treads: each part's level faces grouped by height (2 cm), each group step-sized, in a flight (another tread a+/// rise away beside it) or a single step at the walking surface.+fn treads(s: &Surface, parts: &Parts) -> (HashMap<u32, usize>, Vec<Tread>) {+ let mut groups: HashMap<(u32, i64), Vec<u32>> = HashMap::new();+ for t in 0..s.tri.len() as u32 {+ if s.nrm[t as usize].dot(s.up) > 0.9 && !s.walk[t as usize] && matches!(s.mat[t as usize], Mat::Masonry | Mat::Wood) {+ let y = s.pos[s.tri[t as usize][0] as usize].dot(s.up);+ groups.entry((parts.of[t as usize], (y * 50.0).round() as i64)).or_default().push(t);+ }+ }+ let mut keys: Vec<_> = groups.keys().copied().collect();+ keys.sort();+ let mut cands: Vec<(Tread, f32, Vec<u32>)> = Vec::new();+ for k in keys {+ let tris = &groups[&k];+ let along = longest(s, tris);+ let depth = s.up.cross(along);+ let ((a0, a1), (d0, d1)) = (span(s, tris, along), span(s, tris, depth));+ if !(TREAD_W.0..=TREAD_W.1).contains(&(a1 - a0)) || !(TREAD_D.0..=TREAD_D.1).contains(&(d1 - d0)) {+ continue;+ }+ let y = k.1 as f32 / 50.0;+ let mid = along * ((a0 + a1) / 2.0) + depth * ((d0 + d1) / 2.0) + s.up * y;+ cands.push((Tread { mid, along, half: (a1 - a0) / 2.0 }, y, tris.clone()));+ }+ let mut of = HashMap::new();+ for (i, (t, y, tris)) in cands.iter().enumerate() {+ let flight = cands.iter().any(|(u, z, _)| {+ let h = (t.mid - u.mid) - s.up * (y - z);+ (RISE.0..=RISE.1).contains(&(y - z).abs()) && h.length() < 0.7+ });+ let first = || drop_to_walk(s, t.mid + s.up * 0.01).is_some_and(|d| d <= FIRST_STEP + 0.01);+ if flight || first() {+ for &tr in tris {+ of.insert(tr, i);+ }+ }+ }+ (of, cands.into_iter().map(|c| c.0).collect())+}++/// The rails: iron or wood parts long, thin and at hand height.+fn rails(s: &Surface, parts: &Parts, doors: &[Door]) -> HashSet<u32> {+ let door: HashSet<u32> = doors.iter().map(|d| d.part).collect();+ let mut out = HashSet::new();+ for (k, tris) in parts.tris().iter().enumerate() {+ if tris.is_empty() || door.contains(&(k as u32)) || !matches!(s.mat[tris[0] as usize], Mat::Metal | Mat::Wood) {+ continue;+ }+ let along = longest(s, tris);+ let ((a0, a1), (x0, x1), (y0, y1)) = (span(s, tris, along), span(s, tris, s.up.cross(along)), span(s, tris, s.up));+ if a1 - a0 < RAIL_L || x1 - x0 > RAIL_X || y1 - y0 > RAIL_X {+ continue;+ }+ let top = along * ((a0 + a1) / 2.0) + s.up.cross(along) * ((x0 + x1) / 2.0) + s.up * (y1 + 0.01);+ if drop_to_walk(s, top).is_some_and(|d| (RAIL_Y.0..=RAIL_Y.1).contains(&d)) {+ out.insert(k as u32);+ }+ }+ out+}++/// A wall's point: the shoulder band if another wall faces it under PASSAGE away, the hub band if one faces it GATE+/// away under a ceiling.+fn walls(s: &Surface, q: &Point) -> f32 {+ let o = q.p + q.n * 0.01;+ let Some(h) = s.mesh.cast_local_ray_and_get_normal(&Ray::new(o, q.n), GATE.1, false) else { return 0.0 };+ if s.nrm[h.subshape as usize].dot(q.n) > -0.8 {+ return 0.0;+ }+ let d = h.time_of_impact;+ // people pass between the two faces only if the floor between them is walked: straight down from the middle the+ // first face is a walking surface (between a window's reveals it is the sill)+ // and only along a face as deep as a body (the side of a projecting surround is not a passage wall)+ let t = s.up.cross(q.n).normalize_or_zero();+ let deep = [1.0f32, -1.0].iter().all(|&k| {+ let o = q.p + t * (k * DEEP) + q.n * 0.05;+ s.mesh.cast_local_ray_and_get_normal(&Ray::new(o, -q.n), 0.1, false).is_some_and(|h| s.nrm[h.subshape as usize].dot(q.n) > 0.9)+ });+ if !deep {+ return 0.0;+ }+ let mid = o + q.n * (d / 2.0);+ if !s.mesh.cast_local_ray_and_get_normal(&Ray::new(mid, -s.up), 100.0, false).is_some_and(|h| s.walk[h.subshape as usize]) {+ return 0.0;+ }+ let mut v: f32 = 0.0;+ if d < PASSAGE {+ v = v.max(0.8 * band(q.ground, SHOULDER.0, SHOULDER.1, 0.05));+ }+ if (GATE.0..=GATE.1).contains(&d) && s.mesh.cast_local_ray(&Ray::new(mid, s.up), CEILING, false).is_some() {+ v = v.max(band(q.ground, HUB.0, HUB.1, 0.05));+ }+ v+}++pub(crate) fn touch(s: &Surface, parts: &Parts, doors: &[Door], pts: &[Point]) -> Vec<f32> {+ let door_of: HashMap<u32, &Door> = doors.iter().map(|d| (d.part, d)).collect();+ let (tread_of, treads) = treads(s, parts);+ let rails = rails(s, parts, doors);+ pts.iter()+ .map(|q| {+ let (t, part) = (q.tri as usize, parts.of[q.tri as usize]);+ let mut v: f32 = 0.0;+ if let Some(d) = door_of.get(&part) {+ let y = (q.p - d.foot).dot(s.up);+ let from_lock = (q.p.dot(d.across) - d.lock).abs();+ let reach = (1.0 - from_lock / HAND_REACH).clamp(0.0, 1.0);+ let kick = KICK_HINGE + (1.0 - KICK_HINGE) * (1.0 - from_lock / (d.hi - d.lo)).clamp(0.0, 1.0);+ v = v.max(band(y, HANDLE.0, HANDLE.1, 0.05) * reach).max(band(y, 0.0, KICK, 0.05) * kick);+ }+ if let Some(&i) = tread_of.get(&q.tri) {+ let tr = &treads[i];+ let x = (q.p - tr.mid).dot(tr.along) / tr.half;+ v = v.max((1.0 - x * x).max(0.0));+ }+ if rails.contains(&part) && q.n.dot(s.up) > 0.5 {+ v = 1.0;+ }+ if q.n.dot(s.up).abs() < 0.2 && matches!(s.mat[t], Mat::Plaster | Mat::Masonry) && (HUB.0 - 0.05..=SHOULDER.1 + 0.05).contains(&q.ground) {+ v = v.max(walls(s, q));+ }+ v+ })+ .collect()+}diff --git a/systems/touch/src/lib.rs b/systems/touch/src/lib.rsnew file mode 100644index 00000000..49f12e57--- /dev/null+++ b/systems/touch/src/lib.rs@@ -0,0 +1,137 @@+//! Where hands, feet and wheels wear a model, and where things belong on it (docs/wear.feature WR3), by rules over its+//! triangles' materials and heights, never placed by hand (bands.rs):+//! - a door leaf (wood, standing on the walking surface, 0.7-1.6 m wide, 1.9 m or more tall, under 0.12 m thick):+//! a handle band at 0.95-1.1 m on its lock side and a kick band at 0-0.3 m;+//! - a tread (a level face of a step, 0.2-0.45 m deep, 0.6-4 m wide, in a flight or a single step at the foot):+//! worn at its middle;+//! - a rail (iron or wood, at least 0.5 m long, under 0.12 m across, 0.75-1.2 m up): its top;+//! - walls standing under 3 m apart (a passage): the shoulder band, 1.2-1.6 m;+//! - walls 2.2-4.5 m apart under a ceiling (a gateway): hub height, 0.4-0.9 m.+//! The lock side is where two leaves meet (a pair); a single leaf's is picked by a seed from its place, as the model+//! says nothing of hinges (ASSUMED). Spots (spots.rs) are where the rules say a thing belongs, each with who put it+//! there. Pure: the same input gives the same output.++mod bands;+mod spots;+#[cfg(test)]+mod tests;++use std::collections::HashMap;++use parry3d::glamx::Vec3;+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";++/// What a triangle is made of, as far as touch goes.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum Mat {+ Plaster,+ /// brick, sandstone, granite+ Masonry,+ Wood,+ /// iron+ Metal,+ Other,+}++/// The model: positions, triangles, their planes' normals, materials and which are walking surfaces, the BVH over+/// them (its subshapes are the triangles) and which way is up.+pub struct Surface<'a> {+ pub pos: &'a [Vec3],+ pub tri: &'a [[u32; 3]],+ pub nrm: &'a [Vec3],+ pub mat: &'a [Mat],+ pub walk: &'a [bool],+ pub mesh: &'a TriMesh,+ pub up: Vec3,+}++/// A point to mark (an atlas texel): where it is, its face's normal and triangle, and what the other cause maps say+/// there: the drop to the walking surface below (metres), the rain's reach (0-1), the run-off passing (0-1, as the+/// flow map stores it) and the nearness to a convex arris (0-1).+#[derive(Clone, Copy, Debug)]+pub struct Point {+ pub p: Vec3,+ pub n: Vec3,+ pub tri: u32,+ pub ground: f32,+ pub rain: f32,+ pub flow: f32,+ pub edge: f32,+}++/// Touch at each point (0-1) and the spots, from the rules.+pub fn mark(s: &Surface, pts: &[Point]) -> (Vec<f32>, Vec<Spot>) {+ let parts = Parts::of(s);+ let doors = bands::doors(s, &parts);+ let touch = bands::touch(s, &parts, &doors, pts);+ let spots = spots::spots(s, &doors, pts);+ (touch, spots)+}++/// The parts: triangles of one material joined by shared corners (welded at a millimetre).+pub(crate) struct Parts {+ pub of: Vec<u32>,+ pub n: usize,+}++impl Parts {+ pub fn of(s: &Surface) -> Parts {+ let mut up: Vec<u32> = (0..s.tri.len() as u32).collect();+ fn root(up: &mut [u32], mut i: u32) -> u32 {+ while up[i as usize] != i {+ up[i as usize] = up[up[i as usize] as usize];+ i = up[i as usize];+ }+ i+ }+ let mut first: HashMap<(i64, i64, i64, Mat), u32> = HashMap::new();+ for (t, tri) in s.tri.iter().enumerate() {+ for &v in tri {+ let q = s.pos[v as usize] * 1000.0;+ let k = (q.x.round() as i64, q.y.round() as i64, q.z.round() as i64, s.mat[t]);+ let f = *first.entry(k).or_insert(t as u32);+ let (a, b) = (root(&mut up, f), root(&mut up, t as u32));+ if a != b {+ up[a.max(b) as usize] = a.min(b);+ }+ }+ }+ let mut ids = HashMap::new();+ let of = (0..s.tri.len() as u32).map(|t| {+ let r = root(&mut up, t);+ let n = ids.len() as u32;+ *ids.entry(r).or_insert(n)+ }).collect();+ Parts { of, n: ids.len() }+ }++ /// Each part's triangles.+ pub fn tris(&self) -> Vec<Vec<u32>> {+ let mut out = vec![Vec::new(); self.n];+ for (t, &p) in self.of.iter().enumerate() {+ out[p as usize].push(t as u32);+ }+ out+ }+}++/// A seed from a place, the same on every machine (the lock side of a single leaf).+pub(crate) 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)] {+ h = (h ^ v).wrapping_mul(0x0100_0000_01b3);+ }+ h+}++/// 1 inside [a, b], easing to 0 over `soft` outside it.+pub(crate) fn band(v: f32, a: f32, b: f32, soft: f32) -> f32 {+ let d = (a - v).max(v - b).max(0.0);+ (1.0 - d / soft).clamp(0.0, 1.0)+}diff --git a/systems/touch/src/spots.rs b/systems/touch/src/spots.rsnew file mode 100644index 00000000..e5c91fdf--- /dev/null+++ b/systems/touch/src/spots.rs@@ -0,0 +1,167 @@+//! Where the rules say a thing belongs, each with who put it there (docs/wear.feature WR3). The sizes are ASSUMED+//! until a source is read:+//! - bills (the bill poster): on plain walls (no opening within PLAIN) the rain doesn't reach, 0.5-2.5 m up,+//! 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).+//! 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;++use parry3d::glamx::Vec3;+use parry3d::query::{Ray, RayCast};++use crate::bands::Door;+use crate::{Mat, Point, Surface, seed};++/// A thing a rule says belongs here: what, who put it there, its middle, the face it's on, its size (across, up).+#[derive(Clone, Debug, PartialEq)]+pub struct Spot {+ pub what: &'static str,+ pub by: &'static str,+ pub at: Vec3,+ pub n: Vec3,+ pub size: [f32; 2],+}++const BILL: [f32; 2] = [0.6, 0.85];+const GAP_BILL: f32 = 3.0;+/// a bill's wall has no opening this far across either way+const PLAIN: f32 = 3.0;+const PLATE: [f32; 2] = [0.6, 0.18];+/// an arris's points within this across belong to one corner; plates on one face of a corner this far apart at least+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+const SKY_FAR: f32 = 200.0;++fn standing(s: &Surface, q: &Point) -> bool {+ q.n.dot(s.up).abs() < 0.2+}++fn open(s: &Surface, p: Vec3, n: Vec3, far: f32) -> bool {+ s.mesh.cast_local_ray(&Ray::new(p + n * 0.01, n), far, false).is_none()+}++/// How many of a fixed fan of rays out of a face reach the sky (none hit within SKY_FAR): three elevations by three+/// bearings across the face's front, and straight up.+fn sky(s: &Surface, p: Vec3, n: Vec3) -> usize {+ let across = s.up.cross(n).normalize_or_zero();+ let mut dirs = vec![s.up];+ for el in [15f32, 40.0, 65.0] {+ for az in [-60f32, 0.0, 60.0] {+ let (el, az) = (el.to_radians(), az.to_radians());+ dirs.push((n * az.cos() + across * az.sin()) * el.cos() + s.up * el.sin());+ }+ }+ dirs.iter().filter(|&&d| s.mesh.cast_local_ray(&Ray::new(p + n * 0.05, d), SKY_FAR, false).is_none()).count()+}++/// The face at p is plain wall for PLAIN across each way and from 0.5 m below to 2.5 m above: every ray into it meets+/// plaster or masonry within 0.15 m of its plane (a door, a window, a sill or a recess there is an opening).+fn plain(s: &Surface, p: Vec3, n: Vec3) -> bool {+ let (t, plane) = (s.up.cross(n).normalize_or_zero(), p.dot(n));+ let steps = (PLAIN / 0.5) as i32;+ (-steps..=steps).all(|i| {+ (0..7).all(|j| {+ let o = p + t * (i as f32 * 0.5) + s.up * (j as f32 * 0.5 - 0.5) + n * 0.5;+ s.mesh.cast_local_ray_and_get_normal(&Ray::new(o, -n), 0.8, false).is_some_and(|h| {+ matches!(s.mat[h.subshape as usize], Mat::Plaster | Mat::Masonry) && ((o - n * h.time_of_impact).dot(n) - plane).abs() < 0.15+ })+ })+ })+}++/// Keep candidates in seed order, none nearer than `gap` to one kept.+fn thin(c: Vec<Spot>, gap: f32) -> Vec<Spot> {+ thin_if(c, gap, |_| true)+}++/// As thin, keeping only candidates that pass `ok` (tested only on those the gap leaves).+fn thin_if(mut c: Vec<Spot>, gap: f32, ok: impl Fn(&Spot) -> bool) -> Vec<Spot> {+ c.sort_by_key(|s| seed(s.at));+ let mut kept: Vec<Spot> = Vec::new();+ for s in c {+ if kept.iter().all(|k| (k.at - s.at).length() >= gap) && ok(&s) {+ kept.push(s);+ }+ }+ kept+}++pub(crate) fn spots(s: &Surface, doors: &[Door], pts: &[Point]) -> Vec<Spot> {+ let wall = |q: &Point| matches!(s.mat[q.tri as usize], Mat::Plaster | Mat::Masonry) && standing(s, q);+ let mut out = Vec::new();++ // bills: centred 0.95-2.05 m up, so the sheet stays within 0.5-2.5 m, on a plain wall (a firewall, a lot's wall, a+ // hoarding): Berlin's columns (Litfaß, from 1855) were brought in to keep bills off house fronts+ let bills = pts.iter().filter(|q| wall(q) && q.rain < 0.35 && (0.95..=2.05).contains(&q.ground) && open(s, q.p, q.n, OPEN));+ let bills: Vec<Spot> = bills.map(|q| Spot { what: "bill", by: "bill poster", at: q.p, n: q.n, size: BILL }).collect();+ out.extend(thin_if(bills, GAP_BILL, |b| plain(s, b.at, b.n)));++ // street plates: on a corner whose arris runs up from the walking surface past 3.5 m (the arris points within+ // CORNER across the level plane fill every 0.5 m of height to there), where a second face of the corner has a+ // candidate too and both look onto open ground; one per face of each corner+ let (e1, e2) = s.up.any_orthonormal_pair();+ let flat = |p: Vec3| (p.dot(e1), p.dot(e2));+ let cell = |p: Vec3| ((flat(p).0 / CORNER).floor() as i64, (flat(p).1 / CORNER).floor() as i64);+ let mut arris: BTreeMap<(i64, i64), Vec<&Point>> = BTreeMap::new();+ for q in pts.iter().filter(|q| wall(q) && q.edge > 0.8 && q.ground < 4.0) {+ arris.entry(cell(q.p)).or_default().push(q);+ }+ let near = |p: Vec3| {+ let (c, (x, y)) = (cell(p), flat(p));+ (-1..=1).flat_map(move |i| (-1..=1).map(move |j| (c.0 + i, c.1 + j))).flat_map(|k| arris.get(&k).into_iter().flatten()).filter(move |q| {+ let (a, b) = flat(q.p);+ (a - x).hypot(b - y) <= CORNER+ })+ };+ let tall = |p: Vec3| {+ let bins: std::collections::BTreeSet<i64> = near(p).map(|q| (q.ground * 2.0).floor() as i64).collect();+ (0..7).all(|b| bins.contains(&b))+ };+ let cands: Vec<&Point> = arris.values().flatten().copied().filter(|q| (2.5..=3.0).contains(&q.ground) && tall(q.p) && open(s, q.p, q.n, OPEN * 2.0)).collect();+ let mut by_face: BTreeMap<(i64, i64, i64), Vec<Spot>> = BTreeMap::new();+ for q in cands.iter().filter(|q| cands.iter().any(|r| r.n.dot(q.n) < 0.5 && (r.p - q.p).length() <= CORNER * 2.0)) {+ let k = ((q.n.x * 4.0).round() as i64, (q.n.y * 4.0).round() as i64, (q.n.z * 4.0).round() as i64);+ by_face.entry(k).or_default().push(Spot { what: "street plate", by: "city", at: q.p, n: q.n, size: PLATE });+ }+ for spots in by_face.into_values() {+ out.extend(thin(spots, GAP_PLATE));+ }++ // nameplates: beside a single leaf's lock edge, on whichever side of the leaf looks onto open ground+ for d in doors.iter().filter(|d| !d.paired) {+ let out_of = if d.lock >= d.hi - 1e-4 { 1.0 } else { -1.0 };+ let beside = d.foot + d.across * (d.lock - d.foot.dot(d.across) + out_of * (0.05 + NAMEPLATE[0] / 2.0 + 0.1)) + s.up * 1.5;+ // the outside: of the two wall faces beside the leaf, the one that sees more sky (a hall sees none; a+ // balcony or a hood over a street door hides only part of it)+ let face = |side: Vec3| {+ let o = beside + side * 1.0;+ let h = s.mesh.cast_local_ray_and_get_normal(&Ray::new(o, -side), 1.5, false)?;+ let (n, at) = (s.nrm[h.subshape as usize], o - side * h.time_of_impact);+ let ok = n.dot(side) > 0.8 && matches!(s.mat[h.subshape as usize], Mat::Plaster | Mat::Masonry) && open(s, at, n, OPEN);+ ok.then(|| (sky(s, at, n), at, n))+ };+ let best = [d.facing, -d.facing].into_iter().filter_map(face).max_by(|a, b| a.0.cmp(&b.0));+ if let Some((_, at, n)) = best.filter(|b| b.0 > 0) {+ out.push(Spot { what: "nameplate", by: "tenant", at, n, size: NAMEPLATE });+ }+ }++ // 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/touch/src/tests.rs b/systems/touch/src/tests.rsnew file mode 100644index 00000000..5e2c6811--- /dev/null+++ b/systems/touch/src/tests.rs@@ -0,0 +1,248 @@+//! Synthetic fronts: a door in a wall, a pair of leaves, a flight of steps beside a sill, a passage and a gateway, a+//! rail. Points are sampled on faces 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 crate::{Mat, Point, Spot, Surface, mark};++#[derive(Default)]+struct B {+ pos: Vec<Vec3>,+ tri: Vec<[u32; 3]>,+ nrm: Vec<Vec3>,+ mat: Vec<Mat>,+ walk: Vec<bool>,+}++impl B {+ /// A quad facing `out`, its corners in order around it.+ 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 ground(mut self) -> B {+ let v = |x: f32, z: f32| Vec3::new(x, 0.0, z);+ self.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);+ self+ }+ 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 }+ }+}++/// The point on the face at p looking along n (its triangle found by a ray from just in front).+fn at(mesh: &TriMesh, p: Vec3, n: Vec3) -> Point {+ let h = mesh.cast_local_ray_and_get_normal(&Ray::new(p + n * 0.02, -n), 0.05, false).expect("a face at the point");+ Point { p, n, tri: h.subshape, ground: p.y, rain: 1.0, flow: 0.0, edge: 0.0 }+}++/// A wall with a door opening 1.1 m wide and 2.3 m high at x = 0, its front at z = 0.+fn front(b: &mut B, half: f32) {+ b.cube([-6.0, 0.0, -0.5], [-half, 8.0, 0.0], Mat::Plaster);+ b.cube([half, 0.0, -0.5], [6.0, 8.0, 0.0], Mat::Plaster);+ b.cube([-half, 2.3, -0.5], [half, 8.0, 0.0], Mat::Plaster);+}++/// The leaf's front face, every 5 cm.+fn leaf_face(mesh: &TriMesh, x0: f32, x1: f32) -> Vec<Point> {+ let mut out = Vec::new();+ let mut x = x0 + 0.025;+ while x < x1 {+ for j in 0..44 {+ out.push(at(mesh, Vec3::new(x, 0.025 + j as f32 * 0.05, -0.25), Vec3::Z));+ }+ x += 0.05;+ }+ out+}++#[test]+fn handle_band_lands_on_the_lock_side_and_nowhere_else() {+ let mut b = B::default();+ front(&mut b, 0.55);+ b.cube([-0.5, 0.0, -0.3], [0.5, 2.25, -0.25], Mat::Wood);+ let b = b.ground();+ let mesh = b.mesh();+ let s = b.surface(&mesh);+ let mut pts = leaf_face(&mesh, -0.5, 0.5);+ let wall: Vec<Point> = (0..20).map(|j| at(&mesh, Vec3::new(3.0, 0.05 + j as f32 * 0.1, 0.0), Vec3::Z)).collect();+ pts.extend(&wall);+ let (touch, spots) = mark(&s, &pts);+ let held = |side: f32| pts.iter().zip(&touch).any(|(q, &v)| v > 0.5 && (0.9..1.15).contains(&q.p.y) && q.p.x * side > 0.2);+ assert!(held(1.0) != held(-1.0), "the handle band on exactly one side");+ let lock = if held(1.0) { 1.0 } else { -1.0 };+ for (q, &v) in pts.iter().zip(&touch) {+ let y = q.p.y;+ if q.p.z < -0.1 && y < 0.25 {+ let from_lock = 0.5 - q.p.x * lock;+ assert!(v > 0.3 && (from_lock > 0.2 || v > 0.85), "kick band at {:?}: {v}", q.p);+ }+ if (0.4..0.85).contains(&y) || y > 1.2 || q.p.z > -0.1 {+ assert_eq!(v, 0.0, "nothing at {:?}", q.p);+ }+ }+ let names: Vec<&Spot> = spots.iter().filter(|s| s.what == "nameplate").collect();+ assert_eq!(names.len(), 1);+ assert!(names[0].at.x * lock > 0.5 && (names[0].at.y - 1.5).abs() < 0.01, "the nameplate beside the lock side: {:?}", names[0].at);+}++#[test]+fn a_pair_of_leaves_is_held_where_they_meet() {+ let mut b = B::default();+ front(&mut b, 1.05);+ b.cube([-1.0, 0.0, -0.3], [-0.005, 2.25, -0.25], Mat::Wood);+ b.cube([0.005, 0.0, -0.3], [1.0, 2.25, -0.25], Mat::Wood);+ let b = b.ground();+ let mesh = b.mesh();+ let pts = leaf_face(&mesh, -1.0, 1.0);+ let (touch, _) = mark(&b.surface(&mesh), &pts);+ for (q, &v) in pts.iter().zip(&touch) {+ if (0.95..=1.1).contains(&q.p.y) {+ assert_eq!(v > 0.0, q.p.x.abs() < 0.3, "at {:?}: {v}", q.p);+ }+ }+}++#[test]+fn treads_wear_at_the_middle_and_a_sill_does_not() {+ let mut b = B::default();+ for i in 0..3 {+ b.cube([-0.75, 0.0, -0.3 * (i + 1) as f32], [0.75, 0.17 * (i + 1) as f32, -0.3 * i as f32], Mat::Masonry);+ }+ b.cube([3.0, 0.9, 0.0], [4.2, 0.97, 0.25], Mat::Masonry);+ let b = b.ground();+ let mesh = b.mesh();+ let pts = vec![+ at(&mesh, Vec3::new(0.0, 0.34, -0.45), Vec3::Y),+ at(&mesh, Vec3::new(0.7, 0.34, -0.45), Vec3::Y),+ at(&mesh, Vec3::new(0.0, 0.17, -0.15), Vec3::Y),+ at(&mesh, Vec3::new(3.6, 0.97, 0.12), Vec3::Y),+ ];+ let (touch, _) = mark(&b.surface(&mesh), &pts);+ assert!(touch[0] > 0.9 && touch[2] > 0.9, "middles worn: {touch:?}");+ assert!(touch[1] < 0.3, "the end barely: {touch:?}");+ assert_eq!(touch[3], 0.0, "the sill isn't a tread");+}++#[test]+fn passage_shoulders_and_gateway_hubs() {+ let walls = |roof: bool| {+ let mut b = B::default();+ b.cube([-1.55, 0.0, -5.0], [-1.25, 4.0, 5.0], Mat::Masonry);+ b.cube([1.25, 0.0, -5.0], [1.55, 4.0, 5.0], Mat::Masonry);+ if roof {+ b.cube([-1.55, 4.0, -5.0], [1.55, 4.3, 5.0], Mat::Plaster);+ }+ b.ground()+ };+ for roof in [false, true] {+ let b = walls(roof);+ let mesh = b.mesh();+ let pts: Vec<Point> = [0.6, 1.0, 1.4].iter().map(|&y| at(&mesh, Vec3::new(-1.25, y, 0.0), Vec3::X)).collect();+ let (touch, _) = mark(&b.surface(&mesh), &pts);+ assert!((touch[2] - 0.8).abs() < 1e-4, "shoulder: {touch:?}");+ assert_eq!(touch[1], 0.0);+ assert_eq!(touch[0], if roof { 1.0 } else { 0.0 }, "hub only under a ceiling");+ }+}++#[test]+fn a_rails_top_is_held() {+ let mut b = B::default();+ b.cube([-1.0, 0.9, 2.0], [1.0, 0.95, 2.05], Mat::Metal);+ let b = b.ground();+ let mesh = b.mesh();+ let pts = vec![at(&mesh, Vec3::new(0.3, 0.95, 2.025), Vec3::Y), at(&mesh, Vec3::new(0.3, 0.92, 2.05), Vec3::Z)];+ let (touch, _) = mark(&b.surface(&mesh), &pts);+ assert_eq!(touch, vec![1.0, 0.0]);+}++#[test]+fn street_plates_on_a_corner_and_the_same_twice() {+ let mut b = B::default();+ b.cube([-6.0, 0.0, -8.0], [0.0, 8.0, 0.0], Mat::Plaster);+ let b = b.ground();+ let mesh = b.mesh();+ let mut pts = Vec::new();+ for j in 0..16 {+ let y = 0.125 + j as f32 * 0.25;+ for (p, n) in [(Vec3::new(-0.1, y, 0.0), Vec3::Z), (Vec3::new(0.0, y, -0.1), Vec3::X)] {+ pts.push(Point { edge: 1.0, rain: 0.2, ..at(&mesh, p, n) });+ }+ }+ let (_, spots) = mark(&b.surface(&mesh), &pts);+ let plates: Vec<&Spot> = spots.iter().filter(|s| s.what == "street plate").collect();+ assert_eq!(plates.len(), 2, "{spots:?}");+ assert!(plates.iter().all(|p| (2.5..=3.0).contains(&p.at.y) && p.by == "city"));+ assert!(spots.iter().filter(|s| s.what == "bill").all(|s| (0.95..=2.05).contains(&s.at.y)));+ assert_eq!(mark(&b.surface(&mesh), &pts).1, spots, "the same input, the same spots");+}++#[test]+fn a_leaf_set_into_a_step_is_held_from_the_step() {+ let mut b = B::default();+ front(&mut b, 0.55);+ b.cube([-0.5, 0.0, -0.3], [0.5, 2.25, -0.25], Mat::Wood);+ b.cube([-0.8, 0.0, -0.25], [0.8, 0.17, 0.4], Mat::Masonry);+ let b = b.ground();+ let mesh = b.mesh();+ let pts = leaf_face(&mesh, -0.5, 0.5);+ let (touch, _) = mark(&b.surface(&mesh), &pts);+ let band = |y0: f32, y1: f32| pts.iter().zip(&touch).any(|(q, &v)| v > 0.5 && q.p.x.abs() > 0.2 && (y0..y1).contains(&q.p.y));+ assert!(band(1.13, 1.26), "the handle band from the step's top");+ assert!(!band(0.95, 1.05), "not from the leaf's buried foot");+}++#[test]+fn a_windows_reveals_are_not_a_passage() {+ let mut b = B::default();+ b.cube([-3.0, 0.0, -0.5], [-0.6, 3.0, 0.0], Mat::Plaster);+ b.cube([0.6, 0.0, -0.5], [3.0, 3.0, 0.0], Mat::Plaster);+ b.cube([-0.6, 0.0, -0.5], [0.6, 0.9, 0.0], Mat::Plaster);+ b.cube([-0.65, 0.85, -0.5], [0.65, 0.9, 0.15], Mat::Masonry);+ let b = b.ground();+ let mesh = b.mesh();+ let pts: Vec<Point> = [1.0, 1.3, 1.5].iter().map(|&y| at(&mesh, Vec3::new(-0.6, y, -0.25), Vec3::X)).collect();+ let (touch, _) = mark(&b.surface(&mesh), &pts);+ assert_eq!(touch, vec![0.0; 3], "a window's reveals aren't a passage");+}++#[test]+fn bills_go_on_plain_walls_not_beside_a_door() {+ let mut b = B::default();+ front(&mut b, 0.55);+ b.cube([-0.5, 0.0, -0.3], [0.5, 2.25, -0.25], Mat::Wood);+ b.cube([10.0, 0.0, -0.5], [20.0, 4.0, 0.0], Mat::Masonry);+ let b = b.ground();+ let mesh = b.mesh();+ let mut pts = Vec::new();+ for x in [-5.0f32, -4.0, -3.0, -2.0, -1.0, 1.0, 2.0, 3.0, 4.0, 5.0, 11.0, 13.0, 15.0, 17.0, 19.0] {+ pts.push(Point { rain: 0.1, ..at(&mesh, Vec3::new(x, 1.5, 0.0), Vec3::Z) });+ }+ let (_, spots) = mark(&b.surface(&mesh), &pts);+ let bills: Vec<&Spot> = spots.iter().filter(|s| s.what == "bill").collect();+ assert!(!bills.is_empty() && bills.iter().all(|s| s.at.x > 12.9 && s.at.x < 17.1), "{bills:?}");+}diff --git a/systems/weathering/Cargo.toml b/systems/weathering/Cargo.tomlnew file mode 100644index 00000000..f23d2e43--- /dev/null+++ b/systems/weathering/Cargo.toml@@ -0,0 +1,19 @@+[package]+name = "raea-sys-weathering"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "Cause maps baked from a glTF's geometry (rain, run-off, shelter, sun, damp, touch) for raea/wear"++[dependencies]+# triangle BVH and ray casts (Apache-2.0); in the tree already through rapier3d+parry3d = "0.31"+rayon = "1"+serde_json = "1"+sha2 = "0.10"+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-glb = { path = "../glb" }diff --git a/systems/weathering/src/charts.rs b/systems/weathering/src/charts.rsnew file mode 100644index 00000000..fbc498b7--- /dev/null+++ b/systems/weathering/src/charts.rs@@ -0,0 +1,429 @@+//! Planar charts and their shelf packing, and each texel's point on the surface. A chart is a primitive's triangles+//! joined across shared edges (positions welded to a millimetre, so flat-shaded faces with their own vertices still+//! join) while each stays within CHART_DEG of the first one's plane, projected on that plane: on a wall the atlas's+//! rows run down the wall (s along it, t down it), so the fall line is the same way in every chart. Charts are packed+//! on shelves at `density` texels a metre with a GUTTER each side, after merge.rs has joined the coplanar ones that+//! touch and folded the details too small for texels of their own into the charts they sit on; when the atlas would+//! pass `max_side`, the density is lowered until it fits (the result says which). Every texel a chart covers gets the world point and triangle+//! under its centre; texels within 0.75 of a texel of the chart's edge get the nearest point on it, so a bilinear+//! read at an edge reads the surface.++use std::collections::HashMap;++use parry3d::glamx::Vec3;++use super::{Env, 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;+const CHART_DEG: f32 = 15.0;+const NONE: u32 = u32::MAX;++pub(crate) struct Texel {+ pub x: u16,+ pub y: u16,+ pub p: Vec3,+ pub n: Vec3,+ pub tri: u32,+}++pub(crate) struct Atlas {+ pub w: u32,+ pub h: u32,+ /// the density the whole-model class got, and each chart's+ pub density: f32,+ pub chart_dens: Vec<f32>,+ pub charts: usize,+ /// triangles inside a closed shell, given no texels+ pub hidden: usize,+ pub texels: Vec<Texel>,+ /// per triangle, its chart+ pub chart_of: Vec<u32>,+ /// per primitive: each new vertex's source vertex (the primitive's own numbering), the new indices and TEXCOORD_1+ pub verts: Vec<Vec<u32>>,+ 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]>,+}++impl Atlas {+ pub fn covered(&self) -> Vec<bool> {+ let mut c = vec![false; (self.w * self.h) as usize];+ for t in &self.texels {+ c[t.y as usize * self.w as usize + t.x as usize] = true;+ }+ c+ }+}++pub(crate) struct Chart {+ pub tris: Vec<u32>,+ /// the plane: its normal, its offset (n.p), and the basis across it+ pub n: Vec3,+ pub off: f32,+ pub u: Vec3,+ pub b: Vec3,+ pub s0: f32,+ pub t0: f32,+ pub s1: f32,+ pub t1: f32,+ /// texels a metre asked for it (the highest its own surfaces ask), before the atlas's scale+ pub dens: f32,+ w: u32,+ h: u32,+ ox: u32,+ oy: u32,+}++impl Chart {+ pub fn new(tris: Vec<u32>, n: Vec3, off: f32, (u, b): (Vec3, Vec3), sc: &Scene, up: Vec3) -> Chart {+ let mut c = Chart { tris, n, off, u, b, s0: 0.0, t0: 0.0, s1: 0.0, t1: 0.0, dens: 0.0, w: 0, h: 0, ox: 0, oy: 0 };+ c.orient(sc, up);+ c+ }+ /// A level chart turned in its plane to its smallest rectangle (a sliver of street running across the tile, a+ /// wire's run); a wall keeps its rows down the fall line. Then fitted.+ pub fn orient(&mut self, sc: &Scene, up: Vec3) {+ if self.n == Vec3::ZERO || self.n.dot(up).abs() < 0.95 {+ return self.fit(sc);+ }+ let pts: Vec<(f32, f32)> = self.tris.iter().flat_map(|&t| sc.tri[t as usize]).map(|v| (sc.pos[v as usize].dot(self.u), sc.pos[v as usize].dot(self.b))).collect();+ let h = hull(pts);+ let mut best = (f32::MAX, 0.0f32);+ for i in 0..h.len() {+ let (a, b) = (h[i], h[(i + 1) % h.len()]);+ let th = (b.1 - a.1).atan2(b.0 - a.0);+ let (c, s) = (th.cos(), th.sin());+ let (mut lo, mut hi) = ((f32::MAX, f32::MAX), (f32::MIN, f32::MIN));+ for p in &h {+ let (x, y) = (p.0 * c + p.1 * s, p.1 * c - p.0 * s);+ lo = (lo.0.min(x), lo.1.min(y));+ hi = (hi.0.max(x), hi.1.max(y));+ }+ let area = (hi.0 - lo.0) * (hi.1 - lo.1);+ if area < best.0 * (1.0 - 1e-5) {+ best = (area, th);+ }+ }+ let (c, s) = (best.1.cos(), best.1.sin());+ (self.u, self.b) = (self.u * c + self.b * s, self.b * c - self.u * s);+ self.fit(sc);+ }+ /// Its rectangle in the plane, from its triangles.+ pub fn fit(&mut self, sc: &Scene) {+ (self.s0, self.t0, self.s1, self.t1) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);+ for &t in &self.tris {+ for v in sc.tri[t as usize] {+ let (s, tt) = self.st(sc.pos[v as usize]);+ self.s0 = self.s0.min(s);+ self.s1 = self.s1.max(s);+ self.t0 = self.t0.min(tt);+ self.t1 = self.t1.max(tt);+ }+ }+ }+ /// The density its surfaces ask: the highest of their classes'.+ pub fn asked(&self, sc: &Scene, env: &Env) -> 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) {+ (p.dot(self.u), -p.dot(self.b))+ }+ /// atlas texel coordinates (continuous: texel i covers [i, i+1)) of a world point on this chart+ fn xy(&self, p: Vec3, k: f32) -> (f32, f32) {+ let (s, t, d) = (self.st(p).0, self.st(p).1, self.dens * k);+ (self.ox as f32 + GUTTER as f32 + (s - self.s0) * d, self.oy as f32 + GUTTER as f32 + (t - self.t0) * d)+ }+}++fn weld(p: Vec3) -> (i64, i64, i64) {+ ((p.x * 1000.0).round() as i64, (p.y * 1000.0).round() as i64, (p.z * 1000.0).round() as 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) {+ let u = if n.dot(env.up).abs() < 0.95 {+ env.up.cross(n).normalize()+ } else {+ let east = env.north.cross(env.up).normalize();+ (east - n * east.dot(n)).normalize()+ };+ (u, n.cross(u).normalize())+}++fn charts_of(sc: &Scene, env: &Env, chart_of: &mut [u32]) -> Vec<Chart> {+ let cos = CHART_DEG.to_radians().cos();+ let mut out = Vec::new();+ for pr in &sc.prims {+ let tris = pr.first_tri..pr.first_tri + pr.tris;+ let mut ids: HashMap<(i64, i64, i64), u32> = HashMap::new();+ let mut edges: HashMap<(u32, u32), Vec<u32>> = HashMap::new();+ let welded: Vec<[u32; 3]> = tris+ .clone()+ .map(|t| {+ sc.tri[t].map(|v| {+ let n = ids.len() as u32;+ *ids.entry(weld(sc.pos[v as usize])).or_insert(n)+ })+ })+ .collect();+ for (k, w) in welded.iter().enumerate() {+ for e in 0..3 {+ let (a, b) = (w[e], w[(e + 1) % 3]);+ edges.entry((a.min(b), a.max(b))).or_default().push((pr.first_tri + k) as u32);+ }+ }+ for seed in tris.clone() {+ if chart_of[seed] != NONE {+ continue;+ }+ let id = out.len() as u32;+ chart_of[seed] = id;+ let n = sc.nrm[seed];+ let mut list = vec![seed as u32];+ let mut q = vec![seed];+ while let Some(t) = q.pop() {+ if n == Vec3::ZERO {+ break;+ }+ let w = welded[t - pr.first_tri];+ for e in 0..3 {+ let (a, b) = (w[e], w[(e + 1) % 3]);+ for &o in &edges[&(a.min(b), a.max(b))] {+ let o = o as usize;+ if chart_of[o] == NONE && sc.nrm[o].dot(n) >= cos {+ chart_of[o] = id;+ list.push(o as u32);+ q.push(o);+ }+ }+ }+ }+ list.sort_unstable();+ let (u, b) = if n == Vec3::ZERO { (Vec3::X, Vec3::Y) } else { basis(n, env) };+ let off = if n == Vec3::ZERO { 0.0 } else { n.dot(sc.pos[sc.tri[seed][0] as usize]) };+ out.push(Chart::new(list, n, off, (u, b), sc, env.up));+ }+ }+ out+}++/// Shelves, tallest charts first; the atlas's height, or None when a chart is wider than the side.+fn pack(cs: &mut [Chart], k: f32, side: u32) -> Option<(u32, u32)> {+ for c in cs.iter_mut() {+ let d = c.dens * k;+ c.w = (((c.s1 - c.s0) * d).ceil() as u32).max(1) + 2 * GUTTER;+ c.h = (((c.t1 - c.t0) * d).ceil() as u32).max(1) + 2 * GUTTER;+ }+ let area: f64 = cs.iter().map(|c| c.w as f64 * c.h as f64).sum();+ let widest = cs.iter().map(|c| c.w).max().unwrap_or(1);+ if widest > side {+ return None;+ }+ let w = ((area * 1.2).sqrt().ceil() as u32).next_power_of_two().clamp(64, side).max(widest);+ let mut order: Vec<usize> = (0..cs.len()).collect();+ order.sort_by(|&a, &b| cs[b].h.cmp(&cs[a].h).then(cs[b].w.cmp(&cs[a].w)).then(a.cmp(&b)));+ let (mut x, mut y, mut shelf) = (0u32, 0u32, 0u32);+ for i in order {+ if x + cs[i].w > w {+ y += shelf;+ x = 0;+ shelf = 0;+ }+ cs[i].ox = x;+ cs[i].oy = y;+ x += cs[i].w;+ shelf = shelf.max(cs[i].h);+ }+ Some((w, (y + shelf).div_ceil(4) * 4))+}++pub(crate) fn build(sc: &Scene, env: &Env, 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);+ for (t, &h) in inside.iter().enumerate() {+ if h {+ chart_of[t] = NONE - 1;+ }+ }+ let cs = charts_of(sc, env, &mut chart_of);+ let mut cs = merge::absorb(merge::split(merge::merge(cs, sc, env.up), sc, env), sc, env);+ // the hidden triangles share one texel, which stays empty (zero in every cause)+ let hidden: Vec<u32> = (0..sc.tri.len() as u32).filter(|&t| inside[t as usize]).collect();+ let hid = (!hidden.is_empty()).then(|| {+ let mut c = Chart::new(hidden.clone(), Vec3::ZERO, 0.0, (Vec3::X, Vec3::Y), sc, env.up);+ (c.s0, c.t0, c.s1, c.t1, c.dens) = (0.0, 0.0, 0.0, 0.0, env.density);+ cs.push(c);+ cs.len() - 1+ });+ for (i, c) in cs.iter().enumerate() {+ for &t in &c.tris {+ chart_of[t as usize] = i as u32;+ }+ }+ // the scale on every chart's density, lowered until the atlas fits+ let mut d: f32 = 1.0;+ let (w, h) = loop {+ match pack(&mut cs, d, env.max_side) {+ Some((w, h)) if h <= env.max_side => break (w, h),+ Some((_, h)) => d *= (env.max_side as f32 / h as f32).sqrt() * 0.98,+ None => d *= 0.9,+ }+ if d * env.density < 0.01 {+ return Err(format!("the model doesn't fit a {} atlas at any density", env.max_side));+ }+ };+ // texels under each chart, centre in a triangle first, then the edge band+ let mut owner = vec![NONE; (w * h) as usize];+ let mut texels: Vec<Texel> = Vec::new();+ for (ci, c) in cs.iter().enumerate() {+ if Some(ci) == hid {+ continue;+ }+ for &t in &c.tris {+ let tri = sc.tri[t as usize];+ if sc.nrm[t as usize] == Vec3::ZERO {+ continue;+ }+ let wp = tri.map(|v| sc.pos[v as usize]);+ let q = wp.map(|p| c.xy(p, d));+ let (x0, x1) = (q.iter().map(|p| p.0).fold(f32::MAX, f32::min), q.iter().map(|p| p.0).fold(f32::MIN, f32::max));+ let (y0, y1) = (q.iter().map(|p| p.1).fold(f32::MAX, f32::min), q.iter().map(|p| p.1).fold(f32::MIN, f32::max));+ let xr = (x0.floor().max(c.ox as f32) as u32)..=(x1.ceil().min((c.ox + c.w - 1) as f32) as u32);+ let yr = (y0.floor().max(c.oy as f32) as u32)..=(y1.ceil().min((c.oy + c.h - 1) as f32) as u32);+ for y in yr {+ for x in xr.clone() {+ let i = (y * w + x) as usize;+ if owner[i] != NONE {+ continue;+ }+ if let Some(bc) = bary(q, (x as f32 + 0.5, y as f32 + 0.5)).filter(|b| b.iter().all(|&v| v >= -1e-5)) {+ owner[i] = texels.len() as u32;+ texels.push(Texel { x: x as u16, y: y as u16, p: wp[0] * bc[0] + wp[1] * bc[1] + wp[2] * bc[2], n: sc.nrm[t as usize], tri: t });+ }+ }+ }+ }+ // the edge band: an empty texel within 0.75 of a texel of a triangle takes its nearest point+ let mut best: HashMap<(u32, u32), (f32, u32, [f32; 3])> = HashMap::new();+ for &t in &c.tris {+ if sc.nrm[t as usize] == Vec3::ZERO {+ continue;+ }+ let wp = sc.tri[t as usize].map(|v| sc.pos[v as usize]);+ let q = wp.map(|p| c.xy(p, d));+ let lo = |a: f32| (a - 1.0).floor().max(0.0) as u32;+ let (x0, x1) = (lo(q.iter().map(|p| p.0).fold(f32::MAX, f32::min)).max(c.ox), (q.iter().map(|p| p.0).fold(f32::MIN, f32::max) + 1.0) as u32);+ let (y0, y1) = (lo(q.iter().map(|p| p.1).fold(f32::MAX, f32::min)).max(c.oy), (q.iter().map(|p| p.1).fold(f32::MIN, f32::max) + 1.0) as u32);+ for y in y0..=y1.min(c.oy + c.h - 1) {+ for x in x0..=x1.min(c.ox + c.w - 1) {+ if owner[(y * w + x) as usize] != NONE {+ continue;+ }+ let (dist, bc) = nearest(q, (x as f32 + 0.5, y as f32 + 0.5));+ if dist <= 0.75 && best.get(&(x, y)).is_none_or(|b| dist < b.0) {+ best.insert((x, y), (dist, t, bc));+ }+ }+ }+ }+ let mut band: Vec<_> = best.into_iter().collect();+ band.sort_by_key(|((x, y), _)| (*y, *x));+ for ((x, y), (_, t, bc)) in band {+ let wp = sc.tri[t as usize].map(|v| sc.pos[v as usize]);+ owner[(y * w + x) as usize] = texels.len() as u32;+ texels.push(Texel { x: x as u16, y: y as u16, p: wp[0] * bc[0] + wp[1] * bc[1] + wp[2] * bc[2], n: sc.nrm[t as usize], tri: t });+ }+ }+ // each primitive's vertices split by chart, with their TEXCOORD_1+ let (mut verts, mut index, mut uv) = (Vec::new(), Vec::new(), Vec::new());+ for pr in &sc.prims {+ let mut seen: HashMap<(u32, u32), u32> = HashMap::new();+ let (mut vs, mut ix, mut us) = (Vec::new(), Vec::new(), Vec::new());+ for t in pr.first_tri..pr.first_tri + pr.tris {+ let c = &cs[chart_of[t] as usize];+ for v in sc.tri[t] {+ let local = v - pr.base;+ let id = *seen.entry((local, chart_of[t])).or_insert_with(|| {+ let (x, y) = if Some(chart_of[t] as usize) == hid { ((c.ox + GUTTER) as f32 + 0.5, (c.oy + GUTTER) as f32 + 0.5) } else { c.xy(sc.pos[v as usize], d) };+ vs.push(local);+ us.push([x / w as f32, y / h as f32]);+ (vs.len() - 1) as u32+ });+ ix.push(id);+ }+ }+ verts.push(vs);+ index.push(ix);+ uv.push(us);+ }+ let rects = cs.iter().map(|c| [c.ox, c.oy, c.w, c.h]).collect();+ let chart_dens = cs.iter().map(|c| c.dens * d).collect();+ Ok(Atlas { w, h, density: env.density * d, chart_dens, charts: cs.len(), hidden: hidden.len(), texels, chart_of, verts, index, uv, rects })+}++/// The convex hull of points in a plane, counter-clockwise (Andrew's monotone chain).+fn hull(mut p: Vec<(f32, f32)>) -> Vec<(f32, f32)> {+ p.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1)));+ p.dedup();+ if p.len() < 3 {+ return p;+ }+ let cross = |o: (f32, f32), a: (f32, f32), b: (f32, f32)| (a.0 - o.0) * (b.1 - o.1) - (a.1 - o.1) * (b.0 - o.0);+ let mut h: Vec<(f32, f32)> = Vec::with_capacity(p.len() * 2);+ for pass in 0..2 {+ let start = h.len();+ let pts: Box<dyn Iterator<Item = &(f32, f32)>> = if pass == 0 { Box::new(p.iter()) } else { Box::new(p.iter().rev()) };+ for &q in pts {+ while h.len() >= start + 2 && cross(h[h.len() - 2], h[h.len() - 1], q) <= 0.0 {+ h.pop();+ }+ h.push(q);+ }+ h.pop();+ }+ h+}++/// Barycentric coordinates of p in the 2D triangle q, or None for a degenerate one.+fn bary(q: [(f32, f32); 3], p: (f32, f32)) -> Option<[f32; 3]> {+ let (a, b, c) = (q[0], q[1], q[2]);+ let den = (b.1 - c.1) * (a.0 - c.0) + (c.0 - b.0) * (a.1 - c.1);+ if den.abs() < 1e-12 {+ return None;+ }+ let l0 = ((b.1 - c.1) * (p.0 - c.0) + (c.0 - b.0) * (p.1 - c.1)) / den;+ let l1 = ((c.1 - a.1) * (p.0 - c.0) + (a.0 - c.0) * (p.1 - c.1)) / den;+ Some([l0, l1, 1.0 - l0 - l1])+}++/// The distance from p to the 2D triangle q, and the nearest point's barycentric coordinates.+fn nearest(q: [(f32, f32); 3], p: (f32, f32)) -> (f32, [f32; 3]) {+ if let Some(b) = bary(q, p).filter(|b| b.iter().all(|&v| v >= 0.0)) {+ return (0.0, b);+ }+ let mut best = (f32::MAX, [1.0, 0.0, 0.0]);+ for e in 0..3 {+ let (i, j) = (e, (e + 1) % 3);+ let (a, b) = (q[i], q[j]);+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);+ let len2 = dx * dx + dy * dy;+ let s = if len2 > 0.0 { (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / len2).clamp(0.0, 1.0) } else { 0.0 };+ let (nx, ny) = (a.0 + s * dx, a.1 + s * dy);+ let dist = ((p.0 - nx).powi(2) + (p.1 - ny).powi(2)).sqrt();+ if dist < best.0 {+ let mut bc = [0.0; 3];+ bc[i] = 1.0 - s;+ bc[j] = s;+ best = (dist, bc);+ }+ }+ best+}diff --git a/systems/weathering/src/flow.rs b/systems/weathering/src/flow.rsnew file mode 100644index 00000000..c464f4a7--- /dev/null+++ b/systems/weathering/src/flow.rs@@ -0,0 +1,58 @@+//! causes1's flow, deposit and its kind (WR2): a drop on every texel the rain reaches, its water the rain's reach+//! times the texel's area, walked over the model by raea-sys-runoff. Iron gives rust, zinc white, copper green, and any+//! other face that looks up gives the dust that lies on it; the walking surfaces end a drop, so do roofs (they drain to+//! their gutters).++use parry3d::glamx::Vec3;+use parry3d::shape::TriMesh;+use raea_sys_runoff::{Drop, Kind, Role, Surface, run};++use crate::charts::Atlas;+use crate::scene::{Class, Scene};+use crate::{Env, Walk};++pub(crate) fn flow(sc: &Scene, at: &Atlas, env: &Env, mesh: &TriMesh, c0: &[[u8; 4]], c1: &mut [[u8; 4]]) {+ let mut uv = vec![[[0f32; 2]; 3]; sc.tri.len()];+ for (k, pr) in sc.prims.iter().enumerate() {+ for j in 0..pr.tris {+ for c in 0..3 {+ let u = at.uv[k][at.index[k][3 * j + c] as usize];+ uv[pr.first_tri + j][c] = [u[0] * at.w as f32, u[1] * at.h as f32];+ }+ }+ }+ let role: Vec<Role> = (0..sc.tri.len()).map(|t| role_of(sc, env, t)).collect();+ let s = Surface { pos: &sc.pos, tri: &sc.tri, nrm: &sc.nrm, role: &role, uv: &uv, mesh };+ let dens = |t: u32| at.chart_dens[at.chart_of[t as usize] as usize];+ let at_px = |x: u16, y: u16| y as usize * at.w as usize + x as usize;+ let drops: Vec<Drop> = at.texels.iter().filter_map(|tx| {+ let sky = c0[at_px(tx.x, tx.y)][0] as f32 / 255.0;+ (sky > 0.02).then(|| Drop { p: tx.p + tx.n * 0.002, tri: tx.tri, water: sky / dens(tx.tri).powi(2) })+ }).collect();+ let out = run(&s, &drops, env.up, at.w, at.h);+ for tx in &at.texels {+ let i = at_px(tx.x, tx.y);+ let [f, d, k] = out.bytes(i, dens(tx.tri));+ c1[i] = [f, d, k, c1[i][3]];+ }+}++/// Whether triangle t is a walking surface: of a walking class, or level at the walking height.+pub(crate) fn walks(sc: &Scene, env: &Env, t: usize) -> bool {+ match &env.walk {+ Walk::Classes(cs) => cs.contains(&sc.class[t]),+ Walk::Level(y) => sc.nrm[t].dot(env.up) > 0.9 && sc.tri[t].iter().all(|&v| sc.pos[v as usize].dot(env.up) <= y + 0.05),+ }+}++fn role_of(sc: &Scene, env: &Env, t: usize) -> Role {+ let (c, n, walk) = (sc.class[t], sc.nrm[t], walks(sc, env, t));+ let gives = match c {+ Class::Iron => Kind::Rust,+ Class::Zinc => Kind::Zinc,+ Class::Copper => Kind::Copper,+ _ if n.dot(env.up) > 0.5 => Kind::Grime,+ _ => Kind::None,+ };+ Role { gives, walk, drains: matches!(c, Class::Slate | Class::Felt) && n.dot(env.up) > 0.2 || n == Vec3::ZERO }+}diff --git a/systems/weathering/src/lib.rs b/systems/weathering/src/lib.rsnew file mode 100644index 00000000..3328d73f--- /dev/null+++ b/systems/weathering/src/lib.rs@@ -0,0 +1,224 @@+//! Cause maps baked from a glTF's geometry (docs/wear.feature WR1-WR3): for each texel of a second UV set this bake+//! adds, what weathers that point of the surface, traced from the causes as Dorsey, Pedersen and Hanrahan (1996)+//! trace rain and Chen et al. (2005) trace their gamma-tons: where rain reaches and runs, what the sun and the sky+//! see, edges and hollows, the height over the ground, where hands and feet touch, what the water carries and leaves.+//! raea/wear's recipes read the maps, one WESL function per material class.+//!+//! in: a .glb (static meshes), the environment (`Env::of`), the material classes (`scene::Classes::of`)+//! out: in the store under the request's content key: model.glb (TEXCOORD_1 added, charts.rs), causes0-2.png,+//! meta.json; the same request gives the same bytes+//!+//! 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; spare).++mod charts;+mod flow;+mod maps;+mod merge;+mod rays;+mod scene;+mod touch;+#[cfg(test)]+mod tests;++use std::path::Path;+use std::time::Instant;++use parry3d::glamx::Vec3;+use serde_json::{Map, Value, json};+use sha2::{Digest, Sha256};++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 4";++/// The world the bake's causes come from.+#[derive(Clone, Debug)]+pub struct Env {+ pub up: Vec3,+ pub north: Vec3,+ /// the way rain falls (unit), and its cone's half-angle in radians+ pub rain: Vec3,+ pub spread: f32,+ /// degrees north (the sun's path is the whole year's, and December's for causes3)+ pub lat: f32,+ /// the way driven snow travels in a storm (unit), and its cone's half-angle in radians+ pub snow: Vec3,+ pub snow_spread: f32,+ /// the walking surfaces: triangles of these classes, or a level at this height+ pub walk: Walk,+ /// texels a metre asked (any class), by class where a class asks otherwise, and the atlas's longest side+ pub density: f32,+ pub densities: Vec<(Class, f32)>,+ pub max_side: u32,+ pub sky_rays: u32,+ pub cavity_rays: u32,+}++/// Driven snow in a Berlin winter storm, ASSUMED until the DWD's records are read: from the east-north-east (cold+/// continental air), falling 60 degrees off the vertical.+fn storm(up: Vec3, north: Vec3) -> Vec3 {+ let east = north.cross(up).normalize();+ let from = (east * 22.5f32.to_radians().cos() + north * 22.5f32.to_radians().sin()).normalize();+ (-from * 60f32.to_radians().sin() - up * 60f32.to_radians().cos()).normalize()+}++#[derive(Clone, Debug)]+pub enum Walk {+ Classes(Vec<Class>),+ Level(f32),+}++impl Env {+ /// The request's `env` (every field optional): {up, north, rain: {dir, spread (degrees)}, sun: {lat}, snow: {dir,+ /// 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 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]),+ Some(Value::Array(a)) => Walk::Classes(+ a.iter()+ .map(|c| c.as_str().and_then(Class::of).ok_or_else(|| format!("env.walk: a class name, got {c}")))+ .collect::<R<_>>()?,+ ),+ 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)?,+ 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_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,+ 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)+ }+}++/// The bake of `src` (a .glb) under the request {env, classes}, kept in `store` by content.+pub fn bake(store: &Path, src: &Path, req: &Value) -> R<Value> {+ let bytes = std::fs::read(src).map_err(|e| format!("{}: {e}", src.display()))?;+ let mut key = Sha256::new();+ key.update(VERSION.as_bytes());+ 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(canonical(&strip_src(req)).as_bytes());+ key.update(&bytes);+ let key: String = key.finalize().iter().take(12).map(|b| format!("{b:02x}")).collect();+ let dir = store.join("wear").join(&key);+ let meta = dir.join("meta.json");+ if let Ok(s) = std::fs::read_to_string(&meta) {+ if let Ok(v) = serde_json::from_str::<Value>(&s) {+ return Ok(v);+ }+ }+ let env = Env::of(req.get("env").unwrap_or(&Value::Null))?;+ let classes = Classes::of(req.get("classes").unwrap_or(&Value::Null))?;+ let t0 = Instant::now();+ let sc = scene::read(&bytes, &classes).map_err(|e| format!("{}: {e}", src.display()))?;+ let mesh = rays::mesh_of(&sc);+ let t1 = Instant::now();+ let at = charts::build(&sc, &env, &mesh)?;+ let t2 = Instant::now();+ let n = (at.w * at.h) as usize;+ 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 t3 = Instant::now();+ std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;+ let model = dir.join("model.glb");+ std::fs::write(&model, scene::write(&sc, &at)?).map_err(|e| format!("{}: {e}", model.display()))?;+ let covered = at.covered();+ let mut files = Map::new();+ for (name, mut m) in [("causes0", c0), ("causes1", c1), ("causes2", c2), ("causes3", c3)] {+ maps::dilate(&mut m, &mut covered.clone(), at.w, at.h, charts::GUTTER);+ let p = dir.join(format!("{name}.png"));+ maps::png(&p, &m, at.w, at.h)?;+ files.insert(name.into(), json!(p.display().to_string()));+ }+ let sp = dir.join("spots.json");+ std::fs::write(&sp, spots.to_string()).map_err(|e| format!("{}: {e}", sp.display()))?;+ let ms = |a: Instant, b: Instant| (b - a).as_millis() as u64;+ let out = json!({+ "key": key,+ "file": model.display().to_string(),+ "maps": files,+ "spots": sp.display().to_string(),+ "size": [at.w, at.h],+ "density": at.density,+ "asked_density": env.density,+ "charts": at.charts,+ "hidden_tris": at.hidden,+ "texels": at.texels.len(),+ "tris": sc.tri.len(),+ "ms": { "read": ms(t0, t1), "charts": ms(t1, t2), "causes": ms(t2, t3), "write": ms(t3, Instant::now()) },+ });+ std::fs::write(&meta, out.to_string()).map_err(|e| format!("{}: {e}", meta.display()))?;+ Ok(out)+}++fn strip_src(v: &Value) -> Value {+ let mut v = v.clone();+ if let Some(o) = v.as_object_mut() {+ o.remove("src");+ }+ v+}++/// JSON with every object's keys sorted, so a key doesn't depend on how the request was written.+fn canonical(v: &Value) -> String {+ match v {+ Value::Object(o) => {+ let mut ks: Vec<&String> = o.keys().collect();+ ks.sort();+ let parts: Vec<String> = ks.iter().map(|k| format!("{}:{}", Value::String((*k).clone()), canonical(&o[*k]))).collect();+ format!("{{{}}}", parts.join(","))+ }+ Value::Array(a) => format!("[{}]", a.iter().map(canonical).collect::<Vec<_>>().join(",")),+ v => v.to_string(),+ }+}diff --git a/systems/weathering/src/maps.rs b/systems/weathering/src/maps.rsnew file mode 100644index 00000000..b43218ee--- /dev/null+++ b/systems/weathering/src/maps.rs@@ -0,0 +1,51 @@+//! The maps as PNGs, dilated over the gutters: each pass gives every empty texel the mean of its covered neighbours,+//! so a bilinear (or mipped) read at a chart's edge reads the chart and not the black between charts. GUTTER passes+//! fill a chart's own gutter from its own texels; charts are 2 * GUTTER apart, so they don't bleed into each other.++use std::path::Path;++use super::R;++pub(crate) fn dilate(m: &mut [[u8; 4]], covered: &mut [bool], w: u32, h: u32, passes: u32) {+ let (w, h) = (w as i64, h as i64);+ for _ in 0..passes {+ let mut fill: Vec<(usize, [u8; 4])> = Vec::new();+ for y in 0..h {+ for x in 0..w {+ let i = (y * w + x) as usize;+ if covered[i] {+ continue;+ }+ let (mut s, mut k) = ([0u32; 4], 0u32);+ for dy in -1..=1 {+ for dx in -1..=1 {+ let (xx, yy) = (x + dx, y + dy);+ if (dx, dy) == (0, 0) || xx < 0 || yy < 0 || xx >= w || yy >= h {+ continue;+ }+ let j = (yy * w + xx) as usize;+ if covered[j] {+ for c in 0..4 {+ s[c] += m[j][c] as u32;+ }+ k += 1;+ }+ }+ }+ if k > 0 {+ fill.push((i, s.map(|v| ((v + k / 2) / k) as u8)));+ }+ }+ }+ for (i, v) in fill {+ m[i] = v;+ covered[i] = true;+ }+ }+}++pub(crate) fn png(p: &Path, m: &[[u8; 4]], w: u32, h: u32) -> R<()> {+ let raw: Vec<u8> = m.iter().flatten().copied().collect();+ let img = image::RgbaImage::from_raw(w, h, raw).ok_or("a map whose size isn't its texels")?;+ img.save(p).map_err(|e| format!("{}: {e}", p.display()))+}diff --git a/systems/weathering/src/merge.rs b/systems/weathering/src/merge.rsnew file mode 100644index 00000000..8a278e2f--- /dev/null+++ b/systems/weathering/src/merge.rs@@ -0,0 +1,198 @@+//! Charts joined where the flood fill can't join them. A wall cut into strips by its openings shares no edges between+//! its strips (T-junctions), so each strip would be a chart with gutters of its own: coplanar charts whose rectangles+//! touch become one, and the wall's streaks then run on without a seam. Details too small for texels of their own at+//! the bake's density (a reveal, a frame's face, a bracket) take the texels of the big chart they sit on, by+//! projection on its plane: a reveal then reads the wall at its opening's edge, a frame the wall under it.++use std::collections::HashMap;++use parry3d::glamx::Vec3;++use crate::Env;+use crate::charts::Chart;+use crate::scene::Scene;++/// rectangles closer than this (metres, in their plane) touch+const TOUCH: f32 = 0.02;+/// a small chart's host is a big chart whose plane is within this of the small chart's centre+const HOST_REACH: f32 = 0.35;+/// under this many texels across, or this area in texels, a chart is a detail+const THIN: f32 = 1.5;+const AREA: f32 = 6.0;+/// a sparse chart is cut into cells this many texels square+const SPLIT: f32 = 64.0;++fn find(p: &mut [u32], mut i: u32) -> u32 {+ while p[i as usize] != i {+ p[i as usize] = p[p[i as usize] as usize];+ i = p[i as usize];+ }+ i+}++/// 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> {+ 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() {+ if c.n != Vec3::ZERO {+ groups.entry((q(c.n.x), q(c.n.y), q(c.n.z), (c.off / 0.02).round() as i64)).or_default().push(i as u32);+ }+ }+ let mut parent: Vec<u32> = (0..cs.len() as u32).collect();+ let mut keys: Vec<_> = groups.keys().copied().collect();+ keys.sort_unstable();+ for k in keys {+ let mut g = groups.remove(&k).unwrap();+ g.sort_by(|&a, &b| cs[a as usize].s0.total_cmp(&cs[b as usize].s0).then(a.cmp(&b)));+ // a sweep along s: a chart can only touch those that start before it ends+ for (x, &a) in g.iter().enumerate() {+ let ca = &cs[a as usize];+ for &b in &g[x + 1..] {+ let cb = &cs[b as usize];+ if cb.s0 > ca.s1 + TOUCH {+ break;+ }+ if cb.t0 <= ca.t1 + TOUCH && ca.t0 <= cb.t1 + TOUCH {+ let (ra, rb) = (find(&mut parent, a), find(&mut parent, b));+ if ra != rb {+ parent[ra.max(rb) as usize] = ra.min(rb);+ }+ }+ }+ }+ }+ let mut members: Vec<Vec<u32>> = vec![Vec::new(); cs.len()];+ for i in 0..cs.len() as u32 {+ let r = find(&mut parent, i);+ members[r as usize].push(i);+ }+ let mut taken: Vec<Option<Chart>> = cs.into_iter().map(Some).collect();+ let mut out = Vec::new();+ for (r, m) in members.into_iter().enumerate() {+ if m.is_empty() {+ continue;+ }+ let mut c = taken[r].take().unwrap();+ for &o in &m[1..] {+ c.tris.extend(taken[o as usize].take().unwrap().tris);+ }+ c.tris.sort_unstable();+ c.orient(sc, up);+ out.push(c);+ }+ out+}++/// 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> {+ let mut out = Vec::new();+ for c in cs {+ let d = c.asked(sc, env);+ let cell = SPLIT / d;+ let rect = ((c.s1 - c.s0) * d).max(1.0) * ((c.t1 - c.t0) * d).max(1.0);+ if c.n == Vec3::ZERO || rect < 4.0 * SPLIT * SPLIT {+ out.push(c);+ continue;+ }+ let st = |t: u32| sc.tri[t as usize].map(|v| c.st(sc.pos[v as usize]));+ let filled = c+ .tris+ .iter()+ .map(|&t| {+ let [a, b, e] = st(t);+ ((b.0 - a.0) * (e.1 - a.1) - (e.0 - a.0) * (b.1 - a.1)).abs() / 2.0+ })+ .sum::<f32>()+ * d+ * d;+ if filled >= 0.5 * rect {+ out.push(c);+ continue;+ }+ let mut cells: std::collections::BTreeMap<(i32, i32), Vec<u32>> = Default::default();+ for &t in &c.tris {+ let [a, b, e] = st(t);+ let (s, tt) = ((a.0 + b.0 + e.0) / 3.0, (a.1 + b.1 + e.1) / 3.0);+ cells.entry((((s - c.s0) / cell).floor() as i32, ((tt - c.t0) / cell).floor() as i32)).or_default().push(t);+ }+ for (_, tris) in cells {+ out.push(Chart::new(tris, c.n, c.off, (c.u, c.b), sc, env.up));+ }+ }+ out+}++/// 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> {+ 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);+ c.n != Vec3::ZERO && (w.min(h) < THIN || w * h < AREA)+ };+ let bounds = |c: &Chart| {+ c.tris.iter().flat_map(|&t| sc.tri[t as usize]).fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(l, h), v| {+ let p = sc.pos[v as usize];+ (l.min(p), h.max(p))+ })+ };+ const CELL: f32 = 4.0;+ let cell = |v: Vec3| ((v.x / CELL).floor() as i32, (v.y / CELL).floor() as i32, (v.z / CELL).floor() as i32);+ let mut grid: HashMap<(i32, i32, i32), Vec<u32>> = HashMap::new();+ let is_small: Vec<bool> = cs.iter().zip(&ds).map(|(c, &d)| small(c, d)).collect();+ for (i, c) in cs.iter().enumerate() {+ if is_small[i] || c.n == Vec3::ZERO {+ continue;+ }+ let (lo, hi) = bounds(c);+ let (a, b) = (cell(lo - Vec3::splat(HOST_REACH)), cell(hi + Vec3::splat(HOST_REACH)));+ for x in a.0..=b.0 {+ for y in a.1..=b.1 {+ for z in a.2..=b.2 {+ grid.entry((x, y, z)).or_default().push(i as u32);+ }+ }+ }+ }+ let mut host = vec![u32::MAX; cs.len()];+ for (i, c) in cs.iter().enumerate() {+ if !is_small[i] {+ continue;+ }+ let (lo, hi) = bounds(c);+ let mid = (lo + hi) / 2.0;+ let mut best: Option<(f32, f32, u32)> = None;+ for &h in grid.get(&cell(mid)).into_iter().flatten() {+ let hc = &cs[h as usize];+ let dist = (hc.n.dot(mid) - hc.off).abs();+ let (s, t) = hc.st(mid);+ let over = s >= hc.s0 - HOST_REACH && s <= hc.s1 + HOST_REACH && t >= hc.t0 - HOST_REACH && t <= hc.t1 + HOST_REACH;+ let area = (hc.s1 - hc.s0) * (hc.t1 - hc.t0);+ if over && dist <= HOST_REACH && best.is_none_or(|(bd, ba, _)| dist < bd - 1e-4 || ((dist - bd).abs() <= 1e-4 && area > ba)) {+ best = Some((dist, area, h));+ }+ }+ if let Some((_, _, h)) = best {+ host[i] = h;+ }+ }+ let mut taken: Vec<Option<Chart>> = cs.into_iter().zip(&ds).map(|(mut c, &d)| {+ c.dens = d;+ Some(c)+ }).collect();+ for i in 0..taken.len() {+ if host[i] != u32::MAX {+ let tris = taken[i].take().unwrap().tris;+ // a host's own triangles stay first, so its own surface wins a texel both cover+ taken[host[i] as usize].as_mut().unwrap().tris.extend(tris);+ }+ }+ let mut out: Vec<Chart> = taken.into_iter().flatten().collect();+ for c in &mut out {+ c.fit(sc);+ }+ out+}diff --git a/systems/weathering/src/rays.rs b/systems/weathering/src/rays.rsnew file mode 100644index 00000000..911b9270--- /dev/null+++ b/systems/weathering/src/rays.rs@@ -0,0 +1,260 @@+//! Sky, sun, cavity, edge and ground over every texel, by rays through the model's own triangles (parry3d's BVH).+//! sky rain reach: rays up the rain's cone (its axis the way rain comes from, `Env::spread` wide), each seen one+//! counting n.d, over what an open level roof gets; a wall facing the wind gets some, one under a deep+//! cornice little, one facing away almost none+//! sun the share of the whole year's sun path the point sees, weighted by n.s (raea-sys-exposure)+//! cavity the share of short rays (CAVITY_REACH, cosine-weighted) that hit something: hollows, joints, corners+//! edge nearness to a convex arris, sharper edges counting more; a free edge (a panel's border with nothing+//! continuing past it) counts as an arris, one running into another surface (a wall's foot) doesn't+//! ground the drop to the walking surface below: a ray down, through anything that isn't a walking class+//! open the share of the whole sky seen (cosine-weighted, any distance): where the air reaches whatever the rain+//! does, so soot settles on a sheltered east front and a court's floor stays dark and damp+//! and causes3 (raea-sys-exposure, docs/wear.feature WR9): December's sun, a storm's driven snow and the litter traps.+//! 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 parry3d::glamx::Vec3;+use parry3d::query::{Ray, RayCast};+use parry3d::shape::TriMesh;+use rayon::prelude::*;++use raea_sys_exposure::{Driven, Exposer, Frame};++use super::{Env, Walk};+use crate::charts::Atlas;+use crate::scene::Scene;++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 cone(axis: Vec3, half: f32, (u1, u2): (f32, f32)) -> Vec3 {+ let c = 1.0 - u1 * (1.0 - half.cos());+ let s = (1.0 - c * c).max(0.0).sqrt();+ let (t, b) = across(axis);+ (axis * c + t * (s * (TAU * u2).cos()) + b * (s * (TAU * u2).sin())).normalize()+}++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>>,+ cell: f32,+}++impl Edges {+ fn of(sc: &Scene, mesh: &TriMesh, reach: f32) -> Edges {+ let mut ids: HashMap<(i64, i64, i64), u32> = HashMap::new();+ let mut at: Vec<Vec3> = Vec::new();+ let mut id = |p: Vec3| {+ let k = ((p.x * 1000.0).round() as i64, (p.y * 1000.0).round() as i64, (p.z * 1000.0).round() as i64);+ *ids.entry(k).or_insert_with(|| {+ at.push(p);+ (at.len() - 1) as u32+ })+ };+ let mut by: HashMap<(u32, u32), Vec<u32>> = HashMap::new();+ for (t, tri) in sc.tri.iter().enumerate() {+ if sc.nrm[t] == Vec3::ZERO {+ continue;+ }+ let w = tri.map(|v| id(sc.pos[v as usize]));+ for e in 0..3 {+ let (a, b) = (w[e], w[(e + 1) % 3]);+ if a != b {+ by.entry((a.min(b), a.max(b))).or_default().push(t as u32);+ }+ }+ }+ let centre = |t: u32| {+ let v = sc.tri[t as usize];+ (sc.pos[v[0] as usize] + sc.pos[v[1] as usize] + sc.pos[v[2] as usize]) / 3.0+ };+ let mut keys: Vec<_> = by.keys().copied().collect();+ keys.sort_unstable();+ let mut segs = Vec::new();+ for k in keys {+ let ts = &by[&k];+ let (a, b) = (at[k.0 as usize], at[k.1 as usize]);+ let m = (a + b) / 2.0;+ let sharp = if ts.len() >= 2 {+ let (na, nb) = (sc.nrm[ts[0] as usize], sc.nrm[ts[1] as usize]);+ let convex = (centre(ts[1]) - m).dot(na) < -1e-4 || (centre(ts[0]) - m).dot(nb) < -1e-4;+ if !convex || na.dot(nb) > 20f32.to_radians().cos() { 0.0 } else { (1.0 - na.dot(nb)).clamp(0.0, 1.0) }+ } else {+ let n = sc.nrm[ts[0] as usize];+ let out = m - centre(ts[0]);+ let o = (out - n * out.dot(n)).normalize_or_zero();+ // a free edge, unless another surface carries on past it: from 3 cm past the edge and 3 cm off the+ // face, a ray back toward the edge's line meets it (a wall's foot meets the ground there)+ let back = Ray::new(m + o * 0.03 + n * 0.03, -o);+ if mesh.cast_local_ray(&back, 0.06, false).is_some() { 0.0 } else { 0.6 }+ };+ if sharp > 0.0 {+ segs.push((a, b, sharp));+ }+ }+ let cell = reach * 2.0;+ let mut cells: HashMap<(i32, i32, i32), Vec<u32>> = HashMap::new();+ for (i, (a, b, _)) in segs.iter().enumerate() {+ let (lo, hi) = (a.min(*b) - Vec3::splat(reach), a.max(*b) + Vec3::splat(reach));+ let c = |v: f32| (v / cell).floor() as i32;+ for x in c(lo.x)..=c(hi.x) {+ for y in c(lo.y)..=c(hi.y) {+ for z in c(lo.z)..=c(hi.z) {+ cells.entry((x, y, z)).or_default().push(i as u32);+ }+ }+ }+ }+ Edges { segs, cells, cell }+ }++ fn near(&self, p: Vec3, reach: f32) -> f32 {+ let k = ((p.x / self.cell).floor() as i32, (p.y / self.cell).floor() as i32, (p.z / self.cell).floor() as i32);+ let Some(list) = self.cells.get(&k) else { return 0.0 };+ let mut best: f32 = 0.0;+ for &i in list {+ let (a, b, s) = self.segs[i as usize];+ let ab = b - a;+ let t = ((p - a).dot(ab) / ab.length_squared().max(1e-12)).clamp(0.0, 1.0);+ let d = (p - (a + ab * t)).length();+ best = best.max(s * (1.0 - d / reach).max(0.0));+ }+ best+ }+}++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);+ let widest = at.chart_dens.iter().map(|d| (1.0 / d).max(0.08)).fold(0.08, f32::max);+ let edges = Edges::of(sc, mesh, widest);+ let frame = Frame { up: env.up, north: env.north, lat: env.lat };+ let ex = Exposer::new(mesh, &frame, Driven { dir: env.snow, spread: env.snow_spread }, env.sky_rays);+ let from = -env.rain;+ let k = env.sky_rays;+ let level: f32 = (0..k).map(|j| cone(from, env.spread, sample(0, j)).dot(env.up).max(0.0)).sum::<f32>() / k as f32;+ let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;+ let hit = |o: Vec3, d: Vec3, far: f32| mesh.cast_local_ray(&Ray::new(o, d), far, false).is_some();+ let vals: Vec<([u8; 4], [u8; 4], [u8; 4])> = at+ .texels+ .par_iter()+ .enumerate()+ .map(|(i, t)| {+ let (p, n, i) = (t.p, t.n, i as u32);+ let o = p + n * OFF;+ let mut wet = 0.0;+ for j in 0..k {+ let d = cone(from, env.spread, sample(i, j));+ let c = n.dot(d);+ if c > 0.0 && !hit(o, d, SKY_REACH) {+ wet += c;+ }+ }+ let sky = if level > 0.0 { wet / k as f32 / level } else { 0.0 };+ let x = ex.at(i, p, n);+ let kc = env.cavity_rays;+ let occl = (0..kc).filter(|&j| hit(o, hemi(n, sample(i, 2000 + j)), CAVITY_REACH)).count() as f32 / kc as f32;+ // open: the cosine-weighted share of the sky the point sees at any distance (a court's floor little, a+ // roof all), whatever the rain does+ let open = (0..kc).filter(|&j| !hit(o, hemi(n, sample(i, 3000 + j)), SKY_REACH)).count() as f32 / kc as f32;+ 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];+ ([byte(sky), byte(x.sun), byte(occl), byte(edge)], [byte(ground / GROUND_RANGE), element, byte(open), 255], c3)+ })+ .collect();+ for (t, (a, b, c)) in at.texels.iter().zip(vals) {+ let i = t.y as usize * at.w as usize + t.x as usize;+ c0[i] = a;+ c2[i] = b;+ c3[i] = c;+ }+}++/// The drop from p to the walking surface below, in metres (GROUND_RANGE when there is none within reach).+fn ground(sc: &Scene, mesh: &TriMesh, env: &Env, tri: u32, p: Vec3, n: Vec3) -> f32 {+ match &env.walk {+ Walk::Level(y) => (p.dot(env.up) - y).max(0.0),+ Walk::Classes(walk) => {+ if walk.contains(&sc.class[tri as usize]) && n.dot(env.up) > 0.5 {+ return 0.0;+ }+ let mut o = p + n * OFF;+ for _ in 0..8 {+ let Some(h) = mesh.cast_local_ray_and_get_normal(&Ray::new(o, -env.up), 100.0, false) else { return GROUND_RANGE };+ let q = o - env.up * h.time_of_impact;+ if walk.contains(&sc.class[h.subshape as usize]) {+ return (p - q).dot(env.up).max(0.0);+ }+ o = q - env.up * 0.01;+ }+ GROUND_RANGE+ }+ }+}diff --git a/systems/weathering/src/scene.rs b/systems/weathering/src/scene.rsnew file mode 100644index 00000000..63c6f36d--- /dev/null+++ b/systems/weathering/src/scene.rs@@ -0,0 +1,311 @@+//! glTF to triangles with a class each, and back with TEXCOORD_1. Read: every primitive of every node's mesh (a mesh+//! two nodes use is baked twice, as two meshes, since its two places weather apart), its positions put in the world+//! by the node's transform. Written: each primitive's vertices split where its charts meet (charts.rs), every+//! attribute copied element by element in the new order (whatever its type), TEXCOORD_1 added, and the binary+//! rebuilt with only what is still used. Refused: skins, morph targets, .gltf with outside files, sparse accessors,+//! modes other than triangles, and a material that already reads TEXCOORD_1 (a lightmapped model).++use parry3d::glamx::{Mat4, Quat, Vec3};+use serde_json::{Map, Value, json};++use super::R;+use crate::charts::Atlas;+use raea_sys_glb::{Glb, arr, compact, floats, indices, parse, raw};++/// A surface's material, which decides how each cause marks it (raea/wear's recipes).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum Class {+ Plaster,+ Brick,+ Sandstone,+ Granite,+ Wood,+ Iron,+ Zinc,+ Copper,+ Slate,+ Felt,+ Glass,+ Enamel,+ Brass,+ Ground,+}++const NAMES: [(&str, Class); 14] = [+ ("plaster", Class::Plaster),+ ("brick", Class::Brick),+ ("sandstone", Class::Sandstone),+ ("granite", Class::Granite),+ ("wood", Class::Wood),+ ("iron", Class::Iron),+ ("zinc", Class::Zinc),+ ("copper", Class::Copper),+ ("slate", Class::Slate),+ ("felt", Class::Felt),+ ("glass", Class::Glass),+ ("enamel", Class::Enamel),+ ("brass", Class::Brass),+ ("ground", Class::Ground),+];++impl Class {+ pub fn of(s: &str) -> Option<Class> {+ NAMES.iter().find(|(n, _)| *n == s).map(|(_, c)| *c)+ }+ pub fn name(self) -> &'static str {+ NAMES.iter().find(|(_, c)| *c == self).map(|(n, _)| *n).unwrap_or("plaster")+ }+}++/// By material name, a class or {alpha: {CODE: class}, default}: COLOR_0's alpha (0-255) picks the class, the+/// nearest code within 5. "*" is any other material; with no table everything is plaster.+#[derive(Clone, Debug, Default)]+pub struct Classes(Vec<(String, Pick)>);++#[derive(Clone, Debug)]+enum Pick {+ One(Class),+ Alpha(Vec<(u8, Class)>, Class),+}++impl Classes {+ pub fn of(v: &Value) -> R<Classes> {+ let Some(o) = v.as_object() else { return Ok(Classes::default()) };+ let class = |v: &Value, k: &str| v.as_str().and_then(Class::of).ok_or_else(|| format!("classes.{k}: a class name, got {v}"));+ let mut out = Vec::new();+ for (k, v) in o {+ let p = match v {+ Value::Object(a) => {+ let mut codes = Vec::new();+ for (c, cl) in a.get("alpha").and_then(Value::as_object).ok_or_else(|| format!("classes.{k}: {{alpha, default}}"))? {+ let code: u8 = c.parse().map_err(|_| format!("classes.{k}.alpha: a code 0-255, got {c}"))?;+ codes.push((code, class(cl, k)?));+ }+ Pick::Alpha(codes, a.get("default").map(|d| class(d, k)).transpose()?.unwrap_or(Class::Plaster))+ }+ v => Pick::One(class(v, k)?),+ };+ out.push((k.clone(), p));+ }+ Ok(Classes(out))+ }++ fn pick(&self, material: &str, alpha: Option<u8>) -> Class {+ let p = self.0.iter().find(|(k, _)| k == material).or_else(|| self.0.iter().find(|(k, _)| k == "*"));+ match p.map(|(_, p)| p) {+ None => Class::Plaster,+ Some(Pick::One(c)) => *c,+ Some(Pick::Alpha(codes, d)) => {+ let Some(a) = alpha else { return *d };+ codes.iter().filter(|(c, _)| c.abs_diff(a) <= 5).min_by_key(|(c, _)| c.abs_diff(a)).map(|(_, k)| *k).unwrap_or(*d)+ }+ }+ }+}+++/// 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 mesh: usize,+ pub prim: usize,+ pub first_tri: usize,+ pub tris: usize,+ pub base: u32,+}++pub(crate) struct Scene {+ pub glb: Glb,+ /// every vertex in the world; tri indexes it+ pub pos: Vec<Vec3>,+ pub tri: Vec<[u32; 3]>,+ /// per triangle: its plane's normal (zero for a degenerate one) and its class+ pub nrm: Vec<Vec3>,+ pub class: Vec<Class>,+ pub prims: Vec<Prim>,+ /// per node: the mesh it draws after the bake (a mesh used twice is copied)+ node_mesh: Vec<(usize, usize)>,+}+++fn local(n: &Value) -> Mat4 {+ if let Some(m) = n.get("matrix").and_then(Value::as_array).filter(|m| m.len() == 16) {+ let a: Vec<f32> = m.iter().map(|x| x.as_f64().unwrap_or(0.0) as f32).collect();+ return Mat4::from_cols_slice(&a);+ }+ let v = |k: &str, d: &[f32]| -> Vec<f32> {+ n.get(k).and_then(Value::as_array).map(|a| a.iter().map(|x| x.as_f64().unwrap_or(0.0) as f32).collect()).unwrap_or_else(|| d.to_vec())+ };+ let (t, r, s) = (v("translation", &[0.0; 3]), v("rotation", &[0.0, 0.0, 0.0, 1.0]), v("scale", &[1.0; 3]));+ 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> {+ let glb = parse(bytes)?;+ let j = &glb.json;+ for (i, m) in arr(j, "materials").iter().enumerate() {+ if m.to_string().contains("\"texCoord\":1") {+ return Err(format!("material {i} reads TEXCOORD_1 already (a lightmapped model): the bake would replace it"));+ }+ }+ let nodes = arr(j, "nodes");+ let mut world = vec![None; nodes.len()];+ let roots: Vec<usize> = match j.get("scenes").and_then(|s| s.get(j.get("scene").and_then(Value::as_u64).unwrap_or(0) as usize)) {+ Some(s) => arr(s, "nodes").iter().filter_map(|n| n.as_u64().map(|n| n as usize)).collect(),+ None => (0..nodes.len()).collect(),+ };+ let mut stack: Vec<(usize, Mat4)> = roots.iter().map(|&r| (r, Mat4::IDENTITY)).collect();+ while let Some((n, parent)) = stack.pop() {+ let nd = nodes.get(n).ok_or_else(|| format!("node {n} missing"))?;+ if world[n].is_some() {+ continue;+ }+ let m = parent * local(nd);+ world[n] = Some(m);+ for c in arr(nd, "children").iter().filter_map(Value::as_u64) {+ stack.push((c as usize, m));+ }+ }+ let mut sc = Scene { glb: Glb { json: Value::Null, bin: Vec::new() }, pos: Vec::new(), tri: Vec::new(), nrm: Vec::new(), class: Vec::new(), prims: Vec::new(), node_mesh: Vec::new() };+ let meshes = arr(j, "meshes");+ let mats = arr(j, "materials");+ let mut used = vec![false; meshes.len()];+ for (n, nd) in nodes.iter().enumerate() {+ let (Some(mi), Some(m)) = (nd.get("mesh").and_then(Value::as_u64).map(|m| m as usize), world[n]) else { continue };+ if nd.get("skin").is_some() {+ return Err(format!("node {n} is skinned: a bake is of a still model"));+ }+ let mesh = meshes.get(mi).ok_or_else(|| format!("mesh {mi} missing"))?;+ // a mesh drawn by a second node is baked again as a copy (written as a new mesh)+ let baked_as = if used[mi] { meshes.len() + sc.node_mesh.iter().filter(|(_, b)| *b >= meshes.len()).count() } else { mi };+ used[mi] = true;+ sc.node_mesh.push((n, baked_as));+ for (pi, p) in arr(mesh, "primitives").iter().enumerate() {+ if p.get("mode").and_then(Value::as_u64).unwrap_or(4) != 4 {+ return Err(format!("mesh {mi} primitive {pi}: only triangles are taken"));+ }+ if p.get("targets").is_some() {+ return Err(format!("mesh {mi} primitive {pi}: morph targets aren't taken"));+ }+ let at = &p["attributes"];+ let (pos, _) = floats(&glb, at["POSITION"].as_u64().ok_or_else(|| format!("mesh {mi} primitive {pi}: no POSITION"))? as usize)?;+ let verts = (pos.len() / 3) as u32;+ let idx = match p.get("indices").and_then(Value::as_u64) {+ Some(i) => indices(&glb, i as usize)?,+ None => (0..verts).collect(),+ };+ let alpha = match at.get("COLOR_0").and_then(Value::as_u64) {+ Some(c) => {+ let (f, comps) = floats(&glb, c as usize)?;+ Some((f, comps))+ }+ None => None,+ };+ let mname = p.get("material").and_then(Value::as_u64).and_then(|i| mats.get(i as usize)).and_then(|m| m.get("name")).and_then(Value::as_str).unwrap_or("");+ let base = sc.pos.len() as u32;+ for v in pos.chunks_exact(3) {+ sc.pos.push(m.transform_point3(Vec3::new(v[0], v[1], v[2])));+ }+ let first_tri = sc.tri.len();+ for t in idx.chunks_exact(3) {+ if t.iter().any(|&i| i >= verts) {+ return Err(format!("mesh {mi} primitive {pi}: an index past its vertices"));+ }+ let w = [base + t[0], base + t[1], base + t[2]];+ let (a, b, c) = (sc.pos[w[0] as usize], sc.pos[w[1] as usize], sc.pos[w[2] as usize]);+ sc.nrm.push((b - a).cross(c - a).try_normalize().unwrap_or(Vec3::ZERO));+ let a8 = alpha.as_ref().filter(|(_, k)| *k == 4).map(|(f, _)| (f[t[0] as usize * 4 + 3] * 255.0).round().clamp(0.0, 255.0) as u8);+ sc.class.push(classes.pick(mname, a8));+ sc.tri.push(w);+ }+ sc.prims.push(Prim { mesh: baked_as, prim: pi, first_tri, tris: sc.tri.len() - first_tri, base });+ }+ }+ if sc.tri.is_empty() {+ return Err("no triangles in the scene".into());+ }+ sc.glb = glb;+ Ok(sc)+}++/// 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>> {+ let g = &sc.glb;+ let mut j = g.json.clone();+ let src_meshes: Vec<Value> = arr(&j, "meshes").to_vec();+ let mut accessors: Vec<Value> = arr(&j, "accessors").to_vec();+ let mut views: Vec<Value> = arr(&j, "bufferViews").to_vec();+ let mut bin = g.bin.clone();+ let mut push = |bytes: &[u8], target: Option<u32>, acc: Value| -> usize {+ while bin.len() % 4 != 0 {+ bin.push(0);+ }+ let mut v = json!({"buffer": 0, "byteOffset": bin.len(), "byteLength": bytes.len()});+ if let Some(t) = target {+ v["target"] = json!(t);+ }+ bin.extend_from_slice(bytes);+ views.push(v);+ let mut a = acc;+ a["bufferView"] = json!(views.len() - 1);+ a.as_object_mut().unwrap().remove("byteOffset");+ accessors.push(a);+ accessors.len() - 1+ };+ let mut meshes: Vec<Value> = src_meshes.clone();+ for (k, pr) in sc.prims.iter().enumerate() {+ while meshes.len() <= pr.mesh {+ let copy_of = sc.node_mesh.iter().find(|(_, b)| *b == meshes.len()).map(|(n, _)| arr(&j, "nodes")[*n]["mesh"].as_u64().unwrap() as usize).unwrap_or(0);+ meshes.push(src_meshes[copy_of].clone());+ }+ let (order, idx, uv) = (&at.verts[k], &at.index[k], &at.uv[k]);+ let p = meshes[pr.mesh]["primitives"][pr.prim].clone();+ let mut attrs = Map::new();+ for (name, a) in p["attributes"].as_object().ok_or("a primitive without attributes")? {+ if name == "TEXCOORD_1" {+ continue;+ }+ let (b, comps, csize, src) = raw(g, a.as_u64().ok_or("an attribute that isn't an accessor")? as usize)?;+ let el = comps * csize;+ let mut nb = Vec::with_capacity(order.len() * el);+ for &v in order {+ nb.extend_from_slice(&b[v as usize * el..v as usize * el + el]);+ }+ let mut acc = json!({"componentType": src["componentType"], "type": src["type"], "count": order.len()});+ if let Some(nz) = src.get("normalized") {+ acc["normalized"] = nz.clone();+ }+ if name == "POSITION" {+ let f: Vec<f32> = nb.chunks_exact(4).map(|c| f32::from_le_bytes(c.try_into().unwrap())).collect();+ let (mut lo, mut hi) = ([f32::MAX; 3], [f32::MIN; 3]);+ for v in f.chunks_exact(3) {+ for i in 0..3 {+ lo[i] = lo[i].min(v[i]);+ hi[i] = hi[i].max(v[i]);+ }+ }+ acc["min"] = json!(lo);+ acc["max"] = json!(hi);+ }+ attrs.insert(name.clone(), json!(push(&nb, Some(34962), acc)));+ }+ let uvb: Vec<u8> = uv.iter().flat_map(|q| q.iter().flat_map(|f| f.to_le_bytes())).collect();+ attrs.insert("TEXCOORD_1".into(), json!(push(&uvb, Some(34962), json!({"componentType": 5126, "type": "VEC2", "count": uv.len()}))));+ let ib: Vec<u8> = idx.iter().flat_map(|i| i.to_le_bytes()).collect();+ let ia = push(&ib, Some(34963), json!({"componentType": 5125, "type": "SCALAR", "count": idx.len()}));+ let mut np = p.clone();+ np["attributes"] = Value::Object(attrs);+ np["indices"] = json!(ia);+ meshes[pr.mesh]["primitives"][pr.prim] = np;+ }+ j["meshes"] = json!(meshes);+ if let Some(nodes) = j.get_mut("nodes").and_then(Value::as_array_mut) {+ for (n, m) in &sc.node_mesh {+ nodes[*n]["mesh"] = json!(m);+ }+ }+ j["accessors"] = json!(accessors);+ j["bufferViews"] = json!(views);+ compact(&mut j, &bin)+}+diff --git a/systems/weathering/src/tests.rs b/systems/weathering/src/tests.rsnew file mode 100644index 00000000..bf309b0c--- /dev/null+++ b/systems/weathering/src/tests.rs@@ -0,0 +1,317 @@+//! Synthetic fronts checked by number: walls with and without an overhang on a ground, a slab's arris, walls facing+//! south and north, and the bake end to end (the same bytes twice, TEXCOORD_1 on every primitive).++use std::path::Path;++use parry3d::glamx::Vec3;+use serde_json::{Value, json};++use super::*;++type Prim = (&'static str, Vec<Vec3>, Vec<[u32; 3]>);++/// A quad from o along a then b; its normal is a x b.+fn quad(o: Vec3, a: Vec3, b: Vec3) -> (Vec<Vec3>, Vec<[u32; 3]>) {+ (vec![o, o + a, o + a + b, o + b], vec![[0, 1, 2], [0, 2, 3]])+}++fn join(parts: Vec<(Vec<Vec3>, Vec<[u32; 3]>)>) -> (Vec<Vec3>, Vec<[u32; 3]>) {+ let (mut p, mut t) = (Vec::new(), Vec::new());+ for (pp, tt) in parts {+ let base = p.len() as u32;+ p.extend(pp);+ t.extend(tt.into_iter().map(|q| q.map(|i| i + base)));+ }+ (p, t)+}++/// A box's six faces, normals out.+fn cuboid(lo: Vec3, hi: Vec3) -> (Vec<Vec3>, Vec<[u32; 3]>) {+ let d = hi - lo;+ let (x, y, z) = (Vec3::X * d.x, Vec3::Y * d.y, Vec3::Z * d.z);+ join(vec![+ quad(lo, z, y),+ quad(lo + x, y, z),+ quad(lo, x, z),+ quad(lo + y, z, x),+ quad(lo, y, x),+ quad(lo + z, x, y),+ ])+}++/// A .glb of the primitives, each its own material by name, with flat normals.+fn glb(prims: Vec<Prim>) -> Vec<u8> {+ let (mut bin, mut acc, mut views, mut ps, mut mats) = (Vec::<u8>::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new());+ let mut put = |bytes: Vec<u8>, a: Value, bin: &mut Vec<u8>| {+ views.push(json!({"buffer": 0, "byteOffset": bin.len(), "byteLength": bytes.len()}));+ bin.extend(bytes);+ let mut a = a;+ a["bufferView"] = json!(views.len() - 1);+ acc.push(a);+ acc.len() - 1+ };+ for (k, (name, p, t)) in prims.into_iter().enumerate() {+ let mut pos = Vec::new();+ let mut nrm = Vec::new();+ for tri in &t {+ let (a, b, c) = (p[tri[0] as usize], p[tri[1] as usize], p[tri[2] as usize]);+ let n = (b - a).cross(c - a).normalize();+ for v in [a, b, c] {+ pos.push(v);+ nrm.push(n);+ }+ }+ let (lo, hi) = pos.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(l, h), v| (l.min(*v), h.max(*v)));+ let f = |vs: &[Vec3]| vs.iter().flat_map(|v| [v.x, v.y, v.z]).flat_map(f32::to_le_bytes).collect::<Vec<u8>>();+ let pa = put(f(&pos), json!({"componentType": 5126, "type": "VEC3", "count": pos.len(), "min": lo.to_array(), "max": hi.to_array()}), &mut bin);+ let na = put(f(&nrm), json!({"componentType": 5126, "type": "VEC3", "count": nrm.len()}), &mut bin);+ let idx: Vec<u8> = (0..pos.len() as u32).flat_map(u32::to_le_bytes).collect();+ let ia = put(idx, json!({"componentType": 5125, "type": "SCALAR", "count": pos.len()}), &mut bin);+ ps.push(json!({"attributes": {"POSITION": pa, "NORMAL": na}, "indices": ia, "material": k}));+ mats.push(json!({"name": name}));+ }+ let j = json!({+ "asset": {"version": "2.0"}, "scene": 0, "scenes": [{"nodes": [0]}], "nodes": [{"mesh": 0}],+ "meshes": [{"primitives": ps}], "materials": mats, "accessors": acc, "bufferViews": views,+ "buffers": [{"byteLength": bin.len()}],+ });+ raea_sys_glb::glb_bytes(&j, &bin)+}++/// Wall A (x 0-4) under a 1 m overhang at 2.5 m, wall B (x 20-24) open, both facing +z on a ground at y 0.+fn front() -> Vec<Prim> {+ let (gp, gt) = quad(Vec3::new(-40.0, 0.0, 20.0), Vec3::X * 80.0, Vec3::NEG_Z * 40.0);+ let (ap, at) = quad(Vec3::ZERO, Vec3::X * 4.0, Vec3::Y * 3.0);+ let (bp, bt) = quad(Vec3::new(20.0, 0.0, 0.0), Vec3::X * 4.0, Vec3::Y * 3.0);+ let (op, ot) = cuboid(Vec3::new(0.0, 2.5, 0.0), Vec3::new(4.0, 2.6, 1.0));+ vec![("ground", gp, gt), ("wall", ap, at), ("wall", bp, bt), ("slab", op, ot)]+}++fn env(v: Value) -> Env {+ Env::of(&v).unwrap()+}++fn classes() -> Classes {+ Classes::of(&json!({"ground": "ground", "*": "plaster"})).unwrap()+}++struct Baked {+ at: charts::Atlas,+ c0: Vec<[u8; 4]>,+ c2: Vec<[u8; 4]>,+ c3: Vec<[u8; 4]>,+}++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 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);+ Baked { at, c0, c2, c3 }+}++impl Baked {+ /// The mean of a channel over texels whose point and normal pass `keep`.+ fn mean(&self, map: usize, ch: usize, keep: impl Fn(Vec3, Vec3) -> bool) -> f32 {+ let m = match map {+ 0 => &self.c0,+ 3 => &self.c3,+ _ => &self.c2,+ };+ let v: Vec<f32> = self.at.texels.iter().filter(|t| keep(t.p, t.n)).map(|t| m[t.y as usize * self.at.w as usize + t.x as usize][ch] as f32 / 255.0).collect();+ assert!(!v.is_empty(), "no texels pass the filter");+ v.iter().sum::<f32>() / v.len() as f32+ }+}++fn on_wall(p: Vec3, n: Vec3, x0: f32, x1: f32, y0: f32, y1: f32) -> bool {+ n.z > 0.99 && p.z.abs() < 0.01 && p.x > x0 && p.x < x1 && p.y > y0 && p.y < y1+}++#[test]+fn overhang_shelters_the_wall_under_it() {+ let e = env(json!({"density": 8, "rain": {"dir": [0, -1, -0.5], "spread": 20}, "rays": {"sky": 64}}));+ let b = run(front(), &e);+ let under = b.mean(0, 0, |p, n| on_wall(p, n, 0.5, 3.5, 1.6, 2.4));+ let open = b.mean(0, 0, |p, n| on_wall(p, n, 20.5, 23.5, 1.6, 2.4));+ assert!(open > 0.1, "an open wall facing the rain gets some: {open}");+ assert!(under < 0.4 * open, "under the overhang {under}, open {open}");+}++#[test]+fn ground_is_the_height_over_the_walk() {+ let e = env(json!({"density": 8}));+ let b = run(front(), &e);+ for y in [0.3f32, 1.0, 2.0, 2.9] {+ let g = b.mean(2, 0, |p, n| on_wall(p, n, 20.5, 23.5, y - 0.07, y + 0.07)) * 4.0;+ assert!((g - y).abs() < 0.1, "at {y} m the ground channel reads {g} m");+ }+ // the slab's top: the ray down passes through the slab (not a walking class) to the ground+ let top = b.mean(2, 0, |p, n| n.y > 0.99 && (p.y - 2.6).abs() < 0.01 && p.x > 1.0 && p.x < 3.0 && p.z > 0.2 && p.z < 0.8) * 4.0;+ assert!((top - 2.6).abs() < 0.05, "the slab's top reads {top} m");+}++#[test]+fn arrises_wear_and_a_wall_foot_does_not() {+ let e = env(json!({"density": 16}));+ let b = run(front(), &e);+ let arris = b.mean(0, 3, |p, n| n.y > 0.99 && (p.y - 2.6).abs() < 0.01 && p.z > 0.97 && p.x > 1.0 && p.x < 3.0);+ let middle = b.mean(0, 3, |p, n| on_wall(p, n, 21.0, 23.0, 1.0, 2.0));+ let foot = b.mean(0, 3, |p, n| on_wall(p, n, 21.0, 23.0, 0.0, 0.04));+ assert!(arris > 0.5, "the slab's front arris {arris}");+ assert!(middle == 0.0, "a wall's middle {middle}");+ assert!(foot < 0.05, "a wall's foot on the ground {foot}");+}++#[test]+fn a_south_wall_sees_the_december_sun_and_a_north_one_only_summers() {+ let (sp, st) = quad(Vec3::ZERO, Vec3::X * 4.0, Vec3::Y * 3.0);+ let (np, nt) = quad(Vec3::new(14.0, 0.0, -10.0), Vec3::NEG_X * 4.0, Vec3::Y * 3.0);+ let e = env(json!({"density": 4, "north": [0, 0, -1], "sun": {"lat": 52.5}, "walk": {"y": 0}}));+ let b = run(vec![("wall", sp, st), ("wall", np, nt)], &e);+ let (south, north) = (b.mean(3, 0, |_, n| n.z > 0.99), b.mean(3, 0, |_, n| n.z < -0.99));+ assert!(south > 0.3 && north < 0.02, "December: south {south}, north {north}");+ let (south, north) = (b.mean(0, 1, |_, n| n.z > 0.99), b.mean(0, 1, |_, n| n.z < -0.99));+ assert!(north > 0.0 && south > 3.0 * north, "the year: south {south}, north {north}");+}++#[test]+fn charts_keep_their_density_and_never_overlap() {+ let e = env(json!({"density": 8}));+ let b = run(front(), &e);+ let r = &b.at.rects;+ for (i, a) in r.iter().enumerate() {+ for c in &r[i + 1..] {+ let apart = a[0] + a[2] <= c[0] || c[0] + c[2] <= a[0] || a[1] + a[3] <= c[1] || c[1] + c[3] <= a[1];+ assert!(apart, "charts {a:?} and {c:?} overlap");+ }+ }+ // the open wall's chart: 4 m by 3 m at 8 texels a metre+ let wall = b.at.texels.iter().find(|t| on_wall(t.p, t.n, 20.5, 23.5, 1.0, 2.0)).unwrap();+ let rect = r[b.at.chart_of[wall.tri as usize] as usize];+ let across = (rect[2] - 2 * charts::GUTTER) as f32 / (4.0 * b.at.density);+ let down = (rect[3] - 2 * charts::GUTTER) as f32 / (3.0 * b.at.density);+ assert!((0.95..=1.05).contains(&across) && (0.95..=1.05).contains(&down), "density off: {across} {down}");+}++#[test]+fn a_bake_is_the_same_bytes_twice_and_adds_texcoord_1() {+ let tmp = std::env::temp_dir().join(format!("weathering-test-{}", std::process::id()));+ let src = tmp.join("front.glb");+ std::fs::create_dir_all(&tmp).unwrap();+ std::fs::write(&src, glb(front())).unwrap();+ let req = json!({"env": {"density": 4, "rays": {"sky": 8, "cavity": 4}}, "classes": {"ground": "ground"}});+ let a = bake(&tmp.join("a"), &src, &req).unwrap();+ let b = bake(&tmp.join("b"), &src, &req).unwrap();+ for k in ["file"] {+ assert_eq!(std::fs::read(a[k].as_str().unwrap()).unwrap(), std::fs::read(b[k].as_str().unwrap()).unwrap());+ }+ for m in ["causes0", "causes1", "causes2", "causes3"] {+ assert_eq!(std::fs::read(a["maps"][m].as_str().unwrap()).unwrap(), std::fs::read(b["maps"][m].as_str().unwrap()).unwrap(), "{m}");+ }+ 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();+ let sc = scene::read(&out, &Classes::default()).unwrap();+ assert_eq!(sc.prims.len(), 4);+ for m in sc.glb.json["meshes"].as_array().unwrap() {+ for p in m["primitives"].as_array().unwrap() {+ assert!(p["attributes"].get("TEXCOORD_1").is_some(), "a primitive without TEXCOORD_1");+ assert!(p["attributes"].get("NORMAL").is_some(), "NORMAL was dropped");+ }+ }+ let _ = std::fs::remove_dir_all(&tmp);+}++/// A bake of a real file, run by hand: RAEA_WEAR_SRC (a .glb), RAEA_WEAR_REQ (a request .json), RAEA_WEAR_STORE.+/// cargo test --release -p raea-sys-weathering -- --ignored bake_a_file --nocapture+#[test]+#[ignore]+fn bake_a_file() {+ let var = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("{k} not set"));+ let req: Value = serde_json::from_str(&std::fs::read_to_string(var("RAEA_WEAR_REQ")).unwrap()).unwrap();+ let out = bake(Path::new(&var("RAEA_WEAR_STORE")), Path::new(&var("RAEA_WEAR_SRC")), &req).unwrap();+ println!("{out:#}");+}+++#[test]+fn a_floor_shut_in_a_house_gets_no_texels() {+ let (fp, ft) = quad(Vec3::new(31.0, 0.01, -7.0), Vec3::X * 2.0, Vec3::NEG_Z * 2.0);+ let (hp, ht) = cuboid(Vec3::new(30.0, 0.0, -10.0), Vec3::new(34.0, 3.0, -6.0));+ let mut prims = front();+ prims.push(("house", hp, ht));+ prims.push(("floor", fp, ft));+ let e = env(json!({"density": 8}));+ let b = run(prims, &e);+ assert_eq!(b.at.hidden, 2, "the shut floor's two triangles, and nothing else");+ assert!(b.at.texels.iter().all(|t| !(t.n.y > 0.99 && t.p.y < 0.02 && t.p.y > 0.0 && t.p.x > 31.0 && t.p.x < 33.0 && t.p.z < -7.0 && t.p.z > -9.0)), "a texel on the shut floor");+}++#[test]+fn a_class_can_ask_its_own_density() {+ let e = env(json!({"density": {"*": 8, "ground": 2}}));+ let b = run(front(), &e);+ let chart = |keep: &dyn Fn(Vec3, Vec3) -> bool| {+ let t = b.at.texels.iter().find(|t| keep(t.p, t.n)).unwrap();+ b.at.rects[b.at.chart_of[t.tri as usize] as usize]+ };+ let g = 2 * charts::GUTTER;+ let ground = chart(&|p, n| n.y > 0.99 && p.y.abs() < 0.01);+ let wall = chart(&|p, n| on_wall(p, n, 20.5, 23.5, 1.0, 2.0));+ let (gw, gh) = ((ground[2] - g).max(ground[3] - g), (ground[2] - g).min(ground[3] - g));+ assert_eq!((gw, gh), (160, 80), "the 80 x 40 m ground at 2 texels a metre");+ assert_eq!((wall[2] - g, wall[3] - g), (32, 24), "the 4 x 3 m wall at 8");+}+++#[test]+fn a_court_sees_less_sky_than_the_street() {+ // a 4 x 4 m court shut in by 12 m walls (normals in), beside the open ground+ let walls = join(vec![+ quad(Vec3::new(30.0, 0.0, -14.0), Vec3::X * 4.0, Vec3::Y * 12.0),+ quad(Vec3::new(34.0, 0.0, -10.0), Vec3::NEG_X * 4.0, Vec3::Y * 12.0),+ quad(Vec3::new(30.0, 0.0, -10.0), Vec3::NEG_Z * 4.0, Vec3::Y * 12.0),+ quad(Vec3::new(34.0, 0.0, -14.0), Vec3::Z * 4.0, Vec3::Y * 12.0),+ ]);+ let mut prims = front();+ prims.push(("court", walls.0, walls.1));+ let b = run(prims, &env(json!({"density": 8, "rays": {"cavity": 32}})));+ let court = b.mean(2, 2, |p, n| n.y > 0.99 && p.y.abs() < 0.01 && p.x > 31.0 && p.x < 33.0 && p.z > -13.0 && p.z < -11.0);+ let street = b.mean(2, 2, |p, n| n.y > 0.99 && p.y.abs() < 0.01 && p.x > 10.0 && p.x < 16.0 && p.z > 5.0 && p.z < 15.0);+ assert!(street > 0.9, "the open ground sees the sky: {street}");+ assert!(court < 0.35, "a deep court's floor sees little: {court}");+}++#[test]+fn a_door_is_held_on_one_side_and_gets_its_nameplate() {+ let wall = |x: f32, y: f32, w: f32, h: f32| quad(Vec3::new(x, y, 0.0), Vec3::X * w, Vec3::Y * h);+ let (gp, gt) = quad(Vec3::new(-10.0, 0.0, 10.0), Vec3::X * 20.0, Vec3::NEG_Z * 20.0);+ let (wp, wt) = join(vec![wall(-4.0, 0.0, 3.45, 4.0), wall(0.55, 0.0, 3.45, 4.0), wall(-0.55, 2.3, 1.1, 1.7)]);+ let (dp, dt) = cuboid(Vec3::new(-0.5, 0.0, -0.3), Vec3::new(0.5, 2.25, -0.25));+ let prims = vec![("ground", gp, gt), ("wall", wp, wt), ("door", dp, dt)];+ let classes = Classes::of(&json!({"ground": "ground", "door": "wood", "*": "plaster"})).unwrap();+ 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 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];+ 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 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");+ assert!(!touched(&|p, n| n.z > 0.99 && p.z.abs() < 0.01 && p.x.abs() > 0.6), "nothing on the wall");+ let tmp = std::env::temp_dir().join(format!("weathering-door-{}", std::process::id()));+ std::fs::create_dir_all(&tmp).unwrap();+ std::fs::write(tmp.join("door.glb"), glb(prims)).unwrap();+ 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}");+ let _ = std::fs::remove_dir_all(&tmp);+}diff --git a/systems/weathering/src/touch.rs b/systems/weathering/src/touch.rsnew file mode 100644index 00000000..530a99c9--- /dev/null+++ b/systems/weathering/src/touch.rs@@ -0,0 +1,47 @@+//! 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).++use parry3d::glamx::Vec3;+use parry3d::shape::TriMesh;+use raea_sys_touch::{Mat, Point, Spot, Surface, mark};+use serde_json::{Value, json};++use crate::Env;+use crate::charts::Atlas;+use crate::flow::walks;+use crate::rays::GROUND_RANGE;+use crate::scene::{Class, Scene};++fn mat(c: Class) -> Mat {+ match c {+ Class::Plaster => Mat::Plaster,+ Class::Brick | Class::Sandstone | Class::Granite => Mat::Masonry,+ Class::Wood => Mat::Wood,+ Class::Iron => Mat::Metal,+ _ => Mat::Other,+ }+}++/// 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 {+ 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 };+ let px = |x: u16, y: u16| y as usize * at.w as usize + x as usize;+ let f = |b: u8| b as f32 / 255.0;+ let pts: Vec<Point> = at.texels.iter().map(|tx| {+ let i = px(tx.x, tx.y);+ 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);+ for (tx, v) in at.texels.iter().zip(touch) {+ c1[px(tx.x, tx.y)][3] = (v.clamp(0.0, 1.0) * 255.0).round() as u8;+ }+ 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<_>>())+}++fn round(v: f32) -> f64 {+ (v as f64 * 1000.0).round() / 1000.0+}diff --git a/tools/layers.toml b/tools/layers.tomlindex 57ac4d2e..119599bd 100644--- a/tools/layers.toml+++ b/tools/layers.toml@@ -99,6 +99,11 @@ raea-sys-canvas = "systems"raea-sys-tweak = "systems"raea-sys-filters = "systems"raea-sys-wear = "systems"+raea-sys-weathering = "systems"+raea-sys-runoff = "systems"+raea-sys-touch = "systems"+raea-sys-exposure = "systems"+raea-sys-glb = "systems"raea-sys-procmat = "systems"raea-sys-grass = "systems"raea-sys-page = "systems"@@ -151,6 +156,7 @@ raea-runtime-bundle-lib = "runtime"raea-runtime-calls = "runtime"raea-runtime-shots = "runtime"raea-runtime-canvas = "runtime"+raea-runtime-wear = "runtime"raea-runtime-export = "runtime"raea-runtime-pagestore = "runtime"raea-runtime-cssurls = "runtime"@@ -270,3 +276,11 @@ raea-sys-page-net = trueraea-sys-page-ops = trueraea-sys-fonts = trueraea-sys-image = true+# rain's run-off over a model's surfaces (the weathering bake builds its flow and stains on it)+raea-sys-runoff = true+# where hands, feet and wheels wear a model, and where things belong (the weathering bake's touch and spots)+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+# a .glb read as JSON and bytes and written back (the weathering bake reads and rewrites models through it)+raea-sys-glb = truediff --git a/tools/manual-ref/cli.ts b/tools/manual-ref/cli.tsindex faec6ad7..4ec21161 100644--- a/tools/manual-ref/cli.ts+++ b/tools/manual-ref/cli.ts@@ -30,7 +30,7 @@ const GROUPS: [string, string, string[]][] = [["Check", "What's wrong before anyone watches it.", ["check", "judge", "fingerprint", "findings", "scene", "light", "world", "solid", "next", "doctor", "hook", "traces"]],["Footage", "Takes, cuts and the camera, from your own media.", ["media", "cut", "frame", "track", "splat", "mezz", "neural"]],["Sound", "Music read, foley and instruments made on this machine.", ["song", "sounds", "sao", "tokensynth", "setup-audio"]],- ["Generate and 3D tools", "Generated media, physics bakes, clothes and motion for SOMA's body, Blender and Godot.", ["gen", "physics", "clothes", "motion", "blender", "godot"]],+ ["Generate and 3D tools", "Generated media, physics and weathering bakes, clothes and motion for SOMA's body, Blender and Godot.", ["gen", "physics", "wear", "clothes", "motion", "blender", "godot"]],["Agents and setup", "What an agent reads and shows the person, and the tools raea installs.", ["guide", "context", "notes", "show", "skill", "skills", "setup", "bug"]],]/** A verb's page: VERB.md, but index.md is this section's own page, so raea index's is indexer.md */@@ -38,7 +38,7 @@ const pageOf = (verb: string) => (verb === "index" ? "indexer.md" : `${verb}.md`const groupOf = new Map(GROUPS.flatMap(([g, , vs]) => vs.map((v, i) => [v, { g, i }] as const)))// a verb with its own parser lists its forms itself: that list is its usage-const OWN_HELP: Record<string, string[]> = { media: ["media", "help"], gen: ["gen"], blender: ["blender"], godot: ["godot"], physics: ["physics"] }+const OWN_HELP: Record<string, string[]> = { media: ["media", "help"], gen: ["gen"], blender: ["blender"], godot: ["godot"], physics: ["physics"], wear: ["wear"] }function ownHelp(v: string): string {return run(OWN_HELP[v] ?? [v]).replace(/^REFUSED\s+/, "").replace(/^usage:\s*/, "").split("\n").map((l) => l.replace(/^\s{7}(raea )/, "$1").trimEnd()).join("\n")}