Skip to content

Official Codebase of 3DCodeVerse

Python

effects library: fourteen natural-element modules, one ownership rule, per-pixel finishes

gaoypeng30848358d8e2
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/accumulation.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/accumulation.js
index 551bf58d..0620df6a 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/accumulation.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/accumulation.js
@@ -14,22 +14,20 @@
* `terrain_shade`, `waterside` and `aging` on one material.
*
* THE CONSTRAINT IS THAT NEITHER HAS THICKNESS. `fragmentBody` edits
- * albedo and nothing else; a vertex displacement would tear every
+ * albedo and the lit micro-normal; vertex displacement would tear every
* hard-edged BoxGeometry open at its rim, because the top face's
* vertices carry a different normal from the side's and would walk
* away from them. So a layer sells its depth by what it COVERS (steep
* faces lose it, concave lees keep it), by a torn edge instead of a
* ruled one, and by the shade it drops on the material just outside
- * that edge. Gloss here is per MATERIAL, not per pixel (neither patch
- * uses `patchStandard`'s `roughnessBody`), so each patch composes ONE
- * factor through `composeRoughness`, weighted by how much of the
- * surface it took over.
+ * that edge. Roughness and metalness follow the same local coverage as
+ * the albedo; bare faces retain the authored substrate finish.
*/
import * as THREE from 'three';
import {
- patchStandard, composeRoughness, glslAxes, glslCurv, glslTriNoise,
- seedVec3, toColor, towardRoughness, unit, upVector, worldBase,
+ patchStandard, glslAxes, glslCurv, glslTriNoise,
+ seedVec3, toColor, unit, upVector, worldBase,
} from './shader.js';
// Both patches read these, so they are declared once, in the base.
@@ -106,7 +104,7 @@ function windVector(value, fallback) {
* @param {object} [opts] `depth` metres of lying snow, which sets how
* far down a pitch it holds and how opaque it is (default 0.05; 0.01
* is a dusting, 0.15 buries); `color` THREE.Color or hex (default a
- * cold white at 0.78 linear — snow is the brightest albedo in a scene
+ * neutral white below 0.78 linear — snow is the brightest albedo in a scene
* and still has to sit UNDER the tone curve's shoulder, or its own
* shading clips to one flat card); `up` THREE.Vector3 or [x, y, z], the scene's up
* (default +Y); `wind` THREE.Vector3 or [x, y, z] it blows TOWARD,
@@ -131,16 +129,13 @@ export function patchSnow(material, opts = {}) {
? Math.max(1e-3, melt.radius === undefined ? 0.9 : melt.radius) : 0;
// Snow is a diffuse cover with a faint sheen, and it takes the
// material's gloss over only as far as it takes the surface over.
- composeRoughness(material, 'acc:snow',
- towardRoughness(material, 0.86,
- 0.65 * unit(depth / 0.05)
- * (1 - meltAmt)));
+
patchStandard(material, BASE);
return patchStandard(material, {
name: 'acc:snow',
uniforms: {
uSnowDepth: { value: depth },
- uSnowColor: { value: toColor(opts.color, 0xc9d2dd) },
+ uSnowColor: { value: toColor(opts.color, 0xe0e2e3) },
uSnowUp: { value: upVector(opts.up) },
uSnowWind: { value: windVector(opts.wind, null) },
uSnowMelt: { value: meltAmt },
@@ -156,6 +151,20 @@ export function patchSnow(material, opts = {}) {
'uniform vec4 uSnowWarm;',
'uniform vec3 uSnowSeed;',
].join('\n'),
+ roughnessBody: 'roughnessFactor = mix(roughnessFactor, 0.86, snAmt);',
+ metalnessBody: 'metalnessFactor *= 1.0 - snAmt;',
+ normalBody: [
+ 'vec3 snDx = dFdx(-vViewPosition);',
+ 'vec3 snDy = dFdy(-vViewPosition);',
+ 'vec3 snR1 = cross(snDy, normal);',
+ 'vec3 snR2 = cross(normal, snDx);',
+ 'float snDet = dot(snDx, snR1);',
+ 'float snHeight = snAmt * snF * snFad * 0.0009;',
+ 'vec3 snGradient = sign(snDet) *',
+ ' (dFdx(snHeight) * snR1 + dFdy(snHeight) * snR2);',
+ 'if (abs(snDet) > 1e-12)',
+ ' normal = normalize(abs(snDet) * normal - snGradient);',
+ ].join('\n'),
fragmentBody: [
' vec3 snN = normalize(vAstraWorldN);',
' vec3 snUp = normalize(uSnowUp);',
@@ -216,28 +225,12 @@ export function patchSnow(material, opts = {}) {
' float snF = astraAccNoise(snP * 6.0 + 17.3, snW);',
' float snTn = clamp(mix(snG, snG * 0.66 + snF * 0.34, snFad),',
' 0.0, 1.0);',
- // The tone rides both fields, over a swing that has to live BELOW
- // the tone curve's shoulder: at exposure 1.0 with no post chain,
- // 0.85 linear and 0.56 linear come out of ACES as the same white,
- // so a near-white cover shaded across the top of the curve renders
- // as one flat card however much field is under it.
- ' vec3 snCol = mix(uSnowColor * 0.46, uSnowColor * 1.04,',
+ // Fresh snow is nearly neutral. Wide blue/white albedo swings made
+ // flat ground look marbled; the scene light supplies its shadow hue.
+ ' vec3 snCol = mix(uSnowColor * 0.82, uSnowColor * 1.03,',
' smoothstep(0.16, 0.86, snTn));',
- // Deep pack goes BLUE and a scoured lane goes warm: a drift is lit
- // by the sky through its own scattering, while thin snow hands
- // some of the substrate back. The concave lee counts extra,
- // because a hollow is the bluest snow in any photograph.
- ' float snPack = clamp(smoothstep(0.30, 1.20, snD)',
- ' + clamp(snHold - 1.0, 0.0, 1.0) * 0.6,',
- ' 0.0, 1.0);',
- ' snCol *= mix(vec3(1.05, 1.01, 0.96), vec3(0.90, 0.96, 1.10),',
- ' snPack);',
- // Snow is the most coloured surface in any scene — it reflects
- // whatever lights it — so it takes the swing too, but gently:
- // past a narrow band it stops reading as snow. TWO scales, because
- // one field the width of a yard is still one flat tint on a roof.
- ' snCol = astraHueBreak(snCol, vAstraWorld.xz, 0.22, 0.14);',
- ' snCol = astraHueBreak(snCol, vAstraWorld.xz + 31.7, 1.45, 0.07);',
+ ' snCol = astraHueBreak(snCol, vAstraWorld.xz, 0.22, 0.025);',
+ ' snCol = astraHueBreak(snCol, vAstraWorld.xz + 31.7, 1.45, 0.012);',
// A third of a code value of screen dither: a near-white ramp
// across a roof is the one place 8-bit banding is unmissable, and
// there is no post chain here to dither it for us.
@@ -255,6 +248,7 @@ export function patchSnow(material, opts = {}) {
// Thin snow is TRANSLUCENT — the substrate comes through it — so
// the drifts read as deep and the scoured lanes as shallow.
' float snThin = mix(0.38, 1.0, smoothstep(0.55, 1.30, snD));',
+ ' snThin = mix(snThin, 1.0, snCov * 0.88);',
' float snAmt = clamp(snK * snThin * mix(0.55, 1.0, snCov)',
' * smoothstep(0.0, 0.004, uSnowDepth), 0.0, 1.0);',
' diffuseColor.rgb = mix(diffuseColor.rgb, snCol, snAmt);',
@@ -311,8 +305,7 @@ export function patchSand(material, opts = {}) {
const amount = opts.amount === undefined ? 0.45 : unit(opts.amount);
const seed = opts.seed === undefined ? 1 : opts.seed;
// Sand is the mattest thing in any scene it lands in.
- composeRoughness(material, 'acc:sand',
- towardRoughness(material, 0.94, 0.70 * amount));
+
patchStandard(material, BASE);
return patchStandard(material, {
name: 'acc:sand',
@@ -330,6 +323,8 @@ export function patchSand(material, opts = {}) {
'uniform vec3 uSandUp;',
'uniform vec3 uSandSeed;',
].join('\n'),
+ roughnessBody: 'roughnessFactor = mix(roughnessFactor, 0.94, sdAmt);',
+ metalnessBody: 'metalnessFactor *= 1.0 - sdAmt;',
fragmentBody: [
' vec3 sdN = normalize(vAstraWorldN);',
' vec3 sdUp = normalize(uSandUp);',
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/aging.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/aging.js
index 9637648c..d775fd60 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/aging.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/aging.js
@@ -18,11 +18,9 @@
* `patchDripStains(m, { from })` is the one way to pin the source to an
* exact sill.
*
- * Gloss is per MATERIAL, not per pixel — all three write only at
- * `<color_fragment>`, before `<roughnessmap_fragment>`, and none uses
- * `patchStandard`'s `roughnessBody` — so each patch composes one
- * roughening factor through `composeRoughness`: dirt, rust and dust are
- * all matte.
+ * 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
@@ -36,7 +34,7 @@
*/
import {
- patchStandard, composeRoughness, glslAxes, glslCurv, matteFactor,
+ patchStandard, glslAxes, glslCurv,
seedVec3, toColor, unit, upVector, worldBase,
} from './shader.js';
@@ -56,6 +54,17 @@ const AGE_HEAD = [
// Positive curvature is convex (swept clean), negative the concave
// lee that holds.
glslCurv('astraAgeCurv'),
+ // Surface-gradient bump in view space. Existing normal/bump maps have
+ // already run when normalBody calls this, so their detail is retained.
+ 'vec3 astraAgeBump(vec3 eye, vec3 n, float height) {',
+ ' vec3 dx = dFdx(eye), dy = dFdy(eye);',
+ ' vec3 r1 = cross(dy, n), r2 = cross(n, dx);',
+ ' float determinant = dot(dx, r1);',
+ ' if (abs(determinant) < 1e-12) return n;',
+ ' vec3 gradient = sign(determinant)',
+ ' * (dFdx(height) * r1 + dFdy(height) * r2);',
+ ' return normalize(abs(determinant) * n - gradient);',
+ '}',
].join('\n');
// One base for all three, on the world varyings every library shares;
@@ -68,14 +77,6 @@ const BASE = worldBase('aging:base', 'agP', 'agN', AGE_HEAD);
const seedOffset = (seed, salt) =>
seedVec3(seed + salt, 0.29, 5.13, 9.47, 48);
-// Every effect here is matte, so each raises roughness through
-// `matteFactor`. The `add` each patch passes used to be token — a fully
-// rusted steel tank moved from 0.45 to 0.50 and went on mirroring the
-// sky, which washed the oxide off the frame at every distance. A crust
-// of oxide, dust or dried grime is one of the matte-est things there
-// is, so these now buy real roughness: the cap keeps a surface that
-// already starts rough from moving at all.
-
/**
* The vertical streaks that run down from every ledge, sill and joint.
*
@@ -129,8 +130,6 @@ export function patchDripStains(material, opts = {}) {
const seed = opts.seed === undefined ? 1 : opts.seed;
const from = opts.from;
const gated = Number.isFinite(from);
- composeRoughness(material, 'aging:drip',
- matteFactor(material, 0.22 * unit(strength)));
patchStandard(material, BASE);
return patchStandard(material, {
name: 'aging:drip',
@@ -215,7 +214,10 @@ export function patchDripStains(material, opts = {}) {
' 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;',
});
}
@@ -245,14 +247,9 @@ export function patchDripStains(material, opts = {}) {
* 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. And rust is a dielectric CRUST: per-pixel metalness is as
- * unreachable as per-pixel roughness from this hook, so on a shiny
- * `metalness: 1` tank the oxide tints the metal's own reflection and
- * comes out pink — give a rusting surface a low metalness yourself.
- * What this CAN do is take the whole material matte, and at full
- * strength it does (roughness x1.6, capped at fully rough): a corroded
- * tank that goes on mirroring the sky washes the oxide out of the frame
- * at every distance.
+ * 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.
@@ -268,8 +265,6 @@ 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;
- composeRoughness(material, 'aging:rust',
- matteFactor(material, 0.60 * unit(strength)));
patchStandard(material, BASE);
return patchStandard(material, {
name: 'aging:rust',
@@ -317,9 +312,21 @@ export function patchRust(material, opts = {}) {
' 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.30)',
+ ' 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
@@ -340,8 +347,12 @@ export function patchRust(material, opts = {}) {
' 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 = astraAgeBump(-vViewPosition, normal, rsAmt * (0.00035 + rsFlake * 0.0004 * rsFlakeFade + rsGrain * 0.00015 * rsGrainFade));',
});
}
@@ -386,8 +397,6 @@ 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);
- composeRoughness(material, 'aging:dust',
- matteFactor(material, 0.55 * unit(strength)));
patchStandard(material, BASE);
return patchStandard(material, {
name: 'aging:dust',
@@ -433,8 +442,10 @@ export function patchDust(material, opts = {}) {
' duCol = mix(duCol * vec3(0.92, 0.96, 1.10),',
' duCol * vec3(1.12, 0.94, 0.78),',
' smoothstep(0.22, 0.80, duB));',
- ' diffuseColor.rgb = mix(diffuseColor.rgb, duCol,',
- ' duK * uDustAmt);',
+ ' 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.js
index 8547f1b5..21c918ff 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/atmosphere.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/atmosphere.js
@@ -9,8 +9,9 @@
*/
import * as THREE from 'three';
+import { attachDisposal, snapshotResources } from './lifecycle.js';
import { mulberry32 } from './noise.js';
-import { makeShaderMaterial, patchStandard, tickShaders } from './shader.js';
+import { makeShaderMaterial, patchStandard, tickShaders, keepOutOfDepthPasses } from './shader.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
@@ -184,7 +185,7 @@ function readScene(scene) {
}
let best = null;
let fill = null;
- scene.traverse((o) => {
+ scene.traverseVisible((o) => {
if (o.isDirectionalLight) {
if (!best || o.intensity > best.intensity) best = o;
} else if (o.isHemisphereLight || o.isAmbientLight) {
@@ -196,7 +197,8 @@ function readScene(scene) {
// 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.position.clone();
+ 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();
@@ -463,20 +465,31 @@ export function makeHeightFog(opts = {}) {
});
const mesh = new THREE.Mesh(fogSheets(extent, top, heightAt), mat);
mesh.name = 'HeightFogBank';
- // Drawn with an OVERRIDE material — GTAOPass's depth+normal buffer —
- // a dozen sheets read as a dozen solid floors occluding each other:
- // 50/255 of darkening on ground the fog was not even touching.
- mesh.onBeforeRender = (r, s, cam, geo, m) => {
- geo.setDrawRange(0, m === mat ? Infinity : 0);
- };
- mesh.onAfterRender = (r, s, cam, geo) => {
- geo.setDrawRange(0, Infinity);
+ 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.tick = (t) => tickShaders(group, t);
- return group;
+ group.userData.update = group.userData.tick = (t) => tickShaders(group, t);
+ group.userData.refreshLighting = refreshLighting;
+ return attachDisposal(group, snapshotResources(group));
}
const AERIAL_VERT = [
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/building.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/building.js
index 21554d46..6c8e4b27 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/building.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/building.js
@@ -10,6 +10,19 @@
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. */
@@ -175,8 +188,7 @@ export function block(opts = {}) {
// lightness buckets, so a hundred blocks cost nine materials.
let wallMat = st.wall();
if (opts.color !== undefined) {
- wallMat = wallMat.clone();
- wallMat.userData = {};
+ wallMat = clonePatchedMaterial(wallMat);
wallMat.color = new THREE.Color(opts.color);
} else {
// Half of `tint`'s range: its full swing is +-25% lightness, which
@@ -299,7 +311,7 @@ export function block(opts = {}) {
[dark, darkMat, 'Reveals']], litBins);
root.userData.forward = '-Z';
root.userData.floors = floors + (baseH > 0 ? 1 : 0);
- return root;
+ return ownBuilding(root);
}
/**
@@ -418,7 +430,7 @@ export function casement(opts = {}) {
}
}
root.userData.forward = '-Z';
- return root;
+ return ownBuilding(root);
}
/**
@@ -484,7 +496,7 @@ function interiorCasement(opts) {
root.add(m);
}
root.userData.forward = '+Z';
- return root;
+ return ownBuilding(root);
}
/**
@@ -715,7 +727,7 @@ export function cottage(opts = {}) {
[glass, glassMat, 'Glazing']], litBins);
root.userData.forward = '-Z';
root.userData.ridgeY = h + pitch;
- return root;
+ return ownBuilding(root);
}
/**
@@ -761,7 +773,7 @@ export function tower(opts = {}) {
root.add(mast);
}
root.userData.forward = '-Z';
- return root;
+ return ownBuilding(root);
}
/**
@@ -823,7 +835,14 @@ export function roofClutter(host, opts = {}) {
}
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;
}
@@ -956,5 +975,6 @@ export function cityFabric(opts = {}) {
}
}
}
+ 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.js
index 9bc5519d..2d9c85f9 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/canopy.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/canopy.js
@@ -28,6 +28,7 @@
*/
import * as THREE from 'three';
+import { attachDisposal, snapshotResources } from './lifecycle.js';
import { fbm3, mulberry32 } from './noise.js';
import {
glslLocalDir, patchStandard, shadowLike, tickShaders, unit,
@@ -68,8 +69,8 @@ const LOCAL_DIR = glslLocalDir('leafLocalDir');
* `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, and a `sunDir` below the horizon fades it out for
- * you (the glow is added to the ALBEDO, so nothing else would).
+ * 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
@@ -107,8 +108,8 @@ export function makeCanopy(opts = {}) {
g.add(leafMesh(field, size, droop, hue, lit, under, wind,
opts.shadows === true,
opts.backlit === false ? null : (opts.backlit || {})));
- g.userData.tick = (t) => tickShaders(g, t);
- return g;
+ 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. */
@@ -131,16 +132,7 @@ function shadeOf(c) {
hsl.h + 0.045, Math.min(1, hsl.s * 1.15), hsl.l * 0.3);
}
-/**
- * How much SUN there is to come through a leaf, from the sun's own
- * direction. `patchLeafSSS` adds its transmission to the ALBEDO, before
- * any light is applied, so it does not go out when the sun does: on the
- * night pass of the showcase — sun at -20 deg, ground and sky correctly
- * dark — every crown stayed a bright yellow-green and read as daylight
- * foliage pasted onto a night frame. The ramp holds FULL strength for
- * any sun at or above the horizon, because a low sun is exactly when a
- * backlit crown glows most, and closes over the five degrees below it.
- */
+/** 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);
@@ -208,13 +200,16 @@ function leafField(crowns, opts, shell, size, seed) {
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;
@@ -235,9 +230,19 @@ function leafField(crowns, opts, shell, size, seed) {
// 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 });
- const px = c.x + dx * c.rx * t * lump;
- const py = c.y + dy * c.ry * t * lump;
- const pz = c.z + dz * c.rz * t * lump;
+ 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
@@ -263,7 +268,7 @@ function leafField(crowns, opts, shell, size, seed) {
box.expandByPoint(new THREE.Vector3(px, py, pz));
}
}
- return { n, pos, axis, vary, box };
+ return { n, pos, axis, vary, sprays, box };
}
/** The one instanced mesh every crown shares. */
@@ -272,7 +277,7 @@ function leafMesh(field, size, droop, hue, lit, under, wind, shadows,
// 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, 1, 3);
+ const base = new THREE.PlaneGeometry(1, 1, 2, 6);
const geom = new THREE.InstancedBufferGeometry();
geom.index = base.index;
geom.setAttribute('position', new THREE.BufferAttribute(
@@ -286,9 +291,10 @@ function leafMesh(field, size, droop, hue, lit, under, wind, shadows,
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);
+ 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());
@@ -299,7 +305,7 @@ function leafMesh(field, size, droop, hue, lit, under, wind, shadows,
// grazing angles without chalking the top of the tree.
const mat = new THREE.MeshStandardMaterial({
color: 0xffffff, roughness: 0.78, metalness: 0,
- side: THREE.FrontSide, name: 'CanopyLeaf',
+ side: THREE.DoubleSide, name: 'CanopyLeaf',
});
patchStandard(mat, {
name: 'canopy:leaf',
@@ -328,11 +334,6 @@ function leafMesh(field, size, droop, hue, lit, under, wind, shadows,
// the underside leaves take no sun and no bounce, and only light
// coming THROUGH them says foliage rather than soot.
if (backlit) {
- // 0.62 was too much on OUR pipeline: the transmission lands on the
- // ALBEDO (it is added before lighting), so at 0.62 the sun-side
- // leaves ran past 1.0 albedo and tone-mapped to pale mint. 0.44
- // keeps the whole crown inside the 0.02-0.8 albedo band and leaves
- // the glow to read as glow rather than as a wash.
const amt = backlit.strength === undefined ? 0.44 : backlit.strength;
patchLeafSSS(mat, { sunDir: backlit.sunDir, tint: backlit.tint,
strength: amt * sunUp(backlit.sunDir) });
@@ -362,6 +363,7 @@ const LEAF_HEAD = [
'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
@@ -372,7 +374,7 @@ const LEAF_HEAD = [
].join('\n');
const LEAF_VERTEX = [
- ' vec3 lfN = normalize(iAxis);',
+ ' 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)',
@@ -391,17 +393,18 @@ const LEAF_VERTEX = [
' 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));',
' float lfG = astraFbm2(vec2(',
- ' dot(iPos.xz, lfW) * 0.05 - uTime * uLeafSpeed * 0.5,',
- ' dot(iPos.xz, vec2(-lfW.y, lfW.x)) * 0.2), 2);',
+ ' dot(iSpray.xz, lfW) * 0.05 - uTime * uLeafSpeed * 0.5,',
+ ' dot(iSpray.xz, vec2(-lfW.y, lfW.x)) * 0.2), 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 + iVar.z));',
+ ' * (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.
@@ -418,21 +421,17 @@ const LEAF_VERTEX = [
' 78.233))) * 43758.5453);',
' vLeafB = vec2(lfJit, lfN.y * 0.5 + 0.5);',
'#ifndef FLAT_SHADED',
- // Outward from the crown, not the card's own facing: this is what
- // makes a crown light like a volume instead of a heap of flat chips.
- // Leaves turn toward the light, and a canopy's light is the SKY, so
- // the outward normal is bent upward — but only PART of the way. At
- // the old fixed +1.15 every normal in the crown fell within ~40 deg
- // of straight up, so with a 38 deg sun every leaf took the same
- // near-full diffuse and the mass lost its form: measured, the two
- // crowns rendered as flat pale discs with no lit side. The bend is
- // now weak on the shell, where the outward normal IS the crown's
- // shape, and strong in the interior, where nothing but sky reaches
- // and a leaf lit only by its own facing goes to soot.
- ' float lfSky = 0.34 + 0.44 * (1.0 - iVar.w);',
- ' vNormal = normalize(normalMatrix',
- ' * normalize(lfN + vec3(0.0, lfSky, 0.0)',
- ' + lfE1 * (lfFl * 0.5)));',
+ // 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');
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/celestial.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/celestial.js
index 2d80c83d..05a08ff7 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/celestial.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/celestial.js
@@ -35,6 +35,7 @@
*/
import * as THREE from 'three';
+import { attachDisposal, snapshotResources } from './lifecycle.js';
import { lehmer } from './noise.js';
import {
@@ -71,9 +72,21 @@ const _SIZE = new THREE.Vector2();
function frameGrabber(mat) {
let tex = null;
let fbo = null;
+ let context = null;
+ let disposed = false;
let warned = false;
- return (renderer) => {
+ 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;
@@ -83,9 +96,10 @@ function frameGrabber(mat) {
}
return;
}
- renderer.getDrawingBufferSize(_SIZE);
- const w = _SIZE.x, h = _SIZE.y;
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) {
@@ -103,14 +117,16 @@ function frameGrabber(mat) {
if (!handle) return;
if (!fbo) fbo = gl.createFramebuffer();
const prev = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING);
- 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);
- // Restored to exactly what was bound, so three's own state
- // cache is still telling the truth afterwards.
- gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, prev);
+ 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
@@ -119,6 +135,13 @@ function frameGrabber(mat) {
(!rt && renderer.outputColorSpace === THREE.SRGBColorSpace)
? 1 : 0;
};
+ grab.dispose = () => {
+ if (disposed) return;
+ disposed = true;
+ release();
+ context = null;
+ };
+ return grab;
}
/**
@@ -190,11 +213,13 @@ export function makeHeatShimmer(opts = {}) {
const guard = mesh.onBeforeRender;
const grab = frameGrabber(mat);
mesh.onBeforeRender = (r, s, cam, geo, m) => {
- guard(r, s, cam, geo, m);
+ guard.call(mesh, r, s, cam, geo, m);
if (m === mat) grab(r);
};
- g.userData.tick = (t) => tickShaders(g, t);
- return g;
+ 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. */
@@ -354,8 +379,8 @@ export function makeStars(opts = {}) {
if (opts.milkyWay !== false) g.add(milkyWayMesh(radius, pole, bright));
g.add(starMesh(count, radius, gain, twinkle, rnd, pole, bright,
opts.milkyWay !== false));
- g.userData.tick = (t) => tickShaders(g, t);
- return keepOutOfDepthPasses(g);
+ g.userData.update = g.userData.tick = (t) => tickShaders(g, t);
+ return attachDisposal(keepOutOfDepthPasses(g), snapshotResources(g));
}
/**
@@ -638,13 +663,13 @@ export function makeAurora(opts = {}) {
const g = new THREE.Group();
g.name = 'Aurora';
g.add(mesh);
- g.userData.tick = (t) => tickShaders(g, t);
- return keepOutOfDepthPasses(g);
+ 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 = 72, nv = 20;
+ 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
@@ -752,8 +777,8 @@ function auroraMaterial(color, activity, swing, bright) {
' 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 = normalize(mat3(modelMatrix)',
- ' * normalize(nrm - tg * slope));',
+ ' vN = astraNormalTransform(mat3(modelMatrix),',
+ ' normalize(nrm - tg * slope));',
' vW = (modelMatrix * vec4(transformed, 1.0)).xyz;',
].join('\n'),
fragmentHead: 'uniform vec3 uColor; uniform vec3 uRim;'
@@ -763,19 +788,38 @@ function auroraMaterial(color, activity, swing, bright) {
fragmentMain: [
' float v = vUv.y;',
' float x = vUv.x * uRays + vTag * 23.0 + uTime * uDrift;',
- // Rays are strokes, not a sine: astraStroke antialiases by
- // its own gradient and dissolves once a filament is finer
- // than a pixel, which is what stops the shimmer crawling.
- // The floor is 0.10, not 0.30: at 0.30 the gaps between
- // filaments never went dark and the foot of the curtain
- // rendered as one solid wall of light.
- // Each filament its own width, or the curtain is a printed
- // barcode: real rays run from a hairline to a hand's
- // breadth inside one display.
- ' float w = 0.085 + 0.115 * astraHash11(floor(x) * 0.37 + 2.0);',
- ' float ray = 0.10 + 1.05 * astraStroke(x, w);',
- ' ray *= 0.45 + 0.85 * astraNoise2(vec2(floor(x) * 0.71,',
- ' uTime * 0.06 + vTag * 5.0));',
+ // 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
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloth.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloth.js
index b56c4a21..b7e66233 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloth.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloth.js
@@ -41,6 +41,7 @@
*/
import * as THREE from 'three';
+import { attachDisposal, snapshotResources } from './lifecycle.js';
import { windOf } from './grass.js';
import { mulberry32 } from './noise.js';
@@ -53,7 +54,7 @@ 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 = 7;
+const _STALK_ROWS = 11;
const _STEM_ROWS = 4;
const _EAR_AT = 0.8;
// Tileable modes of the gust field. Integer frequencies only: the
@@ -132,8 +133,8 @@ export function makeFlag(opts = {}) {
fly.rotation.y = yawToX(wind.dir);
fly.add(flagSheet(width, height, rad, color, wind, rand));
g.add(fly);
- g.userData.tick = (t) => tickShaders(g, t);
- return g;
+ 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. */
@@ -192,8 +193,9 @@ function flagSheet(width, height, rad, color, wind, rand) {
// 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.MeshStandardMaterial({
+ 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 = [
@@ -393,8 +395,8 @@ export function makeBanner(opts = {}) {
swing.add(bannerCloth(width, drop, folds, color, wind, rand));
if (opts.rod !== false) swing.add(bannerRod(width, drop));
g.add(swing);
- g.userData.tick = (t) => tickShaders(g, t);
- return g;
+ 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. */
@@ -446,8 +448,9 @@ function bannerCloth(width, drop, folds, color, wind, rand) {
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.MeshStandardMaterial({
+ 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, {
@@ -680,8 +683,10 @@ export function makeWheatField(opts = {}) {
extent, density, rowGap, maxStalks, height, ground, seed);
g.add(stalkMesh(field, extent, straw, ear, wind, waveMps, seed,
opts.shadows === true));
- g.userData.tick = (t) => tickShaders(g, t);
- return g;
+ 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);
}
/**
@@ -788,27 +793,24 @@ function gustTexture(seed, size = 128) {
* the world origin and burn a black slab there.
*/
function stalkLattice(count) {
- const base = new THREE.PlaneGeometry(1, 1, 1, _STALK_ROWS);
- base.translate(0, 0.5, 0);
- // Spend the rows where the curvature is: an evenly spaced strip
- // draws the nodding ear with one segment and it reads as an elbow.
- const p = base.attributes.position;
- for (let i = 0; i < p.count; i++) {
- const a = p.getY(i) * _STALK_ROWS;
- p.setY(i, a <= _STEM_ROWS
- ? _EAR_AT * a / _STEM_ROWS
- : _EAR_AT + (1 - _EAR_AT) * (a - _STEM_ROWS)
- / (_STALK_ROWS - _STEM_ROWS));
+ 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.index = base.index;
- g.setAttribute('position', new THREE.BufferAttribute(
- new Float32Array(base.attributes.position.count * 3), 3));
- g.setAttribute('aCorner', base.attributes.position);
- g.setAttribute('normal', base.attributes.normal);
- g.setAttribute('uv', base.attributes.uv);
- g.instanceCount = count;
- return g;
+ 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. */
@@ -911,6 +913,7 @@ const STALK_HEAD = [
'uniform float uWheatPatch;',
'uniform float uWheatRipen;',
'attribute vec3 aCorner;',
+ 'attribute float aPart;',
'attribute vec3 iPos;',
'attribute vec4 iCrop;',
'attribute vec3 iVar;',
@@ -921,7 +924,7 @@ const STALK_HEAD = [
const STALK_VERTEX = [
' vec3 whRoot = iPos;',
- ' float whV = aCorner.y;',
+ ' 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
@@ -976,11 +979,24 @@ const STALK_VERTEX = [
' 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');
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/clouds.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/clouds.js
index 15aef37c..9e38b3d1 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/clouds.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/clouds.js
@@ -2,6 +2,7 @@
// base, sun-tinted) + optional thin cirrus streaks. three r184's Sky
// cloud branch grid-artifacts at any high contrast — this is the layer.
import * as THREE from 'three';
+import { attachDisposal, snapshotResources } from './lifecycle.js';
import { mulberry32, fbm2 } from './noise.js';
import { makeShaderMaterial, keepOutOfDepthPasses } from './shader.js';
@@ -52,30 +53,68 @@ function lightVector(v) {
Math.cos(moonEl) * Math.sin(az));
}
-/** Soft irregular puff alpha texture: radial falloff x fbm, flat base. */
+/** Seeded billowy puff: RGB stores a shading normal, alpha optical coverage.
+ * The base is flat. This is a distant impostor, not a participating volume.
+ */
export function cloudTexture(seed = 7, size = 256) {
- const data = new Uint8Array(size * size * 4);
- for (let y = 0; y < size; y++) {
- for (let x = 0; x < size; x++) {
- const nx = x / size - 0.5, ny = y / size - 0.5;
- const r = Math.sqrt(nx * nx * 1.05 + ny * ny * 2.2) * 2;
- // Two bands: the low one carves the cauliflower lobes, the high
- // one frays the silhouette. One octave set alone gives the soft
- // airbrushed blob the old texture had.
- const n = fbm2(x / 46, y / 46, { seed, octaves: 3 }) * 0.5 + 0.5;
- const f = fbm2(x / 13, y / 13, { seed: seed + 5, octaves: 2 }) * 0.5 + 0.5;
- let a = Math.max(0, 1 - r) * (0.45 + 0.85 * n) - 0.18;
- a = Math.max(0, Math.min(1, a * 1.9));
- a = a * a * (3 - 2 * a);
- // Erosion, strongest where the body is already thin: keeps the
- // core solid and turns the rim into wisps.
- a *= 1 - 0.55 * (1 - a) * (1 - f);
- a *= Math.min(1, Math.max(0, (ny + 0.34) / 0.10));
- const k = (y * size + x) * 4;
- data[k] = data[k + 1] = data[k + 2] = 255;
- data[k + 3] = Math.round(a * 255);
+ const texture = puffTexture(seed, size, false);
+ // Public alpha texture remains white for callers using it as a color map.
+ const data = texture.image.data;
+ for (let i = 0; i < data.length; i += 4) data[i] = data[i + 1] = data[i + 2] = 255;
+ return texture;
+}
+
+function puffTexture(seed, size, cirrus) {
+ if (!Number.isSafeInteger(seed) || !Number.isInteger(size) || size < 16 || size > 1024) {
+ throw new RangeError('cloudTexture: use an integer seed and size in 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;
+ if (cirrus) {
+ // Wind-sheared ice filaments with curved, tapered ends. Unlike stretching
+ // a round cumulus stamp, these never make parallel cylindrical ribbons.
+ const taper = Math.pow(Math.max(0, 1 - Math.pow(u / .48, 2)), 1.8);
+ const bend = .20 * Math.sin((u + .35) * 3.8) - .06;
+ let threads = 0;
+ for (let k = 0; k < 7; k++) {
+ const center = bend + (k - 3) * .045 + .035 * Math.sin(u * 9 + k * 1.7);
+ const width = .011 + .024 * taper;
+ threads += Math.exp(-Math.pow((v - center) / width, 2)) * (.07 + .07 * Math.sin(k * 2.13 + 1));
+ }
+ field[y * size + x] = threads * taper * border * (.72 + .28 * broad);
}
}
+ 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 at = (dx,dy) => field[Math.max(0,Math.min(size-1,y+dy))*size + Math.max(0,Math.min(size-1,x+dx))];
+ const nx = -(at(1,0)-at(-1,0)) * size * .045;
+ const ny = -(at(0,1)-at(0,-1)) * size * .045;
+ const len = Math.hypot(nx,ny,1),k=(y*size+x)*4;
+ data[k] = (nx/len*.5+.5)*255;
+ data[k+1] = (ny/len*.5+.5)*255;
+ data[k+2] = (1/len*.5+.5)*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;
@@ -83,6 +122,23 @@ export function cloudTexture(seed = 7, size = 256) {
return tex;
}
+function cloudAtlas(seed, cirrus = false) {
+ const tile = 128, cols = 4, rows = 2;
+ const data = new Uint8Array(tile * tile * cols * rows * 4);
+ for (let i=0;i<cols*rows;i++) {
+ const puff = puffTexture(seed + i*977, tile, cirrus);
+ for (let y=0;y<tile;y++) {
+ const start=((Math.floor(i/cols)*tile+y)*tile*cols+(i%cols)*tile)*4;
+ data.set(puff.image.data.subarray(y*tile*4,(y+1)*tile*4),start);
+ }
+ puff.dispose();
+ }
+ const tex = new THREE.DataTexture(data,tile*cols,tile*rows);
+ tex.minFilter=tex.magFilter=THREE.LinearFilter;
+ tex.needsUpdate=true;
+ return tex;
+}
+
/**
* Cumulus layer as ONE instanced billboard mesh (one draw call).
* opts: seed, preset ('day'|'golden'|'overcast'|'night'), count, area,
@@ -103,6 +159,11 @@ export function makeClouds(opts = {}) {
const alpha = opts.alpha ?? p.alpha ?? 0.92;
const wind = opts.wind ?? 3.0;
const stretch = opts.stretch ?? p.stretch ?? 1.0;
+ if (!Number.isSafeInteger(seed) || !Number.isInteger(count) || count < 0 || count > 1000 ||
+ ![area, altitude, spread, alpha, wind, stretch].every(Number.isFinite) ||
+ area <= 0 || spread < 0 || alpha < 0 || alpha > 1 || stretch <= 0) {
+ throw new RangeError('makeClouds: invalid seed, count, area, altitude, spread, alpha, wind or stretch');
+ }
const rand = mulberry32(seed);
const rnd2 = mulberry32(seed + 977);
const puffs = [];
@@ -202,8 +263,13 @@ export function makeClouds(opts = {}) {
// the shader keeps the scene's fog COLOUR and density without
// taking three's fog blend.
...THREE.UniformsUtils.clone(THREE.UniformsLib.fog),
- map: { value: cloudTexture(seed + 101) },
+ map: { value: cloudAtlas(seed + 101, opts._cirrus === true) },
+ uCirrus: { value: opts._cirrus ? 1 : 0 },
uWind: { value: wind },
+ uCameraRight: { value: new THREE.Vector3(1, 0, 0) },
+ uCameraUp: { value: new THREE.Vector3(0, 1, 0) },
+ uCameraForward: { value: new THREE.Vector3(0, 0, 1) },
+ uSunLocal: { value: sunDir.clone() },
uAlpha: { value: alpha },
uLitGain: { value: opts.litGain ?? p.litGain },
uSunDir: { value: sunDir },
@@ -225,7 +291,9 @@ export function makeClouds(opts = {}) {
vertexHead: [
'attribute vec3 aCorner;',
'attribute vec3 iOff; attribute vec2 iScale; attribute vec3 iExtra;',
- 'uniform float uWind; uniform vec3 uSunDir;',
+ 'uniform float uWind; uniform vec3 uSunDir; uniform float uCirrus;',
+ 'uniform vec3 uCameraRight; uniform vec3 uCameraUp;',
+ 'uniform vec3 uCameraForward; uniform vec3 uSunLocal;',
].join('\n'),
vertexMain: [
' vExtra = iExtra;',
@@ -235,17 +303,17 @@ export function makeClouds(opts = {}) {
// cannot lift a cloud off its own flat bottom.
' float flip = step(0.5, fract(iExtra.y * 0.1591));',
' vUv = vec2(mix(uv.x, 1.0 - uv.x, flip), uv.y);',
- ' vec3 right = vec3(viewMatrix[0][0], viewMatrix[1][0],',
- ' viewMatrix[2][0]);',
- ' vec3 up = vec3(viewMatrix[0][1], viewMatrix[1][1],',
- ' viewMatrix[2][1]);',
+ ' vec3 right = uCameraRight;',
+ ' vec3 up = uCameraUp;',
' vec3 p = iOff + vec3(uTime * uWind',
' + sin(iExtra.y + uTime * 0.05) * 6.0, 0.0, 0.0);',
- ' transformed = p + right * aCorner.x * iScale.x',
- ' + up * aCorner.y * iScale.y;',
+ ' float lean = uCirrus * sin(iExtra.y * 4.1) * .14;',
+ ' vec2 corner = mat2(cos(lean),sin(lean),-sin(lean),cos(lean))',
+ ' * (aCorner.xy * iScale);',
+ ' transformed = p + right * corner.x + up * corner.y;',
// The sun in the billboard's own 2D frame: the lit side then
// follows the rig instead of always being the top edge.
- ' vec2 sp = vec2(dot(uSunDir, right), dot(uSunDir, up));',
+ ' vec2 sp = vec2(dot(uSunLocal, right), dot(uSunLocal, up));',
' vSun = length(sp) > 1e-3 ? normalize(sp) : vec2(0.0, 1.0);',
// the lit side is a world direction: mirror it with the uv or the
// light lands on the wrong half of every flipped puff
@@ -255,9 +323,7 @@ export function makeClouds(opts = {}) {
// same cloud with the sun over the shoulder is a white one. One
// dot product decides which, and it is the difference between a
// sky that looks photographed and one that looks painted.
- ' vec3 fwd = vec3(viewMatrix[0][2], viewMatrix[1][2],',
- ' viewMatrix[2][2]);',
- ' vSunZ = dot(uSunDir, fwd);',
+ ' vSunZ = dot(uSunLocal, uCameraForward);',
' vDepth = -(modelViewMatrix * vec4(transformed, 1.0)).z;',
].join('\n'),
fragmentHead: [
@@ -268,37 +334,28 @@ export function makeClouds(opts = {}) {
'uniform float fogDensity; uniform float fogNear; uniform float fogFar;',
].join('\n'),
fragmentMain: [
- ' float a = texture2D(map, vUv).a;',
+ ' float cell = floor(fract(vExtra.y * .7919) * 8.0);',
+ ' vec2 atlasUv = (clamp(vUv,vec2(.004),vec2(.996)) + vec2(mod(cell,4.0),floor(cell/4.0))) / vec2(4,2);',
+ ' vec4 puff = texture2D(map, atlasUv);',
+ ' float a = puff.a;',
' if (a < 0.004) discard;',
// Two lighting terms: the sun's own direction across the puff,
// and a vertical term for the flat shaded base every cumulus has.
- ' float face = dot(vUv - 0.5, vSun) * 2.0;',
- ' float vert = smoothstep(-0.10, 0.62, vUv.y);',
- ' float front = smoothstep(-0.25, 0.65, vSunZ);',
- // one gradient for the whole cluster: the puff\'s own top plus
- // where the puff sits in the mass (iExtra.z)
- ' float upness = clamp(0.45 * vert + 0.62 * vExtra.z, 0.0, 1.0);',
- ' float lit = clamp(0.34 * upness',
- ' + 0.78 * smoothstep(-0.75, 0.55, face), 0.0, 1.0);',
- ' lit *= vExtra.x * mix(0.22, 1.0, front);',
+ ' vec3 normal = normalize(puff.rgb * 2.0 - 1.0);',
+ ' vec3 light = normalize(vec3(vSun * sqrt(max(0.0,1.0-vSunZ*vSunZ)),vSunZ));',
+ ' float incidence = max(dot(normal,light),0.0);',
+ ' float front = smoothstep(-.4,.6,vSunZ);',
+ ' float crown = mix(.68,1.0,vExtra.z);',
+ ' float thickness = -log(max(1.0-a,.02));',
+ ' float skyLit = smoothstep(-.45,.65,normal.y + .30*vExtra.z);',
+ ' float direct = (.20 + .40*incidence + .36*skyLit) * crown * vExtra.x;',
' vec3 sunLit = uSunColor * uLitGain;',
- // The shaded side is sky-lit, so it carries the scene's own haze
- // colour — no hardcoded ambient, and never a black underside.
- // Backlit, the body we see is the shadowed one: darker, bluer.
- ' vec3 ambient = mix(uShade, fogColor, 0.22) * mix(0.52, 1.0, front)',
- ' * mix(0.78, 1.10, vExtra.z);',
- ' vec3 col = mix(ambient, sunLit, lit);',
- // Silver lining: a thin edge transmits instead of reflecting — the
- // one read that says "cloud" and not "sprite". Front-lit it is the
- // sun-facing edge only; backlit the whole silhouette burns.
- // A BAND just inside the silhouette, not everything below an alpha
- // threshold: a rim that runs all the way out into the wisps turns
- // every puff into a lit soap bubble (seen on the night render).
- ' float thin = smoothstep(0.03, 0.26, a)',
- ' * (1.0 - smoothstep(0.24, 0.66, a));',
- ' float rim = thin * mix(0.40 + 0.60 * smoothstep(-0.4, 0.9, face),',
- ' smoothstep(0.0, 0.85, face), front);',
- ' col += sunLit * uRim * rim * mix(2.1, 1.0, front);',
+ ' vec3 ambient = mix(uShade,fogColor,.20) * mix(.92,1.18,vExtra.z);',
+ ' vec3 col = ambient * (.65 + .35*front) + sunLit * direct;',
+ // A silver lining needs backlighting AND an optically thin path. The old
+ // alpha-band highlight outlined every puff, producing gray soap bubbles.
+ ' float silver = pow(max(-vSunZ,0.0),3.0) * thickness * exp(-thickness*1.8);',
+ ' col += sunLit * (uRim * silver * 1.7);',
// Hue variance: warm where the sun reaches, cool where it does
// not, decorrelated per puff by its phase. A cloud deck of one
// flat white is the giveaway of a painted sky.
@@ -328,8 +385,21 @@ export function makeClouds(opts = {}) {
const mesh = new THREE.Mesh(inst, mat);
mesh.name = opts.name || 'CumulusLayer';
mesh.frustumCulled = false;
- mesh.userData.update = (t) => { mat.uniforms.uTime.value = t; };
- return keepOutOfDepthPasses(mesh);
+ const inverse = new THREE.Matrix4();
+ mesh.onBeforeRender = (_renderer, _scene, camera) => {
+ inverse.copy(mesh.matrixWorld).invert();
+ mat.uniforms.uCameraRight.value.setFromMatrixColumn(camera.matrixWorld, 0).transformDirection(inverse);
+ mat.uniforms.uCameraUp.value.setFromMatrixColumn(camera.matrixWorld, 1).transformDirection(inverse);
+ mat.uniforms.uCameraForward.value.setFromMatrixColumn(camera.matrixWorld, 2).transformDirection(inverse);
+ mat.uniforms.uSunLocal.value.copy(mat.uniforms.uSunDir.value).transformDirection(inverse);
+ };
+ mesh.userData.update = (t) => {
+ if (!Number.isFinite(t)) throw new RangeError('CloudLayer.update: time must be finite');
+ mat.uniforms.uTime.value = t;
+ };
+ const owned = snapshotResources(mesh);
+ owned.add(mat.uniforms.map.value);
+ return attachDisposal(keepOutOfDepthPasses(mesh), owned);
}
/**
@@ -354,13 +424,14 @@ export function makeCirrus(opts = {}) {
return makeClouds({
// Its own name: two layers called CumulusLayer collide in the
// census and in the viewer's find-by-name.
- name: 'CirrusLayer',
+ name: opts.name ?? 'CirrusLayer',
+ _cirrus: true,
seed,
count: opts.count ?? 8,
area: opts.area ?? 3200,
altitude: opts.altitude ?? 520,
spread: 120,
- alpha: opts.alpha ?? 0.30,
+ alpha: opts.alpha ?? 0.44,
wind: opts.wind ?? 6.0,
litGain: (opts.litGain ?? p.litGain) * 0.85,
sunColor: opts.sunColor ?? ice.getHex(),
@@ -368,6 +439,6 @@ export function makeCirrus(opts = {}) {
sunDir: opts.sunDir,
rim: opts.rim ?? 0.85,
hueVariance: opts.hueVariance ?? 0.08,
- stretch: opts.stretch ?? 7.0,
+ stretch: opts.stretch ?? 4.5,
});
}
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloudvolume.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloudvolume.js
new file mode 100644
index 00000000..d26bb166
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloudvolume.js
@@ -0,0 +1,368 @@
+/**
+ * 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 } from './shader.js';
+import { attachDisposal, snapshotResources } from './lifecycle.js';
+import { 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 vector(value, fallback, length, label) {
+ const values = value?.toArray ? value.toArray() : value ?? fallback;
+ if (!Array.isArray(values) || values.length !== length || !values.every(Number.isFinite)) {
+ throw new RangeError(`makeCloudVolume: ${label} must contain ${length} finite numbers`);
+ }
+ return values;
+}
+
+function densityTexture(seed) {
+ const random = mulberry32(seed);
+ const grids = [4, 8, 16, 32].map((n) => ({
+ n, data: Float32Array.from({ length: n ** 3 }, () => random()),
+ }));
+ // 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;
+ let noise = 0, amplitude = .5333333;
+ for (const grid of grids) {
+ const gx = u * grid.n, gy = v * grid.n, gz = w * grid.n;
+ // Hermite interpolation before each lattice lookup reduces grid creases.
+ const ease = (q) => Math.floor(q) + smooth(0, 1, q - Math.floor(q));
+ noise += amplitude * sampleGrid3(grid.data, grid.n, ease(gx), ease(gy), ease(gz));
+ amplitude *= .5;
+ }
+ 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(grids[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) {
+ vec3 safe = sign(direction) * max(abs(direction), vec3(1e-6));
+ safe += vec3(equal(direction, vec3(0.0))) * 1e-6;
+ vec3 a = (-uSize * .5 - origin) / safe;
+ vec3 b = (uSize * .5 - origin) / safe;
+ vec3 near = min(a, b), far = max(a, b);
+ return vec2(max(max(near.x, near.y), near.z), min(min(far.x, far.y), far.z));
+}
+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: integer,
+ * 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.
+ * sunDirection: WORLD direction toward the sun, 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, 'size');
+ const wind = vector(opts.wind, [2.5, .4], 2, 'wind');
+ const direction = vector(opts.sunDirection, [-.5, .7, -.3], 3, 'sunDirection');
+ const seed = opts.seed ?? 19;
+ const coverage = opts.coverage ?? .55;
+ const extinction = opts.density ?? .028;
+ const detail = opts.detail ?? .65;
+ const intensity = opts.sunIntensity ?? 1.25;
+ const quality = opts.quality ?? 'balanced';
+ if (!Number.isSafeInteger(seed) || size.some((v) => v <= 0 || v > 100000) ||
+ ![coverage, extinction, intensity, detail].every(Number.isFinite) || coverage < 0 || coverage > 1 ||
+ extinction < 0 || extinction > 10 || intensity < 0 || detail < 0 || detail > 1 || !Object.hasOwn(TIERS, quality) || Math.hypot(...direction) < 1e-9) {
+ throw new RangeError('makeCloudVolume: invalid dimensions, seed, coverage, density, sun intensity or quality');
+ }
+ const tier = TIERS[quality];
+ const texture = densityTexture(seed);
+ let sunPinned = opts.sunDirection !== undefined;
+ const sun = new THREE.Vector3(...direction).normalize();
+ const sunTint = new THREE.Color(opts.sunColor ?? 0xfff3dc);
+ const skyTint = new THREE.Color(opts.skyColor ?? 0x9eb9da);
+ const lightPosition = new THREE.Vector3(), lightTarget = new THREE.Vector3();
+ const skyLight = new THREE.Color(0, 0, 0);
+ const keyColor = new THREE.Color(0, 0, 0);
+ 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
+ vec4 densityClip = uLocalToClip * vec4(firstDensity, 1.0);
+ gl_FragDepth = clamp(densityClip.z / densityClip.w * .5 + .5, 0.0, 1.0);
+ #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];
+ let key = null;
+ skyLight.setRGB(0, 0, 0);
+ scene.traverseVisible((light) => {
+ if (!light.isLight || !(light.intensity > 0)) return;
+ if (light.isDirectionalLight && (!key || light.intensity > key.intensity)) key = light;
+ if (light.isAmbientLight) skyLight.add(light.color.clone().multiplyScalar(light.intensity));
+ if (light.isHemisphereLight) {
+ skyLight.add(light.color.clone().multiplyScalar(light.intensity * .75));
+ skyLight.add(light.groundColor.clone().multiplyScalar(light.intensity * .25));
+ }
+ });
+ keyColor.setRGB(0, 0, 0);
+ if (key) {
+ keyColor.copy(key.color).multiply(sunTint).multiplyScalar(key.intensity / 5.4 * intensity);
+ if (!sunPinned) {
+ key.getWorldPosition(lightPosition);key.target.getWorldPosition(lightTarget);
+ sun.copy(lightPosition).sub(lightTarget).normalize();
+ }
+ }
+ // The scene environment is an independent source of diffuse sky light;
+ // removing a directional light does not remove that authored environment.
+ if (scene.environment) {
+ const environmentLight = .35 * (scene.environmentIntensity ?? 1);
+ skyLight.r += environmentLight;skyLight.g += environmentLight;skyLight.b += environmentLight;
+ }
+ material.uniforms.uSunColor.value.copy(keyColor);
+ material.uniforms.uSkyColor.value.copy(skyTint).multiply(skyLight);
+ 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, 'sunDirection');
+ 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.js
index ccba9d5c..ca206bb0 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/damp.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/damp.js
@@ -22,20 +22,35 @@
* (measured: a splat over a triplanar did exactly that). Every one here
* multiplies or mixes with what it is handed.
*
- * Gloss is per MATERIAL, not per pixel — all three write only at
- * `<color_fragment>`, before `<roughnessmap_fragment>`, and none uses
- * `patchStandard`'s `roughnessBody` — so each composes ONE factor through
- * `composeRoughness`, and they pull BOTH ways: moss and dried mud are
- * matte, damp ground and a water-filled crack are glossy.
+ * 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, composeRoughness, baseRoughness, frac, glslAxes, glslCurv,
- glslTriNoise, seedVec3, toColor, towardRoughness, unit, upVector,
+ patchStandard, frac, glslAxes, glslCurv,
+ glslTriNoise, seedVec3, toColor, unit, upVector,
worldBase,
} from './shader.js';
+/** Perturb the lit view normal from a local coating height in world metres. */
+function coatingNormal(prefix, height) {
+ return [
+ `vec3 ${prefix}Dx = dFdx(-vViewPosition);`,
+ `vec3 ${prefix}Dy = dFdy(-vViewPosition);`,
+ `vec3 ${prefix}R1 = cross(${prefix}Dy, normal);`,
+ `vec3 ${prefix}R2 = cross(normal, ${prefix}Dx);`,
+ `float ${prefix}Det = dot(${prefix}Dx, ${prefix}R1);`,
+ `float ${prefix}Height = ${height};`,
+ `vec3 ${prefix}Gradient = sign(${prefix}Det) *`,
+ ` (dFdx(${prefix}Height) * ${prefix}R1`,
+ ` + dFdy(${prefix}Height) * ${prefix}R2);`,
+ `if (abs(${prefix}Det) > 1e-12)`,
+ ` normal = normalize(abs(${prefix}Det) * normal - ${prefix}Gradient);`,
+ ].join('\n');
+}
+
// 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.
@@ -112,28 +127,7 @@ function northVector(value, up) {
return v.normalize();
}
-/**
- * A wet target that is glossier than the surface it lands on — never a
- * mirror, and never rougher than what it landed on.
- *
- * A FIXED target is wrong in both directions, and roughness here is per
- * MATERIAL, so whatever it does it does to the whole surface. The
- * reference's 0.34 is a water FILM: on our renderer (a baked sky
- * environment, ACES at exposure 1.0, no post chain) it turned a
- * 0.95-rough bank into a sky mirror and lifted the ground from
- * luminance 0.607 to 0.823 — BRIGHTER, when the whole point of the
- * apron is that it is darker. Raising the fixed number instead just
- * moves the error: 0.62 on a 0.5-rough stone would ROUGHEN it when wet.
- *
- * So the target is a RATIO of what the material already is, floored so
- * a rough ground cannot be polished past wet soil, and clamped to the
- * base so a surface already smoother than the floor is left alone.
- */
-function wetTarget(material, floor, ratio) {
- const base = baseRoughness(material);
- if (!(base > 0)) return floor;
- return Math.min(base, Math.max(floor, base * ratio));
-}
+
/**
* Move one colour in HSL, wrapping the hue so a shift may cross 0.
@@ -249,8 +243,7 @@ export function patchMoss(material, opts = {}) {
const color = toColor(opts.color, 0x40592a);
// Moss is matte and it takes the gloss over only as far as it takes
// the surface over.
- composeRoughness(material, 'damp:moss',
- towardRoughness(material, 0.97, 0.70 * amount));
+
patchStandard(material, BASE);
return patchStandard(material, {
name: 'damp:moss',
@@ -276,6 +269,11 @@ export function patchMoss(material, opts = {}) {
'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: coatingNormal('msBump',
+ '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);',
@@ -333,6 +331,7 @@ export function patchMoss(material, opts = {}) {
// 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
@@ -395,9 +394,8 @@ export function patchMoss(material, opts = {}) {
*
* 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. Gloss here is per MATERIAL,
- * not per pixel, so the factor goes DOWN — the opposite direction from
- * moss on the same chain.
+ * 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.
@@ -414,11 +412,9 @@ export function patchMoisture(material, opts = {}) {
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 only a THIRD glossier than the ground it lands on, and never
- // past wet soil: see `wetTarget` for what a fixed number did here.
- composeRoughness(material, 'damp:moisture',
- towardRoughness(material, wetTarget(material, 0.30, 0.68),
- 0.45 * strength));
+ // 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',
@@ -434,6 +430,7 @@ export function patchMoisture(material, opts = {}) {
'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);',
@@ -536,17 +533,9 @@ export function patchCrackedMud(material, opts = {}) {
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 the mattest thing in a bed and water standing in the
- // cracks is the glossiest: ONE factor swings between the two. The dry
- // end is absolute (silt is matte whatever it lands on); the wet end
- // is relative, for the reason `wetTarget` gives — the cracks' gloss
- // is charged to the whole plate, and a mirror-flat plate under a sky
- // environment reads as a bright card, not as a bed holding water.
- composeRoughness(material, 'damp:mud',
- towardRoughness(
- material,
- 0.95 + (wetTarget(material, 0.30, 0.62) - 0.95) * wet,
- 0.45));
+ // 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',
@@ -568,6 +557,11 @@ export function patchCrackedMud(material, opts = {}) {
'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: coatingNormal('mdBump',
+ '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
@@ -581,7 +575,7 @@ export function patchCrackedMud(material, opts = {}) {
' 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.010, 0.055, uMudDepth)',
+ ' 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.
@@ -618,9 +612,9 @@ export function patchCrackedMud(material, opts = {}) {
' 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.16, 1.06, 0.92),',
+ ' 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.08, 0.30, uMudDepth);',
+ ' 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.js
index 10fca781..d0424f3f 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/dapple.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/dapple.js
@@ -152,11 +152,10 @@ export function patchDappledLight(material, opts = {}) {
'#ifdef USE_INSTANCING',
' vAstraDapW = (modelMatrix * instanceMatrix'
+ ' * vec4(transformed, 1.0)).xyz;',
- ' vAstraDapN = normalize(mat3(modelMatrix)'
- + ' * mat3(instanceMatrix) * normal);',
+ ' vAstraDapN = astraNormalTransform(mat3(modelMatrix) * mat3(instanceMatrix), normal);',
'#else',
' vAstraDapW = (modelMatrix * vec4(transformed, 1.0)).xyz;',
- ' vAstraDapN = normalize(mat3(modelMatrix) * normal);',
+ ' vAstraDapN = astraNormalTransform(mat3(modelMatrix), normal);',
'#endif',
].join('\n'),
fragmentHead: [
@@ -215,7 +214,8 @@ export function patchDappledLight(material, opts = {}) {
// fleck travel the way the gap's shadow would.
' vec3 dpS = normalize(uDapSun);',
' float dpUp = max(dpS.y, 0.15);',
- ' vec2 dpAt = vAstraDapW.xz + dpS.xz * (uDapH / dpUp);',
+ ' 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.
@@ -233,7 +233,7 @@ export function patchDappledLight(material, opts = {}) {
// 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) + ' * uDapH / uDapScale;',
+ ' 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);',
@@ -251,8 +251,16 @@ export function patchDappledLight(material, opts = {}) {
// 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);',
- ' totalEmissiveRadiance += dpTint * (uDapAmt * dpBeam * dpF'
- + ' * diffuseColor.rgb);',
+ ' 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'),
});
}
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/environment.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/environment.js
index bca9b9ef..ee8ea5c9 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/environment.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/environment.js
@@ -11,6 +11,7 @@ import * as THREE from 'three';
import { fbm2, mulberry32 } from './noise.js';
import { patchStandard } from './shader.js';
import { skyRadiance } from './sky.js';
+import { snapshotResources, attachDisposal } from './lifecycle.js';
const MOODS = {
day: { zenith: 0x5d8fd6, horizon: 0xdbe3ea, ridge: 0x9fb2c4,
@@ -85,21 +86,33 @@ export function roomShell(opts = {}) {
slab(name, sx, b1 - b0, sz, x, y0 + (b0 + b1) / 2, z, wallMat);
};
if (!holes.length) { place(`Wall_${face}`, 0, f.len, 0, h); continue; }
- const sorted = holes.map((o) => ({ a0: o.center[0] - o.size[0] / 2, a1: o.center[0] + o.size[0] / 2,
- b0: o.center[1] - o.size[1] / 2, b1: o.center[1] + o.size[1] / 2 }))
- .sort((p, q) => p.a0 - q.a0);
- let cursor = 0, n = 0;
- for (const o of sorted) {
- const a0 = Math.max(0, o.a0), a1 = Math.min(f.len, o.a1);
- place(`Wall_${face}_${n++}`, cursor, a0, 0, h); // solid span before the opening
- place(`Wall_${face}_${n++}`, a0, a1, 0, Math.max(0, o.b0)); // sill below it
- place(`Wall_${face}_${n++}`, a0, a1, Math.min(h, o.b1), h); // lintel above it
- cursor = a1;
+ const clipped = holes.map((o) => ({
+ a0:Math.max(0, o.center[0] - o.size[0] / 2),
+ a1:Math.min(f.len, o.center[0] + o.size[0] / 2),
+ b0:Math.max(0, o.center[1] - o.size[1] / 2),
+ b1:Math.min(h, o.center[1] + o.size[1] / 2),
+ })).filter((o) => o.a1 > o.a0 && o.b1 > o.b0);
+ // Subtract the UNION of openings. Independent sills/lintels fill each
+ // other's holes when windows overlap horizontally or sit above a door.
+ const cuts = [...new Set([0, f.len, ...clipped.flatMap((o) => [o.a0, o.a1])])]
+ .sort((a, b) => a - b);
+ let n = 0;
+ for (let i = 0; i + 1 < cuts.length; i++) {
+ const a0 = cuts[i], a1 = cuts[i + 1], middle = (a0 + a1) / 2;
+ const intervals = clipped.filter((o) => o.a0 < middle && middle < o.a1)
+ .sort((a, b) => a.b0 - b.b0);
+ let bottom = 0;
+ for (const opening of intervals) {
+ place(`Wall_${face}_${n++}`, a0, a1, bottom, opening.b0);
+ bottom = Math.max(bottom, opening.b1);
+ }
+ place(`Wall_${face}_${n++}`, a0, a1, bottom, h);
}
- place(`Wall_${face}_${n++}`, cursor, f.len, 0, h);
}
if (opts.ceiling !== false) slab('Ceiling', w + 2 * t, t, d + 2 * t, cx, y0 + h + t / 2, cz, ceilMat);
- return group;
+ const owned = snapshotResources(group);
+ owned.add(wallMat);owned.add(ceilMat);
+ return attachDisposal(group, owned);
}
/**
@@ -202,7 +215,8 @@ export function worldShell(opts = {}) {
horizon.getHex(),
opts.fogDensity === undefined ? density : opts.fogDensity);
- return { group, fog, radius };
+ attachDisposal(group, snapshotResources(group));
+ return { group, fog, radius, dispose:group.userData.dispose };
}
/**
@@ -419,7 +433,7 @@ export function makeOutskirts(opts = {}) {
copse.name = 'OutskirtsCopses';
group.add(copse);
}
- return group;
+ return attachDisposal(group, snapshotResources(group));
}
@@ -664,6 +678,9 @@ export function sunRig(opts = {}) {
sunDisc.renderOrder = -1.5;
}
+ const owned = sunDisc ? snapshotResources(sunDisc) : new Set();
+ owned.add(envTex);owned.add(sun);owned.add(fill);
+ const lifecycle = attachDisposal(new THREE.Group(), owned);
return { sun, fill, envTex, sunDisc, sunDir: dir.clone(), lightDir,
- night, moonDir, mood: moodName };
+ night, moonDir, mood: moodName, dispose:lifecycle.userData.dispose };
}
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/figure.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/figure.js
index 38c8340b..5106d061 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/figure.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/figure.js
@@ -8,6 +8,7 @@
*/
import * as THREE from 'three';
+import { attachDisposal, snapshotResources } from './lifecycle.js';
import * as MAT from './materials.js';
/**
@@ -193,7 +194,7 @@ export function figure(opts = {}) {
head.name = 'head';
head.castShadow = true;
neck.add(new THREE.Mesh(
- new THREE.CylinderGeometry(0.028 * h, 0.032 * h, 0.05 * h, 8), skin));
+ new THREE.CylinderGeometry(0.028 * h, 0.032 * h, 0.07 * h, 8), skin));
neck.add(head);
// A face, at ~150 triangles. Without it the head is a ball, and a
// ball is what makes a close figure read as a shop dummy however
@@ -319,6 +320,16 @@ export function figure(opts = {}) {
root.userData.height = h;
root.userData.joints = joints;
root.userData.hipHeight = hipY;
+ const sole = root.getObjectByName('footL');
+ root.userData.gaitDimensions = { thigh, shin,
+ sole: Array.from({ length: sole.geometry.attributes.position.count }, (_, i) => [
+ sole.geometry.attributes.position.getY(i) + sole.position.y,
+ sole.geometry.attributes.position.getZ(i) + sole.position.z,
+ ]) };
+ root.userData.update = root.userData.tick = () => {};
+ // MAT and eyeMaterial cache their materials across figures. Only the
+ // geometry belongs to this figure; attached held objects stay caller-owned.
+ attachDisposal(root, snapshotResources(root, { materials: false }));
return neutral(root);
}
@@ -330,6 +341,7 @@ function neutral(fig) {
j.rotation.set(r[0], r[1], r[2]);
}
fig.userData.joints.waist.position.set(0, fig.userData.hipHeight, 0);
+ fig.getObjectByName('torso').rotation.set(0, 0, 0);
return fig;
}
@@ -425,44 +437,97 @@ export function walk(fig, t, opts = {}) {
const j = fig.userData.joints;
const h = fig.userData.height;
const L = fig.userData.hipHeight; // hip pivot to sole: the leg
- let a, cyc;
+ if (!Number.isFinite(t)) throw new RangeError('walk: time must be finite');
+ let a, cyc, speed;
if (opts.speed !== undefined) {
- const v = Math.max(0.05, opts.speed);
+ if (!Number.isFinite(opts.speed) || opts.speed < 0)
+ throw new RangeError('walk: speed must be finite and nonnegative');
+ if (opts.speed === 0) {
+ neutral(fig);
+ fig.userData.gait = { phase: 0, speed: 0, stance: [true, true] };
+ return fig;
+ }
+ const v = opts.speed;
const wr = 0.0065 * (h / 1.72); // walk ratio, m per (step/min)
const cadence = Math.min(145, Math.max(70, Math.sqrt(60 * v / wr)));
- cyc = cadence / 120; // stride cycles per second
+ // At an unusually high requested route speed, shorten the cycle instead
+ // of silently clamping foot travel and allowing the planted foot to slide.
+ const reach = fig.userData.gaitDimensions.thigh + fig.userData.gaitDimensions.shin;
+ cyc = Math.max(cadence / 120, v * .55 / (2 * reach * .68));
// stepLen = v / (2 * cyc), so stepLen x cadence === v exactly,
// even where the cadence clamps; a = asin(stepLen / (2 * L)).
a = Math.asin(Math.min(0.98, v / (4 * cyc * L)));
+ speed = v;
} else {
a = opts.stride === undefined ? 0.42 : opts.stride;
cyc = opts.rate === undefined ? 0.95 : opts.rate;
+ speed = 4 * L * Math.sin(a) * cyc;
}
- const p = (t * cyc + (opts.phase || 0)) * Math.PI * 2;
+ const cycle = t * cyc + (opts.phase || 0);
+ const p = cycle * Math.PI * 2;
const sw = Math.sin(p);
- j.hipL.rotation.x = sw * a;
- j.hipR.rotation.x = -sw * a;
- // A knee bends one way only: it flexes on the backswing, never past 0.
- j.kneeL.rotation.x = -Math.max(0, -sw) * a * 1.5;
- j.kneeR.rotation.x = -Math.max(0, sw) * a * 1.5;
- // Ankles: toes up on the landing leg (heel strike), toes down
- // pushing off behind — the two moments the eye reads as contact.
- j.ankleL.rotation.x =
- a * (0.25 * Math.max(0, sw) - 0.6 * Math.max(0, -sw));
- j.ankleR.rotation.x =
- a * (0.25 * Math.max(0, -sw) - 0.6 * Math.max(0, sw));
+ const dimensions = fig.userData.gaitDimensions;
+ const thigh = dimensions.thigh, shin = dimensions.shin;
+ const stanceFraction = 0.55;
+ const halfStroke = Math.min((thigh + shin) * .68,
+ speed * stanceFraction / (2 * Math.max(cyc, 1e-5)));
+ const smooth = (x) => { x = THREE.MathUtils.clamp(x, 0, 1); return x * x * (3 - 2 * x); };
+ const feet = [0, .5].map((offset) => {
+ const phase = THREE.MathUtils.euclideanModulo(cycle - .25 + offset, 1);
+ const stance = phase < stanceFraction;
+ let z, lift = 0, pitch;
+ if (stance) {
+ // A planted foot travels BACKWARD in the figure frame at precisely the
+ // route speed. With root motion along -Z, it stays on one ground point.
+ z = halfStroke * (2 * phase / stanceFraction - 1);
+ pitch = .20 * (1 - smooth(phase / .10))
+ - .35 * smooth((phase - .40) / .15);
+ } else {
+ const q = (phase - stanceFraction) / (1 - stanceFraction);
+ // Cubic return with matching endpoint velocity: the foot does not snap
+ // from the moving stance arc to a zero-velocity swing arc.
+ const slope = 2 * halfStroke / stanceFraction * (1 - stanceFraction);
+ z = halfStroke * (4 * q ** 3 - 6 * q * q + 1)
+ + slope * (2 * q ** 3 - 3 * q * q + q);
+ lift = h * .065 * Math.sin(Math.PI * q) ** 2;
+ pitch = -.35 + .55 * smooth(q);
+ }
+ const c = Math.cos(pitch), s = Math.sin(pitch);
+ let soleY = Infinity;
+ for (const [y, pointZ] of dimensions.sole) soleY = Math.min(soleY, y * c - pointZ * s);
+ return { phase, stance, z: z + .03 * h, y: lift - soleY, pitch };
+ });
+ let pelvisY = L - .004 * h - .038 * h * sw * sw;
+ const reach = (thigh + shin) * .999;
+ for (const foot of feet) {
+ pelvisY = Math.min(pelvisY, foot.y + Math.sqrt(Math.max(.01, reach * reach - foot.z * foot.z)));
+ }
+ for (let i = 0; i < 2; i++) {
+ const side = i === 0 ? 'L' : 'R', foot = feet[i];
+ const y = foot.y - pelvisY, z = foot.z;
+ const cosine = THREE.MathUtils.clamp((y * y + z * z - thigh * thigh - shin * shin)
+ / (2 * thigh * shin), -1, 1);
+ const knee = -Math.acos(cosine);
+ const hip = Math.atan2(-z, -y) - Math.atan2(shin * Math.sin(knee), thigh + shin * Math.cos(knee));
+ j['hip' + side].rotation.set(hip, 0, 0);
+ j['knee' + side].rotation.set(knee, 0, 0);
+ j['ankle' + side].rotation.set(foot.pitch - hip - knee, 0, 0);
+ }
// Arms counter-swing the legs, and the elbow flexes hardest when its
// arm is forward — a straight pumping stick reads as a mannequin.
j.shoulderL.rotation.x = -sw * a * 0.7;
j.shoulderR.rotation.x = sw * a * 0.7;
j.elbowL.rotation.x = 0.35 + 0.3 * Math.max(0, -sw);
j.elbowR.rotation.x = 0.35 + 0.3 * Math.max(0, sw);
- j.waist.rotation.y = sw * 0.06;
- // Pelvis dips TWICE per stride (one dip is the classic procedural
- // limp) and sways once toward the stance foot. Both live on the
- // waist pivot, so route() still owns fig.position.
- j.waist.position.y = L - 0.6 * L * (1 - Math.cos(a * sw));
- j.waist.position.x = 0.023 * (h / 1.72) * sw;
+ // Keep the leg frame stable while the torso twists above it. Rotating the
+ // waist parent would rotate planted feet away from their ground contacts.
+ j.waist.rotation.set(0, 0, 0);
+ fig.getObjectByName('torso').rotation.y = sw * .06;
+ // Pelvis dips twice per stride and lowers enough to keep each target
+ // within leg reach. Route motion remains on fig.position.
+ j.waist.position.set(0, pelvisY, 0);
+ fig.userData.gait = { phase: THREE.MathUtils.euclideanModulo(cycle, 1),
+ speed, stance: feet.map((foot) => foot.stance) };
return fig;
}
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/fire.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/fire.js
new file mode 100644
index 00000000..e882c6c1
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/fire.js
@@ -0,0 +1,398 @@
+/**
+ * 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, patchStandard } from './shader.js';
+
+const finite = (v, fallback, lo, hi) => Number.isFinite(v)
+ ? THREE.MathUtils.clamp(v, lo, hi) : fallback;
+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 fireHash(vec3 p) {
+ p = fract(p * 0.1031);
+ p += dot(p, p.yzx + 33.33);
+ return fract((p.x + p.y) * p.z);
+}
+float fireNoise(vec3 p) {
+ vec3 i = floor(p), f = fract(p);
+ f = f * f * (3.0 - 2.0 * f);
+ return mix(mix(mix(fireHash(i), fireHash(i + vec3(1,0,0)), f.x),
+ mix(fireHash(i + vec3(0,1,0)), fireHash(i + vec3(1,1,0)), f.x), f.y),
+ mix(mix(fireHash(i + vec3(0,0,1)), fireHash(i + vec3(1,0,1)), f.x),
+ mix(fireHash(i + vec3(0,1,1)), fireHash(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', util: false, 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);
+ vec3 safeRay = mix(vec3(-1.0), vec3(1.0), step(vec3(0.0), ray))
+ * max(abs(ray), vec3(0.000001));
+ vec3 ta = (uBoxMin - uCameraLocal) / safeRay;
+ vec3 tb = (uBoxMax - uCameraLocal) / safeRay;
+ vec3 nearT = min(ta, tb), farT = max(ta, tb);
+ float enter = max(0.0, max(nearT.x, max(nearT.y, nearT.z)));
+ float leave = min(farT.x, min(farT.y, farT.z));
+ if (leave <= enter) discard;
+ float ds = (leave - enter) / float(${steps});
+ // Static sub-pixel jitter avoids axial banding without temporal noise.
+ float jitter = fireHash(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
+ vec4 clip = uLocalToClip * vec4(firstHit, 1.0);
+ gl_FragDepth = clamp(clip.z / clip.w * 0.5 + 0.5, 0.0, 1.0);
+ #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]: 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 = finite(opts.radius, candle ? 0.009 : 0.35, 0.001, 20);
+ const height = finite(opts.height, candle ? 0.055 : 1.1, 0.004, 50);
+ const intensity = finite(opts.intensity, 1, 0, 8);
+ const seed = finite(opts.seed, 7, -2147483648, 2147483647) | 0;
+ const wind = [finite(opts.wind?.[0], 0, -0.6, 0.6), finite(opts.wind?.[1], 0, -0.6, 0.6)];
+ 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(finite(opts.embers, candle ? 0 : 26, 0, 256));
+ 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 = finite(opts.lightIntensity, candle ? 0.9 : 14, 0, 10000);
+ let light;
+ if (opts.light !== false) {
+ light = new THREE.PointLight(0xffab53, lightIntensity,
+ finite(opts.lightDistance, height * 8, 0, 1000), 2);
+ light.name = 'FireLight'; light.position.y = height * 0.27;
+ group.add(light);
+ }
+ const sampleEmber = (index, t) => {
+ 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;
+ const y = height * (0.15 + a * 2.2);
+ return { position: new THREE.Vector3(
+ p.x + wind[0] * height * a * 2 + Math.sin(a * 5 + p.drift) * radius * a * 0.3,
+ y, p.z + wind[1] * height * a * 2 + Math.cos(a * 4 + p.drift) * radius * a * 0.3),
+ scale: Math.pow(Math.sin(a * Math.PI), 0.7) * p.size, age: a };
+ };
+ 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);
+ 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 = finite(opts.radius, 0.032, 0.004, 2);
+ const height = finite(opts.height, 0.16, 0.015, 8);
+ const seed = finite(opts.seed, 13, -2147483648, 2147483647) | 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(finite(opts.drips, 7, 0, 24));
+ 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 = finite(opts.flameHeight, radius * 1.47, 0.01, 3);
+ flame = makeFire({ radius: flameHeight * 0.17, height: flameHeight, style: 'candle',
+ seed, wind: opts.wind, quality: opts.quality || 'high', light: opts.light,
+ lightIntensity: finite(opts.lightIntensity, 0.8, 0, 10000), 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/firefield.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/firefield.js
new file mode 100644
index 00000000..c3a3b214
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/firefield.js
@@ -0,0 +1,482 @@
+/**
+ * A bounded shared fire/soot field for fuel beds, large fires and authored
+ * structural-fire scenes. This is prescribed transport, not combustion or
+ * structural simulation. Legacy makeFire/makeCandle remain in fire.js.
+ *
+ * makeFireField({emitters:[{position:[0,0,0],radius:.3,height:1,strength:1}],
+ * seed:7, wind:[.15,0], quality:'balanced', intensity:1,
+ * smoke:{height:3,density:.65,albedo:0x514942},
+ * embers:{count:48,size:[.0015,.006],lifetime:[2,4],riseSpeed:1.2},
+ * lighting:{count:2,intensity:12}, occluders:[], depthResolution:512})
+ *
+ * Positions/dimensions are local metres; wind is local metres/second. All
+ * emitters share one ray integration. A baked source atlas makes runtime
+ * density cost independent of emitter count. Source layout and wind are baked at
+ * construction; rebuild the field to change them. Nonuniform object transforms
+ * are supported; optical depth uses world metres. update(t) takes absolute seconds;
+ * sampleField(x,y,z,t) mirrors the GPU's flame/soot/temperature field.
+ *
+ * Optional occluders are BORROWED Object3D roots. An isolated depth-proxy scene
+ * terminates rays at those opaque meshes, including alpha cuts, instances and
+ * customDepthMaterial deformation. Hidden ancestors are respected. Original
+ * callbacks/parents/materials are never changed. Skinned meshes and morphed
+ * InstancedMesh occluders are unsupported;
+ * custom vertex deformation requires a matching customDepthMaterial. Glass and
+ * other transparent volumes are not depth-resolved. One depth-aware fire field
+ * per scene is recommended; each visible view adds a pass over its occluders.
+ * Logarithmic depth is not supported by the optional depth-termination path.
+ * No global renderer hooks or recursively captured reflective materials.
+ */
+import * as THREE from 'three';
+import { dataTexture3D, mulberry32, sampleGrid3 } from './noise.js';
+import { makeShaderMaterial, keepOutOfDepthPasses, withRendererState } from './shader.js';
+import { snapshotResources, attachDisposal } from './lifecycle.js';
+
+const TIERS = {
+ low: { resolution: 48, steps: 48, lightSteps: 3 },
+ balanced: { resolution: 64, steps: 80, lightSteps: 5 },
+ high: { resolution: 80, steps: 128, lightSteps: 7 },
+};
+const NOISE_RESOLUTION = 48;
+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); };
+const fract = x => x - Math.floor(x);
+function number(value, fallback, min, max, label) {
+ const v = value ?? fallback;
+ if (!Number.isFinite(v) || v < min || v > max) throw new RangeError(`makeFireField: invalid ${label}`);
+ return v;
+}
+function vector(value, fallback, length, label) {
+ const v = value?.toArray ? value.toArray() : value ?? fallback;
+ if (!Array.isArray(v) || v.length !== length || !v.every(Number.isFinite)) {
+ throw new RangeError(`makeFireField: ${label} needs ${length} finite components`);
+ }
+ return v.slice();
+}
+function noiseTexture(seed) {
+ const random = mulberry32(seed), grids = [4, 8, 16].map(n => ({n,
+ data: Float32Array.from({length: n ** 3 * 4}, () => random())}));
+ const n = NOISE_RESOLUTION, data = new Uint8Array(n ** 3 * 4); let at = 0;
+ for (let z = 0; z < n; z++) for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) {
+ for (let c = 0; c < 4; c++) {
+ let sum = 0, amplitude = 4 / 7;
+ for (const grid of grids) {
+ const q = [x, y, z].map(v => { const p = (v + .5) / n * grid.n;
+ return Math.floor(p) + smooth(0, 1, fract(p)); });
+ sum += sampleGrid3(grid.data, grid.n, ...q, 4, c) * amplitude; amplitude *= .5;
+ }
+ data[at++] = Math.round(clamp(sum) * 255);
+ }
+ }
+ return dataTexture3D(data, n, true);
+}
+function sourceAtlas(emitters, box, resolution, smokeHeight, wind, rise, seed) {
+ const extent = box.getSize(new THREE.Vector3()), data = new Uint8Array(resolution ** 3 * 4);
+ const random = mulberry32(seed ^ 0x7139), phases = emitters.map(() => random()); let at = 0;
+ for (let z = 0; z < resolution; z++) for (let y = 0; y < resolution; y++) for (let x = 0; x < resolution; x++) {
+ const px = box.min.x + (x + .5) / resolution * extent.x;
+ const py = box.min.y + (y + .5) / resolution * extent.y;
+ const pz = box.min.z + (z + .5) / resolution * extent.z;
+ let flame = 0, progress = 0, soot = 0, phase = 0, strongest = 0;
+ for (let i = 0; i < emitters.length; i++) {
+ const e = emitters[i], h = py - e.position[1];
+ if (h <= 0 || e.strength === 0) continue;
+ const age = h / rise, dx = px - e.position[0] - wind[0] * age;
+ const dz = pz - e.position[2] - wind[1] * age;
+ const distance = Math.hypot(dx, dz), f = h / e.height;
+ if (f < 1.65) {
+ const profile = Math.pow(Math.max(0, 1 - f / 1.05), .72) * .94 - Math.max(0,f-1.05)*2;
+ const potential = clamp(.5 + (profile - distance / e.radius) * .57 + Math.log2(Math.max(.01,e.strength))*.075);
+ if (potential > flame) { flame = potential; progress = f; phase = phases[i]; }
+ }
+ const s = h / smokeHeight;
+ if (s < 1) {
+ const radius = e.radius * .70 + h * .23;
+ const plume = Math.pow(clamp(1 - distance / radius), .65)
+ * smooth(.025, .16, s) * (1 - smooth(.70, 1, s)) * Math.exp(-s * 1.4) * e.strength;
+ soot += plume * .55;
+ if (plume > strongest && flame === 0) { strongest = plume; phase = phases[i]; }
+ }
+ }
+ data[at++] = Math.round(flame * 255); data[at++] = Math.round(clamp(progress) * 255);
+ data[at++] = Math.round(clamp(soot) * 255); data[at++] = Math.round(phase * 255);
+ }
+ return dataTexture3D(data, resolution, false);
+}
+
+const FIELD = /* glsl */`
+precision highp sampler3D;
+uniform float uTime;
+uniform sampler3D uSourceAtlas, uFieldNoise;
+uniform sampler2D uOpaqueDepth;
+uniform vec3 uBoxMin, uBoxSize, uFlameBoxMin, uFlameBoxSize, uSunLocal, uSunColor, uAmbient, uSootAlbedo;
+uniform vec4 uViewport, uFireLights[4];
+uniform vec3 uFireLightColor;
+uniform mat4 uViewToLocal, uInverseProjection, uLocalToClip;
+uniform mat3 uLocalToWorld;
+uniform float uCoarseScale, uWarp, uRise, uTurbulence, uIntensity;
+uniform float uFlameExtinction, uSootExtinction, uUseOpaqueDepth;
+uniform int uFireLightCount;
+varying vec3 vFieldLocal;
+vec4 fireAtlas(vec3 p) {
+ vec3 uv=(p-uBoxMin)/uBoxSize;
+ if(any(lessThan(uv,vec3(0.0)))||any(greaterThan(uv,vec3(1.0))))return vec4(0.0);
+ return texture(uSourceAtlas,uv);
+}
+vec3 fireFieldSample(vec3 p) {
+ vec4 initial=fireAtlas(p);
+ vec3 flow=p*vec3(.32,.13,.32)/uCoarseScale-vec3(0.0,uTime*uRise*.13/uCoarseScale,0.0);
+ vec3 coarse=texture(uFieldNoise,flow+initial.a*.31).rgb;
+ float anchor=smoothstep(0.0,.22,initial.g);
+ vec3 warped=p+(coarse-.5)*uWarp*vec3(1.0,.38,1.0)*anchor*uTurbulence;
+ vec4 field=fireAtlas(warped);
+ float fine=texture(uFieldNoise,p*vec3(2.6,.75,2.6)-vec3(0.0,uTime*uRise*.75,0.0)+.197).g;
+ float surface=field.r-.5+((coarse.g-.5)*(.35+field.g*.8)+(fine-.5)*.30)*uTurbulence;
+ float flame=smoothstep(-.025,.075,surface)*(1.0-smoothstep(.035,.22,surface)*.97)
+ *smoothstep(0.0,.055,field.g)*(1.0-smoothstep(.90,1.0,field.g));
+ flame*=smoothstep(.21+field.g*.20,.42+field.g*.23,coarse.r*.65+fine*.35);
+ float smoke=field.b*pow(clamp(.68+(coarse.r-.5)*2.4+(fine-.5)*.55,0.0,1.6),1.3);
+ float temperature=clamp(.18+flame*.57+coarse.b*.15-field.g*.18,0.0,1.0);
+ return vec3(flame,smoke,temperature);
+}
+// Light samples use only the precomputed soot scaffold, not every emitter.
+float fireSootCoarse(vec3 p) {
+ vec4 a=fireAtlas(p);
+ float n=texture(uFieldNoise,p*vec3(.32,.13,.32)/uCoarseScale-vec3(0.0,uTime*uRise*.13/uCoarseScale,0.0)+a.a*.31).r;
+ return a.b*pow(clamp(.68+(n-.5)*2.4,0.0,1.6),1.3);
+}
+vec2 fireRange(vec3 origin,vec3 direction,vec3 boxMin,vec3 boxSize) {
+ vec3 safe=mix(vec3(-1.0),vec3(1.0),step(vec3(0.0),direction))*max(abs(direction),vec3(1e-7));
+ vec3 a=(boxMin-origin)/safe,b=(boxMin+boxSize-origin)/safe;
+ vec3 near=min(a,b),far=max(a,b);
+ return vec2(max(near.x,max(near.y,near.z)),min(far.x,min(far.y,far.z)));
+}
+vec2 fireBox(vec3 origin,vec3 direction){return fireRange(origin,direction,uBoxMin,uBoxSize);}
+vec3 fireRadiance(float heat) {
+ vec3 c=mix(vec3(1.8,.06,.002),vec3(4.0,.75,.04),smoothstep(.15,.58,heat));
+ return mix(c,vec3(6.0,2.8,.65),smoothstep(.55,.96,heat))*.72;
+}
+float fireSunTransmission(vec3 p,float jitter) {
+ float end=max(0.0,fireBox(p,uSunLocal).y),sum=0.0;
+ for(int j=0;j<FIELD_LIGHT_STEPS;j++) {
+ float a=float(j)/float(FIELD_LIGHT_STEPS),b=float(j+1)/float(FIELD_LIGHT_STEPS);
+ float start=a*a*end,stop=b*b*end;
+ sum+=fireSootCoarse(p+uSunLocal*mix(start,stop,jitter))*(stop-start);
+ }
+ return exp(-sum*uSootExtinction*length(uLocalToWorld*uSunLocal));
+}
+`;
+
+function fieldMaterial(uniforms, tier) {
+ return makeShaderMaterial({name:'SharedFireSootVolume',util:false,fog:true,
+ transparent:true,depthWrite:false,side:THREE.BackSide,uniforms,
+ defines:{FIELD_STEPS:tier.steps,FIELD_LIGHT_STEPS:tier.lightSteps},
+ varyings:'varying vec3 vFieldLocal;',vertexMain:'vFieldLocal=position;',fragmentHead:FIELD,
+ fragmentMain:/* glsl */`
+ vec2 uv=(gl_FragCoord.xy-uViewport.xy)/uViewport.zw;
+ vec4 nearView=uInverseProjection*vec4(uv*2.0-1.0,-1.0,1.0);
+ vec4 farView=uInverseProjection*vec4(uv*2.0-1.0,1.0,1.0);
+ vec3 origin=(uViewToLocal*vec4(nearView.xyz/nearView.w,1.0)).xyz;
+ vec3 farPoint=(uViewToLocal*vec4(farView.xyz/farView.w,1.0)).xyz;
+ vec3 ray=normalize(farPoint-origin);
+ vec2 range=fireBox(origin,ray);float enter=max(0.0,range.x),leave=range.y;
+ if(uUseOpaqueDepth>.5) {
+ float depth=texture2D(uOpaqueDepth,uv).r;
+ if(depth<.999999) {
+ vec4 viewPoint=uInverseProjection*vec4(uv*2.0-1.0,depth*2.0-1.0,1.0);
+ vec3 localPoint=(uViewToLocal*vec4(viewPoint.xyz/viewPoint.w,1.0)).xyz;
+ leave=min(leave,dot(localPoint-origin,ray));
+ }
+ }
+ if(leave<=enter||uIntensity<=0.0)discard;
+ float metric=length(uLocalToWorld*ray);
+ vec2 hot=fireRange(origin,ray,uFlameBoxMin,uFlameBoxSize);
+ hot=vec2(max(enter,hot.x),min(leave,hot.y));
+ int pre=0,post=0;
+ if(hot.y>hot.x){
+ if(hot.x>enter)pre=int(float(FIELD_STEPS)*.12);
+ if(hot.y<leave)post=int(float(FIELD_STEPS)*.12);
+ }else hot=vec2(enter,leave);
+ int mainCount=FIELD_STEPS-pre-post;
+ float jitter=fract(sin(dot(gl_FragCoord.xy,vec2(12.9898,78.233)))*43758.5453);
+ vec3 radiance=vec3(0.0),first=origin+ray*leave;float transmittance=1.0;bool hit=false;
+ for(int i=0;i<FIELD_STEPS;i++) {
+ float start=hot.x,stop=hot.y,offset=float(i-pre),count=float(mainCount);
+ if(i<pre){start=enter;stop=hot.x;offset=float(i);count=float(pre);}
+ else if(i>=pre+mainCount){start=hot.y;stop=leave;offset=float(i-pre-mainCount);count=float(post);}
+ float ds=(stop-start)/max(count,1.0);
+ vec3 p=origin+ray*(start+(offset+jitter)*ds);
+ vec3 field=fireFieldSample(p);
+ float flame=field.x*uFlameExtinction,soot=field.y*uSootExtinction,total=flame+soot;
+ if(total<.0001)continue;
+ float alpha=1.0-exp(-total*ds*metric);
+ if(!hit&&alpha>.0005){first=p;hit=true;}
+ vec3 incoming=uAmbient;
+ if(soot>.001) {
+ incoming+=uSunColor*fireSunTransmission(p,jitter);
+ for(int j=0;j<4;j++) {
+ if(j>=uFireLightCount)break;
+ vec3 delta=uLocalToWorld*(p-uFireLights[j].xyz);
+ incoming+=uFireLightColor*uFireLights[j].w/(dot(delta,delta)+.09);
+ }
+ }
+ vec3 source=(fireRadiance(field.z)*flame*uIntensity+incoming*uSootAlbedo*soot)/max(total,.0001);
+ radiance+=transmittance*alpha*source;transmittance*=1.0-alpha;
+ if(transmittance<.008)break;
+ }
+ float alpha=1.0-transmittance;if(alpha<.005)discard;
+ #ifndef USE_LOGDEPTHBUF
+ vec4 clip=uLocalToClip*vec4(first,1.0);
+ gl_FragDepth=clamp(clip.z/clip.w*.5+.5,0.0,1.0);
+ #endif
+ gl_FragColor=vec4(radiance/max(alpha,.001),alpha);
+ `});
+}
+
+function visibleInTree(object) {
+ for(let o=object;o;o=o.parent)if(!o.visible)return false;
+ return true;
+}
+
+/** Isolated borrowed-geometry proxies: no original render callbacks can recurse. */
+function depthCapture(roots, resolution) {
+ const scene=new THREE.Scene(),proxies=new Map(),materials=new Map(),ownedInstances=new Set();
+ let target=null,captures=0,disposed=false;
+ const invisible=new THREE.MeshDepthMaterial();invisible.visible=false;
+ function depthMaterial(material, source) {
+ if(!material?.visible||material.transparent||material.transmission>0)return invisible;
+ if(source.customDepthMaterial)return source.customDepthMaterial;
+ let depth=materials.get(material);
+ if(!depth){depth=new THREE.MeshDepthMaterial();materials.set(material,depth);}
+ const changed=depth.map!==material.map||depth.alphaMap!==material.alphaMap
+ ||depth.alphaTest!==material.alphaTest||depth.side!==material.side
+ ||depth.displacementMap!==material.displacementMap||depth.userData.sourceVersion!==material.version;
+ depth.map=material.map;depth.alphaMap=material.alphaMap;depth.alphaTest=material.alphaTest;depth.opacity=material.opacity;
+ depth.side=material.side;depth.displacementMap=material.displacementMap;
+ depth.displacementScale=material.displacementScale;depth.displacementBias=material.displacementBias;
+ depth.wireframe=material.wireframe;depth.vertexColors=material.vertexColors;depth.alphaHash=material.alphaHash;
+ depth.clippingPlanes=material.clippingPlanes;depth.clipIntersection=material.clipIntersection;
+ depth.userData.sourceVersion=material.version;if(changed)depth.needsUpdate=true;
+ return depth;
+ }
+ function sync() {
+ proxies.forEach(proxy=>{proxy.visible=false;});
+ const seen=new Set();
+ for(const root of roots)root.traverse(source=>{
+ if(!source.isMesh||seen.has(source)||!visibleInTree(source))return;
+ seen.add(source);
+ if(source.isSkinnedMesh||source.isInstancedMesh&&source.morphTexture)throw new TypeError('makeFireField: skinned or morphed-instance depth occluders are unsupported');
+ if(source.userData?.astraNoOverride)return;
+ const material=Array.isArray(source.material)?source.material.map(m=>depthMaterial(m,source))
+ :depthMaterial(source.material,source);
+ let proxy=proxies.get(source);
+ if(!proxy){
+ proxy=source.isInstancedMesh?new THREE.InstancedMesh(source.geometry,material,source.instanceMatrix.count)
+ :new THREE.Mesh(source.geometry,material);
+ if(proxy.isInstancedMesh)ownedInstances.add(proxy);
+ proxy.matrixAutoUpdate=false;proxy.frustumCulled=false;proxy.name='FireDepthProxy';
+ proxies.set(source,proxy);scene.add(proxy);
+ }
+ source.updateWorldMatrix(true,false);proxy.visible=true;proxy.geometry=source.geometry;proxy.material=material;
+ proxy.layers.mask=source.layers.mask;
+ proxy.matrix.copy(source.matrixWorld);proxy.matrixWorld.copy(source.matrixWorld);
+ if(source.morphTargetInfluences)proxy.morphTargetInfluences=source.morphTargetInfluences.slice();
+ if(proxy.isInstancedMesh){
+ if(proxy.instanceMatrix.count<source.instanceMatrix.count){
+ proxy.dispose();proxy.instanceMatrix=new THREE.InstancedBufferAttribute(new Float32Array(source.instanceMatrix.array.length),16);
+ }
+ proxy.instanceMatrix.array.set(source.instanceMatrix.array);proxy.instanceMatrix.needsUpdate=true;
+ proxy.count=Math.min(source.count,source.instanceMatrix.count);
+ }
+ });
+ }
+ return {
+ capture(renderer,camera,viewport){
+ if(disposed)throw new Error('Disposed fire depth capture');
+ sync();
+ const scale=resolution/Math.max(viewport.z,viewport.w);
+ const width=Math.max(1,Math.round(viewport.z*scale)),height=Math.max(1,Math.round(viewport.w*scale));
+ if(!target){
+ target=new THREE.WebGLRenderTarget(width,height,{minFilter:THREE.NearestFilter,magFilter:THREE.NearestFilter});
+ target.depthTexture=new THREE.DepthTexture(width,height,THREE.UnsignedIntType);
+ target.depthTexture.minFilter=target.depthTexture.magFilter=THREE.NearestFilter;
+ }else if(target.width!==width||target.height!==height)target.setSize(width,height);
+ withRendererState(renderer,()=>{
+ renderer.xr.enabled=false;renderer.shadowMap.autoUpdate=false;renderer.toneMapping=THREE.NoToneMapping;
+ renderer.setRenderTarget(target);renderer.setScissorTest(false);renderer.setClearColor(0xffffff,1);
+ renderer.clear(true,true,true);renderer.render(scene,camera);
+ });
+ captures++;return target.depthTexture;
+ },
+ get captures(){return captures;},
+ get target(){return target;},
+ dispose(){if(disposed)return;disposed=true;target?.dispose();
+ materials.forEach(m=>m.dispose());invisible.dispose();ownedInstances.forEach(m=>m.dispose());
+ proxies.clear();materials.clear();ownedInstances.clear();scene.clear();},
+ };
+}
+
+export function makeFireField(opts = {}) {
+ const input=opts.emitters??[{position:[0,0,0],radius:.3,height:1,strength:1}];
+ if(!Array.isArray(input)||input.length<1||input.length>16)throw new RangeError('makeFireField: needs1–16 emitters');
+ const emitters=input.map((e,i)=>({position:vector(e.position,[0,0,0],3,`emitter${i} position`),
+ radius:number(e.radius,.3,.025,8,'emitter radius'),height:number(e.height,1,.08,25,'emitter height'),
+ strength:number(e.strength,1,0,4,'emitter strength')}));
+ const activeEmitters=emitters.filter(e=>e.strength>0);
+ const sources=activeEmitters.length?activeEmitters:[emitters[0]];
+ const seed=number(opts.seed,7,-2147483648,2147483647,'seed');
+ if(!Number.isInteger(seed))throw new RangeError('makeFireField: seed must be an integer');
+ const quality=opts.quality??'balanced';if(!Object.hasOwn(TIERS,quality))throw new RangeError('makeFireField: invalid quality');
+ const tier=TIERS[quality],wind=vector(opts.wind,[.12,0],2,'wind');
+ if(wind.some(v=>Math.abs(v)>8))throw new RangeError('makeFireField: wind exceeds8m/s');
+ const intensity=number(opts.intensity,1,0,8,'intensity'),turbulence=number(opts.turbulence,1,0,2,'turbulence');
+ const radius=sources.reduce((s,e)=>s+e.radius,0)/sources.length;
+ const height=Math.max(...sources.map(e=>e.height)),rise=number(opts.riseSpeed,.75+Math.sqrt(height)*.75,.1,12,'riseSpeed');
+ const smoke=opts.smoke===false?{density:0}:opts.smoke??{};
+ const smokeHeight=number(smoke.height,height*3,Math.max(.1,height),80,'smoke height');
+ const smokeDensity=number(smoke.density,.65,0,5,'smoke density');
+ const warp=Math.max(.025,Math.sqrt(radius)*.25),box=new THREE.Box3();
+ for(const e of sources){
+ const top=smokeDensity>0?Math.max(e.height*1.1,smokeHeight):e.height*1.1;
+ const spread=smokeDensity>0?e.radius*.7+smokeHeight*.23:e.radius*1.4;
+ const reach=Math.max(e.radius*(1.35+.85*turbulence),spread)+warp*1.5*turbulence;
+ box.expandByPoint(new THREE.Vector3(e.position[0]-reach+Math.min(0,wind[0]*top/rise),e.position[1],e.position[2]-reach+Math.min(0,wind[1]*top/rise)));
+ box.expandByPoint(new THREE.Vector3(e.position[0]+reach+Math.max(0,wind[0]*top/rise),e.position[1]+top+warp*.3,e.position[2]+reach+Math.max(0,wind[1]*top/rise)));
+ }
+ const flameBox=new THREE.Box3();
+ for(const e of sources){const top=e.height*1.12,reach=e.radius*(1.35+.85*turbulence)+warp*1.5*turbulence;
+ flameBox.expandByPoint(new THREE.Vector3(e.position[0]-reach+Math.min(0,wind[0]*top/rise),e.position[1],e.position[2]-reach+Math.min(0,wind[1]*top/rise)));
+ flameBox.expandByPoint(new THREE.Vector3(e.position[0]+reach+Math.max(0,wind[0]*top/rise),e.position[1]+top+warp*.3,e.position[2]+reach+Math.max(0,wind[1]*top/rise)));
+ }
+ const size=box.getSize(new THREE.Vector3());
+ if(Math.max(size.x,size.y,size.z)>120)throw new RangeError('makeFireField: emitter field exceeds120m');
+ const noise=noiseTexture(seed),atlas=sourceAtlas(emitters,box,tier.resolution,smokeHeight,wind,rise,seed);
+ const emptyDepth=new THREE.DataTexture(new Uint8Array([255,255,255,255]),1,1);emptyDepth.needsUpdate=true;
+ const roots=opts.occluders??[];
+ if(!Array.isArray(roots)||roots.some(o=>!o?.isObject3D))throw new TypeError('makeFireField: occluders must be Object3D roots');
+ const depthResolution=number(opts.depthResolution,512,64,2048,'depthResolution');
+ if(!Number.isInteger(depthResolution))throw new RangeError('makeFireField: depthResolution must be integer');
+ const depth=roots.length?depthCapture(roots.slice(),depthResolution):null;
+ const lighting=opts.lighting===false?{count:0}:opts.lighting??{};
+ const requestedLights=number(lighting.count,Math.min(2,activeEmitters.length),0,4,'light count');
+ const lightCount=Math.min(requestedLights,activeEmitters.length);
+ if(!Number.isInteger(requestedLights))throw new RangeError('makeFireField: light count must be integer');
+ const lightIntensity=number(lighting.intensity,12*radius/.3,0,20000,'light intensity');
+ const uniforms={
+ uTime:{value:0},uSourceAtlas:{value:atlas},uFieldNoise:{value:noise},uOpaqueDepth:{value:emptyDepth},
+ uBoxMin:{value:box.min.clone()},uBoxSize:{value:size.clone()},
+ uFlameBoxMin:{value:flameBox.min.clone()},uFlameBoxSize:{value:flameBox.getSize(new THREE.Vector3())},uViewport:{value:new THREE.Vector4(0,0,1,1)},
+ uViewToLocal:{value:new THREE.Matrix4()},uInverseProjection:{value:new THREE.Matrix4()},
+ uLocalToClip:{value:new THREE.Matrix4()},uLocalToWorld:{value:new THREE.Matrix3()},
+ uSunLocal:{value:new THREE.Vector3(0,1,0)},uSunColor:{value:new THREE.Color(0)},uAmbient:{value:new THREE.Color(.03,.03,.04)},
+ uSootAlbedo:{value:new THREE.Color(smoke.albedo??0x514942)},uCoarseScale:{value:Math.max(.3,Math.sqrt(radius)*.7)},
+ uWarp:{value:warp},uRise:{value:rise},uTurbulence:{value:turbulence},uIntensity:{value:intensity},
+ uFlameExtinction:{value:1.3/Math.sqrt(radius)},uSootExtinction:{value:smokeDensity},uUseOpaqueDepth:{value:0},
+ uFireLightCount:{value:lightCount},uFireLights:{value:Array.from({length:4},()=>new THREE.Vector4())},
+ uFireLightColor:{value:new THREE.Color(0xff973d)},
+ };
+ const group=new THREE.Group();group.name=opts.name??'FireField';
+ const geometry=new THREE.BoxGeometry(size.x,size.y,size.z);geometry.translate(...box.getCenter(new THREE.Vector3()).toArray());
+ const material=fieldMaterial(uniforms,tier);material.userData.bloom=true;
+ const volume=new THREE.Mesh(geometry,material);volume.name='SharedFlameSootVolume';volume.renderOrder=2;volume.visible=activeEmitters.length>0;
+ keepOutOfDepthPasses(volume);group.add(volume);
+ const inverse=new THREE.Matrix4(),sunPosition=new THREE.Vector3(),sunTarget=new THREE.Vector3(),sunDirection=new THREE.Vector3(),ambientColor=new THREE.Color();
+ const guard=volume.onBeforeRender;
+ volume.onBeforeRender=function(renderer,scene,camera,geo,mat,...rest){
+ guard.call(this,renderer,scene,camera,geo,mat,...rest);
+ if(mat!==material||scene.overrideMaterial)return;
+ inverse.copy(volume.matrixWorld).invert();
+ uniforms.uInverseProjection.value.copy(camera.projectionMatrixInverse);
+ uniforms.uViewToLocal.value.multiplyMatrices(inverse,camera.matrixWorld);
+ uniforms.uLocalToClip.value.copy(camera.projectionMatrix).multiply(camera.matrixWorldInverse).multiply(volume.matrixWorld);
+ uniforms.uLocalToWorld.value.setFromMatrix4(volume.matrixWorld);
+ renderer.getCurrentViewport(uniforms.uViewport.value);
+ uniforms.uSunColor.value.setRGB(0,0,0);uniforms.uAmbient.value.setRGB(0,0,0);let strongest=0;
+ scene.traverseVisible(o=>{
+ if(o.isDirectionalLight&&o.intensity>strongest){strongest=o.intensity;
+ o.getWorldPosition(sunPosition);o.target.getWorldPosition(sunTarget);sunDirection.copy(sunPosition).sub(sunTarget).normalize();
+ uniforms.uSunLocal.value.copy(sunDirection).transformDirection(inverse);
+ uniforms.uSunColor.value.copy(o.color).multiplyScalar(o.intensity*.20);
+ }else if(o.isAmbientLight||o.isHemisphereLight)uniforms.uAmbient.value.add(ambientColor.copy(o.color).multiplyScalar(o.intensity*.15));
+ });
+ if(scene.environment)uniforms.uAmbient.value.addScalar(.035);
+ if(depth){
+ if(renderer.capabilities.logarithmicDepthBuffer)throw new Error('makeFireField: occluder depth requires non-logarithmic depth');
+ uniforms.uOpaqueDepth.value=depth.capture(renderer,camera,uniforms.uViewport.value);
+ uniforms.uUseOpaqueDepth.value=1;
+ }
+ };
+ const lights=[];
+ const ranked=activeEmitters.map((e,i)=>({e,i,weight:e.radius*e.radius*e.strength})).sort((a,b)=>b.weight-a.weight);
+ for(let i=0;i<lightCount;i++){
+ const e=ranked[Math.floor(i*ranked.length/lightCount)].e;
+ const light=new THREE.PointLight(0xff973d,lightIntensity,0,2);light.name=`FireFieldLight_${i}`;
+ light.position.fromArray(e.position);light.position.y+=e.height*.24;light.userData.sourceStrength=e.strength;group.add(light);lights.push(light);
+ }
+ const emberOptions=opts.embers===false?{count:0}:opts.embers??{};
+ const requestedEmbers=number(emberOptions.count,48,0,512,'ember count');
+ const count=activeEmitters.length?requestedEmbers:0;
+ if(!Number.isInteger(requestedEmbers))throw new RangeError('makeFireField: ember count must be integer');
+ const emberSize=vector(emberOptions.size,[.0015,.006],2,'ember size');
+ const lifetime=vector(emberOptions.lifetime,[2,4],2,'ember lifetime');
+ if(emberSize[0]<=0||emberSize[1]<emberSize[0]||emberSize[1]>.12||lifetime[0]<=0||lifetime[1]<lifetime[0]||lifetime[1]>30)throw new RangeError('makeFireField: invalid ember size/lifetime');
+ const emberRise=number(emberOptions.riseSpeed,rise,.1,20,'ember rise speed');
+ const random=mulberry32(seed^0x1837),particles=Array.from({length:count},()=>{
+ const total=activeEmitters.reduce((sum,e)=>sum+e.radius*e.radius*e.strength,0);
+ let pick=random()*total,emitter=activeEmitters[activeEmitters.length-1];
+ for(const candidate of activeEmitters){pick-=candidate.radius*candidate.radius*candidate.strength;if(pick<=0){emitter=candidate;break;}}
+ return {emitter,phase:random(),life:THREE.MathUtils.lerp(...lifetime,random()),angle:random()*Math.PI*2,
+ offset:random()*.7,size:THREE.MathUtils.lerp(...emberSize,random())};
+ });
+ const dummy=new THREE.Object3D(),emberColor=new THREE.Color();let embers=null;
+ if(count){embers=new THREE.InstancedMesh(new THREE.SphereGeometry(1,5,3),new THREE.MeshBasicMaterial(),count);
+ embers.name='FieldEmbers';embers.frustumCulled=false;embers.instanceMatrix.setUsage(THREE.DynamicDrawUsage);group.add(embers);}
+ function sampleEmber(index,t){
+ if(!count)return null;const p=particles[clamp(index|0,0,count-1)],a=fract(t/p.life+p.phase),age=a*p.life;
+ const e=p.emitter,swirl=Math.sin(age*2.1+p.angle)*.07*age;
+ return {position:new THREE.Vector3(e.position[0]+Math.cos(p.angle)*e.radius*p.offset+wind[0]*age+swirl,
+ e.position[1]+.08+emberRise*age,e.position[2]+Math.sin(p.angle)*e.radius*p.offset+wind[1]*age+Math.cos(age*1.7+p.angle)*.07*age),
+ size:p.size*Math.pow(Math.sin(a*Math.PI),.6),age:a};
+ }
+ let disposed=false;
+ group.userData.update=group.userData.tick=(t=0)=>{
+ if(disposed)return;number(t,0,-1e9,1e9,'time');material.uniforms.uTime.value=t;
+ lights.forEach((light,i)=>{const flicker=.83+.10*Math.sin(t*(3.1+i*.47)+seed+i*2)+.07*Math.sin(t*7.3+seed*.7+i);
+ light.intensity=lightIntensity*flicker*intensity*light.userData.sourceStrength;
+ uniforms.uFireLights.value[i].set(light.position.x,light.position.y,light.position.z,light.intensity*.10);});
+ if(embers){embers.visible=intensity>0;for(let i=0;i<count;i++){
+ const p=sampleEmber(i,t);dummy.position.copy(p.position);dummy.scale.set(p.size,p.size*2.5,p.size);dummy.updateMatrix();
+ embers.setMatrixAt(i,dummy.matrix);emberColor.setRGB(5*(1-p.age*.82),.6*(1-p.age),.01).multiplyScalar(intensity);embers.setColorAt(i,emberColor);
+ }embers.instanceMatrix.needsUpdate=true;embers.instanceColor.needsUpdate=true;}
+ };
+ const atlasRead=p=>[0,1,2,3].map(c=>{
+ const uv=p.map((v,i)=>(v-box.min.getComponent(i))/size.getComponent(i));
+ return uv.some(v=>v<0||v>1)?0:sampleGrid3(atlas.image.data,tier.resolution,...uv.map(v=>v*tier.resolution-.5),4,c,false)/255;
+ });
+ const noiseRead=(p,c)=>sampleGrid3(noise.image.data,NOISE_RESOLUTION,...p.map(v=>v*NOISE_RESOLUTION-.5),4,c)/255;
+ group.userData.sampleField=(x,y,z,t=material.uniforms.uTime.value)=>{
+ if(![x,y,z,t].every(Number.isFinite))throw new RangeError('makeFireField: sample requires finite coordinates/time');
+ const p=[x,y,z],initial=atlasRead(p),coarseScale=uniforms.uCoarseScale.value;
+ const flow=p.map((v,i)=>v*(i===1?.13:.32)/coarseScale-(i===1?t*rise*.13/coarseScale:0)+initial[3]*.31);
+ const coarse=[0,1,2].map(c=>noiseRead(flow,c)),anchor=smooth(0,.22,initial[1]);
+ const warped=p.map((v,i)=>v+(coarse[i]-.5)*warp*(i===1?.38:1)*anchor*turbulence),field=atlasRead(warped);
+ const fine=noiseRead(p.map((v,i)=>v*(i===1?.75:2.6)-(i===1?t*rise*.75:0)+.197),1);
+ const surface=field[0]-.5+((coarse[1]-.5)*(.35+field[1]*.8)+(fine-.5)*.30)*turbulence;
+ const flame=smooth(-.025,.075,surface)*(1-smooth(.035,.22,surface)*.97)*smooth(0,.055,field[1])*(1-smooth(.90,1,field[1]))
+ *smooth(.21+field[1]*.20,.42+field[1]*.23,coarse[0]*.65+fine*.35);
+ const soot=field[2]*Math.pow(clamp(.68+(coarse[0]-.5)*2.4+(fine-.5)*.55,0,1.6),1.3);
+ return {flame,soot,temperature:clamp(.18+flame*.57+coarse[2]*.15-field[1]*.18)};
+ };
+ const bounds=box.clone();
+ if(count)for(const e of sources){const age=lifetime[1],travel=.07*age+emberSize[1]*3;
+ bounds.expandByPoint(new THREE.Vector3(e.position[0]-e.radius*.7+Math.min(0,wind[0]*age)-travel,e.position[1],e.position[2]-e.radius*.7+Math.min(0,wind[1]*age)-travel));
+ bounds.expandByPoint(new THREE.Vector3(e.position[0]+e.radius*.7+Math.max(0,wind[0]*age)+travel,e.position[1]+.08+emberRise*age+travel,e.position[2]+e.radius*.7+Math.max(0,wind[1]*age)+travel));}
+ group.userData.bounds=bounds;group.userData.sampleEmber=sampleEmber;
+ group.userData.emitters=emitters.map(e=>({...e,position:e.position.slice()}));group.userData.quality=quality;
+ group.userData.cost={emitters:emitters.length,steps:tier.steps,lightSteps:tier.lightSteps,
+ textureBytes:atlas.image.data.byteLength+noise.image.data.byteLength,depthPass:!!depth};
+ group.userData.depthCapture=depth;
+ const owned=snapshotResources(group);[atlas,noise,emptyDepth,...lights].forEach(r=>owned.add(r));
+ if(depth)owned.add(depth);owned.add({dispose(){disposed=true;}});
+ attachDisposal(group,owned);group.userData.update(0);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.js
index c858f950..e9747ed8 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flock.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flock.js
@@ -30,6 +30,7 @@
*/
import * as THREE from 'three';
+import { attachDisposal, snapshotResources } from './lifecycle.js';
import { mulberry32 } from './noise.js';
import {
@@ -38,7 +39,36 @@ import {
} from './shader.js';
const _TAU = Math.PI * 2;
-const _MAX_PTS = 8; // the size of the shader's uPath array
+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) {
@@ -75,6 +105,8 @@ function _defaultPath(extent, height) {
* `size` wingspan in metres (default extent/20, clamped 0.35..2.4).
* @returns {THREE.Group} Named `Flock`, holding ONE instanced mesh,
* with `userData.tick(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);
@@ -103,9 +135,11 @@ export function makeFlock(opts = {}) {
const pts = (opts.path && opts.path.length >= 3
? opts.path.map((p) => readVec3(p))
: _defaultPath(extent, height)).slice(0, _MAX_PTS);
- // Uniform Catmull-Rom, closed: the same curve the shader evaluates,
- // so `speed` is honest metres per second rather than a loop rate.
- const curve = new THREE.CatmullRomCurve3(pts, true, 'catmullrom', 0.5);
+ // 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);
@@ -138,18 +172,14 @@ export function makeFlock(opts = {}) {
// `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 = new THREE.Box3().setFromPoints(curve.getPoints(64));
+ 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 path = [];
- for (let k = 0; k < _MAX_PTS; k++) {
- path.push(pts[Math.min(k, pts.length - 1)].clone());
- }
const mesh = new THREE.Mesh(geom, flockMaterial({
- path, n: pts.length, rate: speed / loop, size: size * 0.5,
+ path: route.texture, rate: speed / loop, size: size * 0.5,
beat, kind, color, sun, sunCol, skyCol,
}));
mesh.name = kind ? 'FlockFish' : 'FlockBirds';
@@ -159,7 +189,12 @@ export function makeFlock(opts = {}) {
const g = new THREE.Group();
g.name = 'Flock';
g.add(mesh);
- g.userData.tick = (t) => tickShaders(g, t);
+ 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);
}
@@ -169,7 +204,6 @@ function flockMaterial(o) {
name: 'Flock',
uniforms: {
uPath: { value: o.path },
- uPathN: { value: o.n },
uRate: { value: o.rate },
uSize: { value: o.size },
uBeat: { value: o.beat },
@@ -191,28 +225,16 @@ function flockMaterial(o) {
'attribute vec3 aCorner;',
'attribute vec3 iOff;',
'attribute vec4 iExtra;',
- 'uniform vec3 uPath[8];',
- 'uniform float uPathN; uniform float uRate;',
+ 'uniform sampler2D uPath;',
+ 'uniform float uRate;',
'uniform float uSize; uniform float uBeat; uniform float uKind;',
'uniform vec3 uColor; uniform vec3 uSun;',
- // Indexed by a loop counter, which is the one form of array
- // indexing every GLSL dialect here accepts.
- 'vec3 flockPt(float i) {',
- ' int idx = int(i + 0.5);',
- ' vec3 p = uPath[0];',
- ' for (int k = 0; k < 8; k++) { if (k == idx) p = uPath[k]; }',
- ' return p;',
- '}',
'vec3 flockPath(float u) {',
- ' float n = uPathN;',
- ' float s = fract(u) * n;',
+ ` float s = fract(u) * ${_PATH_SAMPLES.toFixed(1)};`,
' float i = floor(s), f = s - i;',
- ' vec3 p0 = flockPt(mod(i - 1.0, n)), p1 = flockPt(mod(i, n));',
- ' vec3 p2 = flockPt(mod(i + 1.0, n));',
- ' vec3 p3 = flockPt(mod(i + 2.0, n));',
- ' return 0.5 * (2.0 * p1 + (p2 - p0) * f',
- ' + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * f * f',
- ' + (3.0 * p1 - 3.0 * p2 + p3 - p0) * f * f * f);',
+ ` 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: [
@@ -265,14 +287,17 @@ function flockMaterial(o) {
// 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, -vec3(',
- ' modelViewMatrix[0][2], modelViewMatrix[1][2],',
- ' modelViewMatrix[2][2]))),',
+ ' 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: [
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flowers.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flowers.js
index d9955d29..c68eaff2 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flowers.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flowers.js
@@ -25,6 +25,7 @@
*/
import * as THREE from 'three';
+import { attachDisposal, snapshotResources } from './lifecycle.js';
import { windOf } from './grass.js';
import { patchTranslucency } from './finish.js';
@@ -68,6 +69,7 @@ const _KINDS = {
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.
@@ -80,6 +82,7 @@ const _KINDS = {
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
@@ -91,6 +94,7 @@ const _KINDS = {
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,
},
@@ -158,8 +162,8 @@ export function makeFlowers(opts = {}) {
g.name = opts.name || 'Flowers';
g.add(plantMesh(field, kind, extent, petal, wind, opts.sunDir,
opts.shadows === true));
- g.userData.tick = (t) => tickShaders(g, t);
- return g;
+ g.userData.update = g.userData.tick = (t) => tickShaders(g, t);
+ return attachDisposal(g, snapshotResources(g));
}
/**
@@ -197,7 +201,7 @@ function plantField(extent, density, height, kind, wind, ground, seed,
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 + head);
+ 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++;
@@ -234,6 +238,7 @@ function plantLattice(kind, count) {
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;
@@ -291,7 +296,7 @@ function plantMesh(field, kind, extent, petal, wind, sunDir,
const mat = new THREE.MeshStandardMaterial({
color: 0xffffff, roughness: 0.62, metalness: 0,
- side: THREE.DoubleSide, transparent: true, alphaTest: 0.08,
+ side: THREE.DoubleSide, transparent: false, alphaTest: 0.5, alphaToCoverage: false,
name: 'FlowerPlant',
});
patchStandard(mat, {
@@ -302,6 +307,7 @@ function plantMesh(field, kind, extent, petal, wind, sunDir,
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 },
@@ -322,23 +328,15 @@ function plantMesh(field, kind, extent, petal, wind, sunDir,
fragmentHead: PLANT_FRAGMENT_HEAD,
fragmentBody: PLANT_FRAGMENT,
});
- // A petal is thin and lit through, and this is the thin-leaf patch:
- // one albedo lift toward the light behind it, no third copy of it.
- // The tint stays close to the PETAL: light through a red petal comes
- // out red, and a lift halfway to warm white desaturates a scarlet
- // poppy to salmon on exactly the plants the sun is behind.
+ // 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,
+ sunDir: sunDir, strength: 0.42, power: 2.4, variance: 0,
tint: petal.clone().lerp(new THREE.Color(0xfff2d0), 0.26),
});
- // LAST in the chain, so it sees the transmitted lift as well as the
- // rim brightening. Both are multiplied onto an albedo that already
- // starts near paper on a white flower, and an albedo above 1 is not a
- // brighter petal — it is a petal with no shading left: the tone map
- // pins every pixel of it to the same white and the whole silhouette
- // goes to a paper cut-out. Measured on the daisy: 0.73 base * 1.4 rim
- // * 1.14 value + 0.20 transmitted = 1.36. The floor is the other end
- // of the same rule: a poppy's blotch is a deep bruise, not a hole.
+ // 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, '
@@ -356,39 +354,10 @@ function plantMesh(field, kind, extent, petal, wind, sunDir,
// 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);
- return cutDepthToSilhouette(mesh);
-}
-
-/**
- * Cut the shadow to the shape of the FLOWER, not of its cards.
- *
- * A petal is a rectangle that the fragment stage carves a petal out of,
- * and three's depth shader never sees that carving: measured on this
- * host, a shadowed daisy stamped thirteen hard slate parallelograms on
- * the ground and the patch read as litter dropped round the plants
- * rather than as shade. `patchStandard` writes a fragment body through
- * `<color_fragment>`, which the depth shader does not have — the whole
- * hook is silently dropped there — so the same cut is spliced in above
- * three's own alpha test, which is the one place a depth pass may
- * discard. The uniform map is the surface's own (`shadowLike` shares
- * it), so the profile the shadow is cut by is the profile that is drawn.
- */
-function cutDepthToSilhouette(mesh) {
- const dep = mesh.customDepthMaterial;
- const compile = dep.onBeforeCompile;
- dep.onBeforeCompile = (shader, renderer) => {
- compile(shader, renderer);
- shader.fragmentShader = [
- 'uniform vec2 uFlowProf;',
- 'varying vec4 vFlow;',
- PLANT_PROFILE,
- shader.fragmentShader.replace(
- '#include <alphatest_fragment>',
- PLANT_DEPTH_CUT + '\n#include <alphatest_fragment>'),
- ].join('\n');
- };
- dep.needsUpdate = true;
+ 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;
}
@@ -399,6 +368,7 @@ const PLANT_VERTEX_HEAD = [
'uniform float uFlowBend;',
'uniform float uFlowNod;',
'uniform float uFlowSpike;',
+ 'uniform vec3 uFlowLeaf;',
'uniform float uFlowStep;',
'uniform float uFlowElev;',
'uniform float uFlowCurl;',
@@ -455,6 +425,7 @@ const PLANT_VERTEX = [
// 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;',
@@ -462,7 +433,25 @@ const PLANT_VERTEX = [
// 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 < 0.5) {',
+ ' 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);',
@@ -503,7 +492,7 @@ const PLANT_VERTEX = [
// 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);',
+ ' vNormal = normalize(normalMatrix * -flUp);',
'#endif',
' } else {',
// Lifted off the head plane by its own openness, curled along its
@@ -526,7 +515,7 @@ const PLANT_VERTEX = [
' + 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(flDu, flDs)));',
+ ' vNormal = normalize(normalMatrix * normalize(cross(flDs, flDu)));',
'#endif',
' }',
' }',
@@ -553,9 +542,9 @@ const PLANT_PROFILE = [
// 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) {',
+ ' 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) {',
+ ' } else if (vFlow.x > 0.5 && vFlow.x < 1.5) {',
' if (abs(vFlow.z) > flowProfile(vFlow.y, uFlowProf)) discard;',
' }',
].join('\n');
@@ -576,7 +565,13 @@ const PLANT_FRAGMENT_HEAD = [
const PLANT_FRAGMENT = [
' vec3 flCol;',
' float flA = 1.0;',
- ' if (vFlow.x < 0.5) {',
+ ' 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));',
@@ -600,9 +595,9 @@ const PLANT_FRAGMENT = [
' 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 goes both PALER and more transparent.
+ // reflecting it, so it grows paler. Alpha supplies silhouette coverage.
' float flCore = 1.0 - smoothstep(0.45, 1.0, flD);',
- ' flA = flM * (0.34 + 0.66 * flCore);',
+ ' 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.
@@ -767,7 +762,7 @@ export function makeFalling(opts = {}) {
const g = new THREE.Group();
g.name = opts.name || 'Falling';
g.add(keepOutOfDepthPasses(mesh));
- g.userData.tick = (t) => tickShaders(g, t);
+ 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 * fal[k * 4] * t) % drop;
@@ -778,14 +773,14 @@ export function makeFalling(opts = {}) {
_wrap(pos[k * 3 + 2] + drift.y * t, lim)
+ wob * wobZ(swing[k * 4 + 2], swing[k * 4 + 3], t));
};
- return g;
+ 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: true, alphaTest: 0.08,
+ 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
@@ -920,7 +915,7 @@ const FALL_FRAGMENT = [
' 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 goes paler AND more transparent.
+ // 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
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/foliage_shade.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/foliage_shade.js
index 79da9db0..dcfa05a8 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/foliage_shade.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/foliage_shade.js
@@ -65,36 +65,20 @@ function addPatch(material, part) {
/**
* Backlit leaves glow — the strongest single cue that a tree is alive.
*
- * One transmission term: light arriving from BEHIND the surface and
- * scattering out toward the eye. It is clamped at zero, so the crown
- * lifts only where the camera looks into the sun through it and a
- * front-lit leaf is left exactly as it was. The term rides on the
- * ALBEDO, the one hook `patchStandard` gives the fragment stage, so a
- * backlit leaf lightens toward `tint` instead of emitting on its own.
- *
- * Before the glow goes on, the PIGMENT is broken up. A crown built from
- * one material is one flat green over every leaf it owns, and a flat
- * green is the tell that says "geometry": a real canopy runs warm
- * yellow-green where new growth caught the sun and cool blue-green in
- * the mass behind it, at clump scale and again a metre down. The break
- * is `astraHueBreak` at two scales plus a value swing on the coarser
- * one's own field — so the transmission lands on a varied albedo
- * instead of washing a single tone paler. Measured on the showcase
- * pair: the crown's hue spread went 27 -> 35 degrees close in, 35 -> 45
- * at 20 m, and the share of it sitting in one value bin fell from 0.49
- * (no patch) to 0.30.
+ * Transmission uses the first directional light's radiance and shadow map.
+ * It vanishes when that light is off or occluded. A broad back-surface term
+ * and a narrower forward-scattering lobe reveal thin leaves without raising
+ * their albedo. Pigment variation remains a separate material treatment.
*
* @param {THREE.Material} material Leaf material, patched in place.
* @param {object} [opts] `sunDir` (THREE.Vector3) direction TOWARD the
- * sun — the same vector as the sun light's position, because the term
- * asks whether the eye is looking into it (default a day sun, well
- * above the horizon); at night pass the rig's `lightDir` (the moon),
- * never its `sunDir`, which points under the ground; `tint`
+ * sun; optional direction override, otherwise the first scene directional
+ * light supplies the direction. At night use the moon's direction; `tint`
* (THREE.Color) the transmitted colour, the warm yellow-green a leaf
* turns when lit through; `light` (THREE.Color) the key light's own
* colour, multiplied into that tint so a golden or moonlit rig
* transmits its own light rather than a hardcoded noon (default
- * white); `strength` (default 0.55) how far it lifts the albedo;
+ * white); `strength` (default 0.55) transmitted-light amount;
* `power` (default 3) how tight the lobe is around the sun — lower
* spreads the glow wider off axis; `variance` (default 0.6) the
* pigment swing, 0 to leave the albedo alone; `varyScale` (default 1)
@@ -116,6 +100,7 @@ export function patchLeafSSS(material, opts = {}) {
name: 'leaf',
uniforms: {
uLeafSun: { value: sun },
+ uLeafExplicit: { value: opts.sunDir ? 1 : 0 },
uLeafTint: { value: tint },
uLeafAmt: { value: strength },
uLeafPow: { value: power },
@@ -124,6 +109,7 @@ export function patchLeafSSS(material, opts = {}) {
},
fragmentHead: [
'uniform vec3 uLeafSun;',
+ 'uniform float uLeafExplicit;',
'uniform vec3 uLeafTint;',
'uniform float uLeafAmt;',
'uniform float uLeafPow;',
@@ -159,19 +145,31 @@ export function patchLeafSSS(material, opts = {}) {
' float lVar = clamp((astraFbm2(lP * 0.55 * uLeafVarS, 2)',
' - 0.375) * 2.6, -1.0, 1.0);',
' diffuseColor.rgb *= 1.0 + uLeafVar * 0.5 * lVar;',
- ' vec3 lV = normalize(cameraPosition - vAstraFol);',
- ' float lB = max(dot(lV, -uLeafSun), 0.0);',
- ' float lT = uLeafAmt * pow(lB, uLeafPow);',
- // A crown is not a lamp: what reaches the eye is dappled by how
- // much leaf mass the light crossed, which also leaves
- // neighbouring trees uncorrelated. Two scales — the gaps between
- // clumps, and the leaves themselves — because one makes the glow
- // a soft blob and both make it sparkle.
- ' lT *= 0.42 + 0.72 * astraFbm2(vAstraFol.xz * 1.7 + vAstraFol.y,'
- + ' 3)',
- ' + 0.36 * astraFbm2(vAstraFol.xz * 7.3 - vAstraFol.y * 3.1,'
- + ' 2);',
- ' diffuseColor.rgb += uLeafTint * lT;',
+ // Thin-leaf transmission is incident light, not an albedo multiplier.
+ // The first directional light supplies irradiance and shadow visibility;
+ // a supplied sunDir overrides only the lobe direction for older callers.
+ ' #if NUM_DIR_LIGHTS > 0',
+ ' vec3 lV = normalize(vViewPosition);',
+ ' vec3 lSun = normalize(mix(directionalLights[0].direction,',
+ ' mat3(viewMatrix) * uLeafSun, uLeafExplicit));',
+ ' #ifdef FLAT_SHADED',
+ ' vec3 lN = normalize(cross(dFdx(-vViewPosition), dFdy(-vViewPosition)));',
+ ' #else',
+ ' vec3 lN = normalize(vNormal);',
+ ' #endif',
+ ' lN *= dot(lN, lV) < 0.0 ? -1.0 : 1.0;',
+ ' float lBack = max(-dot(lN, lSun), 0.0);',
+ ' float lForward = pow(max(dot(lV, -lSun), 0.0), uLeafPow);',
+ ' float lT = uLeafAmt * (0.65 * lBack + 0.35 * lForward);',
+ ' float lVisibility = 1.0;',
+ ' #if defined(USE_SHADOWMAP) && NUM_DIR_LIGHT_SHADOWS > 0',
+ ' lVisibility = getShadow(directionalShadowMap[0], directionalLightShadows[0].shadowMapSize,',
+ ' directionalLightShadows[0].shadowIntensity, directionalLightShadows[0].shadowBias,',
+ ' directionalLightShadows[0].shadowRadius, vDirectionalShadowCoord[0]);',
+ ' #endif',
+ ' totalEmissiveRadiance += uLeafTint * lT * directionalLights[0].color',
+ ' * lVisibility * sqrt(max(diffuseColor.rgb, vec3(0.0))) * 0.5;',
+ ' #endif',
].join('\n'),
});
}
@@ -233,7 +231,19 @@ export function patchWind(material, opts = {}) {
// direction is carried into the plant's own frame — a scatter
// gives every instance a different yaw.
' vec3 wD = astraFolLocalDir(vec3(uWindDir.x, 0.0, uWindDir.y));',
+ ' float wDerivative = transformed.y > 0.0 && transformed.y < uWindH',
+ ' ? 2.0 * uWindAmp * wB * wS / max(uWindH, 1e-3) : 0.0;',
' transformed += wD * (uWindAmp * wB * wB * wS);',
+ ' #ifndef FLAT_SHADED',
+ ' mat3 wJacobian = mat3(vec3(1.0, 0.0, 0.0),',
+ ' vec3(0.0, 1.0, 0.0) + wD * wDerivative, vec3(0.0, 0.0, 1.0));',
+ ' vec3 wN = astraNormalTransform(wJacobian, objectNormal);',
+ ' #ifdef USE_INSTANCING',
+ ' wN = astraNormalTransform(mat3(instanceMatrix), wN);',
+ ' #endif',
+ ' transformedNormal = normalMatrix * wN;',
+ ' vNormal = normalize(transformedNormal);',
+ ' #endif',
].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.js
index ee9db7d1..8a03fd6b 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/godrays.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/godrays.js
@@ -29,6 +29,7 @@
*/
import * as THREE from 'three';
+import { attachDisposal, snapshotResources } from './lifecycle.js';
import { lehmer } from './noise.js';
import {
@@ -210,8 +211,8 @@ export function makeGodRays(opts = {}) {
}
g.add(moteMesh(shafts, dir, side, perp, width, color, air,
moteAmp, seed));
- g.userData.tick = (t) => tickShaders(g, t);
- return keepOutOfDepthPasses(g);
+ g.userData.update = g.userData.tick = (t) => tickShaders(g, t);
+ return attachDisposal(keepOutOfDepthPasses(g), snapshotResources(g));
}
/**
@@ -367,7 +368,7 @@ function shaftMaterial(dir, color, air, soft, gain, hazy) {
vertexMain: [
' vUv = uv;',
' vShaft = aShaft;',
- ' vN = normalize(normalMatrix * normal);',
+ ' vN = inverseTransformDirection(normalize(normalMatrix * normal), viewMatrix);',
' vW = (modelMatrix * vec4(transformed, 1.0)).xyz;',
].join('\n'),
fragmentHead: 'uniform vec3 uColor; uniform vec3 uAir;'
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/grass.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/grass.js
index 4acc5a46..44d7c78b 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/grass.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/grass.js
@@ -26,6 +26,7 @@
*/
import * as THREE from 'three';
+import { attachDisposal, snapshotResources } from './lifecycle.js';
import { fbm2, mulberry32 } from './noise.js';
import {
glslLocalDir, patchStandard, shadowLike, tickShaders, unit,
@@ -97,8 +98,8 @@ export function makeGrass(opts = {}) {
if (opts.sward !== false) {
g.add(swardMat(extent, density, lush, dry, clumpAt, ground));
}
- g.userData.tick = (t) => tickShaders(g, t);
- return g;
+ g.userData.update = g.userData.tick = (t) => tickShaders(g, t);
+ return attachDisposal(g, snapshotResources(g));
}
/**
@@ -244,9 +245,11 @@ function bladeMesh(field, extent, lush, dry, wind, shadows) {
low = Math.min(low, field.pos[i]);
high = Math.max(high, field.pos[i]);
}
+ // An arc stays inside its length about the root; include blade half-width.
+ const lateral = field.maxH * 1.10;
geom.boundingBox = new THREE.Box3(
- new THREE.Vector3(-extent / 2, low, -extent / 2),
- new THREE.Vector3(extent / 2, high + field.maxH, extent / 2));
+ new THREE.Vector3(-extent / 2 - lateral, low - field.maxH*.08, -extent / 2 - lateral),
+ new THREE.Vector3(extent / 2 + lateral, high + field.maxH*1.08, extent / 2 + lateral));
geom.boundingSphere = geom.boundingBox.getBoundingSphere(
new THREE.Sphere());
@@ -266,10 +269,9 @@ function bladeMesh(field, extent, lush, dry, wind, shadows) {
color: 0xffffff, roughness: 0.78, metalness: 0,
specularIntensity: 0.30,
side: THREE.DoubleSide, name: 'GrassBlade',
- // And the AO this host does not have: the reference ran GTAO over
- // the field, we have no post chain, and a blade standing in a
- // sward sees a slot of sky rather than a dome.
- envMapIntensity: 0.62,
+ // Shader-built blades do not appear in the host GTAO override pass.
+ // This modest sky occlusion complements the per-blade root treatment.
+ envMapIntensity: 0.80,
});
patchStandard(mat, {
name: 'grass:blade',
@@ -418,17 +420,10 @@ const BLADE_FRAGMENT = [
' grC = astraHueBreak(grC, vGrassW, 0.55, 0.62);',
// The sward is DEEP: a blade's base sits in the shade of its
// neighbours, and that gradient is most of what reads as grass.
- // Deeper than it looks, too — this host has no AO pass, so the
- // occlusion the reference got from GTAO has to live here or the
- // field has no dark interior at all (measured: p05 0.33 over the
- // field, against 0.08-0.15 in a photograph of one).
- // A POWER, not a smoothstep: a smoothstep that reaches the root is
- // already back at 0.9 by mid-blade, which is where most of the
- // field's pixels are, so the frame keeps none of it. Light falls
- // through a sward roughly as a power of the height, and 1.7 is what
- // put this field's fifth percentile in a photograph's range.
- ' float grDepth = pow(clamp(vGrass.x, 0.0, 1.0), 1.7);',
- ' grC *= 0.22 + 0.78 * grDepth;',
+ // These shader-built blades are absent from the host's AO override pass,
+ // so retain a root-occlusion approximation without crushing the mid-blade.
+ ' float grDepth = pow(clamp(vGrass.x, 0.0, 1.0), 1.25);',
+ ' grC *= 0.32 + 0.68 * grDepth;',
' grC += uGrassLush * 0.10 * smoothstep(0.68, 1.0, vGrass.x);',
// TRANSLUCENCY. A blade is a fraction of a millimetre of sap: with
// the sun behind it most of what reaches the eye came THROUGH it,
@@ -458,7 +453,13 @@ const BLADE_FRAGMENT = [
// field, it IS the light on the field, exactly as it is in the
// photograph. Weighted by the depth so the glow stops where the
// sward closes over: a field that glows to its roots is fog.
- ' totalEmissiveRadiance += directionalLights[0].color * grSap',
+ ' float grVisibility = 1.0;',
+ ' #if defined(USE_SHADOWMAP) && NUM_DIR_LIGHT_SHADOWS > 0',
+ ' grVisibility = getShadow(directionalShadowMap[0], directionalLightShadows[0].shadowMapSize,',
+ ' directionalLightShadows[0].shadowIntensity, directionalLightShadows[0].shadowBias,',
+ ' directionalLightShadows[0].shadowRadius, vDirectionalShadowCoord[0]);',
+ ' #endif',
+ ' totalEmissiveRadiance += directionalLights[0].color * grSap * grVisibility',
' * (0.75 * grThru * grBeam * grDepth * grDepth);',
'#endif',
'#endif',
@@ -545,11 +546,9 @@ function swardMat(extent, density, lush, dry, clumpAt, ground) {
' float swG = astraStroke(swU * uGrassGrain * 1.8, 0.10);',
' swCol *= 0.82 + 0.26 * swG;',
// The mat lies UNDER a canopy, so it is always in shade, and
- // deep grass swallows what thin dry ground bounces back. Deeper
- // here than the reference set it: with no AO pass on this host,
- // the mat IS the field's dark interior — everything a photograph
- // of a meadow has between the blades comes from this line.
- ' swCol *= 0.66 - 0.30 * swC;',
+ // deep grass swallows what thin dry ground bounces back. This
+ // approximation remains necessary for the shader-only blade field.
+ ' swCol *= 0.70 - 0.26 * swC;',
' diffuseColor.rgb = swCol;',
].join('\n'),
});
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ice.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ice.js
new file mode 100644
index 00000000..febedaad
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ice.js
@@ -0,0 +1,456 @@
+/** Fractured freshwater ice in metres.
+ *
+ * Each seeded floe is a closed, bevelled solid. Open fissures are geometry,
+ * not dark lines on a transparent plane. Three's physical transmission reads
+ * the opaque scene behind the volume; attenuation follows its local thickness.
+ * Frost changes transmission and roughness together. Trapped air is instanced
+ * inside the volume and therefore shifts relative to its surface with the view.
+ */
+import * as THREE from 'three';
+import { fbm2, mulberry32 } from './noise.js';
+import { patchStandard } from './shader.js';
+import { attachDisposal, snapshotResources } from './lifecycle.js';
+
+const clamp = (x, a, b) => Math.max(a, Math.min(b, x));
+const smooth = (a, b, value) => {
+ const t = clamp((value - a) / (b - a), 0, 1);
+ return t * t * (3 - 2 * t);
+};
+
+// Clip a convex XZ polygon by nx*x + nz*z <= limit.
+function clip(polygon, nx, nz, limit) {
+ const result = [];
+ for (let i = 0; i < polygon.length; i++) {
+ const a = polygon[i], b = polygon[(i + 1) % polygon.length];
+ const da = nx * a[0] + nz * a[1] - limit;
+ const db = nx * b[0] + nz * b[1] - limit;
+ if (da <= 1e-10) result.push(a);
+ if ((da < 0 && db > 0) || (da > 0 && db < 0)) {
+ const t = da / (da - db);
+ result.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]);
+ }
+ }
+ return result.filter((p, i) => {
+ const q = result[(i + result.length - 1) % result.length];
+ return !q || Math.hypot(p[0] - q[0], p[1] - q[1]) > 1e-8;
+ });
+}
+
+function inset(polygon, distance) {
+ const xs=polygon.map(p=>p[0]),zs=polygon.map(p=>p[1]);
+ const x0=Math.min(...xs),x1=Math.max(...xs),z0=Math.min(...zs),z1=Math.max(...zs);
+ let out = [[x0,z0],[x1,z0],[x1,z1],[x0,z1]];
+ for (let i = 0; i < polygon.length && out.length > 2; i++) {
+ const a = polygon[i], b = polygon[(i + 1) % polygon.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, nx * a[0] + nz * a[1] - distance);
+ }
+ return out;
+}
+
+function distanceToEdge(polygon, point) {
+ let distance = Infinity;
+ for (let i = 0; i < polygon.length; i++) {
+ const a = polygon[i], b = polygon[(i + 1) % polygon.length];
+ const dx = b[0] - a[0], dz = b[1] - a[1];
+ distance = Math.min(distance,
+ (dx * (point[1] - a[1]) - dz * (point[0] - a[0])) / Math.hypot(dx, dz));
+ }
+ return distance;
+}
+
+function opticalTexture(width, depth, thicknessAt, maximumThickness, frost, seed, cracks) {
+ const resolution = 512, data = new Uint8Array(resolution * resolution * 4);
+ for (let z = 0; z < resolution; z++) for (let x = 0; x < resolution; x++) {
+ const px = ((x + 0.5) / resolution - 0.5) * width;
+ const pz = ((z + 0.5) / resolution - 0.5) * depth;
+ const field = fbm2(px * 1.8, pz * 1.8, { seed: seed + 101, octaves: 3 });
+ const grain = fbm2(px * 24, pz * 24, { seed: seed + 303, octaves: 2 });
+ const cover = smooth(0.32 - frost * 0.62, 0.53 - frost * 0.62,
+ field + grain * 0.28) * Math.min(1, frost * 3);
+ const i = (z * resolution + x) * 4;
+ data[i] = Math.round((1 - cover * 0.96) * 255);
+ data[i + 1] = Math.round(clamp(thicknessAt(px, pz) / maximumThickness, 0, 1) * 255);
+ data[i + 2] = Math.round(clamp(0.5 + grain, 0, 1) * 255);
+ data[i + 3] = 0;
+ }
+ // Rasterize a sparse branching stress network in the same metric domain
+ // as the volume. Coverage stores subtexel line width, then mipmaps filter
+ // it further. These arrested hairlines terminate inside a solid floe.
+ for (const [a, b] of cracks) {
+ const ax=(a[0]/width+.5)*resolution, ay=(a[1]/depth+.5)*resolution;
+ const bx=(b[0]/width+.5)*resolution, by=(b[1]/depth+.5)*resolution;
+ const dx=bx-ax,dy=by-ay,length2=dx*dx+dy*dy;
+ const steps=Math.max(1,Math.ceil(Math.sqrt(length2)*1.5));
+ const coverage=Math.min(1,0.0025*resolution/Math.sqrt(width*depth));
+ for(let i=0;i<=steps;i++) {
+ const x=ax+dx*i/steps,y=ay+dy*i/steps;
+ for(let oy=-1;oy<=1;oy++)for(let ox=-1;ox<=1;ox++) {
+ const px=Math.floor(x)+ox,py=Math.floor(y)+oy;
+ if(px<0||py<0||px>=resolution||py>=resolution)continue;
+ const t=clamp(((px+.5-ax)*dx+(py+.5-ay)*dy)/Math.max(length2,1e-9),0,1);
+ const distance=Math.hypot(px+.5-ax-t*dx,py+.5-ay-t*dy);
+ const index=(py*resolution+px)*4+3;
+ data[index]=Math.max(data[index],Math.round(Math.max(0,1-distance)*coverage*255));
+ }
+ }
+ }
+ const texture = new THREE.DataTexture(data, resolution, resolution);
+ texture.colorSpace = THREE.NoColorSpace;
+ texture.magFilter = THREE.LinearFilter;
+ texture.minFilter = THREE.LinearMipmapLinearFilter;
+ texture.generateMipmaps = true;
+ texture.anisotropy = 8;
+ texture.needsUpdate = true;
+ return texture;
+}
+
+function iceMaterial(opts, optical, maximumThickness) {
+ const material = new THREE.MeshPhysicalMaterial({
+ color: opts.color ?? 0xc9e7ed,
+ roughness: clamp(opts.roughness ?? 0.075, 0.015, 1),
+ metalness: 0, ior: 1.31,
+ transmission: clamp(opts.transmission ?? 0.98, 0, 1),
+ transmissionMap: optical,
+ thickness: maximumThickness,
+ attenuationColor: new THREE.Color(opts.attenuationColor ?? 0x80c8d5),
+ attenuationDistance: Math.max(0.02, opts.attenuationDistance ?? 1.8),
+ envMapIntensity: opts.envMapIntensity ?? 1,
+ });
+ material.name = 'FracturedFreshwaterIce';
+ patchStandard(material, {
+ name: 'ice:volume',
+ uniforms: {
+ uIceOptical: { value: optical },
+ uIceSeed: { value: (opts.seed ?? 47) % 997 },
+ uIceFrost: { value: clamp(opts.frost ?? 0.35, 0, 1) },
+ },
+ vertexHead: 'attribute float aIceEdge, aIcePath, aIceChip;\nvarying vec3 vIceLocal;\nvarying vec3 vIceFace;\nvarying vec2 vIceUV;\nvarying float vIceEdge, vIcePath, vIceChip;',
+ vertexBody: 'vIceLocal = position; vIceFace = normal; vIceUV = uv; vIceEdge = aIceEdge; vIcePath = aIcePath; vIceChip = aIceChip;',
+ fragmentHead: `
+ uniform sampler2D uIceOptical;
+ uniform float uIceSeed, uIceFrost;
+ varying vec3 vIceLocal, vIceFace;
+ varying vec2 vIceUV;
+ varying float vIceEdge, vIcePath, vIceChip;
+ vec3 iceSurfaceBump(vec3 eye, vec3 n, float height) {
+ vec3 dx = dFdx(eye), dy = dFdy(eye);
+ vec3 a = cross(dy, n), b = cross(n, dx);
+ float determinant = dot(dx, a);
+ if (abs(determinant) < 1e-12) return n;
+ return normalize(abs(determinant) * n - sign(determinant)
+ * (dFdx(height) * a + dFdy(height) * b));
+ }
+ `,
+ fragmentBody: `
+ vec4 iceOptical = texture2D(uIceOptical, vIceUV);
+ float iceTop = smoothstep(0.3, 0.9, normalize(vIceFace).y);
+ float iceFrost = clamp((1.0 - iceOptical.r) / 0.96, 0.0, 1.0) * iceTop;
+ float iceEdge = 1.0 - smoothstep(0.006, 0.04, vIceEdge);
+ float iceRime = iceEdge * iceTop * uIceFrost * 0.28;
+ float iceCover = max(max(iceFrost, iceRime), vIceChip * 0.72);
+ float iceFaceFade = 1.0 - smoothstep(0.35, 1.2, length(fwidth(vIceLocal)) * 110.0);
+ float iceFaceGrain = mix(0.5, astraNoise2(vec2(vIceLocal.x + vIceLocal.z,
+ vIceLocal.y * 0.85) * 110.0), iceFaceFade);
+ float iceFracture = (1.0 - abs(normalize(vIceFace).y)) * 0.24;
+ float iceHairline = iceOptical.a * iceTop;
+ iceCover = max(iceCover, iceHairline * 0.85);
+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.77, 0.84, 0.85), iceCover);
+ // Fine etched surface relief vanishes before it becomes a pixel grid.
+ vec2 iceP = mix(vec2(vIceLocal.x + vIceLocal.z, vIceLocal.y * 0.85),
+ vIceLocal.xz, iceTop) * 65.0 + uIceSeed;
+ float iceFineFade = 1.0 - smoothstep(0.25, 1.0, length(fwidth(iceP)));
+ float iceFine = astraNoise2(iceP) * iceFineFade;
+ float iceHeight = iceCover * (0.0005 + iceFine * 0.0008)
+ + iceFine * 0.000025 + iceFracture * iceFaceGrain * 0.000015;
+ `,
+ roughnessBody: 'roughnessFactor = mix(roughnessFactor + iceFracture, 0.86, iceCover);',
+ normalBody: 'normal = iceSurfaceBump(-vViewPosition, normal, iceHeight);',
+ transmissionBody: `
+ material.thickness = max(0.001, vIcePath);
+ material.transmission = transmission * (1.0 - iceCover * 0.96) * (1.0 - iceFracture);
+ `,
+ });
+ return material;
+}
+
+/**
+ * A Group with a closed volume mesh and optional instanced trapped air.
+ * size number/[width,depth] (default [8,6]), thickness metres (.28),
+ * outline optional convex [[x,z],...] polygon inside size, crackDensity
+ * sites per square metre (.65, capped 180 sites), gap metres
+ * (.018), frost/bubbles/chipping 0..1 (.35/.45/.4), heave metres (0), seed (47),
+ * color/attenuationColor, attenuationDistance metres (1.8), roughness (.075).
+ *
+ * Nominal top is local y=0, bottom near -thickness; heave lifts and tilts
+ * individual floes. sampleHeight(x,z) returns the actual LOCAL upper triangle
+ * height, or null in an open fissure/outside the sheet. update(t,dt) is a
+ * static no-op; dispose() releases only construction-owned resources.
+ *
+ * Optical path is estimated from local thickness on the top and bottom,
+ * and floe width on fracture faces. It is not an exact volume exit trace.
+ * Physical transmission sees opaque scene objects. Transparent water and
+ * other transmissive volumes are not recursively ray traced by this renderer.
+ * A lakebed or opaque water backing supplies that view. Ice does not cast
+ * opaque shadows by default (castShadow:true explicitly opts in).
+ */
+export function makeFracturedIce(opts = {}) {
+ for (const key of ['gap', 'frost', 'bubbles', 'chipping', 'heave', 'seed', 'roughness',
+ 'transmission', 'attenuationDistance', 'envMapIntensity'])
+ if (opts[key] !== undefined && !Number.isFinite(opts[key]))
+ throw new RangeError(`ice ${key} must be finite`);
+ let outline = null;
+ if (opts.outline !== undefined) {
+ if (!Array.isArray(opts.outline) || opts.outline.length < 3 || opts.outline.length > 128
+ || !opts.outline.every(p => Array.isArray(p) && p.length === 2 && p.every(Number.isFinite)))
+ throw new RangeError('ice outline must contain 3..128 finite [x,z] points');
+ outline = opts.outline.map(p => [...p]);
+ const turns = outline.map((a, i) => {
+ const b = outline[(i + 1) % outline.length], c = outline[(i + 2) % outline.length];
+ return (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]);
+ });
+ if (!turns.every(t => t > 1e-10) && !turns.every(t => t < -1e-10))
+ throw new RangeError('ice outline must be strictly convex and ordered around its boundary');
+ if (turns[0] < 0) outline.reverse();
+ if (outline.some((a, i) => {
+ const b = outline[(i + 1) % outline.length];
+ return outline.some(p => (b[0] - a[0]) * (p[1] - a[1])
+ - (b[1] - a[1]) * (p[0] - a[0]) < -1e-10);
+ })) throw new RangeError('ice outline must not intersect itself');
+ }
+ const size = Array.isArray(opts.size) ? opts.size : opts.size !== undefined
+ ? [opts.size, opts.size] : outline
+ ? [2 * Math.max(...outline.map(p => Math.abs(p[0]))), 2 * Math.max(...outline.map(p => Math.abs(p[1])))]
+ : [8, 6];
+ if (size.length !== 2 || !size.every(value => Number.isFinite(value) && value > 0))
+ throw new RangeError('ice size must contain positive finite metres');
+ const [width, depth] = size;
+ if (outline?.some(p => Math.abs(p[0]) > width / 2 || Math.abs(p[1]) > depth / 2))
+ throw new RangeError('ice outline must lie inside the requested size');
+ const thickness = opts.thickness ?? 0.28;
+ if (!Number.isFinite(thickness) || thickness <= 0) throw new RangeError('ice thickness must be positive finite metres');
+ const seed = opts.seed ?? 47, rand = mulberry32(seed);
+ const density = opts.crackDensity ?? 0.65;
+ if (!Number.isFinite(density) || density < 0) throw new RangeError('ice crackDensity must be finite and nonnegative');
+ const count = clamp(Math.round(width * depth * density), 1, 180);
+ const gap = clamp(opts.gap ?? 0.018, 0,
+ Math.min(Math.min(width, depth) * 0.08, Math.sqrt(width * depth / count) * 0.2));
+ const frost = clamp(opts.frost ?? 0.35, 0, 1), heave = Math.max(0, opts.heave ?? 0);
+ const chipping = clamp(opts.chipping ?? 0.4, 0, 1);
+ const thicknessAt = (x, z) => thickness * (0.9
+ + fbm2(x * 0.72, z * 0.72, { seed: seed + 711, octaves: 3 }) * 0.5);
+ const maximumThickness = thickness * 1.3;
+ const sites = [];
+ // Stratification keeps the cells distributed without regular crack lines.
+ const columns = Math.max(1, Math.round(Math.sqrt(count * width / depth)));
+ const rows = Math.ceil(count / columns);
+ for (let i = 0; i < count; i++) sites.push([
+ ((i % columns + 0.12 + rand() * 0.76) / columns - 0.5) * width,
+ ((Math.floor(i / columns) + 0.12 + rand() * 0.76) / rows - 0.5) * depth,
+ ]);
+ // Some pressure fractures split an existing large plate. Keeping both
+ // broad floes and small chips avoids a uniformly sized paving pattern.
+ const cellScale = Math.sqrt(width * depth / count);
+ for (let i = 3; i < sites.length; i += 4) {
+ const anchor = sites[i - 2], angle = rand() * Math.PI * 2;
+ sites[i] = [clamp(anchor[0] + Math.cos(angle) * cellScale * 0.25, -width * 0.49, width * 0.49),
+ clamp(anchor[1] + Math.sin(angle) * cellScale * 0.25, -depth * 0.49, depth * 0.49)];
+ }
+ const boundaryCenter=outline ? outline.reduce((sum,p)=>[sum[0]+p[0]/outline.length,
+ sum[1]+p[1]/outline.length],[0,0]) : [0,0];
+ // One deformation for every shared point. Sampling an inset cell first,
+ // or scaling this by its radius, lets neighboring boundaries cross.
+ const deform=(x,z)=>{
+ const margin=Math.max(0,outline?distanceToEdge(outline,[x,z])
+ :Math.min(width/2-Math.abs(x),depth/2-Math.abs(z)));
+ const strength=Math.min(1,margin/.08)*Math.min(1,cellScale/.25);
+ const warpX=fbm2(x*2.2,z*2.2,{seed:seed+907,octaves:3})*.13
+ +fbm2(x*17,z*17,{seed:seed+813,octaves:2})*.014;
+ const warpZ=fbm2(x*2.2,z*2.2,{seed:seed+1009,octaves:3})*.13
+ +fbm2(x*17,z*17,{seed:seed+1213,octaves:2})*.014;
+ const chip=(1-Math.min(1,margin/.035))*(.002+Math.abs(warpX+warpZ)*.8)
+ *Math.min(1,cellScale/.25);
+ const length=Math.max(1e-9,Math.hypot(boundaryCenter[0]-x,boundaryCenter[1]-z));
+ return [x+warpX*strength+(boundaryCenter[0]-x)/length*chip,
+ z+warpZ*strength+(boundaryCenter[1]-z)/length*chip];
+ };
+ const position = [], uv = [], edge = [], path = [], chips = [], topTriangles = [], cells = [], cracks = [];
+ let opticalWidth = thickness, triangleChip = 0;
+ const vertex = (p, e, vertical) => {
+ position.push(...p); uv.push(p[0] / width + 0.5, p[2] / depth + 0.5); edge.push(e);
+ path.push(THREE.MathUtils.lerp(opticalWidth, thicknessAt(p[0], p[2]), vertical));
+ chips.push(triangleChip);
+ };
+ const triangle = (a, b, c, ea, eb, ec, top = false) => {
+ const normal = new THREE.Vector3().subVectors(new THREE.Vector3(...b), new THREE.Vector3(...a))
+ .cross(new THREE.Vector3().subVectors(new THREE.Vector3(...c), new THREE.Vector3(...a))).normalize();
+ const vertical = Math.abs(normal.y);
+ vertex(a, ea, vertical); vertex(b, eb, vertical); vertex(c, ec, vertical);
+ if (top) topTriangles.push([a, b, c]);
+ };
+ for (const [id, site] of sites.entries()) {
+ let polygon = outline || [[-width / 2, -depth / 2], [width / 2, -depth / 2],
+ [width / 2, depth / 2], [-width / 2, depth / 2]];
+ for (const other of sites) if (other !== site) {
+ const nx = other[0] - site[0], nz = other[1] - site[1];
+ polygon = clip(polygon, nx, nz,
+ (other[0] * other[0] + other[1] * other[1] - site[0] * site[0] - site[1] * site[1]) * 0.5);
+ }
+ const cellGap=gap*(0.38+rand()*.25);
+ if (polygon.length < 3) continue;
+ const center = polygon.reduce((sum, p) => [sum[0] + p[0] / polygon.length,
+ sum[1] + p[1] / polygon.length], [0, 0]);
+ let radius = distanceToEdge(polygon, center);
+ // A shared domain warp makes neighboring fracture sides interlock.
+ // Independent edge noise would overlap floes or widen cracks randomly.
+ const corners = polygon.map(p => [...p]), jagged = [];
+ for (let i = 0; i < polygon.length; i++) {
+ const a = polygon[i], b = polygon[(i + 1) % polygon.length];
+ const steps = clamp(Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / 0.065), 1, 48);
+ for (let j = 0; j < steps; j++) {
+ const x = a[0] + (b[0] - a[0]) * j / steps;
+ const z = a[1] + (b[1] - a[1]) * j / steps;
+ jagged.push(deform(x,z));
+ }
+ }
+ polygon = jagged;
+ // A point in every inward half-plane is in the polygon's visibility
+ // kernel. Shrinking toward it therefore stays inside the shared cell,
+ // even when a fracture boundary is concave. Tiny degenerate chips vanish.
+ const kernel=inset(polygon,0);
+ if(kernel.length<3)continue;
+ center[0]=kernel.reduce((sum,p)=>sum+p[0]/kernel.length,0);
+ center[1]=kernel.reduce((sum,p)=>sum+p[1]/kernel.length,0);
+ radius=distanceToEdge(polygon,center);
+ if(radius<1e-7)continue;
+ const shrink=Math.min(.45,cellGap/radius);
+ polygon=polygon.map(p=>[THREE.MathUtils.lerp(p[0],center[0],shrink),
+ THREE.MathUtils.lerp(p[1],center[1],shrink)]);
+ radius*=1-shrink;
+ opticalWidth = Math.max(thickness, radius * 1.7);
+ const bevel = Math.min(thickness * (0.015 + chipping * 0.10),
+ 0.003 + chipping * 0.025, radius * 0.055);
+ const lift = (rand() - 0.3) * heave;
+ const tiltX = (rand() - 0.5) * heave / Math.max(radius, 0.1) * 0.32;
+ const tiltZ = (rand() - 0.5) * heave / Math.max(radius, 0.1) * 0.32;
+ const topAt = p => lift + (p[0] - center[0]) * tiltX + (p[1] - center[1]) * tiltZ;
+ // Radial bevel retains a one-to-one ring topology even at acute corners.
+ const cuts=polygon.map(p=>.35+Math.abs(fbm2(p[0]*9,p[1]*9,{seed:seed+337,octaves:2}))*2.4);
+ const inner = polygon.map((p,i) => [p[0] + (center[0] - p[0]) * bevel * cuts[i] / radius,
+ p[1] + (center[1] - p[1]) * bevel * cuts[i] / radius]);
+ const top = inner.map(p => [p[0], topAt(p), p[1]]);
+ const rim = polygon.map((p,i) => [p[0], topAt(p) - bevel * cuts[i], p[1]]);
+ // Fracture planes widen and undercut at different depths. Every ring
+ // moves inward from the shared footprint, so neighboring solids fit.
+ const insetPoint=(p,i,amount)=>{
+ const move=Math.min(radius*.08,thickness*amount)*cuts[i];
+ return [p[0]+(center[0]-p[0])*move/radius,p[1]+(center[1]-p[1])*move/radius];
+ };
+ const mid = polygon.map((p,i)=>{const q=insetPoint(p,i,.09);
+ return [q[0],topAt(q)-thicknessAt(...q)*(.38+cuts[i]*.09),q[1]];});
+ const bottom = polygon.map((p,i)=>{const q=insetPoint(p,i,.04);
+ return [q[0],topAt(q)-thicknessAt(...q),q[1]];});
+ const ct = [center[0], topAt(center), center[1]];
+ const cb = [center[0], topAt(center) - thicknessAt(...center), center[1]];
+ for (let i = 0; i < polygon.length; i++) {
+ const j = (i + 1) % polygon.length;
+ triangleChip=0;
+ triangle(ct, top[j], top[i], radius, bevel, bevel, true);
+ triangle(cb, bottom[i], bottom[j], radius, 0, 0);
+ triangleChip=clamp(((cuts[i]+cuts[j])*.5-.65)*2.5,0,1)*chipping;
+ triangle(top[i], top[j], rim[j], bevel, bevel, 0, true);
+ triangle(top[i], rim[j], rim[i], bevel, 0, 0, true);
+ triangleChip*=.25;
+ triangle(rim[i], rim[j], mid[j], 0, 0, 0);
+ triangle(rim[i], mid[j], mid[i], 0, 0, 0);
+ triangleChip*=.3;
+ triangle(mid[i], mid[j], bottom[j], 0, 0, 0);
+ triangle(mid[i], bottom[j], bottom[i], 0, 0, 0);
+ }
+ cells.push({ id, polygon, center, topAt, radius });
+ for(let branch=0;branch<2;branch++) {
+ const start=corners[Math.floor(rand()*corners.length)];
+ const bend=[THREE.MathUtils.lerp(start[0],center[0],.45+rand()*.2),
+ THREE.MathUtils.lerp(start[1],center[1],.45+rand()*.2)];
+ const end=[THREE.MathUtils.lerp(start[0],center[0],.78+rand()*.13),
+ THREE.MathUtils.lerp(start[1],center[1],.78+rand()*.13)];
+ cracks.push([start,bend],[bend,end]);
+ const fork=corners[(corners.indexOf(start)+1)%corners.length];
+ cracks.push([bend,[THREE.MathUtils.lerp(bend[0],fork[0],.25),
+ THREE.MathUtils.lerp(bend[1],fork[1],.25)]]);
+ }
+ }
+ const geometry = new THREE.BufferGeometry();
+ geometry.setAttribute('position', new THREE.Float32BufferAttribute(position, 3));
+ geometry.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2));
+ geometry.setAttribute('aIceEdge', new THREE.Float32BufferAttribute(edge, 1));
+ geometry.setAttribute('aIcePath', new THREE.Float32BufferAttribute(path, 1));
+ geometry.setAttribute('aIceChip', new THREE.Float32BufferAttribute(chips, 1));
+ geometry.computeVertexNormals(); geometry.computeBoundingBox(); geometry.computeBoundingSphere();
+ const optical = opticalTexture(width, depth, thicknessAt, maximumThickness, frost, seed, cracks);
+ const volume = new THREE.Mesh(geometry, iceMaterial(opts, optical, maximumThickness));
+ volume.name = 'IceVolume'; volume.castShadow = opts.castShadow === true; volume.receiveShadow = true;
+ const group = new THREE.Group(); group.name = opts.name ?? 'FracturedIce';
+ group.userData.placement = volume.userData.placement = 'free';
+ group.add(volume);
+
+ // Flattened gas lenses occur in columns where bubbles rose before the
+ // water froze. Their depth is real geometry, not dots on the top texture.
+ const bubbles = clamp(opts.bubbles ?? 0.45, 0, 1);
+ const bubbleCount = clamp(Math.round(width * depth * bubbles * 11), 0, 4000);
+ if (bubbleCount && cells.length) {
+ const bubbleGeometry = new THREE.SphereGeometry(1, 12, 6);
+ const bubbleMaterial = new THREE.MeshStandardMaterial({ color: 0x758f93, roughness: 0.35 });
+ const air = new THREE.InstancedMesh(bubbleGeometry, bubbleMaterial, bubbleCount);
+ air.name = 'TrappedAir'; const dummy = new THREE.Object3D();
+ let cluster = null, remaining = 0;
+ for (let i = 0; i < bubbleCount; i++) {
+ if (remaining === 0) {
+ const cell = cells[Math.floor(rand() * cells.length)];
+ const direction = rand() * Math.PI * 2, spread = Math.sqrt(rand()) * cell.radius * 0.55;
+ cluster = { cell, x: cell.center[0] + Math.cos(direction) * spread,
+ z: cell.center[1] + Math.sin(direction) * spread,
+ size: 0.004 + Math.pow(rand(), 3) * 0.026 };
+ remaining = 1 + Math.floor(rand() * 5);
+ }
+ const { cell } = cluster;
+ const drift = Math.min(0.05, cell.radius * 0.12);
+ const x = cluster.x + (rand() - 0.5) * drift, z = cluster.z + (rand() - 0.5) * drift;
+ const radius = Math.min(thickness * 0.085, cell.radius * 0.06,
+ cluster.size * (0.45 + rand() * 0.95));
+ const localDepth = thicknessAt(x, z);
+ dummy.position.set(x, cell.topAt([x, z]) - localDepth * (0.16 + rand() * 0.68), z);
+ dummy.scale.set(radius, radius * (0.10 + rand() * 0.18), radius * (0.7 + rand() * 0.5));
+ dummy.rotation.set((rand() - 0.5) * 0.18, rand() * Math.PI, (rand() - 0.5) * 0.18);
+ dummy.updateMatrix(); air.setMatrixAt(i, dummy.matrix);
+ remaining--;
+ }
+ air.instanceMatrix.needsUpdate = true; air.computeBoundingSphere();
+ air.userData.placement = 'free'; group.add(air);
+ }
+ // Float32 coordinates are exactly what the GPU and raycaster see.
+ for (const face of topTriangles) for (const point of face)
+ for (let i = 0; i < 3; i++) point[i] = Math.fround(point[i]);
+ group.userData.sampleHeight = (x, z) => {
+ let result = null;
+ for (const [a, b, c] of topTriangles) {
+ const denominator = (b[2] - c[2]) * (a[0] - c[0]) + (c[0] - b[0]) * (a[2] - c[2]);
+ if (Math.abs(denominator) < 1e-12) continue;
+ const wa = ((b[2] - c[2]) * (x - c[0]) + (c[0] - b[0]) * (z - c[2])) / denominator;
+ const wb = ((c[2] - a[2]) * (x - c[0]) + (a[0] - c[0]) * (z - c[2])) / denominator;
+ const wc = 1 - wa - wb;
+ if (Math.min(wa, wb, wc) >= -1e-7) {
+ const y = wa * a[1] + wb * b[1] + wc * c[1];
+ result = result === null ? y : Math.max(result, y);
+ }
+ }
+ return result;
+ };
+ group.userData.floeCount = cells.length;
+ group.userData.floeOutlines = cells.map(cell => cell.polygon.map(point => [...point]));
+ group.userData.seed = seed;
+ group.userData.update = () => {};
+ const owned = snapshotResources(group); owned.add(optical);
+ return attachDisposal(group, owned);
+}
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/instancing.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/instancing.js
index 6bb837b0..9bab0b05 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/instancing.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/instancing.js
@@ -6,6 +6,22 @@
import * as THREE from 'three';
import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
+import { snapshotResources, attachDisposal } from './lifecycle.js';
+
+/** A baked mirror changes triangle orientation as well as vertex positions. */
+function reverseWinding(geometry) {
+ if (!geometry.index) {
+ geometry.setIndex(Array.from({length:geometry.attributes.position.count}, (_, i) => i));
+ }
+ const index = geometry.index;
+ for (let i = 0; i + 2 < index.count; i += 3) {
+ const b = index.getX(i + 1);
+ index.setX(i + 1, index.getX(i + 2));
+ index.setX(i + 2, b);
+ }
+ index.needsUpdate = true;
+ return geometry;
+}
/**
* Build one prototype and stamp it across many transforms.
@@ -34,21 +50,25 @@ import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
* prototype; `name` names the returned group.
* @returns {THREE.Group} A group of InstancedMeshes, positioned in world
* space by the placements. Empty group when there are no placements.
+ * Mirrored placements use a second batch with baked reversed winding;
+ * every instance matrix then has positive determinant, as Three requires.
+ * userData.dispose() releases copied geometry and instance buffers, while
+ * prototype materials/textures remain borrowed. Later children are unowned.
*/
export function instanceAsset(build, placements, opts = {}) {
const group = new THREE.Group();
group.name = opts.name || 'InstancedAsset';
- if (!placements || placements.length === 0) return group;
+ if (!placements || placements.length === 0) return attachDisposal(group, []);
const proto = build(opts.buildOpts || {});
- proto.updateMatrixWorld(true);
+ proto.updateWorldMatrix(true, true);
// Collect meshes with transforms RELATIVE to the prototype root,
// then MERGE by material — unmerged, a 1418-mesh asset would cost
// 1418 draw calls per placement batch; merged, one per material.
const buckets = new Map();
const inv = new THREE.Matrix4().copy(proto.matrixWorld).invert();
- proto.traverse((n) => {
+ proto.traverseVisible((n) => {
if (!n.isMesh || n.isInstancedMesh || !n.geometry) return;
const mats = Array.isArray(n.material) ? n.material : [n.material];
if (!mats[0]) return;
@@ -56,6 +76,7 @@ export function instanceAsset(build, placements, opts = {}) {
for (const { material, geometry } of splitByMaterial(n.geometry, mats)) {
const g = geometry;
g.applyMatrix4(xf);
+ if (xf.determinant() < 0) reverseWinding(g);
// Merging needs identical attribute sets; drop the extras.
for (const name of Object.keys(g.attributes)) {
// `color` stays: a vertexColors material with no color
@@ -81,7 +102,7 @@ export function instanceAsset(build, placements, opts = {}) {
parts.push({ geometry, material, local: new THREE.Matrix4() });
}
}
- if (!parts.length) return group;
+ if (!parts.length) return attachDisposal(group, []);
const world = placements.map((p) => {
const pos = p.position instanceof THREE.Vector3
@@ -91,25 +112,39 @@ export function instanceAsset(build, placements, opts = {}) {
? new THREE.Vector3(...p.scale)
: new THREE.Vector3(1, 1, 1).multiplyScalar(
typeof p.scale === 'number' ? p.scale : 1);
- return new THREE.Matrix4().compose(
+ const matrix = new THREE.Matrix4().compose(
pos,
new THREE.Quaternion().setFromEuler(
new THREE.Euler(0, p.rotationY || 0, 0)),
s);
+ if (!matrix.elements.every(Number.isFinite) || Math.abs(matrix.determinant()) < 1e-12) {
+ throw new RangeError('instanceAsset: placements need finite transforms and nonzero scale');
+ }
+ return matrix;
});
const m = new THREE.Matrix4();
const tint = new THREE.Color();
+ const reflection = new THREE.Matrix4().makeScale(-1, 1, 1);
+ const batches = [[], []];
+ for (let i = 0; i < world.length; i++) batches[world[i].determinant() < 0 ? 1 : 0].push(i);
for (const part of parts) {
+ for (let mirrored = 0; mirrored < batches.length; mirrored++) {
+ const indices = batches[mirrored];
+ if (!indices.length) continue;
+ const geometry = mirrored
+ ? reverseWinding(part.geometry.clone().applyMatrix4(reflection)) : part.geometry;
const mesh = new THREE.InstancedMesh(
- part.geometry, part.material, placements.length);
+ geometry, part.material, indices.length);
mesh.castShadow = true;
mesh.receiveShadow = true;
let tinted = false;
- for (let i = 0; i < placements.length; i++) {
- m.copy(world[i]).multiply(part.local);
+ for (let i = 0; i < indices.length; i++) {
+ const sourceIndex = indices[i];
+ m.copy(world[sourceIndex]).multiply(part.local);
+ if (mirrored) m.multiply(reflection);
mesh.setMatrixAt(i, m);
- const c = placements[i].color;
+ const c = placements[sourceIndex].color;
if (c !== undefined && c !== null) {
// An array is LINEAR — the space the multiply happens in, and the
// only way to say "1.06 of the albedo". set() reads a hex or a
@@ -123,9 +158,11 @@ export function instanceAsset(build, placements, opts = {}) {
mesh.instanceMatrix.needsUpdate = true;
if (tinted && mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
mesh.frustumCulled = false; // one bbox for the whole spread
+ mesh.userData.placementIndices = Int32Array.from(indices);
group.add(mesh);
+ }
}
- return group;
+ return attachDisposal(group, snapshotResources(group, {materials:false}));
}
/**
@@ -238,6 +275,11 @@ function mergeBucket(geos) {
* @returns {Array<object>} Placements for `instanceAsset`.
*/
export function scatterGrid(area, spacing, rand, opts = {}) {
+ if (!Number.isFinite(spacing) || spacing <= 0 ||
+ ![area.x, area.z, area.w, area.d].every(Number.isFinite) || area.w < 0 || area.d < 0) {
+ throw new RangeError('scatterGrid: spacing must be positive and area finite with nonnegative size');
+ }
+ if (area.w === 0 || area.d === 0) return [];
const jitter = opts.jitter ?? 0.35;
const scaleVar = opts.scaleVar ?? 0.12;
// Per-instance SHAPE variation, not just yaw: cheap repetition is
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/lifecycle.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/lifecycle.js
new file mode 100644
index 00000000..2b45620b
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/lifecycle.js
@@ -0,0 +1,55 @@
+/** Explicit, construction-time ownership for procedural effects.
+ *
+ * Capture immediately after building the effect. Later caller-added children
+ * are not owned. Material textures are deliberately excluded: environment maps,
+ * cached maps and other borrowed assets often outlive a single effect. Add only
+ * textures created by this factory to the resource set before attaching it.
+ */
+
+/** Collect geometry, material (including custom shadows) and instance buffers.
+ * Set a category to false when it is borrowed, then add any owned exceptions.
+ * This is a snapshot, not a traversal performed during disposal.
+ */
+export function snapshotResources(root, {
+ geometries = true, materials = true, instances = true,
+} = {}) {
+ const resources = new Set();
+ root.traverse((object) => {
+ if (geometries && object.geometry) resources.add(object.geometry);
+ if (instances && object.isInstancedMesh) resources.add(object);
+ if (materials) {
+ for (const material of [].concat(object.material || [],
+ object.customDepthMaterial || [], object.customDistanceMaterial || [])) {
+ if (material) resources.add(material);
+ }
+ }
+ });
+ return resources;
+}
+
+/** Install userData.dispose() for an explicit iterable of owned resources.
+ * Duplicate resources are released once; repeated disposal is harmless. A
+ * resource may be a Three.js disposable or {dispose(){...}} for external state.
+ * Cleanup continues after an individual failure, then reports all failures.
+ */
+export function attachDisposal(root, resources) {
+ const owned = new Set(resources);
+ for (const resource of owned) {
+ if (!resource || typeof resource.dispose !== 'function') {
+ throw new TypeError('Every owned resource must implement dispose()');
+ }
+ }
+ let disposed = false;
+ root.userData.dispose = () => {
+ if (disposed) return false;
+ disposed = true;
+ const errors = [];
+ for (const resource of owned) {
+ try { resource.dispose(); } catch (error) { errors.push(error); }
+ }
+ owned.clear();
+ if (errors.length) throw new AggregateError(errors, 'Effect resource disposal failed');
+ return true;
+ };
+ return root;
+}
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/materials.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/materials.js
index 4007b09c..bd392935 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/materials.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/materials.js
@@ -1,11 +1,13 @@
/**
* Shared material library: every factory returns a MeshStandardMaterial
- * with procedural value-noise map + roughnessMap + bumpMap and a seeded
+ * with procedural albedo + roughness + linear height maps and a seeded
* variant knob (flat albedo is the strongest "plastic toy" tell).
- * Deterministic, DOM-free (DataTexture), imports only three.
+ * Deterministic and DOM-free (DataTexture). Brick, cobble and fabric
+ * carry their own bonded masonry, irregular stones and woven yarns.
*/
import * as THREE from 'three';
+import { clonePatchedMaterial, patchStandard } from './shader.js';
// ---------------------------------------------------------------- noise
@@ -48,6 +50,18 @@ const cells = (n) => Math.max(1, Math.round(n));
const _texCache = new Map();
+function texture(data, size, color = false) {
+ const tex = new THREE.DataTexture(data, size, size);
+ tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
+ tex.colorSpace = color ? THREE.SRGBColorSpace : THREE.NoColorSpace;
+ tex.magFilter = THREE.LinearFilter;
+ tex.minFilter = THREE.LinearMipmapLinearFilter;
+ tex.generateMipmaps = true;
+ tex.anisotropy = 4;
+ tex.needsUpdate = true;
+ return tex;
+}
+
/**
* Grayscale/tinted noise DataTexture, cached by its parameters.
* @param {object} o size, scale, seed, contrast, tint [r,g,b], base
@@ -135,14 +149,126 @@ export function noiseTexture(o = {}) {
data[i + 3] = 255;
}
}
- const tex = new THREE.DataTexture(data, size, size);
- tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
- tex.colorSpace = o.linear ? THREE.NoColorSpace : THREE.SRGBColorSpace;
- tex.needsUpdate = true;
+ const tex = texture(data, size, !o.linear);
_texCache.set(key, tex);
return tex;
}
+const _structureCache = new Map();
+const smooth = (a, b, value) => {
+ const t = Math.max(0, Math.min(1, (value - a) / (b - a)));
+ return t * t * (3 - 2 * t);
+};
+const fract = (value) => value - Math.floor(value);
+const wrap = (value, period) => ((value % period) + period) % period;
+
+// Surface channels: R = linear height, G = roughness multiplier,
+// B = mortar/sediment coverage. They share one field so no joint can
+// be painted over the raised center of a brick or stone.
+function structuredTextures(kind, seed, options) {
+ const contrast = Math.max(0, options.contrast ?? 0.4);
+ const scale = Math.max(1, options.scale ?? 8);
+ const streak = Math.max(0, Math.min(1, options.streak ?? 0));
+ const key = `${kind}:${seed}:${contrast}:${scale}:${streak}`;
+ if (_structureCache.has(key)) return _structureCache.get(key);
+ const size = 512, color = new Uint8Array(size * size * 4);
+ const surface = new Uint8Array(size * size * 4);
+ const cycles = Math.max(16, Math.min(256, Math.round(scale * 4)));
+ const cyclesY = Math.max(2, Math.round(cycles * (1 - streak * .92)));
+ for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) {
+ const u = (x + 0.5) / size, v = (y + 0.5) / size;
+ const grain = fbm(u * cycles, v * cyclesY, cycles, cyclesY, seed + 101, 3);
+ let height, roughness, joint = 0, tone, hue = 0;
+ if (kind === 'brick') {
+ const row = Math.floor(v * 12), bx = u * 4 + (row % 2) * 0.5;
+ const id = hash2(wrap(Math.floor(bx), 4), row, seed);
+ const fx = fract(bx), fy = fract(v * 12);
+ const edge = Math.min(Math.min(fx, 1 - fx) / 4,
+ Math.min(fy, 1 - fy) / 12);
+ const chipped = edge + (grain - 0.45) * 0.006;
+ joint = 1 - smooth(0.002, 0.008, chipped);
+ const bevel = smooth(0.004, 0.015, chipped);
+ height = 0.15 + bevel * (0.67 + (id - 0.5) * 0.12)
+ + (grain - 0.45) * (0.12 - joint * 0.07);
+ roughness = 0.87 + grain * 0.12 + joint * 0.05;
+ tone = (0.76 + id * 0.22) * (0.89 + grain * 0.20);
+ hue = (id - 0.5) * 0.13;
+ } else if (kind === 'cobble') {
+ const px = u * 6, py = v * 6, ix = Math.floor(px), iy = Math.floor(py);
+ let first = 1e9, second = 1e9, id = 0;
+ for (let j = -1; j <= 1; j++) for (let i = -1; i <= 1; i++) {
+ const cx = ix + i, cy = iy + j, wx = wrap(cx, 6), wy = wrap(cy, 6);
+ const dx = cx + 0.2 + hash2(wx, wy, seed) * 0.6 - px;
+ const dy = cy + 0.2 + hash2(wx, wy, seed + 23) * 0.6 - py;
+ const d = dx * dx + dy * dy;
+ if (d < first) { second = first; first = d; id = hash2(wx, wy, seed + 47); }
+ else if (d < second) second = d;
+ }
+ const edge = Math.sqrt(second) - Math.sqrt(first);
+ const chipped = edge + (grain - 0.45) * 0.055;
+ joint = 1 - smooth(0.025, 0.105, chipped);
+ const round = smooth(0.045, 0.32, chipped);
+ height = 0.12 + round * (0.60 + id * 0.16) + (grain - 0.45) * 0.11;
+ roughness = 0.78 + grain * 0.20 + joint * 0.13;
+ tone = (0.72 + id * 0.25) * (0.89 + grain * 0.20);
+ hue = (id - 0.5) * 0.18;
+ } else if (kind === 'wood' || kind === 'paintedWood') {
+ // The board's longitudinal direction is +V. Growth rings bend
+ // around a few embedded knots; fine pores follow that same flow.
+ const warp = (fbm(u*4,v*2,4,2,seed+67,3)-.5)*.075;
+ let flow=u+warp,knot=0,knotRing=0;
+ for(let k=0;k<2;k++){
+ const kx=.16+hash2(k,17,seed)*.68,ky=.15+hash2(k,39,seed)*.7;
+ const dx=wrap(u-kx+.5,1)-.5,dy=wrap(v-ky+.5,1)-.5;
+ const radius=Math.hypot(dx/.062,dy/.18),weight=Math.exp(-radius*radius*.65);
+ flow+=dx/(Math.abs(dx)+.035)*weight*.042;
+ knot=Math.max(knot,weight);
+ knotRing+=weight*(.5+.5*Math.sin(radius*17+warp*30));
+ }
+ const rings = Math.pow(.5+.5*Math.sin((flow*Math.round(scale*8)+warp)*Math.PI*2),8);
+ const pores = smooth(.57,.77,fbm(u*160,v*18,160,18,seed+89,2));
+ const grainDark = Math.max(rings*.75,knotRing*.72+knot*.18);
+ const painted = kind === 'paintedWood';
+ height = .67 - grainDark*(painted?.07:.24)-pores*(painted?.015:.1)+(grain-.5)*.025;
+ roughness = (painted?.86:.9)+pores*.08+grain*.04;
+ tone = painted ? .98-grainDark*.075-pores*.025
+ : .94-grainDark*.24-pores*.12-knot*.08+(grain-.5)*.08;
+ hue = (grain-.5)*(painted?.025:.065);
+ } else {
+ // Alternating over/under yarns, elliptical cross sections and
+ // longitudinal fibers. A plain checkerboard has no woven relief.
+ const px = u * 64, py = v * 64;
+ const ix = Math.floor(px), iy = Math.floor(py);
+ const fx = fract(px), fy = fract(py);
+ const over = (ix + iy) % 2;
+ const warp = Math.pow(Math.max(0, Math.sin(fx * Math.PI)), 0.7);
+ const weft = Math.pow(Math.max(0, Math.sin(fy * Math.PI)), 0.7);
+ const yarn = over ? warp : weft;
+ const underside = over ? weft : warp;
+ height = 0.12 + yarn * 0.63 + underside * (1 - yarn) * 0.18;
+ const fiber = Math.sin((over ? fx : fy) * Math.PI * 6) * 0.035;
+ height += fiber * yarn;
+ roughness = 0.86 + (1 - yarn) * 0.12;
+ tone = (0.74 + yarn * 0.21 + grain * 0.07) * (over ? 1 : 0.91);
+ }
+ const defaultContrast=kind==='brick'?.4:kind==='cobble'?.5:kind==='fabric'?.22:kind==='paintedWood'?.18:.4;
+ tone=1-(1-tone)*contrast/defaultContrast;
+ const at = (y * size + x) * 4;
+ const byte = (value) => Math.round(Math.max(0, Math.min(1, value)) * 255);
+ color[at] = byte(tone * (1 + hue));
+ color[at + 1] = byte(tone * (1 + hue * 0.15));
+ color[at + 2] = byte(tone * (1 - hue));
+ color[at + 3] = 255;
+ surface[at] = byte(height);
+ surface[at + 1] = byte(roughness);
+ surface[at + 2] = byte(joint);
+ surface[at + 3] = 255;
+ }
+ const result = { map: texture(color, size, true), surface: texture(surface, size) };
+ _structureCache.set(key, result);
+ return result;
+}
+
// ------------------------------------------------------------ factories
function shade(hex, k) {
@@ -212,7 +338,8 @@ function make(o) {
if (key !== null && _matCache.has(key)) return _matCache.get(key);
const seed = _seedBucket(o.seed) + Math.round(variant * 97);
const col = shade(o.color, (variant - 0.5) * (o.spread === undefined ? 0.08 : o.spread));
- const map = noiseTexture({
+ const structured = o.structure ? structuredTextures(o.structure, seed, o) : null;
+ const map = structured?.map || noiseTexture({
scale: o.scale || 6, seed, contrast: o.contrast === undefined ? 0.3 : o.contrast,
streak: o.streak || 0, size: 256,
// Mineral surfaces carry the most hue break (a granite face is
@@ -220,7 +347,7 @@ function make(o) {
// least, because a factory finish really is one colour.
hueBreak: o.hueBreak === undefined ? 0.12 : o.hueBreak,
});
- const rough = noiseTexture({
+ const rough = structured?.surface || noiseTexture({
scale: (o.scale || 6) * 1.7, seed: seed + 41,
contrast: 0.5, base: 1, streak: o.streak || 0, linear: true, size: 256,
});
@@ -229,19 +356,48 @@ function make(o) {
color: col,
map,
roughnessMap: rough,
- bumpMap: o.bump === 0 ? null : map,
+ bumpMap: o.bump === 0 ? null : (structured?.surface || map),
bumpScale: o.bump === undefined ? 0.015 : o.bump,
roughness: o.roughness,
metalness: o.metalness === undefined ? 0 : o.metalness,
}, o.extra || {}));
if (rep !== 1) {
- m.map = map.clone();
- m.map.repeat.set(rep, rep);
- m.map.needsUpdate = true;
- m.roughnessMap = rough.clone();
- m.roughnessMap.repeat.set(rep, rep);
- m.roughnessMap.needsUpdate = true;
- m.bumpMap = m.map;
+ const copies = new Map();
+ for (const slot of ['map', 'roughnessMap', 'bumpMap', 'normalMap']) {
+ const source = m[slot];
+ if (!source?.isTexture) continue;
+ let copy = copies.get(source);
+ if (!copy) {
+ copy = source.clone();
+ copy.repeat.set(rep, rep);
+ copy.needsUpdate = true;
+ copies.set(source, copy);
+ }
+ m[slot] = copy;
+ }
+ }
+ if (structured && m.map?.source === structured.map.source
+ && (o.structure === 'brick' || o.structure === 'cobble')) {
+ patchStandard(m, {
+ name: 'materials:structure',
+ uniforms: {
+ uMaterialStructure: { value: structured.surface },
+ uMaterialJointColor: { value: new THREE.Color(o.jointColor
+ ?? (o.structure === 'brick' ? 0xa69b86 : 0x36372f)) },
+ },
+ fragmentHead: 'uniform sampler2D uMaterialStructure;\nuniform vec3 uMaterialJointColor;',
+ fragmentBody: [
+ '#ifdef USE_MAP',
+ 'float materialJoint = texture2D(uMaterialStructure, vMapUv).b;',
+ 'diffuseColor.rgb = mix(diffuseColor.rgb, uMaterialJointColor, materialJoint);',
+ '#endif',
+ ].join('\n'),
+ metalnessBody: [
+ '#ifdef USE_MAP',
+ 'metalnessFactor *= 1.0 - materialJoint;',
+ '#endif',
+ ].join('\n'),
+ });
}
if (key !== null) {
m.userData.shared = true;
@@ -253,25 +409,26 @@ function make(o) {
export const plaster = (o = {}) => make(Object.assign(
{ color: 0xeae0d0, roughness: 0.85, scale: 5, contrast: 0.22, bump: 0.01 }, o));
export const brick = (o = {}) => make(Object.assign(
- { color: 0x9c4a35, roughness: 0.9, scale: 14, contrast: 0.4, bump: 0.03 }, o));
+ { color: 0x9c4a35, roughness: 0.9, scale: 14, contrast: 0.4,
+ bump: 0.012, structure: 'brick' }, o));
export const travertine = (o = {}) => make(Object.assign(
{ color: 0xd9cdb4, roughness: 0.7, scale: 4, contrast: 0.3, streak: 0.4 }, o));
export const granite = (o = {}) => make(Object.assign(
{ color: 0x8d8b88, roughness: 0.6, scale: 22, contrast: 0.45,
hueBreak: 0.16 }, o));
export const cobble = (o = {}) => make(Object.assign(
- { color: 0x6f6a63, roughness: 0.88, scale: 26, contrast: 0.5, bump: 0.05,
- hueBreak: 0.16 }, o));
+ { color: 0x6f6a63, roughness: 0.88, scale: 26, contrast: 0.5, bump: 0.04,
+ hueBreak: 0.16, structure: 'cobble' }, o));
export const asphalt = (o = {}) => make(Object.assign(
{ color: 0x2f3134, roughness: 0.82, scale: 30, contrast: 0.25 }, o));
export const terracotta = (o = {}) => make(Object.assign(
{ color: 0xb2593a, roughness: 0.78, scale: 10, contrast: 0.32 }, o));
export const weatheredWood = (o = {}) => make(Object.assign(
{ color: 0x7a5a3c, roughness: 0.92, scale: 8, contrast: 0.4, streak: 0.9,
- bump: 0.03 }, o));
+ bump: 0.006, structure: 'wood' }, o));
export const paintedWood = (o = {}) => make(Object.assign(
{ color: 0xc8b18a, roughness: 0.6, scale: 7, contrast: 0.18, streak: 0.8,
- hueBreak: 0.05 }, o));
+ hueBreak: 0.05, bump: 0.0015, structure: 'paintedWood' }, o));
export const paintedIron = (o = {}) => make(Object.assign(
{ color: 0x2d3a3f, roughness: 0.45, metalness: 0.35, scale: 9,
contrast: 0.16, hueBreak: 0.04 }, o));
@@ -283,7 +440,7 @@ export const giltBronze = (o = {}) => make(Object.assign(
contrast: 0.2 }, o));
export const fabric = (o = {}) => make(Object.assign(
{ color: 0xb04b46, roughness: 0.95, scale: 40, contrast: 0.22,
- bump: 0.008 }, o));
+ bump: 0.0008, structure: 'fabric' }, o));
export const foliage = (o = {}) => make(Object.assign(
{ color: 0x3f6b32, roughness: 0.8, scale: 16, contrast: 0.35,
hueBreak: 0.20, extra: { flatShading: false } }, o));
@@ -352,8 +509,7 @@ export function weather(mat, amount = 0.35) {
if (!mat) return mat;
// A cached material is shared by every caller that asked for the same
// look, so ageing in place would age the whole city. Copy first.
- const m = mat.userData && mat.userData.shared ? mat.clone() : mat;
- if (m !== mat) m.userData = {};
+ const m = mat.userData && mat.userData.shared ? clonePatchedMaterial(mat) : mat;
// Ratio, never a fixed step: getHSL works in LINEAR space, where a
// dark colour's lightness is tiny — offsetHSL drove asphalt to pure
// black, an albedo nothing can light. Same fix `shade()` already has.
@@ -378,11 +534,11 @@ export function weather(mat, amount = 0.35) {
*/
export function tint(mat, variant = 0.5) {
const v = _quantise(variant);
- const key = mat.uuid + ':' + v;
+ const key = mat.uuid + ':' + mat.version + ':' + v;
const hit = _tintCache.get(key);
if (hit) return hit;
- const m = mat.clone();
- m.userData = { shared: true };
+ const m = clonePatchedMaterial(mat);
+ m.userData.shared = true;
if (m.color) {
m.color.offsetHSL((v - 0.5) * 0.04, 0, 0);
const hsl = m.color.getHSL({ h: 0, s: 0, l: 0 });
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/meadow.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/meadow.js
new file mode 100644
index 00000000..8c9d4e8c
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/meadow.js
@@ -0,0 +1,380 @@
+/**
+ * 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:{direction:[1,.3],strength:.35,speed:1.2}, dry:.12,
+ * shadows:true, ground:true, diversity:.85, seedHeads:.003}) -> Group; userData.update(t), dispose().
+ * 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, capped at 2,000). No textures or network needed.
+ */
+import * as THREE from 'three';
+import { attachDisposal, snapshotResources } from './lifecycle.js';
+import { fbm2, mulberry32 } from './noise.js';
+import { patchStandard, shadowLike, tickShaders } from './shader.js';
+
+function finite(value, fallback, low, high, name) {
+ const v = value === undefined ? fallback : value;
+ if (!Number.isFinite(v) || v < low || v > high) {
+ throw new RangeError(`makeMeadow: ${name} must be finite in [${low}, ${high}]`);
+ }
+ return v;
+}
+
+// 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 = finite(dimensions[0], 10, .05, 1000, 'size[0]');
+ const sz = finite(dimensions[1], 10, .05, 1000, 'size[1]');
+ const density = finite(opts.density, 700, 0, 20000, 'density');
+ const height = finite(opts.height, .38, .005, 4, 'height');
+ const width = finite(opts.bladeWidth, .011, .0005, .15, 'bladeWidth');
+ const seed = finite(opts.seed, 12, -2147483648, 2147483647, 'seed');
+ const dry = finite(opts.dry, .12, 0, 1, 'dry');
+ const diversity = finite(opts.diversity, .85, 0, 1, 'diversity');
+ const seedHeads = finite(opts.seedHeads, .003, 0, .05, 'seedHeads');
+ const maxBlades = Math.floor(finite(opts.maxBlades, 100000, 1, 300000, 'maxBlades'));
+ const rows = Math.floor(finite(opts.segments, 5, 3, 12, 'segments'));
+ const wind = opts.wind ?? {};
+ const strength = finite(wind.strength, .5, 0, 3, 'wind.strength');
+ const speed = finite(wind.speed, 1.2, 0, 10, 'wind.speed');
+ const direction = wind.direction ?? [1, .3];
+ if (!Array.isArray(direction) || direction.length !== 2 || !direction.every(Number.isFinite)) {
+ throw new TypeError('makeMeadow: wind.direction must be [x,z] finite numbers');
+ }
+ const dir = new THREE.Vector2(...direction);
+ if (dir.lengthSq() < 1e-12) dir.set(1, 0);
+ dir.normalize();
+ 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 = sampleHeight;
+ 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.js
index 55d173a3..9af725a4 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/merge.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/merge.js
@@ -13,7 +13,8 @@
import * as THREE from 'three';
import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
-import { patchStandard } from './shader.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);
@@ -29,10 +30,19 @@ const _SCALARS = [
'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. */
@@ -77,9 +87,12 @@ function _flipWinding(g) {
/** What one material contributes to the shared surface response. */
function _sig(m) {
if (!m) return '';
- return [m.type, m.side, m.transparent === true, m.flatShading === true,
- m.roughness, m.metalness, m.emissive ? m.emissive.getHexString() : '',
- m.emissiveIntensity, m.map ? m.map.uuid : ''].join('|');
+ 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 || [],
+ ]);
}
/**
@@ -104,7 +117,9 @@ function _sig(m) {
* 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. Rename it to the zone it forms.
+ * — 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.
*/
@@ -124,7 +139,6 @@ export function mergeStatic(meshes, opts = {}) {
if (!n.geometry.attributes || !n.geometry.attributes.position) return;
for (let p = n; p; p = p.parent) {
if (!p.visible) return;
- if (p === root) break;
}
found.push(n);
});
@@ -197,29 +211,10 @@ export function mergeStatic(meshes, opts = {}) {
// ONE material: colour lives per-vertex; surface response comes from
// the first piece (colour-only differences by contract).
- const material = new THREE.MeshStandardMaterial({ vertexColors: true });
- if (firstMat) {
- for (const k of _SCALARS) {
- if (firstMat[k] !== undefined) material[k] = firstMat[k];
- }
- for (const k of _MAPS) {
- if (firstMat[k]) material[k] = firstMat[k];
- }
- if (firstMat.emissive) material.emissive.copy(firstMat.emissive);
- if (firstMat.normalMap && firstMat.normalScale) {
- material.normalScale.copy(firstMat.normalScale);
- }
- // A shader-patched material does not survive being rebuilt, and
- // Material.clone() would not have saved it either (it copies
- // userData but NOT onBeforeCompile — a dead chain holding a live
- // cache key). Replay the chain instead, sharing the SOURCE uniform
- // map so one tickShaders still advances both.
- const patches = firstMat.userData && firstMat.userData.astraPatches;
- if (patches && patches.length) {
- material.userData.uniforms = firstMat.userData.uniforms;
- for (const p of patches) patchStandard(material, p);
- }
- }
+ 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 `
@@ -232,5 +227,5 @@ export function mergeStatic(meshes, opts = {}) {
out.name = 'MergedStatic';
out.castShadow = true;
out.receiveShadow = true;
- return out;
+ 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.js
index 17d25f7b..e8c4a6be 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/neon.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/neon.js
@@ -19,6 +19,7 @@
* onto).
*/
+import { attachDisposal, snapshotResources } from './lifecycle.js';
import * as THREE from 'three';
import {
@@ -391,7 +392,10 @@ export function makeNeonTube(opts = {}) {
const g = new THREE.Group();
g.name = 'NeonTube';
- if (!strokes.length) return g;
+ 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);
@@ -411,11 +415,12 @@ export function makeNeonTube(opts = {}) {
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.tick = (t) => tickShaders(g, t);
+ 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);
- return keepOutOfDepthPasses(g);
+ keepOutOfDepthPasses(g);
+ return attachDisposal(g, snapshotResources(g));
}
/** One merged mesh for every stroke at one radius. */
@@ -456,10 +461,10 @@ const SPILL_VERTEX = [
' vec3 nsN = normal;',
'#ifdef USE_INSTANCING',
' nsP = instanceMatrix * nsP;',
- ' nsN = mat3(instanceMatrix) * nsN;',
+ ' nsN = astraNormalTransform(mat3(instanceMatrix), nsN);',
'#endif',
' vNeonSW = (modelMatrix * nsP).xyz;',
- ' vNeonSN = normalize((modelMatrix * vec4(nsN, 0.0)).xyz);',
+ ' vNeonSN = astraNormalTransform(mat3(modelMatrix), nsN);',
].join('\n');
const SPILL_HEAD = [
@@ -750,7 +755,10 @@ export function makeLightTrails(opts = {}) {
const g = new THREE.Group();
g.name = 'LightTrails';
- if (!strokes.length) return g;
+ 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;
@@ -772,8 +780,9 @@ export function makeLightTrails(opts = {}) {
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.tick = (t) => tickShaders(g, t);
- return keepOutOfDepthPasses(g);
+ 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. */
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/noise.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/noise.js
index e860e3d6..5e7a6205 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/noise.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/noise.js
@@ -58,6 +58,9 @@ function _offsets(seed, octaves) {
for (let o = 0; o < octaves; o++) {
offs.push([rand() * 256, rand() * 256, rand() * 256]);
}
+ // Scene previews routinely cycle through fresh seeds. Eviction only
+ // recomputes deterministic offsets; it cannot change a field's values.
+ if (_offsetCache.size >= 256) _offsetCache.delete(_offsetCache.keys().next().value);
_offsetCache.set(key, offs);
}
return offs;
@@ -74,9 +77,14 @@ function _offsets(seed, octaves) {
* @returns {number} Normalized field value in measured about +-0.25 with a seed- and region-dependent bias, NOT the [-1, 1] the octave sum suggests.
*/
export function fbm3(x, y, z, opts = {}) {
- const octaves = opts.octaves || 4;
- const lacunarity = opts.lacunarity || 2;
+ const octaves = opts.octaves ?? 4;
+ const lacunarity = opts.lacunarity ?? 2;
const gain = opts.gain === undefined ? 0.5 : opts.gain;
+ if (!Number.isInteger(octaves) || octaves < 0 || octaves > 32 ||
+ ![x, y, z, lacunarity, gain].every(Number.isFinite) || gain < 0) {
+ throw new RangeError('fbm3: use finite coordinates, 0..32 integer octaves and nonnegative gain');
+ }
+ if (octaves === 0) return 0;
const offs = _offsets(opts.seed === undefined ? 1 : opts.seed, octaves);
let amp = 1;
let freq = 1;
@@ -90,7 +98,9 @@ export function fbm3(x, y, z, opts = {}) {
amp *= gain;
freq *= lacunarity;
}
- return sum / norm;
+ const value = sum / norm;
+ if (!Number.isFinite(value)) throw new RangeError('fbm3: octave parameters overflow');
+ return value;
}
/**
@@ -122,6 +132,9 @@ export function fbm2(x, z, opts = {}) {
* @returns {THREE.DataTexture} RepeatWrapping, needsUpdate already set.
*/
export function noiseDataTexture(size = 256, fn) {
+ if (!Number.isInteger(size) || size < 1 || size > 4096) {
+ throw new RangeError('noiseDataTexture: size must be an integer from 1 to 4096');
+ }
const f = fn ||
((u, v) => 0.5 + 0.35 * fbm2(u * 6, v * 6, { seed: 1 }));
const data = new Uint8Array(size * size * 4);
@@ -155,14 +168,48 @@ export function noiseDataTexture(size = 256, fn) {
return tex;
}
+/**
+ * Trilinear read of a cubic n×n×n grid stored x-fastest, `stride` values per
+ * cell. Coordinates are in cells; `periodic` wraps them, otherwise they clamp
+ * to the edge. The CPU twin of sampling a Data3DTexture, so a density query
+ * and the texture it baked agree.
+ *
+ * @returns {number} The interpolated value of `channel`.
+ */
+export function sampleGrid3(data, n, x, y, z, stride = 1, channel = 0, periodic = true) {
+ const ix = Math.floor(x), iy = Math.floor(y), iz = Math.floor(z);
+ const fx = x - ix, fy = y - iy, fz = z - iz;
+ const index = (v) => periodic ? ((v % n) + n) % n : Math.max(0, Math.min(n - 1, v));
+ let value = 0;
+ for (let dz = 0; dz < 2; dz++) for (let dy = 0; dy < 2; dy++) for (let dx = 0; dx < 2; dx++) {
+ const weight = (dx ? fx : 1 - fx) * (dy ? fy : 1 - fy) * (dz ? fz : 1 - fz);
+ value += data[((index(iz + dz) * n + index(iy + dy)) * n + index(ix + dx)) * stride + channel] * weight;
+ }
+ return value;
+}
+
+/**
+ * An RGBA8 cubic Data3DTexture, linearly filtered, repeating unless
+ * `repeat` is false (then clamped to the edge). needsUpdate is set.
+ */
+export function dataTexture3D(data, size, repeat = true) {
+ const texture = new THREE.Data3DTexture(data, size, size, size);
+ texture.format = THREE.RGBAFormat;
+ texture.minFilter = texture.magFilter = THREE.LinearFilter;
+ texture.wrapS = texture.wrapT = texture.wrapR = repeat ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
+ texture.unpackAlignment = 1;
+ texture.needsUpdate = true;
+ return texture;
+}
+
/**
* Displace a geometry's Y by seeded fBm and refresh its normals.
* Expects an XZ-plane geometry (`PlaneGeometry` after `rotateX`);
* displacement ADDS to existing Y, so pre-shaped geometry keeps shape.
*
* @param {THREE.BufferGeometry} geometry Modified in place.
- * @param {number} amp Peak displacement in metres (fBm spans ~[-1, 1],
- * so peak-to-trough relief is up to ~2 * amp).
+ * @param {number} amp Field multiplier in metres (fBm typically spans about
+ * [-0.25, 0.25], depending on seed and sampled region).
* @param {number} freq Spatial frequency, ~1 / featureMetres (0.02
* gives ~50 m hills).
* @param {number} [seed] Noise seed (default 1).
@@ -177,5 +224,7 @@ export function displaceY(geometry, amp, freq, seed) {
}
pos.needsUpdate = true;
geometry.computeVertexNormals();
+ if (geometry.boundingBox) geometry.computeBoundingBox();
+ if (geometry.boundingSphere) geometry.computeBoundingSphere();
return geometry;
}
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ocean.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ocean.js
new file mode 100644
index 00000000..e3de0cac
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ocean.js
@@ -0,0 +1,562 @@
+/**
+ * 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 { mulberry32 } from './noise.js';
+import { GLSL_UTIL } from './shader.js';
+import { Reflector } from 'three/addons/objects/Reflector.js';
+
+const TAU = Math.PI * 2;
+const COUNT = 32;
+function finite(value, fallback, name, min, max = Infinity) {
+ const v = value === undefined ? fallback : value;
+ if (!Number.isFinite(v) || v < min || v > max)
+ throw new RangeError(`makeOceanSurface: ${name} must be ${min}..${max}`);
+ return v;
+}
+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 sunDirection THREE.Vector3 or [x,y,z].
+ * 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 = {}) {
+ const width = finite(opts.width, 160, 'width', 1, 10000),
+ depth = finite(opts.depth, 160, 'depth', 1, 10000);
+ const height = finite(opts.waveHeight, 1.2, 'waveHeight', 0, 20);
+ const length = finite(opts.wavelength, 18, 'wavelength', 1, 500);
+ const waterDepth = finite(opts.waterDepth, 24, 'waterDepth', 0.1, 10000);
+ const chop = finite(opts.choppiness, 0.85, 'choppiness', 0, 1);
+ const foam = finite(opts.foam, 0.8, 'foam', 0, 2);
+ const segments = Math.round(finite(opts.segments, 160, 'segments', 16, 384));
+ const reflectionSize = Math.round(
+ finite(opts.reflectionSize, 512, 'reflectionSize', 64, 2048)
+ );
+ const seed = finite(opts.seed, 42, 'seed', 0, 4294967295);
+ const wind = opts.windDirection ?? [1, 0.2];
+ if (
+ !Array.isArray(wind) ||
+ wind.length !== 2 ||
+ !wind.every(Number.isFinite) ||
+ Math.hypot(...wind) < 1e-8
+ )
+ throw new RangeError('makeOceanSurface: windDirection must be a nonzero [x,z]');
+ const windAngle = Math.atan2(wind[1], wind[0]);
+ 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,
+ finite(spec.position, 0, 'shoreline.position', -10000, 10000),
+ 1
+ );
+ shoreWidth = finite(spec.width, 5, '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));
+ let sun = new THREE.Vector3(0.6, 0.7, 0.3).normalize();
+ if (opts.sunDirection !== undefined) {
+ if (
+ !opts.sunDirection?.isVector3 &&
+ (!Array.isArray(opts.sunDirection) || opts.sunDirection.length !== 3)
+ ) {
+ throw new RangeError('makeOceanSurface: sunDirection must be a Vector3 or [x,y,z]');
+ }
+ sun = opts.sunDirection.isVector3
+ ? opts.sunDirection.clone()
+ : new THREE.Vector3(...opts.sunDirection);
+ if (![sun.x, sun.y, sun.z].every(Number.isFinite) || sun.length() < 1e-8)
+ throw new RangeError('makeOceanSurface: invalid sunDirection');
+ 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: new THREE.Vector2(...wind).normalize() },
+ 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.
+ geometry.computeBoundingSphere();
+ geometry.boundingSphere.radius += height * 2;
+ geometry.computeBoundingBox();
+ geometry.boundingBox.expandByScalar(height);
+ const u = sea.material.uniforms,
+ base = sea.onBeforeRender;
+ const lp = new THREE.Vector3(),
+ tp = new THREE.Vector3(),
+ ambientContribution = new THREE.Color(),
+ environmentRotation = new THREE.Matrix4();
+ sea.onBeforeRender = function (renderer, scene, camera) {
+ 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()
+ );
+ }
+ let key = null;
+ u.seaKey.value.setRGB(0, 0, 0);
+ u.seaSunColor.value.setRGB(0, 0, 0);
+ u.seaAmbient.value.setRGB(0, 0, 0);
+ scene.traverseVisible((o) => {
+ if (o.isDirectionalLight && (!key || o.intensity > key.intensity)) key = o;
+ if (o.isHemisphereLight || o.isAmbientLight) {
+ ambientContribution.copy(o.color).multiplyScalar(o.intensity / Math.PI);
+ u.seaAmbient.value.add(ambientContribution);
+ }
+ });
+ if (key) {
+ if (opts.sunDirection === undefined) {
+ key.getWorldPosition(lp);
+ key.target.getWorldPosition(tp);
+ u.seaSun.value.copy(lp.sub(tp).normalize());
+ }
+ 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(this, renderer, scene, camera);
+ };
+ let time = 0,
+ disposed = false;
+ 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 = (x, z, t = time) =>
+ group.userData.sampleSurface(x, z, t).position.y;
+ const ownedMaterial = sea.material;
+ const ownedReflection = sea.getRenderTarget();
+ group.userData.dispose = () => {
+ if (disposed) return;
+ disposed = true;
+ geometry.dispose();
+ ownedMaterial.dispose();
+ ownedReflection.dispose();
+ };
+ 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.js
new file mode 100644
index 00000000..a796191c
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/paving.js
@@ -0,0 +1,250 @@
+/** 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 { 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;
+ vec3 paveBump(vec3 eye,vec3 n,float h) {
+ vec3 dx=dFdx(eye),dy=dFdy(eye),a=cross(dy,n),b=cross(n,dx);
+ float determinant=dot(dx,a);
+ if(abs(determinant)<1e-12)return n;
+ return normalize(abs(determinant)*n-sign(determinant)*(dFdx(h)*a+dFdy(h)*b));
+ }
+ `,
+ 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=paveBump(-vViewPosition,normal,paveGrain*.0009+paveFine*.00025);',
+ });
+ return material;
+}
+
+/** Build cobbles or staggered rectangular setts. No external assets needed.
+ * stoneSize is the approximate cell width; at most 4096 stones are generated,
+ * so 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=(x,z)=>{
+ if(!Number.isFinite(x)||!Number.isFinite(z)||Math.abs(x)>width/2||Math.abs(z)>depth/2)return null;
+ 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/place.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/place.js
index 2495b519..6f95a631 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/place.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/place.js
@@ -16,6 +16,21 @@ const _v = new THREE.Vector3();
const _t = new THREE.Vector3();
const DEG = Math.PI / 180;
+/** Raycaster does not check Object3D.visible or invisible ancestors. */
+function visibleInTree(object) {
+ for (let p = object; p; p = p.parent) if (!p.visible) return false;
+ return true;
+}
+
+/** A world position must be converted before writing a child's local slot. */
+function positionInWorld(object, position) {
+ if (object.parent) {
+ object.parent.updateWorldMatrix(true, false);
+ object.position.copy(object.parent.worldToLocal(position.clone()));
+ } else object.position.copy(position);
+ object.updateWorldMatrix(false, true);
+}
+
/** Unit vector for a `forward` string as reported by assets_api.json. */
function fwdVec(forward) {
switch (forward) {
@@ -36,6 +51,7 @@ function columnAt(x, z, targets, top, far, ignore) {
_ray.far = far;
const ys = [];
for (const h of _ray.intersectObjects(targets, true)) {
+ if (!visibleInTree(h.object)) continue;
if (ignore && (h.object === ignore || ignore.getObjectById(h.object.id))) {
continue;
}
@@ -79,18 +95,22 @@ function restingY(ys, y) {
export function seat(obj, surfaces, opts = {}) {
const targets = Array.isArray(surfaces) ? surfaces : [surfaces];
const bite = opts.bite === undefined ? 0.03 : opts.bite;
- obj.updateMatrixWorld(true);
+ obj.updateWorldMatrix(true, true);
// The SURFACE's world matrix has to be current too: a ground group
// built and moved in the same tick still carries its old matrix, so
// every raycast hits the old height and the whole scene seats to it
// (measured 1.53 m under a quay, 2026-08-04 drawbridge repair).
- for (const t of targets) if (t) t.updateMatrixWorld(true);
+ for (const t of targets) if (t) t.updateWorldMatrix(true, true);
_box.setFromObject(obj);
if (_box.isEmpty()) return obj;
const y0 = _box.min.y;
const xs = [_box.min.x, _box.max.x, (_box.min.x + _box.max.x) / 2];
const zs = [_box.min.z, _box.max.z, (_box.min.z + _box.max.z) / 2];
- const drop = opts.maxDrop || 500;
+ const drop = opts.maxDrop ?? 500;
+ if (!Number.isFinite(drop) || drop < 0 || !Number.isFinite(bite)) {
+ throw new RangeError('seat: maxDrop must be finite and nonnegative, bite finite');
+ }
+ if (drop === 0) return obj;
let best = null;
for (const x of xs) {
for (const z of zs) {
@@ -100,7 +120,9 @@ export function seat(obj, surfaces, opts = {}) {
}
}
if (best === null) return obj;
- obj.position.y += best - y0 - bite;
+ const position = obj.getWorldPosition(new THREE.Vector3());
+ position.y += best - y0 - bite;
+ positionInWorld(obj, position);
return obj;
}
@@ -122,7 +144,7 @@ function surfaceList(surfaces) {
*/
function liftAbove(pos, targets, clearance) {
if (!targets.length) return pos;
- for (const t of targets) if (t) t.updateMatrixWorld(true);
+ for (const t of targets) if (t) t.updateWorldMatrix(true, true);
const ys = columnAt(pos.x, pos.z, targets, pos.y + 1000, 4000);
const floorY = restingY(ys, pos.y);
if (floorY === null) return pos;
@@ -151,7 +173,7 @@ function probeView(pos, look, targets) {
dir.multiplyScalar(1 / dist);
_ray.set(pos, dir);
_ray.far = dist;
- const hits = _ray.intersectObjects(targets, true);
+ const hits = _ray.intersectObjects(targets, true).filter((h) => visibleInTree(h.object));
return { dir, dist, hit: hits.length ? hits[0].distance : Infinity };
}
@@ -271,7 +293,7 @@ export function establishingShot(name, heroObj, opts = {}) {
const fov = opts.fov === undefined ? 45 : opts.fov;
const coverage = opts.coverage === undefined ? 0.7 : opts.coverage;
const targets = surfaceList(opts.surfaces);
- heroObj.updateMatrixWorld(true);
+ heroObj.updateWorldMatrix(true, true);
_box.setFromObject(heroObj);
if (_box.isEmpty()) {
return { name, position: [10, 6, 10], lookAt: [0, 0, 0], fov };
@@ -353,7 +375,7 @@ export function establishingShot(name, heroObj, opts = {}) {
export function faceToward(obj, target, forward) {
const p = target instanceof THREE.Vector3
? target : new THREE.Vector3(...target);
- _t.subVectors(p, obj.position);
+ _t.subVectors(p, obj.getWorldPosition(new THREE.Vector3()));
_t.y = 0;
if (_t.lengthSq() < 1e-9) return obj;
return alignAlong(obj, _t, forward);
@@ -365,7 +387,7 @@ export function faceToward(obj, target, forward) {
* guessed yaws).
*
* @param {THREE.Object3D} obj
- * @param {THREE.Vector3|number[]} dir Direction of travel (y ignored).
+ * @param {THREE.Vector3|number[]} dir WORLD direction of travel (y ignored).
* @param {string} [forward] Asset forward from assets_api.json.
* @returns {THREE.Object3D} obj
*/
@@ -376,6 +398,18 @@ export function alignAlong(obj, dir, forward) {
if (d.lengthSq() < 1e-9) return obj;
d.normalize();
const f = fwdVec(forward);
+ if (obj.parent) {
+ obj.parent.updateWorldMatrix(true, false);
+ const inverse = obj.parent.matrixWorld.clone().invert();
+ d.transformDirection(inverse);
+ // Map the world horizontal heading and up into the parent's axes. With
+ // a scaled parent, subtracting its Euler yaw is not a valid conversion.
+ const up = new THREE.Vector3(0, 1, 0).transformDirection(inverse);
+ const basis = new THREE.Matrix4().lookAt(new THREE.Vector3(), d, up);
+ obj.quaternion.setFromRotationMatrix(basis).multiply(
+ new THREE.Quaternion().setFromUnitVectors(f, new THREE.Vector3(0, 0, -1)));
+ return obj;
+ }
// Yaw that takes the asset's own forward onto d.
obj.rotation.y = Math.atan2(d.x, d.z) - Math.atan2(f.x, f.z);
return obj;
@@ -453,9 +487,9 @@ function obstacleBoxes(avoid) {
const roots = Array.isArray(avoid) ? avoid : [avoid];
for (const root of roots) {
if (!root || !root.traverse) continue;
- if (root.updateMatrixWorld) root.updateMatrixWorld(true);
+ if (root.updateWorldMatrix) root.updateWorldMatrix(true, true);
root.traverse((o) => {
- if (!o.isMesh || solids.length >= 3000) return;
+ if (!o.isMesh || !visibleInTree(o) || solids.length >= 3000) return;
const nm = (o.name || (o.parent && o.parent.name) || '');
if (/ground|floor|terrain|road|path|water|sky|dome|wall|roof|ceiling/i
.test(nm)) return;
@@ -576,7 +610,7 @@ export function route(points, opts = {}) {
}
}
if (!obj) return { position, tangent, u };
- obj.position.copy(position);
+ positionInWorld(obj, position);
alignAlong(obj, tangent, opts.forward);
// Roll from the arc distance actually COVERED, which on a ping-pong
// return leg decreases: `s` only ever grows, so a cart driving back
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rain.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rain.js
index 5413c05b..5bec6ff2 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rain.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rain.js
@@ -5,11 +5,13 @@
* no post pass. Delivery frames are STILLS, so every effect must read
* FROZEN: streaks are drawn long, splash phases are spread across the
* field so all radii show at once, and puddle ripples displace real
- * geometry. World-space — add the returned objects
- * at the scene ROOT and drive them from `tick`: `obj.userData.update(t)`.
+ * geometry. Drive each factory with `obj.userData.update(t)`. Rainfall uses
+ * local coordinates and supports transformed parents. Surface-baked splashes
+ * store world-space impact positions and belong at the scene root.
*/
import * as THREE from 'three';
+import { attachDisposal, snapshotResources } from './lifecycle.js';
import { mulberry32, fbm2, noiseDataTexture } from './noise.js';
import { makeShaderMaterial, keepOutOfDepthPasses } from './shader.js';
@@ -101,7 +103,19 @@ function _quads(count) {
* `opacity` (default 0.42) peak alpha before distance fade;
* `follow` (default true) wrap the box around the camera; false pins
* it to `center`;
- * `center` (default [0, height / 2, 0]) box centre when not following.
+ * `center` (default [0, height / 2, 0]) box centre when not following;
+ * `groundY` optional local ground cutoff;
+ * `surfaces` optional borrowed meshes/groups which shelter the rain;
+ * `heightAt(x,z)` optional local terrain-height callback, null means no hit;
+ * `shelterResolution` 8..64 (32), square height atlas samples;
+ * `shelterUpdateDistance` local camera travel before rebuilding (radius*.2).
+ * Shelter uses vertical height-field occlusion: no undercuts, sideways entry
+ * under overhangs or moving-surface dynamics. Resolution limits thin roofs and
+ * edge precision. Each rebuild casts at most resolution squared rays, with
+ * cost also depending on source geometry. Atlas bounds cover the rain box plus
+ * movement padding. Call userData.refreshShelter() after moving/editing/hiding
+ * source surfaces; the next render rebuilds. Camera travel and effect transforms
+ * refresh automatically. Source meshes/materials remain caller-owned.
* @returns {THREE.Mesh} Mesh named 'Rainfall', transparent and
* non-shadowing, with `userData.update(t)` advancing the fall.
*/
@@ -117,7 +131,23 @@ export function makeRain(opts = {}) {
const opacity = opts.opacity === undefined ? 0.42 : opts.opacity;
const follow = opts.follow === false ? 0 : 1;
const center = opts.center || [0, height * 0.5, 0];
+ const surfaces = opts.surfaces ?? [];
+ const shelterResolution = opts.shelterResolution ?? 32;
+ const shelterUpdateDistance = opts.shelterUpdateDistance ?? Math.max(.5, radius * .20);
+ const groundY = opts.groundY ?? -1e8;
+ if (!Array.isArray(surfaces) || surfaces.some((surface) => !surface?.isObject3D) ||
+ !Number.isInteger(shelterResolution) || shelterResolution < 8 || shelterResolution > 64 ||
+ !Number.isFinite(shelterUpdateDistance) || shelterUpdateDistance <= 0 ||
+ !Number.isFinite(groundY) || (opts.heightAt != null && typeof opts.heightAt !== 'function')) {
+ throw new RangeError('makeRain: invalid surfaces, heightAt, groundY or shelter atlas options');
+ }
+ if (!Number.isInteger(count) || count < 0 || count > 1000000 ||
+ ![radius, height, speed, length, width, opacity, ...wind, ...center].every(Number.isFinite) ||
+ radius <= 0 || height <= 0 || speed <= 0 || length <= 0 || width <= 0 || opacity < 0 || opacity > 1 ||
+ wind.length !== 2 || center.length !== 3) {
+ throw new RangeError('makeRain: use finite positive dimensions/speed, count 0..1000000, wind [x,z], center [x,y,z] and opacity 0..1');
+ }
const rand = mulberry32(seed);
const inst = _quads(count);
const off = new Float32Array(count * 3);
@@ -145,6 +175,11 @@ export function makeRain(opts = {}) {
// source, and uTime undeclared there is two hard ERRORS in the
// scene build's preflight — every scene importing this file.
uTime: { value: 0 },
+ uCameraLocal: { value: new THREE.Vector3() },
+ uShelterMap: { value: null },
+ uShelterRect: { value: new THREE.Vector4() },
+ uHasShelter: { value: 0 },
+ uGroundY: { value: groundY },
uVel: { value: new THREE.Vector3(wind[0], -speed, wind[1]) },
uBox: { value: new THREE.Vector3(radius * 2, height, radius * 2) },
uCenter: { value: new THREE.Vector3(...center) },
@@ -168,19 +203,21 @@ export function makeRain(opts = {}) {
'attribute vec3 aCorner;',
'attribute vec3 iOff; attribute vec3 iExtra;',
'uniform float uTime;',
- 'uniform vec3 uVel; uniform vec3 uBox;',
+ 'uniform vec3 uVel; uniform vec3 uBox; uniform vec3 uCameraLocal;',
'uniform vec3 uCenter; uniform float uFollow;',
'uniform float uLen; uniform float uWidth; uniform float uFar;',
+ 'uniform sampler2D uShelterMap; uniform vec4 uShelterRect;',
+ 'uniform float uHasShelter; uniform float uGroundY;',
].join('\n'),
vertexMain: [
' vUv = uv; vJit = iExtra.z;',
- ' vec3 anchor = mix(uCenter, cameraPosition, uFollow);',
+ ' vec3 anchor = mix(uCenter, uCameraLocal, uFollow);',
// Wrap the whole field into a box centred on the anchor: rain is
// everywhere the camera is, for a fixed instance budget.
' vec3 p = mod(iOff + uVel * uTime - anchor + uBox * 0.5, uBox)',
' - uBox * 0.5 + anchor;',
' vec3 axis = normalize(uVel);',
- ' vec3 toCam = p - cameraPosition;',
+ ' vec3 toCam = p - uCameraLocal;',
' float dist = length(toCam);',
' vec3 side = cross(axis, toCam / max(dist, 1e-4));',
' float sl = length(side);',
@@ -189,6 +226,15 @@ export function makeRain(opts = {}) {
' + side * (aCorner.x * uWidth);',
' vFade = iExtra.y * smoothstep(1.0, 6.0, dist)',
' * (1.0 - smoothstep(uFar * 0.55, uFar, dist));',
+ ' vec3 head = p + axis * (.5 * uLen * iExtra.x);',
+ ' float roof = uGroundY;',
+ ' if (uHasShelter > .5) {',
+ ' vec2 shelterUv = (head.xz - uShelterRect.xy) / uShelterRect.zw;',
+ ' if (all(greaterThanEqual(shelterUv, vec2(0.0))) &&',
+ ' all(lessThanEqual(shelterUv, vec2(1.0))))',
+ ' roof = max(roof, texture2D(uShelterMap, shelterUv).r);',
+ ' }',
+ ' vFade *= step(roof + .015, head.y);',
].join('\n'),
fragmentHead: [
'uniform vec3 uColor; uniform vec3 uRim;',
@@ -223,8 +269,114 @@ export function makeRain(opts = {}) {
mesh.name = 'Rainfall';
mesh.frustumCulled = false; // positions live in the shader
mesh.renderOrder = 4; // in front of splashes and puddles
+ keepOutOfDepthPasses(mesh);
+ const beforeRender = mesh.onBeforeRender;
+ const shelter = makeShelterAtlas(mesh, {
+ surfaces, heightAt: opts.heightAt, groundY, resolution: shelterResolution,
+ distance: shelterUpdateDistance, radius, height, center, follow,
+ });
+ const inverse = new THREE.Matrix4();
+ mesh.onBeforeRender = (...args) => {
+ beforeRender.apply(mesh, args);
+ const camera = args[2];
+ inverse.copy(mesh.matrixWorld).invert();
+ camera.getWorldPosition(mat.uniforms.uCameraLocal.value).applyMatrix4(inverse);
+ shelter?.update(mat.uniforms.uCameraLocal.value, inverse);
+ };
mesh.userData.update = (t) => { mat.uniforms.uTime.value = t; };
- return keepOutOfDepthPasses(mesh);
+ const owned = snapshotResources(mesh);
+ if (shelter) owned.add(shelter.texture);
+ return attachDisposal(mesh, owned);
+}
+
+
+/** A bounded vertical height atlas; source surfaces remain caller-owned. */
+function makeShelterAtlas(mesh, cfg) {
+ if (!cfg.surfaces.length && !cfg.heightAt) return null;
+ const n = cfg.resolution;
+ const data = new Float32Array(n * n).fill(cfg.groundY);
+ const texture = new THREE.DataTexture(data, n, n, THREE.RedFormat, THREE.FloatType);
+ texture.minFilter = texture.magFilter = THREE.NearestFilter;
+ texture.generateMipmaps = false;
+ texture.needsUpdate = true;
+ const uniforms = mesh.material.uniforms;
+ uniforms.uShelterMap.value = texture;
+ const rect = uniforms.uShelterRect.value;
+ const lastMatrix = new THREE.Matrix4();
+ const anchor = new THREE.Vector2(Infinity, Infinity);
+ const ray = new THREE.Raycaster();
+ const point = new THREE.Vector3(), hitLocal = new THREE.Vector3();
+ const box = new THREE.Box3(), corner = new THREE.Vector3();
+ const direction = new THREE.Vector3();
+ let dirty = true;
+ const info = { resolution: n, rebuilds: 0, raysPerRebuild: n * n, texelSize: 0 };
+ mesh.userData.shelter = info;
+ mesh.userData.refreshShelter = () => { dirty = true; };
+ mesh.userData.sampleShelterHeight = (x, z) => {
+ if (!Number.isFinite(x) || !Number.isFinite(z)) throw new RangeError('Rainfall.sampleShelterHeight: finite coordinates required');
+ if (!info.rebuilds || x < rect.x || x > rect.x + rect.z || z < rect.y || z > rect.y + rect.w) return null;
+ const ix = Math.min(n - 1, Math.floor((x - rect.x) / rect.z * n));
+ const iz = Math.min(n - 1, Math.floor((z - rect.y) / rect.w * n));
+ const value = data[iz * n + ix];
+ return value <= -1e7 ? null : value;
+ };
+ return {
+ texture,
+ update(cameraLocal, inverse) {
+ const x = cfg.follow ? cameraLocal.x : cfg.center[0];
+ const z = cfg.follow ? cameraLocal.z : cfg.center[2];
+ if (!dirty && Math.hypot(x - anchor.x, z - anchor.y) < cfg.distance && lastMatrix.equals(mesh.matrixWorld)) return;
+ const extent = 2 * (cfg.radius + cfg.distance + .5);
+ const texel = extent / n;
+ // Keep the lattice in fixed local coordinates while the atlas follows.
+ const cx = Math.round(x / texel) * texel, cz = Math.round(z / texel) * texel;
+ rect.set(cx - extent * .5, cz - extent * .5, extent, extent);
+ let top = Math.max(cfg.center[1], cameraLocal.y) + cfg.height;
+ for (const surface of cfg.surfaces) {
+ surface.updateWorldMatrix(true, true);
+ box.setFromObject(surface);
+ if (box.isEmpty()) continue;
+ for (let mask = 0; mask < 8; mask++) {
+ corner.set(mask & 1 ? box.max.x : box.min.x,
+ mask & 2 ? box.max.y : box.min.y, mask & 4 ? box.max.z : box.min.z)
+ .applyMatrix4(inverse);
+ top = Math.max(top, corner.y + 1);
+ }
+ }
+ direction.set(0, -1, 0).transformDirection(mesh.matrixWorld);
+ ray.ray.direction.copy(direction);
+ for (let row = 0; row < n; row++) for (let col = 0; col < n; col++) {
+ const px = rect.x + (col + .5) * texel, pz = rect.y + (row + .5) * texel;
+ let height = cfg.groundY;
+ if (cfg.heightAt) {
+ const sample = cfg.heightAt(px, pz);
+ if (sample != null && !Number.isFinite(sample)) throw new RangeError('Rainfall.heightAt must return a finite height or null');
+ if (sample != null) height = Math.max(height, sample);
+ }
+ if (cfg.surfaces.length) {
+ point.set(px, top, pz).applyMatrix4(mesh.matrixWorld);
+ ray.ray.origin.copy(point);
+ for (const hit of ray.intersectObjects(cfg.surfaces, true)) {
+ let visible = true;
+ for (let object = hit.object; object; object = object.parent) if (!object.visible) { visible = false; break; }
+ if (!visible) continue;
+ hitLocal.copy(hit.point).applyMatrix4(inverse);
+ height = Math.max(height, hitLocal.y);
+ break;
+ }
+ }
+ data[row * n + col] = height;
+ }
+ texture.needsUpdate = true;
+ uniforms.uHasShelter.value = 1;
+ anchor.set(x, z);
+ lastMatrix.copy(mesh.matrixWorld);
+ dirty = false;
+ info.rebuilds++;
+ info.texelSize = texel;
+ info.bounds = [rect.x, rect.y, rect.x + extent, rect.y + extent];
+ },
+ };
}
/**
@@ -422,7 +574,7 @@ export function makeSplashes(opts = {}) {
const pts = _impactPoints(opts, rand);
if (!pts.length) {
group.userData.update = () => {};
- return group;
+ return attachDisposal(group, snapshotResources(group));
}
const n = pts.length;
@@ -597,7 +749,9 @@ export function makeSplashes(opts = {}) {
ringMat.uniforms.uTime.value = t2;
if (crownMat) crownMat.uniforms.uTime.value = t2;
};
- return keepOutOfDepthPasses(group);
+ const owned = snapshotResources(group);
+ if (crownMat) owned.add(crownMat.uniforms.map.value);
+ return attachDisposal(keepOutOfDepthPasses(group), owned);
}
/**
@@ -791,7 +945,7 @@ export function makePuddle(w, d, opts = {}) {
// Crest and trough are not the same water: a crest tips toward
// the sky it mirrors and goes cool, a trough shows the warm bed.
// One achromatic multiply left the pool on a single flat hue.
- const s = h / amp;
+ const s = amp > 0 ? h / amp : 0;
const b = Math.max(0.72, Math.min(1.35, 1 + s * 0.14));
const w = Math.max(0, Math.min(1, 0.5 + 0.5 * s));
col[vi * 3] = b * (1.06 - 0.12 * w);
@@ -808,5 +962,7 @@ export function makePuddle(w, d, opts = {}) {
mesh.receiveShadow = true;
mesh.userData.update = update;
update(0);
- return mesh;
+ const owned = snapshotResources(mesh);
+ if (mat.alphaMap) owned.add(mat.alphaMap);
+ return attachDisposal(mesh, owned);
}
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/roadway.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/roadway.js
index 5f73255e..e2e9d202 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/roadway.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/roadway.js
@@ -30,16 +30,13 @@
* Tracks that must run somewhere else on the same material take
* `offset` (metres across) rather than a second centreline.
*
- * Gloss is per MATERIAL, not per pixel — all three write only at
- * `<color_fragment>`, before `<roughnessmap_fragment>`, and none uses
- * `patchStandard`'s `roughnessBody` — so each patch composes ONE factor
- * through `composeRoughness`: polished ruts and a damp gutter drop it,
- * grit and loose aggregate raise it.
+ * 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, composeRoughness, glslAxes, glslTriNoise, matteFactor,
+ patchStandard, glslAxes, glslTriNoise,
seedVec3, toColor, unit, WORLD_VARYINGS,
} from './shader.js';
@@ -63,6 +60,14 @@ const ROAD_HEAD = [
' return 1.0 - smoothstep(0.30, 0.95,',
' length(fwidth(p)) / max(cycle, 1e-4));',
'}',
+ 'vec3 astraRoadBump(vec3 eye, vec3 n, float height) {',
+ ' vec3 dx = dFdx(eye), dy = dFdy(eye);',
+ ' vec3 a = cross(dy, n), b = cross(n, dx);',
+ ' float determinant = dot(dx, a);',
+ ' if (abs(determinant) < 1e-12) return n;',
+ ' return normalize(abs(determinant) * n - sign(determinant)',
+ ' * (dFdx(height) * a + dFdy(height) * b));',
+ '}',
].join('\n');
// `transformed` is still object-space after <begin_vertex>, so the
@@ -75,14 +80,14 @@ const FRAME_BODY = [
' vec4 rwO = vec4(0.0, 0.0, 0.0, 1.0);',
'#ifdef USE_INSTANCING',
' rwP = instanceMatrix * rwP;',
- ' rwN = mat3(instanceMatrix) * rwN;',
+ ' 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 = normalize((modelMatrix * vec4(rwN, 0.0)).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.
@@ -181,7 +186,7 @@ function withFrame(material, opts) {
* 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
- * `composeRoughness`, glossier.
+ * 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
@@ -212,22 +217,6 @@ export function patchRoadSurface(material, opts = {}) {
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;
- // Polished ruts and a damp gutter are the reachable half of gloss;
- // loose stone is the matte half — but this ONE factor is the whole
- // material's, so it has to be the AREA-WEIGHTED average and not the
- // polished rut's own value. Wheel strips cover about a quarter of a
- // lane and the gutter a twelfth of the width; spending the rut's full
- // polish on all of it turns the road into a sky mirror here, where
- // there is no post chain, a bright sky environment is the specular
- // source and a road is nearly always seen at a grazing angle.
- // Measured 2026-09-01 on this renderer: the old factors composed a
- // tarmac authored at 0.85 down to 0.63 and it read (171,172,175) — a
- // white card — while these compose the same material to 0.86 and it
- // reads (136,138,144), with the repairs, the pale wheel strips and the
- // dark drip line all back in the frame.
- composeRoughness(material, 'road:surface',
- Math.min(matteFactor(material, 0.16 * agg),
- 1 + 0.16 * agg - 0.09 * wear - 0.05 * gutter));
withFrame(material, opts);
return patchStandard(material, {
name: 'road:surface',
@@ -286,17 +275,19 @@ export function patchRoadSurface(material, opts = {}) {
// 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 roGrain = ((roG1 - 0.5) * 0.52 + (roG2 - 0.5) * 0.34',
- ' + (roG3 - 0.5) * 0.30 * roFd) * roFd;',
+ ' 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 + roG3 * 0.55)',
+ ' 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), roG2);',
+ ' 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);',
@@ -317,11 +308,11 @@ export function patchRoadSurface(material, opts = {}) {
' 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 = smoothstep(roPs + roPaa, roPs - roPaa, roPf);',
+ ' vec2 roPe = 1.0 - smoothstep(roPs - roPaa, roPs + roPaa, roPf);',
' float roPk = roPe.x * roPe.y',
' * step(1.0 - uRoadPatch, astraHash21(roPi));',
- ' vec2 roPn = smoothstep(roPs - 0.05 + roPaa, roPs - 0.05 - roPaa,',
- ' roPf);',
+ ' 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.
@@ -371,6 +362,18 @@ export function patchRoadSurface(material, opts = {}) {
// 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 = astraRoadBump(-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'),
});
}
@@ -414,10 +417,6 @@ 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;
- // Grit and weeds are matte, and they cover only the band, so this is
- // the smallest gloss move in the library.
- composeRoughness(material, 'road:seam',
- matteFactor(material, 0.06 + 0.08 * weeds));
withFrame(material, opts);
return patchStandard(material, {
name: 'road:seam',
@@ -482,7 +481,11 @@ export function patchSeamBand(material, opts = {}) {
' 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 = astraRoadBump(-vViewPosition, normal, smHeight);',
});
}
@@ -496,12 +499,10 @@ export function patchSeamBand(material, opts = {}) {
* the road frame's direction, each wandering on its own field (a pair
* of ruled lines is a railway, not a vehicle).
*
- * ALBEDO AND GLOSS ONLY: per-pixel DISPLACEMENT is not reachable from
- * this hook — `fragmentBody` edits `diffuseColor`, and a vertex
- * displacement would tear every hard-edged geometry open at its rim —
- * so depth is sold two ways instead. The press is DARKER (turned-over,
- * damp material) and the ground it displaced piles into a paler RIM
- * just outside it. `depth` drives both.
+ * 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
@@ -538,12 +539,7 @@ export function patchTracks(material, opts = {}) {
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, which is smoother than the loose
- // surface around it — over the width of the tracks, which is a tenth
- // of the ground they cross, and this factor is the whole material's
- // (see `patchRoadSurface`: an over-polished ground is a sky mirror at
- // a grazing angle on this renderer).
- composeRoughness(material, 'road:tracks', 1 - 0.08 * depth);
+ // Pressed ground is packed and damp only inside the track mask.
withFrame(material, opts);
return patchStandard(material, {
name: 'road:tracks',
@@ -618,6 +614,10 @@ export function patchTracks(material, opts = {}) {
// 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 = astraRoadBump(-vViewPosition, normal, tkHeight);',
});
}
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rock.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rock.js
new file mode 100644
index 00000000..f195ee9f
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rock.js
@@ -0,0 +1,347 @@
+/** Closed fractured stones with mineral-scale shading, erosion and a seated foot.
+ * The source form is an intersection of fracture planes, not a stretched sphere.
+ * Shared-edge displacement keeps the surface watertight after tessellation.
+ */
+import * as THREE from 'three';
+import { ConvexGeometry } from 'three/addons/geometries/ConvexGeometry.js';
+import { fbm3, mulberry32 } from './noise.js';
+import { patchStandard } from './shader.js';
+
+const TYPES = {
+ sandstone: { color: 0x9e7250, erosion: 0.028, roughness: 0.91, index: 0 },
+ granite: { color: 0x777970, erosion: 0.040, roughness: 0.79, index: 1 },
+ basalt: { color: 0x535651, erosion: 0.020, roughness: 0.86, index: 2 },
+};
+const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
+const key = (p) => p.toArray().map((x) => Math.round(x * 1e6)).join(',');
+
+function fracturePlanes(rand, type) {
+ // A broken block has several unrelated joint sets. Evenly spaced upright
+ // planes make every seed a column, so distribute fractures in solid angle.
+ const planes = [{ n: new THREE.Vector3(0, -1, 0), d: 0.56 }];
+ const rotation = rand() * Math.PI * 2, count = type === 'basalt' ? 15 : 19;
+ for (let i = 0; i < count; i++) {
+ const y = 1 - 2 * (i + 0.5) / count, r = Math.sqrt(1 - y * y);
+ const a = rotation + i * 2.39996323 + (rand() - 0.5) * 0.4;
+ const n = new THREE.Vector3(Math.cos(a) * r, y + (rand() - 0.5) * 0.26, Math.sin(a) * r).normalize();
+ planes.push({ n, d: 0.61 + rand() * 0.32 });
+ }
+ // Bedding is a broad tilted break, not an axis-aligned lid.
+ planes.push({ n: new THREE.Vector3((rand() - 0.5) * 0.7, 1, (rand() - 0.5) * 0.7).normalize(), d: 0.62 + rand() * 0.2 });
+ return planes;
+}
+
+function planeHull(planes) {
+ const points = [], seen = new Set();
+ for (let i = 0; i < planes.length; i++) for (let j = i + 1; j < planes.length; j++) for (let k = j + 1; k < planes.length; k++) {
+ const a = planes[i], b = planes[j], c = planes[k];
+ const bc = new THREE.Vector3().crossVectors(b.n, c.n), det = a.n.dot(bc);
+ if (Math.abs(det) < 1e-7) continue;
+ const p = bc.multiplyScalar(a.d)
+ .addScaledVector(new THREE.Vector3().crossVectors(c.n, a.n), b.d)
+ .addScaledVector(new THREE.Vector3().crossVectors(a.n, b.n), c.d).divideScalar(det);
+ if (!planes.every((plane) => plane.n.dot(p) <= plane.d + 1e-6)) continue;
+ const id = key(p);
+ if (!seen.has(id)) { seen.add(id); points.push(p); }
+ }
+ return new ConvexGeometry(points);
+}
+
+function rockGeometry(opts, type, size, rand) {
+ const segments = clamp(Math.round(opts.detail ?? 6), 1, 12) * 2;
+ // Keep the exact plane intersections at every detail level. Projecting a
+ // sampled sphere misses the corners and makes small rocks look like pillows.
+ const planes = fracturePlanes(rand, type), firstHull = planeHull(planes);
+ const corners = [], cornerKeys = new Set();
+ for (let i = 0; i < firstHull.attributes.position.count; i++) {
+ const p = new THREE.Vector3().fromBufferAttribute(firstHull.attributes.position, i), id = key(p);
+ if (!cornerKeys.has(id)) { cornerKeys.add(id); corners.push(p); }
+ }
+ // Smaller secondary breaks chip selected corners of the main joint block.
+ // Their true bevel faces preserve a usable silhouette even at detail 1.
+ for (let i = 0; i < 9; i++) {
+ const p = corners[Math.floor(rand() * corners.length)];
+ const n = p.clone().normalize().add(new THREE.Vector3(rand() - 0.5, rand() - 0.5, rand() - 0.5).multiplyScalar(0.3)).normalize();
+ planes.push({ n, d: Math.max(0.38, n.dot(p) - 0.045 - rand() * 0.095) });
+ }
+ firstHull.dispose();
+ const hull = planeHull(planes);
+ const src = hull.attributes.position;
+ const vertices = [], cavities = [], normalGroups = [], welded = new Map();
+ const seed = opts.seed ?? 31, erosion = TYPES[type].erosion * clamp(opts.weathering ?? 1, 0, 2);
+ const chips = [];
+ for (let i = 0; i < 15; i++) {
+ const a = rand() * Math.PI * 2, y = rand() * 1.5 - 0.5;
+ const dir = new THREE.Vector3(Math.cos(a), y, Math.sin(a)).normalize();
+ const u = new THREE.Vector3(-dir.z, 0, dir.x).normalize().applyAxisAngle(dir, rand() * Math.PI);
+ const v = new THREE.Vector3().crossVectors(dir, u);
+ chips.push({ dir, u, v, width: 0.13 + rand() * (type === 'sandstone' ? 0.28 : 0.17),
+ aspect: 0.18 + rand() * (type === 'sandstone' ? 0.52 : 0.27),
+ depth: 0.015 + rand() * (type === 'sandstone' ? 0.09 : 0.05) });
+ }
+ const beds = Array.from({ length: 3 }, () => ({
+ height: -0.31 + rand() * 0.85,
+ width: 0.024 + rand() * 0.025, depth: 0.025 + rand() * 0.04,
+ }));
+ const deform = (p) => {
+ const id = key(p);
+ if (welded.has(id)) return welded.get(id);
+ let radius = p.length();
+ const dir = p.clone().divideScalar(radius);
+ const baseFade = THREE.MathUtils.smoothstep(p.y, -0.56, -0.4);
+ let cavity = 0;
+ for (const chip of chips) {
+ if (dir.dot(chip.dir) < 0.6) continue;
+ // Straight cleavage lips with sloped floors. A smooth radial falloff
+ // creates circular craters, which are inappropriate for broken granite.
+ const u = dir.dot(chip.u) / chip.width;
+ const v = dir.dot(chip.v) / (chip.width * chip.aspect);
+ const footprint = Math.max(Math.abs(u), Math.abs(v));
+ const cut = clamp((1 - footprint) * 2.8, 0, 1);
+ cavity += cut * chip.depth;
+ }
+ const coarse = fbm3(p.x * 3.8, p.y * 3.8, p.z * 3.8, { seed, octaves: 3 });
+ const grain = fbm3(p.x * 16, p.y * 16, p.z * 16, { seed: seed + 87, octaves: 2 });
+ let relief = (coarse * 0.48 + grain * 0.11) * erosion, bedInset = 0;
+ const distances = planes.map((plane) => Math.abs(plane.n.dot(p) - plane.d)).sort((a, b) => a - b);
+ const edgeWear = 1 - THREE.MathUtils.smoothstep(distances[1], 0, 0.12);
+ relief += grain * erosion * edgeWear * 0.85;
+ if (type === 'sandstone') {
+ const bed = p.y + p.x * 0.18 - p.z * 0.11;
+ const weakBed = fbm3(p.x * 0.65, bed * 9, p.z * 0.65, { seed: seed + 12, octaves: 2 });
+ relief -= Math.max(0, weakBed + 0.08) * erosion * 0.85;
+ // A few weak bedding planes form actual recessed ledges. The joint
+ // spacing and depth vary per seed; this is not a periodic stripe shader.
+ const warp = fbm3(p.x * 2, p.y * 0.4, p.z * 2, { seed: seed + 36, octaves: 2 }) * 0.025;
+ for (const joint of beds) {
+ const inset = clamp(1 - Math.abs(bed + warp - joint.height) / joint.width, 0, 1);
+ bedInset += inset * joint.depth * clamp(opts.weathering ?? 1, 0, 2) * (1 - Math.abs(dir.y) * 0.65);
+ }
+ }
+ radius += (relief - Math.min(0.28, cavity) * clamp(opts.weathering ?? 1, 0, 2)) * baseFade;
+ p.copy(dir).multiplyScalar(radius);
+ p.x *= 1 - bedInset * baseFade; p.z *= 1 - bedInset * baseFade;
+ const result = { p, cavity: clamp(cavity * 5 * baseFade, 0, 1), id };
+ welded.set(id, result);
+ return result;
+ };
+ const a = new THREE.Vector3(), b = new THREE.Vector3(), c = new THREE.Vector3();
+ for (let f = 0; f < src.count; f += 3) {
+ a.fromBufferAttribute(src, f); b.fromBufferAttribute(src, f + 1); c.fromBufferAttribute(src, f + 2);
+ const center = a.clone().add(b).add(c).divideScalar(3);
+ let group = 0, error = Infinity;
+ planes.forEach((plane, i) => {
+ const distance = Math.abs(plane.n.dot(center) - plane.d);
+ if (distance < error) { error = distance; group = i; }
+ });
+ const at = (i, j) => a.clone().multiplyScalar(1 - (i + j) / segments)
+ .addScaledVector(b, i / segments).addScaledVector(c, j / segments);
+ const emit = (...points) => points.forEach((p) => {
+ const sample = deform(p);
+ vertices.push(sample.p.x, sample.p.y, sample.p.z); cavities.push(sample.cavity);
+ normalGroups.push(`${group}:${sample.id}`);
+ });
+ for (let i = 0; i < segments; i++) for (let j = 0; j < segments - i; j++) {
+ emit(at(i, j), at(i + 1, j), at(i, j + 1));
+ if (i + j + 1 < segments) emit(at(i + 1, j), at(i + 1, j + 1), at(i, j + 1));
+ }
+ }
+ hull.dispose();
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));
+ geo.setAttribute('rockCavity', new THREE.Float32BufferAttribute(cavities, 1));
+ geo.computeBoundingBox();
+ const bb = geo.boundingBox, span = bb.getSize(new THREE.Vector3()), center = bb.getCenter(new THREE.Vector3());
+ const p = geo.attributes.position;
+ const burial = clamp(opts.burial ?? 0.06, 0, 0.5);
+ for (let i = 0; i < p.count; i++) p.setXYZ(i,
+ (p.getX(i) - center.x) / span.x * size[0],
+ (p.getY(i) - bb.min.y) / span.y * size[1] - burial * size[1],
+ (p.getZ(i) - center.z) / span.z * size[2]);
+ // Smooth within each original fracture plane, retaining its sharp boundary.
+ // A per-triangle crease threshold produces sawtooth seams through a cavity;
+ // these groups depend on geological planes rather than tessellation angles.
+ const accumulated = new Map(), shared = new Map(), ab = new THREE.Vector3(), ac = new THREE.Vector3();
+ for (let i = 0; i < p.count; i += 3) {
+ a.fromBufferAttribute(p, i); b.fromBufferAttribute(p, i + 1); c.fromBufferAttribute(p, i + 2);
+ const n = ab.copy(b).sub(a).cross(ac.copy(c).sub(a));
+ for (let j = 0; j < 3; j++) {
+ const id = normalGroups[i + j];
+ if (!accumulated.has(id)) accumulated.set(id, new THREE.Vector3());
+ accumulated.get(id).add(n);
+ const vertex = id.slice(id.indexOf(':') + 1);
+ if (!shared.has(vertex)) shared.set(vertex, new THREE.Vector3());
+ shared.get(vertex).add(n);
+ }
+ }
+ const normals = new Float32Array(p.count * 3);
+ const edgeSoftness = clamp(opts.weathering ?? 1, 0, 2) * 0.24;
+ for (let i = 0; i < p.count; i++) {
+ const id = normalGroups[i], vertex = id.slice(id.indexOf(':') + 1);
+ accumulated.get(id).clone().normalize().lerp(shared.get(vertex).clone().normalize(), edgeSoftness)
+ .normalize().toArray(normals, i * 3);
+ }
+ geo.setAttribute('normal', new THREE.BufferAttribute(normals, 3));
+ geo.computeBoundingBox(); geo.computeBoundingSphere();
+ return geo;
+}
+
+function rockMaterial(opts, type, height) {
+ const def = TYPES[type];
+ const mat = new THREE.MeshStandardMaterial({ color: opts.color ?? def.color, roughness: def.roughness });
+ mat.name = `${type}Stone`;
+ patchStandard(mat, {
+ name: 'fracturedRockV2',
+ uniforms: {
+ uRockKind: { value: def.index }, uRockSeed: { value: (opts.seed ?? 31) % 997 },
+ uRockHeight: { value: height }, uRockMoisture: { value: clamp(opts.moisture ?? 0, 0, 1) },
+ uRockMoss: { value: clamp(opts.moss ?? 0, 0, 1) },
+ },
+ vertexHead: 'attribute float rockCavity; varying vec3 vRockLocal; varying vec3 vRockLocalNormal; varying float vRockCavity;',
+ vertexBody: 'vRockLocal = position; vRockLocalNormal = normal; vRockCavity = rockCavity;',
+ fragmentHead: `
+ varying vec3 vRockLocal, vRockLocalNormal;
+ varying float vRockCavity;
+ uniform float uRockKind, uRockSeed, uRockHeight, uRockMoisture, uRockMoss;
+ float rockHash(vec3 p) {
+ p = fract(p * 0.1031);
+ p += dot(p, p.yzx + 33.33);
+ return fract((p.x + p.y) * p.z);
+ }
+ // Value and analytic spatial gradient. The gradient is filtered before
+ // normal perturbation; differentiating sampled noise makes visible
+ // 2x2 pixel blocks at grazing angles and when the camera approaches.
+ vec4 rockNoiseGradient(vec3 p) {
+ vec3 i = floor(p), f = fract(p);
+ vec3 u = f*f*f*(f*(f*6.0-15.0)+10.0);
+ vec3 du = 30.0*f*f*(f*(f-2.0)+1.0);
+ float a=rockHash(i), b=rockHash(i+vec3(1,0,0));
+ float c=rockHash(i+vec3(0,1,0)), d=rockHash(i+vec3(1,1,0));
+ float e=rockHash(i+vec3(0,0,1)), f1=rockHash(i+vec3(1,0,1));
+ float g=rockHash(i+vec3(0,1,1)), h=rockHash(i+vec3(1,1,1));
+ float x0=mix(a,b,u.x), x1=mix(c,d,u.x), x2=mix(e,f1,u.x), x3=mix(g,h,u.x);
+ float y0=mix(x0,x1,u.y), y1=mix(x2,x3,u.y);
+ return vec4(mix(y0,y1,u.z),
+ mix(mix(b-a,d-c,u.y),mix(f1-e,h-g,u.y),u.z)*du.x,
+ mix(x1-x0,x3-x2,u.z)*du.y,(y1-y0)*du.z);
+ }
+ float rockNoise(vec3 p) { return rockNoiseGradient(p).x; }
+ `,
+ fragmentBody: `
+ vec3 rockP = vRockLocal + vec3(uRockSeed * 0.17, 0.0, uRockSeed * 0.31);
+ float rockMacro = rockNoise(rockP * 1.4);
+ vec4 rockMesoscale = rockNoiseGradient(rockP * 17.0);
+ float rockMedium = rockMesoscale.x;
+ float rockFootprint = max(length(dFdx(rockP)), length(dFdy(rockP)));
+ float rockFineFade = 1.0 - smoothstep(0.001, 0.009, rockFootprint);
+ vec4 rockMicro = rockNoiseGradient(rockP * 220.0);
+ float rockFine = mix(0.5, rockMicro.x, rockFineFade);
+ float rockBumpFade = 1.0 - smoothstep(0.014, 0.055, rockFootprint);
+ vec3 rockGradient = rockMesoscale.yzw * (17.0 * 0.0024 * rockBumpFade)
+ + rockMicro.yzw * (220.0 * 0.00035 * rockFineFade);
+ float rockBase = 1.0 - smoothstep(-uRockHeight * 0.04, uRockHeight * 0.52, vRockLocal.y);
+ float rockWet = uRockMoisture * clamp(0.16 + 0.77 * rockBase + vRockCavity * 0.16, 0.0, 1.0);
+ // Large alteration patches and crevice deposits are separate from
+ // mineral grains. Their physical scales survive changes in view range.
+ diffuseColor.rgb *= 0.68 + 0.48 * rockMacro;
+ diffuseColor.rgb *= 1.0 - vRockCavity * 0.17;
+ if (uRockKind < 0.5) {
+ vec3 rockBedDirection = vec3(0.18, 1.0, -0.11);
+ float rockBedCoord = dot(vRockLocal, rockBedDirection) * 4.8
+ + rockNoise(rockP * 0.6) * 0.75;
+ float rockBedFade = 1.0 - smoothstep(0.12, 0.48, fwidth(rockBedCoord));
+ vec4 rockBed = rockNoiseGradient(vec3(rockP.x * 0.65, rockBedCoord, rockP.z * 0.65));
+ float rockIron = smoothstep(0.47, 0.75, rockBed.x) * rockBedFade;
+ diffuseColor.rgb *= mix(vec3(1.05, 1.02, 0.96), vec3(0.87, 0.76, 0.65), rockIron * 0.56);
+ diffuseColor.rgb *= 0.96 + (rockMedium - 0.5) * 0.12 + (rockFine - 0.5) * 0.16;
+ rockGradient += (rockBed.yzw * vec3(0.65, 0.0, 0.65)
+ + rockBed.z * rockBedDirection * 4.8) * (0.004 * rockBedFade);
+ } else if (uRockKind < 1.5) {
+ vec4 rockCrystal = rockNoiseGradient(rockP * 92.0);
+ float rockCrystalFade = 1.0 - smoothstep(0.002, 0.013, rockFootprint);
+ float rockQuartz = smoothstep(0.57, 0.8, rockCrystal.x) * rockCrystalFade;
+ float rockMica = (1.0 - smoothstep(0.19, 0.4, rockCrystal.x)) * rockCrystalFade;
+ diffuseColor.rgb *= 0.95 + rockQuartz * 0.17 - rockMica * 0.19;
+ float rockOxide = smoothstep(0.42, 0.7, rockNoise(rockP * 2.1));
+ diffuseColor.rgb *= mix(vec3(0.88, 0.96, 1.0), vec3(1.15, 0.93, 0.71), rockOxide * 0.72);
+ rockGradient += rockCrystal.yzw * (92.0 * 0.00055 * rockCrystalFade);
+ } else {
+ float rockPores = 1.0 - smoothstep(0.1, 0.34, rockFine);
+ diffuseColor.rgb *= 0.88 + rockMedium * 0.16 - rockPores * 0.19;
+ float rockOxide = smoothstep(0.53, 0.78, rockNoise(rockP * 3.8));
+ diffuseColor.rgb *= mix(vec3(0.95, 0.98, 1.0), vec3(1.16, 0.95, 0.77), rockOxide * 0.42);
+ }
+ float rockShelter = clamp(0.36 + normalize(vRockLocalNormal).y * 0.5 + rockBase * 0.2 + vRockCavity * 0.4, 0.0, 1.0);
+ float rockMoss = smoothstep(0.46, 0.67, rockNoise(rockP * 3.5) + (rockMedium - 0.5) * 0.1)
+ * rockShelter * uRockMoss;
+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.058, 0.086, 0.027) * (0.72 + rockMedium * 0.5), rockMoss);
+ diffuseColor.rgb *= 1.0 - rockWet * 0.36;
+ `,
+ roughnessBody: 'roughnessFactor = clamp(roughnessFactor + (rockMedium - 0.5) * 0.16 - rockWet * 0.48, 0.24, 0.98);',
+ normalBody: `
+ vec3 rockDx = dFdx(-vViewPosition), rockDy = dFdy(-vViewPosition);
+ vec3 rockR1 = cross(rockDy, normal), rockR2 = cross(normal, rockDx);
+ float rockDet = dot(rockDx, rockR1);
+ normal = normalize(abs(rockDet) * normal - sign(rockDet) *
+ (dot(rockGradient, dFdx(vRockLocal)) * rockR1 + dot(rockGradient, dFdy(vRockLocal)) * rockR2));
+ `,
+ });
+ return mat;
+}
+
+/** A closed Mesh. type sandstone|granite|basalt; seed; size metres or [x,y,z];
+ * detail 1..12 surface resolution; weathering 0..2; moisture/moss 0..1;
+ * burial fraction (default .06). Default origin is just above the buried foot.
+ * Shading follows local coordinates after parenting, rotation and scaling.
+ * userData.update(t,dt) and userData.dispose() match the animated effects.
+ */
+export function makeRock(opts = {}) {
+ const type = opts.type ?? 'granite';
+ if (!TYPES[type]) throw new RangeError('rock type must be sandstone, granite or basalt');
+ const s = opts.size ?? 1.8;
+ const size = Array.isArray(s) ? s : [s * 1.2, s * 0.82, s];
+ if (size.length !== 3 || !size.every((v) => Number.isFinite(v) && v > 0)) throw new RangeError('rock size must be positive metres');
+ const geometry = rockGeometry(opts, type, size, mulberry32(opts.seed ?? 31));
+ const material = rockMaterial(opts, type, size[1]);
+ const rock = new THREE.Mesh(geometry, material);
+ rock.name = opts.name ?? `${type[0].toUpperCase() + type.slice(1)}Rock`;
+ rock.castShadow = true; rock.receiveShadow = true;
+ rock.userData.update = () => {};
+ let disposed = false;
+ rock.userData.dispose = () => {
+ if (disposed) return;
+ disposed = true;
+ geometry.dispose(); material.dispose();
+ };
+ rock.userData.seed = opts.seed ?? 31;
+ rock.userData.rockType = type;
+ return rock;
+}
+
+/** Seeded scatter; heightAt(x,z) is local to the returned group. Each rock owns
+ * its geometry and material; cap count for close foreground dressing, use
+ * instancing.js for distant repetitions of a few shared prototypes.
+ */
+export function makeRockField(opts = {}) {
+ const rand = mulberry32(opts.seed ?? 31), group = new THREE.Group();
+ const owned = [];
+ group.name = opts.name ?? 'RockField';
+ const count = clamp(Math.round(opts.count ?? 24), 0, 160), radius = Math.max(0.1, opts.radius ?? 9);
+ for (let i = 0; i < count; i++) {
+ const a = rand() * Math.PI * 2, r = Math.sqrt(rand()) * radius;
+ const x = Math.cos(a) * r, z = Math.sin(a) * r;
+ const seed = Math.floor(rand() * 100000), factor = 0.4 + rand() * 0.9;
+ const size = Array.isArray(opts.size) ? opts.size.map((v) => v * factor) : (opts.size ?? 0.6) * factor;
+ const rock = makeRock({ ...opts, seed, size, detail: opts.detail ?? 3 });
+ rock.position.set(x, opts.heightAt?.(x, z) ?? 0, z); rock.rotation.y = rand() * Math.PI * 2;
+ group.add(rock); owned.push(rock);
+ }
+ group.userData.update = () => {};
+ let disposed = false;
+ group.userData.dispose = () => {
+ if (disposed) return;
+ disposed = true;
+ owned.forEach((rock) => rock.userData.dispose());
+ };
+ return group;
+}
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sand.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sand.js
new file mode 100644
index 00000000..d68afc45
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sand.js
@@ -0,0 +1,167 @@
+/** 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 { fbm2, mulberry32 } from './noise.js';
+import { patchStandard } from './shader.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: `
+ vec3 sandDx = dFdx(-vViewPosition), sandDy = dFdy(-vViewPosition);
+ vec3 sandR1 = cross(sandDy, normal), sandR2 = cross(normal, sandDx);
+ float sandDet = dot(sandDx, sandR1);
+ normal = normalize(abs(sandDet) * normal - sign(sandDet) *
+ (sandRippleDH.x * sandR1 + sandRippleDH.y * sandR2) * uSandDetail);
+ `,
+ });
+ return mat;
+}
+
+/**
+ * @param {object} opts seed; size number or [width,depth]; segments (default
+ * 256, max512); duneHeight metres; duneSpacing metres; windDirection [x,z];
+ * rippleSpacing metres; color; detailStrength; grains (0 by default, max1200);
+ * 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 = opts.seed ?? 17;
+ 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 = new THREE.Vector2(...(opts.windDirection ?? [1, 0.18]));
+ if (wind.lengthSq() < 1e-8) wind.set(1, 0);
+ wind.normalize();
+ 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) => {
+ const gx = clamp((x / width + 0.5) * nx, 0, nx);
+ const gz = clamp((z / depth + 0.5) * nz, 0, nz);
+ const ix = Math.min(nx - 1, Math.floor(gx)), iz = Math.min(nz - 1, Math.floor(gz));
+ const fx = gx - ix, fz = gz - iz, a = iz * (nx + 1) + ix;
+ const h00 = p.getY(a), h10 = p.getY(a + 1), h01 = p.getY(a + nx + 1), h11 = p.getY(a + nx + 2);
+ return fx + fz <= 1 ? h00 + fx * (h10 - h00) + fz * (h01 - h00)
+ : h11 + (1 - fx) * (h01 - h11) + (1 - fz) * (h10 - h11);
+ };
+
+ // 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 = sampleHeight;
+ group.userData.update = update;
+ // Assets are explicitly allowed to be parented to this terrain. Snapshot
+ // only the resources constructed here, so caller-owned attachments survive.
+ const owned = [geometry, surface.material, grains?.geometry, grains?.material].filter(Boolean);
+ let disposed = false;
+ group.userData.dispose = () => {
+ if (disposed) return;
+ disposed = true;
+ owned.forEach((resource) => resource.dispose());
+ };
+ group.userData.seed = seed;
+ update(0);
+ return group;
+}
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/shader.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/shader.js
index f3ad0887..e92eea28 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/shader.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/shader.js
@@ -50,6 +50,23 @@ import { lehmer } from './noise.js';
* build the field on the CPU and hand it over as an attribute.
*/
export const GLSL_UTIL = [
+ // Cofactors implement inverse transpose in GLSL ES 1.00 too. Dividing
+ // by a determinant is unnecessary after normalization, but its SIGN
+ // matters for mirrored objects. Unlike column rescaling, this also
+ // handles shear from nested rotations and nonuniform parent scales.
+ 'vec3 astraNormalTransform(mat3 m, vec3 n) {',
+ ' float magnitude = max(length(m[0]), max(length(m[1]), length(m[2])));',
+ ' m /= max(magnitude, 1e-30);',
+ ' vec3 a = cross(m[1], m[2]);',
+ ' vec3 b = cross(m[2], m[0]);',
+ ' vec3 c = cross(m[0], m[1]);',
+ ' vec3 v = mat3(a, b, c) * n;',
+ ' float len2 = dot(v, v);',
+ ' float determinant = dot(m[0], a);',
+ ' if (len2 > 1e-20) return v * inversesqrt(len2)',
+ ' * (determinant < 0.0 ? -1.0 : 1.0);',
+ ' return dot(n, n) > 1e-20 ? normalize(n) : vec3(0.0, 1.0, 0.0);',
+ '}',
'float astraHash11(float p) {',
' p = fract(p * 0.1031);',
' p *= p + 33.33;',
@@ -244,9 +261,10 @@ export function glslCurv(name) {
/**
* `vec3 name(vec3 w)`: a world direction as the LOCAL offset that moves
- * this surface one metre along it — one projection per basis column,
- * valid because compose() leaves the columns orthogonal. `instanced`
- * folds in instanceMatrix, which three applies after the vertex hook.
+ * this surface one metre along it. Uses the reciprocal basis, including
+ * shear produced by nested rotations/nonuniform scales. `instanced` folds
+ * in instanceMatrix, which Three applies after the vertex hook. A singular
+ * transform has no inverse and returns a zero offset instead of NaNs.
*/
export function glslLocalDir(name, instanced = false) {
return [
@@ -254,9 +272,13 @@ export function glslLocalDir(name, instanced = false) {
' mat3 m = mat3(modelMatrix);',
...(instanced ? ['#ifdef USE_INSTANCING',
' m = m * mat3(instanceMatrix);', '#endif'] : []),
- ' return vec3(dot(w, m[0]) / max(dot(m[0], m[0]), 1e-6),',
- ' dot(w, m[1]) / max(dot(m[1], m[1]), 1e-6),',
- ' dot(w, m[2]) / max(dot(m[2], m[2]), 1e-6));',
+ ' vec3 a = cross(m[1], m[2]);',
+ ' vec3 b = cross(m[2], m[0]);',
+ ' vec3 c = cross(m[0], m[1]);',
+ ' float determinant = dot(m[0], a);',
+ ' float magnitude = length(m[0]) * length(m[1]) * length(m[2]);',
+ ' if (abs(determinant) <= max(magnitude * 1e-7, 1e-30)) return vec3(0.0);',
+ ' return vec3(dot(w, a), dot(w, b), dot(w, c)) / determinant;',
'}',
].join('\n');
}
@@ -579,10 +601,16 @@ export function makeShaderMaterial(opts = {}) {
* (uTime added, driven by `tickShaders`); `vertexHead`/`fragmentHead`
* code before main; `vertexBody` runs after `<begin_vertex>` (edit
* `transformed`); `fragmentBody` runs after `<color_fragment>` (edit
- * `diffuseColor`); `roughnessBody` / `metalnessBody` / `outputBody`
+ * `diffuseColor`); `alphaBody` runs before `<alphatest_fragment>` on
+ * both surface and depth/distance materials (coverage/discard logic);
+ * `normalBody` runs after `<normal_fragment_maps>` on the view-space
+ * shading normal; `roughnessBody` / `metalnessBody` / `outputBody`
* run after `<roughnessmap_fragment>` / `<metalnessmap_fragment>` /
* `<opaque_fragment>` (per-pixel `roughnessFactor`, `metalnessFactor`,
- * the lit `gl_FragColor`); `util` include GLSL_UTIL.
+ * the lit `gl_FragColor`); `transmissionBody` edits a Physical material's
+ * `material.thickness` / `material.transmission` after texture sampling
+ * and before volume refraction (only with USE_TRANSMISSION enabled);
+ * `util` include GLSL_UTIL.
* @returns {THREE.Material} The same material.
*/
/**
@@ -651,7 +679,8 @@ export function patchStandard(material, opts = {}) {
const {
name = 'AstraPatch', uniforms = {}, vertexHead = '',
fragmentHead = '', vertexBody = '', fragmentBody = '', util = true,
- roughnessBody = '', metalnessBody = '', outputBody = '',
+ roughnessBody = '', metalnessBody = '', outputBody = '', alphaBody = '', normalBody = '',
+ transmissionBody = '',
} = opts;
// Patches CHAIN. Assigning onBeforeCompile outright — which this did
// — silently dropped every earlier patch and its uniforms, and
@@ -672,7 +701,8 @@ export function patchStandard(material, opts = {}) {
const patches = material.userData.astraPatches || [];
const at = patches.findIndex((p) => p.name === name);
const patch = { name, vertexHead, fragmentHead, vertexBody, fragmentBody,
- roughnessBody, metalnessBody, outputBody, util };
+ roughnessBody, metalnessBody, outputBody, alphaBody, normalBody,
+ transmissionBody, util };
// Re-applying a patch retunes it (its uniforms are already merged);
// pushing it twice would declare its varyings twice.
if (at >= 0) patches[at] = patch;
@@ -713,7 +743,7 @@ export function patchStandard(material, opts = {}) {
fs = fs.replace('#include <color_fragment>',
'#include <color_fragment>\n' + fBody);
}
- // The three LATER hooks. `<color_fragment>` is the albedo, and for
+ // Later hooks. `<color_fragment>` is the albedo, and for
// years it was the only one — which is why a rust crust could only
// be sold by retuning the WHOLE material's roughness (a 30 % crust
// demattes 100 % of the surface), and why aerial perspective could
@@ -721,6 +751,16 @@ export function patchStandard(material, opts = {}) {
// and empty by default, so no existing patch changes.
const join = (key) => patches.map((p) => p[key]).filter(Boolean)
.join('\n');
+ const aBody = join('alphaBody');
+ if (aBody) {
+ fs = fs.replace('#include <alphatest_fragment>',
+ aBody + '\n#include <alphatest_fragment>');
+ }
+ const nBody = join('normalBody');
+ if (nBody) {
+ fs = fs.replace('#include <normal_fragment_maps>',
+ '#include <normal_fragment_maps>\n' + nBody);
+ }
// after <roughnessmap_fragment>: `roughnessFactor` is in scope, and
// every fragmentBody local above it still is.
const rBody = join('roughnessBody');
@@ -734,6 +774,20 @@ export function patchStandard(material, opts = {}) {
fs = fs.replace('#include <metalnessmap_fragment>',
'#include <metalnessmap_fragment>\n' + mBody);
}
+ // Thickness and transmission maps are sampled INSIDE this chunk. A
+ // hook before it would be overwritten; one after it would miss the
+ // refraction calculation. Expand only this opt-in chunk, retaining
+ // Three's USE_TRANSMISSION guard and its native optical model.
+ const tBody = join('transmissionBody');
+ if (tBody && fs.includes('#include <transmission_fragment>')) {
+ const chunk = THREE.ShaderChunk.transmission_fragment;
+ const anchor = 'vec3 pos = vWorldPosition;';
+ if (!chunk?.includes(anchor)) {
+ throw new Error('shader.js: Three transmission chunk changed; review transmissionBody insertion');
+ }
+ fs = fs.replace('#include <transmission_fragment>',
+ chunk.replace(anchor, tBody + '\n\t' + anchor));
+ }
// after <opaque_fragment>: `gl_FragColor` holds the LIT result, still
// linear — tonemapping and the colour-space convert come after this,
// and fog after those. This is the only hook that can add light
@@ -754,6 +808,59 @@ export function patchStandard(material, opts = {}) {
return material;
}
+/** Clone a material and rebuild its registered Astra patch chain.
+ * Three's ordinary clone JSON-copies userData but drops onBeforeCompile, losing
+ * both the shader and typed uniform values. Built-in patches and ShaderMaterial
+ * uniforms follow the same rules: uniform values here are independent
+ * (including vectors, matrices and arrays); textures remain borrowed references,
+ * as they do for ordinary material map slots. Only registered Astra patches can
+ * be rebuilt: additional external wrappers around onBeforeCompile must be
+ * reapplied by their owner. An unpatched material's hook is kept by reference.
+ * Set shareUniforms:true when collapsing a static batch that must retain the
+ * source effect's externally driven uniform map rather than an independent one.
+ */
+export function clonePatchedMaterial(material, { shareUniforms = false } = {}) {
+ // Leave uniforms out of Three's JSON copy: a render-target sampler can carry
+ // a large object graph, and JSON cannot preserve its GPU identity anyway.
+ const source = Object.create(material);
+ source.userData = { ...material.userData };
+ delete source.userData.uniforms;
+ delete source.userData.astraPatches;
+ delete source.userData.astraShader;
+ delete source.userData.astraShared;
+ delete source.userData.shared;
+ // ShaderMaterial.copy uses UniformsUtils.clone, which duplicates ordinary
+ // texture samplers and replaces render-target samplers with null. Borrow
+ // them through the same typed copy used for registered surface patches.
+ if (material.isShaderMaterial) source.uniforms = {};
+ const clone = material.clone.call(source);
+ const copyValue = (value) => {
+ if (!value || typeof value !== 'object' || value.isTexture) return value;
+ if (ArrayBuffer.isView(value)) return value.slice();
+ if (Array.isArray(value)) return value.map(copyValue);
+ if (typeof value.clone === 'function') return value.clone();
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, copyValue(item)]));
+ };
+ const uniformMaps = new Map();
+ const copyUniforms = (uniforms) => {
+ if (shareUniforms) return uniforms;
+ if (!uniformMaps.has(uniforms)) uniformMaps.set(uniforms, Object.fromEntries(
+ Object.entries(uniforms).map(([key, binding]) =>
+ [key, { ...binding, value: copyValue(binding.value) }])));
+ return uniformMaps.get(uniforms);
+ };
+ if (material.isShaderMaterial) clone.uniforms = copyUniforms(material.uniforms);
+ if (material.userData.uniforms) clone.userData.uniforms = copyUniforms(material.userData.uniforms);
+ const patches = material.userData.astraPatches;
+ if (patches?.length) {
+ for (const patch of patches) patchStandard(clone, { ...patch });
+ } else {
+ clone.onBeforeCompile = material.onBeforeCompile;
+ clone.customProgramCacheKey = material.customProgramCacheKey;
+ }
+ return clone;
+}
+
/**
* The world position and normal the surface patches shade from.
*
@@ -780,10 +887,10 @@ export function worldBody(p, n) {
` vec3 ${n} = normal;`,
'#ifdef USE_INSTANCING',
` ${p} = instanceMatrix * ${p};`,
- ` ${n} = mat3(instanceMatrix) * ${n};`,
+ ` ${n} = astraNormalTransform(mat3(instanceMatrix), ${n});`,
'#endif',
` vAstraWorld = (modelMatrix * ${p}).xyz;`,
- ` vAstraWorldN = normalize((modelMatrix * vec4(${n}, 0.0)).xyz);`,
+ ` vAstraWorldN = astraNormalTransform(mat3(modelMatrix), ${n});`,
].join('\n');
}
@@ -918,8 +1025,9 @@ export function tickShaders(root, t) {
/**
* Give a vertex-displaced mesh a shadow that moves with it.
*
- * three draws the shadow map with its OWN MeshDepthMaterial, which
- * never sees `patchStandard`: a displaced surface casts the shadow of
+ * Three draws directional/spot shadows with MeshDepthMaterial and point
+ * shadows with MeshDistanceMaterial. Neither sees `patchStandard`: a
+ * displaced surface casts the shadow of
* its undisplaced geometry — and for the `position`-at-zero instanced
* lattices these libraries build, that is no shadow at all. This
* patches a depth material with the SAME head and body and shares the
@@ -930,27 +1038,39 @@ export function tickShaders(root, t) {
* passed WHOLE — a depth shader has no vNormal to write.
*
* @param {THREE.Mesh} mesh The mesh, its surface patched already.
- * @param {string} name Cache-key name for this depth patch.
+ * @param {string} name Cache-key name for these shadow patches.
* @param {string} head The vertex head the body needs.
* @param {string} body The vertex body: the displacement, or the whole
* body when its normal half is FLAT_SHADED-guarded.
+ * @param {object} [opts] `fragmentHead` and `fragmentBody` provide the same
+ * silhouette test/discard as the surface. The body runs before the alpha
+ * test in both shadow passes. Neither owns the surface's shared textures.
* @returns {THREE.Mesh} The same mesh, now casting.
*/
-export function shadowLike(mesh, name, head, body) {
+export function shadowLike(mesh, name, head, body, opts = {}) {
// A depth pass that matches the surface EXACTLY self-shadows into
// moire, and shadow bias belongs to a light this library cannot
// see: the offset is the surface's own, so it travels with it.
- const dep = new THREE.MeshDepthMaterial({
- depthPacking: THREE.RGBADepthPacking, side: THREE.DoubleSide,
+ const settings = {
+ side: THREE.DoubleSide,
polygonOffset: true, polygonOffsetFactor: 3, polygonOffsetUnits: 8,
+ };
+ const depth = new THREE.MeshDepthMaterial({
+ ...settings, depthPacking: THREE.RGBADepthPacking,
});
- dep.userData.uniforms = mesh.material.userData.uniforms;
- patchStandard(dep, {
- name,
- vertexHead: '#define FLAT_SHADED 1\n' + head,
- vertexBody: body,
- });
- mesh.customDepthMaterial = dep;
+ const distance = new THREE.MeshDistanceMaterial(settings);
+ for (const material of [depth, distance]) {
+ material.userData.uniforms = mesh.material.userData.uniforms;
+ patchStandard(material, {
+ name,
+ vertexHead: '#define FLAT_SHADED 1\n' + head,
+ vertexBody: body,
+ fragmentHead: opts.fragmentHead || '',
+ alphaBody: opts.fragmentBody || '',
+ });
+ }
+ mesh.customDepthMaterial = depth;
+ mesh.customDistanceMaterial = distance;
mesh.castShadow = true;
return mesh;
}
@@ -1112,22 +1232,117 @@ export function instancedQuad(count, w = 1, h = 1, radius = 1e4) {
* @param {THREE.Object3D} obj Mesh, or a group whose meshes to guard.
* @returns {THREE.Object3D} The same object.
*/
+const overrideGuards = new WeakSet();
+
export function keepOutOfDepthPasses(obj) {
obj.traverse((o) => {
- if (!o.isMesh || o.userData.astraNoOverride) return;
- const own = o.material;
+ if (!o.isMesh || overrideGuards.has(o)) return;
+ overrideGuards.add(o);
o.userData.astraNoOverride = true;
- // A shaft of light does not cast a shadow. three 0.184 draws
+ const before = o.onBeforeRender, after = o.onAfterRender;
+ const ranges = [];
+ // A shaft of light does not cast a shadow. Three r182 draws
// the shadow map through its own hook, so the draw-range guard
// below never sees it — the flag is what keeps it out.
o.castShadow = false;
- o.onBeforeRender = (r, s, cam, geo, m) => {
- geo.setDrawRange(0, m === own ? Infinity : 0);
+ o.onBeforeRender = function (...args) {
+ before?.apply(this, args);
+ const [, , , geo, material] = args;
+ ranges.push({geometry:geo, start:geo.drawRange.start, count:geo.drawRange.count});
+ const own = Array.isArray(this.material)
+ ? this.material.includes(material) : this.material === material;
+ if (!own) geo.setDrawRange(0, 0);
};
- o.onAfterRender = (r, s, cam, geo) => {
- geo.setDrawRange(0, Infinity);
+ o.onAfterRender = function (...args) {
+ const range = ranges.pop();
+ if (range) range.geometry.setDrawRange(range.start, range.count);
+ after?.apply(this, args);
};
});
return obj;
}
+// A renderer may nest captures (for example a transmission pass inside a
+// reflection). Reuse one frame per nesting level without sharing live state.
+const rendererStateFrames = new WeakMap();
+
+/**
+ * Run a synchronous capture and restore the caller's renderer state, including
+ * active target rectangles that differ from the target's authored defaults.
+ * This scopes addon render callbacks; it does not coordinate recursive mirrors
+ * or recover the contents of an interrupted frame. Object visibility/matrices
+ * remain the caller's responsibility. The callback must finish synchronously.
+ */
+export function withRendererState(renderer, callback) {
+ let stack = rendererStateFrames.get(renderer);
+ if (!stack) {
+ stack = { depth: 0, frames: [] };
+ rendererStateFrames.set(renderer, stack);
+ }
+ let frame = stack.frames[stack.depth];
+ if (!frame) {
+ frame = {
+ viewport: new THREE.Vector4(), scissor: new THREE.Vector4(),
+ logicalViewport: new THREE.Vector4(), logicalScissor: new THREE.Vector4(),
+ targetViewport: new THREE.Vector4(), targetScissor: new THREE.Vector4(),
+ clearColor: new THREE.Color(),
+ };
+ stack.frames.push(frame);
+ }
+ const gl = renderer.getContext();
+ frame.target = renderer.getRenderTarget();
+ frame.face = renderer.getActiveCubeFace();
+ frame.mip = renderer.getActiveMipmapLevel();
+ frame.xr = renderer.xr.enabled;
+ frame.shadowUpdate = renderer.shadowMap.autoUpdate;
+ frame.toneMapping = renderer.toneMapping;
+ frame.clearAlpha = renderer.getClearAlpha();
+ frame.logicalScissorTest = renderer.getScissorTest();
+ frame.actualScissorTest = gl.isEnabled(gl.SCISSOR_TEST);
+ renderer.getCurrentViewport(frame.viewport);
+ renderer.getViewport(frame.logicalViewport);
+ renderer.getScissor(frame.logicalScissor);
+ frame.scissor.fromArray(gl.getParameter(gl.SCISSOR_BOX));
+ renderer.getClearColor(frame.clearColor);
+ stack.depth++;
+ try {
+ return callback();
+ } finally {
+ try {
+ renderer.xr.enabled = frame.xr;
+ renderer.shadowMap.autoUpdate = frame.shadowUpdate;
+ renderer.toneMapping = frame.toneMapping;
+ renderer.setClearColor(frame.clearColor, frame.clearAlpha);
+ renderer.setViewport(frame.logicalViewport);
+ renderer.setScissor(frame.logicalScissor);
+ renderer.setScissorTest(frame.logicalScissorTest);
+ if (frame.target) {
+ // Rebinding normally resets active rectangles to target
+ // defaults. Use the captured rectangles for this bind, then
+ // return its metadata intact so Three's cache and GL agree.
+ frame.targetViewport.copy(frame.target.viewport);
+ frame.targetScissor.copy(frame.target.scissor);
+ const targetScissorTest = frame.target.scissorTest;
+ frame.target.viewport.copy(frame.viewport);
+ frame.target.scissor.copy(frame.scissor);
+ frame.target.scissorTest = frame.actualScissorTest;
+ try {
+ renderer.setRenderTarget(frame.target, frame.face, frame.mip);
+ } finally {
+ frame.target.viewport.copy(frame.targetViewport);
+ frame.target.scissor.copy(frame.targetScissor);
+ frame.target.scissorTest = targetScissorTest;
+ }
+ } else {
+ renderer.setRenderTarget(null, frame.face, frame.mip);
+ renderer.state.viewport(frame.viewport);
+ renderer.state.scissor(frame.scissor);
+ renderer.state.setScissorTest(frame.actualScissorTest);
+ }
+ } finally {
+ stack.depth--;
+ // Do not keep a disposed caller target alive through this pool.
+ frame.target = null;
+ }
+ }
+}
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/signage.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/signage.js
index 582eb654..8ec7a590 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/signage.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/signage.js
@@ -32,6 +32,7 @@
*/
import * as THREE from 'three';
+import { attachDisposal } from './lifecycle.js';
import { FontLoader } from 'three/addons/loaders/FontLoader.js';
import { TextGeometry } from 'three/addons/geometries/TextGeometry.js';
@@ -295,5 +296,6 @@ export async function makeText(str, opts = {}) {
mesh.add(light);
mesh.userData.light = light;
}
+ attachDisposal(mesh, opts.material ? [geo] : [geo, mat]);
return mesh;
}
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sky.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sky.js
index 6c704aa0..f8472e7d 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sky.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sky.js
@@ -20,6 +20,7 @@
*/
import * as THREE from 'three';
+import { attachDisposal, snapshotResources } from './lifecycle.js';
import { Sky } from 'three/addons/objects/Sky.js';
/**
@@ -244,5 +245,24 @@ export function makeSky(scene, opts = {}) {
scene.add(sky);
scene.background = null; // the dome IS the backdrop (measured req)
- return { sky, sunDir };
+ attachDisposal(sky, snapshotResources(sky));
+ // Update every dependent twilight uniform together. This controls the dome;
+ // callers still update their scene lights and rebake environment lighting.
+ const setSunDirection = (direction) => {
+ const next = direction?.isVector3 ? direction.clone() : new THREE.Vector3(...(direction || []));
+ if (![next.x, next.y, next.z].every(Number.isFinite) || next.lengthSq() < 1e-12) {
+ throw new RangeError('makeSky.setSunDirection: expected a finite nonzero direction');
+ }
+ sunDir.copy(next).normalize();
+ u.sunPosition.value.copy(sunDir);
+ u.uNight.value = nightAmount(sunDir.y);
+ u.uAfterglow.value = afterglowAmount(sunDir.y);
+ u.uLowSun.value = lowSunAmount(sunDir.y);
+ u.uSunAzimuth.value.set(sunDir.x, 0, sunDir.z);
+ if (u.uSunAzimuth.value.lengthSq() < 1e-12) u.uSunAzimuth.value.set(1, 0, 0);
+ else u.uSunAzimuth.value.normalize();
+ return sunDir;
+ };
+ sky.userData.setSunDirection = setSunDirection;
+ return { sky, sunDir, setSunDirection, dispose: sky.userData.dispose };
}
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smalllife.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smalllife.js
index 526a8d3b..74cec94e 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smalllife.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smalllife.js
@@ -19,6 +19,7 @@
*/
import * as THREE from 'three';
+import { attachDisposal, snapshotResources } from './lifecycle.js';
import { mulberry32 } from './noise.js';
// One reader, so a scene's meadow, its reeds and its trees
@@ -30,9 +31,12 @@ import {
} from './shader.js';
const _TAU = Math.PI * 2;
-// Rows up a stem: 12 is where a two-arc bend stops faceting and the
-// top three can carry a seed head.
-const _REED_ROWS = 12;
+// Dense longitudinal rows resolve curved stems and the rounded seed head.
+const _REED_LEVELS = [
+ ...Array.from({length:17},(_,i)=>i*.75/16),
+ .78,.80,.81,.818,.835,.86,.885,.905,.922,.93,.95,1,
+];
+const _REED_ROWS = _REED_LEVELS.length - 1;
// Water damps what stands in it: the submerged stem takes this much of
// the surface bend, on the slower of the two sway rates below.
const _SUB_DAMP = 0.28;
@@ -62,10 +66,8 @@ const _KINDS = {
},
};
-// A swarm is drawn UNLIT, so the scene's own lights have to reach it as a
-// number. Re-read every `_RELIGHT` ticks: a traverse is cheap, but not 60
-// times a second in a scene of thousands of objects.
-const _RELIGHT = 24;
+// A swarm is unlit geometry, so refresh its light approximation every update.
+// This follows animated lights and is independent of update-call history.
// A billboard has no normal, so a direct light contributes its average
// over the facings that see it; a point or spot light is somewhere else
// in the scene and this cannot know how far, so it lands as a small
@@ -94,8 +96,9 @@ function sceneLight(obj, out) {
_lightAcc.setRGB(0, 0, 0);
let n = 0;
root.traverse((o) => {
- if (!o.isLight || o.visible === false || !(o.intensity > 0)) return;
+ if (!o.isLight) return;
n++;
+ if (o.visible === false || !(o.intensity > 0)) return;
const w = (o.isHemisphereLight || o.isAmbientLight) ? 1
: (o.isDirectionalLight ? _DIRECT : _LOCAL);
// A hemisphere light is its two halves averaged; every other kind
@@ -179,12 +182,11 @@ export function makeInsects(opts = {}) {
// The swarm reads the rig it was added to, from the first tick on; a
// caller who never adds it to a scene keeps the neutral 1.0 it was
// built with, which is what an asset preview wants.
- let age = 0;
- g.userData.tick = (t) => {
- if (age++ % _RELIGHT === 0) sceneLight(g, mat.uniforms.uLight.value);
+ g.userData.update = g.userData.tick = (t) => {
+ sceneLight(g, mat.uniforms.uLight.value);
tickShaders(g, t);
};
- return g;
+ return attachDisposal(g, snapshotResources(g));
}
/**
@@ -445,8 +447,9 @@ function insectMaterial(kind, size, drift, color) {
* straw, mixed in per stem; `waterColor` what a drowned stem loses
* its colour INTO (pass the water's own tint, or a stand in a green
* pond fades toward a blue-green that is not there); `shadows` cast
- * stem shadows through a displaced depth pass (default false, see
- * `stemMesh`); `seed` seed (default 11); `name` group name.
+ * stem and leaf shadows through matching depth/distance passes (default false, see
+ * `stemMesh`); `underwaterDistortion` enables a small approximate image distortion
+ * (default false; leave off with a refracting water surface); `seed` seed (default 11); `name` group name.
* @returns {THREE.Group} Named `Reeds`, holding ONE instanced mesh
* `Stems`, with `userData.tick(t)` driving the wind.
*/
@@ -475,9 +478,9 @@ export function makeReeds(opts = {}) {
const g = new THREE.Group();
g.name = opts.name || 'Reeds';
g.add(stemMesh(field, extent, waterY, { color, dry, deep }, wind,
- opts.shadows === true));
- g.userData.tick = (t) => tickShaders(g, t);
- return g;
+ opts.shadows === true, opts.underwaterDistortion === true));
+ g.userData.update = g.userData.tick = (t) => tickShaders(g, t);
+ return attachDisposal(g, snapshotResources(g));
}
/**
@@ -537,17 +540,26 @@ function reedField(extent, density, height, waterY, ground, wind, seed,
* the world origin and burn a black slab there.
*/
function reedLattice(count) {
- const base = new THREE.PlaneGeometry(1, 1, 1, _REED_ROWS);
- base.translate(0, 0.5, 0);
- const g = new THREE.InstancedBufferGeometry();
- g.index = base.index;
- g.setAttribute('position', new THREE.BufferAttribute(
- new Float32Array(base.attributes.position.count * 3), 3));
- g.setAttribute('aCorner', base.attributes.position);
- g.setAttribute('normal', base.attributes.normal);
- g.setAttribute('uv', base.attributes.uv);
- g.instanceCount = count;
- return g;
+ const corners=[], normals=[], uvs=[], parts=[], indices=[];
+ for(let part=0;part<5;part++) {
+ const rows=part===0 ? _REED_ROWS : 10;
+ const start=corners.length/3;
+ for(let j=0;j<=rows;j++)for(let side=0;side<3;side++) {
+ const u=part===0?_REED_LEVELS[j]:j/rows;
+ corners.push(side*.5-.5,u,0); normals.push(0,0,1);
+ uvs.push(side*.5,j/rows);parts.push(part);
+ }
+ for(let j=0;j<rows;j++)for(let side=0;side<2;side++) {
+ const a=start+j*3+side;indices.push(a,a+1,a+3,a+1,a+4,a+3);
+ }
+ }
+ 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;
}
/**
@@ -562,7 +574,7 @@ function reedLattice(count) {
* built when asked — a caller with a tight bound, or kelp with fat
* blades, can have it.
*/
-function stemMesh(field, extent, waterY, palette, wind, shadows) {
+function stemMesh(field, extent, waterY, palette, wind, shadows, distortion) {
const color = palette.color;
const geom = reedLattice(field.n);
const inst = (name, arr, size) => geom.setAttribute(
@@ -573,10 +585,10 @@ function stemMesh(field, extent, waterY, palette, wind, shadows) {
inst('iVar', field.vary, 4);
// position is zero, so the derived bounds would be a point at the
// origin: state the box the bent stand really occupies.
- const reach = extent / 2 + field.maxH * 0.45 + 0.05;
+ const reach = extent / 2 + field.maxH * 1.15 + 0.05;
geom.boundingBox = new THREE.Box3(
new THREE.Vector3(-reach, field.low, -reach),
- new THREE.Vector3(reach, field.high, reach));
+ new THREE.Vector3(reach, field.high + field.maxH * .24, reach));
geom.boundingSphere = geom.boundingBox.getBoundingSphere(new THREE.Sphere());
const mat = new THREE.MeshStandardMaterial({
@@ -595,6 +607,7 @@ function stemMesh(field, extent, waterY, palette, wind, shadows) {
uReedSpeed: { value: wind.speed },
uReedRate: { value: _SWAY_RATE.clone() },
uReedWater: { value: waterY },
+ uReedDistort: { value: distortion ? .012 : 0 },
},
vertexHead: STEM_HEAD,
vertexBody: STEM_VERTEX,
@@ -606,6 +619,7 @@ function stemMesh(field, extent, waterY, palette, wind, shadows) {
'varying vec4 vReed;',
'varying vec4 vReedVar;',
'varying vec2 vReedW;',
+ 'varying float vReedPart;',
].join('\n'),
fragmentBody: STEM_FRAGMENT,
});
@@ -629,6 +643,8 @@ const STEM_HEAD = [
'uniform float uReedSpeed;',
'uniform vec2 uReedRate;',
'uniform float uReedWater;',
+ 'uniform float uReedDistort;',
+ 'attribute float aPart;',
'attribute vec3 aCorner;',
'attribute vec3 iPos;',
'attribute vec4 iShape;',
@@ -637,12 +653,14 @@ const STEM_HEAD = [
'varying vec4 vReed;',
'varying vec4 vReedVar;',
'varying vec2 vReedW;',
+ 'varying float vReedPart;',
glslLocalDir('reedLocalDir'),
].join('\n');
const STEM_VERTEX = [
' vec3 rdRoot = iPos;',
- ' float rdV = aCorner.y;',
+ ' float rdV = aPart < 0.5 ? aCorner.y : 0.15 + aPart * 0.115;',
+ ' vReedPart = aPart;',
' float rdH = max(iShape.x, 1e-3);',
// Gusts are streaks running downwind — the same field grass.js rides,
// so a scene's meadow and its shallows lean together.
@@ -683,10 +701,11 @@ const STEM_VERTEX = [
// Seen THROUGH moving water a submerged stem wavers, and the step at
// the line is the break refraction really puts there.
' float rdWet = step(rdV, rdVw);',
- ' rdSpine.xz += vec2(-rdF.y, rdF.x) * (0.012 * rdWet',
+ ' rdSpine.xz += vec2(-rdF.y, rdF.x) * (uReedDistort * rdV * rdWet',
' * sin(rdT * 0.9 + rdPh + rdV * 7.0));',
- ' float rdT2 = (rdV - 0.9) / 0.11;',
- ' float rdHead = iShape.w * sqrt(max(1.0 - rdT2 * rdT2, 0.0));',
+ ' float rdT2 = (rdV - 0.87) / 0.06;',
+ ' float rdCap = max(abs(rdT2) - 0.68, 0.0) / 0.32;',
+ ' float rdHead = aPart < 0.5 ? iShape.w * sqrt(max(1.0 - rdCap * rdCap, 0.0)) : 0.0;',
' float rdWid = iShape.y * (0.55 + 0.45 * sqrt(max(1.0 - rdV, 0.0)))',
' + rdHead;',
// A stem is round, so its strip faces the eye from every angle
@@ -698,6 +717,24 @@ const STEM_VERTEX = [
' vec3 rdSide = rdCl > 1e-4 ? rdC / rdCl : vec3(1.0, 0.0, 0.0);',
' float rdX = aCorner.x * 2.0;',
' transformed = rdSpine + rdSide * (rdX * rdWid);',
+ ' vec3 rdLeafNormal = vec3(0.0, 1.0, 0.0);',
+ ' if (aPart > 0.5) {',
+ ' float lu = aCorner.y;',
+ ' float la = iBend.z + aPart * 2.39996;',
+ ' vec3 ld = normalize(vec3(cos(la), 0.0, sin(la)));',
+ ' vec3 ls = vec3(-ld.z, 0.0, ld.x);',
+ ' float ll = rdH * (0.30 + 0.12 * fract(iVar.x + aPart * 0.37));',
+ ' float lp = pow(max(sin(3.14159 * lu), 0.0), 0.65);',
+ ' float lw = rdH * (0.009 + 0.006 * iVar.z) * lp;',
+ ' float lrise = ll * (0.62 * sin(3.14159 * lu * 0.7) - 0.20 * lu * lu);',
+ ' float ldY = ll * (0.62 * 3.14159 * 0.7 * cos(3.14159 * lu * 0.7) - 0.40 * lu);',
+ ' float lflutter = iBend.x * 0.035 * sin(rdT * 3.0 + iVar.x + aPart);',
+ ' transformed = rdSpine + ld * (ll * lu) + vec3(0.0, lrise, 0.0)',
+ ' + ls * (rdX * lw) + vec3(0.0, -abs(rdX) * lw * 0.20 + lflutter * lu * lu, 0.0);',
+ ' vec3 ltangent = ld * ll + vec3(0.0, ldY + 2.0 * lflutter * lu, 0.0);',
+ ' rdLeafNormal = normalize(cross(ls - vec3(0.0, sign(rdX) * 0.20, 0.0), ltangent));',
+ ' rdWp = (modelMatrix * vec4(transformed, 1.0)).xyz;',
+ ' }',
' vReed = vec4(rdV, rdHead / max(iShape.w, 1e-4),',
' rdWp.y - uReedWater, rdX);',
' vReedVar = vec4(iVar.y, iVar.z, iVar.w, rdVw);',
@@ -711,6 +748,7 @@ const STEM_VERTEX = [
' vec3 rdFace = normalize(cross(rdSide, rdTan));',
' vNormal = normalize(normalMatrix * normalize(',
' rdFace * sqrt(max(1.0 - rdX * rdX, 0.04)) + rdSide * rdX));',
+ ' if (aPart > 0.5) vNormal = normalize(normalMatrix * rdLeafNormal);',
'#endif',
].join('\n');
@@ -729,6 +767,7 @@ const STEM_FRAGMENT = [
// A POWER, not a smoothstep — a smoothstep is already back at 0.9 by
// mid-stem, which is where most of the stand's pixels are.
' float rdDepth = pow(clamp(vReed.x, 0.0, 1.0), 1.3);',
+ ' if (vReedPart > 0.5) rdDepth = pow(clamp(vReed.x + 0.3, 0.0, 1.0), 0.7);',
' rdCol *= 0.46 + 0.54 * rdDepth;',
' rdCol = mix(rdCol, rdCol * vec3(1.5, 1.35, 0.75),',
' vReedVar.y * smoothstep(0.45, 1.0, vReed.x));',
@@ -743,6 +782,7 @@ const STEM_FRAGMENT = [
' vReed.x * 150.0));',
' float rdIsHead = smoothstep(0.15, 0.6, vReed.y);',
' rdCol = mix(rdCol, rdHeadCol, rdIsHead);',
+ ' if (vReedPart > 0.5) rdCol *= 1.18 - 0.12 * exp(-abs(vReed.w) * 18.0);',
// THE WATERLINE, the whole cue: a dark wet skin the water has
// climbed, a bright meniscus where the surface grabs the stem, and
// below it a stem losing its colour into the water EXPONENTIALLY —
@@ -775,7 +815,14 @@ const STEM_FRAGMENT = [
// in the stand. Dead straw barely passes light either, and a drowned
// stem passes it only as far as the water allows.
' vec3 rdSap = astraHueShift(rdCol, -0.20) * 1.7;',
- ' totalEmissiveRadiance += directionalLights[0].color * rdSap',
+ ' if (vReedPart > 0.5) rdBeam = 0.45 + 0.55 * rdBeam;',
+ ' float rdVisibility = 1.0;',
+ ' #if defined(USE_SHADOWMAP) && NUM_DIR_LIGHT_SHADOWS > 0',
+ ' rdVisibility = getShadow(directionalShadowMap[0], directionalLightShadows[0].shadowMapSize,',
+ ' directionalLightShadows[0].shadowIntensity, directionalLightShadows[0].shadowBias,',
+ ' directionalLightShadows[0].shadowRadius, vDirectionalShadowCoord[0]);',
+ ' #endif',
+ ' totalEmissiveRadiance += directionalLights[0].color * rdSap * rdVisibility',
' * (0.44 * rdThru * rdBeam * rdDepth * (1.0 - 0.86 * rdIsHead)',
' * (1.0 - 0.7 * vReedVar.z) * (1.0 - rdSubm));',
'#endif',
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smoke.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smoke.js
new file mode 100644
index 00000000..986ae2fb
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smoke.js
@@ -0,0 +1,304 @@
+/**
+ * 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 } from './shader.js';
+import { attachDisposal, snapshotResources } from './lifecycle.js';
+import { 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 random = mulberry32(seed);
+ const grids = [4, 8, 16, 32].map(n => ({ n, data: Float32Array.from({ length: n ** 3 * 3 }, () => random()) }));
+ const data = new Uint8Array(RESOLUTION ** 3 * 4);
+ let index = 0;
+ for (let z = 0; z < RESOLUTION; z++) for (let y = 0; y < RESOLUTION; y++) for (let x = 0; x < RESOLUTION; x++) {
+ const values = [0, 0, 0];
+ let amplitude = 8 / 15;
+ for (const grid of grids) {
+ const coords = [x, y, z].map(v => {
+ const q = (v + .5) / RESOLUTION * grid.n;
+ return Math.floor(q) + smooth(0, 1, q - Math.floor(q));
+ });
+ for (let channel = 0; channel < 3; channel++) values[channel] += amplitude * sampleGrid3(grid.data, grid.n, ...coords, 3, channel);
+ amplitude *= .5;
+ }
+ for (const v of values) data[index++] = Math.round(v * 255);
+ data[index++] = 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) {
+ vec3 safe = sign(direction) * max(abs(direction), vec3(1e-7));
+ safe += vec3(equal(direction, vec3(0.0))) * 1e-7;
+ vec3 a = (uBoundsMin - origin) / safe, b = (uBoundsMax - origin) / safe;
+ vec3 lo = min(a,b), hi = max(a,b);
+ return vec2(max(lo.x,max(lo.y,lo.z)), min(hi.x,min(hi.y,hi.z)));
+}
+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 height = opts.height ?? (steam ? .7 : 3);
+ const radius = opts.radius ?? height * (steam ? .09 : .047);
+ const spread = opts.spread ?? (steam ? .16 : .20);
+ const rise = opts.riseSpeed ?? height * (steam ? .38 : .2333333);
+ const wind = opts.wind?.toArray ? opts.wind.toArray() : opts.wind ?? [height * .02, 0];
+ const extinction = opts.density ?? (steam ? 2.1 : 5) / height;
+ const turbulence = opts.turbulence ?? (steam ? .9 : 1);
+ const dissipation = opts.dissipation ?? (steam ? 1.2 : .7);
+ const anisotropy = opts.anisotropy ?? (steam ? .62 : .35);
+ const quality = opts.quality ?? 'balanced', seed = opts.seed ?? 21;
+ if (![height,radius,spread,rise,extinction,turbulence,dissipation,anisotropy].every(Number.isFinite) ||
+ height < .001 || height > 10000 || radius <= 0 || radius > height * 4 || spread < 0 || spread > 2 ||
+ rise <= 0 || extinction < 0 || turbulence < 0 || turbulence > 2 || dissipation < 0 ||
+ Math.abs(anisotropy) > .9 || !Array.isArray(wind) || wind.length !== 2 || !wind.every(Number.isFinite) ||
+ !Number.isSafeInteger(seed) || !Object.hasOwn(TIERS,quality) || Math.hypot(...wind) / rise > 10) {
+ throw new RangeError('makeSmoke/makeSteam: invalid dimensions, flow, density, scattering, seed or quality');
+ }
+ 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
+ vec4 densityClip=uLocalToClip*vec4(firstDensity,1.0);
+ gl_FragDepth=clamp(densityClip.z/densityClip.w*.5+.5,0.0,1.0);
+ #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(), target = new THREE.Vector3(), lightPosition = new THREE.Vector3();
+ 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);
+ mesh.getWorldPosition(position);
+ let sun = null, point = null, best = -1;
+ u.uAmbient.value.setRGB(0,0,0);u.uSunColor.value.setRGB(0,0,0);u.uPointColor.value.setRGB(0,0,0);
+ scene.traverseVisible(light => {
+ if (!light.isLight || !(light.intensity > 0)) return;
+ if (light.isDirectionalLight && (!sun || light.intensity > sun.intensity)) sun = light;
+ if (light.isPointLight) {
+ light.getWorldPosition(lightPosition);
+ const score = light.intensity / Math.max(.01,lightPosition.distanceToSquared(position));
+ if (score > best) { point = light;best = score; }
+ }
+ const amount = light.isAmbientLight ? light.intensity * .28 : light.isHemisphereLight ? light.intensity * .22 : 0;
+ u.uAmbient.value.r += light.color.r * amount;
+ u.uAmbient.value.g += light.color.g * amount;
+ u.uAmbient.value.b += light.color.b * amount;
+ });
+ if (scene.environment) {
+ const level = .12 * (scene.environmentIntensity ?? 1);
+ u.uAmbient.value.r += level;u.uAmbient.value.g += level;u.uAmbient.value.b += level;
+ }
+ if (sun) {
+ sun.getWorldPosition(lightPosition);sun.target.getWorldPosition(target);
+ u.uSunWorld.value.copy(lightPosition).sub(target).normalize();
+ u.uSunLocal.value.copy(u.uSunWorld.value).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.js
index 7f126fc9..9823709b 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/strata.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/strata.js
@@ -21,7 +21,7 @@
import * as THREE from 'three';
import {
- patchStandard, composeRoughness, glslCurv, hash11, seedVec3, toColor,
+ patchStandard, glslCurv, hash11, seedVec3, toColor,
unit, worldBase,
} from './shader.js';
@@ -374,11 +374,8 @@ export function patchRockStrata(material, opts = {}) {
* weaker than the last, so a run continues below where it started and
* tapers out, which is flow rather than stripes.
*
- * Roughness is per MATERIAL here, not per pixel (the patch writes only
- * at `<color_fragment>`, before `<roughnessmap_fragment>`, and does not
- * use `patchStandard`'s `roughnessBody`), so the wash takes a small
- * polish off the whole surface through `composeRoughness` — a face with
- * water tracks is a face that gets wet.
+ * 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.
@@ -397,8 +394,6 @@ 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;
- composeRoughness(material, 'strata:erosion',
- 1 - 0.10 * unit(strength));
patchStandard(material, BASE);
return patchStandard(material, {
name: 'strata:erosion',
@@ -483,5 +478,6 @@ export function patchErosionStreaks(material, opts = {}) {
' 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/stream.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/stream.js
new file mode 100644
index 00000000..bc09a5d0
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/stream.js
@@ -0,0 +1,759 @@
+/**
+ * Clear, flowing stream along a graded Catmull-Rom path (metres, local Y up).
+ * Curved tessellated surface, geometric travelling ripples, obstacle wakes,
+ * advected foam, bed gravel and submerged stones. Uses standard PBR lighting,
+ * environment reflection, scene shadows and fog. Deterministic at absolute time.
+ * This is a kinematic shallow stream, not a Navier-Stokes solver: stones generate
+ * authored wake fields; water does not collide with arbitrary scene geometry.
+ * Refracts the opaque scene through a depth-varying water column using Three's
+ * physical transmission pass. Transparent objects are not in that pass; this
+ * remains a screen-space approximation. Reflections use the environment map,
+ * or an optional mean-grade planar capture of the scene's banks.
+ */
+import * as THREE from 'three';
+import { Reflector } from 'three/addons/objects/Reflector.js';
+import { mulberry32 } from './noise.js';
+import { GLSL_UTIL, withRendererState } from './shader.js';
+
+// IcosahedronGeometry duplicates triangle vertices. Preserve rounded cobble
+// shading after deformation by averaging normals at coincident positions.
+function smoothCobbleNormals(geometry) {
+ geometry.computeVertexNormals();
+ const p = geometry.attributes.position;
+ const n = geometry.attributes.normal;
+ const sums = new Map();
+ const keyAt = (i) =>
+ [p.getX(i), p.getY(i), p.getZ(i)].map((v) => Math.round(v * 1e5)).join(',');
+ for (let i = 0; i < p.count; i++) {
+ const key = keyAt(i);
+ const sum = sums.get(key) ?? new THREE.Vector3();
+ sum.add(new THREE.Vector3().fromBufferAttribute(n, i));
+ sums.set(key, sum);
+ }
+ for (let i = 0; i < p.count; i++) {
+ const sum = sums.get(keyAt(i)).clone().normalize();
+ n.setXYZ(i, sum.x, sum.y, sum.z);
+ }
+}
+
+function option(v, d, name, min, max = Infinity) {
+ v = v === undefined ? d : v;
+ if (!Number.isFinite(v) || v < min || v > max)
+ throw new RangeError(`makeStream: ${name} must be ${min}..${max}`);
+ return v;
+}
+// the library's one GLSL value noise (astraHash21 / astraNoise2)
+const noiseGLSL = GLSL_UTIL;
+
+/**
+ * @param {object} [opts]
+ * points [[x,y,z],...] upstream to downstream (non-increasing control heights);
+ * width=3, widthVariation=0 [0,.3] (irregular bank widths), depth=.45, speed=1.1 m/s, roughness=.5 [0,1] (riffle activity);
+ * segments=180, widthSegments=20, stoneCount=220, seed=42;
+ * obstacles [{u:0..1,lateral:-1..1,radius:.3}] generate stone + trailing wake;
+ * bed=true, waterColor=0x80b6a6, attenuationDistance=3 metres, bedColor=0x554a35;
+ * caustics=.45 [0,1] modulates direct bed light from the ripple curvature.
+ * endFade=0 metres; positive values smoothly flatten ripples at both ends
+ * over that distance, allowing an exact join to a still surface or weir lip.
+ * reflectionSize=0 disables optional bank reflection; use 256..2048 to enable
+ * one mean-grade planar capture. Do not combine it with another scene reflector.
+ * waterColor controls absorption over attenuationDistance, not surface paint.
+ * Result Group .userData.update(t,dt), sample(u,lateral=0,t), dispose().
+ * sample returns {position, tangent, normal, depth, speed} in LOCAL coordinates.
+ * speed/depth are constant along the path; no tributaries/overturning falls.
+ */
+export function makeStream(opts = {}) {
+ const width = option(opts.width, 3, 'width', 0.1, 100),
+ depth = option(opts.depth, 0.45, 'depth', 0.03, 10);
+ const widthVariation = option(opts.widthVariation, 0, 'widthVariation', 0, 0.3);
+ const speed = option(opts.speed, 1.1, 'speed', 0, 15),
+ activity = option(opts.roughness, 0.5, 'roughness', 0, 1);
+ const segments = Math.round(option(opts.segments, 180, 'segments', 16, 512));
+ const acrossSegments = Math.round(option(opts.widthSegments, 20, 'widthSegments', 4, 96));
+ const count = Math.round(option(opts.stoneCount, 220, 'stoneCount', 0, 12000));
+ const attenuationDistance = option(opts.attenuationDistance, 3, 'attenuationDistance', 0.01, 10000);
+ const caustics = option(opts.caustics, 0.45, 'caustics', 0, 1);
+ const reflectionSize = option(opts.reflectionSize, 0, 'reflectionSize', 0, 2048);
+ if (reflectionSize !== 0 && (!Number.isInteger(reflectionSize) || reflectionSize < 256))
+ throw new RangeError('makeStream: reflectionSize must be 0 or an integer from 256 to 2048');
+ const seed = option(opts.seed, 42, 'seed', 0, 4294967295),
+ rng = mulberry32(seed);
+ const points = opts.points ?? [
+ [-2, 0.8, -12],
+ [1, 0.55, -5],
+ [-1, 0.2, 3],
+ [2, 0, 12],
+ ];
+ if (
+ !Array.isArray(points) ||
+ points.length < 2 ||
+ points.some((p) => !Array.isArray(p) || p.length !== 3 || !p.every(Number.isFinite))
+ )
+ throw new RangeError(
+ 'makeStream: points must contain at least two finite [x,y,z] coordinates'
+ );
+ for (let i = 1; i < points.length; i++) {
+ if (points[i][1] > points[i - 1][1] + 1e-6)
+ throw new RangeError(
+ 'makeStream: points must run upstream to downstream (non-increasing y)'
+ );
+ if (Math.hypot(points[i][0] - points[i - 1][0], points[i][2] - points[i - 1][2]) < 0.001)
+ throw new RangeError('makeStream: adjacent points need distinct XZ positions');
+ }
+ const path = new THREE.CatmullRomCurve3(
+ points.map((p) => new THREE.Vector3(p[0], 0, p[2])),
+ false,
+ 'centripetal'
+ );
+ path.arcLengthDivisions = Math.max(400, segments * 3);
+ path.updateArcLengths();
+ const length = path.getLength();
+ const endFade = option(opts.endFade, 0, 'endFade', 0, length * .5);
+ // A spatial Catmull-Rom spline can overshoot perfectly valid flat-to-sloped
+ // control heights and make water run uphill. Use it only for the XZ course;
+ // harmonic Hermite slopes preserve each monotone height interval exactly.
+ const heights = points.map((p) => p[1]);
+ const deltas = heights.slice(1).map((y, i) => y - heights[i]);
+ const slopes = heights.map((_, i) => {
+ if (i === 0) return deltas[0];
+ if (i === heights.length - 1) return deltas.at(-1);
+ const a = deltas[i - 1],
+ b = deltas[i];
+ return a * b > 0 ? (2 * a * b) / (a + b) : 0;
+ });
+ function gradedPoint(u) {
+ const t = path.getUtoTmapping(u);
+ const segment = Math.min(points.length - 2, Math.floor(t * (points.length - 1)));
+ const f = t * (points.length - 1) - segment;
+ const f2 = f * f,
+ f3 = f2 * f;
+ const point = path.getPoint(t);
+ point.y =
+ (2 * f3 - 3 * f2 + 1) * heights[segment] +
+ (f3 - 2 * f2 + f) * slopes[segment] +
+ (-2 * f3 + 3 * f2) * heights[segment + 1] +
+ (f3 - f2) * slopes[segment + 1];
+ return point;
+ }
+ const obstacles = opts.obstacles ?? [
+ { u: 0.25, lateral: -0.35, radius: width * 0.1 },
+ { u: 0.52, lateral: 0.42, radius: width * 0.13 },
+ { u: 0.78, lateral: -0.12, radius: width * 0.09 },
+ ];
+ if (!Array.isArray(obstacles) || obstacles.length > 24)
+ throw new RangeError('makeStream: at most 24 obstacles');
+ const stones = obstacles.map((o, i) => ({
+ u: option(o.u, undefined, `obstacles[${i}].u`, 0, 1),
+ lateral: option(o.lateral, 0, `obstacles[${i}].lateral`, -0.95, 0.95),
+ radius: option(o.radius, width * 0.1, `obstacles[${i}].radius`, 0.002, width * 0.45),
+ }));
+ const phase = rng() * 6.28;
+ const waveRng = mulberry32(seed ^ 0x57a4f319);
+ const rippleBands = Array.from({ length: 11 }, (_, i) => {
+ const wavelength = .28 * 9 ** (i / 10) * (.85 + waveRng() * .3);
+ const angle = (waveRng() - .5) * 2.6;
+ const k = 2 * Math.PI / wavelength;
+ return { ks: k * Math.cos(angle), kl: k * Math.sin(angle),
+ amplitude: .0064 * wavelength ** .9, phase: waveRng() * Math.PI * 2,
+ drift: .92 + waveRng() * .16 };
+ });
+ const widthAt = (u) =>
+ width *
+ (1 +
+ widthVariation *
+ (Math.sin(u * 13.38 + phase) * 0.65 + Math.sin(u * 35.81 + phase * 0.7) * 0.35));
+ const unconstrainedDisplacement =
+ rippleBands.reduce((sum, wave) => sum + wave.amplitude, 0) * (0.3 + activity) +
+ stones.reduce((sum, o) => sum + o.radius * 0.105 * activity, 0);
+ // Keep supported very shallow channels above their bed, including the
+ // narrower optical column at the bank. This also bounds grazing normals.
+ const heightScale = Math.min(1, depth * .38 / Math.max(1e-6, unconstrainedDisplacement));
+ const displacementBound = unconstrainedDisplacement * heightScale;
+ const bedRelief = Math.min(.018, depth * .12);
+ const group = new THREE.Group();
+ group.name = opts.name ?? 'Stream';
+ group.userData.placement = 'free';
+ const uniforms = {
+ streamTime: { value: 0 },
+ streamSpeed: { value: speed },
+ streamWidth: { value: width },
+ streamActivity: { value: activity },
+ streamPhase: { value: phase },
+ streamLength: { value: length },
+ streamWidthVariation: { value: widthVariation },
+ streamHeightScale: { value: heightScale },
+ streamEndFade: { value: endFade },
+ };
+ const wakeCode = stones
+ .map(
+ (o) => `{
+ float ds=s-${(o.u * length).toFixed(7)}, dl=l-(${(o.lateral * widthAt(o.u) * 0.5).toFixed(7)});
+ float radius=${o.radius.toFixed(7)};
+ float gate=smoothstep(-radius*.6,radius*.7,ds)*exp(-max(ds,0.0)/(radius*6.0));
+ float envelope=exp(-pow(dl/(radius*.8+max(ds,0.0)*.21),2.0));
+ h+=gate*envelope*sin(ds*10.0-streamTime*streamSpeed*8.0+abs(dl)*4.0)*radius*.105*streamActivity;
+ }`
+ )
+ .join('\n');
+ const rippleCode = rippleBands.map((wave) =>
+ `h+=${wave.amplitude.toFixed(8)}*sin((s-streamTime*streamSpeed*${wave.drift.toFixed(7)})*${wave.ks.toFixed(7)}+l*${wave.kl.toFixed(7)}+${wave.phase.toFixed(7)});`
+ ).join('\n');
+ const heightGLSL = /* glsl */ `
+ uniform float streamTime;
+ uniform float streamSpeed;
+ uniform float streamWidth;
+ uniform float streamActivity;
+ uniform float streamPhase;
+ uniform float streamLength;
+ uniform float streamWidthVariation;
+ uniform float streamHeightScale;
+ uniform float streamEndFade;
+ float streamLocalWidth(float s){float u=s/streamLength;return streamWidth*(1.0+streamWidthVariation*(sin(u*13.38+streamPhase)*.65+sin(u*35.81+streamPhase*.7)*.35));}
+ float streamHeight(float s,float l){
+ float bank=1.0-pow(clamp(abs(l)/(streamLocalWidth(s)*.5),0.0,1.0),6.0);
+ float h=0.0;
+ ${rippleCode}
+ float riffle=.58+.42*pow(.5+.5*sin(s*.83+l*1.4+streamPhase),2.0);
+ h*=riffle*(.3+streamActivity);
+ ${wakeCode}
+ float endEnvelope=streamEndFade>0.0
+ ? smoothstep(0.0,streamEndFade,s)*smoothstep(0.0,streamEndFade,streamLength-s):1.0;
+ return h*bank*streamHeightScale*endEnvelope;
+ }
+ `;
+ // A bounded, vertical-light focusing approximation, evaluated on the same
+ // moving height field. It modulates only shadowed DIRECT diffuse light, never
+ // emits white lines in shade. This is not a photon/caustic transport solver.
+ const causticGLSL = /* glsl */ `
+ float streamCaustic(vec2 p,float waterDepth){
+ float e=.07,h=streamHeight(p.x,p.y);
+ float xx=(streamHeight(p.x+e,p.y)+streamHeight(p.x-e,p.y)-2.0*h)/(e*e);
+ float yy=(streamHeight(p.x,p.y+e)+streamHeight(p.x,p.y-e)-2.0*h)/(e*e);
+ float xy=(streamHeight(p.x+e,p.y+e)-streamHeight(p.x+e,p.y-e)-streamHeight(p.x-e,p.y+e)+streamHeight(p.x-e,p.y-e))/(4.0*e*e);
+ float d=waterDepth*.2498;
+ float determinant=(1.0+d*xx)*(1.0+d*yy)-d*d*xy*xy;
+ float focused=clamp(.94/max(.38,abs(determinant)),.68,2.4);
+ float footprint=max(length(dFdx(p)),length(dFdy(p)));
+ return mix(1.0,focused,${caustics.toFixed(7)}*(1.0-smoothstep(.045,.18,footprint)));
+ }
+ `;
+ function pathDerivative(u) {
+ const before = Math.max(0, u - 0.00001),
+ after = Math.min(1, u + 0.00001);
+ // s is horizontal path arc length, not the graded 3D curve's arc length.
+ // Preserve the derivative's magnitude: normalizing it changes ripple slopes.
+ return gradedPoint(after).sub(gradedPoint(before)).divideScalar((after - before) * length);
+ }
+ function frame(u) {
+ const position = gradedPoint(u),
+ longitudinal = pathDerivative(u),
+ tangent = longitudinal.clone().normalize(),
+ across = new THREE.Vector3(tangent.z, 0, -tangent.x).normalize();
+ const before = Math.max(0, u - 0.00001),
+ after = Math.min(1, u + 0.00001),
+ db = pathDerivative(before), da = pathDerivative(after),
+ acrossDerivative = new THREE.Vector3(da.z, 0, -da.x).normalize()
+ .sub(new THREE.Vector3(db.z, 0, -db.x).normalize())
+ .divideScalar((after - before) * length);
+ return { position, tangent, across, longitudinal, acrossDerivative };
+ }
+ function height(s, l, t) {
+ const bank = 1 - Math.pow(Math.min(1, Math.abs(l) / (widthAt(s / length) * 0.5)), 6);
+ let h = 0;
+ for (const wave of rippleBands)
+ h += wave.amplitude * Math.sin((s - t * speed * wave.drift) * wave.ks + l * wave.kl + wave.phase);
+ const riffle = .58 + .42 * (.5 + .5 * Math.sin(s * .83 + l * 1.4 + phase)) ** 2;
+ h *= riffle * (.3 + activity);
+ for (const o of stones) {
+ const ds = s - o.u * length,
+ dl = l - o.lateral * widthAt(o.u) * 0.5,
+ r = o.radius;
+ let g = Math.max(0, Math.min(1, (ds + r * 0.6) / (r * 1.3)));
+ g = g * g * (3 - 2 * g) * Math.exp(-Math.max(ds, 0) / (r * 6));
+ const envelope = Math.exp(-Math.pow(dl / (r * 0.8 + Math.max(ds, 0) * 0.21), 2));
+ h +=
+ g *
+ envelope *
+ Math.sin(ds * 10 - t * speed * 8 + Math.abs(dl) * 4) *
+ r *
+ 0.105 *
+ activity;
+ }
+ const endEnvelope = endFade > 0
+ ? THREE.MathUtils.smoothstep(s, 0, endFade) * THREE.MathUtils.smoothstep(length-s, 0, endFade) : 1;
+ return h * bank * heightScale * endEnvelope;
+ }
+ function makeRibbon(bed = false) {
+ const positions = [],
+ uv = [],
+ flows = [],
+ longitudinals = [],
+ acrosses = [],
+ indices = [];
+ for (let i = 0; i <= segments; i++) {
+ const u = i / segments,
+ f = frame(u);
+ for (let j = 0; j <= acrossSegments; j++) {
+ const lateral = (j / acrossSegments) * 2 - 1,
+ l = lateral * widthAt(u) * 0.5 * (bed ? 1.25 : 1);
+ const p = f.position.clone().addScaledVector(f.across, l);
+ if (bed)
+ p.y -= depth * (1 - 0.55 * (l / (widthAt(u) * .5)) ** 2) + bedRelief * Math.sin(i * 0.61 + j * 1.23);
+ positions.push(p.x, p.y, p.z);
+ uv.push(j / acrossSegments, u);
+ flows.push(u * length, l);
+ // Partial derivative of C(s) + l*A(s), holding lateral metres l fixed.
+ // Width variation adds a multiple of the across derivative, which drops
+ // out of their cross product, so this basis also covers tapered banks.
+ const longitudinal = f.longitudinal.clone().addScaledVector(f.acrossDerivative, l);
+ longitudinals.push(longitudinal.x, longitudinal.y, longitudinal.z);
+ acrosses.push(f.across.x, f.across.y, f.across.z);
+ if (i < segments && j < acrossSegments) {
+ const a = i * (acrossSegments + 1) + j,
+ b = a + acrossSegments + 1;
+ indices.push(a, b, a + 1, b, b + 1, a + 1);
+ }
+ }
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
+ g.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2));
+ g.setAttribute('streamFlow', new THREE.Float32BufferAttribute(flows, 2));
+ g.setAttribute('streamLongitudinal', new THREE.Float32BufferAttribute(longitudinals, 3));
+ g.setAttribute('streamAcross', new THREE.Float32BufferAttribute(acrosses, 3));
+ g.setIndex(indices);
+ g.computeVertexNormals();
+ g.computeBoundingBox();
+ g.computeBoundingSphere();
+ g.boundingBox.expandByScalar(displacementBound);
+ g.boundingSphere.radius += displacementBound;
+ return g;
+ }
+ const material = new THREE.MeshPhysicalMaterial({
+ name: 'ClearStreamWater',
+ color: 0xffffff,
+ roughness: 0.04,
+ metalness: 0,
+ ior: 1.333,
+ clearcoat: 0,
+ transmission: 1,
+ thickness: depth,
+ attenuationColor: opts.waterColor ?? 0x80b6a6,
+ attenuationDistance,
+ opacity: 1,
+ depthWrite: true,
+ side: THREE.FrontSide,
+ envMapIntensity: 1,
+ });
+ const foamCode = stones
+ .map(
+ (o) => `{
+ float ds=vStreamFlow.x-${(o.u * length).toFixed(7)},dl=vStreamFlow.y-(${(o.lateral * widthAt(o.u) * 0.5).toFixed(7)}), r=${o.radius.toFixed(7)};
+ float downstream=smoothstep(-r*.4,r*.4,ds)*exp(-max(ds,0.0)/(r*3.8));
+ float wakeWidth=r*.7+max(ds,0.0)*.22;
+ float wakes=exp(-pow((abs(dl)-wakeWidth*.7)/(r*.3+max(ds,0.0)*.08),2.0));
+ wakeFoam+=downstream*wakes;
+ }`
+ )
+ .join('\n');
+ material.onBeforeCompile = (shader) => {
+ Object.assign(shader.uniforms, uniforms);
+ shader.vertexShader = shader.vertexShader
+ .replace(
+ '#include <common>',
+ `#include <common>\nattribute vec2 streamFlow; attribute vec3 streamLongitudinal; attribute vec3 streamAcross; varying vec2 vStreamFlow; varying vec3 vStreamPosition; varying vec3 vStreamLongitudinal; varying vec3 vStreamAcross;\n${heightGLSL}`
+ )
+ .replace(
+ '#include <beginnormal_vertex>',
+ /* glsl */ `
+ float hs=(streamHeight(streamFlow.x+.015,streamFlow.y)-streamHeight(streamFlow.x-.015,streamFlow.y))/.03;
+ float hl=(streamHeight(streamFlow.x,streamFlow.y+.015)-streamHeight(streamFlow.x,streamFlow.y-.015))/.03;
+ vec3 objectNormal=normalize(cross(streamLongitudinal+vec3(0,hs,0),streamAcross+vec3(0,hl,0)));
+ #ifdef USE_TANGENT
+ vec3 objectTangent=vec3(tangent.xyz);
+ #endif
+ `
+ )
+ .replace(
+ '#include <begin_vertex>',
+ `vec3 transformed=position; transformed.y+=streamHeight(streamFlow.x,streamFlow.y); vStreamFlow=streamFlow;vStreamPosition=transformed;vStreamLongitudinal=streamLongitudinal;vStreamAcross=streamAcross;`
+ );
+ shader.fragmentShader = shader.fragmentShader
+ .replace(
+ '#include <common>',
+ `#include <common>\nuniform mat3 normalMatrix; varying vec2 vStreamFlow; varying vec3 vStreamPosition; varying vec3 vStreamLongitudinal; varying vec3 vStreamAcross;\n${heightGLSL}\n${noiseGLSL}`
+ )
+ .replace(
+ '#include <color_fragment>',
+ /* glsl */ `
+ #include <color_fragment>
+ vec2 advect=vec2(vStreamFlow.x-streamTime*streamSpeed,vStreamFlow.y);
+ float cellular=astraNoise2(advect*vec2(4.5,15.0));
+ float fine=astraNoise2(advect*vec2(12.0,29.0));
+ float wakeFoam=0.0;
+ ${foamCode}
+ float foam=clamp(wakeFoam*smoothstep(.52,.80,cellular*.7+fine*.3)*.52*streamActivity,0.0,.72);
+ float bank=pow(clamp(abs(vStreamFlow.y)/(streamLocalWidth(vStreamFlow.x)*.5),0.0,1.0),8.0);
+ foam=max(foam,bank*smoothstep(.76,.94,cellular)*.055*streamActivity);
+ diffuseColor.rgb=mix(diffuseColor.rgb,vec3(.74,.78,.72),foam);
+ // The refracted path reaches the graded bed rather than a flat sheet of
+ // constant thickness. Absorption belongs to the volume, not its surface.
+ float opticalDepth=${depth.toFixed(7)}*(1.0-.55*pow(vStreamFlow.y/(streamLocalWidth(vStreamFlow.x)*.5),2.0));
+ `
+ )
+ .replace(
+ '#include <normal_fragment_maps>',
+ `#include <normal_fragment_maps>
+ // Evaluate resolved slopes per fragment, not by interpolating sparse
+ // vertex normals. Screen-footprint averaging removes distant sparkle.
+ float flowFootprint=max(length(dFdx(vStreamFlow)),length(dFdy(vStreamFlow)));
+ float slopeStep=max(.015,flowFootprint*.6);
+ float streamHs=(streamHeight(vStreamFlow.x+slopeStep,vStreamFlow.y)-streamHeight(vStreamFlow.x-slopeStep,vStreamFlow.y))/(2.0*slopeStep);
+ float streamHl=(streamHeight(vStreamFlow.x,vStreamFlow.y+slopeStep)-streamHeight(vStreamFlow.x,vStreamFlow.y-slopeStep))/(2.0*slopeStep);
+ normal=normalize(normalMatrix*cross(vStreamLongitudinal+vec3(0,streamHs,0),vStreamAcross+vec3(0,streamHl,0)));
+ float microFilter=1.0-smoothstep(.035,.14,flowFootprint);
+ float streamMicro=(astraNoise2(advect*vec2(8.0,12.0))*.0012+astraNoise2(advect*vec2(19.0,24.0))*.0003)*microFilter;
+ vec3 sx=dFdx(-vViewPosition),sy=dFdy(-vViewPosition);
+ vec3 rx=cross(sy,normal),ry=cross(normal,sx);
+ float det=dot(sx,rx);
+ vec2 grad=vec2(dFdx(streamMicro),dFdy(streamMicro));
+ normal=normalize(abs(det)*normal-sign(det)*(grad.x*rx+grad.y*ry));
+ `
+ )
+ .replace(
+ '#include <roughnessmap_fragment>',
+ `#include <roughnessmap_fragment>\nroughnessFactor=mix(roughnessFactor,.67,foam);`
+ )
+ .replace(
+ '#include <transmission_pars_fragment>',
+ THREE.ShaderChunk.transmission_pars_fragment.replaceAll(
+ 'refractionCoords /= 2.0;', `refractionCoords /= 2.0;
+ // Offscreen refraction has no valid source texel. Blend sampled
+ // radiance at the border, never interpolate UV coordinates: a UV
+ // blend folds the image and stretches pebbles into vertical bands.
+ vec4 surfaceNdc=projMatrix*viewMatrix*vec4(position,1.0);
+ vec2 streamSurfaceUv=surfaceNdc.xy/surfaceNdc.w*.5+.5;
+ vec2 border=min(refractionCoords,1.0-refractionCoords);
+ float streamInFrame=smoothstep(0.0,.06,min(border.x,border.y));
+ `
+ ).replace('transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );',
+ `transmittedLight = mix(getTransmissionSample(streamSurfaceUv,roughness,ior),
+ getTransmissionSample(clamp(refractionCoords,vec2(0.0),vec2(1.0)),roughness,ior),streamInFrame);`)
+ .replace('vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );',
+ `vec4 transmissionSample = mix(getTransmissionSample(streamSurfaceUv,roughness,iors[i]),
+ getTransmissionSample(clamp(refractionCoords,vec2(0.0),vec2(1.0)),roughness,iors[i]),streamInFrame);`)
+ .replace('return normalize( refractionVector ) * thickness * modelScale;',
+ // Our thickness below is the solved WORLD ray distance. Scaling a
+ // world direction componentwise would bend it under rotated scale.
+ 'return normalize( refractionVector ) * thickness;')
+ )
+ .replace(
+ '#include <transmission_fragment>',
+ THREE.ShaderChunk.transmission_fragment
+ .replace('material.transmission = transmission;', 'material.transmission = transmission * (1.0 - foam);')
+ .replace('material.thickness = thickness;', `
+ vec3 streamWorldNormal=inverseTransformDirection(normal,viewMatrix);
+ vec3 streamRay=refract(-normalize(cameraPosition-vWorldPosition),streamWorldNormal,1.0/ior);
+ vec3 streamLocalRay=inverse(mat3(modelMatrix))*streamRay;
+ vec3 streamBedNormal=normalize(cross(vStreamLongitudinal,vStreamAcross));
+ float streamBedDistance=(opticalDepth+streamHeight(vStreamFlow.x,vStreamFlow.y))*streamBedNormal.y;
+ material.thickness=max(0.0,streamBedDistance)/max(1e-8,abs(dot(streamLocalRay,streamBedNormal)));
+ `)
+ );
+ if (reflectionSize) {
+ shader.fragmentShader = shader.fragmentShader
+ .replace('#include <common>', '#include <common>\nuniform sampler2D streamReflection;uniform mat4 streamReflectionMatrix;')
+ .replace('#include <lights_fragment_end>', `#include <lights_fragment_end>
+ vec4 reflectionCoord=streamReflectionMatrix*vec4(vStreamPosition,1.0);
+ vec2 reflectionUv=reflectionCoord.xy/reflectionCoord.w;
+ vec3 viewFlat=normalize(normalMatrix*vec3(0.0,1.0,0.0));
+ reflectionUv+=(normal.xy-viewFlat.xy)*.025;
+ vec2 reflectionEdge=min(reflectionUv,1.0-reflectionUv);
+ float reflectionWeight=smoothstep(0.0,.04,min(reflectionEdge.x,reflectionEdge.y))*(1.0-foam);
+ float reflectionLod=clamp(log2(max(1.0,length(fwidth(reflectionUv))*${reflectionSize.toFixed(1)})),0.0,6.0);
+ vec3 bankReflection=textureLod(streamReflection,clamp(reflectionUv,vec2(.001),vec2(.999)),reflectionLod).rgb;
+ vec3 reflectionF=EnvironmentBRDF(normal,geometryViewDir,material.specularColorBlended,material.specularF90,material.roughness);
+ reflectedLight.indirectSpecular=mix(reflectedLight.indirectSpecular,bankReflection*reflectionF,reflectionWeight);
+ `);
+ }
+ };
+ material.customProgramCacheKey = () =>
+ `stream-v4-${seed}-${width}-${widthVariation}-${depth}-${length}-${reflectionSize}-${JSON.stringify(stones)}`;
+ const surface = new THREE.Mesh(makeRibbon(), material);
+ surface.name = 'StreamSurface';
+ surface.receiveShadow = true;
+ surface.renderOrder = 2;
+ group.add(surface);
+ let reflection = null;
+ if (reflectionSize) {
+ // The helper never enters the scene graph. Only its clipped virtual camera
+ // and owned render target are used, so it cannot add a visible water slab.
+ reflection = new Reflector(new THREE.PlaneGeometry(1, 1), {
+ textureWidth: reflectionSize, textureHeight: reflectionSize, multisample: 0,
+ });
+ const first = frame(0).position, last = frame(1).position;
+ const direction = last.clone().sub(first);
+ const grade = direction.y / Math.max(.001, direction.x ** 2 + direction.z ** 2);
+ const gradeNormal = new THREE.Vector3(-direction.x * grade, 1, -direction.z * grade).normalize();
+ reflection.position.copy(frame(.5).position);
+ reflection.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), gradeNormal);
+ reflection.updateMatrix();
+ const target = reflection.getRenderTarget();
+ target.texture.generateMipmaps = true;
+ target.texture.minFilter = THREE.LinearMipmapLinearFilter;
+ uniforms.streamReflection = { value: target.texture };
+ uniforms.streamReflectionMatrix = { value: new THREE.Matrix4() };
+ const inverseMirror = new THREE.Matrix4();
+ const mirrorNormalMatrix = new THREE.Matrix3();
+ const worldMirrorNormal = new THREE.Vector3();
+ const worldMirrorPoint = new THREE.Vector3();
+ const mirrorRotation = new THREE.Quaternion();
+ const mirrorAxis = new THREE.Vector3(0, 0, 1);
+ let capturing = false;
+ surface.onBeforeRender = (renderer, scene, camera, geometry, drawMaterial) => {
+ // GTAO/depth override passes need no colour reflection capture.
+ if (scene.overrideMaterial || capturing || surface.material !== material
+ || (drawMaterial && drawMaterial !== material)) return;
+ // Reflector extracts a rotation from matrixWorld. Passing a scaled or
+ // sheared plane matrix gives it the wrong normal. Transform the plane
+ // by the inverse transpose, then supply an equivalent rigid world frame.
+ mirrorNormalMatrix.getNormalMatrix(group.matrixWorld);
+ worldMirrorNormal.copy(gradeNormal).applyMatrix3(mirrorNormalMatrix).normalize();
+ if (worldMirrorNormal.lengthSq() < .5) return;
+ worldMirrorPoint.copy(reflection.position).applyMatrix4(group.matrixWorld);
+ mirrorRotation.setFromUnitVectors(mirrorAxis, worldMirrorNormal);
+ reflection.matrixWorld.makeRotationFromQuaternion(mirrorRotation).setPosition(worldMirrorPoint);
+ const oldVisible = surface.visible;
+ const oldMirrorVisible = reflection.visible;
+ capturing = true;
+ surface.visible = false;
+ try {
+ withRendererState(renderer, () => {
+ reflection.onBeforeRender(renderer, scene, camera);
+ inverseMirror.copy(reflection.matrixWorld).invert();
+ uniforms.streamReflectionMatrix.value
+ .copy(reflection.material.uniforms.textureMatrix.value)
+ .multiply(inverseMirror).multiply(surface.matrixWorld);
+ });
+ } finally {
+ surface.visible = oldVisible;
+ reflection.visible = oldMirrorVisible;
+ capturing = false;
+ }
+ };
+ }
+ if (opts.bed !== false) {
+ const bedMaterial = new THREE.MeshStandardMaterial({
+ color: opts.bedColor ?? 0x554a35,
+ roughness: 0.9,
+ });
+ bedMaterial.onBeforeCompile = (shader) => {
+ Object.assign(shader.uniforms, uniforms);
+ shader.vertexShader = shader.vertexShader
+ .replace('#include <common>', '#include <common>\nattribute vec2 streamFlow; varying vec2 vBedFlow; varying vec3 vGravelPosition;')
+ .replace(
+ '#include <begin_vertex>',
+ '#include <begin_vertex>\nvGravelPosition=position;vBedFlow=streamFlow;'
+ );
+ shader.fragmentShader = shader.fragmentShader
+ .replace(
+ '#include <common>',
+ `#include <common>\nvarying vec3 vGravelPosition;varying vec2 vBedFlow;\n${noiseGLSL}\n${heightGLSL}\n${causticGLSL}`
+ )
+ .replace(
+ '#include <color_fragment>',
+ /* glsl */ `
+ #include <color_fragment>
+ vec2 gp=vGravelPosition.xz*26.0;
+ vec2 cell=floor(gp), frac=fract(gp);
+ float d1=5.0,d2=5.0,stoneTone=.0;
+ for(int x=-1;x<=1;x++)for(int y=-1;y<=1;y++){
+ vec2 offset=vec2(float(x),float(y));
+ vec2 jitter=vec2(astraHash21(cell+offset),astraHash21(cell+offset+53.2));
+ float dist=length(offset+jitter-frac);
+ if(dist<d1){d2=d1;d1=dist;stoneTone=astraHash21(cell+offset+19.1);}else if(dist<d2)d2=dist;
+ }
+ float filterWidth=max(length(dFdx(gp)),length(dFdy(gp)));
+ float seam=smoothstep(.015,.10,d2-d1);
+ float gravelDetail=mix(.68,.86+stoneTone*.4,seam);
+ diffuseColor.rgb*=mix(gravelDetail,.91,smoothstep(.45,1.6,filterWidth));
+ diffuseColor.rgb=mix(diffuseColor.rgb,diffuseColor.rgb*vec3(.66,.77,.75),.2);
+ `
+ )
+ .replace('#include <lights_fragment_end>', `#include <lights_fragment_end>
+ float waterDepth=${depth.toFixed(7)}*(1.0-.55*pow(vBedFlow.y/(streamLocalWidth(vBedFlow.x)*.5),2.0));
+ reflectedLight.directDiffuse*=streamCaustic(vBedFlow,max(0.0,waterDepth));
+ `);
+ };
+ bedMaterial.customProgramCacheKey = () => `stream-bed-v2-${material.customProgramCacheKey()}-${caustics}`;
+ const bed = new THREE.Mesh(makeRibbon(true), bedMaterial);
+ bed.name = 'StreamBed';
+ bed.receiveShadow = true;
+ group.add(bed);
+ // One geometry/material/draw call for gravel, actual silhouettes under water.
+ if (count > 0) {
+ const stoneGeo = new THREE.IcosahedronGeometry(1, 2);
+ const sp = stoneGeo.attributes.position;
+ for (let i = 0; i < sp.count; i++) {
+ const x = sp.getX(i),
+ y = sp.getY(i),
+ z = sp.getZ(i),
+ r = 1 + 0.13 * Math.sin(x * 4.7 + y * 3.1) * Math.cos(z * 5.3 - x * 2.3);
+ sp.setXYZ(i, x * r, y * r, z * r);
+ }
+ smoothCobbleNormals(stoneGeo);
+ const stoneMaterial = new THREE.MeshStandardMaterial({
+ color: 0xc5bfae,
+ roughness: 0.72,
+ });
+ const pebbleFlows = new Float32Array(count * 3);
+ const pebbleFrames = new Float32Array(count * 2);
+ stoneMaterial.onBeforeCompile = (shader) => {
+ Object.assign(shader.uniforms, uniforms);
+ shader.vertexShader = shader.vertexShader
+ .replace('#include <common>', '#include <common>\nattribute vec3 pebbleFlow;attribute vec2 pebbleFrame;varying vec3 vPebbleFlow;varying vec3 vPebblePoint;')
+ .replace('#include <project_vertex>', `
+ vec3 stoneOffset=(instanceMatrix*vec4(transformed,0.0)).xyz;
+ vPebbleFlow=pebbleFlow+vec3(dot(stoneOffset.xz,pebbleFrame),dot(stoneOffset.xz,vec2(pebbleFrame.y,-pebbleFrame.x)), -stoneOffset.y);
+ vPebblePoint=(instanceMatrix*vec4(transformed,1.0)).xyz;
+ #include <project_vertex>
+ `);
+ shader.fragmentShader = shader.fragmentShader
+ .replace('#include <common>', `#include <common>\nvarying vec3 vPebbleFlow;varying vec3 vPebblePoint;\n${noiseGLSL}\n${heightGLSL}\n${causticGLSL}`)
+ .replace('#include <color_fragment>', `#include <color_fragment>
+ float mineral=astraNoise2(vPebblePoint.xz*43.0+vPebblePoint.y*29.0);
+ float grain=astraNoise2(vPebblePoint.xz*167.0+vPebblePoint.y*97.0);
+ float filterWidth=max(length(dFdx(vPebblePoint)),length(dFdy(vPebblePoint)));
+ diffuseColor.rgb*=mix(.70+mineral*.55+grain*.25,1.1,smoothstep(.008,.04,filterWidth));
+ `)
+ .replace('#include <lights_fragment_end>', `#include <lights_fragment_end>\nreflectedLight.directDiffuse*=streamCaustic(vPebbleFlow.xy,max(0.0,vPebbleFlow.z));`);
+ };
+ stoneMaterial.customProgramCacheKey = () => `stream-cobble-v2-${material.customProgramCacheKey()}-${caustics}`;
+ const pebbles = new THREE.InstancedMesh(stoneGeo, stoneMaterial, count);
+ pebbles.name = 'SubmergedPebbles';
+ pebbles.receiveShadow = true;
+ const temp = new THREE.Object3D(),
+ color = new THREE.Color();
+ for (let i = 0; i < count; i++) {
+ const u = 0.01 + rng() * 0.98,
+ lateral = (rng() * 2 - 1) * 0.91,
+ f = frame(u),
+ r = 0.035 + rng() ** 1.6 * 0.13;
+ temp.position.copy(f.position).addScaledVector(f.across, lateral * widthAt(u) * 0.5);
+ temp.position.y -= depth * (1 - 0.55 * lateral * lateral) - r * 0.2;
+ temp.scale.set(
+ r * (0.8 + rng() * 0.6),
+ r * (0.45 + rng() * 0.4),
+ r * (1 + rng() * 0.65)
+ );
+ temp.rotation.set((rng() - .5) * .32, rng() * 6.28, (rng() - .5) * .32);
+ temp.updateMatrix();
+ pebbles.setMatrixAt(i, temp.matrix);
+ pebbleFlows.set([u * length, lateral * widthAt(u) * .5, depth * (1 - .55 * lateral * lateral)], i * 3);
+ pebbleFrames.set([f.tangent.x, f.tangent.z], i * 2);
+ color.setHSL(0.065 + rng() * 0.07, 0.08 + rng() * 0.22, 0.07 + rng() * 0.16);
+ pebbles.setColorAt(i, color);
+ }
+ pebbles.instanceMatrix.needsUpdate = true;
+ pebbles.instanceColor.needsUpdate = true;
+ stoneGeo.setAttribute('pebbleFlow', new THREE.InstancedBufferAttribute(pebbleFlows, 3));
+ stoneGeo.setAttribute('pebbleFrame', new THREE.InstancedBufferAttribute(pebbleFrames, 2));
+ group.add(pebbles);
+ }
+ }
+ // Wake-generating cobbles are actual obstacles, not white decals in empty water.
+ for (let i = 0; i < stones.length; i++) {
+ const o = stones[i],
+ f = frame(o.u),
+ geo = new THREE.IcosahedronGeometry(o.radius, 2),
+ attr = geo.attributes.position;
+ for (let j = 0; j < attr.count; j++) {
+ const v = new THREE.Vector3().fromBufferAttribute(attr, j);
+ const k = 1 + 0.075 * Math.sin(v.x * 19 + v.z * 13) * Math.cos(v.y * 23);
+ v.multiplyScalar(k);
+ attr.setXYZ(j, v.x, v.y, v.z);
+ }
+ smoothCobbleNormals(geo);
+ const mat = new THREE.MeshStandardMaterial({
+ color: new THREE.Color().setHSL(0.105, 0.1, 0.065 + rng() * 0.045),
+ roughness: 0.47,
+ });
+ const rock = new THREE.Mesh(geo, mat);
+ rock.name = `StreamObstacle_${i}`;
+ rock.position.copy(f.position).addScaledVector(f.across, o.lateral * widthAt(o.u) * 0.5);
+ rock.position.y -= o.radius * 0.32;
+ rock.scale.set(1, 0.72, 1.15);
+ rock.rotation.y = rng() * 6.28;
+ rock.castShadow = rock.receiveShadow = true;
+ group.add(rock);
+ }
+ let time = 0,
+ disposed = false;
+ group.userData.update = (t) => {
+ if (!Number.isFinite(t)) throw new RangeError('makeStream: time must be finite');
+ time = t;
+ uniforms.streamTime.value = t;
+ };
+ group.userData.sample = (u, lateral = 0, t = time) => {
+ if (
+ !Number.isFinite(u) ||
+ u < 0 ||
+ u > 1 ||
+ !Number.isFinite(lateral) ||
+ Math.abs(lateral) > 1 ||
+ !Number.isFinite(t)
+ )
+ throw new RangeError(
+ 'makeStream: sample requires u in [0,1], lateral in [-1,1], finite time'
+ );
+ const f = frame(u),
+ s = u * length,
+ l = lateral * widthAt(u) * 0.5;
+ f.position.addScaledVector(f.across, l);
+ f.position.y += height(s, l, t);
+ const hs = (height(s + 0.015, l, t) - height(s - 0.015, l, t)) / 0.03,
+ hl = (height(s, l + 0.015, t) - height(s, l - 0.015, t)) / 0.03;
+ const normal = f.longitudinal
+ .clone()
+ .addScaledVector(f.acrossDerivative, l)
+ .add(new THREE.Vector3(0, hs, 0))
+ .cross(f.across.clone().add(new THREE.Vector3(0, hl, 0)))
+ .normalize();
+ return {
+ position: f.position,
+ tangent: f.tangent,
+ normal,
+ depth: depth * (1 - 0.55 * lateral * lateral),
+ speed,
+ width: widthAt(u),
+ };
+ };
+ // Snapshot owned resources now. Callers may add children or remove meshes
+ // later; neither action changes which allocations this constructor owns.
+ const ownedResources = new Set();
+ const ownedInstances = [];
+ group.traverse((object) => {
+ if (object.isInstancedMesh) ownedInstances.push(object);
+ for (const resource of [
+ object.geometry,
+ ...(Array.isArray(object.material) ? object.material : [object.material]),
+ ]) {
+ if (resource) ownedResources.add(resource);
+ }
+ });
+ group.userData.dispose = () => {
+ if (disposed) return;
+ disposed = true;
+ for (const resource of ownedResources) resource.dispose();
+ for (const object of ownedInstances) object.dispose();
+ if (reflection) {
+ reflection.geometry.dispose();
+ reflection.dispose();
+ }
+ };
+ group.userData.surface = surface;
+ group.userData.length = length;
+ group.userData.description =
+ 'Graded kinematic stream with geometric ripples, cobble wakes and depth-dependent opaque-scene refraction; no arbitrary fluid collisions';
+ return group;
+}
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/submerged.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/submerged.js
index 538eb58d..71f5e6f6 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/submerged.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/submerged.js
@@ -20,6 +20,7 @@
*/
import * as THREE from 'three';
+import { attachDisposal, snapshotResources } from './lifecycle.js';
import { lehmer } from './noise.js';
import {
composeRoughness, makeShaderMaterial, instancedQuad, keepOutOfDepthPasses,
@@ -412,7 +413,7 @@ export function makeRainRings(opts = {}) {
mesh.name = 'RainRings';
mesh.renderOrder = 2;
mesh.userData.update = (t) => { mat.uniforms.uTime.value = t; };
- return keepOutOfDepthPasses(mesh);
+ return attachDisposal(keepOutOfDepthPasses(mesh), snapshotResources(mesh));
}
const ICE_VARYING = 'varying vec2 vAstraIceUv;';
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.js
index 11f66952..c0333813 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/surface_wear.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/surface_wear.js
@@ -11,11 +11,8 @@
* neither needs a UV; and both CHAIN with each other and with
* `terrain_shade` / `waterside` on one material.
*
- * Gloss is the one thing neither does per pixel: both write only at
- * `<color_fragment>`, which is BEFORE `<roughnessmap_fragment>`, and
- * neither uses `patchStandard`'s `roughnessBody`, so both retune
- * `material.roughness` instead and compose their factors through
- * `composeRoughness`.
+ * 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):
@@ -46,7 +43,7 @@
*/
import {
- patchStandard, composeRoughness, glslAxes, glslTriNoise, hash11, seedVec3,
+ patchStandard, glslAxes, glslTriNoise, seedVec3,
toColor, unit, worldBase,
} from './shader.js';
@@ -85,10 +82,8 @@ const seedOffset = (seed) => seedVec3(seed, 0.17, 3.71, 7.13, 64);
* — 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 varies per MATERIAL, not per pixel (see `composeRoughness`):
- * `seed` detunes the material's own roughness by a few percent, which
- * is what stops every surface in a scene from carrying one identical
- * highlight.
+ * 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
@@ -110,8 +105,6 @@ export function patchMicroBreakup(material, opts = {}) {
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;
- composeRoughness(material, 'micro',
- 1 + (hash11(seed + 1.9) - 0.5) * unit(strength) * 2);
patchStandard(material, BASE);
return patchStandard(material, {
name: 'wear:micro',
@@ -166,6 +159,7 @@ export function patchMicroBreakup(material, opts = {}) {
' 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);',
});
}
@@ -191,9 +185,8 @@ export function patchMicroBreakup(material, opts = {}) {
* this can never flicker into a wireframe. Bevel or smooth-shade the
* edges you want worn; rounded geometry wears where it curves tightest.
*
- * Gloss moves per MATERIAL, not per pixel (see `composeRoughness`): a
- * worn edge is polished, and the small drop in the material's own
- * roughness is the reachable half of that.
+ * 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.
@@ -218,11 +211,6 @@ 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;
- // Area-weighted: the gloss move is the MATERIAL's, and wear covers a
- // fraction of it. Spending the worn patch's full polish on the whole
- // surface is how a painted rail becomes a sky mirror on a renderer
- // with no post chain and a bright environment.
- composeRoughness(material, 'edge', 1 - 0.12 * unit(strength));
patchStandard(material, BASE);
return patchStandard(material, {
name: 'wear:edge',
@@ -280,5 +268,6 @@ export function patchEdgeWear(material, opts = {}) {
' 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.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/terrain.js
index d4ee569d..14846add 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/terrain.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/terrain.js
@@ -1,12 +1,33 @@
/**
* The ground, textured and seatable, in one call (the model takes CODE
* and ignores prose, so the ground ships as a function). `ground()`
- * returns the SAME height function it displaced the mesh with — place
+ * samples the actual mesh triangles — place
* every asset at `h(x, z)`; floating assets are the most-flagged defect.
*/
import * as THREE from 'three';
import * as MAT from './materials.js';
+import { attachDisposal } from './lifecycle.js';
+import { clonePatchedMaterial } from './shader.js';
+
+// PlaneGeometry splits each cell from its lower-left to upper-right vertex.
+// Interpolating the original noise field (or bilinearly interpolating four
+// corners) differs from that triangle surface between vertices.
+function triangleValue(position, nx, ny, gx, gy, component) {
+ gx = Math.max(0, Math.min(nx, gx));
+ gy = Math.max(0, Math.min(ny, gy));
+ const ix = Math.min(nx - 1, Math.floor(gx));
+ const iy = Math.min(ny - 1, Math.floor(gy));
+ const fx = gx - ix, fy = gy - iy;
+ const a = iy * (nx + 1) + ix;
+ const value = (i) => position.array[i * 3 + component];
+ if (fx + fy <= 1) {
+ return value(a) * (1 - fx - fy) + value(a + 1) * fx
+ + value(a + nx + 1) * fy;
+ }
+ return value(a + nx + 2) * (fx + fy - 1)
+ + value(a + 1) * (1 - fy) + value(a + nx + 1) * (1 - fx);
+}
/**
* Build a displaced, textured ground plane and its height function.
@@ -24,7 +45,7 @@ import * as MAT from './materials.js';
*/
export function ground(opts = {}) {
const size = opts.size || 400;
- const segs = Math.min(opts.segments || 128, 128);
+ const segs = Math.max(1, Math.floor(Math.min(opts.segments || 128, 128)));
const rand = opts.rand || (() => 0.5);
const relief = opts.relief === undefined ? 6 : opts.relief;
const scale = opts.scale || 90;
@@ -48,7 +69,7 @@ export function ground(opts = {}) {
return (a * (1 - fx) + b * fx) * (1 - fz) + (c * (1 - fx) + d * fx) * fz;
};
- const height = (x, z) => {
+ const fieldHeight = (x, z) => {
let n = sample(x, z) * 0.65 + sample(x * 2.9, z * 2.9) * 0.35;
n = (n - 0.5) * 2 * relief;
return opts.flat ? n * (1 - Math.min(1, Math.max(0, opts.flat(x, z)))) : n;
@@ -58,7 +79,7 @@ export function ground(opts = {}) {
geo.rotateX(-Math.PI / 2);
const pos = geo.attributes.position;
for (let i = 0; i < pos.count; i++) {
- pos.setY(i, height(pos.getX(i), pos.getZ(i)));
+ pos.setY(i, fieldHeight(pos.getX(i), pos.getZ(i)));
}
geo.computeVertexNormals();
@@ -74,8 +95,7 @@ export function ground(opts = {}) {
// is a few bytes of state, not a second upload.
let material = opts.material || MAT.soil();
if (material.userData && material.userData.shared) {
- material = material.clone();
- material.userData = {};
+ material = clonePatchedMaterial(material);
}
const retiled = new Map();
for (const key of ['map', 'roughnessMap', 'bumpMap', 'normalMap']) {
@@ -98,6 +118,11 @@ export function ground(opts = {}) {
const mesh = new THREE.Mesh(geo, material);
mesh.name = opts.name || 'Ground';
mesh.receiveShadow = true;
+ const owned = new Set([geo, ...retiled.values()]);
+ if (material !== opts.material) owned.add(material);
+ attachDisposal(mesh, owned);
+ const height = (x, z) => triangleValue(pos, segs, segs,
+ (x / size + 0.5) * segs, (z / size + 0.5) * segs, 1);
return { mesh, height };
}
@@ -220,7 +245,7 @@ export function cliff(opts = {}) {
pos.setZ(i, z);
tone.copy(bandColors[bandOf(x, y)]);
// Cheap AO: recessed rock reads darker, ledges catch the light.
- tone.offsetHSL(0, 0, Math.max(-1, Math.min(1, z / relief)) * 0.09);
+ tone.offsetHSL(0, 0, relief === 0 ? 0 : Math.max(-1, Math.min(1, z / relief)) * 0.09);
col[i * 3] = tone.r;
col[i * 3 + 1] = tone.g;
col[i * 3 + 2] = tone.b;
@@ -249,11 +274,13 @@ export function cliff(opts = {}) {
mesh.name = opts.name || 'Cliff';
mesh.castShadow = true;
mesh.receiveShadow = true;
+ attachDisposal(mesh, [geo, material, map, rough]);
const faceAt = (s, y) => {
const x = Math.max(-length / 2, Math.min(length / 2, s - length / 2));
const yy = Math.max(0, Math.min(height, y));
- return new THREE.Vector3(x, yy, depth(x, yy));
+ return new THREE.Vector3(x, yy, triangleValue(pos, segX, segY,
+ (x / length + 0.5) * segX, (1 - yy / height) * segY, 2));
};
return { mesh, faceAt };
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.js
index a6b57ced..fba598f2 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/terrain_shade.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/terrain_shade.js
@@ -20,8 +20,23 @@ const FBM_UNIT = [
'#ifndef ASTRA_FBM_UNIT',
'#define ASTRA_FBM_UNIT',
'float astraFbmUnit(vec2 p, int oct) {',
- ' float d = max(1.0 - pow(0.5, float(oct)), 0.25);',
- ' return clamp(astraFbm2(p, oct) / d, 0.0, 1.0);',
+ ' 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);',
+ '}',
+ 'vec3 astraTerrainBump(vec3 eye, vec3 n, float height) {',
+ ' vec3 dx = dFdx(eye), dy = dFdy(eye);',
+ ' vec3 a = cross(dy, n), b = cross(n, dx);',
+ ' float determinant = dot(dx, a);',
+ ' if (abs(determinant) < 1e-12) return n;',
+ ' return normalize(abs(determinant) * n - sign(determinant)',
+ ' * (dFdx(height) * a + dFdy(height) * b));',
'}',
'#endif',
].join('\n');
@@ -69,6 +84,7 @@ const TRI_HEAD = [
'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);',
@@ -102,6 +118,7 @@ const TRI_BODY = [
// 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 = [
@@ -114,6 +131,7 @@ const SPLAT_HEAD = [
'uniform float uSplatBlend;',
'uniform float uSplatSnowY;',
'uniform float uSplatSnowBand;',
+ 'uniform vec4 uSplatRoughness;',
].join('\n');
const SPLAT_CORE = [
@@ -215,14 +233,16 @@ function withWorld(material) {
* 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 colour, so pass the two
- * tones you want; the material's lighting and maps are untouched.
+ * 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).
@@ -249,9 +269,14 @@ export function patchTriplanar(material, opts = {}) {
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 = astraTerrainBump(-vViewPosition, normal, tpHeight);',
});
}
@@ -279,6 +304,8 @@ export function patchTriplanar(material, opts = {}) {
* 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.
@@ -327,8 +354,19 @@ export function patchSlopeSplat(material, opts = {}) {
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/tree.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/tree.js
new file mode 100644
index 00000000..ab491010
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/tree.js
@@ -0,0 +1,478 @@
+/**
+ * Near and middle-distance trees with connected branches and individual leaves.
+ * Metres; +Y up; the root stays at local y=0. No textures or network requests.
+ *
+ * makeTree({species:'oak'|'birch'|'willow',height:6,crownRadius:2.5,seed:7,
+ * leafDensity:1,leafSize:.12,wind:{dir:[1,.3],strength:.5,speed:1},
+ * autumn:0,shadows:true}) -> Group containing Wood and Leaves.
+ * makeShrub({...}) uses a low, spreading, multi-stem branch architecture.
+ * update(t), tick(t), dispose(), sampleWind(point,t), bounds and branches are
+ * on userData. Time is absolute and repeatable; wind uses local XZ axes.
+ * The leaf mesh is real instancing, so the host AO pass sees its rest pose.
+ * Colour, directional/spot depth and point-distance shadows share deformation.
+ * height and crownRadius are nominal architecture dimensions; bounds is the
+ * actual local envelope including leaves and maximum wind displacement.
+ * leafDensity (0..4) changes leaves per shoot; maxLeaves (default 24000) thins
+ * the entire crown without bias toward early branches. Wood remains connected.
+ * Each factory merges its wood and its leaves into one geometry each.
+ * Default species are heavy geometry. leafSegments (integer
+ * 3..32, defaults oak12/birch16/willow10) controls leaf curvature geometry
+ * independently of crown density; use 4 when individual leaf lobes are unresolved.
+ * Reduce leafDensity/maxLeaves as well for distant trees. These are geometry
+ * assets, not far cards; choose the detail when constructing the tree.
+ * dispose() releases captured owned resources, including detached original
+ * children, and leaves subsequently appended caller resources untouched.
+ * There is no collision, fracture or seasonal growth simulation.
+ */
+import * as THREE from 'three';
+import {mulberry32} from './noise.js';
+import {windOf} from './grass.js';
+import {patchStandard,shadowLike,tickShaders} from './shader.js';
+import {patchLeafSSS} from './foliage_shade.js';
+import {attachDisposal,snapshotResources} from './lifecycle.js';
+
+const TAU=Math.PI*2;
+const SPECIES={
+ oak:{radius:.42,trunk:.037,bark:0x665547,leaf:0x49672b,leafSize:.125,width:.65,
+ primary:12,secondary:5,twigs:4,droop:.03,crownStart:.29},
+ birch:{radius:.28,trunk:.018,bark:0xb8b5a0,leaf:0x587635,leafSize:.085,width:.76,
+ primary:14,secondary:4,twigs:4,droop:.08,crownStart:.28},
+ willow:{radius:.46,trunk:.029,bark:0x625c45,leaf:0x607742,leafSize:.17,width:.19,
+ primary:11,secondary:5,twigs:5,droop:.30,crownStart:.32},
+};
+const finite=(value,fallback,min,max,name)=>{
+ const n=value===undefined?fallback:value;
+ if(!Number.isFinite(n)||n<min||n>max)throw new RangeError(`tree: ${name} must be finite in [${min}, ${max}]`);
+ return n;
+};
+const V=(x=0,y=0,z=0)=>new THREE.Vector3(x,y,z);
+
+const WIND_HEAD=/* glsl */`
+uniform float uTime;
+uniform float uTreeHeight;
+uniform float uTreeAmp;
+uniform float uTreeSpeed;
+uniform float uTreePhase;
+uniform vec2 uTreeWind;
+#ifdef USE_INSTANCING
+attribute vec4 treeLeaf;
+varying vec4 vTreeLeaf;
+#endif
+varying vec3 vTreeRest;
+vec3 treeWindOffset(vec3 p) {
+ float b=clamp(p.y/uTreeHeight,0.0,1.0), t=uTime*uTreeSpeed;
+ float main=(.62*sin(t+uTreePhase)+.28*sin(t*.53+uTreePhase*1.7))
+ *(.65+.35*sin(t*.24+uTreePhase));
+ float side=.25*sin(t*.81+uTreePhase);
+ float twig=.07*sin(p.x*.7+p.z*.43+t*1.7+uTreePhase)*b;
+ vec2 d=(uTreeWind*(main+twig)+vec2(-uTreeWind.y,uTreeWind.x)*side)*uTreeAmp*b*b;
+ return vec3(d.x,0.0,d.y);
+}
+mat3 treeWindJacobian(vec3 p) {
+ float b=clamp(p.y/uTreeHeight,0.0,1.0),t=uTime*uTreeSpeed;
+ float db=p.y>0.0&&p.y<uTreeHeight?1.0/uTreeHeight:0.0;
+ float main=(.62*sin(t+uTreePhase)+.28*sin(t*.53+uTreePhase*1.7))
+ *(.65+.35*sin(t*.24+uTreePhase));
+ vec2 base=uTreeWind*main+vec2(-uTreeWind.y,uTreeWind.x)*(.25*sin(t*.81+uTreePhase));
+ float ph=p.x*.7+p.z*.43+t*1.7+uTreePhase;
+ vec2 dx=uTreeWind*(uTreeAmp*.07*b*b*b*cos(ph)*.7);
+ vec2 dz=uTreeWind*(uTreeAmp*.07*b*b*b*cos(ph)*.43);
+ vec2 dy=uTreeAmp*db*(base*2.0*b+uTreeWind*(.21*b*b*sin(ph)));
+ return mat3(vec3(1.0+dx.x,0.0,dx.y),vec3(dy.x,1.0,dy.y),vec3(dz.x,0.0,1.0+dz.y));
+}
+`;
+const WIND_BODY=/* glsl */`
+ vec3 trP=transformed;
+ vec3 trN=normal;
+ #ifdef USE_INSTANCING
+ float trFlutter=.10*(uTreeAmp/uTreeHeight)*30.0
+ *sin(uTime*uTreeSpeed*5.2+treeLeaf.x);
+ trP.z+=trFlutter*trP.y*trP.y;
+ trN=astraNormalTransform(mat3(vec3(1.,0.,0.),vec3(0.,1.,2.*trFlutter*transformed.y),vec3(0.,0.,1.)),trN);
+ trP=(instanceMatrix*vec4(trP,1.0)).xyz;
+ trN=astraNormalTransform(mat3(instanceMatrix),trN);
+ vTreeLeaf=treeLeaf;
+ #endif
+ vTreeRest=trP;
+ trN=astraNormalTransform(treeWindJacobian(trP),trN);
+ vec3 trMoved=trP+treeWindOffset(trP);
+ #ifdef USE_INSTANCING
+ transformed=(inverse(instanceMatrix)*vec4(trMoved,1.0)).xyz;
+ #else
+ transformed=trMoved;
+ #endif
+ #ifndef FLAT_SHADED
+ transformedNormal=normalMatrix*trN;
+ vNormal=normalize(transformedNormal);
+ #endif
+`;
+
+function windUniforms(height,wind,seed) {
+ return {uTreeHeight:{value:height},uTreeAmp:{value:height*.026*wind.amp},
+ uTreeSpeed:{value:wind.speed},uTreePhase:{value:(seed%65536)*.0137},
+ uTreeWind:{value:wind.dir.clone()}};
+}
+
+function pointOn(branch,t) {return branch.curve.getPoint(THREE.MathUtils.clamp(t,0,1));}
+function tangentOn(branch,t) {return branch.curve.getTangent(THREE.MathUtils.clamp(t,0,1)).normalize();}
+function radiusAt(branch,u) {
+ const taper=branch.order===0?.83:branch.order===1?.90:.95;
+ return branch.radius*Math.pow(1-u*taper,branch.order===0?.78:.88);
+}
+
+/** Build a bounded connected graph, then clothe its terminal shoots. */
+function skeleton(config,random) {
+ const {height:h,radius:r,species,spec,shrub}=config;
+ const branches=[];
+ function branch(parent,at,start,c1,c2,end,radius,order) {
+ const result={id:branches.length,parent:parent?.id??null,at,order,radius,
+ curve:new THREE.CubicBezierCurve3(start,c1,c2,end)};
+ branches.push(result);return result;
+ }
+ const stems=shrub?5:1;
+ for(let stem=0;stem<stems;stem++) {
+ const theta=stem*2.39996+random();
+ const root=shrub?V(Math.cos(theta)*r*.055,0,Math.sin(theta)*r*.055):V();
+ const top=V((random()-.5)*h*.16,h*(shrub?.72:species==='oak'?.88:.92),(random()-.5)*h*.16);
+ if(shrub) {top.x+=Math.cos(theta)*r*.38;top.z+=Math.sin(theta)*r*.38;}
+ const trunkR=h*spec.trunk*(shrub?.45:1)*( .9+random()*.2);
+ const trunk=branch(null,0,root,root.clone().add(V((random()-.5)*h*.07,h*.34,(random()-.5)*h*.07)),
+ top.clone().multiplyScalar(.66).add(V((random()-.5)*h*.10,h*.04,(random()-.5)*h*.10)),top,trunkR,0);
+ // Low buttresses spread the load into the ground. Their ends tuck below
+ // grade, leaving the exposed root shoulder continuous with the trunk.
+ if(!shrub)for(let j=0;j<6;j++) {
+ const a=j*TAU/6+random()*.50,d=V(Math.cos(a),0,Math.sin(a));
+ const start=pointOn(trunk,.022),length=trunkR*(2.8+random()*1.9);
+ const end=root.clone().addScaledVector(d,length);end.y=-trunkR*.40;
+ branch(trunk,.022,start,start.clone().addScaledVector(d,length*.20).add(V(0,-trunkR*.1,0)),
+ end.clone().addScaledVector(d,-length*.35).add(V(0,trunkR*.12,0)),end,trunkR*(.38+random()*.17),-1);
+ }
+ const primaries=shrub?4:spec.primary;
+ for(let i=0;i<primaries;i++) {
+ const at=spec.crownStart+(1-spec.crownStart)*(.02+.89*(i+.30*(random()-.5))/Math.max(1,primaries-1));
+ const start=pointOn(trunk,at),angle=i*2.39996+theta+(random()-.5)*.42;
+ const envelope=Math.sqrt(Math.max(.08,1-Math.pow((at-.43)/.68,2)));
+ let radial=r*envelope*(.55+random()*.50)*(shrub?.55:1);
+ const crownSpread=species==='oak'&&!shrub?1-.65*THREE.MathUtils.smoothstep(at,.50,.96):1;
+ radial*=crownSpread;
+ const dir=V(Math.cos(angle),0,Math.sin(angle));
+ const end=start.clone().addScaledVector(dir,radial).add(V(0,h*(.14+.10*(1-at)),0));
+ if(species==='oak'&&!shrub)end.y=h*(.48+.50*(at-.29)/.71+(random()-.5)*.12);
+ const sideways=V(-dir.z,0,dir.x),crook=(random()-.5)*radial*.70;
+ const primaryRadius=radiusAt(trunk,at)*(.44+random()*.31);
+ const primary=branch(trunk,at,start,
+ start.clone().addScaledVector(tangentOn(trunk,at),radial*(.15+random()*.22))
+ .addScaledVector(dir,radial*.19).addScaledVector(sideways,crook),
+ end.clone().addScaledVector(dir,-radial*(.19+random()*.18))
+ .addScaledVector(sideways,-crook*.65).add(V(0,h*(random()-.40)*.12,0)),end,primaryRadius,1);
+ const secondaryCount=shrub?3:spec.secondary;
+ for(let j=0;j<secondaryCount;j++) {
+ const a=.23+.72*(j+.20*(random()-.5))/Math.max(1,secondaryCount-1),p=pointOn(primary,a);
+ const sign=j%2?1:-1,phi=angle+sign*(.30+random()*.85);
+ const len=r*(.14+random()*.25)*(shrub?.58:1)*crownSpread,d=V(Math.cos(phi),0,Math.sin(phi));
+ const q=p.clone().addScaledVector(d,len).add(V(0,h*(.015+random()*.08-spec.droop*.20),0));
+ const second=branch(primary,a,p,p.clone().addScaledVector(tangentOn(primary,a),len*.26),
+ q.clone().addScaledVector(d,-len*.27).addScaledVector(sideways,(random()-.5)*len*.40).add(V(0,len*.22,0)),q,
+ radiusAt(primary,a)*(.42+random()*.28),2);
+ const twigCount=shrub?3:spec.twigs;
+ for(let k=0;k<twigCount;k++) {
+ const u=.24+.75*k/Math.max(1,twigCount-1),b=pointOn(second,u);
+ const ta=phi+(k%2?1:-1)*(.35+random()*.65);
+ const tl=r*(.15+random()*.10)*(shrub?.60:1)*crownSpread,td=V(Math.cos(ta),0,Math.sin(ta));
+ const down=species==='willow'?h*(.16+random()*.19):h*spec.droop*(.5+random());
+ const e=b.clone().addScaledVector(td,tl).add(V(0,h*(.015+random()*.07)-down,0));
+ branch(second,u,b,b.clone().addScaledVector(tangentOn(second,u),tl*.35),
+ e.clone().addScaledVector(td,-tl*.25).add(V(0,down*.50+tl*.1,0)),e,
+ Math.max(.0011,radiusAt(second,u)*(.48+random()*.22)),3);
+ }
+ }
+ }
+ }
+ // Fine terminal shoots carry the foliage. Their roots lie on real parent
+ // curves; phyllotactic rotations distribute foliage around each shoot.
+ const twigs=branches.filter(b=>b.order===3);
+ for(const twig of twigs)for(let shoot=0;shoot<3;shoot++) {
+ const at=.30+shoot*.31,p=pointOn(twig,at),t=tangentOn(twig,at);
+ const side=new THREE.Vector3().crossVectors(t,V(0,1,0));
+ if(side.lengthSq()<1e-6)side.set(1,0,0);side.normalize();
+ const length=r*(shrub?.095:.12)*(.7+random()*.6);
+ const around=new THREE.Vector3().crossVectors(t,side).normalize();
+ const angle=shoot*2.39996+twig.id*.71+random()*.6;
+ const d=t.clone().multiplyScalar(.42).addScaledVector(side,Math.cos(angle)*.85)
+ .addScaledVector(around,Math.sin(angle)*.85);
+ d.y+=species==='willow'?-.40:.12+random()*.28;d.normalize();
+ const end=p.clone().addScaledVector(d,length);
+ branch(twig,at,p,p.clone().addScaledVector(t,length*.3),
+ end.clone().addScaledVector(d,-length*.24).add(V(0,length*.14,0)),end,
+ Math.max(.00065,radiusAt(twig,at)*(.48+random()*.18)),4);
+ }
+ return branches;
+}
+
+/** Append a tapered tube using a transported frame; no meshes per branch. */
+function tube(data,points,radii,sides,phase=0) {
+ const start=data.positions.length/3;
+ let side=null,along=0;
+ for(let i=0;i<points.length;i++) {
+ if(i)along+=points[i].distanceTo(points[i-1]);
+ const p=points[i],tangent=points[Math.min(i+1,points.length-1)].clone()
+ .sub(points[Math.max(i-1,0)]).normalize();
+ if(!side)side=new THREE.Vector3().crossVectors(tangent,Math.abs(tangent.y)>.92?V(1,0,0):V(0,1,0)).normalize();
+ side.addScaledVector(tangent,-side.dot(tangent)).normalize();
+ const other=new THREE.Vector3().crossVectors(tangent,side).normalize();
+ for(let j=0;j<=sides;j++) {
+ const angle=TAU*j/sides,rad=radii[i]*(1+.045*Math.sin(angle*3+phase+i*.31));
+ const normal=side.clone().multiplyScalar(Math.cos(angle)).addScaledVector(other,Math.sin(angle));
+ const v=p.clone().addScaledVector(normal,rad);
+ const before=Math.max(0,i-1),after=Math.min(points.length-1,i+1);
+ const slope=(radii[after]-radii[before])/Math.max(points[after].distanceTo(points[before]),1e-8);
+ const surfaceNormal=normal.clone().addScaledVector(tangent,-slope).normalize();
+ data.positions.push(v.x,v.y,v.z);data.normals.push(surfaceNormal.x,surfaceNormal.y,surfaceNormal.z);
+ data.uv.push(j/sides*TAU*radii[0]+phase,along);
+ if(i<points.length-1&&j<sides) {
+ const a=start+i*(sides+1)+j,b=a+sides+1;
+ data.indices.push(a,a+1,b,a+1,b+1,b);
+ }
+ }
+ }
+ // End cap prevents exposed terminal shoots from showing an open tube.
+ const center=data.positions.length/3,p=points.at(-1);
+ const direction=p.clone().sub(points.at(-2)).normalize();
+ data.positions.push(p.x,p.y,p.z);data.normals.push(...direction.toArray());data.uv.push(.5,1);
+ const ring=start+(points.length-1)*(sides+1);
+ for(let j=0;j<sides;j++)data.indices.push(center,ring+j,ring+j+1);
+}
+
+function bladeGeometry(species,rows) {
+ const positions=[],uv=[],indices=[];
+ for(let j=0;j<=rows;j++)for(let k=0;k<3;k++) {
+ const u=j/rows,x=k-1;
+ let width=Math.pow(Math.max(Math.sin(Math.PI*u),0),.70);
+ if(species==='oak')width*=.82+.18*Math.cos(u*TAU*5.2);
+ if(species==='birch')width*=1.15-.50*u+(j%2?-.08:.04);
+ if(species==='willow')width*=.88+.12*Math.sin(Math.PI*u);
+ positions.push(x*width*.5,u,.055*Math.sin(Math.PI*u)*(1-x*x)-.10*u*u);
+ uv.push(k/2,u);
+ if(j<rows&&k<2) {const a=j*3+k;indices.push(a,a+1,a+3,a+1,a+4,a+3);}
+ }
+ const geometry=new THREE.BufferGeometry();geometry.setAttribute('position',new THREE.Float32BufferAttribute(positions,3));
+ geometry.setAttribute('uv',new THREE.Float32BufferAttribute(uv,2));geometry.setIndex(indices);geometry.computeVertexNormals();
+ return geometry;
+}
+
+function leafPlacements(branches,config,random,wood) {
+ const leaves=[],{spec,height:h,leafSize,leafDensity,maxLeaves,autumn,species}=config;
+ const countFor=branch=>branch.order<2?0:Math.max(0,Math.round((branch.order===4?20:branch.order===3?4:3)*leafDensity));
+ let remaining=branches.reduce((sum,branch)=>sum+countFor(branch),0);
+ let keep=Math.min(maxLeaves,remaining);
+ for(const branch of branches) {
+ const count=countFor(branch);
+ for(let i=0;i<count;i++) {
+ // Exact-size sampling without replacement thins the whole crown evenly.
+ // A cap must not strip the late-created side or terminal shoots bare.
+ const accepted=random()<keep/Math.max(remaining,1);remaining--;
+ if(!accepted)continue;keep--;
+ const u=.12+.87*(i+.25+random()*.5)/Math.max(count,1),point=pointOn(branch,u);
+ const tangent=tangentOn(branch,u),angle=i*2.39996+branch.id*.83;
+ let side=new THREE.Vector3().crossVectors(tangent,V(0,1,0));
+ if(side.lengthSq()<1e-5)side=V(1,0,0);side.normalize();
+ const normal=new THREE.Vector3().crossVectors(side,tangent).normalize();
+ const radial=side.clone().multiplyScalar(Math.cos(angle)).addScaledVector(normal,Math.sin(angle));
+ const direction=tangent.clone().multiplyScalar(.48).addScaledVector(radial,.85);
+ direction.y+=species==='willow'?-.35:.25;direction.normalize();
+ const length=leafSize*(.70+random()*.55)*(1-.20*u),width=length*spec.width*(.84+random()*.22);
+ const petiole=length*.13;
+ const base=point.clone().addScaledVector(direction,petiole);
+ tube(wood,[point,base],[Math.min(.0015,length*.009),Math.min(.0009,length*.005)],3,angle);
+ let up=V(0,1,0).addScaledVector(radial,.35).normalize();
+ let across=new THREE.Vector3().crossVectors(direction,up);
+ if(across.lengthSq()<1e-6)across=side.clone();across.normalize();
+ up.crossVectors(across,direction).normalize();
+ const matrix=new THREE.Matrix4().makeBasis(across,direction,up);
+ matrix.scale(V(width,length,length));matrix.setPosition(base);
+ const age=THREE.MathUtils.clamp(random()*.55+autumn*.8,0,1);
+ const color=new THREE.Color(config.leafColor).multiplyScalar(.83+random()*.30);
+ color.lerp(new THREE.Color(age>.85?0x895129:0xbaa34a),autumn*(.25+random()*.75));
+ leaves.push({matrix,color,seed:random()*TAU,age,vigor:1-u*.6,branch:branch.id,at:u,anchor:point});
+ }
+ }
+ return leaves;
+}
+
+function woodMaterial(config,uniforms) {
+ const material=new THREE.MeshStandardMaterial({color:config.barkColor,roughness:.92,name:'TreeBark'});
+ material.defines={USE_UV:''};
+ patchStandard(material,{name:'tree:wood',uniforms:{...uniforms,
+ uTreeBirch:{value:config.species==='birch'?1:0},uTreeWillow:{value:config.species==='willow'?1:0}},
+ vertexHead:WIND_HEAD,vertexBody:WIND_BODY,
+ fragmentHead:/* glsl */`
+ varying vec3 vTreeRest; uniform float uTreeBirch,uTreeWillow;
+ float treeBarkResolved(vec2 frequency,vec2 footprint) {
+ return 1.0-smoothstep(.28,.90,max(frequency.x*footprint.x,frequency.y*footprint.y));
+ }
+ float treeBarkHeight(vec2 p,vec2 footprint) {
+ // Branch coordinates are metres around the stem and along its curve.
+ // Slowly wandering grain joins along the branch instead of closing into
+ // equal-height Voronoi tiles. Willow carries a finer, fibrous grain.
+ vec2 frequency=mix(vec2(21.0,5.2),vec2(38.0,3.8),uTreeWillow);
+ float wander=astraNoise2(p*vec2(3.3,4.2))*1.3
+ +astraNoise2(p*vec2(8.1,1.53)+17.2)*.65;
+ vec2 q=p*frequency+vec2(wander,0.0);
+ float coarse=astraNoise2(q);
+ float ridge=smoothstep(.25,.52,coarse);
+ float resolved=treeBarkResolved(frequency,footprint);
+ ridge=mix(.51,ridge,resolved);
+ vec2 fineFrequency=frequency*vec2(1.47,4.90);
+ float fine=astraNoise2(p*fineFrequency+vec2(wander*.8,21.3));
+ fine=mix(.5,smoothstep(.26,.68,fine),treeBarkResolved(fineFrequency,footprint));
+ vec2 grainFrequency=vec2(170.0,105.0);
+ float grain=astraNoise2(p*grainFrequency+37.1);
+ grain=mix(.5,grain,treeBarkResolved(grainFrequency,footprint));
+ return (ridge*.0024+fine*.0018+grain*.0006)*(1.0-uTreeBirch*.94);
+ }
+ float treeLenticelAt(vec2 p) {
+ return smoothstep(.60,.77,astraNoise2(p*vec2(7.8,170.0)+11.7))
+ *smoothstep(.32,.59,astraNoise2(p*vec2(7.0,23.0)+43.2));
+ }
+ float treeLenticel(vec2 p,vec2 footprint) {
+ // Area-sample the narrow horizontal marks before they become subpixel.
+ // A simple amplitude fade loses their pigment and causes distance pops.
+ float marks=0.0;
+ for(int y=-1;y<=1;y++)for(int x=-1;x<=1;x++)
+ marks+=treeLenticelAt(p+vec2(float(x),float(y))*footprint*.333333);
+ float mean=.10*smoothstep(.32,.59,astraNoise2(p*vec2(7.0,23.0)+43.2));
+ return mix(marks/9.0,mean,smoothstep(2.0,4.0,max(footprint.x*7.8,footprint.y*170.0)));
+ }
+ `,
+ fragmentBody:/* glsl */`
+ // All offset height evaluations use this SAME footprint. Differentiating
+ // a per-tap screen filter would turn its quad boundaries into fake relief.
+ vec2 trFootprint=max(abs(dFdx(vUv)),abs(dFdy(vUv)));
+ float trFurrow=treeBarkHeight(vUv,trFootprint)/(1.0-uTreeBirch*.94);
+ diffuseColor.rgb*=mix(.65+.43*smoothstep(.0007,.0047,trFurrow),
+ .90+.10*astraNoise2(vUv*vec2(9.,18.)),uTreeBirch);
+ if(uTreeBirch>.5) diffuseColor.rgb*=1.0-.76*treeLenticel(vUv,trFootprint);
+ diffuseColor.rgb*=mix(.65,1.0,smoothstep(0.0,.35,vTreeRest.y));
+ `,
+ normalBody:/* glsl */`
+ vec2 trE=max(vec2(.0006),trFootprint*.55);
+ vec2 trHeightGradient=vec2(
+ (treeBarkHeight(vUv+vec2(trE.x,0.),trFootprint)-treeBarkHeight(vUv-vec2(trE.x,0.),trFootprint))/(2.*trE.x),
+ (treeBarkHeight(vUv+vec2(0.,trE.y),trFootprint)-treeBarkHeight(vUv-vec2(0.,trE.y),trFootprint))/(2.*trE.y));
+ vec2 trScreenGradient=vec2(dot(trHeightGradient,dFdx(vUv)),dot(trHeightGradient,dFdy(vUv)));
+ vec3 trSigmaX=dFdx(-vViewPosition),trSigmaY=dFdy(-vViewPosition);
+ vec3 trR1=cross(trSigmaY,normal),trR2=cross(normal,trSigmaX);
+ float trDet=dot(trSigmaX,trR1);
+ if(abs(trDet)>1e-12) {
+ vec3 trGradient=(trScreenGradient.x*trR1+trScreenGradient.y*trR2)/trDet;
+ // Keep grazing fragments finite without normalizing tiny determinant-
+ // scaled vectors. Relief slopes above this limit are unresolved here.
+ trGradient*=min(1.0,1.5/max(length(trGradient),1e-8));
+ normal=normalize(normal-trGradient);
+ }
+ `});
+ return material;
+}
+
+function leafMaterial(config,uniforms) {
+ const material=new THREE.MeshPhysicalMaterial({color:0xffffff,roughness:.72,specularIntensity:.35,
+ side:THREE.DoubleSide,name:'TreeLeaf'});
+ patchStandard(material,{name:'tree:leaf',uniforms,vertexHead:WIND_HEAD,vertexBody:WIND_BODY,
+ fragmentHead:'varying vec3 vTreeRest; varying vec4 vTreeLeaf;',
+ fragmentBody:/* glsl */`
+ float trVein=1.0-smoothstep(.012,.038,abs(vUv.x-.5));
+ float trSecondary=sin(vUv.y*60.0-abs(vUv.x-.5)*18.0);
+ diffuseColor.rgb*=.95+.025*trSecondary-.075*trVein;
+ diffuseColor.rgb*=mix(.87,1.10,vTreeLeaf.z);
+ float trScar=astraNoise2(vUv*vec2(35.,52.)+vTreeLeaf.x*5.);
+ diffuseColor.rgb*=1.0-smoothstep(.66,.80,trScar)*vTreeLeaf.y*.25;
+ `});
+ // Explicit UV use is independent of texture presence.
+ material.defines={...(material.defines||{}),USE_UV:''};
+ patchLeafSSS(material,{strength:.62,power:2.3,tint:0xaec371,variance:.14,varyScale:.8});
+ return material;
+}
+
+function build(opts,shrub) {
+ const species=opts.species===undefined?'oak':opts.species;
+ if(!Object.hasOwn(SPECIES,species))throw new RangeError('tree: species must be oak, birch or willow');
+ const spec=SPECIES[species],height=finite(opts.height,shrub?2.2:6,.3,35,'height');
+ const leafSegments=finite(opts.leafSegments,species==='birch'?16:species==='willow'?10:12,3,32,'leafSegments');
+ if(!Number.isInteger(leafSegments))throw new RangeError('tree: leafSegments must be an integer');
+ const config={species,spec,height,shrub,seed:finite(opts.seed,7,-2147483648,2147483647,'seed'),
+ radius:finite(opts.crownRadius,height*(shrub?.58:spec.radius),.1,25,'crownRadius'),
+ leafDensity:finite(opts.leafDensity,1,0,4,'leafDensity'),
+ leafSize:finite(opts.leafSize,spec.leafSize,.025,.5,'leafSize'),
+ maxLeaves:Math.floor(finite(opts.maxLeaves,24000,0,100000,'maxLeaves')),
+ autumn:finite(opts.autumn,0,0,1,'autumn'),
+ barkColor:opts.barkColor??spec.bark,leafColor:opts.leafColor??spec.leaf};
+ const wind=windOf(opts.wind),random=mulberry32(config.seed);
+ if(![wind.amp,wind.speed,wind.dir.x,wind.dir.y].every(Number.isFinite))throw new RangeError('tree: wind must be finite');
+ const branches=skeleton(config,random),wood={positions:[],normals:[],uv:[],indices:[]};
+ for(const branch of branches) {
+ const steps=branch.order===0?28:branch.order===1?18:branch.order===2?10:6;
+ const points=[],radii=[];
+ for(let i=0;i<=steps;i++) {
+ const u=i/steps;points.push(pointOn(branch,u));
+ let radius=radiusAt(branch,u);
+ if(branch.order===0)radius*=1+.95*Math.exp(-u*24);
+ else if(branch.order>0)radius*=1+.48*Math.exp(-u*22)+.17*Math.exp(-Math.pow((u-.085)*18,2));
+ radii.push(Math.max(radius,.0005));
+ }
+ tube(wood,points,radii,branch.order===0?18:branch.order===1?12:5,branch.id*.7);
+ }
+ const leaves=leafPlacements(branches,config,random,wood);
+ const geometry=new THREE.BufferGeometry();geometry.setAttribute('position',new THREE.Float32BufferAttribute(wood.positions,3));
+ geometry.setAttribute('normal',new THREE.Float32BufferAttribute(wood.normals,3));geometry.setAttribute('uv',new THREE.Float32BufferAttribute(wood.uv,2));
+ geometry.setIndex(wood.indices);geometry.computeBoundingBox();
+ const group=new THREE.Group();group.name=opts.name||(shrub?'Shrub':'Tree');
+ const uniforms=windUniforms(height,wind,config.seed),bark=woodMaterial(config,uniforms);
+ const woodMesh=new THREE.Mesh(geometry,bark);woodMesh.name='Wood';woodMesh.receiveShadow=true;group.add(woodMesh);
+ if(opts.shadows!==false)shadowLike(woodMesh,'tree:woodShadow',WIND_HEAD,WIND_BODY);
+ let leafMesh=null;
+ const bounds=geometry.boundingBox.clone();
+ if(leaves.length) {
+ const leafGeometry=bladeGeometry(species,leafSegments),material=leafMaterial(config,uniforms);
+ const data=new Float32Array(leaves.length*4);
+ leafMesh=new THREE.InstancedMesh(leafGeometry,material,leaves.length);leafMesh.name='Leaves';leafMesh.receiveShadow=true;
+ for(let i=0;i<leaves.length;i++) {
+ const leaf=leaves[i];leafMesh.setMatrixAt(i,leaf.matrix);leafMesh.setColorAt(i,leaf.color);
+ data.set([leaf.seed,leaf.age,leaf.vigor,leaf.branch],i*4);
+ }
+ leafGeometry.setAttribute('treeLeaf',new THREE.InstancedBufferAttribute(data,4));
+ leafMesh.instanceMatrix.needsUpdate=true;leafMesh.instanceColor.needsUpdate=true;
+ leafMesh.computeBoundingBox();leafMesh.computeBoundingSphere();bounds.union(leafMesh.boundingBox);group.add(leafMesh);
+ if(opts.shadows!==false)shadowLike(leafMesh,'tree:leafShadow',WIND_HEAD,WIND_BODY);
+ }
+ // The formula's horizontal excursion is <=1.22*amp; flutter adds at most
+ // .078*wind.amp*leaf length, with a conservative allowance for curved blades.
+ const travel=Math.abs(uniforms.uTreeAmp.value)*1.25+config.leafSize*Math.abs(wind.amp)*.12;
+ bounds.expandByScalar(travel);
+ geometry.boundingBox=geometry.boundingBox.clone().expandByScalar(travel);
+ geometry.boundingSphere=geometry.boundingBox.getBoundingSphere(new THREE.Sphere());
+ if(leafMesh) {leafMesh.boundingBox.expandByScalar(travel);leafMesh.boundingSphere=leafMesh.boundingBox.getBoundingSphere(new THREE.Sphere());}
+ group.userData.bounds=bounds;
+ group.userData.species=species;
+ group.userData.branchCount=branches.length;
+ group.userData.leafCount=leaves.length;
+ group.userData.branches=branches.map(branch=>({id:branch.id,parent:branch.parent,at:branch.at,order:branch.order,
+ radius:branch.radius,start:branch.curve.v0.clone(),end:branch.curve.v3.clone(),
+ sample:(u)=>pointOn(branch,finite(u,0,0,1,'branch parameter'))}));
+ group.userData.leafAttachments=leaves.map(leaf=>({branch:leaf.branch,at:leaf.at,anchor:leaf.anchor.clone()}));
+ group.userData.sampleWind=(point,t=0)=>{
+ finite(t,0,-1e9,1e9,'time');const p=point?.isVector3?point.clone():Array.isArray(point)&&point.length===3?V(...point):null;
+ if(!p||![p.x,p.y,p.z].every(Number.isFinite))throw new RangeError('tree: sampleWind needs a finite local Vector3 or [x,y,z]');
+ const u=uniforms,b=THREE.MathUtils.clamp(p.y/height,0,1),time=t*wind.speed,phase=u.uTreePhase.value;
+ const main=(.62*Math.sin(time+phase)+.28*Math.sin(time*.53+phase*1.7))*(.65+.35*Math.sin(time*.24+phase));
+ const side=.25*Math.sin(time*.81+phase),twig=.07*Math.sin(p.x*.7+p.z*.43+time*1.7+phase)*b;
+ const amp=u.uTreeAmp.value*b*b;
+ p.x+=(wind.dir.x*(main+twig)-wind.dir.y*side)*amp;
+ p.z+=(wind.dir.y*(main+twig)+wind.dir.x*side)*amp;
+ return p;
+ };
+ group.userData.update=group.userData.tick=(t=0)=>{finite(t,0,-1e9,1e9,'time');tickShaders(group,t);};
+ return attachDisposal(group,snapshotResources(group));
+}
+
+export function makeTree(opts={}) {return build(opts,false);}
+export function makeShrub(opts={}) {return build(opts,true);}
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/urban.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/urban.js
index 2729cb26..888696bd 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/urban.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/urban.js
@@ -16,13 +16,14 @@
* 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 {
- baseRoughness, composeRoughness, keepOutOfDepthPasses, makeShaderMaterial,
+ keepOutOfDepthPasses, makeShaderMaterial,
patchStandard, tickShaders, toColor, unit,
} from './shader.js';
@@ -73,10 +74,10 @@ const CW_VERTEX = [
' vec3 cwNo = normal;',
'#ifdef USE_INSTANCING',
' cwP = instanceMatrix * cwP;',
- ' cwNo = mat3(instanceMatrix) * cwNo;',
+ ' cwNo = astraNormalTransform(mat3(instanceMatrix), cwNo);',
'#endif',
' vCwW = (modelMatrix * cwP).xyz;',
- ' vCwN = normalize((modelMatrix * vec4(cwNo, 0.0)).xyz);',
+ ' vCwN = astraNormalTransform(mat3(modelMatrix), cwNo);',
].join('\n');
const CW_HEAD = [
@@ -261,11 +262,6 @@ export function patchCurtainWall(material, opts = {}) {
? sky.clone().lerp(new THREE.Color(0xffffff), 0.62)
: toColor(opts.haze, 0xdfe7ee);
const reflect = opts.reflect === undefined ? 0.22 : unit(opts.reflect);
- // Glass is the smoothest thing on a street; roughness is a MATERIAL
- // property here (no patch can reach the per-pixel one).
- const base = baseRoughness(material);
- composeRoughness(material, 'urban:curtain',
- base > 0 ? Math.max(0.05, 0.10 / base) : 1);
return patchStandard(material, {
name: opts.name || 'urban:curtain',
uniforms: {
@@ -296,6 +292,8 @@ export function patchCurtainWall(material, opts = {}) {
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;',
});
}
@@ -742,12 +740,12 @@ export function makePowerLines(opts = {}) {
}
g.userData.spans = spans;
- g.userData.tick = (t) => tickShaders(g, t);
+ 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 g;
+ return attachDisposal(g, snapshotResources(g));
}
@@ -1094,7 +1092,9 @@ export function makeBillboard(opts = {}) {
return g;
};
g.userData.relight();
- g.userData.tick = (t) => tickShaders(g, t);
+ g.userData.update = g.userData.tick = (t) => tickShaders(g, t);
g.userData.forward = '+Z';
- return g;
+ 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.js
index 66aba1fc..a807438e 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/veils.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/veils.js
@@ -42,12 +42,12 @@
* 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.
*
- * All three billboard against the WORLD camera axes, so add them at the
- * scene root or under a translated parent — a rotated or scaled parent
- * tilts the cards.
+ * 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 {
@@ -87,11 +87,11 @@ function _wrap(v, extent, half) {
* 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 every few frames
+ * 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` stays (1,1,1) in a scene with no lights at all,
- * which is what an asset preview and the shader check build.
+ * 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
@@ -110,11 +110,11 @@ 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 < 15) return hit;
+ if (hit && frame === hit.frame) return hit;
const distant = { r: 0, g: 0, b: 0 };
const punctual = [];
let found = 0;
- scene.traverse((o) => {
+ scene.traverseVisible((o) => {
if (!o.isLight || o.visible === false || !(o.intensity > 0)) return;
found++;
const c = o.color;
@@ -157,10 +157,24 @@ function _litByScene(mesh, autoTint) {
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(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) return;
+ 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);
@@ -196,7 +210,7 @@ function _litByScene(mesh, autoTint) {
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);
};
}
@@ -308,7 +322,7 @@ export function makeRainVeil(opts = {}) {
// does not cast a shadow; every other veil in this library says so.
keepOutOfDepthPasses(g);
_litByScene(mesh, autoTint);
- g.userData.tick = (t) => tickShaders(g, t);
+ g.userData.update = g.userData.tick = (t) => tickShaders(g, t);
g.userData.axis = axis.clone();
g.userData.length = len;
g.userData.sample = (i, t) => {
@@ -317,7 +331,7 @@ export function makeRainVeil(opts = {}) {
_wrap(sheet[k * 4] + wind.x * t, extent, half), -sink,
_wrap(sheet[k * 4 + 1] + wind.y * t, extent, half));
};
- return g;
+ return attachDisposal(g, snapshotResources(g));
}
/** One curtain per instance, rolled about its own fall axis. */
@@ -372,7 +386,7 @@ function veilMaterial(cfg) {
// 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 - cameraPosition);',
+ ' 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)',
@@ -391,10 +405,11 @@ function veilMaterial(cfg) {
// 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)',
- ' * (1.0 - smoothstep(0.80, 1.02, 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 - cameraPosition));',
+ ' length(vP - uCameraLocal));',
' float cap = uAlpha * vBright * vFade * prof * near;',
' if (cap < 0.002) discard;',
' float wx = (vUv.x - 0.5) * 2.0 * vHalfW;',
@@ -420,10 +435,10 @@ function veilMaterial(cfg) {
// 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;',
+ ' 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.34 + 0.66 * exp(-d * 2.1)) * sqrt(body);',
+ ' * (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
@@ -536,7 +551,7 @@ export function makeSnowfall(opts = {}) {
g.add(mesh);
keepOutOfDepthPasses(g);
_litByScene(mesh, autoTint);
- g.userData.tick = (t) => tickShaders(g, t);
+ 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;
@@ -549,7 +564,7 @@ export function makeSnowfall(opts = {}) {
+ wob * wobZ(swing[k * 4 + 2], swing[k * 4 + 3], t),
extent, half));
};
- return g;
+ return attachDisposal(g, snapshotResources(g));
}
/** Slow fall, wandering path, and a lens that cannot hold the near ones. */
@@ -604,12 +619,10 @@ function snowMaterial(cfg) {
// 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 - cameraPosition));',
+ ' length(p - uCameraLocal));',
' float s = uSize * aFlake.x * (1.0 + uBokeh * vBlur);',
- ' vec3 camR = vec3(viewMatrix[0][0], viewMatrix[1][0],',
- ' viewMatrix[2][0]);',
- ' vec3 camU = vec3(viewMatrix[0][1], viewMatrix[1][1],',
- ' viewMatrix[2][1]);',
+ ' vec3 camR = uCameraRight;',
+ ' vec3 camU = uCameraUp;',
' transformed = p + camR * (aCorner.x * s)',
' + camU * (aCorner.y * s);',
' float vy = y / uHeight;',
@@ -729,7 +742,7 @@ export function makeMotes(opts = {}) {
// not haze at distance, and the colour is the caller's statement
// about the light they hang in.
_litByScene(mesh, null);
- g.userData.tick = (t) => tickShaders(g, t);
+ 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));
@@ -740,7 +753,7 @@ export function makeMotes(opts = {}) {
pos[k * 3 + 2] + wob * wobZ(swing[k * 4 + 2],
swing[k * 4 + 3], t));
};
- return g;
+ return attachDisposal(g, snapshotResources(g));
}
/** Near-still specks that flash as their faces come round. */
@@ -784,10 +797,8 @@ function moteMaterial(cfg) {
// 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 = vec3(viewMatrix[0][0], viewMatrix[1][0],',
- ' viewMatrix[2][0]);',
- ' vec3 camU = vec3(viewMatrix[0][1], viewMatrix[1][1],',
- ' viewMatrix[2][1]);',
+ ' vec3 camR = uCameraRight;',
+ ' vec3 camU = uCameraUp;',
' transformed = p + camR * (aCorner.x * s)',
' + camU * (aCorner.y * s);',
' float vy = y / uHeight;',
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/water.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/water.js
index 59c646ef..81f42fd6 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/water.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/water.js
@@ -14,7 +14,9 @@
*/
import * as THREE from 'three';
+import { attachDisposal, snapshotResources } from './lifecycle.js';
import { Water } from 'three/addons/objects/Water.js';
+import { withRendererState } from './shader.js';
// Battery-graded freeze point: mid-phase, waves clearly formed.
const FROZEN_TIME = 7.3;
@@ -28,7 +30,6 @@ const _DAY_SUN = new THREE.Vector3(
Math.cos(_EL) * Math.cos(_AZ), Math.sin(_EL),
Math.cos(_EL) * Math.sin(_AZ));
-let _oceans = 0;
/**
* Synthesize the tiling wave-normal DataTexture the Water shader
@@ -168,7 +169,8 @@ const _TAIL = /* glsl */`
// 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 ) );
- vec3 glitter = sunColor * glitterScale * shade
+ 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 );
@@ -215,7 +217,7 @@ function _regrade(material) {
}
/**
- * Read the scene's own lighting once, at the first render, and point the
+ * 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
@@ -228,8 +230,7 @@ const _V2 = new THREE.Vector3();
function _readScene(scene, uniforms, pinned) {
let key = null, keyLum = -1, hemi = null, amb = null;
- scene.traverse((o) => {
- if (!o.visible) return;
+ scene.traverseVisible((o) => {
if (o.isDirectionalLight) {
const c = o.color;
const l = o.intensity
@@ -245,6 +246,8 @@ function _readScene(scene, uniforms, pinned) {
// 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);
@@ -272,9 +275,9 @@ function _readScene(scene, uniforms, pinned) {
}
if (!pinned.ambient) {
const t = uniforms.ambientColor.value;
+ t.setRGB(0, 0, 0);
if (hemi) t.copy(hemi.color).multiplyScalar(hemi.intensity * INV_PI);
else if (amb) t.copy(amb.color).multiplyScalar(amb.intensity * INV_PI);
- else if (scene.fog) t.copy(scene.fog.color).multiplyScalar(0.35);
t.r = Math.min(t.r, 1); t.g = Math.min(t.g, 1); t.b = Math.min(t.b, 1);
}
}
@@ -300,7 +303,7 @@ function _readScene(scene, uniforms, pinned) {
* `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 hemisphere/ambient light, else its fog).
+ * 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`.
*/
@@ -308,13 +311,6 @@ function _readScene(scene, uniforms, pinned) {
export const BROADBAND_EXTENT_M = 300;
export function makeOcean(width, depth, opts = {}) {
- _oceans++;
- if (_oceans > 1) {
- console.warn(
- 'makeOcean: ' + _oceans + ' oceans in one scene — each one ' +
- 're-renders the whole scene per frame. Contract is ONE RTT ' +
- 'surface (one ocean, never alongside a Reflector).');
- }
const sunDir =
(opts.sunDir ? opts.sunDir.clone() : _DAY_SUN.clone()).normalize();
// 512, not 256: a 256px mirror stretched across half a 1280x720 frame
@@ -344,6 +340,8 @@ export function makeOcean(width, depth, opts = {}) {
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
@@ -388,11 +386,21 @@ export function makeOcean(width, depth, opts = {}) {
ambient: opts.ambient !== undefined,
};
const base = water.onBeforeRender;
+ const captureMaterial = water.material;
+ const actualWorld = new THREE.Matrix4();
+ const normalMatrix = new THREE.Matrix3();
+ const worldNormal = new THREE.Vector3();
+ const worldPoint = new THREE.Vector3();
+ const rotation = new THREE.Quaternion();
+ const axis = new THREE.Vector3(0, 0, 1);
let first = true;
- water.onBeforeRender = function (renderer, scene, camera) {
+ let capturing = false;
+ water.onBeforeRender = function (renderer, scene, camera, geometry, material) {
+ if (disposed || scene.overrideMaterial || capturing || this.material !== captureMaterial
+ || (material && material !== captureMaterial)) return;
+ _readScene(scene, uniforms, pinned);
if (first) {
first = false;
- _readScene(scene, uniforms, pinned);
// 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
@@ -404,8 +412,69 @@ export function makeOcean(width, depth, opts = {}) {
mirror.type = THREE.HalfFloatType;
}
}
- base.call(this, renderer, scene, camera);
+ // Water's plane calculation assumes a rigid matrix. Supply the true
+ // inverse-transpose normal while keeping its world-space textureMatrix:
+ // unlike Reflector, Water does not project mesh-local positions.
+ actualWorld.copy(this.matrixWorld);
+ normalMatrix.getNormalMatrix(actualWorld);
+ worldNormal.copy(axis).applyMatrix3(normalMatrix).normalize();
+ if (worldNormal.lengthSq() < 0.5) return;
+ worldPoint.setFromMatrixPosition(actualWorld);
+ rotation.setFromUnitVectors(axis, worldNormal);
+ const autoUpdate = this.matrixWorldAutoUpdate;
+ const needsUpdate = this.matrixWorldNeedsUpdate;
+ const visible = this.visible;
+ // Nested scene updates must not propagate the temporary rigid frame
+ // into caller-owned descendants (including cameras and bones).
+ const descendants = [];
+ for (const child of this.children) child.traverse((node) => {
+ descendants.push([node, node.matrixWorldAutoUpdate, node.matrixWorldNeedsUpdate]);
+ node.matrixWorldAutoUpdate = false;
+ });
+ capturing = true;
+ this.matrixWorldAutoUpdate = false;
+ this.matrixWorld.makeRotationFromQuaternion(rotation).setPosition(worldPoint);
+ try {
+ withRendererState(renderer, () => {
+ if (ownedTarget) {
+ base.call(this, renderer, scene, camera);
+ } else {
+ // 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 {
+ base.call(this, renderer, scene, camera);
+ } finally {
+ renderer.setRenderTarget = setTarget;
+ }
+ }
+ });
+ } finally {
+ this.matrixWorld.copy(actualWorld);
+ this.matrixWorldAutoUpdate = autoUpdate;
+ this.matrixWorldNeedsUpdate = needsUpdate;
+ for (const [node, childAutoUpdate, childNeedsUpdate] of descendants) {
+ node.matrixWorldAutoUpdate = childAutoUpdate;
+ node.matrixWorldNeedsUpdate = childNeedsUpdate;
+ }
+ this.visible = visible;
+ capturing = false;
+ }
};
}
- return water;
+ 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/waterfall.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/waterfall.js
new file mode 100644
index 00000000..fb6dc57f
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/waterfall.js
@@ -0,0 +1,208 @@
+/**
+ * A gravity-driven sheet spilling over a lip, with advected surface detail,
+ * thinning optical depth, aeration, impact foam and the existing ballistic spray.
+ * Origin is the impact water level; the lip is [0,height,0], flow heads toward +Z.
+ * This is an authored weir/free-fall model, not a fluid or collision solver.
+ * The caller supplies the cliff, upstream water and receiving pool.
+ */
+import * as THREE from 'three';
+import { patchStandard, keepOutOfDepthPasses } from './shader.js';
+import { attachDisposal, snapshotResources } from './lifecycle.js';
+import { mulberry32 } from './noise.js';
+import { makeSpray } from './watermist.js';
+
+const GRAVITY = 9.81;
+const TIERS = { low: [32,48], balanced: [56,96], high: [80,160] };
+const clamp = (x,a=0,b=1) => Math.max(a,Math.min(b,x));
+
+const HEAD = /* glsl */`
+uniform float uFallHeight;
+uniform float uFallWidth;
+uniform float uFallFlight;
+uniform float uFallSpeed;
+uniform float uFallThickness;
+uniform float uFallBreakup;
+uniform float uFallFoam;
+uniform float uFallSeed;
+uniform vec4 uFallWaves[4];
+varying vec2 vFallUv;
+varying vec3 vFallView;
+varying float vFallThickness;
+float fallWidth(float u, float t) {
+ return 1.0-.10*u+.025*uFallBreakup*u*sin((t-u*uFallFlight)*3.1+uFallSeed);
+}
+vec3 fallPosition(vec2 uv,float t) {
+ float u=uv.y, travel=u*uFallFlight, emitted=t-travel;
+ float lateral=(uv.x-.5)*uFallWidth;
+ vec3 p=vec3(lateral*fallWidth(u,t),uFallHeight-4.905*travel*travel,uFallSpeed*travel);
+ vec3 n=normalize(vec3(0.0,uFallSpeed,9.81*travel));
+ float ripple=0.0;
+ for(int i=0;i<4;i++) {
+ vec4 wave=uFallWaves[i];
+ ripple+=wave.z*sin(lateral*wave.x-emitted*wave.y+wave.w);
+ }
+ return p+n*ripple*(16.0*u*u*(1.0-u)*(1.0-u));
+}
+`;
+
+/**
+ * makeWaterfall({width:2,height:3,speed:1,thickness:.045,breakup:.6,
+ * foam:.65,spray:true,seed:17,quality:'balanced'}) -> Group.
+ * Metres and seconds. speed is horizontal lip velocity; gravity accelerates
+ * the sheet downward. thickness is lip depth; downstream thickness follows
+ * width * velocity * thickness conservation. Set spray:false or foam:0 for
+ * a clear quiet sheet. No reflection capture is added. Physical transmission
+ * reads opaque scene colour only, with an approximate thin-film optical path.
+ * sample(u,lateral,t) uses u=0 at the lip, u=1 at impact, lateral=-.5..+.5.
+ * Update once with absolute seconds; dispose releases construction-owned data.
+ */
+export function makeWaterfall(opts = {}) {
+ const width=opts.width??2, height=opts.height??3, speed=opts.speed??1;
+ const thickness=opts.thickness??.045, breakup=opts.breakup??.6, foam=opts.foam??.65;
+ const seed=opts.seed??17, quality=opts.quality??'balanced';
+ const attenuationDistance=opts.attenuationDistance??8;
+ const sprayRate=opts.sprayRate??Math.min(500,100*width);
+ if (![width,height,speed,thickness,breakup,foam].every(Number.isFinite) ||
+ width<.02 || width>500 || height<.02 || height>500 || speed<.02 || speed>50 ||
+ thickness<=0 || thickness>Math.min(width,height)*.5 || breakup<0 || breakup>1 || foam<0 || foam>1 ||
+ !Number.isSafeInteger(seed) || !Object.hasOwn(TIERS,quality) ||
+ !(attenuationDistance>0) || (!Number.isFinite(attenuationDistance) && attenuationDistance!==Infinity) ||
+ !Number.isFinite(sprayRate) || sprayRate<0 || sprayRate>100000) {
+ throw new RangeError('makeWaterfall: invalid dimensions, flow, foam, seed or quality');
+ }
+ const flight=Math.sqrt(2*height/GRAVITY), impactZ=speed*flight;
+ const random=mulberry32(seed), waves=[];
+ for(let i=0;i<4;i++) waves.push(new THREE.Vector4(
+ (17+i*11.1)/Math.max(width,.05),20.8+i*19.65,
+ Math.min(width,height)*.004*breakup/(1+i*.8),random()*Math.PI*2));
+ const phase=random()*6.28;
+ const widthAt=(u,t) => width*(1-.10*u+.025*breakup*u*Math.sin((t-u*flight)*3.1+phase));
+ const positionAt=(u,lateral,t) => {
+ const travel=u*flight,emitted=t-travel;
+ const n=new THREE.Vector3(0,speed,GRAVITY*travel).normalize();
+ let ripple=0;
+ for(const w of waves) ripple+=w.z*Math.sin(lateral*width*w.x-emitted*w.y+w.w);
+ return new THREE.Vector3(lateral*widthAt(u,t),height-.5*GRAVITY*travel*travel,speed*travel)
+ .addScaledVector(n,ripple*16*u*u*(1-u)*(1-u));
+ };
+ const material=new THREE.MeshPhysicalMaterial({color:0xffffff,roughness:.12,metalness:0,
+ transmission:1,ior:1.333,thickness,attenuationDistance,
+ attenuationColor:new THREE.Color(opts.waterColor??0xc9e5df),side:THREE.DoubleSide});
+ const uniforms={
+ uFallHeight:{value:height},uFallWidth:{value:width},uFallFlight:{value:flight},
+ uFallSpeed:{value:speed},uFallThickness:{value:thickness},uFallBreakup:{value:breakup},
+ uFallFoam:{value:foam},uFallSeed:{value:phase},uFallWaves:{value:waves},
+ };
+ patchStandard(material,{name:'WaterfallFilm',uniforms,vertexHead:HEAD,fragmentHead:HEAD,
+ vertexBody:/* glsl */`
+ vFallUv=uv;
+ transformed=fallPosition(uv,uTime);
+ vFallView=(modelViewMatrix*vec4(transformed,1.0)).xyz;
+ float velocity=length(vec2(uFallSpeed,9.81*uv.y*uFallFlight));
+ vFallThickness=uFallThickness*uFallSpeed/(velocity*fallWidth(uv.y,uTime));
+ `,
+ fragmentBody:/* glsl */`
+ float fallEmitted=uTime-vFallUv.y*uFallFlight;
+ vec2 fallCoordinate=vec2((vFallUv.x-.5)*uFallWidth,fallEmitted);
+ vec2 fallCoarse=fallCoordinate*vec2(31.0,29.4)+uFallSeed;
+ vec2 fallFine=fallCoordinate*vec2(137.0,97.0)+uFallSeed;
+ float fallRibbon=astraNoise2(fallCoarse);
+ float fallFineResolved=1.0-smoothstep(.30,1.0,max(length(dFdx(fallFine)),length(dFdy(fallFine))));
+ float fallGrain=mix(.5,astraNoise2(fallFine),fallFineResolved);
+ float fallStrand=astraNoise2(fallCoordinate*vec2(19.0,4.1)+uFallSeed);
+ float fallEdge=pow(abs(vFallUv.x-.5)*2.0,10.0);
+ float fallAir=uFallFoam*smoothstep(.55,1.0,vFallUv.y)
+ *smoothstep(.36,.72,fallStrand*.35+fallRibbon*.65)*.16
+ +uFallFoam*fallEdge*.035;
+ float fallRelief=(fallRibbon*.0007+fallGrain*.00014)*(1.0-fallAir*.6);
+ diffuseColor.rgb=mix(vec3(1.0),vec3(.91,.96,.97),fallAir);
+ `,
+ alphaBody:/* glsl */`
+ // Aerated edge strands separate late in the fall. The core remains a
+ // continuous film; discarded gaps reveal the actual background.
+ float fallGap=smoothstep(.60,.98,vFallUv.y)*uFallBreakup;
+ if(fallEdge*fallGap*(1.0-fallRibbon)>.33) discard;
+ `,
+ normalBody:/* glsl */`
+ vec3 fallDx=dFdx(vFallView),fallDy=dFdy(vFallView);
+ vec3 fallN=normalize(cross(fallDx,fallDy));
+ vec3 fallR1=cross(fallDy,fallN),fallR2=cross(fallN,fallDx);
+ float fallDet=dot(fallDx,fallR1);
+ vec3 fallGradient=dFdx(fallRelief)*fallR1+dFdy(fallRelief)*fallR2;
+ normal=normalize(abs(fallDet)*fallN-sign(fallDet)*fallGradient);
+ `,
+ roughnessBody:'roughnessFactor=mix(roughnessFactor,.56,fallAir);',
+ transmissionBody:'material.transmission*=1.0-fallAir*.97; material.thickness=vFallThickness;',
+ });
+ const [nx,ny]=TIERS[quality], positions=[],uvs=[],normals=[],indices=[];
+ for(let iy=0;iy<=ny;iy++) for(let ix=0;ix<=nx;ix++) {
+ const u=iy/ny,lateral=ix/nx-.5,p=positionAt(u,lateral,0);
+ positions.push(...p.toArray());uvs.push(ix/nx,u);
+ const n=new THREE.Vector3(0,speed,GRAVITY*u*flight).normalize();normals.push(...n.toArray());
+ if(ix<nx && iy<ny) {
+ const a=iy*(nx+1)+ix,b=a+1,c=a+nx+1,d=c+1;
+ indices.push(a,c,b,b,c,d);
+ }
+ }
+ const geometry=new THREE.BufferGeometry();
+ geometry.setAttribute('position',new THREE.Float32BufferAttribute(positions,3));
+ geometry.setAttribute('normal',new THREE.Float32BufferAttribute(normals,3));
+ geometry.setAttribute('uv',new THREE.Float32BufferAttribute(uvs,2));geometry.setIndex(indices);
+ const margin=waves.reduce((s,w)=>s+w.z,0)+width*.03;
+ geometry.boundingBox=new THREE.Box3(new THREE.Vector3(-width*.54,-margin,-margin),
+ new THREE.Vector3(width*.54,height+margin,impactZ+margin));
+ geometry.boundingSphere=geometry.boundingBox.getBoundingSphere(new THREE.Sphere());
+ const group=new THREE.Group();group.name=opts.name??'Waterfall';
+ const sheet=new THREE.Mesh(geometry,material);sheet.name='FallingWaterFilm';
+ keepOutOfDepthPasses(sheet);group.add(sheet);
+ let foamMaterial=null;
+ if(foam>0) {
+ foamMaterial=new THREE.MeshStandardMaterial({color:0xdce7e7,roughness:.73,transparent:true,
+ opacity:foam,depthWrite:false,side:THREE.DoubleSide});
+ patchStandard(foamMaterial,{name:'WaterfallImpact',uniforms:{uImpactFoam:{value:foam},uImpactSeed:{value:phase}},
+ vertexHead:'varying vec2 vImpactUv;',vertexBody:'vImpactUv=uv;',
+ fragmentHead:'varying vec2 vImpactUv;\nuniform float uImpactFoam;\nuniform float uImpactSeed;',
+ fragmentBody:/* glsl */`
+ vec2 p=vec2(vImpactUv.x-.5,.5-vImpactUv.y)*2.0;
+ float downstream=p.y+.32;
+ float boundary=1.0-smoothstep(.63,1.0,length(vec2(p.x,downstream*.9)));
+ float cells=astraFbm2(vec2(p.x*17.0,p.y*13.0-uTime*1.8)+uImpactSeed,3);
+ float turbulence=smoothstep(.25,.58,cells);
+ float core=exp(-p.x*p.x*2.8-downstream*downstream*30.0);
+ diffuseColor.a*=boundary*clamp(core*.67+turbulence*.37,0.0,.78);
+ if(diffuseColor.a<.015) discard;
+ `});
+ const foamMesh=new THREE.Mesh(new THREE.PlaneGeometry(width*1.6,Math.max(width*.9,height*.45)),foamMaterial);
+ foamMesh.name='WaterfallImpactFoam';foamMesh.rotation.x=-Math.PI/2;
+ foamMesh.position.set(0,.012,impactZ+Math.max(width*.9,height*.45)*.16);
+ keepOutOfDepthPasses(foamMesh);group.add(foamMesh);
+ }
+ const owned=snapshotResources(group);
+ let spray=null;
+ if(opts.spray!==false && sprayRate>0) {
+ spray=makeSpray({origin:[0,.015,impactZ],radius:width*.28,
+ rate:sprayRate,speed:Math.min(3.4,Math.sqrt(GRAVITY*height)*.36),
+ size:Math.max(.004,Math.min(.025,width*.009)),seed:seed+107});
+ group.add(spray);owned.add({dispose:()=>spray.userData.dispose()});
+ }
+ group.userData.update=t=>{
+ if(!Number.isFinite(t)) throw new RangeError('Waterfall.update: time must be finite');
+ material.userData.uniforms.uTime.value=t;
+ if(foamMaterial) foamMaterial.userData.uniforms.uTime.value=t;
+ if(spray) (spray.userData.update??spray.userData.tick)(t);
+ };
+ group.userData.sample=(u,lateral=0,t=material.userData.uniforms.uTime.value)=>{
+ if(![u,lateral,t].every(Number.isFinite)) throw new RangeError('Waterfall.sample: inputs must be finite');
+ u=clamp(u);lateral=clamp(lateral,-.5,.5);
+ const position=positionAt(u,lateral,t),epsilon=1e-4;
+ const along=positionAt(clamp(u+epsilon),lateral,t).sub(positionAt(clamp(u-epsilon),lateral,t));
+ const across=positionAt(u,clamp(lateral+epsilon,-.5,.5),t).sub(positionAt(u,clamp(lateral-epsilon,-.5,.5),t));
+ const velocity=new THREE.Vector3(0,-GRAVITY*u*flight,speed),actualWidth=widthAt(u,t);
+ return {position,normal:along.cross(across).normalize(),velocity,width:actualWidth,
+ thickness:thickness*speed*width/(velocity.length()*actualWidth),travelTime:u*flight};
+ };
+ group.userData.impact=new THREE.Vector3(0,0,impactZ);
+ group.userData.flightTime=flight;
+ group.userData.quality=quality;
+ return attachDisposal(group,owned);
+}
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/watermist.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/watermist.js
index 53d74c00..96bea2df 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/watermist.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/watermist.js
@@ -35,15 +35,19 @@
* toward the water, so a view from above integrates the profile
* instead of a single slice of it.
*
- * Both billboard against the WORLD camera axes, so add them at the
- * scene root or under a translated parent — a rotated or scaled parent
- * tilts the cards.
+ * 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, tickShaders, keepOutOfDepthPasses } from './shader.js';
+import { instancedQuad, makeShaderMaterial, 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.
@@ -130,7 +134,7 @@ function toFlow(v) {
* `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.tick(t)` driving the drift. Move the
+ * `heightAt`), with `userData.update(t)` (also `tick(t)`) driving the drift. Move the
* group to move the bank.
*/
export function makeWaterMist(opts = {}) {
@@ -214,8 +218,8 @@ export function makeWaterMist(opts = {}) {
const g = new THREE.Group();
g.name = 'WaterMist';
g.add(mesh);
- g.userData.tick = (t) => tickShaders(g, t);
- return keepOutOfDepthPasses(g);
+ 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. */
@@ -261,9 +265,10 @@ function mistMaterial(cfg) {
uDither: { value: 0.010 / Math.sqrt(Math.max(1, cfg.hits)) },
},
varyings: 'varying vec2 vUv; varying vec3 vP;'
- + ' varying float vBase;',
+ + ' varying float vBase; varying vec3 vWaterWorld;',
vertexHead: 'attribute vec3 aCorner; attribute vec4 aPuff;'
- + ' attribute vec2 aCard; uniform vec2 uSize;',
+ + ' attribute vec2 aCard; uniform vec2 uSize;'
+ + glslLocalDir('waterLocalDir'),
vertexMain: [
' vUv = uv;',
' vBase = aPuff.z;',
@@ -274,10 +279,15 @@ function mistMaterial(cfg) {
' 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;'
@@ -372,7 +382,7 @@ function mistMaterial(cfg) {
// 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(vP - cameraPosition);',
+ ' 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),',
@@ -425,7 +435,7 @@ function mistMaterial(cfg) {
* 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.tick(t)` driving it and `userData.sample(i, t)` returning
+ * `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.
*/
@@ -488,7 +498,7 @@ export function makeSpray(opts = {}) {
g.name = 'Spray';
g.position.copy(origin);
g.add(mesh);
- g.userData.tick = (t) => tickShaders(g, t);
+ 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];
@@ -499,7 +509,7 @@ export function makeSpray(opts = {}) {
org[k * 3 + 1] + vy * age - 0.5 * _G * age * age,
org[k * 3 + 2] + vel[k * 3 + 2] * age);
};
- return keepOutOfDepthPasses(g);
+ return attachDisposal(keepOutOfDepthPasses(g), snapshotResources(g));
}
/** One arc per droplet, stretched along the way it is going. */
@@ -529,7 +539,8 @@ function sprayMaterial(color, size, sun, sunColor) {
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;',
+ + ' uniform float uStreak; uniform vec3 uSunDir;'
+ + glslLocalDir('waterLocalDir'),
vertexMain: [
' vUv = uv;',
// Its own flight time, so every droplet relaunches on its
@@ -540,13 +551,22 @@ function sprayMaterial(color, size, sun, sunColor) {
' 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 f = normalize(cameraPosition - c);',
- ' vec3 d = v - f * dot(v, f);',
- ' float dl = length(d);',
- ' vec3 dir = dl > 1e-4 ? d / dl',
- ' : vec3(viewMatrix[0][1], viewMatrix[1][1],',
- ' viewMatrix[2][1]);',
- ' vec3 sid = normalize(cross(f, dir));',
+ ' 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)',
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/waterside.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/waterside.js
index ed235fa6..29a971b4 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/waterside.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/waterside.js
@@ -17,7 +17,7 @@
import * as THREE from 'three';
import {
- composeRoughness, toColor, unit, withBase, worldBase,
+ toColor, unit, withBase, worldBase,
} from './shader.js';
// One base for all three, on the world varyings terrain_shade shares, so
@@ -41,16 +41,8 @@ const BASE = worldBase('waterside:base', 'wsP', 'wsN');
* sky-family colour a `<color_fragment>` patch can reach), which is
* what separates wet sand from sand in shadow.
*
- * `gloss` lands on the MATERIAL, not per pixel: this patch writes only
- * at `<color_fragment>`, BEFORE `<roughnessmap_fragment>` declares
- * `roughnessFactor`, and does not use `patchStandard`'s `roughnessBody`.
- * It therefore defaults to a LIGHT touch:
- * a shore ground is mostly dry, and the reference default of 0.45 took
- * `MAT.soil()` from roughness 0.95 to 0.43 over the whole beach —
- * measured on this renderer (ACES, exposure 1.0, baked environment) it
- * turned the dry sand into satin and pushed the frame to mean_lum 0.85.
- * The per-pixel sheen above is what the wet band actually reads from;
- * pass `gloss: 0.45` when the bank has a material of its own.
+ * `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.
@@ -70,11 +62,12 @@ export function patchShoreWet(material, opts = {}) {
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;
- composeRoughness(material, 'waterside:wet', Math.max(gloss, 0));
+
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) },
@@ -82,11 +75,16 @@ export function patchShoreWet(material, opts = {}) {
},
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
@@ -98,7 +96,7 @@ export function patchShoreWet(material, opts = {}) {
' vec3 wtWet = mix(vec3(wtL), wtDry, 1.0 + uWetSat)',
' * (1.0 - uWetDark);',
' diffuseColor.rgb = mix(wtDry, max(wtWet, vec3(0.0)), wtK);',
- // The sheen the material-wide gloss cannot place: it belongs on
+ // 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);',
@@ -121,10 +119,9 @@ export function patchShoreWet(material, opts = {}) {
* 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
- * noise is stretched sevenfold along it into streamers instead of the
- * bands-marching-at-the-viewer a ranked field would give. On a dead
- * flat surface there is no shore direction to find and it falls back to
- * the world X axis.
+ * 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
@@ -184,6 +181,11 @@ export function patchShoreFoam(material, opts = {}) {
'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;',
@@ -198,20 +200,25 @@ export function patchShoreFoam(material, opts = {}) {
' float fmL = length(fmNx);',
' vec2 fmA = fmL > 1e-3 ? fmNx / fmL : vec2(1.0, 0.0);',
' vec2 fmB = vec2(-fmA.y, fmA.x);',
- ' float fmU = dot(vAstraWorld.xz, fmB);',
- ' float fmV = dot(vAstraWorld.xz, fmA);',
- // Structure runs ACROSS the flow: waves run up the bank, so the
- // tear varies slowly along the shore and fast across it.
- ' float fmN = astraFbm2(vec2(fmU * 0.30 + fmT * 0.05,',
- ' fmV * 2.10 - fmT * 0.35), 3);',
- // The lace: a second, much finer field across the same frame,
- // drifting faster. Without it the streamers read as one poured
- // sheet with a torn outline instead of as bubbles.
- ' float fmD = astraFbm2(vec2(fmU * 1.70,',
- ' fmV * 6.40 - fmT * 0.60), 2);',
+ // 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);',
- ' fmK *= 0.55 + 0.45 * smoothstep(0.18, 0.72, fmD);',
+ ' 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.
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/wetground.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/wetground.js
index fc8fe739..f3e900a2 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/wetground.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/wetground.js
@@ -33,9 +33,10 @@
*/
import * as THREE from 'three';
+import { attachDisposal, snapshotResources } from './lifecycle.js';
import { Reflector } from 'three/addons/objects/Reflector.js';
import { fbm2, noiseDataTexture } from './noise.js';
-import { GLSL_UTIL, patchStandard } from './shader.js';
+import { GLSL_UTIL, patchStandard, withRendererState } from './shader.js';
/**
* The film's swell, shared verbatim by the mirror and the overlay.
@@ -106,7 +107,7 @@ const WET_REFLECTOR_SHADER = {
vUv = textureMatrix * vec4(position, 1.0);
vec4 worldPosition = modelMatrix * vec4(position, 1.0);
vWorldPos = worldPosition.xyz;
- vWorldNormal = normalize(mat3(modelMatrix) * normal);
+ vWorldNormal = inverseTransformDirection(normalize(normalMatrix * normal), viewMatrix);
vec4 mvPosition = viewMatrix * worldPosition;
gl_Position = projectionMatrix * mvPosition;
#include <logdepthbuf_vertex>
@@ -320,6 +321,67 @@ export function makeMirrorFloor(w, d, opts = {}) {
mirror.material.dithering = true;
group.add(mirror);
+ // The addon extracts a rotation from its world matrix, which does not
+ // transform a plane normal correctly under nonuniform scale or shear.
+ // Capture in a rigid frame, then map its local projection back to the
+ // actual affine geometry used by the ordinary draw.
+ const capture = mirror.onBeforeRender;
+ const captureMaterial = mirror.material;
+ const actualWorld = new THREE.Matrix4();
+ const rigidWorld = new THREE.Matrix4();
+ const inverseRigid = new THREE.Matrix4();
+ const normalMatrix = new THREE.Matrix3();
+ const worldNormal = new THREE.Vector3();
+ const worldPoint = new THREE.Vector3();
+ const cameraPoint = new THREE.Vector3();
+ const rotation = new THREE.Quaternion();
+ const axis = new THREE.Vector3(0, 0, 1);
+ let capturing = false;
+ mirror.onBeforeRender = function (renderer, scene, camera, geometry, material) {
+ if (scene.overrideMaterial || capturing || this.material !== captureMaterial
+ || (material && material !== captureMaterial)) return;
+ actualWorld.copy(this.matrixWorld);
+ normalMatrix.getNormalMatrix(actualWorld);
+ worldNormal.copy(axis).applyMatrix3(normalMatrix).normalize();
+ if (worldNormal.lengthSq() < 0.5) return;
+ worldPoint.setFromMatrixPosition(actualWorld);
+ cameraPoint.setFromMatrixPosition(camera.matrixWorld);
+ if (cameraPoint.sub(worldPoint).dot(worldNormal) < 0 && !this.forceUpdate) return;
+ rotation.setFromUnitVectors(axis, worldNormal);
+ rigidWorld.makeRotationFromQuaternion(rotation).setPosition(worldPoint);
+ const autoUpdate = this.matrixWorldAutoUpdate;
+ const needsUpdate = this.matrixWorldNeedsUpdate;
+ const visible = this.visible;
+ // Nested scene updates must not propagate the temporary rigid frame
+ // into caller-owned descendants (including cameras and bones).
+ const descendants = [];
+ for (const child of this.children) child.traverse((node) => {
+ descendants.push([node, node.matrixWorldAutoUpdate, node.matrixWorldNeedsUpdate]);
+ node.matrixWorldAutoUpdate = false;
+ });
+ capturing = true;
+ this.matrixWorldAutoUpdate = false;
+ this.matrixWorld.copy(rigidWorld);
+ try {
+ withRendererState(renderer, () => {
+ capture.call(this, renderer, scene, camera);
+ inverseRigid.copy(rigidWorld).invert();
+ captureMaterial.uniforms.textureMatrix.value
+ .multiply(inverseRigid).multiply(actualWorld);
+ });
+ } finally {
+ this.matrixWorld.copy(actualWorld);
+ this.matrixWorldAutoUpdate = autoUpdate;
+ this.matrixWorldNeedsUpdate = needsUpdate;
+ for (const [node, childAutoUpdate, childNeedsUpdate] of descendants) {
+ node.matrixWorldAutoUpdate = childAutoUpdate;
+ node.matrixWorldNeedsUpdate = childNeedsUpdate;
+ }
+ this.visible = visible;
+ capturing = false;
+ }
+ };
+
const overlayMat = new THREE.MeshStandardMaterial({
color: overlayColor,
roughness: 1,
@@ -381,5 +443,10 @@ export function makeMirrorFloor(w, d, opts = {}) {
overlay.name = 'GroundOverlay';
group.add(overlay);
- return group;
+ const owned = snapshotResources(group);
+ owned.add(mirror.getRenderTarget());
+ for (const texture of [overlayMat.map, overlayMat.alphaMap, overlayMat.roughnessMap]) {
+ if (texture) owned.add(texture);
+ }
+ return attachDisposal(group, owned);
}
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/windows.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/windows.js
index 01eb1cc4..ec1cfa0f 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/windows.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/windows.js
@@ -12,7 +12,8 @@
*/
import * as THREE from 'three';
-import { patchStandard, toColor } from './shader.js';
+import { clonePatchedMaterial, patchStandard, toColor } from './shader.js';
+import { attachDisposal } from './lifecycle.js';
const WIN_VARYINGS = [
'varying vec2 vWinUv;',
@@ -29,12 +30,12 @@ const WIN_VERTEX = [
' vec4 winO = vec4(0.0, 0.0, 0.0, 1.0);',
'#ifdef USE_INSTANCING',
' winP = instanceMatrix * winP;',
- ' winNo = mat3(instanceMatrix) * winNo;',
+ ' winNo = astraNormalTransform(mat3(instanceMatrix), winNo);',
' winO = instanceMatrix * winO;',
'#endif',
' vWinUv = uv;',
' vWinW = (modelMatrix * winP).xyz;',
- ' vWinN = normalize((modelMatrix * vec4(winNo, 0.0)).xyz);',
+ ' vWinN = astraNormalTransform(mat3(modelMatrix), winNo);',
// The draw's own origin, constant across the mesh: it keys the lit
// pattern per BUILDING even where a whole city shares one material.
' vWinKey = (modelMatrix * winO).xyz;',
@@ -371,20 +372,24 @@ function facadeMeshes(root) {
export function makeNightWindows(mesh, opts = {}) {
if (!mesh || !mesh.traverse) return mesh;
const done = new Map();
+ const owned = new Set();
for (const target of facadeMeshes(mesh)) {
const slots = [].concat(target.material);
const next = slots.map((m) => {
if (!m) return m;
if (done.has(m.uuid)) return done.get(m.uuid);
- const out = (m.userData && m.userData.shared) ? m.clone() : m;
- // clone() JSON-copies userData, which would carry a dead patch
- // chain into the cache key of a material that no longer runs it.
- if (out !== m) out.userData = {};
+ const out = (m.userData && m.userData.shared) ? clonePatchedMaterial(m) : m;
+ if (out !== m) owned.add(out);
patchWindowInteriors(out, opts);
done.set(m.uuid, out);
return out;
});
target.material = Array.isArray(target.material) ? next : next[0];
}
+ if (owned.size) {
+ const previous = mesh.userData.dispose;
+ if (previous) owned.add({ dispose: previous });
+ attachDisposal(mesh, owned);
+ }
return mesh;
}
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/woodland.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/woodland.js
index ea7720da..0d45fe67 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/woodland.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/woodland.js
@@ -20,6 +20,7 @@
*/
import * as THREE from 'three';
+import { attachDisposal, snapshotResources } from './lifecycle.js';
import { mulberry32 } from './noise.js';
import { windOf } from './grass.js';
@@ -412,7 +413,9 @@ function rigLight(rig) {
/**
* Stand-ins on cards: a forest, a crowd or a town for one draw call.
*
- * DO NOT USE THESE INSIDE ~35 m. Measured against the same stand built
+ * 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
@@ -472,7 +475,8 @@ export function makeImposters(opts = {}) {
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);
+ 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,
@@ -515,8 +519,8 @@ export function makeImposters(opts = {}) {
const g = new THREE.Group();
g.name = opts.name || 'Imposters';
g.add(keepOutOfDepthPasses(mesh));
- g.userData.tick = (t) => tickShaders(g, t);
- return g;
+ g.userData.update = g.userData.tick = (t) => tickShaders(g, t);
+ return attachDisposal(g, snapshotResources(g));
}
/**
@@ -635,6 +639,7 @@ function imposterMaterial(cfg) {
' 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.
@@ -668,12 +673,24 @@ function imposterMaterial(cfg) {
' 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.
- ' vec2 tD = vec2(iq.x / 0.88, (iq.y - 0.66) / 0.36);',
+ ' 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.34 * (astraFbm2(vec2(atan(tD.y, tD.x) * 1.7, iPh), 3)',
+ ' tR += 0.48 * (astraFbm2(vec2(atan(tD.y, tD.x) * 1.7, iPh), 3)',
' - 0.44);',
' float tCrown = 0.92 - tR;',
- ' iS = max(tCrown, min(0.038 - abs(iq.x), 0.70 - iq.y));',
+ // 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, smoothstep(0.28, 0.02, 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) {',
@@ -717,7 +734,7 @@ function imposterMaterial(cfg) {
' 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.02 || vImpVar.z < 0.5) discard;',
+ ' 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
@@ -728,7 +745,11 @@ function imposterMaterial(cfg) {
' 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.45;',
+ ' 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.
@@ -749,13 +770,13 @@ function imposterMaterial(cfg) {
// 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.26, iS);',
+ ' float iEdge = 1.0 - smoothstep(0.0, 0.12, iS);',
' float iBack = smoothstep(0.15, -0.70, 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.34 * iLeaf * iEdge * iBack',
- ' * (0.45 + 1.35 * iMass * iFine));',
+ ' * (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
@@ -765,9 +786,9 @@ function imposterMaterial(cfg) {
// 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.0, 0.38, iS);',
+ ' float iDeep = smoothstep(-0.02, 0.20, iS);',
' float iAO = max(0.26,',
- ' 1.0 - iLeaf * 0.86 * iDeep * (1.0 - 0.78 * iMass));',
+ ' 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
@@ -775,20 +796,12 @@ function imposterMaterial(cfg) {
' 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, iA);',
+ ' gl_FragColor = vec4(iAlb * iIrr / PI, 1.0);',
].join('\n'),
- // OPAQUE with alpha-to-coverage, not blended. One draw call means
- // the cards are NOT sorted against each other, so a blended card
- // resolves its soft edge against whatever was already in the buffer
- // — the sky — and then writes depth, leaving a pale halo traced
- // around every silhouette that has another card behind it (measured
- // 2.5 per mille of the treeline band). Coverage is decided per
- // MSAA sample instead, which this renderer has (antialias: true),
- // so the edge stays soft, the card behind fills the samples this
- // one did not take, and the field joins the opaque queue where it
- // is depth-sorted front to back for free.
+ // Opaque clipping avoids partial-alpha halos between unsorted cards.
+ // The host post chain handles the silhouette's screen-space antialiasing.
transparent: false,
- alphaToCoverage: true,
+ alphaToCoverage: false,
depthWrite: true,
side: THREE.DoubleSide,
});
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/scene.js b/harness/codeverse3d/languages/scene_threejs/starter/src/scene.js
index 78c139ce..a1035590 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/scene.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/scene.js
@@ -9,7 +9,7 @@
// • loaders.gltf is a GLTFLoader: loaders.gltf.loadAsync('/assets/<name>.glb') for Blender-built assets.
// • Imports allowed: 'three', 'three/addons/*', relative files. No CDN, no network, no DOM access.
// • Raw three.js + GLSL only: never import a helper SDK or any npm package.
-// ./lib/ is the ONE exception and is not an SDK: 44 harness-owned effect modules
+// ./lib/ is the ONE exception and is not an SDK: harness-owned effect modules
// shipped INTO this workspace, already compiled and rendered on this renderer.
// Import and call them (`import { makeGrass } from './lib/grass.js'`); do not
// rewrite them — writes to src/lib/ are reverted. Table: prompts effects_catalog.
diff --git a/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md b/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md
index 87acd411..6ed0e446 100644
--- a/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md
+++ b/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md
@@ -1,6 +1,6 @@
# The shipped effect library — call these before writing your own
-`src/lib/` is in your workspace already: 44 modules, every one of them compiled
+`src/lib/` is in your workspace already: the shipped modules are compiled
and rendered on THIS renderer. They carry the depth and fog chunks a
hand-written shader silently loses, and they are not an outside package — they
are harness code shipped into the workspace, so importing them is allowed where
@@ -16,7 +16,18 @@ says `import { makeGrass } from '../lib/grass.js';`, `src/scene.js` says
| 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. |
+| a campfire, large fuel bed or flames through a building | `makeFireField({ emitters: [{ position: [0,0,0], radius: 0.3, height: 1, strength: 1 }], wind: [0.15,0], smoke: {height: 3, density: 0.65}, occluders: [fuel, walls], quality: 'balanced', seed })` — `lib/firefield.js`; all sources share one flame/soot integration. Wind is local metres/second. Optional borrowed opaque occluders truncate rays, including instancing/alpha cuts; custom deformation needs customDepthMaterial. No glass interleaving, skinned occluders or log-depth capture. Layout/wind are baked: rebuild to change them. Group provides update/dispose, bounds, sampleField(x,y,z,t), sampleEmber(index,t) and cost. Start with one field: each field adds a ray march over 3D textures, plus a depth pass when occluders are given. |
+| 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. |
+| moving OCEAN waves with real displaced geometry | `makeOceanSurface({ width, depth, waveHeight, wavelength, windDirection: [1, 0.2], seed })` — `lib/ocean.js`; dispersive Gerstner waves, reflected scene, crest foam; Group with `userData.update(t, dt)` and `userData.sampleHeight(x, z, t)`. One reflective water body per scene. |
+| a curved shallow STREAM | `makeStream({ points: [[0, 0.6, -8], [2, 0.3, 0], [0, 0, 8]], width: 2, depth: 0.3, speed: 1, seed })` — `lib/stream.js`; points run upstream → downstream, decreasing Y. Refracts the opaque bed/scene through depth-varying water; flowing ripples, stone wakes and approximate caustics. `waterColor: 0x80b6a6, attenuationDistance: 3` controls volume absorption over a distance in metres. Optional `reflectionSize: 512` captures the banks; default 0, and at most ONE planar reflector per scene. Group with `userData.update(t, dt)`, `userData.sample(u, lateral, t)`. Keep terrain BELOW the bed inside the channel. |
+| a falling sheet of water over a weir | `makeWaterfall({ width: 2, height: 3, speed: 1, thickness: 0.045, foam: 0.65, seed })` — `lib/waterfall.js`; gravity accelerates and thins the sheet, with advected ripples, local aeration and impact spray. Origin is impact water level, lip is `[0,height,0]`, flow is +Z. Supply the upstream water, cliff and pool. `userData.sample(u,lateral,t)` uses u=0..1 and lateral=-0.5..0.5; `userData.impact` gives the receiving point. No collision/fluid solver; opaque-scene refraction only. |
+| thick broken ice with actual open fissures | `makeFracturedIce({ size: [8,6], thickness: 0.28, crackDensity: 0.65, frost: 0.35, seed })` — `lib/ice.js`; closed floes, bevels, internal air and local optical thickness. Nominal top is y=0. `userData.sampleHeight(x,z)` returns local top height or null in a gap. Supply an opaque lakebed/water backing: transparent volumes are not recursively refracted. |
+| 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: { direction: [1, 0.3], strength: 0.6, speed: 1 } })` — `lib/meadow.js`; 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 — every broadleaf tree, hedge and 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`. NEVER a displaced sphere: see the rule at the end. |
| trees, bushes, leaves | `patchLeafSSS` · `patchWind` · `patchRootContact` — `lib/foliage_shade.js` |
| bark, and a forest at distance | `patchBark` · `makeImposters` — `lib/woodland.js` |
@@ -41,6 +52,7 @@ says `import { makeGrass } from '../lib/grass.js';`, `src/scene.js` says
| an interior's walls, ceiling and window/door openings | `roomShell({ center, extents, openings, thickness, wallColor, ceilingColor })` — `lib/environment.js`; walls outward of the bounds' faces (inner face = bounds face), openings cut as span / sill / lintel panels. The skeleton's env.js builds it from its INTERIOR constant for an interior plan; six runs measured "not enclosed, a diorama on a flat plane" without one |
| the sky itself | `makeSky(scene, { rig })` — `lib/sky.js`; the dome IS the backdrop, so `scene.background` stays null |
| cloud, cirrus | `makeClouds({ preset, sunDir })` · `makeCirrus()` — `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 |
@@ -53,6 +65,7 @@ says `import { makeGrass } from '../lib/grass.js';`, `src/scene.js` says
| 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 |
| readable lettering on a sign | `makeText` (async — await ONCE at module top level, `.clone()` per copy) — `lib/signage.js` |
| 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 or null outside; 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` |
@@ -62,19 +75,36 @@ says `import { makeGrass } from '../lib/grass.js';`, `src/scene.js` says
| 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` |
+| a scoped synchronous offscreen capture | `withRendererState(renderer, callback)` — `lib/shader.js`; restores target/cube/mip, viewport/scissor, XR, shadow auto-update, tone mapping and clear state even after an error. Object transforms/visibility and other modified flags remain the caller's responsibility. No recursive-reflector coordinator is implied. |
+| explicit cleanup for a procedural group you build | `snapshotResources(group)` · `attachDisposal(group, resources)` — `lib/lifecycle.js`; capture construction-owned geometry/materials before attaching borrowed children. Textures are borrowed unless explicitly added to the resource set. Disposal is idempotent and does not traverse later-added props. |
## The four rules that apply to all of them
+**New natural-element factories use one lifecycle.** Fire, fire field, candle, ocean, stream,
+sand, meadow, smoke, steam, waterfall, tree, shrub, cloud volume, ice and paving provide
+`object.userData.update(t, dt)` (absolute seconds)
+and `object.userData.dispose()`. Store the returned objects and update each ONCE
+from the zone's `userData.update`. Their dimensions, paths and height queries are
+LOCAL coordinates; move/rotate the whole returned object to place it. Call the
+factory before positioning props that sample its surface. These are realtime
+procedural effects, not fluid/combustion solvers. Read the module's JSDoc for
+options and bounds. For older effects, follow the hooks listed below.
+
**1. `patch*` entries CHAIN.** Apply as many as a surface deserves to one
material, in any order — they are composed into one program. Two patches may
not define the same GLSL helper name with different bodies; the library prefixes
its own (`astra…`), so prefix yours.
-**2. A `make*` entry that moves carries its own per-frame hook —
-`userData.tick(t, dt)` on most, `userData.update(t)` on `makeRain`,
-`makeSplashes`, `makePuddle`, `makeClouds`, `makeCirrus`, `makeOcean` and
-`makeRainRings` — and OUR contract drives it from `update(t, dt)`, not from a
-`tick` of your own.** Fan out in `scene.js`:
+Use `clonePatchedMaterial(material)` from `lib/shader.js` to copy a material
+that already carries patches. Three's ordinary `.clone()` drops the shader hook
+and JSON-copies typed uniforms. The library helper replays its registered chain,
+copies vector/colour/matrix uniforms and borrows texture references. Custom
+external `onBeforeCompile` wrappers must still be reapplied by their owner.
+
+**2. Moving factories carry a per-frame hook.** Prefer `userData.update(t, dt)`;
+some older factories use `userData.tick(t, dt)`. Read the factory JSDoc or select
+`effect.userData.update ?? effect.userData.tick`, then call that hook exactly once.
+The host drives the scene's `update(t, dt)`. Fan out in `scene.js`:
```js
function update(t, dt) {
@@ -91,8 +121,7 @@ g.add(rain);
g.userData.update = (t, dt) => { rain.userData.update(t, dt); };
```
-Calling `.tick` on one of those seven throws, and the host then turns
-`update()` off for the whole scene — every animation in it freezes.
+Calling a missing hook throws and can stop the whole scene's animation.
Anything built with `patchStandard` is driven instead by one
`tickShaders(scene, t)` — call it once, in `scene.js`'s `update`. An effect
whose hook is never called stands still.
diff --git a/harness/codeverse3d/prompts/tracks/plan_scene.j2 b/harness/codeverse3d/prompts/tracks/plan_scene.j2
index b0a839c9..96f7c5e0 100644
--- a/harness/codeverse3d/prompts/tracks/plan_scene.j2
+++ b/harness/codeverse3d/prompts/tracks/plan_scene.j2
@@ -8,6 +8,20 @@ The scene uses the same frame: Y up, meters; the ground is around y=0 unless you
LANGUAGE CONTRACT THE BUILDERS WILL FOLLOW:
{{ contract }}
+SHIPPED NATURAL EFFECTS:
+The scene workspace already contains `src/lib/fire.js` (`makeFire`, `makeCandle`),
+`ocean.js` (`makeOceanSurface`), `stream.js` (`makeStream`), `sand.js`
+(`makeSandTerrain`), `rock.js` (`makeRock`, `makeRockField`) and `meadow.js`
+(`makeMeadow`). When they cover the brief, describe their calls and dimensions in
+the owning zone description / environment / effects. Do not request a separate
+StreamRibbon, Flame, CandleTrio or GrassPatch asset that rebuilds the same effect.
+The standalone asset stage only imports Three.js; shipped effects must be composed
+by zone/environment code, which may import `../lib/`. Zone `contents` still lists
+only actual asset names; library effects belong in prose, not invented asset ids.
+Plan the stream's upstream-to-downstream path once, with nonincreasing Y, and
+require terrain banks to use that same surface sampler and local coordinate frame.
+The zone drives each effect's `userData.update(t, dt)` exactly once per frame.
+
## What this track is graded on (write the plan that wins these points)
A scene scores 0.8+ only when every authored camera makes a PICTURE: three depth layers
(something within 5 m framing the shot, the subject at 8-30 m, a hazy horizon above), ground
diff --git a/harness/tests/scene_runtime/lib/_probe.py b/harness/tests/scene_runtime/lib/_probe.py
index 707ac97a..f3c7c0cc 100644
--- a/harness/tests/scene_runtime/lib/_probe.py
+++ b/harness/tests/scene_runtime/lib/_probe.py
@@ -63,7 +63,7 @@ def _three_ready() -> None:
def _stage(root: Path, libs: tuple[str, ...]) -> None:
(root / "lib").mkdir()
# the hub modules every effect imports ride along whatever the test names
- for name in sorted(set(libs) | {"shader.js", "noise.js", "materials.js"}):
+ for name in sorted(set(libs) | {"shader.js", "noise.js", "materials.js", "lifecycle.js"}):
shutil.copy(LIB_DIR / name, root / "lib" / name)
diff --git a/harness/tests/scene_runtime/lib/test_library.py b/harness/tests/scene_runtime/lib/test_library.py
index 723a2940..ea4fa6f9 100644
--- a/harness/tests/scene_runtime/lib/test_library.py
+++ b/harness/tests/scene_runtime/lib/test_library.py
@@ -150,6 +150,29 @@ BUILD: dict[str, str] = {
" return [b, inst((m) => L.windows.patchWindowInteriors(m, { seed: 5 }))]; })()",
"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 })]",
+ "firefield.js": "[L.firefield.makeFireField({ emitters: [{ position: [0, 0, 0], radius: 0.3, height: 1,"
+ " strength: 1 }, { position: [0.8, 0, 0.2], radius: 0.2, height: 0.6, strength: 0.7 }],"
+ " quality: 'low', seed: 5 })]",
+ "ice.js": "[L.ice.makeFracturedIce({ size: [4, 3], thickness: 0.2, seed: 3 })]",
+ "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' })]",
+ "stream.js": "[L.stream.makeStream({ points: [[0, 0.6, -8], [2, 0.3, 0], [0, 0, 8]], width: 2, depth: 0.3,"
+ " seed: 4, obstacles: [{ u: 0.5, lateral: 0.2, radius: 0.3 }] })]",
+ "tree.js": "[L.tree.makeTree({ species: 'birch', height: 4, maxLeaves: 600, seed: 3 }),"
+ " L.tree.makeShrub({ maxLeaves: 300, seed: 2 })]",
+ "waterfall.js": "[L.waterfall.makeWaterfall({ width: 2, height: 3, seed: 4 })]",
}
# What the GPU compiles here, in groups so xdist spreads the browser boots.
@@ -161,6 +184,9 @@ GROUPS: dict[str, tuple[str, ...]] = {
"sky_and_air": ("atmosphere.js", "celestial.js", "clouds.js", "environment.js", "godrays.js",
"sky.js", "veils.js", "flock.js"),
"water": ("rain.js", "water.js", "watermist.js", "wetground.js", "finish.js"),
+ "volumes": ("cloudvolume.js", "fire.js", "firefield.js", "smoke.js"),
+ "ground": ("lifecycle.js", "meadow.js", "paving.js", "rock.js", "sand.js", "tree.js"),
+ "flowing_water": ("ice.js", "ocean.js", "stream.js", "waterfall.js"),
"built": ("building.js", "figure.js", "instancing.js", "materials.js", "merge.js", "neon.js",
"noise.js", "place.js", "signage.js", "terrain.js", "urban.js", "windows.js"),
}
diff --git a/harness/tests/scene_runtime/lib/test_lifecycle.py b/harness/tests/scene_runtime/lib/test_lifecycle.py
new file mode 100644
index 00000000..222eea34
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_lifecycle.py
@@ -0,0 +1,57 @@
+"""Construction-time resource ownership, including independent instance buffers."""
+import pytest
+
+from tests.scene_runtime.lib._probe import measure
+
+pytestmark = pytest.mark.node
+
+
+def test_owned_buffers_shadows_and_explicit_textures_release_once():
+ out = measure("""
+import * as THREE from 'three';
+import {snapshotResources,attachDisposal} from './lib/lifecycle.js';
+const root=new THREE.Group(), geometry=new THREE.BoxGeometry();
+const borrowedMap=new THREE.Texture(), ownedMap=new THREE.DataTexture();
+const material=new THREE.MeshStandardMaterial({map:borrowedMap});
+const mesh=new THREE.InstancedMesh(geometry,material,2);
+mesh.customDepthMaterial=new THREE.MeshDepthMaterial();
+mesh.customDistanceMaterial=new THREE.MeshDistanceMaterial();
+root.add(mesh,new THREE.Mesh(geometry,material));
+const resources=snapshotResources(root);resources.add(ownedMap);
+attachDisposal(root,resources);
+const callerMesh=new THREE.InstancedMesh(new THREE.BoxGeometry(),material,1);
+root.add(callerMesh);
+const events={};
+for(const [name,res] of Object.entries({geometry,material,mesh,ownedMap,borrowedMap,
+ depth:mesh.customDepthMaterial,distance:mesh.customDistanceMaterial,
+ callerMesh,callerGeometry:callerMesh.geometry})) {
+ events[name]=0;res.addEventListener('dispose',()=>events[name]++);
+}
+resources.add(borrowedMap); // The attached ownership set is itself a snapshot.
+const first=root.userData.dispose(),second=root.userData.dispose();
+console.log(JSON.stringify({events,first,second}));
+""")
+ assert out == {"events": {"geometry": 1, "material": 1, "mesh": 1,
+ "ownedMap": 1, "borrowedMap": 0, "depth": 1,
+ "distance": 1, "callerMesh": 0, "callerGeometry": 0},
+ "first": True, "second": False}
+
+
+def test_borrowed_categories_and_failed_disposer_do_not_skip_cleanup():
+ out = measure("""
+import * as THREE from 'three';
+import {snapshotResources,attachDisposal} from './lib/lifecycle.js';
+const mesh=new THREE.Mesh(new THREE.BoxGeometry(),new THREE.MeshStandardMaterial());
+const resources=snapshotResources(mesh,{materials:false});
+let geometry=0,material=0,extra=0,failures=0;
+mesh.geometry.addEventListener('dispose',()=>geometry++);
+mesh.material.addEventListener('dispose',()=>material++);
+resources.add({dispose(){throw new Error('broken extension');}});
+resources.add({dispose(){extra++;}});
+attachDisposal(mesh,resources);
+try {mesh.userData.dispose();} catch(error) {failures=error.errors.length;}
+const repeated=mesh.userData.dispose();
+console.log(JSON.stringify({geometry,material,extra,failures,repeated}));
+""")
+ assert out == {"geometry": 1, "material": 0, "extra": 1,
+ "failures": 1, "repeated": False}
diff --git a/harness/tests/scene_runtime/lib/test_patch_union.py b/harness/tests/scene_runtime/lib/test_patch_union.py
index 5fff1aab..8d9e9ed2 100644
--- a/harness/tests/scene_runtime/lib/test_patch_union.py
+++ b/harness/tests/scene_runtime/lib/test_patch_union.py
@@ -172,11 +172,11 @@ console.log(JSON.stringify({ per, util: GLSL_UTIL, forward: union(ALL),
vs, fs = got["vs"], got["fs"]
body = _main_body(vs)
p = _find(r"vAstraWorld = \(modelMatrix \* (\w+)\)\.xyz;", body).group(1)
- n = _find(r"vAstraWorldN = normalize\(\(modelMatrix \* vec4\((\w+), 0\.0\)\)\.xyz\);",
+ n = _find(r"vAstraWorldN = astraNormalTransform\(mat3\(modelMatrix\), (\w+)\);",
body).group(1)
assert "#ifdef USE_INSTANCING" in body, lib
assert f"{p} = instanceMatrix * {p};" in body, (lib, p)
- assert f"{n} = mat3(instanceMatrix) * {n};" in body, (lib, n)
+ assert f"{n} = astraNormalTransform(mat3(instanceMatrix), {n});" in body, (lib, n)
assert "attribute mat4 instanceMatrix" not in vs, lib
# A varying declared in one stage only is a link failure, and the
# symptom is the patch simply not drawing.
diff --git a/harness/tests/scene_runtime/lib/test_planar_capture.py b/harness/tests/scene_runtime/lib/test_planar_capture.py
new file mode 100644
index 00000000..4c773211
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_planar_capture.py
@@ -0,0 +1,169 @@
+"""GPU behavior of addon-based planar captures and their shared state scope."""
+from __future__ import annotations
+
+import pytest
+
+from tests.scene_runtime.lib._probe import compile_scene
+
+_LIBS = ("water.js", "wetground.js")
+
+
[email protected]("factory", ["wetground", "water"])
+def test_addon_capture_preserves_affine_projection_and_renderer_state(factory: str) -> None:
+ script = r"""
+import * as THREE from 'three';
+import { makeMirrorFloor } from './lib/wetground.js';
+import { makeOcean } from './lib/water.js';
+import { withRendererState } from './lib/shader.js';
+export function createScene({renderer}) {
+ const kind='FACTORY';
+ const scene=new THREE.Scene();scene.background=new THREE.Color(0x667788);
+ const object=kind==='wetground'?makeMirrorFloor(8,8,{rttSize:64,detail:0,ripple:0}):makeOcean(8,8,{rttSize:64,distortionScale:0});
+ const surface=kind==='wetground'?object.getObjectByName('MirrorSurface'):object;
+ // Caller attachments include a mesh, a camera, a bone hierarchy, and a
+ // manually managed world transform; no capture may take ownership of them.
+ const attached=new THREE.Mesh(new THREE.BoxGeometry(.2,.3,.4),new THREE.MeshBasicMaterial());
+ attached.position.set(.3,.4,.5);surface.add(attached);
+ const attachedCamera=new THREE.PerspectiveCamera();attachedCamera.position.set(.2,.7,.1);attached.add(attachedCamera);
+ const bone=new THREE.Bone(),tip=new THREE.Bone();bone.position.set(.1,.2,.3);tip.position.y=.8;
+ attached.add(bone);bone.add(tip);
+ const manual=new THREE.Object3D();manual.matrixAutoUpdate=false;manual.matrixWorldAutoUpdate=false;
+ manual.matrixWorld.makeTranslation(9,8,7);attached.add(manual);
+ const attachments=[attached,attachedCamera,bone,tip,manual];
+ const attachmentMatrices=()=>JSON.stringify(attachments.map(o=>({world:o.matrixWorld.toArray(),
+ inverse:o.isCamera?o.matrixWorldInverse.toArray():null})));
+ const attachmentFlags=()=>attachments.map(o=>[o.matrixAutoUpdate,o.matrixWorldAutoUpdate,o.matrixWorldNeedsUpdate]);
+ const child=new THREE.Group(),parent=new THREE.Group();child.add(object);parent.add(child);scene.add(parent);
+ const marker=new THREE.Mesh(new THREE.BoxGeometry(.8,.8,.8),new THREE.MeshBasicMaterial({color:0xeeaa22}));scene.add(marker);
+ const camera=new THREE.PerspectiveCamera(45,1,.1,100),expectedCamera=new THREE.PerspectiveCamera();
+ const originalRender=renderer.render,originalSetTarget=renderer.setRenderTarget;
+ const originalRatio=renderer.getPixelRatio();
+ const cube=new THREE.WebGLCubeRenderTarget(32,{generateMipmaps:true,minFilter:THREE.LinearMipmapLinearFilter});
+ cube.viewport.set(2,3,12,11);cube.scissor.set(3,4,9,8);cube.scissorTest=true;
+ const state=()=>{
+ const gl=renderer.getContext();return {
+ target:renderer.getRenderTarget()===cube?'cube':renderer.getRenderTarget()?'other':'canvas',
+ face:renderer.getActiveCubeFace(),mip:renderer.getActiveMipmapLevel(),
+ viewport:renderer.getCurrentViewport(new THREE.Vector4()).toArray(),glViewport:Array.from(gl.getParameter(gl.VIEWPORT)),
+ logicalViewport:renderer.getViewport(new THREE.Vector4()).toArray(),logicalScissor:renderer.getScissor(new THREE.Vector4()).toArray(),
+ scissor:Array.from(gl.getParameter(gl.SCISSOR_BOX)),scissorTest:gl.isEnabled(gl.SCISSOR_TEST),logicalTest:renderer.getScissorTest(),
+ xr:renderer.xr.enabled,shadow:renderer.shadowMap.autoUpdate,tone:renderer.toneMapping,
+ clear:renderer.getClearColor(new THREE.Color()).toArray(),alpha:renderer.getClearAlpha(),visible:surface.visible,
+ attachments:attachmentMatrices(),attachmentFlags:attachmentFlags(),
+ matrix:surface.matrixWorld.toArray(),autoUpdate:surface.matrixWorldAutoUpdate,needsUpdate:surface.matrixWorldNeedsUpdate,
+ targetViewport:cube.viewport.toArray(),targetScissor:cube.scissor.toArray(),targetTest:cube.scissorTest,
+ setTargetIdentity:renderer.setRenderTarget===originalSetTarget,
+ };
+ };
+ try {
+ withRendererState(renderer,()=>{
+ for(const transform of [0,1,2]){
+ parent.scale.set(transform===2?-2:2,transform?.4:2,transform?1.6:2);
+ parent.rotation.set(transform?.1:0,transform?.5:0,transform?.2:0);parent.position.set(2,1,3);
+ child.rotation.set(transform?.35:0,transform?.2:0,transform?-.25:0);scene.updateMatrixWorld(true);
+ const world=surface.matrixWorld.clone(),normal=new THREE.Vector3(0,0,1).applyMatrix3(new THREE.Matrix3().getNormalMatrix(world)).normalize();
+ const center=new THREE.Vector3().setFromMatrixPosition(world),tangent=new THREE.Vector3(1,0,0).transformDirection(world);
+ camera.position.copy(center).addScaledVector(normal,4).addScaledVector(tangent,2);camera.lookAt(center);camera.updateMatrixWorld(true);
+ marker.position.copy(center).addScaledVector(normal,1.2);scene.updateMatrixWorld(true);
+ const reflect=p=>p.clone().addScaledVector(normal,-2*p.clone().sub(center).dot(normal));
+ expectedCamera.position.copy(reflect(camera.position));
+ expectedCamera.up.copy(camera.up).transformDirection(camera.matrixWorld).reflect(normal);
+ expectedCamera.lookAt(reflect(camera.position.clone().add(camera.getWorldDirection(new THREE.Vector3()))));expectedCamera.updateMatrixWorld(true);
+ attached.matrixWorldNeedsUpdate=true;
+ const expectedAttachments=attachmentMatrices();
+ let actualCamera=null,captures=0;
+ renderer.render=function(s,c){
+ captures++;actualCamera=c.position.clone();
+ if(captures>1)throw Error('Planar callback recursed');
+ surface.onBeforeRender(this,s,c); // The explicit re-entry must be inert.
+ const result=originalRender.call(this,s,c); // Actual GPU render updates scene matrices.
+ if(attachmentMatrices()!==expectedAttachments)throw Error('Nested capture changed caller attachment matrices');
+ return result;
+ };
+ const before=state();surface.onBeforeRender(renderer,scene,camera);
+ if(captures!==1||actualCamera.distanceTo(expectedCamera.position)>1e-10)throw Error('Wrong transformed mirror camera');
+ if(JSON.stringify(before)!==JSON.stringify(state()))throw Error('Capture changed affine matrix or renderer state');
+ const bias=new THREE.Matrix4().set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1);
+ const expected=bias.multiply(camera.projectionMatrix).multiply(expectedCamera.matrixWorldInverse);
+ const actual=surface.material.uniforms.textureMatrix.value;
+ for(const point of [[0,0,0],[1,0,0],[0,1,0],[-2,.7,0],[.4,-1.3,0]]){
+ const local=new THREE.Vector4(...point,1),wp=local.clone().applyMatrix4(world);
+ const a=(kind==='water'?wp:local).clone().applyMatrix4(actual),b=wp.clone().applyMatrix4(expected);
+ if(Math.abs(a.x/a.w-b.x/b.w)>1e-10||Math.abs(a.y/a.w-b.y/b.w)>1e-10)throw Error('Wrong local/world reflection projection');
+ }
+ renderer.render=originalRender;
+ }
+ parent.scale.set(1,1,1);parent.rotation.set(0,0,0);parent.position.set(0,0,0);child.rotation.set(0,0,0);scene.updateMatrixWorld(true);
+ camera.position.set(0,3,5);camera.lookAt(0,0,0);camera.updateMatrixWorld(true);
+ for(const ratio of [1,2])for(const override of [false,true])for(const throws of [false,true]){
+ renderer.setPixelRatio(ratio);renderer.setRenderTarget(cube,3,1);
+ if(override){renderer.setViewport(4,5,10,9);renderer.setScissor(5,6,7,6);renderer.setScissorTest(false);}
+ renderer.xr.enabled=true;renderer.shadowMap.autoUpdate=true;surface.visible=true;
+ renderer.toneMapping=THREE.ACESFilmicToneMapping;renderer.setClearColor(0x123456,.37);
+ attached.matrixWorldNeedsUpdate=true;
+ const before=state();let caught=false,captures=0;
+ renderer.render=function(...args){
+ captures++;const result=originalRender.apply(this,args);
+ if(attachmentMatrices()!==before.attachments)throw Error('Nested capture changed attachments before success/failure');
+ if(throws){this.toneMapping=THREE.NoToneMapping;this.setClearColor(0xffffff,0);throw Error('injected capture failure');}
+ return result;
+ };
+ try{surface.onBeforeRender(renderer,scene,camera);}catch(e){if(e.message!=='injected capture failure')throw e;caught=true;}
+ if(captures!==1||caught!==throws||JSON.stringify(before)!==JSON.stringify(state()))throw Error('Planar capture leaked state '+JSON.stringify({ratio,override,throws,before,after:state()}));
+ renderer.render=originalRender;
+ }
+ let captures=0;renderer.render=()=>{captures++;};
+ scene.overrideMaterial=new THREE.MeshNormalMaterial();surface.onBeforeRender(renderer,scene,camera);
+ scene.overrideMaterial.dispose();scene.overrideMaterial=null;
+ if(captures!==0)throw Error('Override pass performed colour capture');
+ const originalMaterial=surface.material,foreignMaterial=new THREE.MeshNormalMaterial();
+ surface.material=foreignMaterial;surface.onBeforeRender(renderer,scene,camera);
+ surface.material=originalMaterial;surface.onBeforeRender(renderer,scene,camera,surface.geometry,foreignMaterial);
+ foreignMaterial.dispose();
+ if(captures!==0)throw Error('Material replacement pass performed colour capture');
+ const projection=surface.material.uniforms.textureMatrix.value.clone();
+ camera.position.set(0,-3,5);camera.lookAt(0,0,0);camera.updateMatrixWorld(true);
+ surface.onBeforeRender(renderer,scene,camera);surface.onBeforeRender(renderer,scene,camera);
+ if(captures!==0||!projection.equals(surface.material.uniforms.textureMatrix.value))throw Error('Back-face skip changed cached projection');
+ });
+ } finally {
+ renderer.render=originalRender;renderer.setPixelRatio(originalRatio);cube.dispose();
+ let callerDisposals=0;
+ attached.geometry.addEventListener('dispose',()=>callerDisposals++);
+ attached.material.addEventListener('dispose',()=>callerDisposals++);
+ object.userData.dispose();
+ if(callerDisposals)throw Error('Factory disposed caller attachments');
+ attached.geometry.dispose();attached.material.dispose();
+ marker.geometry.dispose();marker.material.dispose();
+ }
+ return {scene:new THREE.Scene(),cameras:[{name:'probe',position:[0,3,5],lookAt:[0,0,0]}]};
+}
+""".replace("FACTORY", factory)
+ code, output = compile_scene(script, _LIBS, audit_module="src/scene.js")
+ assert code == 0, output
+
+
+def test_renderer_state_scope_is_nested_and_keeps_callback_result_and_exception() -> None:
+ code, output = compile_scene(r"""
+import * as THREE from 'three';
+import {withRendererState} from './lib/shader.js';
+export function createScene({renderer}) {
+ const old=renderer.getRenderTarget();
+ const a=new THREE.WebGLRenderTarget(32,32),b=new THREE.WebGLRenderTarget(16,16);
+ const read=()=>JSON.stringify({target:renderer.getRenderTarget()?.uuid||null,viewport:renderer.getCurrentViewport(new THREE.Vector4()).toArray(),scissor:renderer.getScissor(new THREE.Vector4()).toArray(),alpha:renderer.getClearAlpha(),tone:renderer.toneMapping});
+ try{
+ renderer.setRenderTarget(a);renderer.setViewport(1,2,23,24);renderer.setScissor(3,4,17,18);
+ const initial=read();
+ const result=withRendererState(renderer,()=>{
+ renderer.setRenderTarget(b);renderer.setViewport(2,3,8,9);renderer.setScissor(1,2,7,8);renderer.setClearAlpha(.41);
+ const middle=read(),error=new Error('nested failure');let caught;
+ try{withRendererState(renderer,()=>{renderer.setRenderTarget(null);renderer.setClearAlpha(.17);renderer.toneMapping=THREE.NoToneMapping;throw error;});}catch(e){caught=e;}
+ if(caught!==error||read()!==middle)throw Error('Nested scope did not restore its own entry state');
+ return 37;
+ });
+ if(result!==37||read()!==initial)throw Error('Outer scope result or state changed');
+ }finally{renderer.setRenderTarget(old);a.dispose();b.dispose();}
+ return {scene:new THREE.Scene(),cameras:[{name:'probe',position:[0,3,5],lookAt:[0,0,0]}]};
+}
+""", audit_module="src/scene.js")
+ assert code == 0, output
diff --git a/harness/tests/scene_runtime/lib/test_shader_geometry.py b/harness/tests/scene_runtime/lib/test_shader_geometry.py
new file mode 100644
index 00000000..65de1b56
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_shader_geometry.py
@@ -0,0 +1,272 @@
+"""GPU evidence for transformed surface normals and shared shadow geometry."""
+import json
+
+import pytest
+
+from tests.scene_runtime.lib._probe import compile_scene, measure
+
+pytestmark = pytest.mark.node
+
+
+def test_override_guard_preserves_callbacks_material_arrays_and_draw_range():
+ out = measure("""
+import * as THREE from 'three';
+import {keepOutOfDepthPasses} from './lib/shader.js';
+const geometry=new THREE.BoxGeometry();geometry.setDrawRange(3,12);
+const materials=[new THREE.MeshStandardMaterial(),new THREE.MeshStandardMaterial()];
+const mesh=new THREE.Mesh(geometry,materials),foreign=new THREE.MeshNormalMaterial();
+let before=0,after=0,correctThis=true,restoredAtCallback=true;
+mesh.onBeforeRender=function(){before++;correctThis&&=this===mesh;};
+mesh.onAfterRender=function(){after++;correctThis&&=this===mesh;restoredAtCallback&&=geometry.drawRange.count===12;};
+keepOutOfDepthPasses(mesh);keepOutOfDepthPasses(mesh);
+const args=[null,null,null,geometry,foreign];
+mesh.onBeforeRender(...args);const excluded=geometry.drawRange.count===0;
+mesh.onAfterRender(...args);
+args[4]=materials[1];mesh.onBeforeRender(...args);const arrayVisible=geometry.drawRange.count===12;mesh.onAfterRender(...args);
+mesh.material=new THREE.MeshBasicMaterial();args[4]=mesh.material;
+mesh.onBeforeRender(...args);const replacementVisible=geometry.drawRange.count===12;mesh.onAfterRender(...args);
+console.log(JSON.stringify({before,after,correctThis,restoredAtCallback,excluded,arrayVisible,replacementVisible,range:geometry.drawRange}));
+""")
+ assert out == {"before": 3, "after": 3, "correctThis": True,
+ "restoredAtCallback": True, "excluded": True,
+ "arrayVisible": True, "replacementVisible": True,
+ "range": {"start": 3, "count": 12}}
+
+
+def test_patched_clone_keeps_typed_uniforms_and_borrows_textures():
+ out = measure("""
+import * as THREE from 'three';
+import {patchStandard,clonePatchedMaterial} from './lib/shader.js';
+const texture=new THREE.WebGLRenderTarget(4,4).texture;
+const original=new THREE.MeshStandardMaterial({map:texture});
+patchStandard(original,{name:'typed-patch',uniforms:{
+ uOffset:{value:new THREE.Vector3(1,2,3)},uSample:{value:texture},
+ uColors:{value:[new THREE.Color(.2,.3,.4)]},uWeights:{value:new Float32Array([1,2])}},
+ fragmentHead:'uniform vec3 uOffset;',fragmentBody:'diffuseColor.rgb *= uOffset;'});
+original.userData.shared=true;
+const clone=clonePatchedMaterial(original),a=original.userData.uniforms,b=clone.userData.uniforms;
+b.uOffset.value.x=8;b.uColors.value[0].r=.9;b.uWeights.value[0]=9;
+patchStandard(clone,{name:'second',fragmentBody:'diffuseColor.rgb *= 0.5;'});
+const shader={vertexShader:'void main(){\\n#include <begin_vertex>\\n}',
+ fragmentShader:'void main(){\\n#include <color_fragment>\\n}',uniforms:{}};
+clone.onBeforeCompile(shader);
+console.log(JSON.stringify({typed:b.uOffset.value.isVector3&&b.uColors.value[0].isColor,
+ old:[a.uOffset.value.x,a.uColors.value[0].r,a.uWeights.value[0]],
+ texture:b.uSample.value===texture&&clone.map===texture,
+ chain:original.userData.astraPatches.length,cloneChain:clone.userData.astraPatches.length,
+ applied:shader.fragmentShader.includes('diffuseColor.rgb *= uOffset;')&&shader.fragmentShader.includes('diffuseColor.rgb *= 0.5;'),
+ shared:!!clone.userData.shared,sourceShared:original.userData.shared}));
+""")
+ assert out == {"typed": True, "old": [1, 0.2, 1], "texture": True,
+ "chain": 1, "cloneChain": 2, "applied": True,
+ "shared": False, "sourceShared": True}
+
+
+def test_shader_clone_borrows_samplers_and_preserves_uniform_sharing():
+ out = measure("""
+import * as THREE from 'three';
+import {makeShaderMaterial,clonePatchedMaterial} from './lib/shader.js';
+const target=new THREE.WebGLRenderTarget(4,4),texture=new THREE.Texture();
+const results=[],warnings=[];console.warn=(...args)=>warnings.push(args.join(' '));
+for(const factory of [opts=>new THREE.ShaderMaterial(opts),
+ opts=>new THREE.RawShaderMaterial(opts),opts=>makeShaderMaterial(opts)]) {
+ const uniforms={uTarget:{value:target.texture},uMap:{value:texture},
+ uNested:{value:{samples:[target.texture,texture],offset:new THREE.Vector3(1,2,3)}},
+ uWeights:{value:new Float32Array([1,2])}};
+ const original=factory({uniforms});original.userData.uniforms=original.uniforms;
+ const clone=clonePatchedMaterial(original),shared=clonePatchedMaterial(original,{shareUniforms:true});
+ const source=original.uniforms,copy=clone.uniforms;
+ copy.uNested.value.offset.x=7;copy.uWeights.value[0]=8;
+ results.push({type:clone.type===original.type,
+ borrowed:copy.uTarget.value===target.texture&&copy.uMap.value===texture&&
+ copy.uNested.value.samples[0]===target.texture&&copy.uNested.value.samples[1]===texture,
+ independent:copy!==source&&copy.uTarget!==source.uTarget&&
+ copy.uNested.value.offset.isVector3&&source.uNested.value.offset.x===1&&source.uWeights.value[0]===1,
+ alias:clone.userData.uniforms===copy,
+ shared:shared.uniforms===source&&shared.userData.uniforms===source,
+ intact:source.uTarget.value===target.texture&&source.uMap.value===texture});
+ clone.dispose();shared.dispose();original.dispose();
+}
+target.dispose();texture.dispose();console.log(JSON.stringify({results,warnings}));
+""")
+ assert out == {"results": [dict.fromkeys(
+ ["type", "borrowed", "independent", "alias", "shared", "intact"], True)] * 3,
+ "warnings": []}
+
+
+def test_cloned_and_merged_shader_sample_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;
+ const textureTarget=new THREE.WebGLRenderTarget(8,8),readTarget=new THREE.WebGLRenderTarget(8,8);
+ const sourceScene=new THREE.Scene();sourceScene.background=new THREE.Color(.2,.6,.9);
+ const material=makeShaderMaterial({fog:false,toneMapped:false,
+ uniforms:{uSample:{value:textureTarget.texture},uGain:{value:1}},
+ fragmentHead:'uniform sampler2D uSample; uniform float uGain;',
+ 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);
+ } finally {
+ renderer.setRenderTarget(previous);readTarget.dispose();textureTarget.dispose();
+ merged.userData.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, out
+ assert json.loads(out.strip().splitlines()[-1])["ok"]
+
+
+def test_world_normals_match_inverse_transpose_on_gpu():
+ code, out = compile_scene("""
+import * as THREE from 'three';
+import {patchStandard,worldBase,glslLocalDir} from './lib/shader.js';
+export function createScene({renderer}) {
+ const scene=new THREE.Scene();
+ const material=new THREE.MeshStandardMaterial({side:THREE.DoubleSide,toneMapped:false});
+ patchStandard(material,worldBase('normal-probe','probeP','probeN'));
+ patchStandard(material,{name:'normal-output',uniforms:{uProbe:{value:0}},
+ vertexHead:glslLocalDir('probeLocal',true)+'\\nvarying vec3 vProbeOffset;',
+ vertexBody:'vProbeOffset=mat3(modelMatrix)*mat3(instanceMatrix)*probeLocal(vec3(.4,.1,-.3));',
+ fragmentHead:'uniform float uProbe;\\nvarying vec3 vProbeOffset;',
+ outputBody:'gl_FragColor=vec4(uProbe>0.5?abs(vProbeOffset-vec3(.4,.1,-.3))*100.0:normalize(vAstraWorldN)*0.5+0.5,1.0);'});
+ const geometry=new THREE.PlaneGeometry(4,4);
+ const mesh=new THREE.InstancedMesh(geometry,material,1);
+ mesh.frustumCulled=false;mesh.matrixAutoUpdate=false;scene.add(mesh);
+ const q=new THREE.Quaternion().setFromEuler(new THREE.Euler(.4,.7,-.25));
+ const transforms=[new THREE.Matrix4(),
+ new THREE.Matrix4().compose(new THREE.Vector3(),q,new THREE.Vector3(3,.5,1.2)),
+ new THREE.Matrix4().makeShear(.4,-.2,.6,.1,-.3,.2),
+ new THREE.Matrix4().compose(new THREE.Vector3(),q,new THREE.Vector3(-2,.7,1.5))];
+ const target=new THREE.WebGLRenderTarget(16,16);
+ const previous=renderer.getRenderTarget(),pixel=new Uint8Array(4);
+ let maxError=0,maxOffsetError=0;
+ try {
+ for(const model of transforms) for(const instance of transforms) {
+ mesh.matrix.copy(model);mesh.setMatrixAt(0,instance);mesh.instanceMatrix.needsUpdate=true;
+ mesh.updateMatrixWorld(true);
+ const matrix=new THREE.Matrix4().multiplyMatrices(model,instance);
+ const expected=new THREE.Vector3(0,0,1).applyNormalMatrix(new THREE.Matrix3().getNormalMatrix(matrix));
+ const camera=new THREE.PerspectiveCamera(35,1,.01,100);
+ camera.position.copy(expected).multiplyScalar(12);camera.lookAt(0,0,0);
+ material.userData.uniforms.uProbe.value=0;
+ renderer.setRenderTarget(target);renderer.render(scene,camera);
+ renderer.readRenderTargetPixels(target,8,8,1,1,pixel);
+ for(let k=0;k<3;k++) maxError=Math.max(maxError,Math.abs(pixel[k]/255-(expected.getComponent(k)*.5+.5)));
+ material.userData.uniforms.uProbe.value=1;renderer.render(scene,camera);
+ renderer.readRenderTargetPixels(target,8,8,1,1,pixel);
+ maxOffsetError=Math.max(maxOffsetError,pixel[0],pixel[1],pixel[2]);
+ }
+ } finally {renderer.setRenderTarget(previous);target.dispose();}
+ if(maxError>.008) throw new Error('GPU inverse-transpose normal error: '+maxError);
+ if(maxOffsetError>1) throw new Error('GPU world/local direction error: '+maxOffsetError);
+ return {scene,cameras:[{name:'a',position:[6,3,8],lookAt:[0,0,0],fov:45}]};
+}
+""")
+ assert code == 0, out
+ assert json.loads(out.strip().splitlines()[-1])["ok"]
+
+
+def test_depth_and_distance_share_clock_displacement_and_alpha_silhouette():
+ out = measure("""
+import * as THREE from 'three';
+import {patchStandard,shadowLike,tickShaders} from './lib/shader.js';
+const mesh=new THREE.Mesh(new THREE.PlaneGeometry(),new THREE.MeshStandardMaterial());
+const head='varying vec2 vCut;';
+const body='vCut=uv; transformed.x += sin(uTime);';
+patchStandard(mesh.material,{name:'sway',vertexHead:head,vertexBody:body});
+shadowLike(mesh,'sway-shadow',head,body,{fragmentHead:head,
+ fragmentBody:'if(length(vCut-0.5)>0.4) discard;'});
+tickShaders(mesh,2.5);
+const compiled=[['depth',mesh.customDepthMaterial],['distance',mesh.customDistanceMaterial]]
+ .map(([key,material])=>{
+ const template=THREE.ShaderLib[key];
+ const shader={vertexShader:template.vertexShader,fragmentShader:template.fragmentShader,uniforms:{}};
+ material.onBeforeCompile(shader);
+ return {time:material.userData.uniforms.uTime.value,
+ shared:material.userData.uniforms===mesh.material.userData.uniforms,
+ displaced:shader.vertexShader.includes('transformed.x += sin(uTime);'),
+ cut:shader.fragmentShader.includes('if(length(vCut-0.5)>0.4) discard;'),
+ beforeAlpha:shader.fragmentShader.indexOf('if(length(vCut-0.5)>0.4) discard;')<shader.fragmentShader.indexOf('#include <alphatest_fragment>')};
+ });
+console.log(JSON.stringify({compiled,depth:mesh.customDepthMaterial.isMeshDepthMaterial,
+ distance:mesh.customDistanceMaterial.isMeshDistanceMaterial}));
+""")
+ assert out["depth"] and out["distance"]
+ assert out["compiled"] == [{"time": 2.5, "shared": True, "displaced": True,
+ "cut": True, "beforeAlpha": True}] * 2
+
+
+def test_point_light_shadow_displacement_and_cut_compile_on_gpu():
+ code, out = compile_scene("""
+import * as THREE from 'three';
+import {patchStandard,shadowLike,tickShaders} from './lib/shader.js';
+export function createScene() {
+ const scene=new THREE.Scene();scene.background=new THREE.Color(0x203040);
+ const light=new THREE.PointLight(0xffffff,60,20);light.position.set(2,4,3);light.castShadow=true;scene.add(light);
+ const material=new THREE.MeshStandardMaterial({side:THREE.DoubleSide});
+ const head='varying vec2 vCut;';
+ const body='vCut=uv; transformed.x += .3*sin(uTime+position.y);';
+ const cut='if(length(vCut-0.5)>0.4) discard;';
+ patchStandard(material,{name:'point-cut',vertexHead:head,vertexBody:body,fragmentHead:head,alphaBody:cut});
+ const mesh=new THREE.Mesh(new THREE.PlaneGeometry(2,2,8,8),material);mesh.position.y=1.5;
+ shadowLike(mesh,'point-shadow',head,body,{fragmentHead:head,fragmentBody:cut});scene.add(mesh);
+ const floor=new THREE.Mesh(new THREE.PlaneGeometry(12,12),new THREE.MeshStandardMaterial());
+ floor.rotation.x=-Math.PI/2;floor.receiveShadow=true;scene.add(floor);
+ return {scene,cameras:[{name:'a',position:[4,3,6],lookAt:[0,1,0],fov:45}],update(t){tickShaders(scene,t);}};
+}
+""", audit_module="src/scene.js")
+ assert code == 0, out
+
+
+def test_transmission_hook_runs_after_maps_and_survives_clone_on_gpu():
+ code, out = compile_scene("""
+import * as THREE from 'three';
+import {patchStandard,clonePatchedMaterial} from './lib/shader.js';
+export function createScene({renderer}) {
+ const scene=new THREE.Scene();
+ const map=new THREE.DataTexture(new Uint8Array([64,128,255,255]),1,1);map.needsUpdate=true;
+ const original=new THREE.MeshPhysicalMaterial({transmission:.8,thickness:2,
+ transmissionMap:map,thicknessMap:map,toneMapped:false});
+ patchStandard(original,{name:'optical-add',transmissionBody:
+ 'material.thickness += .2; material.transmission += .1;'});
+ patchStandard(original,{name:'optical-scale',transmissionBody:
+ 'material.thickness *= .5; material.transmission *= .5;',
+ outputBody:'gl_FragColor=vec4(material.thickness*.5,material.transmission,0.,1.);'});
+ const mesh=new THREE.Mesh(new THREE.PlaneGeometry(4,4),original);scene.add(mesh);
+ const camera=new THREE.PerspectiveCamera(40,1,.01,100);camera.position.z=5;
+ const target=new THREE.WebGLRenderTarget(16,16),previous=renderer.getRenderTarget();
+ const clone=clonePatchedMaterial(original),pixel=new Uint8Array(4);
+ try {
+ for(const material of [original,clone]) {
+ mesh.material=material;renderer.setRenderTarget(target);renderer.render(scene,camera);
+ renderer.readRenderTargetPixels(target,8,8,1,1,pixel);
+ const expected=[(2*128/255+.2)*.25,(.8*64/255+.1)*.5,0];
+ if(expected.some((v,i)=>Math.abs(pixel[i]/255-v)>.006))
+ throw new Error('Optical map/patch order or cloned chain failed: '+Array.from(pixel));
+ }
+ } finally {renderer.setRenderTarget(previous);target.dispose();}
+ return {scene,cameras:[{name:'a',position:[0,0,5],lookAt:[0,0,0],fov:40}]};
+}
+""", audit_module="src/scene.js")
+ assert code == 0, out
diff --git a/harness/tests/scene_runtime/lib/test_terrain.py b/harness/tests/scene_runtime/lib/test_terrain.py
index fd636f8c..7c83afc3 100644
--- a/harness/tests/scene_runtime/lib/test_terrain.py
+++ b/harness/tests/scene_runtime/lib/test_terrain.py
@@ -143,3 +143,44 @@ def test_cliff_faceat_matches_the_displaced_mesh(probe):
assert c["drift"] < 1e-4, c
assert abs(c["minY"]) < 1e-6 and abs(c["maxY"] - 40) < 1e-6
assert c["zSpan"] > 2, c
+
+
+def test_surface_samplers_match_triangles_between_vertices_after_parent_transform():
+ result = measure("""
+import * as THREE from 'three';
+import { ground, cliff } from './lib/terrain.js';
+let seed = 37;
+const rand = () => (seed = seed * 16807 % 2147483647) / 2147483647;
+const terrain = ground({ size: 113, segments: 19, relief: 8, scale: 13, rand });
+const wall = cliff({ length: 27, height: 9, relief: 3, rand });
+const parent = new THREE.Group();
+parent.position.set(8, -3, 12); parent.rotation.set(.2, -.5, .1);
+parent.scale.set(1.4, .8, 2.1); parent.add(terrain.mesh, wall.mesh);
+parent.updateMatrixWorld(true);
+const ray = new THREE.Raycaster();
+const error = (mesh, point, direction) => {
+ const origin = point.clone().addScaledVector(direction, -100).applyMatrix4(mesh.matrixWorld);
+ const endpoint = point.clone().add(direction).applyMatrix4(mesh.matrixWorld);
+ ray.set(origin, endpoint.sub(origin).normalize());
+ const hit = ray.intersectObject(mesh, false)[0];
+ if (!hit) throw new Error('Expected a surface hit');
+ return hit.point.distanceTo(point.clone().applyMatrix4(mesh.matrixWorld));
+};
+let groundError = 0, cliffError = 0;
+for (let i = 0; i < 200; i++) {
+ const x = (rand() - .5) * 112, z = (rand() - .5) * 112;
+ groundError = Math.max(groundError, error(terrain.mesh,
+ new THREE.Vector3(x, terrain.height(x, z), z), new THREE.Vector3(0, -1, 0)));
+ const s = rand() * 27, y = rand() * 9;
+ cliffError = Math.max(cliffError, error(wall.mesh,
+ wall.faceAt(s, y), new THREE.Vector3(0, 0, -1)));
+}
+const flat = cliff({ length: 11, height: 4, relief: 0, rand });
+console.log(JSON.stringify({ groundError, cliffError,
+ finiteFlatColors: Array.from(flat.mesh.geometry.attributes.color.array).every(Number.isFinite),
+ edge: terrain.height(-1000, 1000) === terrain.height(-56.5, 56.5) }));
+""", _LIBS)
+ assert result["groundError"] < 2e-5, result
+ assert result["cliffError"] < 2e-5, result
+ assert result["finiteFlatColors"] and result["edge"], result
+
diff --git a/harness/tests/scene_runtime/lib/test_veils.py b/harness/tests/scene_runtime/lib/test_veils.py
index 7d8eaf5c..cb2e8f93 100644
--- a/harness/tests/scene_runtime/lib/test_veils.py
+++ b/harness/tests/scene_runtime/lib/test_veils.py
@@ -44,7 +44,7 @@ const lit = (field, scene, frame) => {
scene.updateMatrixWorld(true);
R.info.render.frame = frame;
const m = field.children[0];
- m.onBeforeRender(R, scene, null, m.geometry, m.material, null);
+ m.onBeforeRender(R, scene, new THREE.PerspectiveCamera(), m.geometry, m.material, null);
return m.material.uniforms.uLight.value.toArray();
};
const rigScene = (elev, fog) => {