Official Codebase of 3DCodeVerse
Python
scene_threejs: prune the effect library to the 12 modules agents import (−17.8k lines)
gaoypenga2a3dd64574f
diff --git a/harness/codeverse3d/languages/scene_threejs/__init__.py b/harness/codeverse3d/languages/scene_threejs/__init__.pyindex b18d40d5..5ce5aa4a 100644--- a/harness/codeverse3d/languages/scene_threejs/__init__.py+++ b/harness/codeverse3d/languages/scene_threejs/__init__.py@@ -245,8 +245,8 @@ _ENV_STUB = """// src/env.js — the environment: the ground every zone seats on// • the ground mesh is named 'Ground…' / 'Terrain…' (the census classifies the ground by name; the placement gate// seats on it); backdrop geometry is named 'Sky…' (it then never inflates the content bounds).// Raw three.js is the baseline. src/lib is an OPTIONAL toolbox the effects catalog lists: lib/terrain.js ground()-// displaces and textures a ground from a height field, lib/sky.js makeSky, lib/environment.js sunRig / roomShell,-// lib/atmosphere.js makeHeightFog — use a call when it fits the brief, write your own when it does not.+// displaces and textures a ground from a height field, lib/sky.js makeSky, lib/environment.js sunRig / roomShell —+// use a call when it fits the brief, write your own when it does not.import * as THREE from 'three';export const SUN_AZIMUTH_DEG = {azimuth}; // 0 = +X, 90 = +Z — {azimuth_note}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/aging.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/aging.jsdeleted file mode 100644index 78b47fc0..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/aging.js+++ /dev/null@@ -1,440 +0,0 @@-/**- * Aging: the three marks that say a surface has STOOD somewhere.- *- * `surface_wear` breaks up the flat colour and takes the finish off the- * edges; these three add the part only weather writes — what ran DOWN- * the face, what corroded where water sat, and what settled on top. All- * three go through `patchStandard`, so lighting, shadows, fog and the- * depth chunks survive; all three shade from world position and world- * normal, so none needs a UV, gravity stays world Y whatever the- * surface is doing, and two objects sharing a scale share one weather.- *- * The constraint that shapes all of them: a fragment sees its own- * position, its own normal and its own screen derivatives, and nothing- * else — it cannot look UP the surface to find the ledge the water- * poured over. So the vertical structure rides fields that are- * STRETCHED along world Y (drips) or CONSTANT along it (rust), which is- * what makes a stain continue below the rim that made it; and- * `patchDripStains(m, { from })` is the one way to pin the source to an- * exact sill.- *- * Coverage drives albedo, roughness and metalness together. Exposed- * substrate keeps its original finish; oxide and deposited dirt become- * rough dielectrics only where the surface is actually covered.- *- * COLOUR: no effect here is one tone. Weather is a mixture — the dirt- * that ran down is not the salt it leached out of the wall, the pit in- * a corrosion patch is not the ochre bloom at its edge, and a drift of- * dust is warmer than the veil between drifts. So each patch carries a- * PAIR (drips, dust) or a TRIPLE (rust) built off its one colour- * option, hue-broken across the field by `astraHueBreak`, and the- * lighter member of each pair is derived from the SURFACE's own albedo- * rather than named here — a leached halo belongs to whatever it is- * leaching out of, and nothing in this file may hardcode a light.- */--import {- patchStandard, glslAxes, glslCurv,- seedVec3, toColor, unit, upVector, worldBase,-} from './shader.js';--// All three patches read these, so they are declared once, in the base.-// Names are age-prefixed rather than shared with surface_wear's: a-// neighbour's helper is only there when that neighbour was applied.-const AGE_HEAD = [- glslAxes('astraAgeAxes'),- // The vertical-streak field: three world-plane projections blended by- // the normal, world Y compressed by `lift` in the two upright ones so- // a feature is taller than wide on ANY face. lift 1.0 = blotches.- 'float astraAgeStreak(vec3 p, vec3 w, float lift) {',- ' return astraNoise2(vec2(p.z, p.y * lift) + 17.3) * w.x',- ' + astraNoise2(p.xz + 41.9) * w.y',- ' + astraNoise2(vec2(p.x, p.y * lift) + 73.1) * w.z;',- '}',- // Positive curvature is convex (swept clean), negative the concave- // lee that holds.- glslCurv('astraAgeCurv'),-].join('\n');--// One base for all three, on the world varyings every library shares;-// the vertex locals are ag* because terrain_shade, waterside and-// surface_wear own astraWp, wsP and wrP.-const BASE = worldBase('aging:base', 'agP', 'agN', AGE_HEAD);--// The constants differ from surface_wear's, or one seed would land this-// library's stains on that one's blotches.-const seedOffset = (seed, salt) =>- seedVec3(seed + salt, 0.29, 5.13, 9.47, 48);--/**- * The vertical streaks that run down from every ledge, sill and joint.- *- * Rain does not wash a facade evenly: it collects on the horizontals,- * pours over their lips, and carries the dirt off them down the face in- * runs — so an exterior with clean verticals under dirty ledges reads- * as a model of a building rather than a building. This lays those runs- * over the albedo, and it is the single strongest "this has stood- * outside" cue there is.- *- * DOWN IS WORLD Y — the field is projected on the world planes and- * stretched ~11x along Y, so a wall at any angle, a pipe and a tank all- * streak vertically with no UV to author and no per-object setup. Three- * thresholds cut it into a pale leached rim, the body of the run and a- * narrow dark core, so the runs come out wide, hairline or absent; and- * the field is sampled a second time 4 * `scale` HIGHER and faded in,- * which drags every feature downward and tapers its tail — that- * asymmetry is what reads as flow rather than as stripes.- *- * The rim is the surface's OWN albedo lifted, not a colour chosen here:- * rain leaches a wall before it dirties it, and a pale edge beside a- * dark core is what makes a run legible at any distance — with the- * grime alone the whole face just dims (measured on the showcase wall:- * the run signal, the high-pass of the column-mean luminance, went- * 0.0111 -> 0.0126 and its peak-to-peak 0.049 -> 0.061 when the rim- * was split out of the wash).- *- * A fragment cannot see the surface above it, so `from` is the only way- * to say where the water came over: given, the runs start just under- * that world Y (each a little lower than its neighbour) and die out at- * their own length; left out, they take their tops from the field- * itself and read as general staining down the whole face. Faces that- * shed nothing — level tops, level soffits — are left alone.- *- * @param {THREE.Material} material A built-in material, patched in- * place — a shared material from `materials.js` streaks every mesh- * wearing it, so clone it first if that is not what you want.- * @param {object} [opts] `strength` how far a run goes toward `color`,- * 0..1 (default 0.35); `color` THREE.Color or hex, the washed-down- * dirt, hue-broken per run so no two are the same brown (default a- * sooty grey-brown); `scale` metres between runs- * (default 0.6; their length scales with it, ~2 to 7 m); `from` world- * Y the runs start below — a ledge top, a sill, a joint (default:- * none, staining down the whole face); `seed` moves them (default 1).- * @returns {THREE.Material} The same material. Its uniforms stay live- * on `material.userData.uniforms`, so `uDripFrom` can follow a sill.- */-export function patchDripStains(material, opts = {}) {- const strength = opts.strength === undefined ? 0.35 : opts.strength;- const scale = opts.scale === undefined ? 0.6 : opts.scale;- const seed = opts.seed === undefined ? 1 : opts.seed;- const from = opts.from;- const gated = Number.isFinite(from);- patchStandard(material, BASE);- return patchStandard(material, {- name: 'aging:drip',- uniforms: {- uDripAmt: { value: unit(strength) },- // A grime that is DARKER than the wall, not a hole in it: the old- // 0x4a4139 lands at 0.074/0.058/0.041 linear and the hue break- // takes the low side of that to 0.04, which reads as a shadow- // rather than as soot. This sits at 0.098/0.072/0.051.- uDripColor: { value: toColor(opts.color, 0x584c40) },- uDripScale: { value: Math.max(1e-3, scale) },- uDripFrom: { value: gated ? from : 0 },- uDripGate: { value: gated ? 1 : 0 },- uDripSeed: { value: seedOffset(seed, 0) },- },- fragmentHead: [- 'uniform float uDripAmt;',- 'uniform vec3 uDripColor;',- 'uniform float uDripScale;',- 'uniform float uDripFrom;',- 'uniform float uDripGate;',- 'uniform vec3 uDripSeed;',- ].join('\n'),- fragmentBody: [- ' vec3 drN = normalize(vAstraWorldN);',- ' vec3 drP = vAstraWorld / uDripScale + uDripSeed;',- // Water runs only where it cannot sit: a level top sheds nothing- // down its own surface, and neither does a level soffit.- ' float drFlow = 1.0 - smoothstep(0.30, 0.92, abs(drN.y));',- ' vec3 drW = astraAgeAxes(drN);',- ' float drA = astraAgeStreak(drP, drW, 0.09);',- // The same field 4 * scale HIGHER, faded in: every feature is- // dragged down from where it started and tapers as it goes.- ' float drB = astraAgeStreak(drP + vec3(0.0, 4.0, 0.0), drW, 0.09);',- // A finer field, stretched even harder, ADDED before the- // threshold rather than multiplied after: it tears the edge of- // every run into fibres that run WITH it.- ' float drC = astraAgeStreak(drP * 3.3, drW, 0.045);',- ' float drF = max(drA, drB * 0.80) + (drC - 0.5) * 0.28;',- // Two thresholds on one field: a broad faint wash with a narrow- // dark core inside it, which is a run rather than a stripe. The- // widths vary because the peaks the thresholds cut do.- //- // fwidth here is a PIXEL guard, not a softener. A wall seen at a- // grazing angle carries a screen gradient many times the width of- // either threshold band, so the old 0.5 cap let it swallow both- // and every run came out an airbrushed smudge with no edge at all- // (measured on the showcase wall: the runs had no local contrast- // to speak of). Capped near one band's width it antialiases and- // stops there.- ' float drAA = clamp(fwidth(drF), 0.0, 0.045);',- // THREE cuts, not two. The outer rim and the body used to be one- // band, so the pale leach and the dark grime landed on the same- // pixels and cancelled — the run lost contrast instead of gaining- // it (wall lum_std 0.0468 -> 0.0415 on the first attempt). Split- // them and the rim frames the body instead of bleaching it.- ' float drWash = smoothstep(0.50 - drAA, 0.60 + drAA, drF);',- ' float drBody = smoothstep(0.60 - drAA, 0.70 + drAA, drF);',- ' float drCore = smoothstep(0.715 - drAA, 0.775 + drAA, drF);',- ' float drRim = drWash * (1.0 - drBody);',- // The sill: full just under it, nothing above it, each run- // starting a little lower and dying at its own length.- ' float drL = mix(3.0, 12.0, drA) * uDripScale;',- ' float drH = uDripFrom - vAstraWorld.y - drB * uDripScale;',- ' float drS = smoothstep(0.0, uDripScale * 0.5, drH)',- ' * (1.0 - smoothstep(drL * 0.4, drL, drH));',- ' float drG = mix(1.0, drS, uDripGate) * drFlow * uDripAmt;',- // What the rain LEACHED, before what it carried: the run's pale- // halo is the surface's own colour lifted, so it belongs to- // whatever it is running on — concrete, render, rusting steel —- // instead of being a grey chosen here. It sits BESIDE the core,- // never under it, which is the light-then-dark pairing that makes- // a run read as a run at any distance.- ' vec3 drSalt = diffuseColor.rgb * 1.34 + 0.030;',- ' diffuseColor.rgb = mix(diffuseColor.rgb, drSalt,',- ' clamp(drRim * 0.85 * drG, 0.0, 1.0));',- // ...and the dirt itself, hue-broken along the wall: two runs off- // one sill are never the same brown, and one flat tone is the- // tell that a texture was painted rather than deposited.- ' vec3 drDirt = astraHueBreak(uDripColor, drP.xz * 0.7 + drP.y,',- ' 0.35, 0.55) * (0.70 + 0.60 * drA);',- ' float drAmt = clamp((0.42 * drBody + 0.58 * drCore) * drG,',- ' 0.0, 1.0);',- ' diffuseColor.rgb = mix(diffuseColor.rgb, drDirt, drAmt);',- ' float drCover = clamp(drAmt + drRim * drG * 0.35, 0.0, 1.0);',- ].join('\n'),- roughnessBody: 'roughnessFactor = mix(roughnessFactor, max(roughnessFactor, 0.92), drCover);',- metalnessBody: 'metalnessFactor *= 1.0 - drCover;',- });-}--/**- * Corrode where water SITS and RUNS, and bleed it downward.- *- * Rust sprayed evenly over a tank is a red tank; rust reads as rust- * because it starts where water cannot leave — the upward faces, the- * lee of a rim, the inside of a corner — and then bleeds down the face- * below in the same patches that fed it. Both halves are here: a- * pooling term from the world normal and the surface's own signed- * curvature, and a running term on the faces that shed.- *- * THE BLEED IS THE FIELD'S DOING — the corrosion map is read from world- * XZ only, so a whole vertical column of surface shares one value, and- * a patch that eats the rim of a tank keeps eating straight down the- * side under it. That is the one way a fragment, which cannot see the- * surface above it, can know what drained onto it. A second field, its- * vertical period in METRES rather than in patches and dragged 2 m- * downward, ends the trail — without it a coarse `scale` paints one- * column floor to ceiling — and THREE tones ride that field rather than- * one brightness ramp: a near-black pitted crust in its lee, the oxide- * through the body, and an ochre bloom where the crust is thinnest.- * That grading is what stops a small subject — a 2.6 m tank, a pipe —- * from reading as a single dark bruise.- *- * Curvature reads ZERO across a hard, unwelded edge (`BoxGeometry`'s- * corners, anything flat-shaded), so the lee term needs bevelled or- * smooth-shaded geometry; the pooling and bleeding terms work on- * anything. Rust becomes a rough dielectric under its coverage mask;- * exposed metal keeps its original reflection. Millimetre crust relief- * fades below a pixel and composes after existing normal and bump maps.- *- * @param {THREE.Material} material A built-in material, patched in- * place — a shared material rusts every mesh wearing it.- * @param {object} [opts] `strength` how far the worst of it goes toward- * `color`, 0..1 (default 0.4); `color` THREE.Color or hex (default an- * iron oxide); `scale` metres across a corrosion patch (default 1.2,- * which also sets the corner radius the lee term looks for); `seed`- * moves the patches (default 1).- * @returns {THREE.Material} The same material, with its uniforms live- * on `material.userData.uniforms`.- */-export function patchRust(material, opts = {}) {- const strength = opts.strength === undefined ? 0.4 : opts.strength;- const scale = opts.scale === undefined ? 1.2 : opts.scale;- const seed = opts.seed === undefined ? 1 : opts.seed;- patchStandard(material, BASE);- return patchStandard(material, {- name: 'aging:rust',- uniforms: {- uRustAmt: { value: unit(strength) },- // An iron oxide with a blue channel. 0x70320f is 0.157/0.034/0.005- // linear — the blue is BLACK, so the mid tone had nowhere to go- // but a bruise, and the pit tone under it went to zero. A real- // goethite/hematite crust sits near 0.25/0.09/0.035.- uRustColor: { value: toColor(opts.color, 0x87542f) },- uRustScale: { value: Math.max(1e-3, scale) },- uRustSeed: { value: seedOffset(seed, 2.3) },- },- fragmentHead: [- 'uniform float uRustAmt;',- 'uniform vec3 uRustColor;',- 'uniform float uRustScale;',- 'uniform vec3 uRustSeed;',- ].join('\n'),- fragmentBody: [- ' vec3 rsN = normalize(vAstraWorldN);',- ' vec3 rsP = vAstraWorld / uRustScale + uRustSeed;',- // Y-INDEPENDENT on purpose: one column of surface, one value, so- // what corrodes a rim goes on corroding the face beneath it.- ' float rsF = astraFbm2(rsP.xz, 3);',- // The bleed's own texture, its vertical period in METRES rather- // than in patches: how far a stain trails is a physical distance,- // so a coarse map must not paint one column floor to ceiling.- ' vec3 rsQ = vec3(rsP.x, vAstraWorld.y * 0.25, rsP.z) * 1.6;',- ' vec3 rsA = astraAgeAxes(rsN);',- ' float rsG = astraAgeStreak(rsQ, rsA, 1.0);',- // The same field 2 m higher, faded in: the stain trails DOWN off- // whatever fed it and dies a couple of metres on.- ' float rsH = astraAgeStreak(rsQ + vec3(0.0, 0.8, 0.0), rsA, 1.0);',- ' float rsB = max(rsG, rsH * 0.82);',- // Where water SITS: on what faces up, and in the concave lee a- // shape shelters from the rain that would rinse it.- ' float rsC = astraAgeCurv(rsN, vAstraWorld);',- ' float rsR = 1.0 / uRustScale;',- ' float rsLee = smoothstep(rsR * 0.5, rsR * 2.0, -rsC);',- ' float rsSit = clamp(smoothstep(-0.05, 0.55, rsN.y)',- ' + rsLee * 0.8, 0.0, 1.0);',- // Where it RUNS: the faces that shed keep the patch that drained- // onto them, textured — not gated — by the streak field.- ' float rsDown = 1.0 - smoothstep(0.30, 0.90, abs(rsN.y));',- ' float rsRun = rsDown',- ' * (0.12 + 0.88 * smoothstep(0.40, 0.62, rsB));',- // Fine corrosion islands interrupt a runoff column. The coarse- // wetting field still connects them to the rim above, while pits- // and flaking edges vary vertically rather than becoming paint.- ' float rsPatch = astraAgeStreak(rsP * 3.7 + 5.8, rsA, 1.0);',- ' float rsGrainFade = 1.0 - smoothstep(0.35, 1.2,',- ' length(fwidth(rsP)) * 140.0);',- ' float rsGrain = mix(0.5, astraAgeStreak(rsP * 140.0, rsA, 1.0), rsGrainFade);',- ' float rsFlakeFade = 1.0 - smoothstep(0.3, 1.0, length(fwidth(rsP)) * 15.0);',- ' float rsFlake = mix(0.5, astraAgeStreak(rsP * 15.0',- ' + vec3(rsPatch * 1.3, rsG * 0.8, rsPatch), rsA, 1.0), rsFlakeFade);',- // The patch edge is torn by the finer field, or corrosion has a- // soft airbrushed boundary no oxide ever had.- ' float rsK = smoothstep(0.46, 0.62, rsF + (rsB - 0.5) * 0.22',- ' + (rsPatch - 0.5) * 0.58 + (rsFlake - 0.5) * 0.38',- ' + (rsGrain - 0.5) * 0.08)',- ' * clamp(rsSit + rsRun, 0.0, 1.0);',- ' float rsAmt = clamp(rsK * uRustAmt, 0.0, 1.0);',- // THREE tones, not one brightness ramp. Corrosion is a stack: a- // near-black pitted crust where it has eaten in, the oxide itself- // across the body of the patch, and a thin ochre bloom at the- // leading edge where it is still only a stain. A single colour- // scaled 0.45..1.05 gives the last of those none of its hue and- // reads as a dark bruise on anything cool-coloured.- ' vec3 rsBase = astraHueBreak(uRustColor, rsP.xz, 0.8, 0.40);',- ' vec3 rsPit = rsBase * vec3(0.38, 0.32, 0.30);',- ' vec3 rsGlow = min(rsBase * vec3(1.30, 1.95, 1.70), vec3(0.82));',- // The three tones ride the STREAK field, so the whole patch is- // graded across rather than one flat oxide with a rim: pits in- // its lee, the oxide through the body, ochre where the crust is- // thin and freshly wet. Confining the bloom to the boundary (a- // first attempt) left the patch reading as one dark bruise on- // anything as small as a 2.6 m tank.- ' vec3 rsCol = mix(rsPit, rsBase, smoothstep(0.16, 0.50, rsB));',- ' rsCol = mix(rsCol, rsGlow, smoothstep(0.50, 0.78, rsB) * 0.60',- ' + clamp(rsK * (1.0 - rsK) * 4.0, 0.0, 1.0) * 0.30);',- ' rsCol *= (0.70 + 0.60 * rsFlake) * (0.94 + 0.12 * rsGrain);',- ' diffuseColor.rgb = mix(diffuseColor.rgb, rsCol, rsAmt);',- ].join('\n'),- roughnessBody: 'roughnessFactor = mix(roughnessFactor, max(roughnessFactor, mix(0.82, 0.97, rsB)), rsAmt);',- metalnessBody: 'metalnessFactor *= 1.0 - rsAmt;',- normalBody: 'normal = astraBump(-vViewPosition, normal, rsAmt * (0.00035 + rsFlake * 0.0004 * rsFlakeFade + rsGrain * 0.00015 * rsGrainFade));',- });-}--/**- * Settle dust on what faces up, thickest where it is flat and sheltered.- *- * An interior or a long-idle exterior loses its contrast from the top- * down: every upward face gets the same pale film, which is why a- * spotless top surface reads as new. This is the cheapest of the three- * — one cosine against the up axis, broken by a blotch field so it is a- * settling rather than a wash — and the one that most changes how OLD a- * room looks.- *- * The film is two tones at ONE value: the coarse grit that fell out- * first sits warm in the drifts, the fine powder the sky keeps lighting- * sits cool in the veil between them, both split by the same field that- * sets the coverage. Equal value keeps the surface lightening evenly- * while the hue moves under it (measured on the showcase slab: hue- * spread 0.066 -> 0.080 at unchanged mean luminance) — a single grey- * mixed over everything is a coat of paint, not a settling.- *- * `up` is a uniform vector, not world Y: dust settles along whatever- * gravity the scene is telling, so a tilted asset, a capsized hull or a- * deck under a listing ship dusts on the faces that actually point up.- *- * SHELTER is the surface's own signed curvature: a convex edge is swept- * by every passing hand and by the rain, a concave corner keeps what- * lands in it. Curvature reads ZERO across a hard unwelded edge, so on- * `BoxGeometry` the shelter term simply does nothing and the cosine- * carries it.- *- * @param {THREE.Material} material A built-in material, patched in- * place — a shared material dusts every mesh wearing it.- * @param {object} [opts] `strength` how far the film goes toward- * `color` on a flat top, 0..1 (default 0.3); `color` THREE.Color or- * hex (default a pale grey); `up` THREE.Vector3 or [x, y, z], the- * world up (default +Y); `seed` moves the blotches (default 1).- * @returns {THREE.Material} The same material, with its uniforms live- * on `material.userData.uniforms`, so `uDustUp` can follow a tilt.- */-export function patchDust(material, opts = {}) {- const strength = opts.strength === undefined ? 0.3 : opts.strength;- const seed = opts.seed === undefined ? 1 : opts.seed;- const up = upVector(opts.up);- patchStandard(material, BASE);- return patchStandard(material, {- name: 'aging:dust',- uniforms: {- uDustAmt: { value: unit(strength) },- uDustColor: { value: toColor(opts.color, 0xb8b2a6) },- uDustUp: { value: up },- uDustSeed: { value: seedOffset(seed, 4.7) },- },- fragmentHead: [- 'uniform float uDustAmt;',- 'uniform vec3 uDustColor;',- 'uniform vec3 uDustUp;',- 'uniform vec3 uDustSeed;',- ].join('\n'),- fragmentBody: [- ' vec3 duN = normalize(vAstraWorldN);',- // Settling is a cosine against the scene's own up, not world Y.- ' float duLay = smoothstep(0.02, 0.70,',- ' dot(duN, normalize(uDustUp)));',- // Swept off what sticks out, held in what is sheltered.- ' float duC = astraAgeCurv(duN, vAstraWorld);',- ' float duHold = 1.0 - 0.85 * smoothstep(3.0, 10.0, duC)',- ' + 0.35 * smoothstep(2.0, 8.0, -duC);',- // Drifts at ~2 m with a grain inside them, or the film is a wash- // of paint rather than something that landed.- ' vec3 duP = vAstraWorld * 0.55 + uDustSeed;',- ' vec3 duW = astraAgeAxes(duN);',- ' float duB = astraAgeStreak(duP, duW, 1.0) * 0.65',- ' + astraAgeStreak(duP * 3.7, duW, 1.0) * 0.35;',- ' float duK = clamp(duLay * duHold',- ' * mix(0.30, 1.0, smoothstep(0.28, 0.78, duB)),',- ' 0.0, 1.0);',- // A settled film is not one grey. The drifts are the coarse warm- // grit that fell out first; the veil between them is the fine- // pale powder the sky keeps lighting. Splitting them by the same- // field that sets the coverage costs nothing and is the whole- // difference between dust and a coat of paint — the two tones sit- // at the same VALUE, so the film still lightens evenly.- ' vec3 duCol = astraHueBreak(uDustColor, duP.xz, 0.5, 0.35);',- // Rec.709-matched on purpose (0.962 against 0.967): a warm/cool- // pair that also differs in VALUE reads as a stain, not a film.- ' duCol = mix(duCol * vec3(0.92, 0.96, 1.10),',- ' duCol * vec3(1.12, 0.94, 0.78),',- ' smoothstep(0.22, 0.80, duB));',- ' float duAmt = clamp(duK * uDustAmt, 0.0, 1.0);',- ' diffuseColor.rgb = mix(diffuseColor.rgb, duCol, duAmt);',- ].join('\n'),- roughnessBody: 'roughnessFactor = mix(roughnessFactor, max(roughnessFactor, 0.96), duAmt);',- metalnessBody: 'metalnessFactor *= 1.0 - duAmt;',- });-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/atmosphere.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/atmosphere.jsdeleted file mode 100644index 87c2649a..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/atmosphere.js+++ /dev/null@@ -1,608 +0,0 @@-/**- * Atmosphere: the two distance cues correct geometry cannot supply.- *- * A fog BANK is geometry — things wade in it, which `scene.fog` can- * never do (it is a function of camera distance, so it veils a figure's- * head exactly as much as its boots). Aerial perspective is the COLOUR- * half of distance: FogExp2 dims but never shifts hue, and without the- * shift a correctly built scene still reads as a tabletop model.- */--import * as THREE from 'three';-import { attachDisposal, snapshotResources } from './lifecycle.js';-import { mulberry32 } from './noise.js';-import { makeShaderMaterial, patchStandard, tickShaders, keepOutOfDepthPasses } from './shader.js';-import { MOODS } from './environment.js';--// Sheets are packed toward the ground (h ~ f^PACK): an evenly spaced-// stack spends most of its geometry in the thin top half where there-// is almost nothing to draw. BASE_H keeps the first sheet off the soil.-//-// LAYERS is the QUANTISATION of the height integral, and it shows: a-// sheet's plane crosses anything vertical standing in the bank along a-// horizontal line, and across that line the count of sheets in front-// changes by one. At 12 sheets a crate in the bank wore six hard-// contour bands (measured on this renderer: six steps over its front-// face, the largest 7/255). Twenty sheets halve the step, and the-// noise floor + dither in the fragment stage break what is left.-const LAYERS = 20;-const PACK = 1.6;-const BASE_H = 0.03;-// Metres of the bank's thickest air that `density` is quoted over, so-// the dial means one physical thing at any `extent`, `height` or-// LAYERS. Written into the GLSL below as 1/REF_M.-const REF_M = 10;-// The day mood's horizon — the fallback for a bank built with no scene-// to read. Not a light colour anyone should be relying on: pass `scene`-// (or `color`) and the bank takes the scene's own.-const DAY_HORIZON = MOODS.day.horizon;-// Henyey-Greenstein asymmetry. Water droplets scatter hard forward, so-// a bank you look THROUGH toward the sun is a light source and the same-// bank with the sun behind you is a grey wall. HG_NORM normalises the-// broadside value to 1 so `uSunAmt` alone sets the strength.-const HG_G = 0.55;-const HG_G2 = HG_G * HG_G;-const HG_NORM = ((1 - HG_G2) / Math.pow(1 + HG_G2, 1.5)).toFixed(6);-// Radiance the key light leaves in a metre of the bank's thickest air,-// per unit of three's directional intensity. Tuned on this renderer-// against the moon rig (2.2) and the day rig (5.4).-const BEAM_K = 0.022;--const LUMA = 'vec3(0.2126, 0.7152, 0.0722)';-/** One horizon read per baked environment, not per patched material. */-const AIR_CACHE = new WeakMap();--/** Luminance of a linear-space THREE.Color. */-function lumOf(c) {- return Math.max(1e-4, 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b);-}--/** `c`'s chromaticity at unit luminance — hue without brightness. */-function chroma(c) {- return c.clone().multiplyScalar(1 / lumOf(c));-}--/**- * The radiance of the air itself, read off the baked environment.- *- * In-scattered light IS the colour of fog, and the scene already- * carries it: `sunRig` bakes the same graded sky the dome draws into a- * linear half-float equirect. The band from the horizon to 25 degrees- * up is what a ground-level ray flies through, so its radiance is the- * bank's colour and the far field's airlight — in every mood, with no- * constant of mine anywhere near it. Measured off this bake: day- * (0.436, 0.764, 1.082), a real sky blue rather than the near-white- * `scene.fog` carries; night (0.026, 0.036, 0.073), seven times the- * night mood's fog colour, which is set to swallow the far field and- * is far too dark to be air.- *- * The middle two quartiles, not the mean: at a low sun the bake's HDR- * sun disc (radiance 5) sits inside this band and doubles a mean- * (golden reads 0.505 flat, 0.262 trimmed).- *- * @param {THREE.Scene} [scene]- * @returns {THREE.Color|null} null unless `scene.environment` is a- * linear equirect DataTexture (a PMREM cube, an LDR texture or no- * environment at all falls back to the fog colour).- */-function horizonRadiance(scene) {- const tex = scene && scene.environment;- const img = tex && tex.image;- const data = img && img.data;- if (!data || tex.mapping !== THREE.EquirectangularReflectionMapping) {- return null;- }- // Per BAKE, not per call: `patchAerialPerspective` is called once per- // material and every one of them would otherwise re-read a quarter of- // the equirect. The cached colour is never handed out — callers of- // `readScene` mutate what they get.- if (AIR_CACHE.has(tex)) {- const hit = AIR_CACHE.get(tex);- return hit ? hit.clone() : null;- }- const half = tex.type === THREE.HalfFloatType;- const w = img.width | 0;- const h = img.height | 0;- const stride = w && h ? data.length / (w * h) : 0;- if ((!half && tex.type !== THREE.FloatType)- || w < 4 || h < 4 || (stride !== 3 && stride !== 4)) {- AIR_CACHE.set(tex, null);- return null;- }- const f = half ? THREE.DataUtils.fromHalfFloat : (v) => v;- // three samples an equirect at v = 0.5 + asin(dir.y) / PI and a- // DataTexture never flips Y, so v 0.500 is the horizon and 0.639 is- // 25 degrees up.- const y1 = Math.min(h, Math.round(0.639 * h));- const px = [];- for (let y = Math.round(0.5 * h); y < y1; y++) {- for (let x = 0; x < w; x += 2) {- const i = (y * w + x) * stride;- const c = [f(data[i]), f(data[i + 1]), f(data[i + 2])];- px.push([0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2], c]);- }- }- if (px.length < 8) {- AIR_CACHE.set(tex, null);- return null;- }- px.sort((a, b) => a[0] - b[0]);- const slice = px.slice(Math.floor(px.length * 0.25),- Math.ceil(px.length * 0.75));- const acc = new THREE.Color(0, 0, 0);- for (const [, c] of slice) { acc.r += c[0]; acc.g += c[1]; acc.b += c[2]; }- acc.multiplyScalar(1 / slice.length);- AIR_CACHE.set(tex, acc);- return acc.clone();-}--/**- * Air is never darker than the light standing in it.- *- * `scene.fog.color` is doing TWO jobs and they part company at night:- * it also has to swallow the far field, so a night mood sets it near- * black (0x0b0f1a — luminance 0.005 linear) while the air in front of- * you is still carrying whatever the sky and the moon put into it. Used- * raw, the far field crushes to a black-blue silhouette (measured: a- * ridge 70 m out fell to (9, 23, 50) against a (26, 36, 64) sky).- * Below `floor` the colour is pulled toward `ref`'s hue and lifted to- * it: dark, but lit, and blue rather than nothing.- *- * @param {THREE.Color} color Mutated and returned.- * @param {THREE.Color|null} ref The hue to fall back toward (the air's- * own radiance, else the fill light).- * @param {number} floor Luminance floor, linear.- */-function inScatterFloor(color, ref, floor) {- if (!ref || !(floor > 0) || lumOf(color) >= floor) return color;- color.lerp(ref, 0.6);- return color.multiplyScalar(floor / lumOf(color));-}--/**- * What the scene says about its own air and its own light.- *- * Atmosphere is the one effect that may not carry colours of its own:- * a bank at a baked-in daylight white is a slab of milk in a night- * scene (measured here: the ground under it read (69,66,64) against a- * (26,36,64) sky — the brightest thing in the frame). So the colour of- * the air comes from `scene.environment`, the fall-backs from- * `scene.fog`, the warm half from the scene's own key light and the- * cool half from its fill.- *- * @param {THREE.Scene} [scene]- * @returns {{air: THREE.Color|null, fog: THREE.Color|null,- * dir: THREE.Vector3|null, sun: THREE.Color|null, key: number,- * amb: THREE.Color|null, ambLum: number, fogFar: number}} — `fogFar` is- * where the scene's fog is (nearly) opaque: a linear Fog's `far`, one- * e-fold of a FogExp2, 0 without fog.- */-function readScene(scene) {- const out = { air: null, fog: null, dir: null, sun: null, key: 0,- amb: null, ambLum: 0, fogFar: 0 };- if (!scene || typeof scene.traverse !== 'function') return out;- out.air = horizonRadiance(scene);- if (scene.fog && scene.fog.color) {- out.fog = scene.fog.color.clone();- out.fogFar = scene.fog.isFog ? scene.fog.far- : scene.fog.density > 0 ? 1 / scene.fog.density : 0;- }- let best = null;- let fill = null;- scene.traverseVisible((o) => {- if (o.isDirectionalLight) {- if (!best || o.intensity > best.intensity) best = o;- } else if (o.isHemisphereLight || o.isAmbientLight) {- if (!fill || o.intensity > fill.intensity) fill = o;- }- });- if (best) {- // sunRig aims its light at the origin, so the position IS the- // vector to the light — and at night that is the MOON, which is- // what a bank actually scatters. An authored `sunDir` from a set- // sun would point under the ground.- out.dir = best.getWorldPosition(new THREE.Vector3());- if (best.target) out.dir.sub(best.target.getWorldPosition(new THREE.Vector3()));- if (out.dir.lengthSq() < 1e-8) out.dir = null;- else out.dir.normalize();- out.sun = best.color.clone();- out.key = best.intensity;- }- if (fill) {- out.amb = fill.color.clone();- out.ambLum = lumOf(fill.color) * fill.intensity;- }- return out;-}--const FOG_VERT = [- ' vPos = transformed;',- // The slope of the view ray decides how much air a sheet stands for,- // and the profile is in WORLD metres of height, so the ray must be- // measured in world space too.- ' vWorld = (modelMatrix * vec4(transformed, 1.0)).xyz;',- ' vH = aH;',- ' vDH = aDH;',-].join('\n');--const FOG_HEAD = [- 'uniform vec3 uColor;',- 'uniform vec3 uSunTint;',- 'uniform vec3 uAmbTint;',- 'uniform vec3 uBeam;',- 'uniform vec3 uSunDir;',- 'uniform float uSunAmt;',- 'uniform float uDensity;',- 'uniform float uTop;',- 'uniform float uScale;',- 'uniform float uFreq;',- 'uniform float uRadius;',- 'uniform vec2 uOffset;',-].join('\n');--const FOG_FRAG = [- // Density falls with HEIGHT in metres and is forced to exactly zero- // at uTop; a bank that merely gets thin has a visible lid.- ' float prof = exp(-vH / uScale)',- ' * (1.0 - smoothstep(uTop * 0.45, uTop, vH));',- // Feather the rim INSIDE the geometry, or a transparent sheet draws- // its own rectangle across the frame.- ' float edge = 1.0 - smoothstep(0.60, 1.0,',- ' length(vPos.xz) / uRadius);',- // METRES OF AIR this sheet stands for: its own slab crossed at the- // view ray's slope, never more than the ray has flown. Ignore the- // slope and the ground at your feet is charged the whole column.- ' vec3 ray = vWorld - cameraPosition;',- ' float dist = length(ray);',- ' float climb = max(abs(ray.y) / dist, 1e-3);',- ' float air = min(vDH / climb, dist) * prof * edge;',- // Extinction per metre at the foot of the bank, from the dial.- ` float sigma = -log(1.0 - min(uDensity, 0.995)) / ${REF_M}.0;`,- ' if (sigma * air < 0.0015) discard;',- // Offset the noise domain by height: without it every sheet wears the- // same blotches and the stack reads as one printed slab.- ' vec2 p = vPos.xz * uFreq + uOffset + vec2(vH * 0.31, vH * -0.22);',- ' p += vec2(uTime * 0.015, uTime * -0.009);',- ' float n = smoothstep(0.20, 0.80, astraFbm2(p, 4));',- // Eaten by noise at the top; at the ground it keeps its MEAN (n runs- // 0..1 about 0.5) but not its uniformity. A flat 1.0 down there was- // the sheet stack's tell: every sheet drew one constant alpha, so- // each sheet's plane printed a hard contour line across anything- // standing in the bank. Patchy air makes the same line a ragged edge,- // and real fog at the soil is patchy anyway.- ' float low = 0.55 + 0.90 * n;',- ' float breakup = mix(low, n, smoothstep(0.10, 0.85, vH / uTop));',- // Beer-Lambert on that air, so the stack telescopes into ONE integral- // however many sheets a ray meets: opacity 1 - exp(-sum of the taus).- ' float a = 1.0 - exp(-sigma * air * breakup * (0.85 + 0.30 * n));',- // A screen-space dither of half the remaining quantisation step: the- // eye integrates the noise and stops finding the contour. Gated by- // `a` so the thin outer wisps are not dusted with speckle.- ' a += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.02',- ' * smoothstep(0.0, 0.12, a);',- ' if (a < 0.002) discard;',- // COLOUR. Fog is not a paint value, it is the light in the air, and- // it has to move: warm and bright looking through it toward the key- // light, cool and flat looking away, brighter at the top of the bank- // where the sky reaches than in the shadowed soil at the bottom.- // uColor is the base (the scene's own fog tint); uSunTint/uAmbTint- // are its two chromaticities at unit luminance, so these mixes move- // HUE and the two literal gains own every change of brightness.- ` float baseL = dot(uColor, ${LUMA});`,- ' vec3 shadeC = mix(uColor, uAmbTint * baseL, 0.35) * 0.76;',- ' vec3 litC = mix(uColor, uSunTint * baseL, 0.55) * 1.18;',- ' vec3 V = ray / dist;',- ' float ct = clamp(dot(V, uSunDir), -1.0, 1.0);',- ` float hgD = 1.0 + ${HG_G2.toFixed(6)} - ${(2 * HG_G).toFixed(6)} * ct;`,- ` float phase = clamp(((1.0 - ${HG_G2.toFixed(6)})`,- ` / (hgD * sqrt(hgD))) / ${HG_NORM}, 0.75, 2.6);`,- ' float sunMix = clamp(0.45 + uSunAmt * (phase - 1.0) * 0.35, 0.0, 1.0);',- // The BEAM is added, not mixed: the sky already in `uColor` outruns- // the moon twenty to one by day and only two to one at night, so a- // multiplier tuned for one is invisible in the other. This term is- // the key light's own radiance in the air, so a moonlit bank glows- // (measured: 32/255, under the soil it covered, before this) while- // the same code adds a modest warm haze at noon.- ' vec3 tint = mix(shadeC, litC, sunMix) + uBeam * phase;',- // The bank is lit from above and shadows itself downward, so the top- // is the bright surface. Without it twenty sheets of one colour are- // still one flat value.- ' tint *= mix(0.88, 1.25, smoothstep(0.0, 0.75, vH / uTop));',- // Patch-to-patch hue spread on the SAME field the density uses, so- // the warm and cool blooms sit where the thick and thin air is.- ' tint = astraHueBreak(tint, p, 0.55, 0.30);',- ' gl_FragColor = vec4(tint, clamp(a, 0.0, 1.0));',-].join('\n');--/**- * Stacked sheets: y follows the terrain, `aH` is height above it,- * `aDH` the metres of column that sheet is the sample of.- */-function fogSheets(extent, top, heightAt) {- // Flat ground needs no tessellation at all — every variation lives in- // the fragment stage, so the whole bank is then LAYERS quads.- const seg = heightAt- ? Math.max(8, Math.min(64, Math.round(extent / 1.5))) : 1;- const row = seg + 1;- const half = extent * 0.5;- const pos = [];- const hs = [];- const dhs = [];- const idx = [];- const at = (l) => BASE_H- + (top - BASE_H) * Math.pow(l / (LAYERS - 1), PACK);- for (let l = 0; l < LAYERS; l++) {- const h = at(l);- // Half way down to the sheet below, half way up to the one above,- // so the stack partitions the column [0, top] exactly once and no- // metre of air is either counted twice or missed.- const dh = (l < LAYERS - 1 ? (h + at(l + 1)) * 0.5 : top)- - (l > 0 ? (at(l - 1) + h) * 0.5 : 0);- const base = l * row * row;- for (let j = 0; j < row; j++) {- const z = -half + (extent * j) / seg;- for (let i = 0; i < row; i++) {- const x = -half + (extent * i) / seg;- pos.push(x, (heightAt ? heightAt(x, z) : 0) + h, z);- hs.push(h);- dhs.push(dh);- }- }- for (let j = 0; j < seg; j++) {- for (let i = 0; i < seg; i++) {- const a = base + j * row + i;- idx.push(a, a + row, a + 1, a + 1, a + row, a + row + 1);- }- }- }- const geo = new THREE.BufferGeometry();- geo.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));- geo.setAttribute('aH', new THREE.Float32BufferAttribute(hs, 1));- geo.setAttribute('aDH', new THREE.Float32BufferAttribute(dhs, 1));- geo.setIndex(idx);- return geo;-}--/**- * A ground-hugging fog bank as real geometry — things WADE in it.- *- * Density is a function of height above the ground, not of camera- * distance: milk in the first metre, gone by `height`, so boots vanish- * while heads stay clear. What a ray then COLLECTS is the air it flies- * through, so the band is a thing you see across — faint at your feet,- * where you look steeply down through a metre of it, and solid down the- * valley, where the same metre lies along the sightline for a hundred.- * Every sheet is one colour, which makes the over-blend order- * independent, so the whole stack is one draw call with no sorting to- * get wrong.- *- * PASS THE SCENE. The bank's colour is in-scattered light, never a- * paint value: `scene` gives it the scene's own fog tint, its key- * light's warmth on the sun side and its fill's cool in the shade, so- * one call reads right at noon and at midnight. Without it the bank- * falls back to a daylight horizon and a night scene gets a slab of- * milk.- *- * @param {object} [opts]- * `scene` THREE.Scene to read (fog colour + the strongest- * DirectionalLight + the fill) — strongly recommended;- * `extent` metres square (default 60); `height` metres at which the- * bank is gone (default 4; `top` is the old name and still works);- * `density` how thick the air is — the opacity of a 10 m horizontal- * look through the bank's foot (default 0.75), so it means the same- * thing at any extent, height or sheet count; `color` THREE.Color- * overriding the base tint (default: the radiance of the scene's own- * air, read off `scene.environment`, then `scene.fog.color`, then the- * day mood horizon); `sunDir` Vector3 or [x, y, z] TOWARD the key- * light, overriding the one read from the scene; `sunAmount` how- * strongly the air scatters that light, 0..1 against a full sun (the- * day rig's 5.4 is 1.0, the moon's 2.2 is 0.44; default from the- * light itself); `heightAt` (x, z) => y to follow terrain —- * omit it and the bank is flat and costs 20 quads; `seed` noise- * offset.- * @returns {THREE.Group} Named `HeightFog`, with `userData.update(t)`- * driving the drift. Move the group to move the bank: the soft rim- * is inscribed in `extent`, so it never shows a boundary of its own.- * Retune later through `uniforms.uColor` / `uDensity` / `uSunAmt`.- */-export function makeHeightFog(opts = {}) {- const extent = opts.extent ?? 60;- // Every other lib in here names this `height` (watermist, rain,- // grass...), and a silently ignored `height` gave the default 4 m- // bank to callers who asked for a 1.6 m one.- const top = Math.max(0.2, opts.height ?? opts.top ?? 4);- const density = opts.density ?? 0.75;- const heightAt = opts.heightAt || null;- const env = readScene(opts.scene);- // The bank is a VOLUME of lit air standing in front of the camera,- // so its colour is the radiance of the air, not the far-field tint- // `scene.fog` carries. Moonlit mist is BRIGHTER than the ground it- // lies on — the ground returns a fraction of the moon, the air- // scatters it whole — and at the raw night fog colour this rendered- // UNDER the soil it covered (28/255 over 45/255) and read as a stain.- const color = opts.color !== undefined ? new THREE.Color(opts.color)- : (env.air ? env.air.clone()- : inScatterFloor(env.fog || new THREE.Color(DAY_HORIZON),- env.amb, 0.55 * env.ambLum));- const sunDir = opts.sunDir- ? (Array.isArray(opts.sunDir)- ? new THREE.Vector3().fromArray(opts.sunDir)- : new THREE.Vector3().copy(opts.sunDir)).normalize()- : (env.dir || new THREE.Vector3(0, 1, 0));- // `sunAmount` is quoted against a full sun (three's physical units:- // the day rig runs 5.4, the moon 2.2), so one dial drives both the- // hue mix and the beam.- const keyI = opts.sunAmount === undefined ? env.key : opts.sunAmount * 5;- const sunAmt = Math.min(1, Math.max(0, keyI / 5));- const beam = (env.sun ? env.sun.clone() : new THREE.Color(0xffffff))- .multiplyScalar(Math.max(0, keyI) * BEAM_K);- const rand = mulberry32(opts.seed ?? 1);- const mat = makeShaderMaterial({- name: 'HeightFog',- uniforms: {- uColor: { value: color },- uSunTint: { value: chroma(env.sun || color) },- uAmbTint: { value: chroma(env.amb || color) },- uBeam: { value: beam },- uSunDir: { value: sunDir },- uSunAmt: { value: sunAmt },- uDensity: { value: density },- uTop: { value: top },- // ~1/4 of the bank is the e-fold, so the first metre carries most- // of the extinction at the default height of 4 m.- uScale: { value: top * 0.28 },- uFreq: { value: 3 / extent },- uRadius: { value: extent * 0.5 },- uOffset: {- value: new THREE.Vector2(rand() * 128, rand() * 128),- },- },- varyings: 'varying vec3 vPos;\nvarying vec3 vWorld;\n'- + 'varying float vH;\nvarying float vDH;',- vertexHead: 'attribute float aH;\nattribute float aDH;',- vertexMain: FOG_VERT,- fragmentHead: FOG_HEAD,- fragmentMain: FOG_FRAG,- transparent: true,- depthWrite: false,- side: THREE.DoubleSide,- });- const mesh = new THREE.Mesh(fogSheets(extent, top, heightAt), mat);- mesh.name = 'HeightFogBank';- const refreshLighting = (scene = opts.scene) => {- const current = readScene(scene);- const uniforms = mat.uniforms;- if (opts.color === undefined) {- const air = current.air || inScatterFloor(- current.fog || new THREE.Color(DAY_HORIZON), current.amb,- .55 * current.ambLum);- uniforms.uColor.value.copy(air);- }- if (!opts.sunDir && current.dir) uniforms.uSunDir.value.copy(current.dir);- const key = opts.sunAmount === undefined ? current.key : opts.sunAmount * 5;- uniforms.uSunAmt.value = Math.min(1, Math.max(0, key / 5));- uniforms.uBeam.value.copy(current.sun || new THREE.Color(0xffffff))- .multiplyScalar(Math.max(0, key) * BEAM_K);- uniforms.uSunTint.value.copy(chroma(current.sun || uniforms.uColor.value));- uniforms.uAmbTint.value.copy(chroma(current.amb || uniforms.uColor.value));- };- mesh.onBeforeRender = (_renderer, scene) => refreshLighting(scene);- keepOutOfDepthPasses(mesh);- const group = new THREE.Group();- group.name = 'HeightFog';- group.add(mesh);- group.userData.update = group.userData.tick = (t) => tickShaders(group, t);- group.userData.refreshLighting = refreshLighting;- return attachDisposal(group, snapshotResources(group));-}--const AERIAL_VERT = [- // three's own fog measures view-space Z (`vFogDepth = -mvPosition.z`),- // so this uses the same ruler and the two cues stay locked. Instances- // are transformed here because <begin_vertex> runs before that.- ' vec4 aerialP = vec4(transformed, 1.0);',- '#ifdef USE_INSTANCING',- ' aerialP = instanceMatrix * aerialP;',- '#endif',- ' vAerialDepth = -(modelViewMatrix * aerialP).z;',-].join('\n');--const AERIAL_FRAG = [- // Chromaticity from the sky, brightness mostly the fragment's own:- // the dimming is FogExp2's job and fighting it double-counts.- ` float aerialL = dot(diffuseColor.rgb, ${LUMA});`,- ' float aerialT = uAerialK * smoothstep(uAerialStart, uAerialEnd,',- ' vAerialDepth);',- // AIRLIGHT, the part pure luminance preservation cannot reach. Air- // does not only tint what is behind it, it glows: the far field- // loses contrast from BOTH ends, darks lifting toward the sky and- // lights settling toward it. Preserving luminance exactly left a- // shadowed ridge 70 m out as black as one at arm's length — the- // silhouette that reads as a hole in the frame rather than distance.- // `uAerialLum` is the sky's own luminance, so at night (a dark sky)- // this correctly nearly vanishes. ONE-SIDED on purpose: airlight is- // light ADDED on the way to the eye. Letting it pull the other way- // dimmed every far surface brighter than the sky, which is the- // extinction half — three's fog owns that, and doing it twice is how- // a hazy distance turns into a dark one.- ' float aerialB = aerialL',- ' + uAerialLift * max(0.0, uAerialLum - aerialL);',- ' diffuseColor.rgb = mix(diffuseColor.rgb,',- ' clamp(uAerialSky * aerialB, 0.0, 1.0), aerialT);',-].join('\n');--const AERIAL_HEAD = [- 'varying float vAerialDepth;',- 'uniform vec3 uAerialSky;',- 'uniform float uAerialStart;',- 'uniform float uAerialEnd;',- 'uniform float uAerialK;',- 'uniform float uAerialLum;',- 'uniform float uAerialLift;',-].join('\n');--/**- * Desaturate a built-in material toward the sky with distance.- *- * FogExp2 dims the far field but never moves its hue, and a saturated- * far hill under correct fog is what still reads as a painted tabletop.- * This tints the ALBEDO (at `<color_fragment>`, so lighting, shadows- * and the fog chunk all still run on top) toward the sky's- * chromaticity at the fragment's own brightness — it composes with the- * scene's fog instead of competing with it.- *- * @param {THREE.Material} material Any built-in material (the patch- * needs three's `<color_fragment>`); patched in place.- * @param {object} [opts] `scene` THREE.Scene to read — the shift then- * targets the scene's OWN fog colour and finishes where that fog- * closes, so the two cues cannot disagree about where far is;- * `skyColor` THREE.Color override (default the day mood horizon,- * matching `worldShell`); `start`/`end` metres over which the shift- * ramps in (default 40 and where the scene's fog closes — a linear- * Fog's far, a FogExp2's e-fold, else the day mood's ~556 m — so the- * shift completes as fog takes over); `strength`- * maximum shift (default 0.8; 1.0 is pure sky); `lift` how much of- * the sky's own brightness the far field takes on — airlight- * (default 0.35; 0 is the pure hue shift, 1 flattens the far field- * to the sky).- * @returns {THREE.Material} The same material; it chains with other- * patches in any order. Tune later through- * `material.userData.uniforms.uAerialK.value`.- */-export function patchAerialPerspective(material, opts = {}) {- const env = readScene(opts.scene);- // The TARGET stays the scene's own fog colour — the whole point is- // that the hue shift and three's fog agree about what far looks like- // — but it is floored by the radiance of the air, so a night mood's- // deliberately black fog cannot take the far field to black with it.- const sky = opts.skyColor !== undefined ? new THREE.Color(opts.skyColor)- : inScatterFloor(env.fog || env.air || new THREE.Color(DAY_HORIZON),- env.air || env.amb,- env.air ? 0.5 * lumOf(env.air) : 0.2 * env.ambLum);- const start = opts.start ?? 40;- // Where the scene's own fog closes (a linear Fog's far, a FogExp2's- // e-fold); with no fog, the day mood's e-fold.- const far = env.fogFar > 0 ? env.fogFar : 1 / MOODS.day.fogDensity;- const end = Math.max(start + 1, opts.end ?? far);- // Pre-divided by its own luminance, so `uAerialSky * L` lands back on- // the fragment's brightness and the shader stays two instructions.- const lum = lumOf(sky);- return patchStandard(material, {- // One name on purpose: the GLSL is identical for every material, so- // they SHOULD share a program. The uniforms stay per material.- name: 'aerialPerspective',- uniforms: {- uAerialSky: { value: sky.clone().multiplyScalar(1 / lum) },- uAerialStart: { value: start },- uAerialEnd: { value: end },- uAerialK: { value: opts.strength ?? 0.8 },- uAerialLum: { value: lum },- uAerialLift: { value: opts.lift ?? 0.35 },- },- vertexHead: 'varying float vAerialDepth;',- vertexBody: AERIAL_VERT,- fragmentHead: AERIAL_HEAD,- fragmentBody: AERIAL_FRAG,- util: false,- });-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/building.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/building.jsdeleted file mode 100644index 48386e54..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/building.js+++ /dev/null@@ -1,998 +0,0 @@-/**- * A facade with real openings, instead of a textured box. The fix is- * depth, not a texture: spandrel bands and mullions with GAPS onto a- * dark recessed shell, a glazed ground floor, plinth and projecting- * cornice — real geometry that holds in silhouette and casts shadow.- * Cheap by design: one merged mesh per material, ~800-1,500 triangles- * for an eight-storey block.- */--import * as THREE from 'three';-import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';-import * as MAT from './materials.js';-import { clonePatchedMaterial } from './shader.js';-import { attachDisposal, snapshotResources } from './lifecycle.js';--// Cached material factories remain borrowed; glazing and explicit color-// variants are owned by this construction, as are its mesh buffers.-function ownBuilding(root) {- const resources = snapshotResources(root);- for (const resource of resources) {- if (resource.isMaterial && resource.userData.shared) resources.delete(resource);- }- return attachDisposal(root, resources);-}---/** Metres of wall per texture tile. One number for the whole module, so- * a mullion, a spandrel and a cornice share one masonry scale. */-const UV_TILE = 2.6;--/**- * A box as geometry, positioned by its centre, with its UVs scaled to a- * CONSTANT texel density.- *- * three gives every box face a full 0..1 UV whatever that face measures,- * so one merged facade stretched a single brick tile across a 14 m wall- * and squeezed the same tile onto a 0.34 m mullion — which is why the- * piers read as vertical woodgrain stripes next to a flat wall. Scaling- * u,v by the face's own metres fixes it for every part at once (the- * library's noise maps are all RepeatWrapping, so uv > 1 tiles).- */-function bx(w, h, d, x, y, z) {- const g = new THREE.BoxGeometry(w, h, d);- const uv = g.attributes.uv;- // BoxGeometry lays its 24 vertices out px, nx, py, ny, pz, nz.- const dims = [[d, h], [d, h], [w, d], [w, d], [w, h], [w, h]];- for (let f = 0; f < 6; f++) {- const su = dims[f][0] / UV_TILE, sv = dims[f][1] / UV_TILE;- for (let i = f * 4; i < f * 4 + 4; i++) {- uv.setXY(i, uv.getX(i) * su, uv.getY(i) * sv);- }- }- uv.needsUpdate = true;- g.translate(x, y, z);- return g;-}--/**- * The warm interior-glow card behind a lit window — one definition so- * `block()`, `cottage()` and `casement()` glow alike. At dusk, lit- * windows are the strongest habitation cue.- *- * Emissive stays in the 1.1-2.6 band: bloom-friendly, and a lit pane- * that peaks at 20 is a white hole with no colour left in it.- */-function litMat(o = {}) {- return MAT.plaster({- color: o.color === undefined ? 0xffdca8 : o.color,- roughness: 1,- hueBreak: 0.02,- extra: { emissive: new THREE.Color(- o.emissive === undefined ? 0xffca7a : o.emissive),- emissiveIntensity: o.intensity === undefined- ? 1.5 : o.intensity } });-}--/**- * A LIT FACADE IS NOT ONE COLOUR. Every window on one emissive material- * turns a night block into a single glowing slab; real windows split by- * room — tungsten living rooms, warm-white bedrooms, the odd cool- * kitchen or stairwell — and that split IS the night read. Three- * buckets keep it to three merged meshes per building.- */-const LIT_CLASSES = [- { color: 0xffd9ad, emissive: 0xffb765, intensity: 1.9 }, // tungsten- { color: 0xffe6c4, emissive: 0xffd39a, intensity: 1.25 }, // warm white- { color: 0xdfe9ff, emissive: 0xbcd4ff, intensity: 1.55 }, // cool room-];--/**- * Wall/trim albedos are held under 0.8 sRGB. Plaster and travertine- * ship near 0.92, which under exposure 1.0 with no post chain lands a- * whole facade at the top of the range — a white card that no shadow- * can shape and no cornice can read against.- */-const STYLES = {- // Stock brick, not pillarbox: 0x9c4a35 under ACES at exposure 1.0- // came out a saturated candy red across a whole facade. Lower- // contrast too — a merged box gives every face a full 0..1 UV, so a- // slim mullion stretches the noise into stripes.- brick: { wall: () => MAT.brick({ color: 0x8d5341, contrast: 0.3 }),- floorH: 3.2, bayW: 3.4,- trim: () => MAT.travertine({ color: 0xc3b79e }),- glassColor: 0x37454f },- masonry: { wall: () => MAT.plaster({ color: 0xc9bcaa }), floorH: 3.4,- bayW: 3.8, trim: () => MAT.travertine({ color: 0xcbbfa8 }),- glassColor: 0x3c4b58 },- stone: { wall: () => MAT.granite(), floorH: 3.6, bayW: 4.0,- trim: () => MAT.travertine({ color: 0xc7bca6 }),- glassColor: 0x374651 },- glass: { wall: () => MAT.brushedSteel(), floorH: 3.9, bayW: 5.0,- trim: () => MAT.brushedSteel(), glassColor: 0x46606f },-};--/**- * Glazing. A dielectric with a fresnel ramp, tinted per style, and a- * lifted `envMapIntensity` so the panes mirror the sky instead of- * reading as black rectangles punched in the wall.- */-function glazing(color, k = 0) {- // Two batches per facade. Real glazing is never one value — blinds,- // curtains, a room behind one pane and none behind the next — and a- // grid of identical panes is the "flat glass tower" verdict.- const c = new THREE.Color(color);- if (k) c.offsetHSL(0.02, -0.05, 0.05);- return MAT.glass({ color: c.getHex(), opacity: k ? 0.55 : 0.66,- extra: { envMapIntensity: 2.2, roughness: k ? 0.14 : 0.08 } });-}--/**- * The shell seen through every opening. NOT black: a room's back wall- * still catches sky through the window, and 0x14161a rendered as a- * hole. This is dark enough to read as depth and light enough that the- * environment shapes it.- */-function revealMat() {- return MAT.plaster({ color: 0x24262c, roughness: 1, hueBreak: 0.05 });-}--/**- * One merged mesh per `[geometries, material, name]` part, then one per- * lit-room class in `litBins`, added to `root` in that order. Empty- * parts are skipped.- */-function addMerged(root, parts, litBins) {- litBins.forEach((geos, i) => parts.push(- [geos, litMat(LIT_CLASSES[i]), i ? 'LitRooms' + (i + 1) : 'LitRooms']));- for (const [geos, mat, nm] of parts) {- if (!geos.length) continue;- const merged = geos.length === 1 ? geos[0] : mergeGeometries(geos, false);- if (!merged) continue;- const m = new THREE.Mesh(merged, mat);- m.name = nm;- // The shell and the lit cards live inside the openings; casting- // from them only stipples the reveal they are meant to fill.- m.castShadow = nm !== 'Reveals' && !nm.startsWith('LitRooms');- m.receiveShadow = true;- root.add(m);- }-}--/**- * Build a block with modelled openings, a plinth and a cornice.- *- * @param {object} opts- * `w` width, `d` depth, `h` height in metres; `style` one of- * `brick | masonry | stone | glass` (default `masonry`); `rand` a- * seeded PRNG (REQUIRED for variation -- no `Math.random`);- * `color` overrides the wall colour; `ground` `'storefront'` (default,- * a taller glazed base) or `'plain'`; `lit` 0..1 fraction of windows- * that glow, for night scenes (default 0); `name`.- * @returns {THREE.Group} Resting on y=0, centred on x/z, facing -Z,- * with `userData.forward` and `userData.floors`. Meshes are named- * `Walls`, `Trim`, `Glazing`, `Reveals` and — only when `lit` — one- * `LitRooms*` per lit class. `LitRooms` deliberately does NOT match- * a `/glaz|pane/` sweep, so re-glazing a facade leaves its lit- * windows glowing.- */-export function block(opts = {}) {- const rand = opts.rand || (() => 0.5);- const w = opts.w || 14;- const d = opts.d || 12;- const h = opts.h || 22;- const st = STYLES[opts.style] || STYLES.masonry;-- // A DISTRICT OF ONE COLOUR reads as one stamped asset however varied- // the massing is. `tint` clones the cached material into nine hue +- // lightness buckets, so a hundred blocks cost nine materials.- let wallMat = st.wall();- if (opts.color !== undefined) {- wallMat = clonePatchedMaterial(wallMat);- wallMat.color = new THREE.Color(opts.color);- } else {- // Half of `tint`'s range: its full swing is +-25% lightness, which- // walks brick from stock to candy. A street wants a batch spread,- // not four different bricks.- wallMat = MAT.tint(wallMat, 0.5 + (rand() - 0.5) * 0.6);- }- const trimMat = st.trim();- const glassMats = [glazing(st.glassColor, 0), glazing(st.glassColor, 1)];- const darkMat = revealMat();-- // A storefront base is taller than the floors above it, which is most- // of what makes a street read as a street rather than a stack.- const baseH = opts.ground === 'plain' ? 0- : Math.min(h * 0.28, st.floorH * 1.45);- const upperH = h - baseH;- const floors = Math.max(1, Math.round(upperH / st.floorH));- const fh = upperH / floors;- const bays = Math.max(1, Math.round(w / st.bayW));- const baysD = Math.max(1, Math.round(d / st.bayW));-- const wall = []; // spandrels + mullions + plinth- const trim = []; // cornice, sills, string courses- const glassBins = [[], []]; // panes, set back inside the openings- const glass = glassBins[0]; // the storefront runs on one batch- const dark = []; // the recess shell seen through the openings- const litBins = LIT_CLASSES.map(() => []); // lit panes, by room class-- // The shell that gives every opening a dark interior behind it. It is- // inset, so what you see through a window is depth, not the sky.- const inset = 0.42;- dark.push(bx(w - inset * 2, h, d - inset * 2, 0, h / 2, 0));-- const plinth = Math.min(0.6, h * 0.03);- wall.push(bx(w + 0.22, plinth, d + 0.22, 0, plinth / 2, 0));-- // Ground floor: wide glazing between slim piers.- if (baseH > 0) {- const pierW = Math.max(0.45, w * 0.035);- for (const [len, along, faceZ] of- [[w, 'x', d / 2], [w, 'x', -d / 2], [d, 'z', w / 2], [d, 'z', -w / 2]]) {- const n = Math.max(2, Math.round(len / (st.bayW * 1.6)));- for (let i = 0; i <= n; i++) {- const t = -len / 2 + (len / n) * i;- const g = along === 'x'- ? bx(pierW, baseH, 0.5, t, plinth + baseH / 2, faceZ)- : bx(0.5, baseH, pierW, faceZ, plinth + baseH / 2, t);- wall.push(g);- }- const gp = along === 'x'- ? bx(len - pierW, baseH * 0.86, 0.12, 0,- plinth + baseH / 2, faceZ - Math.sign(faceZ) * 0.3)- : bx(0.12, baseH * 0.86, len - pierW,- faceZ - Math.sign(faceZ) * 0.3, plinth + baseH / 2, 0);- glass.push(gp);- }- trim.push(bx(w + 0.5, 0.28, d + 0.5, 0, plinth + baseH + 0.14, 0));- }-- // Upper floors, each face built as spandrel bands + mullions with the- // gaps between them left OPEN onto the dark shell.- const y0 = plinth + baseH;- const spandrel = fh * 0.34; // solid band under each window- const openH = fh - spandrel;- for (let f = 0; f < floors; f++) {- const yb = y0 + f * fh;- for (const [len, along, faceOff, n] of- [[w, 'x', d / 2, bays], [w, 'x', -d / 2, bays],- [d, 'z', w / 2, baysD], [d, 'z', -w / 2, baysD]]) {- const s = Math.sign(faceOff);- // Spandrel band across the whole face.- wall.push(along === 'x'- ? bx(len, spandrel, 0.5, 0, yb + spandrel / 2, faceOff)- : bx(0.5, spandrel, len, faceOff, yb + spandrel / 2, 0));- // Mullions between bays.- const mw = Math.max(0.34, len / n * 0.22);- for (let i = 0; i <= n; i++) {- const t = -len / 2 + (len / n) * i;- wall.push(along === 'x'- ? bx(mw, openH, 0.5, t, yb + spandrel + openH / 2, faceOff)- : bx(0.5, openH, mw, faceOff, yb + spandrel + openH / 2, t));- }- // A pane per bay, set back 0.22 m so the reveal reads as depth.- for (let i = 0; i < n; i++) {- const t = -len / 2 + (len / n) * (i + 0.5);- const pw = len / n - mw;- const lit = opts.lit && rand() < opts.lit;- const geo = along === 'x'- ? bx(pw, openH * 0.95, 0.1, t, yb + spandrel + openH / 2,- faceOff - s * 0.22)- : bx(0.1, openH * 0.95, pw, faceOff - s * 0.22,- yb + spandrel + openH / 2, t);- // A lit pane is its OWN card, never the shell: pushing it onto- // `dark` and then making the whole shell emissive lit every- // window in the building from one 22 m glowing box, so `lit:- // 0.4` still came out as a solid lantern.- if (lit) litBins[Math.floor(rand() * LIT_CLASSES.length)- % LIT_CLASSES.length].push(geo);- else glassBins[rand() < 0.72 ? 0 : 1].push(geo);- }- // A sill ledge under the openings — the "missing trim" complaint.- trim.push(along === 'x'- ? bx(len, 0.13, 0.72, 0, yb + spandrel + 0.06, faceOff)- : bx(0.72, 0.13, len, faceOff, yb + spandrel + 0.06, 0));- }- }-- // Cornice + parapet: a flat top edge reads as an untouched box. The- // cornice must clear the projecting corner mullions, not just the- // wall plane, or the roofline still comes out flush.- trim.push(bx(w + 1.3, 0.42, d + 1.3, 0, h + 0.21, 0));- wall.push(bx(w + 0.5, 0.75, d + 0.5, 0, h + 0.42 + 0.375, 0));-- const root = new THREE.Group();- root.name = opts.name || 'Block';- addMerged(root, [[wall, wallMat, 'Walls'],- [trim, trimMat, 'Trim'],- [glassBins[0], glassMats[0], 'Glazing'],- [glassBins[1], glassMats[1], 'Glazing2'],- [dark, darkMat, 'Reveals']], litBins);- root.userData.forward = '-Z';- root.userData.floors = floors + (baseH > 0 ? 1 : 0);- return ownBuilding(root);-}--/**- * A casement window assembly, because a flush quad is not a window.- * The good form in one call: a frame standing proud of the wall, the- * pane recessed >= 0.1 m behind it, a mullion cross, a projecting- * sill, optional louvered shutters hinged open ~55 degrees, and a- * `lit` path that swaps the backing for the warm card `block()` uses.- *- * @param {object} opts- * `w`, `h` opening metres (default 1.1 x 1.4); `frameColor`;- * `shutters` boolean, paired louvered panels hinged open ~55 deg- * (default false); `shutterColor`; `lit` true or a 0..1 chance the- * window glows warm (default 0); `interior` true builds the ROOM- * side of the window instead (see below); `view` `'day' | 'night'`- * for the interior daylight card; `rand` seeded PRNG; `name`.- * @returns {THREE.Group} Centred on the opening, mount plane at z = 0,- * facing -Z (the outside), with `userData.forward`. Position it at- * the window's centre ON the wall face; the frame and sill project- * outward (-Z), the pane and backing sit inside the wall (+Z).- * With `interior: true` the group instead faces +Z (the room).- */-export function casement(opts = {}) {- if (opts.interior) return interiorCasement(opts);- const rand = opts.rand || (() => 0.5);- const w = opts.w || 1.1;- const h = opts.h || 1.4;- const lit = opts.lit === true || (opts.lit ? rand() < opts.lit : false);- const t = Math.max(0.06, w * 0.06); // frame border width- const proud = 0.06; // frame front, beyond the wall- const deep = 0.16; // frame depth, into the wall- const zc = -proud + deep / 2;-- // Joinery paint, held under 0.8 albedo: 0xf4efe6 is a 0.96 white that- // clips against a plaster wall instead of sitting on it.- const frameMat = MAT.paintedWood({ color: opts.frameColor === undefined- ? 0xcbc4b6 : opts.frameColor });- const glassMat = glazing(0x3c4b58);-- // Frame: four borders around the opening, plus the mullion cross that- // splits the glazing into four lights — the depth cue a decal lacks.- const frame = [- bx(w + 2 * t, t, deep, 0, h / 2 + t / 2, zc),- bx(w + 2 * t, t, deep, 0, -h / 2 - t / 2, zc),- bx(t, h, deep, -w / 2 - t / 2, 0, zc),- bx(t, h, deep, w / 2 + t / 2, 0, zc),- bx(0.05, h, 0.05, 0, 0, 0.05),- bx(w, 0.05, 0.05, 0, 0, 0.05),- ];- // The pane sits DEEP in the reveal: >= 0.1 m behind the frame front,- // which is what makes the opening read as depth in raking light.- const pane = bx(w, h, 0.02, 0, 0, proud + 0.02);- // Behind the pane, an interior card: warm-lit when `lit`, dark- // otherwise, so what you see through the glass is never the sky.- const backing = bx(w, h, 0.02, 0, 0, proud + 0.07);- // The sill projects past even the proud frame and sheds the rain.- const sill = bx(w + 2 * t + 0.16, 0.07, 0.24, 0, -h / 2 - t - 0.035,- -0.04);-- const root = new THREE.Group();- root.name = opts.name || 'Casement';- for (const [geos, mat, nm] of [- [frame, frameMat, 'Frame'],- [[sill], frameMat, 'Sill'],- [[pane], glassMat, 'Pane'],- // One window is one room: it draws a WARM class (tungsten or warm- // white), never the cool one — a lone blue window reads as a fault.- [[backing], lit ? litMat(LIT_CLASSES[rand() < 0.5 ? 0 : 1])- : revealMat(), 'Backing']]) {- const merged = geos.length === 1 ? geos[0] : mergeGeometries(geos, false);- const m = new THREE.Mesh(merged, mat);- m.name = nm;- m.castShadow = nm !== 'Backing';- m.receiveShadow = true;- root.add(m);- }-- // Shutters: a stile-and-rail border with tilted louver slats, hinged- // at the jamb and swung ~55 degrees out from the wall plane — the- // form the best audited harbour scene hand-built at 58 degrees.- if (opts.shutters) {- const open = (55 / 180) * Math.PI;- const sw = w * 0.52, sh = h + t;- const st = 0.07, th = 0.03;- const smat = MAT.paintedWood({ color: opts.shutterColor === undefined- ? 0x44584c : opts.shutterColor });- for (const sgn of [-1, 1]) {- // Built extending from the hinge (x = 0) toward the window- // centre, i.e. along -sgn — the CLOSED orientation — then the- // open swing is baked in as a rotation about the hinge.- const cx = -sgn * sw / 2;- const gs = [- bx(sw, st, th, cx, sh / 2 - st / 2, 0),- bx(sw, st, th, cx, -sh / 2 + st / 2, 0),- bx(st, sh, th, -sgn * st / 2, 0, 0),- bx(st, sh, th, -sgn * (sw - st / 2), 0, 0),- ];- const slats = 5;- const span = sh - 2 * st;- for (let i = 0; i < slats; i++) {- const g = new THREE.BoxGeometry(sw - 2 * st, 0.09, 0.02);- g.rotateX(0.6);- g.translate(cx, -span / 2 + (span / slats) * (i + 0.5), 0);- gs.push(g);- }- const merged = mergeGeometries(gs, false);- // -sgn * open swings the free edge toward -Z: outward, off the- // wall, never through it.- merged.applyMatrix4(new THREE.Matrix4().makeRotationY(-sgn * open));- merged.translate(sgn * (w / 2 + t), 0, -proud - th);- const m = new THREE.Mesh(merged, smat);- m.name = sgn < 0 ? 'ShutterL' : 'ShutterR';- m.castShadow = true;- m.receiveShadow = true;- root.add(m);- }- }- root.userData.forward = '-Z';- return ownBuilding(root);-}--/**- * The room side of a window (interior windows ship as black holes —- * the brightest surface a room has reading as its darkest). The film-- * set trick: frame + sill reveal on the room side, a pane, and a- * bright emissive daylight card OUTSIDE the pane, oversized so an- * oblique camera never sees its edge; `view: 'night'` swaps the card.- * Reached via `casement({ interior: true })`; not exported.- *- * @param {object} opts- * `w`, `h` opening metres (default 1.1 x 1.4); `frameColor`;- * `view` `'day'` (default) or `'night'`; `name`.- * @returns {THREE.Group} Centred on the opening, wall plane at z = 0,- * facing +Z (the room), with `userData.forward`. The frame stands- * proud into the room and the sill stool projects past it; the pane- * sits inside the wall (-Z) and the daylight card outside the pane.- */-function interiorCasement(opts) {- const w = opts.w || 1.1;- const h = opts.h || 1.4;- const t = Math.max(0.06, w * 0.06); // frame border width- const proud = 0.06; // frame front, into the room- const deep = 0.16; // frame depth, into the wall- const zc = proud - deep / 2;-- const frameMat = MAT.paintedWood({ color: opts.frameColor === undefined- ? 0xf4efe6 : opts.frameColor });- // Light tint, low opacity: the card behind must shine THROUGH.- const glassMat = MAT.glass({ color: 0xcfe0ee, opacity: 0.3 });-- // Frame borders plus the mullion cross, all on the room side of the- // pane -- the reveal depth that separates a window from a decal.- const frame = [- bx(w + 2 * t, t, deep, 0, h / 2 + t / 2, zc),- bx(w + 2 * t, t, deep, 0, -h / 2 - t / 2, zc),- bx(t, h, deep, -w / 2 - t / 2, 0, zc),- bx(t, h, deep, w / 2 + t / 2, 0, zc),- bx(0.05, h, 0.05, 0, 0, -0.05),- bx(w, 0.05, 0.05, 0, 0, -0.05),- ];- const pane = bx(w, h, 0.02, 0, 0, -(proud + 0.02));- // The daylight card: OUTSIDE the pane (lower Z) and oversized, so an- // oblique interior camera still sees sky, never the card's edge.- const card = bx(w + 0.5, h + 0.5, 0.02, 0, 0, -(proud + 0.09));- const cardMat = opts.view === 'night'- ? litMat({ color: 0x0d1830, emissive: 0x0d1830, intensity: 0.4 })- : litMat({ color: 0xdfeaff, emissive: 0xdfeaff, intensity: 2.2 });- // The stool projects past the proud frame INTO the room.- const sill = bx(w + 2 * t + 0.12, 0.05, 0.24, 0, -h / 2 - 0.025, 0.04);-- const root = new THREE.Group();- root.name = opts.name || 'Casement';- for (const [geo, mat, nm] of [- [mergeGeometries(frame, false), frameMat, 'Frame'],- [sill, frameMat, 'Sill'],- [pane, glassMat, 'Pane'],- [card, cardMat, 'Daylight']]) {- const m = new THREE.Mesh(geo, mat);- m.name = nm;- m.castShadow = nm === 'Frame' || nm === 'Sill';- m.receiveShadow = nm !== 'Daylight';- root.add(m);- }- root.userData.forward = '+Z';- return ownBuilding(root);-}--/**- * A cottage window, built ON a solid wall: a frame ring standing proud- * of the wall face, the pane just outside that face behind the ring, a- * mullion cross and a projecting sill.- *- * The pane CANNOT sit inside the wall the way `casement()`'s does —- * a cottage wall is one solid box with no opening cut in it, so a pane- * behind the face is simply buried (it was, and every cottage window- * shipped as an opaque slab). The depth comes from the proud frame and- * the sill shadow instead.- *- * @param {number} x centre, {number} y centre, {number} z the wall face- * @param {number} s +1 or -1, which way the face looks- * @param {number} ww opening width, {number} wh opening height- * @param {Array} trim geometry sink for frame, cross and sill- * @returns {THREE.BufferGeometry} the pane, for `glass` or a lit bin- */-function cottageWindow(x, y, z, s, ww, wh, trim) {- const t = 0.1; // frame bar- const fz = z + s * 0.09; // ring centre: proud of the wall- trim.push(- bx(ww + 2 * t, t, 0.17, x, y + wh / 2 + t / 2, fz),- bx(ww + 2 * t, t, 0.17, x, y - wh / 2 - t / 2, fz),- bx(t, wh, 0.17, x - ww / 2 - t / 2, y, fz),- bx(t, wh, 0.17, x + ww / 2 + t / 2, y, fz),- bx(0.045, wh, 0.05, x, y, z + s * 0.06),- bx(ww, 0.045, 0.05, x, y, z + s * 0.06),- // The sill projects past even the ring, and its shadow is what- // sells the opening in raking light.- bx(ww + 2 * t + 0.16, 0.06, 0.22, x, y - wh / 2 - t - 0.03,- z + s * 0.1));- return bx(ww, wh, 0.05, x, y, z + s * 0.025);-}--/**- * The same window on a face that does NOT look along Z: built at the- * origin looking -Z, then moved by `M`.- * @returns {THREE.BufferGeometry} the pane- */-function placedWindow(ww, wh, trim, M) {- const local = [];- const pane = cottageWindow(0, 0, 0, -1, ww, wh, local);- for (const g of local) trim.push(g.applyMatrix4(M));- return pane.applyMatrix4(M);-}--/**- * A pitched-roof village building: cottage, shop, inn, centre. The- * roof IS the silhouette — pitch, overhanging eaves, ridge, chimney;- * a village of flat-topped boxes reads as a housing estate.- *- * @param {object} opts- * `w`, `d` footprint metres, `h` wall height to the eaves (default 3),- * `roof` `gable | hip` (default gable), `pitch` roof height as a- * multiple of half-width (default 0.85), `roofColor`, `wallColor`,- * `trimColor` (joinery: frames, sills, door surround), `doorColor`,- * `chimney` boolean (default true), `dormers` count along the -X- * slope (the ridge runs front-to-back, so the gables — door, main- * windows — face +-Z and the slopes face +-X) (default 0),- * `lit` true or a 0..1 fraction of- * windows that glow warm for dusk/night (default 0), `rand` seeded- * PRNG, `name`.- * @returns {THREE.Group} Resting on y=0, centred on x/z, facing -Z.- * Meshes: `Walls`, `Roof`, `Trim` (joinery), `Glazing`, `Door` and,- * when `lit`, `LitRooms*`.- */-export function cottage(opts = {}) {- const rand = opts.rand || (() => 0.5);- const w = opts.w || 7;- const d = opts.d || 6;- const h = opts.h || 3;- const pitch = (opts.pitch === undefined ? 0.85 : opts.pitch) * w / 2;- const eave = Math.max(0.28, w * 0.06); // overhang: reads as a roof-- // Limewash, not a white card: 0xf2ece0 is 0.95 albedo, which under- // exposure 1.0 leaves a cottage the brightest thing in a daylit- // frame — brighter than the sky it stands against.- const wallMat = MAT.tint(MAT.plaster({ color: opts.wallColor === undefined- ? 0xcdc2ae : opts.wallColor }), opts.wallColor === undefined- ? 0.5 + (rand() - 0.5) * 0.6 : 0.5);- // Tile is fired clay, and a roof of it is never ONE red: the seeded- // variant walks the hue and lightness a kiln does.- const roofMat = MAT.terracotta({ color: opts.roofColor === undefined- ? 0xa8492f : opts.roofColor, repeat: 3, hueBreak: 0.18,- variant: opts.roofColor === undefined ? rand() : 0.5, spread: 0.1 });- const trimMat = MAT.paintedWood({ color: opts.trimColor === undefined- ? 0x6b4a33 : opts.trimColor });- const doorMat = MAT.paintedWood({ color: opts.doorColor === undefined- ? 0x3f5148 : opts.doorColor });- const glassMat = glazing(0x3c4b58);- // The lit path block() has and cottage() measurably lacked: at dusk- // every audited failing scene had zero window glow.- const litP = opts.lit === true ? 1 : (opts.lit || 0);-- const walls = [], roof = [], trim = [], glass = [], door = [], stack = [];- const litBins = LIT_CLASSES.map(() => []);- walls.push(bx(w, h, d, 0, h / 2, 0));-- // Windows: a frame ring proud of the wall with the pane behind it —- // NOT a solid slab, which is what a filled frame box reads as.- const bays = Math.max(1, Math.round(w / 2.6));- const ww = Math.min(1.1, w / bays * 0.5), wh = Math.min(1.3, h * 0.45);- for (let i = 0; i < bays; i++) {- const x = -w / 2 + (w / bays) * (i + 0.5);- for (const z of [d / 2, -d / 2]) {- const s = Math.sign(z);- const pane = cottageWindow(x, h * 0.55, z, s, ww, wh, trim);- // A cottage lights room by room, so its warm classes only.- if (litP && rand() < litP) litBins[rand() < 0.6 ? 0 : 1].push(pane);- else glass.push(pane);- }- }- // The EAVES walls (+-X) had no openings at all: whichever way a- // cottage was turned, one long blank elevation faced the camera.- const sideBays = Math.max(1, Math.round(d / 2.8));- for (let i = 0; i < sideBays; i++) {- const z = -d / 2 + (d / sideBays) * (i + 0.5);- for (const sx of [-1, 1]) {- // -Z rotated by -sx*90 deg looks along +-X: the sign matters, the- // wrong one buries the frame in the wall it should stand on.- const M = new THREE.Matrix4().makeRotationY(-sx * Math.PI / 2)- .setPosition(sx * w / 2, h * 0.55, z);- const pane = placedWindow(ww, wh, trim, M);- if (litP && rand() < litP) litBins[rand() < 0.6 ? 0 : 1].push(pane);- else glass.push(pane);- }- }- // Door on the front face: a surround standing proud, a leaf recessed- // inside it, a threshold step. A flush slab reads as painted-on.- const dz = -d / 2;- trim.push(- bx(1.32, 0.14, 0.18, 0, 2.31, dz - 0.09),- bx(0.14, 2.24, 0.18, -0.66, 1.19, dz - 0.09),- bx(0.14, 2.24, 0.18, 0.66, 1.19, dz - 0.09),- bx(1.5, 0.1, 0.5, 0, 0.05, dz - 0.16));- door.push(bx(1.16, 2.18, 0.09, 0, 1.11, dz - 0.045),- bx(0.1, 0.1, 0.06, 0.42, 1.05, dz - 0.12));-- // ROOF. A gable is two slabs meeting at a ridge plus two end walls;- // a hip slopes on all four sides.- const rw = w + eave * 2, rd = d + eave * 2;- if (opts.roof === 'hip') {- const g = new THREE.CylinderGeometry(0.001, Math.SQRT1_2, pitch, 4);- g.rotateY(Math.PI / 4);- g.scale(rw / Math.SQRT2 * Math.SQRT2, 1, rd / Math.SQRT2 * Math.SQRT2);- g.translate(0, h + pitch / 2, 0);- roof.push(g);- } else {- const slope = Math.hypot(pitch, rw / 2);- for (const s of [-1, 1]) {- const g = new THREE.BoxGeometry(slope, 0.16, rd);- g.translate(0, 0, 0);- // NEGATIVE s: the slab's +X end must fall AWAY from the ridge,- // else the roof comes out as a V — invisible in a bbox, so a- // test measures where the roof's high point actually is.- const m = new THREE.Matrix4().makeRotationZ(- -s * Math.atan2(pitch, rw / 2));- g.applyMatrix4(m);- g.translate(s * rw / 4, h + pitch / 2, 0);- roof.push(g);- }- // A ridge cap along the join: the one line every tiled roof has,- // and its absence is why two slabs read as folded cardboard.- roof.push(bx(0.36, 0.15, rd + 0.06, 0, h + pitch - 0.06, 0));- // Gable end walls: a 3-sided cylinder is a prism along its OWN- // axis — rotateX lays it down to face the viewer (rotateY just- // spins it in place). A unit 3-gon spans 1.732 x 1.5 with base at- // y = -0.5, so scale to (w, pitch) and lift the base to the eaves.- //- // The SIGN of that rotateX decides which way up the triangle is,- // and it was positive: three's first radial vertex sits at +Z, so- // +90 deg sends the apex to y = -1 and leaves a FLAT edge at +0.5.- // Measured (rotateX(+PI/2) spans y -1..+0.5, rotateX(-PI/2) spans- // -0.5..+1): every gable shipped upside down, its two top corners- // sticking out through the roof slopes as white wings, and the- // triangle a bbox test sees is identical either way.- for (const s of [-1, 1]) {- const g = new THREE.CylinderGeometry(1, 1, 0.2, 3);- g.rotateX(-Math.PI / 2);- g.scale(w / 1.7320508, pitch / 1.5, 1);- g.translate(0, h + pitch / 3, s * (d / 2 - 0.08));- walls.push(g);- }- }- if (opts.chimney !== false) {- const cx = w * (0.18 + rand() * 0.16);- // A stack is masonry, not limewash: merged into `walls` it came out- // the same white as the cottage and vanished against it.- stack.push(bx(0.7, pitch + 1.1, 0.7, cx, h + (pitch + 1.1) / 2 - 0.2,- d * 0.16));- roof.push(bx(0.92, 0.2, 0.92, cx, h + pitch + 0.85, d * 0.16));- }- // DORMERS RIDE A SLOPE. The ridge runs front-to-back (along Z), so- // the slopes face +-X and the gables face +-Z; a dormer spread along- // X at one Z, as this was, is a box buried INSIDE the roof mass —- // it rendered as nothing at all. They march along the ridge instead,- // set on the -X slope, each protruding through the tiles it sits in.- const nd = opts.dormers || 0;- for (let i = 0; i < nd; i++) {- const z = -d / 2 + (d / (nd + 1)) * (i + 1);- const y = h + pitch * 0.42;- const xs = -(rw / 2) * (1 - 0.42); // the slope surface, at y- walls.push(bx(1.3, 1.1, 1.3, xs - 0.3, y, z));- // Its own little cap, or the dormer is a box growing out of tiles.- roof.push(bx(1.6, 0.13, 1.6, xs - 0.3, y + 0.58, z));- // Built facing -Z, then swung to face -X onto the slope it opens on.- const pane = placedWindow(0.72, 0.62, trim,- new THREE.Matrix4().makeRotationY(Math.PI / 2)- .setPosition(xs - 0.95, y, z));- if (litP && rand() < litP) litBins[rand() < 0.6 ? 0 : 1].push(pane);- else glass.push(pane);- }-- const root = new THREE.Group();- root.name = opts.name || 'Cottage';- // Joinery is NOT roof tile. The frames, sills and door surround used- // to be merged into the Roof mesh and came out terracotta: red- // rectangles pasted on a white wall, which is what the flat-facade- // complaint actually looked like on a cottage.- addMerged(root, [[walls, wallMat, 'Walls'],- [roof, roofMat, 'Roof'],- [stack, MAT.brick({ color: 0x8f5843, variant: rand() }),- 'Chimney'],- [trim, trimMat, 'Trim'],- [door, doorMat, 'Door'],- [glass, glassMat, 'Glazing']], litBins);- root.userData.forward = '-Z';- root.userData.ridgeY = h + pitch;- return ownBuilding(root);-}--/**- * A setback tower: the Manhattan silhouette, in tiers. Towers STEP IN- * as they rise; each tier is a `block()`, so every tier keeps real- * openings.- *- * @param {object} opts- * `w`, `d`, `h` overall metres; `tiers` (default 3); `style` passed- * to `block()`; `taper` fraction each tier narrows by (default 0.22);- * `crown` boolean spire/mast on top (default true); `rand`, `lit`.- * @returns {THREE.Group}- */-export function tower(opts = {}) {- const rand = opts.rand || (() => 0.5);- const tiers = Math.max(1, opts.tiers || 3);- const taper = opts.taper === undefined ? 0.22 : opts.taper;- let w = opts.w || 22, d = opts.d || 20;- const h = opts.h || 90;- const root = new THREE.Group();- root.name = opts.name || 'Tower';- let y = 0;- for (let i = 0; i < tiers; i++) {- // Lower tiers are taller: a stack of equal slabs reads as a layer- // cake, and the real setback ratio is roughly halving.- const share = (tiers - i) / ((tiers * (tiers + 1)) / 2);- const th = h * share;- const t = block({ w, d, h: th, style: opts.style, rand,- lit: opts.lit, ground: i === 0 ? 'storefront' : 'plain' });- t.position.y = y;- t.name = 'Tier' + (i + 1);- root.add(t);- y += th;- w *= 1 - taper; d *= 1 - taper;- }- if (opts.crown !== false) {- const mast = new THREE.Mesh(- new THREE.CylinderGeometry(w * 0.03, w * 0.09, h * 0.09, 8),- MAT.brushedSteel());- mast.position.y = y + h * 0.045;- mast.castShadow = true;- mast.name = 'Crown';- root.add(mast);- }- root.userData.forward = '-Z';- return ownBuilding(root);-}--/**- * Scatter roof furniture on a flat-topped block: water tanks, plant.- * A bare flat roof is the most visible emptiness in an aerial city- * shot after the ground plane itself.- *- * @param {THREE.Object3D} host Block to add onto (roof assumed at its- * bbox top).- * @param {object} opts `rand` (REQUIRED), `tanks` count (default 1),- * `units` HVAC boxes (default 3), `mast` boolean.- * @returns {THREE.Object3D} host- */-export function roofClutter(host, opts = {}) {- const rand = opts.rand || (() => 0.5);- // Clutter becomes a child of the host, so measure the roof in that- // same local frame. A world bbox would apply the host transform twice.- host.updateWorldMatrix(true, true);- const inverse = host.matrixWorld.clone().invert();- const b = new THREE.Box3(), part = new THREE.Box3(), matrix = new THREE.Matrix4();- host.traverse((o) => {- let bounds;- if (o.boundingBox !== undefined) {- if (!o.boundingBox) o.computeBoundingBox();- bounds = o.boundingBox;- } else if (o.geometry) {- if (!o.geometry.boundingBox) o.geometry.computeBoundingBox();- bounds = o.geometry.boundingBox;- }- if (bounds) {- matrix.multiplyMatrices(inverse, o.matrixWorld);- b.union(part.copy(bounds).applyMatrix4(matrix));- }- });- const y = b.max.y;- const w = (b.max.x - b.min.x) * 0.7, d = (b.max.z - b.min.z) * 0.7;- const g = new THREE.Group();- g.name = 'RoofClutter';- g.position.set((b.min.x + b.max.x) * 0.5, 0, (b.min.z + b.max.z) * 0.5);- const wood = MAT.weatheredWood();- const steel = MAT.brushedSteel({ color: 0x8d949b });- for (let i = 0; i < (opts.tanks === undefined ? 1 : opts.tanks); i++) {- const r = Math.min(1.7, w * 0.16);- const tank = new THREE.Mesh(- new THREE.CylinderGeometry(r, r * 1.04, r * 2.1, 12), wood);- const cone = new THREE.Mesh(new THREE.ConeGeometry(r * 1.12, r * 0.7, 12),- wood);- const legs = new THREE.Group();- for (let k = 0; k < 4; k++) {- const a = (k / 4) * Math.PI * 2 + 0.4;- const l = new THREE.Mesh(- new THREE.CylinderGeometry(r * 0.07, r * 0.07, r * 1.5, 6), steel);- l.position.set(Math.cos(a) * r * 0.72, r * 0.75, Math.sin(a) * r * 0.72);- legs.add(l);- }- const t = new THREE.Group();- tank.position.y = r * 1.5 + r * 1.05;- cone.position.y = r * 1.5 + r * 2.1 + r * 0.35;- t.add(legs, tank, cone);- t.position.set((rand() - 0.5) * w, y, (rand() - 0.5) * d);- g.add(t);- }- for (let i = 0; i < (opts.units === undefined ? 3 : opts.units); i++) {- // Its OWN height sets where it sits. A fixed 0.45 lift buried any- // unit over 0.9 m tall in the roof it stands on (measured: 0.09 m- // under, on a box the sampler can make 1.2 m).- const uh = 0.7 + rand() * 0.5;- const u = new THREE.Mesh(- new THREE.BoxGeometry(1.1 + rand(), uh, 0.9 + rand()),- // Plant is replaced piecemeal over decades: three identical grey- // boxes on one axis read as a copy, so each takes its own paint- // bucket and its own yaw.- MAT.tint(steel, rand()));- u.position.set((rand() - 0.5) * w, y + uh / 2, (rand() - 0.5) * d);- u.rotation.y = (rand() - 0.5) * 0.9;- g.add(u);- }- g.traverse((o) => { if (o.isMesh) { o.castShadow = true;- o.receiveShadow = true; } });- ownBuilding(g);- host.add(g);- // Furniture is added after the host's original ownership snapshot.- // Chain its disposer without taking ownership of unrelated children.- const disposeHost = host.userData.dispose;- attachDisposal(host, [- { dispose: () => disposeHost?.() }, { dispose: () => g.userData.dispose() },- ]);- return host;-}--/**- * Block spans and road gaps along one district axis, centred on 0.- *- * Every 4th gap widens to `avenue` when `avenue` is non-zero — the- * Manhattan rhythm of narrow cross-streets against wide avenues.- */-function citySpans(total, cell, street, avenue) {- const cells = [];- const roads = [];- let x = 0;- let i = 0;- while (x + cell <= total + 1e-6) {- cells.push([x, x + cell]);- const gw = avenue && (i + 1) % 4 === 0 ? avenue : street;- if (x + cell + gw + cell <= total + 1e-6) {- roads.push({ center: x + cell + gw / 2, width: gw });- }- x += cell + gw;- i += 1;- }- const off = cells.length ? -cells[cells.length - 1][1] / 2 : 0;- return {- cells: cells.map(([a, b]) => [a + off, b + off]),- roads: roads.map((r) => ({ center: r.center + off, width: r.width })),- };-}--/** Split one block into 2-6 lots: full-width strips, or two columns. */-function cityLots(rand, bw, bd) {- const r = rand();- const n = r < 0.4 ? 2 : r < 0.7 ? 3 : r < 0.85 ? 4 : r < 0.95 ? 5 : 6;- const cols = n <= 3 ? [n] : [Math.floor(n / 2), Math.ceil(n / 2)];- const lots = [];- const cw = bw / cols.length;- for (let c = 0; c < cols.length; c++) {- for (let k = 0; k < cols[c]; k++) {- lots.push({ x: c * cw, z: (bd / cols[c]) * k, w: cw, d: bd / cols[c] });- }- }- return lots;-}--/**- * Fill a district rectangle with believable city fabric in ONE call —- * density is a LAYOUT, not an asset, so this function IS the layout:- * streets/avenues are real gaps, each block subdivides into 2-6 lots,- * every built lot gets a `block()` (or a `tower()` where the skyline- * says tall) with seeded variety, and heights follow `skyline(x, z)`- * so the district reads as one coherent skyline, not uniform stamps.- *- * @param {object} opts- * `rand` seeded PRNG (REQUIRED); `width`, `depth` district metres- * (default 600 x 600); `blockW`, `blockD` block metres (default- * 55 x 90); `streetW` street gap (default 14); `avenueW` every 4th- * north-south street widens to this (default 24); `density` 0..1- * fraction of lots built (default 0.85 — the rest stay empty, like- * parking lots); `skyline` `(x, z) => heightScale` (default 1);- * `styles` array of `block()` styles to draw from; `lit` passed to- * every building for dusk/night; `name`.- * @returns {{group: THREE.Group, buildings: number,- * footprintFrac: number}} `group` rests on y=0, centred on x/z.- * `buildings` is the built count and `footprintFrac` the built lot- * area over district area, so callers and tests can MEASURE- * fullness. `group.userData.streets` lists road centrelines- * (`alongZ: [{x, width}]`, `alongX: [{z, width}]`) for road- * surfaces and traffic routes.- */-export function cityFabric(opts = {}) {- const rand = opts.rand || (() => 0.5);- const width = opts.width || 600;- const depth = opts.depth || 600;- const blockW = opts.blockW || 55;- const blockD = opts.blockD || 90;- const streetW = opts.streetW || 14;- const avenueW = opts.avenueW || 24;- const density = opts.density === undefined ? 0.85 : opts.density;- const skyline = opts.skyline || (() => 1);- const styles = opts.styles || ['masonry', 'brick', 'stone', 'glass'];-- const gx = citySpans(width, blockW, streetW, avenueW);- const gz = citySpans(depth, blockD, streetW, 0);-- const group = new THREE.Group();- group.name = opts.name || 'CityFabric';- group.userData.streets = {- alongZ: gx.roads.map((r) => ({ x: r.center, width: r.width })),- alongX: gz.roads.map((r) => ({ z: r.center, width: r.width })),- };-- let buildings = 0;- let builtArea = 0;- for (let ci = 0; ci < gx.cells.length; ci++) {- const [x0] = gx.cells[ci];- // Which side of this block column fronts an avenue, if either.- const aveEast = (ci + 1) % 4 === 0 && ci + 1 < gx.cells.length;- const aveWest = ci > 0 && ci % 4 === 0;- for (let ri = 0; ri < gz.cells.length; ri++) {- const [z0] = gz.cells[ri];- for (const lot of cityLots(rand, blockW, blockD)) {- if (rand() >= density) continue; // an empty lot, not a hole- // Sidewalk + light-well inset keeps every wall (and the- // cornice that projects past it) strictly inside the block.- const inset = 1.6 + rand() * 1.4;- const lw = lot.w - inset;- const ld = lot.d - inset;- const cx = x0 + lot.x + lot.w / 2;- const cz = z0 + lot.z + lot.d / 2;- const scale = Math.max(0, skyline(cx, cz));- let h = (14 + rand() * 26) * scale * (0.7 + rand() * 0.6);- if (rand() < 0.07) h *= 2.4; // the odd outlier high-rise- h = Math.max(8, h);- const onAvenue = (aveEast && lot.x + lot.w > blockW - 0.5)- || (aveWest && lot.x < 0.5);- const rot = onAvenue && rand() < 0.5;- const style = h > 60 && rand() < 0.5 ? 'glass'- : styles[Math.floor(rand() * styles.length) % styles.length];- const b = h > 60- ? tower({ w: rot ? ld : lw, d: rot ? lw : ld, h, style, rand,- lit: opts.lit, tiers: h > 130 ? 4 : 3 })- : block({ w: rot ? ld : lw, d: rot ? lw : ld, h, style, rand,- lit: opts.lit });- if (rot) b.rotation.y = aveEast ? -Math.PI / 2 : Math.PI / 2;- b.position.set(cx, 0, cz);- group.add(b);- buildings += 1;- builtArea += lw * ld;- }- }- }- ownBuilding(group);- return { group, buildings, footprintFrac: builtArea / (width * depth) };-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/canopy.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/canopy.jsdeleted file mode 100644index 550382b1..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/canopy.js+++ /dev/null@@ -1,484 +0,0 @@-/**- * Canopy: a crown that reads as LEAVES rather than as a green solid.- *- * The failure this replaces is not a lack of effort. A builder given a- * crown reaches for a displaced Icosahedron, and a good one stacks 32- * of them with four octaves of noise — the measured autumn avenue did- * exactly that. It still reads as painted rock, because every one of- * those blobs is a CLOSED CONTINUOUS SURFACE: no gap for the sky to- * come through, one normal field over the whole mass, and one albedo.- * Silhouette is what tells an eye "leaves", and a convex hull has none.- *- * So a crown here is a few thousand separate ovate cards, each with its- * own outward facing, its own tilt and its own hue. Three consequences- * follow, and they are the point:- * - the edge breaks up, because the edge IS leaves;- * - light passes BETWEEN them, so the crown has depth instead of a- * lit side and a dark side;- * - the colour is mixed by the eye, not by the material. Neighbouring- * leaves sit up to `hue` radians apart, which is what a broken-colour- * painter does and what a single MeshStandardMaterial cannot do- * however carefully its one colour is chosen.- *- * Every crown you pass is ONE draw call together — `position` stays at- * zero and each leaf is built in the vertex shader from its instance- * attributes, the same construction `makeGrass` uses for blades. A- * woodland of 40 trees is one mesh, not 40, and not the 158k separate- * meshes the avenue shipped.- */--import * as THREE from 'three';-import { attachDisposal, snapshotResources } from './lifecycle.js';-import { fbm3, mulberry32 } from './noise.js';-import {- glslLocalDir, patchStandard, shadowLike, tickShaders, unit,-} from './shader.js';-import { patchLeafSSS } from './foliage_shade.js';-import { WIND_GUST_GLSL, windOf } from './grass.js';--const LOCAL_DIR = glslLocalDir('leafLocalDir');--/**- * Build the leaf mass for one or more crowns.- *- * Deterministic in `seed`: same seed, same leaves. Drive it from your- * `update` — `canopy.userData.update(t)` — or nothing moves.- *- * @param {object} [opts]- * `crowns` array of `{position: [x, y, z], radius, height?, seed?}`,- * or `{position, size: [x, y, z]}` for a mass that is not a ball —- * a hedge is `size: [0.9, 1.4, 20]`- * in the group's local space — one entry per tree, all sharing the- * single draw call; a lone crown may instead be given as `position`- * + `radius`. `radius` metres of the crown's half-width (default 3),- * `height` its half-height (default `radius * 0.85`, so a crown is- * slightly squat). `leaves` cards per crown — by default it is- * derived from each mass's own surface area, which is the only way- * one number suits both a hedge and an oak;- * `maxLeaves` hard cap over ALL crowns (default 160000 — spread by- * thinning every crown alike, never by dropping the last tree).- * `size` leaf-spray length in metres (default `0.12 *` the mean crown- * radius, so coverage holds at any tree size — set it small only for- * a crown a camera stands under). `color` the albedo of- * a leaf in full sun, `underColor` one deep inside the crown- * (default a darker, cooler form of `color`). `hue` radians of- * leaf-to-leaf hue spread (default 0.30 — this is the broken colour;- * 0 gives back the flat mass). `shell` 0..1 how strongly leaves- * crowd the outer surface (default 0.72; real crowns are hollow).- * `droop` how far a tip falls (default 0.35 of leaf length).- * `backlit` the transmission through a leaf, as `patchLeafSSS` takes- * it (`{sunDir, tint, strength}`) — on by default, because the rim- * of a crown against the sky is lit through and not lit on; `false`- * turns it off. Transmission follows actual scene-light radiance and shadows;- * an explicit `sunDir` below the horizon additionally fades it out.- * `wind` as `makeGrass` takes it. `shadows` cast leaf- * shadows via a- * displaced depth pass (default false — the cost that made grass- * default the same way). `seed` PRNG seed (default 7). `name` group- * name.- * @returns {THREE.Group} Named `Canopy`, holding one `Leaves` mesh,- * with `userData.update(t)`.- */-export function makeCanopy(opts = {}) {- const crowns = crownList(opts);- // A leaf card stands for what the camera can RESOLVE, which at any- // useful distance is a spray, not one leaf. Sized off the mass's- // THINNEST axis, because that is what sets the scale of the foliage- // on it: a 34 m hedge sized off its length grew half-metre leaves.- const thin = crowns.reduce(- (a, c) => a + Math.min(c.rx, c.ry, c.rz), 0) / crowns.length;- const size = opts.size === undefined- ? Math.max(0.05, Math.min(0.4, thin * 0.12))- : opts.size;- const seed = opts.seed === undefined ? 7 : opts.seed;- const shell = unit(opts.shell === undefined ? 0.72 : opts.shell);- const droop = opts.droop === undefined ? 0.35 : opts.droop;- const hue = opts.hue === undefined ? 0.3 : opts.hue;- // Albedos, not screen colours: a scene sun runs at 5-6, so a hex that- // already looks like sunlit foliage tone-maps to pale felt.- const lit = new THREE.Color(- opts.color === undefined ? 0x4d6b28 : opts.color);- const under = new THREE.Color(- opts.underColor === undefined ? shadeOf(lit) : opts.underColor);- const wind = windOf(opts.wind);-- const g = new THREE.Group();- g.name = opts.name || 'Canopy';- const field = leafField(crowns, opts, shell, size, seed);- g.add(leafMesh(field, size, droop, hue, lit, under, wind,- opts.shadows === true,- opts.backlit === false ? null : (opts.backlit || {})));- g.userData.update = g.userData.tick = (t) => tickShaders(g, t);- return attachDisposal(g, snapshotResources(g));-}--/** Clamp to -1..1: the hue offset is scaled by `hue` downstream. */-function clampSigned(v) {- return Math.max(-1, Math.min(1, v));-}--/**- * A leaf in shadow is darker, cooler AND more saturated — never merely- * darker. The old form desaturated it (`s * 0.9`), which is what a- * lightening does, not a shading: mixed against the lit colour across a- * crown it pulled the whole mass toward grey-green felt. A shade leaf is- * physically the more chlorophyll-dense one, so its chroma goes UP as- * its value comes down.- */-function shadeOf(c) {- const hsl = {};- c.getHSL(hsl);- return new THREE.Color().setHSL(- hsl.h + 0.045, Math.min(1, hsl.s * 1.15), hsl.l * 0.3);-}--/** Fade an explicit below-horizon sunlight override; scene lights still set radiance. */-function sunUp(dir) {- if (!dir || dir.y === undefined) return 1;- return unit((dir.y + 0.09) / 0.09);-}--/** Read `crowns`, or the single-crown spelling, into one list. */-function crownList(opts) {- const raw = Array.isArray(opts.crowns) && opts.crowns.length- ? opts.crowns- : [{ position: opts.position, radius: opts.radius }];- return raw.map((c, i) => {- const r = c.radius === undefined ? 3 : c.radius;- const p = c.position || [0, r, 0];- // Per-axis half-extents, because not every leaf mass is a ball. A- // hedge is a long low one, and the first builder offered this- // library wrote its own Icosahedra rather than fake a hedgerow out- // of spheres — its comment said "non-spherical" in as many words.- const sz = Array.isArray(c.size) ? c.size : null;- return {- x: p[0], y: p[1], z: p[2],- rx: sz ? sz[0] : r,- ry: sz ? sz[1] : (c.height === undefined ? r * 0.85 : c.height),- rz: sz ? sz[2] : r,- seed: c.seed === undefined ? i * 131 + 5 : c.seed,- };- });-}--/** Knud Thomsen's approximation; exact enough to set a leaf count. */-function ellipsoidArea(c) {- const p = 1.6;- const a = Math.pow(c.rx, p), b = Math.pow(c.ry, p), d = Math.pow(c.rz, p);- return 4 * Math.PI * Math.pow((a * b + a * d + b * d) / 3, 1 / p);-}--/**- * Place every leaf of every crown.- *- * Leaves crowd the outer shell because that is where a real crown puts- * them and because interior leaves are invisible work: `shell` biases- * the sampled radius, it does not hollow the crown out, so a camera- * looking up through the branches still finds leaves overhead.- */-function leafField(crowns, opts, shell, size, seed) {- const cap = opts.maxLeaves === undefined ? 160000 : opts.maxLeaves;- // Count follows AREA, so coverage — about 1.8 masses-worth of leaf,- // dense enough to read yet open enough to pass sky — holds for a- // hedge and for an oak alike. One fixed count cannot: the same 3100- // cards that clothe a crown leave a 34 m hedgerow bald.- const leafArea = Math.max(1e-4, size * size * 0.5);- const counts = crowns.map((c) => opts.leaves !== undefined- ? opts.leaves- : Math.max(120, Math.round(1.8 * ellipsoidArea(c) / leafArea)));- let total = counts.reduce((a, b) => a + b, 0);- if (total > cap) {- // Thin every mass alike; dropping the last one leaves a gap a- // viewer reads as a missing tree.- const f = cap / total;- for (let i = 0; i < counts.length; i++) {- counts[i] = Math.max(1, Math.floor(counts[i] * f));- }- total = counts.reduce((a, b) => a + b, 0);- }- const n = total;- const pos = new Float32Array(n * 3);- const axis = new Float32Array(n * 3);- const vary = new Float32Array(n * 4);- const sprays = new Float32Array(n * 4);- const box = new THREE.Box3();- let k = 0;- for (let ci = 0; ci < crowns.length; ci++) {- const c = crowns[ci];- const per = counts[ci];- const rand = mulberry32(seed + c.seed);- let spray;- for (let i = 0; i < per; i++, k++) {- if (i % 6 === 0) {- // Direction first, radius second: sampling a box and rejecting- // would thin the poles of every crown alike and read as a seam.- const u = rand() * 2 - 1;- const phi = rand() * Math.PI * 2;- const s = Math.sqrt(Math.max(0, 1 - u * u));- const dx = s * Math.cos(phi), dy = u, dz = s * Math.sin(phi);- const t = Math.pow(rand(), 1 - shell * 0.85);- // A crown is boughs, not a ball: without this the silhouette is- // a perfect sphere and no amount of leaf detail reads as a tree.- // fbm3 is SIGNED about zero — unlike GLSL's astraFbm2, which- // runs 0..0.75 about 0.375. Recentring it here is how the crown- // ends up shrunk to one side.- //- // ONE low frequency, deliberately. A second, finer octave on the- // radius was tried and rendered worse: it scatters leaves ALONG- // the ray instead of moving the shell, so the crown loses the- // dense outer skin that makes it read as mass and thins to a- // haze. Boughs are big; the fine detail is the leaf card itself.- const lump = 1 + 0.42 * fbm3(dx * 1.15, dy * 1.15, dz * 1.15,- { seed: c.seed + 3, octaves: 2 });- spray = {x:c.x+dx*c.rx*t*lump, y:c.y+dy*c.ry*t*lump,- z:c.z+dz*c.rz*t*lump, dx,dy,dz,t,phase:rand()*Math.PI*2};- }- // Six leaves share a short terminal shoot. Alternating pairs and an- // upward-biased shoot turn isolated confetti into coherent foliage.- const {dx,dy,dz,t}=spray;- const along=((i%6)/5-.5)*size*2.2;- const side=i%2===0 ? -1 : 1;- const angle=spray.phase;- const px=spray.x+Math.cos(angle)*along-Math.sin(angle)*size*.24*side;- const py=spray.y+along*.32+Math.sin((i%6)*1.8)*size*.12;- const pz=spray.z+Math.sin(angle)*along+Math.cos(angle)*size*.24*side;- sprays.set([spray.x,spray.y,spray.z,spray.phase],k*4);- pos[k * 3] = px; pos[k * 3 + 1] = py; pos[k * 3 + 2] = pz;- // The outward normal of an ELLIPSOID, not of the unit sphere the- // direction was drawn on: on a long hedge those differ by most- // of a right angle, and the lighting follows the wrong shape.- const nx = dx / c.rx, ny = dy / c.ry, nz = dz / c.rz;- const nl = Math.hypot(nx, ny, nz) || 1;- axis[k * 3] = nx / nl;- axis[k * 3 + 1] = ny / nl;- axis[k * 3 + 2] = nz / nl;- vary[k * 4] = 0.62 + rand() * 0.76; // size- // Hue in two scales. Per-leaf alone averages back to one green- // at any distance — a canopy Monet paints turns warm in whole- // passages and cool in others, and that is the scale that- // survives being seen from across the street.- vary[k * 4 + 1] = clampSigned(- (rand() * 2 - 1) * 0.45- + fbm3(px * 0.42, py * 0.42, pz * 0.42,- { seed: c.seed + 61, octaves: 2 }) * 1.5);- vary[k * 4 + 2] = rand() * Math.PI * 2; // twist / phase- // Depth into the crown, plus a lift for the leaves the sky sees:- // a canopy is lit from ABOVE, not evenly over its shell.- vary[k * 4 + 3] = unit(t * (0.72 + 0.28 * (dy * 0.5 + 0.5)));- box.expandByPoint(new THREE.Vector3(px, py, pz));- }- }- return { n, pos, axis, vary, sprays, box };-}--/** The one instanced mesh every crown shares. */-function leafMesh(field, size, droop, hue, lit, under, wind, shadows,- backlit) {- // Segmented along its length: the ovate profile is zero at BOTH- // ends, so a single quad's four corners all collapse to zero width- // and the crown draws nothing at all.- const base = new THREE.PlaneGeometry(1, 1, 2, 6);- const geom = new THREE.InstancedBufferGeometry();- geom.index = base.index;- geom.setAttribute('position', new THREE.BufferAttribute(- new Float32Array(base.attributes.position.count * 3), 3));- geom.setAttribute('aCorner', base.attributes.position);- geom.setAttribute('uv', base.attributes.uv);- geom.setAttribute('normal', base.attributes.normal);- geom.instanceCount = field.n;- const inst = (name, arr, sz) => geom.setAttribute(- name, new THREE.InstancedBufferAttribute(new Float32Array(arr), sz));- inst('iPos', field.pos, 3);- inst('iAxis', field.axis, 3);- inst('iVar', field.vary, 4);- inst('iSpray', field.sprays, 4);- // position is zero, so the derived bounds would be a point at the- // origin: state the crowns' real box, and never cull on it.- geom.boundingBox = field.box.clone().expandByScalar(size * (1.6 + Math.abs(droop)) + Math.abs(wind.amp) * (1 + size));- geom.boundingSphere = geom.boundingBox.getBoundingSphere(- new THREE.Sphere());-- // 0.78 measured against 0.70 and 0.82 on our pipeline and kept: a- // leaf IS waxy, but with no post chain the dielectric lobe reflects a- // bright sky straight into the crown's crest, and 0.70 traded 0.02 of- // measured foliage saturation for that gloss. 0.78 keeps the sheen at- // grazing angles without chalking the top of the tree.- const mat = new THREE.MeshStandardMaterial({- color: 0xffffff, roughness: 0.78, metalness: 0,- side: THREE.DoubleSide, name: 'CanopyLeaf',- });- patchStandard(mat, {- name: 'canopy:leaf',- uniforms: {- uLeafLit: { value: lit.clone() },- uLeafUnder: { value: under.clone() },- uLeafSize: { value: size },- uLeafDroop: { value: droop },- uLeafHue: { value: hue },- uLeafWind: { value: wind.dir.clone() },- uLeafAmp: { value: wind.amp },- uLeafSpeed: { value: wind.speed },- },- vertexHead: LEAF_HEAD,- vertexBody: LEAF_VERTEX,- fragmentHead: [- 'uniform vec3 uLeafLit;',- 'uniform vec3 uLeafUnder;',- 'varying vec3 vLeaf;',- 'varying vec2 vLeafB;',- ].join('\n'),- fragmentBody: LEAF_FRAGMENT,- });-- // A crown without the backlit glow is a black rim against the sky:- // the underside leaves take no sun and no bounce, and only light- // coming THROUGH them says foliage rather than soot.- if (backlit) {- const amt = backlit.strength === undefined ? 0.44 : backlit.strength;- patchLeafSSS(mat, { sunDir: backlit.sunDir, tint: backlit.tint,- strength: amt * sunUp(backlit.sunDir) });- }- const mesh = new THREE.Mesh(geom, mat);- mesh.name = 'Leaves';- mesh.frustumCulled = false;- mesh.receiveShadow = true;- // Without the displaced depth pass a shadow pass draws only the- // degenerate zero-position quads, so casting stays off by default.- mesh.castShadow = false;- if (shadows) {- shadowLike(mesh, 'canopy:leafDepth', LEAF_HEAD, LEAF_VERTEX);- }- return mesh;-}--const LEAF_HEAD = [- 'uniform float uTime;',- 'uniform float uLeafSize;',- 'uniform float uLeafDroop;',- 'uniform float uLeafHue;',- 'uniform vec2 uLeafWind;',- 'uniform float uLeafAmp;',- 'uniform float uLeafSpeed;',- 'attribute vec3 aCorner;',- 'attribute vec3 iPos;',- 'attribute vec3 iAxis;',- 'attribute vec4 iVar;',- 'attribute vec4 iSpray;',- 'varying vec3 vLeaf;',- // Per-leaf constants the FRAGMENT grade needs and the geometry does- // not: x a decorrelated lightness draw, y how far the leaf's own- // facing looks at the sky. Both are constant over a card, so they- // ride a varying rather than being recomputed per pixel.- 'varying vec2 vLeafB;',- LOCAL_DIR, WIND_GUST_GLSL,-].join('\n');--const LEAF_VERTEX = [- ' vec3 lfN = normalize(iAxis * 0.38 + vec3(cos(iSpray.w) * 0.30, 0.78, sin(iSpray.w) * 0.30));',- // Any stable tangent will do, but the naive cross with +Y collapses- // for the leaves at the crown's top and bottom.- ' vec3 lfRef = abs(lfN.y) > 0.9 ? vec3(1.0, 0.0, 0.0)',- ' : vec3(0.0, 1.0, 0.0);',- ' vec3 lfT = normalize(cross(lfRef, lfN));',- ' vec3 lfB = cross(lfN, lfT);',- ' float lfTw = iVar.z;',- ' vec3 lfE1 = lfT * cos(lfTw) + lfB * sin(lfTw);',- ' vec3 lfE2 = -lfT * sin(lfTw) + lfB * cos(lfTw);',- // Ovate: widest past the middle, drawn to a point at the tip. This- // profile IS the silhouette, and the silhouette is the whole reason- // for the card.- ' float lfV = aCorner.y + 0.5;',- ' float lfProf = sin(3.14159 * pow(lfV, 0.72));',- ' float lfS = iVar.x * uLeafSize;',- ' vec2 lfC = vec2(aCorner.x * lfProf, aCorner.y);',- ' vec3 lfP = iPos + lfE1 * (lfC.x * lfS) + lfE2 * (lfC.y * lfS);',- ' lfP.y -= uLeafDroop * lfS * lfV * lfV;',- ' lfP += lfN * (0.08 * lfS * sin(3.14159 * lfV) * (1.0 - 4.0 * aCorner.x * aCorner.x));',- // Gusts are streaks running downwind, as in the grass: the same wind- // has to move a meadow and the trees over it alike.- ' vec3 lfW3 = leafLocalDir(vec3(uLeafWind.x, 0.0, uLeafWind.y));',- ' vec2 lfW = normalize(lfW3.xz + vec2(1e-5, 0.0));',- ' vec3 lfRootWorld = (modelMatrix * vec4(iSpray.xyz, 1.0)).xyz;',- ' float lfG = astraWindGust(lfRootWorld, uLeafWind,',- ' uTime * uLeafSpeed, vec2(0.05, 0.2));',- ' float lfT2 = uTime * uLeafSpeed;',- // Outer leaves move most: the trunk end of a bough barely travels.- ' float lfSway = uLeafAmp * (0.2 + 1.1 * lfG) * iVar.w',- ' * (0.6 + 0.4 * sin(lfT2 * 1.7 + iSpray.w));',- ' lfP.xz += lfW * lfSway * 0.45;',- // Flutter is the leaf turning on its own stem, which is what catches- // the light — a card that only translates reads as dead foliage.- ' float lfFl = uLeafAmp * (0.35 + 0.65 * lfG)',- ' * sin(lfT2 * 3.1 + iVar.z * 2.3);',- ' lfP += lfN * (lfFl * lfC.y * lfS * 0.9);',- ' transformed = lfP;',- ' vLeaf = vec3(iVar.w, iVar.y * uLeafHue, lfV);',- // Decorrelated from hue, size and twist alike, so no two neighbours- // agree on VALUE either. Hue spread on its own still averages to one- // even green at a distance; a crown's real dazzle is that some leaves- // catch and some do not.- ' float lfJit = fract(sin(iVar.z * 91.7 + dot(iPos.xz, vec2(12.9898,',- ' 78.233))) * 43758.5453);',- ' vLeafB = vec2(lfJit, lfN.y * 0.5 + 0.5);',- '#ifndef FLAT_SHADED',- // The normal follows the actual curved blade, including droop and flutter.- ' float lfProfD = 3.14159 * 0.72 * pow(max(lfV, 0.001), -0.28)',- ' * cos(3.14159 * pow(lfV, 0.72));',- ' vec3 lfDx = lfE1 * (lfProf * lfS) - lfN * (0.64 * aCorner.x * lfS * sin(3.14159 * lfV));',- ' vec3 lfDy = lfE1 * (aCorner.x * lfProfD * lfS) + lfE2 * lfS',- ' - vec3(0.0, 2.0 * uLeafDroop * lfS * lfV, 0.0)',- ' + lfN * (0.08 * lfS * 3.14159 * cos(3.14159 * lfV)',- ' * (1.0 - 4.0 * aCorner.x * aCorner.x) + lfFl * lfS * 0.9);',- ' vec3 lfNormal = cross(lfDx, lfDy);',- ' if (dot(lfNormal, lfNormal) < 1e-10) lfNormal = lfN;',- ' vNormal = normalize(normalMatrix * normalize(lfNormal));',- '#endif',-].join('\n');--const LEAF_FRAGMENT = [- // Depth runs 0.26..0.89 over a crown (measured), so a straight mix- // never reached either end and the interior colour was decoration- // that never showed. Widen it to the range the field actually- // occupies and the crown gets an inside.- ' vec3 lfC = mix(uLeafUnder, uLeafLit,',- ' smoothstep(0.18, 0.88, vLeaf.x));',- // The hue spread between neighbours is the broken colour; without it- // the mass returns to one flat green however many cards it holds.- ' lfC = astraHueShift(lfC, vLeaf.y);',- // Sun leaves and shade leaves are not one leaf at two brightnesses:- // the ones the sky sees are thinner and yellower, the ones facing the- // ground keep their chlorophyll and read cool. This is a real- // botanical split and it is what gives a crown its warm crest.- ' lfC *= mix(vec3(0.92, 1.0, 1.06), vec3(1.12, 1.04, 0.82),',- ' vLeafB.y * vLeafB.y);',- // Value spread leaf to leaf, +-20%: the broken-colour painter varies- // the tone as much as the hue.- ' lfC *= 0.80 + 0.40 * vLeafB.x;',- // The crown's own occlusion. A shadow map sized for a whole scene has- // texels far larger than a leaf, so it can shade the crown's broad- // underside but never the metre of leaf a ray crosses on its way in —- // and without that the inside of a tree is as bright as its rim,- // which is the single clearest tell of fake foliage. Depth is the- // only occlusion signal there is here, and it is a good one.- ' lfC *= 0.55 + 0.45 * smoothstep(0.05, 0.85, vLeaf.x);',- // Sky occlusion, the other half of the same story: a leaf on the- // underside of a crown sees a hand's width of sky and a great deal of- // leaf, and it is this — not the sun — that draws the dark belly- // under a tree and the bright crest over it. Without it a crown lit- // by a bright environment has the same value top and bottom, which is- // why the first render read as a flat pale disc.- ' lfC *= 0.62 + 0.38 * vLeafB.y;',- // A leaf is thin: the light behind it comes through near the tip,- // where there is least of it — and it comes through WARM, because- // what survives a leaf is the red end. Adding the leaf's own colour- // back (the old form) only raised its value and paled the crown.- ' lfC += uLeafLit * vec3(1.5, 1.15, 0.5) * 0.19',- ' * smoothstep(0.45, 1.0, vLeaf.z) * vLeaf.x;',- // Albedo, not a screen colour: hold the whole crown inside the band a- // physical dielectric occupies, so no leaf can blow out under a sun- // running at 5-6 and none goes to a black chip in shade. The floor is- // TINTED — a flat grey floor is how a deep crown loses its colour- // exactly where the two occlusions have made it most saturated.- ' vec3 lfFloor = max(uLeafUnder * 0.25, vec3(0.012));',- ' diffuseColor.rgb = clamp(lfC, lfFloor, vec3(0.8));',-].join('\n');diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/celestial.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/celestial.jsdeleted file mode 100644index 1da8bb72..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/celestial.js+++ /dev/null@@ -1,854 +0,0 @@-/**- * The sky above the scene, and the air that bends what is behind it.- *- * Two different jobs share this file because both live OUTSIDE the- * lit world and both are additive-or-nothing:- *- * A SHIMMER IS NOT A THING YOU CAN SEE. Heat haze has no colour, no- * silhouette and no shape — it is the image behind it, moved. So this- * one never emits a pixel of its own: it grabs the frame drawn so far- * into a texture and resamples it at displaced coordinates. That grab- * is a framebuffer COPY, not a second scene render (a `Reflector`- * re-renders the WHOLE scene at +48 ms/frame on SwiftShader; a copy of- * a frame already drawn is a blit). What it costs and what it cannot- * do is written out on `makeHeatShimmer`.- *- * A NIGHT SKY IS THE DARK FRAME ADDED LIGHT SURVIVES. Stars and- * aurora both ADD light, which is right only while the frame behind- * them is dark — godrays.js measured 12.8% of a pale frame blown past- * 0.97 by exactly this. So both take the same `ambient` escape it has.- * The DEFAULT is the night build, because a star field belongs to- * exactly one frame and that frame is dark; `ambient: 0.9` still buys- * the blend that cannot clip, and it is still measurably harmless over- * a daylight sky (blown_frac 0.0000 on this renderer).- *- * Nothing here is tone-map-exempt except the shimmer, so all of it is- * graded for ACES at exposure 1.0 with no post chain: added light that- * reaches alpha 1 comes back out of the curve WHITE, so the aurora- * saturates toward a ceiling below 1 and the band's gain is spent on- * structure rather than on level.- *- * Neither sky field writes depth, casts a shadow or takes part in fog:- * a star is at infinity and `FogExp2` at the night density erases- * anything past ~400 m, which is why `worldShell()`'s own dome runs- * `fog: false` too.- */--import * as THREE from 'three';-import { attachDisposal, snapshotResources } from './lifecycle.js';--import { lehmer } from './noise.js';-import {- instancedQuad, keepOutOfDepthPasses, makeShaderMaterial,- tickShaders } from './shader.js';--// Backdrop paint order among TRANSPARENT meshes. three renders every-// opaque object before any transparent one whatever renderOrder says,-// so these only sort the sky against itself; depth testing is what-// keeps the scene in front of it.-const ORDER_MILKYWAY = -1.75;-const ORDER_STARS = -1.70;-const ORDER_AURORA = -1.60;-const ORDER_SHIMMER = 20;--const _SIZE = new THREE.Vector2();--/**- * Copy the frame drawn so far into a texture the shimmer can sample.- *- * `renderer.copyFramebufferToTexture` cannot do this job: measured on- * ANGLE/D3D12, `copyTexSubImage2D` is INVALID_OPERATION out of the- * MULTISAMPLED buffer every renderer here draws into (the composer- * runs 4x MSAA, the canvas `antialias: true`), and again into an sRGB- * destination. A resolve BLIT survives both, on one condition: the- * destination's internal format must equal the source's exactly — so- * the type is taken from the bound target (HalfFloat under the post- * chain, byte straight to canvas) and the colour space left off, or- * three allocates SRGB8_ALPHA8 and the copy is refused again.- *- * This is a resolve of a frame already drawn, not a second pass over- * the scene: it does not render the scene again.- */-function frameGrabber(mat) {- let tex = null;- let fbo = null;- let context = null;- let disposed = false;- let warned = false;- const release = () => {- if (tex) tex.dispose();- if (fbo && context) context.deleteFramebuffer(fbo);- tex = null;- fbo = null;- mat.uniforms.uScene.value = null;- };- const grab = (renderer) => {- if (disposed) return;- const gl = renderer.getContext();- if (context && context !== gl) release();- context = gl;- if (typeof gl.blitFramebuffer !== 'function') {- if (!warned) {- warned = true;- console.warn(- 'makeHeatShimmer: no WebGL2 blitFramebuffer — the ' +- 'card cannot read the frame and draws nothing.');- }- return;- }- const rt = renderer.getRenderTarget();- if (rt) _SIZE.set(rt.width, rt.height);- else renderer.getDrawingBufferSize(_SIZE);- const w = _SIZE.x, h = _SIZE.y;- const type = rt ? rt.texture.type : THREE.UnsignedByteType;- if (!tex || tex.image.width !== w || tex.image.height !== h- || tex.type !== type) {- if (tex) tex.dispose();- if (fbo) { gl.deleteFramebuffer(fbo); fbo = null; }- tex = new THREE.FramebufferTexture(w, h);- tex.type = type;- tex.colorSpace = THREE.NoColorSpace;- tex.minFilter = THREE.LinearFilter;- tex.magFilter = THREE.LinearFilter;- mat.uniforms.uScene.value = tex;- }- renderer.initTexture(tex);- const handle = renderer.properties.get(tex).__webglTexture;- if (!handle) return;- if (!fbo) fbo = gl.createFramebuffer();- const prev = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING);- try {- gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, fbo);- gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0,- gl.TEXTURE_2D, handle, 0);- gl.blitFramebuffer(0, 0, w, h, 0, 0, w, h,- gl.COLOR_BUFFER_BIT, gl.NEAREST);- } finally {- // Restore even if an integration supplies a throwing GL wrapper.- gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, prev);- }- mat.uniforms.uResolution.value.set(w, h);- // Straight to canvas the frame is already sRGB-encoded and- // <colorspace_fragment> is about to encode it again; into a- // render target it is linear and that chunk is identity.- mat.uniforms.uEncoded.value =- (!rt && renderer.outputColorSpace === THREE.SRGBColorSpace)- ? 1 : 0;- };- grab.dispose = () => {- if (disposed) return;- disposed = true;- release();- context = null;- };- return grab;-}--/**- * Air over a fire, an exhaust or a summer road: the backdrop, moved.- *- * Draws NOTHING of its own. The fragment's only colour source is a- * copy of the frame taken the instant before this card is drawn,- * sampled at coordinates pushed around by a rising noise field — so- * there is no shape to see, only a wobble in whatever stands behind.- * Verified over a striped backdrop: a stripe edge travels about 6 px- * in a 560 px frame at the default strength.- *- * WHAT IT CANNOT DO, because the copy carries colour and no depth:- * (1) an object standing IN FRONT of the card can be smeared into it,- * since the sample has no way to reject a nearer pixel — keep the card- * behind the things it belongs to; (2) it cannot displace anything- * drawn AFTER it (a later transparent pass, bloom, the AO blend);- * (3) it costs one full-frame copy per shimmer per view, so use one- * card per heat source, not a field of them.- *- * @param {object} [opts]- * `width` / `height` card size in metres (default 2.4 x 3.2); the- * card billboards about its own centre and rests on y = 0, so put- * the group AT the fire; `strength` peak displacement as a fraction- * of FRAME HEIGHT (default 0.012 — refraction is an angle, so the- * screen shift of a distant plume is the same as a near one);- * `speed` how fast the cells rise (default 1); `cells` how many- * convection cells span the card's height (default 3.4 — fewer is- * an engine's slow roll, more is a fire's boil); `seed` PRNG seed- * (default 5).- * @returns {THREE.Group} Named `HeatShimmer`, resting on y = 0, with- * `userData.update(t)`. No `ambient` escape and none needed: a- * material whose output IS the backdrop cannot brighten a frame it- * never adds to.- */-export function makeHeatShimmer(opts = {}) {- const width = opts.width === undefined ? 2.4 : opts.width;- const height = opts.height === undefined ? 3.2 : opts.height;- const strength = opts.strength === undefined ? 0.012 : opts.strength;- const speed = opts.speed === undefined ? 1 : opts.speed;- // Cell SIZE is set by the air, not by the card: scaling the count- // with the card keeps a metre-wide cell on a 3 m plume and on a- // 30 m one, where a fixed count would give the big card boulders.- const cells = opts.cells === undefined- ? Math.max(2.5, height / 0.95) : opts.cells;- const rnd = lehmer(opts.seed === undefined ? 5 : opts.seed);-- // The billboard sweeps a sphere about the card's centre, which is- // half a card up: a stated radius, never instancedQuad's 10 km- // default, or a rig that frames on it frames 10 km of empty air.- const reach = height * 0.5 + Math.hypot(width, height) * 0.5;- const geom = instancedQuad(1, width, height, reach);- const mat = shimmerMaterial(- strength, speed, cells, width / height, height, rnd() * 97);- const mesh = new THREE.Mesh(geom, mat);- mesh.name = 'HeatShimmer';- // Last of the transparents, so the copy holds everything the- // shimmer is supposed to bend.- mesh.renderOrder = ORDER_SHIMMER;-- const g = new THREE.Group();- g.name = 'HeatShimmer';- g.add(mesh);- keepOutOfDepthPasses(g);- // keepOutOfDepthPasses OWNS onBeforeRender (it blanks the draw- // range under an override material), so the grab wraps its guard- // instead of replacing it — and only fires for our own material,- // never inside the AO or shadow pass.- const guard = mesh.onBeforeRender;- const grab = frameGrabber(mat);- mesh.onBeforeRender = (r, s, cam, geo, m) => {- guard.call(mesh, r, s, cam, geo, m);- if (m === mat) grab(r);- };- g.userData.update = g.userData.tick = (t) => tickShaders(g, t);- const owned = snapshotResources(g);- owned.add(grab);- return attachDisposal(g, owned);-}--/** Resample the grabbed frame; emit no colour that is not in it. */-function shimmerMaterial(strength, speed, cells, aspect, height, phase) {- return makeShaderMaterial({- name: 'HeatShimmer',- uniforms: {- uScene: { value: null },- uResolution: { value: new THREE.Vector2(1, 1) },- uEncoded: { value: 0 },- uStrength: { value: strength },- uSpeed: { value: speed },- uCells: { value: cells },- uAspect: { value: aspect },- uPhase: { value: phase },- uCentre: { value: new THREE.Vector3(0, height * 0.5, 0) },- },- varyings: 'varying vec2 vUv;',- vertexHead: 'attribute vec3 aCorner; uniform vec3 uCentre;',- vertexMain: [- ' vUv = uv;',- // Rows of the model-view rotation are the LOCAL directions- // that map to screen x and y, so the card faces the camera- // whatever the group is turned to.- ' mat3 mv3 = mat3(modelViewMatrix);',- ' vec3 rt = vec3(mv3[0][0], mv3[1][0], mv3[2][0]);',- ' vec3 up = vec3(mv3[0][1], mv3[1][1], mv3[2][1]);',- ' transformed = uCentre + rt * aCorner.x + up * aCorner.y;',- ].join('\n'),- fragmentHead: [- 'uniform sampler2D uScene;',- 'uniform vec2 uResolution;',- 'uniform float uStrength; uniform float uSpeed;',- 'uniform float uCells; uniform float uAspect;',- 'uniform float uPhase; uniform float uEncoded;',- // The exact sRGB EOTF, because this has to be the precise- // inverse of the encode three is about to re-apply.- 'vec3 astraCelDecode(vec3 c) {',- ' return mix(pow((c + 0.055) / 1.055, vec3(2.4)),',- ' c / 12.92, step(c, vec3(0.04045)));',- '}',- ].join('\n'),- fragmentMain: [- ' vec2 uv = gl_FragCoord.xy / uResolution;',- ' float t = uTime * uSpeed;',- ' vec2 q = vec2(vUv.x * uCells * uAspect, vUv.y * uCells);',- // Cells RISE, so the field scrolls down through them, and- // the two axes read different noise or the whole card- // slides sideways as one sheet.- ' float nx = astraFbm2(q + vec2(uPhase, -t), 3);',- ' float ny = astraFbm2(q + vec2(uPhase + 31.7, -t * 1.27),',- ' 3);',- // astraFbm2 lands in 0..0.875 about a mean of 0.4375 and- // its octaves almost never align, so the raw signal swings- // by about a tenth: centred and stretched, or uStrength- // means a twelfth of what it says.- ' vec2 n = clamp((vec2(nx, ny) - 0.4375) * 4.0,',- ' vec2(-1.0), vec2(1.0));',- // Hot air spreads and slows as it climbs, so the wobble- // grows up the plume rather than being uniform.- ' vec2 push = n * uStrength * (0.30 + 0.95 * vUv.y);',- // uStrength is a fraction of frame HEIGHT; x has to be- // divided by the aspect or the wobble is anisotropic.- ' push.x *= uResolution.y / uResolution.x;',- ' vec3 behind = texture2D(uScene, uv + push).rgb;',- ' behind = mix(behind, astraCelDecode(behind), uEncoded);',- // The envelope: a plume, not a rectangle. A hard edge here- // is the one way this effect becomes a visible shape.- ' float wan = (astraFbm2(vec2(uPhase, vUv.y * 1.7 - t * 0.5),',- ' 2) - 0.5) * 0.34;',- ' float u = abs(vUv.x - 0.5 + wan) * 2.0;',- ' float body = 0.45 + 0.85 * astraFbm2(q * 0.75',- ' + vec2(uPhase, -t * 0.7), 3);',- ' float a = (1.0 - smoothstep(0.30, 1.0, u))',- ' * smoothstep(0.0, 0.12, vUv.y)',- ' * (1.0 - smoothstep(0.40, 1.0, vUv.y)) * body;',- ' a = clamp(a * 1.9, 0.0, 1.0);',- ' if (a < 0.004) discard;',- ' gl_FragColor = vec4(behind, a);',- ].join('\n'),- // additive:true buys the ALPHA fade into fog — the ordinary- // fog chunk would mix the resampled pixel toward the fog- // colour, which paints haze the frame already has. The blend- // stays NORMAL: this replaces pixels, it does not add light.- additive: true,- blending: THREE.NormalBlending,- // Tone mapping already happened to the pixels being resampled;- // running it again is the one way this shader could change a- // colour instead of moving it.- toneMapped: false,- depthWrite: false,- transparent: true,- side: THREE.DoubleSide,- });-}--/**- * A night sky: mostly faint stars, a Milky Way, and a slow twinkle.- *- * Brightness is drawn from the real one — the number of stars brighter- * than magnitude m grows as 10^(0.6 m), so half of any field sits past- * magnitude 5.5 and under 1% of it is what anyone would call bright.- * A field of equal dots is the giveaway that it was not.- *- * Sits OUTSIDE the world and never occludes it: no depth write, no- * shadow, and every star fades out below ~6 degrees of elevation the- * way real extinction takes them, so a horizon ridge is never speckled.- * Its meshes are named `StarField` / `MilkyWayStars` on purpose — the- * scene renderer keys its content-fit and occluder filters on `star` /- * `sky` in a mesh name, and a 2 km sphere that misses those filters- * becomes the content bbox and pushes every camera out of the scene.- *- * Combine with a dome, never instead of one: `worldShell({mood:- * 'night'})` (lib/environment.js) draws the gradient this sits in- * front of, or `makeSky(scene, { rig })` with a night `sunRig()` for- * a graded physical dome. Neither writes depth (`scene.background`- * is only the clear colour behind them), so the stars paint over- * either one.- *- * @param {object} [opts]- * `count` stars (default 1400); `radius` metres to the star sphere- * (default 2000 — inside `worldShell`'s 4 km dome and the camera's- * far plane, outside any content); `magnitude` overall brightness- * gain for both stars and unresolved Milky Way light (default 1;- * 0 hides both); `twinkle` scintillation depth 0..1 (default- * 0.35, over periods of 4-9 s); `milkyWay` the band of unresolved- * light, which also pulls part of the field into it (default true);- * `seed` PRNG seed (default 3); `ambient` how bright the frame- * behind is, 0 a real night to 1 daylight (default 0.2). Added- * light cannot see what it adds to, so from 0.35 up the field- * switches from ADDING to a plain blend that cannot clip; pass- * `ambient: 0.9` when the sky behind is genuinely bright.- * @returns {THREE.Group} Named `Stars`, centred on the camera's world- * — put it at the origin — with `userData.update(t)`.- */-export function makeStars(opts = {}) {- const count = Math.max(1, Math.round(- opts.count === undefined ? 1400 : opts.count));- const radius = opts.radius === undefined ? 2000 : opts.radius;- const gain = Math.max(0, opts.magnitude === undefined ? 1 : opts.magnitude);- const twinkle = Math.min(Math.max(- opts.twinkle === undefined ? 0.35 : opts.twinkle, 0), 1);- const seed = opts.seed === undefined ? 3 : opts.seed;- // 0.2, not the 0.85 this shipped with. A star field belongs to ONE- // frame — a night one — and at 0.85 the safe blend put the whole- // sky inside a single 8-bit bucket on this renderer (modal_frac- // 0.95, sky luminance flat at 0.19): the catalog promised stars and- // the frame had none. The bright build is still one argument away.- const ambient = Math.min(Math.max(- opts.ambient === undefined ? 0.2 : opts.ambient, 0), 1);- const bright = ambient >= 0.35;- const rnd = lehmer(seed);- // Galactic pole: the band is a great circle, so one vector fixes- // where it crosses the sky.- const pole = new THREE.Vector3(0.34, 0.83, -0.44).normalize();-- const g = new THREE.Group();- g.name = 'Stars';- if (opts.milkyWay !== false) g.add(milkyWayMesh(radius, pole, bright, gain));- g.add(starMesh(count, radius, gain, twinkle, rnd, pole, bright,- opts.milkyWay !== false));- g.userData.update = g.userData.tick = (t) => tickShaders(g, t);- return attachDisposal(keepOutOfDepthPasses(g), snapshotResources(g));-}--/**- * Relative flux for one star, drawn from the magnitude distribution.- *- * Inverse-samples N(<= m) ~ 10^(0.6 m) over magnitude 0..6 and returns- * the linear flux 10^(-0.4 m) — 1 for the brightest star in the field,- * 0.004 for the faintest, median about 0.006. That skew IS the sky.- */-function starFlux(u) {- const top = Math.pow(10, 0.6 * 6);- const m = Math.log(1 + u * (top - 1)) / Math.LN10 / 0.6;- return Math.pow(10, -0.4 * m);-}--/** The stars themselves: GTAO-safe billboards, one per instance. */-function starMesh(count, radius, gain, twinkle, rnd, pole, bright,- banded) {- const geom = instancedQuad(count, 1, 1, radius * 1.02);- const dir = new Float32Array(count * 3);- const star = new Float32Array(count * 4);- const v = new THREE.Vector3();- for (let i = 0; i < count; i++) {- // Upper hemisphere only: a star under the horizon is a star- // behind the ground, and the shader fades the last few degrees.- v.set(rnd() * 2 - 1, rnd(), rnd() * 2 - 1);- if (v.lengthSq() < 1e-6) v.set(0, 1, 0);- v.normalize();- // Part of the field belongs to the band: flattening a share of- // it toward the galactic plane is what makes the Milky Way- // read as stars rather than as painted haze.- if (banded && rnd() < 0.42) {- v.addScaledVector(pole, -v.dot(pole) * (0.55 + 0.4 * rnd()));- v.normalize();- }- dir[i * 3] = v.x; dir[i * 3 + 1] = v.y; dir[i * 3 + 2] = v.z;- star[i * 4] = starFlux(rnd());- star[i * 4 + 1] = rnd();- // 4-9 s periods: the eye reads anything faster as fireflies.- star[i * 4 + 2] = 0.7 + 0.85 * rnd();- star[i * 4 + 3] = rnd();- }- geom.setAttribute('aDir', new THREE.InstancedBufferAttribute(dir, 3));- geom.setAttribute('aStar', new THREE.InstancedBufferAttribute(star, 4));- const mesh = new THREE.Mesh(- geom, starMaterial(radius, gain, twinkle, bright));- mesh.name = 'StarField';- mesh.renderOrder = ORDER_STARS;- return mesh;-}--function starMaterial(radius, gain, twinkle, bright) {- return makeShaderMaterial({- name: 'StarField',- uniforms: {- // ~2 px across at 560 px and fov 55 for the faintest star,- // ~5 px for the brightest: a point source, not a disc.- uSize: { value: radius * 0.0042 },- uRadius: { value: radius },- uTwinkle: { value: twinkle },- uGain: { value: gain * (bright ? 0.55 : 1.0) },- },- varyings: 'varying vec2 vUv; varying float vGain;'- + ' varying vec3 vTint;',- vertexHead: 'attribute vec3 aCorner; attribute vec3 aDir;'- + ' attribute vec4 aStar; uniform float uSize;'- + ' uniform float uRadius; uniform float uTwinkle;',- vertexMain: [- ' vUv = uv;',- ' float f = aStar.x;',- ' float tw = 1.0 + uTwinkle * sin(uTime * aStar.z',- ' + aStar.y * 6.2831853);',- // Extinction: the last few degrees of sky eat a star, which- // is also what keeps the field off a horizon silhouette.- ' vGain = pow(f, 0.38) * tw * smoothstep(0.0, 0.11, aDir.y);',- // Spectral class, biased the way a real field is: warm K/M- // stars are the minority, so the sample is pushed toward- // the blue-white end rather than split down the middle.- ' vec3 hot = mix(vec3(1.0, 0.74, 0.52), vec3(0.70, 0.81, 1.0),',- ' pow(aStar.w, 0.7));',- // At threshold the eye has no colour at all: only the- // bright ones may show their class, or a faint field turns- // into scattered red and blue confetti.- ' vTint = mix(vec3(0.93, 0.95, 1.0), hot,',- ' 0.22 + 0.78 * pow(f, 0.30));',- ' mat3 mv3 = mat3(modelViewMatrix);',- ' vec3 rt = vec3(mv3[0][0], mv3[1][0], mv3[2][0]);',- ' vec3 up = vec3(mv3[0][1], mv3[1][1], mv3[2][1]);',- ' float s = uSize * (0.55 + 0.85 * pow(f, 0.25));',- ' transformed = aDir * uRadius',- ' + (rt * aCorner.x + up * aCorner.y) * s;',- ].join('\n'),- fragmentHead: 'uniform float uGain;',- fragmentMain: [- ' float d = length(vUv - 0.5) * 2.0;',- ' if (d > 1.0) discard;',- // A tight core in a faint halo. A flat disc is the look- // that reads as confetti.- ' float a = (pow(1.0 - d, 4.0) + 0.20 * pow(1.0 - d, 1.4))',- ' * vGain * uGain;',- // A halo this soft steps in 8-bit: one sub-LSB of noise per- // pixel costs nothing and buys the rings back as grain.- ' a += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.006;',- ' if (a < 0.004) discard;',- ' gl_FragColor = vec4(vTint, clamp(a, 0.0, 1.0));',- ].join('\n'),- // 3dcode: no-fog — a star is at infinity, and FogExp2 at the- // night density erases anything past ~400 m. worldShell's own- // dome opts out the same way.- fog: false,- blending: bright ? THREE.NormalBlending : THREE.AdditiveBlending,- transparent: true,- depthWrite: false,- });-}--/** The band: unresolved light, dust lanes, and a bulge to aim at. */-function milkyWayMesh(radius, pole, bright, gain) {- const geom = new THREE.SphereGeometry(radius * 1.01, 48, 24);- // Two axes across the band give the noise a seamless 2D coordinate- // — an atan around the pole would print a meridian down the sky.- const a = new THREE.Vector3(0, 1, 0).cross(pole).normalize();- const b = new THREE.Vector3().crossVectors(pole, a).normalize();- const core = a.clone().multiplyScalar(0.72)- .addScaledVector(b, 0.55).addScaledVector(pole, 0.06).normalize();- const mat = makeShaderMaterial({- name: 'MilkyWay',- uniforms: {- uPole: { value: pole.clone() },- uAxisA: { value: a },- uAxisB: { value: b },- uCore: { value: core },- // Unresolved starlight is faint and nearly neutral. The- // previous warm, high-alpha band became a luminous fog bank.- uArm: { value: new THREE.Color(0xc3c9d9) },- uHub: { value: new THREE.Color(0xd5cbbb) },- uGain: { value: gain * (bright ? 0.018 : 0.045) },- },- varyings: 'varying vec3 vDir;',- vertexMain: ' vDir = normalize(position);',- fragmentHead: 'uniform vec3 uPole; uniform vec3 uAxisA;'- + ' uniform vec3 uAxisB; uniform vec3 uCore;'- + ' uniform vec3 uArm; uniform vec3 uHub;'- + ' uniform float uGain;',- fragmentMain: [- ' vec3 d = normalize(vDir);',- ' float s = dot(d, uPole);',- ' float band = exp(-(s * s) / 0.009);',- // Angular detail follows the galactic plane without a seam.- // Fine star clouds sit inside the narrow unresolved band.- ' vec2 p = vec2(dot(d, uAxisA), dot(d, uAxisB)) * 22.0;',- ' float n = astraFbm2(p + vec2(s * 12.0, 0.0), 4);',- // Dark lanes are dust in front of the band, so they CUT it- // rather than tinting it; a smooth gaussian is a smear.- ' float lanes = smoothstep(0.28, 0.72, n);',- // A second field finer again: star clouds INSIDE the arms.- // One scale of noise is a smear at any contrast.- ' float fine = astraFbm2(p * 2.9 + vec2(11.0, s * 4.0), 3);',- ' lanes *= 0.45 + 0.75 * fine;',- // The Great Rift: dust lying IN the plane, so it splits the- // band down its own spine instead of dimming it evenly.- // Without it the brightest pixel is the exact centre line,- // which is the one place the real band is darkest.- ' float spine = abs(s + (astraNoise2(p * 0.35) - 0.5) * 0.025);',- ' float rift = smoothstep(0.012, 0.065, spine);',- ' float bulge = exp(-(1.0 - dot(d, uCore)) / 0.055);',- ' float a = band * (0.08 + 0.92 * lanes)',- ' * (0.55 + 0.75 * bulge) * mix(0.20, 1.0, rift) * uGain',- // Extinction is a LONG ramp. Ending it at 0.12 put the- // whole fade inside the sky a level camera actually frames,- // and drew a straight horizontal edge across the band.- ' * smoothstep(-0.03, 0.26, d.y);',- // Warm hub, cool arms, and the star clouds carry the mix so- // the band has warm and cold patches instead of one tint.- ' vec3 c = mix(uArm, uHub,',- ' clamp(bulge * 0.65 + (fine - 0.5) * 0.25, 0.0, 1.0));',- // Relative grain preserves zero and scales with magnitude;- // an absolute alpha floor would resurrect a disabled band.- ' a *= 1.0 + (astraHash21(gl_FragCoord.xy) - 0.5) * 0.10;',- ' if (a <= 0.0) discard;',- ' gl_FragColor = vec4(c, clamp(a, 0.0, 1.0));',- ].join('\n'),- // 3dcode: no-fog — see StarField.- fog: false,- side: THREE.BackSide,- blending: bright ? THREE.NormalBlending : THREE.AdditiveBlending,- transparent: true,- depthWrite: false,- });- const mesh = new THREE.Mesh(geom, mat);- mesh.name = 'MilkyWayStars';- mesh.renderOrder = ORDER_MILKYWAY;- return mesh;-}--/**- * The vertical emission profile of one curtain, bottom edge to top.- *- * An aurora is brightest at its LOWER BORDER, where the electrons- * finally stop, and fades up the column — a curtain lit evenly, or- * lit at the top, is the tell. Baked per vertex so the profile is- * data the CPU owns rather than a constant buried in GLSL.- */-function auroraGlow(v) {- const rim = 0.35 + 0.65 * Math.exp(-v * 16);- const k = 1 - Math.min(1, Math.max(0, (v - 0.72) / 0.28));- return rim * Math.exp(-v * 2.3) * k * k * (3 - 2 * k);-}--/**- * Curtains of light: vertical rays, folding, brightest along the foot.- *- * Built as ribbons, not sheets of one brightness: each carries a baked- * `aGlow` profile that falls from its bottom edge upward, the rays run- * across it as antialiased strokes, and the folds brighten where they- * turn edge-on because a sheet's chord through the eye grows there —- * that edge-on flare is what makes an aurora read as a hanging curtain- * instead of a painted band.- *- * The mesh is named `AuroraSkyCurtains`: the scene renderer excludes- * sky envelopes from its content fit by the token `sky` in a mesh- * name, and a 1.4 km curtain that misses it becomes the content bbox.- *- * @param {object} [opts]- * `radius` metres from the origin to the curtain band (default 1400- * — inside `makeStars`'s 2 km sphere); `height` metres of curtain- * (default 400); the foot hangs at `radius * 0.30`, so translate the- * group in Y to raise or lower the display; `color` the main- * emission (default 0x54ffa8, the 557.7 nm oxygen green — the rim- * reddens and the top goes violet on their own); `activity` 0..1- * (default 0.5) driving how many curtains there are, how hard they- * fold and how fast they drift; `seed` PRNG seed (default 9);- * `ambient` how bright the frame behind is, 0 a real night to 1- * daylight (default 0.2) — see `makeStars`; pass `ambient: 0.9` when- * the sky behind is genuinely bright.- *- * The curtains are laid one per equal slice of the compass, jittered- * inside it, so a display always crosses whatever the camera is looking- * at — n independent draws leave holes a hundred degrees wide.- * @returns {THREE.Group} Named `Aurora`, with `userData.update(t)`.- */-export function makeAurora(opts = {}) {- const radius = opts.radius === undefined ? 1400 : opts.radius;- const height = opts.height === undefined ? 400 : opts.height;- const activity = Math.min(Math.max(- opts.activity === undefined ? 0.5 : opts.activity, 0), 1);- const seed = opts.seed === undefined ? 9 : opts.seed;- // 0.2 for the same reason as `makeStars`: an aurora is a night- // effect, and the daylight-safe blend rendered nothing here.- const ambient = Math.min(Math.max(- opts.ambient === undefined ? 0.2 : opts.ambient, 0), 1);- const bright = ambient >= 0.35;- const color = opts.color- ? new THREE.Color(opts.color) : new THREE.Color(0x54ffa8);- const rnd = lehmer(seed);- const n = 3 + Math.round(activity * 4);- const base = radius * 0.30;- const swing = radius * (0.02 + 0.10 * activity);-- const geom = curtainGeometry(n, rnd, radius, base, height, activity);- // The vertex stage folds the ribbon after the sphere is computed,- // so the stated one has to allow for the whole swing or the band- // is culled the moment a fold carries it past the edge.- geom.boundingSphere.radius += swing;- const mesh = new THREE.Mesh(- geom, auroraMaterial(color, activity, swing, bright));- mesh.name = 'AuroraSkyCurtains';- mesh.renderOrder = ORDER_AURORA;-- const g = new THREE.Group();- g.name = 'Aurora';- g.add(mesh);- g.userData.update = g.userData.tick = (t) => tickShaders(g, t);- return attachDisposal(keepOutOfDepthPasses(g), snapshotResources(g));-}--/** All curtains in one ribbon geometry, tagged by `aCurtain`. */-function curtainGeometry(n, rnd, radius, base, height, activity) {- const nu = 128, nv = 24;- const pos = [], uv = [], glow = [], tag = [], idx = [];- for (let c = 0; c < n; c++) {- // STRATIFIED, not random: n independent draws clump, and a- // measured one (seed 11, n = 5) left a 100-degree hole that a- // camera looking into it saw an empty sky through. The real- // auroral oval is an ARC across the whole sky, so one curtain- // per equal slice — jittered inside it — is both truer and the- // only version that cannot miss the frame entirely.- const slice = (Math.PI * 2) / n;- const a0 = (c + rnd()) * slice;- // A curtain covers PART of its slice. The span was an absolute- // arc, so five of them at this activity ran shoulder to- // shoulder all the way round and the display rendered as one- // unbroken wall of bars. Measured against the slice it always- // leaves sky between the curtains, which is the difference- // between a display and a fence.- const span = slice * (0.34 + 0.30 * rnd()) * (0.75 + 0.5 * activity);- const bow = (0.08 + 0.22 * rnd()) * radius;- const ph = rnd() * Math.PI * 2;- const first = pos.length / 3;- for (let j = 0; j <= nv; j++) {- // v packed toward the foot: the bright rim is a tenth of- // the column and an even ladder smears it into a gradient.- const v = Math.pow(j / nv, 1.7);- const y = base + height * v;- const gl = auroraGlow(v);- for (let i = 0; i <= nu; i++) {- const u = i / nu;- const a = a0 + (u - 0.5) * span;- // Two beats of bow: one arc is a fence, two make the- // hairpin folds a curtain actually hangs in.- const r = radius- + bow * Math.sin(u * 6.2831853 * 1.5 + ph)- + bow * 0.45 * Math.sin(u * 6.2831853 * 3.7 + ph * 2.1);- pos.push(Math.cos(a) * r, y, Math.sin(a) * r);- uv.push(u, v);- glow.push(gl);- tag.push((c + 0.5) / n, radius * span);- }- }- for (let j = 0; j < nv; j++) {- for (let i = 0; i < nu; i++) {- const p = first + j * (nu + 1) + i;- idx.push(p, p + nu + 1, p + 1,- p + 1, p + nu + 1, p + nu + 2);- }- }- }- const g = new THREE.BufferGeometry();- g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));- g.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2));- g.setAttribute('aGlow', new THREE.Float32BufferAttribute(glow, 1));- g.setAttribute('aCurtain', new THREE.Float32BufferAttribute(tag, 2));- g.setIndex(idx);- g.computeVertexNormals();- g.computeBoundingSphere();- return g;-}--function auroraMaterial(color, activity, swing, bright) {- const tint = bright ? color.clone().lerp(new THREE.Color(0xffffff),- 0.45) : color.clone();- return makeShaderMaterial({- name: 'Aurora',- uniforms: {- uColor: { value: tint },- uRim: { value: new THREE.Color(0xff5f9e) },- // Green -> TEAL -> violet, in two stops. Mixing 557.7 nm- // green straight to violet passes through grey at the- // halfway point, and a grey band up the middle of a curtain- // is exactly the wash this was showing.- uMid: { value: new THREE.Color(0x3ce6b0) },- uTop: { value: new THREE.Color(0xa855e8) },- uSwing: { value: swing },- uDrift: { value: 0.03 + 0.09 * activity },- uRays: { value: 26 + 34 * activity },- uGain: { value: bright ? 0.30 : 0.85 },- // The ceiling matters more than the gain. ACES desaturates- // as it rolls off, so a curtain allowed to reach alpha 1- // arrives WHITE — measured: 2.1% of the frame clipped past- // 0.97 and the green gone. Held here, the same curtain- // stays inside the part of the curve that keeps its hue.- uPeak: { value: bright ? 0.26 : 0.50 },- },- varyings: 'varying vec2 vUv; varying float vGlow;'- + ' varying vec3 vN; varying vec3 vW; varying float vTag;',- vertexHead: [- 'attribute float aGlow;',- 'attribute vec2 aCurtain;',- 'uniform float uSwing; uniform float uDrift;',- // One fold field, sampled twice so the shading normal can- // follow the fold instead of the flat ribbon it left.- 'float astraCelFold(float u, float tag) {',- ' return (astraFbm2(vec2(u * 2.6 + tag * 17.0,',- ' uTime * uDrift), 3) - 0.5) * uSwing;',- '}',- ].join('\n'),- vertexMain: [- ' vUv = uv;',- ' vGlow = aGlow;',- ' vTag = aCurtain.x;',- ' vec3 nrm = normalize(normal);',- ' float f0 = astraCelFold(uv.x, aCurtain.x);',- ' float f1 = astraCelFold(uv.x + 0.02, aCurtain.x);',- ' transformed += nrm * f0;',- ' vec3 tg = normalize(cross(vec3(0.0, 1.0, 0.0), nrm));',- ' float slope = (f1 - f0) / max(0.02 * aCurtain.y, 1e-3);',- ' vN = astraNormalTransform(mat3(modelMatrix),',- ' normalize(nrm - tg * slope));',- ' vW = (modelMatrix * vec4(transformed, 1.0)).xyz;',- ].join('\n'),- fragmentHead: 'uniform vec3 uColor; uniform vec3 uRim;'- + ' uniform vec3 uMid; uniform vec3 uTop; uniform float uRays;'- + ' uniform float uDrift; uniform float uGain;'- + ' uniform float uPeak;',- fragmentMain: [- ' float v = vUv.y;',- ' float x = vUv.x * uRays + vTag * 23.0 + uTime * uDrift;',- // A warped filament coordinate breaks the even barcode spacing.- // The broad envelope supplies luminous folds; narrow rays carry- // fine detail without forcing every column to the same height.- ' float fold = astraFbm2(vec2(vUv.x * 5.5 + vTag * 13.0,',- ' uTime * uDrift * 0.55), 3);',- ' x += (fold - 0.5) * 3.2;',- ' x += (astraNoise2(vec2(x * 0.41, v * 0.7 + vTag)) - 0.5)',- ' * (0.5 + v * 0.8);',- ' float ray = 0.0;',- ' float pixelWidth = max(fwidth(x), 0.001);',- ' for (int k = -1; k <= 1; k++) {',- ' float rayId = floor(x) + float(k);',- ' float centre = rayId + 0.16',- ' + 0.68 * astraHash11(rayId * 1.37 + 2.0);',- ' float w = 0.05',- ' + 0.13 * astraHash11(rayId * 0.37 + 2.0);',- ' float width = sqrt(w * w + pixelWidth * pixelWidth);',- ' float distance = x - centre;',- ' float strand = exp(-distance * distance / (width * width))',- ' * w / width;',- ' float rayTop = 0.32 + 0.64 * astraNoise2(',- ' vec2(rayId * 0.27 + vTag * 7.0, uTime * 0.035));',- ' strand *= 1.0 - smoothstep(rayTop * 0.40, rayTop, v);',- ' strand *= 0.20 + 1.25 * astraNoise2(vec2(rayId * 0.71,',- ' uTime * 0.06 + vTag * 5.0));',- ' ray += strand;',- ' }',- ' float curtain = smoothstep(0.16, 0.78, fold);',- ' ray = (0.35 * curtain + 0.95 * ray) * (0.35 + curtain);',- ' float foot = 0.018 + 0.035 * astraNoise2(',- ' vec2(vUv.x * 13.0 + vTag * 11.0, uTime * 0.045));',- ' ray *= smoothstep(foot, foot + 0.035, v);',- ' vec3 eye = normalize(cameraPosition - vW);',- // A sheet is thin: the eye cuts a LONGER chord through it- // edge-on, so a fold turning away flares instead of- // vanishing. Clamped, or the silhouette divides by zero.- ' float chord = 1.0 / max(astraFacing(vN, eye), 0.46);',- ' float ends = smoothstep(0.0, 0.10, vUv.x)',- ' * (1.0 - smoothstep(0.90, 1.0, vUv.x));',- ' float a = vGlow * ray * chord * ends * uGain;',- // Saturating toward uPeak rather than toward 1: same slope- // where the curtain is faint, a hard hue-preserving ceiling- // where a fold turns edge-on.- ' a = uPeak * (1.0 - exp(-a * 2.1));',- ' a += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.004;',- ' if (a < 0.003) discard;',- // The green body owns most of the column. Ramping to the- // cool stop from v = 0.05 turned the whole LOWER half —- // the half a level camera ever frames — teal, and 557.7 nm- // green is the one colour that says aurora.- ' vec3 c = mix(uColor, uMid, smoothstep(0.22, 0.68, v));',- ' c = mix(c, uTop, smoothstep(0.62, 0.98, v));',- // The lower border is where the electrons stop and the- // nitrogen answers in magenta — the one warm note in the- // whole display, and the thing that dates a fake aurora.- ' c = mix(c, uRim, (1.0 - smoothstep(0.0, 0.075, v)) * 0.72);',- // No two curtains in one display are the same green. One- // hash per curtain, so the tint is stable in time and the- // band never reads as a single printed colour.- ' float hj = astraHash11(vTag * 13.7 + 4.0);',- ' c *= mix(vec3(1.14, 0.98, 0.76), vec3(0.76, 1.0, 1.20), hj);',- ' gl_FragColor = vec4(c, clamp(a, 0.0, 1.0));',- ].join('\n'),- // 3dcode: no-fog — the curtain hangs a kilometre out, past- // every scene fog density this engine sets.- fog: false,- side: THREE.DoubleSide,- blending: bright ? THREE.NormalBlending : THREE.AdditiveBlending,- transparent: true,- depthWrite: false,- });-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloth.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloth.jsdeleted file mode 100644index 0a2dee72..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloth.js+++ /dev/null@@ -1,1046 +0,0 @@-/**- * Cloth and crop: the three things in a scene that show the wind- * INSTEAD OF being shown by it.- *- * Each of the three fails the same way when it is written as "a sine- * over the surface", and each fails differently:- *- * `makeFlag` — the wave has to TRAVEL from the mast to the fly and- * GROW as it goes. Amplitude is pinned to zero along the attachment- * and largest at the free edge, so the eye reads a sheet held at one- * end. A sine over the whole sheet is a rippling billboard: it has- * no attachment, so it reads as a screen playing a video of cloth.- *- * `makeBanner` — a cloth hung along its TOP edge does not flap, it- * SWINGS, at the pendulum rate its own drop sets (sqrt(g/drop), so a- * long curtain is slower than a short one), and it gathers into fold- * lines that run DOWN from the hanging edge. Flap it like a flag and- * a heavy curtain reads as a sheet of paper.- *- * `makeWheatField` — the subject is the WAVE crossing the field, not- * the stalk. The gust field is shared by every stalk and travels- * downwind at a stated m/s, so neighbours move together with the lag- * between them; per-stalk motion is a tenth of it, the texture that- * makes the wave visible. Give every stalk its own phase — as grass- * does, correctly, at grass's scale — and a hectare of wheat boils- * instead of rippling.- *- * Which sibling do you want?- * `grass.js` — ankle-high ground cover, clumped, per-blade phase; the- * ground itself needs covering.- * `flowers.js` — colour above the grass, nodding heads.- * here — a crop: chest-high, sown in DRILL ROWS, one shared wave.- *- * All three take grass.js's `wind` (its `windOf` is imported, never- * re-read), so one scene's meadow, its wheat and its flags move as one- * wind. All three are deterministic in `seed`, and all three need- * driving from your zone's `update` — `obj.userData.update(t)` — or the wind- * never blows.- */--import * as THREE from 'three';-import { attachDisposal, snapshotResources } from './lifecycle.js';--import { windOf } from './grass.js';-import { mulberry32 } from './noise.js';-import {- glslLocalDir, patchStandard, shadowLike, tickShaders, unit,-} from './shader.js';--const _TAU = Math.PI * 2;-const _G = 9.81;-// Rows up a stalk, and where its ear starts. The ear is a fifth of the-// stalk and takes nearly half the rows, because that is where the bend-// turns hardest; fatter or longer and the crop reads as pennants.-const _STALK_ROWS = 11;-const _STEM_ROWS = 4;-const _EAR_AT = 0.8;-// Tileable modes of the gust field. Integer frequencies only: the-// field scrolls downwind forever, so a seam would cross the crop.-const _WAVE_MODES = [- [1, 0], [0, 1], [1, 1], [1, -1], [2, 1], [1, 2],- [2, -1], [2, 2], [3, 1], [1, 3], [3, 2], [2, 3],-];--/**- * Rotations about Y that send local +X (or +Z) to a world XZ heading.- *- * Both sheets are authored with the wind along one local axis and- * turned by this, so their GLSL never has to carry a wind vector: the- * flag flies along its own +X, the banner swings along its own +Z.- */-function yawToX(dir) {- return Math.atan2(-dir.y, dir.x);-}--function yawToZ(dir) {- return Math.atan2(dir.x, dir.y);-}--/**- * A flag on a mast, whose wave travels out to the fly and grows.- *- * Buys the cue that says "held at one edge": the amplitude envelope is- * a per-vertex attribute pinned to 0 along the hoist and rising to 1- * at the fly, and the phase runs `k*u - rate*t`, so crests LEAVE the- * mast. Chord length is conserved as the sheet ripples (the fly is- * pulled back by the integral of its own slope), or a flapping flag- * grows visibly longer than its own cloth.- *- * The constraint: the mast rests on y = 0 and the sheet hangs from its- * top, so the group can be dropped straight onto ground; and the- * stated bounding sphere covers the sheet's full excursion, because- * the wave lives in the vertex shader and three culls on the sphere.- *- * @param {object} [opts]- * `width` chord of the sheet in metres, mast to fly (default 1.6);- * `height` hoist height of the sheet (default 1.0); `mast` mast- * height in metres (default 6, 0 for no mast at all — a flag already- * hung on someone else's pole); `wind` grass.js's option, a strength- * multiplier or `{dir, strength, speed}` with `dir` the direction it- * BLOWS TOWARD over world XZ — the flag flies that way; `color`- * cloth albedo (default a flag red); `seed` PRNG seed (default 11);- * `name` group name.- * @returns {THREE.Group} Named `Flag`, resting on y = 0, holding- * `Mast` and a `FlagSheet` whose ripple is one patched material,- * with `userData.update(t)` driving it.- */-export function makeFlag(opts = {}) {- const width = opts.width === undefined ? 1.6 : opts.width;- const height = opts.height === undefined ? 1.0 : opts.height;- const mast = opts.mast === undefined ? 6 : opts.mast;- const seed = opts.seed === undefined ? 11 : opts.seed;- const wind = windOf(opts.wind);- const rand = mulberry32(seed);- // Albedo, not a screen colour: a scene sun runs at 5-6, so a hex- // that already looks like sunlit bunting tone-maps to pale card.- // A dye, and a dye has a blue channel: at 0x8e2b28 the green and the- // blue sit at 0.024 and 0.021 in linear, so every part of the sheet- // the sun misses tone-maps to a black-red hole. This reads the same- // red in the light and still has cloth in it in the shade.- const color = new THREE.Color(- opts.color === undefined ? 0x9b3630 : opts.color);-- const g = new THREE.Group();- g.name = opts.name || 'Flag';- const rad = Math.max(0.018, Math.min(0.05, height * 0.045));- if (mast > 0) g.add(mastPole(mast, rad));- const fly = new THREE.Group();- fly.name = 'FlagFly';- fly.position.y = Math.max(mast, height + 0.05);- fly.rotation.y = yawToX(wind.dir);- fly.add(flagSheet(width, height, rad, color, wind, rand));- g.add(fly);- g.userData.update = g.userData.tick = (t) => tickShaders(g, t);- return attachDisposal(g, snapshotResources(g));-}--/** The pole, tapered and capped so it is not a bare cylinder. */-function mastPole(mast, rad) {- const geom = new THREE.CylinderGeometry(rad * 0.72, rad, mast, 10, 1);- geom.translate(0, mast / 2, 0);- const mat = new THREE.MeshStandardMaterial({- color: 0xb8b3a6, roughness: 0.45, metalness: 0.65, name: 'FlagMast',- });- const pole = new THREE.Mesh(geom, mat);- pole.name = 'Mast';- pole.castShadow = true;- pole.receiveShadow = true;- const cap = new THREE.Mesh(- new THREE.SphereGeometry(rad * 1.7, 10, 8), mat);- cap.name = 'MastFinial';- cap.position.y = mast;- cap.castShadow = true;- pole.add(cap);- return pole;-}--/**- * The sheet: one plane whose envelope is CPU data, not GLSL.- *- * `aFlag` carries (u along the chord, the amplitude envelope, its- * derivative for the normal, the integral of its square for the chord- * shortening). Keeping the envelope on the CPU is what lets a test- * read "pinned at the mast, free at the fly" as a number instead of- * trusting a claim about a shader.- */-function flagSheet(width, height, rad, color, wind, rand) {- const segX = Math.max(24, Math.min(96, Math.round(width * 40)));- const segY = Math.max(8, Math.min(48, Math.round(height * 20)));- const geom = new THREE.PlaneGeometry(width, height, segX, segY);- geom.translate(width / 2 + rad, -height / 2, 0);- const pos = geom.attributes.position;- const env = new Float32Array(pos.count * 4);- for (let i = 0; i < pos.count; i++) {- const u = unit((pos.getX(i) - rad) / Math.max(width, 1e-6));- // u^1.6, not u: a linear envelope reads as a sheet hinged at the- // mast, and the growth toward the fly is the whole cue.- env[i * 4] = u;- env[i * 4 + 1] = Math.pow(u, 1.6);- env[i * 4 + 2] = 1.6 * Math.pow(u, 0.6);- env[i * 4 + 3] = Math.pow(u, 4.2) / 4.2;- }- geom.setAttribute('aFlag', new THREE.BufferAttribute(env, 4));-- const waves = Math.max(0.9, Math.min(3, 1.15 * width / Math.max(- height, 1e-3)));- const k = _TAU * waves;- const amp = width * 0.22 * wind.amp;- const rate = 11 * wind.speed;- // A slack flag hangs; a taut one flies. Both are the same cloth, so- // the droop is what `strength` buys back.- const sag = height * 0.30 / (1 + 4.4 * wind.amp);- const shrink = amp * amp * k * k / (4 * Math.max(width, 1e-6));- const mat = new THREE.MeshPhysicalMaterial({- color, roughness: 0.86, metalness: 0, side: THREE.DoubleSide,- sheen: 0.35, sheenRoughness: 0.85, sheenColor: color.clone().multiplyScalar(0.7),- name: 'FlagCloth',- });- const head = [- 'uniform float uFlagAmp;',- 'uniform float uFlagK;',- 'uniform float uFlagRate;',- 'uniform float uFlagTilt;',- 'uniform float uFlagSag;',- 'uniform float uFlagShrink;',- 'uniform float uFlagMaxShrink;',- 'uniform float uFlagWidth;',- 'uniform float uFlagPhase;',- 'attribute vec4 aFlag;',- 'varying vec4 vFlag;',- ].join('\n');- patchStandard(mat, {- name: 'cloth:flag',- uniforms: {- uFlagAmp: { value: amp },- uFlagK: { value: k },- uFlagRate: { value: rate },- uFlagTilt: { value: 0.9 / Math.max(height, 1e-3) },- uFlagSag: { value: sag },- uFlagShrink: { value: shrink },- uFlagMaxShrink: { value: width * 0.25 },- uFlagWidth: { value: width },- uFlagPhase: { value: rand() * _TAU },- // Threads per SHEET, at 300 to the metre and 0.06 wide — thin- // enough that astraStroke drops them once a pixel spans one,- // which is every distance but a hand's breadth away.- uFlagWeave: { value: new THREE.Vector2(width, height)- .multiplyScalar(300) },- // Cloth is fuzzy, so a sheet turning away from the eye catches- // the sky along its own curve instead of ending in an ink edge.- // The facing term is computed per vertex, where the wave's- // normal already is; the fragment only spends it.- uFlagSheen: { value: 0.85 },- // Years on a pole: a flag fades from the FLY inward, because the- // hoist spends its life rolled around the rope.- uFlagFade: { value: 0.42 },- // Radians of dye swing across the sheet, warm to cool. Dyed- // cloth is never one value, and one value is what reads plastic.- uFlagDye: { value: 0.6 },- },- vertexHead: head,- vertexBody: FLAG_MOVE + '\n' + FLAG_NORMAL,- fragmentHead: [- 'uniform vec2 uFlagWeave;',- 'uniform float uFlagSheen;',- 'uniform float uFlagFade;',- 'uniform float uFlagDye;',- 'varying vec4 vFlag;',- ].join('\n'),- fragmentBody: FLAG_FRAGMENT,- });-- const mesh = new THREE.Mesh(geom, mat);- mesh.name = 'FlagSheet';- mesh.castShadow = true;- mesh.receiveShadow = true;- shadowLike(mesh, 'cloth:flagDepth', head, FLAG_MOVE);- // The wave lives in the vertex shader, so the derived bounds are the- // FLAT sheet's and three would cull the flag on a box it leaves.- const reach = amp * 1.42;- geom.boundingBox = new THREE.Box3(- new THREE.Vector3(rad - 0.02, -height - sag, -reach),- new THREE.Vector3(rad + width + 0.02, 0.02, reach));- geom.boundingSphere = geom.boundingBox.getBoundingSphere(- new THREE.Sphere());- return mesh;-}--const FLAG_MOVE = [- ' float flU = aFlag.x;',- // The phase runs k*u - rate*t, so a crest LEAVES the mast; the tilt- // term keeps the crest off the vertical, as a real fly is.- ' float flPh = uFlagK * flU - uFlagRate * uTime + uFlagPhase',- ' + uFlagTilt * transformed.y;',- ' float flS = sin(flPh) + 0.42 * sin(1.7 * flPh + 1.3);',- ' float flD = cos(flPh) + 0.714 * cos(1.7 * flPh + 1.3);',- ' float flZ = uFlagAmp * aFlag.y * flS;',- // Cloth does not stretch: a rippled chord has to give back the- // length its own slope spends, or the fly grows as the wind rises.- ' float flBack = min(uFlagShrink * aFlag.w, uFlagMaxShrink);',- ' transformed.x -= flBack;',- ' transformed.y -= uFlagSag * aFlag.y;',- ' transformed.z += flZ;',- // .w is the facing term the sheen spends; the depth pass is- // FLAT_SHADED and never fills it, so it starts at "square on".- ' vFlag = vec4(flU, uv.y, flS, 1.0);',-].join('\n');--const FLAG_NORMAL = [- '#ifndef FLAT_SHADED',- ' float flZx = uFlagAmp * (aFlag.z * flS + aFlag.y * flD * uFlagK)',- ' / max(uFlagWidth, 1e-4);',- ' float flZy = uFlagAmp * aFlag.y * flD * uFlagTilt;',- // Differentiate the shortened, sagging sheet, not only its Z ripple.- // The clamped shortening has zero derivative beyond the cap.- ' float flXx = 1.0 - (uFlagShrink * aFlag.w < uFlagMaxShrink',- ' ? uFlagShrink * aFlag.y * aFlag.y / max(uFlagWidth, 1e-4) : 0.0);',- ' float flYx = -uFlagSag * aFlag.z / max(uFlagWidth, 1e-4);',- ' vNormal = normalize(normalMatrix * normalize(',- ' cross(vec3(flXx, flYx, flZx), vec3(0.0, 1.0, flZy))));',- // Both in VIEW space, so a scaled or rotated flag needs no basis of- // its own: 1 square on to the eye, 0 edge-on.- ' vec4 flMv = modelViewMatrix * vec4(transformed, 1.0);',- ' vFlag.w = astraFacing(vNormal, -flMv.xyz);',- '#endif',-].join('\n');--const FLAG_FRAGMENT = [- // Dyed cloth is never one hex. A slow warm/cool break across the- // SHEET's own coordinates — so it travels with the cloth rather than- // swimming through it — is the difference between bunting and a- // painted panel, and it costs one fbm.- ' diffuseColor.rgb = astraHueBreak(diffuseColor.rgb,',- ' vec2(vFlag.x * 2.6, vFlag.y * 1.7), 1.0, uFlagDye);',- // Warp and weft, not a wash — and gone before either can alias.- ' float flW = astraStroke(vFlag.y * uFlagWeave.y, 0.06)',- ' + astraStroke(vFlag.x * uFlagWeave.x, 0.06);',- ' diffuseColor.rgb *= 0.94 + 0.10 * flW;',- // The hoist is doubled cloth over a rope, so it is darker and- // slightly duller than the field of the flag.- ' diffuseColor.rgb *= 1.0 - 0.30 * (1.0 - smoothstep(0.0, 0.045,',- ' vFlag.x));',- // And the FLY is the end that has flown: sun and weather take the- // dye out of it, which lightens and desaturates rather than fading- // to grey. Without this a flag is uniformly new, and nothing in a- // scene is uniformly new.- ' float flOld = uFlagFade * smoothstep(0.30, 1.0, vFlag.x);',- ' float flLum = dot(diffuseColor.rgb, vec3(0.2126, 0.7152, 0.0722));',- ' diffuseColor.rgb = mix(diffuseColor.rgb,',- ' mix(diffuseColor.rgb, vec3(flLum), 0.5) * 1.30, flOld);',- // Crests catch the sky and troughs hold shade: this is what makes- // the travelling wave read in flat light as well as in sun. The- // swing carries HUE too — a crest is turned to a blue sky and a- // trough sees only the warm bounce off the cloth beside it.- ' float flC = clamp(vFlag.z * 0.5 + 0.5, 0.0, 1.0);',- ' diffuseColor.rgb *= 0.84 + 0.26 * flC;',- ' diffuseColor.rgb = astraHueShift(diffuseColor.rgb,',- ' (flC - 0.5) * 0.17);',- // Cloth fuzz: the pile stands off the weave, so a sheet turning away- // lights along its own curve instead of ending in an ink edge. This- // is the cue that separates cloth from sheet metal in one frame.- ' float flGrz = 1.0 - clamp(vFlag.w, 0.0, 1.0);',- ' diffuseColor.rgb *= 1.0 + uFlagSheen * flGrz * flGrz * flGrz;',-].join('\n');--/**- * A cloth banner or curtain hung along its top edge.- *- * Buys the cue that says "hung, and heavy": the whole sheet swings as- * a PENDULUM about its top edge at sqrt(g / drop) rad/s — a 4 m- * curtain is visibly slower than a 1 m one — and it gathers into fold- * lines that run straight DOWN from the hanging edge, pinched at the- * rod and opening toward the hem. Nothing flaps: a hung cloth that- * flaps like a flag reads as paper.- *- * The constraint: the fold profile is a function of x ALONE, held in a- * per-vertex attribute, so the folds cannot drift into diagonal- * ripples; and the swing is a rigid rotation about the top edge, so- * the cloth swings without growing.- *- * @param {object} [opts]- * `width` metres across (default 2); `drop` metres from the hanging- * edge to the hem (default 3); `hang` height of the hanging edge- * above the group origin (default `drop`, which puts the hem on- * y = 0); `wind` grass.js's option — the banner leans and swings- * ALONG `dir`; `color` cloth albedo (default a banner crimson);- * `seed` PRNG seed (default 11); `rod` draw the rail it hangs from- * (default true); `folds` how many fold lines across the width- * (default 5); `name` group name.- * @returns {THREE.Group} Named `Banner`, holding `BannerCloth` and- * (unless declined) `BannerRod`, with `userData.update(t)` driving the- * swing.- */-export function makeBanner(opts = {}) {- const width = opts.width === undefined ? 2 : opts.width;- const drop = opts.drop === undefined ? 3 : opts.drop;- const hang = opts.hang === undefined ? drop : opts.hang;- const seed = opts.seed === undefined ? 11 : opts.seed;- const folds = Math.max(1, Math.round(- opts.folds === undefined ? 5 : opts.folds));- const wind = windOf(opts.wind);- const rand = mulberry32(seed);- // A curtain is the biggest flat area this library ships, and it- // usually hangs in its own shade: 0x7a2733 puts its green and blue- // at 0.019 and 0.032 linear, which is a black hole with a red rim.- // Same crimson, with cloth still in it where the sun is not.- const color = new THREE.Color(- opts.color === undefined ? 0x963a36 : opts.color);-- const g = new THREE.Group();- g.name = opts.name || 'Banner';- const swing = new THREE.Group();- swing.name = 'BannerHang';- swing.position.y = hang;- // Local +Z is downwind, so the pendulum swings in the ZY plane and- // the fold lines stay square to the rod.- swing.rotation.y = yawToZ(wind.dir);- swing.add(bannerCloth(width, drop, folds, color, wind, rand));- if (opts.rod !== false) swing.add(bannerRod(width, drop));- g.add(swing);- g.userData.update = g.userData.tick = (t) => tickShaders(g, t);- return attachDisposal(g, snapshotResources(g));-}--/** The rail: what makes "fixed along the top edge" visible. */-function bannerRod(width, drop) {- const r = Math.max(0.012, Math.min(0.045, drop * 0.012));- const geom = new THREE.CylinderGeometry(r, r, width * 1.08, 10, 1);- geom.rotateZ(Math.PI / 2);- const mesh = new THREE.Mesh(geom, new THREE.MeshStandardMaterial({- color: 0x6a5a44, roughness: 0.6, metalness: 0.3, name: 'BannerRod',- }));- mesh.name = 'BannerRod';- mesh.position.y = r * 0.4;- mesh.castShadow = true;- return mesh;-}--/**- * The cloth: folds are CPU data indexed by x, swing is one angle.- *- * `aBan` carries (depth fraction from the rod, the fold profile at- * this x, its slope, the width the fold gathers). Every one of them is- * a function of x or of y ALONE, which is exactly the claim "the folds- * run down" — and a test can read it off the attribute.- */-function bannerCloth(width, drop, folds, color, wind, rand) {- const segX = Math.max(24, Math.min(120, Math.round(width * 26)));- const segY = Math.max(10, Math.min(60, Math.round(drop * 12)));- const geom = new THREE.PlaneGeometry(width, drop, segX, segY);- geom.translate(0, -drop / 2, 0);- const prof = foldProfile(folds, rand);- const pos = geom.attributes.position;- const data = new Float32Array(pos.count * 4);- for (let i = 0; i < pos.count; i++) {- const x = pos.getX(i) / Math.max(width, 1e-6) + 0.5;- const f = prof(x);- data[i * 4] = unit(-pos.getY(i) / Math.max(drop, 1e-6));- data[i * 4 + 1] = f.v;- data[i * 4 + 2] = f.d / Math.max(width, 1e-6);- data[i * 4 + 3] = f.s;- }- geom.setAttribute('aBan', new THREE.BufferAttribute(data, 4));-- // A fold is deep in proportion to its OWN spacing, never to the- // width: at a fifth of the spacing the cloth is already gathering- // back a tenth of its span, and past that it is a concertina.- const fold = Math.min(0.16 * width / folds, drop * 0.06);- // The pendulum a cloth of this drop actually is. Doubling the drop- // slows the swing by 1.41, which is the whole "heavy" cue.- const rate = Math.sqrt(_G / Math.max(drop, 0.05));- const lean = 0.55 * wind.amp;- const sway = 0.18 * wind.amp + 0.02;- const mat = new THREE.MeshPhysicalMaterial({- color, roughness: 0.9, metalness: 0, side: THREE.DoubleSide,- sheen: 0.45, sheenRoughness: 0.9, sheenColor: color.clone().multiplyScalar(0.7),- name: 'BannerClothMat',- });- patchStandard(mat, {- name: 'cloth:banner',- uniforms: {- uBanDrop: { value: drop },- uBanFold: { value: fold },- uBanShrink: { value: fold * fold / Math.max(width, 1e-6) },- uBanShrinkMax: { value: width * 0.15 },- uBanRate: { value: rate },- uBanLean: { value: lean },- uBanSway: { value: sway },- // The hem arrives after the rod: a cloth with no lag swings as- // one board, which is the paper look again.- uBanLag: { value: 0.85 },- uBanPhase: { value: rand() * _TAU },- // Threads across the SHEET at 300 to the metre: thin enough that- // astraStroke drops them before they can alias into moire.- uBanWeave: { value: width * 300 },- // Same three as the flag: the fuzz that lights a turning edge,- // the dye that is never one value, and the dust a hem stands in.- uBanSheen: { value: 0.75 },- uBanDye: { value: 0.38 },- uBanDust: { value: 0.40 },- },- vertexHead: BANNER_HEAD,- vertexBody: BANNER_MOVE + '\n' + BANNER_NORMAL,- fragmentHead: [- 'uniform float uBanWeave;',- 'uniform float uBanSheen;',- 'uniform float uBanDye;',- 'uniform float uBanDust;',- 'varying vec4 vBan;',- ].join('\n'),- fragmentBody: BANNER_FRAGMENT,- });-- const mesh = new THREE.Mesh(geom, mat);- mesh.name = 'BannerCloth';- mesh.castShadow = true;- mesh.receiveShadow = true;- shadowLike(mesh, 'cloth:bannerDepth', BANNER_HEAD, BANNER_MOVE);- // The hem can only RISE as the cloth swings (y = -drop * cos), so- // the box's floor is the drop itself and the asset still rests where- // the caller hung it.- const reach = drop * Math.sin(Math.min(lean + sway, 1.3)) + fold + 0.02;- geom.boundingBox = new THREE.Box3(- new THREE.Vector3(-width / 2 - fold, -drop, -fold - 0.02),- new THREE.Vector3(width / 2 + fold, 0.02, reach));- geom.boundingSphere = geom.boundingBox.getBoundingSphere(- new THREE.Sphere());- return mesh;-}--/**- * The fold profile across the width: value, slope and gathered width.- *- * All three are functions of x ALONE, which is the whole claim "the- * fold lines run down". Seeded sines of integer frequency, so the- * profile is smooth and the count of fold lines is what `folds` says;- * the gathered width is the slope-squared integral, in units of the- * NORMALISED x the shader scales back to metres.- */-function foldProfile(folds, rand) {- const modes = [];- let peak = 1e-6;- for (let i = 0; i < 3; i++) {- modes.push([folds + i, rand() * _TAU, 1 / (1 + i * 1.4)]);- }- const raw = (x) => {- let v = 0;- for (const [f, p, a] of modes) v += a * Math.sin(_TAU * f * x + p);- return v;- };- for (let i = 0; i <= 256; i++) peak = Math.max(peak, Math.abs(raw(i / 256)));- const slope = (x) => {- let d = 0;- for (const [f, p, a] of modes) {- d += a * _TAU * f * Math.cos(_TAU * f * x + p);- }- return d / peak;- };- // One pass of the slope integral, sampled once and reused: cheaper- // than integrating per vertex and identical for equal x.- const N = 512;- const cum = new Float32Array(N + 1);- for (let i = 1; i <= N; i++) {- const s = slope((i - 0.5) / N);- cum[i] = cum[i - 1] + 0.5 * s * s / N;- }- const mid = cum[N] / 2;- return (x) => {- const t = unit(x) * N;- const i = Math.min(N - 1, Math.floor(t));- const f = t - i;- return {- v: raw(unit(x)) / peak,- d: slope(unit(x)),- s: cum[i] + (cum[i + 1] - cum[i]) * f - mid,- };- };-}--const BANNER_HEAD = [- 'uniform float uBanDrop;',- 'uniform float uBanFold;',- 'uniform float uBanShrink;',- 'uniform float uBanShrinkMax;',- 'uniform float uBanRate;',- 'uniform float uBanLean;',- 'uniform float uBanSway;',- 'uniform float uBanLag;',- 'uniform float uBanPhase;',- 'attribute vec4 aBan;',- 'varying vec4 vBan;',-].join('\n');--const BANNER_MOVE = [- ' float bnS = aBan.x;',- // Folds open downward from the rod, where the cloth is nailed flat.- ' float bnE = bnS * (2.0 - bnS);',- ' float bnFold = uBanFold * aBan.y * bnE;',- // ONE angle for the whole cloth, at the drop\'s own pendulum rate,- // with the hem arriving after the rod.- ' float bnA = uBanLean + uBanSway * sin(uBanRate * uTime + uBanPhase',- ' - uBanLag * bnS);',- ' float bnC = cos(bnA), bnSi = sin(bnA);',- ' float bnD = uBanDrop * bnS;',- // Cloth pulled into a fold is cloth taken out of the span, so the- // banner narrows as its folds deepen instead of growing.- ' transformed.x -= clamp(uBanShrink * aBan.w * bnE * bnE,',- ' -uBanShrinkMax, uBanShrinkMax);',- ' transformed.y = -bnD * bnC;',- ' transformed.z = bnD * bnSi + bnFold;',- ' vBan = vec4(bnS, aBan.y, uv.x, 1.0);',-].join('\n');--const BANNER_NORMAL = [- '#ifndef FLAT_SHADED',- // The pendulum angle changes down the sheet, and gathering changes X.- // Differentiate both tangents; omitting either leaves fixed-card lighting.- ' float bnEd = 2.0 - 2.0 * bnS;',- ' float bnAd = -uBanSway * uBanLag * cos(uBanRate * uTime + uBanPhase',- ' - uBanLag * bnS);',- ' float bnFree = abs(uBanShrink * aBan.w * bnE * bnE) < uBanShrinkMax ? 1.0 : 0.0;',- ' vec3 bnDx = vec3(1.0 - bnFree * 0.5 * uBanFold * uBanFold',- ' * aBan.z * aBan.z * bnE * bnE, 0.0, uBanFold * aBan.z * bnE);',- ' vec3 bnDs = vec3(-bnFree * uBanShrink * aBan.w * 2.0 * bnE * bnEd,',- ' -uBanDrop * bnC + bnD * bnSi * bnAd,',- ' uBanDrop * bnSi + bnD * bnC * bnAd + uBanFold * aBan.y * bnEd);',- ' vNormal = normalize(normalMatrix * normalize(cross(bnDs, bnDx)));',- // View space, as the flag's: 1 square on to the eye, 0 edge-on.- ' vec4 bnMv = modelViewMatrix * vec4(transformed, 1.0);',- ' vBan.w = astraFacing(vNormal, -bnMv.xyz);',- '#endif',-].join('\n');--const BANNER_FRAGMENT = [- // A hung cloth is the largest flat area this library draws, so it is- // the one that most needs its dye broken up: a slow warm/cool field- // across the width and down the drop, in the cloth's own frame.- ' diffuseColor.rgb = astraHueBreak(diffuseColor.rgb,',- ' vec2(vBan.z * 2.2, vBan.x * 1.6), 1.0, uBanDye);',- ' float bnW = astraStroke(vBan.z * uBanWeave, 0.06);',- ' diffuseColor.rgb *= 0.95 + 0.09 * bnW;',- // A fold holds shade in its trough and the light on its ridge, and- // the gradient DEEPENS downward as the fold opens. Hue follows the- // value: a trough sees only the sky, a ridge sees the sun.- ' float bnF = vBan.y * smoothstep(0.0, 0.6, vBan.x);',- ' diffuseColor.rgb *= 1.0 + 0.26 * bnF;',- ' diffuseColor.rgb = astraHueShift(diffuseColor.rgb, 0.13 * bnF);',- // A hem stands in dust, and dust GREYS cloth. Darkening alone leaves- // a dark dye reading as soot; this keeps the hem lighter than the- // shadow it sits in and still visibly dirtier than the rod.- ' diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.20, 0.185, 0.16),',- ' uBanDust * smoothstep(0.42, 1.0, vBan.x));',- ' diffuseColor.rgb *= 1.03 - 0.10 * vBan.x;',- // Cloth fuzz at the turn of a fold — the same term the flag spends,- // and here it is what makes the folds read at all in flat light.- ' float bnGrz = 1.0 - clamp(vBan.w, 0.0, 1.0);',- ' diffuseColor.rgb *= 1.0 + uBanSheen * bnGrz * bnGrz * bnGrz;',-].join('\n');--/**- * A field of tall crop whose gusts cross it as visible waves.- *- * Buys the shot a meadow cannot give: a hectare of wheat with the wind- * running over it in long streaks, at a stated metres per second, so- * the field reads as weather rather than as animated scenery. Every- * stalk samples ONE gust field — a seeded, seamlessly tiling texture- * scrolled downwind at `uWheatMps` — so neighbours move together with- * the travel lag between them, and per-stalk wobble is a tenth of it.- *- * The constraint: this is a CROP, not tall grass. It is sown in drill- * rows at `rowGap`, so the field carries lines a meadow never has; the- * stalk is a bare stem with a heavy EAR that bends further than the- * stem does; and the wave is made visible by the pale flank a laid-- * over ear turns to the light, not by the bend alone. For ankle-high- * ground cover use `grass.js`.- *- * @param {object} [opts]- * `extent` metres of the square field's side (default 30, centred on- * the group origin); `density` stalks per square metre (default 70;- * `maxStalks` caps it by widening the DRILL spacing, never by- * dropping a corner); `height` stalk height in metres (default 1.1);- * `wind` grass.js's option — `speed` scales the wave's travel, which- * is `waveMps` metres per second; `color` straw albedo; `earColor`- * the ripe head; `heightAt` (x, z) => y, the caller's ground;- * `seed` PRNG seed (default 11); `rowGap` drill spacing in metres- * (default 0.18); `waveMps` crest travel at `wind.speed` 1 (default- * 7, about what a crop wave really runs at); `maxStalks` hard cap- * (default 70000); `shadows` cast stalk shadows through a displaced- * depth pass (default false — the same cost call grass.js makes);- * `name` group name.- * @returns {THREE.Group} Named `Wheat`, resting on y = 0 (or on- * `heightAt`), holding `Stalks` — ONE draw call — with- * `userData.update(t)` driving the wave.- */-export function makeWheatField(opts = {}) {- const extent = opts.extent === undefined ? 30 : opts.extent;- const density = opts.density === undefined ? 70 : opts.density;- const height = opts.height === undefined ? 1.1 : opts.height;- const seed = opts.seed === undefined ? 11 : opts.seed;- const rowGap = opts.rowGap === undefined ? 0.18 : opts.rowGap;- const maxStalks = opts.maxStalks === undefined ? 70000 : opts.maxStalks;- const waveMps = opts.waveMps === undefined ? 7 : opts.waveMps;- const ground = typeof opts.heightAt === 'function' ? opts.heightAt : null;- const wind = windOf(opts.wind);- const straw = new THREE.Color(- opts.color === undefined ? 0xa8863a : opts.color);- const ear = new THREE.Color(- opts.earColor === undefined ? 0xd2ad55 : opts.earColor);-- const g = new THREE.Group();- g.name = opts.name || 'Wheat';- const field = sowField(- extent, density, rowGap, maxStalks, height, ground, seed);- g.add(stalkMesh(field, extent, straw, ear, wind, waveMps, seed,- opts.shadows === true));- g.userData.update = g.userData.tick = (t) => tickShaders(g, t);- const owned = snapshotResources(g);- owned.add(g.getObjectByName('Stalks').material.userData.uniforms.uWheatWave.value);- return attachDisposal(g, owned);-}--/**- * Sow the field in DRILL ROWS — the cue no meadow has.- *- * A crop is planted by a machine: straight rows at a fixed gap, dense- * along the row, bare between. Scattering it like grass.js's clumps- * would make this library a taller copy of that one, and would lose- * the lines that tell a viewer the ground was worked.- */-function sowField(extent, density, rowGap, maxStalks, height, ground,- seed) {- const rand = mulberry32(seed);- // The drill ran at some angle to the world; the wind does not know- // about it, which is what keeps the wave off the rows.- const ang = rand() * Math.PI;- const ux = Math.cos(ang), uz = Math.sin(ang);- const want = Math.max(1, Math.round(density * extent * extent));- // A cap widens the DRILL spacing, so a capped field is thinner and- // never smaller than the extent it advertises.- const scale = Math.sqrt(Math.max(1, want / maxStalks));- const gap = rowGap * scale;- const step = scale / Math.max(density * rowGap, 1e-3);- const span = extent * 0.71 + gap;- const rows = Math.floor(span / Math.max(gap, 1e-3));- const along = Math.floor(span / Math.max(step, 1e-3));- const half = extent / 2;- const pos = [], crop = [], vary = [];- let n = 0, maxH = 0, low = Infinity, high = -Infinity;- for (let r = -rows; r <= rows && n < maxStalks; r++) {- for (let s = -along; s <= along && n < maxStalks; s++) {- const a = s * step + (rand() - 0.5) * step * 0.8;- const b = r * gap + (rand() - 0.5) * gap * 0.45;- const x = ux * a - uz * b;- const z = uz * a + ux * b;- if (x < -half || x > half || z < -half || z > half) continue;- const y = ground ? ground(x, z) : 0;- const h = height * (0.82 + 0.30 * rand());- pos.push(x, y, z);- // A taller stalk is a longer lever on the same stem, so it lays- // over further in the same gust.- crop.push(h, h * (0.0032 + 0.0016 * rand()), _EAR_AT,- (0.72 + 0.34 * rand()) * (0.7 + 0.5 * h / height));- vary.push(rand(), (rand() - 0.5) * 0.5, (rand() - 0.5) * 0.36);- maxH = Math.max(maxH, h);- low = Math.min(low, y);- high = Math.max(high, y + h);- n++;- }- }- return { n, pos, crop, vary, maxH,- low: n ? low : 0, high: n ? high : 0 };-}--/**- * The gust field, baked once on the CPU so both sides agree on it.- *- * grass.js builds its gusts from GLSL_UTIL's noise, which takes no- * seed — every grass field in every scene gusts identically, and no- * test can read what the shader will see. A tiling texture fixes both:- * it is seeded, and the exact numbers the vertex shader samples are- * readable from `uniforms.uWheatWave.value.image.data`.- *- * @param {number} seed PRNG seed.- * @param {number} [size] Texels per side (default 128).- * @returns {THREE.DataTexture} Repeat-wrapped, linear, no mipmaps- * (a vertex fetch has no derivatives to choose one with).- */-function gustTexture(seed, size = 128) {- const rand = mulberry32(seed);- const modes = _WAVE_MODES.map(- ([p, q]) => [p, q, rand() * _TAU, 1 / Math.pow(p * p + q * q, 0.62)]);- const raw = new Float32Array(size * size);- let peak = 1e-6;- for (let y = 0; y < size; y++) {- for (let x = 0; x < size; x++) {- let v = 0;- for (const [p, q, ph, a] of modes) {- v += a * Math.sin(_TAU * (p * x / size + q * y / size) + ph);- }- raw[y * size + x] = v;- peak = Math.max(peak, Math.abs(v));- }- }- const data = new Uint8Array(size * size * 4);- for (let i = 0; i < raw.length; i++) {- const v = Math.round(255 * unit(0.5 + 0.5 * raw[i] / peak));- data[i * 4] = data[i * 4 + 1] = data[i * 4 + 2] = v;- data[i * 4 + 3] = 255;- }- const tex = new THREE.DataTexture(data, size, size, THREE.RGBAFormat);- tex.wrapS = tex.wrapT = THREE.RepeatWrapping;- tex.minFilter = tex.magFilter = THREE.LinearFilter;- tex.generateMipmaps = false;- tex.needsUpdate = true;- return tex;-}--/**- * The stalk lattice: ONE instanced strip with `position` pinned at 0.- *- * GTAOPass redraws with an override material that ignores this vertex- * shader, so a real stalk left in `position` would stack every copy at- * the world origin and burn a black slab there.- */-function stalkLattice(count) {- const corners=[], normals=[], uvs=[], parts=[], indices=[];- for(let part=0;part<3;part++) {- const rows=part===0 ? _STALK_ROWS : 4, start=corners.length/3;- for(let j=0;j<=rows;j++)for(let side=0;side<2;side++) {- let y=j/rows;- if(part===0) y=j<=_STEM_ROWS ? _EAR_AT*j/_STEM_ROWS- : _EAR_AT+(1-_EAR_AT)*(j-_STEM_ROWS)/(_STALK_ROWS-_STEM_ROWS);- corners.push(side-.5,y,0);normals.push(0,0,1);uvs.push(side,y);parts.push(part);- }- for(let j=0;j<rows;j++) {const a=start+j*2;indices.push(a,a+1,a+2,a+1,a+3,a+2);}- }- const g=new THREE.InstancedBufferGeometry();g.setIndex(indices);- g.setAttribute('position',new THREE.Float32BufferAttribute(new Float32Array(corners.length),3));- g.setAttribute('aCorner',new THREE.Float32BufferAttribute(corners,3));- g.setAttribute('aPart',new THREE.Float32BufferAttribute(parts,1));- g.setAttribute('normal',new THREE.Float32BufferAttribute(normals,3));- g.setAttribute('uv',new THREE.Float32BufferAttribute(uvs,2));- g.instanceCount=count;return g;-}--/** One mesh, one draw call: every stalk lives in the vertex shader. */-function stalkMesh(field, extent, straw, ear, wind, waveMps, seed,- shadows) {- const geom = stalkLattice(field.n);- const inst = (name, arr, size) => geom.setAttribute(- name, new THREE.InstancedBufferAttribute(new Float32Array(arr), size));- inst('iPos', field.pos, 3);- inst('iCrop', field.crop, 4);- inst('iVar', field.vary, 3);- // position is zero, so the derived bounds would be a point at the- // origin. A stalk bends along an arc of its OWN length, so its tip- // never leaves a circle of that radius about its root.- const reach = extent / 2 + field.maxH;- geom.boundingBox = new THREE.Box3(- new THREE.Vector3(-reach, field.low, -reach),- new THREE.Vector3(reach, field.high, reach));- geom.boundingSphere = geom.boundingBox.getBoundingSphere(- new THREE.Sphere());-- const mat = new THREE.MeshStandardMaterial({- color: 0xffffff, roughness: 0.74, metalness: 0,- side: THREE.DoubleSide, name: 'WheatStalk',- });- patchStandard(mat, {- name: 'cloth:wheat',- uniforms: {- uWheatStraw: { value: straw.clone() },- uWheatEar: { value: ear.clone() },- uWheatWave: { value: gustTexture(seed) },- uWheatWind: { value: wind.dir.clone() },- // Metres the crest travels per second, and the metres one tile- // of the gust field covers ALONG and ACROSS the wind. The 3.8:1- // is grass.js's streak ratio, at the scale a crop wave needs.- uWheatMps: { value: waveMps * wind.speed },- uWheatTile: { value: new THREE.Vector2(1 / 46, 1 / 12) },- // The shared wave is what moves this field; the per-stalk terms- // are texture on top of it and must stay a fraction of it.- uWheatBase: { value: 0.10 },- uWheatGust: { value: 0.62 * wind.amp * 2 },- uWheatJitter: { value: 0.05 * wind.amp * 2 },- uWheatNod: { value: 0.9 },- uWheatRate: { value: 2.1 * wind.speed },- uWheatHead: { value: 3.2 },- uWheatDroop: { value: 1.8 },- uWheatSheen: { value: 0.7 },- // A crop does not ripen all at once: it goes first where the- // ground is light and last in the wet corner, so a field carries- // green-gold PATCHES tens of metres across with stalk-to-stalk- // scatter inside them. One flat straw hex over a hectare is the- // single loudest tell that a field was painted, not sown — and it- // costs one fbm of the root position to fix.- uWheatPatch: { value: 0.055 },- uWheatRipen: { value: 1 },- // Straw is a shiny tube: the flank turning away from the eye is- // where a stalk catches the sky, and it is why a crop glitters.- uWheatEdge: { value: 0.26 },- },- vertexHead: STALK_HEAD,- vertexBody: STALK_VERTEX,- fragmentHead: [- 'uniform vec3 uWheatStraw;',- 'uniform vec3 uWheatEar;',- 'uniform float uWheatSheen;',- 'uniform float uWheatEdge;',- 'varying vec4 vWheat;',- 'varying float vWheatTone;',- ].join('\n'),- fragmentBody: STALK_FRAGMENT,- });-- const mesh = new THREE.Mesh(geom, mat);- mesh.name = 'Stalks';- mesh.frustumCulled = false;- mesh.receiveShadow = true;- // Without the displaced depth pass a shadow pass draws only the- // degenerate zero-position quads, so casting stays off by default:- // tens of thousands of stalks in the shadow map are a real- // SwiftShader cost the caller opts into.- mesh.castShadow = false;- if (shadows) {- shadowLike(mesh, 'cloth:stalkDepth', STALK_HEAD, STALK_VERTEX);- }- return mesh;-}--const STALK_HEAD = [- 'uniform sampler2D uWheatWave;',- 'uniform vec2 uWheatWind;',- 'uniform vec2 uWheatTile;',- 'uniform float uWheatMps;',- 'uniform float uWheatBase;',- 'uniform float uWheatGust;',- 'uniform float uWheatJitter;',- 'uniform float uWheatNod;',- 'uniform float uWheatRate;',- 'uniform float uWheatHead;',- 'uniform float uWheatDroop;',- 'uniform float uWheatPatch;',- 'uniform float uWheatRipen;',- 'attribute vec3 aCorner;',- 'attribute float aPart;',- 'attribute vec3 iPos;',- 'attribute vec4 iCrop;',- 'attribute vec3 iVar;',- 'varying vec4 vWheat;',- 'varying float vWheatTone;',- glslLocalDir('clothLocalDir'),-].join('\n');--const STALK_VERTEX = [- ' vec3 whRoot = iPos;',- ' float whV = aPart < 0.5 ? aCorner.y : 0.24 + aPart * 0.19;',- ' float whH = max(iCrop.x, 1e-3);',- // Ripeness: a field-wide patch field plus this stalk's own scatter,- // read ONCE per vertex from the root, so a stalk is one tone from- // its foot to its ear and its neighbours are near it, not random.- ' float whPatch = astraFbm2(whRoot.xz * uWheatPatch, 2) - 0.375;',- ' vWheatTone = clamp((whPatch * 2.2 + iVar.y * 1.4) * uWheatRipen,',- ' -1.0, 1.0);',- // ONE gust field for the whole crop, scrolled downwind at a stated- // m/s: two stalks a metre apart see the same wave, a lag apart.- ' vec3 whRootWorld = (modelMatrix * vec4(whRoot, 1.0)).xyz;',- ' vec2 whW = clothLocalDir(vec3(uWheatWind.x, 0.0, uWheatWind.y)).xz;',- ' whW /= max(length(whW), 1e-5);',- ' vec2 whP = vec2(dot(whRootWorld.xz, uWheatWind),',- ' dot(whRootWorld.xz, vec2(-uWheatWind.y, uWheatWind.x)));',- ' vec2 whUv = vec2((whP.x - uWheatMps * uTime) * uWheatTile.x,',- ' whP.y * uWheatTile.y);',- ' float whWave = texture2D(uWheatWave, whUv).r;',- ' float whGust = smoothstep(0.34, 0.98, whWave);',- // Per-stalk motion is texture, not the subject: a twentieth of the- // gust, or a hectare of wheat boils instead of rippling.- ' float whJit = uWheatJitter * sin(uTime * uWheatRate',- ' + astraStagger(iVar.x));',- ' float whK1 = max(iCrop.w * (uWheatBase + uWheatGust * whGust',- ' + whJit), 1e-3);',- // A ripe ear is the heavy end of a light stem: it hangs even in- // still air, keeps bending after the stem has stopped, and nods.- ' float whK2 = whK1 * uWheatHead + uWheatDroop',- ' + uWheatNod * (0.5 + 0.5 * whGust)',- ' * sin(uTime * uWheatRate * 1.6 + astraStagger(iVar.x) * 1.3);',- ' whK2 = max(whK2, 1e-3);',- ' vec2 whF = normalize(whW + vec2(-whW.y, whW.x) * iVar.z);',- ' float whE0 = iCrop.z;',- // Two circular arcs of the stalk\'s own length: a translated tip- // would stretch a stem that must instead lie over.- ' float whA1 = whK1 * min(whV, whE0);',- ' float whU = whH * (1.0 - cos(whA1)) / whK1;',- ' float whY = whH * sin(whA1) / whK1;',- ' float whA2 = whA1 + whK2 * max(whV - whE0, 0.0);',- ' whU += whH * (cos(whA1) - cos(whA2)) / whK2;',- ' whY += whH * (sin(whA2) - sin(whA1)) / whK2;',- ' vec3 whSpine = whRoot + vec3(whF.x * whU, whY, whF.y * whU);',- ' vec3 whTan = vec3(whF.x * sin(whA2), cos(whA2), whF.y * sin(whA2));',- // The ear: a spindle on the top of the stem, and the only fat part- // of a stalk that is otherwise 4 mm of straw.- ' float whE = clamp((whV - whE0) / max(1.0 - whE0, 1e-3), 0.0, 1.0);',- ' float whEar = whV > whE0 ? sqrt(max(sin(3.14159 * whE), 0.0)) : 0.0;',- ' float whWid = iCrop.y * (1.0 - 0.35 * whV) + whEar * whH * 0.011;',- // A stem is round, so its strip faces the eye from every angle- // instead of collapsing to a line like a flat blade.- ' vec3 whWp = (modelMatrix * vec4(whSpine, 1.0)).xyz;',- ' vec3 whView = normalize(clothLocalDir(cameraPosition - whWp));',- ' vec3 whC = cross(whTan, whView);',- ' float whCl = length(whC);',- ' vec3 whSide = whCl > 1e-4 ? whC / whCl : vec3(1.0, 0.0, 0.0);',- ' float whX = aCorner.x * 2.0;',- ' transformed = whSpine + whSide * (whX * whWid);',- ' vec3 whLeafN = vec3(0.0, 1.0, 0.0);',- ' if (aPart > 0.5) {',- ' float lu=aCorner.y;',- ' float la=iVar.x*6.28318+aPart*2.4;',- ' vec3 ld=vec3(cos(la),0.0,sin(la)), ls=vec3(-sin(la),0.0,cos(la));',- ' float ll=whH*(0.22+0.05*aPart);',- ' float lw=whH*0.009*sin(3.14159*lu);',- ' float ly=ll*(0.45*sin(2.5*lu)-0.20*lu*lu);',- ' transformed=whSpine+ld*(ll*lu)+ls*(whX*lw)+vec3(0.0,ly,0.0);',- ' vec3 lt=ld*ll+vec3(0.0,ll*(1.125*cos(2.5*lu)-0.40*lu),0.0);',- ' whLeafN=normalize(cross(ls,lt));',- ' }',- ' vWheat = vec4(whV, whEar, whGust, whX);',- '#ifndef FLAT_SHADED',- ' vec3 whFace = normalize(cross(whSide, whTan));',- ' vNormal = normalize(normalMatrix * normalize(',- ' whFace * sqrt(max(1.0 - whX * whX, 0.04)) + whSide * whX));',- ' if (aPart > 0.5) vNormal = normalize(normalMatrix * whLeafN);',- '#endif',-].join('\n');--const STALK_FRAGMENT = [- // Green where the crop is still coming, gold where it has come. The- // hue swing is 0.30 rad — under a fifth of that and a mixed field- // reads as one straw with a lighting error in it.- ' float whRipe = vWheatTone * 0.5 + 0.5;',- ' vec3 whCol = astraHueShift(uWheatStraw,',- ' vWheat.w * 0.04 - vWheatTone * 0.30);',- ' whCol *= 0.80 + 0.32 * whRipe;',- // Ripe from the ear DOWN, not only on the ear: from above, a crop- // is the colour of its heads and the hand's breadth under them.- ' float whGold = clamp(0.6 * smoothstep(0.5, 0.95, vWheat.x)',- ' + 0.6 * smoothstep(0.05, 0.5, vWheat.y), 0.0, 1.0);',- ' whCol = mix(whCol, astraHueShift(uWheatEar, -vWheatTone * 0.16),',- ' whGold * (0.62 + 0.38 * whRipe));',- // A crop is DEEP: the foot of a stalk sits in the shade of the row,- // and that gradient is most of what reads as a standing field.- ' whCol *= 0.34 + 0.66 * smoothstep(0.0, 0.55, vWheat.x);',- // Spikelets: the grain sits in ranks up the ear, and this is the- // texture that says wheat rather than tall grass.- ' whCol *= 1.0 - 0.35 * vWheat.y',- ' * astraStroke(vWheat.x * 220.0, 0.08);',- // THE WAVE, made visible: a laid-over crop turns its pale flanks to- // the sky, so a crest is a band of light crossing the field and a- // trough is a band of shade.- ' whCol *= 0.84 + uWheatSheen * vWheat.z * (0.6 + 0.4 * vWheat.y);',- // A stem is a polished tube: its turning flank is where it catches- // the sky, and a field of those flanks is what glitters. The strip- // already carries its across-width coordinate, so this is free.- ' float whFl = abs(vWheat.w);',- ' whCol *= 1.0 + uWheatEdge * whFl * whFl * whFl;',- ' diffuseColor.rgb *= whCol;',-].join('\n');diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/clouds.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/clouds.jsdeleted file mode 100644index 96d1df85..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/clouds.js+++ /dev/null@@ -1,373 +0,0 @@-// A connected, ray-marched cloud deck with optical self-shadowing.-// cloudTexture remains a lightweight public alpha-map helper; the sky-// itself no longer stacks transparent camera-facing puff sprites.-import * as THREE from 'three';-import { attachDisposal, snapshotResources } from './lifecycle.js';-import { mulberry32, fbm2, bakeFbm3, dataTexture3D } from './noise.js';-import { intOption, makeShaderMaterial, keepOutOfDepthPasses, option, positive, readWind, sunVector, makeLightProbe, vector } from './shader.js';--// Scattering tints, multiplied by scene illumination. These are not baked-// cloud brightness: night belongs to the light rig, not black cloud albedo.-const PRESETS = {- day: { sunColor: 0xfff4e6, shadeColor: 0x7e94b8, litGain: 1.55 },- golden: { sunColor: 0xffd0a0, shadeColor: 0x7c82ac, litGain: 1.70 },- // Broad overlapping density at a common altitude.- overcast: { sunColor: 0xbcc3cc, shadeColor: 0x717b8a, litGain: 1.05,- count: 40, altitude: 230, spread: 45, alpha: 0.97,- stretch: 1.9 },- night: { sunColor: 0xe0e8f0, shadeColor: 0x71839c, litGain: 0.85,- alpha: 0.88 },-};--/**- * The vector that actually LIGHTS the deck, from the authored sun.- *- * `sunRig().sunDir` keeps reporting the authored sun after it sets (the- * sky needs it to paint twilight), and a light 20 deg under the ground- * lights nothing: passed straight in, every night cloud is lit from- * below through the earth. Same substitution `environment.js` makes for- * its own key light — the moon rises opposite the sun, 30-55 deg up,- * higher the deeper the sun. No argument keeps the old top-lit look.- */-function lightVector(v) {- const d = new THREE.Vector3(...vector(v,[0,1,0],3,'makeClouds: sunDir'));- if(d.lengthSq()<1e-12) throw new RangeError('makeClouds: sunDir must be nonzero');- d.normalize();- if (d.y >= -0.02) return d;- const el = Math.asin(-d.y); // how deep the sun is- const az = Math.atan2(-d.z, -d.x) * 180 / Math.PI; // opposite azimuth- return sunVector(az, Math.max(30, Math.min(55, 25 + el * 180 / Math.PI)));-}--/** Seeded white-RGB alpha map for lightweight custom cloud sprites. */-export function cloudTexture(seed = 7, size = 256) {- seed=option(seed,7,'cloudTexture: seed');- intOption(size,null,'cloudTexture: size',16,1024);- const field = new Float32Array(size * size);- const rand = mulberry32(seed);- const lobes = Array.from({length: 7}, (_,i) => ({- x: (i / 6 - .5) * .58,- y: -.03 + rand() * .17 - Math.abs(i / 6 - .5) * .18,- radius: .15 + rand() * .12,- }));- for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) {- const u = (x + .5) / size - .5, v = (y + .5) / size - .5;- const broad = fbm2(u * 8 + 7, v * 8 + 3, {seed, octaves: 3});- const fine = fbm2(u * 29 - 3, v * 29 + 9, {seed: seed + 17, octaves: 2});- let density = -Infinity;- for (const l of lobes) {- const r = Math.hypot((u - l.x) * .96, (v - l.y) * 1.16) / l.radius;- density = Math.max(density, 1 - r * r);- }- density = Math.max(0, density + broad * .18 + fine * .035);- const base = THREE.MathUtils.smoothstep(v, -.36, -.26);- const edge = THREE.MathUtils.smoothstep(density, 0, .12);- const border = 1 - THREE.MathUtils.smoothstep(Math.max(Math.abs(u), Math.abs(v)), .43, .49);- field[y * size + x] = Math.sqrt(density) * base * edge * border;-- }- const data = new Uint8Array(size * size * 4);- for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) {- const h = field[y * size + x];- const k=(y*size+x)*4;- data[k]=data[k+1]=data[k+2]=255;- data[k+3] = (1-Math.exp(-h*2.0))*255;- }- const tex = new THREE.DataTexture(data, size, size);- tex.needsUpdate = true;- tex.minFilter = THREE.LinearFilter;- tex.magFilter = THREE.LinearFilter;- return tex;-}--const QUALITY = {- low: { view: 40, light: 3 }, balanced: { view: 64, light: 5 },- high: { view: 96, light: 8 },-};--// One weather footprint for the entire deck. Overlapping masses form a-// continuous medium instead of independently blended/sorted sprite layers.-function weatherTexture(seed, count, area, stretch, cirrus) {- const size = 192, data = new Uint8Array(size * size * 4), random = mulberry32(seed);- const weights=new Float32Array(size*size), tops=new Float32Array(size*size), bases=new Float32Array(size*size);- const banks = Array.from({length: count}, () => ({- x: .12 + random() * .76, z: .12 + random() * .76,- rx: (140 + random() * 220) / area * Math.sqrt(stretch),- rz: (100 + random() * 160) / area / Math.sqrt(stretch),- angle: (random() - .5) * (cirrus ? .35 : 2.4),- top: .40 + random() * .58, base: random(),- }));- if(!cirrus) {- // Unequal connected convection towers break the one-dome-per-bank- // silhouette. A separate random stream preserves authored bank centres.- const lobes=mulberry32(seed+1973),parents=[...banks];- for(const bank of parents) {- for(let i=0;i<5;i++) {- const angle=lobes()*Math.PI*2, reach=.45+lobes()*.4;- banks.push({...bank,x:bank.x+Math.cos(angle)*bank.rx*reach,- z:bank.z+Math.sin(angle)*bank.rz*reach,- rx:bank.rx*(.35+lobes()*.3),rz:bank.rz*(.35+lobes()*.3),- top:.45+lobes()*.55,base:Math.max(0,Math.min(1,bank.base+(lobes()-.5)*.35))});- }- bank.top*=.72;- }- }- for (const b of banks) {- const radius = Math.max(b.rx, b.rz);- const loX = Math.max(0, Math.floor((b.x-radius) * size));- const hiX = Math.min(size-1, Math.ceil((b.x+radius) * size));- const loZ = Math.max(0, Math.floor((b.z-radius) * size));- const hiZ = Math.min(size-1, Math.ceil((b.z+radius) * size));- const c = Math.cos(b.angle), s = Math.sin(b.angle);- for (let z=loZ; z<=hiZ; z++) for (let x=loX; x<=hiX; x++) {- const dx=(x+.5)/size-b.x, dz=(z+.5)/size-b.z;- const r=Math.hypot((c*dx+s*dz)/b.rx,(-s*dx+c*dz)/b.rz);- const coverage=Math.max(0,1-r*r), at=z*size+x, i=at*4, weight=coverage*coverage;- data[i]=Math.max(data[i],Math.round(coverage*255));- weights[at]+=weight;tops[at]+=weight*b.top;bases[at]+=weight*b.base;- data[i+3]=255;- }- }- for(let i=0;i<weights.length;i++) if(weights[i]>0) {- data[i*4+1]=Math.round(tops[i]/weights[i]*255);- data[i*4+2]=Math.round(bases[i]/weights[i]*255);- }- const texture=new THREE.DataTexture(data,size,size);- texture.minFilter=texture.magFilter=THREE.LinearFilter;- texture.wrapS=texture.wrapT=THREE.RepeatWrapping; texture.needsUpdate=true;- return texture;-}--function cloudNoise(seed) {- const size=40, random=mulberry32(seed+851), {values}=bakeFbm3(random,size,[4,8,16],2);- // Periodic cellular billows supply rounded convection cells; fBm alone- // erodes a smooth dome into fuzzy smoke with no internal cloud structure.- const cells=4, features=Float32Array.from({length:cells**3*3},()=>random());- const wrap=i=>((i%cells)+cells)%cells;- const data=new Uint8Array(size**3*4);- for(let i=0;i<size**3;i++) {- const q=[(i%size+.5)/size*cells,(Math.floor(i/size)%size+.5)/size*cells,- (Math.floor(i/(size*size))+.5)/size*cells];- const base=q.map(Math.floor);let nearest=4;- for(let z=-1;z<=1;z++) for(let y=-1;y<=1;y++) for(let x=-1;x<=1;x++) {- const cell=[base[0]+x,base[1]+y,base[2]+z];- const k=((wrap(cell[2])*cells+wrap(cell[1]))*cells+wrap(cell[0]))*3;- const dx=cell[0]+features[k]-q[0],dy=cell[1]+features[k+1]-q[1],dz=cell[2]+features[k+2]-q[2];- nearest=Math.min(nearest,dx*dx+dy*dy+dz*dz);- }- data[i*4]=Math.round(values[i*2]*255);- data[i*4+1]=Math.round(values[i*2+1]*255);- data[i*4+2]=Math.round(Math.max(0,1-Math.sqrt(nearest)/1.2)*255);data[i*4+3]=255;- }- return dataTexture3D(data,size);-}--const DECK_HEAD = /* glsl */`-precision highp sampler3D;-uniform sampler2D uWeather;-uniform sampler3D uNoise;-uniform vec3 uSize, uCenter, uCameraLocal, uSunLocal, uSunDir;-uniform vec3 uSunLight, uSkyLight, uFogColor, uViewLocal, uViewWorld;-uniform vec2 uDrift;-uniform mat3 uLocalToWorld;-uniform mat4 uLocalToClip;-uniform float uAlpha, uExtinction, uRim, uHaze, uSpread, uCirrus, uHue, uOrthographic;-varying vec3 vLocal;--float deckDensity(vec3 position) {- vec3 uv=(position-uCenter)/uSize+.5;- if(any(lessThan(uv,vec3(0)))||any(greaterThan(uv,vec3(1)))) return 0.0;- vec3 p=position-uCenter-vec3(uDrift.x,0,uDrift.y)*uTime;- vec2 broad=texture(uNoise,p/680.0).rg;- vec2 weatherUV=uv.xz-uDrift*uTime/uSize.xz+(broad-.5)*.045;- vec3 weather=texture2D(uWeather,weatherUV).rgb;- float bottom=weather.b*uSpread+(broad.g-.5)*.045;- float h=(uv.y-bottom)/max(.12,.30+weather.g*.64-bottom);- if(h<=0.0||h>=1.0||weather.r<.015) return 0.0;- vec3 q=p/mix(175.0,310.0,uCirrus);- q.x*=mix(1.0,.28,uCirrus); q.z*=mix(1.0,2.7,uCirrus);- vec3 noise=texture(uNoise,q).rgb;- float fine=texture(uNoise,q*3.17+vec3(.17,.31,.73)).g;- float body=weather.r-pow(max(h-.12,0.0),1.6)*.75;- float erosion=(1.0-noise.r)*.28+(1.0-noise.b)*.36+(1.0-fine)*.14;- float base=smoothstep(0.0,.09,h);- float top=1.0-smoothstep(.80,1.0,h);- float edge=smoothstep(0.0,.035,uv.x)*(1.0-smoothstep(.965,1.0,uv.x))- *smoothstep(0.0,.035,uv.z)*(1.0-smoothstep(.965,1.0,uv.z));- float billow=mix(.35,1.0,noise.b)*(.7+.3*noise.g);- return smoothstep(.015,.24,body-erosion)*billow*base*top*edge;-}--float deckShadow(vec3 p) {- float end=max(0.0,astraRayBox(p,uSunLocal,uCenter-uSize*.5,uCenter+uSize*.5).y);- // Short near-surface intervals retain detailed silver edges; longer- // intervals sample the rest of the cloud rather than repeating local shade.- float opticalDepth=0.0;- float metric=length(uLocalToWorld*uSunLocal);- for(int i=0;i<DECK_LIGHT_STEPS;i++) {- float a=float(i)/float(DECK_LIGHT_STEPS),b=float(i+1)/float(DECK_LIGHT_STEPS);- float start=a*a*end,stop=b*b*end;- opticalDepth+=deckDensity(p+uSunLocal*(start+stop)*.5)*(stop-start)*metric*uExtinction;- }- return opticalDepth;-}--float deckPhase(float cosine,float g) {- return (1.0-g*g)/pow(max(.025,1.0+g*g-2.0*g*cosine),1.5);-}-`;--/**- * One ray-marched 3D cloud deck, with connected density, optical extinction,- * self-shadowing and forward scattering. Seed/count/area/altitude/spread keep- * their authored placement roles; individual billboard puffs are no longer used.- * Defaults: area 2600 m, altitude 260 m, spread 120 m, count 14. `alpha` scales- * optical depth (zero is off); `quality` low/balanced/high changes integration- * steps only. `wind` accepts the shared world-XZ wind forms. `sunDir` is a world- * vector toward the light; a below-horizon sun selects the corresponding moon.- * Preset and sunColor/shadeColor tint the actual scene key/fill illumination.- * `litGain`, `rim`, `haze`, `stretch`, `hueVariance` remain optional controls.- *- * update(t) accepts absolute seconds. The returned Mesh owns its two textures- * and supports idempotent disposal. Parent transforms affect the authored deck.- * This is a distant atmospheric layer: it does not cast terrain shadows or- * truncate integration at geometry embedded inside its density. Opaque geometry- * entirely in front/behind is tested against the first participating sample.- * Log-depth hosts retain proxy depth. Cost is higher than the former sprites;- * use quality:'low' for previews, 'high' for large cloud close-ups.- */-export function makeClouds(opts = {}) {- const p=PRESETS[opts.preset||'day']||PRESETS.day, cirrus=opts._cirrus===true;- const seed=option(opts.seed,7,'makeClouds: seed');- const count=intOption(opts.count,p.count??14,'makeClouds: count',0,1000);- const area=positive(opts.area,2600,'makeClouds: area');- const altitude=option(opts.altitude,p.altitude??260,'makeClouds: altitude');- const spread=option(opts.spread,p.spread??120,'makeClouds: spread',0);- const stretch=positive(opts.stretch,p.stretch??1,'makeClouds: stretch');- const alpha=option(opts.alpha,p.alpha??.92,'makeClouds: alpha',0,1);- const gain=option(opts.litGain,p.litGain,'makeClouds: litGain',0);- const rim=option(opts.rim,.55,'makeClouds: rim',0);- const haze=option(opts.haze,.22,'makeClouds: haze',0,1);- const hue=option(opts.hueVariance,.13,'makeClouds: hueVariance',0,1);- const wind=readWind(opts.wind,3,'makeClouds wind');- const quality=opts.quality??'balanced';- if(!Object.hasOwn(QUALITY,quality)) throw new RangeError('makeClouds: quality must be low, balanced or high');- const tier=QUALITY[quality];- const thickness=cirrus?Math.max(45,spread*.55):Math.max(140,spread+170);- const size=new THREE.Vector3(area,thickness,area);- const center=new THREE.Vector3(0,altitude+thickness*.2,-area*.18);- const sun=lightVector(opts.sunDir), sunTint=new THREE.Color(opts.sunColor??p.sunColor);- const skyTint=new THREE.Color(opts.shadeColor??p.shadeColor);- const weather=weatherTexture(seed,count,area,stretch,cirrus), noise=cloudNoise(seed);- const material=makeShaderMaterial({- name:opts.name||'CloudDeckMaterial',transparent:true,depthWrite:false,- side:THREE.BackSide,fog:false,- defines:{DECK_STEPS:tier.view,DECK_LIGHT_STEPS:tier.light},- uniforms:{- uWeather:{value:weather},uNoise:{value:noise},uSize:{value:size},uCenter:{value:center},- uCameraLocal:{value:new THREE.Vector3()},uSunLocal:{value:sun.clone()},uSunDir:{value:sun},- uSunLight:{value:new THREE.Color()},uSkyLight:{value:new THREE.Color()},- uFogColor:{value:new THREE.Color()},uDrift:{value:new THREE.Vector2(wind.x,wind.z)},- uViewLocal:{value:new THREE.Vector3()},uViewWorld:{value:new THREE.Vector3()},- uOrthographic:{value:0},- uWind:{value:wind.strength},uAlpha:{value:alpha},uRim:{value:rim},uHaze:{value:haze},- uExtinction:{value:(cirrus?.006:.035)*alpha},uSpread:{value:Math.min(.28,spread/thickness*.4)},- uCirrus:{value:cirrus?1:0},uHue:{value:hue},- uLocalToWorld:{value:new THREE.Matrix3()},uLocalToClip:{value:new THREE.Matrix4()},- },- varyings:'varying vec3 vLocal;',vertexMain:'vLocal=position;',fragmentHead:DECK_HEAD,- fragmentMain: /* glsl */`- if(uAlpha<=0.0) discard;- vec3 direction=uOrthographic>.5?uViewLocal:normalize(vLocal-uCameraLocal);- float metric=length(uLocalToWorld*direction);- vec3 origin=uCameraLocal;- if(uOrthographic>.5) origin=vLocal-direction*- (dot(uLocalToWorld*(vLocal-uCameraLocal),uViewWorld)/max(metric,1e-8));- vec2 hit=astraRayBox(origin,direction,uCenter-uSize*.5,uCenter+uSize*.5);- float start=max(0.0,hit.x),end=hit.y;- if(end<=start) discard;- float stepSize=(end-start)/float(DECK_STEPS);- vec3 worldDirection=normalize(uLocalToWorld*direction);- float cosine=dot(worldDirection,uSunDir);- float phase=min(3.5,.85*deckPhase(cosine,.62)+.15*deckPhase(cosine,-.22));- float jitter=.15+.7*astraHash21(gl_FragCoord.xy);- float transmittance=1.0;- vec3 radiance=vec3(0),first=origin+direction*end;- bool found=false;- for(int i=0;i<DECK_STEPS;i++) {- vec3 point=origin+direction*(start+(float(i)+jitter)*stepSize);- float density=deckDensity(point);- if(density>.001) {- if(!found){first=point;found=true;}- float tau=deckShadow(point);- float direct=exp(-tau);- float multiple=.30*exp(-tau*.25)+.10*exp(-tau*.065);- float height=clamp((point.y-uCenter.y)/uSize.y+.5,0.0,1.0);- vec3 source=uSunLight*(direct*(.30+phase*uRim*.5)+multiple)- +uSkyLight*(.45+.55*height);- float tint=sin(dot(point,vec3(.006,.011,.009)))*uHue*.08;- source*=vec3(1.0+tint,1.0,1.0-tint);- float opacity=1.0-exp(-density*uExtinction*stepSize*metric);- radiance+=transmittance*opacity*source;- transmittance*=1.0-opacity;- if(transmittance<.008) break;- }- }- float opacity=1.0-transmittance;- if(opacity<.003) discard;- vec3 color=radiance/max(opacity,.001);- float distance=length(uLocalToWorld*(first-uCameraLocal));- color=mix(color,uFogColor,uHaze*(1.0-exp(-distance/3500.0)));- #ifndef USE_LOGDEPTHBUF- gl_FragDepth=astraClipDepth(uLocalToClip,first);- #endif- gl_FragColor=vec4(color,opacity);- `,- });- const mesh=new THREE.Mesh(new THREE.BoxGeometry(...size.toArray()).translate(...center.toArray()),material);- mesh.name=opts.name||'CumulusLayer';- mesh.visible=count>0;- mesh.userData.sceneBackdrop='sky';- keepOutOfDepthPasses(mesh);- const before=mesh.onBeforeRender,readLights=makeLightProbe(),inverse=new THREE.Matrix4();- const drift=new THREE.Vector3(wind.x,0,wind.z),localDrift=new THREE.Vector3();- const inverseLinear=new THREE.Matrix3();- mesh.onBeforeRender=(...args)=>{- before.apply(mesh,args);- const scene=args[1],camera=args[2],u=material.uniforms;- const lights=readLights(scene);- if(opts.sunDir==null && lights.sun) sun.copy(lights.sunDirection);- u.uSunLight.value.setRGB(0,0,0);- if(lights.sun) u.uSunLight.value.copy(sunTint).multiply(lights.sun.color)- .multiplyScalar(gain*lights.sun.intensity/(opts.preset==='night'?2.2:5.4));- const fill=c=>lights.ambient[c]+lights.sky[c]*.8+lights.ground[c]*.2+lights.environment*.12;- u.uSkyLight.value.setRGB(fill('r'),fill('g'),fill('b')).multiply(skyTint);- u.uFogColor.value.copy(scene.fog?.color||u.uSkyLight.value);- inverse.copy(mesh.matrixWorld).invert();- camera.getWorldPosition(u.uCameraLocal.value).applyMatrix4(inverse);- camera.getWorldDirection(u.uViewWorld.value);- u.uViewLocal.value.copy(u.uViewWorld.value).transformDirection(inverse);- u.uOrthographic.value=camera.isOrthographicCamera?1:0;- u.uSunLocal.value.copy(sun).transformDirection(inverse);- u.uLocalToWorld.value.setFromMatrix4(mesh.matrixWorld);- inverseLinear.setFromMatrix4(inverse);- localDrift.copy(drift).applyMatrix3(inverseLinear);u.uDrift.value.set(localDrift.x,localDrift.z);- u.uLocalToClip.value.copy(camera.projectionMatrix).multiply(camera.matrixWorldInverse).multiply(mesh.matrixWorld);- };- mesh.userData.update=t=>{- if(!Number.isFinite(t)) throw new RangeError('CloudLayer.update: time must be finite');- material.uniforms.uTime.value=t;- };- mesh.userData.quality=quality;- mesh.userData.steps={...tier};- const owned=snapshotResources(mesh);owned.add(weather);owned.add(noise);- return attachDisposal(mesh,owned);-}--/** Thin, wind-stretched high-altitude ice-cloud deck; same options as makeClouds. */-export function makeCirrus(opts = {}) {- return makeClouds({preset:'day',...opts,_cirrus:true,name:opts.name??'CirrusLayer',- seed:opts.seed??23,count:opts.count??8,area:opts.area??3200,- altitude:opts.altitude??520,spread:opts.spread??100,alpha:opts.alpha??.44,- wind:opts.wind??6,stretch:opts.stretch??4.5,rim:opts.rim??.85});-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloudvolume.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloudvolume.jsdeleted file mode 100644index 7f48241e..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloudvolume.js+++ /dev/null@@ -1,326 +0,0 @@-/**- * Bounded, ray-marched cumulus clouds. A seeded 3D texture separates a- * stationary billow scaffold from periodic advected density and erosion; Beer extinction and secondary light marches- * supply thickness, sunward shading and silver linings. Three quality tiers- * trade integration accuracy for cost without changing the density field.- *- * This is authored weather, not a fluid solver. Multiple scattering is a- * bounded two-lobe approximation. It does not cast terrain shadows, receive- * scene shadow maps or truncate its integration at intersecting geometry.- * Ordinary depth testing uses the first contributing density sample, so- * opaque objects behind the cloud do not erase its front. Geometry embedded- * in density still needs scene-depth-aware integration, which is not supplied.- * Logarithmic-depth rendering retains proxy-box depth as a fallback.- * Transparent objects follow ordinary Three.js object sorting. No temporal- * reconstruction or external textures are required.- */-import * as THREE from 'three';-import { makeShaderMaterial, keepOutOfDepthPasses, makeLightProbe, option, readWind, vector } from './shader.js';-import { attachDisposal, snapshotResources } from './lifecycle.js';-import { bakeFbm3, dataTexture3D, mulberry32, sampleGrid3 } from './noise.js';--const TIERS = {- low: { steps: 40, lightSteps: 6 },- balanced: { steps: 72, lightSteps: 10 },- high: { steps: 112, lightSteps: 16 },-};-const RESOLUTION = 80;-const clamp = (x, a = 0, b = 1) => Math.max(a, Math.min(b, x));-const smooth = (a, b, x) => {- const t = clamp((x - a) / (b - a));- return t * t * (3 - 2 * t);-};--function densityTexture(seed) {- const random = mulberry32(seed);- const { values: noiseField, lattices } = bakeFbm3(random, RESOLUTION, [4, 8, 16, 32]);- // Unequal convection towers grow from a connected low bank. Small- // satellite billows belong to each tower instead of a regular 3-by-2 grid.- const lobes = [{ x: 0, y: -.15, z: 0, rx: .31, ry: .16, rz: .25 }];- for (let cluster = 0; cluster < 7; cluster++) {- const angle = cluster * 2.399963 + random() * .5;- const spread = cluster === 0 ? 0 : Math.sqrt(cluster / 7);- const x = Math.cos(angle) * .22 * spread + (random() - .5) * .025;- const z = Math.sin(angle) * .16 * spread + (random() - .5) * .025;- const radius = .115 + random() * .075;- const y = -.10 + random() * .13;- lobes.push({ x, y, z, rx: radius * 1.12, ry: radius * 1.45, rz: radius });- for (let lobe = 0; lobe < 7; lobe++) {- const azimuth = random() * Math.PI * 2;- const elevation = -.15 + random() * 1.25;- const r = radius * (.32 + random() * .30);- lobes.push({- x: x + Math.cos(azimuth) * Math.cos(elevation) * radius * .88,- y: y + Math.sin(elevation) * radius * 1.38,- z: z + Math.sin(azimuth) * Math.cos(elevation) * radius * .88,- rx: r, ry: r * (1.0 + random() * .45), rz: r,- });- }- }- const data = new Uint8Array(RESOLUTION ** 3 * 4);- let i = 0;- for (let z = 0; z < RESOLUTION; z++) for (let y = 0; y < RESOLUTION; y++) for (let x = 0; x < RESOLUTION; x++) {- const u = (x + .5) / RESOLUTION, v = (y + .5) / RESOLUTION, w = (z + .5) / RESOLUTION;- const noise = noiseField[i / 4];- let shape = -4;- for (const lobe of lobes) {- const distance = Math.hypot((u - .5 - lobe.x) / lobe.rx,- (v - .5 - lobe.y) / lobe.ry, (w - .5 - lobe.z) / lobe.rz);- shape = Math.max(shape, 1 - distance);- }- const detail = sampleGrid3(lattices[2].data, 16, u * 16, v * 16, w * 16);- // Stationary nested breakup leaves a scalloped boundary. The ellipsoid- // only limits the outer support; its zero band stays inside the proxy.- shape += (detail - .5) * .70;- shape = Math.min(shape, 1 - Math.hypot((u - .5) / .48, (v - .49) / .48, (w - .5) / .48));- const value = clamp(.53 + shape * .66);- // Keep the lower fade out of this thresholded texture. Applying it- // here turns a soft boundary into a nearly flat opaque cloud-base lip.- const border = smooth(0, .07, u) * (1 - smooth(.93, 1, u))- * (1 - smooth(.93, 1, v))- * smooth(0, .07, w) * (1 - smooth(.93, 1, w));- data[i++] = Math.round(value * border * 255);- data[i++] = Math.round(clamp(noise) * 255);- data[i++] = Math.round(clamp(detail) * 255);- // Coverage and advected noise may erode this support but cannot create- // new cloud on a box face. Alpha is support, not rendered opacity.- data[i++] = Math.round(smooth(0, .10, shape) * 255);- }- return dataTexture3D(data, RESOLUTION);-}--const HEAD = /* glsl */`-precision highp sampler3D;-uniform sampler3D uDensityMap;-uniform vec3 uSize;-uniform vec3 uCameraLocal;-uniform vec3 uSunLocal;-uniform vec3 uSunWorld;-uniform vec3 uSunColor;-uniform vec3 uSkyColor;-uniform vec2 uWind;-uniform mat3 uLocalToWorld;-uniform mat4 uLocalToClip;-uniform float uCoverage;-uniform float uDetail;-uniform float uExtinction;-uniform float uTime;-varying vec3 vLocal;--vec2 cloudBox(vec3 origin, vec3 direction) {- return astraRayBox(origin, direction, -uSize * .5, uSize * .5);-}-float cloudDensity(vec3 position) {- vec3 uv = position / uSize + .5;- if (any(lessThan(uv, vec3(0.0))) || any(greaterThan(uv, vec3(1.0)))) return 0.0;- vec3 drift = vec3(uWind.x / uSize.x, 0.0, uWind.y / uSize.z) * uTime;- if (uCoverage <= 0.0) return 0.0;- vec4 field = texture(uDensityMap, uv - drift);- // Keep support in local space while only periodic noise advects.- vec4 scaffold = texture(uDensityMap, uv);- float shape = scaffold.r;- float noise = clamp(shape + (field.g - .5) * 1.15 - (field.b - .5) * .18, 0.0, 1.0);- float baseFade = smoothstep(0.0, .18, uv.y);- float height = baseFade * baseFade * (1.0 - smoothstep(.92, 1.0, uv.y));- float edge = smoothstep(0.0, .10, uv.x) * (1.0 - smoothstep(.90, 1.0, uv.x))- * smoothstep(0.0, .10, uv.z) * (1.0 - smoothstep(.90, 1.0, uv.z));- float threshold = .72 - uCoverage * .40;- vec3 detailUv = (uv - drift) * 5.0 + vec3(.137,.291,.417);- vec4 detailSample = texture(uDensityMap, detailUv);- float fine = clamp((detailSample.g - .22) / .56, 0.0, 1.0);- float erosion = (1.0 - fine) * uDetail * 1.10 * (1.0 - noise);- // Fade the resolved density, not the field before thresholding. This- // makes the bottom lose optical thickness gradually rather than crop flat.- return clamp((noise - threshold - erosion) * 9.0, 0.0, 1.0) * edge * height * scaffold.a;-}-float cloudHG(float cosine, float g) {- float gg = g * g;- return (1.0 - gg) / pow(max(.01, 1.0 + gg - 2.0 * g * cosine), 1.5);-}-float cloudSunDepth(vec3 position, float jitter) {- float end = max(cloudBox(position, uSunLocal).y, 0.0);- float metric = length(uLocalToWorld * uSunLocal);- float opticalDepth = 0.0;- for (int j = 0; j < CLOUD_LIGHT_STEPS; j++) {- // Quadratic spacing resolves the billow immediately around the sample;- // uniform long steps skip its skin and erase small-scale self-shadowing.- float a = float(j) / float(CLOUD_LIGHT_STEPS);- float b = float(j + 1) / float(CLOUD_LIGHT_STEPS);- float start = a * a * end, stop = b * b * end;- vec3 p = position + uSunLocal * mix(start, stop, jitter);- opticalDepth += cloudDensity(p) * (stop - start) * metric * uExtinction;- }- return opticalDepth;-}-`;--/**- * size: local [x,y,z] metres (default [600,180,360]), seed (19),- * coverage: 0..1 (.55), density: extinction / metre (.028),- * quality: 'low'|'balanced'|'high', wind: local [x,z] metres/second,- * advecting density detail through a bounded stationary form. Move the Mesh- * itself for whole-cloud travel; the cloud scaffold never wraps across its box.- * sunDir: WORLD direction toward the sun (`sunDirection` is read too), sunColor and skyColor:- * linear-light THREE.Color or sRGB hex. sunIntensity scales the strongest- * visible directional light (1.25 at the standard 5.4-unit daylight rig).- * Ambient/hemisphere lights and scene.environment supply the sky contribution.- *- * The returned Mesh is centred at its local origin. update(t) accepts absolute- * seconds; sampleDensity(x,y,z,t) returns the same local 0..1 field sampled by- * the GPU before optical extinction. setSunDirection() supports moving light.- */-export function makeCloudVolume(opts = {}) {- const size = vector(opts.size, [600, 180, 360], 3, 'makeCloudVolume: size');- if (size.some((v) => v <= 0 || v > 100000)) throw new RangeError('makeCloudVolume: size must be in (0, 100000] metres');- const w = readWind(opts.wind, [2.5, .4], 'makeCloudVolume wind'), wind = [w.x, w.z];- const sunOption = opts.sunDir ?? opts.sunDirection;- const direction = vector(sunOption, [-.5, .7, -.3], 3, 'makeCloudVolume: sunDir');- if (Math.hypot(...direction) < 1e-9) throw new RangeError('makeCloudVolume: sunDir must be nonzero');- const seed = option(opts.seed, 19, 'makeCloudVolume: seed');- const coverage = option(opts.coverage, .55, 'makeCloudVolume: coverage', 0, 1);- const extinction = option(opts.density, .028, 'makeCloudVolume: density', 0, 10);- const detail = option(opts.detail, .65, 'makeCloudVolume: detail', 0, 1);- const intensity = option(opts.sunIntensity, 1.25, 'makeCloudVolume: sunIntensity', 0);- const quality = opts.quality ?? 'balanced';- if (!Object.hasOwn(TIERS, quality)) throw new RangeError(`makeCloudVolume: quality must be one of ${Object.keys(TIERS)}`);- const tier = TIERS[quality];- const texture = densityTexture(seed);- let sunPinned = sunOption !== undefined && sunOption !== null;- const sun = new THREE.Vector3(...direction).normalize();- const sunTint = new THREE.Color(opts.sunColor ?? 0xfff3dc);- const skyTint = new THREE.Color(opts.skyColor ?? 0x9eb9da);- const readLights = makeLightProbe();- const material = makeShaderMaterial({- name: 'CloudVolumeMaterial', transparent: true, depthWrite: false,- side: THREE.BackSide, fog: false,- defines: { CLOUD_STEPS: tier.steps, CLOUD_LIGHT_STEPS: tier.lightSteps },- uniforms: {- uDensityMap: { value: texture }, uSize: { value: new THREE.Vector3(...size) },- uCameraLocal: { value: new THREE.Vector3() }, uSunLocal: { value: sun.clone() },- uSunWorld: { value: sun }, uLocalToWorld: { value: new THREE.Matrix3() },- uLocalToClip: { value: new THREE.Matrix4() },- uSunColor: { value: new THREE.Color(opts.sunColor ?? 0xfff3dc).multiplyScalar(intensity) },- uSkyColor: { value: new THREE.Color(opts.skyColor ?? 0x9eb9da) },- uCoverage: { value: coverage }, uExtinction: { value: extinction },- uDetail: { value: detail },- uWind: { value: new THREE.Vector2(...wind) }, uTime: { value: 0 },- },- varyings: 'varying vec3 vLocal;',- vertexMain: 'vLocal = position;',- fragmentHead: HEAD,- fragmentMain: /* glsl */`- vec3 direction = normalize(vLocal - uCameraLocal);- vec2 bounds = cloudBox(uCameraLocal, direction);- float start = max(bounds.x, 0.0), end = bounds.y;- if (end <= start || uExtinction <= 0.0 || uCoverage <= 0.0) discard;- float stepLength = (end - start) / float(CLOUD_STEPS);- float metric = length(uLocalToWorld * direction);- vec3 worldDirection = normalize(uLocalToWorld * direction);- float cosine = dot(worldDirection, uSunWorld);- float phase = min(3.0, .82 * cloudHG(cosine, .58) + .18 * cloudHG(cosine, -.24));- // Fixed screen-space jitter is deterministic at a fixed camera/time;- // it breaks integration bands without requiring temporal accumulation.- float jitter = astraHash21(gl_FragCoord.xy) * .8 + .1;- float transmittance = 1.0;- vec3 radiance = vec3(0.0);- vec3 firstDensity = uCameraLocal + direction * end;- bool densityHit = false;- for (int i = 0; i < CLOUD_STEPS; i++) {- vec3 position = uCameraLocal + direction * (start + (float(i) + jitter) * stepLength);- float density = cloudDensity(position);- if (density > .001) {- if (!densityHit) { firstDensity = position; densityHit = true; }- float tau = cloudSunDepth(position, .5);- float single = exp(-tau);- // Two attenuated orders approximate broad multiple scattering.- // They preserve dark cores without the black smoke of single scatter.- float multiple = .50 * exp(-tau * .22) + .20 * exp(-tau * .05);- float height = clamp(position.y / uSize.y + .5, 0.0, 1.0);- vec3 source = uSunColor * (phase * .65 * single + multiple)- + uSkyColor * (.20 + .58 * height);- float alpha = 1.0 - exp(-density * uExtinction * stepLength * metric);- radiance += transmittance * alpha * source;- transmittance *= 1.0 - alpha;- if (transmittance < .012) break;- }- }- float alpha = 1.0 - transmittance;- if (alpha < .003) discard;- // The back face only bounds the integration ray. Test the visible- // density against opaque depth, not the often much farther proxy exit.- #ifndef USE_LOGDEPTHBUF- gl_FragDepth = astraClipDepth(uLocalToClip, firstDensity);- #endif- gl_FragColor = vec4(radiance / max(alpha, .001), alpha);- `,- });- const mesh = new THREE.Mesh(new THREE.BoxGeometry(...size), material);- mesh.name = opts.name ?? 'CloudVolume';- keepOutOfDepthPasses(mesh);- const beforeRender = mesh.onBeforeRender;- const inverse = new THREE.Matrix4();- mesh.onBeforeRender = (...args) => {- beforeRender.apply(mesh, args);- const camera = args[2], scene = args[1];- const { sun: key, sunDirection, ambient, sky, ground, environment } = readLights(scene);- const uniforms = material.uniforms;- uniforms.uSunColor.value.setRGB(0, 0, 0);- if (key) {- uniforms.uSunColor.value.copy(key.color).multiply(sunTint).multiplyScalar(key.intensity / 5.4 * intensity);- if (!sunPinned) sun.copy(sunDirection);- }- // The scene environment is an independent source of diffuse sky light;- // removing a directional light does not remove that authored environment.- const fill = (c) => ambient[c] + sky[c] * .75 + ground[c] * .25 + environment * .35;- uniforms.uSkyColor.value.setRGB(fill('r'), fill('g'), fill('b')).multiply(skyTint);- inverse.copy(mesh.matrixWorld).invert();- camera.getWorldPosition(material.uniforms.uCameraLocal.value).applyMatrix4(inverse);- material.uniforms.uSunLocal.value.copy(sun).transformDirection(inverse);- material.uniforms.uLocalToWorld.value.setFromMatrix4(mesh.matrixWorld);- material.uniforms.uLocalToClip.value.copy(camera.projectionMatrix)- .multiply(camera.matrixWorldInverse).multiply(mesh.matrixWorld);- };- mesh.userData.update = (t) => {- if (!Number.isFinite(t)) throw new RangeError('CloudVolume.update: time must be finite');- material.uniforms.uTime.value = t;- };- mesh.userData.setSunDirection = (value) => {- const values = vector(value, null, 3, 'CloudVolume.setSunDirection');- if (Math.hypot(...values) < 1e-9) throw new RangeError('CloudVolume: sunDirection must be nonzero');- sun.fromArray(values).normalize();- sunPinned = true;- };- mesh.userData.sampleDensity = (x, y, z, t = material.uniforms.uTime.value) => {- if (![x, y, z, t].every(Number.isFinite)) throw new RangeError('CloudVolume.sampleDensity: coordinates/time must be finite');- const uv = [x / size[0] + .5, y / size[1] + .5, z / size[2] + .5];- if (uv.some((v) => v < 0 || v > 1) || coverage === 0) return 0;- const driftingNoise = sampleGrid3(texture.image.data, RESOLUTION,- (uv[0] - wind[0] * t / size[0]) * RESOLUTION - .5,- uv[1] * RESOLUTION - .5,- (uv[2] - wind[1] * t / size[2]) * RESOLUTION - .5, 4, 1) / 255;- const shape = sampleGrid3(texture.image.data, RESOLUTION,- uv[0] * RESOLUTION - .5, uv[1] * RESOLUTION - .5, uv[2] * RESOLUTION - .5, 4, 0) / 255;- const driftingDetail = sampleGrid3(texture.image.data, RESOLUTION,- (uv[0] - wind[0] * t / size[0]) * RESOLUTION - .5, uv[1] * RESOLUTION - .5,- (uv[2] - wind[1] * t / size[2]) * RESOLUTION - .5, 4, 2) / 255;- const noise = clamp(shape + (driftingNoise - .5) * 1.15 - (driftingDetail - .5) * .18);- const support = sampleGrid3(texture.image.data, RESOLUTION,- uv[0] * RESOLUTION - .5, uv[1] * RESOLUTION - .5, uv[2] * RESOLUTION - .5, 4, 3) / 255;- const baseFade = smooth(0, .18, uv[1]);- const height = baseFade * baseFade * (1 - smooth(.92, 1, uv[1]));- const edge = smooth(0, .10, uv[0]) * (1 - smooth(.90, 1, uv[0]))- * smooth(0, .10, uv[2]) * (1 - smooth(.90, 1, uv[2]));- const detailUv = [(uv[0] - wind[0] * t / size[0]) * 5 + .137,- uv[1] * 5 + .291, (uv[2] - wind[1] * t / size[2]) * 5 + .417];- const fine = clamp((sampleGrid3(texture.image.data, RESOLUTION,- detailUv[0] * RESOLUTION - .5, detailUv[1] * RESOLUTION - .5,- detailUv[2] * RESOLUTION - .5, 4, 1) / 255 - .22) / .56);- const erosion = (1 - fine) * detail * 1.10 * (1 - noise);- return clamp((noise - (.72 - coverage * .40) - erosion) * 9) * edge * height * support;- };- mesh.userData.quality = quality;- mesh.userData.steps = { view: tier.steps, light: tier.lightSteps };- const owned = snapshotResources(mesh);- owned.add(texture);- return attachDisposal(mesh, owned);-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/damp.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/damp.jsdeleted file mode 100644index a63a2962..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/damp.js+++ /dev/null@@ -1,608 +0,0 @@-/**- * Damp: what water leaves on ground and stone it never covers.- *- * `waterside` draws the waterline itself. These three are the metres- * AROUND it — the growth on the side that never dries, the darker- * ground that says water is close, and the polygons a bed cracks into- * once the water has gone. All three go through `patchStandard`, so- * lighting, shadows, fog and the depth chunks survive, and all three- * shade from world position and world normal, so none needs a UV and- * two objects sharing a scale share one climate.- *- * DIRECTION IS THE WHOLE EFFECT. Moss sprayed evenly is green paint;- * what reads as moss is that it is on ONE side of every rock, wall and- * trunk in the frame at once — so `north` (the world direction that- * stays shaded) and `up` are uniforms every material can share, and the- * sun-baked face is gated MULTIPLICATIVELY, where no amount of noise- * can put growth on it.- *- * None of them ASSIGNS a colour: each lands on a material that may- * already carry `patchTriplanar`, `patchSlopeSplat`, `patchMicroBreakup`- * or an `aging` mark, and whichever assigned last would erase the rest- * (measured: a splat over a triplanar did exactly that). Every one here- * multiplies or mixes with what it is handed.- *- * Surface finish follows the local material masks through late PBR hooks.- * Moss and dry silt are matte; damp ground and water-filled cracks are glossy.- * Uncovered substrate keeps its own roughness and metalness.- */--import * as THREE from 'three';-import {- patchStandard, frac, glslAxes, glslCurv,- glslTriNoise, seedVec3, toColor, unit, upVector,- worldBase,-} from './shader.js';--// All three patches read these, so they are declared once, in the base.-// astraDamp*, not a neighbour's spelling: patchStandard THROWS when two-// chained patches give one function name two different bodies.-const DAMP_HEAD = [- glslAxes('astraDampAxes'),- // Three world-plane projections blended by the normal: growth has to- // break up the same way on a boulder, a wall and a bridge soffit.- glslTriNoise('astraDampNoise', 29.3, 63.1, 97.7),- // NEGATIVE curvature is the concave crevice that holds water.- glslCurv('astraDampCurv'),- 'vec2 astraDampSite(vec2 c) {',- ' return c + vec2(astraHash21(c), astraHash21(c + 37.7));',- '}',- // Voronoi, measured to the nearest cell BORDER rather than by- // F2 - F1, which rounds every corner into a blob. Mud dries into- // POLYGONS with straight edges and sharp corners, and that is the- // whole difference between cracked mud and a dark noise.- 'vec2 astraDampCells(vec2 p) {',- ' vec2 ci = floor(p);',- ' vec2 cb = vec2(0.0), cr = vec2(0.0);',- ' float cd = 8.0;',- ' for (int y = -1; y <= 1; y++) {',- ' for (int x = -1; x <= 1; x++) {',- ' vec2 g = vec2(float(x), float(y));',- ' vec2 r = astraDampSite(ci + g) - p;',- ' float d = dot(r, r);',- ' if (d < cd) { cd = d; cb = g; cr = r; }',- ' }',- ' }',- ' cd = 8.0;',- ' for (int y = -1; y <= 1; y++) {',- ' for (int x = -1; x <= 1; x++) {',- ' vec2 g = cb + vec2(float(x), float(y));',- ' vec2 r = astraDampSite(ci + g) - p;',- ' vec2 e = r - cr;',- ' if (dot(e, e) > 1e-5) {',- ' cd = min(cd, dot(0.5 * (cr + r), normalize(e)));',- ' }',- ' }',- ' }',- ' return vec2(cd, astraHash21(ci + cb + 0.37));',- '}',-].join('\n');--// One base for all three, on the world varyings every library shares;-// the vertex locals are dm* because terrain_shade, waterside,-// surface_wear, aging and accumulation own astraWp, wsP, wrP, agP and acP.-const BASE = worldBase('damp:base', 'dmP', 'dmN', DAMP_HEAD);--// The constants differ from surface_wear's, aging's and accumulation's,-// or one seed would grow this library's moss along that library's-// blotches.-const seedOffset = (seed, salt) =>- seedVec3(seed + salt, 2.71, 6.83, 11.29, 40);--/**- * Read `north` as the HORIZONTAL direction that stays shaded.- *- * A compass direction has no component along `up`: one tipped toward- * the sky would grow moss on every ceiling in the scene. Dropping that- * component leaves a north parallel to up with no direction at all, so- * that degenerate case takes any perpendicular instead.- */-function northVector(value, up) {- const v = new THREE.Vector3(0, 0, -1);- if (value) v.fromArray(value.toArray ? value.toArray() : value);- if (!(v.lengthSq() > 1e-9)) v.set(0, 0, -1);- v.addScaledVector(up, -v.dot(up));- if (!(v.lengthSq() > 1e-6)) {- const axis = Math.abs(up.z) < 0.9- ? new THREE.Vector3(0, 0, 1) : new THREE.Vector3(1, 0, 0);- v.crossVectors(up, axis);- }- return v.normalize();-}----/**- * Move one colour in HSL, wrapping the hue so a shift may cross 0.- *- * Every tone below is DERIVED, never a second option: a caller sets one- * `color` per patch and the family is read off it, so a scene retuning- * its moss cannot end up with a cushion and a crust from two different- * plants — and so no tone can be lost by a caller who set only one.- */-function shifted(base, dh, ds, lightness) {- const hsl = { h: 0, s: 0, l: 0 };- base.getHSL(hsl);- return new THREE.Color().setHSL(- frac(hsl.h + dh), Math.min(1, hsl.s * ds), unit(lightness(hsl.l)));-}--/**- * The four tones of a moss cushion, and the two of a dried plate.- *- * ONE FLAT VALUE IS THE TELL. A cushion photographs as a hue RANGE, not- * a colour: blue-black in the depth between the clumps, the body green- * where it is thick, a yellow-green crown on the tips that see the sky,- * and — where the moss thins — crustose lichen, which is a different- * organism and a different colour, pale sage in its middle and ochre at- * its rim. Painted as one green with a brightness ramp over it (which- * is what this was), a metre of it reads as felt.- *- * Same for a bed that cracked: the plates did not all dry at the same- * hour, so the ones that went first are pale and grey and the ones that- * held their water are darker and warmer, and the CELL is what carries- * that difference — a per-plate brightness alone reads as dirt on a- * single chip of paint.- *- * THE SIGN OF EVERY HUE SHIFT IS THE PART THAT IS EASY TO GET WRONG- * (measured: the first pass had both moss shifts inverted and rendered- * an acid-green cushion with lavender crust). In HSL, hue RISES from- * yellow through yellow-green to green to blue-green — so the CROWN,- * which is new growth and yellower, shifts DOWN, and the depth, which- * is shaded and blue-green, shifts UP. Same on the bed: the plate that- * dried first is yellower (up from an orange-brown), the one that held- * its water is redder (down).- *- * And the spread is SMALL. These are two tones of one substance, not- * two substances: a swing wide enough to name reads as tiling.- */-const lichenTone = (base) =>- shifted(base, 0.020, 0.42, (l) => Math.min(0.50, l * 1.40 + 0.12));-const crustTone = (base) =>- shifted(base, -0.150, 0.62, (l) => Math.min(0.46, l * 1.45 + 0.10));-const mossDeep = (base) =>- shifted(base, 0.045, 1.22, (l) => Math.max(0.04, l * 0.50));-const mossCrown = (base) =>- shifted(base, -0.045, 0.86, (l) => Math.min(0.52, l * 1.75 + 0.05));-const siltPale = (base) =>- shifted(base, 0.018, 0.72, (l) => Math.min(0.72, l * 1.00 + 0.03));-const siltDamp = (base) =>- shifted(base, -0.018, 1.18, (l) => Math.max(0.04, l * 0.82));--/**- * Grow moss and lichen on the side that never dries — and only there.- *- * Moss sprayed evenly over a rock is green paint; what reads as moss is- * that every rock, wall foot and trunk in the frame carries it on the- * SAME side, thickest low down where water lingers and in the crevices- * that hold it, and none at all on the face the sun bakes. Getting that- * direction right is the whole effect, so `north` — the world direction- * that stays shaded — is a uniform every material in a scene can share.- *- * FOUR TERMS DECIDE WHERE IT HOLDS. The SHADE is the cosine against- * `north`. Level faces hold rain whatever they face, so the cosine- * against `up` adds. CREVICES are the surface's own signed curvature:- * the concave lee keeps what a convex edge sheds — and curvature reads- * ZERO across a hard, unwelded edge (`BoxGeometry`'s corners, anything- * flat-shaded), so there the two cosines carry it alone. And it thins- * with height above the plane through the world origin, where an asset- * rests: splash, ground damp and shade all live at the foot. That foot- * is world-absolute, so a scene standing its ground at y = 40 gets the- * thin end of the fade everywhere rather than a wrong answer.- *- * THE SUN GATE IS MULTIPLICATIVE. A face turned to the sun loses the- * growth however generous the field is, keeping it only in the crevices- * that shade themselves — which is what stops this becoming an even- * green wash the moment `amount` is raised. Lichen rides the same gate- * at a finer grain and without the foot fade, because it crusts the- * exposed shaded stone that moss cannot hold.- *- * It MIXES over the albedo it is handed (and shades the material just- * outside its edge, the only thickness a patch that cannot displace- * geometry has), so a triplanar, a splat or a stain underneath survives- * everywhere the moss is thin. Gloss here is per MATERIAL, not per pixel:- * moss is the mattest thing on any rock, so its factor goes UP.- *- * @param {THREE.Material} material A built-in material, patched in- * place — a shared material from `materials.js` grows moss on every- * mesh wearing it, so clone it first (and clone BEFORE patching).- * @param {object} [opts] `amount` how much of the shaded side is taken,- * 0..1 (default 0.45; 0.15 is a trace in the crevices, 0.9 is a- * cushion); `color` THREE.Color or hex, the moss (default a deep damp- * green — the cushion's deep and crown tones and BOTH lichen tones- * are derived from it, so one option moves the whole family); `up`- * THREE.Vector3 or [x, y, z], the scene's up (default +Y); `north`- * THREE.Vector3 or- * [x, y, z], the world direction that stays SHADED, horizontal- * (default -Z); `seed` moves the growth (default 1).- * @returns {THREE.Material} The same material, with its uniforms live- * on `material.userData.uniforms`, so `uMossNorth` can swing with the- * sun a scene was lit for.- */-export function patchMoss(material, opts = {}) {- const amount = opts.amount === undefined ? 0.45 : unit(opts.amount);- const seed = opts.seed === undefined ? 1 : opts.seed;- const up = upVector(opts.up);- const color = toColor(opts.color, 0x40592a);- // Moss is matte and it takes the gloss over only as far as it takes- // the surface over.-- patchStandard(material, BASE);- return patchStandard(material, {- name: 'damp:moss',- uniforms: {- uMossAmt: { value: amount },- uMossColor: { value: color },- uMossDeep: { value: mossDeep(color) },- uMossCrown: { value: mossCrown(color) },- uMossLichen: { value: lichenTone(color) },- uMossCrust: { value: crustTone(color) },- uMossUp: { value: up },- uMossNorth: { value: northVector(opts.north, up) },- uMossSeed: { value: seedOffset(seed, 0.4) },- },- fragmentHead: [- 'uniform float uMossAmt;',- 'uniform vec3 uMossColor;',- 'uniform vec3 uMossDeep;',- 'uniform vec3 uMossCrown;',- 'uniform vec3 uMossLichen;',- 'uniform vec3 uMossCrust;',- 'uniform vec3 uMossUp;',- 'uniform vec3 uMossNorth;',- 'uniform vec3 uMossSeed;',- ].join('\n'),- roughnessBody: 'roughnessFactor = mix(roughnessFactor, 0.97, clamp((msK + msLiK) * msOn, 0.0, 1.0));',- metalnessBody: 'metalnessFactor *= 1.0 - clamp((msK + msLiK) * msOn, 0.0, 1.0);',- normalBody: 'normal = astraBump(-vViewPosition, normal, '- + 'msOn * (msK * (0.001 + 0.003 * msG) + msLiK * 0.0008)'- + ' * (1.0 - smoothstep(0.03, 0.10, length(fwidth(vAstraWorld)))));',- fragmentBody: [- ' vec3 msN = normalize(vAstraWorldN);',- ' vec3 msUp = normalize(uMossUp);',- ' vec3 msNo = normalize(uMossNorth);',- // The shaded side: full on the face that looks north, gone on the- // one that looks at the sun. This is the whole effect.- ' float msFace = dot(msN, msNo);',- ' float msShade = smoothstep(-0.20, 0.55, msFace);',- ' float msLie = smoothstep(0.05, 0.70, dot(msN, msUp));',- // Crevices hold what an edge sheds. ~0.35 m features, the size of- // the hollows a cushion of moss actually fills.- ' float msCv = astraDampCurv(msN, vAstraWorld);',- ' float msLee = smoothstep(1.2, 6.0, -msCv);',- ' float msShed = smoothstep(1.8, 7.5, msCv);',- // Water lingers at the FOOT — splash, ground damp, and the shade- // of whatever is standing there — measured along `up` from the- // plane through the world origin, where an asset rests.- ' float msFoot = 1.0 - smoothstep(0.30, 2.60,',- ' dot(vAstraWorld, msUp));',- ' float msHold = clamp(msShade * 0.85 + msLie * 0.30',- ' + msLee * 0.70 - msShed * 0.55, 0.0, 1.6);',- ' msHold *= mix(0.30, 1.0, msFoot);',- // MULTIPLICATIVE, so no field can put moss on a baked face: it- // survives there only in the crevices that shade themselves.- ' float msSun = smoothstep(0.05, 0.75, -msFace)',- ' * (1.0 - msLee * 0.65);',- ' float msDry = 1.0 - clamp(msSun, 0.0, 1.0);',- ' msHold *= msDry;',- ' vec3 msW = astraDampAxes(msN);',- ' vec3 msP = vAstraWorld * 3.2 + uMossSeed;',- // Three octaves, not one: a cushion has clumps inside it and a- // torn edge, and one octave is an airbrush.- ' float msG = astraDampNoise(msP, msW) * 0.55',- ' + astraDampNoise(msP * 2.7, msW) * 0.28',- ' + astraDampNoise(msP * 7.9, msW) * 0.17;',- ' float msD = msHold * (0.42 + 1.10 * msG);',- // One threshold, torn by its own screen gradient: a clean edge is- // paint, and moss has none anywhere.- ' float msT = mix(1.05, 0.26, uMossAmt);',- ' float msAA = clamp(fwidth(msD), 0.0, 0.35);',- ' float msK = smoothstep(msT - 0.05 - msAA, msT + 0.14 + msAA, msD);',- // Lichen: the same direction, a finer grain, and no foot fade —- // it crusts the shaded stone above where moss can hold. TWO- // octaves, because one gives round blobs at one size, which read- // as mould spots rather than as a crust with a torn rim.- ' float msLi = astraDampNoise(msP * 7.7 + 5.3, msW) * 0.68',- ' + astraDampNoise(msP * 19.0 + 11.7, msW) * 0.32;',- ' float msLiK = smoothstep(0.52, 0.78, msLi) * msShade * msDry',- ' * (1.0 - msK) * max(msLie, 0.35);',- // The material just OUTSIDE the edge stays damp under the growth.- ' float msLip = (1.0 - msK)',- // Keep the edge shadow inside positive growth. A fixed subtraction- // made this threshold negative at high coverage, darkening dry,- // sun-facing walls even though both moss and lichen were absent.- ' * smoothstep(msT * 0.40, msT - 0.02, msD);',- // `amount` 0 is OFF, which a threshold alone cannot say: a deep- // enough crevice would clear any threshold. Declared here with- // the rest of the MASK, so everything above this line is scalar- // maths a probe can lift out and evaluate against a swept normal.- ' float msOn = smoothstep(0.0, 0.05, uMossAmt);',- ' msLip *= msOn;',- ' diffuseColor.rgb *= 1.0 - 0.20 * msLip;',- // THE CUSHION IS A HUE RANGE. Deep in the shade between the- // clumps, body green where it is thick, a yellow-green crown on- // the tips that see the sky — the field that tore the edge is the- // same field that says which of the three a pixel is.- ' vec3 msCol = mix(uMossDeep, uMossColor,',- ' smoothstep(0.14, 0.60, msG));',- ' msCol = mix(msCol, uMossCrown,',- ' 0.80 * smoothstep(0.58, 0.98,',- ' msG * (0.78 + 0.44 * msLi)));',- // Warm where the sun grazes it, cool where only the sky reaches —- // projected on the north/up plane, so a boulder and a wall break- // the same way and nothing needs a UV. Never on world Y.- ' vec2 msQ = vec2(dot(msP, msNo), dot(msP, msUp));',- ' msCol = astraHueBreak(msCol, msQ, 0.55, 0.20);',- // The crust is two colours too: pale sage where it is thick,- // ochre where it is thinning back to the stone.- ' vec3 msCr = mix(uMossCrust, uMossLichen,',- ' smoothstep(0.50, 0.84, msLi));',- // `amount` moved the THRESHOLD, so where the mask is full the- // growth is nearly opaque; multiplying by it again is a wash.- ' diffuseColor.rgb = mix(diffuseColor.rgb, msCol,',- ' clamp(msK * msOn',- ' * mix(0.60, 1.0, uMossAmt), 0.0, 1.0));',- ' diffuseColor.rgb = mix(diffuseColor.rgb, msCr,',- ' clamp(msLiK * msOn',- ' * mix(0.30, 0.62, uMossAmt),',- ' 0.0, 1.0));',- ].join('\n'),- });-}--/**- * Darken and gloss the ground as it approaches water, out to `reach`.- *- * Ground within a few metres of a shoreline is visibly darker and- * glossier than the ground beyond it — the pores are full — and without- * that apron a lake sits on the land like a mirror dropped on a lawn.- * The edge is irregular, because the damp follows where the ground- * dips, never a contour.- *- * WHERE IT MEETS `patchShoreWet`. That patch owns the WATERLINE: the- * decimetres either side of `level`, fully wet below it and fading out- * over a `band` of ~0.25 m above. This owns the METRES beyond that, and- * the two are meant to be worn together — set `reach` to several metres- * and the apron hands over to the tide mark, which is darker again.- * They compose MULTIPLICATIVELY (both scale the albedo they are handed,- * neither assigns), so the overlap deepens rather than fighting; keep- * `strength` under `patchShoreWet`'s `darken` or the apron reads as the- * waterline and the real one disappears into it.- *- * REACH IS A HEIGHT, NOT A PLAN DISTANCE. A fragment sees its own- * position and nothing else — it cannot find where the shoreline runs —- * so the measure is world Y above `waterY`, exactly as- * `patchShallowWater` measures depth. A water surface is level by- * definition, so world Y is right here in a way it never is for a- * deposit, and it needs a bank that RISES: on ground climbing 1 m over- * 4 m, `reach: 1` darkens the first 4 m of it. Flat ground at the water's- * own level is damp all over, which is what a salt flat looks like.- *- * It MULTIPLIES the albedo it is handed and deepens its colour, so a- * triplanar, a splat or a wear pattern underneath comes through the- * apron rather than being replaced by it. The same local moisture mask- * lowers roughness; uncovered substrate retains its authored finish.- *- * @param {THREE.Material} material A built-in material, patched in- * place — a shared material damps every mesh wearing it.- * @param {object} [opts] `waterY` world Y of the water surface (default- * 0); `reach` metres of HEIGHT above it the damp climbs, zero beyond- * (default 1.5); `strength` how dark it goes at the water's edge,- * 0..1 (default 0.45); `seed` moves the irregular edge (default 1).- * @returns {THREE.Material} The same material, with its uniforms live- * on `material.userData.uniforms`, so `uMoistY` can follow a tide.- */-export function patchMoisture(material, opts = {}) {- const waterY = opts.waterY === undefined ? 0 : opts.waterY;- const reach = opts.reach === undefined ? 1.5 : Math.max(1e-3, opts.reach);- const strength = opts.strength === undefined ? 0.45 : unit(opts.strength);- const seed = opts.seed === undefined ? 1 : opts.seed;- // Damp ground is the glossiest thing on a shore that is not water —- // but rough ground retains a broad wet-soil highlight. Already polished- // substrate must never become rougher when the moisture mask increases.-- patchStandard(material, BASE);- return patchStandard(material, {- name: 'damp:moisture',- uniforms: {- uMoistY: { value: waterY },- uMoistReach: { value: reach },- uMoistAmt: { value: strength },- uMoistSeed: { value: seedOffset(seed, 2.9) },- },- fragmentHead: [- 'uniform float uMoistY;',- 'uniform float uMoistReach;',- 'uniform float uMoistAmt;',- 'uniform vec3 uMoistSeed;',- ].join('\n'),- roughnessBody: 'roughnessFactor = mix(roughnessFactor, min(roughnessFactor, max(0.30, roughnessFactor * 0.68)), moA);',- fragmentBody: [- ' float moH = vAstraWorld.y - uMoistY;',- ' float moT = clamp(moH / uMoistReach, 0.0, 1.0);',- // The edge wanders: a level contour is a ruled line no bank has.- ' float moN = astraFbm2(vAstraWorld.xz * 0.55',- ' + uMoistSeed.xz, 3) - 0.44;',- // The wander dies at BOTH ends of the ramp — the waterline is- // saturated whatever the noise says and `reach` is the reach — so- // it can only ever move the edge inside the apron.- ' float moW = clamp(moT + moN * 3.4 * moT * (1.0 - moT), 0.0, 1.0);',- // A capillary margin has an EDGE, not a gradient across the whole- // apron: the ramp is steep and the wander is what shapes it.- ' float moK = 1.0 - smoothstep(0.10, 0.80, moW);',- // Mottled, or the apron is a painted band; the field is centred- // so it cannot push the damp past the ramp either.- ' float moB = astraFbm2(vAstraWorld.xz * 1.9 + uMoistSeed.zx, 3);',- ' float moA = clamp(moK * uMoistAmt * (0.70 + 0.66 * moB),',- ' 0.0, 1.0);',- // THE CAPILLARY RIM. Water climbing a bank carries the ground's- // own dust with it and leaves it as a pale mineral bloom at the- // exact line it stops — which is the only thing that gives the- // apron an EDGE from twenty metres, where the darkening alone is- // a gradient with nothing to read. It rides the same wander, so- // the rim follows the damp rather than ruling its own contour,- // and BOTH ends are gated so nothing survives at or past `reach`.- ' float moR = smoothstep(0.55, 0.85, moW)',- ' * (1.0 - smoothstep(0.85, 1.00, moW))',- ' * (1.0 - smoothstep(0.80, 1.00, moT))',- ' * uMoistAmt * (0.55 + 0.55 * moB);',- // A third of a code value of screen dither: the ramp runs over- // metres of near-flat ground and there is no post chain here to- // break the steps for us. Gated by the apron's own strength, so- // a surface this patch does not reach is left untouched.- ' float moD = (astraHash21(gl_FragCoord.xy) - 0.5) * 0.008',- ' * max(moA, moR);',- // Wet ground is darker AND deeper in colour: pushing away from- // its own luminance is the saturation half of that. One write,- // folding in what it was handed — a patch that ASSIGNED here- // would erase the triplanar it lands on, and the bloom is that- // same albedo lifted and warmed rather than a colour of its own.- ' float moL = dot(diffuseColor.rgb, vec3(0.2126, 0.7152, 0.0722));',- ' diffuseColor.rgb = clamp(',- ' mix(mix(vec3(moL), diffuseColor.rgb, 1.0 + 0.45 * moA)',- ' * (1.0 - 0.55 * moA),',- ' vec3(moL) * vec3(1.62, 1.54, 1.40), 0.42 * moR)',- ' + moD, 0.0, 1.0);',- ].join('\n'),- });-}--/**- * Crack a dried bed into curling polygons — cracks dark, plates pale.- *- * A lakebed, a paddy field in drought or the last puddle in a yard all- * dry the same way: the surface shrinks, tears into Voronoi polygons a- * hand's width across, and every plate curls up at its edges. A noise- * field cannot fake it, because what the eye reads is the STRAIGHT- * edges and sharp corners of the cells — so this measures the distance- * to the nearest cell BORDER (not F2 - F1, which rounds every corner- * off) and thresholds that into a crack.- *- * THE CURL IS THE SECOND HALF. A patch cannot displace geometry — a- * vertex displacement would tear a hard-edged bed open at its rim — so- * the lifted lip is a bright band just inside each crack and the crack- * itself is a dark line, which is exactly what a curled plate does to- * the light. `depth` widens the crack, darkens it and lifts the lip- * together, because a bed that dried harder did all three.- *- * `wet` fills the cracks with water instead of shadow: the network goes- * dark and cold rather than dusty, the plates keep their pale dry tops,- * and the material's gloss goes the other way — a drying bed is matte,- * a bed whose cracks still hold water is not.- *- * THE PLATES ARE READ FROM WORLD XZ, because a bed is level by- * definition (unlike a deposit, which needs the scene's own `up`), and- * the pattern thins from about 28 degrees off level and is gone by 57,- * where that projection would smear into stripes. The cell field is- * warped by a slow noise first, or every plate is the same size — and- * the same warp opens the cracks in one patch and leaves hairlines in- * the next, because a bed does not dry evenly.- *- * It MIXES over the albedo it is handed, weighted by how level the- * surface is, so a triplanar or a splat underneath still carries the- * bank while the flat of the bed cracks.- *- * @param {THREE.Material} material A built-in material, patched in- * place — a shared material cracks every mesh wearing it.- * @param {object} [opts] `scale` metres across one plate (default 0.35- * — 0.1 is a sun-baked crust, 1.0 a lakebed); `depth` how far the- * drying has gone, 0..1: crack width, darkness and curl together- * (default 0.5); `color` THREE.Color or hex, the dry plate (default a- * pale silt); `wet` 0..1 how much water is still in the cracks- * (default 0); `seed` moves the cells (default 1).- * @returns {THREE.Material} The same material, with its uniforms live- * on `material.userData.uniforms`, so `uMudWet` can dry over a shot.- */-export function patchCrackedMud(material, opts = {}) {- const scale = opts.scale === undefined ? 0.35 : Math.max(1e-3, opts.scale);- const depth = opts.depth === undefined ? 0.5 : unit(opts.depth);- const wet = opts.wet === undefined ? 0 : unit(opts.wet);- const seed = opts.seed === undefined ? 1 : opts.seed;- const mudColor = toColor(opts.color, 0x9c8a71);- // Dry silt is matte; wet cracks carry narrower highlights. Both finishes- // use the existing mud mask instead of changing the entire substrate.-- patchStandard(material, BASE);- return patchStandard(material, {- name: 'damp:mud',- uniforms: {- uMudScale: { value: scale },- uMudDepth: { value: depth },- uMudColor: { value: mudColor },- uMudPale: { value: siltPale(mudColor) },- uMudDamp: { value: siltDamp(mudColor) },- uMudWet: { value: wet },- uMudSeed: { value: seedOffset(seed, 5.1) },- },- fragmentHead: [- 'uniform float uMudScale;',- 'uniform float uMudDepth;',- 'uniform vec3 uMudColor;',- 'uniform vec3 uMudPale;',- 'uniform vec3 uMudDamp;',- 'uniform float uMudWet;',- 'uniform vec3 uMudSeed;',- ].join('\n'),- roughnessBody: 'roughnessFactor = mix(roughnessFactor, mix(0.95, 0.28, uMudWet * (0.32 + 0.68 * mdCrk)), mdAmt);',- metalnessBody: 'metalnessFactor *= 1.0 - mdAmt;',- normalBody: 'normal = astraBump(-vViewPosition, normal, '- + 'mdAmt * uMudDepth * uMudScale * (mdLip * 0.025 - mdCrk * 0.010)'- + ' * (1.0 - smoothstep(0.025, 0.12, length(fwidth(vAstraWorld)))));',- fragmentBody: [- ' vec3 mdN = normalize(vAstraWorldN);',- // A bed is level: the cells are read from world XZ, and a face- // past ~45 degrees would smear that projection into stripes.- ' float mdLie = smoothstep(0.55, 0.88, mdN.y);',- ' vec2 mdP = vAstraWorld.xz / uMudScale + uMudSeed.xz;',- // Warped first, or every plate is the same size and the network- // reads as a tiling rather than as a surface that tore.- ' vec2 mdWp = vec2(astraFbm2(mdP * 0.31 + 7.1, 3),',- ' astraFbm2(mdP * 0.31 + 23.9, 3)) - 0.44;',- ' vec2 mdC = astraDampCells(mdP + mdWp * 1.10);',- // Crack width in CELLS, so one `depth` widens, darkens and lifts;- // water standing in a crack spreads it wider still.- ' float mdW = mix(0.004, 0.022, uMudDepth)',- ' * mix(1.0, 1.6, uMudWet)',- // A bed does not dry evenly: the same warp opens the cracks in- // one patch of it and leaves hairlines in the next.- ' * (1.0 + mdWp.x * 1.5);',- ' float mdAA = clamp(fwidth(mdC.x), 0.0, 0.25);',- ' float mdCrk = 1.0 - smoothstep(mdW, mdW * 2.6 + mdAA, mdC.x);',- // The lip: a plate curls UP at its edge, so the band just inside- // each crack catches the light the crack itself loses — and a- // soaked lip has nothing to catch it with.- ' float mdLip = smoothstep(mdW * 2.0, mdW * 5.5, mdC.x)',- ' * (1.0 - smoothstep(mdW * 6.0, mdW * 15.0, mdC.x))',- ' * (1.0 - 0.70 * uMudWet);',- // PER-PLATE TONE, AND IT IS A HUE. The plates did not all dry at- // the same hour: the ones that went first are pale and grey, the- // ones that held their water are darker and warmer, and the CELL- // hash is what makes them pieces rather than a pattern. A- // brightness ramp alone (which is what this was) reads as dirt on- // one flat chip of paint.- ' float mdG = astraFbm2(mdP * 3.3 + uMudSeed.zx, 3);',- ' vec3 mdPl = mix(uMudDamp, uMudPale,',- ' clamp(mdC.y * 1.16 - 0.08, 0.0, 1.0));',- ' mdPl *= (0.92 + 0.18 * mdG) * mix(1.0, 0.78, uMudWet);',- // Silt grain INSIDE the plate, at a finer scale than the plates:- // warm where the sun bakes it, cool in the film of shade a curl- // throws over itself.- ' mdPl = astraHueBreak(mdPl, mdP * 1.7, 1.0, 0.18);',- // A crack is a groove lit only by the sky, so its shadow is COOL- // — the one place on a sun-baked bed that is not warm.- ' vec3 mdDk = uMudColor * mix(0.34, 0.16, uMudDepth)',- ' * vec3(0.86, 0.95, 1.16);',- // Water in the crack, not shadow: far darker and cold, because a- // filled crack is a window into it rather than a shaded groove.- ' vec3 mdWc = uMudColor * 0.09 * vec3(0.75, 0.95, 1.30);',- ' vec3 mdCol = mix(mdPl, mix(mdDk, mdWc, uMudWet), mdCrk);',- // The lip catches the SUN, so it is warmer as well as brighter —- // a lip that only brightens reads as a highlight on plastic.- ' mdCol = mix(mdCol, mdCol * vec3(1.06, 1.02, 0.97),',- ' clamp(mdLip * 1.30, 0.0, 1.0));',- ' mdCol *= 1.0 + mdLip * mix(0.04, 0.12, uMudDepth);',- ' float mdAmt = clamp(mdLie * mix(0.55, 1.0, uMudDepth), 0.0, 1.0);',- ' diffuseColor.rgb = mix(diffuseColor.rgb, mdCol, mdAmt);',- ].join('\n'),- });-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/dapple.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/dapple.jsdeleted file mode 100644index 3a1ecd15..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/dapple.js+++ /dev/null@@ -1,357 +0,0 @@-/**- * The moving light patches a canopy throws on everything under it.- *- * After aerial perspective this is the strongest single cue that a- * frame is OUTDOORS and under something living: a forest floor, a- * verandah under a vine, a street under plane trees. Without it the- * ground under a tree is a flat tone with a shadow blob on it.- *- * It goes on the material of the surface BEING LIT, not on the canopy,- * because the pattern belongs to the- * leaves overhead, which the floor knows nothing about. So the caller- * states where the canopy is and how dense it is.- *- * The gaps SLIDE ALONG THE SUN, not down the world axes: a gap in the- * canopy projects along the sun direction, so as the pattern drifts in- * the wind the patch on the ground travels the way the shadow of that- * gap would. Projecting straight down instead is the tell that turns- * dapple into a moving texture.- */--import * as THREE from 'three';-import { patchStandard, composeRoughness, sunVector } from './shader.js';--// The day rig's sun (azimuth 35, elevation 48), matching water.js,-// so a surface that was not told where the sun is agrees.-const DAY_SUN = sunVector(35, 48);--// Half the sun's angular diameter, in radians (0.53 deg across). This is-// the ONE number that sets how soft a sunfleck's edge is: the penumbra a-// canopy `h` metres up throws is h * this, ~6 cm under a 7 m crown and-// ~2 cm under a low vine. Measured against it, the edge of a 0.7 m fleck-// is a tenth of the fleck wide — nearly hard. A smoothstep spread over-// the noise's whole swing instead (what this file did until 2026-09-01)-// blurs every fleck into the "cloudy" look the notes below warn about.-const SUN_HALF_ANGLE = 0.00465;--// How much the fbm field's value moves across one unit of its own domain-// — measured over astraFbm2 at 3 octaves. Converting a distance (the-// penumbra, a pixel footprint) into the value-space width a smoothstep-// wants is a multiply by this and nothing more.-const FIELD_SLOPE = 0.26;--/** Warm sun through a gap; the low-sun end is what a fleck goes at dusk. */-const FLECK_HIGH = new THREE.Color(0xffeec0);-const FLECK_LOW = new THREE.Color(0xffc287);--/**- * Dappled canopy light on the surface under it.- *- * The pattern is the union of two drifting fields at different scales,- * thresholded: leaf shadow is not a smooth wobble but a scatter of- * bright holes with hard-ish edges, and one octave of noise gives the- * cloudy blur that reads as fog on the floor instead. It lifts the- * light rather than the albedo — a sunfleck on a shaded floor is often- * the only direct light there is, and lifting albedo alone would cap it- * at the ambient the floor already receives.- *- * Three things make a fleck read as SUNLIGHT rather than as a pale- * texture, and all three are geometry the caller already stated:- * - its edge is a penumbra (`SUN_HALF_ANGLE * height`), not a fade- * across the noise's whole swing — and it widens again to whatever- * the pixel footprint is, so a floor running to the horizon greys- * out instead of crawling;- * - it is STRETCHED along the sun's ground track by 1/sin(elevation),- * the same way the round gap's shadow is: at a 38 deg sun a fleck is- * 1.6x longer than it is wide, and it is that elongation, not the- * brightness, that says where the sun is;- * - its rim is greener than its middle. Light that clipped a leaf on- * the way through carries the leaf's transmission, so a fleck runs- * warm-white in the core to yellow-green at the edge — a single flat- * colour is the tell of a decal.- *- * @param {THREE.Material} material Material of the LIT surface, patched- * in place. Needs a lit material with an `emissive` (a Standard or- * Physical); a Basic has none and a raw ShaderMaterial ignores this.- * @param {object} [opts] `sunDir` (THREE.Vector3) direction TOWARD the- * sun, the same vector the sun light sits on (default the day rig's);- * `height` metres from this surface up to the canopy (default 6) —- * what sets how far the pattern slides as it drifts AND how soft the- * flecks are, so a low vine and a high crown neither move nor blur- * alike; `scale` metres across one leaf gap (default 0.7); `density`- * 0..1 how much canopy there is (default 0.5) — 0 is open sky and- * lights everything, 1 is closed and lets almost nothing through;- * `strength` how bright a fleck goes (default 0.55); `speed` metres- * per second the canopy drifts (default 0.35); `color` (THREE.Color- * or hex) the light's own colour — the default is read off `sunDir`,- * warm-white overhead and orange near the horizon, so a dusk scene- * does not get noon flecks; `leaf` (THREE.Color or hex) what light- * through the leaf itself carries, the fleck's rim colour (default a- * yellow-green); `seed`.- * @returns {THREE.Material} The same material.- */-export function patchDappledLight(material, opts = {}) {- const sun = (opts.sunDir ? opts.sunDir.clone() : DAY_SUN.clone())- .normalize();- const height = opts.height === undefined ? 6 : opts.height;- const scale = Math.max(0.05, opts.scale === undefined ? 0.7 : opts.scale);- const density = Math.min(1, Math.max(0,- opts.density === undefined ? 0.5 : opts.density));- const strength = opts.strength === undefined ? 0.55 : opts.strength;- const speed = opts.speed === undefined ? 0.35 : opts.speed;- // A fleck is a picture of THE SUN, so its colour is the sun's: the- // caller who set the rig low has already said the light is orange.- const warm = Math.min(1, Math.max(0, (sun.y - 0.05) / 0.45));- const color = opts.color === undefined- ? FLECK_LOW.clone().lerp(FLECK_HIGH, warm * warm * (3 - 2 * warm))- : new THREE.Color(opts.color);- const leaf = new THREE.Color(opts.leaf === undefined ? 0x9ec06a : opts.leaf);- const seed = opts.seed === undefined ? 1 : opts.seed;-- if (!material.emissive) {- console.warn('patchDappledLight: needs a lit material (Standard or '- + 'Physical) — a sunfleck is light, not paint.');- }- // A canopy makes the floor under it damp and matte more often than- // not; a whole factor would fight a wet patch, so this is gentle.- composeRoughness(material, 'dapple', 1 + 0.06 * density);-- // A fleck is the light that MISSED the canopy, so the albedo- // `patchCanopyShade` took away (its stand-in for the shadow three- // will not cast) must not be taken away from the fleck as well —- // that is what made a fleck in deep shade dimmer than one at the- // edge of the crown, which is backwards. The shade runs first, so- // its average cut is known here; give it back, capped, and only- // when the pair is really in use.- const can = material.userData.astraCanopy;- const comp = can- ? Math.min(1.7, 1 / Math.max(0.4,- 1 - can.depth * can.density * (0.72 + 0.28 * can.density)))- : 1;-- return patchStandard(material, {- name: 'dapple',- uniforms: {- uDapSun: { value: sun },- uDapH: { value: height },- uDapScale: { value: scale },- uDapDens: { value: density },- uDapAmt: { value: strength * comp },- uDapSpeed: { value: speed },- uDapColor: { value: color },- uDapLeaf: { value: leaf },- uDapSeed: { value: seed },- },- vertexHead: 'varying vec3 vAstraDapW;\nvarying vec3 vAstraDapN;',- vertexBody: [- '#ifdef USE_INSTANCING',- ' vAstraDapW = (modelMatrix * instanceMatrix'- + ' * vec4(transformed, 1.0)).xyz;',- ' vAstraDapN = astraNormalTransform(mat3(modelMatrix) * mat3(instanceMatrix), normal);',- '#else',- ' vAstraDapW = (modelMatrix * vec4(transformed, 1.0)).xyz;',- ' vAstraDapN = astraNormalTransform(mat3(modelMatrix), normal);',- '#endif',- ].join('\n'),- fragmentHead: [- 'varying vec3 vAstraDapW;',- 'varying vec3 vAstraDapN;',- 'uniform float uTime;',- 'uniform vec3 uDapSun;',- 'uniform float uDapH;',- 'uniform float uDapScale;',- 'uniform float uDapDens;',- 'uniform float uDapAmt;',- 'uniform float uDapSpeed;',- 'uniform vec3 uDapColor;',- 'uniform vec3 uDapLeaf;',- 'uniform float uDapSeed;',- // Gaps, not clouds: fbm thresholded well above its mean leaves- // scattered holes with edges. Two scales union because a canopy- // has both leaf gaps and branch gaps — the leaf field is the- // common one and the branch field the rare wide hole, so its- // threshold sits ABOVE the other's; equal thresholds (what this- // did before) let the coarse field cover the floor and every- // fleck came out a metre-wide puddle.- //- // `w` is the edge width in VALUE space — the penumbra and the- // pixel, converted by the field's own slope; the branch field is- // 2.7x coarser, so the same distance is a smaller fraction of- // its swing.- //- // Returned as (gap, core): the core is the same gap eroded by- // one threshold step, i.e. the part of it the whole sun reaches.- // Taking the core off the gap VALUE instead would make the rim- // a couple of pixels wide once the edge is properly hard, and- // the leaf-green it carries would never be seen.- 'vec2 astraDapGaps(vec2 p, float d, float w) {',- ' float a = astraFbm2(p, 3);',- ' float b = astraFbm2(p * 0.37 + 11.3, 2);',- // A canopy is not evenly thin: gaps CROWD where the crown is- // sparse and give out under a thick one. Modulating the- // threshold at crown scale is what turns an even scatter —- // which reads as camouflage — into flecks that belong to a- // tree. This field drifts with the rest, so a thin patch of- // canopy travels over the floor as one.- ' float c = astraFbm2(p * 0.13 + 5.1, 2);',- ' float t = mix(0.28, 0.76, d) + (c - 0.375) * 0.45;',- ' float wb = 0.05 + w * 0.5;',- ' float ga = smoothstep(t - w, t + w, a);',- ' float gb = smoothstep(t + 0.10 - wb, t + 0.10 + wb, b);',- ' float ca = smoothstep(t + 0.035 - w, t + 0.035 + w, a);',- ' float cb = smoothstep(t + 0.145 - wb, t + 0.145 + wb, b);',- ' return vec2(max(ga, gb * 0.9), max(ca, cb * 0.9));',- '}',- ].join('\n'),- fragmentBody: [- // Where this fragment's sunbeam CROSSED the canopy. Sliding the- // sample point along the sun (not straight up) is what makes a- // fleck travel the way the gap's shadow would.- ' vec3 dpS = normalize(uDapSun);',- ' float dpUp = max(dpS.y, 0.15);',- ' float dpHeight = max(0.0, uDapH - vAstraDapW.y);',- ' vec2 dpAt = vAstraDapW.xz + dpS.xz * (dpHeight / dpUp);',- ' vec2 dpP = dpAt / uDapScale + uDapSeed * 17.0;',- // The canopy drifts across the wind; the floor sees that drift- // magnified by how far overhead it is.- ' dpP += vec2(1.0, 0.35) * (uTime * uDapSpeed / uDapScale);',- // The gap's shadow is an ellipse: a slanted beam lands long. The- // sample is COMPRESSED along the sun's ground track, which is- // what stretches the pattern out along it in the world.- ' vec2 dpAx = dpS.xz;',- ' float dpAxL = length(dpAx);',- ' if (dpAxL > 1e-4) {',- ' dpAx /= dpAxL;',- ' float dpEl = clamp(1.0 / dpUp, 1.0, 3.0);',- ' dpP += dpAx * (dot(dpP, dpAx) * (1.0 / dpEl - 1.0));',- ' }',- // Edge = the sun's penumbra at this height, never finer than the- // pixel: the second term is what keeps a receding floor from- // boiling into noise.- ' float dpPen = ' + SUN_HALF_ANGLE.toFixed(5) + ' * dpHeight / uDapScale;',- ' float dpAA = fwidth(dpP.x) + fwidth(dpP.y);',- ' float dpW = clamp((dpPen + dpAA) * ' + FIELD_SLOPE.toFixed(2) + ','- + ' 0.012, 0.40);',- ' vec2 dpGC = astraDapGaps(dpP, uDapDens, dpW);',- ' float dpG = dpGC.x;',- // Only what faces the sun catches a fleck, and a fleck on a- // surface already in full sun adds nothing anyone can see. The- // knee keeps a grazing face from wearing a hard lambert line.- ' float dpF = max(dot(normalize(vAstraDapN), dpS), 0.0);',- ' dpF *= smoothstep(0.0, 0.30, dpF);',- // Rim green, core sun, and no two flecks quite the same colour.- ' float dpCore = dpGC.y;',- ' vec3 dpTint = mix(uDapLeaf, uDapColor, dpCore);',- ' dpTint = astraHueBreak(dpTint, dpP, 0.23, 0.34);',- // The core of a fleck is the whole sun; its rim is a sliver of- // one. That ratio is what gives a bloom pass something to find.- ' float dpBeam = dpG * (1.0 + 2.2 * dpCore);',- ' float dpVisibility = 1.0;',- ' #if defined(USE_SHADOWMAP) && NUM_DIR_LIGHT_SHADOWS > 0',- ' dpVisibility = getShadow(directionalShadowMap[0], directionalLightShadows[0].shadowMapSize,',- ' directionalLightShadows[0].shadowIntensity, directionalLightShadows[0].shadowBias,',- ' directionalLightShadows[0].shadowRadius, vDirectionalShadowCoord[0]);',- ' #endif',- ' #if NUM_DIR_LIGHTS > 0',- ' totalEmissiveRadiance += dpTint * (uDapAmt * dpBeam * dpF * dpVisibility',- ' * diffuseColor.rgb) * directionalLights[0].color / 3.14159265;',- ' #endif',- ].join('\n'),- });-}--/**- * The shade a canopy casts, as a floor-level tint rather than a shadow.- *- * Three's shadow maps do not reach an instanced crown of billboards,- * and a forest floor lit exactly like open ground reads as a lawn with- * trees standing on it. This darkens and cools the surface by how much- * canopy is overhead, so `patchDappledLight`'s flecks have something- * to be flecks ON. Apply it before the dapple; both compose.- *- * `density` is COVERAGE: at 0.5 about half the floor is under crown.- * Until 2026-09-01 the depth of the shade was multiplied by the density- * as well as thresholded by it, so the default asked for half a canopy- * and got a 9% darkening — measured on our renderer, a 28 m floor came- * back with a 0.07 luminance range, i.e. a flat card. The shade is the- * expensive half of this file: flecks are only bright relative to it.- *- * @param {THREE.Material} material Material of the shaded surface.- * @param {object} [opts] `density` 0..1 (default 0.5); `scale` metres- * across one crown (default 6) — this is the CROWN scale, an order- * above the leaf-gap scale, so the two never beat together; `cool`- * (THREE.Color or hex) what the shade tints toward, default the green- * a canopy bounces down; `depth` 0..1 how dark the deepest shade goes- * (default 0.80 — never to black: what light a forest floor has is- * sky and bounce, and crushing it is the other way to lose the- * effect); `seed`.- * @returns {THREE.Material} The same material.- */-export function patchCanopyShade(material, opts = {}) {- const density = Math.min(1, Math.max(0,- opts.density === undefined ? 0.5 : opts.density));- const scale = Math.max(0.5, opts.scale === undefined ? 6 : opts.scale);- const cool = new THREE.Color(- opts.cool === undefined ? 0x5d6b48 : opts.cool);- const depth = Math.min(1, Math.max(0,- opts.depth === undefined ? 0.80 : opts.depth));- const seed = opts.seed === undefined ? 1 : opts.seed;- // What `patchDappledLight` gives back to its flecks; see there.- material.userData.astraCanopy = { density, depth };- return patchStandard(material, {- name: 'canopyShade',- uniforms: {- uCanDens: { value: density },- uCanScale: { value: scale },- uCanCool: { value: cool },- uCanDepth: { value: depth },- uCanSeed: { value: seed },- },- vertexHead: 'varying vec3 vAstraCanW;',- vertexBody: [- '#ifdef USE_INSTANCING',- ' vAstraCanW = (modelMatrix * instanceMatrix'- + ' * vec4(transformed, 1.0)).xyz;',- '#else',- ' vAstraCanW = (modelMatrix * vec4(transformed, 1.0)).xyz;',- '#endif',- ].join('\n'),- fragmentHead: [- 'varying vec3 vAstraCanW;',- 'uniform float uCanDens;',- 'uniform float uCanScale;',- 'uniform vec3 uCanCool;',- 'uniform float uCanDepth;',- 'uniform float uCanSeed;',- ].join('\n'),- fragmentBody: [- ' vec2 cnP = vAstraCanW.xz / uCanScale + uCanSeed * 5.0;',- // Crowns, and the grove they stand in: one field alone lays every- // tree down at the same size and the floor reads as a texture.- ' float cnA = astraFbm2(cnP, 3);',- ' float cnB = astraFbm2(cnP * 0.41 + 3.7, 2);',- ' float cnF = cnA * 0.72 + cnB * 0.28;',- // The threshold, not the amplitude, is what `density` moves: the- // field crosses it over about `density` of the ground.- ' float cnT = mix(0.72, 0.10, uCanDens);',- // A 28 m floor is 4 crowns across and every gradient on it is- // gentle enough to band on an 8-bit target; one bit of hash is- // cheaper than any dither texture.- ' float cnD = (astraHash21(gl_FragCoord.xy) - 0.5) * 0.012;',- ' float cnK = smoothstep(cnT, cnT + 0.30, cnF + cnD);',- // Deep shade is not just dark, it is GREEN — that light came- // through leaves — and no two patches of it are the same green.- ' vec3 cnTint = astraHueBreak(uCanCool, cnP, 1.7, 0.34);',- // Under the thickest crown the last light left is SKY, not the- // green bounced off the leaf above — so the deep end of the- // shade leans blue while its edge stays leaf-green. One flat- // tint over the whole range is what leaves shade reading as- // grey paint.- ' cnTint *= mix(vec3(1.0), vec3(0.84, 0.95, 1.14),',- ' smoothstep(0.5, 1.0, cnK));',- ' diffuseColor.rgb = mix(diffuseColor.rgb, cnTint, cnK * 0.45);',- ' diffuseColor.rgb *= 1.0 - uCanDepth * cnK'- + ' * mix(0.72, 1.0, uCanDens);',- ].join('\n'),- });-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/fire.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/fire.jsdeleted file mode 100644index 3bf5196a..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/fire.js+++ /dev/null@@ -1,393 +0,0 @@-/**- * View-independent fire and candles, in metres, Y up.- *- * makeFire({radius:.35, height:1.1, seed:7, quality:'high'}) returns a Group- * standing on y=0. Call group.userData.update(t, dt) with absolute seconds.- * A bounded, advected density field is integrated front to back; no textures,- * camera-facing flame cards or accumulated simulation state are needed.- * This is an artistic combustion/temperature model, not a fluid solver.- *- * quality: low=32 / medium=56 / high=88 ray samples. Cost scales with screen- * coverage. Share a few fires, rather than hundreds of close-up volumes.- * Normal transparency cannot correctly interleave this volume with transparent- * glass or another volume. Solid occluders in front are depth-tested; geometry- * embedded in the volume should be placed at its base (logs, wick).- * Accurate luminous-surface depth requires the default non-logarithmic depth- * buffer. With logarithmic depth enabled, the proxy back face supplies depth- * and embedded opaque objects can incorrectly clip the flame.- * dispose() owns only resources created here. It is safe to call twice.- */-import * as THREE from 'three';-import { attachDisposal, snapshotResources } from './lifecycle.js';-import { mulberry32 } from './noise.js';-import { makeShaderMaterial, keepOutOfDepthPasses, option, patchStandard, readWind } from './shader.js';--// Fire CLAMPS a number outside its range (a flame too big or too bright is-// still a flame); a value that is not a number throws like every option.-const clamped = (v, fallback, lo, hi, label) => THREE.MathUtils.clamp(option(v, fallback, label), lo, hi);-const QUALITY = { low: 32, medium: 56, high: 88 };--const FIELD = /* glsl */`-uniform float uRadius, uHeight, uIntensity, uCandle, uSeed;-uniform vec2 uWind;-uniform vec3 uBoxMin, uBoxMax, uCameraLocal;-uniform mat4 uLocalToClip;-float fireNoise(vec3 p) {- vec3 i = floor(p), f = fract(p);- f = f * f * (3.0 - 2.0 * f);- return mix(mix(mix(astraHash31(i), astraHash31(i + vec3(1,0,0)), f.x),- mix(astraHash31(i + vec3(0,1,0)), astraHash31(i + vec3(1,1,0)), f.x), f.y),- mix(mix(astraHash31(i + vec3(0,0,1)), astraHash31(i + vec3(1,0,1)), f.x),- mix(astraHash31(i + vec3(0,1,1)), astraHash31(i + vec3(1,1,1)), f.x), f.y), f.z);-}-float fireFbm(vec3 p) {- return fireNoise(p) * 0.57 + fireNoise(p * 2.07 + 13.4) * 0.28- + fireNoise(p * 4.21 - 7.1) * 0.15;-}-// Local density and normalized temperature. Advection moves upward as time-// increases. Domain warping gives the crest detached, rolling tongues.-vec2 fireField(vec3 p) {- float flameScale = mix(0.90 + 0.06 * sin(uTime * 6.2 + uSeed)- + 0.04 * sin(uTime * 9.7 + uSeed * 1.4),- 0.965 + 0.025 * sin(uTime * 7.1 + uSeed), uCandle);- float y = p.y / (uHeight * flameScale);- if (y <= 0.0 || y >= 1.08) return vec2(0.0);- float t = uTime * mix(1.7, 1.1, uCandle);- vec2 bend = uWind * uHeight * y * y;- bend += uRadius * y * y * vec2(sin(t * 2.7 + uSeed), cos(t * 1.9 + uSeed))- * mix(0.5, 0.24, uCandle);- vec3 q = vec3((p.xz - bend) / uRadius, y).xzy;- float r = length(q.xz);- vec3 flow = vec3(q.x * 2.7, y * 5.1 - t * 2.0, q.z * 2.7) + uSeed;- float coarse = fireFbm(flow);- float curl = fireNoise(flow * 0.72 + vec3(0.0, t * 0.42, 4.0));- // Five irregular fuel tongues share one smooth 3-D density volume.- float campProfile = pow(max(0.0, 1.0 - y), 0.82) * 0.30;- float campDistance = r;- for (int k = 0; k < 4; k++) {- float a = float(k) * 1.570796 + uSeed;- float tongueY = y * (1.23 + 0.27 * sin(float(k) * 7.7 + uSeed));- vec2 centre = vec2(sin(a), cos(a)) * (0.50 - y * 0.13);- centre += vec2(sin(y * 8.0 - t * 3.0 + a), cos(y * 6.0 - t * 2.3 + a)) * y * 0.2;- float tongue = pow(max(0.0, 1.0 - tongueY), 0.9) * 0.26;- campDistance = min(campDistance, length(q.xz - centre) + campProfile - tongue);- }- float candleProfile = pow(max(0.0, sin(3.14159 * pow(min(y, 1.0), 0.62))), 0.86);- float profile = mix(campProfile, candleProfile, uCandle);- float disturbance = mix((coarse - 0.49) * (0.35 + y * 0.5)- + (curl - 0.5) * 0.08, (coarse - 0.5) * 0.12, uCandle);- float surface = profile + disturbance - mix(campDistance, r, uCandle);- float density = smoothstep(-0.025, 0.075, surface);- // Combustion is strongest on the mixing interface, not in the unburned- // centre. Thin rolling reaction sheets retain transparent interior gaps.- density *= mix(0.16 + 0.84 * (1.0 - smoothstep(0.08, 0.36, surface)), 1.0, uCandle);- density *= smoothstep(0.0, mix(0.07, 0.025, uCandle), y)- * (1.0 - smoothstep(0.88, 1.075, y));- // Candle's unburned vapour pocket and blue reaction zone near the wick.- float pocket = (1.0 - smoothstep(0.10, 0.36, y))- * (1.0 - smoothstep(0.18, 0.52, r));- density *= 1.0 - pocket * uCandle * 0.88;- float temperature = clamp(0.23 + 0.69 * density + 0.12 * coarse - 0.24 * y, 0.0, 1.0);- return vec2(density, temperature);-}-vec3 fireEmission(float heat) {- vec3 c = mix(vec3(1.8, 0.055, 0.002), vec3(4.0, 0.76, 0.025),- smoothstep(0.08, 0.46, heat));- c = mix(c, vec3(6.2, 3.1, 0.68), smoothstep(0.40, 0.80, heat));- return mix(c, vec3(7.0, 5.1, 2.3), smoothstep(0.78, 1.0, heat));-}-`;--function fireMaterial({ radius, height, wind, intensity, candle, seed, steps, box }) {- const mat = makeShaderMaterial({- name: 'FireVolume', fog: true,- uniforms: {- uRadius: { value: radius }, uHeight: { value: height },- uWind: { value: new THREE.Vector2(...wind) },- uIntensity: { value: intensity }, uCandle: { value: candle ? 1 : 0 },- uSeed: { value: (seed >>> 0) % 997 * 0.173 },- uBoxMin: { value: box.min.clone() }, uBoxMax: { value: box.max.clone() },- uCameraLocal: { value: new THREE.Vector3() },- uLocalToClip: { value: new THREE.Matrix4() },- },- varyings: 'varying vec3 vFireLocal;',- vertexMain: 'vFireLocal = position;',- fragmentHead: FIELD,- fragmentMain: /* glsl */`- if (uIntensity <= 0.0) discard;- vec3 ray = normalize(vFireLocal - uCameraLocal);- vec2 range = astraRayBox(uCameraLocal, ray, uBoxMin, uBoxMax);- float enter = max(0.0, range.x), leave = range.y;- if (leave <= enter) discard;- float ds = (leave - enter) / float(${steps});- // Static sub-pixel jitter avoids axial banding without temporal noise.- float jitter = astraHash31(vec3(gl_FragCoord.xy, 0.13));- vec3 color = vec3(0.0);- float transmittance = 1.0;- vec3 firstHit = uCameraLocal + ray * leave;- bool hit = false;- for (int i = 0; i < ${steps}; i++) {- vec3 p = uCameraLocal + ray * (enter + (float(i) + jitter) * ds);- vec2 field = fireField(p);- float optical = field.x * ds * mix(2.8, 4.2, uCandle) / uRadius;- float a = 1.0 - exp(-optical);- if (!hit && field.x > 0.10) { firstHit = p; hit = true; }- vec3 emitted = fireEmission(field.y);- emitted *= mix(vec3(0.36, 0.13, 0.025), vec3(0.65, 0.57, 0.43), uCandle);- float blue = uCandle * (1.0 - smoothstep(0.025, 0.19, p.y / uHeight));- emitted = mix(emitted, vec3(0.08, 0.28, 1.5), blue);- color += transmittance * a * emitted * uIntensity;- transmittance *= 1.0 - a;- if (transmittance < 0.008) break;- }- float alpha = 1.0 - transmittance;- if (alpha < 0.008) discard;- // Depth from the luminous field, not its empty bounding cube. This also- // makes the volume visible to a camera inside its proxy geometry.- #ifndef USE_LOGDEPTHBUF- gl_FragDepth = astraClipDepth(uLocalToClip, firstHit);- #endif- gl_FragColor = vec4(color / max(alpha, 0.001), alpha);- `,- transparent: true, depthWrite: false, side: THREE.BackSide,- });- mat.userData.bloom = true;- return mat;-}--function installDispose(group) {- const owned = snapshotResources(group);- group.traverse((o) => { if (o.isLight && o.dispose) owned.add(o); });- attachDisposal(group, owned);- const dispose = group.userData.dispose;- group.userData.dispose = () => {- if (dispose()) group.userData.disposed = true;- };-}--/**- * @param {object} [opts]- * radius=.35, height=1.1: flame envelope in metres; style='campfire'|'candle'.- * wind=[x,z] (or any shader.js readWind spelling): lateral lean / height, bounded to ±.6. intensity=1: emission.- * quality='medium'; seed=7; embers=26 (0 for candle), max 256.- * light=true, lightIntensity=14 (candela), lightDistance=height*8.- * Flame geometry only: add your own logs/burner. userData.bounds is local and- * includes ember trajectories. update(t) is deterministic even when rewound.- */-export function makeFire(opts = {}) {- const candle = opts.style === 'candle';- const radius = clamped(opts.radius, candle ? 0.009 : 0.35, 0.001, 20, 'makeFire: radius');- const height = clamped(opts.height, candle ? 0.055 : 1.1, 0.004, 50, 'makeFire: height');- const intensity = clamped(opts.intensity, 1, 0, 8, 'makeFire: intensity');- const seed = clamped(opts.seed, 7, -2147483648, 2147483647, 'makeFire: seed') | 0;- const w = readWind(opts.wind, [0, 0], 'makeFire wind');- // bounded to ±.6 per axis by scaling both, so a strong wind still leans the way it blows- const lean = 0.6 / Math.max(0.6, Math.abs(w.x), Math.abs(w.z));- const wind = [w.x * lean, w.z * lean];- const steps = Object.hasOwn(QUALITY, opts.quality) ? QUALITY[opts.quality] : QUALITY.medium;- const extentX = radius * 1.65 + Math.abs(wind[0]) * height * 1.2;- const extentZ = radius * 1.65 + Math.abs(wind[1]) * height * 1.2;- const box = new THREE.Box3(new THREE.Vector3(-extentX, 0, -extentZ),- new THREE.Vector3(extentX, height * 1.1, extentZ));- const group = new THREE.Group(); group.name = candle ? 'CandleFlame' : 'Fire';- const geometry = new THREE.BoxGeometry(extentX * 2, height * 1.1, extentZ * 2);- geometry.translate(0, height * 0.55, 0);- const material = fireMaterial({ radius, height, wind, intensity, candle, seed, steps, box });- const volume = new THREE.Mesh(geometry, material); volume.name = 'FlameVolume';- volume.renderOrder = 2;- keepOutOfDepthPasses(volume);- const guard = volume.onBeforeRender;- const inverse = new THREE.Matrix4(), cameraLocal = material.uniforms.uCameraLocal.value;- volume.onBeforeRender = (r, s, cam, geo, mat, draw) => {- guard.call(volume, r, s, cam, geo, mat, draw);- inverse.copy(volume.matrixWorld).invert();- cameraLocal.setFromMatrixPosition(cam.matrixWorld).applyMatrix4(inverse);- material.uniforms.uLocalToClip.value.copy(cam.projectionMatrix)- .multiply(cam.matrixWorldInverse).multiply(volume.matrixWorld);- };- group.add(volume);-- const random = mulberry32(seed);- const count = Math.round(clamped(opts.embers, candle ? 0 : 26, 0, 256, 'makeFire: embers'));- const particles = Array.from({ length: count }, () => ({- phase: random(), life: 1.5 + random() * 2.0,- x: (random() - 0.5) * radius * 1.5, z: (random() - 0.5) * radius * 1.5,- drift: random() * 6.283, size: radius * (0.006 + random() * 0.01),- }));- let embers;- const emberMat = count ? new THREE.MeshBasicMaterial({ color: 0xffffff }) : null;- const dummy = new THREE.Object3D(), color = new THREE.Color();- if (count) {- emberMat.userData.bloom = true;- embers = new THREE.InstancedMesh(new THREE.SphereGeometry(1, 5, 4), emberMat, count);- embers.name = 'FireEmbers'; embers.visible = intensity > 0; embers.instanceMatrix.setUsage(THREE.DynamicDrawUsage);- embers.frustumCulled = false;- group.add(embers);- box.expandByPoint(new THREE.Vector3(-radius * 1.2 - Math.abs(wind[0]) * height * 2.1,- height * 2.5 + radius * 0.05, -radius * 1.2 - Math.abs(wind[1]) * height * 2.1));- box.expandByPoint(new THREE.Vector3(radius * 1.2 + Math.abs(wind[0]) * height * 2.1,- height * 2.5 + radius * 0.05, radius * 1.2 + Math.abs(wind[1]) * height * 2.1));- }- const lightIntensity = clamped(opts.lightIntensity, candle ? 0.9 : 14, 0, 10000, 'makeFire: lightIntensity');- let light;- if (opts.light !== false) {- light = new THREE.PointLight(0xffab53, lightIntensity,- clamped(opts.lightDistance, height * 8, 0, 1000, 'makeFire: lightDistance'), 2);- light.name = 'FireLight'; light.position.y = height * 0.27;- group.add(light);- }- // `out` lets update() reuse one record instead of allocating per ember.- const sampleEmber = (index, t, out = { position: new THREE.Vector3() }) => {- if (!particles.length) return null;- const p = particles[THREE.MathUtils.clamp(index | 0, 0, count - 1)];- const a = ((t / p.life + p.phase) % 1 + 1) % 1;- out.position.set(- p.x + wind[0] * height * a * 2 + Math.sin(a * 5 + p.drift) * radius * a * 0.3,- height * (0.15 + a * 2.2), p.z + wind[1] * height * a * 2 + Math.cos(a * 4 + p.drift) * radius * a * 0.3);- out.scale = Math.pow(Math.sin(a * Math.PI), 0.7) * p.size; out.age = a;- return out;- };- const ember = { position: new THREE.Vector3() };- group.userData.update = (t, _dt) => {- if (group.userData.disposed) return;- t = Number.isFinite(t) ? t : 0;- material.uniforms.uTime.value = t;- const flicker = 0.88 + 0.07 * Math.sin(t * 11 + seed)- + 0.05 * Math.sin(t * 17.3 + seed * 0.31);- if (light) light.intensity = lightIntensity * flicker * intensity;- for (let i = 0; i < count; i++) {- const p = sampleEmber(i, t, ember);- dummy.position.copy(p.position); dummy.scale.set(p.scale, p.scale * 2.7, p.scale);- dummy.rotation.z = Math.sin(t + i) * 0.25; dummy.updateMatrix();- embers.setMatrixAt(i, dummy.matrix);- color.setRGB(3.5 * (1 - p.age * 0.75), 0.7 * (1 - p.age), 0.025).multiplyScalar(intensity);- embers.setColorAt(i, color);- }- if (embers) { embers.instanceMatrix.needsUpdate = true; embers.instanceColor.needsUpdate = true; }- };- group.userData.tick = group.userData.update;- installDispose(group);- group.userData.bounds = box.clone();- group.userData.sampleEmber = sampleEmber;- group.userData.quality = steps;- group.userData.update(0, 0);- return group;-}--function waxGeometry(radius, height, seed) {- // Continuous turned wall and dished top: no coincident cylinder cap/pool.- const vertices = [], uv = [], indices = [];- const segments = 80;- const profile = [- [0, 0], [radius * 0.94, 0], [radius, height * 0.015],- [radius, height * 0.89], [radius * 0.998, height * 0.973],- [radius * 0.91, height], [radius * 0.78, height * 0.993],- [radius * 0.66, height * 0.953], [radius * 0.38, height * 0.943], [0, height * 0.943],- ];- for (let j = 0; j < profile.length; j++) {- for (let i = 0; i <= segments; i++) {- const a = i / segments * Math.PI * 2;- const rough = Math.sin(a * 3 + seed) * 0.38 + Math.sin(a * 7 + seed * 0.2) * 0.19;- const [r, y] = profile[j];- const rim = j >= 4 && j <= 7 ? rough * Math.min(height * 0.019, radius * 0.09) : 0;- const rr = r * (1 + 0.007 * Math.sin(a * 11 + j * 0.7));- vertices.push(Math.sin(a) * rr, y + rim, Math.cos(a) * rr);- uv.push(i / segments, j / (profile.length - 1));- if (j && i) {- const b = j * (segments + 1) + i;- indices.push(b, b - 1, b - segments - 1, b - 1, b - segments - 2, b - segments - 1);- }- }- }- const g = new THREE.BufferGeometry();- g.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));- g.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2));- g.setIndex(indices); g.computeVertexNormals(); g.computeBoundingSphere();- return g;-}--/**- * A candle whose base is y=0: radius=.032, height=.16, color=0xe9cf9b,- * drips=7, seed=13, lit=true, flameHeight=.047, quality='high'.- * Includes melted lip, glossy wax pool, cooled runoff and a charred curved wick.- * Returned Group has update(t,dt), tick(t), dispose(), bounds and flame handles.- * lightIntensity=.8 candela approximates one candle; scene exposure is unchanged.- */-export function makeCandle(opts = {}) {- const radius = clamped(opts.radius, 0.032, 0.004, 2, 'makeCandle: radius');- const height = clamped(opts.height, 0.16, 0.015, 8, 'makeCandle: height');- const seed = clamped(opts.seed, 13, -2147483648, 2147483647, 'makeCandle: seed') | 0;- const lit = opts.lit !== false;- const group = new THREE.Group(); group.name = 'Candle';- const wax = new THREE.MeshPhysicalMaterial({ color: opts.color ?? 0xe9cf9b,- roughness: 0.41, metalness: 0, clearcoat: 0.08, clearcoatRoughness: 0.4 });- wax.name = 'WarmTranslucentWax';- patchStandard(wax, { name: 'CandleWax', util: true,- uniforms: { uWaxHeight: { value: height }, uWaxRadius: { value: radius },- uWaxLit: { value: lit ? 1 : 0 } },- vertexHead: 'varying vec3 vWaxLocal;', vertexBody: 'vWaxLocal = position;',- fragmentHead: 'varying vec3 vWaxLocal; uniform float uWaxHeight, uWaxRadius, uWaxLit;',- fragmentBody: `- float grain = astraNoise2(vWaxLocal.xy * 720.0) - 0.5;- diffuseColor.rgb *= 1.0 + grain * 0.035;- `,- outputBody: `- float waxGlow = exp(-(uWaxHeight - vWaxLocal.y) / max(uWaxRadius * 0.8, 0.001));- gl_FragColor.rgb += uWaxLit * waxGlow * vec3(0.24, 0.045, 0.008);- `,- });- const body = new THREE.Mesh(waxGeometry(radius, height, seed), wax);- body.name = 'CandleWaxBody'; body.castShadow = true; body.receiveShadow = true; group.add(body);- const pool = new THREE.Mesh(new THREE.CircleGeometry(radius * 0.59, 64),- new THREE.MeshPhysicalMaterial({ color: opts.color ?? 0xe9cf9b, roughness: 0.10,- clearcoat: 1, clearcoatRoughness: 0.04, metalness: 0 }));- pool.name = 'MoltenWaxPool'; pool.rotation.x = -Math.PI / 2; pool.position.y = height * 0.947;- group.add(pool);-- const random = mulberry32(seed), drips = Math.round(clamped(opts.drips, 7, 0, 24, 'makeCandle: drips'));- const dripMat = wax;- for (let i = 0; i < drips; i++) {- const angle = random() * Math.PI * 2;- const length = height * (0.08 + random() * 0.46);- const width = radius * (0.04 + random() * 0.045);- const points = [];- for (let j = 0; j < 9; j++) {- const a = angle + Math.sin(j / 8 * Math.PI) * 0.03;- const r = radius * (j === 0 ? 0.93 : 1.004);- points.push(new THREE.Vector3(Math.sin(a) * r, height * 0.988 - length * j / 8, Math.cos(a) * r));- }- const drip = new THREE.Mesh(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(points), 20, width, 8, false), dripMat);- drip.name = `WaxDrip_${i}`; drip.castShadow = true; group.add(drip);- const bead = new THREE.Mesh(new THREE.SphereGeometry(width * 1.32, 10, 8), dripMat);- bead.name = `WaxDripBead_${i}`; bead.position.copy(points[8]); bead.scale.y = 1.55; group.add(bead);- }- const wickHeight = Math.min(radius * 0.29, height * 0.11);- const wickCurve = new THREE.CatmullRomCurve3([- new THREE.Vector3(0, height * 0.944, 0),- new THREE.Vector3(radius * 0.02, height * 0.944 + wickHeight * 0.65, 0),- new THREE.Vector3(radius * 0.10, height * 0.944 + wickHeight, radius * 0.025),- ]);- const wick = new THREE.Mesh(new THREE.TubeGeometry(wickCurve, 12, radius * 0.021, 8, false),- new THREE.MeshStandardMaterial({ color: 0x17100b, roughness: 1,- emissive: lit ? 0x6e1901 : 0, emissiveIntensity: lit ? 0.35 : 0 }));- wick.name = 'CharredWick'; group.add(wick);- let flame;- if (lit) {- const flameHeight = clamped(opts.flameHeight, radius * 1.47, 0.01, 3, 'makeCandle: flameHeight');- flame = makeFire({ radius: flameHeight * 0.17, height: flameHeight, style: 'candle',- seed, wind: opts.wind, quality: opts.quality || 'high', light: opts.light,- lightIntensity: clamped(opts.lightIntensity, 0.8, 0, 10000, 'makeCandle: lightIntensity'), lightDistance: Math.max(1, height * 14),- intensity: opts.intensity });- flame.position.y = height * 0.944 + wickHeight * 0.6;- group.add(flame);- }- group.userData.flame = flame || null;- group.userData.update = (t, dt) => {- if (!group.userData.disposed) flame?.userData.update(t, dt);- };- group.userData.tick = group.userData.update;- installDispose(group);- group.updateMatrixWorld(true);- group.userData.bounds = new THREE.Box3().setFromObject(group);- return group;-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flock.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flock.jsdeleted file mode 100644index 5c41a34e..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flock.js+++ /dev/null@@ -1,394 +0,0 @@-/**- * A skein of birds crossing the sky — the cheapest motion there is.- *- * A still scene with nothing moving in it reads as a model shoot, and- * animating a flock on the CPU means rebuilding a matrix per bird per- * frame, which caps the count at the point where a flock stops looking- * like one. So EVERY moving part lives in the vertex shader driven by- * uTime: the whole flock rides a closed path, each bird holds its own- * lag and offset off that path, and its wings beat on its own phase.- * Nothing is touched per frame but one float, so ten thousand birds- * cost what ten do, in ONE draw call.- *- * A bird at distance is two strokes. There is no bird model here: the- * quad is a screen-aligned billboard whose span axis is the projection- * of the real wing axis (so a bird flying at the camera foreshortens- * to a mark), and the silhouette — a V whose tips lag the root — is- * drawn in the fragment. Silhouette and motion carry it.- *- * COLOUR is lit, not painted. A skein is the one effect a viewer has- * seen ten thousand times, so the tells are cheap to spot: birds all- * one flat value, and a wingbeat "flash" that mixes toward WHITE on- * every bird at once. Both are gone. Each bird carries its own albedo- * (a warm/cool tilt and a value spread off `color`), the two wings- * ROLL opposite ways through the stroke so one catches the sun while- * the other is edge-on, and every bright thing on the bird — the- * membrane sheen, the light through the backlit primaries — arrives- * in `sunColor`, with `skyColor` as the ambient that keeps the shaded- * side off black. Pass the scene's own rig colours and the flock- * belongs to the frame it flies over.- */--import * as THREE from 'three';-import { attachDisposal, snapshotResources } from './lifecycle.js';--import { mulberry32 } from './noise.js';-import {- instancedQuad, keepOutOfDepthPasses, makeShaderMaterial, readVec3,- tickShaders,-} from './shader.js';--const _TAU = Math.PI * 2;-const _MAX_PTS = 8;-const _PATH_SAMPLES = 2048;--// Equal-distance samples avoid the acceleration produced by advancing a-// Catmull-Rom parameter through unequally spaced control points. Manual linear-// interpolation needs no floating-point texture filtering extension.-function pathTable(curve) {- curve.arcLengthDivisions = _PATH_SAMPLES * 4;- curve.updateArcLengths();- const data = new Float32Array(_PATH_SAMPLES * 4);- const bounds = new THREE.Box3();- for (let i = 0; i < _PATH_SAMPLES; i++) {- const point = curve.getPointAt(i / _PATH_SAMPLES);- point.toArray(data, i * 4);- bounds.expandByPoint(point);- }- const texture = new THREE.DataTexture(data, _PATH_SAMPLES, 1,- THREE.RGBAFormat, THREE.FloatType);- texture.name = 'FlockArcLengthPath';- texture.minFilter = texture.magFilter = THREE.NearestFilter;- texture.generateMipmaps = false;- texture.needsUpdate = true;- const sample = (distance) => {- const f = THREE.MathUtils.euclideanModulo(distance, 1) * _PATH_SAMPLES;- const i = Math.floor(f), j = (i + 1) % _PATH_SAMPLES;- return new THREE.Vector3().fromArray(data, i * 4)- .lerp(new THREE.Vector3().fromArray(data, j * 4), f - i);- };- return { texture, bounds, sample };-}--/** Default route: a shallow ellipse over the scene, gently undulating. */-function _defaultPath(extent, height) {- const pts = [];- for (let k = 0; k < 6; k++) {- const a = (k / 6) * _TAU;- pts.push(new THREE.Vector3(- Math.cos(a) * extent,- height * (1 + 0.12 * Math.sin(a * 2)),- Math.sin(a) * extent * 0.62));- }- return pts;-}--/**- * Build a flock travelling as a loose skein, animated in the shader.- *- * @param {object} [opts]- * `count` individuals (default 120) — one draw call at any count;- * `kind` 'bird' (default) or 'fish', which swaps the silhouette and- * turns the body along the travel direction; `extent` radius in- * metres of the default flight loop (default 60); `height` its- * altitude in metres (default 28); `speed` metres per second along- * the path (default 9); `color` the ALBEDO the plumage is varied- * around, not the pixel colour — it is lit here; `wingBeat` beats- * per second (default 3.2 birds / 1.6 fish); `sunDir` direction the- * KEY LIGHT comes from — pass `rig.lightDir`, not `rig.sunDir`,- * because at night the light is the moon and `sunDir` is under the- * horizon, where this turns the sun term off; `sunColor` that light's- * colour (pass `rig.sun.color`); `skyColor` the ambient the shaded- * side is lit by (pass `rig.fill.color`, or the water's tint for a- * school); `seed` PRNG seed (default 11); `path` 3 to 8 waypoints- * ([x,y,z] or Vector3) of a CLOSED loop replacing the default one;- * `size` wingspan in metres (default extent/20, clamped 0.35..2.4).- * @returns {THREE.Group} Named `Flock`, holding ONE instanced mesh,- * with `userData.update(t)` advancing the only thing that changes.- * `userData.samplePath(t)` returns the local centreline point at absolute- * seconds; lateral formation offsets and individual bobbing are additional.- */-export function makeFlock(opts = {}) {- const count = Math.max(1, opts.count === undefined ? 120 : opts.count);- const kind = opts.kind === 'fish' ? 1 : 0;- const extent = opts.extent === undefined ? 60 : opts.extent;- const height = opts.height === undefined ? 28 : opts.height;- const speed = opts.speed === undefined ? 9 : opts.speed;- const beat = opts.wingBeat === undefined- ? (kind ? 1.6 : 3.2) : opts.wingBeat;- const seed = opts.seed === undefined ? 11 : opts.seed;- const size = opts.size === undefined- ? Math.min(2.4, Math.max(0.35, extent * 0.05)) : opts.size;- // An ALBEDO, so it is lit rather than drawn: 0x23262c reflects 1.5%- // of what lands on it, which is a hole in the sky at any exposure.- // A rook's back is nearer 4%, and that is what reads as a bird.- const color = new THREE.Color(- opts.color === undefined ? (kind ? 0x9fb4c2 : 0x36393f) : opts.color);- const sun = readVec3(opts.sunDir, 0.45, 0.78, 0.35).normalize();- // Defaults are a daylight rig's own two colours; a caller with a- // rig should hand over its sun and its sky and stop guessing.- const sunCol = new THREE.Color(- opts.sunColor === undefined ? 0xffe9cf : opts.sunColor);- const skyCol = new THREE.Color(- opts.skyColor === undefined ? 0x93b4dd : opts.skyColor);-- const pts = (opts.path && opts.path.length >= 3- ? opts.path.map((p) => readVec3(p))- : _defaultPath(extent, height)).slice(0, _MAX_PTS);- // Centripetal interpolation prevents cusps between unevenly spaced points.- // Sample the closed route at equal arc lengths; the shader- // interpolates the same table so speed is metres per second.- const curve = new THREE.CatmullRomCurve3(pts, true, 'centripetal');- const route = pathTable(curve);- const loop = Math.max(curve.getLength(), 1e-3);-- const geom = instancedQuad(count, 1, 1);- const spread = size * 6;- // Strung out along the route, never wrapped onto its own tail.- const skein = Math.min(loop * 0.45, count * size * 2.4);- const rand = mulberry32(seed);- const off = new Float32Array(count * 3);- const ext = new Float32Array(count * 4);- let wide = 0, tall = 0;- for (let i = 0; i < count; i++) {- const t = count > 1 ? i / (count - 1) : 0;- const lag = t * skein + (rand() - 0.5) * (skein / count);- // A skein is a wavy line, not a block: the slow sinusoid is the- // shape, the jitter keeps it from reading as a drawn curve.- off[i * 3] = Math.sin(t * 5.0) * spread * 0.5- + (rand() - 0.5) * spread * 0.7;- off[i * 3 + 1] = Math.sin(t * 3.3 + 1.0) * spread * 0.22- + (rand() - 0.5) * spread * 0.45;- off[i * 3 + 2] = lag / loop;- ext[i * 4] = rand() * _TAU;- ext[i * 4 + 1] = 0.78 + rand() * 0.5;- ext[i * 4 + 2] = 0.85 + rand() * 0.35;- ext[i * 4 + 3] = size * (0.25 + rand() * 0.55);- wide = Math.max(wide, Math.abs(off[i * 3]) + ext[i * 4 + 3] * 1.4);- tall = Math.max(tall, Math.abs(off[i * 3 + 1]) + ext[i * 4 + 3]);- }- geom.setAttribute('iOff', new THREE.InstancedBufferAttribute(off, 3));- geom.setAttribute('iExtra', new THREE.InstancedBufferAttribute(ext, 4));- // `position` is all zeros, so the bounds three would compute are a- // point at the origin: framing, culling and the census all need the- // volume the shader actually flies the flock through.- const box = route.bounds.clone();- box.expandByVector(new THREE.Vector3(- wide + size, tall + size, wide + size));- geom.boundingBox = box;- geom.boundingSphere = box.getBoundingSphere(new THREE.Sphere());-- const mesh = new THREE.Mesh(geom, flockMaterial({- path: route.texture, rate: speed / loop, size: size * 0.5,- beat, kind, color, sun, sunCol, skyCol,- }));- mesh.name = kind ? 'FlockFish' : 'FlockBirds';- mesh.frustumCulled = false; // every position lives in the shader- mesh.renderOrder = 3;-- const g = new THREE.Group();- g.name = 'Flock';- g.add(mesh);- g.userData.update = g.userData.tick = (t) => tickShaders(g, t);- g.userData.samplePath = (t = 0) => route.sample(t * speed / loop);- g.userData.pathLength = loop;- const owned = snapshotResources(g);- owned.add(route.texture);- attachDisposal(g, owned);- return keepOutOfDepthPasses(g);-}--/** The one material: path, formation, beat and silhouette, all in GLSL. */-function flockMaterial(o) {- return makeShaderMaterial({- name: 'Flock',- uniforms: {- uPath: { value: o.path },- uRate: { value: o.rate },- uSize: { value: o.size },- uBeat: { value: o.beat },- uKind: { value: o.kind },- uColor: { value: o.color },- uSun: { value: o.sun },- uSunCol: { value: o.sunCol },- uSky: { value: o.skyCol },- },- varyings: [- 'varying vec2 vUv; varying float vPhase;',- // x,y: the sun against the bird's own up and wing axes —- // the roll of the stroke rotates between them. z: how much- // the flock is BACKLIT from this camera. w: this bird's- // stroke depth, which is also its silhouette's bend.- 'varying vec4 vLit; varying vec3 vTint;',- ].join(' '),- vertexHead: [- 'attribute vec3 aCorner;',- 'attribute vec3 iOff;',- 'attribute vec4 iExtra;',- 'uniform sampler2D uPath;',- 'uniform float uRate;',- 'uniform float uSize; uniform float uBeat; uniform float uKind;',- 'uniform vec3 uColor; uniform vec3 uSun;',- 'vec3 flockPath(float u) {',- ` float s = fract(u) * ${_PATH_SAMPLES.toFixed(1)};`,- ' float i = floor(s), f = s - i;',- ` vec3 a = texture2D(uPath, vec2((i + 0.5) / ${_PATH_SAMPLES.toFixed(1)}, 0.5)).xyz;`,- ` vec3 b = texture2D(uPath, vec2((mod(i + 1.0, ${_PATH_SAMPLES.toFixed(1)}) + 0.5) / ${_PATH_SAMPLES.toFixed(1)}, 0.5)).xyz;`,- ' return mix(a, b, f);',- '}',- ].join('\n'),- vertexMain: [- ' vUv = uv;',- // The flock rides the loop as one; the bird's own lag is- // what makes it FOLLOW rather than march in a slab.- ' float u = uTime * uRate - iOff.z;',- ' vec3 c = flockPath(u);',- ' vec3 fwd = normalize(flockPath(u + 0.004) - c',- ' + vec3(1e-5, 0.0, 0.0));',- ' vec3 sd = cross(fwd, vec3(0.0, 1.0, 0.0));',- ' float sl = length(sd);',- ' sd = sl > 1e-4 ? sd / sl : vec3(1.0, 0.0, 0.0);',- ' vec3 ud = cross(sd, fwd);',- // Decorrelated bob: offsets under a few turns leave the- // flock breathing in unison, which reads as one object.- ' float st = astraStagger(iExtra.x);',- ' c += sd * (iOff.x + sin(uTime * 0.63 + st) * iExtra.w * 1.4)',- ' + ud * (iOff.y + sin(uTime * 0.91 + st * 1.7) * iExtra.w);',- ' vPhase = uTime * uBeat * iExtra.z * 6.2831 + iExtra.x;',- // Camera axes in LOCAL space (rows of modelViewMatrix), so- // the billboard survives a rotated or moved parent group.- ' vec3 camR = vec3(modelViewMatrix[0][0], modelViewMatrix[1][0],',- ' modelViewMatrix[2][0]);',- ' vec3 camU = vec3(modelViewMatrix[0][1], modelViewMatrix[1][1],',- ' modelViewMatrix[2][1]);',- // Span across flight for a bird, along it for a fish; the- // quad takes its width from that axis PROJECTED on screen,- // so a bird coming at the camera loses its span.- ' vec3 ax = mix(sd, fwd, uKind);',- ' vec2 e = vec2(dot(ax, camR), dot(ax, camU));',- ' float el = length(e);',- ' vec2 ex = el > 1e-4 ? e / el : vec2(1.0, 0.0);',- ' vec2 ey = vec2(-ex.y, ex.x);',- ' ey = ey.y < 0.0 ? -ey : ey;',- ' float sz = uSize * iExtra.y;',- ' vec2 q = ex * (aCorner.x * 2.0 * sz * clamp(el, 0.34, 1.0))',- ' + ey * (aCorner.y * 2.0 * sz * 0.8);',- ' transformed = c + camR * q.x + camU * q.y;',- // ONE albedo across the flock is the tell of an instanced- // field. A skein is juveniles and adults, dry backs and- // wet ones: a value spread, plus a warm/cool tilt (not a- // hue rotation — that returns a near-grey bird unchanged).- ' float bv = astraHash11(iExtra.x * 7.13 + 3.1);',- ' float bw = astraHash11(iExtra.x * 3.77 + 11.9);',- ' float tw = (bw - 0.5) * 0.5;',- ' vTint = uColor * (0.62 + bv * 1.02)',- ' * vec3(1.0 + tw, 1.0, 1.0 - tw);',- // A fifth of any skein is gliding at any instant, wings- // held: a frozen frame in which every bird holds the same V- // is the second tell, after the flat colour.- ' float gl = astraHash11(iExtra.x * 13.31 + 0.7);',- // The route is local but the key light is world-space. Transform- // the normal axes before taking their dot products with the sun.- ' ud = inverseTransformDirection(normalMatrix * ud, viewMatrix);',- ' sd = inverseTransformDirection(normalMatrix * sd, viewMatrix);',- // The sun in the bird's OWN frame (x against its up axis, y- // against its wing axis), so the fragment can roll each wing- // between the two through the stroke, and how backlit the- // flock is from this camera.- ' vLit = vec4(dot(ud, uSun), dot(sd, uSun),',- ' smoothstep(0.05, 0.85, dot(uSun, normalize(',- ' (modelMatrix * vec4(c, 1.0)).xyz - cameraPosition))),',- ' mix(0.30, 1.0, smoothstep(0.0, 0.32, gl)));',- ].join('\n'),- fragmentHead: [- 'uniform vec3 uColor; uniform vec3 uSun; uniform float uKind;',- 'uniform vec3 uSunCol; uniform vec3 uSky;',- ].join('\n'),- fragmentMain: [- ' vec2 q = vUv * 2.0 - 1.0;',- ' float au = abs(q.x);',- ' float cl, h;',- ' float stroke = 0.0;',- ' if (uKind < 0.5) {',- // Two strokes: one line per wing, tips lagging the root- // through the beat, thick at the body and gone at the tip.- ' stroke = sin(vPhase - au * 0.9);',- ' cl = stroke * 0.72 * pow(au, 1.3) * vLit.w;',- // A gaussian body summed onto the wing line gives a hard- // four-cornered DIAMOND at close range — the one place this- // mark is read as a shape rather than a speck. An ellipse- // for the body and a tapering wing keep the round back and- // the thin primaries a bird actually has.- ' float body = 0.25 * sqrt(max(0.0, 1.0 - au * au / 0.018));',- ' float wing = 0.068 * (1.0 - 0.5 * au)',- ' * (1.0 - smoothstep(0.78, 1.0, au));',- // Union by hypot, not max: a max leaves a crease at the- // shoulder, and the body's own axis is ACROSS the span, so- // the ellipse is narrow in x and long in y.- ' h = sqrt(body * body + wing * wing);',- ' } else {',- ' stroke = sin(vPhase + q.x * 2.6);',- ' cl = stroke * 0.15 * (0.32 + 0.68 * (0.5 - q.x * 0.5));',- ' h = 0.30 * sqrt(max(0.0, 1.0 - q.x * q.x))',- ' + 0.26 * (1.0 - smoothstep(-1.0, -0.55, q.x));',- ' }',- ' float d = abs(q.y - cl);',- // A bird is a handful of pixels: without gradient-width- // antialiasing the silhouette stipples out of the frame.- ' float aa = max(fwidth(d), 0.004);',- ' float a = 1.0 - smoothstep(h - aa, h + aa, d);',- ' if (a < 0.01) discard;',- // The wings are MIRROR images: through the stroke they roll- // opposite ways about the flight line, so one turns its- // upper surface into the sun while the other goes edge-on.- // That asymmetry is the shimmer of a real skein — a flash- // keyed on the beat alone lights every bird identically and- // reads as a flickering white speck field.- ' float roll = cos(vPhase - au * 0.9) * 1.15 * vLit.w',- ' * (q.x < 0.0 ? -1.0 : 1.0);',- // A fish rolls about its own long axis instead, and shows- // its FLANK: the axes swap.- ' float ndl = mix(vLit.x, vLit.y, uKind) * cos(roll)',- ' + mix(vLit.y, vLit.x, uKind) * sin(roll);',- ' float up = clamp(ndl, 0.0, 1.0);',- // Below the horizon there is no sun to catch, and the- // ambient goes with it — the flock is then a shape against- // whatever the sky still has.- ' float dayF = smoothstep(-0.18, 0.12, uSun.y);',- // IRRADIANCE, not a lerp weight. The open sky is a hemisphere- // of light: its integral is a multiple of the sky's own- // radiance, not a fraction of it, and a shaded bird lit at- // "0.26 of sky" landed on 7/255 — a hole punched in the- // frame. These two scalars put a dark bird's shaded side at- // ~24/255 with the sky's hue still in it, and its sunlit- // side four times that, which is where a rook photographs.- ' vec3 irr = (uSky * (1.34 + 0.40 * clamp(-ndl, 0.0, 1.0))',- ' * mix(0.30, 1.0, dayF)',- ' + uSunCol * (1.74 * up * dayF))',- // A fish is under WATER: the same sky arrives at it filtered- // and halved. Without this a silver flank (a genuine 40%- // albedo) meets full daylight and clips to white paper.- ' * mix(1.0, 0.45, uKind);',- ' vec3 c = vTint * irr;',- // The membrane is glossy: at the roll that lines a wing up- // with the sun the whole stroke flares. Narrow, and in the- // colour of the SUN — a flare toward white is the tell of- // a flock painted rather than lit.- ' c += uSunCol * (pow(up, 5.0) * dayF * 0.30',- ' * (1.0 - uKind * 0.3));',- // Backlit, the light comes THROUGH the wing: a flock- // against the sun is not a field of black specks, it is- // black BODIES with lit primaries. The band stops short of- // the outer tip, where the silhouette is one antialiased- // pixel and any glow lands on the sky instead of the bird.- ' float thin = smoothstep(0.22, 0.72, au)',- ' * (1.0 - smoothstep(0.86, 1.0, au));',- ' c += uSunCol * (vLit.z * dayF * 0.26 * (1.0 - uKind * 0.5)',- ' * thin * (0.45 + 0.55 * clamp(-ndl, 0.0, 1.0)));',- ' gl_FragColor = vec4(c, a);',- ].join('\n'),- transparent: true,- depthWrite: false,- side: THREE.DoubleSide,- });-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flowers.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flowers.jsdeleted file mode 100644index 7768672a..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flowers.js+++ /dev/null@@ -1,951 +0,0 @@-/**- * Flowers: the colour a meadow carries above the grass, and the petals- * and leaves that come down out of the air.- *- * `makeFlowers` seats flowering plants on the caller's ground and nods- * their heads in the SAME wind grass.js rides — `windOf` is imported- * rather than re-read, so one scene's meadow and its flowers lean and- * gust together. A petal is a thin double-sided card whose rim is- * translucent and which is lit THROUGH — by `patchLeafSSS` on the- * plants, whose sun is stated, and by `patchTranslucency` on what is- * in the air, which takes its light from the scene's own lamps; the- * silhouette (a disc of petals, a cup, a spike) is a set of UNIFORMS- * and never baked GLSL, because `patchStandard` hands one compiled- * program to every material that shares a patch name.- *- * `makeFalling` is the other half: leaves or petals drifting DOWN- * through the air, each at its own rate, tumbling about its own axis- * and sliding sideways as it goes, because a leaf does not fall- * straight. The whole field wraps inside the volume it advertises, so- * the box it states is the box it occupies.- *- * Both are ONE draw call whose every moving part lives in the vertex- * shader, both are deterministic in `seed`, and both need driving from- * your zone's `update` — `obj.userData.update(t)` — or nothing moves.- */--import * as THREE from 'three';-import { attachDisposal, snapshotResources } from './lifecycle.js';--import { WIND_GUST_GLSL, windOf } from './grass.js';-import { patchTranslucency } from './finish.js';-import { patchLeafSSS } from './foliage_shade.js';-import { mulberry32 } from './noise.js';-import {- glslLocalDir, glslWob, instancedQuad, keepOutOfDepthPasses, patchStandard,- shadowLike, tickShaders, wobX, wobZ,-} from './shader.js';--const _TAU = Math.PI * 2;-// Rows up a stem: 3 is where the bend of a 30 cm stalk stops faceting.-const _STEM_ROWS = 3;-// The most arc a stem is laid over by, and the largest the gust term-// (0.25 + 1.25 * fbm) * (0.62 + 0.38 * sway) can reach. Both are read-// by the CPU to state a box the shader cannot leave.-const _MAX_BEND = 1.2;-const _PUSH_MAX = 1.19;--/**- * One row per silhouette. These numbers ARE the difference between the- * three flowers: `elev` lifts a petal off the head plane (flat disc,- * upright cup), `spike` spreads the florets DOWN the stem instead of- * gathering them at the tip, and `prof` is the petal's outline.- *- * The colour rows are the OTHER half. A patch needs a spread of petal- * colour or it reads as one moulded part, but that spread has to stay- * inside the species: `sib` is the sibling albedo, stated as an HSL- * offset from whatever petal colour the caller ends up with (so it- * follows `opts.color` too), and `hue` is how far a single plant may- * rotate off the line between them. `astraHueShift` is an RGB-space- * rotation about the grey axis: on a near-primary it drives a channel- * NEGATIVE and the clamp turns the swing into a fork, so a saturated- * kind gets a SMALL rotation and takes its variety from `sib` instead- * (measured: 0.25 rad on the poppy split the field into two lobes,- * amber at 20-40 deg and magenta at 330-355 deg, with nothing between).- */-const _KINDS = {- daisy: {- petals: 13, cols: 1, rows: 3, step: _TAU / 13,- elev: 0.17, curl: -0.12, cup: 0.14, spike: 0,- len: 0.055, wid: 0.022, disc: 0.017, bulge: 0.008,- prof: [2.6, 0.40], blotch: 0,- leaf: [.32,.075,.25],- height: 0.32, petal: 0xdedad0, throat: 0xc9c3a6, disc_: 0xbe8f10,- // Warm cream to a cool paper white: the swing a white flower- // really carries, and safe to rotate because it is barely coloured.- // The cool end drops SATURATION as it turns — a white that keeps- // its saturation across half the wheel is a blue flower.- sib: [0.42, -0.10, 0.015], hue: 0.30,- },- poppy: {- petals: 5, cols: 2, rows: 3, step: _TAU / 5,- elev: 0.74, curl: 0.34, cup: 0.60, spike: 0,- len: 0.060, wid: 0.052, disc: 0.013, bulge: 0.010,- prof: [1.6, 0.60], blotch: 0.8,- leaf: [.32,.065,.60],- height: 0.44, petal: 0xa2200c, throat: 0x4a1208, disc_: 0x2a1e12,- // Scarlet to vermilion, the two ends of a field poppy — WARM, both- // of them. The other way round the wheel is carmine, which the- // pale transmitted lift then carries the rest of the way to pink.- sib: [0.020, 0.02, 0.045], hue: 0.07,- },- lavender: {- petals: 34, cols: 1, rows: 1, step: 2.39996,- elev: 1.00, curl: 0.10, cup: 0.30, spike: 0.30,- len: 0.026, wid: 0.019, disc: 0, bulge: 0,- prof: [2.0, 0.50], blotch: 0,- leaf: [.22,.025,.64],- height: 0.52, petal: 0x8a72c8, throat: 0xa696d6, disc_: 0x6a5aa8,- sib: [-0.035, 0.10, -0.10], hue: 0.16,- },-};--/** The sibling albedo a kind spreads toward, from the caller's own. */-function siblingOf(color, kind) {- return color.clone().offsetHSL(kind.sib[0], kind.sib[1], kind.sib[2]);-}--/**- * A patch of flowering plants, rooted on the caller's ground.- *- * Buys the one thing a green meadow is missing: colour that stands- * ABOVE the grass line and moves with it. Thin double-sided petals- * with translucent rims, a stem that bends on an arc of its own- * length, and a head that nods a beat behind the stem because a head- * is heavy. Every plant differs — height, head size, how far it has- * opened, hue, lean and the jitter of each petal — since a field of- * identical flowers is a texture, not a field.- *- * @param {object} [opts]- * `extent` metres of the square patch's side (default 6, centred on- * the group's origin); `density` plants per square metre (default 9;- * `maxPlants` caps it, default 12000); `height` stem height in metres- * (default per kind, 0.32-0.52, varied per plant); `kind` 'daisy'- * (default, a flat disc of narrow petals round a boss), 'poppy' (a- * deep cup of five broad petals with a dark throat) or 'lavender' (a- * spike of florets running down the stem); `color` petal colour, an- * ALBEDO not a screen colour — a scene sun runs at 5-6, so a hex that- * already looks sunlit tone-maps to paper, and the patch spreads- * ITSELF either side of whatever you pass (each plant sits somewhere- * between it and a sibling the kind states as an HSL offset, then- * leans a few degrees more); `shadows` cast into the shadow map- * (default false — a head is smaller than a shadow texel on a rig- * fitted to a whole scene, so it lands as a block; turn it on for a- * sun rig fitted to the patch); `heightAt` (x, z) => y, the- * caller's ground height (default flat y = 0); `wind` grass.js's- * option in either spelling — a strength multiplier or- * `{dir, strength, speed}` — so one wind moves a scene's grass and its- * flowers together; `seed` PRNG seed (default 7); `sunDir`- * THREE.Vector3 toward the sun, for the light coming THROUGH a petal;- * `name` group name.- * @returns {THREE.Group} Named `Flowers`, holding ONE instanced mesh- * `Plants` whose stated box is the box it occupies at any bend, with- * `userData.update(t)` driving the wind.- */-export function makeFlowers(opts = {}) {- const kind = _KINDS[opts.kind] || _KINDS.daisy;- const extent = Math.max(0.2, opts.extent === undefined ? 6 : opts.extent);- const density = Math.max(0.01,- opts.density === undefined ? 9 : opts.density);- const height = Math.max(0.02,- opts.height === undefined ? kind.height : opts.height);- const maxPlants = opts.maxPlants === undefined ? 12000 : opts.maxPlants;- const seed = opts.seed === undefined ? 7 : opts.seed;- const ground = typeof opts.heightAt === 'function' ? opts.heightAt : null;- const wind = windOf(opts.wind);- const petal = new THREE.Color(- opts.color === undefined ? kind.petal : opts.color);-- const field = plantField(- extent, density, height, kind, wind, ground, seed, maxPlants);- const g = new THREE.Group();- g.name = opts.name || 'Flowers';- g.add(plantMesh(field, kind, extent, petal, wind, opts.sunDir,- opts.shadows === true));- g.userData.update = g.userData.tick = (t) => tickShaders(g, t);- return attachDisposal(g, snapshotResources(g));-}--/**- * Plant the patch, and state what it can reach.- *- * Reach is computed from the SAME arc the vertex shader draws, at the- * largest bend the gust term can produce, so the stated box holds at- * every t rather than at t = 0.- */-function plantField(extent, density, height, kind, wind, ground, seed,- maxPlants) {- const want = Math.max(- 1, Math.min(Math.round(density * extent * extent), maxPlants));- const cells = Math.max(1, Math.round(Math.sqrt(want)));- const step = extent / cells;- const rand = mulberry32(seed);- const pos = [], shape = [], bend = [], vary = [];- let n = 0, reach = 0, low = Infinity, high = -Infinity;- for (let iz = 0; iz < cells && n < maxPlants; iz++) {- for (let ix = 0; ix < cells && n < maxPlants; ix++) {- const x = -extent / 2 + (ix + rand()) * step;- const z = -extent / 2 + (iz + rand()) * step;- const y = ground ? ground(x, z) : 0;- const h = height * (0.62 + 0.7 * rand());- // Head size, and how far this one has OPENED: a patch where every- // bloom is at full spread reads as plastic.- const hs = 0.8 + 0.55 * rand();- const open = 0.55 + 0.7 * rand();- const stiff = (0.7 + 0.6 * rand()) * (0.55 + 0.6 * h / height);- const lean = 0.05 + 0.16 * rand();- pos.push(x, y, z);- shape.push(h, height * (0.011 + 0.006 * rand()), hs, open);- bend.push(wind.amp * stiff, rand() * _TAU, lean, rand() * _TAU);- vary.push((rand() - 0.5) * kind.hue, rand() * _TAU, rand(),- 0.82 + 0.32 * rand());- const k = Math.min(_MAX_BEND, lean + wind.amp * stiff * _PUSH_MAX);- const head = headReach(kind, hs);- reach = Math.max(reach, h * (1 - Math.cos(k)) / k + Math.max(head,h*.40));- low = Math.min(low, y);- high = Math.max(high, y + h + head);- n++;- }- }- return { n, pos, shape, bend, vary, reach,- low: n ? low : 0, high: n ? high : 0 };-}--/** How far a head of scale `hs` sticks out past the stem's tip. */-function headReach(kind, hs) {- const s = hs * 1.25;- return Math.max(- kind.disc * hs + kind.len * s * (1 + Math.abs(kind.curl))- + kind.wid * s * (1 + Math.abs(kind.cup)),- kind.disc * s * 1.5 + kind.bulge * s);-}--/**- * One plant as base geometry: a stem strip, its petals, its boss.- *- * Every copy is built in the vertex shader from `aCorner` and `aPart`- * (which part, which petal, how many), so the KIND lives in the layout- * and in uniforms — never in the GLSL, which one program serves for- * all three. `position` stays at zero for the GTAO reason- * `instancedQuad` documents.- */-function plantLattice(kind, count) {- const pieces = [];- const stem = new THREE.PlaneGeometry(1, 1, 1, _STEM_ROWS);- stem.translate(0, 0.5, 0);- pieces.push([stem, 0, 0, 1]);- for (let i = 0; i < kind.petals; i++) {- pieces.push([new THREE.PlaneGeometry(1, 1, kind.cols, kind.rows),- 1, i, kind.petals]);- }- for(let i=0;i<6;i++) pieces.push([new THREE.PlaneGeometry(1,1,2,6),3,i,6]);- if (kind.disc > 0) pieces.push([new THREE.PlaneGeometry(1, 1), 2, 0, 1]);-- let nv = 0, ni = 0;- for (const [geo] of pieces) {- nv += geo.attributes.position.count;- ni += geo.index.count;- }- const corner = new Float32Array(nv * 3);- const normal = new Float32Array(nv * 3);- const part = new Float32Array(nv * 3);- const index = new Uint16Array(ni);- let v = 0, i = 0;- for (const [geo, id, idx, total] of pieces) {- const p = geo.attributes.position.array;- const nm = geo.attributes.normal.array;- for (let k = 0; k < geo.index.count; k++) {- index[i++] = geo.index.array[k] + v;- }- for (let k = 0; k < geo.attributes.position.count; k++) {- corner.set([p[k * 3], p[k * 3 + 1], p[k * 3 + 2]], (v + k) * 3);- normal.set([nm[k * 3], nm[k * 3 + 1], nm[k * 3 + 2]], (v + k) * 3);- part.set([id, idx, total], (v + k) * 3);- }- v += geo.attributes.position.count;- }-- const g = new THREE.InstancedBufferGeometry();- g.setIndex(new THREE.BufferAttribute(index, 1));- g.setAttribute('position', new THREE.BufferAttribute(- new Float32Array(nv * 3), 3));- g.setAttribute('aCorner', new THREE.BufferAttribute(corner, 3));- g.setAttribute('aPart', new THREE.BufferAttribute(part, 3));- g.setAttribute('normal', new THREE.BufferAttribute(normal, 3));- g.instanceCount = count;- return g;-}--/** One mesh, one draw call: every plant lives in the vertex shader. */-function plantMesh(field, kind, extent, petal, wind, sunDir,- shadows) {- const geom = plantLattice(kind, field.n);- const inst = (name, arr, size) => geom.setAttribute(- name, new THREE.InstancedBufferAttribute(new Float32Array(arr), size));- inst('iPos', field.pos, 3);- inst('iShape', field.shape, 4);- inst('iBend', field.bend, 4);- inst('iVar', field.vary, 4);- // position is zero, so the derived bounds would be a point at the- // origin: state the box a fully bent patch really occupies.- const half = extent / 2 + field.reach;- geom.boundingBox = new THREE.Box3(- new THREE.Vector3(-half, field.low, -half),- new THREE.Vector3(half, field.high, half));- geom.boundingSphere = geom.boundingBox.getBoundingSphere(new THREE.Sphere());-- const mat = new THREE.MeshStandardMaterial({- color: 0xffffff, roughness: 0.62, metalness: 0,- side: THREE.DoubleSide, transparent: false, alphaTest: 0.5, alphaToCoverage: false,- name: 'FlowerPlant',- });- patchStandard(mat, {- name: 'flowers:plant',- uniforms: {- uFlowWind: { value: wind.dir.clone() },- uFlowSpeed: { value: wind.speed },- uFlowBend: { value: _MAX_BEND },- uFlowNod: { value: 0.22 },- uFlowSpike: { value: kind.spike },- uFlowLeaf: { value: new THREE.Vector3(...kind.leaf) },- uFlowStep: { value: kind.step },- uFlowElev: { value: kind.elev },- uFlowCurl: { value: kind.curl },- uFlowCup: { value: kind.cup },- uFlowSize: { value: new THREE.Vector2(kind.len, kind.wid) },- uFlowDisc: { value: kind.disc },- uFlowBulge: { value: kind.bulge },- uFlowProf: { value: new THREE.Vector2(kind.prof[0], kind.prof[1]) },- uFlowBlotch: { value: kind.blotch },- uFlowPetal: { value: petal.clone() },- uFlowPetalB: { value: siblingOf(petal, kind) },- uFlowThroat: { value: new THREE.Color(kind.throat) },- uFlowDiscCol: { value: new THREE.Color(kind.disc_) },- uFlowStem: { value: new THREE.Color(0x4a6626) },- },- vertexHead: PLANT_VERTEX_HEAD,- vertexBody: PLANT_VERTEX,- fragmentHead: PLANT_FRAGMENT_HEAD,- fragmentBody: PLANT_FRAGMENT,- });- // Thin-petal transmission uses the actual directional radiance and shadow- // visibility. Keep its tint near the petal pigment; generic green variation- // would colour white petals blue and scarlet poppies salmon.- patchLeafSSS(mat, {- sunDir: sunDir, strength: 0.42, power: 2.4, variance: 0,- tint: petal.clone().lerp(new THREE.Color(0xfff2d0), 0.26),- });- // Keep the pigment and bright rim inside a reflectance range. Transmitted- // radiance is separate and remains free to respond to the scene lighting.- patchStandard(mat, {- name: 'flowers:albedoRange',- fragmentBody: ' diffuseColor.rgb = clamp(diffuseColor.rgb, '- + 'vec3(0.015), vec3(0.86));',- });-- const mesh = new THREE.Mesh(geom, mat);- mesh.name = 'Plants';- mesh.receiveShadow = true;- keepOutOfDepthPasses(mesh);- // A meadow's worth of flower heads in the shadow map stamps a hard- // black flower on the ground under each one, which reads as litter- // rather than shade. Opt-in, as grass and wheat already are.- if (!shadows) return mesh;- // The AO guard must not cost the patch its shadow: the shadow pass- // draws through its own hook with our depth material, so casting is- // turned back on AFTER the guard, with the displacement it needs.- shadowLike(mesh, 'flowers:plantDepth', PLANT_VERTEX_HEAD, PLANT_VERTEX, {- fragmentHead: 'uniform vec2 uFlowProf;\nvarying vec4 vFlow;\n' + PLANT_PROFILE,- fragmentBody: PLANT_DEPTH_CUT,- });- return mesh;-}--const PLANT_VERTEX_HEAD = [- 'uniform float uTime;',- 'uniform vec2 uFlowWind;',- 'uniform float uFlowSpeed;',- 'uniform float uFlowBend;',- 'uniform float uFlowNod;',- 'uniform float uFlowSpike;',- 'uniform vec3 uFlowLeaf;',- 'uniform float uFlowStep;',- 'uniform float uFlowElev;',- 'uniform float uFlowCurl;',- 'uniform float uFlowCup;',- 'uniform vec2 uFlowSize;',- 'uniform float uFlowDisc;',- 'uniform float uFlowBulge;',- 'attribute vec3 aCorner;',- 'attribute vec3 aPart;',- 'attribute vec3 iPos;',- 'attribute vec4 iShape;',- 'attribute vec4 iBend;',- 'attribute vec4 iVar;',- 'varying vec4 vFlow;',- 'varying vec3 vFlowVar;',- glslLocalDir('flowLocalDir'), WIND_GUST_GLSL,- // The gust field grass.js rides: streaks running downwind, so a- // scene's meadow and its flowers are pushed by the same air.- 'float flowSway(vec3 root, float ph, float lag) {',- ' vec3 worldRoot = (modelMatrix * vec4(root, 1.0)).xyz;',- ' float t = uTime * uFlowSpeed;',- ' float s = astraWindPhase(worldRoot, ph);',- ' return (sin(t * 1.7 + s - lag)',- ' + 0.35 * sin(t * 2.9 + s * 1.7 - lag)) / 1.35;',- '}',- 'vec2 flowBend(vec3 root, vec4 b) {',- ' vec2 w = flowLocalDir(vec3(uFlowWind.x, 0.0, uFlowWind.y)).xz;',- ' w /= max(length(w), 1e-5);',- ' vec3 worldRoot = (modelMatrix * vec4(root, 1.0)).xyz;',- ' float gust = astraWindGust(worldRoot, uFlowWind,',- ' uTime * uFlowSpeed, vec2(0.055, 0.21));',- ' float push = (0.25 + 1.25 * gust)',- ' * (0.62 + 0.38 * flowSway(root, b.w, 0.0));',- ' return vec2(cos(b.y), sin(b.y)) * b.z + w * (b.x * push);',- '}',- // A circular arc of the stem's own length: a translated tip would- // stretch the stem instead of laying it over.- 'void flowArc(float v, float h, float k, vec2 f, out vec3 p,',- ' out vec3 tn) {',- ' float a = k * v;',- ' float u = h * (1.0 - cos(a)) / k;',- ' p = vec3(f.x * u, h * sin(a) / k, f.y * u);',- ' tn = vec3(f.x * sin(a), cos(a), f.y * sin(a));',- '}',-].join('\n');--const PLANT_VERTEX = [- ' vec3 flRoot = iPos;',- ' vec2 flB = flowBend(flRoot, iBend);',- ' float flL = length(flB);',- ' vec2 flF = flL > 1e-5 ? flB / flL : vec2(1.0, 0.0);',- ' float flK = clamp(flL, 1e-3, uFlowBend);',- ' float flPart = aPart.x;',- // Florets ride DOWN the stem on a spike and gather at the tip on a- // disc or a cup: one uniform, three silhouettes.- ' float flV = flPart < 0.5 ? aCorner.y',- ' : 1.0 - uFlowSpike * (aPart.y / max(aPart.z - 1.0, 1.0));',- ' if (flPart > 2.5) flV = 0.06 + uFlowLeaf.z * aPart.y / 5.0;',- ' vec3 flP, flT;',- ' flowArc(flV, iShape.x, flK, flF, flP, flT);',- ' vec3 flAt = flRoot + flP;',- // hue lean, tone, and where this plant sits between the kind's two- // petal albedos — hashed off the whorl phase so it is decorrelated- // from both of the others and costs no attribute.- ' vFlowVar = vec3(iVar.x, iVar.w, astraHash11(iVar.y * 1.37 + 0.21));',- ' if (flPart > 2.5) {',- ' float lu = aCorner.y + 0.5, lx = aCorner.x * 2.0;',- ' float la = iVar.y + aPart.y * 2.39996;',- ' vec3 ld = vec3(cos(la), 0.0, sin(la));',- ' vec3 ls = vec3(-ld.z, 0.0, ld.x);',- ' float ll = iShape.x * uFlowLeaf.x * (0.8 + 0.35 * iVar.z);',- ' float lp = pow(max(sin(3.14159 * lu), 0.0), 0.7);',- ' float lw = iShape.x * uFlowLeaf.y * lp;',- ' float ly = ll * (0.48 * sin(3.14159 * lu * 0.8) - 0.16 * lu * lu);',- ' transformed = flAt + ld * (ll * lu) + ls * (lx * lw)',- ' + vec3(0.0, ly - abs(lx) * lw * 0.22, 0.0);',- ' vFlow = vec4(3.0, lu, lx, flV);',- '#ifndef FLAT_SHADED',- ' vec3 lt = ld * ll + vec3(0.0, ll * (0.48 * 3.14159 * 0.8',- ' * cos(3.14159 * lu * 0.8) - 0.32 * lu), 0.0);',- ' vNormal = normalize(normalMatrix * normalize(cross(',- ' ls - vec3(0.0, sign(lx) * 0.22, 0.0), lt)));',- '#endif',- ' } else if (flPart < 0.5) {',- ' vec3 flW = (modelMatrix * vec4(flAt, 1.0)).xyz;',- ' vec3 flView = normalize(flowLocalDir(cameraPosition - flW));',- ' vec3 flC = cross(flT, flView);',- ' float flCl = length(flC);',- ' vec3 flSide = flCl > 1e-4 ? flC / flCl : vec3(1.0, 0.0, 0.0);',- ' float flX = aCorner.x * 2.0;',- ' float flWid = iShape.y * (0.55 + 0.45 * sqrt(max(1.0 - flV, 0.0)));',- ' transformed = flAt + flSide * (flX * flWid);',- ' vFlow = vec4(0.0, flV, flX, 0.0);',- '#ifndef FLAT_SHADED',- // The normal of a round stalk, not of a card.- ' vec3 flFace = normalize(cross(flSide, flT));',- ' vNormal = normalize(normalMatrix * normalize(',- ' flFace * sqrt(max(1.0 - flX * flX, 0.04)) + flSide * flX));',- '#endif',- ' } else {',- // The head is heavy, so it nods a beat BEHIND the stem it sits on.- ' vec3 flUp = normalize(flT + flowLocalDir(vec3(uFlowWind.x, 0.0, uFlowWind.y))',- ' * (uFlowNod * flowSway(flRoot, iBend.w, 0.9)));',- ' vec3 flRef = abs(flUp.z) < 0.9 ? vec3(0.0, 0.0, 1.0)',- ' : vec3(1.0, 0.0, 0.0);',- ' vec3 flR = normalize(cross(flUp, flRef));',- ' vec3 flFwd = cross(flR, flUp);',- ' float flJit = astraHash21(vec2(aPart.y, iVar.z));',- ' float flAng = (aPart.y + 0.5) * uFlowStep + iVar.y',- ' + (flJit - 0.5) * 0.45;',- ' vec3 flDir = cos(flAng) * flR + sin(flAng) * flFwd;',- ' vec3 flAx = normalize(cross(flUp, flDir));',- ' float flS = iShape.z * (0.75 + 0.5 * flJit);',- ' if (flPart > 1.5) {',- ' float flD = uFlowDisc * iShape.z * 2.0;',- ' float flQ = (aCorner.x * aCorner.x + aCorner.y * aCorner.y) * 4.0;',- ' transformed = flAt + flR * (aCorner.x * flD)',- ' + flFwd * (aCorner.y * flD)',- ' + flUp * (uFlowBulge * iShape.z * max(1.0 - flQ, 0.0));',- ' vFlow = vec4(2.0, aCorner.y, aCorner.x, 0.0);',- '#ifndef FLAT_SHADED',- // vNormal must match the WINDING, not the intent: three flips it by- // gl_FrontFacing on a double-sided face, so a normal that disagrees- // is turned away from the eye and the face renders unlit.- ' vNormal = normalize(normalMatrix * -flUp);',- '#endif',- ' } else {',- // Lifted off the head plane by its own openness, curled along its- // length and cupped across it: flat disc, deep cup, or floret.- ' float flU = aCorner.y + 0.5;',- ' float flEl = uFlowElev * iShape.w;',- ' vec3 flOut = flDir * cos(flEl) + flUp * sin(flEl);',- ' float flLen = uFlowSize.x * flS;',- ' float flWid = uFlowSize.y * flS;',- ' vec3 flDu = flOut * flLen',- ' + flUp * (2.0 * uFlowCurl * flU * flLen);',- ' vec3 flDs = flAx * flWid',- ' + flUp * (2.0 * uFlowCup * aCorner.x * flWid);',- // Petals start at the RIM of the boss, or thirteen of them bury the- // one part of a daisy that says daisy.- ' transformed = flAt + flOut * (uFlowDisc * iShape.z)',- ' + flOut * (flU * flLen)',- ' + flUp * (uFlowCurl * flU * flU * flLen)',- ' + flAx * (aCorner.x * flWid)',- ' + flUp * (uFlowCup * aCorner.x * aCorner.x * flWid);',- ' vFlow = vec4(1.0, flU, aCorner.x * 2.0, flJit);',- '#ifndef FLAT_SHADED',- ' vNormal = normalize(normalMatrix * normalize(cross(flDs, flDu)));',- '#endif',- ' }',- ' }',-].join('\n');--// Half-width of a petal at u along it. (p, q) is the whole outline:-// p toward 3 gives parallel sides with round ends, q under 0.5 a-// blunt tip, both together a broad fan. Shared with the depth pass,-// which cuts the shadow by the same curve.-const PLANT_PROFILE = [- 'float flowProfile(float u, vec2 pq) {',- ' return pow(max(1.0 - pow(abs(2.0 * u - 1.0), pq.x), 0.0), pq.y);',- '}',-].join('\n');--// The colour pass discards outside the petal and inside nothing else;-// this is that test with the shading taken out.-//-// What this CANNOT fix is a shadow texel wider than the flower: the-// default `sunRig` fits its frustum to a 150 m scene, which is 7 cm a-// texel at 4096, and a daisy head is 5 cm. At that ratio every kind of-// flower casts the same one-texel slate block whatever shape it really-// is, which is why `shadows` is opt-in and why the honest place to turn-// it on is a scene whose sun rig is fitted to the patch (`bounds: 12`-// puts six texels across a head, measured below).-const PLANT_DEPTH_CUT = [- ' if (vFlow.x > 1.5 && vFlow.x < 2.5) {',- ' if (length(vec2(vFlow.y, vFlow.z)) * 2.0 > 1.0) discard;',- ' } else if (vFlow.x > 0.5 && vFlow.x < 1.5) {',- ' if (abs(vFlow.z) > flowProfile(vFlow.y, uFlowProf)) discard;',- ' }',-].join('\n');--const PLANT_FRAGMENT_HEAD = [- 'uniform vec2 uFlowProf;',- 'uniform float uFlowBlotch;',- 'uniform vec3 uFlowPetal;',- 'uniform vec3 uFlowPetalB;',- 'uniform vec3 uFlowThroat;',- 'uniform vec3 uFlowDiscCol;',- 'uniform vec3 uFlowStem;',- 'varying vec4 vFlow;',- 'varying vec3 vFlowVar;',- PLANT_PROFILE,-].join('\n');--const PLANT_FRAGMENT = [- ' vec3 flCol;',- ' float flA = 1.0;',- ' if (vFlow.x > 2.5) {',- ' flCol = uFlowStem * (0.82 + 0.32 * vFlowVar.z);',- ' flCol *= 1.0 - 0.15 * exp(-abs(vFlow.z) * 20.0);',- ' flCol *= 0.96 + 0.04 * sin(vFlow.y * 54.0 + abs(vFlow.z) * 8.0);',- ' flCol = mix(flCol, flCol * vec3(1.45, 1.05, 0.62),',- ' smoothstep(0.6, 1.0, vFlow.y) * smoothstep(0.6, 1.0, vFlowVar.z));',- ' } else if (vFlow.x < 0.5) {',- // A patch is DEEP: the foot of a stem sits in its neighbours' shade.- ' flCol = uFlowStem * (0.42 + 0.58 * smoothstep(0.0, 0.5, vFlow.y));',- ' flCol *= 0.93 + 0.14 * astraNoise2(vec2(vFlow.y * 40.0, 3.0));',- // Green is the one hue a hue ROTATION cannot vary safely (it is the- // channel that would go negative), and a saturated kind rotates- // barely at all: this is the stem's own yellow-green to blue-green- // swing, on the same per-plant number the petals mix by.- ' flCol *= mix(vec3(1.10, 1.0, 0.84), vec3(0.88, 1.0, 1.10),',- ' vFlowVar.z);',- ' } else if (vFlow.x > 1.5) {',- ' float flR = length(vec2(vFlow.y, vFlow.z)) * 2.0;',- ' if (flR > 1.0) discard;',- // A boss is packed with florets, and darker at its heart.- ' flCol = uFlowDiscCol * (0.72 + 0.5 * astraNoise2(',- ' vec2(vFlow.y, vFlow.z) * 90.0));',- ' flCol *= 0.55 + 0.45 * smoothstep(0.15, 0.85, flR);',- ' } else {',- ' float flW = flowProfile(vFlow.y, uFlowProf);',- ' float flD = abs(vFlow.z) / max(flW, 1e-3);',- ' float flAa = max(fwidth(flD), 0.02);',- ' float flM = 1.0 - smoothstep(1.0 - flAa, 1.0 + flAa, flD);',- ' if (flM < 0.02) discard;',- // The rim of a petal is one cell thick: it passes light rather than- // reflecting it, so it grows paler. Alpha supplies silhouette coverage.- ' float flCore = 1.0 - smoothstep(0.45, 1.0, flD);',- ' flA = flM;',- // This plant's own place between the kind's two petal albedos, and- // THEN the throat: the gradient into the centre belongs to the- // flower actually being drawn, not to the row in the table.- ' vec3 flPet = mix(uFlowPetal, uFlowPetalB, vFlowVar.z);',- ' flCol = mix(uFlowThroat, flPet, smoothstep(0.0, 0.45, vFlow.y));',- ' flCol *= 1.0 + 0.25 * (1.0 - flCore);',- // Veins run out from the base, and the throat of a poppy is a- // blotch rather than a gradient — a deep bruise of the petal's own- // colour, never a hole punched through it.- ' flCol *= 0.94 + 0.13 * astraStroke(vFlow.z * 2.5, 0.22);',- ' flCol = mix(flCol, max(uFlowThroat * 0.42, vec3(0.02)),',- ' uFlowBlotch * (1.0 - smoothstep(0.02, 0.34, vFlow.y)));',- // Petal to petal inside ONE head: a little tone, and a little warm- // to cool with it, because a head is a cup whose near side is lit by- // the sun and whose far side is lit by the sky.- ' flCol *= 0.88 + 0.24 * vFlow.w;',- ' flCol *= mix(vec3(1.035, 1.0, 0.955), vec3(0.965, 1.0, 1.045),',- ' vFlow.w);',- ' }',- // Clamped at zero: astraHueShift is a rotation in RGB, and on a- // saturated albedo it drives the small channels NEGATIVE. Left to run- // on through the multiply, half a poppy field comes back magenta.- ' flCol = max(astraHueShift(flCol, vFlowVar.x), vec3(0.0)) * vFlowVar.y;',- ' diffuseColor.rgb = flCol;',- ' diffuseColor.a *= flA;',-].join('\n');--/**- * One row per falling kind: how it is shaped and how it comes down.- * A leaf is longer, heavier and tumbles faster than a petal, which- * hangs in the air and slides much further sideways per metre fallen.- */-const _FALL_KINDS = {- petal: {- size: 0.030, aspect: 0.72, fall: 0.42, spin: 1.6, wob: 0.42,- curl: 0.22, prof: [2.4, 0.52], notch: 0.55, vein: 0.06, hue: 0.15,- color: 0xe8b3c0, sib: [-0.045, 0.10, -0.08],- },- leaf: {- size: 0.075, aspect: 0.46, fall: 0.85, spin: 2.8, wob: 0.30,- curl: 0.38, prof: [1.9, 0.55], notch: 0, vein: 0.22, hue: 0.22,- color: 0xb0641c, sib: [-0.040, 0.05, -0.09],- },-};--// The slide: `wobX`/`wobZ` on the CPU mirror, the same pair in GLSL.-const _FALL_WOB_GLSL = glslWob('flowFallWob');--/** Wrap v into [-lim, lim), the CPU mirror of GLSL mod(). */-function _wrap(v, lim) {- return v - Math.floor((v + lim) / (2 * lim)) * 2 * lim;-}--/**- * Leaves or petals drifting DOWN through the air.- *- * This is the cue that says autumn, or a cherry in bloom: the air- * itself carrying something. A leaf does not fall straight, so no two- * come down alike — each has its own fall rate, its own tumble about- * its own axis (which turns it edge-on and back, the flicker that- * reads as a leaf) and its own sideways slide, a curve that goes- * nowhere in particular while the wind carries the whole field- * downwind.- *- * The field WRAPS inside the volume it advertises — `extent` square,- * `height` tall, its foot on y = 0 — so it never leaves the box it- * states, and the box is what three culls it by.- *- * @param {object} [opts]- * `extent` metres square the field covers (default 8); `height`- * metres it stands (default 5); `count` pieces in the air (default- * 240 — one draw call regardless); `kind` 'petal' (default, small,- * slow, notched at the tip, sliding far) or 'leaf' (longer, heavier,- * tumbling faster); `size` length in metres (default 0.030 petal /- * 0.075 leaf); `color` albedo, not a screen colour, and spread either- * side of itself per piece the way the planted patch spreads its- * petals; `wind` grass.js's- * option in either spelling, so the drift matches the meadow's gusts;- * `seed` PRNG seed (default 13); `name` group name. The light coming- * THROUGH a piece is read from the scene's OWN lights, so there is no- * sun to state and nothing to keep in step.- * @returns {THREE.Group} Named `Falling`, holding ONE instanced mesh- * `Drift`, with `userData.update(t)` advancing the fall and- * `userData.sample(i, t)` giving piece i's group-local position — the- * CPU mirror of the vertex shader.- */-export function makeFalling(opts = {}) {- const kind = _FALL_KINDS[opts.kind] || _FALL_KINDS.petal;- const extent = Math.max(0.5, opts.extent === undefined ? 8 : opts.extent);- const height = Math.max(0.3, opts.height === undefined ? 5 : opts.height);- const count = Math.max(1, Math.round(- opts.count === undefined ? 240 : opts.count));- const size = Math.max(0.002, opts.size === undefined ? kind.size : opts.size);- const seed = opts.seed === undefined ? 13 : opts.seed;- const wind = windOf(opts.wind);- const color = new THREE.Color(- opts.color === undefined ? kind.color : opts.color);- // grass.js states wind as radians of tip bend; a metre per second of- // downwind drift per 0.5 of it is a breeze that matches that sway.- const drift = wind.dir.clone().multiplyScalar(2 * wind.amp);- const wob = kind.wob * size / kind.size;- const fall = kind.fall;-- const rand = mulberry32(seed);- const pos = new Float32Array(count * 3);- const fal = new Float32Array(count * 4);- const axis = new Float32Array(count * 3);- const swing = new Float32Array(count * 4);- const vary = new Float32Array(count * 2);- // Half the quad's own diagonal, plus the widest slide, is the room- // the wrap has to leave so the field cannot cross its own box.- const span = 0.5 * size * (1 + kind.aspect) * 1.35;- const lim = Math.max(1e-3, extent / 2 - span - wob);- const drop = Math.max(1e-3, height - 2 * span);- for (let i = 0; i < count; i++) {- pos[i * 3] = (rand() * 2 - 1) * lim;- pos[i * 3 + 1] = rand() * drop;- pos[i * 3 + 2] = (rand() * 2 - 1) * lim;- // Its own fall rate, its own tumble: a field that comes down at- // one speed reads as a sheet of confetti.- fal[i * 4] = 0.62 + 0.76 * rand();- fal[i * 4 + 1] = 0.75 + 0.55 * rand();- fal[i * 4 + 2] = (rand() < 0.5 ? -1 : 1) * (0.5 + rand());- fal[i * 4 + 3] = rand() * _TAU;- const a = rand() * _TAU;- const y = rand() * 1.4 - 0.7;- const r = Math.sqrt(Math.max(1 - y * y, 0));- axis[i * 3] = Math.cos(a) * r;- axis[i * 3 + 1] = y;- axis[i * 3 + 2] = Math.sin(a) * r;- swing[i * 4] = 0.5 + 1.1 * rand();- swing[i * 4 + 1] = rand() * _TAU;- swing[i * 4 + 2] = 0.5 + 1.1 * rand();- swing[i * 4 + 3] = rand() * _TAU;- vary[i * 2] = (rand() - 0.5) * kind.hue;- vary[i * 2 + 1] = 0.72 + 0.5 * rand();- }-- // The REAL radius: `position` is all zeros, so this sphere is the- // only thing three can cull the field by, and the box below is the- // same volume stated the way the asset census reads it.- const radius = 0.5 * Math.sqrt(2 * extent * extent + height * height);- const geom = instancedQuad(count, 1, 1, radius);- geom.setAttribute('aPos', new THREE.InstancedBufferAttribute(pos, 3));- geom.setAttribute('aFall', new THREE.InstancedBufferAttribute(fal, 4));- geom.setAttribute('aAxis', new THREE.InstancedBufferAttribute(axis, 3));- geom.setAttribute('aWob', new THREE.InstancedBufferAttribute(swing, 4));- geom.setAttribute('aVar', new THREE.InstancedBufferAttribute(vary, 2));- // instancedQuad ships no `normal`, and a zero one NaNs through the- // shadow-bias path of every lit material; the shader overwrites it.- geom.setAttribute('normal', new THREE.PlaneGeometry(1, 1).attributes.normal);- geom.boundingBox = new THREE.Box3(- new THREE.Vector3(-extent / 2, 0, -extent / 2),- new THREE.Vector3(extent / 2, height, extent / 2));- geom.boundingSphere = geom.boundingBox.getBoundingSphere(new THREE.Sphere());-- const mesh = new THREE.Mesh(geom, fallMaterial({- kind, size, color, drift, wob, fall, lim, drop, span,- }));- mesh.name = 'Drift';- mesh.renderOrder = 3;- const g = new THREE.Group();- g.name = opts.name || 'Falling';- g.add(keepOutOfDepthPasses(mesh));- g.userData.update = g.userData.tick = (t) => tickShaders(g, t);- const driftFrame = new THREE.Matrix3(), localDrift = new THREE.Vector3();- g.userData.sample = (i, t) => {- // Match fallLocalDir's inverse linear map and singular cutoff, even- // when a caller changes an ancestor before the next render.- mesh.updateWorldMatrix(true, false);- driftFrame.setFromMatrix4(mesh.matrixWorld);- const m = driftFrame.elements;- const magnitude = Math.hypot(m[0], m[1], m[2])- * Math.hypot(m[3], m[4], m[5]) * Math.hypot(m[6], m[7], m[8]);- if (Math.abs(driftFrame.determinant()) <= Math.max(magnitude * 1e-7, 1e-30)) {- localDrift.set(0, 0, 0);- } else {- localDrift.set(drift.x, 0, drift.y).applyMatrix3(driftFrame.invert());- }- const k = Math.min(count - 1, Math.max(0, i | 0));- const y = (pos[k * 3 + 1] - fall * fal[k * 4] * t) % drop;- return new THREE.Vector3(- _wrap(pos[k * 3] + localDrift.x * t, lim)- + wob * wobX(swing[k * 4], swing[k * 4 + 1], t),- (y < 0 ? y + drop : y) + span,- _wrap(pos[k * 3 + 2] + localDrift.z * t, lim)- + wob * wobZ(swing[k * 4 + 2], swing[k * 4 + 3], t))- .applyMatrix4(mesh.matrix); // Piece center in the advertised group frame.- };- return attachDisposal(g, snapshotResources(g));-}--/** Fall, tumble, slide and silhouette — all of it in GLSL. */-function fallMaterial(cfg) {- const mat = new THREE.MeshStandardMaterial({- color: 0xffffff, roughness: 0.68, metalness: 0,- side: THREE.DoubleSide, transparent: false, alphaTest: 0.5, alphaToCoverage: false,- name: 'FallingLeaf',- });- // FIRST, so this patch's body runs after it and can hand it the- // world normal: a piece in the air takes every attitude, and the- // half turned away from the sun is exactly the half lit THROUGH.- // A piece in the air is nearly always seen against the SKY, and a- // thin backlit petal against a bright sky is the one thing that has- // to glow or it reads as a speck of dirt on the lens — measured- // here: at 0.9/3 the drift over the horizon came back tan-brown at- // half the sky's luminance. A wider lobe (lower power) is what puts- // the light back into the pieces that are only half turned away.- patchTranslucency(mat, {- thickness: 0.0004, strength: 1.35, power: 2.2,- color: cfg.color.clone().lerp(new THREE.Color(0xfff2d0), 0.5),- });- patchStandard(mat, {- name: 'flowers:fall',- uniforms: {- uFallDrift: { value: cfg.drift.clone() },- uFallRate: { value: cfg.fall },- uFallSize: { value: new THREE.Vector2(- cfg.size * cfg.kind.aspect, cfg.size) },- uFallSpin: { value: cfg.kind.spin },- uFallCurl: { value: cfg.kind.curl },- uFallWob: { value: cfg.wob },- uFallLim: { value: cfg.lim },- uFallDrop: { value: cfg.drop },- uFallFoot: { value: cfg.span },- uFallProf: { value: new THREE.Vector2(- cfg.kind.prof[0], cfg.kind.prof[1]) },- uFallNotch: { value: cfg.kind.notch },- uFallVein: { value: cfg.kind.vein },- uFallColor: { value: cfg.color.clone() },- uFallColorB: { value: siblingOf(cfg.color, cfg.kind) },- },- vertexHead: FALL_VERTEX_HEAD,- vertexBody: FALL_VERTEX,- fragmentHead: FALL_FRAGMENT_HEAD,- fragmentBody: FALL_FRAGMENT,- });- return mat;-}--const FALL_VERTEX_HEAD = [- 'uniform float uTime;',- 'uniform vec2 uFallDrift;',- 'uniform float uFallRate;',- 'uniform vec2 uFallSize;',- 'uniform float uFallSpin;',- 'uniform float uFallCurl;',- 'uniform float uFallWob;',- 'uniform float uFallLim;',- 'uniform float uFallDrop;',- 'uniform float uFallFoot;',- 'attribute vec3 aCorner;',- 'attribute vec3 aPos;',- 'attribute vec4 aFall;',- 'attribute vec3 aAxis;',- 'attribute vec4 aWob;',- 'attribute vec2 aVar;',- 'varying vec4 vFall;',- 'varying vec3 vFallVar;',- // finish.js's shared world pair. Its own vertex body reads the- // `normal` ATTRIBUTE, which for geometry built in the vertex shader- // is a constant — so this patch runs last and supplies the truth.- 'varying vec3 vAstraWorld;',- 'varying vec3 vAstraWorldN;',- _FALL_WOB_GLSL, glslLocalDir('fallLocalDir'),-].join('\n');--const FALL_VERTEX = [- ' vec2 flW = vec2(flowFallWobX(aWob.x, aWob.y, uTime),',- ' flowFallWobZ(aWob.z, aWob.w, uTime));',- // Every piece wraps inside the stated box: its own fall rate down,- // the shared wind across, its own slide on top of that.- ' float flY = mod(aPos.y - uFallRate * aFall.x * uTime, uFallDrop);',- ' vec2 flDrift = fallLocalDir(vec3(uFallDrift.x, 0.0, uFallDrift.y)).xz;',- ' vec2 flXZ = mod(aPos.xz + flDrift * uTime + uFallLim,',- ' 2.0 * uFallLim) - uFallLim + uFallWob * flW;',- ' vec3 flP = vec3(flXZ.x, flY + uFallFoot, flXZ.y);',- // The tumble axis lies IN the leaf, so the face turns edge-on and- // back once a turn — that flicker is what reads as falling.- ' vec3 flA = normalize(aAxis + 0.3 * vec3(flW.x, 0.0, flW.y));',- ' vec3 flRef = abs(flA.y) < 0.9 ? vec3(0.0, 1.0, 0.0)',- ' : vec3(1.0, 0.0, 0.0);',- ' vec3 flE1 = normalize(cross(flA, flRef));',- ' vec3 flE2 = cross(flA, flE1);',- ' float flAng = uFallSpin * aFall.z * uTime + aFall.w;',- ' vec3 flX = flE1 * cos(flAng) + flE2 * sin(flAng);',- ' vec2 flS = uFallSize * aFall.y;',- // A dry leaf is CURVED across its width, so its shading is a- // gradient: flat cards turned from the sun read as black confetti.- ' vec3 flN = cross(flA, flX);',- ' transformed = flP + flX * (aCorner.x * flS.x)',- ' + flA * (aCorner.y * flS.y)',- ' + flN * (uFallCurl * aCorner.x * aCorner.x * flS.x);',- ' vFall = vec4(uv, aFall.y, 0.0);',- // hue lean, tone, and where this piece sits between the kind's two- // albedos — hashed off its own slide phase, so no attribute grows.- ' vFallVar = vec3(aVar, astraHash11(aWob.y * 1.37 + 0.21));',- ' vec3 flNc = normalize(flN - 2.0 * uFallCurl * aCorner.x * flX);',- ' vAstraWorld = (modelMatrix * vec4(transformed, 1.0)).xyz;',- ' vAstraWorldN = normalize((modelMatrix * vec4(flNc, 0.0)).xyz);',- '#ifndef FLAT_SHADED',- // The quad's own winding, y cross x: three flips this by- // gl_FrontFacing, so the opposite sign leaves half the field unlit.- ' vNormal = normalize(normalMatrix * flNc);',- '#endif',-].join('\n');--const FALL_FRAGMENT_HEAD = [- 'uniform vec2 uFallProf;',- 'uniform float uFallNotch;',- 'uniform float uFallVein;',- 'uniform vec3 uFallColor;',- 'uniform vec3 uFallColorB;',- 'varying vec4 vFall;',- 'varying vec3 vFallVar;',- 'float flowFallProfile(float u, vec2 pq) {',- ' return pow(max(1.0 - pow(abs(2.0 * u - 1.0), pq.x), 0.0), pq.y);',- '}',-].join('\n');--const FALL_FRAGMENT = [- ' float flU = vFall.y;',- ' float flX = vFall.x * 2.0 - 1.0;',- ' float flW = flowFallProfile(flU, uFallProf);',- // A cherry petal is notched at its tip; a leaf runs to a point.- ' flW -= uFallNotch * flW',- ' * (1.0 - smoothstep(0.0, 0.30, length(vec2(flX, flU - 1.0))));',- ' float flD = abs(flX) / max(flW, 1e-3);',- ' float flAa = max(fwidth(flD), 0.03);',- ' float flM = 1.0 - smoothstep(1.0 - flAa, 1.0 + flAa, flD);',- ' if (flM < 0.02) discard;',- // Thin at the rim: it passes light instead of reflecting it, so the- // edge grows paler; alpha is clipped coverage rather than blended glass.- ' float flCore = 1.0 - smoothstep(0.4, 1.0, flD);',- // Its own place between the kind's two albedos first, then a SMALL- // rotation clamped at zero: on a rust leaf a wide rotation drives- // blue negative one way and green the other, and the field forks into- // olive and pink instead of running through the browns between them.- ' vec3 flCol = mix(uFallColor, uFallColorB, vFallVar.z);',- ' flCol = max(astraHueShift(flCol, vFallVar.x), vec3(0.0)) * vFallVar.y;',- ' flCol *= 1.0 + 0.45 * (1.0 - flCore);',- ' flCol *= 1.0 - uFallVein * (1.0 - smoothstep(0.0, 0.09, abs(flX)))',- ' * smoothstep(0.02, 0.2, flU);',- ' flCol *= 0.93 + 0.12 * astraStroke(flU * 6.0, 0.24);',- // The rim brightening and the tone jitter both multiply, and an- // albedo over 1 is a piece with no shading left on it: the tone map- // pins every pixel of it to the same white.- ' diffuseColor.rgb = min(flCol, vec3(0.86));',- ' diffuseColor.a *= flM * (0.42 + 0.58 * flCore);',-].join('\n');diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/godrays.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/godrays.jsdeleted file mode 100644index 74af4857..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/godrays.js+++ /dev/null@@ -1,599 +0,0 @@-/**- * Shafts of light that read as LIGHT, not as glowing cylinders.- *- * A beam is not a surface. What the eye sees is the light scattered- * back out of the air along its line of sight, so the brightness of a- * pixel is the LENGTH OF THE CHORD it cuts through the beam — greatest- * through the core, zero at the silhouette. For a tube that chord is- * exactly |n . v|, which is `astraFacing`, so weighting an additive- * double-sided shell by it turns the shell into its own volume- * integral. Skip that weight and the front and back faces stack at the- * rim into a bright OUTLINE: that outline IS the solid-cylinder look,- * and no amount of colour tuning removes it.- *- * The rest is what stops it reading as geometry. Every shaft shares ONE- * direction, because parallel rays converge on the sun through- * perspective alone and a fanned set converges nowhere. They widen as- * they fall, they are brightest at the gap they came through, their- * striations run ACROSS the beam rather than along it, they hand over- * to a pool of light on the floor instead of stopping at a rim, and- * dust drifts inside them — a beam with nothing in it has no air.- *- * And a beam is not ONE colour. The air that makes it visible is also- * what scatters the blue back out of it, so every part of the effect- * carries two tints: the source hue at the gap and in the core, an AIR- * hue at the far end and at the feathered rim. Both are derived from- * the caller's own `color` (or handed over as `hazeColor`), so a scene- * that tints its sun tints its air with it and nothing here states a- * light colour of its own.- */--import * as THREE from 'three';-import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';-import { attachDisposal, snapshotResources } from './lifecycle.js';--import { lehmer } from './noise.js';-import {- instancedQuad, makeShaderMaterial, sweepProfile, tickShaders, keepOutOfDepthPasses } from './shader.js';--const _UP = new THREE.Vector3(0, 1, 0);--/**- * Build a field of light shafts, their floor pools and their dust.- *- * Encodes the constraint that makes the effect read: the shafts are- * ADDITIVE, volumeless and weighted by `astraFacing`, so they brighten- * whatever is behind them and vanish at their own silhouette. They are- * never opaque, never depth-writing and never vertical — a vertical- * prism of constant width is the shape that reads as a pipe.- *- * @param {object} [opts]- * `count` shafts (default 7); `height` metres from the gap they come- * through down to the floor (default 6); `maxLength` metres a shaft- * may actually run (default `1.6 * height`): the length is the drop- * divided by the slant, so a low sun turns a stated drop into a- * spear several times longer — a shaft cut short fades out in the- * air and throws no floor pool; `width` shaft width where it- * enters (default 0.55 — it lands ~1.4x wider); `spread` metres the- * shafts are spread across (default width * count * 1.7); `sunDir`- * direction the light TRAVELS, THREE.Vector3 or [x,y,z] (default- * [-0.38,-1,-0.26]; a vector aimed AT the sun is flipped, a- * near-horizontal one is tilted until it reaches the floor);- * `ambient` how bright the SURROUNDINGS are, 0 an unlit interior to 1- * open daylight (default 0.85). Added light cannot see what it adds- * to: over a pale backdrop it clips at any visible strength, so at- * 0.35 and above the shafts scatter instead — normal blending, pale,- * low alpha — which lowers the contrast behind them the way a- * daylight shaft does. Scattering is the DEFAULT because a caller- * handed a 0-to-1 range picks the middle, and the middle used to be- * the mode that clips; `color` light colour (default warm daylight);- * `hazeColor` what the AIR scatters back — the far end of every beam,- * the rim, the outside of each pool (default: `color` tilted the way- * Rayleigh tilts it, cooler and paler at the same luminance; pass the- * scene's own sky or fog colour to tie the shafts to it);- * `softness` 0..1 how far the edge feathers into the air (default- * 0.55); `seed` PRNG seed (default 11).- * @returns {THREE.Group} Named `GodRays`, resting on y = 0, with- * `userData.update(t)` driving every shader in it.- */-export function makeGodRays(opts = {}) {- const count = Math.max(1, Math.round(- opts.count === undefined ? 7 : opts.count));- const height = opts.height === undefined ? 6 : opts.height;- const width = opts.width === undefined ? 0.55 : opts.width;- const spread = opts.spread === undefined- ? width * count * 1.7 : opts.spread;- const color = opts.color- ? new THREE.Color(opts.color) : new THREE.Color(0xffeecb);- const air = airColor(color, opts.hazeColor);- const soft = opts.softness === undefined ? 0.55 : opts.softness;- // Added light adds to whatever is behind it, and no shader can read- // that. Measured on one asset: the shafts that read as light in a- // dark room blew 12.8% of a pale frame past 0.97 unchanged. So the- // caller states how bright the surroundings are — 0 an unlit- // interior, 1 open daylight — and the default assumes it was not- // asked, which is the case that failed.- const ambient = Math.min(Math.max(- opts.ambient === undefined ? 0.85 : opts.ambient, 0), 1);- // Dimming does not save it: measured over a pale backdrop, cutting- // the gain 3.6x moved the blown-out area from 12.8% to 11.3%,- // because 0.94 + anything visible still clips. So past this point- // the shafts stop ADDING light and start scattering it — which is- // what a daylight shaft actually does to the contrast behind it.- // Added light only survives a DARK frame, so scattering is- // the default and adding is the exception you ask for. A- // composer handed '0 interior, 1 daylight' picks the middle,- // and the middle used to be the mode that clips.- const hazy = ambient >= 0.35;- // Added light STACKS. The additive gain was tuned on the default- // seven 0.55 m shafts; a nave asking for eight 2.2 m ones adds- // about five times the light through the same air and the frame- // clips — measured, 1.9% of a dark interior blown pure white, and- // the judge called the result "physical beams" rather than light.- // Normalising by the beam load leaves the default untouched and- // damps only the configurations that would clip.- const seed = opts.seed === undefined ? 11 : opts.seed;-- const dir = slantDir(opts.sunDir);- const side = new THREE.Vector3().crossVectors(_UP, dir);- if (side.lengthSq() < 1e-8) side.set(1, 0, 0);- side.normalize();- // In the slant plane and across it: the only frame in which a- // section keeps a fixed width whatever the sun's azimuth is.- const perp = new THREE.Vector3().crossVectors(dir, side).normalize();- const run = new THREE.Vector3(dir.x, 0, dir.z);- const runLen = run.length();- if (runLen > 1e-6) run.divideScalar(runLen); else run.set(0, 0, 1);-- const rnd = lehmer(seed);- const shafts = [];- const drop = height / -dir.y;- // A shaft's LENGTH is the drop divided by the slant, so a low sun- // turns a stated 32 m into a 103 m spear across the whole scene:- // measured on a delivered gorge at an 18 deg sun, where the judge- // called them "disproportionately massive" solid meshes. The drop- // is what the caller stated; the drawn length is capped, and a- // shaft cut short simply fades out in the air.- const maxLen = opts.maxLength === undefined- ? height * 1.6- : Math.max(opts.maxLength, height * 0.5);-- // Length counts as much as width: the light a shaft adds is the- // screen area it covers, and a 35 m shaft puts nearly four times- // what a 9 m one does through the same air. Reference is the- // default seven 0.55 m shafts at their own capped length.- const slantLen = Math.min(- maxLen, height / Math.max(0.15, Math.abs(dir.y)));- const beam = (count * width * slantLen) / (7 * 0.55 * 1.6 * 6);- const load = Math.pow(Math.max(1, beam), 0.75);- // The hazy branch was a FLAT gain, so outdoors — where ambient is- // always high — nothing was ever damped: four 35 m shafts came out- // as solid white wedges across the frame.- const gain = (hazy ? 0.34 : 0.62 * (1 - 0.5 * ambient)) / load;- // The pools and the dust are added light too, and only the SHAFTS- // were ever taught what a bright frame costs. Measured on the eight- // 2.2 m outdoor rig the shafts had already been fixed for: the dust- // came out as white bokeh balls hanging in the SKY and the pools as- // blown discs on sunlit dirt — 0.21% of the frame past 0.97, all of- // it from these two. Both are additive marks laid ON a background,- // so what clips them is how bright that background already is; the- // load enters at its square root, because a heavier rig multiplies- // how MANY marks there are far more than it stacks them.- const spread_ = Math.sqrt(load);- const poolAmp = (hazy ? 0.62 : 1) / spread_;- const moteAmp = (hazy ? 0.55 : 1) / spread_;- for (let i = 0; i < count; i++) {- const u = count === 1 ? 0 : (i / (count - 1)) * 2 - 1;- const rTop = width * 0.5 * (0.68 + 0.64 * rnd());- const flare = 1.28 + 0.34 * rnd();- const ratio = 1.0 + 0.45 * rnd();- const roll = rnd() * Math.PI;- const cs = Math.cos(roll), sn = Math.sin(roll);- const b1 = side.clone().multiplyScalar(cs)- .addScaledVector(perp, sn);- const b2 = side.clone().multiplyScalar(-sn)- .addScaledVector(perp, cs);- // Land the LOWEST vertex of the last section on y = 0 exactly,- // so the group rests on the floor it lights.- const kY = Math.abs(perp.y)- * Math.sqrt(ratio * ratio * sn * sn + cs * cs);- const yEnd = rTop * flare * kY;- const full = (height - yEnd) / -dir.y;- const len = Math.min(full, maxLen);- // Only a shaft that still reaches the floor throws a pool.- const lands = len >= full - 1e-6;- const top = new THREE.Vector3(0, height, 0)- .addScaledVector(side, u * spread * 0.5- + (rnd() - 0.5) * spread * 0.5 / count)- .addScaledVector(run, (rnd() - 0.4) * spread * 0.16- - runLen * drop * 0.5);- shafts.push({ top, len, rTop, flare, ratio, b1, b2, lands });- }-- const g = new THREE.Group();- g.name = 'GodRays';- g.add(shaftMesh(shafts, dir, color, air, soft, gain, hazy));- const landed = shafts.filter((s) => s.lands);- if (landed.length) {- g.add(poolMesh(landed, dir, run, side, color, air, poolAmp));- }- g.add(moteMesh(shafts, dir, side, perp, width, color, air,- moteAmp, seed));- g.userData.update = g.userData.tick = (t) => tickShaders(g, t);- return attachDisposal(keepOutOfDepthPasses(g), snapshotResources(g));-}--/**- * What the AIR gives back, derived from the light it is lit by.- *- * Not a stated blue: a hardcoded haze colour under a red sun is a beam- * whose far end disagrees with its own scene. Scattering takes the long- * wavelengths out and puts the short ones back, which is a MULTIPLIER- * on the source, and renormalising to the source luminance keeps it a- * change of hue rather than a second, dimmer lamp. Hue interpolation- * would have to cross green to get from a warm sun to a cool sky; this- * crosses white, which is where the real transition goes.- */-function airColor(c, over) {- if (over) return new THREE.Color(over);- const a = c.clone().multiply(new THREE.Color(0.80, 0.95, 1.20));- const lum = (x) => 0.2126 * x.r + 0.7152 * x.g + 0.0722 * x.b;- const k = lum(c) / Math.max(lum(a), 1e-4);- return a.multiplyScalar(Math.min(k, 4));-}--/** Where the light travels: downward, and steeply enough to land. */-function slantDir(v) {- const d = Array.isArray(v)- ? new THREE.Vector3(v[0], v[1], v[2])- : (v && v.isVector3 ? v.clone() : new THREE.Vector3(-0.38, -1, -0.26));- if (d.lengthSq() < 1e-8) d.set(-0.38, -1, -0.26);- d.normalize();- if (d.y > 0) d.negate();- if (d.y > -0.25) { d.y = -0.25; d.normalize(); }- return d;-}--/**- * How far the field reaches from the group's own origin.- *- * The instanced lattices keep `position` at zero for the GTAO override,- * so three's own bounding sphere would be a point; culling reads the- * sphere, and a point at the origin culls the whole field the moment- * the origin leaves frame. This states the real extent instead.- */-function fieldRadius(shafts, dir) {- let r = 1;- for (const s of shafts) {- const x = s.top.x + dir.x * s.len;- const y = s.top.y + dir.y * s.len;- const z = s.top.z + dir.z * s.len;- r = Math.max(r, Math.hypot(s.top.x, s.top.y, s.top.z),- Math.hypot(x, y, z) + s.rTop * s.flare * s.ratio);- }- return r;-}--/** The beams themselves: swept tubes carrying a volume integral. */-function shaftMesh(shafts, dir, color, air, soft, gain, hazy) {- const parts = shafts.map((s, i) => ({- tag: (i + 0.5) / shafts.length,- geometry: sweepProfile(- (t) => ({- x: s.top.x + dir.x * s.len * t,- y: s.top.y + dir.y * s.len * t,- z: s.top.z + dir.z * s.len * t,- }),- (a, t) => {- // Widens as it falls: a constant section is a pipe, and- // the eye names it one.- const r = s.rTop * (1 + (s.flare - 1) * t);- const p = Math.cos(a) * r * s.ratio, q = Math.sin(a) * r;- return {- x: s.b1.x * p + s.b2.x * q,- y: s.b1.y * p + s.b2.y * q,- z: s.b1.z * p + s.b2.z * q,- };- },- { nu: 28, nv: 22 }),- }));- for (const { geometry, tag } of parts) {- geometry.setAttribute('aShaft', new THREE.BufferAttribute(- new Float32Array(geometry.attributes.position.count).fill(tag), 1));- }- const geometry = mergeGeometries(parts.map((p) => p.geometry));- for (const part of parts) part.geometry.dispose();- const mesh = new THREE.Mesh(- geometry,- shaftMaterial(dir, color, air, soft, gain, hazy));- mesh.name = 'Shafts';- mesh.renderOrder = 3;- return mesh;-}--/** Chord-weighted scattering, striated across the beam. */-function shaftMaterial(dir, color, air, soft, gain, hazy) {- // Scattering, not adding: a pale, low-alpha normal blend lowers the- // contrast behind the shaft instead of clipping a bright frame.- // The paling used to be a 0.55 lerp to WHITE, which is why an- // outdoor field of shafts came out as grey smoke — the one thing- // sunlight through a gap never looks like. A third of that keeps- // the veil safe over a bright frame (alpha is what clips, and alpha- // is untouched) and the DEPTH of air, not the mode, is what takes- // the colour out of the far end.- const tint = hazy ? color.clone().lerp(new THREE.Color(0xffffff), 0.18)- : color;- // A NORMAL blend replaces what is behind it, so the colour has to- // carry the luminance the alpha carries in the additive branch.- // At 1.0 the veil tone-maps to 0.915 while this sky sits at 0.94 —- // a shaft of light that DARKENS the sky it crosses, which is the- // grey-smoke look these came out as. Straight into the ACES- // shoulder instead: 1.9 lands at 0.96, brighter than the sky by a- // hair and far brighter than the shade, and the shoulder is what- // keeps it from clipping. The additive branch is untouched —- // there the alpha already IS the brightness.- const lift = hazy ? 1.9 : 1.0;- return makeShaderMaterial({- name: 'GodRayShaft',- uniforms: {- uColor: { value: tint.clone().multiplyScalar(lift) },- uAir: { value: air.clone().multiplyScalar(lift) },- // How much air the shaft is seen through before the depth- // term adds any: none in a room, a haze outdoors.- uAirMix: { value: hazy ? 0.22 : 0.0 },- uDir: { value: dir.clone() },- uSoft: { value: 1.0 + 2.0 * Math.min(Math.max(soft, 0), 1) },- uGain: { value: gain },- },- varyings: 'varying vec2 vUv; varying vec3 vN; varying vec3 vW; varying vec3 vDir;'- + ' varying float vShaft;',- vertexHead: 'attribute float aShaft; uniform vec3 uDir;',- vertexMain: [- ' vUv = uv;',- ' vShaft = aShaft;',- ' vN = inverseTransformDirection(normalize(normalMatrix * normal), viewMatrix);',- ' vW = (modelMatrix * vec4(transformed, 1.0)).xyz;',- ' vDir = normalize(mat3(modelMatrix) * uDir);',- ].join('\n'),- fragmentHead: 'uniform vec3 uColor; uniform vec3 uAir;'- + ' uniform float uAirMix;'- + ' uniform float uSoft;'- + ' uniform float uGain;',- fragmentMain: [- ' float v = clamp(vUv.y, 0.0, 1.0);',- ' vec3 eye = normalize(cameraPosition - vW);',- // The chord the eye cuts through the beam. Zero at the- // silhouette, so the shell never draws its own outline.- ' float face = astraFacing(vN, eye);',- ' float chord = pow(face, uSoft);',- // |n.v| is the chord only ACROSS the beam; looking down it- // the walls turn edge-on while the real chord grows.- ' float axial = abs(dot(eye, normalize(vDir)));',- ' chord *= 1.0 / max(sqrt(max(0.0, 1.0 - axial * axial)), 0.62);',- ' float sd = astraStagger(vShaft);',- // Sampled on a circle so the pattern has no seam where the- // section closes, and drifts far slower ALONG than across.- ' float ang = vUv.x * 6.2831853;',- ' vec2 ring = vec2(cos(ang), sin(ang)) * 2.7;',- ' float striae = 0.46 + 0.72 * astraFbm2(ring + vec2(sd,',- ' v * 1.4 - uTime * 0.05), 3);',- // Brightest at the gap it came through; the air eats the- // rest on the way down.- ' float fade = exp(-v * 1.15);',- ' float ends = smoothstep(0.0, 0.11, v)',- ' * (1.0 - smoothstep(0.86, 1.0, v));',- // Beams of one brightness are a fence; real gaps let- // through what they let through.- ' float amp = 0.55 + 0.8 * astraHash11(vShaft * 13.0 + 0.5);',- ' float a = uGain * amp * chord * striae * fade * ends;',- // Rolled off instead of clamped: a beam that saturates- // draws a flat white band with a hard rim, which is the- // cylinder again.- ' a = 1.0 - exp(-a * 1.25);',- // Colour along the beam, not one flat tint for all six.- // Depth of air cools it toward the floor, the feathered rim- // is nothing BUT air, and each shaft stands in its own- // amount of it — so the field carries a spread of tints the- // way a photograph does instead of one stencilled hue.- ' float hz = astraHash11(vShaft * 7.0 + 2.3);',- ' float mist = clamp(uAirMix + 0.42 * v',- ' + 0.26 * (1.0 - face) + (hz - 0.5) * 0.26, 0.0, 1.0);',- ' vec3 c = mix(uColor, uAir, mist) * (0.72 + 0.5 * chord);',- ' c = astraHueShift(c, (hz - 0.5) * 0.14);',- // A beam is one long, very shallow ramp — exactly the- // gradient 8-bit output bands. A sub-LSB shake of the alpha- // turns the terraces back into noise.- ' a += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.005;',- ' if (a < 0.002) discard;',- ' gl_FragColor = vec4(c, clamp(a, 0.0, 1.0));',- ].join('\n'),- transparent: true,- // Added light fades into distance through its alpha (shader.js- // `additive`); a hazy veil is a surface and takes the fog colour.- additive: !hazy,- blending: hazy ? THREE.NormalBlending : THREE.AdditiveBlending,- side: THREE.DoubleSide,- depthWrite: false,- });-}--/** Where each beam lands: a soft ellipse, so it hands over. */-function poolMesh(shafts, dir, run, side, color, air, spark) {- const n = shafts.length;- // A stated radius, not the 10 km default: every rig that- // frames on the sphere would otherwise frame a kilometre- // of empty air around a 20 m shaft. It has to be a NUMBER —- // `run + side * 2` on two Vector3s is the string- // "[object Object]NaN", and a bounding sphere of NaN radius is- // one `frustumCulled = true` away from a field that never draws.- const geom = instancedQuad(n, 2, 2, fieldRadius(shafts, dir));- const pos = new Float32Array(n * 3), size = new Float32Array(n * 2);- shafts.forEach((s, i) => {- const rBot = s.rTop * s.flare;- pos[i * 3] = s.top.x + dir.x * s.len;- pos[i * 3 + 1] = 0.02;- pos[i * 3 + 2] = s.top.z + dir.z * s.len;- // A slanted beam meets the floor in an ellipse stretched by the- // slant; the glow margin is what keeps it off its own rim.- size[i * 2] = rBot * s.ratio * 2.3 / Math.max(-dir.y, 0.25);- size[i * 2 + 1] = rBot * 2.3;- });- geom.setAttribute('aPos', new THREE.InstancedBufferAttribute(pos, 3));- geom.setAttribute('aSize', new THREE.InstancedBufferAttribute(size, 2));- const mat = makeShaderMaterial({- name: 'GodRayPool',- uniforms: {- uColor: { value: color.clone() },- uAir: { value: air.clone() },- uAmp: { value: spark },- uRun: { value: run.clone() },- uSide: { value: side.clone() },- },- varyings: 'varying vec2 vUv;',- vertexHead: 'attribute vec3 aCorner; attribute vec3 aPos;'- + ' attribute vec2 aSize;'- + ' uniform vec3 uRun; uniform vec3 uSide;',- vertexMain: [- ' vUv = uv;',- ' transformed = aPos + uRun * (aCorner.x * aSize.x)',- ' + uSide * (aCorner.y * aSize.y);',- ].join('\n'),- fragmentHead: 'uniform vec3 uColor; uniform vec3 uAir;'- + ' uniform float uAmp;',- fragmentMain: [- ' float d = length(vUv * 2.0 - 1.0);',- ' if (d > 1.0) discard;',- ' float shim = 0.72 + 0.28 * astraFbm2(vUv * 5.0',- ' + vec2(uTime * 0.05, 0.0), 3);',- // Two falloffs: the wide one is the scattered margin, the- // narrow one the patch of floor the beam actually stands- // on. One power alone is a soft blob with no centre.- ' float a = (pow(1.0 - d, 2.9) * 0.44',- ' + pow(1.0 - d, 7.0) * 0.26) * shim * uAmp;',- // A pool has a hot heart and a scattered margin: holding one- // tint out to the rim is what makes it read as a decal.- ' vec3 c = mix(uColor, uAir, smoothstep(0.15, 1.0, d) * 0.7);',- ' a += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.005;',- ' gl_FragColor = vec4(c, clamp(a, 0.0, 1.0));',- ].join('\n'),- additive: true,- });- const mesh = new THREE.Mesh(geom, mat);- mesh.name = 'Pools';- mesh.frustumCulled = false;- mesh.renderOrder = 2;- return mesh;-}--/** Dust drifting inside the beams, as GTAO-safe billboards. */-function moteMesh(shafts, dir, side, perp, width, color, air, spark, seed) {- const n = Math.max(30, shafts.length * 44);- const geom = instancedQuad(n, 1, 1, fieldRadius(shafts, dir) + width);- const rnd = lehmer((seed >>> 0) * 7 + 13);- const org = new Float32Array(n * 3), off = new Float32Array(n * 3);- const data = new Float32Array(n * 4);- for (let i = 0; i < n; i++) {- const s = shafts[i % shafts.length];- // Placed by sqrt of a uniform draw, or every mote crowds the- // axis and the beam looks threaded on a wire.- const r = s.rTop * Math.sqrt(rnd());- const a = rnd() * Math.PI * 2;- const p = Math.cos(a) * r * s.ratio, q = Math.sin(a) * r;- org[i * 3] = s.top.x; org[i * 3 + 1] = s.top.y;- org[i * 3 + 2] = s.top.z;- off[i * 3] = s.b1.x * p + s.b2.x * q;- off[i * 3 + 1] = s.b1.y * p + s.b2.y * q;- off[i * 3 + 2] = s.b1.z * p + s.b2.z * q;- data[i * 4] = rnd();- // Dust, and dust is SMALL. Sized off the beam it rides, a mote- // was a tenth of the shaft's width across — 25-odd pixels of- // white disc at close range, which reads as falling snow or a- // dirty lens, never as air. A third of that lands in the 3-8 px- // range a real glint occupies, and the spread across the field- // is widened so they are not all one bead size.- data[i * 4 + 1] = width * (0.024 + 0.052 * rnd() * rnd());- data[i * 4 + 2] = s.len;- data[i * 4 + 3] = s.flare;- }- geom.setAttribute('aOrigin', new THREE.InstancedBufferAttribute(org, 3));- geom.setAttribute('aOff', new THREE.InstancedBufferAttribute(off, 3));- geom.setAttribute('aSeed', new THREE.InstancedBufferAttribute(data, 4));- const mesh = new THREE.Mesh(- geom, moteMaterial(dir, side, perp, color, air, spark, width));- mesh.name = 'Motes';- mesh.frustumCulled = false;- mesh.renderOrder = 4;- return mesh;-}--/** Billboarded dust: its own view-space projection, so raw sources. */-function moteMaterial(dir, side, perp, color, air, spark, width) {- return makeShaderMaterial({- name: 'GodRayMotes',- uniforms: {- // Lit BY the beam, so it keeps the beam's hue: the old 0.45- // lerp to white made the dust whiter than the light that- // lights it, which is the bokeh look.- // Declared even though makeShaderMaterial supplies it: this- // is the one material here that ships a RAW vertex shader,- // and the harness's own audit (runtime_js/lib/glsl_audit.mjs)- // reads the JS for a binding and the GLSL for a declaration- // rather than trusting the factory.- uTime: { value: 0 },- uColor: { value: color.clone().lerp(new THREE.Color(1, 1, 1),- 0.22) },- uAir: { value: air.clone() },- uAmp: { value: spark },- // Wobble is a distance in metres and size is a radius; they- // rode one attribute, so shrinking the dust also froze it.- uWob: { value: Math.max(width, 1e-3) * 0.22 },- uDir: { value: dir.clone() },- uSide: { value: side.clone() },- uPerp: { value: perp.clone() },- },- vertexShader: [- '#include <common>',- '#include <logdepthbuf_pars_vertex>',- '#include <fog_pars_vertex>',- 'attribute vec3 aCorner;',- 'attribute vec3 aOrigin;',- 'attribute vec3 aOff;',- 'attribute vec4 aSeed;',- // One line, because the audit only reads quoted strings long- // enough to look like GLSL: `uniform float uTime;` alone is- // 20 characters and is skipped, so the file it sits in reads- // as using uTime without declaring it.- 'uniform float uTime; uniform vec3 uDir; uniform vec3 uSide;',- 'uniform vec3 uPerp; uniform float uWob;',- 'varying vec2 vUv;',- 'varying float vLife;',- 'varying float vTwinkle;',- 'varying float vMist;',- 'void main() {',- ' vUv = uv;',- ' float k = fract(aSeed.x + uTime * 0.035);',- ' vLife = k;',- ' float ph = aSeed.x * 6.2831853;',- // Deeper in the beam is deeper in air: the far dust goes to- // the air hue while the near dust keeps the light's own.- ' vMist = clamp(0.25 + 0.5 * k + 0.35 * fract(aSeed.x * 7.3),',- ' 0.0, 1.0);',- // Dust does not fall straight: it hangs and wanders, so the- // wobble is wider than the drift is fast.- ' float wb = uWob * (0.55 + aSeed.x);',- ' vec3 wob = uSide * sin(uTime * 0.5 + ph) * wb',- ' + uPerp * cos(uTime * 0.37 + ph * 1.7) * wb * 0.82;',- ' vec3 c = aOrigin + aOff * (1.0 + (aSeed.w - 1.0) * k)',- ' + uDir * (aSeed.z * k) + wob;',- ' vTwinkle = 0.55 + 0.45 * sin(uTime * 2.1 + ph * 3.0);',- ' vec4 mvPosition = modelViewMatrix * vec4(c, 1.0);',- ' mvPosition.xy += aCorner.xy * aSeed.y;',- ' gl_Position = projectionMatrix * mvPosition;',- '#include <logdepthbuf_vertex>',- '#include <fog_vertex>',- '}',- ].join('\n'),- // The fragment is built by makeShaderMaterial so `additive` can- // fade the dust into distance through its alpha.- util: false,- fragmentHead: 'uniform vec3 uColor; uniform vec3 uAir; uniform float uAmp;'- + ' varying vec2 vUv; varying float vLife; varying float vTwinkle;'- + ' varying float vMist;',- fragmentMain: [- ' float d = length(vUv - 0.5) * 2.0;',- ' if (d > 1.0) discard;',- // Lives and dies inside the beam so nothing pops at the- // wrap, and dims with it toward the floor.- ' float life = sin(vLife * 3.14159265);',- // A glint has a core and a hint of halo, not one soft disc:- // the sharper power is what stops a 6 px sprite reading as- // a ball of cotton.- ' float a = (pow(1.0 - d, 3.4) + 0.14 * pow(1.0 - d, 1.3))',- ' * life * vTwinkle * exp(-vLife * 1.2) * 1.05 * uAmp;',- ' if (a < 0.003) discard;',- ' gl_FragColor = vec4(mix(uColor, uAir, vMist),',- ' clamp(a, 0.0, 1.0));',- ].join('\n'),- additive: true,- });-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/meadow.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/meadow.jsdeleted file mode 100644index ee7d7a3e..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/meadow.js+++ /dev/null@@ -1,373 +0,0 @@-/**- * Close-view meadow: curved leaf ribbons with a shaded fold and botanical variation.- * Metres, local XZ footprint, seeded placement; wind is in the field's LOCAL XZ.- * Blades use one instanced draw; sparse seed culms and soil are optional draws.- * Real instance matrices keep the blades present in the host's AO pass. Moving sun shadows- * use the same deformation as the colour pass. AO sees the rest pose (no TAA).- * Moving directional, spot and point-light shadows share that deformation.- *- * makeMeadow({size:[10,10], density:700, height:.38, seed:12, heightAt,- * mask, wind:{dir:[1,.3],strength:1,speed:1}, dry:.12,- * shadows:true, ground:true, diversity:.85, seedHeads:.003}) -> Group; userData.update(t), dispose().- * wind is grass.js's `windOf` over shader.js `readWind`: a number (strength), [x,z] or- * {dir|direction, strength, speed}, so one wind moves the meadow, grass and trees alike (strength 1 = breeze).- * density = blades/m² before the mask; maxBlades bounds memory and triangles.- * mask(x,z) -> 0..1 and heightAt(x,z) are LOCAL coordinates. A mask of 0- * leaves soil, a mask of 1 grows all blades. diversity (0..1) blends between- * one simple growth habit and mixed fine/arched/basal/senescent foliage.- * seedHeads is culms per blade (default .003, 0 disables; a large field thins them). No textures or network needed.- */-import * as THREE from 'three';-import { attachDisposal, snapshotResources } from './lifecycle.js';-import { windOf } from './grass.js';-import { fbm2, mulberry32 } from './noise.js';-import { boundedSampler, option, patchStandard, shadowLike, tickShaders } from './shader.js';--// The rest mesh has an actual silhouette: GTAO's override material draws the-// real instance matrices instead of the origin-degenerate helper lattices.-function ribbon(rows) {- const pos=[],uv=[],idx=[];- // Spend the same triangle budget on longitudinal curvature. The midrib fold- // is shaded by the two edge normals; a third column was invisible at grass- // scale but left only four segments along a conspicuously angular leaf.- const segments=rows*2;- for(let j=0;j<=segments;j++) {- const t=j/segments,w=Math.pow(1-t,.38);- for(let k=0;k<2;k++) {- pos.push((k-.5)*w,Math.sin(t*.42)/.42,(1-Math.cos(t*.42))/.42);- uv.push(k,t);- }- }- for(let j=0;j<segments;j++) {- const a=j*2,b=a+1,c=a+2,d=c+1;idx.push(a,b,c,b,d,c);- }- const g=new THREE.BufferGeometry();- g.setAttribute('position',new THREE.Float32BufferAttribute(pos,3));- g.setAttribute('uv',new THREE.Float32BufferAttribute(uv,2));- g.setIndex(idx);g.computeVertexNormals();return g;-}--const HEAD = /* glsl */`- attribute vec4 meadowVar;- attribute vec4 meadowShape;- attribute vec4 meadowBotany;- uniform vec2 uMeadowWind;- uniform float uMeadowStrength, uMeadowSpeed, uMeadowCulm;- varying vec4 vMeadow;- varying vec4 vMeadowBotany;- varying vec2 vMeadowUv;-`;--const VERTEX = /* glsl */`- float mdT = uv.y;- vec3 mdScale = vec3(length(instanceMatrix[0].xyz),- length(instanceMatrix[1].xyz), length(instanceMatrix[2].xyz));- mat3 mdRotation = mat3(instanceMatrix[0].xyz / mdScale.x,- instanceMatrix[1].xyz / mdScale.y,- instanceMatrix[2].xyz / mdScale.z);- vec2 mdRoot = instanceMatrix[3].xz;- float mdPhase = meadowVar.x * 6.2831853;- float mdTime = uTime * uMeadowSpeed;- float mdGust = .34 + .30 * sin(dot(mdRoot, uMeadowWind) * 1.15 - mdTime * 1.8)- + .18 * sin(dot(mdRoot, vec2(-uMeadowWind.y,uMeadowWind.x)) * .7- - mdTime * .81 + 1.7);- float mdFlutter = sin(mdTime * (4.5 + meadowVar.w * 2.) + mdPhase + mdRoot.x * 2.1) * .065;- vec2 mdWindLocal = vec2(dot(uMeadowWind, mdRotation[0].xz),- dot(uMeadowWind, mdRotation[2].xz));- float mdFlex = mix(.28, .95, smoothstep(.15,.9,meadowBotany.x));- vec2 mdBend = vec2(.12 * sin(mdPhase), meadowShape.x)- + mdWindLocal * uMeadowStrength * (mdGust + mdFlutter) * mdFlex;- float mdAngle = clamp(length(mdBend), .015, 2.80);- vec2 mdDirection = normalize(mdBend + vec2(.00001));- // Integrate a unit-length tangent: stiff young leaves rise before their tips- // roll; mature broad leaves arch from the crown; senescent leaves curl down.- // Shape varies by botanical form, not by stretching the same circular arc.- vec3 mdSpine = vec3(0.);- float mdStep = mdT / 5.;- for(int mdI=0; mdI<5; mdI++) {- float mdS=(float(mdI)+.5)*mdStep;- float mdA=meadowBotany.w + mdAngle*pow(mdS,meadowShape.y);- mdSpine += vec3(mdDirection.x*sin(mdA),cos(mdA),mdDirection.y*sin(mdA))*mdStep;- }- float mdTipA=meadowBotany.w + mdAngle*pow(mdT,meadowShape.y);- vec3 mdTangent = vec3(mdDirection.x*sin(mdTipA),cos(mdTipA),mdDirection.y*sin(mdTipA));- vec3 mdSide0=normalize(vec3(1.,0.,0.)-mdTangent*mdTangent.x);- vec3 mdNormal0=normalize(cross(mdSide0,mdTangent));- float mdTwist=meadowShape.z*mdT*mdT + .12*sin(mdPhase+mdT*5.)*mdT;- vec3 mdSide=mdSide0*cos(mdTwist)+mdNormal0*sin(mdTwist);- vec3 mdN=normalize(cross(mdSide,mdTangent));- float mdBroad=smoothstep(.25,.65,meadowBotany.x);- float mdWidth=pow(max(0.,1.-mdT),mix(.38,.32,mdBroad))- * mix(1.,.52+.48*smoothstep(0.,.13,mdT),mdBroad);- float mdAcross=uv.x-.5;- float mdRatio=mdScale.x/mdScale.y;- vec3 mdP=mdSpine+mdSide*(mdAcross*mdWidth*mdRatio)- +mdN*(abs(mdAcross)*mdWidth*mdRatio*meadowShape.w);- transformed=vec3(mdP.x/mdRatio,mdP.y,mdP.z);- if(uMeadowCulm>.5) {- transformed=mdSpine+mdSide*position.x+mdN*position.z;- }- vMeadow=vec4(mdT,meadowVar.z,meadowVar.w,meadowVar.x);- vMeadowBotany=meadowBotany;- vMeadowUv=uv;- #ifndef FLAT_SHADED- if(uMeadowCulm>.5) mdN=normalize(mdSide*normal.x+mdTangent*normal.y+mdN*normal.z);- else mdN=normalize(mdN-mdSide*sign(mdAcross)*meadowShape.w);- transformedNormal=normalMatrix*mdRotation*mdN;- vNormal=normalize(transformedNormal);- #endif-`;--const FRAGMENT = /* glsl */`- float mdSpecies=vMeadowBotany.x, mdAge=vMeadowBotany.y;- float mdHabitat=vMeadowBotany.z;- // Moist, shaded crowns skew blue-green; vigorous new growth is lime; old- // blades keep their straw tips, russet sheath and wax loss along the leaf.- vec3 mdGreen=uMeadowGreen*mix(vec3(.67,.89,1.30),vec3(1.35,1.10,.69),mdHabitat);- mdGreen*=mix(vec3(.80,.94,1.12),vec3(1.13,1.04,.81),mdSpecies);- vec3 mdLeaf=mix(mdGreen,uMeadowStraw,vMeadow.y);- mdLeaf*=.77+.47*vMeadow.z;- float mdDryTip=smoothstep(1.-mdAge*.57,1.,vMeadow.x)*smoothstep(.30,.9,mdAge);- float mdScar=astraNoise2(vec2(vMeadowUv.x*5.,vMeadowUv.y*18.)+vMeadow.w*37.);- mdLeaf=mix(mdLeaf,uMeadowStraw*vec3(.83,.65,.43),mdDryTip*.85);- mdLeaf*=1.-smoothstep(.62,.82,mdScar)*mdAge*.24;- // MSAA edge fragments can extrapolate slightly below the root. Fractional- // powers need a bounded base, especially in untone-mapped transmission RTTs.- float mdHeight=clamp(vMeadow.x,0.,1.);- float mdDepth=mix(.32,1.,pow(mdHeight,.60));- float mdVeins=.98+.02*sin(vMeadowUv.x*51.+vMeadow.w*3.);- float mdMidrib=1.-smoothstep(.016,.075,abs(vMeadowUv.x-.5));- diffuseColor.rgb=mdLeaf*mdDepth*mdVeins*(1.-.07*mdMidrib);- float mdSheath=(1.-smoothstep(.01,.14,vMeadow.x))*smoothstep(.45,.95,mdAge);- diffuseColor.rgb=mix(diffuseColor.rgb,uMeadowStraw*vec3(.30,.17,.10),mdSheath*.55);- #if NUM_DIR_LIGHTS > 0- #ifndef FLAT_SHADED- vec3 mdEye=normalize(vViewPosition),mdNormal=normalize(vNormal);- vec3 mdLight=directionalLights[0].direction;- float mdBack=clamp(-dot(mdNormal,mdLight)*sign(dot(mdNormal,mdEye)),0.,1.);- float mdForward=pow(max(0.,dot(mdEye,-mdLight)),3.);- vec3 mdSap=mdLeaf*vec3(1.35,1.08,.60);- float mdVisibility=1.;- #if defined(USE_SHADOWMAP) && NUM_DIR_LIGHT_SHADOWS > 0- mdVisibility=getShadow(directionalShadowMap[0],directionalLightShadows[0].shadowMapSize,- directionalLightShadows[0].shadowIntensity,directionalLightShadows[0].shadowBias,- directionalLightShadows[0].shadowRadius,vDirectionalShadowCoord[0]);- #endif- totalEmissiveRadiance+=mdSap*directionalLights[0].color- *(.20*mdBack+.22*mdForward)*pow(mdHeight,1.4)*(1.-mdAge*.35)*mdVisibility;- #endif- #endif-`;--function seedHeadGeometry() {- const positions=[],normals=[];- const stem=new THREE.CylinderGeometry(.0012,.0017,1,4,6,false);- stem.translate(0,.5,0);- const flat=stem.toNonIndexed();positions.push(...flat.attributes.position.array);- normals.push(...flat.attributes.normal.array);- stem.dispose();flat.dispose();- // Alternating closed spikelets, not a camera-facing flower photograph.- for(let i=0;i<8;i++) {- const sphere=new THREE.SphereGeometry(1,6,4),grain=sphere.toNonIndexed();- sphere.dispose();- const p=grain.attributes.position,n=grain.attributes.normal,a=i*2.399963,r=.0038;- const normal=new THREE.Vector3();- for(let j=0;j<p.count;j++) {- positions.push(Math.cos(a)*r+p.getX(j)*.0042,- .838+i*.021+p.getY(j)*.012,Math.sin(a)*r+p.getZ(j)*.0042);- normal.set(n.getX(j)/.0042,n.getY(j)/.012,n.getZ(j)/.0042).normalize();- normals.push(normal.x,normal.y,normal.z);- }- grain.dispose();- }- const g=new THREE.BufferGeometry();- g.setAttribute('position',new THREE.Float32BufferAttribute(positions,3));- const uv=[];for(let i=0;i<positions.length;i+=3) uv.push(.5,positions[i+1]);- g.setAttribute('uv',new THREE.Float32BufferAttribute(uv,2));- g.setAttribute('normal',new THREE.Float32BufferAttribute(normals,3));return g;-}--function makeSeedHeads({count,rand,roots,botany,height,green,straw,dir,strength,speed,shadows}) {- const geometry=seedHeadGeometry(),vars=[],forms=[],traits=[],matrices=[];- const dummy=new THREE.Object3D();- for(let i=0;i<count;i++) {- const at=Math.floor(rand()*roots.length/3),phase=rand();- const h=height*(1.40+.55*rand());- dummy.position.set(roots[at*3],roots[at*3+1]-.003,roots[at*3+2]);- dummy.rotation.set(0,rand()*Math.PI*2,0);dummy.scale.setScalar(h);dummy.updateMatrix();- matrices.push(dummy.matrix.clone());- vars.push(phase,rand(),.3,rand());forms.push(.18+rand()*.44,1.45,0,.05);- traits.push(.10,.62,botany[at*4+2],0);- }- geometry.setAttribute('meadowVar',new THREE.InstancedBufferAttribute(new Float32Array(vars),4));- geometry.setAttribute('meadowShape',new THREE.InstancedBufferAttribute(new Float32Array(forms),4));- geometry.setAttribute('meadowBotany',new THREE.InstancedBufferAttribute(new Float32Array(traits),4));- const material=new THREE.MeshStandardMaterial({color:0xffffff,roughness:.69,name:'MeadowSeedHeads'});- material.userData.bloom=false;- patchStandard(material,{name:'meadow:seed',vertexHead:HEAD,vertexBody:VERTEX,- fragmentHead:'varying vec4 vMeadow; uniform vec3 uMeadowGreen,uMeadowStraw;',- fragmentBody:`diffuseColor.rgb=mix(uMeadowGreen*.72,uMeadowStraw*.87,- smoothstep(.80,.86,vMeadow.x))*(.82+.32*vMeadow.z);`,- uniforms:{uMeadowGreen:{value:green},uMeadowStraw:{value:straw},uMeadowWind:{value:dir},- uMeadowStrength:{value:strength},uMeadowSpeed:{value:speed},uMeadowCulm:{value:1}},- });- const mesh=new THREE.InstancedMesh(geometry,material,count);mesh.name='MeadowSeedHeads';- matrices.forEach((m,i)=>mesh.setMatrixAt(i,m));mesh.instanceMatrix.needsUpdate=true;- mesh.receiveShadow=true;mesh.frustumCulled=false;- if(shadows) shadowLike(mesh,'meadow:seed-depth',HEAD,VERTEX);- return mesh;-}--/** @returns {THREE.Group} Rooted meadow, animated by userData.update(seconds). */-export function makeMeadow(opts = {}) {- const dimensions = Array.isArray(opts.size) ? opts.size : [opts.size ?? 10, opts.size ?? 10];- const sx = option(dimensions[0], 10, 'makeMeadow: size[0]', .05, 1000);- const sz = option(dimensions[1], 10, 'makeMeadow: size[1]', .05, 1000);- const density = option(opts.density, 700, 'makeMeadow: density', 0, 20000);- const height = option(opts.height, .38, 'makeMeadow: height', .005, 4);- const width = option(opts.bladeWidth, .011, 'makeMeadow: bladeWidth', .0005, .15);- const seed = option(opts.seed, 12, 'makeMeadow: seed');- const dry = option(opts.dry, .12, 'makeMeadow: dry', 0, 1);- const diversity = option(opts.diversity, .85, 'makeMeadow: diversity', 0, 1);- const seedHeads = option(opts.seedHeads, .003, 'makeMeadow: seedHeads', 0, .05);- const maxBlades = Math.floor(option(opts.maxBlades, 100000, 'makeMeadow: maxBlades', 1, 300000));- const rows = Math.floor(option(opts.segments, 5, 'makeMeadow: segments', 3, 12));- const wind = windOf(opts.wind);- const strength = option(wind.amp, .5, 'makeMeadow: wind.strength', 0, 3);- // The meadow's own gust clock runs 1.2x the shared wind's.- const speed = option(wind.speed * 1.2, 1.2, 'makeMeadow: wind.speed', 0, 10);- const dir = wind.dir;- if (!Number.isFinite(dir.x) || !Number.isFinite(dir.y)) {- throw new TypeError('makeMeadow: wind direction must be [x,z] finite numbers');- }- const heightAt = opts.heightAt ?? (() => 0), mask = opts.mask ?? (() => 1);- if (typeof heightAt !== 'function' || typeof mask !== 'function') {- throw new TypeError('makeMeadow: heightAt and mask must be functions');- }- const sampleHeight = (x, z) => {- const y = heightAt(x, z);- if (!Number.isFinite(y)) throw new RangeError('makeMeadow: heightAt returned a non-finite value');- return y;- };- const rand = mulberry32(seed);- const roots = [], vars = [], shapes = [], botany = [], matrices = [];- const target = Math.min(maxBlades, Math.round(sx * sz * density));- const dummy = new THREE.Object3D();- // Every handful of blades shares a crown, but each leaf has its own angle.- // Centres cover the ENTIRE footprint even when maxBlades limits the density.- const tuftSize = 9;- for (let i = 0; i < target;) {- const cx=(rand()-.5)*sx,cz=(rand()-.5)*sz;- const wet=fbm2(cx*.43,cz*.43,{seed,octaves:3});- const habitat=THREE.MathUtils.clamp(.5+wet*2.4,0,1);- const formPatch=fbm2(cx*.81+47,cz*.81-19,{seed:seed+113,octaves:2});- const patchDry=THREE.MathUtils.clamp(dry+wet*.55,0,1);- const tuftH=height*(.66+.57*rand())*(1+wet*.9);- const crownYaw=rand()*Math.PI*2;- for(let j=0;j<tuftSize && i<target;j++,i++) {- const phi=crownYaw+j*2.399963+(rand()-.5)*.65;- const r=Math.sqrt(rand())*height*.075;- const x=THREE.MathUtils.clamp(cx+Math.cos(phi)*r,-sx/2,sx/2);- const z=THREE.MathUtils.clamp(cz+Math.sin(phi)*r,-sz/2,sz/2);- const coverage=mask(x,z);- if(!Number.isFinite(coverage)) throw new RangeError('makeMeadow: mask returned a non-finite value');- if(rand()>=THREE.MathUtils.clamp(coverage,0,1)) continue;- // An individual crown keeps a family resemblance, with old outer leaves- // and a few fine upright shoots. Habitat changes the mix between crowns.- const choose=rand()+formPatch*.55;- let form=choose<.10?0:choose<.72?1:2;- const old=rand()<(.10+dry*.25)*diversity;- if(old) form=3;- const age=old?.72+rand()*.28:Math.min(.86,rand()*.67+dry*.12);- const phase=rand(),bendRandom=rand(),tone=rand();- const preset=[- [.91,.48,.28,.68,1.55,.18,.10],- [1.19,1.08,1.15,1.30,1.02,.59,.19],- [.71,1.50,1.80,.85,.78,.95,.25],- [1.04,.77,2.36,.31,.85,1.35,.10],- ][form];- const h=tuftH*THREE.MathUtils.lerp(.90,preset[0],diversity)*(.79+.42*rand());- const w=width*THREE.MathUtils.lerp(1,preset[1],diversity)*(.73+.52*rand());- const curvature=THREE.MathUtils.lerp(.8,preset[2]+bendRandom*preset[3],diversity);- // Keep even a fully wind-loaded old leaf above its crown plane.- const curl=Math.max(1,THREE.MathUtils.lerp(1,preset[4]+rand()*.25,diversity));- const twist=(rand()-.5)*2*preset[5]*diversity;- const fold=preset[6]*(.7+rand()*.6);- const y=sampleHeight(x,z);- dummy.position.set(x,y-.003,z);dummy.rotation.set(0,phi,0);dummy.scale.set(w,h,h);- dummy.updateMatrix();matrices.push(dummy.matrix.clone());roots.push(x,y,z);- const leafDry=old?.58+rand()*.40:THREE.MathUtils.clamp(patchDry+(rand()-.5)*.10,0,1);- vars.push(phase,bendRandom,leafDry,tone);- shapes.push(curvature,curl,twist,fold);- botany.push(form/3,age,habitat,form===3?.08:form===2?.12:0);- }- }- const group = new THREE.Group(); group.name = opts.name ?? 'Meadow';- const green = new THREE.Color(opts.color ?? 0x527829);- const straw = new THREE.Color(opts.dryColor ?? 0xaaa166);- const geometry = ribbon(rows);- geometry.setAttribute('meadowVar', new THREE.InstancedBufferAttribute(new Float32Array(vars), 4));- geometry.setAttribute('meadowShape', new THREE.InstancedBufferAttribute(new Float32Array(shapes), 4));- geometry.setAttribute('meadowBotany', new THREE.InstancedBufferAttribute(new Float32Array(botany), 4));- const material = new THREE.MeshPhysicalMaterial({- color: 0xffffff, side: THREE.DoubleSide, roughness: .68, metalness: 0,- specularIntensity: .45, envMapIntensity: .55, name: 'MeadowLeaf',- });- material.userData.bloom = false;- patchStandard(material, {name: 'meadow:leaf', vertexHead: HEAD, vertexBody: VERTEX,- fragmentHead: `varying vec4 vMeadow; varying vec4 vMeadowBotany; varying vec2 vMeadowUv;- uniform vec3 uMeadowGreen, uMeadowStraw;`, fragmentBody: FRAGMENT,- roughnessBody: 'roughnessFactor = clamp(.39 + vMeadowBotany.y*.35 + vMeadow.y*.24, .36, .95);',- uniforms: {uMeadowGreen: {value: green}, uMeadowStraw: {value: straw},- uMeadowWind: {value: dir}, uMeadowStrength: {value: strength}, uMeadowSpeed: {value: speed},- uMeadowCulm: {value: 0}},- });- const blades = new THREE.InstancedMesh(geometry, material, matrices.length);- matrices.forEach((m, i) => blades.setMatrixAt(i, m));- blades.instanceMatrix.needsUpdate = true;- blades.name = 'MeadowBlades'; blades.receiveShadow = true;- // Actual wind bounds extend beyond rest geometry; avoid edge popping.- blades.frustumCulled = false;- blades.computeBoundingBox(); blades.computeBoundingSphere();- if (opts.shadows !== false) shadowLike(blades, 'meadow:depth', HEAD, VERTEX);- group.add(blades);- const headCount=Math.min(2000,Math.round(matrices.length*seedHeads));- if(headCount) {- const heads=makeSeedHeads({count:headCount,rand,roots,botany,height,green,straw,- dir,strength,speed,shadows:opts.shadows!==false});- group.add(heads);- }- group.userData.seedHeadCount=headCount;-- if (opts.ground !== false) {- const nx = Math.min(160, Math.max(8, Math.ceil(sx * 4)));- const nz = Math.min(160, Math.max(8, Math.ceil(sz * 4)));- const geo = new THREE.PlaneGeometry(sx, sz, nx, nz); geo.rotateX(-Math.PI / 2);- const p = geo.attributes.position;- for (let i = 0; i < p.count; i++) p.setY(i, sampleHeight(p.getX(i), p.getZ(i)) - .006);- geo.computeVertexNormals();- const soil = new THREE.MeshStandardMaterial({color: 0x34321e, roughness: .98,- envMapIntensity: .6, name: 'MeadowSoil'});- patchStandard(soil, {name: 'meadow:soil',- vertexHead: 'varying vec3 vMeadowSoil;', vertexBody: 'vMeadowSoil = transformed;',- fragmentHead: 'varying vec3 vMeadowSoil;',- fragmentBody: `float mdSoil = astraFbm2(vMeadowSoil.xz * 14., 3);- float mdLitter = astraFbm2(vMeadowSoil.xz * 2.1, 2);- diffuseColor.rgb *= .66 + .62 * mdSoil;- diffuseColor.rgb = mix(diffuseColor.rgb, vec3(.08,.063,.027), smoothstep(.48,.7,mdLitter)*.4);`,- });- const ground = new THREE.Mesh(geo, soil); ground.name = 'MeadowSoil';- ground.receiveShadow = true; group.add(ground);- }- group.userData.bladeCount = matrices.length;- group.userData.roots = new Float32Array(roots);- group.userData.sampleHeight = boundedSampler(sx, sz, heightAt);- group.userData.update = (t) => {- if (!Number.isFinite(t)) throw new RangeError('makeMeadow.update: time must be finite');- tickShaders(group, t);- };- group.userData.tick = group.userData.update;- // Includes instance buffers and both custom shadow materials.- attachDisposal(group, snapshotResources(group));- return group;-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/merge.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/merge.jsdeleted file mode 100644index b621e833..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/merge.js+++ /dev/null@@ -1,231 +0,0 @@-/**- * Draw-call collapse for static props: many positioned meshes in, ONE- * mesh out. Software GL is DRAW-CALL-bound, making this the biggest- * SwiftShader perf lever. Never- * merge anything update animates or a fix round must retarget alone.- *- * The merge is also where a batch stops looking like a batch: 40 stones- * cut from one material arrive as ONE albedo, and a wall of one albedo- * reads as an extruded solid, not as stone. `variance` (on by default)- * gives every piece its own small value/warmth offset, keyed to where- * the piece SITS, so the collapse costs the wall nothing in hue spread.- */--import * as THREE from 'three';-import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';-import { clonePatchedMaterial } from './shader.js';-import { snapshotResources, attachDisposal } from './lifecycle.js';--const _KEEP = ['position', 'normal', 'uv', 'color'];-const _WHITE = new THREE.Color(1, 1, 1);-const _C = new THREE.Vector3();--// Surface response carried over from the batch's first material. `color`-// is deliberately absent — it becomes vertex colour. Everything else here-// is what makes the merged mesh shade the way its pieces did; dropping-// `emissive` renders merged lanterns as dead grey boxes, and dropping-// `side` deletes every back-facing card in a DoubleSide batch.-const _SCALARS = [- 'roughness', 'metalness', 'emissiveIntensity', 'envMapIntensity',- 'opacity', 'transparent', 'alphaTest', 'depthWrite', 'side', 'shadowSide',- 'flatShading', 'toneMapped', 'dithering', 'fog', 'aoMapIntensity',- 'bumpScale', 'displacementScale', 'displacementBias',- 'depthTest', 'colorWrite', 'premultipliedAlpha', 'lightMapIntensity',- 'transmission', 'thickness', 'attenuationDistance', 'ior', 'dispersion',- 'clearcoat', 'clearcoatRoughness', 'sheen', 'sheenRoughness',- 'specularIntensity', 'iridescence', 'iridescenceIOR',- 'anisotropy', 'anisotropyRotation',-];-const _MAPS = [- 'map', 'roughnessMap', 'metalnessMap', 'normalMap', 'bumpMap', 'aoMap',- 'alphaMap', 'emissiveMap', 'lightMap', 'displacementMap',- 'envMap', 'transmissionMap', 'thicknessMap', 'clearcoatMap',- 'clearcoatNormalMap', 'clearcoatRoughnessMap', 'sheenColorMap',- 'sheenRoughnessMap', 'iridescenceMap', 'iridescenceThicknessMap',- 'specularColorMap', 'specularIntensityMap', 'anisotropyMap',-];--/** Stable per-piece hash in [0,1) from a world position. */-function _hash(x, y, z, k) {- const s = Math.sin(x * 127.1 + y * 311.7 + z * 74.7 + k * 37.3) * 43758.5453;- return s - Math.floor(s);-}--/**- * Reverse triangle winding in place (index triples, or the vertex runs of- * a non-indexed geometry). A mirrored placement — `scale.x = -1`, how a- * matching pair gets made — has a negative-determinant world matrix, and- * baking that flips which side of every triangle faces out. The piece then- * renders as its own interior: front faces culled, the back ones lit from- * behind. Un-baked it never showed, because three flips winding per draw- * from the matrix it can still see; after the bake there is no matrix left.- */-function _flipWinding(g) {- if (g.index) {- const a = g.index.array;- for (let i = 0; i + 2 < a.length; i += 3) {- const t = a[i + 1]; a[i + 1] = a[i + 2]; a[i + 2] = t;- }- g.index.needsUpdate = true;- return;- }- for (const name of Object.keys(g.attributes)) {- const at = g.attributes[name];- const n = at.itemSize;- const arr = at.array;- for (let i = 0; i + 2 < at.count; i += 3) {- for (let k = 0; k < n; k++) {- const p = (i + 1) * n + k;- const q = (i + 2) * n + k;- const t = arr[p]; arr[p] = arr[q]; arr[q] = t;- }- }- at.needsUpdate = true;- }-}--/** What one material contributes to the shared surface response. */-function _sig(m) {- if (!m) return '';- return JSON.stringify([- m.type, ..._SCALARS.map((key) => m[key]), ..._MAPS.map((key) => m[key]?.uuid),- ...['emissive', 'attenuationColor', 'sheenColor', 'specularColor', 'normalScale',- 'clearcoatNormalScale', 'iridescenceThicknessRange'].map((key) => m[key]?.toArray?.() ?? m[key]),- m.userData.astraPatches || [],- ]);-}--/**- * Merge positioned static meshes into one vertex-coloured Mesh.- * World matrices and material colours are baked in; pieces may differ- * ONLY by colour — the FIRST mesh's material supplies the shared- * surface response (and a batch that disagrees about it says so in the- * console, rather than losing half its look silently). A merge that- * fails throws rather than shipping a partial scene.- *- * Invisible pieces are skipped: `visible = false` is how a scene hides- * an LOD stand-in, and baking one in would make it permanent.- *- * @param {Array<THREE.Object3D>} meshes Positioned meshes (or groups- * of meshes) to consume. Add the RETURNED mesh to the scene instead- * of these.- * @param {object} opts- * `variance` (default 0.12, 0 disables) per-piece albedo spread: each- * piece's baked colour is nudged in value by ±variance and in warm/cool- * by ±0.6·variance, from a hash of where the piece sits — so the offset- * is stable across runs, independent of input order, and two pieces of- * one material stop being the same flat swatch. Set 0 when the baked- * colours are data (colour-coded parts, a legend, a gradient you built).- * @returns {THREE.Mesh} One shadow-casting mesh named 'MergedStatic'- * — one draw call. Preserves the first material's type and physical response.- * userData.dispose() releases its owned geometry/material; source objects,- * shared maps and caller additions remain borrowed.- * @throws {Error} When the input holds no mesh or the geometries- * cannot merge.- */-export function mergeStatic(meshes, opts = {}) {- const { variance = 0.12 } = opts;- if (!meshes || meshes.length === 0) {- throw new Error('mergeStatic: got an empty input array');- }-- // Collect leaf meshes with world matrices up to date (parents too:- // a group's own transform must reach its children's bakes).- const found = [];- for (const root of meshes) {- root.updateWorldMatrix(true, true);- root.traverse((n) => {- if (!n.isMesh || n.isInstancedMesh || !n.geometry) return;- if (!n.geometry.attributes || !n.geometry.attributes.position) return;- for (let p = n; p; p = p.parent) {- if (!p.visible) return;- }- found.push(n);- });- }- if (found.length === 0) {- throw new Error('mergeStatic: no meshes found in the input');- }-- // mergeGeometries refuses to mix indexed and non-indexed inputs; if- // both appear, expand the indexed ones.- const mixed = found.some((m) => m.geometry.index === null);-- const geos = [];- let firstMat = null;- let odd = 0;- for (const mesh of found) {- let g = mesh.geometry.clone();- if (mixed && g.index) g = g.toNonIndexed();- g.applyMatrix4(mesh.matrixWorld); // bake pos + rot + scale- // applyMatrix4 carries normals through the normal matrix, which is- // right even under a mirror — but the winding is not.- if (mesh.matrixWorld.determinant() < 0) _flipWinding(g);- g.morphAttributes = {};- for (const name of Object.keys(g.attributes)) {- if (!_KEEP.includes(name)) g.deleteAttribute(name);- }- if (!g.attributes.normal) g.computeVertexNormals();- const count = g.attributes.position.count;- if (!g.attributes.uv) {- g.setAttribute(- 'uv', new THREE.BufferAttribute(new Float32Array(count * 2), 2));- }- const mat = Array.isArray(mesh.material)- ? mesh.material[0] : mesh.material;- if (!firstMat && mat) firstMat = mat;- else if (_sig(mat) !== _sig(firstMat)) odd++;- // The piece's material colour becomes vertex colour, modulating- // any colours the geometry already carries (strata bands etc.).- const tint = mat && mat.color ? mat.color : _WHITE;- const old = g.attributes.color;- // Per-piece spread, hashed from where the piece ended up: same seed- // every run, unchanged if the caller reorders the batch, and different- // for two copies of one prop standing apart.- let val = 1;- let warm = 0;- if (variance > 0) {- g.computeBoundingBox();- g.boundingBox.getCenter(_C);- val = 1 + (_hash(_C.x, _C.y, _C.z, 1) - 0.5) * 2 * variance;- warm = (_hash(_C.x, _C.y, _C.z, 7) - 0.5) * 1.2 * variance;- }- const rgb = new Float32Array(count * 3);- for (let i = 0; i < count; i++) {- rgb[i * 3] = Math.min(- 1, tint.r * (old ? old.getX(i) : 1) * val * (1 + warm));- rgb[i * 3 + 1] = Math.min(1, tint.g * (old ? old.getY(i) : 1) * val);- rgb[i * 3 + 2] = Math.min(- 1, tint.b * (old ? old.getZ(i) : 1) * val * (1 - warm));- }- g.setAttribute('color', new THREE.BufferAttribute(rgb, 3));- geos.push(g);- }-- const merged = mergeGeometries(geos, false);- if (!merged) {- throw new Error(- 'mergeStatic: geometries would not merge (incompatible '- + 'attribute sets) — merge compatible pieces per batch');- }-- // ONE material: colour lives per-vertex; surface response comes from- // the first piece (colour-only differences by contract).- const material = firstMat- ? clonePatchedMaterial(firstMat, {shareUniforms:true}) : new THREE.MeshStandardMaterial();- material.vertexColors = true;- if (material.color) material.color.setRGB(1, 1, 1);- if (odd) {- console.warn(- `mergeStatic: ${odd} of ${found.length} pieces disagree with the `- + 'first material about the shared surface response (side, '- + 'emissive, roughness, map…) — those differences are LOST. '- + 'Merge one material family per batch; only colour may vary.');- }-- const out = new THREE.Mesh(merged, material);- out.name = 'MergedStatic';- out.castShadow = true;- out.receiveShadow = true;- return attachDisposal(out, snapshotResources(out));-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/neon.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/neon.jsdeleted file mode 100644index c777afbd..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/neon.js+++ /dev/null@@ -1,756 +0,0 @@-/**- * Neon: the light a sign MAKES, not the sign itself.- *- * A night city assembled rather than lit fails in one specific way —- * bright signs on unlit walls. These three break that: a bent tube with- * a core hot enough to clip white and a halo that pools where the glass- * bends back past itself; the light that tube throws onto the brick- * behind it and the pavement below; and the head- and tail-light- * streaks along a road, the only motion a still frame can show.- *- * All three ADD light, because added light survives a DARK frame and- * clips over a bright one — and a night city is exactly the dark frame- * where adding is correct. Each factory still takes an `ambient` escape- * (0 an unlit street, 1 open daylight): from 0.35 up it stops adding- * and paints a pale, normal-blended tube instead, so the 0.5 a composer- * picks when handed "0 to 1" is the mode that cannot clip.-- */--import { attachDisposal, snapshotResources } from './lifecycle.js';-import * as THREE from 'three';-import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';--import {- keepOutOfDepthPasses, makeShaderMaterial, patchStandard, sweepProfile,- readVec3, seedLattice, tickShaders, toColor } from './shader.js';--const _UP = new THREE.Vector3(0, 1, 0);--// How many spill sources one program carries. The array length is baked-// into the GLSL and `patchStandard` gives every spill patch ONE cache-// key, so it is a constant here and the live count is a uniform.-const SPILL_MAX = 8;--// A failing tube does not blink on a clock: it holds, drops out for a-// frame or two, then buzzes at the mains while it strikes again.-// Shared verbatim by the tube and the spill so one seed stutters both.-const FLICK_GLSL = [- 'float astraNeonFlick(float t, float key, float amt) {',- ' if (amt <= 0.0) return 1.0;',- ' float s = astraHash11(floor(t * 14.0) * 1.13 + key);',- ' float dip = step(s, amt * 0.30);',- ' float buzz = 0.86 + 0.14 * sin(t * 96.0 + key);',- ' return mix(1.0, mix(buzz, 0.08 + 0.22 * s, dip), amt);',- '}',-].join('\n');--// HOW WHITE THE MIDDLE OF THE GLASS GOES, and it is not very white.-// Additive layers SUM: the near and far walls of a double-sided shell-// plus the halo twice stack four deep on the middle of a tube, and-// every channel a colour carries is multiplied by that stack. Whitening-// the colour BEFORE it threw the gas away — measured, a cyan sign-// rendered as a white strip light with a cyan edge. A tube IS meant to-// clip, toward its OWN hue, which the stack does by itself once the-// colour stays saturated. So: a fifth of the way to white dead centre,-// gone two thirds out — a hot line in coloured glass.-const FILAMENT_GLSL = [- 'float astraNeonFilament(float face, float hot) {',- ' return pow(face, 14.0) * hot * 0.22;',- '}',-].join('\n');--// One vehicle's colour temperature, as a signed offset off the lane's-// own colour. Spent two ways at the call site because a lane's colour-// can be anything: a hue rotation moves a saturated tail-light, a-// warm/cool tilt is the only thing that moves a near-white head-light.-const TEMP_GLSL = [- 'float astraTrailTemp(float id, float vary) {',- ' return (astraHash11(id * 5.71 + 1.9) - 0.5) * vary;',- '}',-].join('\n');--const seedKey = (seed) => seedLattice(seed) * 0.011;--/**- * One polyline or a set of them, always as an array of strokes.- *- * A sign is lettering as often as it is a single bent tube, and a- * caller holding one stroke per character should not have to wrap it.- */-function toStrokes(path) {- if (!Array.isArray(path) || !path.length) return [];- const head = path[0];- const nested = Array.isArray(head)- && (Array.isArray(head[0]) || (head[0] && head[0].isVector3)- || (head[0] && typeof head[0] === 'object'));- const raw = nested ? path : [path];- return raw.map((s) => {- const out = [];- for (const p of s) {- const v = readVec3(p);- // A repeated point is a zero-length segment, and a- // zero-length segment has no tangent to build a frame on.- if (!out.length || out[out.length - 1].distanceTo(v) > 1e-6) {- out.push(v);- }- }- return out;- }).filter((s) => s.length >= 2);-}--/**- * Round every corner: glass bends on a radius.- *- * A mitred corner is a thing no glassblower makes, and the sweep would- * pinch there. Each corner becomes a quadratic through points `bend`- * back along both legs, which keeps the tube within `bend / 4` of the- * polyline it was given.- */-function filletPath(pts, bend) {- if (pts.length < 3 || bend <= 0) return pts.map((p) => p.clone());- const out = [pts[0].clone()];- for (let i = 1; i < pts.length - 1; i++) {- const a = pts[i - 1], b = pts[i], c = pts[i + 1];- const u = new THREE.Vector3().subVectors(a, b);- const w = new THREE.Vector3().subVectors(c, b);- const la = u.length(), lc = w.length();- const k = Math.min(bend, la * 0.45, lc * 0.45);- if (k < 1e-5) { out.push(b.clone()); continue; }- u.multiplyScalar(k / la);- w.multiplyScalar(k / lc);- for (let j = 0; j <= 6; j++) {- const t = j / 6, s = 1 - t;- out.push(new THREE.Vector3(- s * s * (b.x + u.x) + 2 * s * t * b.x- + t * t * (b.x + w.x),- s * s * (b.y + u.y) + 2 * s * t * b.y- + t * t * (b.y + w.y),- s * s * (b.z + u.z) + 2 * s * t * b.z- + t * t * (b.z + w.z)));- }- }- out.push(pts[pts.length - 1].clone());- return out;-}--/** Stations spaced by ARC LENGTH, so v is metres and pulses ride it. */-function resample(pts, n) {- const acc = [0];- for (let i = 1; i < pts.length; i++) {- acc.push(acc[i - 1] + pts[i].distanceTo(pts[i - 1]));- }- const total = acc[acc.length - 1];- const out = [];- let j = 0;- for (let i = 0; i <= n; i++) {- const d = total * (i / n);- while (j < acc.length - 2 && acc[j + 1] < d) j++;- const seg = Math.max(acc[j + 1] - acc[j], 1e-9);- const f = Math.min(Math.max((d - acc[j]) / seg, 0), 1);- out.push(pts[j].clone().lerp(pts[j + 1], f));- }- return { pts: out, length: total };-}--/**- * A rotation-minimising frame at every station.- *- * Rebuilding the section from a fixed up-vector spins the profile- * through every bend and shears the tube; transporting the previous- * normal keeps it steady.- */-function frames(pts) {- const n = pts.length;- const tan = [];- for (let i = 0; i < n; i++) {- const a = pts[Math.max(i - 1, 0)];- const b = pts[Math.min(i + 1, n - 1)];- const t = new THREE.Vector3().subVectors(b, a);- if (t.lengthSq() < 1e-12) t.copy(tan[i - 1] || _UP);- tan.push(t.normalize());- }- let nrm = Math.abs(tan[0].y) > 0.9- ? new THREE.Vector3(1, 0, 0) : _UP.clone();- const out = [];- for (let i = 0; i < n; i++) {- nrm = nrm.clone().addScaledVector(tan[i], -nrm.dot(tan[i]));- if (nrm.lengthSq() < 1e-10) {- nrm.set(tan[i].y, -tan[i].x, 0);- if (nrm.lengthSq() < 1e-10) nrm.set(1, 0, 0);- }- nrm.normalize();- out.push({- p: pts[i], t: tan[i].clone(), n: nrm.clone(),- b: new THREE.Vector3().crossVectors(tan[i], nrm).normalize(),- });- }- return out;-}--/** One stroke as a swept circular section around its own frame. */-function tubeGeometry(st, radius, nu) {- const nv = st.length - 1;- const at = (t) => st[Math.min(nv, Math.max(0, Math.round(t * nv)))];- return sweepProfile(- (t) => at(t).p,- (a, t) => {- const s = at(t);- const c = Math.cos(a) * radius, d = Math.sin(a) * radius;- return {- x: s.n.x * c + s.b.x * d,- y: s.n.y * c + s.b.y * d,- z: s.n.z * c + s.b.z * d,- };- },- { nu, nv });-}--/** Stations for every stroke of a path, filleted and arc-length even. */-function strokeStations(strokes, bend, step) {- return strokes.map((s) => {- const smooth = filletPath(s, bend);- const rough = resample(smooth, 4).length;- const n = Math.min(400, Math.max(8, Math.round(rough / step)));- const r = resample(smooth, n);- return { frames: frames(r.pts), length: r.length };- });-}--/**- * The glowing gas, as a chord integral through the shell.- *- * `astraFacing` is exactly the chord the eye cuts through a tube:- * longest down the axis, zero at the silhouette. Skip it and the front- * and back faces of the shell stack at the rim into a bright OUTLINE,- * which is the solid-plastic-rod look no colour tuning removes.- *- * `toe` is the second half of that: the chord is exact for a CYLINDER- * and the mesh is an n-gon, so at the outermost facet the normal is- * still up to 180/n degrees off perpendicular and the shell ends on a- * live alpha — a crease that draws the halo's own polygon around the- * letter. Fading the chord out over `toe` puts that under the discard.- */-function tubeMaterial(name, color, gain, core, hot, flicker, key, hazy,- toe, vary) {- // Pale, not white: over a bright wall a core that clips to white is- // a tube you cannot read, which is the day failure mirrored.- const tint = hazy- ? color.clone().lerp(new THREE.Color(1, 1, 1), 0.20) : color.clone();- const hotv = hazy ? hot * 0.25 : hot;- return makeShaderMaterial({- name,- additive: !hazy,- uniforms: {- uColor: { value: tint },- uGain: { value: gain },- uCore: { value: core },- uHot: { value: hotv },- uFlicker: { value: flicker },- uKey: { value: key },- uToe: { value: toe },- uVary: { value: vary },- },- varyings:- 'varying vec3 vNeonN; varying vec3 vNeonW; varying vec2 vNeonUv;',- vertexMain: [- ' vNeonN = inverseTransformDirection(normalize(normalMatrix * normal), viewMatrix);',- ' vNeonW = (modelMatrix * vec4(transformed, 1.0)).xyz;',- ' vNeonUv = uv;',- ].join('\n'),- fragmentHead: [- 'uniform vec3 uColor; uniform float uGain; uniform float uCore;',- 'uniform float uHot; uniform float uFlicker;',- 'uniform float uKey; uniform float uToe; uniform float uVary;',- FLICK_GLSL,- FILAMENT_GLSL,- ].join('\n'),- fragmentMain: [- ' vec3 eye = normalize(cameraPosition - vNeonW);',- ' float face = astraFacing(vNeonN, eye);',- ' float body = pow(face, uCore) * smoothstep(0.0, uToe, face);',- ' float a = uGain * body',- ' * astraNeonFlick(uTime, uKey, uFlicker);',- // Rolled off, not clamped: a tube that saturates draws a- // flat band with a hard rim, which is the rod again.- ' a = 1.0 - exp(-a * 1.6);',- // One tube is not one colour: electrodes run hotter, the- // phosphor is not evenly laid, the glass is not evenly- // thick. The drift rides each stroke's own v, so a word- // bent one stroke per letter drifts per LETTER — which is- // what stops four letters reading as one printed decal.- ' float drift = astraNoise2(vec2(vNeonUv.y * 9.0, uKey))',- ' - 0.5;',- ' vec3 gas = astraHueShift(uColor, drift * uVary);',- ' vec3 c = mix(gas, vec3(1.0),',- ' astraNeonFilament(face, uHot));',- // A halo is a wide, shallow ramp: in 8-bit output that is- // exactly the gradient that bands into rings.- ' a += (astraHash21(gl_FragCoord.xy + uKey) - 0.5) * 0.005;',- ' if (a < 0.003) discard;',- ' gl_FragColor = vec4(c, clamp(a, 0.0, 1.0));',- ].join('\n'),- transparent: true,- blending: hazy ? THREE.NormalBlending : THREE.AdditiveBlending,- side: THREE.DoubleSide,- depthWrite: false,- });-}--/**- * A bent glass tube that GLOWS — core, halo and its own colour bleed.- *- * Two shells swept along the same path: a thin one carrying the hot- * core and a fat one carrying the halo, both weighted by the chord the- * eye cuts through them, both ADDITIVE. Additive is what makes the- * colour bleed onto itself where the tube bends back past its own halo,- * and additive is right here because added light survives a DARK frame- * and clips over a bright one — a night street is that dark frame. Over- * anything brighter, say so with `ambient` and the tube switches to a- * pale normal-blended glass instead of clipping the sky out.- *- * @param {object} [opts]- * `path` a polyline (`[[x,y,z], ...]` or Vector3s) OR an array of- * those — one stroke per character of a word (default a 2 m bar);- * `radius` tube radius in metres (default 0.05: real glass is ~0.008,- * but a tube thinner than a pixel renders as a dashed line);- * `color` the gas colour, as its MEAN — the hue drifts a few degrees- * along each stroke, so a word bent one stroke per letter is four- * related colours rather than one flat fill (default 0xff2e6a);- * `intensity` overall gain- * (default 1); `halo` how many tube radii the glow reaches (default- * 3.6); `bend` corner radius in metres (default 6 * radius, capped at- * 45% of the shorter leg — the tube stays within bend/4 of the- * polyline); `flicker` 0..1 failing-tube stutter (default 0, OFF —- * a whole sign stuttering is a story, and most signs work);- * `ambient` how bright the surroundings are, 0 an unlit street to 1- * open daylight (default 0.15, this being a night library; from 0.35- * up the tube stops adding light and turns pale and normal-blended,- * so a composer who is unsure and picks 0.5 gets the mode that cannot- * clip); `seed` the flicker phase (default 3).- * @returns {THREE.Group} Named `NeonTube`, guarded by- * `keepOutOfDepthPasses` (a glow card is a solid wall to the GTAO- * override pass, and a light source must cast no shadow), with- * `userData.update(t)` and `userData.spillSources()` — the world points- * to hand straight to `patchNeonSpill`.- */-export function makeNeonTube(opts = {}) {- const radius = Math.max(1e-3,- opts.radius === undefined ? 0.05 : opts.radius);- const strokes = toStrokes(opts.path && opts.path.length ? opts.path- : [[-1, 0, 0], [1, 0, 0]]);- const color = toColor(opts.color, 0xff2e6a);- const intensity = opts.intensity === undefined ? 1 : opts.intensity;- const halo = opts.halo === undefined ? 3.6 : opts.halo;- const bend = opts.bend === undefined ? radius * 6 : opts.bend;- const flicker = Math.min(Math.max(- opts.flicker === undefined ? 0 : opts.flicker, 0), 1);- const ambient = Math.min(Math.max(- opts.ambient === undefined ? 0.15 : opts.ambient, 0), 1);- const key = seedKey(opts.seed === undefined ? 3 : opts.seed);- const hazy = ambient >= 0.35;-- const g = new THREE.Group();- g.name = 'NeonTube';- if (!strokes.length) {- g.userData.update = g.userData.tick = () => {};- return attachDisposal(g, []);- }- const st = strokeStations(strokes, bend,- Math.max(0.02, Math.min(radius * 2.2, bend * 0.25)));- const gain = Math.max(0, intensity) * (hazy ? 1.9 : 1.05);- // THE ADDITIVE BUDGET (see FILAMENT_GLSL for why display space is- // what stacks). The old gains laid four layers of ~0.8 and ~0.44 on- // the middle of the glass — a sum near 2.5, where every channel of- // every colour clips and the sign renders white whatever gas it- // holds. Budgeted to ~1.4 instead: the strong channel still clips,- // as a tube must, and the weak ones keep the hue.- // 18 sides, not 10: the halo is `halo` times the radius of the- // glass, so its silhouette is the widest polygon here and a 10-gon- // draws that polygon around the letter (measured: a 2% alpha step- // at the outermost facet). The core's facets fit inside a pixel.- g.add(shell(st, radius * Math.max(1.2, halo), 18, tubeMaterial(- 'NeonHalo', color, gain * (hazy ? 0.12 : 0.148), 2.6, 0.10,- flicker, key, hazy, 0.45, 0.20), 'NeonHalo', 2));- g.add(shell(st, radius, 14, tubeMaterial(- 'NeonCore', color, gain * (hazy ? 1.0 : 0.41), 0.85, 0.9,- flicker, key, hazy, 0.10, 0.13), 'NeonCore', 3));- g.userData.update = g.userData.tick = (t) => tickShaders(g, t);- // Sources for `patchNeonSpill`, read through the group's CURRENT- // world matrix, so placing the sign moves the light it throws.- g.userData.spillSources = (n) => sampleSources(g, st, color, n);- keepOutOfDepthPasses(g);- return attachDisposal(g, snapshotResources(g));-}--/** One merged mesh for every stroke at one radius. */-function shell(st, radius, nu, material, name, order) {- const parts = st.map((s) => tubeGeometry(s.frames, radius, nu));- const geometry = mergeGeometries(parts);- for (const part of parts) part.dispose();- const mesh = new THREE.Mesh(geometry, material);- mesh.name = name;- mesh.renderOrder = order;- return mesh;-}--/** Evenly spaced points along the whole sign, in world space. */-function sampleSources(group, st, color, count) {- const n = Math.min(SPILL_MAX, Math.max(1,- count === undefined ? 4 : Math.round(count)));- const all = [];- for (const s of st) for (const f of s.frames) all.push(f.p);- group.updateWorldMatrix(true, false);- const out = [];- for (let i = 0; i < n; i++) {- const k = Math.round((i + 0.5) / n * (all.length - 1));- out.push({- position: all[k].clone().applyMatrix4(group.matrixWorld),- color: color.clone(),- });- }- return out;-}--const SPILL_VARYINGS =- 'varying vec3 vNeonSW;\nvarying vec3 vNeonSN;';--// `transformed` is still object-space at <begin_vertex>, so an-// instanced wall needs instanceMatrix folded in by hand.-const SPILL_VERTEX = [- ' vec4 nsP = vec4(transformed, 1.0);',- ' vec3 nsN = normal;',- '#ifdef USE_INSTANCING',- ' nsP = instanceMatrix * nsP;',- ' nsN = astraNormalTransform(mat3(instanceMatrix), nsN);',- '#endif',- ' vNeonSW = (modelMatrix * nsP).xyz;',- ' vNeonSN = astraNormalTransform(mat3(modelMatrix), nsN);',-].join('\n');--const SPILL_HEAD = [- 'uniform vec3 uNeonPos[' + SPILL_MAX + '];',- 'uniform vec3 uNeonCol[' + SPILL_MAX + '];',- 'uniform float uNeonCount;',- 'uniform float uNeonRadius;',- 'uniform float uNeonGain;',- 'uniform float uNeonFlicker;',- 'uniform float uNeonKey;',- // Windowed inverse square: 1 at the source, EXACTLY 0 at radius and- // beyond. A bare 1/d^2 never reaches zero, so every wall in the- // scene keeps a wash of every sign in it and the night goes flat.- 'float astraNeonFall(float d, float r) {',- ' float x = clamp(d / max(r, 1e-4), 0.0, 1.0);',- ' float w = 1.0 - x * x;',- ' return w * w / (1.0 + 12.0 * x * x);',- '}',- FLICK_GLSL,-].join('\n');--const SPILL_BODY = [- ' vec3 nsSum = vec3(0.0);',- ' vec3 nsN = normalize(vNeonSN);',- ' for (int i = 0; i < ' + SPILL_MAX + '; i++) {',- ' if (float(i) >= uNeonCount) break;',- ' vec3 dv = uNeonPos[i] - vNeonSW;',- ' float d = length(dv);',- // A sign is a broad source, not a point: a hard lambert terminator- // would cut the pavement off right under the tube that lights it.- ' float lam = dot(nsN, dv / max(d, 1e-4)) * 0.5 + 0.5;',- ' lam = clamp(lam, 0.0, 1.0);',- ' nsSum += uNeonCol[i] * (astraNeonFall(d, uNeonRadius) * lam * lam);',- ' }',- ' nsSum *= uNeonGain * astraNeonFlick(uTime, uNeonKey, uNeonFlicker);',- // A pool is a metres-wide ramp on a flat wall — the widest, softest- // gradient in the library and the one that rings in 8-bit output.- // Proportional, so an unlit wall stays unlit instead of gaining a- // floor of noise.- ' nsSum *= 1.0 + (astraHash21(gl_FragCoord.xy + uNeonKey) - 0.5)',- ' * 0.03;',- // Arriving light is REFLECTED, so it takes the wall's own colour —- // but never all of it, or a dark wall swallows the sign entirely.- ' totalEmissiveRadiance +=',- ' nsSum * mix(vec3(0.30), diffuseColor.rgb, 0.70);',-].join('\n');--/**- * The light a sign throws onto the wall behind and the road below.- *- * Without this a neon sign is a bright decal on an unlit wall, which is- * the single tell that a night scene was assembled rather than lit. Each- * source adds a windowed inverse square, wrapped by how the surface- * faces it and reflected through the surface's own albedo, straight- * into `totalEmissiveRadiance` — so it ADDS light, correct over the- * dark frame a night city is and clipping over a bright one, which is- * what `ambient` is for. It is a `patchStandard`, so it needs a LIT- * material (MeshStandard/MeshPhysical, not Basic), and it chains- * happily with `patchMicroBreakup`.- *- * The one constraint it cannot solve: nothing is occluded. Light- * reaches the far side of a wall as readily as the near one, so keep- * `radius` to what the sign really reaches (a few metres) and put the- * sources on the face they light.- *- * @param {THREE.Material} material A built-in material, patched in- * place. Clone a shared `materials.js` instance first.- * @param {object} [opts]- * `sources` up to 8 world points with colours — a Vector3, an- * `[x,y,z]`, or `{ position, color }`; `makeNeonTube().userData- * .spillSources()` hands back exactly this; `radius` metres the- * light reaches, ZERO beyond it (default 4); `strength` how bright- * the pool reads (default 1); `ambient` how bright the surroundings- * are, 0 an unlit street to 1 open daylight (default 0.15 — from- * 0.35 up the spill is cut back hard, because emissive added to an- * already-lit wall is the same clip); `flicker`/`seed` pass the SAME- * pair as the tube and the wall stutters with it (default 0, off);- * `name` the program cache key (default 'neon:spill' — every option- * here is a UNIFORM, so one name is correct and two differently lit- * walls still share one compiled program).- * @returns {THREE.Material} The same material; its uniforms live on- * `material.userData.uniforms`, so a scene can move or dim the- * sources per frame.- */-export function patchNeonSpill(material, opts = {}) {- const radius = Math.max(1e-3,- opts.radius === undefined ? 4 : opts.radius);- const strength = Math.max(0,- opts.strength === undefined ? 1 : opts.strength);- const ambient = Math.min(Math.max(- opts.ambient === undefined ? 0.15 : opts.ambient, 0), 1);- const flicker = Math.min(Math.max(- opts.flicker === undefined ? 0 : opts.flicker, 0), 1);- const list = (Array.isArray(opts.sources) ? opts.sources : [])- .slice(0, SPILL_MAX);- const pos = [], col = [];- for (let i = 0; i < SPILL_MAX; i++) {- const s = list[i];- const p = s && (s.position || s.point || s);- pos.push(readVec3(s && p));- col.push(s ? toColor(s.color, 0xff2e6a) : new THREE.Color(0, 0, 0));- }- return patchStandard(material, {- name: opts.name || 'neon:spill',- uniforms: {- uNeonPos: { value: pos },- uNeonCol: { value: col },- uNeonCount: { value: list.length },- uNeonRadius: { value: radius },- // Emissive added to a wall the sun already lit clips the- // same way an additive pass does, so the escape is a gain.- uNeonGain: { value: strength * (1 - 0.85 * ambient) },- uNeonFlicker: { value: flicker },- uNeonKey: { value: seedKey(opts.seed === undefined ? 3- : opts.seed) },- },- vertexHead: SPILL_VARYINGS,- vertexBody: SPILL_VERTEX,- fragmentHead: [SPILL_VARYINGS, SPILL_HEAD].join('\n'),- fragmentBody: SPILL_BODY,- });-}--/** A flat ribbon riding the road, u across and v along the arc. */-function ribbonGeometry(fr, offset, halfW, lift) {- const n = fr.length;- const pos = new Float32Array(n * 2 * 3);- const nor = new Float32Array(n * 2 * 3);- const uv = new Float32Array(n * 2 * 2);- const idx = new Uint32Array((n - 1) * 6);- const lat = new THREE.Vector3();- for (let i = 0; i < n; i++) {- lat.crossVectors(fr[i].t, _UP);- if (lat.lengthSq() < 1e-9) lat.set(1, 0, 0);- lat.normalize();- const v = i / (n - 1);- for (let s = 0; s < 2; s++) {- const k = (i * 2 + s);- const w = offset + (s === 0 ? -halfW : halfW);- pos[k * 3] = fr[i].p.x + lat.x * w;- pos[k * 3 + 1] = fr[i].p.y + lift;- pos[k * 3 + 2] = fr[i].p.z + lat.z * w;- nor[k * 3 + 1] = 1;- uv[k * 2] = s;- uv[k * 2 + 1] = v;- }- if (i < n - 1) {- const a = i * 2;- idx.set([a, a + 1, a + 2, a + 1, a + 3, a + 2], i * 6);- }- }- const g = new THREE.BufferGeometry();- g.setAttribute('position', new THREE.BufferAttribute(pos, 3));- g.setAttribute('normal', new THREE.BufferAttribute(nor, 3));- g.setAttribute('uv', new THREE.BufferAttribute(uv, 2));- g.setIndex(new THREE.BufferAttribute(idx, 1));- return g;-}--/**- * Comet-shaped pulses riding v, one lane per material.- *- * The head is a hot point and everything behind it is the smear a long- * exposure leaves; `uDir` flips which way along the path that is, so- * the two lanes run against each other from one shared source.- */-function trailMaterial(name, color, dir, count, rate, gain, hot, fore,- key, hazy, vary) {- const tint = hazy- ? color.clone().lerp(new THREE.Color(1, 1, 1), 0.20) : color.clone();- const hotv = hazy ? hot * 0.25 : hot;- return makeShaderMaterial({- name,- additive: !hazy,- uniforms: {- uColor: { value: tint },- uDir: { value: dir },- uCount: { value: count },- uRate: { value: rate },- uGain: { value: gain },- uHot: { value: hotv },- uFore: { value: fore },- uKey: { value: key },- uVary: { value: vary },- },- varyings: 'varying vec2 vTrailUv;',- vertexMain: ' vTrailUv = uv;',- fragmentHead: [- 'uniform vec3 uColor; uniform float uDir; uniform float uCount;',- 'uniform float uRate; uniform float uGain; uniform float uHot;',- 'uniform float uFore; uniform float uKey; uniform float uVary;',- TEMP_GLSL,- ].join('\n'),- fragmentMain: [- ' float u = vTrailUv.x * 2.0 - 1.0;',- ' float s = uDir * vTrailUv.y * uCount - uTime * uRate;',- ' float f = fract(s);',- ' float id = floor(s) + uKey;',- // A lane is not one vehicle: each sits at its own place- // across the lane and carries its own brightness.- ' float du = u - (astraHash11(id * 1.37) - 0.5) * 0.55;',- ' float amp = 0.45 + 1.0 * astraHash11(id * 2.13 + 3.1);',- ' float head = pow(f, 26.0);',- ' float tail = pow(f, 3.2);',- // A lamp lights the road IN FRONT of itself. Without this- // the smear stops dead at the head and the cut reads as a- // straight-edged slab laid across the lane.- ' float fore = exp(-f * 12.0) * uFore;',- ' float core = exp(-du * du * 26.0);',- // The road catching the same lamp: wider, dimmer, and the- // reason a streak is not a floating line. It must reach- // ZERO at the ribbon edge or the road wears a hard slab.- ' float rim = 1.0 - u * u;',- ' float wash = exp(-du * du * 2.2) * 0.42 * rim * rim;',- ' float ends = smoothstep(0.0, 0.05, vTrailUv.y)',- ' * (1.0 - smoothstep(0.95, 1.0, vTrailUv.y));',- ' float a = uGain * amp * ends',- ' * ((head + (tail + fore) * 0.42) * core',- ' + (tail + fore) * wash);',- ' a = 1.0 - exp(-a * 1.6);',- // No two vehicles carry the same lamp: halogen against cold- // LED one way, a braked tail-light against a coasting one- // the other.- ' float w = astraTrailTemp(id, uVary);',- ' vec3 lamp = astraHueShift(uColor, w)',- ' * vec3(1.0 + w, 1.0 + w * 0.15, 1.0 - w);',- ' vec3 c = mix(lamp, vec3(1.0), head * uHot);',- // The wash is a metre-wide ramp across tarmac: the one- // gradient in this effect wide enough to band.- ' a += (astraHash21(gl_FragCoord.xy + uKey) - 0.5) * 0.005;',- ' if (a < 0.003) discard;',- ' gl_FragColor = vec4(c, clamp(a, 0.0, 1.0));',- ].join('\n'),- transparent: true,- blending: hazy ? THREE.NormalBlending : THREE.AdditiveBlending,- side: THREE.DoubleSide,- depthWrite: false,- });-}--/**- * Head- and tail-light streaks along a road: motion in a still frame.- *- * Two ribbons laid on the road, one per lane, each carrying comet- * pulses that ride the path's own arc length — so the streaks BEND with- * the road instead of crossing it. Warm white runs one way and red the- * other, which is what tells a reader the traffic has two directions.- * The pulses ADD light, correct over the dark frame a night road is and- * wrong over a bright one; `ambient` is the escape.- *- * @param {object} [opts]- * `path` the road centreline as a polyline (`[[x,y,z], ...]` or- * Vector3s; default a 40 m straight); `count` streaks per lane- * (default 5); `speed` metres per second along the path (default 14);- * `warm` the lane running FORWARD along the path, head-lights- * (default 0xffeec8); `cool` the lane running back, tail-lights- * (default 0xff1e14 — `cool` names the lane, not the hue). Each is- * the lane's MEAN: every vehicle rotates a few degrees off it, so a- * lane reads as traffic rather than as eight copies of one lamp;- * `width`- * streak width in metres (default 0.5; the ribbon carrying its wash- * is six times that, so the road wants `2 * lane + 6 * width` of- * tarmac); `lane` metres from the centreline to each lane (default- * width * 4); `lift` metres above- * the road (default 0.03, enough to clear z-fighting); `ambient`- * 0 an unlit street to 1 open daylight (default 0.15 — from 0.35 up- * the streaks turn pale and normal-blended instead of clipping);- * `seed` per-vehicle jitter (default 7).- * @returns {THREE.Group} Named `LightTrails`, holding `TrailsWarm` and- * `TrailsCool`, guarded by `keepOutOfDepthPasses` (an additive card- * is an opaque wall to the GTAO override pass, and a moving light- * must cast no shadow), with `userData.update(t)`.- */-export function makeLightTrails(opts = {}) {- const strokes = toStrokes(opts.path && opts.path.length ? opts.path- : [[0, 0, -20], [0, 0, 20]]);- const count = Math.max(1, Math.round(- opts.count === undefined ? 5 : opts.count));- const speed = opts.speed === undefined ? 14 : opts.speed;- const width = Math.max(0.02,- opts.width === undefined ? 0.5 : opts.width);- const lane = opts.lane === undefined ? width * 4 : opts.lane;- const lift = opts.lift === undefined ? 0.03 : opts.lift;- const ambient = Math.min(Math.max(- opts.ambient === undefined ? 0.15 : opts.ambient, 0), 1);- const key = seedKey(opts.seed === undefined ? 7 : opts.seed);- const hazy = ambient >= 0.35;-- const g = new THREE.Group();- g.name = 'LightTrails';- if (!strokes.length) {- g.userData.update = g.userData.tick = () => {};- return attachDisposal(g, []);- }- const line = strokes[0];- const smooth = filletPath(line, Math.max(lane, width) * 2);- const rough = resample(smooth, 4).length;- const r = resample(smooth, Math.min(600, Math.max(24,- Math.round(rough * 1.5))));- const fr = frames(r.pts);- // Pulses per second along the path: `speed` is metres, and v is- // metres because the stations were spaced by arc length.- const rate = speed * count / Math.max(r.length, 1e-3);- const gain = hazy ? 0.55 : 1.15;- const half = width * 3;- // 0.5, not 0.7, on the head-lights: a lamp that whitens hard has- // no colour temperature left to vary, and the white it clips to is- // the last thing the frame records — the post chain's bloom only- // haloes it.- g.add(laneMesh(fr, -lane, half, lift, trailMaterial(- 'NeonTrailWarm', toColor(opts.warm, 0xffeec8), 1, count, rate,- gain, 0.5, 0.60, key, hazy, 0.40), 'TrailsWarm'));- g.add(laneMesh(fr, lane, half, lift, trailMaterial(- 'NeonTrailCool', toColor(opts.cool, 0xff1e14), -1, count, rate,- gain, 0.15, 0.22, key + 5.3, hazy, 0.16), 'TrailsCool'));- g.userData.update = g.userData.tick = (t) => tickShaders(g, t);- keepOutOfDepthPasses(g);- return attachDisposal(g, snapshotResources(g));-}--/** One lane's ribbon, named so a test and a composer can find it. */-function laneMesh(fr, offset, halfW, lift, material, name) {- const mesh = new THREE.Mesh(- ribbonGeometry(fr, offset, halfW, lift), material);- mesh.name = name;- mesh.renderOrder = 2;- return mesh;-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ocean.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ocean.jsdeleted file mode 100644index deccd780..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ocean.js+++ /dev/null@@ -1,525 +0,0 @@-/**- * Displaced, reflective ocean. Metres, Y up, local XZ surface at mean y=0.- * Thirty-two directional Gerstner bands use gravity-wave dispersion omega²=gk tanh(kd),- * with analytic surface derivatives and compression-driven whitecaps. This is a- * deterministic real-time approximation, NOT an FFT spectrum or fluid solver.- * Planar reflections approximate the mean sea plane (one extra scene render).- * One reflecting surface per scene; do not combine with Water/Reflector floors.- * References: NVIDIA GPU Gems ch. 1 (directional Gerstner waves), and- * Bruneton, Neyret & Holzschuch, Real-time Realistic Ocean Lighting (2010),- * https://hal.science/inria-00443630 . The slope-variance- * filtering here is a compact approximation, not their full anisotropic BRDF.- * Equirectangular scene environments supply directional sky reflection; actual- * nearby objects retain the mean-plane RTT reflection. Cube/PMREM environments- * fall back to the reflection image. No screen-space refraction or fluid solve.- */-import * as THREE from 'three';-import { attachDisposal, snapshotResources } from './lifecycle.js';-import { mulberry32 } from './noise.js';-import { boundedSampler, GLSL_UTIL, makeLightProbe, option, planarCapture, readWind, vector } from './shader.js';-import { Reflector } from 'three/addons/objects/Reflector.js';--const TAU = Math.PI * 2;-const COUNT = 32;-const waveGLSL = /* glsl */ `-uniform float seaTime;-uniform vec4 seaWaves[32];-uniform vec2 seaPhases[32];-uniform float seaChop;-uniform vec4 seaShore;-uniform float seaShoreWidth;-float shoreFactor(vec2 q) {- float d = dot(q, seaShore.xy) - seaShore.z;- return mix(1.0, smoothstep(-0.5, seaShoreWidth * 1.7, d), seaShore.w);-}-void seaSurface(vec2 q, float footprint, out vec3 p, out vec3 n,- out float compression, out float unresolvedVariance) {- p=vec3(q.x,0.0,q.y);- vec3 dx=vec3(1.0,0.0,0.0), dz=vec3(0.0,0.0,1.0);- float shoal=shoreFactor(q);- vec2 shoalD=vec2(shoreFactor(q+vec2(.005,0.0))-shoreFactor(q-vec2(.005,0.0)),- shoreFactor(q+vec2(0.0,.005))-shoreFactor(q-vec2(0.0,.005)))/.01;- unresolvedVariance=0.0;- for(int i=0;i<32;i++) {- vec4 w=seaWaves[i];- float phase=w.w*dot(w.xy,q)-seaPhases[i].x*seaTime+seaPhases[i].y;- float sn=sin(phase),cs=cos(phase);- // The normal field is integrated over the pixel footprint. Missing slopes- // become BRDF roughness rather than vanishing or aliasing into bright lines.- float resolved=exp(-.5*pow(w.w*footprint*.55,2.0));- float amplitude=w.z*resolved;- float a=amplitude*shoal,h=seaChop*amplitude;- unresolvedVariance+=.5*pow(w.z*w.w*shoal,2.0)*(1.0-resolved*resolved);- p+=vec3(h*shoal*w.x*cs,a*sn,h*shoal*w.y*cs);- float cx=shoalD.x*cs-shoal*w.w*w.x*sn;- float cz=shoalD.y*cs-shoal*w.w*w.y*sn;- dx+=vec3(h*w.x*cx,amplitude*(shoalD.x*sn+shoal*w.w*w.x*cs),h*w.y*cx);- dz+=vec3(h*w.x*cz,amplitude*(shoalD.y*sn+shoal*w.w*w.y*cs),h*w.y*cz);- }- n=normalize(cross(dz,dx));- compression=1.0-(dx.x*dz.z-dx.z*dz.x);-}-`;-const vertex = /* glsl */ `-uniform mat4 textureMatrix;-varying vec4 seaMirror;-varying vec3 seaWorld;-varying vec2 seaRest;-#include <common>-#include <fog_pars_vertex>-#include <shadowmap_pars_vertex>-#include <logdepthbuf_pars_vertex>-${waveGLSL}-void main() {- seaRest=vec2(position.x,-position.y);- vec3 p,n; float compression,variance;- seaSurface(seaRest,0.0,p,n,compression,variance);- vec3 transformed=vec3(p.x,-p.z,p.y);- vec3 objectNormal=vec3(n.x,-n.z,n.y);- #include <defaultnormal_vertex>- vec4 worldPosition=modelMatrix*vec4(transformed,1.0);- seaWorld=worldPosition.xyz;- seaMirror=textureMatrix*vec4(transformed,1.0);- vec4 mvPosition=modelViewMatrix*vec4(transformed,1.0);- gl_Position=projectionMatrix*mvPosition;- #include <logdepthbuf_vertex>- #include <fog_vertex>- #include <shadowmap_vertex>-}-`;-const fragment = /* glsl */ `-uniform sampler2D tDiffuse;-uniform sampler2D seaReflectionDepth;-uniform sampler2D seaEnvironment;-uniform float seaEnvironmentEnabled;-uniform float seaEnvironmentIntensity;-uniform mat3 seaEnvironmentRotation;-uniform float seaCompressionRms;-uniform vec3 color;-uniform vec3 seaDeep;-uniform vec3 seaShallow;-uniform vec3 seaSun;-uniform vec3 seaSunColor;-uniform vec3 seaAmbient;-uniform vec3 seaKey;-uniform float seaFoam;-uniform float seaHeightScale;-uniform float seaReflectionSize;-uniform vec2 seaWind;-uniform mat3 seaRotation;-varying vec4 seaMirror;-varying vec3 seaWorld;-varying vec2 seaRest;-#include <common>-#include <packing>-#include <bsdfs>-#include <fog_pars_fragment>-#include <logdepthbuf_pars_fragment>-#include <lights_pars_begin>-#include <shadowmap_pars_fragment>-#include <shadowmask_pars_fragment>-${waveGLSL}-${GLSL_UTIL}-vec3 seaNoiseGradient(vec2 p) {- vec2 i=floor(p),f=fract(p),u=f*f*(3.0-2.0*f),du=6.0*f*(1.0-f);- float a=astraHash21(i),b=astraHash21(i+vec2(1,0)),c=astraHash21(i+vec2(0,1)),d=astraHash21(i+vec2(1,1));- return vec3(mix(mix(a,b,u.x),mix(c,d,u.x),u.y),- mix(b-a,d-c,u.y)*du.x,mix(c-a,d-b,u.x)*du.y);-}-float seaFbm(vec2 q) {- return astraNoise2(q)*.57+astraNoise2(q*2.13+7.2)*.28+astraNoise2(q*4.31)*.15;-}-// Dielectric water Fresnel uses air/water indices, not a tinted metal lobe.-float seaFresnel(float c) {- c=clamp(c,0.0,1.0);- float g=sqrt(1.333*1.333-1.0+c*c);- float a=(g-c)/(g+c), b=(c*(g+c)-1.0)/(c*(g-c)+1.0);- return .5*a*a*(1.0+b*b);-}-float seaGGX(float alpha,float nh,float nv,float nl) {- float a2=alpha*alpha;- float denominator=nh*nh*(a2-1.0)+1.0;- float distribution=a2/(PI*denominator*denominator);- float visibility=.5/max(nl*sqrt(nv*nv*(1.0-a2)+a2)- +nv*sqrt(nl*nl*(1.0-a2)+a2),.0001);- return distribution*visibility;-}-void main() {- #include <logdepthbuf_fragment>- vec2 q=seaRest;- float footprint=max(length(dFdx(q)),length(dFdy(q)));- vec3 p,localNormal; float compression,variance;- seaSurface(q,footprint,p,localNormal,compression,variance);- // Advected broadband wind-ripple slopes fill the sub-metre range without- // the visible directional comb made by a handful of capillary sine waves.- // Analytic noise gradients stay continuous and feed lost variance into GGX.- vec2 slope=vec2(0.0);- vec2 crossWind=vec2(-seaWind.y,seaWind.x);- mat2 frame=mat2(seaWind,crossWind);- vec2 aligned=vec2(dot(q,seaWind),dot(q,crossWind));- for(int i=0;i<5;i++) {- float fi=float(i),frequency=3.7*pow(2.07,fi);- float slopeAmplitude=.095/(1.0+fi*.13);- float resolved=exp(-.5*pow(frequency*footprint*.8,2.0));- vec2 flow=vec2(seaTime*(.11+.031*fi),sin(fi*3.4)*seaTime*.026);- vec3 field=seaNoiseGradient(aligned*vec2(1.0,1.35)*frequency-flow+seaPhases[i].y*7.3);- slope+=frame*(field.yz*vec2(1.0,1.35))*slopeAmplitude*resolved;- variance+=.15*slopeAmplitude*slopeAmplitude*(1.0-resolved*resolved);- }- localNormal=normalize(localNormal+vec3(-slope.x,0.0,-slope.y));- vec3 n=normalize(seaRotation*localNormal);- vec3 eyeDir=normalize(cameraPosition-seaWorld);- float nv=max(dot(n,eyeDir),.001);- float alpha=clamp(sqrt(.0025+variance),.05,.42);- // Average Fresnel over the unresolved normal cone. This is a compact- // quadrature, not the exact anisotropic ocean BRDF from Bruneton et al.- float fresnel=seaFresnel(nv);- fresnel=(fresnel*2.0+seaFresnel(clamp(nv+alpha,0.0,1.0))- +seaFresnel(clamp(nv-alpha,0.0,1.0)))*.25;- // Mip-filter the reflection by unresolved slope variance. A perfectly sharp- // planar sample beside a rough sun lobe was the old polished-plastic cue.- vec3 normalView=mat3(viewMatrix)*n;- vec3 meanView=mat3(viewMatrix)*normalize(seaRotation*vec3(0,1,0));- vec2 distortion=(normalView.xy-meanView.xy)*.075;- vec2 reflectedUV=seaMirror.xy/seaMirror.w+distortion;- float lod=clamp(log2(max(1.0,alpha*seaReflectionSize*.15)),0.0,9.0);- vec3 reflected=texture2DLodEXT(tDiffuse,clamp(reflectedUV,vec2(.002),vec2(.998)),lod).rgb;- vec3 diffuseSky=seaAmbient;- if(seaEnvironmentEnabled>.5) {- vec3 reflectionDirection=normalize(reflect(-eyeDir,n));- reflectionDirection=seaEnvironmentRotation*reflectionDirection;- float skyVisibility=smoothstep(-.16,.09,reflectionDirection.y);- reflectionDirection.y=max(.008,reflectionDirection.y);- reflectionDirection=normalize(reflectionDirection);- vec3 tangent=normalize(cross(reflectionDirection,abs(reflectionDirection.y)<.99?vec3(0,1,0):vec3(1,0,0)));- vec3 bitangent=cross(reflectionDirection,tangent);- vec3 env=texture2D(seaEnvironment,equirectUv(reflectionDirection)).rgb*.4;- env+=texture2D(seaEnvironment,equirectUv(normalize(reflectionDirection+tangent*alpha*1.8))).rgb*.15;- env+=texture2D(seaEnvironment,equirectUv(normalize(reflectionDirection-tangent*alpha*1.8))).rgb*.15;- env+=texture2D(seaEnvironment,equirectUv(normalize(reflectionDirection+bitangent*alpha*1.8))).rgb*.15;- env+=texture2D(seaEnvironment,equirectUv(normalize(reflectionDirection-bitangent*alpha*1.8))).rgb*.15;- // A downward reflected ray on a continuous sea meets another wave, not- // the terrestrial ground hemisphere of the scene's environment map.- // The second wave still reflects the bright horizon at a grazing angle.- // Replacing it with dark body colour produces implausible black hatch lines.- env=mix(env*.72+seaDeep*(seaAmbient+seaKey*.24)*.28,env,skyVisibility);- // Five cosine-weighted upper-hemisphere samples estimate the broad sky- // irradiance on diffuse whitecaps. A stylized fill light can be purple even- // when the visible/environment sky is blue; foam should reflect that sky.- diffuseSky=texture2D(seaEnvironment,equirectUv(seaEnvironmentRotation*vec3(0,1,0))).rgb*.25;- diffuseSky+=texture2D(seaEnvironment,equirectUv(seaEnvironmentRotation*vec3(.8165,.57735,0))).rgb*.1875;- diffuseSky+=texture2D(seaEnvironment,equirectUv(seaEnvironmentRotation*vec3(-.8165,.57735,0))).rgb*.1875;- diffuseSky+=texture2D(seaEnvironment,equirectUv(seaEnvironmentRotation*vec3(0,.57735,.8165))).rgb*.1875;- diffuseSky+=texture2D(seaEnvironment,equirectUv(seaEnvironmentRotation*vec3(0,.57735,-.8165))).rgb*.1875;- diffuseSky*=seaEnvironmentIntensity;- float reflectionDepth=texture2D(seaReflectionDepth,clamp(reflectedUV,vec2(.002),vec2(.998))).r;- // Keep actual reflected coast/rocks. Only sky pixels use the directional- // environment, so their reflection follows the full wave normal instead- // of stretching a screen-space sky pixel into long glossy streaks.- reflected=mix(reflected,env*seaEnvironmentIntensity,step(.99999,reflectionDepth));- }- float shade=getShadowMask();- float nl=max(dot(n,seaSun),0.0);- float coastDistance=dot(q,seaShore.xy)-seaShore.z;- float shallowness=seaShore.w*(1.0-smoothstep(0.0,seaShoreWidth*3.0,coastDistance));- vec3 body=mix(seaDeep,seaShallow,shallowness*.75);- // Scattering under the interface is broad; it must not print the surface- // normal's Lambert stripes onto every wave face like opaque painted plastic.- vec3 ambient=seaAmbient;- vec3 scatter=body*(ambient*1.2+seaKey*.80*shade);- float back=pow(max(dot(eyeDir,-seaSun),0.0),5.0);- float thinCrest=smoothstep(.10,.65,p.y/seaHeightScale);- scatter+=seaShallow*seaKey*back*thinCrest*.28*shade;- vec3 halfDir=normalize(eyeDir+seaSun);- float nh=max(dot(n,halfDir),0.0),vh=max(dot(eyeDir,halfDir),0.0);- float sunAlpha=sqrt(alpha*alpha+.00465*.00465);- vec3 specular=seaKey*PI*seaFresnel(vh)*seaGGX(sunAlpha,nh,nv,nl)*nl*shade;- vec2 foamUV=q-seaWind*seaTime*.23;- float patches=seaFbm(foamUV*.61+vec2(astraNoise2(q*.22),astraNoise2(q*.22+8.1))*1.5);- float breakingThreshold=max(.15,seaCompressionRms*1.5);- float crest=smoothstep(breakingThreshold,breakingThreshold+.11,compression)- *smoothstep(.06,.35,p.y/seaHeightScale);- crest*=smoothstep(.38,.62,patches);- float incoming=sin(coastDistance*1.4-seaTime*1.15+astraNoise2(q*.3)*2.1);- float coast=seaShore.w*(1.0-smoothstep(.1,seaShoreWidth,abs(coastDistance)))- *smoothstep(.45,.90,incoming+patches*.25)*smoothstep(.33,.66,patches);- float bubble=seaFbm(foamUV*9.0);- float detailFade=exp(-footprint*24.0);- float coverage=mix(.8,smoothstep(.26,.68,bubble),detailFade);- float foam=clamp((crest*1.7+coast)*seaFoam*coverage,0.0,.98);- vec3 foamLight=diffuseSky+seaKey*nl*shade;- vec3 foamColor=vec3(.76,.79,.76)*foamLight;- vec3 outgoing=mix(scatter*(1.0-fresnel)+reflected*fresnel+specular,foamColor,foam);- gl_FragColor=vec4(outgoing,1.0);- #include <tonemapping_fragment>- #include <colorspace_fragment>- #include <fog_fragment>-}-`;--/**- * @param {object} [opts]- * width/depth (metres); waveHeight (significant wave height Hs); wavelength (m);- * windDirection [x,z]; waterDepth (m); choppiness [0,1]; foam [0,2]; seed;- * segments [16,384] along the longest edge; reflectionSize [64,2048];- * waterColor/shallowColor; optional sunDir THREE.Vector3 or [x,y,z] (`sunDirection` is read too).- * shoreline: {direction:[x,z],position,width}; water is on the positive side- * of dot(localXZ,direction)-position. It softens waves and adds swash foam.- * Return Group: .userData.update(t,dt), sampleHeight(x,z,t), sampleSurface(x,z,t),- * dispose(). Sampling uses LOCAL group coordinates, absolute seconds. Group may- * be translated/rotated/scaled. Local heights are not world-space raycasts.- */-export function makeOceanSurface(opts = {}) {- let disposed = false;- const width = option(opts.width, 160, 'makeOceanSurface: width', 1, 10000),- depth = option(opts.depth, 160, 'makeOceanSurface: depth', 1, 10000);- const height = option(opts.waveHeight, 1.2, 'makeOceanSurface: waveHeight', 0, 20);- const length = option(opts.wavelength, 18, 'makeOceanSurface: wavelength', 1, 500);- const waterDepth = option(opts.waterDepth, 24, 'makeOceanSurface: waterDepth', 0.1, 10000);- const chop = option(opts.choppiness, 0.85, 'makeOceanSurface: choppiness', 0, 1);- const foam = option(opts.foam, 0.8, 'makeOceanSurface: foam', 0, 2);- const segments = Math.round(option(opts.segments, 160, 'makeOceanSurface: segments', 16, 384));- const reflectionSize = Math.round(- option(opts.reflectionSize, 512, 'makeOceanSurface: reflectionSize', 64, 2048)- );- const seed = option(opts.seed, 42, 'makeOceanSurface: seed');- const wind = readWind(opts.windDirection, [1, 0.2], 'makeOceanSurface windDirection');- if (Math.hypot(wind.x, wind.z) < 1e-8)- throw new RangeError('makeOceanSurface: windDirection must be a nonzero [x,z]');- const windAngle = Math.atan2(wind.z, wind.x);- const rng = mulberry32(seed),- waves = [],- phases = [];- // Sample a gravity-wave energy envelope in logarithmic wavenumber bands.- // For deep water E(k) is proportional to k^-3 exp[-1.25(kp/k)^2].- // Multiplying by the logarithmic bin width gives each component's variance.- // This finite directional quadrature is not an FFT/JONSWAP simulation.- let varianceSum = 0;- for (let i = 0; i < COUNT; i++) {- const band = (i + 0.18 + rng() * 0.64) / COUNT;- const waveLength = length * 2.6 * Math.pow(0.065 / 2.6, band);- const k = TAU / waveLength;- const relativeLength = waveLength / length;- const spread = 0.32 + 0.95 * band;- const angle = windAngle + (rng() - 0.5) * spread * 2;- const amplitude =- relativeLength *- Math.exp(-0.625 * relativeLength * relativeLength) *- (0.78 + rng() * 0.44);- waves.push(new THREE.Vector4(Math.cos(angle), Math.sin(angle), amplitude, k));- phases.push(- new THREE.Vector2(Math.sqrt(9.81 * k * Math.tanh(k * waterDepth)), rng() * TAU)- );- varianceSum += amplitude * amplitude;- }- // Hs = 4 sigma for a random-phase sea; the public waveHeight is its sea-state- // scale, not an impossible promise that no individual wave exceeds it.- const amplitudeScale = height / (4 * Math.sqrt(0.5 * varianceSum));- for (const wave of waves) wave.z *= amplitudeScale;- const steepness = waves.reduce((s, w) => s + w.z * w.w, 0);- let shore = new THREE.Vector4(0, 1, 0, 0),- shoreWidth = 5;- if (opts.shoreline) {- const spec = opts.shoreline,- direction = spec.direction ?? [0, 1];- if (- !Array.isArray(direction) ||- direction.length !== 2 ||- !direction.every(Number.isFinite) ||- Math.hypot(...direction) < 1e-8- )- throw new RangeError('makeOceanSurface: invalid shoreline.direction');- const norm = Math.hypot(...direction);- shore = new THREE.Vector4(- direction[0] / norm,- direction[1] / norm,- option(spec.position, 0, 'makeOceanSurface: shoreline.position', -10000, 10000),- 1- );- shoreWidth = option(spec.width, 5, 'makeOceanSurface: shoreline.width', 0.1, 500);- }- // Bound BOTH the wave derivative and the changing shoaling envelope. A- // narrow beach under large waves otherwise folds horizontal coordinates,- // making a queried height multi-valued and fixed-point inversion diverge.- const shoreGradient = shore.w ? 1.5 / (shoreWidth * 1.7 + 0.5) : 0;- const derivativeBound = steepness + waves.reduce((sum, w) => sum + w.z, 0) * shoreGradient;- const chopScale = chop * Math.min(1.1, 0.88 / Math.max(derivativeBound, 1e-8));- const sunOption = opts.sunDir ?? opts.sunDirection;- const sun = new THREE.Vector3(...vector(sunOption, [0.6, 0.7, 0.3], 3, 'makeOceanSurface: sunDir'));- if (sun.length() < 1e-8) throw new RangeError('makeOceanSurface: sunDir must be nonzero');- sun.normalize();- const uniforms = THREE.UniformsUtils.merge([- THREE.UniformsLib.fog,- THREE.UniformsLib.lights,- {- color: { value: new THREE.Color(0xffffff) },- tDiffuse: { value: null },- textureMatrix: { value: new THREE.Matrix4() },- seaTime: { value: 0 },- seaWaves: { value: waves },- seaPhases: { value: phases },- seaChop: { value: chopScale },- seaShore: { value: shore },- seaShoreWidth: { value: shoreWidth },- seaFoam: { value: foam },- seaHeightScale: { value: Math.max(height, 0.01) },- seaReflectionSize: { value: reflectionSize },- seaReflectionDepth: { value: null },- seaEnvironment: { value: null },- seaEnvironmentEnabled: { value: 0 },- seaEnvironmentIntensity: { value: 1 },- seaEnvironmentRotation: { value: new THREE.Matrix3() },- seaCompressionRms: {- value: Math.sqrt(waves.reduce((sum, w) => sum + 0.5 * (chopScale * w.z * w.w) ** 2, 0)),- },- seaDeep: { value: new THREE.Color(opts.waterColor ?? 0x083e4d) },- seaShallow: { value: new THREE.Color(opts.shallowColor ?? 0x248d88) },- seaSun: { value: sun },- seaSunColor: { value: new THREE.Color(0xffffff) },- seaAmbient: { value: new THREE.Color(0.28, 0.36, 0.43) },- seaKey: { value: new THREE.Color(0.8, 0.8, 0.8) },- seaWind: { value: wind.dir.clone() },- seaRotation: { value: new THREE.Matrix3() },- },- ]);- const nx = Math.max(8, Math.round((segments * width) / Math.max(width, depth)));- const nz = Math.max(8, Math.round((segments * depth) / Math.max(width, depth)));- const geometry = new THREE.PlaneGeometry(width, depth, nx, nz);- // Concentrate samples around the local origin: near-camera crests remain- // curved while distant water does not spend the same triangles per metre.- // A sinh distribution preserves useful near-field density even at kilometre- // extents; the old power law lost that density when the horizon moved out.- const grid = geometry.attributes.position;- const gridFocus = Math.max(3, Math.log(Math.max(width, depth) / 16) + 2.5);- for (let i = 0; i < grid.count; i++) {- const x = grid.getX(i) / (width * 0.5),- y = grid.getY(i) / (depth * 0.5);- grid.setXY(- i,- (Math.sinh(x * gridFocus) / Math.sinh(gridFocus)) * width * 0.5,- (Math.sinh(y * gridFocus) / Math.sinh(gridFocus)) * depth * 0.5- );- }- grid.needsUpdate = true;- const sea = new Reflector(geometry, {- textureWidth: reflectionSize,- textureHeight: reflectionSize,- multisample: 0,- shader: {- name: 'DisplacedOcean',- uniforms,- vertexShader: vertex,- fragmentShader: fragment,- },- });- sea.getRenderTarget().depthTexture = new THREE.DepthTexture(- reflectionSize,- reflectionSize,- THREE.UnsignedIntType- );- sea.material.uniforms.seaReflectionDepth.value = sea.getRenderTarget().depthTexture;- sea.getRenderTarget().texture.generateMipmaps = true;- sea.getRenderTarget().texture.minFilter = THREE.LinearMipmapLinearFilter;- sea.name = 'OceanSurface';- sea.rotation.x = -Math.PI / 2;- sea.material.lights = true;- sea.material.fog = true;- sea.receiveShadow = true;- const group = new THREE.Group();- group.name = opts.name ?? 'Ocean';- group.add(sea);- group.userData.placement = 'free';- // Shader displacement needs a conservative bound for frustum/scene probes:- // crests reach the amplitude sum (local z), chop moves them by chopScale times it.- const reach = waves.reduce((sum, w) => sum + w.z, 0);- geometry.computeBoundingBox();- geometry.boundingBox.expandByVector(new THREE.Vector3(chopScale * reach, chopScale * reach, reach));- geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());- const u = sea.material.uniforms,- base = sea.onBeforeRender;- const readLights = makeLightProbe(), environmentRotation = new THREE.Matrix4();- // One guarded colour-pass capture: never in override (GTAO/depth) passes or- // nested captures, renderer state restored, rigid mirror frame under scale.- planarCapture(sea, (renderer, scene, camera, toRigid) => {- const environment = scene.environment;- const equirect =- environment &&- (environment.mapping === THREE.EquirectangularReflectionMapping ||- environment.mapping === THREE.EquirectangularRefractionMapping);- u.seaEnvironmentEnabled.value = equirect ? 1 : 0;- u.seaEnvironment.value = equirect ? environment : null;- u.seaEnvironmentIntensity.value = scene.environmentIntensity ?? 1;- if (scene.environmentRotation) {- u.seaEnvironmentRotation.value.setFromMatrix4(- environmentRotation.makeRotationFromEuler(scene.environmentRotation).invert()- );- }- const { sun: key, sunDirection, ambient, sky } = readLights(scene);- u.seaKey.value.setRGB(0, 0, 0);- u.seaSunColor.value.setRGB(0, 0, 0);- u.seaAmbient.value.copy(ambient).add(sky).multiplyScalar(1 / Math.PI);- if (key) {- if (sunOption === undefined || sunOption === null) u.seaSun.value.copy(sunDirection);- u.seaSunColor.value.copy(key.color);- u.seaKey.value.copy(key.color).multiplyScalar(key.intensity / Math.PI);- }- group.updateWorldMatrix(true, false);- u.seaRotation.value.getNormalMatrix(group.matrixWorld);- base.call(sea, renderer, scene, camera);- u.textureMatrix.value.multiply(toRigid);- }, { skip: () => disposed });- let time = 0;- const smooth = (x) => {- x = Math.max(0, Math.min(1, x));- return x * x * (3 - 2 * x);- };- const shoreAt = (x, z) =>- shore.w- ? smooth((x * shore.x + z * shore.y - shore.z + 0.5) / (shoreWidth * 1.7 + 0.5))- : 1;- function evaluate(x, z, t) {- const s = shoreAt(x, z),- p = new THREE.Vector3(x, 0, z);- for (let i = 0; i < COUNT; i++) {- const w = waves[i],- phase = w.w * (w.x * x + w.y * z) - phases[i].x * t + phases[i].y;- p.x += chopScale * w.z * s * w.x * Math.cos(phase);- p.z += chopScale * w.z * s * w.y * Math.cos(phase);- p.y += w.z * s * Math.sin(phase);- }- return p;- }- group.userData.update = (t) => {- if (!Number.isFinite(t)) throw new RangeError('makeOceanSurface: time must be finite');- time = t;- u.seaTime.value = t;- };- group.userData.sampleSurface = (x, z, t = time) => {- if (![x, z, t].every(Number.isFinite))- throw new RangeError('makeOceanSurface: sampling coordinates/time must be finite');- let qx = x,- qz = z;- // Fixed-point inversion: return height at the displaced XZ, not at its rest vertex.- for (let i = 0; i < 128; i++) {- const p = evaluate(qx, qz, t);- const ex = x - p.x,- ez = z - p.z;- qx += ex;- qz += ez;- if (ex * ex + ez * ez < 1e-14) break;- }- const position = evaluate(qx, qz, t),- dx = evaluate(qx + 0.005, qz, t).sub(evaluate(qx - 0.005, qz, t));- const dz = evaluate(qx, qz + 0.005, t).sub(evaluate(qx, qz - 0.005, t));- return { position, normal: dz.cross(dx).normalize() };- };- group.userData.sampleHeight = boundedSampler(width, depth,- (x, z, t = time) => group.userData.sampleSurface(x, z, t).position.y);- const owned = snapshotResources(group).add(sea.getRenderTarget());- owned.add({ dispose() { disposed = true; } });- attachDisposal(group, owned);- group.userData.surface = sea;- group.userData.description =- '32-band dispersive Gerstner ocean; mean-plane reflection; no fluid interaction or overturning breakers';- return group;-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/paving.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/paving.jsdeleted file mode 100644index 07f177e0..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/paving.js+++ /dev/null@@ -1,243 +0,0 @@-/** Foreground paving with closed stones, rounded cut edges and recessed joints.- * Units are metres. The nominal walking surface is local y=0, the underside- * is -thickness; relief varies the stones around that nominal surface.- * sampleHeight(x,z) follows the actual Float32 triangles and the joint bed,- * returning null outside the rectangular patch. It uses LOCAL coordinates.- * Two merged meshes keep draw cost independent of the number of stones.- */-import * as THREE from 'three';-import { mulberry32, fbm2 } from './noise.js';-import { boundedSampler, patchStandard } from './shader.js';-import { attachDisposal, snapshotResources } from './lifecycle.js';--const clamp=(x,a,b)=>Math.max(a,Math.min(b,x));-const lerp=(a,b,t)=>a+(b-a)*t;-const mixPoint=(a,b,t)=>[lerp(a[0],b[0],t),lerp(a[1],b[1],t)];--function clip(poly,nx,nz,limit) {- const out=[];- for(let i=0;i<poly.length;i++) {- const a=poly[i],b=poly[(i+1)%poly.length];- const da=a[0]*nx+a[1]*nz-limit,db=b[0]*nx+b[1]*nz-limit;- if(da<=1e-12)out.push(a);- if(da*db<0)out.push(mixPoint(a,b,da/(da-db)));- }- return out.filter((p,i)=>Math.hypot(p[0]-out[(i+out.length-1)%out.length][0],- p[1]-out[(i+out.length-1)%out.length][1])>1e-9);-}--function inset(poly,distance) {- let out=poly;- for(let i=0;i<poly.length&&out.length>2;i++) {- const a=poly[i],b=poly[(i+1)%poly.length];- const length=Math.hypot(b[0]-a[0],b[1]-a[1]);- const nx=(b[1]-a[1])/length,nz=-(b[0]-a[0])/length;- out=clip(out,nx,nz,a[0]*nx+a[1]*nz-distance);- }- return out;-}--function cells(width,depth,stoneSize,pattern,rand) {- // Cap the grid before allocating. Extreme aspect ratios still retain one- // row, so the bound remains meaningful for long, narrow paths.- let nx=Math.max(1,Math.ceil(width/stoneSize));- let nz=Math.max(1,Math.ceil(depth/stoneSize));- const budget=pattern==='setts'?2048:4096;- const factor=Math.sqrt(nx*nz/budget);- if(factor>1){nx=Math.max(1,Math.floor(nx/factor));nz=Math.max(1,Math.floor(nz/factor));}- if(nx*nz>budget){if(nx>nz)nx=Math.floor(budget/nz);else nz=Math.floor(budget/nx);}- const sx=width/nx,sz=depth/nz,result=[];- if(pattern==='setts') {- for(let row=0;row<nz;row++) {- const shift=(row%2)*sx*.5,bounds=[-width/2];- for(let col=1;col<=nx;col++) {- const x=-width/2+col*sx-shift+(rand()-.5)*sx*.14;- if(x>-width/2+sx*.12&&x<width/2-sx*.12)bounds.push(x);- }- bounds.push(width/2);- for(let col=0;col<bounds.length-1;col++)result.push([- [bounds[col],-depth/2+row*sz],[bounds[col+1],-depth/2+row*sz],- [bounds[col+1],-depth/2+(row+1)*sz],[bounds[col],-depth/2+(row+1)*sz],- ]);- }- } else {- const sites=[];- for(let z=0;z<nz;z++)for(let x=0;x<nx;x++)sites.push([- -width/2+(x+.5+(rand()-.5)*.78)*sx,- -depth/2+(z+.5+(rand()-.5)*.78)*sz,- ]);- // Neighbor bounds are derived from physical distances. A fixed +/-2- // index window would miss neighbors when the last row is very narrow.- const rx=Math.ceil(3*Math.max(sx,sz)/sx),rz=Math.ceil(3*Math.max(sx,sz)/sz);- for(let z=0;z<nz;z++)for(let x=0;x<nx;x++) {- const a=sites[z*nx+x];- let poly=[[-width/2,-depth/2],[width/2,-depth/2],[width/2,depth/2],[-width/2,depth/2]];- for(let j=Math.max(0,z-rz);j<=Math.min(nz-1,z+rz)&&poly.length>2;j++)- for(let i=Math.max(0,x-rx);i<=Math.min(nx-1,x+rx)&&poly.length>2;i++) {- if(i===x&&j===z)continue;- const b=sites[j*nx+i],dx=b[0]-a[0],dz=b[1]-a[1];- poly=clip(poly,dx,dz,(b[0]*b[0]+b[1]*b[1]-a[0]*a[0]-a[1]*a[1])/2);- }- result.push(poly);- }- }- return {polygons:result,spacing:Math.min(sx,sz)};-}--function surfaceMaterial(opts,bedHeight) {- const moisture=clamp(opts.moisture??0,0,1);- const material=new THREE.MeshStandardMaterial({color:opts.color??0x626158,flatShading:true,- vertexColors:true,roughness:clamp(opts.roughness??.86,.05,1),metalness:0});- material.name='CutPavingStone';- patchStandard(material,{- name:'paving:stone',uniforms:{uPaveMoisture:{value:moisture},uPaveBed:{value:bedHeight}},- vertexHead:'varying vec3 vPaveLocal;',vertexBody:'vPaveLocal=position;',- fragmentHead:`- varying vec3 vPaveLocal;- uniform float uPaveMoisture, uPaveBed;- `,- fragmentBody:`- vec2 paveP=vPaveLocal.xz+vPaveLocal.y*vec2(.47,.81);- float paveFoot=max(length(dFdx(paveP)),length(dFdy(paveP)));- float paveFineFade=1.0-smoothstep(.001,.006,paveFoot);- float paveGrainFade=1.0-smoothstep(.004,.02,paveFoot);- float paveGrain=(astraNoise2(paveP*63.0)-.5)*paveGrainFade;- float paveFine=(astraNoise2(paveP*310.0)-.5)*paveFineFade;- float paveMacro=astraFbm2(paveP*5.0,3)-.4375;- float paveContact=1.0-smoothstep(uPaveBed-.002,uPaveBed+.02,vPaveLocal.y);- diffuseColor.rgb*=1.0+paveMacro*.22+paveGrain*.13+paveFine*.09;- diffuseColor.rgb*=mix(1.0,.63,uPaveMoisture)*mix(1.0,.78,paveContact);- `,- roughnessBody:`- roughnessFactor=clamp(mix(roughnessFactor+paveGrain*.10,.30,uPaveMoisture)- +paveContact*.09,.08,1.0);- `,- normalBody:'normal=astraBump(-vViewPosition,normal,paveGrain*.0009+paveFine*.00025);',- });- return material;-}--/** Build cobbles or staggered rectangular setts. No external assets needed.- * stoneSize is the approximate cell width; exceptionally large patches- * automatically use coarser stones.- * joint, thickness and relief are metres. Zero relief removes height/tilt- * variation but keeps the rounded cut edges and small intrinsic crown.- * Materials remain ordinary physical dielectric surfaces with real shadows.- */-export function makePaving(opts={}) {- const size=opts.size??[4,4],width=Array.isArray(size)?size[0]:size,- depth=Array.isArray(size)?size[1]:size;- const stoneSize=opts.stoneSize??.24,thickness=opts.thickness??.10;- const pattern=opts.pattern??'cobble';- for(const [name,value] of Object.entries({width,depth,stoneSize,thickness,- joint:opts.joint??.012,relief:opts.relief??.014,seed:opts.seed??17,- moisture:opts.moisture??0,roughness:opts.roughness??.86})) {- if(!Number.isFinite(value)||(['width','depth','stoneSize','thickness'].includes(name)&&value<=0))- throw new RangeError(`${name} must be finite${['width','depth','stoneSize','thickness'].includes(name)?' and positive':''}`);- }- if(!['cobble','setts'].includes(pattern))throw new RangeError('pattern must be cobble or setts');- if((opts.joint??.012)<0||(opts.relief??.014)<0)throw new RangeError('joint and relief must be nonnegative');- const seed=opts.seed??17,rand=mulberry32(seed),layout=cells(width,depth,stoneSize,pattern,rand);- const joint=clamp(opts.joint??.012,0,layout.spacing*.22);- const relief=clamp(opts.relief??.014,0,thickness*.35);- const jointDepth=Math.min(thickness*.62,Math.max(layout.spacing*.085,.006));- const bedHeight=-jointDepth;- const positions=[],colors=[],indices=[],ranges=[],outlines=[];- const color=new THREE.Color();- const triangle=(a,b,c)=>indices.push(a,c,b); // XZ counterclockwise points face +Y.- const vertex=(p,c)=>{const i=positions.length/3;positions.push(...p);colors.push(c.r,c.g,c.b);return i;};- for(const cell of layout.polygons) {- let poly=inset(cell,joint*.5);- if(poly.length<3)continue;- const center=poly.reduce((sum,p)=>[sum[0]+p[0]/poly.length,sum[1]+p[1]/poly.length],[0,0]);- // Trim each convex corner. Every point stays inside its own cell and- // contributes to a real curved/chipped bevel rather than a bump outline.- const rounded=[];- for(let i=0;i<poly.length;i++) {- const previous=poly[(i+poly.length-1)%poly.length],p=poly[i],next=poly[(i+1)%poly.length];- const trim=(pattern==='cobble'?.22:.10)*(0.7+rand()*.6);- rounded.push(mixPoint(p,previous,trim),mixPoint(p,next,trim));- }- poly=rounded;- const radius=Math.min(...poly.map(p=>Math.hypot(p[0]-center[0],p[1]-center[1])));- if(radius<Math.max(1e-6,joint*.15))continue;- const height=(rand()-.5)*relief,tx=(rand()-.5)*relief*.35/radius,tz=(rand()-.5)*relief*.35/radius;- const crown=Math.min(radius*.019,thickness*.022)*(pattern==='cobble'?1:.24);- const bevel=Math.min(radius*.12,jointDepth*.58,thickness*.17);- const tint=1+(rand()-.5)*.36,warm=(rand()-.5)*.065;- color.setRGB(tint*(1+warm),tint,tint*(1-warm));- const start=indices.length,base=positions.length/3,n=poly.length;- const cuts=poly.map(()=>rand()<.24?rand()*.26:0);- const edgeWear=poly.map(()=>.88+rand()*.24);- for(let ring=0;ring<4;ring++)for(let i=0;i<n;i++) {- const p=poly[i],r=ring===0?.93:ring===1?1:ring===2?.978:1-(pattern==='cobble'?.125:.08)*edgeWear[i]-cuts[i]*.32;- const x=lerp(center[0],p[0],r),z=lerp(center[1],p[1],r);- const tilt=(x-center[0])*tx+(z-center[1])*tz;- const chip=fbm2(x*41,z*41,{seed:seed+11,octaves:2})*Math.min(.0015,thickness*.02);- const y=ring===0?-thickness:ring===1?Math.min(bedHeight-Math.min(.003,thickness*.06),height-bevel*1.3):- ring===2?height-bevel*edgeWear[i]+tilt+chip:height+tilt+chip-cuts[i]*bevel*.9;- vertex([x,y,z],color);- }- for(let ring=0;ring<3;ring++)for(let i=0;i<n;i++) {- const next=(i+1)%n,a=base+ring*n+i,b=base+ring*n+next,c=b+n,d=a+n;- triangle(a,b,c);triangle(a,c,d);- }- const top=vertex([center[0],height+crown,center[1]],color);- const bottom=vertex([center[0],-thickness,center[1]],color);- for(let i=0;i<n;i++) {- const next=(i+1)%n;- triangle(top,base+3*n+i,base+3*n+next);- triangle(bottom,base+next,base+i);- }- ranges.push([start,indices.length-start]);outlines.push(poly.map(p=>[...p]));- }- const geometry=new THREE.BufferGeometry();- geometry.setAttribute('position',new THREE.Float32BufferAttribute(positions,3));- geometry.setAttribute('color',new THREE.Float32BufferAttribute(colors,3));- geometry.setIndex(indices);geometry.computeVertexNormals();geometry.computeBoundingBox();geometry.computeBoundingSphere();- // Three scales bounding spheres by the largest matrix column, which can- // under-bound shear from nested nonuniform scale and rotation. sqrt(3)- // bounds the ratio to the matrix spectral norm; exact bounds stay intact.- geometry.boundingSphere.radius*=Math.sqrt(3);- const material=surfaceMaterial(opts,bedHeight),stones=new THREE.Mesh(geometry,material);- stones.name='PavingStones';stones.castShadow=true;stones.receiveShadow=true;- const bedGeometry=new THREE.BoxGeometry(width,thickness-jointDepth,depth);- bedGeometry.translate(0,(-thickness+bedHeight)/2,0);- bedGeometry.computeBoundingSphere();bedGeometry.boundingSphere.radius*=Math.sqrt(3);- const bedMaterial=new THREE.MeshStandardMaterial({color:opts.jointColor??0x514c40,- roughness:lerp(.99,.72,clamp(opts.moisture??0,0,1)),metalness:0});- const bed=new THREE.Mesh(bedGeometry,bedMaterial);bed.name='PavingJointBed';bed.castShadow=true;bed.receiveShadow=true;- const root=new THREE.Group();root.name=opts.name??'Paving';root.add(bed,stones);- root.userData.placement=bed.userData.placement=stones.userData.placement='free';-- // Index upward-facing triangles after Float32 conversion. Query exactly- // what the GPU/raycaster receives, including sloped bevels at joint edges.- const p=geometry.attributes.position,index=geometry.index.array,bins=new Map();- const binSize=Math.max(layout.spacing,1e-5),triangles=[];- for(let i=0;i<index.length;i+=3) {- const a=index[i],b=index[i+1],c=index[i+2];- const ax=p.getX(a),az=p.getZ(a),bx=p.getX(b),bz=p.getZ(b),cx=p.getX(c),cz=p.getZ(c);- const det=(bz-cz)*(ax-cx)+(cx-bx)*(az-cz);- // CCW in world XZ is a DOWN-facing triangle; skip bottom and verticals.- if(det>=-1e-13)continue;- const t={ax,az,bx,bz,cx,cz,ay:p.getY(a),by:p.getY(b),cy:p.getY(c),det};- const id=triangles.length;triangles.push(t);- for(let x=Math.floor(Math.min(ax,bx,cx)/binSize);x<=Math.floor(Math.max(ax,bx,cx)/binSize);x++)- for(let z=Math.floor(Math.min(az,bz,cz)/binSize);z<=Math.floor(Math.max(az,bz,cz)/binSize);z++) {- const key=x+','+z;if(!bins.has(key))bins.set(key,[]);bins.get(key).push(id);- }- }- root.userData.sampleHeight=boundedSampler(width,depth,(x,z)=>{- let height=bedHeight;- for(const id of bins.get(Math.floor(x/binSize)+','+Math.floor(z/binSize))??[]) {- const t=triangles[id],a=((t.bz-t.cz)*(x-t.cx)+(t.cx-t.bx)*(z-t.cz))/t.det;- const b=((t.cz-t.az)*(x-t.cx)+(t.ax-t.cx)*(z-t.cz))/t.det,c=1-a-b;- if(Math.min(a,b,c)>=-1e-7)height=Math.max(height,a*t.ay+b*t.by+c*t.cy);- }- return height;- });- root.userData.update=()=>{};- Object.assign(root.userData,{seed,stoneCount:ranges.length,stoneRanges:ranges,- stoneOutlines:outlines,size:[width,depth],stoneSize:layout.spacing,joint,relief,bedHeight});- return attachDisposal(root,snapshotResources(root));-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/roadway.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/roadway.jsdeleted file mode 100644index 610e62fd..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/roadway.js+++ /dev/null@@ -1,615 +0,0 @@-/**- * Roadway: the made surface underfoot, and the mess where it stops.- *- * A road, a path or a yard is in nearly every scene here, it is the- * surface a viewer walks on every day, and it arrives flat grey. These- * three patches give it the marks that say TRAFFIC: the aggregate it- * was mixed from, the two polished strips per lane where the wheels- * run, the repairs cut into it, the damp gutter at the kerb, the gravel- * and weeds where it meets the ground it was laid on, and the tracks- * pressed into whatever is soft beside it.- *- * All three go through `patchStandard`, so lighting, shadows, fog and- * the depth chunks survive; all three shade from world position and- * world normal, so none needs a UV; and all three CHAIN with- * `terrain_shade`, `surface_wear`, `aging`, `accumulation` and- * `strata` on one material.- *- * THE ROAD FRAME is what makes this a roadway rather than more noise.- * Every patch works in (ALONG, ACROSS) metres, taken from the mesh's- * OWN axis: `dir` is an object-space direction carried through- * `modelMatrix`, and across is the horizontal perpendicular measured- * from the mesh's own origin. A rut is a line of constant ACROSS, so a- * rut laid along a world axis would walk off the road the moment it- * turned; this one turns with it, and a curve built from rotated- * segments gets ruts that follow each one.- *- * ONE FRAME PER MATERIAL: `dir`, `halfWidth` and `center` belong to the- * ROAD and all three patches share them — an option left out inherits- * what an earlier call set, and the last call that gives one wins.- * Tracks that must run somewhere else on the same material take- * `offset` (metres across) rather than a second centreline.- *- * Gloss follows the same local masks as color: tire lanes polish,- * gutters stay damp and collected grit remains matte at the verge.- */--import * as THREE from 'three';-import {- patchStandard, glslAxes, glslTriNoise,- seedVec3, toColor, unit, WORLD_VARYINGS,-} from './shader.js';--// The world varyings terrain_shade, surface_wear, aging, accumulation and-// strata share, so a material wearing several libraries carries ONE-// world position; vAstraRoad is this library's own and no neighbour's.-const ROAD_VARYINGS = [WORLD_VARYINGS, 'varying vec4 vAstraRoad;'].join('\n');--// All three patches read these, so they are declared once, in the-// frame. astraRoad*, not a neighbour's spelling: patchStandard THROWS-// when two chained patches give one function name two different bodies.-const ROAD_HEAD = [- glslAxes('astraRoadAxes'),- // Three world-plane projections blended by the normal: the top of a- // kerb and its face have to carry the same grit.- glslTriNoise('astraRoadNoise', 31.7, 67.3, 13.9),- // A fine field is TEXTURE up close and STATIC once a pixel spans a- // cycle of it, so every grain here is faded out by the world size of- // its own pixel. `cycle` is metres per repeat.- 'float astraRoadFade(vec3 p, float cycle) {',- ' return 1.0 - smoothstep(0.30, 0.95,',- ' length(fwidth(p)) / max(cycle, 1e-4));',- '}',-].join('\n');--// `transformed` is still object-space after <begin_vertex>, so the-// instance transform is folded in by hand or every copy takes its road-// from the mesh origin.-const FRAME_BODY = [- ' vec4 rwP = vec4(transformed, 1.0);',- ' vec3 rwN = normal;',- ' vec4 rwD = vec4(uRoadDir, 0.0);',- ' vec4 rwO = vec4(0.0, 0.0, 0.0, 1.0);',- '#ifdef USE_INSTANCING',- ' rwP = instanceMatrix * rwP;',- ' rwN = astraNormalTransform(mat3(instanceMatrix), rwN);',- // Each copy is its own segment UNLESS a centreline was given, which- // says every copy belongs to ONE road.- ' rwD = mix(instanceMatrix * rwD, rwD, uRoadCenter.w);',- ' rwO = mix(instanceMatrix * rwO, rwO, uRoadCenter.w);',- '#endif',- ' vAstraWorld = (modelMatrix * rwP).xyz;',- ' vAstraWorldN = astraNormalTransform(mat3(modelMatrix), rwN);',- ' vec3 rwA = normalize((modelMatrix * rwD).xyz);',- // The centreline is OBJECT-space like the direction, so a road built- // inside a turned group needs no world arithmetic from its author.- ' rwO = mix(rwO, vec4(uRoadCenter.xyz, 1.0), uRoadCenter.w);',- ' vec3 rwC = (modelMatrix * rwO).xyz;',- // Across is the HORIZONTAL perpendicular, so the pair is a road frame- // and not the world axes; a road standing on end has no across.- ' vec3 rwX = cross(vec3(0.0, 1.0, 0.0), rwA);',- ' rwX = normalize(mix(vec3(1.0, 0.0, 0.0), rwX,',- ' step(1e-4, dot(rwX, rwX))));',- ' vAstraRoad = vec4(rwA, dot(vAstraWorld - rwC, rwX));',-].join('\n');--const FRAME_HEAD = [- 'uniform vec3 uRoadDir;',- 'uniform vec4 uRoadCenter;',- 'uniform float uRoadHalf;',-].join('\n');--// The constants differ from surface_wear's, aging's and accumulation's,-// or one seed would lay this library's grit along that library's-// blotches.-const seedOffset = (seed, salt) =>- seedVec3(seed + salt, 2.11, 6.37, 11.83, 40);--/** Read a direction option, never as a zero vector the GPU divides by. */-function dirVector(value, fallback) {- const v = new THREE.Vector3();- v.fromArray(value.toArray ? value.toArray() : value);- if (!(v.lengthSq() > 1e-9)) return fallback.clone();- return v.normalize();-}--/**- * The road frame every patch here works in, applied once.- *- * Named, so a material wearing all three gets ONE copy of the base: two- * would declare the same vertex locals and redefine the same helpers,- * which is a compile error and a throw respectively. The frame belongs- * to the ROAD, not to a patch, so an option left out INHERITS what an- * earlier call set rather than resetting it to the default.- *- * @param {THREE.Material} material The material to patch, in place.- * @param {object} opts `dir` object-space direction of travel (default- * +Z); `halfWidth` metres from the centreline to the kerb (default- * 3.5); `center` THREE.Vector3 or [x, y, z], a point on the- * centreline in the MESH'S OWN space (default: the mesh's origin —- * and giving one also makes every instance share this one road).- * @returns {THREE.Material} The same material.- */-function withFrame(material, opts) {- const live = material.userData.uniforms || {};- const was = (name, fallback) => (live[name] ? live[name].value : fallback);- const dir = opts.dir === undefined- ? was('uRoadDir', new THREE.Vector3(0, 0, 1))- : dirVector(opts.dir, new THREE.Vector3(0, 0, 1));- const half = opts.halfWidth === undefined- ? was('uRoadHalf', 3.5) : Math.max(0.05, opts.halfWidth);- const at = new THREE.Vector3();- if (opts.center) at.fromArray(- opts.center.toArray ? opts.center.toArray() : opts.center);- const center = opts.center === undefined- ? was('uRoadCenter', new THREE.Vector4(0, 0, 0, 0))- : new THREE.Vector4(at.x, at.y, at.z, 1);- return patchStandard(material, {- name: 'road:frame',- uniforms: {- uRoadDir: { value: dir.clone() },- uRoadCenter: { value: center.clone() },- uRoadHalf: { value: half },- },- vertexHead: [ROAD_VARYINGS, FRAME_HEAD].join('\n'),- fragmentHead: [ROAD_VARYINGS, FRAME_HEAD, ROAD_HEAD].join('\n'),- vertexBody: FRAME_BODY,- });-}--/**- * Asphalt or gravel: aggregate, wheel ruts, repairs and a damp gutter.- *- * A road is not a grey plane and it is not evenly worn — it is worn in- * TWO STRIPS PER LANE, where the wheels run, with the drip line between- * them and the silt at its edge. That asymmetry is the whole cue: it is- * what says a surface is driven on rather than painted, and it is the- * one thing a flat material can never suggest. Four layers, all in the- * road's own (along, across) frame:- *- * AGGREGATE is the stone in the mix — a fine dark speckle at- * `aggregate` 0 (a hot-rolled asphalt), loose pale chips at 1 (a gravel- * track) — faded out once a pixel spans a stone, because past that it- * is not texture, it is static. RUTS are the polished wheel lines, a- * wandering pair 1.5 m apart in each lane — the road is divided into- * WHOLE lanes, so a single-track lane keeps one pair and a two-lane- * road gets four strips, and the lane centre between each pair keeps- * the darker drip line. PATCHES are repairs: saw-cut rectangles in the- * road's own frame, each its own batch of tar, sealed at the rim — a- * soft-edged blob is an oil stain, not a repair. GUTTER is the- * hand-span at the kerb that never dries: darker, greener and, through- * a local roughness mask, glossier.- *- * ON A COLOUR THAT IS ALREADY THERE: this one RULES the hue — it is the- * made surface, and `color` is what it was made of — but it carries- * whatever is in `diffuseColor` through as a light/dark variation- * rather than assigning over it, so a `patchTriplanar` or a- * `patchMicroBreakup` under it still shows in the result.- *- * @param {THREE.Material} material A built-in material, patched in- * place — a shared material from `materials.js` surfaces every mesh- * wearing it, so clone it first (and clone BEFORE patching).- * @param {object} [opts] `aggregate` fineness of the mix, 0 asphalt to- * 1 loose gravel (default 0.25); `wear` how polished the wheel ruts- * are, 0..1 (default 0.5); `patches` how much of it has been dug up- * and made good, 0..1 (default 0.25); `gutter` how damp and silted- * the kerb line is, 0..1 (default 0.35); `color` THREE.Color or hex,- * the surface's own tone (default a worn bitumen grey); `lane` metres- * of one traffic lane, which sets where the ruts run (default 3.4);- * `dir`/`halfWidth`/`center` the road frame (see `withFrame`);- * `seed` moves the aggregate and the repairs (default 1).- * @returns {THREE.Material} The same material, with its uniforms live- * on `material.userData.uniforms`, so `uRoadGutter` can wet down- * over a shot.- */-export function patchRoadSurface(material, opts = {}) {- const agg = opts.aggregate === undefined ? 0.25 : unit(opts.aggregate);- const wear = opts.wear === undefined ? 0.5 : unit(opts.wear);- const patches = opts.patches === undefined ? 0.25 : unit(opts.patches);- const gutter = opts.gutter === undefined ? 0.35 : unit(opts.gutter);- const lane = opts.lane === undefined ? 3.4 : Math.max(0.5, opts.lane);- const seed = opts.seed === undefined ? 1 : opts.seed;- withFrame(material, opts);- return patchStandard(material, {- name: 'road:surface',- uniforms: {- uRoadAgg: { value: agg },- uRoadWear: { value: wear },- uRoadPatch: { value: patches },- uRoadGutter: { value: gutter },- uRoadColor: { value: toColor(opts.color, 0x565658) },- uRoadLane: { value: lane },- uRoadSeed: { value: seedOffset(seed, 0.9) },- },- fragmentHead: [- 'uniform float uRoadAgg;',- 'uniform float uRoadWear;',- 'uniform float uRoadPatch;',- 'uniform float uRoadGutter;',- 'uniform vec3 uRoadColor;',- 'uniform float uRoadLane;',- 'uniform vec3 uRoadSeed;',- ].join('\n'),- fragmentBody: [- ' float roU = dot(vAstraWorld, vAstraRoad.xyz);',- ' float roA = abs(vAstraRoad.w);',- // The road's tone rules, but it carries what is already in the- // albedo as a variation: assigning outright erases a neighbour.- ' float roKeep = dot(diffuseColor.rgb, vec3(0.3333));',- ' vec3 roCol = uRoadColor',- ' * mix(0.88, 1.12, clamp(roKeep * 1.7, 0.0, 1.0));',- // TWO STRIPS PER LANE, and they come FIRST: a polished rut is- // where the aggregate stopped showing, not a stripe painted on- // top of it. The road is divided into WHOLE lanes, so every lane- // centre lands inside it — a single-track lane keeps one pair.- ' float roN = max(floor(2.0 * uRoadHalf / max(uRoadLane, 0.5)), 1.0);',- ' float roLw = 2.0 * uRoadHalf / roN;',- ' float roK = clamp(floor((vAstraRoad.w + uRoadHalf) / roLw),',- ' 0.0, roN - 1.0);',- ' float roCen = (roK + 0.5) * roLw - uRoadHalf;',- // Nothing drives a ruled line: the wheel path wanders along the- // road, which is what stops the pair reading as rails.- ' float roWob = (astraNoise2(vec2(roU * 0.06, 3.7) + uRoadSeed.yz)',- ' - 0.5) * 0.30;',- ' float roTr = min(0.75, roLw * 0.32);',- ' float roRut = (1.0 - smoothstep(0.12, 0.38,',- ' abs(abs(vAstraRoad.w - roCen) - roTr + roWob)))',- ' * uRoadWear;',- // The stone in the mix, gone once a pixel spans one of them and- // polished away under the wheels.- ' float roGs = mix(0.018, 0.075, uRoadAgg);',- ' vec2 roQ = vec2(roU, vAstraRoad.w) / roGs + uRoadSeed.xy;',- ' float roFd = astraRoadFade(vAstraWorld, roGs) * (1.0 - roRut * 0.7);',- ' float roG1 = astraNoise2(roQ);',- ' float roG2 = astraNoise2(roQ * 2.7 + 19.3);',- // A THIRD octave, on roFd twice so it is the first to go: two- // octaves of value noise at one stone size read as soft blobs —- // digital camouflage, not aggregate — and the break-up that makes- // them stone is finer than the stone itself.- ' float roG3 = astraNoise2(roQ * 5.9 + 41.7);',- ' float roG2Fade = astraRoadFade(vAstraWorld, roGs / 2.7);',- ' float roG3Fade = astraRoadFade(vAstraWorld, roGs / 5.9);',- ' float roGrain = ((roG1 - 0.5) * 0.52 + (roG2 - 0.5) * 0.34 * roG2Fade',- ' + (roG3 - 0.5) * 0.30 * roG3Fade) * roFd;',- ' roCol *= 1.0 + roGrain * mix(0.22, 0.60, uRoadAgg);',- // A chip is a STONE, and a road is never mixed from one stone: the- // exposed faces run warm (flint, limestone dust) to cool (granite,- // basalt) on a field decorrelated from the one that placed them.- ' float roChip = smoothstep(0.62, 0.74, roG1 * 0.45 + mix(0.5, roG3, roG3Fade) * 0.55)',- ' * uRoadAgg * roFd;',- ' vec3 roStone = roCol * 1.5 + vec3(0.035, 0.033, 0.030);',- ' roStone *= mix(vec3(1.07, 1.00, 0.90),',- ' vec3(0.93, 0.99, 1.09), mix(0.5, roG2, roG2Fade));',- ' roCol = mix(roCol, roStone, roChip * 0.7);',- ' roCol = mix(roCol, uRoadColor * mix(1.06, 1.42, uRoadWear),',- ' roRut * 0.85);',- // The drip strip down the lane centre, between the wheels.- ' float roOil = (1.0 - smoothstep(0.06, 0.34,',- ' abs(vAstraRoad.w - roCen))) * uRoadWear;',- ' roCol *= 1.0 - roOil * 0.30;',- // REPAIRS ARE SAW-CUT: a rectangle in the road's own frame with a- // sealed rim, one per cell of a coarse grid. A soft blob is an- // oil stain; only a straight edge reads as something dug up.- ' vec2 roPq = vec2(roU / 5.6, vAstraRoad.w / 3.3) + uRoadSeed.zx;',- ' vec2 roPi = floor(roPq);',- // Jittered inside its cell and never quite filling it, or the- // repairs line up on a lattice and read as paving slabs.- ' vec2 roPj = vec2(astraHash21(roPi + 5.3),',- ' astraHash21(roPi + 17.1)) - 0.5;',- ' vec2 roPf = abs(fract(roPq) - 0.5 + roPj * 0.22);',- ' vec2 roPs = vec2(0.13 + 0.25 * astraHash21(roPi + 3.1),',- ' 0.11 + 0.27 * astraHash21(roPi + 7.7));',- ' vec2 roPaa = fwidth(roPq) * 0.7 + 0.0015;',- ' vec2 roPe = 1.0 - smoothstep(roPs - roPaa, roPs + roPaa, roPf);',- ' float roPk = roPe.x * roPe.y',- ' * step(1.0 - uRoadPatch, astraHash21(roPi));',- ' vec2 roPn = 1.0 - smoothstep(roPs - 0.05 - roPaa, roPs - 0.05 + roPaa,',- ' roPf);',- ' float roRim = roPk * (1.0 - roPn.x * roPn.y);',- // A repair is a different BATCH, not a black rectangle: some are- // darker than the road it was cut into and some are paler.- ' float roPt = mix(0.80, 1.12, astraHash21(roPi + 11.9));',- ' roCol = mix(roCol, uRoadColor * roPt * (1.0 + roGrain * 1.2),',- ' roPk * 0.8);',- ' roCol *= 1.0 - roRim * 0.22;',- // METRE-SCALE WEATHER, and the only structure on this surface that- // survives to the horizon: every field above is finer than a pixel- // within a few metres of the camera and fades out BY DESIGN, which- // left the road one flat value past that — a grey card with a- // repair grid on it. Two slow octaves in the road's own frame, and- // a hue that walks with them from warm (dust, sun-bleached binder,- // limestone fines) to cool (fresh bitumen, the damp side of a- // patch), so the variance is in COLOUR and not only in level. The- // mix is centred, so the road's mean tone is the one it was given.- ' vec2 roMq = vec2(roU, vAstraRoad.w) + uRoadSeed.yx;',- ' float roBlot = (astraNoise2(roMq * 0.115) - 0.5) * 0.55',- ' + (astraNoise2(roMq * 0.034 + 4.7) - 0.5) * 0.45;',- ' float roHue = clamp(0.5 + roBlot * 1.7, 0.0, 1.0);',- ' roCol *= (1.0 + roBlot * 0.30)',- ' * mix(vec3(0.950, 0.984, 1.062),',- ' vec3(1.072, 1.012, 0.940), roHue);',- // The gutter never dries and it silts up; its inner edge is- // ragged, or it is a painted line. Two bands, not one: the damp- // strip inside the kerb goes dark and COOL, and the silt washed to- // the kerb line itself sits on top of it PALER and warm — a single- // flat darkening reads as a stripe someone painted there.- ' float roGw = mix(0.10, 0.60, uRoadGutter);',- ' float roGj = (astraNoise2(vec2(roU * 0.35, 9.1) + uRoadSeed.xy)',- ' - 0.5) * roGw * 0.7;',- ' float roGut = smoothstep(uRoadHalf - roGw + roGj,',- ' uRoadHalf + roGj, roA) * uRoadGutter;',- // Silt is washed along the kerb and dropped where the fall eases,- // so how much of it there is walks ALONG the road: an even pale- // line at the kerb is road marking, not dirt.- ' float roSilt = smoothstep(uRoadHalf - roGw * 0.34 + roGj,',- ' uRoadHalf + roGj, roA) * uRoadGutter',- ' * smoothstep(0.30, 0.72,',- ' astraNoise2(vec2(roU * 0.5, 2.3) + uRoadSeed.zx));',- ' roCol = mix(roCol, roCol * vec3(0.44, 0.49, 0.56),',- ' roGut * (1.0 - roSilt * 0.55));',- ' roCol = mix(roCol, roCol * vec3(1.58, 1.44, 1.17), roSilt * 0.62);',- // A metre-scale gradient across a near-neutral grey BANDS at eight- // bits, and the aggregate that would have hidden it has faded out- // by the distance the banding appears. Sub-LSB, per pixel, so it- // costs one hash and never reads as noise.- ' roCol *= 1.0 + (astraHash21(gl_FragCoord.xy) - 0.5) * 0.010;',- ' diffuseColor.rgb = roCol;',- // Metric surface-gradient relief preserves the base mesh silhouette.- // Fine aggregate disappears before subpixel grain can shimmer.- ' float roHeight = roGrain * mix(0.0005, 0.008, uRoadAgg)',- ' * (1.0 - roRut * 0.7) + roChip * 0.002 - roRut * 0.004',- ' - roRim * 0.0008 + roSilt * 0.0008;',- ].join('\n'),- normalBody: 'normal = astraBump(-vViewPosition, normal, roHeight);',- roughnessBody: [- 'roughnessFactor = mix(roughnessFactor, max(roughnessFactor, 0.94), uRoadAgg * 0.18);',- 'roughnessFactor = mix(roughnessFactor, max(0.32, roughnessFactor * 0.78), roRut);',- 'roughnessFactor = mix(roughnessFactor, min(roughnessFactor, 0.32), roGut * (1.0 - roSilt));',- 'roughnessFactor = mix(roughnessFactor, max(roughnessFactor, 0.95), roSilt);',- ].join('\n'),- });-}--/**- * The gravel, grit and weeds where a made surface meets the ground.- *- * Nothing in a photograph meets anything else with a clean edge, and- * this is the paving version of that: tarmac does not stop at a ruled- * line on grass, it frays into the spill that was swept off it, the- * grit that washed off it, and the weeds that took the joint. A road- * with a clean edge reads as a decal on the ground however good the- * surface itself is, so this is the cheapest thing in the library.- *- * The band straddles the kerb line — |across| = `halfWidth` — and its- * half-width WANDERS between about half of what it was given and all- * of it, so the edge is ragged and still strictly inside `width`. Weeds- * take the joint and the ground side of it and never the made surface;- * the hairline of shadow in the joint itself is the only depth a patch- * that cannot displace geometry has, and it is faded out by its own- * pixel size before it can alias.- *- * ON A COLOUR THAT IS ALREADY THERE: it MIXES over it by the band mask- * and leaves everything outside the band untouched — so it lands on the- * road's material and on the verge's alike. On the verge, pass the- * road's `center` and `halfWidth`: a fragment on the grass cannot know- * where the tarmac ended.- *- * @param {THREE.Material} material A built-in material, patched in- * place — a shared material bands every mesh wearing it.- * @param {object} [opts] `width` metres the whole band spans, kerb line- * in the middle (default 0.5); `color` THREE.Color or hex, the grit- * and gravel (default a pale grey-brown); `weeds` how much has taken- * root, 0..1 (default 0.4); `dir`/`halfWidth`/`center` the road frame- * (see `withFrame`); `seed` moves the grit and the tufts (default 1).- * @returns {THREE.Material} The same material, with its uniforms live- * on `material.userData.uniforms` — `uSeamWeed` is the weed tone, so- * a dry season can yellow it.- */-export function patchSeamBand(material, opts = {}) {- const width = opts.width === undefined ? 0.5 : Math.max(1e-3, opts.width);- const weeds = opts.weeds === undefined ? 0.4 : unit(opts.weeds);- const seed = opts.seed === undefined ? 1 : opts.seed;- withFrame(material, opts);- return patchStandard(material, {- name: 'road:seam',- uniforms: {- uSeamWidth: { value: width },- uSeamColor: { value: toColor(opts.color, 0x847a6d) },- uSeamWeeds: { value: weeds },- uSeamWeed: { value: new THREE.Color(0x53602f) },- uSeamSeed: { value: seedOffset(seed, 5.3) },- },- fragmentHead: [- 'uniform float uSeamWidth;',- 'uniform vec3 uSeamColor;',- 'uniform float uSeamWeeds;',- 'uniform vec3 uSeamWeed;',- 'uniform vec3 uSeamSeed;',- ].join('\n'),- fragmentBody: [- ' float smU = dot(vAstraWorld, vAstraRoad.xyz);',- // Signed metres past the kerb line, so the two sides can differ.- ' float smD = abs(vAstraRoad.w) - uRoadHalf;',- ' float smH = uSeamWidth * 0.5;',- // The half-width wanders along the road and never exceeds what it- // was given, so a ragged band is still a BOUNDED one.- ' float smR = mix(0.45, 1.0, astraNoise2(vec2(smU * 0.8, 5.7)',- ' + uSeamSeed.xy));',- ' float smK = 1.0 - smoothstep(smR * smH * 0.45, smR * smH,',- ' abs(smD));',- ' vec3 smW = astraRoadAxes(normalize(vAstraWorldN));',- ' vec3 smP = vAstraWorld * 22.0 + uSeamSeed;',- ' float smFd = astraRoadFade(vAstraWorld, 0.045);',- ' float smFc = astraRoadFade(vAstraWorld, 0.20);',- ' float smG = astraRoadNoise(smP, smW);',- ' float smC = astraRoadNoise(smP * 0.22, smW);',- // Grit is the fine half and gravel the coarse half. BOTH converge- // to their average as the pixel grows past them: a band that keeps- // its contrast into the distance is a dashed white line.- ' vec3 smCol = uSeamColor * mix(1.0, mix(0.84, 1.16, smC), smFc)',- ' * (1.0 + (smG - 0.5) * 0.40 * smFd);',- // Gravel is SWEPT UP off a road, not quarried from one stone: a- // slow field in the road's own frame (about a two-metre cycle, so- // it is still there when the grain has faded) walks the band from- // limestone-warm to granite-cool, and the same field splits the- // weeds into dry stems and green leaf below.- ' float smHue = astraNoise2(vec2(smU, vAstraRoad.w) * 0.55',- ' + uSeamSeed.zx);',- ' smCol *= mix(vec3(1.07, 1.00, 0.91), vec3(0.93, 0.99, 1.08), smHue);',- // WEEDS take the joint and the ground side of it: a tuft in the- // middle of the tarmac is a decal.- ' float smOut = smoothstep(-smH * 0.30, smH * 0.55, smD);',- ' float smTf = astraNoise2(vec2(smU, vAstraRoad.w) * 6.5',- ' + uSeamSeed.yz);',- ' float smWd = mix(0.26, smoothstep(0.60, 0.82, smTf), smFc)',- ' * mix(0.20, 1.0, smOut) * uSeamWeeds;',- ' vec3 smWc = uSeamWeed * mix(0.70, 1.20, smG)',- ' * mix(vec3(1.18, 1.05, 0.72),',- ' vec3(0.84, 1.02, 0.94), smHue);',- ' smCol = mix(smCol, smWc, smWd);',- ' diffuseColor.rgb = mix(diffuseColor.rgb, smCol, smK * 0.88);',- // The joint itself, faded out by its own pixel size: a hairline- // that survives past the distance it can be resolved is moire.- ' float smJt = (1.0 - smoothstep(0.0, smH * 0.22, abs(smD)))',- ' * astraRoadFade(vAstraWorld, smH * 0.44);',- ' diffuseColor.rgb *= 1.0 - smJt * 0.45;',- ' float smHeight = smK * ((smG - 0.5) * 0.007 * smFd',- ' + (smC - 0.5) * 0.012 * smFc) - smJt * 0.004;',- ].join('\n'),- roughnessBody: 'roughnessFactor = mix(roughnessFactor, max(roughnessFactor, 0.97), smK);',- normalBody: 'normal = astraBump(-vViewPosition, normal, smHeight);',- });-}--/**- * Tyre tracks or footprints pressed into a soft surface.- *- * Mud, sand, snow and dust all record what crossed them, and a soft- * surface with nothing written on it reads as untouched ground however- * good its own texture is — which is why an otherwise finished yard,- * verge or beach still looks like a render. `count` tracks run along- * the road frame's direction, each wandering on its own field (a pair- * of ruled lines is a railway, not a vehicle).- *- * Color, local gloss and filtered surface-gradient normals describe the- * press. Geometry and silhouette stay unchanged: use displaced meshes for- * foreground ruts that need to occlude a wheel or leave a visible edge.- * The press is darker and damp; a paler raised rim carries displaced soil.- *- * `kind` is a UNIFORM, not two sources: 'tyre' lays a continuous band- * with chevron tread (through `astraStroke`, which kills itself once a- * pixel spans a rib), 'foot' lays discrete prints one stride apart,- * each stepping to its own side of the line so a single trail reads as- * a walk rather than as a ladder.- *- * ON A COLOUR THAT IS ALREADY THERE: it MIXES over it, and the colour- * it mixes toward is that same albedo darkened — so the tracks are made- * OF the surface they are pressed into, whatever a neighbouring patch- * put there, and outside them nothing changes.- *- * @param {THREE.Material} material A built-in material, patched in- * place — a shared material tracks every mesh wearing it.- * @param {object} [opts] `dir` object-space direction of travel- * (default +Z); `count` how many parallel tracks, 1..8 (default 2 —- * one vehicle, one walker); `depth` how deep they are pressed, 0..1- * (default 0.5); `kind` 'tyre' or 'foot' (default 'tyre'); `gauge`- * metres between tracks (default 1.6 for tyre, 0.3 for foot);- * `offset` metres ACROSS the frame that the group runs at, so a- * vehicle can drive down one lane and a seam band on the same- * material can still sit on the centreline it belongs to (default 0);- * `center`/`halfWidth` the road frame (see `withFrame`); `seed` moves- * the wander and the prints (default 1).- * @returns {THREE.Material} The same material, with its uniforms live- * on `material.userData.uniforms`, so `uTrkDepth` can press in over- * a shot.- */-export function patchTracks(material, opts = {}) {- const count = Math.max(1, Math.min(8, Math.round(- opts.count === undefined ? 2 : opts.count)));- const depth = opts.depth === undefined ? 0.5 : unit(opts.depth);- const foot = opts.kind === 'foot';- const gauge = opts.gauge === undefined- ? (foot ? 0.30 : 1.6) : Math.max(0.02, opts.gauge);- const seed = opts.seed === undefined ? 1 : opts.seed;- // Pressed ground is packed and damp only inside the track mask.- withFrame(material, opts);- return patchStandard(material, {- name: 'road:tracks',- uniforms: {- uTrkCount: { value: count },- uTrkDepth: { value: depth },- uTrkKind: { value: foot ? 1 : 0 },- uTrkGauge: { value: gauge },- uTrkOffset: { value: opts.offset === undefined ? 0 : opts.offset },- uTrkSeed: { value: seedOffset(seed, 8.7) },- },- fragmentHead: [- 'uniform float uTrkCount;',- 'uniform float uTrkDepth;',- 'uniform float uTrkKind;',- 'uniform float uTrkGauge;',- 'uniform float uTrkOffset;',- 'uniform vec3 uTrkSeed;',- ].join('\n'),- fragmentBody: [- ' float tkU = dot(vAstraWorld, vAstraRoad.xyz);',- ' float tkPress = 0.0;',- ' float tkWide = 0.0;',- ' float tkTread = 0.0;',- // A churned tyre rut is ~27 cm across and a boot 11; the stride- // and the rib pitch are the same constants for everyone.- ' float tkHw = mix(0.135, 0.055, uTrkKind);',- // Prints and ribs are gone before a pixel spans one of them, and- // a line of prints converges to the worn TRAIL it really is- // rather than to a row of sparkling dots.- ' float tkFd = astraRoadFade(vAstraWorld, 0.30);',- ' for (int i = 0; i < 8; i++) {',- ' if (float(i) >= uTrkCount) break;',- ' float tkO = (float(i) - (uTrkCount - 1.0) * 0.5) * uTrkGauge',- ' + uTrkOffset;',- ' float tkWob = (astraNoise2(vec2(tkU * 0.22, float(i) * 7.3)',- ' + uTrkSeed.xy) - 0.5) * 0.45;',- ' float tkX = vAstraRoad.w - tkO - tkWob;',- // TYRE: a continuous band with chevron ribs square across it.- ' float tkB = 1.0 - smoothstep(tkHw * 0.68, tkHw, abs(tkX));',- ' float tkBw = 1.0 - smoothstep(tkHw, tkHw * 1.7, abs(tkX));',- // Half-width 0.06, not a fat rib: astraStroke clamps its own- // antialias at 0.30 and self-kills between w * 1.5 and w * 5, so- // only a thin stroke ever reaches the kill instead of greying out.- ' float tkRb = astraStroke(tkU / 0.065 + abs(tkX) * 3.6,',- ' 0.06);',- // FOOT: one print per stride, each stepping to its own side.- ' float tkC = floor(tkU / 0.72);',- ' float tkAl = (tkU / 0.72 - tkC - 0.5) * 0.72 / 0.15;',- ' float tkAc = (tkX - (mod(tkC, 2.0) - 0.5) * 0.11) / 0.055;',- ' float tkE = length(vec2(tkAl, tkAc));',- ' float tkTr = (1.0 - smoothstep(0.9, 1.7, abs(tkAc))) * 0.45;',- ' float tkPr = mix(tkTr, 1.0 - smoothstep(0.74, 1.0, tkE), tkFd);',- ' float tkPw = 1.0 - smoothstep(1.0, 1.45, tkE);',- ' tkPress = max(tkPress, mix(tkB, tkPr, uTrkKind));',- ' tkWide = max(tkWide, mix(tkBw, tkPw, uTrkKind));',- ' tkTread = max(tkTread, mix(tkB * tkRb, tkPr * 0.5, uTrkKind));',- ' }',- ' float tkRim = clamp(tkWide - tkPress, 0.0, 1.0) * tkFd;',- // Made OF the surface it is pressed into: turned over and damp,- // so the same albedo, darker.- ' vec3 tkCol = diffuseColor.rgb * mix(1.0, 0.55, uTrkDepth)',- ' * (1.0 - tkTread * 0.17 * tkFd);',- // Turned-over material is DAMP as well as dark, and damp is cool:- // a press that only darkens reads as a shadow painted on the- // ground rather than as ground that was moved.- ' tkCol *= mix(vec3(1.0), vec3(0.94, 0.975, 1.045), uTrkDepth);',- ' diffuseColor.rgb = mix(diffuseColor.rgb, tkCol,',- ' clamp(tkPress * uTrkDepth, 0.0, 1.0));',- // The material it displaced has to go somewhere, and the pale rim- // is the only thickness this hook can show — dry crumbs off the- // top of the surface, so it lifts WARM against the cool press.- ' diffuseColor.rgb *= 1.0 + tkRim * uTrkDepth',- ' * vec3(0.30, 0.25, 0.17);',- ' float tkHeight = uTrkDepth * (-tkPress * 0.013',- ' - tkTread * tkFd * 0.002 + tkRim * 0.006);',- ].join('\n'),- roughnessBody: 'roughnessFactor = mix(roughnessFactor, max(0.12, roughnessFactor * 0.58), clamp(tkPress * uTrkDepth, 0.0, 1.0));',- normalBody: 'normal = astraBump(-vViewPosition, normal, tkHeight);',- });-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sand.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sand.jsdeleted file mode 100644index 918c7bdf..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sand.js+++ /dev/null@@ -1,146 +0,0 @@-/** Wind-shaped dunes in metres. Geometry and surface detail share local coordinates.- * `sampleHeight(x,z)` interpolates the actual rendered triangles, so stones and- * footsteps can be seated without a second, subtly different height function.- */-import * as THREE from 'three';-import { attachDisposal, snapshotResources } from './lifecycle.js';-import { fbm2, mulberry32 } from './noise.js';-import { boundedSampler, option, patchStandard, readWind } from './shader.js';-import { triangleValue } from './terrain.js';--const TAU = Math.PI * 2;-const clamp = (x, lo, hi) => Math.max(lo, Math.min(hi, x));--function sandMaterial(opts, wind, seed) {- const mat = new THREE.MeshStandardMaterial({- color: opts.color ?? 0xc9a16b, roughness: 0.87, metalness: 0,- });- mat.name = 'AeolianSand';- patchStandard(mat, {- name: 'aeolianSand',- uniforms: {- uSandWind: { value: wind }, uSandSeed: { value: seed % 997 },- uSandRipple: { value: Math.max(0.025, opts.rippleSpacing ?? 0.14) },- uSandDetail: { value: clamp(opts.detailStrength ?? 1, 0, 2) },- },- vertexHead: 'varying vec3 vSandLocal;',- vertexBody: 'vSandLocal = position;',- fragmentHead: `- varying vec3 vSandLocal;- uniform vec2 uSandWind;- uniform float uSandSeed, uSandRipple, uSandDetail;- vec2 sandRippleGradient(vec2 p) {- vec2 q = vec2(dot(p, uSandWind), dot(p, vec2(-uSandWind.y, uSandWind.x)));- float warp = astraNoise2(q * vec2(0.3, 0.8) + uSandSeed) * 0.22;- float c = (q.x + warp) / uSandRipple;- // Filter BEFORE differentiating. dFdx(sin(highFrequency)) makes a- // visible 2x2 quad lattice; an analytic derivative has no such grid.- float fade = 1.0 - smoothstep(0.07, 0.28, fwidth(c));- float slope = (cos(c * 6.2831853) + 0.34 * cos(c * 12.5663706 + 0.6))- * fade * uSandRipple * 0.025 * 6.2831853;- return slope * vec2(dFdx(c), dFdy(c));- }- `,- fragmentBody: `- float sandMacro = astraFbm2(vSandLocal.xz * 0.11 + uSandSeed, 3);- float sandGrainFoot = max(length(dFdx(vSandLocal)), length(dFdy(vSandLocal)));- float sandGrainFade = 1.0 - smoothstep(0.0007, 0.008, sandGrainFoot);- float sandGrain = astraHash21(floor(vSandLocal.xz * 1400.0) + uSandSeed);- vec2 sandRippleDH = sandRippleGradient(vSandLocal.xz);- diffuseColor.rgb *= 0.87 + 0.30 * sandMacro;- diffuseColor.rgb *= 1.0 + (sandGrain - 0.5) * sandGrainFade * 0.24;- diffuseColor.rgb *= vec3(1.0 + sandMacro * 0.055, 1.0, 1.0 - sandMacro * 0.065);- `,- roughnessBody: `- roughnessFactor = clamp(roughnessFactor - sandGrainFade * smoothstep(0.93, 1.0, sandGrain) * 0.32, 0.48, 0.98);- `,- normalBody: 'normal = astraBumpSlope(-vViewPosition, normal, sandRippleDH * uSandDetail);',- });- return mat;-}--/**- * @param {object} opts seed; size number or [width,depth]; segments (default- * 256); duneHeight metres; duneSpacing metres; windDirection [x,z];- * rippleSpacing metres; color; detailStrength; grains (0 by default);- * windSpeed metres/sec. A group, with userData.sampleHeight/update/dispose.- * sampleHeight takes LOCAL x,z; parent assets to this group after seating them.- */-export function makeSandTerrain(opts = {}) {- const seed = option(opts.seed, 17, 'makeSandTerrain: seed');- const rand = mulberry32(seed);- const size = Array.isArray(opts.size) ? opts.size : [opts.size ?? 80, opts.size ?? 80];- if (size.length !== 2 || !size.every((n) => Number.isFinite(n) && n > 0)) throw new RangeError('sand size must be positive metres');- const [width, depth] = size;- const nx = clamp(Math.round(opts.segments ?? 256), 8, 512);- const nz = clamp(Math.round(nx * depth / width), 8, 512);- const wind = readWind(opts.windDirection, [1, 0.18], 'makeSandTerrain windDirection').dir;- const height = Math.max(0, opts.duneHeight ?? 3.8);- const spacing = Math.max(1, opts.duneSpacing ?? 19);- const phase = rand() * spacing;- const field = (x, z) => {- const u = x * wind.x + z * wind.y, v = -x * wind.y + z * wind.x;- const bend = Math.sin(v / spacing * 1.7 + phase) * spacing * 0.15- + fbm2(u / spacing * 0.7, v / spacing * 1.1, { seed, octaves: 2 }) * spacing * 0.35;- const f = ((u + bend + phase) / spacing % 1 + 1) % 1;- // Long shallow stoss face; short steep lee face. A continuous sharp crest- // gives the surface a direction which symmetric sine hills do not have.- const ridge = f < 0.77 ? Math.pow(f / 0.77, 1.75) : Math.pow((1 - f) / 0.23, 0.92);- const envelope = 0.84 + 0.16 * Math.sin(v / spacing * 1.3 + phase);- return height * (ridge * envelope + 0.16 * fbm2(x / spacing * 1.7, z / spacing * 1.7, { seed: seed + 83, octaves: 3 }));- };- const geometry = new THREE.PlaneGeometry(width, depth, nx, nz);- geometry.rotateX(-Math.PI / 2);- const p = geometry.attributes.position;- for (let i = 0; i < p.count; i++) p.setY(i, field(p.getX(i), p.getZ(i)));- geometry.computeVertexNormals();- geometry.computeBoundingBox();- geometry.computeBoundingSphere();- const surface = new THREE.Mesh(geometry, sandMaterial(opts, wind, seed));- surface.name = 'DuneSurface';- surface.castShadow = true;- surface.receiveShadow = true;- surface.userData.placement = 'free';- const group = new THREE.Group();- group.name = opts.name ?? 'SandTerrain';- group.userData.placement = 'free';- group.add(surface);-- const sampleHeight = (x, z) => triangleValue(p, nx, nz, (x / width + 0.5) * nx, (z / depth + 0.5) * nz, 1);-- // Sparse saltating grains: CPU updates cost a few hundred points, not a- // second terrain shader. Their vertical trajectory follows the same mesh.- const count = clamp(Math.round(opts.grains ?? 0), 0, 1200);- let grains = null, seeds = [];- if (count) {- const geo = new THREE.BufferGeometry();- geo.setAttribute('position', new THREE.Float32BufferAttribute(new Float32Array(count * 3), 3));- seeds = Array.from({ length: count }, () => [rand() * width - width / 2, rand() * depth - depth / 2, rand(), 0.02 + rand() * 0.10]);- const mat = new THREE.PointsMaterial({ color: opts.color ?? 0xe2c79f, size: 0.009,- transparent: true, opacity: 0.40, depthWrite: false, sizeAttenuation: true });- grains = new THREE.Points(geo, mat);- grains.name = 'WindblownGrains';- grains.frustumCulled = false;- grains.userData.placement = 'free';- group.add(grains);- }- const update = (t) => {- if (!grains) return;- const pos = grains.geometry.attributes.position;- const speed = opts.windSpeed ?? 0.85;- const wrap = (v, n) => ((v + n / 2) % n + n) % n - n / 2;- for (let i = 0; i < count; i++) {- const [x0, z0, ph, hop] = seeds[i];- const x = wrap(x0 + t * speed * wind.x, width), z = wrap(z0 + t * speed * wind.y, depth);- pos.setXYZ(i, x, sampleHeight(x, z) + 0.008 + Math.abs(Math.sin(t * 7 + ph * TAU)) * hop, z);- }- pos.needsUpdate = true;- };- group.userData.sampleHeight = boundedSampler(width, depth, sampleHeight);- group.userData.update = update;- group.userData.seed = seed;- update(0);- // Assets may be parented to this terrain later; the construction-time- // snapshot keeps those caller attachments borrowed.- return attachDisposal(group, snapshotResources(group));-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sky.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sky.jsindex 0fe7cd7f..f602cc67 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sky.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sky.js@@ -195,7 +195,7 @@ export function makeSky(scene, opts = {}) {? opts.rig.sunDir.clone().normalize() : sunDir;u.sunPosition.value.copy(sunDir);// r184 Sky ships value-noise clouds ON by default — grid artifacts- // at readable contrast. Clouds come from ./clouds.js instead.+ // at readable contrast. Clouds are the scene's own.if (u.cloudCoverage) u.cloudCoverage.value = 0;// THE GRADE. Extra uniforms on the addon's own material; thediff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smoke.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smoke.jsdeleted file mode 100644index 7ea994bb..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smoke.js+++ /dev/null@@ -1,264 +0,0 @@-/**- * Rising smoke and condensation plumes: a bounded 3D density field advected- * upward, widened by entrainment, bent by wind and illuminated through itself.- * Absolute time and a seeded noise texture make scrubbing deterministic.- *- * This is an authored transport model, not a fluid simulation. It has no- * collision response, scene-shadow reception or terrain shadow casting. Keep- * dense opaque intersections out of the visible plume: its first contributing- * density supplies fragment depth, so empty proxy space cannot erase visible- * front wisps. This does not truncate integration at opaque scene depth; an- * object cutting through actual density still needs a scene-depth pass.- * The front-density depth correction requires standard, non-logarithmic depth.- * Overlapping transparent objects use ordinary Three.js object sorting.- */-import * as THREE from 'three';-import { makeShaderMaterial, keepOutOfDepthPasses, makeLightProbe, option, positive, readWind } from './shader.js';-import { attachDisposal, snapshotResources } from './lifecycle.js';-import { bakeFbm3, dataTexture3D, mulberry32, sampleGrid3 } from './noise.js';--const RESOLUTION = 48;-const TIERS = { low: [36, 4], balanced: [64, 6], high: [100, 10] };-const clamp = (x, a = 0, b = 1) => Math.max(a, Math.min(b, x));-const smooth = (a, b, x) => { const t = clamp((x - a) / (b - a)); return t * t * (3 - 2 * t); };--function noiseTexture(seed) {- const { values } = bakeFbm3(mulberry32(seed), RESOLUTION, [4, 8, 16, 32], 3);- const data = new Uint8Array(RESOLUTION ** 3 * 4).fill(255);- for (let i = 0; i < values.length; i++) data[i + Math.floor(i / 3)] = Math.round(values[i] * 255);- return dataTexture3D(data, RESOLUTION);-}--const HEAD = /* glsl */`-precision highp sampler3D;-uniform sampler3D uPlumeNoise;-uniform vec3 uBoundsMin;-uniform vec3 uBoundsMax;-uniform vec3 uCameraLocal;-uniform mat3 uLocalToWorld;-uniform mat4 uLocalToClip;-uniform vec3 uSunLocal;-uniform vec3 uSunWorld;-uniform vec3 uSunColor;-uniform vec3 uAmbient;-uniform vec3 uPointLocal;-uniform vec3 uPointColor;-uniform vec2 uPointFalloff;-uniform vec3 uAlbedo;-uniform vec2 uWind;-uniform float uHeight;-uniform float uRadius;-uniform float uSpread;-uniform float uRise;-uniform float uTurbulence;-uniform float uDissipation;-uniform float uExtinction;-uniform float uAnisotropy;-uniform float uTime;-varying vec3 vPlumeLocal;--vec2 plumeBox(vec3 origin, vec3 direction) {- return astraRayBox(origin, direction, uBoundsMin, uBoundsMax);-}-float plumeDensity(vec3 p) {- float y = p.y;- if (y <= 0.0 || y >= uHeight) return 0.0;- float h = y / uHeight, age = y / uRise;- float phase = (y - uTime * uRise) / uHeight;- vec2 drift = uWind * age + uTurbulence * y * .13 *- vec2(sin(phase*8.1), cos(phase*6.7+1.4));- vec3 q = vec3(p.x-drift.x, y-uTime*uRise, p.z-drift.y) / uRadius;- vec3 warp = texture(uPlumeNoise,q*.083).rgb - .5;- float coarse = texture(uPlumeNoise,q*.115+warp*.34).r;- float fine = texture(uPlumeNoise,q*.49+warp*.21+vec3(.17,.39,.61)).g;- float radius = uRadius + uSpread * y;- float irregular = (coarse-.5)*3.8*uTurbulence*smoothstep(.02,.18,h);- float radial = length(p.xz-drift) / radius;- float body = max(0.0,1.0-radial+irregular);- float density = pow(max(0.0,body*.85-(1.0-fine)*.30*uTurbulence),1.2);- return min(density,1.0) * smoothstep(0.0,.018,h) *- (1.0-smoothstep(.65,1.0,h)) * exp(-uDissipation*h);-}-float plumePhase(float cosine) {- float g = uAnisotropy, gg = g*g;- return (1.0-gg) / (12.5663706144 * pow(max(.001,1.0+gg-2.0*g*cosine),1.5));-}-float plumeTransmission(vec3 p, vec3 direction, float distance) {- float end = min(max(0.0,plumeBox(p,direction).y),distance);- float metric = length(uLocalToWorld*direction);- float tau = 0.0;- for(int j=0;j<PLUME_LIGHT_STEPS;j++) {- float a=float(j)/float(PLUME_LIGHT_STEPS), b=float(j+1)/float(PLUME_LIGHT_STEPS);- float start=a*a*end, stop=b*b*end;- tau += plumeDensity(p+direction*(start+stop)*.5)*(stop-start)*metric*uExtinction;- }- return exp(-tau);-}-`;--/**- * makeSmoke({height:3,radius:.14,spread:.20,riseSpeed:.7,wind:[.06,0],- * density:5/height,turbulence:1,dissipation:.7,color:0xb0b5bc,- * anisotropy:.35,quality:'balanced',seed:21,name:'Smoke'}) -> Mesh.- * Distances are local metres; wind/riseSpeed are local metres per second.- * density is optical extinction per WORLD metre. The origin is the emitter- * at local y=0. Geometry bounds include wind displacement and turbulence.- *- * Lighting follows the strongest visible directional and point light, plus- * an average ambient/hemisphere/environment contribution. Local light shadow- * marches only include this plume. color is scattering albedo (linear Color- * or sRGB hex). update(t) uses absolute seconds; sampleDensity(x,y,z,t) queries- * the same seeded field; dispose() releases only construction-owned resources.- */-export function makeSmoke(opts = {}) {- return makePlume(opts, false);-}--/** Condensation preset: lighter scattering, faster upward motion and dilution. */-export function makeSteam(opts = {}) {- return makePlume(opts, true);-}--function makePlume(opts, steam) {- const L = steam ? 'makeSteam: ' : 'makeSmoke: ';- const height = option(opts.height, steam ? .7 : 3, L + 'height', .001, 10000);- const radius = positive(opts.radius, height * (steam ? .09 : .047), L + 'radius', height * 4);- const spread = option(opts.spread, steam ? .16 : .20, L + 'spread', 0, 2);- const rise = positive(opts.riseSpeed, height * (steam ? .38 : .2333333), L + 'riseSpeed');- const w = readWind(opts.wind, [height * .02, 0], 'makeSmoke/makeSteam wind'), wind = [w.x, w.z];- const extinction = option(opts.density, (steam ? 2.1 : 5) / height, L + 'density', 0);- const turbulence = option(opts.turbulence, steam ? .9 : 1, L + 'turbulence', 0, 2);- const dissipation = option(opts.dissipation, steam ? 1.2 : .7, L + 'dissipation', 0);- const anisotropy = option(opts.anisotropy, steam ? .62 : .35, L + 'anisotropy', -.9, .9);- const seed = option(opts.seed, 21, L + 'seed');- const quality = opts.quality ?? 'balanced';- if (!Object.hasOwn(TIERS, quality)) throw new RangeError(`${L}quality must be one of ${Object.keys(TIERS)}`);- if (Math.hypot(...wind) / rise > 10) throw new RangeError(`${L}wind must be at most 10x riseSpeed`);- const texture = noiseTexture(seed), [steps, lightSteps] = TIERS[quality];- const maxRadius = (radius + spread * height) * (1 + turbulence * 1.9) + turbulence * height * .13;- const drift = wind.map(v => v * height / rise);- const boundsMin = new THREE.Vector3(Math.min(0,drift[0])-maxRadius,0,Math.min(0,drift[1])-maxRadius);- const boundsMax = new THREE.Vector3(Math.max(0,drift[0])+maxRadius,height,Math.max(0,drift[1])+maxRadius);- const material = makeShaderMaterial({- name: steam ? 'SteamVolumeMaterial' : 'SmokeVolumeMaterial', transparent: true,- depthWrite: false, side: THREE.BackSide, fog: false,- defines: { PLUME_STEPS: steps, PLUME_LIGHT_STEPS: lightSteps },- uniforms: {- uPlumeNoise: { value: texture }, uBoundsMin: { value: boundsMin }, uBoundsMax: { value: boundsMax },- uCameraLocal: { value: new THREE.Vector3() }, uLocalToWorld: { value: new THREE.Matrix3() },- uLocalToClip: { value: new THREE.Matrix4() },- uSunLocal: { value: new THREE.Vector3(0,1,0) }, uSunWorld: { value: new THREE.Vector3(0,1,0) },- uSunColor: { value: new THREE.Color(0) }, uAmbient: { value: new THREE.Color(0) },- uPointLocal: { value: new THREE.Vector3() }, uPointColor: { value: new THREE.Color(0) },- uPointFalloff: { value: new THREE.Vector2() },- uAlbedo: { value: new THREE.Color(opts.color ?? (steam ? 0xf8faff : 0xb0b5bc)) },- uWind: { value: new THREE.Vector2(...wind) }, uHeight: { value: height }, uRadius: { value: radius },- uSpread: { value: spread }, uRise: { value: rise }, uExtinction: { value: extinction },- uTurbulence: { value: turbulence }, uDissipation: { value: dissipation }, uAnisotropy: { value: anisotropy },- uTime: { value: 0 },- },- varyings: 'varying vec3 vPlumeLocal;', vertexMain: 'vPlumeLocal=position;', fragmentHead: HEAD,- fragmentMain: /* glsl */`- vec3 direction=normalize(vPlumeLocal-uCameraLocal);- vec2 bounds=plumeBox(uCameraLocal,direction);- float start=max(0.0,bounds.x), end=bounds.y;- if(end<=start || uExtinction<=0.0) discard;- float stepLength=(end-start)/float(PLUME_STEPS);- float metric=length(uLocalToWorld*direction);- vec3 worldDirection=normalize(uLocalToWorld*direction);- float sunPhase=plumePhase(dot(worldDirection,uSunWorld));- float jitter=.15+.7*astraHash21(gl_FragCoord.xy);- float transmittance=1.0;- vec3 radiance=vec3(0.0);- vec3 firstDensity=uCameraLocal+direction*end;- bool densityHit=false;- for(int i=0;i<PLUME_STEPS;i++) {- vec3 p=uCameraLocal+direction*(start+(float(i)+jitter)*stepLength);- float density=plumeDensity(p);- if(density>.001) {- if(!densityHit){firstDensity=p;densityHit=true;}- float sunT=plumeTransmission(p,uSunLocal,1e6);- vec3 lighting=uAmbient*(.5+.5*exp(-density*uExtinction*uRadius)) + uSunColor*sunPhase*sunT;- if(max(uPointColor.r,max(uPointColor.g,uPointColor.b))>0.0) {- vec3 delta=uPointLocal-p;- float localDistance=max(length(delta),1e-5);- vec3 pointDirection=delta/localDistance;- vec3 worldDelta=uLocalToWorld*delta;- float distance=max(length(worldDelta),.01);- float falloff=1.0/max(pow(distance,uPointFalloff.y),.01);- if(uPointFalloff.x>0.0) falloff*=pow(clamp(1.0-pow(distance/uPointFalloff.x,4.0),0.0,1.0),2.0);- lighting+=uPointColor*falloff*plumePhase(dot(worldDirection,normalize(worldDelta)))*- plumeTransmission(p,pointDirection,localDistance);- }- float alpha=1.0-exp(-density*uExtinction*stepLength*metric);- radiance+=transmittance*alpha*lighting*uAlbedo;- transmittance*=1.0-alpha;- if(transmittance<.01) break;- }- }- float alpha=1.0-transmittance;- if(alpha<.002) discard;- // The exit face is only a ray proxy, often behind nearby opaque objects.- // Depth-test the visible field instead of discarding its entire ray.- #ifndef USE_LOGDEPTHBUF- gl_FragDepth=astraClipDepth(uLocalToClip,firstDensity);- #endif- gl_FragColor=vec4(radiance/max(alpha,.001),alpha);- `,- });- const size = boundsMax.clone().sub(boundsMin), centre = boundsMin.clone().add(boundsMax).multiplyScalar(.5);- const geometry = new THREE.BoxGeometry(size.x,size.y,size.z).translate(centre.x,centre.y,centre.z);- const mesh = new THREE.Mesh(geometry,material);- mesh.name = opts.name ?? (steam ? 'Steam' : 'Smoke');- keepOutOfDepthPasses(mesh);- const before = mesh.onBeforeRender, inverse = new THREE.Matrix4();- const position = new THREE.Vector3(), readLights = makeLightProbe();- const u = material.uniforms;- mesh.onBeforeRender = (...args) => {- before.apply(mesh,args);- const [,scene,camera] = args;- inverse.copy(mesh.matrixWorld).invert();- camera.getWorldPosition(u.uCameraLocal.value).applyMatrix4(inverse);- u.uLocalToWorld.value.setFromMatrix4(mesh.matrixWorld);- u.uLocalToClip.value.copy(camera.projectionMatrix).multiply(camera.matrixWorldInverse).multiply(mesh.matrixWorld);- const { sun, point, ambient, sky, environment, sunDirection } = readLights(scene, mesh.getWorldPosition(position));- u.uSunColor.value.setRGB(0,0,0);u.uPointColor.value.setRGB(0,0,0);- const fill = (c) => ambient[c] * .28 + sky[c] * .22 + environment * .12;- u.uAmbient.value.setRGB(fill('r'), fill('g'), fill('b'));- if (sun) {- u.uSunWorld.value.copy(sunDirection);- u.uSunLocal.value.copy(sunDirection).transformDirection(inverse);- u.uSunColor.value.copy(sun.color).multiplyScalar(sun.intensity);- }- if (point) {- point.getWorldPosition(u.uPointLocal.value).applyMatrix4(inverse);- u.uPointColor.value.copy(point.color).multiplyScalar(point.intensity);- u.uPointFalloff.value.set(point.distance,point.decay);- }- };- mesh.userData.update = t => {- if (!Number.isFinite(t)) throw new RangeError('Smoke.update: time must be finite');- u.uTime.value = t;- };- const noise = (x,y,z,c) => sampleGrid3(texture.image.data,RESOLUTION,- x*RESOLUTION-.5,y*RESOLUTION-.5,z*RESOLUTION-.5,4,c)/255;- mesh.userData.sampleDensity = (x,y,z,t = u.uTime.value) => {- if (![x,y,z,t].every(Number.isFinite)) throw new RangeError('Smoke.sampleDensity: coordinates/time must be finite');- if (y <= 0 || y >= height) return 0;- const h = y/height, phase = (y-t*rise)/height;- const dx = wind[0]*y/rise+turbulence*y*.13*Math.sin(phase*8.1);- const dz = wind[1]*y/rise+turbulence*y*.13*Math.cos(phase*6.7+1.4);- const q = [(x-dx)/radius,(y-t*rise)/radius,(z-dz)/radius];- const warp = [0,1,2].map(c => noise(...q.map(v => v*.083),c)-.5);- const coarse = noise(...q.map((v,i) => v*.115+warp[i]*.34),0);- const fine = noise(...q.map((v,i) => v*.49+warp[i]*.21+[.17,.39,.61][i]),1);- const irregular = (coarse-.5)*3.8*turbulence*smooth(.02,.18,h);- const body = Math.max(0,1-Math.hypot(x-dx,z-dz)/(radius+spread*y)+irregular);- const value = Math.pow(Math.max(0,body*.85-(1-fine)*.30*turbulence),1.2);- return Math.min(value,1)*smooth(0,.018,h)*(1-smooth(.65,1,h))*Math.exp(-dissipation*h);- };- mesh.userData.bounds = new THREE.Box3(boundsMin.clone(),boundsMax.clone());- mesh.userData.quality = quality;- const owned = snapshotResources(mesh);owned.add(texture);- return attachDisposal(mesh,owned);-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/strata.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/strata.jsdeleted file mode 100644index 9823709b..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/strata.js+++ /dev/null@@ -1,483 +0,0 @@-/**- * The two marks that make a cliff read as ROCK and not as brown- * geometry: the beds it was laid down in, and the runs the rain has cut- * down it. Neither is decoration — a face with no bedding reads as a- * displaced blob, and one with no runs reads as a clean model of rock.- *- * Both go through `patchStandard`, so the built-in's lighting, shadows,- * fog and depth chunks survive, and both shade from world position and- * world normal — no UV to author, and a face at any angle gets the same- * geology. They are meant to land ON TOP of `patchTriplanar` /- * `patchSlopeSplat`, whose noise keeps showing through both.- *- * The constraint that shapes them: a fragment sees its own position,- * its own normal and its own screen derivatives, and nothing else. So- * the beds ride world ALTITUDE — one stack for the whole scene, which- * is why two cliffs a hundred metres apart line up — and a run learns- * where water collects only from the way the surface BENDS under it (a- * gully across the flow, a lip along it) plus its own field smeared- * downslope, which is what gives a run a head and a tail.- */--import * as THREE from 'three';-import {- patchStandard, glslCurv, hash11, seedVec3, toColor,- unit, worldBase,-} from './shader.js';--// Helpers both patches share, all astraStrata-prefixed: GLSL has one-// global namespace, and a chained patch redefining a neighbour's-// function is a compile error naming neither of them.-const STRATA_HEAD = [- 'float astraStrataFbm(vec2 p) {',- ' return clamp(astraFbm2(p, 3) / 0.875, 0.0, 1.0);',- '}',- // The floor of bed `k`, offset by its own hash. Under half a bed, so- // the stack stays in order however the offsets fall and the bed- // holding a coordinate is always within one of its floor().- 'float astraStrataFloor(float k, float s) {',- ' return k + (astraHash21(vec2(k, s)) - 0.5) * 0.9;',- '}',- // Value noise in 3-D, built from the 2-D one: the run field is- // smeared along the fall line, which is no world axis, so an- // axis-projected field cannot carry it.- 'float astraStrataN3(vec3 p) {',- ' float k = floor(p.z), f = p.z - k;',- ' f = f * f * (3.0 - 2.0 * f);',- ' return mix(astraNoise2(p.xy + k * 37.13),',- ' astraNoise2(p.xy + (k + 1.0) * 37.13), f);',- '}',- // A run is the SMEAR of a source along the flow: taps UPSLOPE of here- // with decaying weight, so a feature is long downslope, narrow across- // it, and tapers out below where it started.- 'float astraStrataRun(vec3 p, vec3 d, float len, int taps) {',- ' float s = astraStrataN3(p), w = 1.0, a = 1.0, o = 0.0;',- // Unevenly spaced: at one tap per noise cell they would all land on- // the same lattice phase and comb the run into blocks. The count is- // the aspect ratio — a tap cannot reach past its neighbour's cell.- ' for (int i = 0; i < 6; i++) {',- ' if (i >= taps) break;',- ' o += len * (0.11 + 0.035 * float(i));',- ' a *= 0.78; w += a;',- ' s += a * astraStrataN3(p - d * o);',- ' }',- ' return clamp((s / w - 0.5) * 2.2 + 0.5, 0.0, 1.0);',- '}',- // Total curvature: negative is the concave that holds water.- glslCurv('astraStrataCurv'),- // The same, restricted to ONE surface direction. A lip is convex- // along the flow and a rib is convex across it, and they do opposite- // things to a run, so the two halves have to be separable.- 'float astraStrataBend(vec3 n, vec3 p, vec3 d) {',- ' float ax = dot(dFdx(p), d), ay = dot(dFdy(p), d);',- ' return (dot(dFdx(n), d) * ax + dot(dFdy(n), d) * ay)',- ' / max(ax * ax + ay * ay, 1e-12);',- '}',- // Only a bend the size of a run is a landform: `k` is curvature in- // run widths, and the pixel-scale wrinkle under it (k of 4 and up)- // is not a gully and must not be allowed to draw one.- 'float astraStrataBand(float k) {',- ' return smoothstep(0.15, 0.80, k) * (1.0 - smoothstep(2.0, 5.0, k));',- '}',-].join('\n');--// On the world varyings terrain_shade, aging, surface_wear and waterside-// share, so a material wearing several libraries carries ONE world-// position.-const BASE = worldBase('strata:base', 'stbP', 'stbN', STRATA_HEAD);--// A pale sandstone, an iron-rich tan, a grey-green marl and a dark-// red-brown mudstone: enough spread that a thin dark bed between two-// thick pale ones is possible.-//-// The four differ in HUE and in saturation, not only in value. A ramp-// that walks one hue from light to dark is a greyscale ramp with a-// tint on it, and the beds then read as a barcode rather than as-// geology.-//-// They are also authored WARM on purpose, and the reason is measured-// rather than taste. Most of a cliff is in its own shade, and the fill-// this library ships (`sunRig`: a hemisphere at 0x9db8e8 over warm-// ground, plus a blue-sky environment) puts LINEAR (1, 1.56, 2.45) on-// a shaded vertical face — a neutral grey albedo renders (88, 110,-// 134) there. An albedo has to beat that ratio to come back as rock at-// all: at G/R above ~0.64 linear the bed returns GREEN, which is how-// the original palette's mid tones read. These are solved against that-// measurement, so a shaded face returns roughly (1, 0.90, 0.73) for-// the buff down to (1, 0.63, 0.40) for the mudstone — sandstone, and-// under a neutral or overcast rig, red-rock sandstone. The four are-// spread by SATURATION between those, never toward yellow: a bed that-// reaches G/R = 1 in the render is one grain-multiply away from green.-const BEDS = [0xcc9f78, 0x8e6541, 0x74583f, 0x5b3a23];--// The constants differ from aging's and surface_wear's, or one seed-// would lay these runs down the middle of that library's stains.-const seedOffset = (seed, salt) =>- seedVec3(seed + salt, 1.63, 6.41, 11.09, 52);--/**- * Resample any palette to the four tones the shader ramps through.- *- * The count is fixed because the GLSL is: an option may vary by- * uniform, never by source, so two cliffs with two-colour and- * five-colour palettes still share one compiled program.- */-function palette4(colors) {- const list = (Array.isArray(colors) && colors.length ? colors : BEDS)- .map((c) => toColor(c, BEDS[1]));- if (list.length === 1) return [0, 1, 2, 3].map(() => list[0].clone());- return [0, 1, 2, 3].map((i) => {- const t = (i / 3) * (list.length - 1);- const k = Math.min(Math.floor(t), list.length - 2);- return list[k].clone().lerp(list[k + 1], t - k);- });-}--/**- * The normal of the bedding plane: world up, tipped by `tilt` degrees.- *- * The dip DIRECTION comes from the seed rather than from another- * option, so a scene sets one tilt and one seed and every cliff in it- * dips the same way.- */-function beddingUp(tilt, seed) {- const dip = Math.max(-85, Math.min(85, tilt)) * Math.PI / 180;- const az = hash11(seed + 0.71) * Math.PI * 2;- return new THREE.Vector3(- Math.sin(dip) * Math.cos(az), Math.cos(dip),- Math.sin(dip) * Math.sin(az)).normalize();-}--/**- * Lay sedimentary beds through the rock, by world ALTITUDE.- *- * A cliff reads as rock because it shows the layers it was deposited- * in, and the eye checks them against each other: beds have to run- * THROUGH the scene, so the band at 12 m on this face continues at- * 12 m on the one across the valley. That is why the coordinate is- * `dot(worldPosition, beddingNormal)` and nothing else — no UV, no- * object space, no per-mesh phase — and why every cliff should be- * given the same options.- *- * `tilt` is the whole point. Level beds read as a stripe texture; beds- * dipping a few degrees read as geology, because the bands then cut- * across the topography instead of following it. It is a dip in- * DEGREES, and the dip direction comes from `seed`.- *- * Three things keep it from being wallpaper. Bed THICKNESS varies, in- * two registers: a slow warp of the stack coordinate gives a run of- * thick beds and then a run of thin ones, and every bed floor carries- * its own offset on top of that, so a 0.8 m stack measures anywhere- * from 0.13 m to 1.5 m bed to bed. The bedding surfaces UNDULATE, by- * `jitter` of a bed over ~30 m of ground, so no boundary is a ruled- * line. And every so often a contact carries a thin dark PARTING —- * drawn with `astraStroke`, which fades a stroke out once a pixel spans- * more than it, so the seams thin away with distance instead of- * aliasing into moire. Past a pixel per bed the whole stack dissolves- * into its own mean tone, for the same reason.- *- * @param {THREE.Material} material A built-in material, patched in- * place — a shared material from `materials.js` beds every mesh- * wearing it, so clone it first if that is not what you want.- * @param {object} [opts] `spacing` metres of an average bed (default- * 0.8; thickness varies about it); `tilt` dip of the beds in degrees- * (default 7 — 0 is level and reads as texture, past ~25 it reads as- * folded); `colors` array of THREE.Color or hex, resampled to the- * four tones the beds ramp through (default a buff-to-mudstone run,- * authored WARM against this renderer's blue-sky fill — see BEDS; a- * palette that is merely "rock-coloured" comes back cyan in shade);- * `contrast` how far the albedo goes toward the bed tone, 0..1- * (default 0.7); `jitter` how far a bedding surface wanders, in beds- * (default 0.35); `seed` moves the tones, the wander and the dip- * direction (default 1).- * @returns {THREE.Material} The same material. Its uniforms stay live- * on `material.userData.uniforms`, so `uStrataUp` can be retuned for- * a whole scene at once.- */-export function patchRockStrata(material, opts = {}) {- const spacing = opts.spacing === undefined ? 0.8 : opts.spacing;- const tilt = opts.tilt === undefined ? 7 : opts.tilt;- const contrast = opts.contrast === undefined ? 0.7 : opts.contrast;- const jitter = opts.jitter === undefined ? 0.35 : opts.jitter;- const seed = opts.seed === undefined ? 1 : opts.seed;- const beds = palette4(opts.colors);- patchStandard(material, BASE);- return patchStandard(material, {- name: 'strata:beds',- uniforms: {- uStrataUp: { value: beddingUp(tilt, seed) },- uStrataSpacing: { value: Math.max(1e-3, spacing) },- uStrataAmt: { value: unit(contrast) },- uStrataJit: { value: Math.max(0, jitter) },- uStrataSeed: { value: seedOffset(seed, 0) },- uStrataC0: { value: beds[0] },- uStrataC1: { value: beds[1] },- uStrataC2: { value: beds[2] },- uStrataC3: { value: beds[3] },- },- fragmentHead: [- 'uniform vec3 uStrataUp;',- 'uniform float uStrataSpacing;',- 'uniform float uStrataAmt;',- 'uniform float uStrataJit;',- 'uniform vec3 uStrataSeed;',- 'uniform vec3 uStrataC0;',- 'uniform vec3 uStrataC1;',- 'uniform vec3 uStrataC2;',- 'uniform vec3 uStrataC3;',- // A ramp, not a set: neighbouring beds take unrelated points on- // it, so a sequence gets both near-twins and hard contacts.- 'vec3 astraStrataTone(float f) {',- ' float g = f * 3.0;',- ' vec3 c = mix(uStrataC0, uStrataC1, clamp(g, 0.0, 1.0));',- ' c = mix(c, uStrataC2, clamp(g - 1.0, 0.0, 1.0));',- ' return mix(c, uStrataC3, clamp(g - 2.0, 0.0, 1.0));',- '}',- // Which point of the ramp a bed takes. A uniform draw lands a- // quarter of the beds in the palest quarter and a quarter in the- // darkest, and consecutive beds then alternate near-white and- // near-black: a barcode, not a formation. This pulls the middle- // of the draw toward the middle of the ramp and leaves the two- // ends alone, so most beds are mid-tone and the pale marker bed- // and the dark parting bed stay rare enough to read as events.- // Monotone and continuous, so the contact antialiasing below is- // untouched.- 'float astraStrataPick(float h) {',- ' float e = abs(2.0 * h - 1.0);',- ' return 0.5 + (h - 0.5) * (0.45 + 0.55 * e * e);',- '}',- ].join('\n'),- fragmentBody: [- // Altitude across the beds, in beds. World, and anchored to- // nothing the mesh knows, so two cliffs cut one stack.- ' float stB = dot(vAstraWorld, normalize(uStrataUp))',- ' / uStrataSpacing;',- // The surfaces undulate over ~30 m of ground: no bed was ever- // laid down against a ruler.- ' stB += (astraStrataFbm(vAstraWorld.xz * 0.035',- ' + uStrataSeed.xz) - 0.5) * uStrataJit;',- // A slow stretch of the stack by a function of ITSELF: a run of- // thick beds, then a run of thin ones, the way a formation reads.- ' stB += (astraStrataFbm(vec2(stB * 0.16, uStrataSeed.y)) - 0.5)',- ' * 1.20;',- // ...and each bed floor carries its OWN offset on top of that, so- // one bed comes out several times another. A stripe of one width- // is wallpaper, and this is the line that stops it being one.- ' float stI = floor(stB);',- ' float stLo = astraStrataFloor(stI, uStrataSeed.z);',- ' if (stB < stLo) {',- ' stI -= 1.0;',- ' stLo = astraStrataFloor(stI, uStrataSeed.z);',- ' }',- ' float stHi = astraStrataFloor(stI + 1.0, uStrataSeed.z);',- ' if (stB >= stHi) {',- ' stI += 1.0; stLo = stHi;',- ' stHi = astraStrataFloor(stI + 1.0, uStrataSeed.z);',- ' }',- ' float stTh = max(stHi - stLo, 1e-3);',- ' float stF = (stB - stLo) / stTh;',- // Continuous across a contact where stF is not, so the seam's own- // antialiasing reads a gradient there instead of a jump.- ' float stP = stI + stF;',- ' float stAA = clamp(fwidth(stB) / stTh, 1e-4, 2.0);',- // astraHash21, not astraHash11: over consecutive integers the 1-D- // one lands 40% of the beds in its palest quarter and the cliff- // comes out bleached.- ' float stNb = stI + (stF < 0.5 ? -1.0 : 1.0);',- // A contact is sharp in the rock, and a sharp edge in a shader is- // what crawls — MSAA never sees one — so it is resolved over the- // pixel it actually covers.- ' vec3 stCol = mix(',- ' astraStrataTone(astraStrataPick(',- ' astraHash21(vec2(stI, uStrataSeed.z + 2.3)))),',- ' astraStrataTone(astraStrataPick(',- ' astraHash21(vec2(stNb, uStrataSeed.z + 2.3)))),',- ' 0.5 - 0.5 * smoothstep(0.0, stAA, min(stF, 1.0 - stF)));',- // Grain from world XZ only, so within a bed it streaks ALONG the- // bedding on any vertical face, and each bed gets its own.- ' float stG = astraStrataFbm(vAstraWorld.xz * 1.1 + stI * 4.7);',- // In HUE as well as value: one bed is not one colour across a- // face — it is warm where the iron collected and washed out where- // it did not — and a scalar multiply here leaves a whole bed- // flat, which is what makes a shader stack read as printed- // stripes. The far end of the grain is BLEACHED, barely cool: on- // a face already lit by a blue sky a cool multiply is what tips a- // bed past G/R = 1 and turns it green, and a green patch is not- // a mineral.- ' stCol *= mix(vec3(1.12, 1.02, 0.87), vec3(0.95, 0.97, 1.01),',- ' stG);',- // A finer mottle on top, so the metre-scale grain is not the- // smallest thing on the rock at arm's length.- ' float stG2 = astraStrataFbm(vAstraWorld.xz * 3.7 + stI * 9.1);',- ' stCol *= mix(0.93, 1.06, stG2);',- // Every bed is a little darker at its foot, which is the shadow- // of the ledge the harder bed above it makes — and warmer, since- // that is where the iron coming down the face stops.- ' stCol *= mix(vec3(1.0), vec3(1.0, 0.92, 0.80),',- ' 1.0 - smoothstep(0.0, 0.32, stF));',- ' stCol *= mix(0.93, 1.03, smoothstep(0.0, 0.30, stF));',- // The occasional thin dark parting at a contact, in fractions of- // the bed it belongs to; astraStroke fades it out rather than- // aliasing once a pixel spans more than the seam itself.- ' float stS = astraHash21(vec2(stI, uStrataSeed.z + 5.1));',- ' float stSeam = astraStroke(stP + 0.5, mix(0.02, 0.09, stS))',- ' * smoothstep(0.55, 0.75, stS)',- // ...and it fades in and out ALONG the bed, on that bed's own- // grain. A parting of one strength the whole way round is a- // scribed line, which is the tell that a shader drew the contact.- ' * mix(0.28, 1.0, stG);',- // A parting is a thin bed of clay, not a hole punched in the- // cliff: it goes to a dark, slightly cooler version of the rock- // above it and keeps a floor, so the seam never crushes to black- // and never loses its hue.- ' stCol = mix(stCol,',- ' stCol * vec3(0.50, 0.49, 0.54)',- ' + vec3(0.012, 0.011, 0.012), 0.66 * stSeam);',- // A pixel that spans a bed cannot show one, so the stack- // dissolves into its own mean tone there instead of into moire —- // and the far cliff keeps its rock colour rather than reverting.- ' vec3 stAvg = 0.25 * (uStrataC0 + uStrataC1 + uStrataC2',- ' + uStrataC3);',- ' stCol = mix(stCol, stAvg, smoothstep(0.30, 1.00, stAA));',- ' diffuseColor.rgb = mix(diffuseColor.rgb, stCol, uStrataAmt);',- ].join('\n'),- });-}--/**- * Cut the runs the rain leaves down a face, along the FALL LINE.- *- * Rock does not weather evenly: water sheets off the ledges, gathers- * into threads and takes the dirt down the steepest path, which is- * straight down a vertical face and the fall line on anything shallower- * — never world Y on a slope, and never a UV direction. The fall line- * is `gravity - normal * dot(gravity, normal)`, and a run is that- * direction's SMEAR of the field: taps upslope of each fragment with- * decaying weight, so features come out long downslope, narrow across- * it, and bend as the surface turns. (Squashing the position along the- * fall line instead is cheaper and wrong — the lever arm is the whole- * world position, so a 1% turn of the normal moves the field a whole- * feature and the surface's own wrinkles get painted on it.)- *- * They must not be everywhere, and a fragment cannot look up the slope- * to find the ledge that fed it. What it CAN see is the way the surface- * bends under it, so the sources are read from curvature split into its- * two halves: concave ACROSS the flow is a gully and holds its thread- * the whole way down, convex ALONG the flow is a lip and pours what it- * catches over, and convex across is a rib that sheds sideways and- * stays clean. A source lowers the field's THRESHOLD rather than- * dimming it, so clean rock keeps a few strong runs and a gully floor- * darkens broadly. On flat-shaded geometry (`BoxGeometry`, anything- * unwelded) curvature reads zero and the field alone carries it.- *- * The fade downslope is the smear's own decay: each tap upslope arrives- * weaker than the last, so a run continues below where it started and- * tapers out, which is flow rather than stripes.- *- * The same wash mask polishes roughness locally. The dry rock between- * runs retains its original finish and a live strength of zero restores it.- *- * @param {THREE.Material} material A built-in material, patched in- * place — a shared material streaks every mesh wearing it.- * @param {object} [opts] `strength` how far a run goes toward `color`,- * 0..1 (default 0.45); `color` THREE.Color or hex, the mineral the- * runs carry — the shader derives a rust and a darker varnish from it- * (default a dark iron brown; a NEUTRAL dark here renders as a- * slate-blue patch under a blue-sky fill, which is what the reference- * grey-brown did); `scale` metres across a run (default 0.8; its- * length is ~8x that, and the curvature the sources look for scales- * with it); `seed` moves them (default 1).- * @returns {THREE.Material} The same material, with its uniforms live- * on `material.userData.uniforms`.- */-export function patchErosionStreaks(material, opts = {}) {- const strength = opts.strength === undefined ? 0.45 : opts.strength;- const scale = opts.scale === undefined ? 0.8 : opts.scale;- const seed = opts.seed === undefined ? 1 : opts.seed;- patchStandard(material, BASE);- return patchStandard(material, {- name: 'strata:erosion',- uniforms: {- uErosAmt: { value: unit(strength) },- uErosColor: { value: toColor(opts.color, 0x3e2615) },- uErosScale: { value: Math.max(1e-3, scale) },- uErosSeed: { value: seedOffset(seed, 3.7) },- },- fragmentHead: [- 'uniform float uErosAmt;',- 'uniform vec3 uErosColor;',- 'uniform float uErosScale;',- 'uniform vec3 uErosSeed;',- ].join('\n'),- fragmentBody: [- ' vec3 erN = normalize(vAstraWorldN);',- // The fall line is gravity with the normal taken out, and its- // LENGTH is the sine of the slope — one expression gives the way- // the water goes and the gate that keeps it off level ground.- ' vec3 erG = vec3(0.0, -1.0, 0.0) + erN * erN.y;',- ' float erSin = length(erG);',- ' vec3 erD = erG / max(erSin, 1e-4);',- ' vec3 erP = vAstraWorld / uErosScale + uErosSeed;',- // Long: the smear is what makes a run a run, and at 5.5 it came- // out as round blotches on a face this size — a stain, not a- // track. Six taps over 7.5 run widths is an 8:1 feature before- // the threshold ever sees it.- ' float erA = astraStrataRun(erP, erD, 7.5, 6);',- // A finer smear ADDED before the threshold rather than multiplied- // after: it tears every run's edge into threads that run WITH it.- // Weighted hard enough to actually break the edge — at 0.26 the- // broad field won everywhere and the runs closed back into blobs.- ' float erFib = astraStrataRun(erP * 3.4, erD, 2.8, 4);',- ' float erF = erA + (erFib - 0.5) * 0.40;',- // Curvature in run widths, split by direction: a hollow ACROSS- // the flow holds water, a break ALONG it pours what it caught- // over, a rib across it sheds sideways and stays clean.- ' float erAl = astraStrataBend(erN, vAstraWorld, erD) * uErosScale;',- ' float erAc = astraStrataCurv(erN, vAstraWorld) * uErosScale',- ' - erAl;',- ' float erSrc = clamp(0.34 + 0.60 * astraStrataBand(-erAc)',- ' + 0.40 * astraStrataBand(erAl)',- ' - 0.32 * astraStrataBand(erAc), 0.0, 1.0);',- // A source lowers the BAR rather than dimming the run: clean rock- // keeps only the strongest few. The span is narrow because a- // screen-derivative gate is flat per TRIANGLE.- ' float erT = mix(0.72, 0.58, erSrc);',- ' float erAA = clamp(fwidth(erF), 0.0, 0.5);',- // Two levels on one field, kept APART rather than summed away: a- // broad wash and the darker core inside it are different- // minerals, and the pair is what makes a run read as a run and- // not as a smudge.- ' float erBroad = smoothstep(erT - 0.10 - erAA,',- ' erT + 0.04 + erAA, erF);',- ' float erCore = smoothstep(erT + 0.04 - erAA,',- ' erT + 0.15 + erAA, erF);',- ' float erK = 0.45 * erBroad + 0.55 * erCore;',- // A slope to run down, and not a soffit: what faces down drips- // clear of the rock instead of tracking across it.- ' float erFlow = smoothstep(0.10, 0.42, erSin)',- ' * (1.0 - smoothstep(0.15, 0.65, -erN.y));',- ' float erAmt = clamp(erK * erFlow * uErosAmt, 0.0, 1.0);',- // Which mineral this run carries, from a field far coarser than- // the run itself, so ONE run is one mineral the whole way down- // instead of speckling along its length: iron leaves a rust- // margin, manganese the near-black varnish of a desert face.- // Neither variant is allowed to go neutral: under a blue-sky fill- // a neutral dark stain renders as a slate-blue patch, which is- // how a grey-brown default reads on a cliff in its own shade.- ' float erMin = astraStrataN3(erP * 0.21 + 13.7);',- ' vec3 erIron = uErosColor * vec3(1.55, 1.15, 0.78);',- ' vec3 erMang = uErosColor * vec3(0.55, 0.58, 0.72);',- ' vec3 erTint = mix(erIron, erMang,',- ' erCore * mix(0.35, 0.95, erMin));',- // A wet track DARKENS the rock it runs over and keeps that- // rock\'s hue; replacing the albedo outright erases the bedding- // the runs are supposed to run ACROSS, which is what turns a- // face of runs into a face of grey cloud. So the stain is a- // darkening of what is underneath, tinted toward the mineral.- ' vec3 erWet = diffuseColor.rgb * mix(0.30, 0.78, erA);',- ' vec3 erCol = mix(erWet, erTint * mix(0.78, 1.22, erA), 0.56);',- ' diffuseColor.rgb = mix(diffuseColor.rgb, erCol, erAmt);',- ].join('\n'),- roughnessBody: 'roughnessFactor = mix(roughnessFactor, max(0.12, roughnessFactor * 0.72), erAmt);',- });-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/surface_wear.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/surface_wear.jsdeleted file mode 100644index 5accf700..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/surface_wear.js+++ /dev/null@@ -1,272 +0,0 @@-/**- * Surface wear: the two passes that land on EVERY material in a scene.- *- * The rest of this library shades one KIND of thing — a cliff, a leaf,- * a waterline. These two shade whatever they are handed, which is why- * they are the cheapest realism here: a scene reads as CG largely- * because every material paints one exact colour at one exact gloss- * over a whole object, and no photographed surface does either. Both go- * through `patchStandard`, so lighting, shadows, fog and the depth- * chunks survive; both shade from world position and world normal, so- * neither needs a UV; and both CHAIN with each other and with- * `terrain_shade` / `waterside` on one material.- *- * The same local fields modify roughness after the roughness map: clean- * areas retain their authored finish and worn edges alone become polished.- *- * PORT NOTES (2026-09-01, measured on our host — no post chain, ACES in- * the fragment tail, a bright baked environment as the specular source):- *- * 1. The breakup's hue jitter was `astraHueShift`, a rotation about the- * grey axis, and that rotation returns a NEUTRAL unchanged — exactly- * zero on a grey, 0.0014 peak channel move on our stone albedo- * 0x8d8577 at the default 0.03. Stone, plaster, concrete and dirt- * are most of what this patch ever lands on, so the one line meant- * to make it "a change of MATERIAL rather than a brightness dial"- * was a no-op on them. It is a warm/cool break now — the swing- * daylight actually makes, and the same transfer `astraHueBreak`- * uses — so `hue` is a fraction of the albedo, not radians.- * 2. Edge wear degenerated into a barber pole on anything thin. Past- * ~3x the onset curvature the ramp is saturated, so on a 6 cm rail- * post the ONLY structure left was one 14 cm blotch field on a 12 cm- * object: alternating solid bands of flat bone white. The break-up- * is two octaves now, both scaled to the width asked for, and the- * worn tone is thinned paint before it is bare substrate.- * 3. The worn tone was one flat colour over every material wearing it.- * It carries its own value and warm/cool variance now, and the- * default substrate came down from 0xe8e2d6 (0.816 linear — over- * the top of the sane albedo range before the value break, and it- * read as white primer under our sun) to 0xd2cabb, which leaves the- * break room to peak at 0.79.- * 4. Edge gloss was an area-weighted error: a whole material polished- * by 0.35 * strength for wear that covers a fraction of it. 0.12.- */--import {- patchStandard, glslAxes, glslCurv, glslTriNoise, seedVec3,- toColor, unit, worldBase,-} from './shader.js';--// Both patches read the same two fields, so they are built once. A-// planar UV would smear either of them into vertical streaks on a wall,-// and these patches land on walls.-const WEAR_HEAD = [- glslAxes('astraWearAxes'),- glslTriNoise('astraWearNoise', 13.7, 41.3, 71.9),- glslCurv('astraWearCurv'),-].join('\n');--// On the world varyings terrain_shade and waterside share, so a material-// wearing a splat, a waterline and wear declares ONE pair; the locals-// are prefixed wr because those two vertex bodies own astraWp and wsP.-const BASE = worldBase('wear:base', 'wrP', 'wrN', WEAR_HEAD);--const seedOffset = (seed) => seedVec3(seed, 0.17, 3.71, 7.13, 64);--/**- * Break up the flat, even surface that reads as moulded plastic.- *- * A built-in material paints one exact colour over a whole object and- * nothing photographed is one exact colour — that evenness is most of- * what "CG" means, and it costs one patch on every material to lose.- * This lays a faint world-space variation over the albedo: a slow- * blotch at `scale`, a mid field at half of it, a grain at a quarter,- * and a warm/cool break so it is a change of MATERIAL rather than a- * brightness dial. Every field is projected on the three world axes and- * blended by the world normal, so a wall gets grain instead of vertical- * streaks and two objects sharing a scale share a surface.- *- * Keep it under the threshold of "what is that": the test of a good- * breakup is that it cannot be named in a still, only missed when it is- * taken away. Past ~0.2 `strength` it stops being texture and reads as- * dirt, and the grain fades itself out once a pixel spans a cycle of it- * — beyond that it is no longer texture but static, which is the one- * way this reads as an effect rather than as a surface.- *- * Roughness follows the seeded breakup per pixel, breaking uniform- * highlights without changing the material's authored base roughness.- *- * @param {THREE.Material} material A built-in material, patched in- * place — a shared material from `materials.js` patches every mesh- * wearing it, so clone it first if that is not what you want.- * @param {object} [opts] `scale` metres per cycle of the blotch- * (default 0.6); `strength` peak albedo swing either way, 0..1- * (default 0.10); `hue` the warm/cool break, as a fraction of the- * albedo either way (default 0.15 — NOT radians, see the port note;- * it is the peak, and the field reaches about 0.6 of it, which puts- * the typical swing on `astraHueBreak`'s own calibrated stone number);- * `seed` decorrelates two materials and picks the roughness detune- * (default 1).- * @returns {THREE.Material} The same material. Its uniforms stay live- * on `material.userData.uniforms` for a scene that wants to retune- * them.- */-export function patchMicroBreakup(material, opts = {}) {- const scale = opts.scale === undefined ? 0.6 : opts.scale;- const strength = opts.strength === undefined ? 0.10 : opts.strength;- const hue = opts.hue === undefined ? 0.15 : opts.hue;- const seed = opts.seed === undefined ? 1 : opts.seed;- patchStandard(material, BASE);- return patchStandard(material, {- name: 'wear:micro',- uniforms: {- uMicroScale: { value: Math.max(1e-3, scale) },- uMicroAmt: { value: unit(strength) },- uMicroHue: { value: hue },- uMicroSeed: { value: seedOffset(seed) },- },- fragmentHead: [- 'uniform float uMicroScale;',- 'uniform float uMicroAmt;',- 'uniform float uMicroHue;',- 'uniform vec3 uMicroSeed;',- ].join('\n'),- fragmentBody: [- ' vec3 mbW = astraWearAxes(normalize(vAstraWorldN));',- ' vec3 mbP = vAstraWorld / uMicroScale + uMicroSeed;',- ' float mbLo = astraWearNoise(mbP, mbW);',- ' float mbMi = astraWearNoise(mbP * 2.03, mbW);',- ' float mbHi = astraWearNoise(mbP * 4.1, mbW);',- // Each field is dropped once a pixel spans most of a cycle of it:- // past that it is no longer texture, it is static, and static is- // the one way this reads as an effect. Two octaves need two- // fades, or the mid one aliases across a floor at grazing angle- // while the fine one is already gone.- ' float mbFw = length(fwidth(mbP));',- // Filter each field toward its mean BEFORE either brightness or- // hue reads it. Filtering only brightness left coloured static at- // grazing angles, and even the coarsest octave aliases far away.- ' mbLo = mix(0.5, mbLo, 1.0 - smoothstep(0.35, 1.00, mbFw));',- ' mbMi = mix(0.5, mbMi, 1.0 - smoothstep(0.35, 1.00, mbFw * 2.03));',- ' mbHi = mix(0.5, mbHi, 1.0 - smoothstep(0.35, 1.00, mbFw * 4.1));',- // Value noise clusters around 0.5, so it is centred and stretched- // to reach the strength asked for; three octaves rather than two- // because a surface with one blotch size and one grain size is- // still a pattern, and the clamp keeps `strength` a hard bound- // however they stack.- ' float mbV = clamp((mbLo - 0.5) * 2.4',- ' + (mbMi - 0.5) * 1.5',- ' + (mbHi - 0.5) * 1.6, -1.0, 1.0);',- // WARM/COOL, not a hue rotation: rotating about the grey axis- // leaves a neutral exactly unchanged, and stone, plaster and- // concrete are most of what this rides on. Warm where the sun has- // dried and bleached it, cool where only the sky reaches. It- // rides the DIFFERENCE of two fields, which is not the brightness- // field again.- ' float mbT = clamp((mbLo - mbHi) * 2.2, -1.0, 1.0) * uMicroHue;',- ' diffuseColor.rgb *= vec3(1.0 + mbT, 1.0 + mbT * 0.15,',- ' 1.0 - mbT);',- // The dark half of the field is dust and grime, and dust is- // greyer than what it settles on: saturation varies with it, so- // the patch is a change of material and not one brightness dial.- ' float mbL = dot(diffuseColor.rgb, vec3(0.2126, 0.7152, 0.0722));',- ' diffuseColor.rgb = mix(diffuseColor.rgb, vec3(mbL),',- ' max(-mbV, 0.0) * uMicroAmt * 0.6);',- ' diffuseColor.rgb *= 1.0 + mbV * uMicroAmt;',- ].join('\n'),- roughnessBody: 'roughnessFactor = clamp(roughnessFactor * (1.0 - mbV * uMicroAmt * 0.5), 0.04, 1.0);',- });-}--/**- * Lighten the convex edges, where hands and weather take the finish off.- *- * Paint wears off what sticks out. An object whose edges match its- * faces exactly has never been touched, and giving the edges back their- * lighter, harder-worn tone is the second thing (after breaking the- * flat colour) that moves a surface from moulded to used.- *- * EDGE ROUTE — the world normal's screen-space DERIVATIVE divided by- * the world-space length of that same pixel step. The ratio is the- * surface's curvature in 1/m, which is the one edge estimate a fragment- * can compute: it holds still under distance and resolution (a raw- * `fwidth(normal)` would draw a fixed-pixel-width line that thickens as- * the camera pulls back), and it is SIGNED, so a concave corner — where- * dirt collects rather than wear — is left alone.- *- * It reads ZERO across a hard, unwelded edge (`BoxGeometry`'s corners,- * anything flat-shaded): derivatives never cross a primitive, so both- * faces see a constant normal right up to the seam. That is also why- * this can never flicker into a wireframe. Bevel or smooth-shade the- * edges you want worn; rounded geometry wears where it curves tightest.- *- * Gloss follows the same wear mask: polished edges leave unworn paint- * at its authored roughness.- *- * @param {THREE.Material} material A built-in material, patched in- * place — a shared material patches every mesh wearing it.- * The worn area is not one flat colour. Light wear is the paint itself- * rubbed thin — the surface's OWN tone, lightened and desaturated,- * which is what keeps the wear belonging to the object it is on — and- * only the hardest-hit part goes through to `color`, which is itself- * broken up in value and in warm/cool. A single flat tone painted over- * every material in a scene is the thing this patch exists to undo.- *- * @param {object} [opts] `strength` how far the edge goes toward- * `color`, 0..1 (default 0.35); `color` THREE.Color or hex, the bare- * substrate under the finish (default a warm bone); `width` the- * feature RADIUS in metres- * where wear BEGINS, reaching full at a third of it (default 0.35 —- * a 12 cm rim wears through, a 2 m barrel is untouched); `seed`- * moves the patchy break-up (default 1).- * @returns {THREE.Material} The same material, with its uniforms live- * on `material.userData.uniforms`.- */-export function patchEdgeWear(material, opts = {}) {- const strength = opts.strength === undefined ? 0.35 : opts.strength;- const width = opts.width === undefined ? 0.35 : opts.width;- const seed = opts.seed === undefined ? 1 : opts.seed;- patchStandard(material, BASE);- return patchStandard(material, {- name: 'wear:edge',- uniforms: {- uEdgeAmt: { value: unit(strength) },- uEdgeColor: { value: toColor(opts.color, 0xd2cabb) },- uEdgeWidth: { value: Math.max(1e-3, width) },- uEdgeSeed: { value: seedOffset(seed + 0.5) },- },- fragmentHead: [- 'uniform float uEdgeAmt;',- 'uniform vec3 uEdgeColor;',- 'uniform float uEdgeWidth;',- 'uniform vec3 uEdgeSeed;',- ].join('\n'),- fragmentBody: [- ' vec3 ewN = normalize(vAstraWorldN);',- // Curvature in 1/m: how far the normal turns per metre the- // surface travels under one pixel. Positive is convex, and only- // the convex half wears.- ' float ewC = astraWearCurv(ewN, vAstraWorld);',- ' float ewR = 1.0 / uEdgeWidth;',- ' float ewK = smoothstep(ewR, ewR * 3.0, ewC);',- // Rubbing is patchy and FINE, at TWO scales. The ramp above is- // saturated everywhere on anything much tighter than `width` — a- // 6 cm rail post is 1.0 over every pixel — so a single blotch- // field is the only structure left there, and a 14 cm blotch on a- // 12 cm object is a barber pole, not wear. The second octave is- // the chipping inside each patch; both are tied to the width- // asked for, so the pattern scales with the feature and a- // re-render at another distance is the same surface.- ' vec3 ewAx = astraWearAxes(ewN);',- ' vec3 ewQ = vAstraWorld * (ewR * 3.4) + uEdgeSeed;',- ' float ewP = astraWearNoise(ewQ, ewAx);',- ' float ewF = astraWearNoise(ewQ * 3.3 + 11.3, ewAx);',- ' float ewG = 1.0 - smoothstep(0.35, 1.00,',- ' length(fwidth(ewQ)) * 3.3);',- ' ewK *= smoothstep(0.36, 0.72, ewP + (ewF - 0.5) * ewG);',- // Thinned finish first, bare substrate only where it is worn- // through: the light half keeps the object's OWN hue (lightened- // and desaturated), and the substrate carries its own value and- // warm/cool spread, so no two worn patches are the same colour.- ' float ewL = dot(diffuseColor.rgb, vec3(0.2126, 0.7152, 0.0722));',- ' vec3 ewThin = mix(diffuseColor.rgb, vec3(ewL), 0.45) * 1.16;',- ' float ewT = (ewF - 0.5) * ewG * 0.24;',- ' vec3 ewBare = uEdgeColor * (0.86 + 0.24 * ewP)',- ' * vec3(1.0 + ewT, 1.0 + ewT * 0.15, 1.0 - ewT);',- ' vec3 ewTone = mix(ewThin, ewBare, smoothstep(0.35, 0.90, ewK));',- ' diffuseColor.rgb = mix(diffuseColor.rgb, ewTone,',- ' clamp(ewK * uEdgeAmt, 0.0, 1.0));',- ].join('\n'),- roughnessBody: 'roughnessFactor = mix(roughnessFactor, max(0.06, roughnessFactor * 0.58), clamp(ewK * uEdgeAmt, 0.0, 1.0));',- });-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/terrain_shade.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/terrain_shade.jsdeleted file mode 100644index c786e98f..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/terrain_shade.js+++ /dev/null@@ -1,366 +0,0 @@-/**- * Terrain surfaces that read as rock, not as stretched wallpaper.- *- * Both patches here shade from the SURFACE — world position and world- * normal — so neither needs a UV and the ground and the cliff from- * `terrain.js` can wear one look at any angle. Each is a `patchStandard`- * on a material you already built, so the built-in's lighting, shadows,- * fog and depth chunks stay exactly as they were.- */--import { patchStandard, toColor, worldBase } from './shader.js';--// The whole interface between the stages: the world varyings every-// library shares, written once by this base.-const WORLD = worldBase('terrain:world', 'astraWp', 'astraWn');--// astraFbm2 sums 0.5, 0.25, ... so its top end moves with the octave-// count; rescaled to 0..1, one mix factor means the same at any count.-const FBM_UNIT = [- '#ifndef ASTRA_FBM_UNIT',- '#define ASTRA_FBM_UNIT',- 'float astraFbmUnit(vec2 p, int oct) {',- ' float footprint = max(length(dFdx(p)), length(dFdy(p)));',- ' float sum = 0.0, weight = 0.0, amplitude = 0.5, frequency = 1.0;',- ' for (int i = 0; i < 6; i++) {',- ' if (i >= oct) break;',- ' float resolved = 1.0 - smoothstep(0.25, 0.85, footprint * frequency);',- ' sum += amplitude * mix(0.5, astraNoise2(p * frequency), resolved);',- ' weight += amplitude; amplitude *= 0.5; frequency *= 2.0;',- ' }',- ' return clamp(sum / max(weight, 0.25), 0.0, 1.0);',- '}',- '#endif',-].join('\n');--// MINERAL colour, and the reason both patches stopped looking like-// putty.-//-// `astraHueBreak` at one scale is a TINT, not a grain: its field is a-// 2-octave fbm, so at the ~3 m wavelength the two bodies below used to-// ask for, anything boulder-sized lands whole inside a single lobe.-// Measured on this library's showcase before this block: a 1 m boulder-// came out R-B = -32 (cold slate) against the unpatched dirt beside it-// at +21, saturation 0.06-0.09, and a hue spread of 0.02-0.03 across a-// whole region — one flat cold value, which is the exact defect the-// palette probe names.-//-// So: TWO scales — patch-sized over hand-sized — and a mean pulled-// warm. Rock in daylight is never cooler than the ground beside it;-// the cool half of the swing only happens where the sky alone reaches,-// and the LIGHT does that for free. The ochre term rides the same-// world field the mesh does, so the warm patches sit on the surface-// rather than on a screen grid.-const GRAIN = [- '#ifndef ASTRA_TERRAIN_GRAIN',- '#define ASTRA_TERRAIN_GRAIN',- 'vec3 astraTerrainGrain(vec3 c, vec3 wp, float swing) {',- // astraHueBreak's own swing is a HALF-amplitude of 0.375 * swing, so- // splitting one 0.34 call into two smaller ones lost amplitude- // instead of gaining structure: the first attempt moved rendered- // saturation by 0.00-0.03 and was invisible. Both scales run at or- // above the original swing; the two fields are decorrelated, so they- // stack to mineral movement rather than to one louder tint.- ' vec3 g = astraHueBreak(c, wp.xz + wp.y * 0.55, 0.40, swing * 0.80);',- ' g = astraHueBreak(g, wp.zx + wp.y * 0.9 + 27.3, 2.4, swing * 1.15);',- ' float w = clamp(astraFbmUnit(wp.xz * 0.85 + wp.y * 0.35 + 5.1, 3)',- ' * 1.25 - 0.12, 0.0, 1.0);',- ' return g * mix(vec3(0.92, 0.96, 1.04), vec3(1.21, 1.05, 0.84), w);',- '}',- '#endif',-].join('\n');--const TRI_HEAD = [- 'uniform vec3 uTriA;',- 'uniform vec3 uTriB;',- 'uniform float uTriScale;',- 'uniform float uTriSharp;',- 'uniform int uTriOct;',- 'uniform float uTriRelief, uTriRoughness;',- 'vec3 astraTriWeights(vec3 n, float sharp) {',- ' vec3 w = pow(abs(n), vec3(sharp));',- ' return w / max(w.x + w.y + w.z, 1e-4);',- '}',-].join('\n');--const TRI_BODY = [- ' vec3 tpW = astraTriWeights(normalize(vAstraWorldN), uTriSharp);',- ' vec3 tpP = vAstraWorld / uTriScale;',- // One noise read on three planes mirrors itself across the diagonals- // and the seam shows as a crease; the offsets decorrelate them.- ' float tpN = astraFbmUnit(tpP.yz + 11.3, uTriOct) * tpW.x',- ' + astraFbmUnit(tpP.zx + 41.7, uTriOct) * tpW.y',- ' + astraFbmUnit(tpP.xy + 71.1, uTriOct) * tpW.z;',- // Kept in a local the SPLAT can read: patch bodies are- // concatenated into one main(), and a splat that simply- // assigned over this erased the whole triplanar.- ' vec3 tpC = mix(uTriA, uTriB, clamp(tpN, 0.0, 1.0));',- // MASS-scale value, and the up-face wash. A cliff is light and dark- // ROCK; rain bleaches the ledges pale and leaves the sheltered- // undersides dark. Without these two the whole wall is one tone- // dithered — measured at luminance sigma 0.023 across a 13 m face.- // Kept in `tpV` so a SPLAT landing on top can carry the same- // structure instead of flattening it back out.- ' float tpM = astraFbmUnit(tpP.xz * 0.21 + 3.3, 3);',- ' float tpU = normalize(vAstraWorldN).y * 0.5 + 0.5;',- ' float tpV = mix(0.80, 1.15, tpM) * mix(0.84, 1.10, tpU);',- ' tpC *= tpV;',- // Rock is never one colour at arm's length: a granite face runs pink,- // grey and near-black across a metre, and the palette probe named- // exactly this surface "one flat hue".- ' tpC = astraTerrainGrain(tpC, vAstraWorld, 0.42);',- ' diffuseColor.rgb = tpC;',- ' float tpHeight = (tpN - 0.5) * uTriRelief;',-].join('\n');--const SPLAT_HEAD = [- 'uniform vec3 uSplatGrass;',- 'uniform vec3 uSplatScree;',- 'uniform vec3 uSplatRock;',- 'uniform vec3 uSplatSnow;',- 'uniform float uSplatLow;',- 'uniform float uSplatHigh;',- 'uniform float uSplatBlend;',- 'uniform float uSplatSnowY;',- 'uniform float uSplatSnowBand;',- 'uniform vec4 uSplatRoughness;',-].join('\n');--const SPLAT_CORE = [- ' vec3 spN = normalize(vAstraWorldN);',- // A threshold on normal.y alone draws a contour line no hillside has;- // ~12 m of noise wanders it onto the rock itself.- ' float spJit = (astraFbmUnit(vAstraWorld.xz * 0.08, 3) - 0.5) * 0.16;',- // 12 m of wander still draws a SMOOTH edge across anything- // boulder-sized: the grass cap on a 1 m rock came out a lime sticker- // with a clean rim (measured saturation 0.39 against 0.06 for the- // rock under it). A hand-scale term breaks that rim into speckle.- ' float spFine = (astraFbmUnit(vAstraWorld.xz * 1.6',- ' + vAstraWorld.y * 0.9 + 4.7, 4) - 0.5) * 0.11;',- ' float spUp = clamp(spN.y + spJit + spFine, 0.0, 1.0);',- ' float spB = max(uSplatBlend, 1e-3);',- ' float spG = smoothstep(uSplatLow - spB, uSplatLow + spB, spUp);',- ' float spR = 1.0 - smoothstep(uSplatHigh - spB, uSplatHigh + spB, spUp);',- ' vec3 spC = mix(mix(uSplatScree, uSplatRock, spR), uSplatGrass, spG);',- // The zone tones are three near-neutral greys and a green; three- // greys blended by a slope ramp is a flat card whatever the ramp.- // BEFORE the snow, so a partly covered slope still shows the rock's- // own mineral colour through the drifts.- ' spC = astraTerrainGrain(spC, vAstraWorld, 0.45);',- // MASS scale, ~4.5 m: a hillside is light and dark ground before it- // is any of these zones, and without it the only value variation was- // a 1.6 m dither that averages out at any distance (measured modal- // luminance 0.93 over a whole crag, down to 0.86 with this line).- ' float spMass = astraFbmUnit(vAstraWorld.xz * 0.22',- ' + vAstraWorld.y * 0.09 + 17.9, 3);',- ' spC *= mix(0.80, 1.18, spMass);',- // Snow lies only where the slope can hold it, so the same two knobs- // gate it and the steepest faces stay bare rock above the line.- ' float spHold = smoothstep(uSplatHigh, uSplatLow, spUp);',- ' float spSnow = smoothstep(uSplatSnowY - uSplatSnowBand,',- ' uSplatSnowY + uSplatSnowBand,',- ' vAstraWorld.y + spJit * uSplatSnowBand * 2.8);',- // Snow is not a white card. Wind packs it into drifts and SCOURS- // bare patches, so the same field has to move the COVERAGE, not just- // tint the white: a smooth ramp painted the whole cap one value- // (measured hue spread 0.003 and luminance sigma 0.018 over an entire- // peak, a dead frozen frame). Tinting the snow alone did not shift- // either number; letting rock show through does.- // The hue break is a TENTH of the rock's — snow that swings hue looks- // like ice cream — because the cold-shade / warm-sun split of real- // snow is the LIGHT's job, not the albedo's.- ' float spDrift = astraFbmUnit(vAstraWorld.xz * 1.15',- ' + vAstraWorld.y * 0.5 + 8.3, 4);',- ' vec3 spSnowC = astraHueBreak(uSplatSnow * mix(0.84, 1.06, spDrift),',- ' vAstraWorld.xz, 1.4, 0.09);',- ' float spCov = clamp(spSnow * spHold * mix(0.45, 1.45, spDrift),',- ' 0.0, 1.0);',- ' spC = mix(spC, spSnowC, spCov);',- ' float spVar = astraFbmUnit(vAstraWorld.xz * 0.6, 3);',-].join('\n');--// The last line, and its only variant. A `.replace` on the assembled-// body was silent when it missed — and a missed replace here is-// exactly the bug the composition comment below describes.-const SPLAT_TAIL = ' diffuseColor.rgb = spC * mix(0.86, 1.14, spVar);';--// Applied over a triplanar, the zone colour must carry that grain-// rather than replace it: the two are a colour and a variation, not-// two colours. `tpV` brings the triplanar's mass-scale value and-// up-face wash through as well, at half strength — without it the-// splat flattened the cliff structure the triplanar had just built.-const SPLAT_TAIL_OVER_TRI =- ' diffuseColor.rgb = spC * mix(0.86, 1.14, spVar)'- + ' * mix(0.88, 1.12, clamp(tpN, 0.0, 1.0)) * mix(1.0, tpV, 0.5);';--const SPLAT_BODY = [SPLAT_CORE, SPLAT_TAIL].join('\n');-const SPLAT_BODY_OVER_TRI = [SPLAT_CORE, SPLAT_TAIL_OVER_TRI].join('\n');--// Metres. Far above any authored terrain, yet small enough that the-// +/-5 m snow band survives float32 (at 1e9 it would collapse to NaN).-const SNOW_OFF = 1e6;--/** Clamp to the 1..6 astraFbm2 actually loops over. */-function toOctaves(value) {- return Math.max(1, Math.min(6, Math.round(value)));-}--/**- * The world position and normal both patches shade from, applied once.- *- * Named, so a material wearing both patches gets one copy: two copies- * declared the same locals and redefined the same helper, and the- * material was dead — verified on the GPU by a sibling library that- * landed on the same bank material.- */-function withWorld(material) {- return patchStandard(material, WORLD);-}---/**- * Project a procedural rock surface on the world axes — no UVs at all.- *- * A planar UV smears every steep face (the ground's own UV stretches to- * a vertical streak on a cliff), so this blends three world-axis noise- * projections by the world normal instead: a face at ANY angle gets the- * projection it faces most, and geometry that shares a scale shares a- * look with no UV to author. Replaces the base color and mineral finish;- * existing normal maps remain underneath the filtered metric relief.- *- * @param {THREE.Material} material A built-in material, patched in place.- * @param {object} [opts] `scale` world metres per repeat (default 2);- * `sharpness` blend exponent, higher = harder plane transitions- * (default 4); `colorA`/`colorB` THREE.Color or hex, the low and high- * ends of the noise; `noiseOctaves` detail levels 1..6 (default 4);- * `relief` surface-gradient height in metres (default .002, zero disables),- * `roughness` mineral finish (default .86). Geometry is not displaced.- * `name` the program cache key (default 'terrain:triplanar' — every- * patch KIND needs its own, or three's per-type program cache serves- * one compiled program to both and the second never runs).- * @returns {THREE.Material} The same material. Its uniforms stay live on- * `material.userData.uniforms` for a scene that wants to retune them.- */-export function patchTriplanar(material, opts = {}) {- const scale = opts.scale === undefined ? 2 : opts.scale;- const sharpness = opts.sharpness === undefined ? 4 : opts.sharpness;- const oct = opts.noiseOctaves === undefined ? 4 : opts.noiseOctaves;- withWorld(material);- material.userData.astraTriplanar = true;- return patchStandard(material, {- name: opts.name || 'terrain:triplanar',- uniforms: {- // HUE-SEPARATED, not two values of one hue. The old pair sat at- // 33 and 37 degrees, so the three-plane noise produced a value- // ramp and nothing else — the grain had no colour to move- // between. A shaded grey-pink at 12 degrees under a buff ochre- // at 42 gives the mix 30 degrees to travel, which is what a- // weathered rock face actually does.- uTriA: { value: toColor(opts.colorA, 0x6d5952) },- uTriB: { value: toColor(opts.colorB, 0xab9670) },- uTriScale: { value: Math.max(1e-3, scale) },- uTriSharp: { value: Math.max(1, sharpness) },- uTriOct: { value: toOctaves(oct) },- uTriRelief: { value: Math.max(0, opts.relief ?? 0.002) },- uTriRoughness: { value: Math.max(0, Math.min(1, opts.roughness ?? 0.86)) },- },- fragmentHead: [FBM_UNIT, GRAIN, TRI_HEAD].join('\n'),- fragmentBody: TRI_BODY,- roughnessBody: 'roughnessFactor = clamp(uTriRoughness + (tpN - 0.5) * 0.10, 0.04, 1.0);',- metalnessBody: 'metalnessFactor = 0.0;',- normalBody: 'normal = astraBump(-vViewPosition, normal, tpHeight);',- });-}--/**- * Choose the surface by SLOPE first and height second.- *- * Colouring terrain by height alone paints a cliff the same as the- * meadow beside it at the same altitude; what the eye reads is that- * nothing grows on a steep face. So grass takes the flats, scree the- * mid slopes, bare rock the steepest, and snow lands above `snowLine`- * ONLY where the slope can hold it — the steep faces stay bare rock- * through the snow line, which is what makes a peak read as a peak.- * Every boundary is noise-wandered, since a clean contour reads as a- * decal.- *- * @param {THREE.Material} material A built-in material, patched in place.- * @param {object} [opts] `grass`/`scree`/`rock`/`snow` THREE.Color or- * hex; `snowLine` metres of world Y (default Infinity = no snow);- * `snowBand` half-width of the snow transition in metres (default 5 —- * right for a mountain, and far too wide for anything smaller: at the- * default a 9 m spire is snow-hazed from base to tip instead of- * capped, so a boulder field or a 10 m crag wants 1..2);- * `slopeLow`/`slopeHigh` the normal.y that ends the flats and begins- * the bare rock (default 0.75/0.45 — slopeLow is the GENTLER slope, so- * it is the LARGER normal.y, and the pair is ordered here because a- * GLSL smoothstep with its edges inverted is undefined); `blend`- * half-width of both slope transitions in normal.y (default 0.08);- * `roughness` optional {grass, scree, rock, snow} finish values (defaults- * .94/.9/.8/.92). All zones are dielectric; prior normal maps remain.- * `name` the program cache key (default 'terrain:slopeSplat').- * @returns {THREE.Material} The same material. Its uniforms stay live on- * `material.userData.uniforms`, so `uSplatSnowY` can be animated.- */-export function patchSlopeSplat(material, opts = {}) {- const low = opts.slopeLow === undefined ? 0.75 : opts.slopeLow;- const high = opts.slopeHigh === undefined ? 0.45 : opts.slopeHigh;- const blend = opts.blend === undefined ? 0.08 : opts.blend;- const line = opts.snowLine;- const band = opts.snowBand === undefined ? 5 : opts.snowBand;- withWorld(material);- // The two are a colour and a variation. Whichever lands second- // used to assign straight over the first, so on the terrain the- // prompts recommend — both — one of them was always invisible.- // A MARK, not a name: patchTriplanar invites a custom `name`, and- // detecting by name sent the splat straight back to assigning over- // it the moment anyone used that option.- const overTri = material.userData.astraTriplanar === true;- return patchStandard(material, {- name: opts.name || (overTri ? 'terrain:slopeSplat+tri'- : 'terrain:slopeSplat'),- uniforms: {- // The zones read as MATERIALS, not as one grey at four- // brightnesses: bare rock is the darkest AND the most saturated- // (fresh, wet, lichened), scree is pale and dusty and nearly- // neutral, grass is a dry olive rather than the lime the old- // 0x55703a made of a boulder cap (saturation 0.48 -> 0.38).- uSplatGrass: { value: toColor(opts.grass, 0x5f6b42) },- uSplatScree: { value: toColor(opts.scree, 0xa08e73) },- uSplatRock: { value: toColor(opts.rock, 0x6e5844) },- // Snow albedo, not snow LIGHT: 0xeef2f6 is 0.93-0.97 linear, over- // the 0.8 an unlit dielectric may hold, and it left the cap a- // dead flat card (hue spread 0.005 across a whole peak). The sun- // is what makes snow white; a neutral 0.79 keeps the highlight- // room ACES needs and lets the drift break show.- uSplatSnow: { value: toColor(opts.snow, 0xcbc9c4) },- uSplatLow: { value: Math.max(low, high) },- // Equal slope thresholds otherwise make the snow-holding smoothstep- // divide by zero, even though the grass/rock ramps still have a blend.- uSplatHigh: { value: Math.min(low, high, Math.max(low, high) - 1e-4) },- uSplatBlend: { value: Math.max(1e-3, blend) },- uSplatSnowY: { value: Number.isFinite(line) ? line : SNOW_OFF },- // A band that cannot RESOLVE against the off-sentinel makes a- // smoothstep with equal edges: 0/0, NaN, and a black terrain.- // float32 steps by 0.125 m at 1e6, so the OFF case floors the- // band at a metre; with a real snow line any positive band works.- uSplatSnowBand: {- value: Number.isFinite(line)- ? Math.max(1e-2, band) : Math.max(1, band),- },- uSplatRoughness: { value: [- opts.roughness?.grass ?? 0.94, opts.roughness?.scree ?? 0.9,- opts.roughness?.rock ?? 0.8, opts.roughness?.snow ?? 0.92,- ].map(value => Math.max(0, Math.min(1, value))) },- },- fragmentHead: [FBM_UNIT, GRAIN, SPLAT_HEAD].join('\n'),- fragmentBody: overTri ? SPLAT_BODY_OVER_TRI : SPLAT_BODY,- roughnessBody: [- 'float spRough = mix(mix(uSplatRoughness.y, uSplatRoughness.z, spR),',- ' uSplatRoughness.x, spG);',- 'roughnessFactor = clamp(mix(spRough, uSplatRoughness.w, spCov)',- ' + (spFine * 0.3 + spMass * 0.02 - 0.01) * (1.0 - spCov), 0.04, 1.0);',- ].join('\n'),- metalnessBody: 'metalnessFactor = 0.0;',- });-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/urban.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/urban.jsdeleted file mode 100644index 650bcfae..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/urban.js+++ /dev/null@@ -1,1082 +0,0 @@-/**- * The three things that say CITY rather than a row of boxes: a glazed- * facade, the cables strung over the street, and the hoarding on the- * gable end.- *- * Each replaces a specific cheat. A curtain wall drawn as one shiny- * material is one mirror sheet — real glazing is a grid of separately- * hung panels, each at its own angle and tint, and what it shows- * depends on where you stand: the sky at grazing angles, the room- * head-on. Power lines drawn as straight tubes are a truss; a hanging- * cable is a CATENARY and the eye knows the difference. And a- * billboard without its structure is a floating decal.- *- * COST CONTRACT: `patchCurtainWall` spends NO render target. The scene- * has exactly one (an ocean's reflection),- * and a facade is never what should spend it — see the patch's own JSDoc for what it does instead.- */--import { attachDisposal, snapshotResources } from './lifecycle.js';-import * as THREE from 'three';-import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';--import { patchNeonSpill } from './neon.js';-import { fbm2, mulberry32, noiseDataTexture } from './noise.js';-import {- keepOutOfDepthPasses, makeShaderMaterial,- patchStandard, readVec3, seedLattice, tickShaders, toColor, unit,-} from './shader.js';--const _UP = new THREE.Vector3(0, 1, 0);--const seedOffset = (seed) => seedLattice(seed) * 0.0517;--/** Read a `[w, h]`, `{w, h}` or single number as a metric pair. */-function toPair(value, dw, dh) {- if (value === undefined || value === null) return [dw, dh];- if (Array.isArray(value)) {- return [Math.max(1e-3, value[0] || dw),- Math.max(1e-3, value[1] === undefined ? dh : value[1])];- }- if (typeof value === 'number') return [Math.max(1e-3, value), value];- return [Math.max(1e-3, value.w === undefined ? dw : value.w),- Math.max(1e-3, value.h === undefined ? dh : value.h)];-}---// ---------------------------------------------------------------- glass--const CW_VARYINGS = [- 'varying vec3 vCwW;',- 'varying vec3 vCwN;',-].join('\n');--// `transformed` is still object-space at <begin_vertex>, so an-// instanced skyline needs instanceMatrix folded in by hand.-const CW_VERTEX = [- ' vec4 cwP = vec4(transformed, 1.0);',- ' vec3 cwNo = normal;',- '#ifdef USE_INSTANCING',- ' cwP = instanceMatrix * cwP;',- ' cwNo = astraNormalTransform(mat3(instanceMatrix), cwNo);',- '#endif',- ' vCwW = (modelMatrix * cwP).xyz;',- ' vCwN = astraNormalTransform(mat3(modelMatrix), cwNo);',-].join('\n');--const CW_HEAD = [- 'uniform vec2 uCwPanel;',- 'uniform vec3 uCwTint;',- 'uniform vec3 uCwMetal;',- 'uniform vec3 uCwSky;',- 'uniform vec3 uCwHaze;',- 'uniform vec3 uCwGround;',- 'uniform vec3 uCwBlindCol;',- 'uniform float uCwMullion;',- 'uniform float uCwReflect;',- 'uniform float uCwBow;',- 'uniform float uCwBlinds;',- 'uniform float uCwCurve;',- 'uniform float uCwSeed;',- 'uniform float uCwGain;',- 'uniform float uCwCoat;',- // Schlick, with the head-on term the COATING sets rather than glass's- // own 4% — untinted glass at 4% renders as a black hole, and the- // grazing limit is 1 for any coating, which is the whole effect.- 'float astraCwFresnel(float ndv, float f0) {',- ' float c = clamp(1.0 - clamp(ndv, 0.0, 1.0), 0.0, 1.0);',- ' float c2 = c * c;',- ' return f0 + (1.0 - f0) * c2 * c2 * c;',- '}',- // One key per panel, built from astraHash11 of a linear combination- // so the same numbers can be read on the CPU.- 'float astraCwKey(float ix, float iy) {',- ' return astraHash11(ix * 1.0731 + iy * 7.3313 + 0.317);',- '}',- 'float astraCwJit(float key, float k) {',- ' return astraHash11(key * 19.73 + k * 3.117 + 0.611);',- '}',-].join('\n');--const CW_BODY = [- ' vec3 cwN = normalize(vCwN);',- ' vec3 cwV = normalize(cameraPosition - vCwW);',- // dot(p.xz, t) is EXACT arc length along a flat face at any- // orientation and 0 round a tower, where the azimuth term carries it- // instead; a facade needs a METRIC grid, never a UV one.- ' vec2 cwTz = vec2(-cwN.z, cwN.x);',- ' float cwTl = length(cwTz);',- ' float cwFace = smoothstep(0.20, 0.55, cwTl);',- ' vec2 cwT = cwTl > 1e-4 ? cwTz / cwTl : vec2(1.0, 0.0);',- ' float cwU = dot(vCwW.xz, cwT) + uCwCurve * atan(cwN.z, cwN.x);',- ' vec2 cwG = vec2(cwU, vCwW.y) / uCwPanel;',- ' vec2 cwAa = fwidth(cwG);',- ' vec2 cwId = floor(cwG);',- ' float cwKey = astraCwKey(cwId.x + uCwSeed, cwId.y - uCwSeed);',- // Per-panel detail is texture until a pixel spans a panel and static- // after it, so every panel-scale term fades to its mean exactly there.- ' float cwSharp = 1.0 - smoothstep(0.30, 0.85, max(cwAa.x, cwAa.y));',- ' float cwMull = max(astraStroke(cwG.x, uCwMullion * 0.5 / uCwPanel.x),',- ' astraStroke(cwG.y, uCwMullion * 0.5 / uCwPanel.y));',- ' cwMull *= cwFace;',- // Every panel hangs at its own angle. Without this the whole wall- // shares one reflected ray and reads as a single mirror sheet.- ' vec3 cwTan = vec3(cwT.x, 0.0, cwT.y);',- ' vec3 cwBi = cross(cwN, cwTan);',- ' float cwB1 = (astraCwJit(cwKey, 1.0) - 0.5) * 2.0 * uCwBow * cwSharp;',- ' float cwB2 = (astraCwJit(cwKey, 2.0) - 0.5) * 2.0 * uCwBow * cwSharp;',- ' vec3 cwPn = normalize(cwN + cwTan * cwB1 + cwBi * cwB2);',- ' float cwF0 = uCwReflect * mix(0.82, 1.18,',- ' astraCwJit(cwKey, 3.0) * cwSharp + 0.5 * (1.0 - cwSharp));',- ' float cwFr = astraCwFresnel(dot(cwPn, cwV), clamp(cwF0, 0.0, 1.0));',- ' vec3 cwRay = reflect(-cwV, cwPn);',- ' vec3 cwRefl = mix(uCwGround, uCwHaze,',- ' smoothstep(-0.30, 0.01, cwRay.y));',- ' cwRefl = mix(cwRefl, uCwSky, smoothstep(0.0, 0.55, cwRay.y));',- // Glass FILTERS what is behind it — the room already in- // diffuseColor — and never replaces it; the tint is a hue, so a- // dark green glass does not black the interior out.- ' float cwTm = max(max(uCwTint.r, uCwTint.g), max(uCwTint.b, 1e-3));',- ' vec3 cwFilt = mix(vec3(1.0), uCwTint / cwTm, 0.85);',- // A coating reflects a TINTED image. Left untinted, a tower under a- // hazy sky returns the haze and reads as one grey sheet whatever the- // glass is — which is why real glazing reads green, bronze or blue- // from across the street and this did not.- ' cwRefl *= mix(vec3(1.0), uCwTint / cwTm, uCwCoat);',- // Coating batch varies unit to unit: brightness AND a warm/cool tilt,- // both fading to their mean when a pixel spans a panel. This is what- // stops a hundred panels sharing one colour.- ' float cwJb = astraCwJit(cwKey, 7.0) - 0.5;',- ' float cwJh = (astraCwJit(cwKey, 8.0) - 0.5) * cwSharp;',- ' cwRefl *= (1.0 + 0.26 * cwJb * cwSharp)',- ' * vec3(1.0 + 0.17 * cwJh, 1.0, 1.0 - 0.17 * cwJh);',- ' vec3 cwGl = diffuseColor.rgb * cwFilt;',- // A few panels have the blind down: the one thing that DOES hide the- // room, and the cheapest proof the panels are not one surface. It is- // an interior surface, so it is filtered by the same glass.- ' float cwBl = step(astraCwJit(cwKey, 4.0), uCwBlinds * cwSharp);',- ' float cwDrop = 0.30 + 0.50 * astraCwJit(cwKey, 5.0);',- ' float cwEdge = max(cwAa.y, 0.01);',- ' cwBl *= smoothstep(1.0 - cwDrop - cwEdge, 1.0 - cwDrop + cwEdge,',- ' fract(cwG.y));',- ' cwGl = mix(cwGl, uCwBlindCol * cwFilt',- ' * (0.26 + 0.22 * astraCwJit(cwKey, 6.0)), cwBl);',- ' float cwGlass = cwFace * (1.0 - cwMull);',- ' diffuseColor.rgb = mix(diffuseColor.rgb, cwGl, cwGlass);',- ' diffuseColor.rgb = mix(diffuseColor.rgb, uCwMetal, cwMull);',- // What the mirror TAKES out of the transmitted image, and what it- // returns: reflected radiance, which no albedo term can carry — a- // facade in shadow still mirrors the sky.- ' float cwRw = cwFr * cwGlass;',- ' diffuseColor.rgb *= 1.0 - 0.85 * cwRw;',- ' totalEmissiveRadiance += cwRefl * (cwRw * uCwGain);',-].join('\n');--/**- * Glaze a facade: mullion grid, fresnel sky, and panels that differ.- *- * A curtain wall shaded as one smooth material is one MIRROR SHEET, and- * that is the tell however good the reflection is. Real glazing is a- * grid of separately hung units: each panel sits at a slightly- * different angle, carries a slightly different tint and coating batch,- * and every fifth one has the blind down. This lays that grid on in- * world METRES (never UV — a facade merged from boxes carries a full- * 0..1 UV per box), varies it per panel, and reflects the sky through a- * Schlick fresnel so the tower shows the sky at grazing angles and its- * own interior head-on.- *- * NO RENDER TARGET, which is the constraint that shapes it. The scene- * gets ONE whole-scene reflection pass and a facade must never be what- * spends it: a Reflector re-renders the scene (+48 ms/frame- * measured). The other way out costs something this does not: an- * envMap material needs an equirect BAKE and hands three's IBL a- * roughness-blurred lookup that cannot show the per-panel break-up,- * and it does not show the room behind the glass. Here- * the reflection is an ANALYTIC sky evaluated per fragment from the- * reflected ray — no target, no texture, no bake. The honest trade: it- * reflects sky, haze and ground, never the building across the street.- * Pair it with an `envMap` when you want that; three's IBL runs- * underneath this untouched.- *- * It never assigns over `diffuseColor.rgb` — it FILTERS- * what is already there by the glass tint, dims it by what the mirror- * takes, and adds the reflection through `totalEmissiveRadiance`. So- * what is behind the glass stays visible head-on and is progressively- * replaced by sky toward grazing, which is what the eye reads as glass.- * It chains with `patchMicroBreakup`.- *- * @param {THREE.Material} material A lit built-in material (MeshStandard- * / MeshPhysical — the reflection needs `totalEmissiveRadiance`),- * patched in place. Clone a shared `materials.js` instance first.- * @param {object} [opts] `mullion` width of the aluminium member in- * metres (default 0.07); `panel` glazing unit size in metres, `[w, h]`- * / `{w, h}` / one number (default 1.5 x 3.6 — a floor-height unit);- * `tint` glass colour, used as a HUE the glass filters by (default- * 0x33556b); `reflect` head-on reflectance 0..1, the coating (default- * 0.22; 0.04 is uncoated glass, 0.45 a mirror-glass tower — the- * grazing limit is 1 whatever this is); `sky` / `haze` / `ground` what- * the reflected ray finds looking up, along the horizon and down- * (defaults a daylight sky; pass a night sky and the same glass reads- * as night); `bow` radians each panel may be off true (default 0.020,- * about a degree — 0 gives back the mirror sheet); `blinds` fraction- * of panels with the blind down (default 0.16); `curve` radius in- * `coat` how much of the glass tint the REFLECTED image carries, 0- * an uncoated pane that returns the sky's own colour to 1 a fully- * tinted mirror (default 0.45 — at 0 a tower under a hazy sky reads- * as one grey sheet whatever `tint` says); `curve` radius in- * metres of a ROUND tower, so the mullion pitch follows the arc- * instead of the chord (default 0, flat; the azimuth seam falls at- * -X); `metal` mullion colour (default 0x8d949a); `blindCol` (default- * 0xcfc7b6); `gain` reflection brightness (default 1); `seed` moves- * which panels differ how (default 1); `name` the program cache key- * (default 'urban:curtain' — every option here is a UNIFORM, so one- * name is correct and two differently tuned towers share one compiled- * program).- * @returns {THREE.Material} The same material, its uniforms live on- * `material.userData.uniforms` so a scene can swing `uCwSky` from day- * to dusk without rebuilding anything.- */-export function patchCurtainWall(material, opts = {}) {- const panel = toPair(opts.panel, 1.5, 3.6);- const mullion = opts.mullion === undefined ? 0.07 : opts.mullion;- const sky = toColor(opts.sky, 0x7ba6d8);- const haze = opts.haze === undefined- ? sky.clone().lerp(new THREE.Color(0xffffff), 0.62)- : toColor(opts.haze, 0xdfe7ee);- const reflect = opts.reflect === undefined ? 0.22 : unit(opts.reflect);- return patchStandard(material, {- name: opts.name || 'urban:curtain',- uniforms: {- uCwPanel: { value: new THREE.Vector2(panel[0], panel[1]) },- uCwTint: { value: toColor(opts.tint, 0x33556b) },- uCwMetal: { value: toColor(opts.metal, 0x8d949a) },- uCwSky: { value: sky },- uCwHaze: { value: haze },- uCwGround: { value: toColor(opts.ground, 0x4b4740) },- uCwBlindCol: { value: toColor(opts.blindCol, 0xcfc7b6) },- // Clamped under half the panel: a mullion wider than that is a- // wall with slots in it, and astraStroke only vanishes cleanly- // for a THIN stroke.- uCwMullion: { value: Math.max(- 0, Math.min(mullion, Math.min(panel[0], panel[1]) * 0.25)) },- uCwReflect: { value: reflect },- uCwBow: { value: Math.max(0, opts.bow === undefined ? 0.020- : opts.bow) },- uCwBlinds: { value: unit(opts.blinds === undefined ? 0.16- : opts.blinds) },- uCwCurve: { value: Math.max(0, opts.curve || 0) },- uCwSeed: { value: seedOffset(opts.seed) },- uCwGain: { value: Math.max(0, opts.gain === undefined ? 1- : opts.gain) },- uCwCoat: { value: unit(opts.coat === undefined ? 0.45 : opts.coat) },- },- vertexHead: CW_VARYINGS,- vertexBody: CW_VERTEX,- fragmentHead: [CW_VARYINGS, CW_HEAD].join('\n'),- fragmentBody: CW_BODY,- roughnessBody: 'roughnessFactor = mix(roughnessFactor, 0.10, cwGlass);',- metalnessBody: 'metalnessFactor *= 1.0 - cwGlass;',- });-}---// ---------------------------------------------------------------- cable--/**- * The catenary parameter `a` for a span that sags `sag` at midspan.- *- * sag = a * (cosh(L / 2a) - 1) has no closed form, so it is bisected on- * u = L / 2a, where the left side rises monotonically from 0.- *- * @param {number} span Horizontal distance between the ends, metres.- * @param {number} sag Midspan dip below the chord, metres.- * @returns {number} `a` in metres; Infinity for a straight cable.- */-function catenaryA(span, sag) {- if (!(sag > 1e-6) || !(span > 1e-6)) return Infinity;- let lo = 1e-6;- let hi = 1;- while (span / (2 * hi) * (Math.cosh(hi) - 1) < sag && hi < 1e4) hi *= 2;- for (let i = 0; i < 80; i++) {- const mid = 0.5 * (lo + hi);- if (span / (2 * mid) * (Math.cosh(mid) - 1) < sag) lo = mid;- else hi = mid;- }- return span / (2 * (0.5 * (lo + hi)));-}--/**- * Sample the true hanging curve between two points.- *- * A parabola is the giveaway: it is the small-sag limit of this, and it- * gets the CURVATURE wrong — constant along the span where a catenary's- * grows as cosh, so the cable leaves the insulator at the wrong angle.- *- * @param {THREE.Vector3} a One attachment point.- * @param {THREE.Vector3} b The other, at any height.- * @param {number} sag Midspan dip in metres.- * @param {number} n Segments.- * @returns {THREE.Vector3[]} n + 1 points from `a` to `b`.- */-function catenaryPoints(a, b, sag, n) {- const span = Math.hypot(b.x - a.x, b.z - a.z);- const par = catenaryA(span, sag);- const out = [];- if (!Number.isFinite(par)) {- for (let i = 0; i <= n; i++) {- out.push(a.clone().lerp(b, i / n));- }- return out;- }- // Fit the SAME curve to unequal end heights by sliding its low point,- // which is what a cable on a slope does.- const k = Math.asinh((b.y - a.y)- / (2 * par * Math.sinh(span / (2 * par))));- const p = span / 2 - par * k;- const q = a.y - par * Math.cosh(p / par);- for (let i = 0; i <= n; i++) {- const s = (i / n) * span;- out.push(new THREE.Vector3(- a.x + (b.x - a.x) * (i / n),- par * Math.cosh((s - p) / par) + q,- a.z + (b.z - a.z) * (i / n)));- }- return out;-}--const CABLE_VARYINGS = [- 'varying float vCbSide;',- 'varying float vCbUp;',- 'varying float vCbFade;',-].join('\n');--const CABLE_VHEAD = [- 'attribute vec3 aCbTan;',- 'attribute vec3 aCbRide;',- 'uniform float uCbRadius;',- 'uniform float uCbMinPx;',- 'uniform float uCbViewH;',- 'uniform float uCbSway;',- // A conductor is ~1 cm across and a pixel at 80 m is 10, so a- // world-width cable breaks into dashes exactly where a skyline needs- // it. Widen it to a floor of `minPx` and pay for it in alpha.- 'float astraCbHalf(float depth, float perPx, float radius,',- ' float minPx) {',- ' return max(radius, minPx * perPx * depth);',- '}',-].join('\n');--const CABLE_VERTEX = [- ' vec3 cbW = (modelMatrix * vec4(transformed, 1.0)).xyz;',- ' mat3 cbM = mat3(modelMatrix);',- ' float cbSc = max(length(cbM[0]), 1e-6);',- ' vec3 cbT = normalize(cbM * aCbTan);',- // Wind: the span swings about its ends, so the envelope rides in on- // the attribute and the phase decorrelates neighbouring conductors.- ' vec3 cbLat = normalize(cross(cbT, vec3(0.0, 1.0, 0.0)) + 1e-6);',- ' float cbSw = sin(uTime * 0.63 + aCbRide.x) * uCbSway * aCbRide.y;',- ' vec3 cbOff = cbLat * cbSw',- ' + vec3(0.0, cos(uTime * 0.41 + aCbRide.x) * uCbSway * 0.35',- ' * aCbRide.y, 0.0);',- ' cbW += cbOff;',- ' vec3 cbV = normalize(cameraPosition - cbW);',- ' vec3 cbSd = cross(cbT, cbV);',- ' float cbSl = length(cbSd);',- ' cbSd = cbSl > 1e-5 ? cbSd / cbSl : vec3(1.0, 0.0, 0.0);',- ' float cbDepth = max(-(viewMatrix * vec4(cbW, 1.0)).z, 1e-3);',- // Metres per pixel comes from the camera's OWN projection, so a wide- // lens and a long lens both get the same on-screen thickness.- ' float cbPerPx = 2.0 / (max(projectionMatrix[1][1], 1e-4) * uCbViewH);',- ' float cbHalf = astraCbHalf(cbDepth, cbPerPx, uCbRadius, uCbMinPx);',- ' vCbFade = clamp(uCbRadius / cbHalf, 0.35, 1.0);',- ' vCbSide = aCbRide.z;',- ' vCbUp = aCbRide.z * cbSd.y;',- ' cbOff += cbSd * (aCbRide.z * cbHalf);',- // Back to object space: exact for the rigid-plus-uniform-scale- // placement a group gets, which is every placement in this engine.- ' transformed += (transpose(cbM) * cbOff) / (cbSc * cbSc);',-].join('\n');--const CABLE_FRAGMENT = [- // The edge feather is capped and then DIVIDED OUT of the alpha: at a- // 1.5 px ribbon the feather spans the whole width, and left- // uncompensated it threw away three quarters of the ink the cable is- // owed — a line that is present and invisible is still a dashed line.- ' float cbAa = clamp(fwidth(vCbSide) * 1.5, 0.02, 0.7);',- ' float cbA = (1.0 - smoothstep(1.0 - cbAa, 1.0, abs(vCbSide)))',- ' / (1.0 - 0.5 * cbAa);',- ' cbA = min(cbA * vCbFade, 1.0);',- ' if (cbA < 0.004) discard;',- // A round wire: the near side of the cylinder catches the sky and the- // far side is its own silhouette.- ' float cbRound = sqrt(max(1.0 - vCbSide * vCbSide, 0.0));',- ' vec3 cbCol = uCbColor * (0.62 + 0.38 * vCbUp)',- ' * (0.72 + 0.28 * cbRound);',- ' gl_FragColor = vec4(cbCol, cbA);',-].join('\n');--/**- * Build the ribbon: one strip per strand, position on the CENTRELINE.- *- * Both sides of the strip share the centreline and the vertex shader- * spreads them, so the GTAO override pass — which draws raw `position`- * — sees a zero-area strip instead of a wall, and the bounding box- * measures the cable rather than its widened silhouette.- */-function cableGeometry(strands) {- const pos = [], tan = [], ride = [], idx = [];- let base = 0;- for (const s of strands) {- const n = s.pts.length;- for (let i = 0; i < n; i++) {- const p = s.pts[i];- const a = s.pts[Math.max(0, i - 1)];- const b = s.pts[Math.min(n - 1, i + 1)];- const t = new THREE.Vector3().subVectors(b, a);- if (t.lengthSq() < 1e-12) t.set(1, 0, 0);- t.normalize();- const env = Math.sin(Math.PI * (i / (n - 1)));- for (let k = 0; k < 2; k++) {- pos.push(p.x, p.y, p.z);- tan.push(t.x, t.y, t.z);- ride.push(s.phase, env, k === 0 ? -1 : 1);- }- if (i < n - 1) {- const a0 = base + i * 2;- idx.push(a0, a0 + 1, a0 + 2, a0 + 1, a0 + 3, a0 + 2);- }- }- base += n * 2;- }- const g = new THREE.BufferGeometry();- g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));- g.setAttribute('aCbTan', new THREE.Float32BufferAttribute(tan, 3));- g.setAttribute('aCbRide', new THREE.Float32BufferAttribute(ride, 3));- g.setIndex(idx);- g.computeBoundingSphere();- return g;-}--/**- * Weathering in a vertex colour: damp at the foot, sun-silvered up.- *- * A run of poles merged into one mesh is ONE flat brown, and that is- * what says "the same prop, twenty times" from across the street. Real- * timber differs pole to pole (creosote batch, how long it has stood)- * and along its own length (the bottom metre stays wet, the top bleaches- * grey). This is the whole of that fix and it costs nothing: no extra- * draw call, no texture, and `mergeGeometries` needs the attribute on- * every piece anyway. It only ever DARKENS — the tone runs down from 1- * and the warm/cool tilt is normalised — so `color` stays the material's- * true albedo instead of quietly becoming a floor under a brighter one.- *- * @param {THREE.BufferGeometry} geo Already translated into place.- * @param {() => number} rand The run's seeded stream.- * @param {number} foot World y the piece rises from.- * @param {object} [opts] `spread` piece-to-piece tone range, `tilt`- * warm/cool range, `damp` metres the wet foot reaches.- * @returns {THREE.BufferGeometry} The same geometry.- */-function paintPiece(geo, rand, foot, opts = {}) {- const pos = geo.attributes.position;- const col = new Float32Array(pos.count * 3);- const tone = 1 - rand()- * (opts.spread === undefined ? 0.24 : opts.spread);- const tilt = (rand() - 0.5) * (opts.tilt === undefined ? 0.10 : opts.tilt);- const damp = Math.max(0.05, opts.damp === undefined ? 1.6 : opts.damp);- // The tilt is a HUE, not a gain: normalised, so the warm channel- // reaches 1 and the cool one falls, and neither lifts the albedo.- const norm = 1 / (1 + Math.abs(tilt));- for (let i = 0; i < pos.count; i++) {- const h = unit((pos.getY(i) - foot) / damp);- const v = tone * (0.78 + 0.22 * h);- col[i * 3] = v * (1 + tilt) * norm;- col[i * 3 + 1] = v * norm * (1 + Math.abs(tilt) * 0.5);- col[i * 3 + 2] = v * (1 - tilt) * norm;- }- geo.setAttribute('color', new THREE.Float32BufferAttribute(col, 3));- return geo;-}--/** A box as geometry, yawed about Y and positioned by its centre. */-function _box(w, h, d, x, y, z, yaw) {- const g = new THREE.BoxGeometry(w, h, d);- if (yaw) g.rotateY(yaw);- g.translate(x, y, z);- return g;-}--/** Resample a route into `spans` equal-length legs, ends included. */-function resample(points, spans) {- const seg = [];- let total = 0;- for (let i = 1; i < points.length; i++) {- const d = points[i].distanceTo(points[i - 1]);- seg.push(d);- total += d;- }- if (!(total > 0)) return points.map((p) => p.clone());- const out = [];- for (let k = 0; k <= spans; k++) {- let want = (k / spans) * total;- let i = 0;- while (i < seg.length - 1 && want > seg[i]) { want -= seg[i]; i++; }- out.push(points[i].clone().lerp(- points[i + 1], Math.min(1, want / Math.max(seg[i], 1e-9))));- }- return out;-}--/**- * Cables between poles, hanging in a true CATENARY.- *- * Two things carry this and neither is the geometry of a tube. The- * curve is the catenary a hanging chain actually makes, not the- * parabola that is its small-sag limit — the parabola's curvature is- * constant along the span, so its cable leaves the insulator at the- * wrong angle and the eye reads a drawn arc. And the cable is drawn as- * a CAMERA-FACING ribbon whose half-width has a floor in PIXELS: a real- * conductor is about a centimetre across, a pixel at 80 m is ten, and a- * world-width tube therefore breaks into dashes exactly where a skyline- * needs it. The ribbon widens to that floor and gives back the extra- * width in alpha, so the line stays continuous and simply gets fainter.- *- * The poles come with it: tapered shafts, crossarms square to the run,- * and a ceramic insulator under every conductor.- *- * @param {object} [opts] `points` the route as pole bases, `[[x,y,z],- * ...]` or Vector3s — y is the GROUND there (default a 44 m run);- * `spans` resample the route into this many equal legs, so two points- * and `spans: 4` give five poles (default: a pole per point); `sag`- * midspan dip in metres (default 4% of the mean span — a slack line- * is 8%, a taut transmission line 2%); `thickness` cable DIAMETER in- * metres (default 0.04); `minPixels` the width the cable never falls- * below on screen (default 1.5 — this is what stops the aliasing, set- * 0 for the honest sub-pixel cable and its dashes); `viewportHeight`- * the frame height in px that width is measured against (default 576,- * the renderer's; `userData.setViewport(px)` retunes it);- * `poles` false for bare cables, or `{height, arms, wires, spread,- * radius, color}` (default 8.5 m, 2 arms, 3 wires an arm, 2.4 m- * spread — the poles are still what SPACES the cables when this is- * false; the pole `color` is the timber's albedo, which per-pole- * weathering DARKENS in a vertex colour so a run of them is never one- * flat brown); `color` conductor colour (default 0x15181c); `sway` metres of- * wind swing at midspan, driven by `tick` (default 0.05); `seed`- * detunes each conductor's sag and swing (default 1).- * @returns {THREE.Group} Named `PowerLines`, resting on the y of its- * points, with `userData.update(t)` (the sway), `userData.setViewport(px)`- * and `userData.spans` — the measured span lengths. The cable mesh is- * guarded by `keepOutOfDepthPasses`: a transparent ribbon is a solid- * wall to the GTAO override pass.- */-export function makePowerLines(opts = {}) {- const raw = (Array.isArray(opts.points) && opts.points.length >= 2- ? opts.points : [[-22, 0, 0], [22, 0, 0]]).map((p) => readVec3(p));- const poleAt = opts.spans > 0 ? resample(raw, Math.round(opts.spans))- : raw;- const spec = Object.assign(- { height: 8.5, arms: 2, spread: 2.4, radius: 0.15, color: 0x6d6255 },- (opts.poles && typeof opts.poles === 'object') ? opts.poles : {});- const rand = mulberry32(Math.round(opts.seed === undefined ? 1- : opts.seed));- const arms = Math.max(1, Math.round(spec.arms));- const perArm = Math.max(1, Math.round(- spec.wires === undefined ? 3 : spec.wires));- const radius = Math.max(1e-3,- (opts.thickness === undefined ? 0.04 : opts.thickness) * 0.5);-- const g = new THREE.Group();- g.name = 'PowerLines';-- // Crossarm direction at each pole: square to the run, bisected at a- // corner so a turning line does not tear its own arms apart.- const side = [];- for (let i = 0; i < poleAt.length; i++) {- const a = poleAt[Math.max(0, i - 1)];- const b = poleAt[Math.min(poleAt.length - 1, i + 1)];- const d = new THREE.Vector3().subVectors(b, a);- d.y = 0;- if (d.lengthSq() < 1e-9) d.set(1, 0, 0);- d.normalize();- side.push(new THREE.Vector3().crossVectors(_UP, d).normalize());- }-- // Where every conductor lands, pole by pole.- const hooks = poleAt.map((p, i) => {- const out = [];- for (let a = 0; a < arms; a++) {- const y = p.y + spec.height - 0.55 - a * 1.15;- for (let k = 0; k < perArm; k++) {- const off = perArm < 2 ? 0- : (k / (perArm - 1) - 0.5) * spec.spread;- out.push(new THREE.Vector3(- p.x + side[i].x * off, y + 0.18, p.z + side[i].z * off));- }- }- return out;- });-- const spans = [];- for (let i = 1; i < poleAt.length; i++) {- spans.push(Math.hypot(poleAt[i].x - poleAt[i - 1].x,- poleAt[i].z - poleAt[i - 1].z));- }- const mean = spans.reduce((a, b) => a + b, 0) / Math.max(1, spans.length);- const sag0 = opts.sag === undefined ? mean * 0.04 : opts.sag;-- const strands = [];- for (let c = 0; c < hooks[0].length; c++) {- // A lower arm hangs slacker than the one above it, and no two- // conductors on a line are tensioned identically.- const slack = (1 + 0.10 * Math.floor(c / perArm))- * (0.92 + 0.16 * rand());- for (let i = 1; i < hooks.length; i++) {- strands.push({- pts: catenaryPoints(hooks[i - 1][c], hooks[i][c], sag0 * slack,- Math.max(8, Math.round(spans[i - 1] * 1.2))),- phase: rand() * Math.PI * 2,- });- }- }-- const viewH = Math.max(64, opts.viewportHeight === undefined- ? 576 : opts.viewportHeight);- const cableMat = makeShaderMaterial({- name: 'PowerCable',- uniforms: {- uCbColor: { value: toColor(opts.color, 0x15181c) },- uCbRadius: { value: radius },- uCbMinPx: { value: Math.max(0, opts.minPixels === undefined- ? 1.5 : opts.minPixels) * 0.5 },- uCbViewH: { value: viewH },- uCbSway: { value: Math.max(0, opts.sway === undefined ? 0.05- : opts.sway) },- },- varyings: CABLE_VARYINGS,- vertexHead: CABLE_VHEAD,- vertexMain: CABLE_VERTEX,- fragmentHead: 'uniform vec3 uCbColor;',- fragmentMain: CABLE_FRAGMENT,- transparent: true,- depthWrite: false,- side: THREE.DoubleSide,- });- const cables = new THREE.Mesh(cableGeometry(strands), cableMat);- cables.name = 'Cables';- cables.renderOrder = 2;- g.add(keepOutOfDepthPasses(cables));-- if (opts.poles !== false) {- const wood = [];- const ceramic = [];- for (let i = 0; i < poleAt.length; i++) {- const p = poleAt[i];- const yaw = Math.atan2(side[i].x, side[i].z);- const shaft = new THREE.CylinderGeometry(- spec.radius * 0.72, spec.radius, spec.height, 8);- shaft.translate(p.x, p.y + spec.height / 2, p.z);- wood.push(paintPiece(shaft, rand, p.y));- for (let a = 0; a < arms; a++) {- const y = p.y + spec.height - 0.55 - a * 1.15;- wood.push(paintPiece(_box(0.11, 0.16, spec.spread + 0.5,- p.x, y, p.z, yaw), rand, y - 0.4));- // The knee braces: without them the arm is a stick balanced on- // a pole, which is the one thing a crossarm never is.- for (const s of [-1, 1]) {- const kn = new THREE.BoxGeometry(0.07, 0.93, 0.07);- kn.rotateX(s * 0.632);- kn.translate(0, y - 0.38, s * 0.28);- kn.rotateY(yaw);- kn.translate(p.x, 0, p.z);- wood.push(paintPiece(kn, rand, y - 0.9));- }- }- for (const h of hooks[i]) {- const ins = new THREE.CylinderGeometry(0.075, 0.055, 0.20, 6);- ins.translate(h.x, h.y - 0.10, h.z);- // Porcelain weathers too, just far less; the ramp reads as the- // grime that collects on the skirt of every insulator.- ceramic.push(paintPiece(ins, rand, h.y - 0.22,- { spread: 0.12, tilt: 0.05, damp: 0.22 }));- }- }- const poleMesh = new THREE.Mesh(- mergeGeometries(wood, false),- new THREE.MeshStandardMaterial({- color: spec.color, roughness: 0.92, metalness: 0.02,- vertexColors: true,- }));- poleMesh.name = 'Poles';- poleMesh.castShadow = true;- poleMesh.receiveShadow = true;- g.add(poleMesh);- const insMesh = new THREE.Mesh(- mergeGeometries(ceramic, false),- new THREE.MeshStandardMaterial({- color: 0x6f7a6a, roughness: 0.35, metalness: 0.0,- vertexColors: true,- }));- insMesh.name = 'Insulators';- insMesh.castShadow = true;- g.add(insMesh);- }-- g.userData.spans = spans;- g.userData.update = g.userData.tick = (t) => tickShaders(g, t);- g.userData.setViewport = (px) => {- cableMat.uniforms.uCbViewH.value = Math.max(64, px);- return g;- };- return attachDisposal(g, snapshotResources(g));-}---// ------------------------------------------------------------ billboard--const GLOW_FRAGMENT = [- ' vec2 bbD = abs(vBbUv - 0.5) * 2.0;',- ' float bbA = (1.0 - smoothstep(0.18, 1.0, bbD.x))',- ' * (1.0 - smoothstep(0.18, 1.0, bbD.y));',- // A halo is glow in the AIR round the sign, and the board is opaque:- // the card must not veil the artwork it sits in front of. Left solid- // through the middle it clipped the top band of the poster to 1.0 in- // daylight AND at night — an additive sheet over the face flattens- // the print and buys nothing without a bloom pass. So it is hollowed- // out over the board's own outline (`uBbInner`, the face as a- // fraction of this card) down to `uBbCore`, which only a light box —- // whose face really does emit — keeps above zero.- ' float bbOut = max(bbD.x / uBbInner.x, bbD.y / uBbInner.y);',- ' bbA *= mix(uBbCore, 1.0, smoothstep(0.60, 1.04, bbOut));',- // Lit from within it is even; lit by lamps on the top rail it is- // brightest under them and gone at the hoarding's feet.- ' bbA *= mix(1.0, smoothstep(-0.35, 0.95, vBbUv.y), uBbBias);',- // Rolled off, not clamped: a saturating halo draws a flat slab with a- // hard rim, which is the card again.- ' bbA = 1.0 - exp(-bbA * bbA * uBbGain * 3.4);',- ' if (bbA < 0.004) discard;',- // The gradient is metres wide and 8 bits deep, which is exactly where- // banding rings; a sub-LSB dither costs one hash and removes it.- ' bbA *= 1.0 + (astraHash21(gl_FragCoord.xy) - 0.5) * 0.06;',- ' gl_FragColor = vec4(uBbColor, bbA);',-].join('\n');--/**- * The pasted-up sheet: bold blocks, a headline band, paper grain.- *- * Three things this refuses, each one measured on a rendered board.- * The grain was `sin(u * 91.7 + v * 47.3) * 43758.5 % 1`, which is not- * a hash at those frequencies — it is a low-order beat, and it printed- * as DIAGONAL STRIPES across the whole poster. It is fBm now. The ink- * peaked at L 0.92, i.e. an albedo of ~0.9: a sheet of paper is not a- * light source, and under the gooseneck lamps that white clipped- * before the grade could touch it, so every colour is held inside the- * 0.02..0.80 band. And one flat ink over the sheet is the flat-decal- * tell, so the paper carries ink-density mottle, a bill-poster's PASTE- * SEAMS (a sheet this size is hung in strips) and sun bleach up the- * face — hue variance the eye reads as printing rather than as fill.- *- * The band is stated in sRGB because that is what a colour texture- * holds: 0.155..0.80 here is 0.02..0.60 linear, i.e. the albedo band- * with the top left clear for the lamps to work in.- */-function posterTexture(color, seed, lit) {- const key = Math.round(seed);- const rand = mulberry32(key * 977 + 13);- const base = toColor(color, 0xc8352f);- const hsl = { h: 0, s: 0, l: 0 };- base.getHSL(hsl);- // Paper white is a WARM off-white, never 1.0 — the ceiling is the top- // of the albedo band, and `lit` only decides where inside it we sit.- const CEIL = lit ? 0.80 : 0.74;- const FLOOR = 0.155;- const paper = new THREE.Color().setHSL(- (hsl.h + 0.47) % 1, Math.min(0.16, hsl.s * 0.22 + 0.04), CEIL * 0.94);- const accent = new THREE.Color().setHSL(- (hsl.h + 0.47) % 1, Math.min(1, hsl.s * 0.8 + 0.15), CEIL * 0.68);- const dark = new THREE.Color().setHSL(- (hsl.h + 0.02) % 1, hsl.s * 0.9, Math.max(0.09, hsl.l * 0.34));- // Round-robin, not a roll per bar: a poster printed in three inks uses- // all three. Rolling independently gave sheets that came out as four- // near-black bars on red — one hue, which is the flat-decal look this- // is here to avoid.- const inks = [paper, dark, accent, dark];- const bars = [];- for (let i = 0; i < 4; i++) {- bars.push({ y: 0.10 + rand() * 0.72, h: 0.05 + rand() * 0.13,- x: 0.04 + rand() * 0.30, w: 0.30 + rand() * 0.60,- c: inks[(i + Math.round(seed)) % inks.length] });- }- // Where the billposter's strips butt up, and how each strip was inked.- const strips = 2 + Math.round(rand());- const stripTone = [];- for (let i = 0; i <= strips; i++) stripTone.push(0.955 + rand() * 0.09);- const ox = seedOffset(key) * 0.37;- const tex = noiseDataTexture(128, (u, v) => {- const c = base.clone();- for (const b of bars) {- if (v > b.y && v < b.y + b.h && u > b.x && u < Math.min(1, b.x + b.w)) {- c.copy(b.c);- }- }- const s = Math.min(strips - 1, Math.floor(u * strips));- const su = u * strips - s;- // The seam itself: a hairline of shadow where one sheet laps the next.- const seam = 1 - 0.14 * (1 - Math.min(1, Math.min(su, 1 - su) * 26));- // Ink density (broad) and paper grain (fine), both real fBm so the- // sheet cannot beat against its own sampling.- const mottle = fbm2(u * 3.3 + ox, v * 3.3, { seed: key + 5 });- const grain = fbm2(u * 96, v * 96, { octaves: 2, seed: key + 31 });- const n = stripTone[s] * seam * (1 + 0.16 * mottle + 0.10 * grain);- // Sun bleach: the top of a hoarding fades first, and it fades WARM.- const bleach = 0.13 * v * v;- const tilt = 0.05 * mottle;- const out = [- unit(c.r * n * (1 + tilt) + bleach * CEIL * 0.30),- unit(c.g * n + bleach * CEIL * 0.27),- unit(c.b * n * (1 - tilt) + bleach * CEIL * 0.22),- ];- // The floor is held on LUMINANCE, not per channel: clamping each- // channel to it turns a dark red ink into a pink-grey, and the point- // of the floor is that nothing on the sheet is a hole.- const lum = 0.2126 * out[0] + 0.7152 * out[1] + 0.0722 * out[2];- const k = lum < FLOOR ? FLOOR / Math.max(lum, 1e-4) : 1;- return out.map((x) => Math.min(CEIL, x * k));- });- tex.colorSpace = THREE.SRGBColorSpace;- return tex;-}--/**- * A hoarding or a lit sign panel, on the structure that holds it up.- *- * A billboard without its frame is a decal floating in the air, so the- * legs, the back bracing and the rim come with the face. `kind` picks- * which of the two real things this is, and they light differently- * because they ARE lit differently: a `'hoarding'` is a pasted sheet- * lit from OUTSIDE by gooseneck lamps on the top rail, so the poster is- * brightest under each lamp and falls off toward its feet; a `'panel'`- * is a light box lit from WITHIN, so the face is even and the structure- * around it catches the spill.- *- * The light itself is `lib/neon.js`: `patchNeonSpill` already owns- * windowed falloff, the wrapped terminator a broad source needs, and- * the reflection through the receiving surface's own albedo, so this- * hands its sources to that patch instead of growing a second copy. It- * patches its OWN structure that way at build time and hands the same- * sources out through `userData.spillSources(n)` — give them to a- * `patchNeonSpill` on the wall behind or the pavement below, which is- * the difference between a lit sign and a lit street.- *- * @param {object} [opts] `width` / `height` of the face in metres- * (default 6 x 3); `kind` `'hoarding'` (default) or `'panel'`;- * `color` the poster's dominant ink, which is also what the sign- * throws (default 0xc8352f); `lit` (default false) turns on the- * lamps or the light box, the halo and the spill; `lift` metres from- * the ground to the bottom of the face (default the greater of 2.4- * and half the height); `frameColor` (default 0x4a4c4f); `glow` halo- * brightness (default 1); `ambient` how bright the surroundings are,- * 0 an unlit street to 1 open daylight, passed straight to- * `patchNeonSpill` (default 0.15); `seed` the poster and the lamp- * spacing (default 1).- * @returns {THREE.Group} Named `Billboard`, resting at y = 0 and facing- * +Z (`userData.forward`), with `userData.spillSources(n)` (world- * points, read through the group's CURRENT matrix),- * `userData.relight()` — call it after MOVING a lit sign, since the- * spill on its own structure was aimed where it was built — and- * `userData.update(t)`. The halo is guarded by `keepOutOfDepthPasses`.- */-export function makeBillboard(opts = {}) {- const w = Math.max(0.5, opts.width === undefined ? 6 : opts.width);- const h = Math.max(0.4, opts.height === undefined ? 3 : opts.height);- const panelKind = opts.kind === 'panel' ? 'panel' : 'hoarding';- const lit = !!opts.lit;- const lift = opts.lift === undefined ? Math.max(2.4, h * 0.5) : opts.lift;- const color = toColor(opts.color, 0xc8352f);- const seed = opts.seed === undefined ? 1 : opts.seed;- const rand = mulberry32(Math.round(seed) * 131 + 7);- const ambient = unit(opts.ambient === undefined ? 0.15 : opts.ambient);- const y0 = lift + h / 2;-- const g = new THREE.Group();- g.name = 'Billboard';-- const frameMat = new THREE.MeshStandardMaterial({- color: opts.frameColor === undefined ? 0x4a4c4f : opts.frameColor,- roughness: 0.62, metalness: 0.55,- });- const boardMat = new THREE.MeshStandardMaterial({- color: 0x2b2c2e, roughness: 0.85, metalness: 0.1,- });- const faceMat = new THREE.MeshStandardMaterial({- map: posterTexture(color, seed, lit),- roughness: panelKind === 'panel' ? 0.28 : 0.78,- metalness: 0,- });- if (lit && panelKind === 'panel') {- // A light box is lit from within: emissive is the only term that- // survives an unlit street, and the map keeps the artwork in it.- faceMat.emissive = new THREE.Color(0xffffff);- faceMat.emissiveMap = faceMat.map;- faceMat.emissiveIntensity = 1.5 * (1 - 0.7 * ambient);- }-- const board = new THREE.Mesh(new THREE.BoxGeometry(w, h, 0.14), boardMat);- board.position.set(0, y0, -0.02);- board.name = 'Board';- board.castShadow = true;- board.receiveShadow = true;- g.add(board);-- const face = new THREE.Mesh(- new THREE.PlaneGeometry(w - 0.18, h - 0.18), faceMat);- face.position.set(0, y0, 0.06);- face.name = 'Face';- face.receiveShadow = true;- g.add(face);-- // Legs, rim and back bracing in one mesh: a billboard is a steel- // frame with a sheet on it, and the frame is most of the silhouette.- const steel = [];- const legX = w * 0.3;- for (const sx of [-legX, legX]) {- steel.push(_box(0.18, y0 + h / 2, 0.18, sx, (y0 + h / 2) / 2, -0.16));- // The raking strut every real hoarding has behind it, lifted by- // its own half-thickness so the foot rests ON the ground.- const ang = Math.atan2(lift * 0.75, lift);- const rake = new THREE.BoxGeometry(0.12, Math.hypot(lift, lift * 0.75),- 0.12);- rake.rotateX(-ang);- rake.translate(sx, lift * 0.5 + 0.06 * Math.sin(ang),- -0.16 - lift * 0.375);- steel.push(rake);- }- steel.push(_box(w + 0.24, 0.16, 0.16, 0, y0 + h / 2 + 0.08, 0));- steel.push(_box(w + 0.24, 0.16, 0.16, 0, y0 - h / 2 - 0.08, 0));- steel.push(_box(0.16, h, 0.16, -w / 2 - 0.08, y0, 0));- steel.push(_box(0.16, h, 0.16, w / 2 + 0.08, y0, 0));-- const lamps = [];- const sources = [];- if (lit && panelKind === 'hoarding') {- const n = Math.max(2, Math.round(w / 3));- for (let i = 0; i < n; i++) {- const x = (i + 0.5) / n * w - w / 2 + (rand() - 0.5) * 0.1;- const ly = y0 + h / 2 + 0.62;- steel.push(_box(0.09, 0.09, 0.9, x, ly, 0.42));- steel.push(_box(0.09, 0.7, 0.09, x, ly - 0.35, 0.86));- const head = new THREE.CylinderGeometry(0.17, 0.11, 0.2, 10);- head.rotateX(Math.PI * 0.42);- head.translate(x, ly - 0.62, 0.84);- lamps.push(head);- sources.push({ position: new THREE.Vector3(x, ly - 0.72, 0.78),- color: new THREE.Color(0xfff0cf) });- }- }-- const frame = new THREE.Mesh(mergeGeometries(steel, false), frameMat);- frame.name = 'Frame';- frame.castShadow = true;- frame.receiveShadow = true;- g.add(frame);-- if (lamps.length) {- const lampMat = new THREE.MeshStandardMaterial({- color: 0xd8d2c4, roughness: 0.4, metalness: 0.6,- emissive: new THREE.Color(0xfff0cf),- emissiveIntensity: 2.2 * (1 - 0.7 * ambient),- });- const lampMesh = new THREE.Mesh(mergeGeometries(lamps, false), lampMat);- lampMesh.name = 'Lamps';- g.add(lampMesh);- }- if (lit && panelKind === 'panel') {- for (let i = 0; i < 4; i++) {- sources.push({- position: new THREE.Vector3(- (i / 3 - 0.5) * w * 0.8, y0 + (rand() - 0.5) * h * 0.5, 0.1),- color: color.clone(),- });- }- }-- if (lit) {- // The card carries the halo OUTSIDE the board now, so it has to be- // big enough to hold one: at 1.5 x 1.7 the aureole was a bright rim- // a few pixels wide instead of light standing in the air.- const CARD = [2.0, 2.2];- const glow = new THREE.Mesh(- new THREE.PlaneGeometry(w * CARD[0], h * CARD[1]),- makeShaderMaterial({- name: 'BillboardGlow',- uniforms: {- uBbColor: { value: panelKind === 'panel'- ? color.clone().lerp(new THREE.Color(0xffffff), 0.35)- : new THREE.Color(0xffe9c4) },- // A halo is light scattered in the AIR, so it is only ever- // visible against a darker frame: linear in `ambient` it- // still clipped the sky round a hoarding at midday- // (blown_frac 0.033 in the day close view), and the curve is- // what makes one card read at night and vanish by noon.- uBbGain: { value: Math.max(0, opts.glow === undefined ? 1- : opts.glow)- * Math.pow(Math.max(0, 1 - ambient), 1.7) },- uBbBias: { value: panelKind === 'panel' ? 0 : 1 },- // Where the board's own outline falls on this card.- uBbInner: { value: new THREE.Vector2(1 / CARD[0], 1 / CARD[1]) },- uBbCore: { value: panelKind === 'panel' ? 0.30 : 0.0 },- },- varyings: 'varying vec2 vBbUv;',- vertexMain: ' vBbUv = uv;',- fragmentHead: 'uniform vec3 uBbColor;\nuniform float uBbGain;\n'- + 'uniform float uBbBias;\nuniform vec2 uBbInner;\n'- + 'uniform float uBbCore;',- fragmentMain: GLOW_FRAGMENT,- additive: true,- }));- glow.position.set(0, y0, 0.09);- glow.name = 'Glow';- glow.renderOrder = 3;- g.add(keepOutOfDepthPasses(glow));- }-- // Sources are read through the CURRENT world matrix, so placing the- // sign moves the light it throws.- g.userData.spillSources = (n) => {- g.updateWorldMatrix(true, false);- const want = Math.min(8, Math.max(1, Math.round(- n === undefined ? sources.length || 1 : n)));- const pick = want >= sources.length- ? sources- : sources.filter((_, i) => i % Math.ceil(sources.length / want) === 0)- .slice(0, want);- return pick.map((s) => ({- position: s.position.clone().applyMatrix4(g.matrixWorld),- color: s.color.clone(),- }));- };- // The sign lights its OWN structure through neon.js rather than- // growing a second spill; the face too, when lamps light it.- g.userData.relight = () => {- if (!sources.length) return g;- const list = g.userData.spillSources(sources.length);- const reach = Math.max(w, h) * 1.4;- // Measured at night: a strength of 1.1 on the steel and 1.5 on the- // poster clipped both — the frame went to a white silhouette and the- // top third of the artwork disappeared into the wash. A gooseneck- // makes POOLS on a sheet, so the spill has to stay under the ink it- // is lighting.- patchNeonSpill(frameMat, { sources: list, radius: reach,- strength: 0.72, ambient });- if (panelKind === 'hoarding') {- patchNeonSpill(faceMat, { sources: list, radius: reach,- strength: 0.85, ambient });- }- return g;- };- g.userData.relight();- g.userData.update = g.userData.tick = (t) => tickShaders(g, t);- g.userData.forward = '+Z';- const owned = snapshotResources(g);- owned.add(faceMat.map);- return attachDisposal(g, owned);-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/veils.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/veils.jsdeleted file mode 100644index 802253bf..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/veils.js+++ /dev/null@@ -1,821 +0,0 @@-/**- * Weather seen AT DISTANCE: the veils, not the drops.- *- * Drops near the camera are a wrap box a few metres- * wide, streaks measured in centimetres. A rainy valley needs the other- * thing entirely: the pale sheets of rain crossing the far hillside,- * tens of metres tall, slanted with the wind, that tell you the weather- * is out THERE. Same for snow, and for the dust and pollen that say- * this air has something in it. None of the three is a bigger copy of- * the near-field version, and the differences are the point:- *- * `makeRainVeil` is a handful of huge slanted curtains, not thousands- * of streaks. A curtain is legible only if it never shows an edge and- * never reads as a rectangle, so each one billboards about its OWN- * fall axis and carries filaments that travel down its face.- *- * `makeSnowfall` is not rain that is white. A snowflake falls at- * under a metre a second and WANDERS — its horizontal path is a curve- * with no preferred direction — and that wander is the whole- * difference. Flakes near the camera are drawn bigger and softer,- * because a real lens focussed on the valley cannot hold them.- *- * `makeMotes` is the air itself: specks that hang, barely drift, and- * flash as they turn their faces to the light.- *- * BLENDING — all three blend NORMALLY, none of them additively.- * `godrays.js` measures what added light does to a bright frame: 12.8%- * of it past 0.97, and 3.6x less gain still left 11.3%, because 0.94- * plus anything visible clips. Every effect here is pale and every one- * of them can appear in daylight, so additive blending would turn each- * into a solid white slab at any strength worth having. Rain and snow- * SCATTER — they lower the contrast of what is behind them, which is- * the opposite of adding — and a mote is a speck of matter, not a lamp;- * its glint is carried to near-white through ALPHA, which is the- * brightest an element that does not add is allowed to be.- *- * LIGHT — none of the three is a lit material, and all three read the- * scene anyway: each field probes the lights around it every few frames- * and multiplies its colour by that irradiance, normalised so the- * library's own day rig is 1.0. Daylight is therefore unchanged and a- * moonlit valley no longer carries a glowing white curtain. A lamp is- * included with its falloff at the field's own origin, which is what- * puts a mote volume standing in a lamp's pool into that pool.- *- * Camera vectors are converted to local coordinates, so translated,- * rotated and scaled parents retain the authored local field.- */--import * as THREE from 'three';-import { attachDisposal, snapshotResources } from './lifecycle.js';--import { lehmer } from './noise.js';-import {- glslWob, instancedQuad, keepOutOfDepthPasses, makeShaderMaterial,- readWind, tickShaders, wobX, wobZ } from './shader.js';--// Terminal fall of medium rain. Written once because the slant, the-// sheet length and the streak rate must all read the same number.-const _RAIN_FALL = 9.0;--// The swing: `wobX`/`wobZ` on the CPU mirror, the same pair in GLSL.-const _WOB_GLSL = glslWob('astraVeilWob');--/** Wrap v into [-half, half), the CPU mirror of GLSL mod(). */-function _wrap(v, extent, half) {- return v - Math.floor((v + half) / extent) * extent;-}--/*- * LIGHT. None of the three materials is lit — they are billboards with- * a colour and an alpha — and an unlit pale card is the brightest thing- * in any frame that is not daylight. Measured on the moonlit rig- * (elevation -20): the rain curtain came back at 0.62 luminance over a- * 0.12 scene, a glowing sheet hanging in front of a night sky, and the- * motes stayed white inside a shadow. Nothing here can be lit properly- * — a veil is a volume, not a surface — but what it SCATTERS is the- * irradiance where it hangs, and that is one vec3 the scene can be- * asked for. So each field probes its own scene once per render frame- * and multiplies its colour by the answer, normalised so the library's- * own day rig lands on 1.0 and every veil in daylight looks exactly as- * it did. `uLight` becomes zero when all contributing lights are removed.- * Effect previews should provide an ambient light explicitly.- */--// Weights per light type: a veil sees the whole sky and only a slice of-// a directional beam (forward scatter), so the hemisphere dominates.-const _W_HEMI_SKY = 0.62;-const _W_HEMI_GROUND = 0.18;-const _W_DIR = 0.12;-// Irradiance the library's `sunRig()` day preset puts on a veil, so the-// probe is a no-op at noon and a real dimming everywhere else.-const _LIGHT_REF = 1.02;--const _PROBE = new WeakMap();-const _TMP_AT = new THREE.Vector3();-const _TMP_LP = new THREE.Vector3();--/** The distant (position-free) part of a scene's light, cached per frame. */-function _probeScene(scene, frame) {- const hit = _PROBE.get(scene);- if (hit && frame === hit.frame) return hit;- const distant = { r: 0, g: 0, b: 0 };- const punctual = [];- let found = 0;- scene.traverseVisible((o) => {- if (!o.isLight || o.visible === false || !(o.intensity > 0)) return;- found++;- const c = o.color;- const i = o.intensity;- if (o.isAmbientLight) {- distant.r += c.r * i; distant.g += c.g * i; distant.b += c.b * i;- } else if (o.isHemisphereLight) {- const g = o.groundColor;- distant.r += (c.r * _W_HEMI_SKY + g.r * _W_HEMI_GROUND) * i;- distant.g += (c.g * _W_HEMI_SKY + g.g * _W_HEMI_GROUND) * i;- distant.b += (c.b * _W_HEMI_SKY + g.b * _W_HEMI_GROUND) * i;- } else if (o.isDirectionalLight) {- distant.r += c.r * i * _W_DIR;- distant.g += c.g * i * _W_DIR;- distant.b += c.b * i * _W_DIR;- } else if (o.isPointLight || o.isSpotLight) {- punctual.push(o);- }- });- const out = { frame, distant, punctual, found, fog: scene.fog || null };- _PROBE.set(scene, out);- return out;-}--/**- * Drive `uLight` (and, when the caller left the colour alone, the hue of- * `uColor`) from the scene the mesh is being drawn in.- *- * A lamp is included with its own inverse-square falloff at the FIELD's- * origin, which is what gives a mote volume standing in a lamp's pool a- * warm lift and leaves the 70 m rain field untouched by it.- *- * @param {THREE.Mesh} mesh Carries a `makeShaderMaterial` with `uLight`.- * @param {THREE.Color} [autoTint] The default colour to pull into the- * scene's fog hue — omitted when the caller passed a colour of its own.- */-function _litByScene(mesh, autoTint) {- const prev = mesh.onBeforeRender;- const uni = mesh.material.uniforms;- const base = autoTint ? autoTint.clone() : null;- const hsl = { h: 0, s: 0, l: 0 };- const own = { h: 0, s: 0, l: 0 };- const inverse = new THREE.Matrix4();- uni.uCameraLocal = { value: new THREE.Vector3() };- uni.uCameraRight = { value: new THREE.Vector3(1, 0, 0) };- uni.uCameraUp = { value: new THREE.Vector3(0, 1, 0) };- mesh.material.vertexShader = 'uniform vec3 uCameraLocal; uniform vec3 uCameraRight; uniform vec3 uCameraUp;\n' + mesh.material.vertexShader;- mesh.material.fragmentShader = 'uniform vec3 uCameraLocal;\n' + mesh.material.fragmentShader;- mesh.onBeforeRender = (r, scene, cam, geo, mat, grp) => {- if (prev) prev.call(mesh, r, scene, cam, geo, mat, grp);- inverse.copy(mesh.matrixWorld).invert();- cam.getWorldPosition(uni.uCameraLocal.value).applyMatrix4(inverse);- uni.uCameraRight.value.setFromMatrixColumn(cam.matrixWorld, 0).transformDirection(inverse);- uni.uCameraUp.value.setFromMatrixColumn(cam.matrixWorld, 1).transformDirection(inverse);- const p = _probeScene(scene, r.info.render.frame);- if (!p.found) {- uni.uLight.value.setRGB(0, 0, 0);- if (base) uni.uColor.value.copy(base);- return;- }- let { r: er, g: eg, b: eb } = p.distant;- if (p.punctual.length) {- mesh.getWorldPosition(_TMP_AT);- for (const l of p.punctual) {- l.getWorldPosition(_TMP_LP);- const d2 = Math.max(0.25, _TMP_LP.distanceToSquared(_TMP_AT));- if (l.distance > 0 && d2 > l.distance * l.distance) continue;- const a = (l.intensity / d2) * _W_DIR;- er += l.color.r * a; eg += l.color.g * a; eb += l.color.b * a;- }- }- // The floor keeps a veil legible in a scene lit by one dim lamp;- // the ceiling stops a lamp two metres away turning it into a- // white slab, which is the failure ordinary blending exists to- // avoid in the first place.- // ADAPTATION, not physics. A straight ratio is right for the- // hue and too steep for the value: a moonlit curtain at 0.15 of- // daylight is a curtain nobody can see, while the eye watching- // that valley has opened up. The 0.82 exponent is the whole of- // the fudge — it is 1.0 at daylight, so noon is untouched, and- // it lifts the moonlit field to 0.21 of it.- const k = 1 / _LIGHT_REF;- const adapt = (e) => Math.min(1.7,- Math.max(0.05, Math.pow(Math.max(0, e * k), 0.82)));- uni.uLight.value.setRGB(adapt(er), adapt(eg), adapt(eb));- // FOG HUE. A veil the scene's own haze does not agree with reads- // as a card in front of the weather rather than part of it — so- // an untouched default takes the fog's HUE and keeps its own- // lightness. Taking the fog's value as well would send the veil- // to black in a night scene the light probe has already dimmed.- if (base && p.fog) {- p.fog.color.getHSL(hsl);- base.getHSL(own);- uni.uColor.value.setHSL(hsl.h,- Math.min(0.30, hsl.s * 0.75 + own.s * 0.25), own.l);- } else if (base) uni.uColor.value.copy(base);- };-}--/**- * Sheets of rain crossing the middle and far distance.- *- * A few very large curtains, not a cloud of streaks: at 80 m a drop is- * far under a pixel, so what the eye is given is the SHEET — leaning- * with the wind, thickest at its foot, ragged at its edges, with- * filaments running down its face. Two constraints keep it from reading- * as flat cards, which is the one way this effect fails. Each sheet- * billboards about its own fall axis, so it turns its face to every- * camera and never shows an edge or a rectangle; and the per-sheet- * alpha is solved from how many sheets a ray across the field crosses,- * so `density` means the same veil however many of them there are and- * an overlap never stacks into a slab.- *- * BLENDING: ORDINARY. Rain scatters — it lowers the contrast of the- * ridge behind it — and a sheet this size added to a daylight sky- * would clip to a white slab at any strength worth having.- *- * @param {object} [opts]- * `extent` metres square the sheets are spread over (default 120 —- * this is landscape weather, so think valley, not garden);- * `height` metres from the cloud base to the ground (default 60 —- * a veil no taller than the ridge it crosses reads as ground haze,- * so give it half again the height of what it falls past);- * `direction` wind in m/s as a number (along +x), [dx, dz] or a- * THREE.Vector2/3 (default [3.5, 0]) — it sets the SLANT (against a- * 9 m/s fall) and the speed the sheets travel across the field;- * `density` how much the veil hides, 0 to 1 (default 0.6; 0.9 is a- * downpour that greys out the far ridge);- * `color` THREE.Color or hex — the veil's ALBEDO, which the scene's- * own light then multiplies (default a cool grey that takes the- * scene fog's HUE at its own lightness, so the sheets never stand in- * front of the weather; pass a colour to keep that from happening);- * `seed` PRNG seed (default 7).- * @returns {THREE.Group} Named `RainVeil`, centred on its own origin- * with the sheets' feet at y ~ 0, with `userData.update(t)`,- * `userData.sample(i, t)` giving sheet i's foot and `userData.axis`- * the shared fall direction. Move the group to place the field.- */-export function makeRainVeil(opts = {}) {- const extent = Math.max(6,- opts.extent === undefined ? 120 : opts.extent);- const height = Math.max(3,- opts.height === undefined ? 60 : opts.height);- const w = readWind(opts.direction, [3.5, 0], 'makeRainVeil direction');- const wind = new THREE.Vector2(w.x, w.z);- const density = Math.min(0.97, Math.max(0.02,- opts.density === undefined ? 0.6 : opts.density));- const color = new THREE.Color(- opts.color === undefined ? 0xb9c6d4 : opts.color);- const autoTint = opts.color === undefined ? color : null;- const rnd = lehmer(opts.seed === undefined ? 7 : opts.seed);-- const axis = new THREE.Vector3(wind.x, -_RAIN_FALL, wind.y).normalize();- // Length ALONG the slanted axis that spans `height` vertically, so- // the cloud base stays level however hard the wind blows.- const len = height / Math.max(0.2, -axis.y);- const half = extent * 0.5;- const sink = height * 0.05;-- const count = Math.round(Math.min(9, Math.max(4, extent / 25)));- const sheet = new Float32Array(count * 4);- const veil = new Float32Array(count * 2);- const footR = Math.hypot(half * Math.SQRT2, sink);- const topR = Math.hypot(half * Math.SQRT2 + len * Math.hypot(axis.x,- axis.z), len * -axis.y - sink);- let widths = 0;- let radius = 0;- for (let i = 0; i < count; i++) {- // Stratified around a ring, never a uniform draw: a uniform one- // puts two sheets on top of each other and leaves a third of- // the valley with no weather in it at all.- const a = ((i + rnd()) / count) * Math.PI * 2;- const r = half * (0.22 + 0.74 * rnd());- const hw = extent * (0.09 + 0.09 * rnd());- sheet[i * 4] = Math.cos(a) * r;- sheet[i * 4 + 1] = Math.sin(a) * r;- sheet[i * 4 + 2] = hw;- sheet[i * 4 + 3] = rnd() * 40;- veil[i * 2] = 0.62 + 0.58 * rnd();- veil[i * 2 + 1] = rnd() * 9;- widths += hw * 2;- radius = Math.max(radius, Math.max(footR, topR) + hw);- }- // Sheets a ray across the field crosses. Solving the per-sheet- // alpha from it keeps `density` the depth of the VEIL at any count,- // and the 2.6 pays back what the profile and the holes take.- const hits = Math.max(0.8, widths / extent);- const alpha = Math.min(0.70, Math.max(0.01,- 2.6 * (1 - Math.pow(1 - density, 1 / hits))));-- const geom = instancedQuad(count, 1, 1, radius * 1.02);- geom.setAttribute('aSheet', new THREE.InstancedBufferAttribute(sheet, 4));- geom.setAttribute('aVeil', new THREE.InstancedBufferAttribute(veil, 2));-- const mesh = new THREE.Mesh(geom, veilMaterial({- color, alpha, axis, wind, extent, half, len, sink,- wisp: Math.max(1.2, extent * 0.05),- near: Math.max(4, extent * 0.08),- }));- mesh.name = 'RainSheets';- mesh.renderOrder = 3;- const g = new THREE.Group();- g.name = 'RainVeil';- g.add(mesh);- // A curtain of rain is not a wall to the ambient-occlusion pass and- // does not cast a shadow; every other veil in this library says so.- keepOutOfDepthPasses(g);- _litByScene(mesh, autoTint);- g.userData.update = g.userData.tick = (t) => tickShaders(g, t);- g.userData.axis = axis.clone();- g.userData.length = len;- g.userData.sample = (i, t) => {- const k = Math.min(count - 1, Math.max(0, i | 0));- return new THREE.Vector3(- _wrap(sheet[k * 4] + wind.x * t, extent, half), -sink,- _wrap(sheet[k * 4 + 1] + wind.y * t, extent, half));- };- return attachDisposal(g, snapshotResources(g));-}--/** One curtain per instance, rolled about its own fall axis. */-function veilMaterial(cfg) {- return makeShaderMaterial({- name: 'RainVeilSheets',- uniforms: {- uTime: { value: 0 },- uColor: { value: cfg.color },- uLight: { value: new THREE.Color(1, 1, 1) },- uAlpha: { value: cfg.alpha },- uAxis: { value: cfg.axis },- uWind: { value: cfg.wind },- uExtent: { value: cfg.extent },- uHalf: { value: cfg.half },- uLen: { value: cfg.len },- uSink: { value: cfg.sink },- uWisp: { value: cfg.wisp },- uNear: { value: cfg.near },- uFall: { value: _RAIN_FALL },- // Metres between filaments across the sheet and between- // their heads down it.- uSpacing: { value: 0.55 },- uSeg: { value: 6.0 },- },- varyings: 'varying vec2 vUv; varying vec3 vP;'- + ' varying float vBright; varying float vSeed;'- + ' varying float vHalfW; varying float vFade;',- // `uniform float uTime;` rides on a long line on purpose: the- // GLSL audit only reads quoted strings long enough to look like- // shader source, so alone it is skipped and this file reads as- // using uTime without ever declaring it (shader.js injects the- // declaration, and the duplicate here is deduped away).- vertexHead: 'attribute vec3 aCorner; attribute vec4 aSheet;'- + ' uniform float uTime;'- + ' attribute vec2 aVeil; uniform vec3 uAxis;'- + ' uniform vec2 uWind; uniform float uExtent;'- + ' uniform float uHalf; uniform float uLen;'- + ' uniform float uSink;',- vertexMain: [- ' vUv = uv;',- ' vBright = aVeil.x;',- ' vSeed = aVeil.y + aSheet.w;',- ' vHalfW = aSheet.z;',- // The whole curtain travels with the wind and wraps in the- // field; the edge fade below hides the wrap.- ' vec2 fxz = mod(aSheet.xy + uWind * uTime + uHalf, uExtent)',- ' - uHalf;',- ' vec3 foot = vec3(fxz.x, -uSink, fxz.y);',- ' vec3 up = -uAxis;',- ' vec3 mid = foot + up * (uLen * 0.5);',- // Rolled about its OWN fall axis: the slant stays true from- // every camera and the sheet never turns edge-on, which is- // the moment a curtain would betray itself as a card.- ' vec3 side = cross(uAxis, mid - uCameraLocal);',- ' float sl = length(side);',- ' side = sl > 1e-4 ? side / sl : vec3(1.0, 0.0, 0.0);',- ' transformed = foot + up * ((aCorner.y + 0.5) * uLen)',- ' + side * (aCorner.x * 2.0 * aSheet.z);',- ' vP = transformed;',- ' vFade = 1.0 - smoothstep(0.85, 1.20,',- ' length(fxz) / uHalf);',- ].join('\n'),- fragmentHead: 'uniform vec3 uColor; uniform vec3 uLight;'- + ' uniform float uAlpha;'- + ' uniform float uLen; uniform float uWisp;'- + ' uniform float uNear; uniform float uFall;'- + ' uniform float uSpacing; uniform float uSeg;',- fragmentMain: [- ' vec2 e = abs(vUv * 2.0 - 1.0);',- // Denser at the foot and gone into the cloud at the top —- // and soft on both flanks, because a rim IS the card.- ' float prof = mix(1.0, 0.45, vUv.y)',- ' * smoothstep(0.0, 0.16, vUv.y)',- ' * (1.0 - smoothstep(0.76, 1.0, vUv.y))',- ' * (1.0 - smoothstep(0.30, 1.0, e.x));',- ' float near = smoothstep(uNear * 0.3, uNear,',- ' length(vP - uCameraLocal));',- ' float cap = uAlpha * vBright * vFade * prof * near;',- ' if (cap < 0.002) discard;',- ' float wx = (vUv.x - 0.5) * 2.0 * vHalfW;',- ' float wy = vUv.y * uLen + uTime * uFall;',- // Stretched 8x along the fall. Round blotches are what- // makes a pale mass read as steam; rain is drawn out into- // bands that run the whole way down the shaft.- ' vec2 q = vec2(wx / uWisp, wy / (uWisp * 8.0)) + vSeed;',- ' float band = astraFbm2(q, 3) * 0.72',- ' + astraNoise2(q * 3.1 + vec2(0.0, 4.0)) * 0.28;',- // GUSTS, metres across, under the centimetre bands: a real- // curtain is thick in patches and thin between them, and- // without that the sheet is flat everywhere the filaments- // are not, which is what makes the filaments read as- // scratches on the ridge instead of rain in front of it.- // Centred on 1.0, so `density` still means what it says.- ' float gust = astraFbm2(q * 0.21 + vec2(5.3, 1.7), 2);',- ' float body = mix(0.42, 1.0, smoothstep(0.20, 0.78, band))',- ' * mix(0.68, 1.28, smoothstep(0.14, 0.64, gust));',- // Filaments travelling down the face: without them a sheet- // this size is a painted gradient and reads as a backdrop.- // Thin (0.10 of the spacing, not 0.16) so `astraStroke`'s- // own kill can still retire them at distance, never fully- // off between heads, and coupled to `body` — a filament in- // a thin part of the curtain has nothing to be made of.- ' float ux = wx / uSpacing + 0.65 * astraNoise2(vec2(wx * .11, wy * .045) + vSeed);',- ' float d = fract(wy / uSeg + astraStagger(floor(ux) + vSeed));',- ' float fil = astraStroke(ux, 0.12)',- ' * (0.12 + 0.38 * exp(-d * 4.5)) * body;',- ' float a = cap * body * (1.0 + 0.66 * fil);',- // Hue variance inside one curtain: broad warm/cool patches- // across its face, plus a per-sheet offset, so a stack of- // them is weather rather than one flat grey wash.- ' vec3 c = astraHueBreak(uColor, q, 0.34, 0.32);',- ' float hue = astraHash11(vSeed * 0.37) * 2.0 - 1.0;',- ' c *= 1.0 + hue * vec3(0.06, 0.012, -0.065);',- // Dither: a curtain is a wide, shallow alpha ramp over a- // smooth sky, which is exactly where 8-bit output bands.- ' a += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.006;',- ' if (a < 0.003) discard;',- ' gl_FragColor = vec4(c * uLight * (0.96 + 0.11 * fil),',- ' clamp(a, 0.0, 1.0));',- ].join('\n'),- transparent: true,- depthWrite: false,- side: THREE.DoubleSide,- });-}--/**- * Snow: flakes that fall slowly and WANDER, not white rain.- *- * A raindrop falls at 9 m/s down a straight line; a flake falls at well- * under one and its horizontal path is a curve that goes nowhere in- * particular. That wander is the entire difference between snow and- * white rain, so it is not decoration here — every flake carries its- * own two swing frequencies and phases, and the CPU mirror runs the- * same curve the vertex shader does. The second half is the lens:- * flakes nearer than the focus distance are drawn BIGGER and softer,- * with their alpha divided by the same factor, because a camera- * focussed on the valley cannot hold a flake at arm's length and a- * field of uniformly crisp dots reads as a particle system.- *- * BLENDING: ORDINARY, for the same reason as the rain — snow scatters,- * and white added to a bright winter frame has nowhere to go.- *- * @param {object} [opts]- * `extent` metres square the field covers (default 40); `height`- * metres it stands (default 18); `rate` flakes reaching the ground- * per second across the whole field (default 260 — the count is- * solved from it and the fall time, so there is no particle budget to- * guess); `size` flake diameter in metres (default 0.035, which also- * sets how fast they fall and how far they swing); `drift` wind in- * m/s, a number (along +x), [dx, dz] or a THREE.Vector2/3 (default- * [0.35, 0] — snow drifts, it does not race); `color` THREE.Color or- * hex, the flake albedo the scene's light multiplies (default a cold- * white that takes the fog's hue); `seed` PRNG seed (default 9).- * @returns {THREE.Group} Named `Snowfall`, its foot on y = 0, with- * `userData.update(t)` and `userData.sample(i, t)` returning flake i's- * group-local position — the CPU mirror of the vertex shader.- */-export function makeSnowfall(opts = {}) {- const extent = Math.max(2, opts.extent === undefined ? 40 : opts.extent);- const height = Math.max(1, opts.height === undefined ? 18 : opts.height);- const rate = Math.max(1, opts.rate === undefined ? 260 : opts.rate);- const size = Math.max(0.002,- opts.size === undefined ? 0.035 : opts.size);- const d = readWind(opts.drift, [0.35, 0], 'makeSnowfall drift');- const drift = new THREE.Vector2(d.x, d.z);- const color = new THREE.Color(- opts.color === undefined ? 0xf2f7ff : opts.color);- const rnd = lehmer(opts.seed === undefined ? 9 : opts.seed);- const autoTint = opts.color === undefined ? color : null;-- // A bigger flake carries more mass per unit drag, so it falls- // faster and swings wider; both are read off `size`.- const fall = 0.45 + 6 * size;- const wob = 0.22 + 4.5 * size;- const half = extent * 0.5;- const count = Math.round(Math.min(9000,- Math.max(120, rate * (height / fall))));-- const pos = new Float32Array(count * 3);- const flake = new Float32Array(count * 4);- const swing = new Float32Array(count * 4);- let scale = 0;- for (let i = 0; i < count; i++) {- pos[i * 3] = (rnd() - 0.5) * extent;- pos[i * 3 + 1] = rnd() * height;- pos[i * 3 + 2] = (rnd() - 0.5) * extent;- flake[i * 4] = 0.6 + 0.9 * rnd();- flake[i * 4 + 1] = 0.65 + 0.8 * rnd();- flake[i * 4 + 2] = 0.55 + 0.6 * rnd();- flake[i * 4 + 3] = rnd();- swing[i * 4] = 0.35 + 0.95 * rnd();- swing[i * 4 + 1] = rnd() * 6.283;- swing[i * 4 + 2] = 0.35 + 0.95 * rnd();- swing[i * 4 + 3] = rnd() * 6.283;- scale = Math.max(scale, flake[i * 4]);- }- const focus = Math.max(2, extent * 0.10);- const bokeh = 2.4;- // The wrap keeps every flake inside the box, so the only thing the- // sphere has to add is the widest a quad can be drawn.- const radius = Math.hypot(half * Math.SQRT2, height)- + size * scale * (1 + bokeh) * Math.SQRT1_2;-- const geom = instancedQuad(count, 1, 1, radius * 1.02);- geom.setAttribute('aPos', new THREE.InstancedBufferAttribute(pos, 3));- geom.setAttribute('aFlake', new THREE.InstancedBufferAttribute(flake, 4));- geom.setAttribute('aSwing', new THREE.InstancedBufferAttribute(swing, 4));-- const mesh = new THREE.Mesh(geom, snowMaterial({- color, size, fall, wob, drift, extent, half, height, focus, bokeh,- }));- mesh.name = 'Snowflakes';- mesh.renderOrder = 3;- const g = new THREE.Group();- g.name = 'Snowfall';- g.add(mesh);- keepOutOfDepthPasses(g);- _litByScene(mesh, autoTint);- g.userData.update = g.userData.tick = (t) => tickShaders(g, t);- g.userData.sample = (i, t) => {- const k = Math.min(count - 1, Math.max(0, i | 0));- const y = pos[k * 3 + 1] - fall * flake[k * 4 + 1] * t;- return new THREE.Vector3(- _wrap(pos[k * 3] + drift.x * t- + wob * wobX(swing[k * 4], swing[k * 4 + 1], t),- extent, half),- y - Math.floor(y / height) * height,- _wrap(pos[k * 3 + 2] + drift.y * t- + wob * wobZ(swing[k * 4 + 2], swing[k * 4 + 3], t),- extent, half));- };- return attachDisposal(g, snapshotResources(g));-}--/** Slow fall, wandering path, and a lens that cannot hold the near ones. */-function snowMaterial(cfg) {- return makeShaderMaterial({- name: 'SnowflakeField',- uniforms: {- uTime: { value: 0 },- uColor: { value: cfg.color },- uLight: { value: new THREE.Color(1, 1, 1) },- uAlpha: { value: 0.85 },- uSize: { value: cfg.size },- uFall: { value: cfg.fall },- uWob: { value: cfg.wob },- uDrift: { value: cfg.drift },- uExtent: { value: cfg.extent },- uHalf: { value: cfg.half },- uHeight: { value: cfg.height },- uFocus: { value: cfg.focus },- uBokeh: { value: cfg.bokeh },- },- varyings: 'varying vec2 vUv; varying float vBright;'- + ' varying float vBlur; varying float vFade;'- + ' varying float vHue; varying float vTumble;',- vertexHead: 'attribute vec3 aCorner; attribute vec3 aPos;'- + ' uniform float uTime;'- + ' attribute vec4 aFlake; attribute vec4 aSwing;'- + ' uniform float uSize; uniform float uFall;'- + ' uniform float uWob; uniform vec2 uDrift;'- + ' uniform float uExtent; uniform float uHalf;'- + ' uniform float uHeight; uniform float uFocus;'- + ' uniform float uBokeh;\n' + _WOB_GLSL,- vertexMain: [- ' vUv = uv;',- ' vBright = aFlake.z;',- // aFlake.w was spare. A field of flakes at ONE white is the- // give-away that they came out of a loop: real ones catch- // the sun or only the sky, and they TUMBLE — face, edge,- // face — which is a slow breath of brightness, not a- // sparkle. Both ride this one per-flake number.- ' vHue = aFlake.w * 2.0 - 1.0;',- ' vTumble = 0.74 + 0.26 * abs(sin(uTime * (0.7 + aFlake.w)',- ' + aFlake.w * 6.283));',- // Its own fall speed, so the field never descends as a- // sheet, and its own two swings, which is the wander.- ' float y = mod(aPos.y - uFall * aFlake.y * uTime, uHeight);',- ' vec2 w = vec2(astraVeilWobX(aSwing.x, aSwing.y, uTime),',- ' astraVeilWobZ(aSwing.z, aSwing.w, uTime));',- ' vec2 xz = mod(aPos.xz + uDrift * uTime + uWob * w + uHalf,',- ' uExtent) - uHalf;',- ' vec3 p = vec3(xz.x, y, xz.y);',- // Nearer than the focus distance: bigger and blurrier, the- // way a lens focussed on the valley renders arm's length.- ' vBlur = 1.0 - smoothstep(0.0, uFocus,',- ' length(p - uCameraLocal));',- ' float s = uSize * aFlake.x * (1.0 + uBokeh * vBlur);',- ' vec3 camR = uCameraRight;',- ' vec3 camU = uCameraUp;',- ' transformed = p + camR * (aCorner.x * s)',- ' + camU * (aCorner.y * s);',- ' float vy = y / uHeight;',- ' vFade = smoothstep(0.0, 0.05, vy)',- ' * (1.0 - smoothstep(0.86, 1.0, vy))',- ' * (1.0 - smoothstep(0.74, 1.02, length(xz) / uHalf));',- ].join('\n'),- fragmentHead: 'uniform vec3 uColor; uniform vec3 uLight;'- + ' uniform float uAlpha;',- fragmentMain: [- ' float d = length(vUv - 0.5) * 2.0;',- ' if (d > 1.0) discard;',- // In focus it is a disc with a soft rim; out of focus it is- // a smear, and the same factor takes its alpha away.- ' float core = 1.0 - smoothstep(mix(0.42, 0.0, vBlur),',- ' 1.0, d);',- ' float a = uAlpha * vBright * vFade * core * vTumble',- ' / (1.0 + 2.4 * vBlur);',- ' a += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.006;',- ' if (a < 0.004) discard;',- // Snow is white the way paper is white: the ones the sun- // reaches are warm, the ones only the sky reaches are blue.- ' vec3 c = uColor * (1.0 + vHue * vec3(0.055, 0.008, -0.06));',- ' gl_FragColor = vec4(c * uLight, clamp(a, 0.0, 1.0));',- ].join('\n'),- transparent: true,- depthWrite: false,- side: THREE.DoubleSide,- });-}--/**- * Dust or pollen hanging in a shaft of light.- *- * What this buys is the statement that the air is not empty — the thing- * a light shaft, a barn interior or a summer meadow has and a rendered- * one never does. The constraint is that motes must not read as- * particles: they hang almost still (a few centimetres a second of- * settle, a bounded wander that never leaves the stated volume) and- * they TWINKLE, because a speck of matter is a flake with faces, and- * what the eye actually catches is the flash as one comes round to the- * light. A speck at constant brightness reads as a dot on the lens.- *- * BLENDING: ORDINARY, though a mote is the one of the three that is- * arguably light. It is a speck of MATTER, and additive specks over a- * sunlit wall clip; the glint rides alpha up to a near-white instead.- *- * @param {object} [opts]- * `extent` metres square the volume covers (default 6); `height`- * metres it stands (default 4); `count` specks (default 320 — a- * shaft of light holds surprisingly few, and a fog of them reads as- * noise); `size` speck diameter in metres (default 0.024 — it is the- * glint that has to be visible, not the grain); `color` THREE.Color- * or hex (default a warm near-white — the dust's own colour, spread- * ochre to grey per speck and then multiplied by the light actually- * reaching the volume, lamps included); `seed` PRNG seed- * (default 13).- * @returns {THREE.Group} Named `Motes`, its foot on y = 0, with- * `userData.update(t)`, `userData.sample(i, t)` giving speck i's- * group-local position and `userData.volume` the box it stays in.- */-export function makeMotes(opts = {}) {- const extent = Math.max(0.5, opts.extent === undefined ? 6 : opts.extent);- const height = Math.max(0.3, opts.height === undefined ? 4 : opts.height);- const count = Math.round(Math.min(4000,- Math.max(8, opts.count === undefined ? 320 : opts.count)));- const size = Math.max(0.001,- opts.size === undefined ? 0.024 : opts.size);- const color = new THREE.Color(- opts.color === undefined ? 0xfff2d8 : opts.color);- const rnd = lehmer(opts.seed === undefined ? 13 : opts.seed);-- const half = extent * 0.5;- // Dust does not fall so much as fail to stay up.- const settle = 0.035;- const wob = Math.min(0.35, extent * 0.12);- // Start inside the volume by the whole swing, so the wander can- // never carry a speck out of the box the caller was promised.- const inner = Math.max(0, half - wob);-- const pos = new Float32Array(count * 3);- const mote = new Float32Array(count * 4);- const swing = new Float32Array(count * 4);- let scale = 0;- for (let i = 0; i < count; i++) {- pos[i * 3] = (rnd() * 2 - 1) * inner;- pos[i * 3 + 1] = rnd() * height;- pos[i * 3 + 2] = (rnd() * 2 - 1) * inner;- mote[i * 4] = 0.5 + 1.5 * rnd();- mote[i * 4 + 1] = 0.5 + 1.3 * rnd();- mote[i * 4 + 2] = rnd() * 6.283;- mote[i * 4 + 3] = 0.55 + 0.6 * rnd();- swing[i * 4] = 0.12 + 0.34 * rnd();- swing[i * 4 + 1] = rnd() * 6.283;- swing[i * 4 + 2] = 0.12 + 0.34 * rnd();- swing[i * 4 + 3] = rnd() * 6.283;- scale = Math.max(scale, mote[i * 4]);- }- const radius = Math.hypot(half * Math.SQRT2, height)- + size * scale * 1.2 * Math.SQRT1_2;-- const geom = instancedQuad(count, 1, 1, radius * 1.02);- geom.setAttribute('aPos', new THREE.InstancedBufferAttribute(pos, 3));- geom.setAttribute('aMote', new THREE.InstancedBufferAttribute(mote, 4));- geom.setAttribute('aSwing', new THREE.InstancedBufferAttribute(swing, 4));-- const mesh = new THREE.Mesh(geom, moteMaterial({- color, size, settle, wob, height,- }));- mesh.name = 'DustMotes';- mesh.renderOrder = 3;- const g = new THREE.Group();- g.name = 'Motes';- g.add(mesh);- keepOutOfDepthPasses(g);- // No fog tint for dust: motes are LIT matter close to the camera,- // not haze at distance, and the colour is the caller's statement- // about the light they hang in.- _litByScene(mesh, null);- g.userData.update = g.userData.tick = (t) => tickShaders(g, t);- g.userData.volume = { extent, height };- g.userData.sample = (i, t) => {- const k = Math.min(count - 1, Math.max(0, i | 0));- const y = pos[k * 3 + 1] - settle * t;- return new THREE.Vector3(- pos[k * 3] + wob * wobX(swing[k * 4], swing[k * 4 + 1], t),- y - Math.floor(y / height) * height,- pos[k * 3 + 2] + wob * wobZ(swing[k * 4 + 2],- swing[k * 4 + 3], t));- };- return attachDisposal(g, snapshotResources(g));-}--/** Near-still specks that flash as their faces come round. */-function moteMaterial(cfg) {- return makeShaderMaterial({- name: 'DustMotes',- uniforms: {- uTime: { value: 0 },- uColor: { value: cfg.color },- uLight: { value: new THREE.Color(1, 1, 1) },- uAlpha: { value: 0.95 },- uSize: { value: cfg.size },- uSettle: { value: cfg.settle },- uWob: { value: cfg.wob },- uHeight: { value: cfg.height },- uSpin: { value: 1.6 },- },- varyings: 'varying vec2 vUv; varying float vBright;'- + ' varying float vTw; varying float vFade;'- + ' varying float vHue;',- vertexHead: 'attribute vec3 aCorner; attribute vec3 aPos;'- + ' uniform float uTime;'- + ' attribute vec4 aMote; attribute vec4 aSwing;'- + ' uniform float uSize; uniform float uSettle;'- + ' uniform float uWob; uniform float uHeight;'- + ' uniform float uSpin;\n' + _WOB_GLSL,- vertexMain: [- ' vUv = uv;',- ' vBright = aMote.w;',- // Dust is not white. A shaft holds grain, pollen, ash and- // fibre at once, and their spread runs ochre to cool grey —- // one flat tint is the tell that this is a particle system.- ' vHue = astraHash11(aMote.z * 4.7 + aMote.y) * 2.0 - 1.0;',- ' float y = mod(aPos.y - uSettle * uTime, uHeight);',- ' vec3 p = vec3(',- ' aPos.x + uWob * astraVeilWobX(aSwing.x, aSwing.y, uTime),',- ' y,',- ' aPos.z + uWob * astraVeilWobZ(aSwing.z, aSwing.w,',- ' uTime));',- // A mote is a flake with faces: it flashes when one comes- // round to the light and all but vanishes edge-on.- ' vTw = pow(abs(sin(uTime * uSpin * aMote.y + aMote.z)), 5.0);',- ' float s = uSize * aMote.x * (0.45 + 0.75 * vTw);',- ' vec3 camR = uCameraRight;',- ' vec3 camU = uCameraUp;',- ' transformed = p + camR * (aCorner.x * s)',- ' + camU * (aCorner.y * s);',- ' float vy = y / uHeight;',- ' vFade = smoothstep(0.0, 0.06, vy)',- ' * (1.0 - smoothstep(0.90, 1.0, vy));',- ].join('\n'),- fragmentHead: 'uniform vec3 uColor; uniform vec3 uLight;'- + ' uniform float uAlpha;',- fragmentMain: [- ' float d = length(vUv - 0.5) * 2.0;',- ' if (d > 1.0) discard;',- // A bright centre inside a wide soft skirt, not a disc with- // an edge: a speck at this size is a point spread, and a- // hard rim is what makes a field of them read as a dot- // screen printed on the lens.- ' float core = (1.0 - smoothstep(0.16, 1.0, d))',- ' * (0.55 + 0.45 * (1.0 - smoothstep(0.0, 0.42, d)));',- ' float a = uAlpha * vBright * vFade * core',- ' * (0.18 + 0.82 * vTw);',- ' a += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.006;',- ' if (a < 0.004) discard;',- ' vec3 c = uColor * (1.0 + vHue * vec3(0.10, 0.015, -0.14));',- ' gl_FragColor = vec4(c * uLight * (0.78 + 0.44 * vTw),',- ' clamp(a, 0.0, 1.0));',- ].join('\n'),- transparent: true,- depthWrite: false,- side: THREE.DoubleSide,- });-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/water.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/water.jsdeleted file mode 100644index 5d408395..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/water.js+++ /dev/null@@ -1,409 +0,0 @@-/**- * Reflective water plane: the addon Water shader with a procedural- * wave-normal map (npm three ships no waternormals.jpg, so- * `makeWaterNormals()` synthesizes a deterministic tiling one).- * Every Water instance re-renders the WHOLE scene per frame:- * contract is ONE water plane, never alongside a Reflector floor.- * Stills freeze `uniforms.time`; animate via `mesh.userData.update(t)`.- *- * The addon's fragment shader is REGRADED here (see `_regrade`): its- * stock look is a 30%-reflective milk with a flat +0.1 veil, which on- * our pipeline (ACES, exposure 1.0) renders a pool as pale plastic —- * measured 2026-09-01, a still pool read mean_lum 0.73 at BOTH a steep- * and a grazing view, i.e. no Fresnel at all.- */--import * as THREE from 'three';-import { attachDisposal, snapshotResources } from './lifecycle.js';-import { Water } from 'three/addons/objects/Water.js';-import { makeLightProbe, planarCapture, sunVector } from './shader.js';--// Battery-graded freeze point: mid-phase, waves clearly formed.-const FROZEN_TIME = 7.3;--// Default sun matches the day rig in lib/environment.js (azimuth 35,-// elevation 48, same axis convention), so a scene that forgot to pass-// sunDir still gets specular broadly agreeing with the shipped light.-const _DAY_SUN = sunVector(35, 48);---/**- * Synthesize the tiling wave-normal DataTexture the Water shader- * needs (npm three ships no waternormals.jpg). A sum of integer-- * frequency sines guarantees a seamless wrap; finite differences use- * a fixed UV-space strength, independent of texture resolution.- *- * @param {number} [size] Texture width and height in px (default 256).- * @returns {THREE.DataTexture} RGBA, RepeatWrapping, needsUpdate set.- */-export function makeWaterNormals(size = 256, opts = {}) {- // Tiling heightfield: sum of integer-frequency sines.- const h = new Float32Array(size * size);- // Eight pure tones read as CORDUROY at a grazing angle — it is- // the periodicity of the SET that shows, not any one wave. The- // broadband set spreads 28 directions at 1/f^2 and kills it, at- // the cost of a calmer surface; only wide water needs it.- const waves = opts.broadband ? [- [1, 1, 1.3000, 5.34], [0, -5, 0.1040, 3.33],- [1, -1, 1.3000, 3.01], [4, -1, 0.1529, 4.21],- [2, -4, 0.1300, 1.12], [-3, -1, 0.2600, 2.37],- [1, -5, 0.1000, 3.75], [4, 4, 0.0812, 4.83],- [-2, 2, 0.3250, 1.58], [-6, 3, 0.0578, 6.14],- [-3, -5, 0.0765, 4.67], [-2, 1, 0.5200, 3.62],- [4, -5, 0.0634, 5.34], [-6, -6, 0.0361, 5.28],- [-3, 0, 0.2889, 4.61], [-5, 2, 0.0897, 0.28],- [-1, 2, 0.5200, 6.18], [-1, 0, 2.6000, 2.22],- [-1, 3, 0.2600, 1.89], [1, -2, 0.5200, 5.29],- [-4, -5, 0.0634, 3.96], [2, -5, 0.0897, 2.32],- [-2, 6, 0.0650, 5.36], [2, -1, 0.5200, 5.77],- [-2, 0, 0.6500, 0.05], [5, -3, 0.0765, 2.56],- [-5, -5, 0.0520, 4.68], [1, 0, 2.6000, 0.65]- ] : [- [3, 1, 1.0, 0.0], [5, 2, 0.7, 1.3], [2, 4, 0.55, 2.1],- [7, 3, 0.4, 4.2], [4, 6, 0.35, 0.7], [9, 5, 0.25, 3.3],- [11, 8, 0.18, 5.1], [6, 10, 0.15, 2.6],- ];- for (let y = 0; y < size; y++) {- for (let x = 0; x < size; x++) {- const u = (x / size) * Math.PI * 2;- const v = (y / size) * Math.PI * 2;- let s = 0;- for (const [fx, fy, a, p] of waves) {- s += a * Math.sin(fx * u + fy * v + p);- }- h[y * size + x] = s;- }- }- // Finite-difference normals -> RGB.- const data = new Uint8Array(size * size * 4);- // A central difference spans 2/size in UV. Preserve the graded 256px- // slopes while changing resolution; without the texel-spacing factor,- // doubling quality halved every wave slope and flattened the water.- const amp = 2.2 * (size / 256);- for (let y = 0; y < size; y++) {- for (let x = 0; x < size; x++) {- const xm = (x - 1 + size) % size, xp = (x + 1) % size;- const ym = (y - 1 + size) % size, yp = (y + 1) % size;- const dx = (h[y * size + xp] - h[y * size + xm]) * amp;- const dy = (h[yp * size + x] - h[ym * size + x]) * amp;- const inv = 1 / Math.hypot(dx, dy, 1);- const i = (y * size + x) * 4;- data[i] = (-dx * inv * 0.5 + 0.5) * 255;- data[i + 1] = (-dy * inv * 0.5 + 0.5) * 255;- data[i + 2] = (inv * 0.5 + 0.5) * 255;- data[i + 3] = 255;- }- }- const tex = new THREE.DataTexture(data, size, size, THREE.RGBAFormat);- tex.wrapS = tex.wrapT = THREE.RepeatWrapping;- // DataTexture defaults to NearestFilter with no mipmaps, which prints- // a fine dither over water seen from any distance. Only visible once- // the wave size stopped moireing over the top of it.- tex.minFilter = THREE.LinearMipmapLinearFilter;- tex.magFilter = THREE.LinearFilter;- tex.generateMipmaps = true;- tex.anisotropy = 16;- tex.needsUpdate = true;- return tex;-}--// The regraded tail of the addon's fragment shader, spliced in over the-// range `vec2 distortion = ...` .. `gl_FragColor = ...` (see `_regrade`).-const _TAIL = /* glsl */`- // ---- 3dcode regrade ------------------------------------------------- // The addon scales its screen-space reflection offset by 1/distance- // with no ceiling, so water 3 m from the eye samples the mirror ONE- // FULL FRAME away (0.33 * distortionScale) and prints slivers of sky- // through the near surface. Cap the offset at the value the far half- // already uses; beyond ~1/maxDistort metres nothing changes at all.- vec2 distortion = surfaceNormal.xz- * min( maxDistort, 0.001 + 1.0 / distance ) * distortionScale;- vec3 reflectionSample = vec3( texture2D( mirrorSampler,- mirrorCoord.xy / mirrorCoord.w + distortion ) );-- // Fresnel: the addon hardcodes rf0 = 0.3, so its water is 30%- // mirror even looked straight down into — the single reason a stock- // Water pool reads as pale milk. Dielectric water is F0 = 0.02 and- // only turns mirror at grazing, which is what gives a body of water- // its dark near half and bright far half.- float theta = max( dot( eyeDirection, surfaceNormal ), 0.0 );- float reflectance = rf0 + ( 1.0 - rf0 ) * pow( 1.0 - theta, 5.0 );-- // A body colour with a HUE FIELD, not one flat value: a slow read of- // the same wave map drifts the mix between the deep tone and a- // shallower, greener one. The period is turbScale METRES (set from- // the plane's extent), not a constant — pinned to one, a pond samples- // a single texel of the field and the whole basin comes out one- // colour, which is the flatness this term exists to break.- vec3 turbSample = texture2D( normalSampler,- worldPosition.xz / turbScale- + vec2( time / 190.0, time / 230.0 ) ).rgb;- float turbid = clamp( 0.5 + ( turbSample.x - 0.5 ) * 1.3, 0.0, 1.0 );- float wMag = max( max( waterColor.r, waterColor.g ), waterColor.b );- // The deep tone gets a dark NEUTRAL floor. The graded 0x0e3f5c has a- // red channel of 0.0045 linear — 4% of its blue — and a body with one- // dead channel reads electric rather than deep (measured at night:- // mean RGB 0.034/0.140/0.276, saturation 0.85). Real water always- // carries some neutral scatter, and the floor is still under the- // 0.02 the aesthetic brief calls the bottom of a sane albedo.- vec3 body = mix( max( waterColor * 0.62, vec3( 0.015, 0.022, 0.030 ) ),- waterColor * 1.9 + vec3( 0.05, 0.30, 0.16 ) * wMag, turbid );-- // Lit as the dielectric it is: sky ambient so water in shadow is- // never black, plus the key light's real irradiance, shadowed by the- // scene. Both come from the scene itself (see makeOcean's sniff).- float shade = getShadowMask();- float lambert = max( dot( sunDirection, surfaceNormal ), 0.0 );- vec3 bodyLit = body * ( ambientColor + keyColor * lambert * shade );- // Backlit crests glow — the one cue that reads as TRANSLUCENT, and- // it only fires when the eye is looking into the key light.- float back = pow( max( 0.0, dot( eyeDirection, -sunDirection ) ), 3.0 );- bodyLit += body * keyColor * back * 0.55 * shade;-- // Glitter is ADDITIVE. The addon gates its whole specular behind- // the mirror sample, so a sun track can only appear where the- // mirror was already bright — i.e. never on dark water, which is- // exactly where a sun track is the brightest thing in a frame.- // Two lobes: a tight glint on the crests, a broad sheen holding them- // together. Peak ~2.6, inside the 1.5-4 a bloom pass takes cleanly.- vec3 sunReflect = normalize( reflect( -sunDirection, surfaceNormal ) );- float glint = max( 0.0, dot( eyeDirection, sunReflect ) );- float keyGain = max( max( keyColor.r, keyColor.g ), keyColor.b ) * 3.14159265 / 5.4;- vec3 glitter = sunColor * glitterScale * keyGain * shade- * ( 0.3 + 0.7 * reflectance )- * ( pow( glint, 420.0 ) * 2.6 + pow( glint, 28.0 ) * 0.22 );-- vec3 outgoingLight =- mix( bodyLit, reflectionSample, reflectance ) + glitter;- // A mirror this smooth bands in 8 bits; a sub-LSB of hash noise in- // linear costs one mad and removes it.- float dth = fract( sin( dot( gl_FragCoord.xy,- vec2( 12.9898, 78.233 ) ) ) * 43758.5453 );- outgoingLight += ( dth - 0.5 ) * 0.0022;- gl_FragColor = vec4( outgoingLight, alpha );`;--/**- * Splice `_TAIL` over the addon shader's own shading tail and declare the- * uniforms it adds. Version-tolerant: if either anchor is missing (a- * three release rewrote Water.js) the material is left exactly as the- * addon built it and the caller gets a warning, never a broken shader.- *- * @param {THREE.ShaderMaterial} material The Water material.- * @returns {boolean} true when the regrade was applied.- */-function _regrade(material) {- const src = material.fragmentShader;- const END = 'gl_FragColor = vec4( outgoingLight, alpha );';- const a = src.indexOf('vec2 distortion =');- const b = src.indexOf(END);- if (a < 0 || b < 0 || b < a) {- console.warn(- 'makeOcean: this three build\'s Water shader does not carry the '- + 'anchors the 3dcode regrade splices over — shipping the addon '- + 'look unchanged (pale, no Fresnel).');- return false;- }- material.fragmentShader =- src.slice(0, a).replace(- 'uniform vec3 waterColor;',- 'uniform vec3 waterColor;\n\t\t\t\tuniform vec3 ambientColor;'- + '\n\t\t\t\tuniform vec3 keyColor;\n\t\t\t\tuniform float rf0;'- + '\n\t\t\t\tuniform float glitterScale;'- + '\n\t\t\t\tuniform float maxDistort;'- + '\n\t\t\t\tuniform float turbScale;')- + _TAIL + src.slice(b + END.length);- return true;-}--/**- * Read the scene's visible lighting on each render and point the- * water's key light at it. Water is built before the scene exists, so- * without this a night pool glitters for a noon sun in a colour nothing- * else in the frame is lit by — the failure the aesthetic brief calls- * "hardcoded light colours".- *- * Only uniforms the caller did NOT pin are touched.- */-function _readScene(lights, uniforms, pinned) {- const { sun: key, sunDirection, ambient, sky } = lights;- // three's Lambert BRDF divides irradiance by PI; the water body is a- // Lambert term too, so the same 1/PI is what puts it on the same scale- // as every MeshStandardMaterial around it.- const INV_PI = 1 / Math.PI;- uniforms.keyColor.value.setRGB(0, 0, 0);- if (!pinned.sunColor) uniforms.sunColor.value.setRGB(0, 0, 0);- if (key) {- uniforms.keyColor.value.copy(key.color)- .multiplyScalar(Math.min(6, key.intensity) * INV_PI);- if (!pinned.sunColor) {- // HUE only: the glitter lobes are graded artistic values (a sun- // disc we do not model), so they must not be scaled by whatever- // watts the rig runs at — only tinted by its colour.- const c = key.color;- const peak = Math.max(c.r, c.g, c.b, 1e-4);- uniforms.sunColor.value.copy(c).multiplyScalar(1 / peak);- }- if (!pinned.sunDir) {- uniforms.sunDirection.value.copy(sunDirection);- }- }- if (!pinned.ambient) {- const t = uniforms.ambientColor.value;- // Hemisphere and ambient irradiance add, as they do on nearby PBR- // surfaces. Selecting one dropped fill light whenever a sky rig existed.- t.copy(ambient).add(sky).multiplyScalar(INV_PI);- t.r = Math.min(t.r, 1); t.g = Math.min(t.g, 1); t.b = Math.min(t.b, 1);- }-}--/**- * Build the scene's ONE reflective water plane (XZ, faces +Y): the flat,- * normal-mapped option for calm or distant water. Visible waves are- * ocean.js's makeOceanSurface, which owns "ocean".- * Returned mesh is at y = 0; set `position.y` to the water level.- * Defaults are graded values — keep them unless the brief says not to.- *- * @param {number} width X extent in metres.- * @param {number} depth Z extent in metres.- * @param {object} [opts]- * `sunDir` normalized THREE.Vector3 toward the sun — pass the SAME- * direction the key light uses so the glitter track agrees with the- * shadows (default: the day rig's axis);- * `waterColor` hex (default 0x0e3f5c);- * `sunColor` hex (default 0xffffff);- * `distortionScale` reflection wobble (default 2.8);- * `rttSize` reflection render-target px (default 512);- * `size` wave-pattern density uniform (default: scaled to the plane);- * `waterNormals` texture override (default `makeWaterNormals(256)`);- * `fog` fold scene fog into the shader (default true);- * `rf0` Fresnel reflectance head-on (default 0.02, real water);- * `glitter` sun-track strength, 0 kills it (default 1);- * `ambient` hex sky ambient for the water BODY (default: read off the- * scene's visible hemisphere/ambient light).- * @returns {THREE.Mesh} The Water mesh, rotated flat, named 'Ocean',- * with `userData.update(t)` driving the wave phase for `tick`.- */-/** Water wider than this gets the broadband (28-direction) wave set. */-export const BROADBAND_EXTENT_M = 300;--export function makeOcean(width, depth, opts = {}) {- const sunDir =- (opts.sunDir ? opts.sunDir.clone() : _DAY_SUN.clone()).normalize();- // 512, not 256: a 256px mirror stretched across half a 1280x720 frame- // tears into stair-stepped blocks at grazing angles — 9 confirmed- // sightings across the 2026-08-04 gallery audit. Cost is one extra- // scene pass at 4x the pixels, still the cheapest thing in the frame.- const rtt = opts.rttSize || 512;- const _extent = Math.max(width, depth);- const water = new Water(new THREE.PlaneGeometry(width, depth), {- textureWidth: rtt,- textureHeight: rtt,- waterNormals: opts.waterNormals- // 300 m, not 1500: a 380 m and a 440 m storm sea (two lighthouse runs,- // 2026-09-09) read as "a checkerboard of white crescents" from every- // overview and the establishing shot — the eight-tone set's own period- // shows wherever the water is wide enough to be seen at a grazing angle,- // and a scene's sea is exactly that. Pools and ponds keep the lively set.- || makeWaterNormals(256, { broadband: _extent > BROADBAND_EXTENT_M }),- sunDirection: sunDir,- sunColor: opts.sunColor === undefined ? 0xffffff : opts.sunColor,- waterColor:- opts.waterColor === undefined ? 0x0e3f5c : opts.waterColor,- distortionScale: opts.distortionScale === undefined ?- 2.8 : opts.distortionScale,- fog: opts.fog === undefined ? true : opts.fog,- });- water.rotation.x = -Math.PI / 2;- water.name = 'Ocean';- const uniforms = water.material.uniforms;- let ownedTarget = null;- let disposed = false;- uniforms.time.value = FROZEN_TIME;- // The shader samples the normals at worldPosition.xz * size / 103, so- // one wave period is ~103/size metres. Hold that at a twelfth of the- // plane and the graded 6 falls out at 200 m while a 2800 m harbor gets- // 0.44 — measured as the largest value that does not moire into radial- // stripes at grazing angles (0.70 stripes, 1.2 is unusable).- //- // The law used to be capped at 6, which froze it for anything under- // 206 m and gave an 18 m pool ONE wave period across the whole basin —- // an ocean swell in a bathtub (measured 2026-09-01: ripple contrast- // 1.22 at size 6, 2.51 at 30). The cap is now 30, the largest value- // that stays clean at a 1024 px grazing close-up; 68 speckles the far- // band into per-pixel sparkle. Big water is untouched.- const _autoSize = Math.min(30, 1236 / Math.max(_extent, 1));- uniforms.size.value = opts.size === undefined ? _autoSize : opts.size;- water.userData.update = (t) => {- uniforms.time.value = FROZEN_TIME + t;- };-- // ---- the regrade: our pipeline, and the scene's own light ---------- if (_regrade(water.material)) {- uniforms.rf0 = { value: opts.rf0 === undefined ? 0.02 : opts.rf0 };- uniforms.glitterScale =- { value: opts.glitter === undefined ? 1 : opts.glitter };- uniforms.maxDistort =- { value: opts.maxDistort === undefined ? 0.05 : opts.maxDistort };- // Two-and-a-bit patches of turbidity across the plane, never finer- // than 8 m: any tighter and the colour field starts competing with- // the waves instead of sitting under them.- uniforms.turbScale = { value: Math.max(8, _extent / 2.5) };- uniforms.keyColor = { value: new THREE.Color(1, 1, 1) };- // Fallback ambient ≈ the day rig's hemisphere at 1/PI, used only- // until `_readScene` finds the scene's real one on the first frame.- uniforms.ambientColor = {- value: opts.ambient === undefined- ? new THREE.Color(0.149, 0.215, 0.364)- : new THREE.Color(opts.ambient),- };- const pinned = {- sunColor: opts.sunColor !== undefined,- sunDir: opts.sunDir !== undefined,- ambient: opts.ambient !== undefined,- };- const base = water.onBeforeRender;- const readLights = makeLightProbe();- let first = true;- // Water's plane calculation assumes a rigid matrix; planarCapture- // supplies one while keeping Water's world-space textureMatrix (unlike- // Reflector, Water does not project mesh-local positions).- planarCapture(water, (renderer, scene, camera) => {- _readScene(readLights(scene), uniforms, pinned);- if (first) {- first = false;- // The mirror target is 8-bit LINEAR (three disables tone mapping- // and sRGB encoding when rendering to a non-sRGB target), so the- // bottom of its range quantises to a handful of steps: a night- // sky at ~0.002 linear reflects as two flat bands. Half-float- // costs 2 bytes a texel on ONE 512px target and removes it.- const mirror = uniforms.mirrorSampler.value;- if (renderer.extensions.has('EXT_color_buffer_float')- || renderer.extensions.has('EXT_color_buffer_half_float')) {- mirror.type = THREE.HalfFloatType;- }- }- if (ownedTarget) return base.call(water, renderer, scene, camera);- // Three keeps this target private. Capture only its own target- // on the first mirror draw, restoring the method even on error.- const setTarget = renderer.setRenderTarget;- renderer.setRenderTarget = function (target, ...args) {- if (target && target.texture === uniforms.mirrorSampler.value) ownedTarget = target;- return setTarget.call(this, target, ...args);- };- try {- return base.call(water, renderer, scene, camera);- } finally {- renderer.setRenderTarget = setTarget;- }- }, { skip: () => disposed });- }- const owned = snapshotResources(water);- if (!opts.waterNormals) owned.add(uniforms.normalSampler.value);- owned.add({ dispose() {- disposed = true;- if (ownedTarget) ownedTarget.dispose();- else uniforms.mirrorSampler.value.dispose();- ownedTarget = null;- } });- return attachDisposal(water, owned);-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/watermist.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/watermist.jsdeleted file mode 100644index a463aa35..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/watermist.js+++ /dev/null@@ -1,612 +0,0 @@-/**- * The air over moving water, and the droplets moving water throws.- *- * `makeWaterMist` is the veil that hangs over a river, a weir or a- * wake: thickest in the first hand's breadth above the surface, gone by- * a couple of metres, streaked ALONG the flow and scrolling downstream- * with it. `atmosphere.js` `makeHeightFog` is the same height profile- * in STILL air — evenly blotched, barely moving — and the two must not- * read alike, so everything here that costs anything goes into the- * motion: the streaks lie down the current, and the top of the bank- * runs ahead of its foot.- *- * `makeSpray` is the other half a wake or a waterfall foot needs and- * neither has today: the droplets thrown UP where water strikes, each- * on its own ballistic arc, stretched along its own motion so it reads- * as fast, and fading as it falls back.- *- * BLENDING — both are pale, both can appear in daylight, so both use- * ORDINARY blending. `makeShaderMaterial({ additive: true })` is for- * light that ADDS, and `godrays.js` measures what added light does to a- * bright frame: 12.8% of it blown past 0.97, and cutting the gain 3.6x- * still left 11.3%, because 0.94 plus anything visible clips. Mist does- * the opposite of adding — it SCATTERS, lowering the contrast behind- * it — and a droplet is an object, not a light.- *- * The mist is a field of soft cards, and the whole difficulty is that- * no card may be visible. Three things do that, and dropping any one- * of them puts the cards back in the frame. The structure a fragment- * shows comes from ONE noise field read at the fragment's own- * position, so overlapping cards agree and their sum along a view ray- * is a crude volume integral. Every card faces the camera squarely and- * is no wider than the bank is deep, so a ray crossing the bank meets- * a dozen of them rather than one — one card per pixel paints its own- * noise raw, and that ribbon IS the card. And their heights are packed- * toward the water, so a view from above integrates the profile- * instead of a single slice of it.- *- * Flow, height samples and ballistic gravity use group-local coordinates.- * Cards face the world camera under rotated, scaled or sheared parents;- * sunDir remains a world-space direction. Nonuniform scale changes apparent- * card size with view direction, while preserving local simulation units.- * These are transparent particles, without scene-depth soft intersections- * or collisions. Rotating the group also rotates its local gravity.- */--import * as THREE from 'three';-import { attachDisposal, snapshotResources } from './lifecycle.js';--import { lehmer } from './noise.js';-import { instancedQuad, makeShaderMaterial, readVec3, tickShaders, keepOutOfDepthPasses, glslLocalDir } from './shader.js';--// Free fall. It is written twice on purpose — in the vertex shader and-// in the CPU mirror `userData.sample` — so both read this one number.-const _G = 9.81;--/**- * The key light as a direction plus how much of it there is.- *- * Mist and spray are LIT things, not coloured ones: what they show is- * an albedo times what reaches them. The sun below the horizon delivers- * nothing, so the gain goes to zero there and the skylight term (the- * scene's own fog colour) is all that is left — which is what turns- * both of these dark at night without the caller saying so.- *- * @param {*} v A THREE.Vector3, an [x,y,z], or nothing.- * @returns {{dir: THREE.Vector3, gain: number}} Unit direction TOWARD- * the sun (default straight up, the neutral top-lit read for a- * caller with no rig to hand) and 0..1 for how far it has risen.- */-function toSun(v) {- const d = readVec3(v);- if (d.lengthSq() < 1e-8) return { dir: new THREE.Vector3(0, 1, 0), gain: 1 };- d.normalize();- // 0 at the horizon, full by ten degrees up: the last of the sun- // reddens and dims the scene's own lights long before this matters.- const gain = Math.min(1, Math.max(0, (d.y - 0.005) / 0.175));- return { dir: d, gain };-}--/** Downstream velocity as a unit direction in xz plus a speed. */-function toFlow(v) {- let x = 0.45;- let z = 0;- if (typeof v === 'number') {- x = v;- } else if (Array.isArray(v)) {- x = v[0] || 0;- z = (v.length > 2 ? v[2] : v[1]) || 0;- } else if (v && (v.isVector3 || v.isVector2)) {- x = v.x;- z = v.isVector3 ? v.z : v.y;- }- const speed = Math.hypot(x, z);- if (speed < 1e-5) return { dir: new THREE.Vector2(1, 0), speed: 0 };- return { dir: new THREE.Vector2(x / speed, z / speed), speed };-}--/**- * The mist that hangs over moving water — air, not a stack of cards.- *- * Density falls with height ABOVE THE WATER, not with camera distance,- * so a hull sits in it and a bank above it does not. Every card is- * faint; the per-card alpha is solved from how many of them a- * horizontal ray crosses, so `density` means the same thickness- * whatever `extent` and `height` make of the card count.- *- * @param {object} [opts]- * `extent` metres square the bank covers (default 14; full strength- * right across it and gone by its corners, so it draws no boundary- * of its own); `height` metres at which the mist is gone (default 2- * — mist over water is a low thing, and a tall one reads as- * weather); `density` how thick the bank is, 0 to 1 (default 0.5 a- * clear haze; 0.9 hides the far bank);- * `color` the medium's ALBEDO, THREE.Color or hex (default a pale- * blue-grey) — it is multiplied by the light that reaches the bank,- * never emitted, so keep it near white and let the scene colour it;- * `sunDir` THREE.Vector3 or [x,y,z] TOWARD the key light, from- * `sunRig().sunDir` (default +Y, top lit) — the bank scatters it- * FORWARD, so it burns looking into the sun and greys looking away,- * and it delivers nothing once the sun is down;- * `sunColor` THREE.Color or hex for that light (default a warm- * white); `drift` downstream velocity in m/s, a number (along +x), [dx, dz],- * [dx, dy, dz] or a THREE.Vector2/3 (default [0.45, 0]) — it sets- * both the direction the streaks lie in and how fast they travel;- * `heightAt` (x, z) => y water surface height, so the bank follows a- * sloping reach; `seed` PRNG seed (default 5).- * @returns {THREE.Group} Named `WaterMist`, its foot on y = 0 (or on- * `heightAt`), with `userData.update(t)` (also `tick(t)`) driving the drift. Move the- * group to move the bank.- */-export function makeWaterMist(opts = {}) {- const extent = Math.max(1, opts.extent === undefined ? 14 : opts.extent);- const top = Math.max(0.2, opts.height === undefined ? 2 : opts.height);- const density = Math.min(0.97, Math.max(0,- opts.density === undefined ? 0.5 : opts.density));- const color = new THREE.Color(- opts.color === undefined ? 0xdfeaf2 : opts.color);- const sun = toSun(opts.sunDir);- const sunColor = new THREE.Color(- opts.sunColor === undefined ? 0xfff2e0 : opts.sunColor);- const flow = toFlow(opts.drift);- const heightAt = opts.heightAt || null;- const rnd = lehmer(opts.seed === undefined ? 5 : opts.seed);-- // Cards no wider than the bank is deep. A ray that crosses the- // bank must meet SEVERAL of them or the one it meets paints its- // own noise raw, and a single card's pattern is a visible ribbon.- const cardW = Math.min(extent * 0.25,- Math.max(1, top * 1.1, extent / 22));- const cardH = top * 1.1;- const count = Math.round(Math.min(1200, Math.max(24,- 14 * (extent * extent) / (cardW * cardW))));- // Cards a horizontal ray crosses. Solving the per-card alpha from- // it keeps `density` the thickness of the BANK at any card count,- // and the constant pays back what the height profile, the wisps and- // the card envelope take. It rose from 9 to 16 when the card- // envelope was softened to kill the striping — a softer envelope- // spends more of every card, and `density` has to go on meaning the- // same thickness. Measured on the weir showcase against a- // mist-free control: the bank's own contribution over the wall came- // back to 5.3/255 where the hard-edged 9 gave 5.9.- const hits = Math.max(1, (count * cardW) / extent);- const alpha = Math.min(0.60,- 16.0 * (1 - Math.pow(1 - density, 1 / hits)));- // Wisps scale with the bank's own height, not with the reach: a- // pattern stretched to the extent reads as one printed backdrop.- const wisp = Math.min(Math.max(top * 1.2, 0.8), extent * 0.28);-- const puff = new Float32Array(count * 4);- const card = new Float32Array(count * 2);- const cols = Math.ceil(Math.sqrt(count));- let radius = 0;- for (let i = 0; i < count; i++) {- // A jittered grid, never a uniform draw: the clumps and holes a- // uniform draw leaves read as separate clouds, not one bank.- const gx = ((i % cols) + 0.5) / cols - 0.5;- const gz = (Math.floor(i / cols) + 0.5) / cols - 0.5;- const x = (gx + (rnd() - 0.5) / cols) * extent;- const z = (gz + (rnd() - 0.5) / cols) * extent;- const base = heightAt ? heightAt(x, z) : 0;- // Heights PACKED toward the water, because that is where the- // mist is: cards all at one height leave a view from above- // integrating a single slice of the profile.- const mid = base + top * 1.05 * Math.pow(rnd(), 1.6);- const s = 0.70 + 0.75 * rnd();- puff[i * 4] = x;- puff[i * 4 + 1] = z;- puff[i * 4 + 2] = base;- puff[i * 4 + 3] = mid;- card[i * 2] = s;- card[i * 2 + 1] = 0.80 + 0.5 * rnd();- radius = Math.max(radius, Math.hypot(x, mid, z)- + 0.5 * Math.hypot(cardW * s, cardH * card[i * 2 + 1]));- }- // position stays at zero for the AO pass, so the sphere is the only- // thing three can cull the field by; the margin covers the float32- // the attributes are read back at.- const geom = instancedQuad(count, 1, 1, radius * 1.02);- geom.setAttribute('aPuff', new THREE.InstancedBufferAttribute(puff, 4));- geom.setAttribute('aCard', new THREE.InstancedBufferAttribute(card, 2));-- const mesh = new THREE.Mesh(geom, mistMaterial({- color, alpha, top, extent, flow, cardW, cardH, wisp,- sun, sunColor, hits,- offset: new THREE.Vector2(rnd() * 96, rnd() * 96),- }));- mesh.name = 'MistCards';- mesh.renderOrder = 2;- const g = new THREE.Group();- g.name = 'WaterMist';- g.add(mesh);- g.userData.update = g.userData.tick = (t) => tickShaders(g, t);- return attachDisposal(keepOutOfDepthPasses(g), snapshotResources(g));-}--/** Camera-facing cards, all reading one scrolling field of air. */-function mistMaterial(cfg) {- return makeShaderMaterial({- name: 'WaterMistCards',- uniforms: {- // Declared and bound HERE as well as by shader.js, because the- // static GLSL audit reads one FILE at a time: the dither line- // below carries `gl_FragCoord`, which is what makes the audit- // collect the string at all, and it then sees a file that reads- // uTime without ever declaring or binding it. godrays.js- // carries the same pair for the same reason.- uTime: { value: 0 },- uColor: { value: cfg.color },- uAlpha: { value: cfg.alpha },- uTop: { value: cfg.top },- // Under half the height is the e-fold, so the first hand's- // breadth over the water carries most of the extinction.- uScale: { value: cfg.top * 0.45 },- uFreq: { value: 1 / cfg.wisp },- uFlow: { value: cfg.flow.dir },- uSpeed: { value: cfg.flow.speed },- uSize: { value: new THREE.Vector2(cfg.cardW, cfg.cardH) },- uRadius: { value: cfg.extent * 0.5 },- // Metres downstream per metre of height.- uShear: { value: cfg.top * 0.9 },- uOffset: { value: cfg.offset },- uSunDir: { value: cfg.sun.dir },- uSunColor: { value: cfg.sunColor },- // Skylight is the scene's OWN fog colour, lifted: the fog- // is the sky seen through a kilometre of it and the bank is- // a metre away, so it arrives brighter than the horizon.- uSkyGain: { value: 1.28 },- // Forward-scattered sun at its peak, held UNDER the sky- // term: a bank that out-runs the sky reads as a lamp.- uSunGain: { value: 0.75 * cfg.sun.gain },- // Dither, PER CARD. A dozen independent draws of it sum as- // a random walk, so the amplitude has to be divided by the- // root of the stack depth or the veil comes out visibly- // grainy — measured: 0.004 flat put a coarse speckle right- // across the bank at 85 cards deep.- uDither: { value: 0.010 / Math.sqrt(Math.max(1, cfg.hits)) },- },- varyings: 'varying vec2 vUv; varying vec3 vP;'- + ' varying float vBase; varying vec3 vWaterWorld;',- vertexHead: 'attribute vec3 aCorner; attribute vec4 aPuff;'- + ' attribute vec2 aCard; uniform vec2 uSize;'- + glslLocalDir('waterLocalDir'),- vertexMain: [- ' vUv = uv;',- ' vBase = aPuff.z;',- // Square on to the camera from every elevation. An upright- // card seen from above shows the bank's thin foot as a- // ribbon; this one shows it spread across its face.- ' vec3 camR = vec3(viewMatrix[0][0], viewMatrix[1][0],',- ' viewMatrix[2][0]);',- ' vec3 camU = vec3(viewMatrix[0][1], viewMatrix[1][1],',- ' viewMatrix[2][1]);',- ' camR = waterLocalDir(camR);',- ' camU = waterLocalDir(camU);',- ' camR /= max(length(camR), 1e-8);',- ' camU /= max(length(camU), 1e-8);',- ' vec3 mid = vec3(aPuff.x, aPuff.w, aPuff.y);',- ' transformed = mid + camR * (aCorner.x * uSize.x * aCard.x)',- ' + camU * (aCorner.y * uSize.y * aCard.y);',- ' vP = transformed;',- ' vWaterWorld = (modelMatrix * vec4(transformed, 1.0)).xyz;',- ].join('\n'),- fragmentHead: 'uniform vec3 uColor; uniform float uAlpha;'- + ' uniform float uTop; uniform float uScale;'- + ' uniform float uFreq; uniform vec2 uFlow;'- + ' uniform float uSpeed; uniform float uRadius;'- + ' uniform vec2 uOffset; uniform float uShear;'- + ' uniform vec3 uSunDir; uniform vec3 uSunColor;'- + ' uniform float uSkyGain; uniform float uSunGain;'- + ' uniform float uDither; uniform float uTime;',- fragmentMain: [- // Height above THIS card's water, so a sloping reach keeps- // its own surface, and zero before either card edge.- ' float h = vP.y - vBase;',- // Both axes: the height profile cannot fade a card the- // camera is looking down on, and its rim would be an edge.- // The VERTICAL fade starts almost at the middle: a camera- // near the top of the bank sees the cards' upper rims- // near edge-on and a late fade lands them all in one screen- // band, which is the horizontal striping a night frame- // showed across the whole veil.- ' vec2 e = abs(vUv * 2.0 - 1.0);',- ' float env = (1.0 - smoothstep(0.30, 1.0, e.x))',- ' * (1.0 - smoothstep(0.16, 1.0, e.y));',- // The profile at its thickest (lift = 1) bounds this- // fragment, so everything outside the bank leaves before- // paying for three noise fields — and the cards are stacked- // a dozen deep, which is most of what this effect costs.- ' float cap = uAlpha * env * exp(-h / uScale)',- ' * (1.0 - smoothstep(uTop * 0.35, uTop, h))',- ' * smoothstep(-uTop * 0.22, -uTop * 0.02, h);',- ' if (cap < 0.002) discard;',- ' float along = dot(vP.xz, uFlow) - uTime * uSpeed;',- ' float across = dot(vP.xz, vec2(-uFlow.y, uFlow.x));',- // Compressed along the current, so the wisps lie DOWN it- // instead of blotching like still air.- ' vec2 q0 = vec2(along * 0.70, across) * uFreq + uOffset;',- // How deep the bank is HERE, read at the surface: a- // constant top is a lid, and a lid is what reads as a slab.- // TWO scales, and the coarse one carries most of the swing.- // A ray crosses a dozen cards spread over metres of xz, so- // the integral averages any pattern shorter than the ray- // away to its mean — the wisp scale survives inside one- // card and vanishes from the sum, which is exactly how the- // first render came out with a flat top and no tongues.- // Only structure metres across lives through the integral.- ' float coarse = astraFbm2(q0 * 0.30 + vec2(11.3, 4.7), 2);',- ' float lift = 0.20 + 0.42 * astraFbm2(q0, 3) + 0.62 * coarse;',- ' float prof = exp(-h / (uScale * lift))',- ' * (1.0 - smoothstep(uTop * lift * 0.35, uTop * lift, h))',- ' * smoothstep(-uTop * 0.22, -uTop * 0.02, h);',- // Higher air has been carried further downstream. Without- // this shear a card paints one column of the xz field over- // its whole height, and the field reads as flat ribbons.- ' vec2 q = q0 + vec2(h * uShear * uFreq, 0.0);',- ' float n = astraFbm2(q, 4);',- ' float sh = -uTime * uSpeed * uFreq * 0.55;',- ' float n2 = astraFbm2(q * 2.6 + vec2(sh, h * 0.5), 3);',- ' float wisp = smoothstep(0.12, 0.80, mix(n, n2, 0.32));',- // Full strength across the whole square and gone by its- // corners: an inscribed fade leaves mist on a third of the- // reach the caller asked for.- ' float edge = 1.0 - smoothstep(1.0, 1.42,',- ' length(vP.xz) / uRadius);',- ' float a = uAlpha * prof * wisp * env * edge;',- // A ramp this smooth across this many pixels bands in 8- // bits, and a dozen cards stack the SAME ramp, so the steps- // land on top of each other instead of dissolving. Under- // half a code value, per pixel, moving.- ' a += (astraHash21(gl_FragCoord.xy + vec2(uTime * 60.0))',- ' - 0.5) * uDither;',- ' if (a < 0.002) discard;',- // LIGHT, not paint. What a scattering medium shows is its- // albedo times what reaches it, so `uColor` is multiplied- // by the scene's own light and never emitted: `fogColor` IS- // the skylight at ground level, and reading it is what- // makes this bank pale at noon and a dim blue-grey at- // night with nothing said by the caller. (It exists only- // when the scene has fog — hence the guard, and the white- // fallback that leaves a fogless scene looking as before.)- ' vec3 sky = vec3(1.0);',- ' #ifdef USE_FOG',- ' sky = fogColor;',- ' #endif',- // Forward scattering, as the Henyey-Greenstein lobe rather- // than a power of the cosine. Water droplets throw light ON- // rather than back, so a bank between the camera and the- // sun burns and the same bank with the sun behind is grey —- // the one read that separates mist from a grey card. The- // lobe matters because it is BROAD: `pow(mu, 3)` only fires- // within about 30 degrees of the sun, and the flip test- // below moved the veil 2% between mu = +0.64 and mu = -0.85,- // which is no coupling at all at the angles a camera- // actually stands at. Normalised so side-scatter (mu = 0)- // reads 0.20, the value the power form had as its floor.- ' vec3 V = normalize(vWaterWorld - cameraPosition);',- ' float mu = dot(V, uSunDir);',- ' float den = 1.3025 - 1.10 * mu;',- ' float hg = clamp(0.2929 / max(pow(den, 1.5), 1e-3),',- ' 0.14, 2.0);',- // The foot of a bank stands in the shade of the bank above- // it, so the sun reaches the top of the profile first.- ' float open = mix(0.40, 1.0,',- ' smoothstep(0.0, uTop * 0.75, h));',- ' vec3 col = uColor * (sky * uSkyGain + uColor * 0.032',- ' + uSunColor * (uSunGain * hg * open));',- // Never one flat value: cool in the thick of it where only- // sky gets in, warm where the sun does, plus a slow break- // across the reach so no two tongues are the same grey.- ' float warm = clamp(hg * open, 0.0, 1.0);',- ' col *= mix(vec3(0.94, 0.98, 1.07), vec3(1.05, 1.00, 0.94),',- ' warm);',- ' col = astraHueBreak(col, vP.xz, uFreq * 0.5, 0.16);',- // One flat colour per fragment keeps the over-blend order- // independent, so overlapping cards need no sorting.- ' gl_FragColor = vec4(col, clamp(a, 0.0, 1.0));',- ].join('\n'),- transparent: true,- depthWrite: false,- side: THREE.DoubleSide,- });-}--/**- * Droplets thrown UP where water strikes — real arcs, not a puff.- *- * Every droplet is launched from the impact ring with its own speed and- * its own flight time, rises, slows, and falls back under gravity; the- * count is solved from `rate` times the longest flight, so the field is- * continuous without anyone guessing a particle count. They are- * stretched along their own motion in the view plane, because a round- * dot at this size reads as snow and the streak is what reads as water.- *- * @param {object} [opts]- * `origin` impact point, THREE.Vector3 or [x,y,z] (default 0,0,0 —- * the group is MOVED there, so the droplets stay local);- * `radius` metres the impacts are spread over (default 0.7);- * `rate` droplets launched per second (default 120);- * `speed` launch speed in m/s (default 4.5 — it decides the height:- * 4.5 m/s tops out near a metre); `size` droplet diameter in metres- * (default 0.055); `color` the droplet's ALBEDO, THREE.Color or hex- * (default pale water) — multiplied by the light that reaches it,- * never emitted; `sunDir` THREE.Vector3 or [x,y,z] TOWARD the key- * light, from `sunRig().sunDir` (default +Y) — a droplet is a lens,- * so the sun comes back off it as a hard glint and nothing at all- * once the sun is down; `sunColor` for that light (default a warm- * white); `seed` PRNG seed (default 3).- * @returns {THREE.Group} Named `Spray`, positioned at `origin`, with- * `userData.update(t)` (also `tick(t)`) driving it and `userData.sample(i, t)` returning- * droplet i's group-local position — the CPU mirror of the ballistics- * the vertex shader runs.- */-export function makeSpray(opts = {}) {- const origin = readVec3(opts.origin);- const radius = Math.max(0.01,- opts.radius === undefined ? 0.7 : opts.radius);- const rate = Math.max(1, opts.rate === undefined ? 120 : opts.rate);- const speed = Math.max(0.4, opts.speed === undefined ? 4.5 : opts.speed);- const size = Math.max(0.004,- opts.size === undefined ? 0.055 : opts.size);- const color = new THREE.Color(- opts.color === undefined ? 0xeaf4ff : opts.color);- const sun = toSun(opts.sunDir);- const sunColor = new THREE.Color(- opts.sunColor === undefined ? 0xfff2e0 : opts.sunColor);- const rnd = lehmer(opts.seed === undefined ? 3 : opts.seed);-- // A droplet lives one whole arc, so the field is exactly the launch- // rate times the longest flight — no particle count to guess.- const count = Math.round(Math.min(900,- Math.max(8, (rate * 2 * speed) / _G)));- const org = new Float32Array(count * 3);- const vel = new Float32Array(count * 3);- const ph = new Float32Array(count * 2);- let reach = 0;- for (let i = 0; i < count; i++) {- const a = rnd() * Math.PI * 2;- const r = radius * Math.sqrt(rnd());- const vy = speed * (0.52 + 0.48 * rnd());- // Thrown OUTWARD from where it struck, and far slower sideways- // than up: a symmetric cone reads as a fountain, not an impact.- const ang = a + (rnd() - 0.5) * 1.1;- const vh = speed * (0.10 + 0.38 * rnd());- org[i * 3] = Math.cos(a) * r;- org[i * 3 + 1] = rnd() * 0.05;- org[i * 3 + 2] = Math.sin(a) * r;- vel[i * 3] = Math.cos(ang) * vh;- vel[i * 3 + 1] = vy;- vel[i * 3 + 2] = Math.sin(ang) * vh;- ph[i * 2] = rnd();- ph[i * 2 + 1] = 0.55 + 0.95 * rnd();- const t = (2 * vy) / _G;- const far = Math.hypot(org[i * 3] + vel[i * 3] * t,- org[i * 3 + 2] + vel[i * 3 + 2] * t);- const apex = org[i * 3 + 1] + (vy * vy) / (2 * _G);- reach = Math.max(reach,- Math.hypot(far, apex) + size * ph[i * 2 + 1] * 1.5);- }- const geom = instancedQuad(count, 1, 1, reach * 1.02);- geom.setAttribute('aOrg', new THREE.InstancedBufferAttribute(org, 3));- geom.setAttribute('aVel', new THREE.InstancedBufferAttribute(vel, 3));- geom.setAttribute('aPhase', new THREE.InstancedBufferAttribute(ph, 2));-- const mesh = new THREE.Mesh(geom,- sprayMaterial(color, size, sun, sunColor));- mesh.name = 'SprayDroplets';- mesh.renderOrder = 3;- const g = new THREE.Group();- g.name = 'Spray';- g.position.copy(origin);- g.add(mesh);- g.userData.update = g.userData.tick = (t) => tickShaders(g, t);- g.userData.sample = (i, t) => {- const k = Math.min(count - 1, Math.max(0, i | 0));- const vy = vel[k * 3 + 1];- const flight = (2 * vy) / _G;- const age = ((((ph[k * 2] + t / flight) % 1) + 1) % 1) * flight;- return new THREE.Vector3(- org[k * 3] + vel[k * 3] * age,- org[k * 3 + 1] + vy * age - 0.5 * _G * age * age,- org[k * 3 + 2] + vel[k * 3 + 2] * age);- };- return attachDisposal(keepOutOfDepthPasses(g), snapshotResources(g));-}--/** One arc per droplet, stretched along the way it is going. */-function sprayMaterial(color, size, sun, sunColor) {- return makeShaderMaterial({- name: 'SprayDroplets',- uniforms: {- uColor: { value: color },- uAlpha: { value: 0.85 },- uSize: { value: size },- uG: { value: _G },- // Seconds of travel drawn into the streak: a droplet at- // launch runs ~2.5x its width, one at the apex is round.- uStreak: { value: 0.33 },- uSunDir: { value: sun.dir },- uSunColor: { value: sunColor },- // A droplet is close and sees the whole sky, so it takes- // more skylight than the mist does.- uSkyGain: { value: 1.5 },- // The glint. It peaks near 1.8 in linear — bright enough to- // survive a bloom threshold, nowhere near the 20 that turns- // a highlight into a white hole.- uSunGain: { value: 0.95 * sun.gain },- },- varyings: 'varying vec2 vUv; varying float vLife;'- + ' varying float vGlint; varying float vJit;',- vertexHead: 'attribute vec3 aCorner; attribute vec3 aOrg;'- + ' attribute vec3 aVel; attribute vec2 aPhase;'- + ' uniform float uSize; uniform float uG;'- + ' uniform float uStreak; uniform vec3 uSunDir;'- + glslLocalDir('waterLocalDir'),- vertexMain: [- ' vUv = uv;',- // Its own flight time, so every droplet relaunches on its- // own beat and the field never pulses together.- ' float flight = 2.0 * aVel.y / uG;',- ' float age = fract(aPhase.x + uTime / flight) * flight;',- ' vLife = age / flight;',- ' vec3 c = aOrg + vec3(aVel.x, 0.0, aVel.z) * age;',- ' c.y += aVel.y * age - 0.5 * uG * age * age;',- ' vec3 v = vec3(aVel.x, aVel.y - uG * age, aVel.z);',- ' vec3 cw = (modelMatrix * vec4(c, 1.0)).xyz;',- ' vec3 vw = mat3(modelMatrix) * v;',- ' vec3 f = cameraPosition - cw;',- ' f /= max(length(f), 1e-8);',- ' vec3 d = vw - f * dot(vw, f);',- ' if (length(d) < 1e-4) {',- ' d = vec3(viewMatrix[0][1], viewMatrix[1][1],',- ' viewMatrix[2][1]);',- ' d -= f * dot(d, f);',- ' }',- ' vec3 dir = d / max(length(d), 1e-8);',- ' vec3 sid = cross(f, dir);',- ' dir = waterLocalDir(dir);',- ' sid = waterLocalDir(sid);',- ' dir /= max(length(dir), 1e-8);',- ' sid /= max(length(sid), 1e-8);',- ' float w = uSize * aPhase.y;',- ' float st = 1.0 + uStreak * length(v);',- ' transformed = c + dir * (aCorner.y * w * st)',- ' + sid * (aCorner.x * w);',- // Per droplet, not per pixel: a sphere this small is one- // highlight, and the whole lighting is a function of where- // it sits between the camera and the sun.- ' vGlint = pow(max(dot(-f, uSunDir), 0.0), 2.0);',- // No two the same. aPhase.y already varies the SIZE; this- // decorrelates the brightness from it so the big ones are- // not also the bright ones.- ' vJit = fract(aPhase.y * 7.3 + aPhase.x * 3.1);',- ].join('\n'),- fragmentHead: 'uniform vec3 uColor; uniform float uAlpha;'- + ' uniform vec3 uSunColor; uniform float uSkyGain;'- + ' uniform float uSunGain;',- fragmentMain: [- ' float d = length(vUv - 0.5) * 2.0;',- ' if (d > 1.0) discard;',- // A solid core with a one-pixel rim: a droplet is water,- // not a glow, and a soft blob at this size reads as dust.- ' float core = 1.0 - smoothstep(0.45, 1.0, d);',- // Thrown clear, then spent: it thins on the way back down- // instead of winking out at the end of its arc.- ' float rise = smoothstep(0.0, 0.05, vLife);',- ' float fall = 1.0 - smoothstep(0.40, 1.0, vLife);',- ' float a = uAlpha * core * rise * fall;',- ' if (a < 0.004) discard;',- // Same law as the mist: albedo times what arrives. The- // scene's fog colour is the skylight a droplet swims in, so- // the field goes from white in the sun to a dim blue-grey- // at night with nothing said by the caller.- ' vec3 sky = vec3(1.0);',- ' #ifdef USE_FOG',- ' sky = fogColor;',- ' #endif',- // A droplet is a LENS, so the sun leaves it as a hard- // glint pointed at the camera rather than a diffuse wash —- // and there is always a little skylight in the shade of it.- ' vec3 col = uColor * (sky * uSkyGain + uColor * 0.05',- ' + uSunColor * uSunGain * (0.28 + 0.72 * vGlint));',- ' col *= 0.80 + 0.40 * vJit;',- // The rim of a sphere refracts, so it out-runs the body:- // this is what keeps it a droplet and not a flat disc.- ' col *= 0.88 + 0.30 * core;',- ' gl_FragColor = vec4(col, clamp(a, 0.0, 1.0));',- ].join('\n'),- transparent: true,- depthWrite: false,- side: THREE.DoubleSide,- });-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/waterside.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/waterside.jsdeleted file mode 100644index 29a971b4..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/waterside.js+++ /dev/null@@ -1,368 +0,0 @@-/**- * Waterlines: the contact transitions where ground, rock and water meet.- *- * A bank that meets water at a flat cut reads as two slabs intersecting,- * and it is the cheapest realism there is to fix. All three patches here- * go through `patchStandard`, so each material keeps its lighting,- * shadows, fog and depth chunks, and they CHAIN — a shore ground- * normally wears `patchShoreWet` and `patchShoreFoam` at once. Every- * tunable is a uniform, so two materials wearing one patch share one- * compiled program while keeping their own values.- *- * They complement `water.js` instead of fighting it: the addon Water is- * a reflective (RTT) surface and its raw ShaderMaterial has no- * `<color_fragment>` hook, so `patchShallowWater` belongs on a plain- * standard-material reach (a shallow bay, a river) beside it.- */--import * as THREE from 'three';-import {- toColor, unit, withBase, worldBase,-} from './shader.js';--// One base for all three, on the world varyings terrain_shade shares, so-// a bank wearing a splat and a waterline declares ONE pair.-const BASE = worldBase('waterside:base', 'wsP', 'wsN');--/**- * Darken and gloss the ground below a waterline, fading out above it.- *- * Wet ground is darker than dry ground — that is the whole cue, and- * without it a bank meets the water as a flat cut with no contact at- * all. The fade band above the line is what makes it a shore rather- * than a painted stripe, and the line itself is noise-wandered because- * a level contour is a ruled edge no bank has. Below the line the- * surface stays fully wet, so submerged ground reads as submerged.- *- * Wetting is not a grey multiply. A water film drops the albedo AND- * deepens the colour already there, then gleams at grazing angles — so- * the band carries all three: darken, saturate, and a fresnel sheen in- * the SKY's hue (`fogColor` where the scene is fogged, which is the one- * sky-family colour a `<color_fragment>` patch can reach), which is- * what separates wet sand from sand in shadow.- *- * `gloss` multiplies roughness inside the wet mask. Dry substrate keeps- * its authored roughness, even when one material spans the entire beach.- *- * @param {THREE.Material} material A built-in material, patched in- * place.- * @param {object} [opts] `level` world Y of the water surface (default- * 0); `band` metres of fade ABOVE it (default 0.25); `darken` how far- * the albedo drops at full wet, 0..1 (default 0.45); `saturate` extra- * chroma at full wet (default 0.35); `sheen` grazing-angle lift in- * the sky's hue (default 0.22); `gloss` multiplier on the material's- * dry roughness (default 0.85).- * @returns {THREE.Material} The same material. Its uniforms stay live on- * `material.userData.uniforms`, so `uWetY` can follow a tide.- */-export function patchShoreWet(material, opts = {}) {- const level = opts.level === undefined ? 0 : opts.level;- const band = opts.band === undefined ? 0.25 : opts.band;- const darken = opts.darken === undefined ? 0.45 : opts.darken;- const gloss = opts.gloss === undefined ? 0.85 : opts.gloss;- const sat = opts.saturate === undefined ? 0.35 : opts.saturate;- const sheen = opts.sheen === undefined ? 0.22 : opts.sheen;-- return withBase(material, BASE, {- name: 'waterside:shoreWet',- uniforms: {- uWetY: { value: level },- uWetGloss: { value: Math.max(0, gloss) },- uWetBand: { value: Math.max(band, 1e-3) },- uWetDark: { value: unit(darken) },- uWetSat: { value: Math.max(sat, 0) },- uWetSheen: { value: Math.max(sheen, 0) },- },- fragmentHead: [- 'uniform float uWetY;',- 'uniform float uWetGloss;',- 'uniform float uWetBand;',- 'uniform float uWetDark;',- 'uniform float uWetSat;',- 'uniform float uWetSheen;',- ].join('\n'),- roughnessBody: [- 'roughnessFactor = mix(roughnessFactor,',- ' max(0.045, roughnessFactor * uWetGloss), wtK);',- ].join('\n'),- fragmentBody: [- ' float wtH = vAstraWorld.y - uWetY;',- // astraFbm2 over 3 octaves averages ~0.44; centred there, this- // wanders the tide mark by up to half a band either way.- ' wtH += (astraFbm2(vAstraWorld.xz * 0.7, 3) - 0.44) * uWetBand;',- ' float wtK = astraContact(wtH, uWetBand);',- ' vec3 wtDry = diffuseColor.rgb;',- ' float wtL = dot(wtDry, vec3(0.2126, 0.7152, 0.0722));',- ' vec3 wtWet = mix(vec3(wtL), wtDry, 1.0 + uWetSat)',- ' * (1.0 - uWetDark);',- ' diffuseColor.rgb = mix(wtDry, max(wtWet, vec3(0.0)), wtK);',- // The extra grazing sheen belongs on- // the film, not on the dry beach behind it. cameraPosition is a- // three built-in in both stages, so no extra varying is needed.- ' vec3 wtSky = vec3(0.42, 0.50, 0.60);',- '#ifdef USE_FOG',- ' wtSky = fogColor;',- '#endif',- ' vec3 wtV = normalize(cameraPosition - vAstraWorld);',- ' float wtF = astraFresnel(vAstraWorldN, wtV, 4.0);',- ' diffuseColor.rgb += wtSky * (wtF * wtK * uWetSheen);',- ].join('\n'),- });-}--/**- * A broken white band where water meets anything, torn into streamers.- *- * Foam is the second contact cue and it works on ground, rock or a- * jetty leg alike. It is strongest AT the waterline and hands over to- * both neighbours — fading up the bank and down under the surface —- * rather than ending at an edge. The tear runs ALONG the shore because- * the waves run across it: the horizontal part of the world normal- * points up-slope, so its perpendicular is the shore direction, and the- * world-space field is smoothed along it into elongated patches.- * This keeps curved objects from collapsing a projected coordinate into- * stripes. On a flat surface it uses world X as the fallback direction.- *- * The band breathes: two decorrelated swells move the LINE itself, so- * the foam runs up the bank and drains again. Drive it with- * `tickShaders(scene, t)` — an un-advanced uTime is a frozen band.- *- * Foam is bubbles, never poured paint, so the band is broken TWICE: the- * streamer field tears it along the shore and a fine lace field breaks- * the churn inside it. And it is not one flat white — the thin film at- * the tail keeps a good part of the wet colour under it while only the- * churn goes bright, and the whole band carries a hue break, because a- * single white is the giveaway of a painted waterline. The default- * white is graded to 0.74-0.79 linear so it lifts under bloom instead- * of clipping (a 0xeef4f5 foam runs 0.87 in blue and blows first).- *- * A band in world Y covers `band / slope` metres of GROUND, so the- * flatter the surface the wider it spreads — and on the one surface- * that is exactly level, a water plane, it spreads over the whole- * reach: measured here, a foam patch on a flat reach tinted every- * fragment of it (contact 0.59 at t = 1.5) and laid streamers out to- * the horizon. So the band fades out once its own footprint passes- * `reach` metres, which leaves the bank, the rocks and the piles- * untouched and takes the wash off the open water. A flat reach has no- * waterline of its own; the foam belongs on what the water MEETS.- *- * @param {THREE.Material} material A built-in material, patched in- * place.- * @param {object} [opts] `level` world Y of the water surface (default- * 0); `band` metres the foam reaches EITHER side of it (default- * 0.35); `color` THREE.Color or hex (default a cold white); `speed`- * swell rate in radians per second (default 0.6); `strength` peak- * coverage, 0..1 (default 0.85); `reach` metres of ground the band- * may cover before it fades out (default 3, gone by 2.5x that; pass- * a huge value to put the band back on level surfaces).- * @returns {THREE.Material} The same material, with its uniforms live on- * `material.userData.uniforms`.- */-export function patchShoreFoam(material, opts = {}) {- const level = opts.level === undefined ? 0 : opts.level;- const band = opts.band === undefined ? 0.35 : opts.band;- const speed = opts.speed === undefined ? 0.6 : opts.speed;- const strength = opts.strength === undefined ? 0.85 : opts.strength;- const reach = opts.reach === undefined ? 3 : opts.reach;- return withBase(material, BASE, {- name: 'waterside:shoreFoam',- uniforms: {- uFoamY: { value: level },- uFoamBand: { value: Math.max(band, 1e-3) },- uFoamColor: { value: toColor(opts.color, 0xdfe6e4) },- uFoamSpeed: { value: speed },- uFoamAmt: { value: unit(strength) },- uFoamReach: { value: Math.max(reach, 1e-3) },- },- fragmentHead: [- 'uniform float uFoamY;',- 'uniform float uFoamBand;',- 'uniform vec3 uFoamColor;',- 'uniform float uFoamSpeed;',- 'uniform float uFoamAmt;',- 'uniform float uFoamReach;',- 'float astraFoamNoise(vec3 p, vec3 w) {',- ' return astraFbm2(p.yz, 2) * w.x',- ' + astraFbm2(p.xz, 2) * w.y',- ' + astraFbm2(p.xy, 2) * w.z;',- '}',- ].join('\n'),- fragmentBody: [- ' float fmT = uTime * uFoamSpeed;',- // Two swells, not one: a single sine is a metronome, and it is- // the LINE that moves, so the band runs up and drains.- ' float fmS = sin(fmT) * 0.35 + sin(fmT * 0.63 + 1.7) * 0.22;',- ' float fmH = vAstraWorld.y - uFoamY - fmS * uFoamBand;',- // The shore frame: a bank tilts its normal up-slope, so the- // horizontal normal is ACROSS the shore and its perpendicular- // runs along it. Dead flat, there is no shore — use +X.- ' vec2 fmNx = vAstraWorldN.xz;',- ' float fmL = length(fmNx);',- ' vec2 fmA = fmL > 1e-3 ? fmNx / fmL : vec2(1.0, 0.0);',- ' vec2 fmB = vec2(-fmA.y, fmA.x);',- // Keep noise in world space. Projecting position onto a changing- // curved-surface normal collapses one coordinate on spheres and- // creates vertical stripe fans. Average along the shore instead.- ' vec3 fmW = pow(abs(normalize(vAstraWorldN)), vec3(4.0));',- ' fmW /= max(dot(fmW, vec3(1.0)), 1e-4);',- ' vec3 fmP = vAstraWorld;',- ' vec3 fmFlow = vec3(fmA.x, 0.0, fmA.y);',- ' vec3 fmAlong = vec3(fmB.x, 0.0, fmB.y);',- ' vec3 fmQ = fmP * 2.10 - fmFlow * fmT * 0.35;',- ' float fmN = astraFoamNoise(fmQ, fmW) * 0.50;',- ' fmN += astraFoamNoise(fmQ + fmAlong * 0.9, fmW) * 0.25;',- ' fmN += astraFoamNoise(fmQ - fmAlong * 0.9, fmW) * 0.25;',- ' float fmD = astraFoamNoise(fmP * 9.5',- ' - fmFlow * fmT * 0.60 + vec3(17.1, 8.7, 31.2), fmW);',- ' float fmK = astraContact(abs(fmH), uFoamBand);',- ' fmK *= smoothstep(0.24, 0.62, fmN);',- ' float fmAA = min(fwidth(fmD), 0.18);',- ' fmK *= 0.22 + 0.78 * smoothstep(0.28 - fmAA,',- ' 0.66 + fmAA, fmD);',- // How much GROUND this band covers: a rise of uFoamBand runs- // band * Ny / |Nxz| metres along a surface of that slope, and- // 1/0 on a level one — where the band would be the whole reach.- ' float fmSpan = uFoamBand * abs(vAstraWorldN.y) / max(fmL, 1e-4);',- ' fmK *= 1.0 - smoothstep(uFoamReach, uFoamReach * 2.5, fmSpan);',- // The tail is a thin film that still shows what is under it; only- // the churn goes bright. Then a hue break, so no two square- // metres of the band are the same white.- ' vec3 fmC = mix(uFoamColor * 0.70, uFoamColor,',- ' smoothstep(0.30, 0.88, fmN));',- ' fmC = astraHueBreak(fmC, vAstraWorld.xz, 1.7, 0.14);',- ' diffuseColor.rgb = mix(diffuseColor.rgb, fmC,',- ' clamp(fmK * uFoamAmt, 0.0, 1.0));',- ].join('\n'),- });-}--// Odd, so the grid is symmetric about the centre of `bounds` and the-// least-squares normal equations decouple into three sums.-const BED_SAMPLES = 9;--/**- * Fit `bed(x, z) = c0 + cx*x + cz*z` to `bedAt` over `bounds`.- *- * Least squares on a grid symmetric about its own centre, where the- * cross terms vanish, so no matrix solve is needed.- */-function fitBedPlane(bedAt, bounds, level) {- const flat = new THREE.Vector3(level, 0, 0);- if (typeof bedAt !== 'function') return flat;- const [x0, z0, x1, z1] = bounds;- const xc = (x0 + x1) / 2;- const zc = (z0 + z1) / 2;- const n = BED_SAMPLES;- let sb = 0, sx = 0, sz = 0, sxx = 0, szz = 0;- for (let i = 0; i < n; i++) {- for (let j = 0; j < n; j++) {- const x = x0 + (x1 - x0) * (i / (n - 1));- const z = z0 + (z1 - z0) * (j / (n - 1));- const b = bedAt(x, z);- if (!Number.isFinite(b)) return flat;- sb += b;- sx += (x - xc) * b;- sz += (z - zc) * b;- sxx += (x - xc) * (x - xc);- szz += (z - zc) * (z - zc);- }- }- const cx = sxx > 1e-9 ? sx / sxx : 0;- const cz = szz > 1e-9 ? sz / szz : 0;- return new THREE.Vector3(sb / (n * n) - cx * xc - cz * zc, cx, cz);-}--/**- * Colour a water surface by how deep it runs, so a reach is not a slab.- *- * One flat colour over a whole reach is what makes water read as a- * sheet of plastic laid on the ground; real water goes pale and warm- * where it runs thin over the bank and saturates into the deep tone- * where the bed drops away, which is also what tells the eye where the- * bank IS. The shallow edge is noise-wandered so the isoline does not- * rule a contour across the surface.- *- * DEPTH ROUTE — the bed comes from world XZ through a tilted plane- * least-squares FITTED to `bedAt` on the CPU, and depth is this- * fragment's own world Y minus that plane. That is the one of the two- * that a fragment shader can actually run: world Y against a `bedLevel`- * is a single number over a flat water plane and would paint the whole- * reach one colour, while a true per-fragment `bedAt` needs the- * heightfield uploaded as a texture or a depth prepass, and this engine- * runs neither. A plane is exact for a bed that slopes, which is what a- * bank is; with no `bedAt` it degenerates to the constant `bedLevel`.- *- * Not for the addon Water from `water.js` — that is a raw- * ShaderMaterial with no `<color_fragment>` hook (and a reflective RTT- * surface). Use this on a plain standard-material reach beside it.- *- * @param {THREE.Material} material The water surface's built-in- * material, patched in place.- * @param {object} [opts] `bedAt` function(x, z) returning the bed's- * world Y, sampled 9x9 over `bounds` and fitted; `bounds`- * [minX, minZ, maxX, maxZ] to fit over (default 120 m about the- * origin); `bedLevel` the constant bed used when there is no `bedAt`- * (default -2, two metres under a surface at y = 0); `deep` /- * `shallow` THREE.Color or hex — the deep end defaults to water.js's- * own `waterColor`, so a reach agrees with the scene's RTT ocean, and- * the shallow end to a muted jade (0x6fa392, ~0.27 linear; the pale- * sage it replaced ran 0.40-0.57 and came back off this renderer as- * white paint); `range` metres of depth over which shallow becomes- * deep (default 2); `edgeFade` how much of the material's own opacity- * survives in the shallows, so the bed shows through where the water- * runs thin (default 0.55 on a transparent material, 1 on an opaque- * one, where alpha is ignored anyway).- * @returns {THREE.Material} The same material, with its uniforms live on- * `material.userData.uniforms`.- */-export function patchShallowWater(material, opts = {}) {- const bedLevel = opts.bedLevel === undefined ? -2 : opts.bedLevel;- const bounds = opts.bounds || [-60, -60, 60, 60];- const range = opts.range === undefined ? 2 : opts.range;- // A UNIFORM, never a second source variant: the cache key names the- // patch, so the first material to compile decides the GLSL for every- // material wearing this chain. Opaque materials get 1 — three- // discards alpha there, and a fade they cannot show is a lie in the- // uniform dump.- const fade = opts.edgeFade === undefined- ? (material && material.transparent ? 0.55 : 1)- : unit(opts.edgeFade);- return withBase(material, BASE, {- name: 'waterside:shallow',- uniforms: {- uShoalBed: { value: fitBedPlane(opts.bedAt, bounds, bedLevel) },- uShoalDeep: { value: toColor(opts.deep, 0x0e3f5c) },- uShoalShallow: { value: toColor(opts.shallow, 0x6fa392) },- uShoalRange: { value: Math.max(range, 1e-3) },- uShoalFade: { value: fade },- },- fragmentHead: [- 'uniform vec3 uShoalBed;',- 'uniform vec3 uShoalDeep;',- 'uniform vec3 uShoalShallow;',- 'uniform float uShoalRange;',- 'uniform float uShoalFade;',- ].join('\n'),- fragmentBody: [- ' float swBed = uShoalBed.x + uShoalBed.y * vAstraWorld.x',- ' + uShoalBed.z * vAstraWorld.z;',- ' float swD = vAstraWorld.y - swBed;',- // The shoal edge wanders by a third of the range, or the ramp- // draws a contour line across open water.- ' swD += (astraFbm2(vAstraWorld.xz * 0.35, 3) - 0.44)',- ' * uShoalRange * 0.7;',- ' float swK = smoothstep(0.0, uShoalRange, max(swD, 0.0));',- ' vec3 swC = mix(uShoalShallow, uShoalDeep, swK);',- // Silt, weed and bed patches move the hue at metre scale, and- // they do it in the SHALLOWS, where the bed shows through; the- // deep end is the colour of water and holds still. Without this- // the reach is one clean ramp — the tell of painted water.- ' swC = astraHueBreak(swC, vAstraWorld.xz, 0.09,',- ' 0.34 * (1.0 - swK * 0.8));',- ' diffuseColor.rgb = swC;',- // Thin water is see-through water: the bed under the shoal edge- // is the cue that says where the bank goes.- ' diffuseColor.a *= mix(uShoalFade, 1.0, swK);',- ].join('\n'),- });-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/woodland.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/woodland.jsdeleted file mode 100644index e864906b..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/woodland.js+++ /dev/null@@ -1,811 +0,0 @@-/**- * The two halves of a forest: the trunk the camera walks up to, and the- * stand-ins for everything too far away to be worth geometry.- *- * `patchBark` shades a trunk. Bark is the one surface in a scene the- * viewer has touched, so a flat brown cylinder is read instantly as a- * placeholder — and the cue is not roughness, it is DIRECTION: a trunk's- * fissures are long and narrow and they run UP. Isotropic noise on a- * trunk reads as stone. The field here is sampled with its along-trunk- * axis divided by `aniso`, so every feature is stretched that many times- * up the trunk before anything else happens to it.- *- * `makeImposters` puts a silhouette on a card. A hundred real trees is a- * budget; a hundred cards is one draw call, and past ~35 m nobody can- * tell (measured — see the function's own note). Cards carry the cost of- * a forest, a crowd or a distant town in the only place it is affordable.- *- * Both go through `lib/shader.js`, so both keep the depth and fog chunks- * that decide whether an effect is in the frame at all.- */--import * as THREE from 'three';-import { attachDisposal, snapshotResources } from './lifecycle.js';--import { mulberry32 } from './noise.js';-import { windOf } from './grass.js';-import {- composeRoughness, glslLocalDir, instancedQuad, keepOutOfDepthPasses,- makeShaderMaterial, patchStandard, readVec3, seedVec3, tickShaders,- toColor, unit,-} from './shader.js';--const _TAU = Math.PI * 2;--/**- * The four barks, as UNIFORM values over one shared program.- *- * `aniso` is how many times longer a fissure is than it is wide;- * `crack` is its half-width and its contrast; `node` is the metres- * between a birch's peel seams or a bamboo's nodes.- */-// `tint` is an ALBEDO: nothing here goes over 0.80 on a channel, or the-// bark clips before the tone map can shape it. Birch was 0xd8d4c8-// (0.85) and rendered as a white pole on this pipeline — measured 0.746-// mean luminance with a p95 of 0.833, the brightest thing in a daylight-// frame including the sky's own gradient.-const BARK_KINDS = {- pine: { id: 0, tint: 0x8f5a33, scale: 0.075, aniso: 5.5,- crack: [0.25, 0.85], plate: [0.55, 1.00], node: 0, rough: 1.22 },- birch: { id: 1, tint: 0xc2beb1, scale: 0.110, aniso: 6.0,- crack: [0.13, 0.55], plate: [0, 0], node: 0.55, rough: 1.08 },- oak: { id: 2, tint: 0x6f5940, scale: 0.085, aniso: 10.5,- crack: [0.24, 1.00], plate: [0, 0], node: 0, rough: 1.30 },- bamboo: { id: 3, tint: 0x9aa858, scale: 0.160, aniso: 12.0,- crack: [0.07, 0.35], plate: [0, 0], node: 0.34, rough: 0.72 },-};--const seedOffset = (seed) => seedVec3(seed, 0.29, 4.13, 9.67, 48);--const BARK_VARYINGS = [- 'varying vec3 vAstraBarkP;',- 'varying vec3 vAstraBarkN;',- 'varying vec3 vAstraBarkS;',-].join('\n');--// The grain lives in the TRUNK's own frame, so the sun has to come down-// into it; three applies instanceMatrix after this hook, hence the-// branch. Projection, not inverse: compose() leaves the columns-// orthogonal.-const BARK_VERTEX_HEAD = [- BARK_VARYINGS,- 'uniform vec3 uBarkSun;',- glslLocalDir('astraBarkLocalDir', true),-].join('\n');--const BARK_FRAGMENT_HEAD = [- BARK_VARYINGS,- 'uniform float uBarkKind;',- 'uniform float uBarkScale;',- 'uniform float uBarkAniso;',- 'uniform float uBarkDepth;',- 'uniform float uBarkMoss;',- 'uniform vec2 uBarkCrack;',- 'uniform vec2 uBarkPlate;',- 'uniform float uBarkNode;',- 'uniform vec3 uBarkAxis;',- 'uniform vec3 uBarkTint;',- 'uniform vec3 uBarkMossColor;',- 'uniform vec3 uBarkSeed;',- 'vec3 astraBarkPerp(vec3 ax) {',- ' vec3 g = abs(ax.y) > 0.9 ? vec3(1.0, 0.0, 0.0) : vec3(0.0, 1.0, 0.0);',- ' return normalize(cross(ax, g));',- '}',- // Two 2D slices that SHARE the along-trunk coordinate: one divide by- // uBarkAniso then stretches every feature up the trunk at once, which- // is the whole difference between bark and gravel.- 'float astraBarkFbm(vec2 q, float h) {',- ' return 0.5 * (astraFbm2(vec2(q.x, h), 3)',- ' + astraFbm2(vec2(q.y, h) + 31.7, 3));',- '}',- // 0 ON a fissure line, 1 in the middle of a ridge: a fissure is where- // the field crosses its own median, which is a CURVE, not a blob.- // The gain sets how fast the ridge saturates, and it is what decides- // whether the cut reads as a LINE or as a cloud: at 4.8 the sub-1 band- // was wide enough that the kind's own cut width turned it into- // camouflage blotches on our render. 6.4 keeps the same curves and- // makes the dark part of them narrow.- 'float astraBarkRidge(vec2 q, float h) {',- ' return clamp(abs(astraBarkFbm(q, h) - 0.4375) * 6.4, 0.0, 1.0);',- '}',-].join('\n');--const BARK_FRAGMENT_BODY = [- ' vec3 bkAx = normalize(uBarkAxis);',- ' vec3 bkT1 = astraBarkPerp(bkAx);',- ' vec3 bkT2 = cross(bkAx, bkT1);',- ' float bkSc = max(uBarkScale, 1e-3);',- // ALONG is divided by aniso and ACROSS is not. This one asymmetry is- // the claim the whole patch makes.- ' float bkH = dot(vAstraBarkP, bkAx) / (bkSc * max(uBarkAniso, 1.0))',- ' + uBarkSeed.z;',- ' vec2 bkQ = vec2(dot(vAstraBarkP, bkT1), dot(vAstraBarkP, bkT2))',- ' / bkSc + uBarkSeed.xy;',- ' float bkV = astraBarkRidge(bkQ, bkH);',- ' float bkCut = 1.0 - smoothstep(0.0, uBarkCrack.x, bkV);',- // The second, finer set of cracks is scaled 3.1x ACROSS the trunk and- // only 1.35x along it: scaling both (it was 2.7 and 2.7) kept the- // aspect and so produced short strokes, which is the speckle that read- // as camouflage rather than as grain. Narrow and LONG is the whole- // point of the module.- ' float bkV2 = astraBarkRidge(bkQ * 3.1 + 9.3, bkH * 1.35);',- ' float bkFine = 1.0 - smoothstep(0.0, uBarkCrack.x * 0.5, bkV2);',- ' bkCut = clamp(bkCut + 0.40 * bkFine * (1.0 - bkCut), 0.0, 1.0);',- // HUE VARIANCE, before the kind's own structure. A trunk is never one- // colour — sapwood, weathering and the side the rain runs down move it- // warm and cool over half a metre — and a flat tint is what makes a- // shaded trunk read as a brown cylinder however good the fissures are.- // The same field, read very coarsely, so the drift follows the GRAIN- // instead of spotting the trunk.- ' float bkDr = astraBarkFbm(bkQ * 0.16, bkH * 0.16 + 5.3) - 0.4375;',- ' vec3 bkTint = uBarkTint * vec3(1.0 + bkDr * 1.10,',- ' 1.0 + bkDr * 0.26, 1.0 - bkDr * 0.85);',- ' float bkFlat = 0.0;',- ' if (uBarkKind < 0.5) {',- // PINE sheds in plates the size of a hand: a second field, coarse and- // barely stretched, cut at its own median into cells.- ' float bkPl = astraBarkRidge(bkQ * uBarkPlate.x,',- ' bkH * uBarkPlate.y + 4.7);',- ' float bkGap = 1.0 - smoothstep(0.0, 0.18, bkPl);',- ' bkCut = clamp(max(bkCut * 0.45, bkGap * 0.9), 0.0, 1.0);',- ' bkTint = mix(bkTint, bkTint * vec3(1.35, 0.95, 0.70), bkPl);',- ' } else if (uBarkKind < 1.5) {',- // BIRCH is the one bark whose marks run ACROSS: lenticel dashes over- // a papery skin the vertical grain barely scores.- ' float bkLn = astraBarkRidge(bkQ * 1.1 + 3.1, bkH * 11.0);',- ' float bkDash = 1.0 - smoothstep(0.0, 0.12, bkLn);',- ' float bkPeel = 1.0 - smoothstep(0.0, 0.10,',- ' astraBarkRidge(bkQ * 0.12 + 7.7, bkH * uBarkNode));',- ' bkCut = clamp(bkCut * 0.22 + bkDash * 0.65 + bkPeel * 0.55,',- ' 0.0, 1.0);',- ' } else if (uBarkKind < 2.5) {',- // OAK: the deepest fissures, and the flats between them are the- // ridge TOPS, which catch the light rather than only losing it.- ' bkCut = clamp(bkCut * 1.2, 0.0, 1.0);',- ' bkFlat = smoothstep(0.55, 0.95, bkV);',- ' } else {',- // BAMBOO: smooth culm, hard node. The ring is the only strong mark- // and the collar above it is paler.- ' float bkNd = abs(fract(bkH * uBarkNode) - 0.5) * 2.0;',- ' float bkRing = 1.0 - smoothstep(0.0, 0.10, bkNd);',- ' bkCut = clamp(bkCut * 0.35 + bkRing, 0.0, 1.0);',- ' bkTint = mix(bkTint * vec3(1.10, 1.14, 0.86), bkTint,',- ' smoothstep(0.08, 0.40, bkNd));',- ' }',- // Relief, not paint: the object-space gradient of the fissure depth- // tilts the normal this patch cannot reach, and the sun answers.- ' vec3 bkPx = dFdx(vAstraBarkP), bkPy = dFdy(vAstraBarkP);',- ' vec3 bkGr = (bkPx * dFdx(bkCut) + bkPy * dFdy(bkCut))',- ' / max(dot(bkPx, bkPx) + dot(bkPy, bkPy), 1e-12);',- ' vec3 bkNr = normalize(vAstraBarkN);',- ' vec3 bkSun = normalize(vAstraBarkS);',- ' float bkRel = dot(normalize(bkNr + bkGr * uBarkDepth * bkSc), bkSun)',- ' - dot(bkNr, bkSun);',- // The floor is 0.58, not 0.45: nothing outdoors is lit by the sun- // alone, and a relief that can take a facet to 45% of its own albedo- // paints black holes where a fissure turns away.- ' float bkLit = clamp(1.0 + bkRel * 0.9 + bkFlat * 0.10, 0.58, 1.6);',- // The albedo underneath is kept as LUMINANCE — a trunk you coloured- // dark stays dark, and every patch already on this material shows- // through. Never an assignment.- ' float bkLum = dot(diffuseColor.rgb, vec3(0.3333));',- ' vec3 bkBase = bkTint * (0.75 + 0.55 * smoothstep(0.02, 0.35, bkLum));',- ' diffuseColor.rgb = mix(diffuseColor.rgb, bkBase, 0.72);',- // The ridge is lifted as far as the fissure is cut, or a barked trunk- // is simply a darker trunk than the one it replaced. The FLOOR is- // 0.72 of the depth asked for and never zero: a fissure still sees- // the sky, and a black one is the one thing that reads as paint- // rather than as relief.- ' diffuseColor.rgb *= mix(1.0 + 0.30 * uBarkDepth,',- ' 1.0 - 0.72 * uBarkDepth, bkCut);',- // And what reaches the bottom of a fissure is SKY, not sun: the cut- // is cooler than the ridge beside it, which is the depth cue that- // survives being resolved down to four pixels.- ' diffuseColor.rgb *= mix(vec3(1.0), vec3(0.88, 0.95, 1.10),',- ' bkCut * 0.65);',- ' diffuseColor.rgb *= bkLit;',- ' float bkMs = uBarkMoss * bkCut * smoothstep(0.30, 0.75,',- ' astraBarkFbm(bkQ * 0.30, bkH * 0.30 + 2.9));',- // Moss takes the trunk's own drift: one flat green cushion is the- // giveaway that a bark is a texture and not a place things grow.- ' diffuseColor.rgb = mix(diffuseColor.rgb,',- ' uBarkMossColor * (1.0 + bkDr * 0.90), clamp(bkMs, 0.0, 1.0));',-].join('\n');--/**- * Give a trunk bark that runs UP it — the cue a flat brown cylinder- * misses.- *- * A trunk is the one surface in an outdoor scene a camera gets close- * enough to read, and what it reads is direction: fissures many times- * longer than they are wide, running along the grain. This samples its- * field with the along-axis coordinate divided by `aniso` (5.5 to 12,- * by kind), so the features are stretched up the trunk before the kind's- * own structure is cut into them — plates for pine, papery lenticel- * bands for birch, deep ridges for oak, smooth nodes for bamboo. All- * four are ONE program: the kind is a uniform, so a stand of four- * species costs one compile.- *- * The field is shaded from the trunk's OWN frame (object space, `axis`- * default +Y), so it wraps a cylinder correctly wherever the tree is- * placed and does not swim when the tree moves. A fallen log or a branch- * needs its own `axis`.- *- * It BLENDS over the albedo: the kind's tint is mixed 0.72 over what is- * there, weighted by that albedo's own luminance, then the fissures- * multiply it down — so a dark trunk stays dark and any patch already on- * the material shows through. It never assigns `diffuseColor.rgb`.- * Roughness is per MATERIAL, not per pixel (`composeRoughness`): bark is- * matte, bamboo is not.- *- * The one thing a fragment patch cannot reach is the normal, so the- * relief is baked into the albedo instead — the object-space gradient of- * the fissure depth against `sun`. It fades out on its own once a pixel- * spans a fissure, which is why the trunk does not sparkle at distance.- *- * @param {THREE.Material} material Trunk material, patched in place — a- * shared material from `materials.js` barks every mesh wearing it, so- * clone it first (and clone BEFORE patching).- * @param {object} [opts] `kind` 'pine' | 'birch' | 'oak' (default) |- * 'bamboo'; `scale` metres across one fissure (default by kind,- * 0.075..0.16 — this is the width of a crack, not the trunk);- * `depth` 0..1 how far the fissures cut, in shade and in relief- * (default 0.55); `mossy` 0..1 green held in the fissures (default- * 0.12 — `damp.js`'s `patchMoss` grows the cushion on the shaded- * side, this is only what lodges in the cracks); `axis` the trunk's- * own axis in OBJECT space, THREE.Vector3 or [x, y, z] (default +Y);- * `tint` THREE.Color or hex, the bark colour (default by kind);- * `sunDir` world direction TOWARD the sun, for the relief (default a- * day sun; `sun` is read too); `seed` moves the field (default 1).- * @returns {THREE.Material} The same material, uniforms live on- * `material.userData.uniforms`.- */-export function patchBark(material, opts = {}) {- const kind = BARK_KINDS[opts.kind] || BARK_KINDS.oak;- const scale = Math.max(1e-3,- opts.scale === undefined ? kind.scale : opts.scale);- const depth = unit(opts.depth === undefined ? 0.55 : opts.depth);- const mossy = unit(opts.mossy === undefined ? 0.12 : opts.mossy);- const seed = opts.seed === undefined ? 1 : opts.seed;- const axis = readVec3(opts.axis, 0, 1, 0);- if (axis.lengthSq() < 1e-9) axis.set(0, 1, 0);- // A node count in FIELD units: the along-axis coordinate is already- // divided by scale * aniso, so a spacing in metres has to come back- // through the same divide or `scale` would move the nodes.- const node = kind.node > 0- ? (scale * kind.aniso) / kind.node : 0;- composeRoughness(material, 'woodland:bark',- 1 + (kind.rough - 1) * (0.4 + 0.6 * depth));- return patchStandard(material, {- name: 'woodland:bark',- uniforms: {- uBarkKind: { value: kind.id },- uBarkScale: { value: scale },- uBarkAniso: { value: kind.aniso },- uBarkDepth: { value: depth },- uBarkMoss: { value: mossy },- uBarkCrack: { value: new THREE.Vector2(kind.crack[0], kind.crack[1]) },- uBarkPlate: { value: new THREE.Vector2(kind.plate[0], kind.plate[1]) },- uBarkNode: { value: node },- uBarkAxis: { value: axis.normalize() },- uBarkTint: { value: toColor(opts.tint, kind.tint) },- uBarkMossColor: { value: toColor(opts.mossColor, 0x46551f) },- uBarkSun: { value: readVec3(opts.sunDir ?? opts.sun, 0.45, 0.78, 0.35).normalize() },- uBarkSeed: { value: seedOffset(seed) },- },- vertexHead: BARK_VERTEX_HEAD,- vertexBody: [- ' vAstraBarkP = transformed;',- ' vAstraBarkN = normal;',- ' vAstraBarkS = astraBarkLocalDir(uBarkSun);',- ].join('\n'),- fragmentHead: BARK_FRAGMENT_HEAD,- fragmentBody: BARK_FRAGMENT_BODY,- });-}--/**- * The four silhouettes, and what each is worth as a card.- *- * `cross` is whether the stand-in gets two fixed quads at right angles- * (which hold still while the camera moves) or one that turns to face- * it. A tree is watched from a moving camera; a distant figure is not.- */-const IMPOSTER_KINDS = {- tree: { id: 0, cross: true, height: 9, aspect: 0.92, hue: 0.13,- color: 0x4a5c26, second: 0x8a7050, sway: 0.020,- bow: [1.9, 1.6, 0.20, 0.15], mid: 0.66 },- conifer: { id: 1, cross: true, height: 14, aspect: 0.52, hue: 0.10,- color: 0x2f4429, second: 0x7a6244, sway: 0.012,- bow: [1.3, 1.0, 0.25, 0.32], mid: 0.50 },- person: { id: 2, cross: false, height: 1.75, aspect: 0.46, hue: 0.55,- color: 0x9c6a55, second: 0x40465a, sway: 0,- bow: [1.1, 0.2, 0.90, 0.30], mid: 0.55 },- building: { id: 3, cross: true, height: 11, aspect: 1.35, hue: 0.06,- color: 0xa89880, second: 0x3a3630, sway: 0,- bow: [0.5, 0.1, 1.40, 0.20], mid: 0.50 },-};--// The fallback irradiance, matched to THIS renderer's own daylight rig-// (`environment.js` sunRig 'day': a 0xfff0d8 sun at 5.4 and a 1.4-// hemisphere, at exposure 1.0 with no post chain). The reference's-// 3.0 / 0.85 was graded for a different exposure and a bloom pass, and-// it lands a card field visibly under the geometry standing in it.-// Pass `rig` and none of this is guesswork.-// Measured off sunRig('day') here: the hemisphere delivers (0.42, 0.50,-// 0.71) of irradiance and the environment bake a further (1.25, 1.68,-// 2.11). Linear working values, not a hex — an irradiance over 1 has no-// hex to be written as.-const DAY_SUN = new THREE.Color(0xfff0d8).multiplyScalar(5.4);-const DAY_AMBIENT = new THREE.Color(1.67, 2.18, 2.82);--/**- * The irradiance a diffuse surface takes from an equirect environment.- *- * `sunRig` bakes its environment as a linear half-float equirect of- * RADIANCE, and every lit material in the scene is receiving it through- * three's PMREM. A card is not, so without this the far field is lit by- * the hemisphere alone and lands under the geometry standing in it — by- * a factor that is not a constant, because the ratio of sky bake to- * hemisphere is completely different at noon and at midnight (measured- * here: a treeline tuned to match by day came out at 0.72 of the real- * crown beside it under the moon).- *- * Solid-angle weighted mean radiance over the sphere, times PI. Sampled- * on a 64 x 32 grid, which is 2 048 texels of a 256 x 128 bake.- *- * @returns {THREE.Color|null} null for a texture with no readable data- * (a PMREM render target, a loaded image), which is not an error —- * the caller falls back to the hemisphere alone.- */-function envIrradiance(tex) {- const img = tex && tex.image;- const data = img && img.data;- if (!data || !img.width || !img.height) return null;- const w = img.width, h = img.height;- const half = tex.type === THREE.HalfFloatType;- const dy = Math.max(1, Math.round(h / 32));- const dx = Math.max(1, Math.round(w / 64));- let r = 0, g = 0, b = 0, sum = 0;- for (let y = 0; y < h; y += dy) {- // Row 0 is the nadir, as the bake writes it.- const cw = Math.cos(((y + 0.5) / h - 0.5) * Math.PI);- for (let x = 0; x < w; x += dx) {- const i = (y * w + x) * 4;- const f = half ? THREE.DataUtils.fromHalfFloat : (v) => v;- r += f(data[i]) * cw;- g += f(data[i + 1]) * cw;- b += f(data[i + 2]) * cw;- sum += cw;- }- }- if (sum <= 0) return null;- return new THREE.Color(r / sum, g / sum, b / sum)- .multiplyScalar(Math.PI);-}--/**- * Read a `sunRig()` package as the three numbers a card needs.- *- * A card does its own lighting — it has no normals three can light and- * no place in the shadow map — so the ONE thing that makes it belong is- * being handed the same irradiance the geometry beside it receives:- * the directional as irradiance (colour times intensity), and the- * indirect as hemisphere PLUS the baked environment, which is what- * three gives every lit mesh in the scene.- */-function rigLight(rig) {- if (!rig || !rig.sun || !rig.fill) return null;- // The hemisphere at the mix a roughly upright surface sees.- const amb = rig.fill.color.clone()- .lerp(rig.fill.groundColor, 0.45)- .multiplyScalar(rig.fill.intensity);- const env = envIrradiance(rig.envTex);- if (env) amb.add(env);- return {- sunDir: (rig.sunDir ? rig.sunDir.clone()- : rig.sun.position.clone()).normalize(),- sunColor: rig.sun.color.clone().multiplyScalar(rig.sun.intensity),- ambient: amb,- };-}--/**- * Stand-ins on cards: a forest, a crowd or a town for one draw call.- *- * Use when each crown spans roughly 60 screen pixels or fewer. The older- * ~35 m guideline was measured at 512 px and is not resolution-independent.- * Measured against the same stand built- * as real geometry (mean absolute pixel difference over the frame,- * 512 px, daylight): 15 m 12.6/255 and plainly flat — the crown's- * silhouette is right but it has no interior and the eye reads a- * cut-out; 40 m 4.1/255, which is the point where a still frame stops- * telling them apart; 90 m 1.4/255, indistinguishable. So put real- * geometry in the near field and hand the rest to this — and give the- * two the same species colours, because the join is where a mismatch- * shows.- *- * Every card is seated on `heightAt` with its BASE at the ground, is- * scaled and hue-shifted per instance (a field of identical cards is- * wallpaper at any distance), and — for `tree` and `conifer` — leans on- * `grass.js`'s `windOf`, so one `wind` option moves the meadow, the- * reeds and the far treeline together.- *- * The whole field is ONE `InstancedBufferGeometry`: `position` stays at- * zero (the GTAO reason `instancedQuad` documents) and the cards are- * built in the vertex shader, so the stated bounding SPHERE is the only- * thing three can cull the field by. It is computed from the real- * placements here. The mesh is guarded by `keepOutOfDepthPasses`,- * because an override material draws a transparent card as a solid wall- * — which also means these cards cast no shadow; their contact with the- * ground is the darkened foot in the silhouette itself.- *- * @param {object} [opts] `source` 'tree' (default) | 'conifer' |- * 'person' | 'building'; `count` stand-ins (default 120 — one draw- * call at any count); `extent` metres of the square field's side,- * centred on the group's origin (default 120); `height` metres of the- * average stand-in (default by source: 9 / 14 / 1.75 / 11);- * `heightAt` (x, z) => y, the ground the cards are seated on (default- * y = 0); `seed` PRNG seed (default 7); `cross` two fixed quads at- * right angles instead of one turning card (default true except for- * `person`); `color` the main albedo, `trunkColor` the second one- * (trunk, clothing, window); `rig` the `sunRig()` package the scene is- * lit by — PASS IT: a card does its own lighting, so this is the whole- * of what makes the far field belong to the near one, and it is what- * turns a treeline down at night; `sunDir`/`sunColor`/`ambient` the- * same three by hand, each overriding `rig` (defaults: this- * renderer's own daylight rig); `wind` as `grass.js`'s `windOf` reads- * it; `name` group name.- * @returns {THREE.Group} Named `Imposters`, resting on the ground,- * holding ONE mesh, with `userData.update(t)` driving the lean. Add it- * at the scene ROOT: the cards billboard against WORLD axes.- */-export function makeImposters(opts = {}) {- const kind = IMPOSTER_KINDS[opts.source] || IMPOSTER_KINDS.tree;- const count = Math.max(1, Math.round(- opts.count === undefined ? 120 : opts.count));- const extent = Math.max(1, opts.extent === undefined ? 120 : opts.extent);- const height = Math.max(0.05,- opts.height === undefined ? kind.height : opts.height);- const ground = typeof opts.heightAt === 'function' ? opts.heightAt : null;- const seed = opts.seed === undefined ? 7 : opts.seed;- const cross = opts.cross === undefined ? kind.cross : !!opts.cross;- const wind = windOf(opts.wind);-- const field = plant(count, extent, seed, kind, ground);- const cards = cross ? count * 2 : count;- const width = height * kind.aspect;- const half = 0.5 * width * field.scale * (cross ? Math.SQRT2 : 1)- + Math.abs(kind.sway * wind.amp * 2) * height;- const box = new THREE.Box3(- new THREE.Vector3(-extent / 2 - half, field.low, -extent / 2 - half),- new THREE.Vector3(extent / 2 + half, field.high + height * field.scale,- extent / 2 + half));- const sphere = box.getBoundingSphere(new THREE.Sphere());-- // The REAL radius: `position` is all zeros, so three has nothing else- // to cull by and the 10 km default would frame 10 km of empty air.- const geom = instancedQuad(cards, 1, 1, sphere.radius);- geom.setAttribute('aPos', new THREE.InstancedBufferAttribute(- cardArray(field.pos, cross, 3), 3));- geom.setAttribute('aCard', new THREE.InstancedBufferAttribute(- cardArray(field.card, cross, 4), 4));- if (cross) {- const yaw = geom.attributes.aCard.array;- for (let i = 0; i < count; i++) yaw[(i * 2 + 1) * 4] += Math.PI / 2;- }- geom.boundingBox = box;- // instancedQuad centres its sphere on the ORIGIN; this one is centred- // on the field, so it is tighter and it is what three culls by. The- // radius passed above is only the floor under it.- geom.boundingSphere = sphere;-- const light = rigLight(opts.rig);- const mesh = new THREE.Mesh(geom, imposterMaterial({- kind, width, height, cross, wind,- color: toColor(opts.color, kind.color),- second: toColor(opts.trunkColor, kind.second),- sun: opts.sunDir === undefined && light- ? light.sunDir : readVec3(opts.sunDir, 0.45, 0.78, 0.35).normalize(),- // Irradiance, not a screen colour.- sunColor: opts.sunColor === undefined- ? (light ? light.sunColor : DAY_SUN.clone())- : toColor(opts.sunColor, 0xffffff),- ambient: opts.ambient === undefined- ? (light ? light.ambient : DAY_AMBIENT.clone())- : toColor(opts.ambient, 0xffffff),- }));- mesh.name = 'ImposterCards';- const g = new THREE.Group();- g.name = opts.name || 'Imposters';- g.add(keepOutOfDepthPasses(mesh));- g.userData.update = g.userData.tick = (t) => tickShaders(g, t);- return attachDisposal(g, snapshotResources(g));-}--/**- * Seat `count` stand-ins on a jittered grid over the field.- *- * The grid is shuffled before it is cut to `count`, or a field that does- * not fill its last row loses a rectangular corner of itself.- */-function plant(count, extent, seed, kind, ground) {- const cells = Math.max(1, Math.ceil(Math.sqrt(count)));- const step = extent / cells;- const rand = mulberry32(seed);- const order = [];- for (let i = 0; i < cells * cells; i++) order.push(i);- for (let i = order.length - 1; i > 0; i--) {- const j = Math.floor(rand() * (i + 1));- const t = order[i]; order[i] = order[j]; order[j] = t;- }- const pos = new Float32Array(count * 3);- const card = new Float32Array(count * 4);- let low = Infinity, high = -Infinity, scale = 0;- for (let i = 0; i < count; i++) {- const c = order[i % order.length];- const x = -extent / 2 + ((c % cells) + rand()) * step;- const z = -extent / 2 + (Math.floor(c / cells) + rand()) * step;- const y = ground ? ground(x, z) : 0;- pos[i * 3] = x; pos[i * 3 + 1] = y; pos[i * 3 + 2] = z;- const s = 0.72 + 0.62 * rand() * rand();- card[i * 4] = rand() * _TAU;- card[i * 4 + 1] = s;- card[i * 4 + 2] = (rand() * 2 - 1) * kind.hue;- card[i * 4 + 3] = rand();- low = Math.min(low, y); high = Math.max(high, y);- scale = Math.max(scale, s);- }- return { pos, card, low, high, scale };-}--/** Repeat each stand-in's data once per card it gets. */-function cardArray(src, cross, stride) {- if (!cross) return src;- const out = new Float32Array(src.length * 2);- for (let i = 0; i < src.length / stride; i++) {- for (let k = 0; k < stride; k++) {- out[i * 2 * stride + k] = src[i * stride + k];- out[(i * 2 + 1) * stride + k] = src[i * stride + k];- }- }- return out;-}--/** Card, silhouette and light — the whole stand-in, in one program. */-function imposterMaterial(cfg) {- return makeShaderMaterial({- name: 'Imposters',- uniforms: {- uImpKind: { value: cfg.kind.id },- uImpSize: { value: new THREE.Vector2(cfg.width, cfg.height) },- uImpFace: { value: cfg.cross ? 0 : 1 },- uImpSway: { value: cfg.kind.sway * cfg.wind.amp * 2 },- uImpWind: { value: cfg.wind.dir.clone() },- uImpSpeed: { value: cfg.wind.speed },- uImpColor: { value: cfg.color },- uImpSecond: { value: cfg.second },- uImpSun: { value: cfg.sun },- uImpBow: { value: new THREE.Vector4(- cfg.kind.bow[0], cfg.kind.bow[1], cfg.kind.bow[2],- cfg.kind.bow[3]) },- uImpMid: { value: cfg.kind.mid },- uImpSunColor: { value: cfg.sunColor },- uImpAmbient: { value: cfg.ambient },- },- varyings: 'varying vec2 vImpUv; varying vec4 vImpVar;'- + ' varying vec3 vImpN;',- vertexHead: [- 'attribute vec3 aCorner;',- 'attribute vec3 aPos;',- 'attribute vec4 aCard;',- 'uniform vec2 uImpSize;',- 'uniform float uImpFace;',- 'uniform float uImpSway;',- 'uniform float uImpSpeed;',- 'uniform vec2 uImpWind;',- 'uniform vec4 uImpBow;',- 'uniform float uImpMid;',- // The sun vector is a FRAGMENT uniform in the reference; the- // front/back test below needs it here too, and dedupeUniforms- // keeps the two declarations from colliding.- 'uniform vec3 uImpSun;',- glslLocalDir('impLocalDir'),- ].join('\n'),- vertexMain: [- ' vImpUv = uv;',- // Camera axes in LOCAL space (rows of modelViewMatrix), so a- // moved or rotated parent cannot tear the field off the camera.- ' vec3 camR = vec3(modelViewMatrix[0][0], modelViewMatrix[1][0],',- ' modelViewMatrix[2][0]);',- ' vec3 up = vec3(0.0, 1.0, 0.0);',- // A stand-in yaws, it never tips: a card that also pitches with- // the camera lifts a whole forest off the ground together.- ' vec3 faceR = normalize(camR - up * dot(camR, up)',- ' + vec3(1e-5, 0.0, 0.0));',- ' vec3 crossR = vec3(cos(aCard.x), 0.0, sin(aCard.x));',- ' vec3 right = normalize(mix(crossR, faceR, uImpFace));',- ' float hf = aCorner.y + 0.5;',- ' vec3 p = aPos + right * (aCorner.x * uImpSize.x * aCard.y)',- ' + up * (hf * uImpSize.y * aCard.y);',- // One wind for the whole scene (grass.js windOf), and only the- // top of the stand-in answers it.- ' vec3 rootWorld = (modelMatrix * vec4(aPos, 1.0)).xyz;',- ' float sw = uTime * uImpSpeed + astraStagger(rootWorld.x + rootWorld.z * 0.31);',- ' p += impLocalDir(vec3(uImpWind.x, 0.0, uImpWind.y))',- ' * (uImpSway * uImpSize.y * hf * hf * sin(sw));',- ' transformed = p;',- // A crown is round, and the two quads of a cross have to agree- // about that or the seam between them lights as a hard edge: the- // fake normal is RADIAL from the mass centre, not the card's own.- ' vec3 fwd = cross(right, up);',- ' vImpN = right * (aCorner.x * uImpBow.x)',- ' + up * ((hf - uImpMid) * uImpBow.y + uImpBow.w)',- ' + fwd * uImpBow.z;',- ' vImpN = astraNormalTransform(mat3(modelMatrix), vImpN);',- // The other quad of a cross is edge-on exactly when this one is- // square to the camera, and an edge-on card is a lit 1 px sliver- // down the middle of the crown. Fade it; nothing is lost.- ' vec3 camF = vec3(modelViewMatrix[0][2], modelViewMatrix[1][2],',- ' modelViewMatrix[2][2]);',- // WHICH SIDE OF THE MASS THE SUN IS ON, in world space, so it is- // the same answer for both quads of a cross and for a card that- // turns. +1 the sun is behind the camera (the visible half is the- // lit half); -1 the stand is between the camera and the sun and- // the visible half is in its own shadow, transmitting.- ' vec3 wPos = (modelMatrix * vec4(transformed, 1.0)).xyz;',- ' float sunSide = dot(uImpSun,',- ' normalize(cameraPosition - wPos));',- ' vImpVar = vec4(aCard.z, aCard.w,',- ' mix(smoothstep(0.10, 0.42, abs(dot(fwd, camF))), 1.0,',- ' uImpFace), sunSide);',- ].join('\n'),- fragmentHead: [- 'uniform float uImpKind;',- 'uniform vec3 uImpColor;',- 'uniform vec3 uImpSecond;',- 'uniform vec3 uImpSunColor;',- 'uniform vec3 uImpAmbient;',- 'uniform vec3 uImpSun;',- ].join('\n'),- fragmentMain: [- ' vec2 iq = vec2(vImpUv.x * 2.0 - 1.0, vImpUv.y);',- ' float iPh = vImpVar.y * 37.0;',- ' float iS = -1.0;',- ' vec3 iAlb = uImpColor;',- ' if (uImpKind < 0.5) {',- // A broadleaf is one ragged mass on a short stem, and the edge is- // where the eye decides tree or lollipop.- ' float tLean = (fract(iPh * 0.73) - 0.5) * 0.20 * iq.y;',- ' float tWide = 0.76 + 0.18 * fract(iPh * 0.41);',- ' vec2 tD = vec2((iq.x - tLean) / tWide,',- ' (iq.y - 0.64 - 0.025 * sin(iPh)) / (0.31 + 0.035 * fract(iPh)));',- ' float tR = length(tD);',- ' tR += 0.48 * (astraFbm2(vec2(atan(tD.y, tD.x) * 1.7, iPh), 3)',- ' - 0.44);',- ' float tCrown = 0.92 - tR;',- // Foliage has gaps between sprays and a porous outline. Filtering the- // finest field keeps a small distant crown stable rather than stippled.- ' vec2 tLeafP = iq * vec2(39.0, 52.0) + iPh;',- ' float tFootprint = max(length(dFdx(tLeafP)), length(dFdy(tLeafP)));',- ' float tLeaf = mix(astraFbm2(tLeafP, 3), 0.44, smoothstep(0.7, 2.0, tFootprint));',- ' float tClump = astraFbm2(iq * vec2(13.0, 19.0) + iPh * 1.3, 3);',- ' tCrown -= (0.50 - tClump) * 0.36 + (0.46 - tLeaf) * 0.22;',- ' float tGaps = tLeaf - mix(0.17, 0.33, (1.0 - smoothstep(0.02, 0.28, tCrown)));',- ' tCrown = min(tCrown, tGaps);',- ' iS = max(tCrown, min(0.026 - abs(iq.x - tLean * iq.y), 0.70 - iq.y));',- ' iAlb = mix(uImpSecond, uImpColor * (0.66 + 0.60 * iq.y),',- ' smoothstep(-0.02, 0.10, tCrown));',- ' } else if (uImpKind < 1.5) {',- // A spire that steps out at every whorl is a conifer; a clean- // triangle is a traffic cone.- ' float cW = 0.80 * pow(max(1.0 - iq.y, 0.0), 0.80);',- ' cW *= 0.78 + 0.34 * abs(fract(iq.y * 6.0 + iPh) - 0.5) * 2.0;',- ' cW -= 0.10 * astraFbm2(vec2(iq.y * 22.0, iPh), 2);',- ' iS = max(cW - abs(iq.x), min(0.035 - abs(iq.x), 0.14 - iq.y));',- ' iAlb = mix(uImpSecond, uImpColor * (0.60 + 0.62 * iq.y),',- ' smoothstep(0.10, 0.20, iq.y));',- ' } else if (uImpKind < 2.5) {',- // Head, shoulders and the gap between the legs. iq.x spans HALF- // the card and iq.y the whole height, so a round head is an- // ellipse here.- ' float pW = 0.60 - 0.17 * smoothstep(0.80, 0.90, iq.y)',- ' - 0.17 * (1.0 - smoothstep(0.52, 0.74, iq.y))',- ' + 0.07 * (1.0 - smoothstep(0.34, 0.52, iq.y));',- ' float pBody = min(min(pW - abs(iq.x), 0.90 - iq.y), iq.y);',- ' iS = max(0.29 - length(vec2(iq.x, (iq.y - 0.915) * 4.8)),',- ' min(pBody, max(abs(iq.x) - 0.11, iq.y - 0.38)));',- ' iAlb = mix(uImpSecond, uImpColor,',- ' smoothstep(0.38, 0.46, iq.y));',- ' iAlb = mix(iAlb, uImpColor * 1.35,',- ' smoothstep(0.85, 0.90, iq.y));',- ' } else {',- // A roofline that steps per instance, and windows that vanish on- // their own once a pixel spans one (astraStroke).- ' float bTop = 0.60 + 0.36 * fract(iPh * 3.7);',- ' float bW = 0.34 + 0.16 * fract(iPh * 7.3);',- ' iS = min(bW - abs(iq.x), bTop - iq.y);',- ' float bWin = astraStroke(iq.x * 7.0 + 0.5, 0.26)',- ' * astraStroke(iq.y * 13.0, 0.24)',- ' * step(iq.y, bTop - 0.06);',- ' iAlb = mix(uImpColor * (0.80 + 0.30 * iq.y), uImpSecond,',- ' bWin * 0.85);',- ' }',- // A card is antialiased by its own gradient or a distant stand- // stipples in and out of the frame as the camera turns.- ' float iAA = fwidth(iS) + 1e-4;',- ' float iA = clamp(iS / iAA + 0.5, 0.0, 1.0);',- // Dropped whole, never faded: a card that still writes depth at- // 5% alpha punches a sky-coloured hole through the one behind it.- ' if (iA < 0.5 || vImpVar.z < 0.5) discard;',- // LEAVES, NOT FELT. A crown is clumps with light between them,- // and one flat mass is what makes a card read as a cut-out at any- // distance. The field is in card space at the instance's own- // phase, so no two stand-ins clump alike.- ' float iLeaf = uImpKind < 1.5 ? 1.0 : 0.0;',- ' float iMass = astraFbm2(vec2(iq.x * 5.2, vImpUv.y * 5.2)',- ' + iPh, 3);',- ' iAlb *= 1.0 + iLeaf * (iMass - 0.375) * 1.15;',- ' float iFine = astraFbm2(vec2(iq.x * 17.0, vImpUv.y * 17.0)',- ' + iPh * 1.7, 2);',- ' iAlb *= 1.0 + iLeaf * (iFine - 0.375) * 0.85;',- ' vec2 iSprayP = iq * vec2(55.0, 72.0) + iPh * 2.1;',- ' float iSprayFootprint = max(length(dFdx(iSprayP)), length(dFdy(iSprayP)));',- ' float iSpray = mix(astraNoise2(iSprayP), 0.5, smoothstep(0.6, 1.8, iSprayFootprint));',- ' iAlb *= 1.0 + iLeaf * (iSpray - 0.5) * 0.60;',- // Hue VARIANCE inside one crown, not only between crowns: the- // sunlit leaves are yellow and the ones in the mass are- // blue-green, and a ball of one hue is a painted ball.- ' iAlb = astraHueBreak(iAlb, vec2(iq.x, vImpUv.y) + iPh, 3.3,',- ' mix(0.20, 0.62, iLeaf));',- ' iAlb = astraHueShift(iAlb, vImpVar.x);',- // The card is flat and the thing it stands for is not: the bowed- // normal is what puts a lit side and a shaded side on it.- ' vec3 iN = normalize(vImpN);',- ' float iNdL = max(dot(iN, uImpSun), 0.0);',- // A crown is a BALL, and the camera only ever sees one half of- // it. The bowed normal knows nothing about that, so on a BACKLIT- // stand it hands half of every card a full sun term the geometry- // beside it does not get — measured on this renderer at 1.41x the- // real crown's luminance, which is what a treeline pasted on with- // scissors looks like. Fold the sun down as the mass turns away.- ' iNdL *= mix(0.09, 1.0, smoothstep(-0.30, 0.45, vImpVar.w));',- // What a backlit crown DOES do is glow: the sun comes through the- // thin edge of the mass. Warm, weighted to the silhouette, and- // gone the moment the sun is on the camera's side.- ' float iEdge = 1.0 - smoothstep(0.0, 0.12, iS);',- ' float iBack = (1.0 - smoothstep(-0.70, 0.15, vImpVar.w));',- // Broken by the same clump field, or the glow is a stroke drawn- // round the silhouette rather than light coming through leaves.- ' vec3 iTrans = uImpSunColor * vec3(1.0, 0.82, 0.44)',- ' * (0.065 * iLeaf * iEdge * iBack',- ' * smoothstep(0.30, 0.52, iMass) * (0.25 + 0.75 * iFine));',- // A CROWN OCCLUDES ITSELF. Nothing else here can supply that — a- // card has no ambient occlusion, no self-shadow and no place in- // the shadow map — and handed the TRUE environment irradiance- // (the one every lit mesh in the scene receives) an unoccluded- // mass reads as a pale green cloud: measured 1.57x the real crown- // standing in the same field. The deep interior of a crown sees a- // fraction of the sky its outer leaves do. Floored, because that- // fraction is not zero: what bounced off the ground and off the- // rest of the wood gets in whatever the leaves do.- ' float iDeep = smoothstep(-0.02, 0.20, iS);',- ' float iAO = max(0.26,',- ' 0.60 - iLeaf * 0.34 * iDeep * (1.0 - 0.78 * iMass));',- // Irradiance over PI, the same arithmetic a built-in Lambert- // does, so a card sits at the brightness its geometry would.- // A crown's underside sees less sky than its top, and that- // gradient is most of what says "mass" rather than "cut-out".- ' vec3 iIrr = (uImpAmbient * iAO',- ' + uImpSunColor * iNdL * mix(1.0, iAO, 0.75) + iTrans)',- ' * mix(0.62, 1.06, smoothstep(0.0, 0.85, iq.y));',- ' gl_FragColor = vec4(iAlb * iIrr / PI, 1.0);',- ].join('\n'),- // Opaque clipping avoids partial-alpha halos between unsorted cards.- // The host post chain handles the silhouette's screen-space antialiasing.- transparent: false,- alphaToCoverage: false,- depthWrite: true,- side: THREE.DoubleSide,- });-}diff --git a/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md b/harness/codeverse3d/prompts/scene_threejs/effects_catalog.mdindex 5bf2abc1..2279dd74 100644--- a/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md+++ b/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md@@ -16,47 +16,17 @@ and `src/assets/x.js` say `import { makeGrass } from '../lib/grass.js';`,| Want | Call || --- | --- |-| a small flame or wax candle | `makeFire({ radius, height, seed, quality: 'high' })` · `makeCandle({ radius, height, seed, lit: true })` — `lib/fire.js`; volumetric flame, moving illumination, wick and wax. Returns a Group with `userData.update(t, dt)`; use metres (candle radius about 0.025, height 0.15). Fire is transparent: avoid intersecting glass volumes. |-| rising smoke, steam from a cup or vent | `makeSmoke({ height: 3, radius: 0.14, wind: [0.06, 0], riseSpeed: 0.7, seed, quality: 'balanced' })` · `makeSteam({ height: 0.5, radius: 0.03 })` — `lib/smoke.js`; bounded 3D density with upward advection, widening, dilution and internal light attenuation. Mesh origin is the emitter at local y=0. `userData.update(t)`, `userData.sampleDensity(x,y,z,t)` and `userData.dispose()`. Directional/point/ambient scene lights illuminate it. Keep opaque geometry outside its `userData.bounds`; intersections and overlapping transparent volumes are not depth-resolved. |-| the OCEAN, a lake or any sizeable water body | `makeOceanSurface({ width, depth, waveHeight, wavelength, windDirection: [1, 0.2], seed })` — `lib/ocean.js`, the ocean: dispersive Gerstner waves on real displaced geometry, reflected scene, crest foam; Group with `userData.update(t, dt)` and `userData.sampleHeight(x, z, t)`. Its flat option, for calm or distant water where no wave shape reads (a pond, a far lake): `makeOcean(w, d, { sunDir })` — `lib/water.js`, a normal-mapped mirror plane. Each planar reflector re-renders the scene once per frame: keep the total inside the fps / draw budget `scene_probe` reports (one is the safe default). |-| dunes, wind ripples, sand grains | `makeSandTerrain({ size: [60, 60], duneHeight: 3, duneSpacing: 18, windDirection: [1, 0.3], seed })` — `lib/sand.js`; Group with `userData.sampleHeight(x, z)` and `userData.update(t, dt)`. Sample height for every prop. || a close-view fractured rock or a talus field | `makeRock({ type: 'sandstone', size: [2, 1.5, 2], seed, moisture: 0.2 })` · `makeRockField` — `lib/rock.js`; types sandstone / granite / basalt; closed geometry, stratification and weathering. Rock rests at local y≈0; place using terrain height. |-| close-view grass with folded blades and flowing wind | `makeMeadow({ size: [8, 8], height: 0.3, density: 900, heightAt, mask, seed, wind: { dir: [1, 0.3], strength: 1.2, speed: 1 } })` — `lib/meadow.js`; every effect's wind option (wind; the veils' direction and drift; the ocean's and sand's windDirection) is read by ONE reader, `readWind` in `lib/shader.js` — a number, `[x, z]`, a vector or this object — so one wind object moves meadow, grass, trees, fire, smoke and rain alike; mask(x,z) is 0..1 coverage; Group with `userData.update(t, dt)`. Set `ground: false` over an existing terrain. Fit the sun shadow frustum tightly; blades need millimetre-scale shadow texels. || a grassy surface | `makeGrass({ extent, density, height, heightAt, patchy })` — `lib/grass.js` || a complete near/middle-distance tree or shrub | `makeTree({ species: 'oak', height: 6, crownRadius: 2.5, leafDensity: 1, seed, wind: { dir: [1,0.3], strength: 0.5, speed: 1 } })` · `makeShrub` — `lib/tree.js`; oak/birch/willow, connected branches, individual leaves and matching moving shadows. Root at y=0, actual envelope in `userData.bounds`. A default tree is heavy geometry. `leafSegments: 4` reduces per-leaf geometry while preserving crown density; species defaults are 10–16 for close views. Also lower `opts.maxLeaves`/`opts.leafDensity`, or use distant imposters when leaves are unresolved. |-| a crown of leaves for a broadleaf tree, a hedge or a bush | `makeCanopy({ crowns: [{position, radius, height}] — or [{position, size:[x,y,z]}] for a mass that is not a ball, which is how a hedge is built — color, hue, wind })` — `lib/canopy.js`; thousands of leaf cards as one draw call. Foliage is judged on whether it reads as leaves (silhouette break-up, light through it, hue spread): this is one construction that does — see the measurement at the end. || trees, bushes, leaves | `patchLeafSSS` · `patchWind` · `patchRootContact` — `lib/foliage_shade.js` |-| bark, and a forest at distance | `patchBark` · `makeImposters` — `lib/woodland.js` |-| light through a canopy | `patchDappledLight` · `patchCanopyShade` — `lib/dapple.js`; goes on the surface being LIT, not on the tree |-| flowers, drifting petals or leaves | `makeFlowers` · `makeFalling` — `lib/flowers.js` |-| birds or fish in motion | `makeFlock({ count, kind, extent, height, path })` — `lib/flock.js` |-| mist over moving water, spray where it lands | `makeWaterMist` · `makeSpray` — `lib/watermist.js` |-| a waterline | `patchShoreWet` · `patchShoreFoam` · `patchShallowWater` — `lib/waterside.js` |-| moss, damp near water, dried mud | `patchMoss` · `patchMoisture` · `patchCrackedMud` — `lib/damp.js` |-| rock, cliff, ground | `patchTriplanar` · `patchSlopeSplat` — `lib/terrain_shade.js` || ground and cliff geometry | `ground({ size, rand: mulberry32(seed), relief, flat })` returns `{ mesh, height }` — one terrain option (a displaced plane with a seeded heightfield and an optional flat mask; with no seeded rand it is flat); whatever the env's heightAt(x, z) returns must be its real height · `cliff({ length, height, rand })` — `lib/terrain.js`. The brief decides the landform; a floor, terraces or a canyon are not this call. |-| a cliff that reads as rock | `patchRockStrata` · `patchErosionStreaks` — `lib/strata.js`; bedding by world altitude, so every cliff in a scene shares one bedding plane || countryside continuing beyond the content | `makeOutskirts({ inner, baseY, heightAt, shellRadius, colors, seed })` — `lib/environment.js`; seam-matched relief, field patchwork and wooded clusters — one option for a rural setting. The requirement is that no camera sees the ground end against the sky (`world_edge_visible`) or a diorama on an empty plane (judged); how the world continues — a street that keeps going, a sea, a canyon wall, a city, fog that closes — is the brief's. || a Blender hero's own keyframed motion (the GLB carries a clip) | nothing to call — the assembled scene plays every clone's clips; `clone.userData.clipOffset = 0.7` de-phases a copy || the sun, the fill and the baked environment | `sunRig({ azimuth, elevation })` — `lib/environment.js`; returns `{ sun, fill, sunDisc, envTex, sunDir }`. Add the lights, assign `scene.environment = rig.envTex` || a rectangular interior's walls, ceiling and window/door openings | `roomShell({ center, extents, openings, thickness, wallColor, ceilingColor, glazed, frameColor, bay })` — `lib/environment.js`; walls sit outward of the box you pass (inner face = that box's face, which need not be the plan bounds), openings cut as span / sill / lintel panels; glazed: true makes every wall and the roof glass on an iron frame grid (a conservatory, greenhouse, glass atrium). One option for a box-shaped room; the requirement for any interior is that it reads as enclosed from every camera (six runs measured "not enclosed, a diorama on a flat plane" with no walls or roof) || the sky itself | `makeSky(scene, { rig })` — `lib/sky.js`; the dome IS the backdrop; it keeps a `scene.background` already set and gives an unset one its horizon colour |-| cloud, cirrus | `makeClouds({ preset, sunDir, quality: 'balanced' })` · `makeCirrus()` — one ray-marched cloud deck with scene-lit self-shadowing; `lib/clouds.js` |-| volumetric cumulus with internal sunlight attenuation | `makeCloudVolume({ size: [600,180,360], coverage: 0.55, density: 0.028, wind: [2.5,0.4], seed, quality: 'balanced' })` — `lib/cloudvolume.js`; Mesh centred on its local origin. Move it to cloud altitude. Wind advects density/erosion inside a bounded billow scaffold; translate the Mesh to move the whole cloud. `userData.sampleDensity(x,y,z,t)` mirrors the GPU field. Use one bounded sky volume and inspect its screen cost. No terrain shadows or opaque-depth intersections. |-| stars, the Milky Way, aurora, heat shimmer | `makeStars` · `makeAurora` · `makeHeatShimmer` — `lib/celestial.js` |-| fog on the ground, distance haze | `makeHeightFog` · `patchAerialPerspective` — `lib/atmosphere.js` |-| shafts of light | `makeGodRays({ count, height, sunDir, ambient })` — `lib/godrays.js`; the default is daylight — pass `ambient` BELOW 0.35 only for a genuinely unlit interior, where the shafts switch to adding light |-| rain sheets at distance, snowfall, motes | `makeRainVeil` · `makeSnowfall` · `makeMotes` — `lib/veils.js`; weather you see ACROSS the valley |-| a building, a cottage, a city block | `block` · `cottage` · `cityFabric` — `lib/building.js` |-| a glazed facade, power lines, a hoarding | `patchCurtainWall` · `makePowerLines` · `makeBillboard` — `lib/urban.js`; the facade spends no second render target |-| a neon sign, and the light it throws | `makeNeonTube` · `patchNeonSpill` · `makeLightTrails` — `lib/neon.js`; a sign that does not light its own wall is a decal |-| a road, a path, a worn surface | `patchRoadSurface` · `patchSeamBand` · `patchTracks` — `lib/roadway.js` |-| foreground cobbles or rectangular stone setts with real joints | `makePaving({ size: [4,4], stoneSize: 0.24, pattern: 'cobble', joint: 0.012, thickness: 0.10, relief: 0.014, seed })` — `lib/paving.js`; merged closed bevelled stones and a recessed joint bed, two meshes and a bounded stone count. Nominal top is y=0, bottom=-thickness. `userData.sampleHeight(x,z)` returns the exact local stone/joint height; seat props using it. Use material-only cobbles for distant surfaces. |-| a flag, a hanging banner, a wheat field | `makeFlag` · `makeBanner` · `makeWheatField` — `lib/cloth.js`; the wave TRAVELS |-| a surface that has stood somewhere | `patchDripStains` · `patchRust` · `patchDust` — `lib/aging.js` |-| any surface at all | `patchMicroBreakup` · `patchEdgeWear` — `lib/surface_wear.js` || paper, wax, jade, petals; oil film, beetle shell | `patchTranslucency` · `patchIridescence` — `lib/finish.js` |-| the same asset hundreds of times, in one draw call | `mergeStatic(meshes)` — `lib/merge.js` || a textured standard material without a texture file | `brick` · `granite` · `cobble` · `asphalt` · `weatheredWood` · `brushedSteel` · `fabric` · `foliage` · `soil` · `skin` · `glass` (21 in all) · `tint(mat, variant)` — `lib/materials.js` || noise on the CPU (heightfields the shader must agree with) | `fbm2` · `fbm3` · `mulberry32` · `displaceY` — `lib/noise.js` || your own shader, safely | `makeShaderMaterial` · `patchStandard` · `shadowLike` · `tickShaders` — `lib/shader.js` |@@ -65,8 +35,7 @@ and `src/assets/x.js` say `import { makeGrass } from '../lib/grass.js';`,## The four rules that apply to all of them-**New natural-element factories use one lifecycle.** Fire, candle, ocean,-sand, meadow, smoke, steam, tree, shrub, cloud volume and paving provide+**The natural-element factories use one lifecycle.** Tree, shrub, rock and grass provide`object.userData.update(t, dt)` (absolute seconds)and `object.userData.dispose()`. Store the returned objects and update each ONCEfrom the zone's `userData.update`. Their dimensions, paths and height queries are@@ -76,9 +45,8 @@ returns the surface height there, or `null` off the patch. Itnever throws, so test for `null` before seating a prop. These are realtimeprocedural effects, not fluid/combustion solvers. Read the module's JSDoc foroptions and bounds: an option left out or `null` takes its default, and an invalid-one throws a RangeError that names it (fire clamps an out-of-range number instead).-The direction toward the sun is `sunDir` in every factory. For older effects, follow-the hooks listed below.+one throws a RangeError that names it.+The direction toward the sun is `sunDir` in every factory.**1. `patch*` entries CHAIN.** Apply as many as a surface deserves to onematerial, in any order — they are composed into one program. Two patches may@@ -105,9 +73,9 @@ function update(t, dt) {and in a zone, call the effect's own hook from the group's `update`:```js-const motes = makeMotes();-g.add(motes);-g.userData.update = (t, dt) => { motes.userData.update(t, dt); };+const lawn = makeGrass({ extent: 6, heightAt });+g.add(lawn);+g.userData.update = (t, dt) => { lawn.userData.update(t, dt); };```Calling a missing hook throws and can stop the whole scene's animation.@@ -115,9 +83,9 @@ Anything built with `patchStandard` is driven instead by one`tickShaders(scene, t)` — call it once, in `scene.js`'s `update`. An effectwhose hook is never called stands still.-**3. Shadows.** Displaced vegetation casts REAL moving shadows: flags,-banners, reeds and flowers by default; grass and wheat behind `shadows: true`-(tens of thousands of instances in the shadow map is a cost you opt into). A+**3. Shadows.** Displaced vegetation casts REAL moving shadows: trees by+default; grass behind `shadows: true` (tens of thousands of instances in the+shadow map is a cost you opt into). Adisplaced lattice of your own gets the same through `shadowLike` in`lib/shader.js` — without it the shadow is cast by the UNDISPLACED geometry.@@ -151,6 +119,6 @@ stacked 32 of them per tree and shipped what the renderer flagged as "a single funtextured material, an unreadable slab" (judged `asset_quality_detail`). Measured onthe same tree: hue spread across the crown went from 3.6° to 9.4° and the 5–95 rangefrom 10 to 22 when the crown became separate leaf cards — a photograph carries 25–45.-Any construction that gets there is fine; `makeCanopy` (near crowns, hedges, bushes)-and `makeImposters` (a far treeline) are two shipped options, and a stylised brief-(low-poly, paper-craft) may legitimately want something else.+Any construction that gets there is fine; `makeTree` / `makeShrub` (separate leaf cards)+is the shipped option, and a stylised brief (low-poly, paper-craft) may legitimately want+something else.diff --git a/harness/codeverse3d/prompts/scene_threejs/system.md b/harness/codeverse3d/prompts/scene_threejs/system.mdindex 01ed94ab..2f3608ff 100644--- a/harness/codeverse3d/prompts/scene_threejs/system.md+++ b/harness/codeverse3d/prompts/scene_threejs/system.md@@ -51,7 +51,7 @@ What is measured on every authored camera (the `scene_frames` gate, ERROR on faiby more than 60/255). No authored camera moving is `no_motion` (ERROR); the judge's`nothing_moves` follows it.* **Budget.** `scene_probe` reports draw calls and triangles (WARN above 5 000 draws, ERROR- above 15 000; 3 000 000 unique triangles). Instancing (`InstancedMesh`, `mergeStatic`) is+ above 15 000; 3 000 000 unique triangles). Instancing (`InstancedMesh`) or merged static geometry ishow repeated geometry usually stays inside it.Requirements that hold for every brief:diff --git a/harness/codeverse3d/prompts/tracks/plan_scene.j2 b/harness/codeverse3d/prompts/tracks/plan_scene.j2index 38b37bc5..aec2863a 100644--- a/harness/codeverse3d/prompts/tracks/plan_scene.j2+++ b/harness/codeverse3d/prompts/tracks/plan_scene.j2@@ -12,12 +12,11 @@ LANGUAGE CONTRACT THE BUILDERS WILL FOLLOW:{{ contract }}SHIPPED LIBRARY (optional toolbox):-The scene workspace already contains, under `src/lib/`: `fire.js` (`makeFire`, `makeCandle`),-`smoke.js` (`makeSmoke`, `makeSteam`), `cloudvolume.js`-(`makeCloudVolume`), `ocean.js` (`makeOceanSurface`), `sand.js` (`makeSandTerrain`),+The scene workspace already contains, under `src/lib/`:`rock.js` (`makeRock`, `makeRockField`: sandstone / granite / basalt rocks and talus),-`tree.js` (`makeTree`: oak / birch / willow; `makeShrub`), `meadow.js` (`makeMeadow`) and-`paving.js` (`makePaving`). Use a call when its output fits the brief: name it, its module and+`tree.js` (`makeTree`: oak / birch / willow; `makeShrub`), `grass.js` (`makeGrass`),+`terrain.js` (`ground`, `cliff`) and `environment.js` (`sunRig`, `makeOutskirts`, `roomShell`).+Use a call when its output fits the brief: name it, its module andits dimensions in the owning zone description / environment / effects. An element the librarydoes not grow in the form the brief wants (a pine, a palm, a carved stone, a different kind ofboat) is an asset built from scratch within the triangle budget below; so is a grove or forest,diff --git a/harness/codeverse3d/prompts/tracks/scene_env.j2 b/harness/codeverse3d/prompts/tracks/scene_env.j2index 5d23d2be..7c4960ec 100644--- a/harness/codeverse3d/prompts/tracks/scene_env.j2+++ b/harness/codeverse3d/prompts/tracks/scene_env.j2@@ -93,8 +93,7 @@ and the zones, read by nothing in the harness.fill, env map, disc and shadows for a sunlit exterior in one call — one option; any light setthat passes the gate and matches the brief's sources is as good.Aerial perspective is judged (`thin_atmosphere`: "horizon with no atmospheric falloff"): fog- does most of it; `makeHeightFog` / `patchAerialPerspective` in `lib/atmosphere.js` are optional- extras, kept subtle or the frame reads milky (`blown_frac`).+ does most of it, kept subtle or the frame reads milky (`blown_frac`).5. **Shadows are not jagged** (judged): a shadow texel ≤ ~0.05 m over the content.`sunRig({ bounds })` fits frustum, map size and bias to the radius it is given — pass thecontent radius, not the ground size; a hand-set `sun.shadow.*` must meet the same texel size.diff --git a/harness/codeverse3d/prompts/tracks/scene_refine.j2 b/harness/codeverse3d/prompts/tracks/scene_refine.j2index dd872bf7..364ca016 100644--- a/harness/codeverse3d/prompts/tracks/scene_refine.j2+++ b/harness/codeverse3d/prompts/tracks/scene_refine.j2@@ -64,7 +64,7 @@ the number passes; a judge note that repeats needs a visible change in the named| sparse, token, "a diorama on a plane", empty midground | the description's contents are requirements (the census compares them: `missing_content`, `zone_empty`; a count under half the layout's is an INFO `density_note`); "sparse / diorama" means the frame has empty regions the brief would fill — fill them with what the brief implies || flat / dark / monochrome light, black shade, jagged shadows | flat / dark frames are measured (mean lum, std, flat band); jagged shadows mean shadow texels larger than ~0.05 m over the content — tighten the frustum (`sunRig({ bounds })` with the content radius); the light's colours are the brief's time of day and sources || frames at t=0 and t=1.5 identical, "nothing moves", `no_motion` | a camera moves when ≥ 0.4 % of its pixels change by more than 8/255 (or ≥ 0.08 % by more than 60/255); none moving is the gate's `no_motion` ERROR and the judge's `nothing_moves`; the hook is `userData.update` (never `tick`), and the amplitude has to show at 1024×576 (foliage ±0.10–0.20 rad, particles ≥ 0.6 m per 1.5 s, water ≥ 3 cm or a scrolling normal are amplitudes that have passed) |-| `hard_edged_particles`, "sharp-edged quads / spheres / discs for steam, dust, sparks", the brief's "soft particle effect" must-item unverified | the finding measures sharp-edged particle sprites; any soft-edged construction passes (the library's `makeSmoke` / `makeSteam` / `makeMotes` / `makeFire` volumes, or a radial-alpha sprite on every point) |+| `hard_edged_particles`, "sharp-edged quads / spheres / discs for steam, dust, sparks", the brief's "soft particle effect" must-item unverified | the finding measures sharp-edged particle sprites; any soft-edged construction passes (a bounded density volume, or a radial-alpha sprite on every point) || camera inside geometry / shows only sky or a wall | the eye must be ≥ 0.5 m from every surface and the frame ≥ 10 % content (20 % for the establishing view): move the camera in `src/scene.js` or what blocks it |{% if current_files %}diff --git a/harness/codeverse3d/prompts/tracks/scene_zone.j2 b/harness/codeverse3d/prompts/tracks/scene_zone.j2index 2ecaeeb8..39870cf4 100644--- a/harness/codeverse3d/prompts/tracks/scene_zone.j2+++ b/harness/codeverse3d/prompts/tracks/scene_zone.j2@@ -99,10 +99,10 @@ So `{{ zone_file }}` exports `export function build(ctx) → THREE.Group` namedacross the frame, everything a pure function of `t`, driven from `userData.update`. Particlesmust be soft-edged (judge `hard_edged_particles`: bare `PointsMaterial` squares, a chain ofspheres for a steam jet, polygon sparks all fire it, and with it the brief's "soft particle- effect" must-item) — the library's volumes or a radial-alpha sprite both pass.+ effect" must-item) — a bounded density volume or a radial-alpha sprite both pass.6. **Budget.** Stay inside the draw-call / triangle budget `scene_probe` reports (WARN above 5 000- draws, ERROR above 15 000; 3 000 000 unique triangles); `InstancedMesh` / `mergeStatic` are the cheap- ways to repeat.+ draws, ERROR above 15 000; 3 000 000 unique triangles); `InstancedMesh` and merged static geometry are+ the cheap ways to repeat.## DON'T- Sun, sky, ground and cameras are the env's. This zone may add the practical lights its settingdiff --git a/harness/codeverse3d/skills/c3d-scene-atmosphere/SKILL.md b/harness/codeverse3d/skills/c3d-scene-atmosphere/SKILL.mdindex b01b68fe..989e81c9 100644--- a/harness/codeverse3d/skills/c3d-scene-atmosphere/SKILL.md+++ b/harness/codeverse3d/skills/c3d-scene-atmosphere/SKILL.md@@ -36,7 +36,7 @@ horizon-to-zenith gradient, a sun term around `sunDir` (a halo and, if the briefshows it, a disk), and a haze band that pulls the lowest degrees toward the horizon colour.The curve shapes and the colours are the brief's sky: a low sun widens the halo and warms thehorizon, an overcast sky is one flat gradient, a night sky hashes the direction for stars-(`makeStars`, `makeAurora` in `lib/celestial.js` do it for you) and shades a moon.+and shades a moon.## Bake the SAME sky into `scene.environment`@@ -62,20 +62,19 @@ If you bake your own equirect `DataTexture`, these are bugs when broken:Requirement: if the brief's sky has clouds, they read as soft volumes at the authoredcameras, not as hard-edged cards (judged: `hard_edged_particles`, `materials_shaders_effects`).-Strong options: `makeClouds` / `makeCirrus` from `lib/clouds.js` (one ray-marched deck,-scene-lit); `makeCloudVolume` from `lib/cloudvolume.js` when a cumulus is close enough to-need internal light; or sprite puffs from one shared radial-gradient canvas in a flattened-cluster, bottoms tinted darker, `depthWrite: false`. Volumetrics cost frame time; the brief-decides whether a cloud earns it.+Strong options: a ray-marched deck lit from `sunDir` for a sky-filling layer, a volume with+internal light when a cumulus is close enough to need it, or sprite puffs from one shared+radial-gradient canvas in a flattened cluster, bottoms tinted darker, `depthWrite: false`.+Volumetrics cost frame time; the brief decides whether a cloud earns it.## HazeIf the brief's weather has haze or fog: keep it in the sky's hue family and thin enough thatthe midground stays readable — the frame gate reads a washed frame as `flat_frame` (oneluminance band holding > 92 % of an authored frame is an ERROR) and the judge reads no-falloff at all as `thin_atmosphere`. `makeHeightFog` and `patchAerialPerspective` from-`lib/atmosphere.js` do ground fog and distance haze; `scene.fog` alone does the simplest-version. A clear dry day may have almost none. The shader-trap skill covers the fog uniforms+falloff at all as `thin_atmosphere`. `scene.fog` does the simplest version; ground fog is+a height-faded layer of your own, distance haze a view-distance blend toward the horizon+colour. A clear dry day may have almost none. The shader-trap skill covers the fog uniformscustom shaders must honour.## Verify before you finishdiff --git a/harness/codeverse3d/skills/c3d-scene-atmosphere/references/exotic-space.md b/harness/codeverse3d/skills/c3d-scene-atmosphere/references/exotic-space.mdindex 4c7a4144..4eac9f7b 100644--- a/harness/codeverse3d/skills/c3d-scene-atmosphere/references/exotic-space.md+++ b/harness/codeverse3d/skills/c3d-scene-atmosphere/references/exotic-space.md@@ -37,9 +37,8 @@ pattern visible through the throat is what sells it.## Nebula and starfieldLarge additive fbm-canvas billboards (alpha = fbm squared) in two or three hues, plus a-few near-black NORMAL-blended dust-lane sprites. Starfield: `makeStars` from-`lib/celestial.js`, or `Points` with power-law brightness, a slight colour spread and a-few hero stars with cross-flare sprites.+few near-black NORMAL-blended dust-lane sprites. Starfield: `Points` with power-law+brightness, a slight colour spread and a few hero stars with cross-flare sprites.## Planetdiff --git a/harness/codeverse3d/skills/c3d-scene-composition/SKILL.md b/harness/codeverse3d/skills/c3d-scene-composition/SKILL.mdindex c1d47a12..50e78ce9 100644--- a/harness/codeverse3d/skills/c3d-scene-composition/SKILL.md+++ b/harness/codeverse3d/skills/c3d-scene-composition/SKILL.md@@ -113,11 +113,11 @@ How the world continues is the brief's place. Strong options, each on its own enland from the content out to the fog with seam-matched relief, fields and woodedclusters; `ground` from `lib/terrain.js` with its `relief` option is the simpler version.* **A ridge or mesa on ONE side**, with the opposite side falling away to fog or water.-* **A treeline** (`makeImposters` from `lib/woodland.js` at distance) or an orchard edge.-* **A far skyline** — `cityFabric` from `lib/building.js`, a harbour wall, a viaduct.-* **A shoreline**: `makeOceanSurface` or `makeOcean` to the horizon on one or more sides.+* **A treeline** (imposter cards at distance) or an orchard edge.+* **A far skyline** — a city block mass, a harbour wall, a viaduct.+* **A shoreline**: water to the horizon on one or more sides.* **Fog only**, when the brief's weather is thick enough that the ground fades before it- ends (`makeHeightFog`, `patchAerialPerspective` from `lib/atmosphere.js`).+ ends.* **Walls, cliffs, or an interior** with no horizon at all (`roomShell`, `cliff`).A ring of near-identical copies stamped evenly round the world is measureddiff --git a/harness/codeverse3d/skills/c3d-scene-lighting/SKILL.md b/harness/codeverse3d/skills/c3d-scene-lighting/SKILL.mdindex ace9dbdf..d0c84c86 100644--- a/harness/codeverse3d/skills/c3d-scene-lighting/SKILL.md+++ b/harness/codeverse3d/skills/c3d-scene-lighting/SKILL.md@@ -106,8 +106,7 @@ the band are measured failures, one week apart in the same wave:So every lantern, lamp, sign, window or fire near a camera gets its OWN `PointLight` nextto its emissive surface (the starter's `PRACTICAL` numbers in `lib/environment.js` are-one measured setting; `makeNeonTube` + `patchNeonSpill` in `lib/neon.js` do a sign and the-light it throws), a low but non-zero base colour on dark materials so they read as material+one measured setting), a low but non-zero base colour on dark materials so they read as materialand not as void, and shadows left dark. The starter night rig was measured to sit in theband; added fills push the frame out of it, as the courtyard showed.diff --git a/harness/codeverse3d/skills/c3d-scene-materials/SKILL.md b/harness/codeverse3d/skills/c3d-scene-materials/SKILL.mdindex d99f72d8..9eb95300 100644--- a/harness/codeverse3d/skills/c3d-scene-materials/SKILL.md+++ b/harness/codeverse3d/skills/c3d-scene-materials/SKILL.md@@ -27,9 +27,8 @@ Requirement: at crop scale no large surface reads as a single untextured value ubrief's material really is flat — new paint, a lacquered floor (judged: `placeholder_material`,`flat_ground`). A strong option: the shipped procedural materials in `lib/materials.js`(`plaster`, `brick`, `granite`, `cobble`, `asphalt`, `weatheredWood`, `soil`, `foliage` and-the rest) already carry low-contrast variance; `patchMicroBreakup` and `patchEdgeWear` from-`lib/surface_wear.js` chain onto any material you made yourself. A `noiseTexture` from the-same module as `roughnessMap` breaks a highlight into something other than a perfect oval.+the rest) already carry low-contrast variance. A `noiseTexture` from the same module as+`roughnessMap` breaks a highlight into something other than a perfect oval.## Copies do not read as twins@@ -52,8 +51,8 @@ it vary across the surface.## Edges near the lensNear an authored camera a razor 90° edge catches light like CAD (judged:-`asset_quality_detail`). A chamfer (`ExtrudeGeometry` with `bevelEnabled`), a bevelled-`makePaving` for cobbles, or smoothed normals is one way out; background boxes can stay+`asset_quality_detail`). A chamfer (`ExtrudeGeometry` with `bevelEnabled`), bevelled+cobbles, or smoothed normals is one way out; background boxes can staysharp.## Terrain that reads as a landform@@ -66,8 +65,8 @@ options when the place has relief: `ground` from `lib/terrain.js` with `relief`seeded `rand`, returning the mesh and the height function in one; or your own heightfieldfrom domain-warped `fbm2` (`lib/noise.js`) with a power curve so lowlands stay flat andridges steepen, normals recomputed after displacement. Colour by slope and height with the-materials the place has — `patchSlopeSplat` and `patchTriplanar` from `lib/terrain_shade.js`-do that in the shader; a worn path or a wheel rut carved into `heightAt` itself lands+materials the place has — a slope splat in the shader (`patchStandard` from `lib/shader.js`+keeps the fog and depth chunks); a worn path or a wheel rut carved into `heightAt` itself landseverything placed on it at the right height. The alpine sand/grass/rock/snow ramp is onepalette, right for an alpine brief.@@ -76,10 +75,10 @@ palette, right for an alpine brief.The judge's `monotonous_vegetation` is "one shape stamped many times — no variation insilhouette, size or hue, and placed in a ring or a grid rather than clusters". So: morethan one species where the place has more than one (`makeTree` / `makeShrub` from-`lib/tree.js` for near trees, `makeCanopy` for every broadleaf crown and hedge,-`makeImposters` for a forest at distance), clusters with clearings rather than a lattice+`lib/tree.js` for near trees, imposter cards for a forest at distance), clusters with+clearings rather than a lattice(a jittered grid times a clump mask from `fbm2` is one option), and a ground-cover layer (`makeGrass`, `makeMeadow`) so plants grow out of the ground instead of standing+cover layer (`makeGrass`) so plants grow out of the ground instead of standingon it.## Dressing@@ -88,8 +87,8 @@ The judge's `undressed_scene` is "no small props or clutter — a showroom of aobjects". A place has the small things its use leaves behind: tools by the bench, cups onthe table, litter at the kerb, pebbles at the water, cables on the wall. Props againstsomething (a wall base, a path edge, under a bench) read as belonging; props alone on open-ground read as scatter. `patchSeamBand` and `patchTracks` (`lib/roadway.js`) dress where a-structure meets the ground, so the seam is not a hard undressed line (`flat_ground`).+ground read as scatter. A seam band or wheel tracks dress where a structure meets the+ground, so the seam is not a hard undressed line (`flat_ground`).## Seating is measureddiff --git a/harness/codeverse3d/skills/c3d-scene-materials/references/terrain-and-scatter.md b/harness/codeverse3d/skills/c3d-scene-materials/references/terrain-and-scatter.mdindex 1d681325..e70745ac 100644--- a/harness/codeverse3d/skills/c3d-scene-materials/references/terrain-and-scatter.md+++ b/harness/codeverse3d/skills/c3d-scene-materials/references/terrain-and-scatter.md@@ -27,7 +27,7 @@ function height(x, z) {## Colour by slope and height-Vertex colours or `patchSlopeSplat` (`lib/terrain_shade.js`): a steep-slope material+Vertex colours or a slope splat in the shader: a steep-slope material(rock, bare earth) overriding by `normal.y`, then height bands blended by smoothstep withthe materials the place has, each band jittered by a high-frequency noise, band edgesoverlapping rather than a hard line.diff --git a/harness/codeverse3d/skills/c3d-scene-motion/SKILL.md b/harness/codeverse3d/skills/c3d-scene-motion/SKILL.mdindex eab4e3aa..15525f9c 100644--- a/harness/codeverse3d/skills/c3d-scene-motion/SKILL.md+++ b/harness/codeverse3d/skills/c3d-scene-motion/SKILL.md@@ -114,7 +114,7 @@ return { scene, cameras, update(t, dt) {Add a mover to the list in the same edit that creates it — a zone whose`userData.update` nobody walks is failure mode 2 wearing a disguise. Library effects-(`makeFire`, `makeSmoke`, `makeOceanSurface`, `makeFlag` …) carry their own+(`makeTree`, `makeGrass`, `makeRock` …) carry their own`userData.update(t, dt)`; call each once from the zone that owns it, and anything builtwith `patchStandard` is driven by one `tickShaders(scene, t)` in `scene.js`.@@ -187,12 +187,11 @@ is a decal. Options that read:* **Paths**: a `CatmullRomCurve3`sampled at `(t * speed / len + u0) % 1`, facing the tangent; distinct `u0` offsets spacethe traffic.-* **Rain** as elongated streaks (`makeRainVeil` at distance) — elongation is- the motion cue; **snow** as soft sprites with per-flake sway (`makeSnowfall`); **motes**- and pollen from `makeMotes`; every particle gets its own phase so a frozen frame is- mid-motion, never at a synchronized extreme.-* **Fire additive, smoke normal**: `makeFire` with a flickering light,- `makeSmoke` / `makeSteam` as a bounded density — a chain of spheres is not steam.+* **Rain** as elongated streaks — elongation is the motion cue; **snow** as soft sprites+ with per-flake sway; **motes** and pollen the same; every particle gets its own phase so a+ frozen frame is mid-motion, never at a synchronized extreme.+* **Fire additive, smoke normal**: a flame with a flickering light, smoke and steam as a+ bounded density — a chain of spheres is not steam.## Depthdiff --git a/harness/codeverse3d/skills/c3d-scene-motion/references/motion_recipes.md b/harness/codeverse3d/skills/c3d-scene-motion/references/motion_recipes.mdindex 1e4b96b3..9de88722 100644--- a/harness/codeverse3d/skills/c3d-scene-motion/references/motion_recipes.md+++ b/harness/codeverse3d/skills/c3d-scene-motion/references/motion_recipes.md@@ -4,10 +4,9 @@ The measure: each authored camera is rendered at t = 0 and t = 1.5 s and the twodifferenced; a camera MOVES when ≥ 0.4 % of its pixels change by more than 8/255 (or ≥ 0.08 %by more than 60/255). None moving is the gate's `no_motion` ERROR and the judge's`nothing_moves`. Everything below is one way to clear it; the library's own movers-(`makeFalling` in `lib/flowers.js`, `makeSnowfall` / `makeMotes` in `lib/veils.js`,-`makeFlock` in `lib/flock.js`, `makeFlag` in `lib/cloth.js`, `patchWind` in `lib/foliage_shade.js`)-cover the common cases without any code of-yours, and each carries `userData.update(t, dt)` for the zone to call.+(`makeTree` / `makeShrub` in `lib/tree.js`, `makeGrass` in `lib/grass.js`, `patchWind` in+`lib/foliage_shade.js`) cover swaying vegetation without any code of yours, and each carries+`userData.update(t, dt)` for the zone to call.## Seeded randomnessdiff --git a/harness/codeverse3d/skills/c3d-scene-night/SKILL.md b/harness/codeverse3d/skills/c3d-scene-night/SKILL.mdindex dde31c82..d4e9f5f7 100644--- a/harness/codeverse3d/skills/c3d-scene-night/SKILL.md+++ b/harness/codeverse3d/skills/c3d-scene-night/SKILL.md@@ -47,8 +47,7 @@ shaft.Measured in the reference harness: a NORMAL-blended shaft at 0.3+ opacity renders as asolid white TENT and buries the scene behind it. Additive blending at a few percent opacity,-alpha fading along the cone, is the range that reads; `makeGodRays` from `lib/godrays.js`-does it with its own ceiling. If the shaft reads clearly in a thumbnail, it is too strong.+alpha fading along the cone, is the range that reads. If the shaft reads clearly in a thumbnail, it is too strong.## Wet roaddiff --git a/harness/codeverse3d/skills/c3d-scene-water/SKILL.md b/harness/codeverse3d/skills/c3d-scene-water/SKILL.mdindex 64c8df06..6fdd19ff 100644--- a/harness/codeverse3d/skills/c3d-scene-water/SKILL.md+++ b/harness/codeverse3d/skills/c3d-scene-water/SKILL.md@@ -1,6 +1,6 @@---name: c3d-scene-water-description: "Use when a scene_threejs session builds water in any form - pond, lake, harbor, river, ocean, pool, canal, waterfall or fountain. Water is a dielectric, not a mirror: the single most common water bug is metalness, and the second is an environment bake it has nothing to reflect. States what has to be true and how the judge and the motion probe read it, then the library's water modules as the strong options, the shared noise block that keeps terrain, shoreline and scatter agreeing, Gerstner for open water, and foam that reads."+description: "Use when a scene_threejs session builds water in any form - pond, lake, harbor, river, ocean, pool, canal, waterfall or fountain. Water is a dielectric, not a mirror: the single most common water bug is metalness, and the second is an environment bake it has nothing to reflect. States what has to be true and how the judge and the motion probe read it, then the shared noise block that keeps terrain, shoreline and scatter agreeing, Gerstner for open water, and foam that reads."license: Apache-2.0compatibility: three r0.182, headless WebGL; ACES tone mapping, exposure 1.0.metadata:@@ -32,17 +32,7 @@ why real water is dark at your feet and mirror-bright at the horizon.pixel bar (`nothing_moves`).* The shoreline agrees with the terrain: water, bank and anything seated near it sample theone height function, or the placement gate reports `floating` / `sunken` at the edge.-* ONE reflective water body per scene (the library's reflectors each re-render the scene).--## Strong options from the library--`makeOceanSurface` from `lib/ocean.js` for the ocean, a lake or any sizeable body-(dispersive Gerstner waves on displaced geometry, reflected scene, crest foam);-`makeOcean` from `lib/water.js` for calm or distant water where no wave shape reads;-`makeWaterMist` / `makeSpray` from `lib/watermist.js`;-`patchShoreWet` / `patchShoreFoam` / `patchShallowWater` from `lib/waterside.js` on the-bank. Each-carries `userData.update(t, dt)` — call it from the zone's own update.+* ONE reflective water body per scene (a planar reflector re-renders the scene).## Your own material@@ -67,11 +57,11 @@ terrain uses.Foam from DEPTH against the shared height hugs the banks and reads in a still frame; crestfoam on open water is harder and pays less. Open ocean reads as sea when the surface itself-displaces (Gerstner waves, dispersive — `makeOceanSurface` ships them; your own keeps the-steepness sum below 1 or the crests loop over, and takes normals from the displaced-surface) rather than only scrolling normals on a flat plane. A waterfall reads with scrolled-vertical streaks thresholded to white over translucent water and soft mist at the base-(`makeWaterMist`); a fountain's particles as pure ballistic arcs of `t` still+displaces (Gerstner waves, dispersive — keep the steepness sum below 1 or the crests loop+over, and take normals from the displaced surface) rather than only scrolling normals on a+flat plane. A waterfall reads with scrolled+vertical streaks thresholded to white over translucent water and soft mist at the base; a+fountain's particles as pure ballistic arcs of `t` stillread frozen mid-flight. `references/gerstner-and-foam.md` has the wave maths.## Verify before you finishdiff --git a/harness/codeverse3d/skills/c3d-scene-water/references/gerstner-and-foam.md b/harness/codeverse3d/skills/c3d-scene-water/references/gerstner-and-foam.mdindex ff28d14c..efb3d368 100644--- a/harness/codeverse3d/skills/c3d-scene-water/references/gerstner-and-foam.md+++ b/harness/codeverse3d/skills/c3d-scene-water/references/gerstner-and-foam.md@@ -1,8 +1,5 @@# Gerstner waves and shoreline foam — the deeper cut-`makeOceanSurface` in `lib/ocean.js` already does all of this; what follows is for a water-body the library's options cannot shape.-## Why Gerstner and not displaced noiseNoise-displaced water bobs; Gerstner water TRAVELS. Each wave moves vertices in a circle —diff --git a/harness/codeverse3d/spatial/probes.py b/harness/codeverse3d/spatial/probes.pyindex 384e2cc9..855ec5d8 100644--- a/harness/codeverse3d/spatial/probes.py+++ b/harness/codeverse3d/spatial/probes.py@@ -367,7 +367,7 @@ def _draw_findings(c: dict[str, Any]) -> list[GateFinding]:f"{draws:,} draw calls per frame (each visible mesh is one) exceed the {limit:,} budget"+ (f" — most in {where}" if where else "")+ "; instance repeated geometry with InstancedMesh or merge "- "static clutter with mergeGeometries (lib/merge.js mergeStatic)",+ "static clutter with BufferGeometryUtils.mergeGeometries",target="scene", kind="draw_calls", draws=draws, limit=limit)]diff --git a/harness/codeverse3d/tracks/scene_assets.py b/harness/codeverse3d/tracks/scene_assets.pyindex 0e42709e..4f4c9e5f 100644--- a/harness/codeverse3d/tracks/scene_assets.py+++ b/harness/codeverse3d/tracks/scene_assets.py@@ -775,7 +775,7 @@ def _scene_context(ctx: RunContext) -> dict[str, Any]:#: what names a library row, per scene language: the factory right after a backtick and the module-#: it lives in. three.js: a camelCase call (``makeTree(``, ``patchMoss``) — a bare lowercase one+#: it lives in. three.js: a camelCase call (``makeTree(``, ``patchWind``) — a bare lowercase one#: (``seat``, ``block``) is an ordinary word in a sheet — and ``lib/tree.js``. bpy: the library is#: snake_case (``tree(``, ``water_surface(``) and ``lib/vegetation.py``; a sheet that says "a stone#: water trough" draws the water row too, which costs a line and never misleads.diff --git a/harness/tests/prompts/manifest.json b/harness/tests/prompts/manifest.jsonindex 48317212..5f113f05 100644--- a/harness/tests/prompts/manifest.json+++ b/harness/tests/prompts/manifest.json@@ -435,7 +435,7 @@"chat:model:asset_fishing_boat:r00/system": {"bytes": 3483, "sha256": "79f9f153926a1b9edee34e0fbc13767ff419319c18575fc0ad2bb553d9e6f3ad"},"chat:planner:planner/messages": {"bytes": 204, "sha256": "b91c27cbf7a8071bf320a68a6113bd25896bf0422f92b9087fb155bad18dbdc1"},"chat:planner:planner/sampling": {"bytes": 8047, "sha256": "ac5eba7173d30fcdfc0682ff102fc65e9f4325a5a4f1fbdaca4b0dcd4547d4b1"},- "chat:planner:planner/system": {"bytes": 26758, "sha256": "aab6253b3d1b9716c2e6e1786d07b89bd8efabb1f2476f5f9c10e18b3fe6ae8f"},+ "chat:planner:planner/system": {"bytes": 26641, "sha256": "97cc784b73ca9dfb4f46cc62c0db7c73d9cb6085db85b7feba1895d98e0fa6f6"},"chat:planner:zone-layout#0/messages": {"bytes": 331, "sha256": "eeefd42e9d8d37a901af0ae126aebf39fb2e7861fabe6208d3a9408e1a3c1b37"},"chat:planner:zone-layout#0/sampling": {"bytes": 3397, "sha256": "160445a83ede28afc0191547fd42d9341e694ef70aaad380bebf60ead0a65c49"},"chat:planner:zone-layout#0/system": {"bytes": 3326, "sha256": "494acec302dd23fa2fc6ee1eb6d48e873d6cf0ad98bad413e27578cf062313d4"},@@ -449,24 +449,24 @@"job:asset_bollard@r00/prompt": {"bytes": 5182, "sha256": "eb2371d5d91daf0664ea4155eed95618b5798277e9b8e5cd118e48181aa499a3"},"job:asset_bollard@r00/scope": {"bytes": 357, "sha256": "450d659126efa73cdfe3371f18464e6ab40230af78367de6994d4712c9a8aaaf"},"job:asset_bollard@r00/system": {"bytes": 997, "sha256": "20d72b3bb074ab09ce4b2b6656b8bd0fcffef4fd3d437f2c171cb3efd96d475c"},- "job:env@r00/prompt": {"bytes": 43413, "sha256": "7ef4021041fe74bcab2a6235390553c1673e50a46648263698434a3460d2106c"},+ "job:env@r00/prompt": {"bytes": 36302, "sha256": "f12e0b146910ce6a10b44229fb8b080fc72943831b04231f0522f6fdfb3892b2"},"job:env@r00/scope": {"bytes": 334, "sha256": "b94c09720c9e481759ea0408d7ef708c4d5a3e47b1c2b28a8d901a7c77d7c66b"},- "job:env@r00/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},- "job:refine_quay@r01/prompt": {"bytes": 10092, "sha256": "7424fa604c576ccaa58bb104174f27b1ff6b38ea9682f3335170b1d821e73bd0"},+ "job:env@r00/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},+ "job:refine_quay@r01/prompt": {"bytes": 10042, "sha256": "1eefaead62e4787c4560d4411a977b090d9471c643a56ade7130591f15c57af1"},"job:refine_quay@r01/scope": {"bytes": 352, "sha256": "95a620093126d95e34400b4879d58c03bb641810cf02cc497835c80890c54a01"},- "job:refine_quay@r01/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},- "job:refine_quay@r02/prompt": {"bytes": 10091, "sha256": "a7903f9067f34e57d0427111e8fe759f3f3d34e7c654b8f8baf2798aaa19bdc8"},+ "job:refine_quay@r01/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},+ "job:refine_quay@r02/prompt": {"bytes": 10041, "sha256": "3f485e7944fabb2d2d73ee22843106c6c78606038a44cedbdb5f38d9a4d47920"},"job:refine_quay@r02/scope": {"bytes": 352, "sha256": "8aa778406fd06798c42801c5bc312072027e3d61c29b95e15a785dd2bdff4d2d"},- "job:refine_quay@r02/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},- "job:refine_water@r01/prompt": {"bytes": 10097, "sha256": "2af3470e4b4cf5e411e22cc5402886696b2adc9eaf0460a7b934b5351ccb73e0"},+ "job:refine_quay@r02/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},+ "job:refine_water@r01/prompt": {"bytes": 10047, "sha256": "2ffb0fea225d7eb12d212d915509b18ad0db399e348e3591e8bd4645161fca7a"},"job:refine_water@r01/scope": {"bytes": 354, "sha256": "5c7aa29b996f768b637082248e69fbe65f7ed49d9f5abff27c464da564365b74"},- "job:refine_water@r01/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},- "job:refine_water@r02/prompt": {"bytes": 10096, "sha256": "99d6e0866d9bc4a9475f55db3e6b6efc7166bcb74b0bd80dd8157fa319086045"},+ "job:refine_water@r01/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},+ "job:refine_water@r02/prompt": {"bytes": 10046, "sha256": "cd53c801097a71cc216752a5fb8db633e2abaed8f40817d26a193010cf2ae2de"},"job:refine_water@r02/scope": {"bytes": 354, "sha256": "cbf41e8b42c1c64671a237a42d06bd8188616fd533a767c716e64758d211f737"},- "job:refine_water@r02/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},- "job:zones_quay_water@r00/prompt": {"bytes": 49368, "sha256": "6376c1139592edc6e6937b2c6781d259b570692940460b358eb3b2fd651260c0"},+ "job:refine_water@r02/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},+ "job:zones_quay_water@r00/prompt": {"bytes": 42361, "sha256": "ba7f066f892074d3b6230f7380a1a3492167ab8c24a045e3ee38f0acab6a420a"},"job:zones_quay_water@r00/scope": {"bytes": 379, "sha256": "5b1def419a1370ab2d9f2345bc4a5232ef3c793d4e4f1e01bd5ab9a3a8e88a7d"},- "job:zones_quay_water@r00/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},+ "job:zones_quay_water@r00/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},"judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3690, "sha256": "5e7031f1c8d724681399e545e6adf0af8e6a8da6cae4364c7220a15b41f0744b"},"judge:scene:runs/run/artifacts/renders/r00/messages": {"bytes": 4930, "sha256": "562ef4bfc6b24c34604482cb73a02fb4b01da5c0e70685e3a1a4e1dda616a827"},"judge:scene:runs/run/artifacts/renders/r00/sampling": {"bytes": 14066, "sha256": "1f67b211de491259bed48f1499b8dbd9fa2037a903a637ba53befda40ade693d"},@@ -520,7 +520,7 @@"chat:model:planner/system": {"bytes": 20977, "sha256": "0a3c2ea2bfb39981a166952054d1dcc10dffdf097d493e89b03e0b8586d2ee8e"},"chat:planner:planner/messages": {"bytes": 204, "sha256": "b91c27cbf7a8071bf320a68a6113bd25896bf0422f92b9087fb155bad18dbdc1"},"chat:planner:planner/sampling": {"bytes": 8047, "sha256": "ac5eba7173d30fcdfc0682ff102fc65e9f4325a5a4f1fbdaca4b0dcd4547d4b1"},- "chat:planner:planner/system": {"bytes": 26758, "sha256": "aab6253b3d1b9716c2e6e1786d07b89bd8efabb1f2476f5f9c10e18b3fe6ae8f"},+ "chat:planner:planner/system": {"bytes": 26641, "sha256": "97cc784b73ca9dfb4f46cc62c0db7c73d9cb6085db85b7feba1895d98e0fa6f6"},"chat:planner:zone-layout#0/messages": {"bytes": 401, "sha256": "73206223434695497c74e5f8f5bc0a0f1b147a7dc38147645c6cf42b5372484b"},"chat:planner:zone-layout#0/sampling": {"bytes": 3397, "sha256": "160445a83ede28afc0191547fd42d9341e694ef70aaad380bebf60ead0a65c49"},"chat:planner:zone-layout#0/system": {"bytes": 3391, "sha256": "fa6d28546a947ddc6ab8d0adb8af97a1605873109a47cf7f097f72d9788fd678"},@@ -535,12 +535,12 @@"job:asset_crate@r00/prompt": {"bytes": 18032, "sha256": "27dfd5f4bedcc036f93c844230347401da2c4c4f8b1d300bfaece147b704c3fc"},"job:asset_crate@r00/scope": {"bytes": 430, "sha256": "3c4b45fd7cc847cc6a6a5f3b83784cddab99440be445d61f924f56b834cd1476"},"job:asset_crate@r00/system": {"bytes": 3716, "sha256": "6068eff7b8c36b4edcc5d64ead79bd3de7386e0bbaf4fb141210883fb34f8518"},- "job:env@r00/prompt": {"bytes": 43413, "sha256": "7ef4021041fe74bcab2a6235390553c1673e50a46648263698434a3460d2106c"},+ "job:env@r00/prompt": {"bytes": 36302, "sha256": "f12e0b146910ce6a10b44229fb8b080fc72943831b04231f0522f6fdfb3892b2"},"job:env@r00/scope": {"bytes": 334, "sha256": "b94c09720c9e481759ea0408d7ef708c4d5a3e47b1c2b28a8d901a7c77d7c66b"},- "job:env@r00/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},- "job:zones_quay_water@r00/prompt": {"bytes": 49548, "sha256": "6a131737cde4664b3b56a91cea3933eee53d3394a55975cfcba433ec6da3fbfb"},+ "job:env@r00/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},+ "job:zones_quay_water@r00/prompt": {"bytes": 42541, "sha256": "986c0f46f90e4f652c336741d6925c1bf7f7b2d83dbe5977ba8a9856dfa4c576"},"job:zones_quay_water@r00/scope": {"bytes": 379, "sha256": "5b1def419a1370ab2d9f2345bc4a5232ef3c793d4e4f1e01bd5ab9a3a8e88a7d"},- "job:zones_quay_water@r00/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},+ "job:zones_quay_water@r00/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},"judge:asset:runs/run/_assets/crate/artifacts/renders/r00/assets/crate/input": {"bytes": 3759, "sha256": "d3507d23f5a84d828cef7b6b6f9b2c5df3795a2c300ee7aaeb038af59267fc30"},"judge:asset:runs/run/_assets/crate/artifacts/renders/r00/assets/crate/messages": {"bytes": 3099, "sha256": "eee511c765a105054417cb3fa37bf67c24bcf9022da44dc086385878a61d5f67"},"judge:asset:runs/run/_assets/crate/artifacts/renders/r00/assets/crate/sampling": {"bytes": 8355, "sha256": "a80299c8dfc30739d05a0274526c361cb406c78a1ab5e923fcdf78d8c78ea73a"},@@ -577,14 +577,14 @@"chat:model:asset_fishing_boat:r00/system": {"bytes": 3483, "sha256": "79f9f153926a1b9edee34e0fbc13767ff419319c18575fc0ad2bb553d9e6f3ad"},"chat:planner:planner/messages": {"bytes": 204, "sha256": "b91c27cbf7a8071bf320a68a6113bd25896bf0422f92b9087fb155bad18dbdc1"},"chat:planner:planner/sampling": {"bytes": 8047, "sha256": "ac5eba7173d30fcdfc0682ff102fc65e9f4325a5a4f1fbdaca4b0dcd4547d4b1"},- "chat:planner:planner/system": {"bytes": 26758, "sha256": "aab6253b3d1b9716c2e6e1786d07b89bd8efabb1f2476f5f9c10e18b3fe6ae8f"},+ "chat:planner:planner/system": {"bytes": 26641, "sha256": "97cc784b73ca9dfb4f46cc62c0db7c73d9cb6085db85b7feba1895d98e0fa6f6"},"context:runs/run/files": {"bytes": 55674, "sha256": "b13f8fe30cb373f4e8eae10b376ba430710b7c28fc71b830f63a35fefae4eb36"},- "job:env@r00/prompt": {"bytes": 43413, "sha256": "7ef4021041fe74bcab2a6235390553c1673e50a46648263698434a3460d2106c"},+ "job:env@r00/prompt": {"bytes": 36302, "sha256": "f12e0b146910ce6a10b44229fb8b080fc72943831b04231f0522f6fdfb3892b2"},"job:env@r00/scope": {"bytes": 334, "sha256": "b94c09720c9e481759ea0408d7ef708c4d5a3e47b1c2b28a8d901a7c77d7c66b"},- "job:env@r00/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},- "job:zones_quay_water@r00/prompt": {"bytes": 48695, "sha256": "69d9b51d3d241fd0a71bcd11b36734233dd13f4eb139b1c06d70073ae97147bf"},+ "job:env@r00/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},+ "job:zones_quay_water@r00/prompt": {"bytes": 41688, "sha256": "752f5e1a1ee0e088ac14df293d7d28d56a29c6d8249f3a2a13f1d1e2249964df"},"job:zones_quay_water@r00/scope": {"bytes": 379, "sha256": "5b1def419a1370ab2d9f2345bc4a5232ef3c793d4e4f1e01bd5ab9a3a8e88a7d"},- "job:zones_quay_water@r00/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},+ "job:zones_quay_water@r00/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},"judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3690, "sha256": "ebaaf972b6033176defee1013c1eb8b83843caef8172efe2dba99ccfb339a33f"},"judge:scene:runs/run/artifacts/renders/r00/messages": {"bytes": 4930, "sha256": "562ef4bfc6b24c34604482cb73a02fb4b01da5c0e70685e3a1a4e1dda616a827"},"judge:scene:runs/run/artifacts/renders/r00/sampling": {"bytes": 14066, "sha256": "1f67b211de491259bed48f1499b8dbd9fa2037a903a637ba53befda40ade693d"},@@ -612,7 +612,7 @@"chat:model:asset_fishing_boat:r00/system": {"bytes": 3483, "sha256": "79f9f153926a1b9edee34e0fbc13767ff419319c18575fc0ad2bb553d9e6f3ad"},"chat:planner:planner/messages": {"bytes": 204, "sha256": "b91c27cbf7a8071bf320a68a6113bd25896bf0422f92b9087fb155bad18dbdc1"},"chat:planner:planner/sampling": {"bytes": 8047, "sha256": "ac5eba7173d30fcdfc0682ff102fc65e9f4325a5a4f1fbdaca4b0dcd4547d4b1"},- "chat:planner:planner/system": {"bytes": 26758, "sha256": "aab6253b3d1b9716c2e6e1786d07b89bd8efabb1f2476f5f9c10e18b3fe6ae8f"},+ "chat:planner:planner/system": {"bytes": 26641, "sha256": "97cc784b73ca9dfb4f46cc62c0db7c73d9cb6085db85b7feba1895d98e0fa6f6"},"chat:planner:zone-layout#0/messages": {"bytes": 331, "sha256": "eeefd42e9d8d37a901af0ae126aebf39fb2e7861fabe6208d3a9408e1a3c1b37"},"chat:planner:zone-layout#0/sampling": {"bytes": 3397, "sha256": "160445a83ede28afc0191547fd42d9341e694ef70aaad380bebf60ead0a65c49"},"chat:planner:zone-layout#0/system": {"bytes": 3326, "sha256": "494acec302dd23fa2fc6ee1eb6d48e873d6cf0ad98bad413e27578cf062313d4"},@@ -623,27 +623,27 @@"chat:planner:zone-layout#2/sampling": {"bytes": 3397, "sha256": "160445a83ede28afc0191547fd42d9341e694ef70aaad380bebf60ead0a65c49"},"chat:planner:zone-layout#2/system": {"bytes": 3326, "sha256": "494acec302dd23fa2fc6ee1eb6d48e873d6cf0ad98bad413e27578cf062313d4"},"context:runs/run/files": {"bytes": 55674, "sha256": "b13f8fe30cb373f4e8eae10b376ba430710b7c28fc71b830f63a35fefae4eb36"},- "job:env@r00/prompt": {"bytes": 43413, "sha256": "7ef4021041fe74bcab2a6235390553c1673e50a46648263698434a3460d2106c"},+ "job:env@r00/prompt": {"bytes": 36302, "sha256": "f12e0b146910ce6a10b44229fb8b080fc72943831b04231f0522f6fdfb3892b2"},"job:env@r00/scope": {"bytes": 334, "sha256": "b94c09720c9e481759ea0408d7ef708c4d5a3e47b1c2b28a8d901a7c77d7c66b"},- "job:env@r00/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},+ "job:env@r00/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},"job:r00_baseline_repair1@r00/prompt": {"bytes": 3261, "sha256": "d6f7ee211ced016d303fba6017d6c0d86148b201135f6b9e659220f797bcc967"},"job:r00_baseline_repair1@r00/scope": {"bytes": 392, "sha256": "3321d34981a6a1b8621a35e4260c3378e9659f6371db48dbcfbd6a23e7d8547d"},- "job:r00_baseline_repair1@r00/system": {"bytes": 22749, "sha256": "5cd22054b3960b4e3e40aa9c3507bdaa4695eda55a300e3e631690560853f8bb"},+ "job:r00_baseline_repair1@r00/system": {"bytes": 22760, "sha256": "e3b1eca12c36fe0236357f37c0d36bd9040e43198afa42ad1de4e8fd10f0a46d"},"job:r00_baseline_repair2@r00/prompt": {"bytes": 3566, "sha256": "9095f72e1353c3ec863bff95f03c6de38ed4f19dc90420926eac8b9be360b7ec"},"job:r00_baseline_repair2@r00/scope": {"bytes": 394, "sha256": "7cb6a3e71ece9cc8d28cb865866a4877727e69d379c03d4a45a411b5414741d1"},- "job:r00_baseline_repair2@r00/system": {"bytes": 22749, "sha256": "5cd22054b3960b4e3e40aa9c3507bdaa4695eda55a300e3e631690560853f8bb"},+ "job:r00_baseline_repair2@r00/system": {"bytes": 22760, "sha256": "e3b1eca12c36fe0236357f37c0d36bd9040e43198afa42ad1de4e8fd10f0a46d"},"job:r01_refine_repair1@r01/prompt": {"bytes": 3261, "sha256": "d6f7ee211ced016d303fba6017d6c0d86148b201135f6b9e659220f797bcc967"},"job:r01_refine_repair1@r01/scope": {"bytes": 390, "sha256": "c69eaed8419cbb3ca77f53c7d3c95376ea17825ab53ecfb476b9c77c389a31d3"},- "job:r01_refine_repair1@r01/system": {"bytes": 22749, "sha256": "5cd22054b3960b4e3e40aa9c3507bdaa4695eda55a300e3e631690560853f8bb"},+ "job:r01_refine_repair1@r01/system": {"bytes": 22760, "sha256": "e3b1eca12c36fe0236357f37c0d36bd9040e43198afa42ad1de4e8fd10f0a46d"},"job:r01_refine_repair2@r01/prompt": {"bytes": 3566, "sha256": "9095f72e1353c3ec863bff95f03c6de38ed4f19dc90420926eac8b9be360b7ec"},"job:r01_refine_repair2@r01/scope": {"bytes": 392, "sha256": "68a7f7b764450f2c01bca83cc4ff4ccf70cc065902e80b97985922a7383ecd19"},- "job:r01_refine_repair2@r01/system": {"bytes": 22749, "sha256": "5cd22054b3960b4e3e40aa9c3507bdaa4695eda55a300e3e631690560853f8bb"},- "job:rebuild@r01/prompt": {"bytes": 10049, "sha256": "aa103063270f75b7b12d2f4e9d0795c02c69651ae119a3ee404e2e59391260a1"},+ "job:r01_refine_repair2@r01/system": {"bytes": 22760, "sha256": "e3b1eca12c36fe0236357f37c0d36bd9040e43198afa42ad1de4e8fd10f0a46d"},+ "job:rebuild@r01/prompt": {"bytes": 9999, "sha256": "b0613319c17fcb470abe74f0cbbfabd3085bc20f065e090d3b327ab854203014"},"job:rebuild@r01/scope": {"bytes": 382, "sha256": "6ea60c37d5ea2360a24a236ed77174ca29ebdcb1ed8331da08e68fc494305dc9"},- "job:rebuild@r01/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},- "job:zones_quay_water@r00/prompt": {"bytes": 49368, "sha256": "6376c1139592edc6e6937b2c6781d259b570692940460b358eb3b2fd651260c0"},+ "job:rebuild@r01/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},+ "job:zones_quay_water@r00/prompt": {"bytes": 42361, "sha256": "ba7f066f892074d3b6230f7380a1a3492167ab8c24a045e3ee38f0acab6a420a"},"job:zones_quay_water@r00/scope": {"bytes": 379, "sha256": "5b1def419a1370ab2d9f2345bc4a5232ef3c793d4e4f1e01bd5ab9a3a8e88a7d"},- "job:zones_quay_water@r00/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},+ "job:zones_quay_water@r00/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},"skills:runs/run:baseline@r00/routed": {"bytes": 156, "sha256": "cae5ab46c39f9f4efb7ae3c4758b05d768025f93d525d5e13812b916a583fd30"},"skills:runs/run:env@r00/routed": {"bytes": 164, "sha256": "eb0e2aca5a76b26e49a2d2c862a9405ef2e3e1130e719cca9a1f23fe1b264402"},"skills:runs/run:refine@r01/routed": {"bytes": 156, "sha256": "cae5ab46c39f9f4efb7ae3c4758b05d768025f93d525d5e13812b916a583fd30"},@@ -669,7 +669,7 @@"chat:model:asset_fishing_boat:r00/system": {"bytes": 3483, "sha256": "79f9f153926a1b9edee34e0fbc13767ff419319c18575fc0ad2bb553d9e6f3ad"},"chat:planner:planner/messages": {"bytes": 204, "sha256": "b91c27cbf7a8071bf320a68a6113bd25896bf0422f92b9087fb155bad18dbdc1"},"chat:planner:planner/sampling": {"bytes": 8047, "sha256": "ac5eba7173d30fcdfc0682ff102fc65e9f4325a5a4f1fbdaca4b0dcd4547d4b1"},- "chat:planner:planner/system": {"bytes": 26758, "sha256": "aab6253b3d1b9716c2e6e1786d07b89bd8efabb1f2476f5f9c10e18b3fe6ae8f"},+ "chat:planner:planner/system": {"bytes": 26641, "sha256": "97cc784b73ca9dfb4f46cc62c0db7c73d9cb6085db85b7feba1895d98e0fa6f6"},"chat:planner:zone-layout#0/messages": {"bytes": 331, "sha256": "eeefd42e9d8d37a901af0ae126aebf39fb2e7861fabe6208d3a9408e1a3c1b37"},"chat:planner:zone-layout#0/sampling": {"bytes": 3397, "sha256": "160445a83ede28afc0191547fd42d9341e694ef70aaad380bebf60ead0a65c49"},"chat:planner:zone-layout#0/system": {"bytes": 3326, "sha256": "494acec302dd23fa2fc6ee1eb6d48e873d6cf0ad98bad413e27578cf062313d4"},@@ -680,18 +680,18 @@"chat:planner:zone-layout#2/sampling": {"bytes": 3397, "sha256": "160445a83ede28afc0191547fd42d9341e694ef70aaad380bebf60ead0a65c49"},"chat:planner:zone-layout#2/system": {"bytes": 3326, "sha256": "494acec302dd23fa2fc6ee1eb6d48e873d6cf0ad98bad413e27578cf062313d4"},"context:runs/run/files": {"bytes": 55674, "sha256": "b13f8fe30cb373f4e8eae10b376ba430710b7c28fc71b830f63a35fefae4eb36"},- "job:env@r00/prompt": {"bytes": 43413, "sha256": "7ef4021041fe74bcab2a6235390553c1673e50a46648263698434a3460d2106c"},+ "job:env@r00/prompt": {"bytes": 36302, "sha256": "f12e0b146910ce6a10b44229fb8b080fc72943831b04231f0522f6fdfb3892b2"},"job:env@r00/scope": {"bytes": 334, "sha256": "b94c09720c9e481759ea0408d7ef708c4d5a3e47b1c2b28a8d901a7c77d7c66b"},- "job:env@r00/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},- "job:refine_quay@r01/prompt": {"bytes": 10092, "sha256": "7424fa604c576ccaa58bb104174f27b1ff6b38ea9682f3335170b1d821e73bd0"},+ "job:env@r00/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},+ "job:refine_quay@r01/prompt": {"bytes": 10042, "sha256": "1eefaead62e4787c4560d4411a977b090d9471c643a56ade7130591f15c57af1"},"job:refine_quay@r01/scope": {"bytes": 352, "sha256": "95a620093126d95e34400b4879d58c03bb641810cf02cc497835c80890c54a01"},- "job:refine_quay@r01/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},- "job:refine_water@r01/prompt": {"bytes": 10097, "sha256": "2af3470e4b4cf5e411e22cc5402886696b2adc9eaf0460a7b934b5351ccb73e0"},+ "job:refine_quay@r01/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},+ "job:refine_water@r01/prompt": {"bytes": 10047, "sha256": "2ffb0fea225d7eb12d212d915509b18ad0db399e348e3591e8bd4645161fca7a"},"job:refine_water@r01/scope": {"bytes": 354, "sha256": "5c7aa29b996f768b637082248e69fbe65f7ed49d9f5abff27c464da564365b74"},- "job:refine_water@r01/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},- "job:zones_quay_water@r00/prompt": {"bytes": 49368, "sha256": "6376c1139592edc6e6937b2c6781d259b570692940460b358eb3b2fd651260c0"},+ "job:refine_water@r01/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},+ "job:zones_quay_water@r00/prompt": {"bytes": 42361, "sha256": "ba7f066f892074d3b6230f7380a1a3492167ab8c24a045e3ee38f0acab6a420a"},"job:zones_quay_water@r00/scope": {"bytes": 379, "sha256": "5b1def419a1370ab2d9f2345bc4a5232ef3c793d4e4f1e01bd5ab9a3a8e88a7d"},- "job:zones_quay_water@r00/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},+ "job:zones_quay_water@r00/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},"judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3690, "sha256": "5e7031f1c8d724681399e545e6adf0af8e6a8da6cae4364c7220a15b41f0744b"},"judge:scene:runs/run/artifacts/renders/r00/messages": {"bytes": 4930, "sha256": "562ef4bfc6b24c34604482cb73a02fb4b01da5c0e70685e3a1a4e1dda616a827"},"judge:scene:runs/run/artifacts/renders/r00/sampling": {"bytes": 14066, "sha256": "1f67b211de491259bed48f1499b8dbd9fa2037a903a637ba53befda40ade693d"},@@ -729,21 +729,21 @@"chat:model:asset_fishing_boat:r00/messages": {"bytes": 3365, "sha256": "583f9c5888c4ff1567e3cbb2d9e3e8701e31169fd30f295d89dae16e046e55cc"},"chat:model:asset_fishing_boat:r00/sampling": {"bytes": 92, "sha256": "08e72af1b4fb249378c5a151e019ded70a1014eafa4d50f70927bb225f695678"},"chat:model:asset_fishing_boat:r00/system": {"bytes": 3483, "sha256": "79f9f153926a1b9edee34e0fbc13767ff419319c18575fc0ad2bb553d9e6f3ad"},- "chat:model:env:r00/messages": {"bytes": 46351, "sha256": "c130b3dc17e9fdbd5b3ab768be7a001322de0d137af4af17cc38001306d7c7e8"},+ "chat:model:env:r00/messages": {"bytes": 38565, "sha256": "e404db77101e03a7c02a8f64db75498d9ef83856d9221cbbb7d6119885af8488"},"chat:model:env:r00/sampling": {"bytes": 92, "sha256": "08e72af1b4fb249378c5a151e019ded70a1014eafa4d50f70927bb225f695678"},- "chat:model:env:r00/system": {"bytes": 7632, "sha256": "2c187b396badbf62b604234f29d488679bf5a0446f67f0cfacb703509fc1e8ea"},- "chat:model:refine_quay:r01/messages": {"bytes": 12521, "sha256": "7f839ae609b083385bc8a1c2d960e0d9c31842cac9e3c95f2c74d2afea73de17"},+ "chat:model:env:r00/system": {"bytes": 7643, "sha256": "8fe362b492ce25d3be225db62d90a4c34b3bd5d2174fc489ed1105702cb03486"},+ "chat:model:refine_quay:r01/messages": {"bytes": 11829, "sha256": "90cd2dc95416397f4c6f0d2f57deb29f32fb251fced5fb9cf27708df5b627f1c"},"chat:model:refine_quay:r01/sampling": {"bytes": 92, "sha256": "2a36044e5c117fc288123a5937c6e3cb5845f040b4de69f9c2440f623956c381"},- "chat:model:refine_quay:r01/system": {"bytes": 7632, "sha256": "2c187b396badbf62b604234f29d488679bf5a0446f67f0cfacb703509fc1e8ea"},- "chat:model:refine_water:r01/messages": {"bytes": 12527, "sha256": "c7684c66aed9311a614b682e72e5698a373e6b8ac81f7669eda75389f8157fa4"},+ "chat:model:refine_quay:r01/system": {"bytes": 7643, "sha256": "8fe362b492ce25d3be225db62d90a4c34b3bd5d2174fc489ed1105702cb03486"},+ "chat:model:refine_water:r01/messages": {"bytes": 11835, "sha256": "123c73ad0423a4c07441eab7ed500c40e991a9572a04882913ab596e52579b0f"},"chat:model:refine_water:r01/sampling": {"bytes": 92, "sha256": "2a36044e5c117fc288123a5937c6e3cb5845f040b4de69f9c2440f623956c381"},- "chat:model:refine_water:r01/system": {"bytes": 7632, "sha256": "2c187b396badbf62b604234f29d488679bf5a0446f67f0cfacb703509fc1e8ea"},- "chat:model:zones_quay_water:r00/messages": {"bytes": 52167, "sha256": "1ec086c228a94517243c0bec4e7227a51e7dcf5ce72c1170dd6ef4d3be0c1c86"},+ "chat:model:refine_water:r01/system": {"bytes": 7643, "sha256": "8fe362b492ce25d3be225db62d90a4c34b3bd5d2174fc489ed1105702cb03486"},+ "chat:model:zones_quay_water:r00/messages": {"bytes": 44486, "sha256": "008fcbfad58b891992d7d30e1d6e55345c7d658eca9863f87f49172cc58da5cd"},"chat:model:zones_quay_water:r00/sampling": {"bytes": 92, "sha256": "08e72af1b4fb249378c5a151e019ded70a1014eafa4d50f70927bb225f695678"},- "chat:model:zones_quay_water:r00/system": {"bytes": 7632, "sha256": "2c187b396badbf62b604234f29d488679bf5a0446f67f0cfacb703509fc1e8ea"},+ "chat:model:zones_quay_water:r00/system": {"bytes": 7643, "sha256": "8fe362b492ce25d3be225db62d90a4c34b3bd5d2174fc489ed1105702cb03486"},"chat:planner:planner/messages": {"bytes": 204, "sha256": "b91c27cbf7a8071bf320a68a6113bd25896bf0422f92b9087fb155bad18dbdc1"},"chat:planner:planner/sampling": {"bytes": 8047, "sha256": "ac5eba7173d30fcdfc0682ff102fc65e9f4325a5a4f1fbdaca4b0dcd4547d4b1"},- "chat:planner:planner/system": {"bytes": 26758, "sha256": "aab6253b3d1b9716c2e6e1786d07b89bd8efabb1f2476f5f9c10e18b3fe6ae8f"},+ "chat:planner:planner/system": {"bytes": 26641, "sha256": "97cc784b73ca9dfb4f46cc62c0db7c73d9cb6085db85b7feba1895d98e0fa6f6"},"chat:planner:zone-layout#0/messages": {"bytes": 331, "sha256": "eeefd42e9d8d37a901af0ae126aebf39fb2e7861fabe6208d3a9408e1a3c1b37"},"chat:planner:zone-layout#0/sampling": {"bytes": 3397, "sha256": "160445a83ede28afc0191547fd42d9341e694ef70aaad380bebf60ead0a65c49"},"chat:planner:zone-layout#0/system": {"bytes": 3326, "sha256": "494acec302dd23fa2fc6ee1eb6d48e873d6cf0ad98bad413e27578cf062313d4"},diff --git a/harness/tests/scene_gates/test_draw_budget.py b/harness/tests/scene_gates/test_draw_budget.pyindex 3c24e738..69dc7231 100644--- a/harness/tests/scene_gates/test_draw_budget.py+++ b/harness/tests/scene_gates/test_draw_budget.py@@ -33,7 +33,7 @@ def test_the_probe_gates_the_census_draw_count(draws: int, severity: Severity |(f,) = hitsassert f.severity == severity and report.passed is (severity != Severity.ERROR)assert f.data["draws"] == draws and f.data["limit"] == limit- for text in (f"{draws:,}", f"{limit:,}", "Market", "InstancedMesh", "mergeGeometries", "lib/merge.js"):+ for text in (f"{draws:,}", f"{limit:,}", "Market", "InstancedMesh", "mergeGeometries"):assert text in f.message, textdiff --git a/harness/tests/scene_runtime/lib/test_building.py b/harness/tests/scene_runtime/lib/test_building.pydeleted file mode 100644index 36ec1d92..00000000--- a/harness/tests/scene_runtime/lib/test_building.py+++ /dev/null@@ -1,136 +0,0 @@-"""building.js — regressions for the facade and cottage bugs the showcase render caught."""-from __future__ import annotations--import pytest-from _probe import measure--pytestmark = pytest.mark.node--_LIBS = ("building.js", "materials.js")--_PRELUDE = """-import * as THREE from 'three';-import { block, cottage } from './lib/building.js';--const mk = (s0) => { let s = s0;- return () => (s = (s * 16807) % 2147483647) / 2147483647; };--/** Emissive hex of every named mesh part. */-function parts(root) {- const out = {};- root.traverse((o) => { if (o.isMesh) out[o.name] = o.material.emissive ? o.material.emissive.getHex() : null; });- return out;-}--/** Name of the first mesh a ray meets, or null. */-function firstHit(root, from, dir) {- const meshes = [];- root.traverse((o) => { if (o.isMesh) meshes.push(o); });- const hit = new THREE.Raycaster(- new THREE.Vector3().fromArray(from),- new THREE.Vector3().fromArray(dir).normalize(), 0, 400)- .intersectObjects(meshes, true);- return hit.length ? hit[0].object.name : null;-}-"""---def _measure(script: str) -> dict:- return measure(_PRELUDE + script, _LIBS)----def test_roof_clutter_uses_the_hosts_local_roof_after_placement():- """World roof height was added as local Y, applying host transforms twice."""- out = _measure("""-import { roofClutter } from './lib/building.js';-const layouts = [false,true].map(transformed => {- const parent = new THREE.Group(), host = new THREE.Group();- const roof = new THREE.Mesh(new THREE.BoxGeometry(10,4,6), new THREE.MeshStandardMaterial());- roof.position.set(2,3,-1); host.add(roof); parent.add(host);- if(transformed) {- parent.position.set(19,-3,7); parent.rotation.set(.1,.5,-.2);- parent.scale.set(.8,1.3,1.6);- host.position.set(8,11,-4); host.rotation.set(.2,-.7,.1);- host.scale.set(2,.6,1.2);- }- roofClutter(host,{rand:()=>.5,tanks:0,units:1});- const clutter=host.getObjectByName('RoofClutter'), unit=clutter.children[0];- unit.geometry.computeBoundingBox();- const local = unit.geometry.boundingBox.clone().translate(unit.position).translate(clutter.position);- return {center:local.getCenter(new THREE.Vector3()).toArray(),- size:local.getSize(new THREE.Vector3()).toArray(),foot:local.min.y};-});-console.log(JSON.stringify(layouts));-""")- plain, transformed = out- assert plain["center"][0] == pytest.approx(2)- assert plain["center"][2] == pytest.approx(-1)- assert plain["foot"] == pytest.approx(5)- assert transformed["foot"] == pytest.approx(plain["foot"])- assert transformed["center"] == pytest.approx(plain["center"])- assert transformed["size"] == pytest.approx(plain["size"])--[email protected](scope="module")-def lit_block() -> dict:- return _measure("""-const b = block({ w: 16, d: 14, h: 26, style: 'masonry', lit: 0.45,- rand: mk(5) });-const glow = [];-b.traverse((o) => {- if (o.isMesh && o.material.emissive && o.material.emissiveIntensity > 0- && o.material.emissive.getHex() !== 0) {- glow.push({ name: o.name, emissive: o.material.emissive.getHex(),- intensity: o.material.emissiveIntensity,- tris: o.geometry.index ? o.geometry.index.count / 3- : o.geometry.attributes.position.count / 3 });- }-});-// Panes are boxes: 12 triangles each, lit or dark. The ratio IS the-// `lit` fraction the caller asked for -- unless the whole shell glows.-const litPanes = glow.reduce((a, g) => a + g.tris, 0) / 12;-let darkPanes = 0;-b.traverse((o) => { if (o.isMesh && o.name.startsWith('Glazing'))- darkPanes += (o.geometry.index ? o.geometry.index.count / 3- : o.geometry.attributes.position.count / 3) / 12; });-console.log(JSON.stringify({- revealEmissive: parts(b).Reveals,- glow,- litPanes, darkPanes,-}));-""")---def test_a_lit_block_lights_windows_not_the_whole_shell(lit_block):- """The reveal shell is ONE box spanning the building."""- m = lit_block- assert m["revealEmissive"] == 0, (- "the interior shell itself glows -- every window in the building "- "lights from one box")- assert all(g["name"].startswith("LitRooms") for g in m["glow"]), m["glow"]- # `lit: 0.45` has to mean 45% of the windows, not the building.- frac = m["litPanes"] / (m["litPanes"] + m["darkPanes"])- assert 0.25 < frac < 0.65, (frac, m["litPanes"], m["darkPanes"])- assert m["darkPanes"] >= 8, ("no window stayed dark", m["darkPanes"])---# ------------------------------------------------------------- the cottage-[email protected](scope="module")-def cot() -> dict:- return _measure("""-const W = 8, D = 7, H = 3.2, PITCH = 0.85 * W / 2;-const c = cottage({ w: W, d: D, h: H, dormers: 2, roof: 'gable', rand: mk(23) });-// apex up: the gable triangle is narrow near the ridge, wide at the eaves (walls mesh only)-const wallsOnly = new THREE.Group();-c.traverse((o) => { if (o.isMesh && o.name === 'Walls') wallsOnly.add(o.clone()); });-const gableAt = (frac) => firstHit(wallsOnly, [W * 0.35, H + PITCH * frac, 40], [0, 0, -1]);-console.log(JSON.stringify({ gableHigh: gableAt(0.75), gableLow: gableAt(0.15) }));-""")---def test_cottage_gable_ends_are_apex_up(cot):- """`rotateX(+PI/2)` put the 3-gon's apex at y=-1: every gable shipped upside down (a bbox cannot tell)."""- assert cot["gableLow"] == "Walls", cot- assert cot["gableHigh"] is None, cotdiff --git a/harness/tests/scene_runtime/lib/test_clouds.py b/harness/tests/scene_runtime/lib/test_clouds.pydeleted file mode 100644index e3aff3e5..00000000--- a/harness/tests/scene_runtime/lib/test_clouds.py+++ /dev/null@@ -1,89 +0,0 @@-"""Cloud deck transport, placement, and ownership regressions."""-from __future__ import annotations--import pytest--from tests.scene_runtime.lib._probe import compile_scene--pytestmark = pytest.mark.node---def test_cloud_transport_matches_beer_lambert_and_camera_projection():- """Constant data isolates optical integration from authored noise and color."""- code, out = compile_scene("""-import * as THREE from 'three';-import {makeClouds} from './lib/clouds.js';-export function createScene({renderer}) {- const scene=new THREE.Scene();- // An odd target has an exact center pixel in both projection models.- const target=new THREE.WebGLRenderTarget(17,17,{type:THREE.FloatType});- const pixel=new Float32Array(4),previous=renderer.getRenderTarget();- const clear=new THREE.Color();renderer.getClearColor(clear);const clearAlpha=renderer.getClearAlpha();- const results=[];- try {- renderer.setClearColor(0,0);renderer.setRenderTarget(target);- for(const transformed of [false,true])for(const quality of ['low','balanced','high']) {- const parent=new THREE.Group(),placement=new THREE.Group();parent.add(placement);scene.add(parent);- if(transformed) {- parent.position.set(37,-8,23);parent.rotation.y=.41;parent.scale.set(1.7,.8,1.4);- placement.position.set(-9,11,14);placement.rotation.y=-.55;placement.scale.set(.9,1.2,1.3);- }- parent.updateMatrixWorld(true);- const linear=new THREE.Matrix3().setFromMatrix4(placement.matrixWorld);- const worldAxis=new THREE.Vector3(0,0,1).applyMatrix3(linear),metric=worldAxis.length();- const deck=makeClouds({quality,area:100,altitude:0,spread:0,alpha:.12,- sunDir:worldAxis.clone().normalize(),wind:0});- placement.add(deck);- const material=deck.material,u=material.uniforms;- for(const name of ['uWeather','uNoise']) {- u[name].value.image.data.fill(255);u[name].value.needsUpdate=true;- }- const center=u.uCenter.value,size=u.uSize.value;- const point=center.clone();point.y+=(-.5+.22)*size.y;- const sunStart=point.clone();sunStart.z-=.4*size.z;- u.uProbePoint={value:sunStart};- // Read actual production transport, bypassing artistic source color and- // blending. The material's ray setup and density/shadow loops still run.- material.blending=THREE.NoBlending;material.toneMapped=false;material.depthTest=false;- material.onBeforeCompile=shader=>{- shader.fragmentShader='uniform vec3 uProbePoint;\\n'+shader.fragmentShader;- shader.fragmentShader=shader.fragmentShader.replace('#include <tonemapping_fragment>',- 'gl_FragColor=vec4(opacity,deckShadow(uProbePoint),deckDensity(uProbePoint),1.0);\\n#include <tonemapping_fragment>');- };- const localEye=point.clone();localEye.z+=size.z*1.2;- const eye=localEye.applyMatrix4(placement.matrixWorld),aim=point.clone().applyMatrix4(placement.matrixWorld);- const cameras=[new THREE.PerspectiveCamera(45,1,.1,5000),new THREE.OrthographicCamera(-80,80,80,-80,.1,5000)];- const samples=[];- for(const camera of cameras) {- camera.position.copy(eye);camera.lookAt(aim);camera.updateMatrixWorld(true);- renderer.render(scene,camera);renderer.readRenderTargetPixels(target,8,8,1,1,pixel);- if(!Array.from(pixel).every(Number.isFinite)||pixel[3]!==1)throw Error('Empty/nonfinite cloud probe: '+pixel);- samples.push(Array.from(pixel));- }- // The integral of each 3.5%-wide smoothstep boundary is half its width.- // View crosses two fades; light from z=.1 crosses only the exit fade.- const extinction=u.uExtinction.value;- const expectedOpacity=1-Math.exp(-size.z*.965*metric*extinction);- const expectedShadow=size.z*(.9-.035/2)*metric*extinction;- for(const sample of samples) {- if(Math.abs(sample[2]-1)>.00001)throw Error('Probe density is not constant: '+sample);- if(Math.abs(sample[0]-expectedOpacity)>.005)throw Error('Cloud view optical depth lost world distance: '+[quality,transformed,sample[0],expectedOpacity]);- if(Math.abs(sample[1]/expectedShadow-1)>.03)throw Error('Cloud light march did not integrate the full path: '+[quality,transformed,sample[1],expectedShadow]);- }- if(Math.abs(samples[0][0]-samples[1][0])>.0002)throw Error('Orthographic/perspective center rays disagree: '+samples);- results.push({transformed,quality,opacity:samples[0][0],shadow:samples[0][1]});- u.uAlpha.value=0;- renderer.render(scene,cameras[0]);renderer.readRenderTargetPixels(target,8,8,1,1,pixel);- if(pixel.some(v=>v!==0))throw Error('Alpha zero left cloud transport: '+pixel);- scene.remove(parent);deck.userData.dispose();- }- for(const transformed of [false,true]) {- const group=results.filter(r=>r.transformed===transformed),reference=group[2];- for(const row of group)if(Math.abs(row.opacity-reference.opacity)>.005||Math.abs(row.shadow/reference.shadow-1)>.03)- throw Error('Cloud quality changed integrated density: '+JSON.stringify(group));- }- } finally {renderer.setRenderTarget(previous);renderer.setClearColor(clear,clearAlpha);target.dispose();}- return {scene:new THREE.Scene(),cameras:[{name:'probe',position:[0,0,1],lookAt:[0,0,0]}]};-}-""", ("clouds.js",))- assert code == 0, outdiff --git a/harness/tests/scene_runtime/lib/test_godrays.py b/harness/tests/scene_runtime/lib/test_godrays.pydeleted file mode 100644index 87eef59c..00000000--- a/harness/tests/scene_runtime/lib/test_godrays.py+++ /dev/null@@ -1,144 +0,0 @@-"""godrays.js (8 recorded scenes import it) — regressions: a NaN bounding sphere, an-additive default that blew out daylight frames, and a low sun stretching shafts into spears."""--from __future__ import annotations--from tests.scene_runtime.lib._probe import measure--_LIBS = ("shader.js", "godrays.js")--# Per-shaft end rings, recovered from the merged geometry: uv.y is 0 at the-# gap the light comes through and 1 where it lands, and aShaft tags which-# shaft a vertex belongs to.-_RINGS = """-function rings(mesh) {- const p = mesh.geometry.attributes.position.array;- const uv = mesh.geometry.attributes.uv.array;- const tag = mesh.geometry.attributes.aShaft.array;- const acc = new Map();- for (let i = 0; i < tag.length; i++) {- const v = uv[i * 2 + 1];- const end = v < 1e-6 ? 'top' : (v > 1 - 1e-6 ? 'bot' : null);- if (!end) continue;- const k = tag[i].toFixed(4);- if (!acc.has(k)) acc.set(k, { top: [], bot: [] });- acc.get(k)[end].push([p[i * 3], p[i * 3 + 1], p[i * 3 + 2]]);- }- const mean = (pts) => pts.reduce(- (a, q) => [a[0] + q[0] / pts.length, a[1] + q[1] / pts.length,- a[2] + q[2] / pts.length], [0, 0, 0]);- const radius = (pts, c) => pts.reduce(- (a, q) => a + Math.hypot(q[0] - c[0], q[1] - c[1], q[2] - c[2])- / pts.length, 0);- return [...acc.values()].map((r) => {- const t = mean(r.top), b = mean(r.bot);- const d = [b[0] - t[0], b[1] - t[1], b[2] - t[2]];- const L = Math.hypot(d[0], d[1], d[2]);- return {- axis: [d[0] / L, d[1] / L, d[2] / L],- run: Math.hypot(d[0], d[2]),- rTop: radius(r.top, t), rBot: radius(r.bot, b),- };- });-}-"""---def test_the_instanced_fields_state_a_real_bounding_sphere():- """The stated radius was `run + side * 2` on two Vector3s — the string- "[object Object]NaN" — so both instanced fields shipped a NaN sphere."""- out = measure("""-import { makeGodRays } from './lib/godrays.js';-const g = makeGodRays({ count: 5, height: 8, width: 0.9, seed: 2 });-const r = (n) => g.getObjectByName(n).geometry.boundingSphere.radius;-console.log(JSON.stringify({- pools: r('Pools'), motes: r('Motes'),- finite: Number.isFinite(r('Pools')) && Number.isFinite(r('Motes')),-}));-""", _LIBS)- assert out["finite"], out- # It has to actually cover the field: the drop alone is 8 m.- assert out["pools"] > 8 and out["motes"] > 8, out- # ...and not the 10 km default, which frames a kilometre of empty air.- assert out["pools"] < 200 and out["motes"] < 200, out---def test_the_default_is_the_mode_that_cannot_wreck_a_frame():- """A gorge passed `ambient: 0.5` and got the additive build, a white slab- over daylight; adding light is the exception a caller asks for."""- out = measure("""-import * as THREE from 'three';-import { makeGodRays } from './lib/godrays.js';-const mode = (o) => makeGodRays(o).getObjectByName('Shafts')- .material.blending === THREE.NormalBlending;-console.log(JSON.stringify({- unspecified: mode({ seed: 1 }),- composerMiddle: mode({ ambient: 0.5, seed: 1 }),- daylight: mode({ ambient: 1.0, seed: 1 }),- unlitInterior: mode({ ambient: 0.0, seed: 1 }),- dimRoom: mode({ ambient: 0.2, seed: 1 }),-}));-""", _LIBS)- assert out["unspecified"], "a library's default must be the safe one"- assert out["composerMiddle"], "0.5 is the value a composer actually picks"- assert out["daylight"]- assert not out["unlitInterior"] and not out["dimRoom"], (- "a genuinely dark room still gets added light")---def test_a_low_sun_cannot_stretch_a_shaft_into_a_spear():- """At an 18 deg sun a 32 m drop became a 103 m shaft: a delivered gorge drew- five 100 m bars. The drawn length is capped; only a shaft that still- reaches the floor throws a pool."""- out = measure(_RINGS + """-import { makeGodRays } from './lib/godrays.js';-// 18 deg elevation: the delivered gorge's own sun.-const el = 18 * Math.PI / 180;-const sun = [-Math.cos(el), -Math.sin(el), 0];-const full = (g) => {- const rs = rings(g.getObjectByName('Shafts'));- return rs.map((r) => r.run / Math.cos(el));-};-const low = makeGodRays({ count: 5, height: 32, width: 0.85,- spread: 22, sunDir: sun, seed: 4 });-const wide = makeGodRays({ count: 5, height: 32, width: 0.85,- spread: 22, sunDir: sun, seed: 4,- maxLength: 200 });-const steep = makeGodRays({ count: 5, height: 32, width: 0.85,- spread: 22, sunDir: [0, -1, -0.2], seed: 4 });-console.log(JSON.stringify({- capped: Math.max(...full(low)),- uncapped: Math.max(...full(wide)),- steep: Math.max(...full(steep)),- cappedNames: low.children.map((c) => c.name).sort(),- steepNames: steep.children.map((c) => c.name).sort(),-}));-""", _LIBS)- # 32 / sin(18 deg) = 103 m if nothing caps it; the cap is 1.6x.- assert out["uncapped"] > 95, out- assert out["capped"] <= 32 * 1.6 + 1.0, out- # A shaft that no longer reaches the floor throws no pool...- assert out["cappedNames"] == ["Motes", "Shafts"], out- # ...while a steep sun still lands, and keeps its pool.- assert out["steep"] < 32 * 1.6, out- assert out["steepNames"] == ["Motes", "Pools", "Shafts"], out-----def test_added_light_fades_with_distance_and_never_takes_the_fog_colour():- """The pools and dust were additive but built without `additive: true`, so each- faded its alpha AND ran three's fog chunk, which ADDS fog-coloured haze to an- added light. Every additive material ends in the alpha fade only."""- out = measure("""-import * as THREE from 'three';-import { makeGodRays } from './lib/godrays.js';-const g = makeGodRays({ count: 3, height: 6, seed: 2 });-const mats = [];-g.traverse((o) => { if (o.material && o.material.blending === THREE.AdditiveBlending) mats.push({- name: o.material.name, mix: o.material.fragmentShader.includes('#include <fog_fragment>'),- fade: o.material.fragmentShader.includes('gl_FragColor.a *= 1.0 - clamp(astraFogF') }); });-console.log(JSON.stringify(mats));-""", _LIBS)- assert {m["name"] for m in out} >= {"GodRayPool", "GodRayMotes"}, out- assert all(m["fade"] and not m["mix"] for m in out), outdiff --git a/harness/tests/scene_runtime/lib/test_library.py b/harness/tests/scene_runtime/lib/test_library.pyindex 82aa5ab5..e5058783 100644--- a/harness/tests/scene_runtime/lib/test_library.py+++ b/harness/tests/scene_runtime/lib/test_library.py@@ -9,7 +9,6 @@ import pytestfrom codeverse3d.languages.scene_threejs import lib_filesfrom codeverse3d.prompts import PROMPTS_DIRfrom tests.scene_runtime.lib._probe import compile_scene, measure-from tests.scene_runtime.lib.test_patch_union import LIBRARIES as PATCH_UNIONpytestmark = pytest.mark.node@@ -22,28 +21,6 @@ _PROSE = {"update", "tick", "ambient", "sunDir", "shadows", "true", "false", "co# `rand`, `heightAt`, `sunDir`, `scene`, `on(patch...)` (a mesh wearing those patches) and `inst(patch...)`# (a 4-copy InstancedMesh: the only compile of a patch's USE_INSTANCING branch); each value is an array of Object3Ds.BUILD: dict[str, str] = {- "aging.js": "[on((m) => L.aging.patchDripStains(m), (m) => L.aging.patchRust(m),"- " (m) => L.aging.patchDust(m))]",- "atmosphere.js": "[L.atmosphere.makeHeightFog({ scene, extent: 30, top: 4, heightAt, seed: 4 }),"- " inst((m) => L.atmosphere.patchAerialPerspective(m, { scene }))]",- "building.js": "(() => { const b = L.building.block({ w: 10, d: 8, h: 12, rand, lit: 0.4 });"- " L.building.roofClutter(b, { rand });"- " return [b, L.building.cottage({ rand, lit: true }), L.building.tower({ rand }),"- " L.building.casement({ lit: true }),"- " L.building.cityFabric({ rand, width: 60, depth: 60 }).group]; })()",- "canopy.js": "[L.canopy.makeCanopy({ crowns: [{ position: [0, 4, 0], radius: 2, height: 3 },"- " { position: [6, 1, 0], size: [4, 1.5, 1] }], shadows: true })]",- "celestial.js": "[L.celestial.makeHeatShimmer({ seed: 1 }), L.celestial.makeStars({ count: 200, seed: 2 }),"- " L.celestial.makeStars({ count: 200, seed: 4, ambient: 0.9 }),"- " L.celestial.makeAurora({ seed: 3 }), L.celestial.makeAurora({ seed: 5, ambient: 0.9 })]",- "cloth.js": "[L.cloth.makeFlag({ seed: 3 }), L.cloth.makeBanner({ seed: 5 }),"- " L.cloth.makeWheatField({ extent: 6, density: 20, seed: 7, shadows: true })]",- "clouds.js": "[L.clouds.makeClouds({ seed: 11, preset: 'day', sunDir }),"- " L.clouds.makeCirrus({ seed: 23, sunDir })]",- "damp.js": "[on((m) => L.damp.patchMoss(m), (m) => L.damp.patchMoisture(m),"- " (m) => L.damp.patchCrackedMud(m))]",- "dapple.js": "[inst((m) => L.dapple.patchCanopyShade(m, { density: 0.6 }),"- " (m) => L.dapple.patchDappledLight(m, { height: 7, sunDir }))]","environment.js": "(() => { const rig = L.environment.sunRig({ azimuth: 140, elevation: 30 });"" return [L.environment.worldShell({}).group, rig.sun, rig.fill, rig.sunDisc,"" L.environment.makeOutskirts({ inner: 30, heightAt, seed: 2 }),"@@ -51,88 +28,38 @@ BUILD: dict[str, str] = {" openings: [{ wall: 'south', width: 1.2, height: 2 }] })]; })()","finish.js": "[on((m) => L.finish.patchTranslucency(m, { thickness: 0.01 }),"" (m) => L.finish.patchIridescence(m, { seed: 4 }))]",- "flock.js": "[L.flock.makeFlock({ count: 60, seed: 4 }),"- " L.flock.makeFlock({ count: 30, kind: 'fish', extent: 8, height: 3, seed: 5 })]",- "flowers.js": "[L.flowers.makeFlowers({ extent: 4, heightAt }),"- " L.flowers.makeFalling({ extent: 4, height: 3 })]","foliage_shade.js": "[inst((m) => L.foliage_shade.patchLeafSSS(m, { sunDir }),"" (m) => L.foliage_shade.patchWind(m, { strength: 0.3, height: 5 })),"" on((m) => L.foliage_shade.patchWind(m, { height: 5 }),"" (m) => L.foliage_shade.patchRootContact(m, { band: 0.6 }))]",- "godrays.js": "[L.godrays.makeGodRays({ count: 4, height: 5, seed: 4 }),"- " L.godrays.makeGodRays({ count: 3, height: 5, ambient: 0.05, seed: 9 })]","grass.js": "[L.grass.makeGrass({ extent: 6, density: 40, heightAt, shadows: true })]","materials.js": "['plaster', 'brick', 'granite', 'cobble', 'weatheredWood', 'brushedSteel', 'fabric',"" 'foliage', 'soil', 'skin', 'water', 'glass'].map((n, i) => {"" const k = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1),"" L.materials.tint(L.materials[n](), i / 12)); k.position.x = i * 1.2; return k; })",- "merge.js": "[L.merge.mergeStatic([0, 1, 2].map((i) => { const k = new THREE.Mesh("- "new THREE.BoxGeometry(1, 1, 1), std({ color: 0x806040 + i })); k.position.x = i * 2;"- " return k; }))]",- "neon.js": "(() => { const tube = L.neon.makeNeonTube({ radius: 0.05, seed: 5 });"- " const wall = on((m) => L.surface_wear.patchMicroBreakup(m),"- " (m) => L.neon.patchNeonSpill(m, { sources: [{ position: [0, 1, 1], color: 0xff2e6a }] }));"- " return [tube, L.neon.makeNeonTube({ ambient: 0.8, seed: 6 }), wall,"- " L.neon.makeLightTrails({ path: [[-10, 0, 0], [10, 0, 0]], seed: 2 })]; })()","noise.js": "(() => { const g = new THREE.PlaneGeometry(10, 10, 16, 16); g.rotateX(-Math.PI / 2);"" L.noise.displaceY(g, 1, 0.2, 3);"" return [new THREE.Mesh(g, std({ map: L.noise.noiseDataTexture(32,"" (x, y) => L.noise.fbm2(x * 8, y * 8)) }))]; })()",- "roadway.js": "[on((m) => L.roadway.patchRoadSurface(m), (m) => L.roadway.patchSeamBand(m),"- " (m) => L.roadway.patchTracks(m))]","shader.js": "[]","sky.js": "(L.sky.makeSky(scene, {}), [])",- "strata.js": "[on((m) => L.strata.patchRockStrata(m), (m) => L.strata.patchErosionStreaks(m))]",- "surface_wear.js": "[on((m) => L.surface_wear.patchMicroBreakup(m), (m) => L.surface_wear.patchEdgeWear(m))]","terrain.js": "[L.terrain.ground({ size: 40, segments: 24, rand, relief: 4 }).mesh,"" L.terrain.cliff({ length: 20, height: 8, rand }).mesh]",- "terrain_shade.js": "[on((m) => L.terrain_shade.patchTriplanar(m),"- " (m) => L.terrain_shade.patchSlopeSplat(m, { snowLine: 3 }))]",- "urban.js": "[inst((m) => L.urban.patchCurtainWall(m, {})),"- " on((m) => L.urban.patchCurtainWall(m, { curve: 4.5, coat: 1, blinds: 0.4 })),"- " L.urban.makePowerLines({ seed: 5 }), L.urban.makeBillboard({ lit: true, seed: 6 })]",- "veils.js": "[L.veils.makeRainVeil({ extent: 40, height: 20 }),"- " L.veils.makeSnowfall({ extent: 20, height: 10, seed: 4 }),"- " L.veils.makeMotes({ extent: 4, height: 3, seed: 6 })]",- "water.js": "[L.water.makeOcean(18, 14, { sunDir })]",- "watermist.js": "[L.watermist.makeWaterMist({ extent: 8, height: 2, heightAt }),"- " L.watermist.makeSpray({ origin: [0, 0, 0], seed: 3 })]",- "waterside.js": "[on((m) => L.waterside.patchShoreWet(m), (m) => L.waterside.patchShoreFoam(m),"- " (m) => L.waterside.patchShallowWater(m))]",- "woodland.js": "[on((m) => L.woodland.patchBark(m, { kind: 'oak' })),"- " L.woodland.makeImposters({ count: 30, extent: 20, heightAt })]",- "cloudvolume.js": "[(() => { const c = L.cloudvolume.makeCloudVolume({ size: [60, 18, 36], quality: 'low',"- " seed: 3 }); c.position.y = 20; return c; })()]",- "fire.js": "[L.fire.makeFire({ radius: 0.3, height: 0.9, quality: 'low', seed: 7 }),"- " L.fire.makeCandle({ seed: 2 })]","lifecycle.js": "(() => { const g = new THREE.Group(); g.add(new THREE.Mesh(new THREE.BoxGeometry(), std()));"" L.lifecycle.attachDisposal(g, L.lifecycle.snapshotResources(g)); return [g]; })()",- "meadow.js": "[L.meadow.makeMeadow({ size: [2, 2], density: 60, heightAt, seed: 4 })]",- "ocean.js": "[L.ocean.makeOceanSurface({ width: 20, depth: 20, segments: 32, reflectionSize: 64, seed: 2 })]",- "paving.js": "[L.paving.makePaving({ size: [2, 2], stoneSize: 0.24, seed: 3 }),"- " L.paving.makePaving({ size: [2, 2], pattern: 'setts', seed: 4 })]","rock.js": "[L.rock.makeRock({ type: 'granite', size: [1, 0.8, 1], seed: 4 }),"" L.rock.makeRockField({ count: 6, radius: 3, seed: 5 })]",- "sand.js": "[L.sand.makeSandTerrain({ size: [20, 20], seed: 3 })]",- "smoke.js": "[L.smoke.makeSmoke({ quality: 'low', seed: 2 }), L.smoke.makeSteam({ quality: 'low' })]","tree.js": "[L.tree.makeTree({ species: 'birch', height: 4, maxLeaves: 600, seed: 3 }),"" L.tree.makeShrub({ maxLeaves: 300, seed: 2 })]",}# What the GPU compiles here, in groups so xdist spreads the browser boots.-# shader.js is compiled through its own construction paths (test_shader.py)-# and the seven patch libraries chain by chain (test_patch_union.py).+# shader.js is compiled through its own construction paths (test_shader.py).GROUPS: dict[str, tuple[str, ...]] = {- "vegetation": ("canopy.js", "cloth.js", "flowers.js", "foliage_shade.js", "grass.js",- "woodland.js", "dapple.js"),- "sky_and_air": ("atmosphere.js", "celestial.js", "clouds.js", "environment.js", "godrays.js",- "sky.js", "veils.js", "flock.js"),- "water": ("water.js", "watermist.js", "finish.js"),- "volumes": ("cloudvolume.js", "fire.js", "smoke.js"),- "ground": ("lifecycle.js", "meadow.js", "paving.js", "rock.js", "sand.js", "tree.js"),- "flowing_water": ("ocean.js",),- "built": ("building.js", "materials.js", "merge.js", "neon.js",- "noise.js", "terrain.js", "urban.js"),+ "vegetation": ("foliage_shade.js", "grass.js", "tree.js"),+ "sky_and_air": ("environment.js", "sky.js"),+ "ground": ("lifecycle.js", "rock.js", "terrain.js"),+ "built": ("finish.js", "materials.js", "noise.js"),}_PRELUDE = "\n".join(f"import * as L_{m[:-3]} from './lib/{m}';" for m in MODULES) + """@@ -168,7 +95,7 @@ def test_every_module_is_built_and_compiled_somewhere():assert set(BUILD) == set(MODULES)grouped = [m for g in GROUPS.values() for m in g]assert len(grouped) == len(set(grouped))- assert set(grouped) | set(PATCH_UNION) | {"shader.js"} == set(MODULES)+ assert set(grouped) | {"shader.js"} == set(MODULES)def test_every_module_imports_and_exports_what_the_catalog_advertises():@@ -200,7 +127,7 @@ console.log(JSON.stringify({ exports, errors }));# the planner routes an element to a zone that cannot build it (or, listed short, to a hand-built asset)plan = (PROMPTS_DIR / "tracks" / "plan_scene.j2").read_text(encoding="utf-8")shipped = re.findall(r"`([a-z_]+\.js)`\s*\(([^)]*)\)", plan)- assert len(shipped) >= 9, shipped+ assert len(shipped) >= 5, shippedstale += [f"plan_scene.j2: {n} ({m})" for m, calls in shippedfor n in re.findall(r"`(make[A-Za-z]+)`", calls) if n not in exported.get(m, ())]assert not stale, stale@@ -257,8 +184,9 @@ export async function createScene({ renderer }) {# Named bugs where a factory once built silently broken output from input it# should refuse: (module, call, a phrase the RangeError must carry).REFUSALS = [- # a NaN wind direction normalised to NaN and poisoned every dune vertex- ("sand.js", "makeSandTerrain({ windDirection: [NaN, 1] })", "windDirection"),+ # a NaN size would displace every vertex to NaN; a NaN wind direction, every leaf+ ("rock.js", "makeRock({ size: [1, NaN, 1] })", "size"),+ ("tree.js", "makeTree({ wind: { dir: [NaN, 1] } })", "wind"),]@@ -275,39 +203,23 @@ console.log(JSON.stringify({{ error }}));# One option rule (audit N33): null takes the default, an invalid one throws a RangeError naming it, a seed is-# any finite number, the sun is `sunDir` everywhere (a derived seed built in one effect and threw in its neighbour).+# any finite number (a derived seed built in one effect and threw in its neighbour)._OPTIONS = """import * as THREE from 'three';-import { makeFire } from './lib/fire.js';import { makeTree } from './lib/tree.js';-import { makeMeadow } from './lib/meadow.js';-import { makeOceanSurface } from './lib/ocean.js';-import { makeSmoke } from './lib/smoke.js';-import { makeClouds } from './lib/clouds.js';-import { makeCloudVolume } from './lib/cloudvolume.js';-import { makeSandTerrain } from './lib/sand.js';import { makeRock } from './lib/rock.js';-import { makePaving } from './lib/paving.js';import { readVec3 } from './lib/shader.js';const calls = {- fire: (o) => makeFire(o),- tree: (o) => makeTree({ leafDensity: .05, ...o }), meadow: (o) => makeMeadow({ size: [1, 1], density: 20, ...o }),- ocean: (o) => makeOceanSurface({ width: 10, depth: 10, segments: 16, ...o }),- smoke: (o) => makeSmoke({ quality: 'low', ...o }), clouds: (o) => makeClouds({ count: 2, ...o }),- cloudvolume: (o) => makeCloudVolume({ quality: 'low', ...o }),- sand: (o) => makeSandTerrain({ size: [10, 10], segments: 16, ...o }),- rock: (o) => makeRock(o), paving: (o) => makePaving({ size: [2, 2], ...o }),+ tree: (o) => makeTree({ leafDensity: .05, ...o }),+ rock: (o) => makeRock(o),};const seeds = { null: null, big: 2 ** 40, fraction: 3.7, text: '7' };const run = (f) => { try { f(); return 'ok'; } catch (e) { return e instanceof RangeError ? e.message : 'not a RangeError: ' + e; } };const out = { seed: {} };for (const [name, call] of Object.entries(calls))out.seed[name] = Object.fromEntries(Object.entries(seeds).map(([k, seed]) => [k, run(() => call({ seed }))]));-const sunOf = (g) => { let v; g.traverse((o) => { const u = o.material?.uniforms; v ??= (u?.seaSun ?? u?.uSunWorld)?.value; }); return v?.toArray(); };-out.sun = { ocean: sunOf(calls.ocean({ sunDir: [0, 1, 0] })), cloudvolume: sunOf(calls.cloudvolume({ sunDir: [0, 1, 0] })) };-out.nullDefaults = run(() => calls.meadow({ height: null }));-out.fireClamps = run(() => makeFire({ radius: 1e6 }));-out.badNames = [run(() => calls.meadow({ height: 'tall' })), run(() => calls.smoke({ spread: 5 })), run(() => calls.cloudvolume({ coverage: 2 }))];+out.nullDefaults = run(() => calls.tree({ height: null }));+out.badNames = [run(() => calls.tree({ height: 'tall' })), run(() => calls.tree({ leafDensity: 9 })), run(() => calls.rock({ type: 'marble' }))];out.point = readVec3([1, 2]).toArray().concat(readVec3(null, 4, 5, 6).toArray(), readVec3({ x: 1 }).toArray());console.log(JSON.stringify(out));"""@@ -318,8 +230,7 @@ def test_every_factory_reads_its_options_by_one_rule():for name, row in out["seed"].items():assert row["null"] == row["big"] == row["fraction"] == "ok", (name, row)assert "seed" in row["text"], (name, row)- assert out["sun"] == {"ocean": [0, 1, 0], "cloudvolume": [0, 1, 0]}, out["sun"]- assert out["nullDefaults"] == out["fireClamps"] == "ok", out- for phrase, message in zip(("height", "spread", "coverage"), out["badNames"], strict=True):+ assert out["nullDefaults"] == "ok", out+ for phrase, message in zip(("height", "leafDensity", "type"), out["badNames"], strict=True):assert phrase in message, out["badNames"]assert out["point"] == [1, 2, 0, 4, 5, 6, 1, 0, 0]diff --git a/harness/tests/scene_runtime/lib/test_merge.py b/harness/tests/scene_runtime/lib/test_merge.pydeleted file mode 100644index c7671159..00000000--- a/harness/tests/scene_runtime/lib/test_merge.py+++ /dev/null@@ -1,55 +0,0 @@-"""merge.js — regressions."""-from __future__ import annotations--import pytest-from _probe import measure--pytestmark = pytest.mark.node--_LIBS = ("merge.js",)---def test_a_mirrored_piece_is_not_baked_inside_out():- """`scale.x = -1` reverses the winding once baked."""- out = measure("""-import * as THREE from 'three';-import { mergeStatic } from './lib/merge.js';-const facing = (mesh) => {- const g = mesh.geometry;- const p = g.attributes.position, n = g.attributes.normal;- const idx = g.index;- const tri = idx ? idx.count / 3 : p.count / 3;- const a = new THREE.Vector3(), b = new THREE.Vector3(), c = new THREE.Vector3();- let out = 0;- for (let t = 0; t < tri; t++) {- const i0 = idx ? idx.getX(t * 3) : t * 3;- const i1 = idx ? idx.getX(t * 3 + 1) : t * 3 + 1;- const i2 = idx ? idx.getX(t * 3 + 2) : t * 3 + 2;- a.fromBufferAttribute(p, i0);- b.fromBufferAttribute(p, i1).sub(a);- c.fromBufferAttribute(p, i2).sub(a);- b.cross(c);- const vn = new THREE.Vector3().fromBufferAttribute(n, i0);- if (b.dot(vn) > 0) out++;- }- return [out, tri];-};-const mk = (sx, geo) => {- const m = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ color: 0x998877 }));- m.position.set(4, 1, 0); m.rotation.set(0.2, 0.5, 0.13); m.scale.x = sx;- return m;-};-const plain = facing(mergeStatic([mk(1, new THREE.BoxGeometry(0.5, 1.9, 1.1))]));-const mirrored = facing(mergeStatic([mk(-1, new THREE.BoxGeometry(0.5, 1.9, 1.1))]));-// the non-indexed path flips vertex runs instead of index triples-const nonIdx = facing(mergeStatic(- [mk(-1, new THREE.BoxGeometry(0.5, 1.9, 1.1).toNonIndexed())]));-// a mirrored piece merged NEXT TO a plain one must not disturb it-const both = facing(mergeStatic([mk(1, new THREE.BoxGeometry(1, 1, 1)),- mk(-1, new THREE.BoxGeometry(1, 1, 1))]));-console.log(JSON.stringify({ plain, mirrored, nonIdx, both }));-""", _LIBS)- for name in ("plain", "mirrored", "nonIdx", "both"):- out_faces, tris = out[name]- assert tris > 0 and out_faces == tris, (- f"{name}: {out_faces}/{tris} triangles wind outward")diff --git a/harness/tests/scene_runtime/lib/test_patch_union.py b/harness/tests/scene_runtime/lib/test_patch_union.pydeleted file mode 100644index a3601f1a..00000000--- a/harness/tests/scene_runtime/lib/test_patch_union.py+++ /dev/null@@ -1,247 +0,0 @@-"""The seven surface-patch libraries on ONE material."""-from __future__ import annotations--import itertools-import json-import re-from collections import Counter--import pytest--from tests.scene_runtime.lib._probe import (- LIB_DIR,- SHADER_JS,- _find,- _main_body,- compile_scene,- measure,-)--pytestmark = pytest.mark.node--# The seven, and the patches each ships.-LIBRARIES: dict[str, tuple[str, ...]] = {- "terrain_shade.js": ("patchTriplanar", "patchSlopeSplat"),- "waterside.js": ("patchShoreWet", "patchShoreFoam", "patchShallowWater"),- "surface_wear.js": ("patchMicroBreakup", "patchEdgeWear"),- "aging.js": ("patchDripStains", "patchRust", "patchDust"),- "strata.js": ("patchRockStrata", "patchErosionStreaks"),- "damp.js": ("patchMoss", "patchMoisture", "patchCrackedMud"),- "roadway.js": ("patchRoadSurface", "patchSeamBand", "patchTracks"),-}-ALL = [p for patches in LIBRARIES.values() for p in patches]--# Shared ON PURPOSE: the clock tickShaders drives, and the one world-# position / normal pair every library's base writes (shader.js-# WORLD_VARYINGS), so a material wearing several declares ONE.-SHARED = {"uniform": {"uTime"}, "varying": {"vAstraWorld", "vAstraWorldN"}}--# Every patch at its defaults, but the splat's snow line pulled into frame-# so its snow branch is live code. Shared by the probe and the scene.-_APPLY_JS = "\n".join(- f"import {{ {', '.join(patches)} }} from './lib/{lib}';"- for lib, patches in LIBRARIES.items()) + """-const LIBS = """ + json.dumps({lib: list(p) for lib, p in LIBRARIES.items()}) + """;-const PATCH = { """ + ", ".join(ALL) + """ };-const OPTS = { patchSlopeSplat: { snowLine: 30 } };-const apply = (m, names) => {- for (const n of names) PATCH[n](m, OPTS[n] || {});- return m;-};-const ALL = Object.values(LIBS).flat();-"""--# What a head or a body declares, by kind (the return types are the set-# patchStandard's own duplicate-helper check reads).-_TYPE = r"(?:void|float|u?int|bool|[biu]?vec[234]|mat[234](?:x[234])?)"-_HELPER = re.compile(r"^\s*(?:(?:lowp|mediump|highp)\s+)?" + _TYPE + r"\s+(\w+)\s*\(", re.M)-_LOCAL = re.compile(r"^\s*(?:const\s+)?(?:(?:lowp|mediump|highp)\s+)?"- r"(?:float|u?int|bool|[biu]?vec[234]|mat[234])\s+(\w+)\s*[=;,\[]", re.M)-_VARYING = re.compile(r"^\s*varying\s+(?:(?:lowp|mediump|highp)\s+)?\w+\s+(\w+)\s*;", re.M)-_DECL = re.compile(r"^\s*(?:uniform|varying)\s+(?:(?:lowp|mediump|highp)\s+)?\w+\s+(\w+)", re.M)---def _unguarded(src: str) -> str:- """Drop ``#ifndef X ..."""- return re.sub(r"#ifndef\b.*?#endif", "", src, flags=re.S)---def test_no_library_declares_a_name_another_owns():- """All 45 pairs, both stages, four kinds of name — each library compiled ALONE, so a clash is caught however the two ever meet."""- out = measure(SHADER_JS + """-import * as THREE from 'three';-import { GLSL_UTIL } from './lib/shader.js';-""" + _APPLY_JS + """-const std = () => new THREE.MeshStandardMaterial({ color: 0x8b8478, roughness: 0.7 });-const per = {};-for (const [lib, names] of Object.entries(LIBS)) {- const m = apply(std(), names);- const s = compile(m);- per[lib] = { uniforms: Object.keys(m.userData.uniforms),- vs: s.vertexShader, fs: s.fragmentShader };-}-const union = (names) => {- const s = compile(apply(std(), names));- return { vs: s.vertexShader, fs: s.fragmentShader };-};-console.log(JSON.stringify({ per, util: GLSL_UTIL, forward: union(ALL),- reversed: union(ALL.slice().reverse()) }));-""", tuple(LIBRARIES))- util = set(_HELPER.findall(out["util"]))- owns = {}- for lib, got in out["per"].items():- vs, fs = got["vs"], got["fs"]- heads = vs[:vs.index("void main")] + fs[:fs.index("void main")]- owns[lib] = {- "uniform": set(got["uniforms"]) - SHARED["uniform"],- "varying": set(_VARYING.findall(vs + fs)) - SHARED["varying"],- "helper": set(_HELPER.findall(heads)) - util,- "local": set(_LOCAL.findall(_main_body(vs) + _main_body(fs))),- }- # An empty set would make every pair below pass for nothing.- assert owns[lib]["uniform"] and owns[lib]["local"], (lib, owns[lib])- clashes = [f"{a} and {b} both declare the {kind}(s) {sorted(both)}"- for (a, mine), (b, theirs) in itertools.combinations(owns.items(), 2)- for kind in mine if (both := mine[kind] & theirs[kind])]- assert not clashes, "\n".join(clashes)-- for order in ("forward", "reversed"):- for stage in ("vs", "fs"):- src = out[order][stage]- for kind, found in (("declaration", _DECL.findall(src)),- ("helper", _HELPER.findall(_unguarded(src))),- ("main() local", _LOCAL.findall(_main_body(src)))):- twice = sorted(n for n, c in Counter(found).items() if c > 1)- assert not twice, f"{order} chain, {stage}: {kind}(s) {twice} twice"- # each library's vertex stage is its world base and no more: instancing folds in `instanceMatrix`- # (else every copy of a scattered rock shades from the mesh origin), no stage-split varying,- # nothing displaces `transformed` (a hard-edged bed would tear open at its rim)- for lib, got in out["per"].items():- vs, fs = got["vs"], got["fs"]- body = _main_body(vs)- p = _find(r"vAstraWorld = \(modelMatrix \* (\w+)\)\.xyz;", body).group(1)- assert f"{p} = instanceMatrix * {p};" in body, (lib, p)- assert set(_VARYING.findall(vs)) == set(_VARYING.findall(fs)), lib- assert not re.search(r"\btransformed\s*[-+*/]?=", body), lib---# Every chain the scene compiles: (name, patches, options, instances). Each patch ALONE (catches a body-# reading what a sibling declares), all of them forward and reversed, and the variants that change the-# program: flat shading, instancing (the only compile of USE_INSTANCING), transparency, maps, `fog: false`.-MATERIALS: list[tuple[str, list[str], dict, int]] = [- *((f"{name} alone", [name], {}, 0) for name in ALL),- ("every patch", ALL, {}, 0),- ("every patch, reversed, flat-shaded, instanced", ALL[::-1],- {"flatShading": True}, 4),- ("every patch, transparent, textured, unfogged", ALL,- {"transparent": True, "opacity": 0.6, "textured": True, "fog": False}, 0),-]--# A workspace SCENE for check_shaders.mjs: fogged (USE_FOG is a define, never compiled otherwise), a-# CASTING sun (else no shadow-map chunks), a camera (else the host reports no boot), plus terrain.js's-# ground and cliff wearing the splat and triplanar.-_SCENE = """-import * as THREE from 'three';-import { tickShaders } from './lib/shader.js';-import { ground, cliff } from './lib/terrain.js';-""" + _APPLY_JS + """-const MATERIALS = """ + json.dumps(MATERIALS) + """;--export const BOUNDS = { min: [-40, 0, -40], max: [40, 30, 40] };--export function createScene({ renderer }) {- // The report pins an error on the materials whose source holds the line- // it quotes, and every chain here shares most of its lines. So each- // material's cache key carries its own index, and the host's error hook- // is wrapped to name the chain whose program did not link.- const labels = [];- const tag = (mat, label) => {- const key = mat.customProgramCacheKey;- const i = labels.push(label) - 1;- mat.name = label;- mat.customProgramCacheKey = () => key() + '#' + i;- };- const hook = renderer.debug.onShaderError;- renderer.debug.onShaderError = (gl, program, ...rest) => {- const p = renderer.info.programs.find((x) => x.program === program);- const i = p && /#(\\d+)$/.exec(p.cacheKey);- console.error('this chain did not link: ' + (i ? labels[i[1]] : p ? p.name : '?'));- if (hook) hook(gl, program, ...rest);- };-- const scene = new THREE.Scene();- scene.fog = new THREE.FogExp2(0xcfd8e6, 0.0035);- scene.add(new THREE.HemisphereLight(0xbcd6ef, 0x4a4130, 0.9));- const sun = new THREE.DirectionalLight(0xfff0d6, 2.5);- sun.position.set(5, 8, 7);- sun.castShadow = true;- scene.add(sun);-- const tex = new THREE.DataTexture(new Uint8Array([200, 190, 170, 255]), 1, 1);- tex.colorSpace = THREE.SRGBColorSpace;- tex.needsUpdate = true;- MATERIALS.forEach(([label, names, o, count], i) => {- const { textured, ...params } = o;- const mat = new THREE.MeshStandardMaterial(Object.assign(- { color: 0x8b8478, roughness: 0.7 }, params,- textured ? { map: tex, bumpMap: tex, roughnessMap: tex, vertexColors: true } : {}));- tag(apply(mat, names), label);- const geo = new THREE.IcosahedronGeometry(0.6, 2);- if (textured) {- geo.setAttribute('color', new THREE.Float32BufferAttribute(- new Array(geo.attributes.position.count * 3).fill(0.9), 3));- }- const mesh = count ? new THREE.InstancedMesh(geo, mat, count) : new THREE.Mesh(geo, mat);- for (let k = 0; k < count; k++) {- mesh.setMatrixAt(k, new THREE.Matrix4().makeTranslation(0, k * 1.3, 0));- }- mesh.position.set((i % 10) * 2 - 9, 0.6, Math.floor(i / 10) * 2 - 6);- mesh.castShadow = mesh.receiveShadow = true;- mesh.frustumCulled = false;- scene.add(mesh);- });-- let s = 7;- const rand = () => ((s = (s * 16807) % 2147483647) / 2147483647);- const land = ground({ size: 80, segments: 24, rand, relief: 10 });- tag(patchSlopeSplat(land.mesh.material, { snowLine: 9, snowBand: 2.5 }),- 'ground() with patchSlopeSplat');- const wall = cliff({ length: 30, height: 12, rand });- tag(patchTriplanar(wall.mesh.material, { scale: 3.5 }), 'cliff() with patchTriplanar');- wall.mesh.position.set(0, 0, -20);- scene.add(land.mesh, wall.mesh);- return {- scene,- cameras: [{ name: 'hero', position: [0, 16, 26], lookAt: [0, 1, 0], fov: 60 }],- update(t) { tickShaders(scene, t); },- };-}-"""---def _library_line(glsl: str | None) -> str:- """Where a quoted GLSL line lives in the library."""- needle = (glsl or "").strip()- hits = [f"{lib}:{n}" for lib in (*LIBRARIES, "shader.js")- for n, text in enumerate((LIB_DIR / lib).read_text(encoding="utf-8").splitlines(), 1)- if len(needle) > 2 and needle in text]- return " ".join(hits[:3]) or "(not a library line)"---def test_every_chain_compiles_on_the_real_renderer(tmp_path):- """The only witness that counts."""- report_path = tmp_path / "report.json"- code, out = compile_scene(- _SCENE, (*LIBRARIES, "terrain.js"), report=report_path)- assert report_path.is_file(), out # the preflight itself died: `out` says why- report = json.loads(report_path.read_text(encoding="utf-8"))- problems = [f"{_library_line(e.get('source_line'))}: {e.get('message')}"- for e in report["errors"]]- problems += [f"{w.get('file')}: {w.get('message')}" for w in report["warnings"]]- assert code == 0 and report["ok"] and not problems, "\n".join(problems) or out- compiled = report["compile"]- assert compiled["gpu"], "this claim is only worth a real GPU"- # Every chain above is its own program (plus ground and cliff):- # a green exit on a compile that skipped them would prove nothing.- assert compiled["custom_materials"] >= len(MATERIALS) + 2, compiled- assert compiled["programs"] >= len(MATERIALS) + 2, compileddiff --git a/harness/tests/scene_runtime/lib/test_shader.py b/harness/tests/scene_runtime/lib/test_shader.pyindex a90dbbdd..a6bfbc12 100644--- a/harness/tests/scene_runtime/lib/test_shader.py+++ b/harness/tests/scene_runtime/lib/test_shader.py@@ -157,41 +157,24 @@ export function build() {assert "ERROR" not in out, out-# The catalog's one wind object, the [x,z] pair the fire/smoke rows use, a number and a-# Vector3: each handed to every wind reader. Before readWind, the object threw in-# smoke/clouds/cloudvolume (RangeError), fire read no wind,-# and windOf ignored the pair and blew the default way.+# The catalog's one wind object, an [x,z] pair, a number and a Vector3: each handed to+# both wind readers. Before readWind, windOf ignored the pair and blew the default way._WIND = """import * as THREE from 'three';import { readWind } from './lib/shader.js';import { windOf } from './lib/grass.js';-import { makeFire } from './lib/fire.js';-import { makeSmoke } from './lib/smoke.js';-import { makeCloudVolume } from './lib/cloudvolume.js';-import { makeClouds } from './lib/clouds.js';-import { makeRainVeil } from './lib/veils.js';-const uni = (g, name) => { let u; g.traverse((o) => { const v = o.material?.uniforms?.[name]; if (v && !u) u = v.value; }); return u; };const xz = (v) => v.isVector3 ? [v.x, v.z] : typeof v === 'number' ? [v, 0] : [v.x, v.y];const winds = { object: { dir: [1, 0.3], strength: 1.2, speed: 1 }, pair: [1, 0.3], number: 1.2,vec3: new THREE.Vector3(1, 5, 0.3) };const out = {};for (const [k, w] of Object.entries(winds)) {const r = readWind(w, [0, 0]);- out[k] = {- read: [r.dir.x, r.dir.y],- windOf: xz(windOf(w).dir),- fire: xz(uni(makeFire({ wind: w }), 'uWind')),- smoke: xz(makeSmoke({ wind: w }).material.uniforms.uWind.value),- cloudVolume: xz(makeCloudVolume({ wind: w, quality: 'low' }).material.uniforms.uWind.value),- clouds: uni(makeClouds({ wind: w, count: 2 }), 'uWind'),- veil: xz(uni(makeRainVeil({ direction: w }), 'uWind')),- };+ out[k] = { read: [r.dir.x, r.dir.y], windOf: xz(windOf(w).dir) };}console.log(JSON.stringify(out));"""-_WIND_LIBS = ("grass.js", "fire.js", "smoke.js", "cloudvolume.js",- "clouds.js", "veils.js")+_WIND_LIBS = ("grass.js",)@pytest.fixture(scope="module")@@ -206,12 +189,8 @@ def test_one_wind_is_read_the_same_way_by_every_effect(wind, spelling):# the number has no direction of its own: it blows along the fallback'sexpect = [1, 0] if spelling == "number" else [1 / math.hypot(1, 0.3), 0.3 / math.hypot(1, 0.3)]assert ref == pytest.approx(expect)- for reader in ("fire", "smoke", "cloudVolume", "veil"):- v = w[reader]- n = math.hypot(*v)- assert n > 0 and all(math.isfinite(c) for c in v), (reader, v)- if spelling != "number": # a number blows along each effect's own default direction- assert (v[0] / n, v[1] / n) == pytest.approx(tuple(ref), abs=1e-6), (reader, v)+ v = w["windOf"]+ n = math.hypot(*v)+ assert n > 0 and all(math.isfinite(c) for c in v), vif spelling != "number": # windOf's own fallback direction is (1, 0.45)- assert w["windOf"] == pytest.approx(ref)- assert math.isfinite(w["clouds"]) and w["clouds"] > 0+ assert v == pytest.approx(ref)diff --git a/harness/tests/scene_runtime/lib/test_shader_geometry.py b/harness/tests/scene_runtime/lib/test_shader_geometry.pyindex dea4463d..c6c43238 100644--- a/harness/tests/scene_runtime/lib/test_shader_geometry.py+++ b/harness/tests/scene_runtime/lib/test_shader_geometry.py@@ -8,11 +8,10 @@ from tests.scene_runtime.lib._probe import compile_scenepytestmark = pytest.mark.node-def test_cloned_and_merged_shader_sample_live_render_target_on_gpu():+def test_cloned_shader_samples_live_render_target_on_gpu():code, out = compile_scene("""import * as THREE from 'three';import {makeShaderMaterial,clonePatchedMaterial} from './lib/shader.js';-import {mergeStatic} from './lib/merge.js';export function createScene({renderer}) {const scene=new THREE.Scene(),camera=new THREE.OrthographicCamera(-1,1,1,-1,.1,10);camera.position.z=2;@@ -24,29 +23,21 @@ export function createScene({renderer}) {fragmentMain:'gl_FragColor=texture2D(uSample,vec2(.5))*vec4(vec3(uGain),1.0);'});const original=new THREE.Mesh(new THREE.PlaneGeometry(2,2),material);const clone=new THREE.Mesh(original.geometry,clonePatchedMaterial(material));- const merged=mergeStatic([original],{variance:0});const previous=renderer.getRenderTarget(),expected=new Uint8Array(4),actual=new Uint8Array(4);try {renderer.setRenderTarget(textureTarget);renderer.render(sourceScene,camera);renderer.readRenderTargetPixels(textureTarget,4,4,1,1,expected);- for(const mesh of [clone,merged]) {- scene.add(mesh);renderer.setRenderTarget(readTarget);renderer.render(scene,camera);- renderer.readRenderTargetPixels(readTarget,4,4,1,1,actual);scene.remove(mesh);- if(actual.some((value,i)=>Math.abs(value-expected[i])>2))- throw new Error('Lost cloned/merged render-target sampler: '+actual+' expected '+expected);- }- // The batch follows the source clock/control map after construction.- material.uniforms.uGain.value=.5;scene.add(merged);renderer.render(scene,camera);- renderer.readRenderTargetPixels(readTarget,4,4,1,1,actual);scene.remove(merged);- if(actual.slice(0,3).some((value,i)=>Math.abs(value-expected[i]*.5)>2))- throw new Error('Merged shader disconnected source controls: '+actual);+ scene.add(clone);renderer.setRenderTarget(readTarget);renderer.render(scene,camera);+ renderer.readRenderTargetPixels(readTarget,4,4,1,1,actual);scene.remove(clone);+ if(actual.some((value,i)=>Math.abs(value-expected[i])>2))+ throw new Error('Lost cloned render-target sampler: '+actual+' expected '+expected);} finally {renderer.setRenderTarget(previous);readTarget.dispose();textureTarget.dispose();- merged.userData.dispose();clone.material.dispose();original.geometry.dispose();material.dispose();+ clone.material.dispose();original.geometry.dispose();material.dispose();}return {scene,cameras:[{name:'a',position:[0,0,2],lookAt:[0,0,0],fov:45}]};}-""", libs=("merge.js",))+""")assert code == 0, outassert json.loads(out.strip().splitlines()[-1])["ok"]diff --git a/harness/tests/scene_runtime/test_skeleton.py b/harness/tests/scene_runtime/test_skeleton.pyindex 42d675b2..9e0d4961 100644--- a/harness/tests/scene_runtime/test_skeleton.py+++ b/harness/tests/scene_runtime/test_skeleton.py@@ -74,7 +74,7 @@ def test_both_skeleton_paths_ship_the_effect_library(tmp_path):from codeverse3d.languages.scene_threejs import lib_filesnames = {p.name for p in lib_files()}- assert len(names) >= 40 and "grass.js" in names and "shader.js" in names+ assert len(names) >= 12 and "grass.js" in names and "shader.js" in namesfor label, plan in (("example", None), ("plan", make_plan())):ws = Workspace(tmp_path / label)