Skip to content

Official Codebase of 3DCodeVerse

Python

effects library: ray-marched cloud deck, light-probe/water-transport/vegetation/surface-filtering work, night lab scene — the local dev session's uncommitted work, integrated

gaoypengb4452096d4c3
diff --git a/harness/codeverse3d/languages/opengl_python/wrappers/run_gl.py b/harness/codeverse3d/languages/opengl_python/wrappers/run_gl.py
index bbe3dbf2..445486c9 100644
--- a/harness/codeverse3d/languages/opengl_python/wrappers/run_gl.py
+++ b/harness/codeverse3d/languages/opengl_python/wrappers/run_gl.py
@@ -113,6 +113,10 @@ class Pass:
t.filter = (ctx.LINEAR, ctx.LINEAR)
t.repeat_x = t.repeat_y = False
self.fbo = [ctx.framebuffer(color_attachments=[t]) for t in self.tex]
+ # Texture allocation does not define its contents. Both sides must
+ # start black: the first draw samples the other side as u_prev.
+ for fbo in self.fbo:
+ fbo.clear(0.0, 0.0, 0.0, 1.0)
self.cur = 0
@property
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 6c8e4b27..48386e54 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/building.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/building.js
@@ -789,12 +789,30 @@ export function tower(opts = {}) {
*/
export function roofClutter(host, opts = {}) {
const rand = opts.rand || (() => 0.5);
- host.updateMatrixWorld(true);
- const b = new THREE.Box3().setFromObject(host);
+ // Clutter becomes a child of the host, so measure the roof in that
+ // same local frame. A world bbox would apply the host transform twice.
+ host.updateWorldMatrix(true, true);
+ const inverse = host.matrixWorld.clone().invert();
+ const b = new THREE.Box3(), part = new THREE.Box3(), matrix = new THREE.Matrix4();
+ host.traverse((o) => {
+ let bounds;
+ if (o.boundingBox !== undefined) {
+ if (!o.boundingBox) o.computeBoundingBox();
+ bounds = o.boundingBox;
+ } else if (o.geometry) {
+ if (!o.geometry.boundingBox) o.geometry.computeBoundingBox();
+ bounds = o.geometry.boundingBox;
+ }
+ if (bounds) {
+ matrix.multiplyMatrices(inverse, o.matrixWorld);
+ b.union(part.copy(bounds).applyMatrix4(matrix));
+ }
+ });
const y = b.max.y;
const w = (b.max.x - b.min.x) * 0.7, d = (b.max.z - b.min.z) * 0.7;
const g = new THREE.Group();
g.name = 'RoofClutter';
+ g.position.set((b.min.x + b.max.x) * 0.5, 0, (b.min.z + b.max.z) * 0.5);
const wood = MAT.weatheredWood();
const steel = MAT.brushedSteel({ color: 0x8d949b });
for (let i = 0; i < (opts.tanks === undefined ? 1 : opts.tanks); i++) {
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 0b9f1855..550382b1 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/canopy.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/canopy.js
@@ -34,7 +34,7 @@ import {
glslLocalDir, patchStandard, shadowLike, tickShaders, unit,
} from './shader.js';
import { patchLeafSSS } from './foliage_shade.js';
-import { windOf } from './grass.js';
+import { WIND_GUST_GLSL, windOf } from './grass.js';
const LOCAL_DIR = glslLocalDir('leafLocalDir');
@@ -370,7 +370,7 @@ const LEAF_HEAD = [
// facing looks at the sky. Both are constant over a card, so they
// ride a varying rather than being recomputed per pixel.
'varying vec2 vLeafB;',
- LOCAL_DIR,
+ LOCAL_DIR, WIND_GUST_GLSL,
].join('\n');
const LEAF_VERTEX = [
@@ -398,9 +398,9 @@ const LEAF_VERTEX = [
// 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(iSpray.xz, lfW) * 0.05 - uTime * uLeafSpeed * 0.5,',
- ' dot(iSpray.xz, vec2(-lfW.y, lfW.x)) * 0.2), 2);',
+ ' vec3 lfRootWorld = (modelMatrix * vec4(iSpray.xyz, 1.0)).xyz;',
+ ' float lfG = astraWindGust(lfRootWorld, uLeafWind,',
+ ' uTime * uLeafSpeed, vec2(0.05, 0.2));',
' float lfT2 = uTime * uLeafSpeed;',
// Outer leaves move most: the trunk end of a bough barely travels.
' float lfSway = uLeafAmp * (0.2 + 1.1 * lfG) * iVar.w',
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/caustics.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/caustics.js
index 77bfb639..cf423093 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/caustics.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/caustics.js
@@ -45,6 +45,11 @@ const CAU_HEAD = [
const CAU_BODY = [
' float cauD = max(uCauLevel - vAstraWorld.y, 0.0);',
+ // The projection, incident cosine and extinction must describe the SAME
+ // refracted beam. Using the air direction here put low-sun caustics on
+ // near-vertical faces while starving the floor the bent ray actually hits.
+ ' vec3 cauBeam = normalize(vec3(uCauSlide.x, 1.0, uCauSlide.y));',
+ ' float cauPath = cauD / cauBeam.y;',
// Shade from where this fragment's light ENTERED the water: the net
// belongs to the surface overhead, so a riser takes a stretched
// slice of the floor's net instead of a pattern of its own.
@@ -104,8 +109,10 @@ const CAU_BODY = [
// fraction of a depth down. The column it loses light IN is the
// tint below — extinction is per channel, not one number.
' float cauK = smoothstep(0.0, uCauFade * 0.3, cauD);',
- ' cauK *= 0.12 + 0.88 * max(dot(normalize(vAstraWorldN), uCauSun),',
- ' 0.0);',
+ ' cauK *= max(dot(normalize(vAstraWorldN), cauBeam), 0.0);',
+ // No beam enters the surface from a sun below its horizon. The short
+ // transition also avoids a hard on/off edge at grazing incidence.
+ ' cauK *= smoothstep(0.0, 0.05, uCauSun.y);',
// A long shallow shelf is one smooth ramp of this term over hundreds
// of pixels, which is exactly where 8-bit output bands.
' cauK *= 1.0 + (astraHash21(gl_FragCoord.xy) - 0.5) * 0.05;',
@@ -118,9 +125,9 @@ const CAU_BODY = [
// net evenly and left a deep floor lit the same colour as a shin-
// deep one; a per-channel Beer-Lambert is what makes shallow water
// warm and a depth go green-blue — the whole reason a pool
- // photographs. uCauAbs is luminance-neutral, so the net still dims
- // over exactly the `depthFade` metres asked for: only the hue splits.
- ' vec3 cauTint = uCauColor * exp(-cauD * uCauAbs);',
+ // photographs. The coefficients have unit luminance-weighted mean,
+ // preserving the initial extinction rate set by `depthFade`.
+ ' vec3 cauTint = uCauColor * exp(-cauPath * uCauAbs);',
// Dispersion: a lone filament is a fold seen edge-on and keeps the
// cool end, a crossing is achromatic and runs warm-white.
' float cauNf = cauNode / (cauNode + cauFil * 0.5 + 1e-4);',
@@ -160,13 +167,10 @@ function refractSlide(sun) {
* water really has, because the true ratio takes the net monochrome
* cyan inside three metres and a pool is not an ocean trench.
*
- * NORMALISED to luminance, so this is a pure hue split and not a
- * dimmer: mid-grey still decays over exactly the metres the caller
- * asked for, and `depthFade` keeps meaning what it meant before there
- * was a colour here at all. (Weighting by Rec.709 rather than thirds
- * matters — green carries 71% of the luminance and is the channel in
- * the middle, so an unweighted normalisation would darken the net by a
- * tenth at every depth.)
+ * Normalised to a unit luminance-weighted mean extinction rate, so
+ * `depthFade` sets the initial loss per metre. At greater depth the
+ * surviving blue/green light decays more slowly; a spectral mixture
+ * cannot retain one exact luminance e-fold distance at every depth.
*/
function absorption(fade) {
const w = new THREE.Vector3(1 / 0.62, 1 / 1.00, 1 / 1.45);
@@ -206,7 +210,11 @@ const seedOffset = (seed) => new THREE.Vector2(seedLattice(seed) * 0.103,
* ENTERED the water: this fragment's world XZ slid toward the sun by
* its own depth, refracted. So the net belongs to the surface overhead
* and a step riser takes a stretched slice of the same net rather than
- * a pattern of its own. And it is ridged interference — two wave
+ * a pattern of its own. Incidence and absorption use that same bent
+ * ray: a grazing sun still reaches the floor steeply, the beam loses
+ * light over its full slanted water path, and back-facing surfaces
+ * receive no direct caustics. A sun below the horizon contributes none.
+ * And it is ridged interference — two wave
* trains crossing, plus a slow third that bunches the light — so the
* bright nodes travel at neither train's speed, where one fbm at any
* speed reads as dirt sliding over the floor.
@@ -239,7 +247,7 @@ const seedOffset = (seed) => new THREE.Vector2(seedLattice(seed) * 0.103,
* burns — a node peaks near 3 x this (default 4); `speed` how fast
* the water runs (default 0.35); `color` THREE.Color or hex of the
* light ABOVE the surface, before the water tints it (default a
- * warm daylight white); `depthFade` metres of water the net survives
+ * warm daylight white); `depthFade` metres of beam travel in water the net survives
* in luminance — red keeps 0.62 of that and blue 1.45, which is the
* ramp from a warm step to a green-blue drain (default 3); `seed`
* moves the lattice, so two pools are not one pool twice (default 1);
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 3ee20ccd..7cb4ebc3 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/celestial.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/celestial.js
@@ -334,15 +334,16 @@ function shimmerMaterial(strength, speed, cells, aspect, height, phase) {
*
* Combine with a dome, never instead of one: `worldShell({mood:
* 'night'})` (lib/environment.js) draws the gradient this sits in
- * front of, and `makeSky()` (lib/sky.js) is a DAYLIGHT dome — its
- * Preetham shader has no night. Both leave `scene.background` null and
+ * front of, or `makeSky(scene, { rig })` with a night `sunRig()` for
+ * a graded physical dome. Both leave `scene.background` null and
* neither writes depth, so the stars paint over either one.
*
* @param {object} [opts]
* `count` stars (default 1400); `radius` metres to the star sphere
* (default 2000 — inside `worldShell`'s 4 km dome and the camera's
* far plane, outside any content); `magnitude` overall brightness
- * gain (default 1); `twinkle` scintillation depth 0..1 (default
+ * gain for both stars and unresolved Milky Way light (default 1;
+ * 0 hides both); `twinkle` scintillation depth 0..1 (default
* 0.35, over periods of 4-9 s); `milkyWay` the band of unresolved
* light, which also pulls part of the field into it (default true);
* `seed` PRNG seed (default 3); `ambient` how bright the frame
@@ -357,7 +358,7 @@ export function makeStars(opts = {}) {
const count = Math.max(1, Math.round(
opts.count === undefined ? 1400 : opts.count));
const radius = opts.radius === undefined ? 2000 : opts.radius;
- const gain = opts.magnitude === undefined ? 1 : opts.magnitude;
+ const gain = Math.max(0, opts.magnitude === undefined ? 1 : opts.magnitude);
const twinkle = Math.min(Math.max(
opts.twinkle === undefined ? 0.35 : opts.twinkle, 0), 1);
const seed = opts.seed === undefined ? 3 : opts.seed;
@@ -376,7 +377,7 @@ export function makeStars(opts = {}) {
const g = new THREE.Group();
g.name = 'Stars';
- if (opts.milkyWay !== false) g.add(milkyWayMesh(radius, pole, bright));
+ if (opts.milkyWay !== false) g.add(milkyWayMesh(radius, pole, bright, gain));
g.add(starMesh(count, radius, gain, twinkle, rnd, pole, bright,
opts.milkyWay !== false));
g.userData.update = g.userData.tick = (t) => tickShaders(g, t);
@@ -498,7 +499,7 @@ function starMaterial(radius, gain, twinkle, bright) {
}
/** The band: unresolved light, dust lanes, and a bulge to aim at. */
-function milkyWayMesh(radius, pole, bright) {
+function milkyWayMesh(radius, pole, bright, gain) {
const geom = new THREE.SphereGeometry(radius * 1.01, 48, 24);
// Two axes across the band give the noise a seamless 2D coordinate
// — an atan around the pole would print a meridian down the sky.
@@ -513,19 +514,11 @@ function milkyWayMesh(radius, pole, bright) {
uAxisA: { value: a },
uAxisB: { value: b },
uCore: { value: core },
- // TWO colours, because the band has two: the bulge is seen
- // through the whole disc of dust and comes out reddened,
- // while the outer arms are the blue-white of the young
- // stars in them. One flat tint is what made this render as
- // a grey cloud (sky hue sigma 0.0025 over the band).
- uArm: { value: new THREE.Color(0x9fbcf8) },
- uHub: { value: new THREE.Color(0xffd79a) },
- // Higher than the 0.42 this shipped with, because the alpha
- // it multiplies is no longer a plateau: deep dust lanes,
- // the rift and a real extinction ramp take most of the band
- // to nearly nothing, and the gain has to buy the star
- // clouds back or the whole band disappears with the wash.
- uGain: { value: bright ? 0.24 : 0.62 },
+ // Unresolved starlight is faint and nearly neutral. The
+ // previous warm, high-alpha band became a luminous fog bank.
+ uArm: { value: new THREE.Color(0xc3c9d9) },
+ uHub: { value: new THREE.Color(0xd5cbbb) },
+ uGain: { value: gain * (bright ? 0.018 : 0.045) },
},
varyings: 'varying vec3 vDir;',
vertexMain: ' vDir = normalize(position);',
@@ -536,29 +529,27 @@ function milkyWayMesh(radius, pole, bright) {
fragmentMain: [
' vec3 d = normalize(vDir);',
' float s = dot(d, uPole);',
- ' float band = exp(-(s * s) / 0.032);',
- // 7.0, not 3.2: at the coarse scale one lobe of the noise
- // spanned tens of degrees and the band arrived as a bank of
- // grey FOG. The band is unresolved STARS — its texture has
- // to be finer than the shape it fills.
- ' vec2 p = vec2(dot(d, uAxisA), dot(d, uAxisB)) * 7.0;',
- ' float n = astraFbm2(p + vec2(s * 6.0, 0.0), 4);',
+ ' float band = exp(-(s * s) / 0.009);',
+ // Angular detail follows the galactic plane without a seam.
+ // Fine star clouds sit inside the narrow unresolved band.
+ ' vec2 p = vec2(dot(d, uAxisA), dot(d, uAxisB)) * 22.0;',
+ ' float n = astraFbm2(p + vec2(s * 12.0, 0.0), 4);',
// Dark lanes are dust in front of the band, so they CUT it
// rather than tinting it; a smooth gaussian is a smear.
- ' float lanes = smoothstep(0.26, 0.72, n);',
+ ' float lanes = smoothstep(0.28, 0.72, n);',
// A second field finer again: star clouds INSIDE the arms.
// One scale of noise is a smear at any contrast.
' float fine = astraFbm2(p * 2.9 + vec2(11.0, s * 4.0), 3);',
- ' lanes *= 0.34 + 1.05 * fine;',
+ ' lanes *= 0.45 + 0.75 * fine;',
// The Great Rift: dust lying IN the plane, so it splits the
// band down its own spine instead of dimming it evenly.
// Without it the brightest pixel is the exact centre line,
// which is the one place the real band is darkest.
- ' float spine = abs(s + (astraNoise2(p * 0.35) - 0.5) * 0.05);',
- ' float rift = smoothstep(0.05, 0.17, spine);',
- ' float bulge = exp(-pow(1.0 - dot(d, uCore), 2.0) / 0.09);',
- ' float a = band * (0.10 + 1.15 * lanes)',
- ' * (0.55 + 1.15 * bulge) * mix(0.30, 1.0, rift) * uGain',
+ ' float spine = abs(s + (astraNoise2(p * 0.35) - 0.5) * 0.025);',
+ ' float rift = smoothstep(0.012, 0.065, spine);',
+ ' float bulge = exp(-(1.0 - dot(d, uCore)) / 0.055);',
+ ' float a = band * (0.08 + 0.92 * lanes)',
+ ' * (0.55 + 0.75 * bulge) * mix(0.20, 1.0, rift) * uGain',
// Extinction is a LONG ramp. Ending it at 0.12 put the
// whole fade inside the sky a level camera actually frames,
// and drew a straight horizontal edge across the band.
@@ -566,11 +557,11 @@ function milkyWayMesh(radius, pole, bright) {
// Warm hub, cool arms, and the star clouds carry the mix so
// the band has warm and cold patches instead of one tint.
' vec3 c = mix(uArm, uHub,',
- ' clamp(bulge * 0.8 + (fine - 0.42) * 1.1, 0.0, 1.0));',
- // Sub-LSB dither: a veil this smooth bands into visible
- // contour rings on an 8-bit frame.
- ' a += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.004;',
- ' if (a < 0.003) discard;',
+ ' clamp(bulge * 0.65 + (fine - 0.5) * 0.25, 0.0, 1.0));',
+ // Relative grain preserves zero and scales with magnitude;
+ // an absolute alpha floor would resurrect a disabled band.
+ ' a *= 1.0 + (astraHash21(gl_FragCoord.xy) - 0.5) * 0.10;',
+ ' if (a <= 0.0) discard;',
' gl_FragColor = vec4(c, clamp(a, 0.0, 1.0));',
].join('\n'),
// 3dcode: no-fog — see StarField.
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 238d774f..67c3966a 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloth.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloth.js
@@ -293,8 +293,13 @@ const FLAG_NORMAL = [
' float flZx = uFlagAmp * (aFlag.z * flS + aFlag.y * flD * uFlagK)',
' / max(uFlagWidth, 1e-4);',
' float flZy = uFlagAmp * aFlag.y * flD * uFlagTilt;',
+ // Differentiate the shortened, sagging sheet, not only its Z ripple.
+ // The clamped shortening has zero derivative beyond the cap.
+ ' float flXx = 1.0 - (uFlagShrink * aFlag.w < uFlagMaxShrink',
+ ' ? uFlagShrink * aFlag.y * aFlag.y / max(uFlagWidth, 1e-4) : 0.0);',
+ ' float flYx = -uFlagSag * aFlag.z / max(uFlagWidth, 1e-4);',
' vNormal = normalize(normalMatrix * normalize(',
- ' vec3(-flZx, -flZy, 1.0)));',
+ ' cross(vec3(flXx, flYx, flZx), vec3(0.0, 1.0, flZy))));',
// Both in VIEW space, so a scaled or rotated flag needs no basis of
// its own: 1 square on to the eye, 0 edge-on.
' vec4 flMv = modelViewMatrix * vec4(transformed, 1.0);',
@@ -590,11 +595,18 @@ const BANNER_MOVE = [
const BANNER_NORMAL = [
'#ifndef FLAT_SHADED',
- ' float bnZx = uBanFold * aBan.z * bnE;',
- ' float bnZd = uBanFold * aBan.y * (2.0 - 2.0 * bnS)',
- ' / max(uBanDrop, 1e-4);',
- ' vNormal = normalize(normalMatrix * normalize(',
- ' vec3(-bnZx * bnC, bnSi + bnZd, bnC)));',
+ // The pendulum angle changes down the sheet, and gathering changes X.
+ // Differentiate both tangents; omitting either leaves fixed-card lighting.
+ ' float bnEd = 2.0 - 2.0 * bnS;',
+ ' float bnAd = -uBanSway * uBanLag * cos(uBanRate * uTime + uBanPhase',
+ ' - uBanLag * bnS);',
+ ' float bnFree = abs(uBanShrink * aBan.w * bnE * bnE) < uBanShrinkMax ? 1.0 : 0.0;',
+ ' vec3 bnDx = vec3(1.0 - bnFree * 0.5 * uBanFold * uBanFold',
+ ' * aBan.z * aBan.z * bnE * bnE, 0.0, uBanFold * aBan.z * bnE);',
+ ' vec3 bnDs = vec3(-bnFree * uBanShrink * aBan.w * 2.0 * bnE * bnEd,',
+ ' -uBanDrop * bnC + bnD * bnSi * bnAd,',
+ ' uBanDrop * bnSi + bnD * bnC * bnAd + uBanFold * aBan.y * bnEd);',
+ ' vNormal = normalize(normalMatrix * normalize(cross(bnDs, bnDx)));',
// View space, as the flag's: 1 square on to the eye, 0 edge-on.
' vec4 bnMv = modelViewMatrix * vec4(transformed, 1.0);',
' vBan.w = astraFacing(vNormal, -bnMv.xyz);',
@@ -934,9 +946,11 @@ const STALK_VERTEX = [
' -1.0, 1.0);',
// ONE gust field for the whole crop, scrolled downwind at a stated
// m/s: two stalks a metre apart see the same wave, a lag apart.
- ' vec2 whW = uWheatWind;',
- ' vec2 whP = vec2(dot(whRoot.xz, whW),',
- ' dot(whRoot.xz, vec2(-whW.y, whW.x)));',
+ ' vec3 whRootWorld = (modelMatrix * vec4(whRoot, 1.0)).xyz;',
+ ' vec2 whW = clothLocalDir(vec3(uWheatWind.x, 0.0, uWheatWind.y)).xz;',
+ ' whW /= max(length(whW), 1e-5);',
+ ' vec2 whP = vec2(dot(whRootWorld.xz, uWheatWind),',
+ ' dot(whRootWorld.xz, vec2(-uWheatWind.y, uWheatWind.x)));',
' vec2 whUv = vec2((whP.x - uWheatMps * uTime) * uWheatTile.x,',
' whP.y * uWheatTile.y);',
' float whWave = texture2D(uWheatWave, whUv).r;',
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 514fc51b..96d1df85 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/clouds.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/clouds.js
@@ -1,32 +1,21 @@
-// Cloud layers: ONE InstancedMesh of billboard puffs (fbm alpha, flat
-// base, sun-tinted) + optional thin cirrus streaks. three r184's Sky
-// cloud branch grid-artifacts at any high contrast — this is the layer.
+// A connected, ray-marched cloud deck with optical self-shadowing.
+// cloudTexture remains a lightweight public alpha-map helper; the sky
+// itself no longer stacks transparent camera-facing puff sprites.
import * as THREE from 'three';
import { attachDisposal, snapshotResources } from './lifecycle.js';
-import { mulberry32, fbm2 } from './noise.js';
-import { intOption, makeShaderMaterial, keepOutOfDepthPasses, option, positive, readWind, sunVector } from './shader.js';
+import { mulberry32, fbm2, bakeFbm3, dataTexture3D } from './noise.js';
+import { intOption, makeShaderMaterial, keepOutOfDepthPasses, option, positive, readWind, sunVector, makeLightProbe, vector } from './shader.js';
-// Cumulus/cirrus mood presets, graded for THIS renderer: ACES filmic at
-// exposure 1.0, sRGB out, and nothing after that rescues a dim top or
-// pulls a tint back (the post chain's bloom takes only EMISSION, which a
-// cloud has none of, and its grade is identity unless the scene asks).
-// A lit cumulus top is the brightest diffuse thing in a daylight frame,
-// so `sunColor` is a near-WHITE with a warm bias — the old 0xffc890 sun
-// tint was graded against a bloom+grade chain and lands as tan smoke
-// here (measured: cloud region (224,233,236) against a (232,239,242)
-// sky, 3% contrast). `shadeColor` is the sky-lit underside, never
-// neutral grey: it is where the blue comes from.
+// Scattering tints, multiplied by scene illumination. These are not baked
+// cloud brightness: night belongs to the light rig, not black cloud albedo.
const PRESETS = {
day: { sunColor: 0xfff4e6, shadeColor: 0x7e94b8, litGain: 1.55 },
golden: { sunColor: 0xffd0a0, shadeColor: 0x7c82ac, litGain: 1.70 },
- // A sheet, not a field of dark clumps: wide overlapping puffs at one
- // altitude, and the flattest lighting of the four.
+ // Broad overlapping density at a common altitude.
overcast: { sunColor: 0xbcc3cc, shadeColor: 0x717b8a, litGain: 1.05,
count: 40, altitude: 230, spread: 45, alpha: 0.97,
stretch: 1.9 },
- // Moonlit: dark but LIT — a cool silver top over a deep blue base,
- // never the black cut-out a plain brightness scale gives.
- night: { sunColor: 0xa8bfe0, shadeColor: 0x2c3652, litGain: 0.60,
+ night: { sunColor: 0xe0e8f0, shadeColor: 0x71839c, litGain: 0.85,
alpha: 0.88 },
};
@@ -41,28 +30,19 @@ const PRESETS = {
* higher the deeper the sun. No argument keeps the old top-lit look.
*/
function lightVector(v) {
- if (!v || !v.isVector3) return new THREE.Vector3(0, 1, 0);
- const d = v.clone().normalize();
+ const d = new THREE.Vector3(...vector(v,[0,1,0],3,'makeClouds: sunDir'));
+ if(d.lengthSq()<1e-12) throw new RangeError('makeClouds: sunDir must be nonzero');
+ d.normalize();
if (d.y >= -0.02) return d;
const el = Math.asin(-d.y); // how deep the sun is
const az = Math.atan2(-d.z, -d.x) * 180 / Math.PI; // opposite azimuth
return sunVector(az, Math.max(30, Math.min(55, 25 + el * 180 / Math.PI)));
}
-/** Seeded billowy puff: RGB stores a shading normal, alpha optical coverage.
- * The base is flat. This is a distant impostor, not a participating volume.
- */
+/** Seeded white-RGB alpha map for lightweight custom cloud sprites. */
export function cloudTexture(seed = 7, size = 256) {
- 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) {
- option(seed, null, 'cloudTexture: seed');
- intOption(size, null, 'cloudTexture: size', 16, 1024);
+ seed=option(seed,7,'cloudTexture: seed');
+ intOption(size,null,'cloudTexture: size',16,1024);
const field = new Float32Array(size * size);
const rand = mulberry32(seed);
const lobes = Array.from({length: 7}, (_,i) => ({
@@ -84,30 +64,13 @@ function puffTexture(seed, size, cirrus) {
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;
+ const k=(y*size+x)*4;
+ data[k]=data[k+1]=data[k+2]=255;
data[k+3] = (1-Math.exp(-h*2.0))*255;
}
const tex = new THREE.DataTexture(data, size, size);
@@ -117,318 +80,294 @@ function puffTexture(seed, size, cirrus) {
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);
+const QUALITY = {
+ low: { view: 40, light: 3 }, balanced: { view: 64, light: 5 },
+ high: { view: 96, light: 8 },
+};
+
+// One weather footprint for the entire deck. Overlapping masses form a
+// continuous medium instead of independently blended/sorted sprite layers.
+function weatherTexture(seed, count, area, stretch, cirrus) {
+ const size = 192, data = new Uint8Array(size * size * 4), random = mulberry32(seed);
+ const weights=new Float32Array(size*size), tops=new Float32Array(size*size), bases=new Float32Array(size*size);
+ const banks = Array.from({length: count}, () => ({
+ x: .12 + random() * .76, z: .12 + random() * .76,
+ rx: (140 + random() * 220) / area * Math.sqrt(stretch),
+ rz: (100 + random() * 160) / area / Math.sqrt(stretch),
+ angle: (random() - .5) * (cirrus ? .35 : 2.4),
+ top: .40 + random() * .58, base: random(),
+ }));
+ if(!cirrus) {
+ // Unequal connected convection towers break the one-dome-per-bank
+ // silhouette. A separate random stream preserves authored bank centres.
+ const lobes=mulberry32(seed+1973),parents=[...banks];
+ for(const bank of parents) {
+ for(let i=0;i<5;i++) {
+ const angle=lobes()*Math.PI*2, reach=.45+lobes()*.4;
+ banks.push({...bank,x:bank.x+Math.cos(angle)*bank.rx*reach,
+ z:bank.z+Math.sin(angle)*bank.rz*reach,
+ rx:bank.rx*(.35+lobes()*.3),rz:bank.rz*(.35+lobes()*.3),
+ top:.45+lobes()*.55,base:Math.max(0,Math.min(1,bank.base+(lobes()-.5)*.35))});
+ }
+ bank.top*=.72;
+ }
+ }
+ for (const b of banks) {
+ const radius = Math.max(b.rx, b.rz);
+ const loX = Math.max(0, Math.floor((b.x-radius) * size));
+ const hiX = Math.min(size-1, Math.ceil((b.x+radius) * size));
+ const loZ = Math.max(0, Math.floor((b.z-radius) * size));
+ const hiZ = Math.min(size-1, Math.ceil((b.z+radius) * size));
+ const c = Math.cos(b.angle), s = Math.sin(b.angle);
+ for (let z=loZ; z<=hiZ; z++) for (let x=loX; x<=hiX; x++) {
+ const dx=(x+.5)/size-b.x, dz=(z+.5)/size-b.z;
+ const r=Math.hypot((c*dx+s*dz)/b.rx,(-s*dx+c*dz)/b.rz);
+ const coverage=Math.max(0,1-r*r), at=z*size+x, i=at*4, weight=coverage*coverage;
+ data[i]=Math.max(data[i],Math.round(coverage*255));
+ weights[at]+=weight;tops[at]+=weight*b.top;bases[at]+=weight*b.base;
+ data[i+3]=255;
+ }
+ }
+ for(let i=0;i<weights.length;i++) if(weights[i]>0) {
+ data[i*4+1]=Math.round(tops[i]/weights[i]*255);
+ data[i*4+2]=Math.round(bases[i]/weights[i]*255);
+ }
+ const texture=new THREE.DataTexture(data,size,size);
+ texture.minFilter=texture.magFilter=THREE.LinearFilter;
+ texture.wrapS=texture.wrapT=THREE.RepeatWrapping; texture.needsUpdate=true;
+ return texture;
+}
+
+function cloudNoise(seed) {
+ const size=40, random=mulberry32(seed+851), {values}=bakeFbm3(random,size,[4,8,16],2);
+ // Periodic cellular billows supply rounded convection cells; fBm alone
+ // erodes a smooth dome into fuzzy smoke with no internal cloud structure.
+ const cells=4, features=Float32Array.from({length:cells**3*3},()=>random());
+ const wrap=i=>((i%cells)+cells)%cells;
+ const data=new Uint8Array(size**3*4);
+ for(let i=0;i<size**3;i++) {
+ const q=[(i%size+.5)/size*cells,(Math.floor(i/size)%size+.5)/size*cells,
+ (Math.floor(i/(size*size))+.5)/size*cells];
+ const base=q.map(Math.floor);let nearest=4;
+ for(let z=-1;z<=1;z++) for(let y=-1;y<=1;y++) for(let x=-1;x<=1;x++) {
+ const cell=[base[0]+x,base[1]+y,base[2]+z];
+ const k=((wrap(cell[2])*cells+wrap(cell[1]))*cells+wrap(cell[0]))*3;
+ const dx=cell[0]+features[k]-q[0],dy=cell[1]+features[k+1]-q[1],dz=cell[2]+features[k+2]-q[2];
+ nearest=Math.min(nearest,dx*dx+dy*dy+dz*dz);
}
- puff.dispose();
+ data[i*4]=Math.round(values[i*2]*255);
+ data[i*4+1]=Math.round(values[i*2+1]*255);
+ data[i*4+2]=Math.round(Math.max(0,1-Math.sqrt(nearest)/1.2)*255);data[i*4+3]=255;
}
- const tex = new THREE.DataTexture(data,tile*cols,tile*rows);
- tex.minFilter=tex.magFilter=THREE.LinearFilter;
- tex.needsUpdate=true;
- return tex;
+ return dataTexture3D(data,size);
}
+const DECK_HEAD = /* glsl */`
+precision highp sampler3D;
+uniform sampler2D uWeather;
+uniform sampler3D uNoise;
+uniform vec3 uSize, uCenter, uCameraLocal, uSunLocal, uSunDir;
+uniform vec3 uSunLight, uSkyLight, uFogColor, uViewLocal, uViewWorld;
+uniform vec2 uDrift;
+uniform mat3 uLocalToWorld;
+uniform mat4 uLocalToClip;
+uniform float uAlpha, uExtinction, uRim, uHaze, uSpread, uCirrus, uHue, uOrthographic;
+varying vec3 vLocal;
+
+float deckDensity(vec3 position) {
+ vec3 uv=(position-uCenter)/uSize+.5;
+ if(any(lessThan(uv,vec3(0)))||any(greaterThan(uv,vec3(1)))) return 0.0;
+ vec3 p=position-uCenter-vec3(uDrift.x,0,uDrift.y)*uTime;
+ vec2 broad=texture(uNoise,p/680.0).rg;
+ vec2 weatherUV=uv.xz-uDrift*uTime/uSize.xz+(broad-.5)*.045;
+ vec3 weather=texture2D(uWeather,weatherUV).rgb;
+ float bottom=weather.b*uSpread+(broad.g-.5)*.045;
+ float h=(uv.y-bottom)/max(.12,.30+weather.g*.64-bottom);
+ if(h<=0.0||h>=1.0||weather.r<.015) return 0.0;
+ vec3 q=p/mix(175.0,310.0,uCirrus);
+ q.x*=mix(1.0,.28,uCirrus); q.z*=mix(1.0,2.7,uCirrus);
+ vec3 noise=texture(uNoise,q).rgb;
+ float fine=texture(uNoise,q*3.17+vec3(.17,.31,.73)).g;
+ float body=weather.r-pow(max(h-.12,0.0),1.6)*.75;
+ float erosion=(1.0-noise.r)*.28+(1.0-noise.b)*.36+(1.0-fine)*.14;
+ float base=smoothstep(0.0,.09,h);
+ float top=1.0-smoothstep(.80,1.0,h);
+ float edge=smoothstep(0.0,.035,uv.x)*(1.0-smoothstep(.965,1.0,uv.x))
+ *smoothstep(0.0,.035,uv.z)*(1.0-smoothstep(.965,1.0,uv.z));
+ float billow=mix(.35,1.0,noise.b)*(.7+.3*noise.g);
+ return smoothstep(.015,.24,body-erosion)*billow*base*top*edge;
+}
+
+float deckShadow(vec3 p) {
+ float end=max(0.0,astraRayBox(p,uSunLocal,uCenter-uSize*.5,uCenter+uSize*.5).y);
+ // Short near-surface intervals retain detailed silver edges; longer
+ // intervals sample the rest of the cloud rather than repeating local shade.
+ float opticalDepth=0.0;
+ float metric=length(uLocalToWorld*uSunLocal);
+ for(int i=0;i<DECK_LIGHT_STEPS;i++) {
+ float a=float(i)/float(DECK_LIGHT_STEPS),b=float(i+1)/float(DECK_LIGHT_STEPS);
+ float start=a*a*end,stop=b*b*end;
+ opticalDepth+=deckDensity(p+uSunLocal*(start+stop)*.5)*(stop-start)*metric*uExtinction;
+ }
+ return opticalDepth;
+}
+
+float deckPhase(float cosine,float g) {
+ return (1.0-g*g)/pow(max(.025,1.0+g*g-2.0*g*cosine),1.5);
+}
+`;
+
/**
- * Cumulus layer as ONE instanced billboard mesh (one draw call).
- * opts: seed, preset ('day'|'golden'|'overcast'|'night'), count, area,
- * altitude, spread, sunDir (THREE.Vector3 toward the sun — the lit side
- * follows it, and a sun already below the horizon becomes the moon),
- * sunColor, shadeColor, alpha, wind (m/s along +x), rim (silver-lining
- * strength, 0.55), haze (how far the deck may recede into scene.fog,
- * 0.22 — the fog COLOUR is always the scene's), hueVariance (0.13).
- * Animate cloud drift from your update: `layer.userData.update(t)`.
+ * One ray-marched 3D cloud deck, with connected density, optical extinction,
+ * self-shadowing and forward scattering. Seed/count/area/altitude/spread keep
+ * their authored placement roles; individual billboard puffs are no longer used.
+ * Defaults: area 2600 m, altitude 260 m, spread 120 m, count 14. `alpha` scales
+ * optical depth (zero is off); `quality` low/balanced/high changes integration
+ * steps only. `wind` accepts the shared world-XZ wind forms. `sunDir` is a world
+ * vector toward the light; a below-horizon sun selects the corresponding moon.
+ * Preset and sunColor/shadeColor tint the actual scene key/fill illumination.
+ * `litGain`, `rim`, `haze`, `stretch`, `hueVariance` remain optional controls.
+ *
+ * update(t) accepts absolute seconds. The returned Mesh owns its two textures
+ * and supports idempotent disposal. Parent transforms affect the authored deck.
+ * This is a distant atmospheric layer: it does not cast terrain shadows or
+ * truncate integration at geometry embedded inside its density. Opaque geometry
+ * entirely in front/behind is tested against the first participating sample.
+ * Log-depth hosts retain proxy depth. Cost is higher than the former sprites;
+ * use quality:'low' for previews, 'high' for large cloud close-ups.
*/
export function makeClouds(opts = {}) {
- const p = PRESETS[opts.preset || 'day'] || PRESETS.day;
- const seed = option(opts.seed, 7, 'makeClouds: seed');
- const count = intOption(opts.count, p.count ?? 14, 'makeClouds: count', 0, 1000);
- const area = positive(opts.area, 2600, 'makeClouds: area');
- const altitude = option(opts.altitude, p.altitude ?? 260, 'makeClouds: altitude');
- const spread = option(opts.spread, p.spread ?? 120, 'makeClouds: spread', 0);
- const alpha = option(opts.alpha, p.alpha ?? 0.92, 'makeClouds: alpha', 0, 1);
- const wind = readWind(opts.wind, 3.0, 'makeClouds wind').strength;
- const stretch = positive(opts.stretch, p.stretch ?? 1.0, 'makeClouds: stretch');
- const rand = mulberry32(seed);
- const rnd2 = mulberry32(seed + 977);
- const puffs = [];
- for (let c = 0; c < count; c++) {
- const cx = (rand() - 0.5) * area;
- const cz = (rand() - 0.5) * area - area * 0.18;
- const cy = altitude + (rand() - 0.5) * spread;
- const w = 130 + rand() * 240;
- const n = 5 + Math.floor(rand() * 5);
- const cluster = [];
- for (let q = 0; q < n; q++) {
- const t = (q + 0.5) / n - 0.5;
- cluster.push({
- x: cx + t * w * (1.5 + rand() * 0.5),
- y: cy + (rand() - 0.35) * w * 0.22 - Math.abs(t) * w * 0.3,
- z: cz + (rand() - 0.5) * w * 0.35,
- s: w * (0.55 + rand() * 0.5) * (1 - Math.abs(t) * 0.75),
- b: 0.75 + rand() * 0.25,
- ph: rand() * Math.PI * 2,
- h: 0,
- });
- }
- // A CROWN over the middle of the row. A single line of puffs is a
- // caterpillar, not a cumulus: the silhouette a cumulus is recognised
- // by is a flat base under a stack of smaller lobes.
- // Its own stream, so adding the crown did not reshuffle the deck a
- // caller already framed a shot around.
- const crown = 1 + Math.floor(rnd2() * 3);
- for (let q = 0; q < crown; q++) {
- const t = (rnd2() - 0.5) * 0.55;
- const up = 0.30 + rnd2() * 0.34;
- cluster.push({
- x: cx + t * w * 1.6,
- y: cy + w * up * 0.55,
- z: cz + (rnd2() - 0.5) * w * 0.3,
- s: w * (0.36 + rnd2() * 0.30),
- b: 0.85 + rnd2() * 0.15,
- ph: rnd2() * Math.PI * 2,
- h: 0,
- });
- }
- // Where each puff sits inside ITS OWN cluster, 0 at the base and 1
- // at the crown. Without it every billboard carries the same top-lit
- // gradient and a cluster reads as a bag of identical blobs instead
- // of one mass with a shaded underside — the single biggest tell of
- // billboard clouds.
- const lo = Math.min(...cluster.map((q) => q.y));
- const hi = Math.max(...cluster.map((q) => q.y));
- for (const q of cluster) {
- q.h = (q.y - lo) / Math.max(1e-3, hi - lo);
- puffs.push(q);
- }
- }
- const geo = new THREE.PlaneGeometry(1, 1);
- const inst = new THREE.InstancedBufferGeometry();
- inst.index = geo.index;
- // `position` stays at the ORIGIN and the corner offsets ride a custom
- // attribute: GTAOPass redraws the scene with an override material that
- // does NOT run this vertex shader, so a real 1x1 quad here burns a
- // hard-edged black rectangle into AO at world origin (measured).
- inst.attributes.position = new THREE.BufferAttribute(
- new Float32Array(geo.attributes.position.count * 3), 3);
- inst.setAttribute('aCorner', geo.attributes.position);
- inst.attributes.uv = geo.attributes.uv;
- inst.instanceCount = puffs.length;
- const off = new Float32Array(puffs.length * 3);
- const sc = new Float32Array(puffs.length * 2);
- const ex = new Float32Array(puffs.length * 3);
- puffs.forEach((q, i) => {
- off[i * 3] = q.x; off[i * 3 + 1] = q.y; off[i * 3 + 2] = q.z;
- sc[i * 2] = q.s * stretch; sc[i * 2 + 1] = q.s * 0.62 / Math.max(1, stretch * 0.45);
- ex[i * 3] = q.b; ex[i * 3 + 1] = q.ph; ex[i * 3 + 2] = q.h;
- });
- inst.setAttribute('iOff', new THREE.InstancedBufferAttribute(off, 3));
- inst.setAttribute('iScale', new THREE.InstancedBufferAttribute(sc, 2));
- inst.setAttribute('iExtra', new THREE.InstancedBufferAttribute(ex, 3));
- // Toward the sun. `sunDir` was documented and then ignored: every puff
- // was lit from straight up, so a low sun and a high sun painted the
- // same cloud. Default +Y keeps that old top-lit behaviour when a
- // caller has no rig to hand.
- const sunDir = lightVector(opts.sunDir);
- const mat = makeShaderMaterial({
- name: opts.name || 'CumulusLayer',
- transparent: true,
- depthWrite: false,
- // NOT three's fog. A cloud deck sits 300-1500 m out, and a scene's
- // FogExp2 is authored for scene-scale geometry: at the density a
- // 120 m courtyard uses (0.0035) the whole deck resolves to 100% fog
- // colour — measured, the layer above was invisible on this host
- // (darkest cloud pixel = the fog colour exactly). The layer opts out
- // of the chunk and mixes its OWN bounded aerial perspective toward
- // `fogColor` below, so it still recedes into the scene's haze and in
- // the scene's hue, but never disappears into it.
- fog: false,
- uniforms: {
- // three refreshes these itself once `mat.fog = true` (below) —
- // the shader keeps the scene's fog COLOUR and density without
- // taking three's fog blend.
- ...THREE.UniformsUtils.clone(THREE.UniformsLib.fog),
- 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 },
- uRim: { value: opts.rim ?? 0.55 },
- uHazeMax: { value: opts.haze ?? 0.22 },
- uHazeScale: { value: 0.35 },
- uHue: { value: opts.hueVariance ?? 0.13 },
- uSunColor: {
- value: new THREE.Color(opts.sunColor ?? p.sunColor),
- },
- uShade: {
- value: new THREE.Color(opts.shadeColor ?? p.shadeColor),
- },
+ const p=PRESETS[opts.preset||'day']||PRESETS.day, cirrus=opts._cirrus===true;
+ const seed=option(opts.seed,7,'makeClouds: seed');
+ const count=intOption(opts.count,p.count??14,'makeClouds: count',0,1000);
+ const area=positive(opts.area,2600,'makeClouds: area');
+ const altitude=option(opts.altitude,p.altitude??260,'makeClouds: altitude');
+ const spread=option(opts.spread,p.spread??120,'makeClouds: spread',0);
+ const stretch=positive(opts.stretch,p.stretch??1,'makeClouds: stretch');
+ const alpha=option(opts.alpha,p.alpha??.92,'makeClouds: alpha',0,1);
+ const gain=option(opts.litGain,p.litGain,'makeClouds: litGain',0);
+ const rim=option(opts.rim,.55,'makeClouds: rim',0);
+ const haze=option(opts.haze,.22,'makeClouds: haze',0,1);
+ const hue=option(opts.hueVariance,.13,'makeClouds: hueVariance',0,1);
+ const wind=readWind(opts.wind,3,'makeClouds wind');
+ const quality=opts.quality??'balanced';
+ if(!Object.hasOwn(QUALITY,quality)) throw new RangeError('makeClouds: quality must be low, balanced or high');
+ const tier=QUALITY[quality];
+ const thickness=cirrus?Math.max(45,spread*.55):Math.max(140,spread+170);
+ const size=new THREE.Vector3(area,thickness,area);
+ const center=new THREE.Vector3(0,altitude+thickness*.2,-area*.18);
+ const sun=lightVector(opts.sunDir), sunTint=new THREE.Color(opts.sunColor??p.sunColor);
+ const skyTint=new THREE.Color(opts.shadeColor??p.shadeColor);
+ const weather=weatherTexture(seed,count,area,stretch,cirrus), noise=cloudNoise(seed);
+ const material=makeShaderMaterial({
+ name:opts.name||'CloudDeckMaterial',transparent:true,depthWrite:false,
+ side:THREE.BackSide,fog:false,
+ defines:{DECK_STEPS:tier.view,DECK_LIGHT_STEPS:tier.light},
+ uniforms:{
+ uWeather:{value:weather},uNoise:{value:noise},uSize:{value:size},uCenter:{value:center},
+ uCameraLocal:{value:new THREE.Vector3()},uSunLocal:{value:sun.clone()},uSunDir:{value:sun},
+ uSunLight:{value:new THREE.Color()},uSkyLight:{value:new THREE.Color()},
+ uFogColor:{value:new THREE.Color()},uDrift:{value:new THREE.Vector2(wind.x,wind.z)},
+ uViewLocal:{value:new THREE.Vector3()},uViewWorld:{value:new THREE.Vector3()},
+ uOrthographic:{value:0},
+ uWind:{value:wind.strength},uAlpha:{value:alpha},uRim:{value:rim},uHaze:{value:haze},
+ uExtinction:{value:(cirrus?.006:.035)*alpha},uSpread:{value:Math.min(.28,spread/thickness*.4)},
+ uCirrus:{value:cirrus?1:0},uHue:{value:hue},
+ uLocalToWorld:{value:new THREE.Matrix3()},uLocalToClip:{value:new THREE.Matrix4()},
},
- varyings: [
- 'varying vec2 vUv; varying vec3 vExtra;',
- 'varying vec2 vSun; varying float vDepth; varying float vSunZ;',
- ].join('\n'),
- vertexHead: [
- 'attribute vec3 aCorner;',
- 'attribute vec3 iOff; attribute vec2 iScale; attribute vec3 iExtra;',
- '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;',
- // Half the puffs wear the puff texture mirrored: one alpha map
- // repeated at N scales is a recognisable stamp, and a free u-flip
- // doubles the silhouettes. The base cut runs in v, so mirroring u
- // 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 = uCameraRight;',
- ' vec3 up = uCameraUp;',
- ' vec3 p = iOff + vec3(uTime * uWind',
- ' + sin(iExtra.y + uTime * 0.05) * 6.0, 0.0, 0.0);',
- ' 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(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
- ' vSun.x *= 1.0 - 2.0 * flip;',
- // ...and whether it is in front of or behind the deck. A cloud
- // seen against the sun is a DARK body with a burning rim; the
- // 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.
- ' vSunZ = dot(uSunLocal, uCameraForward);',
- ' vDepth = -(modelViewMatrix * vec4(transformed, 1.0)).z;',
- ].join('\n'),
- fragmentHead: [
- 'uniform sampler2D map; uniform vec3 uSunColor; uniform vec3 uShade;',
- 'uniform float uAlpha; uniform float uLitGain; uniform float uRim;',
- 'uniform float uHazeMax; uniform float uHazeScale; uniform float uHue;',
- 'uniform vec3 fogColor;',
- 'uniform float fogDensity; uniform float fogNear; uniform float fogFar;',
- ].join('\n'),
- fragmentMain: [
- ' 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.
- ' 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;',
- ' 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.
- ' col = astraHueBreak(col, vUv * 2.2 + vExtra.y * 6.3, 1.0, uHue);',
- // Bounded aerial perspective (see the `fog: false` note above).
- ' float hz = 0.0;',
- '#ifdef USE_FOG',
- '#ifdef FOG_EXP2',
- ' float fd = fogDensity * uHazeScale * vDepth;',
- ' hz = 1.0 - exp(-fd * fd);',
- '#else',
- ' hz = clamp((vDepth - fogNear) / max(fogFar - fogNear, 1e-4),',
- ' 0.0, 1.0) * uHazeScale * 2.0;',
- '#endif',
- '#endif',
- ' col = mix(col, fogColor, clamp(hz, 0.0, 1.0) * uHazeMax);',
- // A cloud is one long smooth ramp across hundreds of pixels: at 8
- // bits that bands. One LSB of hash noise costs nothing and kills
- // the rings.
- ' col += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.004;',
- ' gl_FragColor = vec4(col, a * uAlpha);',
- ].join('\n'),
+ varyings:'varying vec3 vLocal;',vertexMain:'vLocal=position;',fragmentHead:DECK_HEAD,
+ fragmentMain: /* glsl */`
+ if(uAlpha<=0.0) discard;
+ vec3 direction=uOrthographic>.5?uViewLocal:normalize(vLocal-uCameraLocal);
+ float metric=length(uLocalToWorld*direction);
+ vec3 origin=uCameraLocal;
+ if(uOrthographic>.5) origin=vLocal-direction*
+ (dot(uLocalToWorld*(vLocal-uCameraLocal),uViewWorld)/max(metric,1e-8));
+ vec2 hit=astraRayBox(origin,direction,uCenter-uSize*.5,uCenter+uSize*.5);
+ float start=max(0.0,hit.x),end=hit.y;
+ if(end<=start) discard;
+ float stepSize=(end-start)/float(DECK_STEPS);
+ vec3 worldDirection=normalize(uLocalToWorld*direction);
+ float cosine=dot(worldDirection,uSunDir);
+ float phase=min(3.5,.85*deckPhase(cosine,.62)+.15*deckPhase(cosine,-.22));
+ float jitter=.15+.7*astraHash21(gl_FragCoord.xy);
+ float transmittance=1.0;
+ vec3 radiance=vec3(0),first=origin+direction*end;
+ bool found=false;
+ for(int i=0;i<DECK_STEPS;i++) {
+ vec3 point=origin+direction*(start+(float(i)+jitter)*stepSize);
+ float density=deckDensity(point);
+ if(density>.001) {
+ if(!found){first=point;found=true;}
+ float tau=deckShadow(point);
+ float direct=exp(-tau);
+ float multiple=.30*exp(-tau*.25)+.10*exp(-tau*.065);
+ float height=clamp((point.y-uCenter.y)/uSize.y+.5,0.0,1.0);
+ vec3 source=uSunLight*(direct*(.30+phase*uRim*.5)+multiple)
+ +uSkyLight*(.45+.55*height);
+ float tint=sin(dot(point,vec3(.006,.011,.009)))*uHue*.08;
+ source*=vec3(1.0+tint,1.0,1.0-tint);
+ float opacity=1.0-exp(-density*uExtinction*stepSize*metric);
+ radiance+=transmittance*opacity*source;
+ transmittance*=1.0-opacity;
+ if(transmittance<.008) break;
+ }
+ }
+ float opacity=1.0-transmittance;
+ if(opacity<.003) discard;
+ vec3 color=radiance/max(opacity,.001);
+ float distance=length(uLocalToWorld*(first-uCameraLocal));
+ color=mix(color,uFogColor,uHaze*(1.0-exp(-distance/3500.0)));
+ #ifndef USE_LOGDEPTHBUF
+ gl_FragDepth=astraClipDepth(uLocalToClip,first);
+ #endif
+ gl_FragColor=vec4(color,opacity);
+ `,
});
- // Opted out of three's fog BLEND, opted in to its fog UNIFORMS: this
- // is what makes the renderer keep fogColor/fogDensity current.
- mat.fog = true;
- const mesh = new THREE.Mesh(inst, mat);
- mesh.name = opts.name || 'CumulusLayer';
- mesh.frustumCulled = false;
- const inverse = new THREE.Matrix4();
- mesh.onBeforeRender = (_renderer, _scene, camera) => {
+ const mesh=new THREE.Mesh(new THREE.BoxGeometry(...size.toArray()).translate(...center.toArray()),material);
+ mesh.name=opts.name||'CumulusLayer';
+ mesh.visible=count>0;
+ mesh.userData.sceneBackdrop='sky';
+ keepOutOfDepthPasses(mesh);
+ const before=mesh.onBeforeRender,readLights=makeLightProbe(),inverse=new THREE.Matrix4();
+ const drift=new THREE.Vector3(wind.x,0,wind.z),localDrift=new THREE.Vector3();
+ const inverseLinear=new THREE.Matrix3();
+ mesh.onBeforeRender=(...args)=>{
+ before.apply(mesh,args);
+ const scene=args[1],camera=args[2],u=material.uniforms;
+ const lights=readLights(scene);
+ if(opts.sunDir==null && lights.sun) sun.copy(lights.sunDirection);
+ u.uSunLight.value.setRGB(0,0,0);
+ if(lights.sun) u.uSunLight.value.copy(sunTint).multiply(lights.sun.color)
+ .multiplyScalar(gain*lights.sun.intensity/(opts.preset==='night'?2.2:5.4));
+ const fill=c=>lights.ambient[c]+lights.sky[c]*.8+lights.ground[c]*.2+lights.environment*.12;
+ u.uSkyLight.value.setRGB(fill('r'),fill('g'),fill('b')).multiply(skyTint);
+ u.uFogColor.value.copy(scene.fog?.color||u.uSkyLight.value);
inverse.copy(mesh.matrixWorld).invert();
- 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);
+ camera.getWorldPosition(u.uCameraLocal.value).applyMatrix4(inverse);
+ camera.getWorldDirection(u.uViewWorld.value);
+ u.uViewLocal.value.copy(u.uViewWorld.value).transformDirection(inverse);
+ u.uOrthographic.value=camera.isOrthographicCamera?1:0;
+ u.uSunLocal.value.copy(sun).transformDirection(inverse);
+ u.uLocalToWorld.value.setFromMatrix4(mesh.matrixWorld);
+ inverseLinear.setFromMatrix4(inverse);
+ localDrift.copy(drift).applyMatrix3(inverseLinear);u.uDrift.value.set(localDrift.x,localDrift.z);
+ u.uLocalToClip.value.copy(camera.projectionMatrix).multiply(camera.matrixWorldInverse).multiply(mesh.matrixWorld);
};
- mesh.userData.update = (t) => {
- if (!Number.isFinite(t)) throw new RangeError('CloudLayer.update: time must be finite');
- mat.uniforms.uTime.value = t;
+ mesh.userData.update=t=>{
+ if(!Number.isFinite(t)) throw new RangeError('CloudLayer.update: time must be finite');
+ material.uniforms.uTime.value=t;
};
- const owned = snapshotResources(mesh);
- owned.add(mat.uniforms.map.value);
- return attachDisposal(keepOutOfDepthPasses(mesh), owned);
+ mesh.userData.quality=quality;
+ mesh.userData.steps={...tier};
+ const owned=snapshotResources(mesh);owned.add(weather);owned.add(noise);
+ return attachDisposal(mesh,owned);
}
-/**
- * Thin high-altitude streaks — the same instanced billboard layer,
- * stretched flat and thinned out.
- * opts: seed, preset, count, area, altitude, sunDir, sunColor.
- */
+/** Thin, wind-stretched high-altitude ice-cloud deck; same options as makeClouds. */
export function makeCirrus(opts = {}) {
- // Reuses the proven cumulus billboard shader as stretched streaks —
- // Sprites rendered as black slabs under the post chain (measured on
- // the manhattan run), and tilted planes went edge-on from low cams.
- const seed = option(opts.seed, 23, 'makeCirrus: seed');
- // Ice, not water: whiter and cooler than the cumulus of the same hour,
- // and thin enough that the light comes THROUGH — hence the wide rim.
- // Derived from the PRESET rather than fixed, or a night deck gets a
- // daylight-white streak across it (measured on the night render: the
- // cirrus band read as a light leak over a deep blue sky).
- const p = PRESETS[opts.preset || 'day'] || PRESETS.day;
- const white = new THREE.Color(0xffffff);
- const ice = new THREE.Color(p.sunColor).lerp(white, 0.35);
- const veil = new THREE.Color(p.shadeColor).lerp(white, 0.55);
- return makeClouds({
- // Its own name: two layers called CumulusLayer collide in the
- // census and in the viewer's find-by-name.
- 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.44,
- wind: opts.wind ?? 6.0,
- litGain: (opts.litGain ?? p.litGain) * 0.85,
- sunColor: opts.sunColor ?? ice.getHex(),
- shadeColor: opts.shadeColor ?? veil.getHex(),
- sunDir: opts.sunDir,
- rim: opts.rim ?? 0.85,
- hueVariance: opts.hueVariance ?? 0.08,
- stretch: opts.stretch ?? 4.5,
- });
+ return makeClouds({preset:'day',...opts,_cirrus:true,name:opts.name??'CirrusLayer',
+ seed:opts.seed??23,count:opts.count??8,area:opts.area??3200,
+ altitude:opts.altitude??520,spread:opts.spread??100,alpha:opts.alpha??.44,
+ wind:opts.wind??6,stretch:opts.stretch??4.5,rim:opts.rim??.85});
}
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/damp.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/damp.js
index 9cb84131..a63a2962 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/damp.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/damp.js
@@ -308,7 +308,10 @@ export function patchMoss(material, opts = {}) {
' * (1.0 - msK) * max(msLie, 0.35);',
// The material just OUTSIDE the edge stays damp under the growth.
' float msLip = (1.0 - msK)',
- ' * smoothstep(msT - 0.55, msT - 0.02, msD);',
+ // Keep the edge shadow inside positive growth. A fixed subtraction
+ // made this threshold negative at high coverage, darkening dry,
+ // sun-facing walls even though both moss and lichen were absent.
+ ' * smoothstep(msT * 0.40, msT - 0.02, msD);',
// `amount` 0 is OFF, which a threshold alone cannot say: a deep
// enough crevice would clear any threshold. Declared here with
// the rest of the MASK, so everything above this line is scalar
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 9dd026a7..2ccb57dd 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/environment.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/environment.js
@@ -565,6 +565,9 @@ export const PRACTICAL = Object.freeze({ emissiveIntensity: 3.0, intensity: 1.5,
* the moon. `sunDir` still reports the authored (below-horizon) sun so
* `makeSky()` paints twilight/night on it; `lightDir` is the vector the
* shadow light actually uses (equal to `sunDir` by day).
+ * An explicit night mood with an above-horizon direction uses that
+ * direction for the moon; `skySunDir` supplies the set sun to both
+ * the environment bake and `makeSky()`.
*
* @param {object} [opts]
* `mood` one of `day | golden | night | overcast` (default `day`;
@@ -582,13 +585,13 @@ export const PRACTICAL = Object.freeze({ emissiveIntensity: 3.0, intensity: 1.5,
* on, except overcast).
* @returns {{sun: THREE.DirectionalLight, fill: THREE.HemisphereLight,
* envTex: THREE.DataTexture, sunDisc: THREE.Mesh|null,
- * sunDir: THREE.Vector3, lightDir: THREE.Vector3, night: boolean,
+ * sunDir: THREE.Vector3, skySunDir: THREE.Vector3, lightDir: THREE.Vector3, night: boolean,
* moonDir: THREE.Vector3|null, mood: string}}
* Add `sun`, `fill` (and `sunDisc` when present) to the scene and
* assign `envTex` to `scene.environment`. The sun aims at the origin.
* `sunDir` is the normalized sun vector — for a physical atmosphere
* dome hand the whole rig to `makeSky(scene, { rig })` from ./sky.js,
- * which slaves the dome to this vector and hides the flat disc (the
+ * which uses `skySunDir` and hides the flat disc (the
* Preetham shader draws its own sun; a night rig's moon disc stays).
*/
export function sunRig(opts = {}) {
@@ -737,8 +740,13 @@ export function sunRig(opts = {}) {
// it at the skyline the way hills occlude a low sun.
let sunDisc = null;
if (opts.disc === undefined ? rig.disc : opts.disc) {
+ // The moon subtends about half a degree, independent of sky radius.
+ // Keep the existing daytime disc grade; only the moon was oversized.
+ const discRadius = night
+ ? radius * 0.9 * Math.tan(THREE.MathUtils.degToRad(0.52 / 2))
+ : radius * 0.012;
sunDisc = new THREE.Mesh(
- new THREE.CircleGeometry(radius * (night ? 0.007 : 0.012), 24),
+ new THREE.CircleGeometry(discRadius, night ? 48 : 24),
new THREE.MeshBasicMaterial({
color: rig.discColor, fog: false, depthWrite: false,
}));
@@ -751,6 +759,6 @@ export function sunRig(opts = {}) {
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,
+ return { sun, fill, envTex, sunDisc, sunDir: dir.clone(), skySunDir: skySun.clone(), lightDir,
night, moonDir, mood: moodName, dispose:lifecycle.userData.dispose };
}
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 42337345..5c41a34e 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flock.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flock.js
@@ -330,7 +330,7 @@ function flockMaterial(o) {
' stroke = sin(vPhase + q.x * 2.6);',
' cl = stroke * 0.15 * (0.32 + 0.68 * (0.5 - q.x * 0.5));',
' h = 0.30 * sqrt(max(0.0, 1.0 - q.x * q.x))',
- ' + 0.26 * smoothstep(-0.55, -1.0, q.x);',
+ ' + 0.26 * (1.0 - smoothstep(-1.0, -0.55, q.x));',
' }',
' float d = abs(q.y - cl);',
// A bird is a handful of pixels: without gradient-width
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 52d86588..7768672a 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flowers.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flowers.js
@@ -27,7 +27,7 @@
import * as THREE from 'three';
import { attachDisposal, snapshotResources } from './lifecycle.js';
-import { windOf } from './grass.js';
+import { WIND_GUST_GLSL, windOf } from './grass.js';
import { patchTranslucency } from './finish.js';
import { patchLeafSSS } from './foliage_shade.js';
import { mulberry32 } from './noise.js';
@@ -384,21 +384,22 @@ const PLANT_VERTEX_HEAD = [
'attribute vec4 iVar;',
'varying vec4 vFlow;',
'varying vec3 vFlowVar;',
- glslLocalDir('flowLocalDir'),
+ glslLocalDir('flowLocalDir'), WIND_GUST_GLSL,
// The gust field grass.js rides: streaks running downwind, so a
// scene's meadow and its flowers are pushed by the same air.
'float flowSway(vec3 root, float ph, float lag) {',
- ' vec2 w = uFlowWind;',
+ ' vec3 worldRoot = (modelMatrix * vec4(root, 1.0)).xyz;',
' float t = uTime * uFlowSpeed;',
- ' float s = astraStagger(ph + root.x * 0.07 + root.z * 0.11);',
+ ' float s = astraWindPhase(worldRoot, ph);',
' return (sin(t * 1.7 + s - lag)',
' + 0.35 * sin(t * 2.9 + s * 1.7 - lag)) / 1.35;',
'}',
'vec2 flowBend(vec3 root, vec4 b) {',
- ' vec2 w = uFlowWind;',
- ' vec2 q = vec2(dot(root.xz, w), dot(root.xz, vec2(-w.y, w.x)));',
- ' float t = uTime * uFlowSpeed;',
- ' float gust = astraFbm2(vec2(q.x * 0.055 - t * 0.5, q.y * 0.21), 2);',
+ ' vec2 w = flowLocalDir(vec3(uFlowWind.x, 0.0, uFlowWind.y)).xz;',
+ ' w /= max(length(w), 1e-5);',
+ ' vec3 worldRoot = (modelMatrix * vec4(root, 1.0)).xyz;',
+ ' float gust = astraWindGust(worldRoot, uFlowWind,',
+ ' uTime * uFlowSpeed, vec2(0.055, 0.21));',
' float push = (0.25 + 1.25 * gust)',
' * (0.62 + 0.38 * flowSway(root, b.w, 0.0));',
' return vec2(cos(b.y), sin(b.y)) * b.z + w * (b.x * push);',
@@ -469,7 +470,7 @@ const PLANT_VERTEX = [
'#endif',
' } else {',
// The head is heavy, so it nods a beat BEHIND the stem it sits on.
- ' vec3 flUp = normalize(flT + vec3(uFlowWind.x, 0.0, uFlowWind.y)',
+ ' vec3 flUp = normalize(flT + flowLocalDir(vec3(uFlowWind.x, 0.0, uFlowWind.y))',
' * (uFlowNod * flowSway(flRoot, iBend.w, 0.9)));',
' vec3 flRef = abs(flUp.z) < 0.9 ? vec3(0.0, 0.0, 1.0)',
' : vec3(1.0, 0.0, 0.0);',
@@ -763,15 +764,29 @@ export function makeFalling(opts = {}) {
g.name = opts.name || 'Falling';
g.add(keepOutOfDepthPasses(mesh));
g.userData.update = g.userData.tick = (t) => tickShaders(g, t);
+ const driftFrame = new THREE.Matrix3(), localDrift = new THREE.Vector3();
g.userData.sample = (i, t) => {
+ // Match fallLocalDir's inverse linear map and singular cutoff, even
+ // when a caller changes an ancestor before the next render.
+ mesh.updateWorldMatrix(true, false);
+ driftFrame.setFromMatrix4(mesh.matrixWorld);
+ const m = driftFrame.elements;
+ const magnitude = Math.hypot(m[0], m[1], m[2])
+ * Math.hypot(m[3], m[4], m[5]) * Math.hypot(m[6], m[7], m[8]);
+ if (Math.abs(driftFrame.determinant()) <= Math.max(magnitude * 1e-7, 1e-30)) {
+ localDrift.set(0, 0, 0);
+ } else {
+ localDrift.set(drift.x, 0, drift.y).applyMatrix3(driftFrame.invert());
+ }
const k = Math.min(count - 1, Math.max(0, i | 0));
const y = (pos[k * 3 + 1] - fall * fal[k * 4] * t) % drop;
return new THREE.Vector3(
- _wrap(pos[k * 3] + drift.x * t, lim)
+ _wrap(pos[k * 3] + localDrift.x * t, lim)
+ wob * wobX(swing[k * 4], swing[k * 4 + 1], t),
(y < 0 ? y + drop : y) + span,
- _wrap(pos[k * 3 + 2] + drift.y * t, lim)
- + wob * wobZ(swing[k * 4 + 2], swing[k * 4 + 3], t));
+ _wrap(pos[k * 3 + 2] + localDrift.z * t, lim)
+ + wob * wobZ(swing[k * 4 + 2], swing[k * 4 + 3], t))
+ .applyMatrix4(mesh.matrix); // Piece center in the advertised group frame.
};
return attachDisposal(g, snapshotResources(g));
}
@@ -848,7 +863,7 @@ const FALL_VERTEX_HEAD = [
// is a constant — so this patch runs last and supplies the truth.
'varying vec3 vAstraWorld;',
'varying vec3 vAstraWorldN;',
- _FALL_WOB_GLSL,
+ _FALL_WOB_GLSL, glslLocalDir('fallLocalDir'),
].join('\n');
const FALL_VERTEX = [
@@ -857,7 +872,8 @@ const FALL_VERTEX = [
// Every piece wraps inside the stated box: its own fall rate down,
// the shared wind across, its own slide on top of that.
' float flY = mod(aPos.y - uFallRate * aFall.x * uTime, uFallDrop);',
- ' vec2 flXZ = mod(aPos.xz + uFallDrift * uTime + uFallLim,',
+ ' vec2 flDrift = fallLocalDir(vec3(uFallDrift.x, 0.0, uFallDrift.y)).xz;',
+ ' vec2 flXZ = mod(aPos.xz + flDrift * uTime + uFallLim,',
' 2.0 * uFallLim) - uFallLim + uFallWob * flW;',
' vec3 flP = vec3(flXZ.x, flY + uFallFoot, flXZ.y);',
// The tumble axis lies IN the leaf, so the face turns edge-on and
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 ee2c22e1..74af4857 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 { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
import { attachDisposal, snapshotResources } from './lifecycle.js';
import { lehmer } from './noise.js';
@@ -253,37 +254,6 @@ function fieldRadius(shafts, dir) {
return r;
}
-/** Every shaft in one geometry, tagged by `aShaft` so they differ. */
-function mergeShafts(parts) {
- let nv = 0, ni = 0;
- for (const p of parts) {
- nv += p.geometry.attributes.position.count;
- ni += p.geometry.index.count;
- }
- const pos = new Float32Array(nv * 3), nor = new Float32Array(nv * 3);
- const uv = new Float32Array(nv * 2), tag = new Float32Array(nv);
- const idx = new Uint32Array(ni);
- let v = 0, k = 0;
- for (const p of parts) {
- const a = p.geometry.attributes;
- pos.set(a.position.array, v * 3);
- nor.set(a.normal.array, v * 3);
- uv.set(a.uv.array, v * 2);
- for (let i = 0; i < a.position.count; i++) tag[v + i] = p.tag;
- const src = p.geometry.index.array;
- for (let i = 0; i < src.length; i++) idx[k + i] = src[i] + v;
- v += a.position.count;
- k += src.length;
- }
- const g = new THREE.BufferGeometry();
- g.setAttribute('position', new THREE.BufferAttribute(pos, 3));
- g.setAttribute('normal', new THREE.BufferAttribute(nor, 3));
- g.setAttribute('uv', new THREE.BufferAttribute(uv, 2));
- g.setAttribute('aShaft', new THREE.BufferAttribute(tag, 1));
- g.setIndex(new THREE.BufferAttribute(idx, 1));
- return g;
-}
-
/** The beams themselves: swept tubes carrying a volume integral. */
function shaftMesh(shafts, dir, color, air, soft, gain, hazy) {
const parts = shafts.map((s, i) => ({
@@ -307,8 +277,14 @@ function shaftMesh(shafts, dir, color, air, soft, gain, hazy) {
},
{ nu: 28, nv: 22 }),
}));
+ for (const { geometry, tag } of parts) {
+ geometry.setAttribute('aShaft', new THREE.BufferAttribute(
+ new Float32Array(geometry.attributes.position.count).fill(tag), 1));
+ }
+ const geometry = mergeGeometries(parts.map((p) => p.geometry));
+ for (const part of parts) part.geometry.dispose();
const mesh = new THREE.Mesh(
- mergeShafts(parts),
+ geometry,
shaftMaterial(dir, color, air, soft, gain, hazy));
mesh.name = 'Shafts';
mesh.renderOrder = 3;
@@ -349,17 +325,18 @@ function shaftMaterial(dir, color, air, soft, gain, hazy) {
uSoft: { value: 1.0 + 2.0 * Math.min(Math.max(soft, 0), 1) },
uGain: { value: gain },
},
- varyings: 'varying vec2 vUv; varying vec3 vN; varying vec3 vW;'
+ varyings: 'varying vec2 vUv; varying vec3 vN; varying vec3 vW; varying vec3 vDir;'
+ ' varying float vShaft;',
- vertexHead: 'attribute float aShaft;',
+ vertexHead: 'attribute float aShaft; uniform vec3 uDir;',
vertexMain: [
' vUv = uv;',
' vShaft = aShaft;',
' vN = inverseTransformDirection(normalize(normalMatrix * normal), viewMatrix);',
' vW = (modelMatrix * vec4(transformed, 1.0)).xyz;',
+ ' vDir = normalize(mat3(modelMatrix) * uDir);',
].join('\n'),
fragmentHead: 'uniform vec3 uColor; uniform vec3 uAir;'
- + ' uniform float uAirMix; uniform vec3 uDir;'
+ + ' uniform float uAirMix;'
+ ' uniform float uSoft;'
+ ' uniform float uGain;',
fragmentMain: [
@@ -371,8 +348,8 @@ function shaftMaterial(dir, color, air, soft, gain, hazy) {
' float chord = pow(face, uSoft);',
// |n.v| is the chord only ACROSS the beam; looking down it
// the walls turn edge-on while the real chord grows.
- ' float axial = abs(dot(eye, uDir));',
- ' chord *= 1.0 / max(sqrt(1.0 - axial * axial), 0.62);',
+ ' float axial = abs(dot(eye, normalize(vDir)));',
+ ' chord *= 1.0 / max(sqrt(max(0.0, 1.0 - axial * axial)), 0.62);',
' float sd = astraStagger(vShaft);',
// Sampled on a circle so the pattern has no seam where the
// section closes, and drifts far slower ALONG than across.
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 cfebed4c..1d711a24 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/grass.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/grass.js
@@ -38,6 +38,18 @@ const BLADE_ROWS = 4;
const LOCAL_DIR = glslLocalDir('grassLocalDir');
+// Shared by grass, flowers, reeds and canopy. Sample in world metres, then
+// carry the direction into each plant's local frame before bending it.
+export const WIND_GUST_GLSL = [
+ 'float astraWindGust(vec3 root, vec2 wind, float time, vec2 scale) {',
+ ' vec2 p = vec2(dot(root.xz, wind), dot(root.xz, vec2(-wind.y, wind.x)));',
+ ' return astraFbm2(p * scale - vec2(time * 0.5, 0.0), 2);',
+ '}',
+ 'float astraWindPhase(vec3 root, float phase) {',
+ ' return astraStagger(phase + root.x * 0.07 + root.z * 0.11);',
+ '}',
+].join('\n');
+
/**
* Cover a patch of ground in grass.
*
@@ -306,7 +318,7 @@ const BLADE_HEAD = [
'attribute vec4 iVar;',
'varying vec3 vGrass;',
'varying vec2 vGrassW;',
- LOCAL_DIR,
+ LOCAL_DIR, WIND_GUST_GLSL,
].join('\n');
const BLADE_VERTEX = [
@@ -314,15 +326,14 @@ const BLADE_VERTEX = [
' float grV = aCorner.y;',
// Gusts are streaks running downwind, so the field is compressed
// ALONG the wind and travels with it; across it, structure is fine.
- ' vec2 grW = uGrassWind;',
- ' vec2 grP = vec2(dot(grBase.xz, grW),',
- ' dot(grBase.xz, vec2(-grW.y, grW.x)));',
- ' float grGust = astraFbm2(',
- ' vec2(grP.x * 0.055 - uTime * uGrassSpeed * 0.5, grP.y * 0.21), 2);',
+ ' vec3 grRootWorld = (modelMatrix * vec4(grBase, 1.0)).xyz;',
+ ' vec2 grW = grassLocalDir(vec3(uGrassWind.x, 0.0, uGrassWind.y)).xz;',
+ ' grW /= max(length(grW), 1e-5);',
+ ' float grGust = astraWindGust(grRootWorld, uGrassWind,',
+ ' uTime * uGrassSpeed, vec2(0.055, 0.21));',
// Neighbours out of phase: offsets under a full turn leave a whole
// row nodding in step.
- ' float grPh = astraStagger(iVar.y + grBase.x * 0.07',
- ' + grBase.z * 0.11);',
+ ' float grPh = astraWindPhase(grRootWorld, iVar.y);',
' float grT = uTime * uGrassSpeed;',
' float grS = (sin(grT * 2.1 + grPh)',
' + 0.35 * sin(grT * 3.7 + grPh * 1.7)) / 1.35;',
@@ -365,7 +376,7 @@ const BLADE_VERTEX = [
// it reads the same coordinate, so a straw patch is straw in both,
// and a value that moved with the gust would make the field's colour
// slide about under the wind.
- ' vGrassW = (modelMatrix * vec4(grBase, 1.0)).xz;',
+ ' vGrassW = grRootWorld.xz;',
// Dryness swings at the METRE as well as per blade. The clump field
// already dries the thin ground, but a meadow also goes to straw in
// bands that have nothing to do with how dense it is — sun, drainage,
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 af43c9a4..d264c054 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/neon.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/neon.js
@@ -21,6 +21,7 @@
import { attachDisposal, snapshotResources } from './lifecycle.js';
import * as THREE from 'three';
+import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
import {
keepOutOfDepthPasses, makeShaderMaterial, patchStandard, sweepProfile,
@@ -189,34 +190,6 @@ function frames(pts) {
return out;
}
-/** Concatenate position / normal / uv geometries into one draw. */
-function mergeGeoms(list) {
- let nv = 0, ni = 0;
- for (const g of list) {
- nv += g.attributes.position.count;
- ni += g.index.count;
- }
- const pos = new Float32Array(nv * 3), nor = new Float32Array(nv * 3);
- const uv = new Float32Array(nv * 2), idx = new Uint32Array(ni);
- let v = 0, k = 0;
- for (const g of list) {
- const a = g.attributes;
- pos.set(a.position.array, v * 3);
- nor.set(a.normal.array, v * 3);
- uv.set(a.uv.array, v * 2);
- const src = g.index.array;
- for (let i = 0; i < src.length; i++) idx[k + i] = src[i] + v;
- v += a.position.count;
- k += src.length;
- }
- const out = new THREE.BufferGeometry();
- out.setAttribute('position', new THREE.BufferAttribute(pos, 3));
- out.setAttribute('normal', new THREE.BufferAttribute(nor, 3));
- out.setAttribute('uv', new THREE.BufferAttribute(uv, 2));
- out.setIndex(new THREE.BufferAttribute(idx, 1));
- return out;
-}
-
/** One stroke as a swept circular section around its own frame. */
function tubeGeometry(st, radius, nu) {
const nv = st.length - 1;
@@ -283,7 +256,7 @@ function tubeMaterial(name, color, gain, core, hot, flicker, key, hazy,
varyings:
'varying vec3 vNeonN; varying vec3 vNeonW; varying vec2 vNeonUv;',
vertexMain: [
- ' vNeonN = normalize(mat3(modelMatrix) * normal);',
+ ' vNeonN = inverseTransformDirection(normalize(normalMatrix * normal), viewMatrix);',
' vNeonW = (modelMatrix * vec4(transformed, 1.0)).xyz;',
' vNeonUv = uv;',
].join('\n'),
@@ -414,9 +387,10 @@ export function makeNeonTube(opts = {}) {
/** One merged mesh for every stroke at one radius. */
function shell(st, radius, nu, material, name, order) {
- const mesh = new THREE.Mesh(
- mergeGeoms(st.map((s) => tubeGeometry(s.frames, radius, nu))),
- material);
+ const parts = st.map((s) => tubeGeometry(s.frames, radius, nu));
+ const geometry = mergeGeometries(parts);
+ for (const part of parts) part.dispose();
+ const mesh = new THREE.Mesh(geometry, material);
mesh.name = name;
mesh.renderOrder = order;
return mesh;
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 9bfd8766..4c16fa33 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rain.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rain.js
@@ -13,7 +13,7 @@
import * as THREE from 'three';
import { attachDisposal, snapshotResources } from './lifecycle.js';
import { mulberry32, fbm2, noiseDataTexture } from './noise.js';
-import { intOption, makeShaderMaterial, keepOutOfDepthPasses, option, positive, readWind, vector } from './shader.js';
+import { instancedQuad, intOption, makeShaderMaterial, keepOutOfDepthPasses, option, positive, readWind, vector } from './shader.js';
const _UP = new THREE.Vector3(0, 1, 0);
@@ -46,29 +46,14 @@ const _AIR_GLSL = [
'}',
].join('\n');
-/**
- * Build the instanced quad geometry every effect here draws with.
- *
- * `position` is deliberately ZERO and the corners travel in `aCorner`:
- * the render chain's GTAO pass re-draws the scene with an override
- * material that ignores these shaders, and a real unit quad then
- * printed a black AO slab at the world origin.
- *
- * @param {number} count Instances.
- * @returns {THREE.InstancedBufferGeometry} Degenerate quad with
- * `aCorner` + `uv`, instanceCount set.
- */
-function _quads(count) {
- const geo = new THREE.PlaneGeometry(1, 1);
- const verts = geo.attributes.position.count;
- const inst = new THREE.InstancedBufferGeometry();
- inst.index = geo.index;
- inst.setAttribute('position',
- new THREE.BufferAttribute(new Float32Array(verts * 3), 3));
- inst.setAttribute('aCorner', geo.attributes.position);
- inst.attributes.uv = geo.attributes.uv;
- inst.instanceCount = count;
- return inst;
+/** Raycaster includes invisible meshes and children of hidden groups. */
+function visibleHit(hit) {
+ for (let object = hit.object; object; object = object.parent) {
+ if (!object.visible) return false;
+ }
+ const material = Array.isArray(hit.object.material)
+ ? hit.object.material[hit.face?.materialIndex ?? 0] : hit.object.material;
+ return material?.visible !== false;
}
/**
@@ -143,7 +128,7 @@ export function makeRain(opts = {}) {
'makeRain: shelterUpdateDistance');
const groundY = option(opts.groundY, -1e8, 'makeRain: groundY');
const rand = mulberry32(seed);
- const inst = _quads(count);
+ const inst = instancedQuad(count);
const off = new Float32Array(count * 3);
const ext = new Float32Array(count * 3);
for (let i = 0; i < count; i++) {
@@ -351,9 +336,7 @@ function makeShelterAtlas(mesh, cfg) {
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;
+ if (!visibleHit(hit)) continue;
hitLocal.copy(hit.point).applyMatrix4(inverse);
height = Math.max(height, hitLocal.y);
break;
@@ -482,6 +465,7 @@ function _impactPoints(opts, rand) {
const ray = new THREE.Raycaster(
new THREE.Vector3(), new THREE.Vector3(0, -1, 0));
const nm = new THREE.Matrix3();
+ const surfaceMatrix = new THREE.Matrix4();
const out = [];
// Rejections (steep faces, undersides) re-sample; the budget stops a
// scene whose only "surface" is a wall from looping forever.
@@ -501,11 +485,18 @@ function _impactPoints(opts, rand) {
if (surfaces.length) {
ray.ray.origin.set(x, top, z);
for (const h of ray.intersectObjects(surfaces, true)) {
- if (h.face) { hit = h; break; }
+ if (h.face && visibleHit(h)) { hit = h; break; }
}
}
if (hit) {
- nm.getNormalMatrix(hit.object.matrixWorld);
+ // InstancedMesh raycasts return geometry-local face normals. Include
+ // the individual transform before the object's world normal matrix,
+ // or tilted instances splash flat and steep ones evade maxSlopeDeg.
+ if (hit.instanceId !== undefined) {
+ hit.object.getMatrixAt(hit.instanceId, surfaceMatrix);
+ surfaceMatrix.premultiply(hit.object.matrixWorld);
+ } else surfaceMatrix.copy(hit.object.matrixWorld);
+ nm.getNormalMatrix(surfaceMatrix);
const n = hit.face.normal.clone().applyMatrix3(nm).normalize();
if (n.y < minNy) continue;
out.push({ p: hit.point.clone().addScaledVector(n, lift), n });
@@ -658,7 +649,7 @@ export function makeSplashes(opts = {}) {
' gl_FragColor = vec4(c, a);',
].join('\n'),
});
- const rings = new THREE.Mesh(attrs(_quads(n)), ringMat);
+ const rings = new THREE.Mesh(attrs(instancedQuad(n)), ringMat);
rings.name = 'SplashRings';
rings.frustumCulled = false;
rings.renderOrder = 2;
@@ -732,7 +723,7 @@ export function makeSplashes(opts = {}) {
' gl_FragColor = vec4(c, a);',
].join('\n'),
});
- const crowns = new THREE.Mesh(attrs(_quads(n)), crownMat);
+ const crowns = new THREE.Mesh(attrs(instancedQuad(n)), crownMat);
crowns.name = 'SplashCrowns';
crowns.frustumCulled = false;
crowns.renderOrder = 3;
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 83903113..956e53bb 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/shader.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/shader.js
@@ -1599,13 +1599,16 @@ export function planarCapture(mesh, capture, {
* A reader for the lights an effect shades itself with, reused per draw:
* `const readLights = makeLightProbe(); const l = readLights(scene, near);`
* Over the VISIBLE lights with intensity > 0 it returns (one reused object):
- * `sun` the strongest directional light and `sunDirection` the world unit
+ * `sun` the directional light with the greatest linear luminance and
+ * `sunDirection` the world unit
* vector toward it (position minus target; +Y without a sun); `ambient`,
* `sky` and `ground` the summed ambient colour and hemisphere sky/ground
* colours, each times intensity (linear); `environment` the scene
* environment's intensity (0 without one); and, when `near` (a world
- * Vector3) is given, `point` the point light with the most
- * intensity / distance² there. Each effect applies its own calibration.
+ * Vector3) is given, `point` the point light with the greatest attenuated
+ * luminance there, using Three's decay and smooth distance cutoff.
+ * Black lights and lights beyond their cutoff cannot displace a visible
+ * source. Each effect applies its own calibration after selection.
*/
export function makeLightProbe() {
const probe = {
@@ -1613,21 +1616,31 @@ export function makeLightProbe() {
ambient: new THREE.Color(), sky: new THREE.Color(), ground: new THREE.Color(),
};
const at = new THREE.Vector3(), target = new THREE.Vector3(), scratch = new THREE.Color();
+ const luminance = (color) => .2126 * color.r + .7152 * color.g + .0722 * color.b;
return (scene, near = null) => {
- let score = -1;
+ let sunScore = 0, pointScore = 0;
probe.sun = probe.point = null;
probe.ambient.setRGB(0, 0, 0); probe.sky.setRGB(0, 0, 0); probe.ground.setRGB(0, 0, 0);
scene.traverseVisible((light) => {
if (!light.isLight || !(light.intensity > 0)) return;
const i = light.intensity;
- if (light.isDirectionalLight && (!probe.sun || i > probe.sun.intensity)) probe.sun = light;
+ if (light.isDirectionalLight) {
+ const score = i * luminance(light.color);
+ if (score > sunScore) { sunScore = score; probe.sun = light; }
+ }
else if (light.isAmbientLight) probe.ambient.add(scratch.copy(light.color).multiplyScalar(i));
else if (light.isHemisphereLight) {
probe.sky.add(scratch.copy(light.color).multiplyScalar(i));
probe.ground.add(scratch.copy(light.groundColor).multiplyScalar(i));
} else if (near && light.isPointLight) {
- const s = i / Math.max(.01, light.getWorldPosition(at).distanceToSquared(near));
- if (s > score) { score = s; probe.point = light; }
+ const distance = light.getWorldPosition(at).distanceTo(near);
+ // Same attenuation as Three's getDistanceAttenuation: selection
+ // must not prefer a nearby lamp whose range has already ended.
+ const cutoff = light.distance > 0
+ ? Math.max(0, 1 - (distance / light.distance) ** 4) ** 2 : 1;
+ const score = i * luminance(light.color) * cutoff
+ / Math.max(.01, distance ** light.decay);
+ if (score > pointScore) { pointScore = score; probe.point = light; }
}
});
probe.sunDirection.set(0, 1, 0);
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 c9aa3868..6d2f3859 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sky.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sky.js
@@ -132,7 +132,7 @@ export function skyRadiance(dir, sunDir, opts = {}) {
/**
* Build the atmosphere dome, add it to the scene, null the
* background, and return the normalized sun vector for the key light.
- * Sun precedence: `rig` (slaves to rig.sunDir; hides the rig's flat
+ * Sun precedence: `rig` (uses the rig's baked skySunDir; hides its flat
* disc — the Preetham shader draws its own; a NIGHT rig's disc is the
* moon and stays) > `sunDir` (normalized copy, input untouched) >
* `elevationDeg`/`azimuthDeg` (same convention as `sunRig()`).
@@ -151,7 +151,9 @@ export function skyRadiance(dir, sunDir, opts = {}) {
* half-extent driver (default 4500).
* @returns {{sky: THREE.Mesh, sunDir: THREE.Vector3}} The dome
* (already in the scene) and the normalized sun direction — place
- * the key light at `sunDir * distance`, aimed at the origin.
+ * the key light at `sunDir * distance`, aimed at the origin. With a
+ * rig, this preserves its authored `sunDir` (the moon for an explicit
+ * night mood); the dome uses the rig's separate `skySunDir`.
*/
export function makeSky(scene, opts = {}) {
const sky = new Sky();
@@ -171,7 +173,9 @@ export function makeSky(scene, opts = {}) {
let sunDir;
if (opts.rig && opts.rig.sunDir) {
- sunDir = opts.rig.sunDir.clone().normalize();
+ // A night rig's above-horizon direction belongs to the moon. Use
+ // the same set-sun direction that the rig baked into its environment.
+ sunDir = (opts.rig.skySunDir || opts.rig.sunDir).clone().normalize();
// The Preetham shader draws its own solar disc; the rig's flat
// CircleGeometry disc on the same vector would double the sun. A
// night rig's disc is the MOON on another vector: it stays.
@@ -182,6 +186,8 @@ export function makeSky(scene, opts = {}) {
sunDir = sunVector(opts.azimuthDeg === undefined ? 135 : opts.azimuthDeg,
opts.elevationDeg === undefined ? 15 : opts.elevationDeg);
}
+ const reportedSunDir = opts.rig?.sunDir
+ ? opts.rig.sunDir.clone().normalize() : sunDir;
u.sunPosition.value.copy(sunDir);
// r184 Sky ships value-noise clouds ON by default — grid artifacts
// at readable contrast. Clouds come from ./clouds.js instead.
@@ -256,8 +262,9 @@ export function makeSky(scene, opts = {}) {
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;
+ reportedSunDir.copy(sunDir);
+ return reportedSunDir;
};
sky.userData.setSunDirection = setSunDirection;
- return { sky, sunDir, setSunDirection, dispose: sky.userData.dispose };
+ return { sky, sunDir: reportedSunDir, 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 599aa37b..c2cb9b00 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smalllife.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smalllife.js
@@ -24,7 +24,7 @@ import { attachDisposal, snapshotResources } from './lifecycle.js';
import { mulberry32 } from './noise.js';
// One reader, so a scene's meadow, its reeds and its trees
// cannot drift apart on the same `wind` option.
-import { windOf } from './grass.js';
+import { WIND_GUST_GLSL, windOf } from './grass.js';
import {
glslLocalDir, instancedQuad, makeShaderMaterial, patchStandard, readVec3,
shadowLike, tickShaders, unit,
@@ -403,7 +403,7 @@ function insectMaterial(kind, size, drift, color) {
// the same flash is a beetle, and at full strength it landed on
// the day frame as a white speck that read as a dirty lens.
' float dim = 1.0 - clamp(dot(uLight, vec3(0.5)), 0.0, 1.0);',
- ' float lit = clamp(pulse * (0.4 + 0.6 * smoothstep(0.5, 0.0, d))',
+ ' float lit = clamp(pulse * (0.4 + 0.6 * (1.0 - smoothstep(0.0, 0.5, d)))',
' * (0.25 + 0.75 * dim), 0.0, 1.0);',
' col = mix(body * uLight, hot, lit);',
' }',
@@ -654,7 +654,7 @@ const STEM_HEAD = [
'varying vec4 vReedVar;',
'varying vec2 vReedW;',
'varying float vReedPart;',
- glslLocalDir('reedLocalDir'),
+ glslLocalDir('reedLocalDir'), WIND_GUST_GLSL,
].join('\n');
const STEM_VERTEX = [
@@ -664,13 +664,12 @@ const STEM_VERTEX = [
' 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.
- ' vec2 rdW = uReedWind;',
- ' vec2 rdP = vec2(dot(rdRoot.xz, rdW),',
- ' dot(rdRoot.xz, vec2(-rdW.y, rdW.x)));',
+ ' vec3 rdRootWorld = (modelMatrix * vec4(rdRoot, 1.0)).xyz;',
+ ' vec2 rdW = reedLocalDir(vec3(uReedWind.x, 0.0, uReedWind.y)).xz;',
+ ' rdW /= max(length(rdW), 1e-5);',
' float rdT = uTime * uReedSpeed;',
- ' float rdGust = astraFbm2(vec2(rdP.x * 0.055 - rdT * 0.5,',
- ' rdP.y * 0.21), 2);',
- ' float rdPh = astraStagger(iVar.x + rdRoot.x * 0.07 + rdRoot.z * 0.11);',
+ ' float rdGust = astraWindGust(rdRootWorld, uReedWind, rdT, vec2(0.055, 0.21));',
+ ' float rdPh = astraWindPhase(rdRootWorld, iVar.x);',
' float rdSway = (sin(rdT * uReedRate.x + rdPh)',
' + 0.35 * sin(rdT * uReedRate.x * 1.8 + rdPh * 1.7)) / 1.35;',
// Under water: one slow sine, no harmonic, and late — the surface has
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 316e6213..3a7fb90b 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/submerged.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/submerged.js
@@ -49,11 +49,17 @@ const seedOffset = (seed) => new THREE.Vector2(seedLattice(seed) * 0.091,
* coefficients given outright (THREE.Vector3 or [r, g, b], per metre).
*/
function extinctionVec(value) {
- if (value && value.isVector3) return value.clone();
- if (Array.isArray(value)) {
- return new THREE.Vector3(value[0] || 0, value[1] || 0, value[2] || 0);
+ const channels = value?.isVector3 ? value.toArray() : Array.isArray(value) ? value : null;
+ if (channels) {
+ if (channels.length !== 3 || !channels.every(k => Number.isFinite(k) && k >= 0)) {
+ throw new RangeError('patchUnderwater: extinction requires three finite nonnegative coefficients');
+ }
+ return new THREE.Vector3(...channels);
+ }
+ const k = value === undefined ? 0.35 : value;
+ if (!Number.isFinite(k) || k < 0) {
+ throw new RangeError('patchUnderwater: extinction must be finite and nonnegative');
}
- const k = value === undefined ? 0.35 : Math.max(0, value);
return EXT_RATIO.clone().multiplyScalar(k);
}
@@ -184,7 +190,7 @@ const UNDER_BODY = [
* 0); `color` THREE.Color or hex the water goes toward (default a
* green-blue); `extinction` per-metre loss — a scalar on water's own
* spectrum (default 0.35) or a THREE.Vector3 / [r, g, b] of
- * coefficients outright; `murk` how far drifting silt swings the
+ * finite nonnegative coefficients outright; `murk` how far drifting silt swings the
* path length AND its colour, 0..1 (default 0.5); `light` how much
* light there is for the column to scatter, 1 = open daylight
* (default 1; 0.15..0.3 under a night sky, more under a lamp);
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 c0333813..5accf700 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
@@ -43,7 +43,7 @@
*/
import {
- patchStandard, glslAxes, glslTriNoise, seedVec3,
+ patchStandard, glslAxes, glslCurv, glslTriNoise, seedVec3,
toColor, unit, worldBase,
} from './shader.js';
@@ -53,6 +53,7 @@ import {
const WEAR_HEAD = [
glslAxes('astraWearAxes'),
glslTriNoise('astraWearNoise', 13.7, 41.3, 71.9),
+ glslCurv('astraWearCurv'),
].join('\n');
// On the world varyings terrain_shade and waterside share, so a material
@@ -132,16 +133,20 @@ export function patchMicroBreakup(material, opts = {}) {
// fades, or the mid one aliases across a floor at grazing angle
// while the fine one is already gone.
' float mbFw = length(fwidth(mbP));',
- ' float mbGm = 1.0 - smoothstep(0.35, 1.00, mbFw * 2.03);',
- ' float mbG = 1.0 - smoothstep(0.35, 1.00, mbFw * 4.1);',
+ // Filter each field toward its mean BEFORE either brightness or
+ // hue reads it. Filtering only brightness left coloured static at
+ // grazing angles, and even the coarsest octave aliases far away.
+ ' mbLo = mix(0.5, mbLo, 1.0 - smoothstep(0.35, 1.00, mbFw));',
+ ' mbMi = mix(0.5, mbMi, 1.0 - smoothstep(0.35, 1.00, mbFw * 2.03));',
+ ' mbHi = mix(0.5, mbHi, 1.0 - smoothstep(0.35, 1.00, mbFw * 4.1));',
// Value noise clusters around 0.5, so it is centred and stretched
// to reach the strength asked for; three octaves rather than two
// because a surface with one blotch size and one grain size is
// still a pattern, and the clamp keeps `strength` a hard bound
// however they stack.
' float mbV = clamp((mbLo - 0.5) * 2.4',
- ' + (mbMi - 0.5) * 1.5 * mbGm',
- ' + (mbHi - 0.5) * 1.6 * mbG, -1.0, 1.0);',
+ ' + (mbMi - 0.5) * 1.5',
+ ' + (mbHi - 0.5) * 1.6, -1.0, 1.0);',
// WARM/COOL, not a hue rotation: rotating about the grey axis
// leaves a neutral exactly unchanged, and stone, plaster and
// concrete are most of what this rides on. Warm where the sun has
@@ -228,16 +233,10 @@ export function patchEdgeWear(material, opts = {}) {
].join('\n'),
fragmentBody: [
' vec3 ewN = normalize(vAstraWorldN);',
- ' vec3 ewPx = dFdx(vAstraWorld);',
- ' vec3 ewPy = dFdy(vAstraWorld);',
- ' vec3 ewNx = dFdx(ewN);',
- ' vec3 ewNy = dFdy(ewN);',
// Curvature in 1/m: how far the normal turns per metre the
// surface travels under one pixel. Positive is convex, and only
// the convex half wears.
- ' float ewD = dot(ewPx, ewPx) + dot(ewPy, ewPy);',
- ' float ewC = (dot(ewNx, ewPx) + dot(ewNy, ewPy))',
- ' / max(ewD, 1e-12);',
+ ' float ewC = astraWearCurv(ewN, vAstraWorld);',
' float ewR = 1.0 / uEdgeWidth;',
' float ewK = smoothstep(ewR, ewR * 3.0, ewC);',
// Rubbing is patchy and FINE, at TWO scales. The ramp above is
@@ -261,7 +260,7 @@ export function patchEdgeWear(material, opts = {}) {
// warm/cool spread, so no two worn patches are the same colour.
' float ewL = dot(diffuseColor.rgb, vec3(0.2126, 0.7152, 0.0722));',
' vec3 ewThin = mix(diffuseColor.rgb, vec3(ewL), 0.45) * 1.16;',
- ' float ewT = (ewF - 0.5) * 0.24;',
+ ' float ewT = (ewF - 0.5) * ewG * 0.24;',
' vec3 ewBare = uEdgeColor * (0.86 + 0.24 * ewP)',
' * vec3(1.0 + ewT, 1.0 + ewT * 0.15, 1.0 - ewT);',
' vec3 ewTone = mix(ewThin, ewBare, smoothstep(0.35, 0.90, ewK));',
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 82d4ec41..c9e828a5 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/terrain.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/terrain.js
@@ -29,6 +29,23 @@ export function triangleValue(position, nx, ny, gx, gy, component) {
+ value(a + 1) * (1 - fy) + value(a + nx + 1) * (1 - fx);
}
+// Ground and cliff share the same seeded, periodic bilinear lattice. Keep
+// wrapping here: a tiny negative coordinate can round up to N after adding N.
+function latticeSampler(rand) {
+ const N = 32, lat = new Float32Array(N * N);
+ for (let i = 0; i < lat.length; i++) lat[i] = rand();
+ const wrap = (t) => { let w = t % N; if (w < 0) w += N; return w >= N ? w - N : w; };
+ return (u, v) => {
+ const uu = wrap(u), vv = wrap(v);
+ const i0 = Math.floor(uu), j0 = Math.floor(vv);
+ const fx = uu - i0, fz = vv - j0;
+ const i1 = (i0 + 1) % N, j1 = (j0 + 1) % N;
+ const a = lat[j0 * N + i0], b = lat[j0 * N + i1];
+ const c = lat[j1 * N + i0], d = lat[j1 * N + i1];
+ return (a * (1 - fx) + b * fx) * (1 - fz) + (c * (1 - fx) + d * fx) * fz;
+ };
+}
+
/**
* Build a displaced, textured ground plane and its height function.
*
@@ -50,24 +67,8 @@ export function ground(opts = {}) {
const relief = opts.relief === undefined ? 6 : opts.relief;
const scale = opts.scale || 90;
- // A small seeded lattice, bilinearly sampled: the same field drives the
- // mesh and the height function, so they cannot drift apart.
- const N = 32;
- const lat = new Float32Array(N * N);
- for (let i = 0; i < N * N; i++) lat[i] = rand();
- const sample = (x, z) => {
- // wrap into [0, N): `u + N` for a u of -1e-16 rounds to N itself (below one ulp of 32),
- // and lat[j * N + N] is the next row or undefined — measured 2026-09-08, 15 NaN vertices
- // in an outskirts ring where the polar grid's x came out as -1.5e-14 (D71)
- const wrap = (t) => { let w = t % N; if (w < 0) w += N; return w >= N ? w - N : w; };
- const uu = wrap(x / scale), vv = wrap(z / scale);
- const i0 = Math.floor(uu), j0 = Math.floor(vv);
- const fx = uu - i0, fz = vv - j0;
- const i1 = (i0 + 1) % N, j1 = (j0 + 1) % N;
- const a = lat[j0 * N + i0], b = lat[j0 * N + i1];
- const c = lat[j1 * N + i0], d = lat[j1 * N + i1];
- return (a * (1 - fx) + b * fx) * (1 - fz) + (c * (1 - fx) + d * fx) * fz;
- };
+ const lattice = latticeSampler(rand);
+ const sample = (x, z) => lattice(x / scale, z / scale);
const fieldHeight = (x, z) => {
let n = sample(x, z) * 0.65 + sample(x * 2.9, z * 2.9) * 0.35;
@@ -181,20 +182,7 @@ export function cliff(opts = {}) {
const bands = bandColors.length;
const bandH = height / bands;
- // One seeded lattice drives the mesh, the band edges AND faceAt, so
- // none of them can drift apart (the same trick ground() uses).
- const N = 32;
- const lat = new Float32Array(N * N);
- for (let i = 0; i < N * N; i++) lat[i] = rand();
- const sample = (u, v) => {
- const uu = ((u % N) + N) % N, vv = ((v % N) + N) % N;
- const i0 = Math.floor(uu), j0 = Math.floor(vv);
- const fx = uu - i0, fz = vv - j0;
- const i1 = (i0 + 1) % N, j1 = (j0 + 1) % N;
- const a = lat[j0 * N + i0], b = lat[j0 * N + i1];
- const c = lat[j1 * N + i0], d = lat[j1 * N + i1];
- return (a * (1 - fx) + b * fx) * (1 - fz) + (c * (1 - fx) + d * fx) * fz;
- };
+ const sample = latticeSampler(rand);
// Per-band ledge offsets and a few meandering gullies, all seeded up
// front so faceAt closes over the exact numbers the mesh used.
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 97704829..c786e98f 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
@@ -335,7 +335,9 @@ export function patchSlopeSplat(material, opts = {}) {
// room ACES needs and lets the drift break show.
uSplatSnow: { value: toColor(opts.snow, 0xcbc9c4) },
uSplatLow: { value: Math.max(low, high) },
- uSplatHigh: { value: Math.min(low, high) },
+ // Equal slope thresholds otherwise make the snow-holding smoothstep
+ // divide by zero, even though the grass/rock ramps still have a blend.
+ uSplatHigh: { value: Math.min(low, high, Math.max(low, high) - 1e-4) },
uSplatBlend: { value: Math.max(1e-3, blend) },
uSplatSnowY: { value: Number.isFinite(line) ? line : SNOW_OFF },
// A band that cannot RESOLVE against the off-sentinel makes a
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 51ba30a5..5d408395 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/water.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/water.js
@@ -16,7 +16,7 @@
import * as THREE from 'three';
import { attachDisposal, snapshotResources } from './lifecycle.js';
import { Water } from 'three/addons/objects/Water.js';
-import { planarCapture, sunVector } from './shader.js';
+import { makeLightProbe, planarCapture, sunVector } from './shader.js';
// Battery-graded freeze point: mid-phase, waves clearly formed.
const FROZEN_TIME = 7.3;
@@ -30,8 +30,8 @@ const _DAY_SUN = sunVector(35, 48);
/**
* Synthesize the tiling wave-normal DataTexture the Water shader
* needs (npm three ships no waternormals.jpg). A sum of integer-
- * frequency sines guarantees a seamless wrap; finite differences at
- * strength 2.2 turn the heightfield into tangent-space normals.
+ * frequency sines guarantees a seamless wrap; finite differences use
+ * a fixed UV-space strength, independent of texture resolution.
*
* @param {number} [size] Texture width and height in px (default 256).
* @returns {THREE.DataTexture} RGBA, RepeatWrapping, needsUpdate set.
@@ -76,7 +76,10 @@ export function makeWaterNormals(size = 256, opts = {}) {
}
// Finite-difference normals -> RGB.
const data = new Uint8Array(size * size * 4);
- const amp = 2.2; // normal strength (the battery-graded value)
+ // A central difference spans 2/size in UV. Preserve the graded 256px
+ // slopes while changing resolution; without the texel-spacing factor,
+ // doubling quality halved every wave slope and flattened the water.
+ const amp = 2.2 * (size / 256);
for (let y = 0; y < size; y++) {
for (let x = 0; x < size; x++) {
const xm = (x - 1 + size) % size, xp = (x + 1) % size;
@@ -221,23 +224,8 @@ function _regrade(material) {
*
* Only uniforms the caller did NOT pin are touched.
*/
-const _V1 = new THREE.Vector3();
-const _V2 = new THREE.Vector3();
-
-function _readScene(scene, uniforms, pinned) {
- let key = null, keyLum = -1, hemi = null, amb = null;
- scene.traverseVisible((o) => {
- if (o.isDirectionalLight) {
- const c = o.color;
- const l = o.intensity
- * (c.r * 0.2126 + c.g * 0.7152 + c.b * 0.0722);
- if (l > keyLum) { keyLum = l; key = o; }
- } else if (o.isHemisphereLight) {
- if (!hemi || o.intensity > hemi.intensity) hemi = o;
- } else if (o.isAmbientLight) {
- if (!amb || o.intensity > amb.intensity) amb = o;
- }
- });
+function _readScene(lights, uniforms, pinned) {
+ const { sun: key, sunDirection, ambient, sky } = lights;
// three's Lambert BRDF divides irradiance by PI; the water body is a
// Lambert term too, so the same 1/PI is what puts it on the same scale
// as every MeshStandardMaterial around it.
@@ -256,24 +244,14 @@ function _readScene(scene, uniforms, pinned) {
uniforms.sunColor.value.copy(c).multiplyScalar(1 / peak);
}
if (!pinned.sunDir) {
- // A directional light aims from its world position at its TARGET,
- // and a rig that moved the target (a low sun tracked onto a
- // subject) would otherwise hand the glitter a direction the
- // shadows do not use. An un-parented target sits at the origin,
- // which is exactly what `position` alone assumes.
- const p = _V1.setFromMatrixPosition(key.matrixWorld);
- const q = key.target
- ? _V2.setFromMatrixPosition(key.target.matrixWorld)
- : _V2.set(0, 0, 0);
- p.sub(q);
- if (p.lengthSq() > 1e-12) uniforms.sunDirection.value.copy(p).normalize();
+ uniforms.sunDirection.value.copy(sunDirection);
}
}
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);
+ // Hemisphere and ambient irradiance add, as they do on nearby PBR
+ // surfaces. Selecting one dropped fill light whenever a sky rig existed.
+ t.copy(ambient).add(sky).multiplyScalar(INV_PI);
t.r = Math.min(t.r, 1); t.g = Math.min(t.g, 1); t.b = Math.min(t.b, 1);
}
}
@@ -384,12 +362,13 @@ export function makeOcean(width, depth, opts = {}) {
ambient: opts.ambient !== undefined,
};
const base = water.onBeforeRender;
+ const readLights = makeLightProbe();
let first = true;
// Water's plane calculation assumes a rigid matrix; planarCapture
// supplies one while keeping Water's world-space textureMatrix (unlike
// Reflector, Water does not project mesh-local positions).
planarCapture(water, (renderer, scene, camera) => {
- _readScene(scene, uniforms, pinned);
+ _readScene(readLights(scene), uniforms, pinned);
if (first) {
first = false;
// The mirror target is 8-bit LINEAR (three disables tone mapping
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 647530dd..a463aa35 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/watermist.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/watermist.js
@@ -160,8 +160,8 @@ export function makeWaterMist(opts = {}) {
// mist-free control: the bank's own contribution over the wall came
// back to 5.3/255 where the hard-edged 9 gave 5.9.
const hits = Math.max(1, (count * cardW) / extent);
- const alpha = Math.min(0.60, Math.max(0.004,
- 16.0 * (1 - Math.pow(1 - density, 1 / hits))));
+ const alpha = Math.min(0.60,
+ 16.0 * (1 - Math.pow(1 - density, 1 / hits)));
// Wisps scale with the bank's own height, not with the reach: a
// pattern stretched to the extent reads as one printed backdrop.
const wisp = Math.min(Math.max(top * 1.2, 0.8), extent * 0.28);
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 25e7c5df..e864906b 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/woodland.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/woodland.js
@@ -610,6 +610,7 @@ function imposterMaterial(cfg) {
// front/back test below needs it here too, and dedupeUniforms
// keeps the two declarations from colliding.
'uniform vec3 uImpSun;',
+ glslLocalDir('impLocalDir'),
].join('\n'),
vertexMain: [
' vImpUv = uv;',
@@ -629,8 +630,10 @@ function imposterMaterial(cfg) {
' + up * (hf * uImpSize.y * aCard.y);',
// One wind for the whole scene (grass.js windOf), and only the
// top of the stand-in answers it.
- ' float sw = uTime * uImpSpeed + astraStagger(aPos.x + aPos.z * 0.31);',
- ' p.xz += uImpWind * (uImpSway * uImpSize.y * hf * hf * sin(sw));',
+ ' vec3 rootWorld = (modelMatrix * vec4(aPos, 1.0)).xyz;',
+ ' float sw = uTime * uImpSpeed + astraStagger(rootWorld.x + rootWorld.z * 0.31);',
+ ' p += impLocalDir(vec3(uImpWind.x, 0.0, uImpWind.y))',
+ ' * (uImpSway * uImpSize.y * hf * hf * sin(sw));',
' transformed = p;',
// A crown is round, and the two quads of a cross have to agree
// about that or the seam between them lights as a hard edge: the
@@ -688,7 +691,7 @@ function imposterMaterial(cfg) {
' 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));',
+ ' float tGaps = tLeaf - mix(0.17, 0.33, (1.0 - smoothstep(0.02, 0.28, tCrown)));',
' tCrown = min(tCrown, tGaps);',
' iS = max(tCrown, min(0.026 - abs(iq.x - tLean * iq.y), 0.70 - iq.y));',
' iAlb = mix(uImpSecond, uImpColor * (0.66 + 0.60 * iq.y),',
@@ -707,8 +710,8 @@ function imposterMaterial(cfg) {
// the card and iq.y the whole height, so a round head is an
// ellipse here.
' float pW = 0.60 - 0.17 * smoothstep(0.80, 0.90, iq.y)',
- ' - 0.17 * smoothstep(0.74, 0.52, iq.y)',
- ' + 0.07 * smoothstep(0.52, 0.34, iq.y);',
+ ' - 0.17 * (1.0 - smoothstep(0.52, 0.74, iq.y))',
+ ' + 0.07 * (1.0 - smoothstep(0.34, 0.52, iq.y));',
' float pBody = min(min(pW - abs(iq.x), 0.90 - iq.y), iq.y);',
' iS = max(0.29 - length(vec2(iq.x, (iq.y - 0.915) * 4.8)),',
' min(pBody, max(abs(iq.x) - 0.11, iq.y - 0.38)));',
@@ -771,7 +774,7 @@ function imposterMaterial(cfg) {
// thin edge of the mass. Warm, weighted to the silhouette, and
// gone the moment the sun is on the camera's side.
' float iEdge = 1.0 - smoothstep(0.0, 0.12, iS);',
- ' float iBack = smoothstep(0.15, -0.70, vImpVar.w);',
+ ' float iBack = (1.0 - smoothstep(-0.70, 0.15, vImpVar.w));',
// Broken by the same clump field, or the glow is a stroke drawn
// round the silhouette rather than light coming through leaves.
' vec3 iTrans = uImpSunColor * vec3(1.0, 0.82, 0.44)',
diff --git a/harness/codeverse3d/prompts/glsl_shader/cookbook.md b/harness/codeverse3d/prompts/glsl_shader/cookbook.md
index f0289bd5..a462e882 100644
--- a/harness/codeverse3d/prompts/glsl_shader/cookbook.md
+++ b/harness/codeverse3d/prompts/glsl_shader/cookbook.md
@@ -246,9 +246,9 @@ float curtain(vec2 p, float t, float seed, out float k) {
vec3 auroraCol(float k) { return mix(vec3(0.10, 0.95, 0.42), vec3(0.70, 0.20, 0.85), smoothstep(0.18, 0.9, k)); } // green low, violet crown
vec3 aurora(vec2 p, float t) { // three curtains at different depths: nearest brightest
vec3 acc = vec3(0.0); float k = 0.0;
- acc += auroraCol(k) * curtain(p, t, 0.0, k) * 1.00;
- acc += auroraCol(k) * curtain(p - vec2(0.3, 0.12), t * 0.8, 11.0, k) * 0.55;
- acc += auroraCol(k) * curtain(p - vec2(-0.5, 0.22), t * 0.6, 23.0, k) * 0.30;
+ float a = curtain(p, t, 0.0, k); acc += auroraCol(k) * a; // curtain() sets k
+ a = curtain(p - vec2(0.3, 0.12), t * 0.8, 11.0, k); acc += auroraCol(k) * a * 0.55;
+ a = curtain(p - vec2(-0.5, 0.22), t * 0.6, 23.0, k); acc += auroraCol(k) * a * 0.30;
return acc; // then: col += au * 1.7 + au * au * 0.5; (bloom on the bright edge)
}
```
diff --git a/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md b/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md
index 950cfaab..3d22c78c 100644
--- a/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md
+++ b/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md
@@ -50,7 +50,7 @@ says `import { makeGrass } from '../lib/grass.js';`, `src/scene.js` says
| the sun, the fill and the baked environment | `sunRig({ azimuth, elevation })` — `lib/environment.js`; returns `{ sun, fill, sunDisc, envTex, sunDir }`. Add the lights, assign `scene.environment = rig.envTex` |
| an interior's walls, ceiling and window/door openings | `roomShell({ center, extents, openings, thickness, wallColor, ceilingColor, glazed, frameColor, bay })` — `lib/environment.js`; walls outward of the bounds' faces (inner face = bounds face), openings cut as span / sill / lintel panels; glazed: true makes every wall and the roof glass on an iron frame grid (a conservatory, greenhouse, glass atrium). 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` |
+| cloud, cirrus | `makeClouds({ preset, sunDir, quality: 'balanced' })` · `makeCirrus()` — one ray-marched cloud deck with scene-lit self-shadowing; `lib/clouds.js` |
| volumetric cumulus with internal sunlight attenuation | `makeCloudVolume({ size: [600,180,360], coverage: 0.55, density: 0.028, wind: [2.5,0.4], seed, quality: 'balanced' })` — `lib/cloudvolume.js`; Mesh centred on its local origin. Move it to cloud altitude. Wind advects density/erosion inside a bounded billow scaffold; translate the Mesh to move the whole cloud. `userData.sampleDensity(x,y,z,t)` mirrors the GPU field. Use one bounded sky volume and inspect its screen cost. No terrain shadows or opaque-depth intersections. |
| stars, the Milky Way, aurora, heat shimmer | `makeStars` · `makeAurora` · `makeHeatShimmer` — `lib/celestial.js` |
| fog on the ground, distance haze | `makeHeightFog` · `patchAerialPerspective` — `lib/atmosphere.js` |
diff --git a/harness/codeverse3d/tracks/prompting.py b/harness/codeverse3d/tracks/prompting.py
index 397d2b81..dcc1abdd 100644
--- a/harness/codeverse3d/tracks/prompting.py
+++ b/harness/codeverse3d/tracks/prompting.py
@@ -200,7 +200,7 @@ def is_always_chapter(title: str, always: Sequence[str] = COOKBOOK_ALWAYS) -> bo
return any(name.lower() in low for name in always)
-def select_cookbook_chapters(ctx: RunContext, brief: str, *, budget: int = 9000,
+def select_cookbook_chapters(ctx: RunContext, brief: str, *, budget: int = 9500,
always: Sequence[str] = COOKBOOK_ALWAYS) -> list[Section]:
"""The cookbook chapters (cookbook order) a brief calls for.
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index c4b2e7a8..58d0abe1 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -270,6 +270,10 @@ BuildResult.error_type spellings (languages/_common.py): MISSING_ENTRY = "Missin
**Scene effect ownership and shader composition** are stated where they live: `src/lib/lifecycle.js`
(`snapshotResources` / `attachDisposal`) and `src/lib/shader.js` (`patchStandard`, `clonePatchedMaterial`) (D97).
+Scene drawables whose materials all have `depthWrite: false` may set
+`userData.sceneBackdrop = 'sky'` to exclude themselves from content camera framing
+and classify as sky in census/coverage regardless of name or scale; opaque drawables
+cannot opt in (`runtime_js/lib/backdrop.mjs`).
Wrappers are standalone (never import codeverse3d). The three python build wrappers live
together in `languages/wrappers/` — `run_bpy.py`, `run_bpy_links.py` (Blender's python 3.11),
diff --git a/harness/examples/graphics_lab/README.md b/harness/examples/graphics_lab/README.md
index a518ae02..c19e066f 100644
--- a/harness/examples/graphics_lab/README.md
+++ b/harness/examples/graphics_lab/README.md
@@ -1,6 +1,6 @@
# Graphics Lab
-Sixteen hand-composed studies of fire, water, terrain, vegetation, atmosphere,
+Seventeen hand-composed studies of fire, water, terrain, vegetation, atmosphere,
worked materials and independent shader files, covering the effect modules in
`codeverse3d/languages/scene_threejs/starter/src/lib/`. Every image and film
comes from Three.js scene code rendered through the production scene host; there
@@ -57,3 +57,17 @@ with the cookbook recipes it calls exactly as the `graphics` track does. Output
goes to `output/recipes/` with an `index.html` of stills or 144-frame films.
All example UI, code and documentation stay in English.
+
+## Library regression checks
+
+Run `python -m pytest tests/scene_runtime/lib tests/graphics -q -n2` from
+`harness/` when maintaining effects. Besides shader compilation, these checks
+measure transformed wind and cloth normals, light selection, underwater
+transport, material filtering, and feedback initialization on the real rendering
+paths. Use the rendered studies above to assess appearance and motion as well;
+passing numerical checks alone does not establish visual realism.
+
+The moonlit coast (`--case night`) exercises the connected cloud deck, restrained
+star field, physical moon size, and their reflections. `makeClouds` now integrates
+one 3D density field; `quality: 'low' | 'balanced' | 'high'` controls sampling cost.
+The original alpha-map helper `cloudTexture` remains available for custom sprites.
diff --git a/harness/examples/graphics_lab/build.py b/harness/examples/graphics_lab/build.py
index f42b0d1e..9ac213ac 100644
--- a/harness/examples/graphics_lab/build.py
+++ b/harness/examples/graphics_lab/build.py
@@ -32,6 +32,7 @@ CASES = (
("campfire", "14", "Fire in the clearing", "Campfire and bonfire · Char, embers and rising smoke", "flame"),
("structural_fire", "15", "Fire through a structure", "Window and roof flames · Opaque-depth intersections", "flame"),
("external_shader", "16", "Light on alloy", "External GLSL · An animated material study", "shader study"),
+ ("night", "17", "The moonlit coast", "Connected cloud volumes · Moonlight over open water", "night"),
)
diff --git a/harness/examples/graphics_lab/scenes/night.js b/harness/examples/graphics_lab/scenes/night.js
new file mode 100644
index 00000000..81c9f43a
--- /dev/null
+++ b/harness/examples/graphics_lab/scenes/night.js
@@ -0,0 +1,124 @@
+/** Moonlight over a basalt headland and a quiet, open sea. */
+import * as THREE from 'three';
+import { sunRig } from '../lib/environment.js';
+import { makeSky } from '../lib/sky.js';
+import { makeClouds } from '../lib/clouds.js';
+import { makeStars } from '../lib/celestial.js';
+import { makeOceanSurface } from '../lib/ocean.js';
+import { makeRock } from '../lib/rock.js';
+import { fbm2, mulberry32 } from '../lib/noise.js';
+
+export const BOUNDS = { min: [-500, -8, -780], max: [140, 55, 220] };
+
+function shoreX(z) {
+ return 8 + z * 0.18 + 5 * Math.sin(z * 0.016)
+ - 12 * Math.exp(-(((z + 50) / 50) ** 2));
+}
+
+export function heightAt(x, z) {
+ const inland = shoreX(z) - x;
+ const coastalSlope = THREE.MathUtils.smoothstep(inland, -7, 28);
+ const hills = 12 + 24 * Math.exp(-(((z + 230) / 150) ** 2))
+ + 33 * Math.exp(-(((z + 570) / 170) ** 2));
+ const rockRelief = fbm2(x * 0.055, z * 0.055, { seed: 53, octaves: 4 });
+ return -3.2 + 7.4 * coastalSlope
+ + hills * THREE.MathUtils.smoothstep(inland, 10, 150)
+ + rockRelief * 3.1 * coastalSlope;
+}
+
+export function createScene() {
+ const scene = new THREE.Scene();
+ const rig = sunRig({
+ mood: 'night', azimuth: -72, elevation: 21, bounds: 95,
+ intensity: 0.55, fill: 0.36, fillSky: 0x8293ab, fillGround: 0x121823,
+ radius: 4000, disc: true,
+ });
+ // The general rig has a readability floor; this exposure calls for a
+ // dimmer sky fill so moonlit faces separate from sheltered basalt.
+ rig.fill.intensity = 0.36;
+ scene.add(rig.sun, rig.fill, rig.sunDisc);
+ scene.environment = rig.envTex;
+ scene.environmentIntensity = 0.55;
+ const sky = makeSky(scene, { rig, turbidity: 2.7, scale: 4500 });
+ scene.fog = new THREE.FogExp2(0x253143, 0.00065);
+ scene.userData.grade = { exposure: 0.95, contrast: 1.015, saturation: 0.78 };
+
+ const stars = makeStars({
+ seed: 18, count: 650, magnitude: 0.34, twinkle: 0.1, milkyWay: false,
+ });
+ scene.add(stars);
+ const clouds = makeClouds({
+ preset: 'night', seed: 19, count: 14, area: 2400, altitude: 190, spread: 70,
+ sunDir: rig.lightDir, alpha: 0.6, wind: 1.5, rim: 0.22, haze: 0.14, quality: 'high',
+ });
+ clouds.rotation.y = 0.65;
+ scene.add(clouds);
+
+ const ocean = makeOceanSurface({
+ seed: 83, width: 2400, depth: 2400, segments: 320,
+ waveHeight: 0.32, wavelength: 22, windDirection: [0.35, 1],
+ choppiness: 0.5, foam: 0.06, reflectionSize: 1024,
+ waterColor: 0x081b23, shallowColor: 0x183339, sunDir: rig.lightDir,
+ });
+ scene.add(ocean);
+
+ // A continuous coast extends beneath the water. Height and dressing share
+ // one field, keeping the foreshore attached even between large outcrops.
+ const terrainGeometry = new THREE.PlaneGeometry(650, 1000, 180, 240);
+ terrainGeometry.rotateX(-Math.PI / 2);
+ terrainGeometry.translate(-190, 0, -280);
+ const positions = terrainGeometry.attributes.position;
+ const colors = new Float32Array(positions.count * 3);
+ const base = new THREE.Color(0x55534d), color = new THREE.Color();
+ for (let i = 0; i < positions.count; i++) {
+ const x = positions.getX(i), z = positions.getZ(i);
+ positions.setY(i, heightAt(x, z));
+ const variation = fbm2(x * 0.035, z * 0.035, { seed: 117, octaves: 3 });
+ color.copy(base).multiplyScalar(0.88 + variation * 0.46).toArray(colors, i * 3);
+ }
+ terrainGeometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
+ terrainGeometry.computeVertexNormals();
+ const terrainMaterial = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.94 });
+ const terrain = new THREE.Mesh(terrainGeometry, terrainMaterial);
+ terrain.name = 'CoastalHeadland';
+ terrain.castShadow = terrain.receiveShadow = true;
+ scene.add(terrain);
+
+ const rocks = [], rng = mulberry32(271);
+ const addRock = (x, z, size, seed) => {
+ const rock = makeRock({
+ type: 'basalt', seed, size, detail: 5, color: 0x555b60,
+ moisture: 0.65, weathering: 1.2, moss: 0.02, burial: 0.13,
+ });
+ rock.position.set(x, heightAt(x, z) - 0.22, z);
+ rock.rotation.y = rng() * Math.PI * 2;
+ scene.add(rock); rocks.push(rock);
+ };
+ addRock(-7, 12, [13, 4.6, 12], 72);
+ addRock(2, 23, [10, 3.2, 9], 18);
+ addRock(-8, -5, [8, 3.8, 10], 84);
+ addRock(-23, -32, [11, 5.8, 14], 46);
+ for (let i = 0; i < 22; i++) {
+ const z = -46 + rng() * 83, x = shoreX(z) - 1 - rng() * 16;
+ const size = 0.7 + rng() ** 2 * 3.3;
+ addRock(x, z, [size * 1.5, size * 0.62, size], 401 + i);
+ }
+
+ let disposed = false;
+ return {
+ scene,
+ cameras: [
+ { name: 'moonlit_coast', position: [8, 4.8, 23], lookAt: [0, 22, -115], fov: 46 },
+ { name: 'waterline', position: [11, 2.2, 4], lookAt: [5, 17, -120], fov: 43 },
+ ],
+ update(t, dt) {
+ stars.userData.update(t); clouds.userData.update(t); ocean.userData.update(t, dt);
+ },
+ dispose() {
+ if (disposed) return;
+ disposed = true;
+ for (const object of [stars, clouds, ocean, ...rocks]) object.userData.dispose();
+ terrainGeometry.dispose(); terrainMaterial.dispose(); sky.dispose(); rig.dispose();
+ },
+ };
+}
diff --git a/harness/runtime_js/lib/backdrop.mjs b/harness/runtime_js/lib/backdrop.mjs
index 63484812..e58a5051 100644
--- a/harness/runtime_js/lib/backdrop.mjs
+++ b/harness/runtime_js/lib/backdrop.mjs
@@ -5,7 +5,8 @@
* (`host_coverage.mjs`, which masks the same three classes per frame), so the
* word "content" means exactly one thing everywhere.
*
- * Rules (name + world-box shape, in order):
+ * Rules (explicit metadata, then name + world-box shape, in order):
+ * sky a non-depth-writing drawable with userData.sceneBackdrop === 'sky'
* sky a sky-ish name spanning > 50 m or not writing depth, or anything enormous (span > 2 km,
* or tall AND wide: sy > 300 with span > 300)
* content an InstancedMesh (scatter spans the map but is not ground)
@@ -84,11 +85,14 @@ export const GROUND_NAME_RE = /\b(ground|terrain|floor|water|ocean|sea|lake|rive
/**
* 'sky' | 'ground' | 'content' for one drawable with world box `box`.
- * @param {object} obj mesh/points/line/sprite (only `name`, `parent`, `isInstancedMesh` are read)
+ * @param {object} obj mesh/points/line/sprite (name, parent, userData, material, isInstancedMesh)
* @param {{min:{x,y,z}, max:{x,y,z}}} box world-space AABB
* @param {number} contentSpan horizontal span of the known content bbox (0 = unknown)
*/
export function classifyBackdrop(obj, box, contentSpan = 0) {
+ // Procedural sky volumes may be compact or carry a caller's custom name.
+ // Only non-solid drawables can opt in; metadata cannot hide opaque content.
+ if (obj.userData?.sceneBackdrop === 'sky' && nonSolid(obj)) return 'sky';
// Generated scene names normally use PascalCase / snake_case. Word boundaries
// alone missed PlanetSkyBackdrop and SkyAtmosphereBand0, framing the sky as a
// building. Keep the same vocabulary and shape rules for every naming style.
diff --git a/harness/tests/graphics/test_gl_runtime.py b/harness/tests/graphics/test_gl_runtime.py
index fd0616ca..20577c72 100644
--- a/harness/tests/graphics/test_gl_runtime.py
+++ b/harness/tests/graphics/test_gl_runtime.py
@@ -4,11 +4,14 @@ from __future__ import annotations
import json
+import numpy as np
import pytest
+from PIL import Image
from codeverse3d.contracts.plan import GraphicsPlan, PassPlan
from codeverse3d.languages.glsl_shader import GlslShaderRuntime
from codeverse3d.languages.opengl_python import OpenGLPythonRuntime
+from codeverse3d.spatial import gl_render
from codeverse3d.spatial.gl_render import GlHost, GlHostError
from codeverse3d.spatial.registry import ToolContext, get_tool
@@ -72,6 +75,56 @@ def test_feedback_and_nan_detection(tmp_ws, host):
assert any(f["data"]["kind"] == "nan" for f in metrics["gate"]["findings"]) and not metrics["gate"]["passed"]
[email protected]("buffer_a", [False, True], ids=["image", "buffer_a"])
+def test_feedback_starts_black_even_when_allocated_texture_memory_is_dirty(tmp_path, monkeypatch, buffer_a):
+ """Exercise real GL with nonzero allocation contents, not driver-provided zeros."""
+ runner = tmp_path / "dirty_gl_runner.py"
+ runner.write_text(f"""
+import importlib.util
+import sys
+import moderngl
+import numpy as np
+original = moderngl.Context.texture
+def dirty_texture(self, size, components, data=None, **kwargs):
+ if data is None and kwargs.get('dtype') == 'f4':
+ data = np.full((size[1], size[0], components), .375, dtype='f4').tobytes()
+ return original(self, size, components, data=data, **kwargs)
+moderngl.Context.texture = dirty_texture
+spec = importlib.util.spec_from_file_location('real_runner', {str(gl_render.RUNNER)!r})
+module = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(module)
+sys.exit(module.main())
+""")
+ monkeypatch.setattr(gl_render, "RUNNER", runner)
+ previous = """#version 330 core
+uniform vec2 u_resolution;
+uniform sampler2D u_prev;
+out vec4 fragColor;
+void main() { fragColor = texture(u_prev, gl_FragCoord.xy / u_resolution); }
+"""
+ image = """#version 330 core
+uniform vec2 u_resolution;
+uniform sampler2D u_prev;
+uniform sampler2D u_buffer_a;
+out vec4 fragColor;
+void main() {
+ vec2 uv=gl_FragCoord.xy/u_resolution;
+ vec4 a=texture(u_prev,uv), b=texture(u_buffer_a,uv);
+ bool black=all(equal(a,vec4(0,0,0,1))) && all(equal(b,vec4(0,0,0,1)));
+ fragColor=black?vec4(0,1,0,1):vec4(1,0,0,1);
+}
+""" if buffer_a else previous
+ try:
+ result = GlHost(timeout_s=90).render_fragment_shader(
+ image, tmp_path / "frames", width=8, height=8, times=(0.0,),
+ buffer_a_src=previous if buffer_a else None, feedback=True)
+ except GlHostError as exc:
+ pytest.skip(f"OpenGL unavailable: {exc}")
+ assert result.ok, result.error_message
+ pixels = np.asarray(Image.open(result.frames[0].path).convert("RGB"))
+ assert np.all(pixels == ([0, 255, 0] if buffer_a else [0, 0, 0])), pixels.tolist()
+
+
def test_program_skeleton_builds_and_errors_map(tmp_ws, host):
ws = _ws_with_plan(tmp_ws)
rt = OpenGLPythonRuntime(host=host)
diff --git a/harness/tests/graphics/test_recipe_quality.py b/harness/tests/graphics/test_recipe_quality.py
index 751c19df..6ccbbea5 100644
--- a/harness/tests/graphics/test_recipe_quality.py
+++ b/harness/tests/graphics/test_recipe_quality.py
@@ -18,7 +18,7 @@ pytest.importorskip("moderngl")
def test_sdf_transport_and_surface_response_on_real_gl(tmp_path):
known = cookbook_functions(load_text("glsl_shader/cookbook.md"))
- requested = ("sdStar", "sdSegment", "sun", "dropsLayer", "bokehSoft", "beerTransmittance", "phaseHG", "pbrDirect")
+ requested = ("sdStar", "sdSegment", "sun", "dropsLayer", "bokehSoft", "beerTransmittance", "phaseHG", "pbrDirect", "aurora")
recipes = "\n\n".join(r.text for r in with_helpers([known[k] for k in requested], known))
shader = """
void mainImage(out vec4 fragColor,in vec2 fragCoord) {
@@ -54,6 +54,13 @@ void mainImage(out vec4 fragColor,in vec2 fragCoord) {
float disc=sun(uv,vec2(.5),.1);
if(any(isnan(rain))||any(isnan(bokeh))||isnan(disc)) failures+=1.0;
if(any(lessThan(rain,vec2(0)))||any(greaterThan(rain,vec2(1)))) failures+=1.0;
+ // The color of each curtain uses its OWN output height. Evaluating color
+ // before an out-parameter call silently borrowed the preceding layer's k.
+ vec2 p=uv-vec2(.5,.15); float k=0.0; vec3 expectedAurora=vec3(0);
+ float a0=curtain(p,u_time,0.0,k); expectedAurora+=auroraCol(k)*a0;
+ float a1=curtain(p-vec2(.3,.12),u_time*.8,11.0,k); expectedAurora+=auroraCol(k)*a1*.55;
+ float a2=curtain(p-vec2(-.5,.22),u_time*.6,23.0,k); expectedAurora+=auroraCol(k)*a2*.30;
+ if(length(aurora(p,u_time)-expectedAurora)>1e-6) failures+=1.0;
fragColor=vec4(min(failures,1.0),failures==0.0?1.0:0.0,failures/16.0,1.0);
}
"""
diff --git a/harness/tests/scene_runtime/lib/test_building.py b/harness/tests/scene_runtime/lib/test_building.py
index fb7dc891..cf059a06 100644
--- a/harness/tests/scene_runtime/lib/test_building.py
+++ b/harness/tests/scene_runtime/lib/test_building.py
@@ -64,6 +64,38 @@ def _measure(script: str) -> dict:
return measure(_PRELUDE + script, _LIBS)
+def test_roof_clutter_uses_the_hosts_local_roof_after_placement():
+ """World roof height was added as local Y, applying host transforms twice."""
+ out = _measure("""
+import { roofClutter } from './lib/building.js';
+const layouts = [false,true].map(transformed => {
+ const parent = new THREE.Group(), host = new THREE.Group();
+ const roof = new THREE.Mesh(new THREE.BoxGeometry(10,4,6), new THREE.MeshStandardMaterial());
+ roof.position.set(2,3,-1); host.add(roof); parent.add(host);
+ if(transformed) {
+ parent.position.set(19,-3,7); parent.rotation.set(.1,.5,-.2);
+ parent.scale.set(.8,1.3,1.6);
+ host.position.set(8,11,-4); host.rotation.set(.2,-.7,.1);
+ host.scale.set(2,.6,1.2);
+ }
+ roofClutter(host,{rand:()=>.5,tanks:0,units:1});
+ const clutter=host.getObjectByName('RoofClutter'), unit=clutter.children[0];
+ unit.geometry.computeBoundingBox();
+ const local = unit.geometry.boundingBox.clone().translate(unit.position).translate(clutter.position);
+ return {center:local.getCenter(new THREE.Vector3()).toArray(),
+ size:local.getSize(new THREE.Vector3()).toArray(),foot:local.min.y};
+});
+console.log(JSON.stringify(layouts));
+""")
+ plain, transformed = out
+ assert plain["center"][0] == pytest.approx(2)
+ assert plain["center"][2] == pytest.approx(-1)
+ assert plain["foot"] == pytest.approx(5)
+ assert transformed["foot"] == pytest.approx(plain["foot"])
+ assert transformed["center"] == pytest.approx(plain["center"])
+ assert transformed["size"] == pytest.approx(plain["size"])
+
+
@pytest.fixture(scope="module")
def facade() -> dict:
return _measure("""
@@ -222,4 +254,3 @@ def test_cottage_joinery_is_not_roof_tile(cot):
assert m["chimneyIsNotWall"], (
"the stack is limewash, not masonry", m["names"])
-
diff --git a/harness/tests/scene_runtime/lib/test_celestial.py b/harness/tests/scene_runtime/lib/test_celestial.py
index 8918967c..46af7c05 100644
--- a/harness/tests/scene_runtime/lib/test_celestial.py
+++ b/harness/tests/scene_runtime/lib/test_celestial.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import pytest
-from tests.scene_runtime.lib._probe import measure
+from tests.scene_runtime.lib._probe import compile_scene, measure
pytestmark = pytest.mark.node
@@ -34,3 +34,52 @@ console.log(JSON.stringify({ marks }));
for name, flag, marker in out["marks"]:
assert flag, f"{name} does not opt out of fog"
assert marker, f"{name} opts out but writes no marker for the checker"
+
+
+def test_milky_way_is_faint_and_magnitude_controls_all_starlight():
+ """Diffuse galactic light must not become a bright cloud or ignore magnitude."""
+ code, out = compile_scene("""
+import * as THREE from 'three';
+import {makeStars} from './lib/celestial.js';
+export function createScene({renderer}) {
+ const scene=new THREE.Scene(), camera=new THREE.PerspectiveCamera(100,1,.1,5000);
+ const target=new THREE.WebGLRenderTarget(96,96,{type:THREE.FloatType});
+ const pixels=new Float32Array(96*96*4), previous=renderer.getRenderTarget();
+ const clear=new THREE.Color();renderer.getClearColor(clear);const clearAlpha=renderer.getClearAlpha();
+ const groups=[1,.5,0].map(magnitude=>makeStars({count:200,seed:18,magnitude}));
+ const pole=groups[0].getObjectByName('MilkyWayStars').material.uniforms.uPole.value;
+ const core=groups[0].getObjectByName('MilkyWayStars').material.uniforms.uCore.value;
+ const directions=[core,core.clone().negate(),new THREE.Vector3(0,1,0),
+ new THREE.Vector3(-.6,.2,-1).normalize()];
+ try {
+ renderer.setClearColor(0,0);renderer.setRenderTarget(target);
+ for(const direction of directions) {
+ camera.lookAt(direction);camera.updateMatrixWorld(true);
+ const energies=[];
+ for(const group of groups) {
+ group.getObjectByName('StarField').visible=false;scene.add(group);
+ renderer.render(scene,camera);renderer.readRenderTargetPixels(target,0,0,96,96,pixels);
+ let energy=0,peak=0;
+ for(let i=0;i<pixels.length;i+=4) {
+ const l=.2126*pixels[i]+.7152*pixels[i+1]+.0722*pixels[i+2];
+ if(!Number.isFinite(l))throw Error('Nonfinite galactic light');
+ energy+=l;peak=Math.max(peak,l);
+ }
+ if(peak>.035||energy/(96*96)>.008)throw Error('Milky Way became luminous fog: '+[peak,energy]);
+ energies.push(energy);scene.remove(group);
+ }
+ if(energies[0]<=.001)throw Error('Unresolved starlight disappeared');
+ if(Math.abs(energies[1]/energies[0]-.5)>.0001||energies[2]!==0)
+ throw Error('Magnitude does not control diffuse starlight: '+energies);
+ }
+ const off=groups[2];off.getObjectByName('StarField').visible=true;scene.add(off);
+ renderer.render(scene,camera);renderer.readRenderTargetPixels(target,0,0,96,96,pixels);
+ for(let i=0;i<pixels.length;i+=4)if(pixels[i]||pixels[i+1]||pixels[i+2])throw Error('Magnitude zero left visible stars');
+ } finally {
+ renderer.setRenderTarget(previous);renderer.setClearColor(clear,clearAlpha);
+ target.dispose();groups.forEach(g=>g.userData.dispose());
+ }
+ return {scene:new THREE.Scene(),cameras:[{name:'probe',position:[0,0,1],lookAt:[0,0,0]}]};
+}
+""", _LIBS)
+ assert code == 0, out
diff --git a/harness/tests/scene_runtime/lib/test_clouds.py b/harness/tests/scene_runtime/lib/test_clouds.py
index 59a9d9dd..c4941e5d 100644
--- a/harness/tests/scene_runtime/lib/test_clouds.py
+++ b/harness/tests/scene_runtime/lib/test_clouds.py
@@ -1,9 +1,9 @@
-"""clouds.js — regression: `sunDir` was documented and ignored, and a set sun lit the
-night deck from under the ground."""
+"""Cloud deck transport, placement, and ownership regressions."""
from __future__ import annotations
import pytest
-from _probe import measure
+
+from tests.scene_runtime.lib._probe import compile_scene, measure
pytestmark = pytest.mark.node
@@ -25,3 +25,114 @@ console.log(JSON.stringify({
assert m["day"][1] > 0.5, m
assert m["set"][1] > 0.4 and m["set"][0] < 0, m
assert m["none"][1] == 1.0, m
+
+
+def test_cloud_deck_seed_options_and_disposal():
+ out = measure("""
+import {makeClouds} from './lib/clouds.js';
+const hash=texture=>{
+ let h=2166136261;
+ for(const byte of texture.image.data)h=Math.imul(h^byte,16777619);
+ return h>>>0;
+};
+const decks=[makeClouds({seed:7}),makeClouds({seed:7}),makeClouds({seed:8}),makeClouds({count:0})];
+const weather=decks.slice(0,3).map(d=>hash(d.material.uniforms.uWeather.value));
+const noise=decks.slice(0,3).map(d=>hash(d.material.uniforms.uNoise.value));
+let rejected=false;
+try {makeClouds({quality:'toString'});} catch(error) {rejected=error instanceof RangeError;}
+const empty=decks[3].visible===false;
+const counts=[];
+for(const deck of decks) {
+ const u=deck.material.uniforms;
+ for(const resource of [deck.geometry,deck.material,u.uWeather.value,u.uNoise.value]) {
+ const at=counts.length;counts.push(0);resource.addEventListener('dispose',()=>counts[at]++);
+ }
+ deck.userData.dispose();deck.userData.dispose();
+}
+console.log(JSON.stringify({weather,noise,rejected,empty,counts}));
+""", ("clouds.js",))
+ for field in (out["weather"], out["noise"]):
+ assert field[0] == field[1] and field[0] != field[2], out
+ assert out["rejected"] and out["empty"], out
+ assert out["counts"] == [1] * 16, out
+
+
+def test_cloud_transport_matches_beer_lambert_and_camera_projection():
+ """Constant data isolates optical integration from authored noise and color."""
+ code, out = compile_scene("""
+import * as THREE from 'three';
+import {makeClouds} from './lib/clouds.js';
+export function createScene({renderer}) {
+ const scene=new THREE.Scene();
+ // An odd target has an exact center pixel in both projection models.
+ const target=new THREE.WebGLRenderTarget(17,17,{type:THREE.FloatType});
+ const pixel=new Float32Array(4),previous=renderer.getRenderTarget();
+ const clear=new THREE.Color();renderer.getClearColor(clear);const clearAlpha=renderer.getClearAlpha();
+ const results=[];
+ try {
+ renderer.setClearColor(0,0);renderer.setRenderTarget(target);
+ for(const transformed of [false,true])for(const quality of ['low','balanced','high']) {
+ const parent=new THREE.Group(),placement=new THREE.Group();parent.add(placement);scene.add(parent);
+ if(transformed) {
+ parent.position.set(37,-8,23);parent.rotation.y=.41;parent.scale.set(1.7,.8,1.4);
+ placement.position.set(-9,11,14);placement.rotation.y=-.55;placement.scale.set(.9,1.2,1.3);
+ }
+ parent.updateMatrixWorld(true);
+ const linear=new THREE.Matrix3().setFromMatrix4(placement.matrixWorld);
+ const worldAxis=new THREE.Vector3(0,0,1).applyMatrix3(linear),metric=worldAxis.length();
+ const deck=makeClouds({quality,area:100,altitude:0,spread:0,alpha:.12,
+ sunDir:worldAxis.clone().normalize(),wind:0});
+ placement.add(deck);
+ const material=deck.material,u=material.uniforms;
+ for(const name of ['uWeather','uNoise']) {
+ u[name].value.image.data.fill(255);u[name].value.needsUpdate=true;
+ }
+ const center=u.uCenter.value,size=u.uSize.value;
+ const point=center.clone();point.y+=(-.5+.22)*size.y;
+ const sunStart=point.clone();sunStart.z-=.4*size.z;
+ u.uProbePoint={value:sunStart};
+ // Read actual production transport, bypassing artistic source color and
+ // blending. The material's ray setup and density/shadow loops still run.
+ material.blending=THREE.NoBlending;material.toneMapped=false;material.depthTest=false;
+ material.onBeforeCompile=shader=>{
+ shader.fragmentShader='uniform vec3 uProbePoint;\\n'+shader.fragmentShader;
+ shader.fragmentShader=shader.fragmentShader.replace('#include <tonemapping_fragment>',
+ 'gl_FragColor=vec4(opacity,deckShadow(uProbePoint),deckDensity(uProbePoint),1.0);\\n#include <tonemapping_fragment>');
+ };
+ const localEye=point.clone();localEye.z+=size.z*1.2;
+ const eye=localEye.applyMatrix4(placement.matrixWorld),aim=point.clone().applyMatrix4(placement.matrixWorld);
+ const cameras=[new THREE.PerspectiveCamera(45,1,.1,5000),new THREE.OrthographicCamera(-80,80,80,-80,.1,5000)];
+ const samples=[];
+ for(const camera of cameras) {
+ camera.position.copy(eye);camera.lookAt(aim);camera.updateMatrixWorld(true);
+ renderer.render(scene,camera);renderer.readRenderTargetPixels(target,8,8,1,1,pixel);
+ if(!Array.from(pixel).every(Number.isFinite)||pixel[3]!==1)throw Error('Empty/nonfinite cloud probe: '+pixel);
+ samples.push(Array.from(pixel));
+ }
+ // The integral of each 3.5%-wide smoothstep boundary is half its width.
+ // View crosses two fades; light from z=.1 crosses only the exit fade.
+ const extinction=u.uExtinction.value;
+ const expectedOpacity=1-Math.exp(-size.z*.965*metric*extinction);
+ const expectedShadow=size.z*(.9-.035/2)*metric*extinction;
+ for(const sample of samples) {
+ if(Math.abs(sample[2]-1)>.00001)throw Error('Probe density is not constant: '+sample);
+ if(Math.abs(sample[0]-expectedOpacity)>.005)throw Error('Cloud view optical depth lost world distance: '+[quality,transformed,sample[0],expectedOpacity]);
+ if(Math.abs(sample[1]/expectedShadow-1)>.03)throw Error('Cloud light march did not integrate the full path: '+[quality,transformed,sample[1],expectedShadow]);
+ }
+ if(Math.abs(samples[0][0]-samples[1][0])>.0002)throw Error('Orthographic/perspective center rays disagree: '+samples);
+ results.push({transformed,quality,opacity:samples[0][0],shadow:samples[0][1]});
+ u.uAlpha.value=0;
+ renderer.render(scene,cameras[0]);renderer.readRenderTargetPixels(target,8,8,1,1,pixel);
+ if(pixel.some(v=>v!==0))throw Error('Alpha zero left cloud transport: '+pixel);
+ scene.remove(parent);deck.userData.dispose();
+ }
+ for(const transformed of [false,true]) {
+ const group=results.filter(r=>r.transformed===transformed),reference=group[2];
+ for(const row of group)if(Math.abs(row.opacity-reference.opacity)>.005||Math.abs(row.shadow/reference.shadow-1)>.03)
+ throw Error('Cloud quality changed integrated density: '+JSON.stringify(group));
+ }
+ } finally {renderer.setRenderTarget(previous);renderer.setClearColor(clear,clearAlpha);target.dispose();}
+ return {scene:new THREE.Scene(),cameras:[{name:'probe',position:[0,0,1],lookAt:[0,0,0]}]};
+}
+""", ("clouds.js",))
+ assert code == 0, out
diff --git a/harness/tests/scene_runtime/lib/test_environment.py b/harness/tests/scene_runtime/lib/test_environment.py
index 47f47cf4..a742d86b 100644
--- a/harness/tests/scene_runtime/lib/test_environment.py
+++ b/harness/tests/scene_runtime/lib/test_environment.py
@@ -17,6 +17,64 @@ def _measure(script: str) -> dict:
return measure(script, _LIBS)
+def test_night_dome_uses_the_bakes_set_sun_instead_of_the_moon():
+ """An explicit night rig baked night reflections but painted a daylight dome."""
+ out = _measure("""
+import * as THREE from 'three';
+import { sunRig } from './lib/environment.js';
+import { makeSky } from './lib/sky.js';
+const states = [
+ {mood:'night'}, {mood:'day'}, {mood:'golden',elevation:-5},
+].map(options => {
+ const rig = sunRig({...options, disc:true});
+ const original = rig.sunDir.clone();
+ const {sky, sunDir, setSunDirection} = makeSky(new THREE.Scene(), {rig});
+ const u = sky.material.uniforms;
+ const state = {night:u.uNight.value, solarY:u.sunPosition.value.y,
+ lightY:rig.lightDir.y, discVisible:rig.sunDisc.visible,
+ agreesWithBake:u.sunPosition.value.distanceTo(rig.skySunDir),
+ inputUnchanged:rig.sunDir.distanceTo(original),
+ publicDirectionUnchanged:sunDir.distanceTo(original)};
+ setSunDirection([0,1,0]);
+ state.canReturnToDay = u.uNight.value === 0 && u.sunPosition.value.y === 1 && sunDir.y === 1;
+ sky.userData.dispose(); rig.dispose();
+ return state;
+});
+console.log(JSON.stringify(states));
+""")
+ night, day, twilight = out
+ assert night["night"] == 1 and night["solarY"] < 0 < night["lightY"]
+ assert night["discVisible"], "The moon remains visible beside the night sky"
+ assert day["night"] == 0 and day["solarY"] > 0
+ assert not day["discVisible"], "The physical sky already draws its own sun"
+ assert 0 < twilight["night"] < 1 and twilight["solarY"] < 0
+ assert all(s["agreesWithBake"] < 1e-12 and s["inputUnchanged"] == 0 for s in out)
+ assert all(s["publicDirectionUnchanged"] < 1e-12 for s in out)
+ assert all(s["canReturnToDay"] for s in out)
+
+
+def test_moon_angular_size_is_independent_of_sky_radius_and_scene_fog():
+ out = _measure("""
+import * as THREE from 'three';
+import { sunRig } from './lib/environment.js';
+const moons = [400,4000,12000].map(radius => {
+ const rig=sunRig({mood:'night',radius}), moon=rig.sunDisc;
+ const diameter=THREE.MathUtils.radToDeg(2*Math.atan(moon.geometry.parameters.radius/moon.position.length()));
+ const state={diameter,fog:moon.material.fog,depthWrite:moon.material.depthWrite,
+ aligned:moon.position.clone().normalize().dot(rig.lightDir)};
+ rig.dispose();return state;
+});
+const day=sunRig({mood:'day',radius:4000});
+const daytime={radius:day.sunDisc.geometry.parameters.radius,segments:day.sunDisc.geometry.parameters.segments};
+day.dispose();console.log(JSON.stringify({moons,daytime}));
+""")
+ for moon in out["moons"]:
+ assert moon["diameter"] == pytest.approx(.52)
+ assert not moon["fog"] and not moon["depthWrite"]
+ assert moon["aligned"] == pytest.approx(1)
+ assert out["daytime"] == {"radius": 48, "segments": 24}
+
+
_SHELL = """
import * as THREE from 'three';
import { worldShell } from './lib/environment.js';
diff --git a/harness/tests/scene_runtime/lib/test_light_probe.py b/harness/tests/scene_runtime/lib/test_light_probe.py
new file mode 100644
index 00000000..f6dffc73
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_light_probe.py
@@ -0,0 +1,78 @@
+"""Effects must choose a light that actually contributes at their sample point."""
+from __future__ import annotations
+
+import pytest
+
+from tests.scene_runtime.lib._probe import measure
+
+pytestmark = pytest.mark.node
+
+
[email protected](scope="module")
+def lights():
+ return measure("""
+import * as THREE from 'three';
+import { makeLightProbe } from './lib/shader.js';
+const read = makeLightProbe(), near = new THREE.Vector3();
+const selected = (lights) => {
+ const scene = new THREE.Scene(); scene.add(...lights);
+ const value = read(scene, near);
+ return { sun: value.sun?.name ?? null, point: value.point?.name ?? null };
+};
+const directional = (name, color, intensity) => {
+ const light = new THREE.DirectionalLight(color, intensity); light.name = name; return light;
+};
+const point = (name, color, intensity, x, range = 0, decay = 2) => {
+ const light = new THREE.PointLight(color, intensity, range, decay);
+ light.position.x = x; light.name = name; return light;
+};
+const results = {
+ directionalColor: selected([directional('red', 0xff0000, 2), directional('green', 0x00ff00, 1)]),
+ black: selected([directional('black', 0, 1e6), point('black', 0, 1e6, .1)]),
+ pointColor: selected([point('red', 0xff0000, 2, 2), point('green', 0x00ff00, 1, 2)]),
+ outsideRange: selected([point('out', 0xffffff, 1e6, 2, 1), point('in', 0xffffff, 1, 3)]),
+ smoothRange: selected([point('edge', 0xffffff, 100, 9.99, 10), point('far', 0xffffff, 1, 20)]),
+ decay: selected([point('decaying', 0xffffff, 100, 10), point('constant', 0xffffff, 2, 10, 0, 0)]),
+};
+const scene = new THREE.Scene(), hidden = new THREE.Group(); hidden.visible = false;
+hidden.add(directional('hidden', 0xffffff, 1e6), point('hidden', 0xffffff, 1e6, .1));
+scene.add(hidden, new THREE.AmbientLight(0xff0000, .5), new THREE.HemisphereLight(0x00ff00, 0x0000ff, 2));
+const rig = new THREE.Group(); rig.position.set(3, 4, 5);
+const sun = directional('world', 0xffffff, 1); sun.position.set(2, 3, 4);
+sun.target.position.set(2, 1, 4); rig.add(sun, sun.target); scene.add(rig);
+const value = read(scene, near);
+results.world = { sun: value.sun.name, point: value.point?.name ?? null,
+ direction: value.sunDirection.toArray(), ambient: value.ambient.toArray(),
+ sky: value.sky.toArray(), ground: value.ground.toArray() };
+const empty = read(new THREE.Scene());
+results.reset = { sun: empty.sun, point: empty.point, direction: empty.sunDirection.toArray(),
+ ambient: empty.ambient.toArray(), sky: empty.sky.toArray(), ground: empty.ground.toArray() };
+console.log(JSON.stringify(results));
+""")
+
+
+def test_directional_selection_uses_emitted_color(lights):
+ assert lights["directionalColor"]["sun"] == "green"
+ assert lights["black"] == {"sun": None, "point": None}
+
+
[email protected]("case,expected", [
+ ("pointColor", "green"), ("outsideRange", "in"),
+ ("smoothRange", "far"), ("decay", "constant"),
+])
+def test_point_selection_accounts_for_color_range_and_decay(lights, case, expected):
+ assert lights[case]["point"] == expected
+
+
+def test_visible_scene_lights_sum_and_use_world_space(lights):
+ world = lights["world"]
+ assert world["sun"] == "world" and world["point"] is None
+ assert world["direction"] == pytest.approx([0, 1, 0])
+ assert world["ambient"] == pytest.approx([.5, 0, 0])
+ assert world["sky"] == pytest.approx([0, 2, 0])
+ assert world["ground"] == pytest.approx([0, 0, 2])
+
+
+def test_reused_probe_clears_previous_scene_lights(lights):
+ assert lights["reset"] == {"sun": None, "point": None, "direction": [0, 1, 0],
+ "ambient": [0, 0, 0], "sky": [0, 0, 0], "ground": [0, 0, 0]}
diff --git a/harness/tests/scene_runtime/lib/test_rain.py b/harness/tests/scene_runtime/lib/test_rain.py
index 2d7b0905..6f14f49b 100644
--- a/harness/tests/scene_runtime/lib/test_rain.py
+++ b/harness/tests/scene_runtime/lib/test_rain.py
@@ -64,3 +64,62 @@ const finite = (g) => {
console.log(JSON.stringify(finite(makeSplashes({ area: 12, y: 0, seed: 4 }))));
""", _LIBS)
assert out["total"] > 0 and out["bad"] == 0, out
+
+
+def test_hidden_surfaces_do_not_collect_splashes_or_shelter_rain():
+ """A hidden ancestor/material must agree with what is actually rendered."""
+ out = measure("""
+import * as THREE from 'three';
+import { makeRain, makeSplashes } from './lib/rain.js';
+const scene = new THREE.Scene(), hidden = new THREE.Group();
+hidden.visible = false; scene.add(hidden);
+const roof = new THREE.Mesh(new THREE.BoxGeometry(5, .3, 5), new THREE.MeshStandardMaterial());
+roof.position.y = 4; hidden.add(roof);
+const invisible = roof.clone(); invisible.material = roof.material.clone();
+invisible.material.visible = false; invisible.position.y = 2; scene.add(invisible);
+scene.updateMatrixWorld(true);
+const surfaces = [roof, invisible];
+const splashes = makeSplashes({ surfaces, area: 4, count: 60, surfaceBias: 0, crowns: false });
+const impact = splashes.getObjectByName('SplashRings').geometry.attributes.iOff;
+const rainfall = makeRain({ surfaces, radius: 3, count: 2, follow: false, groundY: 0 });
+scene.add(rainfall); scene.updateMatrixWorld(true);
+const camera = new THREE.PerspectiveCamera(); camera.position.set(0, 3, 6); camera.updateMatrixWorld(true);
+rainfall.onBeforeRender({}, scene, camera, rainfall.geometry, rainfall.material);
+rainfall.onAfterRender({}, scene, camera, rainfall.geometry, rainfall.material);
+console.log(JSON.stringify({ heights: Array.from({length: impact.count}, (_, i) => impact.getY(i)),
+ shelter: rainfall.userData.sampleShelterHeight(0, 0) }));
+splashes.userData.dispose(); rainfall.userData.dispose();
+""", _LIBS)
+ assert out["shelter"] == 0, out
+ assert out["heights"] == pytest.approx([0.012] * 60), out
+
+
+def test_instanced_splash_normals_follow_affine_surface_and_reject_steep_faces():
+ """The normal and lift belong to each tilted instance, including parent scale."""
+ out = measure("""
+import * as THREE from 'three';
+import { makeSplashes } from './lib/rain.js';
+const parent = new THREE.Group(); parent.rotation.y = .4; parent.scale.set(1.6, .8, 1.2);
+const geometry = new THREE.PlaneGeometry(5, 5); geometry.rotateX(-Math.PI / 2);
+const roof = new THREE.InstancedMesh(geometry, new THREE.MeshStandardMaterial({side: THREE.DoubleSide}), 1);
+parent.add(roof); const instance = new THREE.Matrix4().makeRotationZ(.55);
+instance.setPosition(0, 3, 0); roof.setMatrixAt(0, instance); parent.updateMatrixWorld(true);
+const expected = new THREE.Vector3(0, 1, 0).applyMatrix3(new THREE.Matrix3()
+ .getNormalMatrix(roof.matrixWorld.clone().multiply(instance))).normalize();
+const center = new THREE.Vector3(0, 0, 0).applyMatrix4(roof.matrixWorld.clone().multiply(instance));
+const splash = makeSplashes({surfaces: [roof], count: 80, surfaceBias: 1, ground: false, crowns: false});
+const rings = splash.getObjectByName('SplashRings'), normal = rings.geometry.attributes.iNrm, off = rings.geometry.attributes.iOff;
+let normalError = 0, liftError = 0;
+for (let i = 0; i < off.count; i++) {
+ normalError = Math.max(normalError, new THREE.Vector3().fromBufferAttribute(normal, i).distanceTo(expected));
+ liftError = Math.max(liftError, Math.abs(new THREE.Vector3().fromBufferAttribute(off, i).sub(center).dot(expected) - .012));
+}
+instance.makeRotationZ(1.48).setPosition(0, 3, 0); roof.setMatrixAt(0, instance);
+roof.computeBoundingBox(); roof.computeBoundingSphere();
+const steep = makeSplashes({surfaces: [roof], count: 40, surfaceBias: 1, ground: false, crowns: false});
+console.log(JSON.stringify({normalError, liftError, count: off.count, steepCount: steep.children.length}));
+splash.userData.dispose(); steep.userData.dispose();
+""", _LIBS)
+ assert out["count"] == 80, out
+ assert out["normalError"] < 1e-6 and out["liftError"] < 1e-6, out
+ assert out["steepCount"] == 0, out
diff --git a/harness/tests/scene_runtime/lib/test_surface_filtering.py b/harness/tests/scene_runtime/lib/test_surface_filtering.py
new file mode 100644
index 00000000..f706d60f
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_surface_filtering.py
@@ -0,0 +1,77 @@
+"""Unresolved material grain averages away, including its chroma variation."""
+import json
+
+import pytest
+
+from tests.scene_runtime.lib._probe import compile_scene
+
+pytestmark = pytest.mark.node
+
+
+def test_micro_breakup_keeps_resolved_detail_and_filters_subpixel_color():
+ code, out = compile_scene("""
+import * as THREE from 'three';
+import { patchStandard } from './lib/shader.js';
+import { patchMicroBreakup } from './lib/surface_wear.js';
+export function createScene({renderer}) {
+ const scene = new THREE.Scene();
+ const material = new THREE.MeshStandardMaterial({color:new THREE.Color(.4,.4,.4),toneMapped:false});
+ patchMicroBreakup(material,{strength:.3,hue:.5,scale:.4,seed:7});
+ patchStandard(material,{name:'read-albedo',outputBody:'gl_FragColor=vec4(diffuseColor.rgb,1.0);'});
+ const plane = new THREE.Mesh(new THREE.PlaneGeometry(2,2),material);scene.add(plane);
+ const camera = new THREE.OrthographicCamera(-1,1,1,-1,.1,10);camera.position.z=2;
+ const target = new THREE.WebGLRenderTarget(64,64),pixels = new Uint8Array(64*64*4);
+ const previous = renderer.getRenderTarget();
+ try {
+ renderer.setRenderTarget(target);
+ for (const scale of [.4, .0001]) {
+ material.userData.uniforms.uMicroScale.value=scale;
+ renderer.render(scene,camera);renderer.readRenderTargetPixels(target,0,0,64,64,pixels);
+ let lo=255,hi=0,maxError=0;
+ for(let i=0;i<pixels.length;i+=4) for(let c=0;c<3;c++) {
+ lo=Math.min(lo,pixels[i+c]);hi=Math.max(hi,pixels[i+c]);
+ maxError=Math.max(maxError,Math.abs(pixels[i+c]-102));
+ }
+ if(scale>.1 && hi-lo<12) throw new Error('Resolved material lost its grain: '+[lo,hi]);
+ if(scale<.1 && maxError>1) throw new Error('Subpixel material grain/chroma did not filter to its mean: '+maxError);
+ }
+ } finally {
+ renderer.setRenderTarget(previous);target.dispose();plane.geometry.dispose();material.dispose();
+ }
+ scene.remove(plane);
+ return {scene,cameras:[{name:'probe',position:[0,0,2],lookAt:[0,0,0],fov:45}]};
+}
+""", libs=("surface_wear.js",))
+ assert code == 0, out
+ assert json.loads(out.strip().splitlines()[-1])["ok"]
+
+
+def test_moss_casts_no_edge_shadow_on_a_dry_sun_facing_wall():
+ code, out = compile_scene("""
+import * as THREE from 'three';
+import { patchStandard } from './lib/shader.js';
+import { patchMoss } from './lib/damp.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 material=new THREE.MeshStandardMaterial({color:new THREE.Color(.4,.4,.4),toneMapped:false});
+ // The wall faces +Z; the shaded side is -Z. There is no local concavity.
+ patchMoss(material,{amount:1,north:[0,0,-1]});
+ patchStandard(material,{name:'dry-wall-albedo',outputBody:'gl_FragColor=vec4(diffuseColor.rgb,1.0);'});
+ const plane=new THREE.Mesh(new THREE.PlaneGeometry(2,2),material);scene.add(plane);
+ const target=new THREE.WebGLRenderTarget(32,32),pixels=new Uint8Array(32*32*4);
+ const previous=renderer.getRenderTarget();
+ try {
+ renderer.setRenderTarget(target);renderer.render(scene,camera);
+ renderer.readRenderTargetPixels(target,0,0,32,32,pixels);
+ for(let i=0;i<pixels.length;i+=4) for(let c=0;c<3;c++)
+ if(Math.abs(pixels[i+c]-102)>1) throw new Error('Absent moss darkened the dry wall: '+pixels[i+c]);
+ } finally {
+ renderer.setRenderTarget(previous);target.dispose();plane.geometry.dispose();material.dispose();
+ }
+ scene.remove(plane);
+ return {scene,cameras:[{name:'probe',position:[0,0,2],lookAt:[0,0,0],fov:45}]};
+}
+""", libs=("damp.js",))
+ assert code == 0, out
+ assert json.loads(out.strip().splitlines()[-1])["ok"]
diff --git a/harness/tests/scene_runtime/lib/test_vegetation_dynamics.py b/harness/tests/scene_runtime/lib/test_vegetation_dynamics.py
new file mode 100644
index 00000000..f9ddba53
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_vegetation_dynamics.py
@@ -0,0 +1,220 @@
+"""Numerical regressions for world wind and normals of deformed cloth."""
+from __future__ import annotations
+
+import re
+
+import pytest
+
+from tests.scene_runtime.lib._probe import LIB_DIR, compile_scene, measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("grass.js", "flowers.js", "smalllife.js", "canopy.js", "cloth.js",
+ "foliage_shade.js", "finish.js")
+
+# Run the production material's actual vertex patch, with constant per-plant
+# attributes across a screen quad. Float readback measures positions/normals
+# independently of rasterized blade size, lighting, or camera-facing widths.
+_VERTEX_PROBE = """
+function vertexProbe(source, renderer, scene, camera, target) {
+ const compiled = {uniforms:{}, fragmentShader:'void main() {}', vertexShader:`
+ uniform vec3 uProbePoint, uProbeRoot;
+ uniform float uProbeNormal;
+ varying vec3 vNormal, vProbe;
+ void main() {
+ vNormal=vec3(0.,0.,1.);
+ #include <begin_vertex>
+ vProbe=uProbeNormal>.5 ? vNormal : (modelMatrix*vec4(transformed,1.)).xyz-uProbeRoot;
+ gl_Position=vec4(position.xy,0.,1.);
+ }`};
+ source.material.onBeforeCompile(compiled);
+ const uniforms={...compiled.uniforms,uProbePoint:{value:new THREE.Vector3()},
+ uProbeRoot:{value:new THREE.Vector3()},uProbeNormal:{value:0}};
+ const material=new THREE.ShaderMaterial({uniforms,
+ vertexShader:compiled.vertexShader.replace('#include <begin_vertex>','#include <begin_vertex>\\n transformed=uProbePoint;'),
+ fragmentShader:'varying vec3 vProbe; void main(){gl_FragColor=vec4(vProbe,1.);}',
+ toneMapped:false,depthTest:false,depthWrite:false});
+ const geometry=new THREE.PlaneGeometry(2,2);
+ for(const [name,attribute] of Object.entries(source.geometry.attributes)) {
+ if(['position','normal','uv'].includes(name)) continue;
+ const value=Array.from(attribute.array.slice(0,attribute.itemSize));
+ geometry.setAttribute(name,new THREE.Float32BufferAttribute(Array(4).fill(value).flat(),attribute.itemSize));
+ }
+ const mesh=new THREE.Mesh(geometry,material);mesh.frustumCulled=false;mesh.matrixAutoUpdate=false;
+ const pixel=new Float32Array(4);
+ return {
+ sample({matrix=new THREE.Matrix4(),root=new THREE.Vector3(),point=new THREE.Vector3(),attrs={},normal=false,time=0}={}) {
+ mesh.matrix.copy(matrix);uniforms.uProbePoint.value.copy(point);uniforms.uProbeRoot.value.copy(root);
+ uniforms.uProbeNormal.value=normal?1:0;uniforms.uTime.value=time;
+ for(const [name,value] of Object.entries(attrs)) {
+ const a=geometry.attributes[name];for(let i=0;i<a.count;i++)a.array.set(value,i*a.itemSize);a.needsUpdate=true;
+ }
+ scene.add(mesh);renderer.setRenderTarget(target);renderer.render(scene,camera);
+ renderer.readRenderTargetPixels(target,1,1,1,1,pixel);scene.remove(mesh);
+ if(!Array.from(pixel).every(Number.isFinite)||pixel[3]!==1)throw new Error('Nonfinite/empty vertex readback: '+pixel);
+ return new THREE.Vector3().fromArray(pixel);
+ },
+ dispose(){geometry.dispose();material.dispose();},uniforms,
+ };
+}
+"""
+
+
+def test_legacy_vegetation_shares_world_wind_after_parent_rotation_and_translation():
+ code, out = compile_scene("""
+import * as THREE from 'three';
+import {makeGrass} from './lib/grass.js';
+import {makeFlowers} from './lib/flowers.js';
+import {makeReeds} from './lib/smalllife.js';
+import {makeCanopy} from './lib/canopy.js';
+import {makeWheatField} from './lib/cloth.js';
+""" + _VERTEX_PROBE + """
+export function createScene({renderer}) {
+ const scene=new THREE.Scene(),camera=new THREE.OrthographicCamera(-1,1,1,-1,.1,10);camera.position.z=2;
+ const opts={extent:2,density:2,seed:5,wind:{dir:[1,.35],strength:1.4},shadows:true};
+ const groups=[makeGrass(opts),makeFlowers(opts),makeReeds(opts),makeWheatField(opts),makeCanopy({density:4,...opts})];
+ const names=['Blades','Plants','Stems','Stalks','Leaves'];
+ const shape=[{iShape:[1,.05,0,0],iVar:[0,.37,.2,0]},
+ {iShape:[1,.02,1,1],iBend:[.6,0,0,.4],iVar:[0,.4,.3,1],aPart:[0,0,0]},
+ {iShape:[1,.02,.2,.03],iBend:[.5,.1,0,0],iVar:[.37,.2,.3,.4],aPart:[0]},
+ {iCrop:[1,.01,.8,1],iVar:[.37,0,0],aPart:[0]},
+ {iAxis:[0,1,0],iVar:[0,.2,.4,1]}];
+ const target=new THREE.WebGLRenderTarget(4,4,{type:THREE.FloatType}),previous=renderer.getRenderTarget();
+ let error=0,shadowError=0;
+ try {
+ for(let kind=0;kind<groups.length;kind++) {
+ const source=groups[kind].getObjectByName(names[kind]);
+ const probe=vertexProbe(source,renderer,scene,camera,target);
+ const shadow=vertexProbe({geometry:source.geometry,material:source.customDepthMaterial},renderer,scene,camera,target);
+ for(const root of [new THREE.Vector3(0,0,0),new THREE.Vector3(2.5,0,-4)]) for(const time of [0,.73,3.1]) {
+ let reference=null;
+ for(const yaw of [0,Math.PI/2,-Math.PI/3]) {
+ const matrix=new THREE.Matrix4().makeRotationY(yaw);
+ matrix.setPosition(yaw===0?0:3,0,yaw===0?0:-2);
+ const local=root.clone().applyMatrix4(matrix.clone().invert());
+ const attrs={...shape[kind],iPos:local.toArray(),aCorner:[0,1,0]};
+ if(kind===4)attrs.iSpray=[...local.toArray(),.4];
+ const sample={matrix,root,attrs,time},actual=probe.sample(sample),depth=shadow.sample(sample);
+ if(reference)error=Math.max(error,actual.distanceTo(reference));else reference=actual;
+ shadowError=Math.max(shadowError,actual.distanceTo(depth));
+ }
+ }
+ probe.dispose();shadow.dispose();
+ }
+ } finally {renderer.setRenderTarget(previous);target.dispose();groups.forEach(g=>g.userData.dispose());}
+ if(error>.002||shadowError>.00001)throw new Error('World-wind/depth mismatch: '+JSON.stringify({error,shadowError}));
+ return {scene,cameras:[{name:'a',position:[0,0,2],lookAt:[0,0,0],fov:45}]};
+}
+""", _LIBS, audit_module="src/scene.js")
+ assert code == 0, out
+
+
+def test_flag_and_banner_normals_match_finite_differences_of_their_displacement():
+ code, out = compile_scene("""
+import * as THREE from 'three';
+import {makeFlag,makeBanner} from './lib/cloth.js';
+""" + _VERTEX_PROBE + """
+export function createScene({renderer}) {
+ const scene=new THREE.Scene(),camera=new THREE.OrthographicCamera(-1,1,1,-1,.1,10);camera.position.z=2;
+ const groups=[makeFlag({width:2,height:1,wind:3}),makeBanner({width:2,drop:2,wind:3})];
+ const target=new THREE.WebGLRenderTarget(4,4,{type:THREE.FloatType}),previous=renderer.getRenderTarget();
+ let error=0;
+ try {
+ for(let kind=0;kind<2;kind++) {
+ const source=groups[kind].getObjectByName(kind?'BannerCloth':'FlagSheet');
+ const probe=vertexProbe(source,renderer,scene,camera,target);
+ const sample=(x,y,time,normal=false)=>{
+ const u=x/2+.5,s=-y/2,k=5;
+ // Analytic profiles isolate the displacement from tessellation density.
+ const attrs=kind?{aBan:[s,Math.sin(k*x),k*Math.cos(k*x),k*k*x/2+k*Math.sin(2*k*x)/4]}:
+ {aFlag:[u,u**1.6,1.6*u**.6,u**4.2/4.2]};
+ return probe.sample({point:new THREE.Vector3(x,y,0),attrs,time,normal});
+ };
+ const epsilon=.0005;
+ for(const x of [-.73,.13,.77])for(const y of [-.25,-.8])for(const time of [.4,1.6]) {
+ const dx=sample(x+epsilon,y,time).sub(sample(x-epsilon,y,time));
+ const dy=sample(x,y+epsilon,time).sub(sample(x,y-epsilon,time));
+ const expected=dx.cross(dy).normalize(),actual=sample(x,y,time,true).normalize();
+ error=Math.max(error,1-expected.dot(actual));
+ }
+ probe.dispose();
+ }
+ } finally {renderer.setRenderTarget(previous);target.dispose();groups.forEach(g=>g.userData.dispose());}
+ if(error>.00005)throw new Error('Cloth normal does not follow displaced tangents: '+error);
+ return {scene,cameras:[{name:'a',position:[0,0,2],lookAt:[0,0,0],fov:45}]};
+}
+""", ("cloth.js", "grass.js"), audit_module="src/scene.js")
+ assert code == 0, out
+
+
+def test_legacy_transition_masks_have_defined_edges():
+ """Equal snow slopes and six reversed silhouette ramps were undefined GLSL."""
+ out = measure("""
+import * as THREE from 'three';
+import {patchSlopeSplat} from './lib/terrain_shade.js';
+const values=[];
+for(const pair of [[.6,.6],[.6,.6+1e-10],[.45,.75],[.75,.45]]) {
+ const m=patchSlopeSplat(new THREE.MeshStandardMaterial(),{slopeLow:pair[0],slopeHigh:pair[1]});
+ const u=m.userData.uniforms,lo=Math.fround(u.uSplatHigh.value),hi=Math.fround(u.uSplatLow.value);
+ const masks=[lo-.01,(lo+hi)/2,hi+.01].map(x=>THREE.MathUtils.smoothstep(x,lo,hi));
+ values.push({lo,hi,masks});
+}
+console.log(JSON.stringify({values}));
+""", ("terrain_shade.js",))
+ for item in out["values"]:
+ assert item["lo"] < item["hi"]
+ assert item["masks"] == pytest.approx([0, .5, 1], abs=1e-8)
+ for module in ("flock.js", "smalllife.js", "woodland.js"):
+ # GLSL leaves edge0 >= edge1 undefined even when one GPU accepts it.
+ for match in re.finditer(r"smoothstep\(\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*,",
+ (LIB_DIR / module).read_text()):
+ assert float(match[1]) < float(match[2]), (module, match[0])
+
+
+def test_falling_sample_matches_gpu_after_parent_and_child_transforms():
+ """World wind must have the same local velocity in the public CPU sampler."""
+ code, out = compile_scene("""
+import * as THREE from 'three';
+import {makeFalling} from './lib/flowers.js';
+""" + _VERTEX_PROBE + """
+export function createScene({renderer}) {
+ const scene=new THREE.Scene(),camera=new THREE.OrthographicCamera(-1,1,1,-1,.1,10);camera.position.z=2;
+ const parent=new THREE.Group(),group=makeFalling({count:7,seed:13,extent:8,height:5,
+ wind:{dir:[1,.35],strength:1.4}}),source=group.getObjectByName('Drift');
+ parent.add(group);parent.matrixAutoUpdate=group.matrixAutoUpdate=source.matrixAutoUpdate=false;
+ const matrix=(position,rotation,scale)=>new THREE.Matrix4().compose(new THREE.Vector3(...position),
+ new THREE.Quaternion().setFromEuler(new THREE.Euler(...rotation)),new THREE.Vector3(...scale));
+ const identity=new THREE.Matrix4(),outer=matrix([3,.7,-4],[.2,.6,-.1],[1.7,.65,2.3]);
+ const local=matrix([-.5,.2,.8],[0,.47,0],[.8,1.2,1.4]);
+ const child=matrix([.3,.4,-.6],[.2,.9,.4],[.8,1.2,2.1]);
+ const nearSingular=new THREE.Matrix4().set(1,0,1,0, 0,1,0,0, 0,0,1e-9,0, 0,0,0,1);
+ const transforms=[[identity,identity,identity],
+ [matrix([2,0,-1],[0,Math.PI/2,0],[1,1,1]),identity,identity],
+ [outer,local,identity],[outer,local,child],
+ [identity,identity,new THREE.Matrix4().makeScale(0,1,1)],
+ [identity,identity,nearSingular]];
+ const target=new THREE.WebGLRenderTarget(4,4,{type:THREE.FloatType}),previous=renderer.getRenderTarget();
+ const probe=vertexProbe(source,renderer,scene,camera,target);
+ let error=0;
+ try {
+ for(const [parentMatrix,groupMatrix,childMatrix] of transforms) {
+ parent.matrix.copy(parentMatrix);group.matrix.copy(groupMatrix);source.matrix.copy(childMatrix);
+ // No scene update/render precedes sample(): it must refresh its ancestors.
+ for(const time of [.73,0,3.1,-2.4,31.7])for(const index of [-4,3,99]) {
+ const expected=group.userData.sample(index,time);
+ // Rendering refreshes matrices independently of the public CPU sampler.
+ source.updateWorldMatrix(true,false);expected.applyMatrix4(group.matrixWorld);
+ const k=Math.min(6,Math.max(0,index)),attrs={aCorner:[0,0,0]};
+ for(const name of ['aPos','aFall','aAxis','aWob','aVar']) {
+ const a=source.geometry.attributes[name];attrs[name]=Array.from(a.array.slice(k*a.itemSize,(k+1)*a.itemSize));
+ }
+ const actual=probe.sample({matrix:source.matrixWorld,attrs,time});
+ error=Math.max(error,actual.distanceTo(expected));
+ }
+ }
+ } finally {renderer.setRenderTarget(previous);probe.dispose();target.dispose();group.userData.dispose();}
+ if(error>.00015)throw new Error('Falling CPU/GPU transformed sample mismatch: '+error);
+ return {scene,cameras:[{name:'a',position:[0,0,2],lookAt:[0,0,0],fov:45}]};
+}
+""", _LIBS, audit_module="src/scene.js")
+ assert code == 0, out
diff --git a/harness/tests/scene_runtime/lib/test_water_transport.py b/harness/tests/scene_runtime/lib/test_water_transport.py
new file mode 100644
index 00000000..a870cb64
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_water_transport.py
@@ -0,0 +1,129 @@
+"""Rendered water lighting and refracted caustic transport regressions."""
+from __future__ import annotations
+
+import pytest
+
+from tests.scene_runtime.lib._probe import compile_scene, measure
+
+pytestmark = pytest.mark.node
+
+
+def test_normal_texture_resolution_preserves_wave_slopes():
+ out = measure("""
+import { makeWaterNormals } from './lib/water.js';
+const slopes = (size, broadband) => {
+ const texture = makeWaterNormals(size, {broadband}), data = texture.image.data;
+ let sum = 0;
+ for(let i = 0; i < data.length; i += 4) {
+ const x = data[i] / 255 * 2 - 1, y = data[i + 1] / 255 * 2 - 1, z = data[i + 2] / 255 * 2 - 1;
+ sum += (x * x + y * y) / (z * z);
+ }
+ texture.dispose(); return Math.sqrt(sum / (data.length / 4));
+};
+console.log(JSON.stringify({ narrow: [128, 256, 512].map(s => slopes(s, false)),
+ broad: [128, 256, 512].map(s => slopes(s, true)) }));
+""", ("water.js",))
+ for spectrum in out.values():
+ assert spectrum == pytest.approx([spectrum[1]] * 3, rel=0.025), out
+ # The default 256px appearance is preserved, not flattened to the 512px one.
+ assert out["narrow"][1] == pytest.approx(0.6003103576558382), out
+
+
+def test_underwater_extinction_is_finite_nonnegative_and_caller_owned():
+ out = measure("""
+import * as THREE from 'three';
+import { patchUnderwater } from './lib/submerged.js';
+const invalid = [-1, NaN, Infinity, [-1, .2, .3], [0, NaN, 1], [0, 1],
+ new THREE.Vector3(0, -.2, .3), new THREE.Vector3(0, Infinity, .3)];
+let rejected = 0;
+for(const extinction of invalid) {
+ const material = new THREE.MeshStandardMaterial();
+ try { patchUnderwater(material, {extinction}); }
+ catch(error) { if(error instanceof RangeError) rejected++; else throw error; }
+ material.dispose();
+}
+const input = new THREE.Vector3(0, .2, .3), material = new THREE.MeshStandardMaterial();
+patchUnderwater(material, {extinction: input});
+const before = material.userData.uniforms.uSubExt.value.toArray(); input.set(1, 1, 1);
+console.log(JSON.stringify({rejected, total: invalid.length, before,
+ after: material.userData.uniforms.uSubExt.value.toArray()}));
+material.dispose();
+""", ("submerged.js",))
+ assert out["rejected"] == out["total"], out
+ assert out["before"] == out["after"] == [0, 0.2, 0.3], out
+
+
+def test_water_sums_fill_and_caustics_follow_the_refracted_beam():
+ code, output = compile_scene(r"""
+import * as THREE from 'three';
+import { makeOcean } from './lib/water.js';
+import { patchCaustics } from './lib/caustics.js';
+import { withRendererState } from './lib/shader.js';
+export function createScene({renderer}) {
+ const scene = new THREE.Scene(), camera = new THREE.PerspectiveCamera(45, 1, .1, 50);
+ camera.position.set(0, 4, 5); camera.lookAt(0, 0, 0); camera.updateMatrixWorld(true);
+ const sky = new THREE.HemisphereLight(0x6ca1ca, 0x101010, .7);
+ const fill = new THREE.AmbientLight(0xc99771, .45);
+ const other = new THREE.AmbientLight(0x637486, .3);
+ const key = new THREE.DirectionalLight(0xffbbaa, 2); key.position.set(4, 7, 1);
+ key.target.position.set(1, 2, -2); scene.add(sky, fill, other, key, key.target);
+ const water = makeOcean(6, 6, { rttSize: 64 }); scene.add(water); scene.updateMatrixWorld(true);
+ const checkColor = (a, b) => {
+ if (Math.max(...a.toArray().map((v, i) => Math.abs(v - b.toArray()[i]))) > 1e-10)
+ throw Error('Water omitted ambient/hemisphere illumination');
+ };
+ water.onBeforeRender(renderer, scene, camera);
+ checkColor(water.material.uniforms.ambientColor.value, sky.color.clone().multiplyScalar(.7)
+ .add(fill.color.clone().multiplyScalar(.45)).add(other.color.clone().multiplyScalar(.3)).multiplyScalar(1 / Math.PI));
+ const expectedDirection = key.position.clone().sub(key.target.position).normalize();
+ if(water.material.uniforms.sunDirection.value.distanceTo(expectedDirection) > 1e-10) throw Error('Water ignored light target');
+ sky.visible = false; fill.visible = false; other.visible = false;
+ water.onBeforeRender(renderer, scene, camera);
+ checkColor(water.material.uniforms.ambientColor.value, new THREE.Color(0, 0, 0));
+ scene.remove(water); water.userData.dispose();
+ const pinned = makeOcean(6, 6, { rttSize: 64, ambient: 0x123456, sunDir: new THREE.Vector3(1, 2, 3), sunColor: 0xabcdef });
+ scene.add(pinned); scene.updateMatrixWorld(true); pinned.onBeforeRender(renderer, scene, camera);
+ checkColor(pinned.material.uniforms.ambientColor.value, new THREE.Color(0x123456));
+ checkColor(pinned.material.uniforms.sunColor.value, new THREE.Color(0xabcdef));
+ if(pinned.material.uniforms.sunDirection.value.distanceTo(new THREE.Vector3(1, 2, 3).normalize()) > 1e-10) throw Error('Water changed pinned direction');
+ scene.remove(pinned); pinned.userData.dispose();
+
+ const basin = new THREE.Scene(), top = new THREE.OrthographicCamera(-1, 1, 1, -1, .1, 20);
+ top.position.set(0, 4, 0); top.up.set(0, 0, -1); top.lookAt(0, -1, 0); top.updateMatrixWorld(true);
+ const sun = new THREE.Vector3(1, .1, 0).normalize();
+ const material = new THREE.MeshStandardMaterial({color: 0xffffff, roughness: 1, side: THREE.DoubleSide});
+ patchCaustics(material, {sunDir: sun, level: 0, strength: 1, color: 0xffffff, depthFade: 3});
+ const geometry = new THREE.PlaneGeometry(2, 2); geometry.rotateX(-Math.PI / 2);
+ const surface = new THREE.Mesh(geometry, material); surface.position.y = -1; basin.add(surface);
+ const target = new THREE.WebGLRenderTarget(32, 32, {type: THREE.FloatType});
+ const pixels = new Float32Array(32 * 32 * 4), u = material.userData.uniforms;
+ function energy(normal) {
+ for(let i = 0; i < geometry.attributes.normal.count; i++) geometry.attributes.normal.setXYZ(i, ...normal);
+ geometry.attributes.normal.needsUpdate = true;
+ renderer.setRenderTarget(target); renderer.render(basin, top); renderer.readRenderTargetPixels(target, 0, 0, 32, 32, pixels);
+ const sum = [0, 0, 0];
+ for(let i = 0; i < pixels.length; i += 4) for(let c = 0; c < 3; c++) sum[c] += pixels[i + c];
+ return sum;
+ }
+ try { withRendererState(renderer, () => {
+ renderer.toneMapping = THREE.NoToneMapping;
+ const upward = energy([0, 1, 0]), facing = energy([1, 0, 0]), away = energy([-1, 0, 0]);
+ const slide = u.uCauSlide.value.length(), cosWater = 1 / Math.hypot(1, slide);
+ if(upward[0] <= 0 || Math.abs(facing[0] / upward[0] - slide) > .002) throw Error('Caustic incidence used the air ray');
+ if(Math.max(...away) > 1e-6) throw Error('Back-facing surface received direct caustics');
+ // Move to twice the depth while preserving the surface entry point. The
+ // pattern, focus and incidence stay fixed; only Beer-Lambert changes.
+ surface.position.set(-u.uCauSlide.value.x, -2, -u.uCauSlide.value.y);
+ top.position.x = surface.position.x; top.position.z = surface.position.z; top.updateMatrixWorld(true);
+ const deep = energy([0, 1, 0]);
+ for(let c = 0; c < 3; c++) {
+ const expected = Math.exp(-u.uCauAbs.value.getComponent(c) / cosWater);
+ if(Math.abs(deep[c] / upward[c] - expected) > .003) throw Error('Caustics absorbed over vertical depth instead of beam length');
+ }
+ u.uCauSun.value.y *= -1;
+ if(Math.max(...energy([0, 1, 0])) > 1e-6) throw Error('A set sun still produced caustics');
+ }); } finally { target.dispose(); geometry.dispose(); material.dispose(); }
+ return {scene: new THREE.Scene(), cameras: [{name: 'probe', position: [0, 3, 5], lookAt: [0, 0, 0]}]};
+}
+""", ("water.js", "caustics.js"), audit_module="src/scene.js")
+ assert code == 0, output
diff --git a/harness/tests/scene_runtime/lib/test_watermist.py b/harness/tests/scene_runtime/lib/test_watermist.py
index 9241295a..69b161b8 100644
--- a/harness/tests/scene_runtime/lib/test_watermist.py
+++ b/harness/tests/scene_runtime/lib/test_watermist.py
@@ -38,3 +38,17 @@ console.log(JSON.stringify({
assert out["none"] == out["high"], out
assert out["noneDir"] == [0, 1, 0], out
assert abs(sum(v * v for v in out["unit"]) - 1.0) < 1e-6, out
+
+
+def test_zero_mist_density_has_zero_optical_opacity():
+ out = measure("""
+import { makeWaterMist } from './lib/watermist.js';
+const alpha = density => {
+ const mist = makeWaterMist({ density, extent: 4 });
+ const a = mist.getObjectByName('MistCards').material.uniforms.uAlpha.value;
+ mist.userData.dispose(); return a;
+};
+console.log(JSON.stringify({ off: alpha(0), faint: alpha(.0001), normal: alpha(.5) }));
+""", _LIBS)
+ assert out["off"] == 0, out
+ assert 0 < out["faint"] < out["normal"], out
diff --git a/harness/tests/scene_runtime/test_backdrop.py b/harness/tests/scene_runtime/test_backdrop.py
index 948107d9..cd672a4f 100644
--- a/harness/tests/scene_runtime/test_backdrop.py
+++ b/harness/tests/scene_runtime/test_backdrop.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
+from pathlib import Path
import pytest
@@ -12,6 +13,7 @@ from tests.scene_runtime.conftest import needs_node, run_node_json
pytestmark = [pytest.mark.node, needs_node]
RUNTIME_JS = get_settings().runtime_js_dir()
+LIB_DIR = Path(__file__).resolve().parents[2] / "codeverse3d/languages/scene_threejs/starter/src/lib"
CASES = [
# (name, box size [sx, sy, sz], instanced, content span, expected)
@@ -87,6 +89,50 @@ console.log(JSON.stringify({{ content: census.content_bbox, all: census.bbox, fr
assert got["all"]["min"][0] < -270 # background geometry is retained and still counted
+def test_explicit_sky_metadata_requires_non_depth_writing_materials():
+ got = run_node_json(f"""
+import * as THREE from 'three';
+import {{ classifyBackdrop, drawableBox }} from '{RUNTIME_JS}/lib/backdrop.mjs';
+const clear = new THREE.MeshBasicMaterial({{ depthWrite: false }});
+const solid = new THREE.MeshBasicMaterial();
+const classify = (material, marker) => {{
+ const mesh = new THREE.Mesh(new THREE.BoxGeometry(10, 10, 10), material);
+ mesh.name = 'WeatherPart'; mesh.userData.sceneBackdrop = marker;
+ return classifyBackdrop(mesh, drawableBox(mesh, THREE));
+}};
+console.log(JSON.stringify([
+ classify(clear, 'sky'), classify(solid, 'sky'), classify([clear, solid], 'sky'),
+ classify(clear, undefined), classify(clear, 'content'),
+]));
+""")
+ assert got == ["sky", "content", "content", "content", "content"]
+
+
+def test_compact_clouds_preserve_content_framing_with_custom_names_and_scale():
+ got = run_node_json(f"""
+import * as THREE from 'three';
+import {{ makeClouds, makeCirrus }} from '{LIB_DIR}/clouds.js';
+import {{ sceneCensus }} from '{RUNTIME_JS}/lib/host_census.mjs';
+import {{ framingBox }} from '{RUNTIME_JS}/lib/orbit.mjs';
+const results = [];
+for (const factory of [makeClouds, makeCirrus]) for (const custom of [false, true]) {{
+ const scene = new THREE.Scene();
+ const subject = new THREE.Mesh(new THREE.BoxGeometry(10, 10, 10), new THREE.MeshStandardMaterial());
+ subject.name = 'House'; scene.add(subject);
+ const cloud = factory({{ count: 1, area: 600, quality: 'low', ...(custom ? {{ name: 'WeatherDeck' }} : {{}}) }});
+ if (custom) cloud.scale.setScalar(.01);
+ scene.add(cloud);
+ const census = sceneCensus(scene, THREE);
+ results.push({{ kind: census.groups[1].kind, framed: framingBox(census) }});
+ cloud.userData.dispose(); subject.geometry.dispose(); subject.material.dispose();
+}}
+console.log(JSON.stringify(results));
+""")
+ for result in got:
+ assert result["kind"] == "sky", result
+ assert result["framed"] == {"min": [-5, -5, -5], "max": [5, 5, 5], "size": [10, 10, 10]}, result
+
+
#: names on both sides of every JS name rule: acronyms, instance separators, long numeric ids
NAMES = ["Leg_2", "Rock.003", "Fence-1", "Leg2", "DonkeyCart_800006", "Leg_", "Planter_12", "LEDStairs",
"HDRISky", "UVGround", "GPUTerrain", "PondWater", "pond_water", "SkyAtmosphereBand0", "TV-Stand.2", ""]