Skip to content

Official Codebase of 3DCodeVerse

Python

effect library: one option rule, one point reader, and sampleHeight is null off its patch

gaoypenga226143f2479
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 fd02c419..514fc51b 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/clouds.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/clouds.js
@@ -4,7 +4,7 @@
import * as THREE from 'three';
import { attachDisposal, snapshotResources } from './lifecycle.js';
import { mulberry32, fbm2 } from './noise.js';
-import { makeShaderMaterial, keepOutOfDepthPasses, readWind, sunVector } from './shader.js';
+import { intOption, makeShaderMaterial, keepOutOfDepthPasses, option, positive, readWind, sunVector } 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
@@ -61,9 +61,8 @@ export function cloudTexture(seed = 7, size = 256) {
}
function puffTexture(seed, size, cirrus) {
- if (!Number.isSafeInteger(seed) || !Number.isInteger(size) || size < 16 || size > 1024) {
- throw new RangeError('cloudTexture: use an integer seed and size in 16..1024');
- }
+ option(seed, null, '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) => ({
@@ -147,19 +146,14 @@ function cloudAtlas(seed, cirrus = false) {
*/
export function makeClouds(opts = {}) {
const p = PRESETS[opts.preset || 'day'] || PRESETS.day;
- const seed = opts.seed ?? 7;
- const count = opts.count ?? p.count ?? 14;
- const area = opts.area ?? 2600;
- const altitude = opts.altitude ?? p.altitude ?? 260;
- const spread = opts.spread ?? p.spread ?? 120;
- const alpha = opts.alpha ?? p.alpha ?? 0.92;
+ 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 = opts.stretch ?? p.stretch ?? 1.0;
- if (!Number.isSafeInteger(seed) || !Number.isInteger(count) || count < 0 || count > 1000 ||
- ![area, altitude, spread, alpha, wind, stretch].every(Number.isFinite) ||
- area <= 0 || spread < 0 || alpha < 0 || alpha > 1 || stretch <= 0) {
- throw new RangeError('makeClouds: invalid seed, count, area, altitude, spread, alpha, wind or stretch');
- }
+ const stretch = positive(opts.stretch, p.stretch ?? 1.0, 'makeClouds: stretch');
const rand = mulberry32(seed);
const rnd2 = mulberry32(seed + 977);
const puffs = [];
@@ -407,7 +401,7 @@ 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 = opts.seed ?? 23;
+ 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
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloudvolume.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloudvolume.js
index c586b58e..7f48241e 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloudvolume.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloudvolume.js
@@ -15,7 +15,7 @@
* reconstruction or external textures are required.
*/
import * as THREE from 'three';
-import { makeShaderMaterial, keepOutOfDepthPasses, makeLightProbe, readWind } from './shader.js';
+import { makeShaderMaterial, keepOutOfDepthPasses, makeLightProbe, option, readWind, vector } from './shader.js';
import { attachDisposal, snapshotResources } from './lifecycle.js';
import { bakeFbm3, dataTexture3D, mulberry32, sampleGrid3 } from './noise.js';
@@ -31,14 +31,6 @@ const smooth = (a, b, x) => {
return t * t * (3 - 2 * t);
};
-function vector(value, fallback, length, label) {
- const values = value?.toArray ? value.toArray() : value ?? fallback;
- if (!Array.isArray(values) || values.length !== length || !values.every(Number.isFinite)) {
- throw new RangeError(`makeCloudVolume: ${label} must contain ${length} finite numbers`);
- }
- return values;
-}
-
function densityTexture(seed) {
const random = mulberry32(seed);
const { values: noiseField, lattices } = bakeFbm3(random, RESOLUTION, [4, 8, 16, 32]);
@@ -163,12 +155,12 @@ float cloudSunDepth(vec3 position, float jitter) {
`;
/**
- * size: local [x,y,z] metres (default [600,180,360]), seed: integer,
+ * size: local [x,y,z] metres (default [600,180,360]), seed (19),
* coverage: 0..1 (.55), density: extinction / metre (.028),
* quality: 'low'|'balanced'|'high', wind: local [x,z] metres/second,
* advecting density detail through a bounded stationary form. Move the Mesh
* itself for whole-cloud travel; the cloud scaffold never wraps across its box.
- * sunDirection: WORLD direction toward the sun, sunColor and skyColor:
+ * sunDir: WORLD direction toward the sun (`sunDirection` is read too), sunColor and skyColor:
* linear-light THREE.Color or sRGB hex. sunIntensity scales the strongest
* visible directional light (1.25 at the standard 5.4-unit daylight rig).
* Ambient/hemisphere lights and scene.environment supply the sky contribution.
@@ -178,23 +170,22 @@ float cloudSunDepth(vec3 position, float jitter) {
* the GPU before optical extinction. setSunDirection() supports moving light.
*/
export function makeCloudVolume(opts = {}) {
- const size = vector(opts.size, [600, 180, 360], 3, 'size');
+ const size = vector(opts.size, [600, 180, 360], 3, 'makeCloudVolume: size');
+ if (size.some((v) => v <= 0 || v > 100000)) throw new RangeError('makeCloudVolume: size must be in (0, 100000] metres');
const w = readWind(opts.wind, [2.5, .4], 'makeCloudVolume wind'), wind = [w.x, w.z];
- const direction = vector(opts.sunDirection, [-.5, .7, -.3], 3, 'sunDirection');
- const seed = opts.seed ?? 19;
- const coverage = opts.coverage ?? .55;
- const extinction = opts.density ?? .028;
- const detail = opts.detail ?? .65;
- const intensity = opts.sunIntensity ?? 1.25;
+ const sunOption = opts.sunDir ?? opts.sunDirection;
+ const direction = vector(sunOption, [-.5, .7, -.3], 3, 'makeCloudVolume: sunDir');
+ if (Math.hypot(...direction) < 1e-9) throw new RangeError('makeCloudVolume: sunDir must be nonzero');
+ const seed = option(opts.seed, 19, 'makeCloudVolume: seed');
+ const coverage = option(opts.coverage, .55, 'makeCloudVolume: coverage', 0, 1);
+ const extinction = option(opts.density, .028, 'makeCloudVolume: density', 0, 10);
+ const detail = option(opts.detail, .65, 'makeCloudVolume: detail', 0, 1);
+ const intensity = option(opts.sunIntensity, 1.25, 'makeCloudVolume: sunIntensity', 0);
const quality = opts.quality ?? 'balanced';
- if (!Number.isSafeInteger(seed) || size.some((v) => v <= 0 || v > 100000) ||
- ![coverage, extinction, intensity, detail].every(Number.isFinite) || coverage < 0 || coverage > 1 ||
- extinction < 0 || extinction > 10 || intensity < 0 || detail < 0 || detail > 1 || !Object.hasOwn(TIERS, quality) || Math.hypot(...direction) < 1e-9) {
- throw new RangeError('makeCloudVolume: invalid dimensions, seed, coverage, density, sun intensity or quality');
- }
+ if (!Object.hasOwn(TIERS, quality)) throw new RangeError(`makeCloudVolume: quality must be one of ${Object.keys(TIERS)}`);
const tier = TIERS[quality];
const texture = densityTexture(seed);
- let sunPinned = opts.sunDirection !== undefined;
+ let sunPinned = sunOption !== undefined && sunOption !== null;
const sun = new THREE.Vector3(...direction).normalize();
const sunTint = new THREE.Color(opts.sunColor ?? 0xfff3dc);
const skyTint = new THREE.Color(opts.skyColor ?? 0x9eb9da);
@@ -294,7 +285,7 @@ export function makeCloudVolume(opts = {}) {
material.uniforms.uTime.value = t;
};
mesh.userData.setSunDirection = (value) => {
- const values = vector(value, null, 3, 'sunDirection');
+ const values = vector(value, null, 3, 'CloudVolume.setSunDirection');
if (Math.hypot(...values) < 1e-9) throw new RangeError('CloudVolume: sunDirection must be nonzero');
sun.fromArray(values).normalize();
sunPinned = true;
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/fire.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/fire.js
index d50e6976..3bf5196a 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/fire.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/fire.js
@@ -20,10 +20,11 @@
import * as THREE from 'three';
import { attachDisposal, snapshotResources } from './lifecycle.js';
import { mulberry32 } from './noise.js';
-import { makeShaderMaterial, keepOutOfDepthPasses, patchStandard, readWind } from './shader.js';
+import { makeShaderMaterial, keepOutOfDepthPasses, option, patchStandard, readWind } from './shader.js';
-const finite = (v, fallback, lo, hi) => Number.isFinite(v)
- ? THREE.MathUtils.clamp(v, lo, hi) : fallback;
+// Fire CLAMPS a number outside its range (a flame too big or too bright is
+// still a flame); a value that is not a number throws like every option.
+const clamped = (v, fallback, lo, hi, label) => THREE.MathUtils.clamp(option(v, fallback, label), lo, hi);
const QUALITY = { low: 32, medium: 56, high: 88 };
const FIELD = /* glsl */`
@@ -175,10 +176,10 @@ function installDispose(group) {
*/
export function makeFire(opts = {}) {
const candle = opts.style === 'candle';
- const radius = finite(opts.radius, candle ? 0.009 : 0.35, 0.001, 20);
- const height = finite(opts.height, candle ? 0.055 : 1.1, 0.004, 50);
- const intensity = finite(opts.intensity, 1, 0, 8);
- const seed = finite(opts.seed, 7, -2147483648, 2147483647) | 0;
+ const radius = clamped(opts.radius, candle ? 0.009 : 0.35, 0.001, 20, 'makeFire: radius');
+ const height = clamped(opts.height, candle ? 0.055 : 1.1, 0.004, 50, 'makeFire: height');
+ const intensity = clamped(opts.intensity, 1, 0, 8, 'makeFire: intensity');
+ const seed = clamped(opts.seed, 7, -2147483648, 2147483647, 'makeFire: seed') | 0;
const w = readWind(opts.wind, [0, 0], 'makeFire wind');
// bounded to ±.6 per axis by scaling both, so a strong wind still leans the way it blows
const lean = 0.6 / Math.max(0.6, Math.abs(w.x), Math.abs(w.z));
@@ -207,7 +208,7 @@ export function makeFire(opts = {}) {
group.add(volume);
const random = mulberry32(seed);
- const count = Math.round(finite(opts.embers, candle ? 0 : 26, 0, 256));
+ const count = Math.round(clamped(opts.embers, candle ? 0 : 26, 0, 256, 'makeFire: embers'));
const particles = Array.from({ length: count }, () => ({
phase: random(), life: 1.5 + random() * 2.0,
x: (random() - 0.5) * radius * 1.5, z: (random() - 0.5) * radius * 1.5,
@@ -227,11 +228,11 @@ export function makeFire(opts = {}) {
box.expandByPoint(new THREE.Vector3(radius * 1.2 + Math.abs(wind[0]) * height * 2.1,
height * 2.5 + radius * 0.05, radius * 1.2 + Math.abs(wind[1]) * height * 2.1));
}
- const lightIntensity = finite(opts.lightIntensity, candle ? 0.9 : 14, 0, 10000);
+ const lightIntensity = clamped(opts.lightIntensity, candle ? 0.9 : 14, 0, 10000, 'makeFire: lightIntensity');
let light;
if (opts.light !== false) {
light = new THREE.PointLight(0xffab53, lightIntensity,
- finite(opts.lightDistance, height * 8, 0, 1000), 2);
+ clamped(opts.lightDistance, height * 8, 0, 1000, 'makeFire: lightDistance'), 2);
light.name = 'FireLight'; light.position.y = height * 0.27;
group.add(light);
}
@@ -313,9 +314,9 @@ function waxGeometry(radius, height, seed) {
* lightIntensity=.8 candela approximates one candle; scene exposure is unchanged.
*/
export function makeCandle(opts = {}) {
- const radius = finite(opts.radius, 0.032, 0.004, 2);
- const height = finite(opts.height, 0.16, 0.015, 8);
- const seed = finite(opts.seed, 13, -2147483648, 2147483647) | 0;
+ const radius = clamped(opts.radius, 0.032, 0.004, 2, 'makeCandle: radius');
+ const height = clamped(opts.height, 0.16, 0.015, 8, 'makeCandle: height');
+ const seed = clamped(opts.seed, 13, -2147483648, 2147483647, 'makeCandle: seed') | 0;
const lit = opts.lit !== false;
const group = new THREE.Group(); group.name = 'Candle';
const wax = new THREE.MeshPhysicalMaterial({ color: opts.color ?? 0xe9cf9b,
@@ -343,7 +344,7 @@ export function makeCandle(opts = {}) {
pool.name = 'MoltenWaxPool'; pool.rotation.x = -Math.PI / 2; pool.position.y = height * 0.947;
group.add(pool);
- const random = mulberry32(seed), drips = Math.round(finite(opts.drips, 7, 0, 24));
+ const random = mulberry32(seed), drips = Math.round(clamped(opts.drips, 7, 0, 24, 'makeCandle: drips'));
const dripMat = wax;
for (let i = 0; i < drips; i++) {
const angle = random() * Math.PI * 2;
@@ -372,10 +373,10 @@ export function makeCandle(opts = {}) {
wick.name = 'CharredWick'; group.add(wick);
let flame;
if (lit) {
- const flameHeight = finite(opts.flameHeight, radius * 1.47, 0.01, 3);
+ const flameHeight = clamped(opts.flameHeight, radius * 1.47, 0.01, 3, 'makeCandle: flameHeight');
flame = makeFire({ radius: flameHeight * 0.17, height: flameHeight, style: 'candle',
seed, wind: opts.wind, quality: opts.quality || 'high', light: opts.light,
- lightIntensity: finite(opts.lightIntensity, 0.8, 0, 10000), lightDistance: Math.max(1, height * 14),
+ lightIntensity: clamped(opts.lightIntensity, 0.8, 0, 10000, 'makeCandle: lightIntensity'), lightDistance: Math.max(1, height * 14),
intensity: opts.intensity });
flame.position.y = height * 0.944 + wickHeight * 0.6;
group.add(flame);
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/firefield.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/firefield.js
index c7c8d9c1..04d3c908 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/firefield.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/firefield.js
@@ -29,7 +29,7 @@
*/
import * as THREE from 'three';
import { bakeFbm3, dataTexture3D, mulberry32, sampleGrid3 } from './noise.js';
-import { makeShaderMaterial, keepOutOfDepthPasses, makeLightProbe, readWind, withRendererState } from './shader.js';
+import { intOption, makeShaderMaterial, keepOutOfDepthPasses, makeLightProbe, option, readWind, vector, withRendererState } from './shader.js';
import { snapshotResources, attachDisposal } from './lifecycle.js';
const TIERS = {
@@ -41,18 +41,6 @@ const NOISE_RESOLUTION = 48;
const clamp = (x, a = 0, b = 1) => Math.max(a, Math.min(b, x));
const smooth = (a, b, x) => { const t = clamp((x - a) / (b - a)); return t * t * (3 - 2 * t); };
const fract = x => x - Math.floor(x);
-function number(value, fallback, min, max, label) {
- const v = value ?? fallback;
- if (!Number.isFinite(v) || v < min || v > max) throw new RangeError(`makeFireField: invalid ${label}`);
- return v;
-}
-function vector(value, fallback, length, label) {
- const v = value?.toArray ? value.toArray() : value ?? fallback;
- if (!Array.isArray(v) || v.length !== length || !v.every(Number.isFinite)) {
- throw new RangeError(`makeFireField: ${label} needs ${length} finite components`);
- }
- return v.slice();
-}
function noiseTexture(seed) {
const { values } = bakeFbm3(mulberry32(seed), NOISE_RESOLUTION, [4, 8, 16], 4);
return dataTexture3D(Uint8Array.from(values, v => Math.round(clamp(v) * 255)), NOISE_RESOLUTION, true);
@@ -306,22 +294,21 @@ function depthCapture(roots, resolution) {
export function makeFireField(opts = {}) {
const input=opts.emitters??[{position:[0,0,0],radius:.3,height:1,strength:1}];
if(!Array.isArray(input)||input.length<1||input.length>16)throw new RangeError('makeFireField: needs1–16 emitters');
- const emitters=input.map((e,i)=>({position:vector(e.position,[0,0,0],3,`emitter${i} position`),
- radius:number(e.radius,.3,.025,8,'emitter radius'),height:number(e.height,1,.08,25,'emitter height'),
- strength:number(e.strength,1,0,4,'emitter strength')}));
+ const emitters=input.map((e,i)=>({position:vector(e.position, [0,0,0], 3, `makeFireField: emitter${i} position`),
+ radius:option(e.radius, .3, 'makeFireField: emitter radius', .025, 8),height:option(e.height, 1, 'makeFireField: emitter height', .08, 25),
+ strength:option(e.strength, 1, 'makeFireField: emitter strength', 0, 4)}));
const activeEmitters=emitters.filter(e=>e.strength>0);
const sources=activeEmitters.length?activeEmitters:[emitters[0]];
- const seed=number(opts.seed,7,-2147483648,2147483647,'seed');
- if(!Number.isInteger(seed))throw new RangeError('makeFireField: seed must be an integer');
+ const seed=option(opts.seed, 7, 'makeFireField: seed');
const quality=opts.quality??'balanced';if(!Object.hasOwn(TIERS,quality))throw new RangeError('makeFireField: invalid quality');
const tier=TIERS[quality],w=readWind(opts.wind,[.12,0],'makeFireField wind'),wind=[w.x,w.z];
if(wind.some(v=>Math.abs(v)>8))throw new RangeError('makeFireField: wind exceeds8m/s');
- const intensity=number(opts.intensity,1,0,8,'intensity'),turbulence=number(opts.turbulence,1,0,2,'turbulence');
+ const intensity=option(opts.intensity, 1, 'makeFireField: intensity', 0, 8),turbulence=option(opts.turbulence, 1, 'makeFireField: turbulence', 0, 2);
const radius=sources.reduce((s,e)=>s+e.radius,0)/sources.length;
- const height=Math.max(...sources.map(e=>e.height)),rise=number(opts.riseSpeed,.75+Math.sqrt(height)*.75,.1,12,'riseSpeed');
+ const height=Math.max(...sources.map(e=>e.height)),rise=option(opts.riseSpeed, .75+Math.sqrt(height)*.75, 'makeFireField: riseSpeed', .1, 12);
const smoke=opts.smoke===false?{density:0}:opts.smoke??{};
- const smokeHeight=number(smoke.height,height*3,Math.max(.1,height),80,'smoke height');
- const smokeDensity=number(smoke.density,.65,0,5,'smoke density');
+ const smokeHeight=option(smoke.height, height*3, 'makeFireField: smoke height', Math.max(.1,height), 80);
+ const smokeDensity=option(smoke.density, .65, 'makeFireField: smoke density', 0, 5);
const warp=Math.max(.025,Math.sqrt(radius)*.25),box=new THREE.Box3();
for(const e of sources){
const top=smokeDensity>0?Math.max(e.height*1.1,smokeHeight):e.height*1.1;
@@ -341,14 +328,12 @@ export function makeFireField(opts = {}) {
const emptyDepth=new THREE.DataTexture(new Uint8Array([255,255,255,255]),1,1);emptyDepth.needsUpdate=true;
const roots=opts.occluders??[];
if(!Array.isArray(roots)||roots.some(o=>!o?.isObject3D))throw new TypeError('makeFireField: occluders must be Object3D roots');
- const depthResolution=number(opts.depthResolution,512,64,2048,'depthResolution');
- if(!Number.isInteger(depthResolution))throw new RangeError('makeFireField: depthResolution must be integer');
+ const depthResolution=intOption(opts.depthResolution, 512, 'makeFireField: depthResolution', 64, 2048);
const depth=roots.length?depthCapture(roots.slice(),depthResolution):null;
const lighting=opts.lighting===false?{count:0}:opts.lighting??{};
- const requestedLights=number(lighting.count,Math.min(2,activeEmitters.length),0,4,'light count');
+ const requestedLights=intOption(lighting.count, Math.min(2,activeEmitters.length), 'makeFireField: light count', 0, 4);
const lightCount=Math.min(requestedLights,activeEmitters.length);
- if(!Number.isInteger(requestedLights))throw new RangeError('makeFireField: light count must be integer');
- const lightIntensity=number(lighting.intensity,12*radius/.3,0,20000,'light intensity');
+ const lightIntensity=option(lighting.intensity, 12*radius/.3, 'makeFireField: light intensity', 0, 20000);
const uniforms={
uTime:{value:0},uSourceAtlas:{value:atlas},uFieldNoise:{value:noise},uOpaqueDepth:{value:emptyDepth},
uBoxMin:{value:box.min.clone()},uBoxSize:{value:size.clone()},
@@ -397,13 +382,12 @@ export function makeFireField(opts = {}) {
light.position.fromArray(e.position);light.position.y+=e.height*.24;light.userData.sourceStrength=e.strength;group.add(light);lights.push(light);
}
const emberOptions=opts.embers===false?{count:0}:opts.embers??{};
- const requestedEmbers=number(emberOptions.count,48,0,512,'ember count');
+ const requestedEmbers=intOption(emberOptions.count, 48, 'makeFireField: ember count', 0, 512);
const count=activeEmitters.length?requestedEmbers:0;
- if(!Number.isInteger(requestedEmbers))throw new RangeError('makeFireField: ember count must be integer');
- const emberSize=vector(emberOptions.size,[.0015,.006],2,'ember size');
- const lifetime=vector(emberOptions.lifetime,[2,4],2,'ember lifetime');
+ const emberSize=vector(emberOptions.size, [.0015,.006], 2, 'makeFireField: ember size');
+ const lifetime=vector(emberOptions.lifetime, [2,4], 2, 'makeFireField: ember lifetime');
if(emberSize[0]<=0||emberSize[1]<emberSize[0]||emberSize[1]>.12||lifetime[0]<=0||lifetime[1]<lifetime[0]||lifetime[1]>30)throw new RangeError('makeFireField: invalid ember size/lifetime');
- const emberRise=number(emberOptions.riseSpeed,rise,.1,20,'ember rise speed');
+ const emberRise=option(emberOptions.riseSpeed, rise, 'makeFireField: ember rise speed', .1, 20);
const random=mulberry32(seed^0x1837),particles=Array.from({length:count},()=>{
const total=activeEmitters.reduce((sum,e)=>sum+e.radius*e.radius*e.strength,0);
let pick=random()*total,emitter=activeEmitters[activeEmitters.length-1];
@@ -425,7 +409,7 @@ export function makeFireField(opts = {}) {
const ember={position:new THREE.Vector3()};
let disposed=false;
group.userData.update=group.userData.tick=(t=0)=>{
- if(disposed)return;number(t,0,-1e9,1e9,'time');material.uniforms.uTime.value=t;
+ if(disposed)return;option(t, 0, 'makeFireField: time', -1e9, 1e9);material.uniforms.uTime.value=t;
lights.forEach((light,i)=>{const flicker=.83+.10*Math.sin(t*(3.1+i*.47)+seed+i*2)+.07*Math.sin(t*7.3+seed*.7+i);
light.intensity=lightIntensity*flicker*intensity*light.userData.sourceStrength;
uniforms.uFireLights.value[i].set(light.position.x,light.position.y,light.position.z,light.intensity*.10);});
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ice.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ice.js
index 6c2daa87..4de69c74 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ice.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ice.js
@@ -190,7 +190,7 @@ function iceMaterial(opts, optical, maximumThickness) {
export function makeFracturedIce(opts = {}) {
for (const key of ['gap', 'frost', 'bubbles', 'chipping', 'heave', 'seed', 'roughness',
'transmission', 'attenuationDistance', 'envMapIntensity'])
- if (opts[key] !== undefined && !Number.isFinite(opts[key]))
+ if (opts[key] != null && !Number.isFinite(opts[key]))
throw new RangeError(`ice ${key} must be finite`);
let outline = null;
if (opts.outline !== undefined) {
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/meadow.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/meadow.js
index 3e6318fc..ee7d7a3e 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/meadow.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/meadow.js
@@ -21,15 +21,7 @@ import * as THREE from 'three';
import { attachDisposal, snapshotResources } from './lifecycle.js';
import { windOf } from './grass.js';
import { fbm2, mulberry32 } from './noise.js';
-import { patchStandard, shadowLike, tickShaders } from './shader.js';
-
-function finite(value, fallback, low, high, name) {
- const v = value === undefined ? fallback : value;
- if (!Number.isFinite(v) || v < low || v > high) {
- throw new RangeError(`makeMeadow: ${name} must be finite in [${low}, ${high}]`);
- }
- return v;
-}
+import { boundedSampler, option, patchStandard, shadowLike, tickShaders } from './shader.js';
// The rest mesh has an actual silhouette: GTAO's override material draws the
// real instance matrices instead of the origin-degenerate helper lattices.
@@ -229,21 +221,21 @@ function makeSeedHeads({count,rand,roots,botany,height,green,straw,dir,strength,
/** @returns {THREE.Group} Rooted meadow, animated by userData.update(seconds). */
export function makeMeadow(opts = {}) {
const dimensions = Array.isArray(opts.size) ? opts.size : [opts.size ?? 10, opts.size ?? 10];
- const sx = finite(dimensions[0], 10, .05, 1000, 'size[0]');
- const sz = finite(dimensions[1], 10, .05, 1000, 'size[1]');
- const density = finite(opts.density, 700, 0, 20000, 'density');
- const height = finite(opts.height, .38, .005, 4, 'height');
- const width = finite(opts.bladeWidth, .011, .0005, .15, 'bladeWidth');
- const seed = finite(opts.seed, 12, -2147483648, 2147483647, 'seed');
- const dry = finite(opts.dry, .12, 0, 1, 'dry');
- const diversity = finite(opts.diversity, .85, 0, 1, 'diversity');
- const seedHeads = finite(opts.seedHeads, .003, 0, .05, 'seedHeads');
- const maxBlades = Math.floor(finite(opts.maxBlades, 100000, 1, 300000, 'maxBlades'));
- const rows = Math.floor(finite(opts.segments, 5, 3, 12, 'segments'));
+ const sx = option(dimensions[0], 10, 'makeMeadow: size[0]', .05, 1000);
+ const sz = option(dimensions[1], 10, 'makeMeadow: size[1]', .05, 1000);
+ const density = option(opts.density, 700, 'makeMeadow: density', 0, 20000);
+ const height = option(opts.height, .38, 'makeMeadow: height', .005, 4);
+ const width = option(opts.bladeWidth, .011, 'makeMeadow: bladeWidth', .0005, .15);
+ const seed = option(opts.seed, 12, 'makeMeadow: seed');
+ const dry = option(opts.dry, .12, 'makeMeadow: dry', 0, 1);
+ const diversity = option(opts.diversity, .85, 'makeMeadow: diversity', 0, 1);
+ const seedHeads = option(opts.seedHeads, .003, 'makeMeadow: seedHeads', 0, .05);
+ const maxBlades = Math.floor(option(opts.maxBlades, 100000, 'makeMeadow: maxBlades', 1, 300000));
+ const rows = Math.floor(option(opts.segments, 5, 'makeMeadow: segments', 3, 12));
const wind = windOf(opts.wind);
- const strength = finite(wind.amp, .5, 0, 3, 'wind.strength');
+ const strength = option(wind.amp, .5, 'makeMeadow: wind.strength', 0, 3);
// The meadow's own gust clock runs 1.2x the shared wind's.
- const speed = finite(wind.speed * 1.2, 1.2, 0, 10, 'wind.speed');
+ const speed = option(wind.speed * 1.2, 1.2, 'makeMeadow: wind.speed', 0, 10);
const dir = wind.dir;
if (!Number.isFinite(dir.x) || !Number.isFinite(dir.y)) {
throw new TypeError('makeMeadow: wind direction must be [x,z] finite numbers');
@@ -369,7 +361,7 @@ export function makeMeadow(opts = {}) {
}
group.userData.bladeCount = matrices.length;
group.userData.roots = new Float32Array(roots);
- group.userData.sampleHeight = sampleHeight;
+ group.userData.sampleHeight = boundedSampler(sx, sz, heightAt);
group.userData.update = (t) => {
if (!Number.isFinite(t)) throw new RangeError('makeMeadow.update: time must be finite');
tickShaders(group, t);
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 a61e7f8c..af43c9a4 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/neon.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/neon.js
@@ -24,7 +24,7 @@ import * as THREE from 'three';
import {
keepOutOfDepthPasses, makeShaderMaterial, patchStandard, sweepProfile,
- seedLattice, tickShaders, toColor } from './shader.js';
+ readVec3, seedLattice, tickShaders, toColor } from './shader.js';
const _UP = new THREE.Vector3(0, 1, 0);
@@ -73,13 +73,6 @@ const TEMP_GLSL = [
const seedKey = (seed) => seedLattice(seed) * 0.011;
-/** A point in any accepted spelling as its own Vector3. */
-function toVec(p) {
- if (p && p.isVector3) return p.clone();
- if (Array.isArray(p)) return new THREE.Vector3(p[0], p[1], p[2]);
- return new THREE.Vector3(p.x || 0, p.y || 0, p.z || 0);
-}
-
/**
* One polyline or a set of them, always as an array of strokes.
*
@@ -96,7 +89,7 @@ function toStrokes(path) {
return raw.map((s) => {
const out = [];
for (const p of s) {
- const v = toVec(p);
+ const v = readVec3(p);
// A repeated point is a zero-length segment, and a
// zero-length segment has no tangent to build a frame on.
if (!out.length || out[out.length - 1].distanceTo(v) > 1e-6) {
@@ -560,7 +553,7 @@ export function patchNeonSpill(material, opts = {}) {
for (let i = 0; i < SPILL_MAX; i++) {
const s = list[i];
const p = s && (s.position || s.point || s);
- pos.push(s ? toVec(p) : new THREE.Vector3());
+ pos.push(readVec3(s && p));
col.push(s ? toColor(s.color, 0xff2e6a) : new THREE.Color(0, 0, 0));
}
return patchStandard(material, {
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ocean.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ocean.js
index 46ee8e95..deccd780 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ocean.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ocean.js
@@ -16,17 +16,11 @@
import * as THREE from 'three';
import { attachDisposal, snapshotResources } from './lifecycle.js';
import { mulberry32 } from './noise.js';
-import { GLSL_UTIL, makeLightProbe, planarCapture, readWind } from './shader.js';
+import { boundedSampler, GLSL_UTIL, makeLightProbe, option, planarCapture, readWind, vector } from './shader.js';
import { Reflector } from 'three/addons/objects/Reflector.js';
const TAU = Math.PI * 2;
const COUNT = 32;
-function finite(value, fallback, name, min, max = Infinity) {
- const v = value === undefined ? fallback : value;
- if (!Number.isFinite(v) || v < min || v > max)
- throw new RangeError(`makeOceanSurface: ${name} must be ${min}..${max}`);
- return v;
-}
const waveGLSL = /* glsl */ `
uniform float seaTime;
uniform vec4 seaWaves[32];
@@ -268,7 +262,7 @@ void main() {
* width/depth (metres); waveHeight (significant wave height Hs); wavelength (m);
* windDirection [x,z]; waterDepth (m); choppiness [0,1]; foam [0,2]; seed;
* segments [16,384] along the longest edge; reflectionSize [64,2048];
- * waterColor/shallowColor; optional sunDirection THREE.Vector3 or [x,y,z].
+ * waterColor/shallowColor; optional sunDir THREE.Vector3 or [x,y,z] (`sunDirection` is read too).
* shoreline: {direction:[x,z],position,width}; water is on the positive side
* of dot(localXZ,direction)-position. It softens waves and adds swash foam.
* Return Group: .userData.update(t,dt), sampleHeight(x,z,t), sampleSurface(x,z,t),
@@ -277,18 +271,18 @@ void main() {
*/
export function makeOceanSurface(opts = {}) {
let disposed = false;
- const width = finite(opts.width, 160, 'width', 1, 10000),
- depth = finite(opts.depth, 160, 'depth', 1, 10000);
- const height = finite(opts.waveHeight, 1.2, 'waveHeight', 0, 20);
- const length = finite(opts.wavelength, 18, 'wavelength', 1, 500);
- const waterDepth = finite(opts.waterDepth, 24, 'waterDepth', 0.1, 10000);
- const chop = finite(opts.choppiness, 0.85, 'choppiness', 0, 1);
- const foam = finite(opts.foam, 0.8, 'foam', 0, 2);
- const segments = Math.round(finite(opts.segments, 160, 'segments', 16, 384));
+ const width = option(opts.width, 160, 'makeOceanSurface: width', 1, 10000),
+ depth = option(opts.depth, 160, 'makeOceanSurface: depth', 1, 10000);
+ const height = option(opts.waveHeight, 1.2, 'makeOceanSurface: waveHeight', 0, 20);
+ const length = option(opts.wavelength, 18, 'makeOceanSurface: wavelength', 1, 500);
+ const waterDepth = option(opts.waterDepth, 24, 'makeOceanSurface: waterDepth', 0.1, 10000);
+ const chop = option(opts.choppiness, 0.85, 'makeOceanSurface: choppiness', 0, 1);
+ const foam = option(opts.foam, 0.8, 'makeOceanSurface: foam', 0, 2);
+ const segments = Math.round(option(opts.segments, 160, 'makeOceanSurface: segments', 16, 384));
const reflectionSize = Math.round(
- finite(opts.reflectionSize, 512, 'reflectionSize', 64, 2048)
+ option(opts.reflectionSize, 512, 'makeOceanSurface: reflectionSize', 64, 2048)
);
- const seed = finite(opts.seed, 42, 'seed', 0, 4294967295);
+ const seed = option(opts.seed, 42, 'makeOceanSurface: seed');
const wind = readWind(opts.windDirection, [1, 0.2], 'makeOceanSurface windDirection');
if (Math.hypot(wind.x, wind.z) < 1e-8)
throw new RangeError('makeOceanSurface: windDirection must be a nonzero [x,z]');
@@ -339,10 +333,10 @@ export function makeOceanSurface(opts = {}) {
shore = new THREE.Vector4(
direction[0] / norm,
direction[1] / norm,
- finite(spec.position, 0, 'shoreline.position', -10000, 10000),
+ option(spec.position, 0, 'makeOceanSurface: shoreline.position', -10000, 10000),
1
);
- shoreWidth = finite(spec.width, 5, 'shoreline.width', 0.1, 500);
+ shoreWidth = option(spec.width, 5, 'makeOceanSurface: shoreline.width', 0.1, 500);
}
// Bound BOTH the wave derivative and the changing shoaling envelope. A
// narrow beach under large waves otherwise folds horizontal coordinates,
@@ -350,21 +344,10 @@ export function makeOceanSurface(opts = {}) {
const shoreGradient = shore.w ? 1.5 / (shoreWidth * 1.7 + 0.5) : 0;
const derivativeBound = steepness + waves.reduce((sum, w) => sum + w.z, 0) * shoreGradient;
const chopScale = chop * Math.min(1.1, 0.88 / Math.max(derivativeBound, 1e-8));
- let sun = new THREE.Vector3(0.6, 0.7, 0.3).normalize();
- if (opts.sunDirection !== undefined) {
- if (
- !opts.sunDirection?.isVector3 &&
- (!Array.isArray(opts.sunDirection) || opts.sunDirection.length !== 3)
- ) {
- throw new RangeError('makeOceanSurface: sunDirection must be a Vector3 or [x,y,z]');
- }
- sun = opts.sunDirection.isVector3
- ? opts.sunDirection.clone()
- : new THREE.Vector3(...opts.sunDirection);
- if (![sun.x, sun.y, sun.z].every(Number.isFinite) || sun.length() < 1e-8)
- throw new RangeError('makeOceanSurface: invalid sunDirection');
- sun.normalize();
- }
+ const sunOption = opts.sunDir ?? opts.sunDirection;
+ const sun = new THREE.Vector3(...vector(sunOption, [0.6, 0.7, 0.3], 3, 'makeOceanSurface: sunDir'));
+ if (sun.length() < 1e-8) throw new RangeError('makeOceanSurface: sunDir must be nonzero');
+ sun.normalize();
const uniforms = THREE.UniformsUtils.merge([
THREE.UniformsLib.fog,
THREE.UniformsLib.lights,
@@ -476,7 +459,7 @@ export function makeOceanSurface(opts = {}) {
u.seaSunColor.value.setRGB(0, 0, 0);
u.seaAmbient.value.copy(ambient).add(sky).multiplyScalar(1 / Math.PI);
if (key) {
- if (opts.sunDirection === undefined) u.seaSun.value.copy(sunDirection);
+ if (sunOption === undefined || sunOption === null) u.seaSun.value.copy(sunDirection);
u.seaSunColor.value.copy(key.color);
u.seaKey.value.copy(key.color).multiplyScalar(key.intensity / Math.PI);
}
@@ -530,8 +513,8 @@ export function makeOceanSurface(opts = {}) {
const dz = evaluate(qx, qz + 0.005, t).sub(evaluate(qx, qz - 0.005, t));
return { position, normal: dz.cross(dx).normalize() };
};
- group.userData.sampleHeight = (x, z, t = time) =>
- group.userData.sampleSurface(x, z, t).position.y;
+ group.userData.sampleHeight = boundedSampler(width, depth,
+ (x, z, t = time) => group.userData.sampleSurface(x, z, t).position.y);
const owned = snapshotResources(group).add(sea.getRenderTarget());
owned.add({ dispose() { disposed = true; } });
attachDisposal(group, owned);
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/paving.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/paving.js
index e0c05db6..07f177e0 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/paving.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/paving.js
@@ -7,7 +7,7 @@
*/
import * as THREE from 'three';
import { mulberry32, fbm2 } from './noise.js';
-import { patchStandard } from './shader.js';
+import { boundedSampler, patchStandard } from './shader.js';
import { attachDisposal, snapshotResources } from './lifecycle.js';
const clamp=(x,a,b)=>Math.max(a,Math.min(b,x));
@@ -227,8 +227,7 @@ export function makePaving(opts={}) {
const key=x+','+z;if(!bins.has(key))bins.set(key,[]);bins.get(key).push(id);
}
}
- root.userData.sampleHeight=(x,z)=>{
- if(!Number.isFinite(x)||!Number.isFinite(z)||Math.abs(x)>width/2||Math.abs(z)>depth/2)return null;
+ root.userData.sampleHeight=boundedSampler(width,depth,(x,z)=>{
let height=bedHeight;
for(const id of bins.get(Math.floor(x/binSize)+','+Math.floor(z/binSize))??[]) {
const t=triangles[id],a=((t.bz-t.cz)*(x-t.cx)+(t.cx-t.bx)*(z-t.cz))/t.det;
@@ -236,7 +235,7 @@ export function makePaving(opts={}) {
if(Math.min(a,b,c)>=-1e-7)height=Math.max(height,a*t.ay+b*t.by+c*t.cy);
}
return height;
- };
+ });
root.userData.update=()=>{};
Object.assign(root.userData,{seed,stoneCount:ranges.length,stoneRanges:ranges,
stoneOutlines:outlines,size:[width,depth],stoneSize:layout.spacing,joint,relief,bedHeight});
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 b04ab33d..9bfd8766 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 { makeShaderMaterial, keepOutOfDepthPasses, readWind } from './shader.js';
+import { intOption, makeShaderMaterial, keepOutOfDepthPasses, option, positive, readWind, vector } from './shader.js';
const _UP = new THREE.Vector3(0, 1, 0);
@@ -120,34 +120,28 @@ function _quads(count) {
* non-shadowing, with `userData.update(t)` advancing the fall.
*/
export function makeRain(opts = {}) {
- const seed = opts.seed === undefined ? 5 : opts.seed;
- const count = opts.count === undefined ? 7000 : opts.count;
- const radius = opts.radius === undefined ? 16 : opts.radius;
- const height = opts.height === undefined ? 18 : opts.height;
- const speed = opts.speed === undefined ? 14 : opts.speed;
- const length = opts.length === undefined ? 0.6 : opts.length;
- const width = opts.width === undefined ? 0.014 : opts.width;
+ const seed = option(opts.seed, 5, 'makeRain: seed');
+ const count = intOption(opts.count, 7000, 'makeRain: count', 0, 1000000);
+ const radius = positive(opts.radius, 16, 'makeRain: radius');
+ const height = positive(opts.height, 18, 'makeRain: height');
+ const speed = positive(opts.speed, 14, 'makeRain: speed');
+ const length = positive(opts.length, 0.6, 'makeRain: length');
+ const width = positive(opts.width, 0.014, 'makeRain: width');
const w = readWind(opts.wind, [1.4, 0], 'makeRain wind'), wind = [w.x, w.z];
- const opacity = opts.opacity === undefined ? 0.42 : opts.opacity;
+ const opacity = option(opts.opacity, 0.42, 'makeRain: opacity', 0, 1);
const follow = opts.follow === false ? 0 : 1;
- const center = opts.center || [0, height * 0.5, 0];
+ const center = vector(opts.center, [0, height * 0.5, 0], 3, 'makeRain: center');
const surfaces = opts.surfaces ?? [];
- const shelterResolution = opts.shelterResolution ?? 32;
- const shelterUpdateDistance = opts.shelterUpdateDistance ?? Math.max(.5, radius * .20);
- const groundY = opts.groundY ?? -1e8;
- if (!Array.isArray(surfaces) || surfaces.some((surface) => !surface?.isObject3D) ||
- !Number.isInteger(shelterResolution) || shelterResolution < 8 || shelterResolution > 64 ||
- !Number.isFinite(shelterUpdateDistance) || shelterUpdateDistance <= 0 ||
- !Number.isFinite(groundY) || (opts.heightAt != null && typeof opts.heightAt !== 'function')) {
- throw new RangeError('makeRain: invalid surfaces, heightAt, groundY or shelter atlas options');
+ if (!Array.isArray(surfaces) || surfaces.some((surface) => !surface?.isObject3D)) {
+ throw new RangeError('makeRain: surfaces must be an array of Object3D');
}
-
- if (!Number.isInteger(count) || count < 0 || count > 1000000 ||
- ![radius, height, speed, length, width, opacity, ...center].every(Number.isFinite) ||
- radius <= 0 || height <= 0 || speed <= 0 || length <= 0 || width <= 0 || opacity < 0 || opacity > 1 ||
- center.length !== 3) {
- throw new RangeError('makeRain: use finite positive dimensions/speed, count 0..1000000, wind [x,z], center [x,y,z] and opacity 0..1');
+ if (opts.heightAt != null && typeof opts.heightAt !== 'function') {
+ throw new RangeError('makeRain: heightAt must be a function');
}
+ const shelterResolution = intOption(opts.shelterResolution, 32, 'makeRain: shelterResolution', 8, 64);
+ const shelterUpdateDistance = positive(opts.shelterUpdateDistance, Math.max(.5, radius * .20),
+ 'makeRain: shelterUpdateDistance');
+ const groundY = option(opts.groundY, -1e8, 'makeRain: groundY');
const rand = mulberry32(seed);
const inst = _quads(count);
const off = new Float32Array(count * 3);
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rock.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rock.js
index f678e4a3..c58d2ed5 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rock.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rock.js
@@ -6,7 +6,7 @@ import * as THREE from 'three';
import { ConvexGeometry } from 'three/addons/geometries/ConvexGeometry.js';
import { attachDisposal, snapshotResources } from './lifecycle.js';
import { fbm3, mulberry32 } from './noise.js';
-import { patchStandard } from './shader.js';
+import { option, patchStandard } from './shader.js';
const TYPES = {
sandstone: { color: 0x9e7250, erosion: 0.028, roughness: 0.91, index: 0 },
@@ -292,7 +292,8 @@ export function makeRock(opts = {}) {
const s = opts.size ?? 1.8;
const size = Array.isArray(s) ? s : [s * 1.2, s * 0.82, s];
if (size.length !== 3 || !size.every((v) => Number.isFinite(v) && v > 0)) throw new RangeError('rock size must be positive metres');
- const geometry = rockGeometry(opts, type, size, mulberry32(opts.seed ?? 31));
+ // rockGeometry and rockMaterial read opts.seed themselves, with this default
+ const geometry = rockGeometry(opts, type, size, mulberry32(option(opts.seed, 31, 'makeRock: seed')));
const material = rockMaterial(opts, type, size[1]);
const rock = new THREE.Mesh(geometry, material);
rock.name = opts.name ?? `${type[0].toUpperCase() + type.slice(1)}Rock`;
@@ -309,7 +310,7 @@ export function makeRock(opts = {}) {
* instancing.js for distant repetitions of a few shared prototypes.
*/
export function makeRockField(opts = {}) {
- const rand = mulberry32(opts.seed ?? 31), group = new THREE.Group();
+ const rand = mulberry32(option(opts.seed, 31, 'makeRockField: seed')), group = new THREE.Group();
group.name = opts.name ?? 'RockField';
const count = clamp(Math.round(opts.count ?? 24), 0, 160), radius = Math.max(0.1, opts.radius ?? 9);
for (let i = 0; i < count; i++) {
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sand.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sand.js
index 2cf7d5b0..918c7bdf 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sand.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sand.js
@@ -5,7 +5,7 @@
import * as THREE from 'three';
import { attachDisposal, snapshotResources } from './lifecycle.js';
import { fbm2, mulberry32 } from './noise.js';
-import { patchStandard, readWind } from './shader.js';
+import { boundedSampler, option, patchStandard, readWind } from './shader.js';
import { triangleValue } from './terrain.js';
const TAU = Math.PI * 2;
@@ -67,7 +67,7 @@ function sandMaterial(opts, wind, seed) {
* sampleHeight takes LOCAL x,z; parent assets to this group after seating them.
*/
export function makeSandTerrain(opts = {}) {
- const seed = opts.seed ?? 17;
+ const seed = option(opts.seed, 17, 'makeSandTerrain: seed');
const rand = mulberry32(seed);
const size = Array.isArray(opts.size) ? opts.size : [opts.size ?? 80, opts.size ?? 80];
if (size.length !== 2 || !size.every((n) => Number.isFinite(n) && n > 0)) throw new RangeError('sand size must be positive metres');
@@ -136,7 +136,7 @@ export function makeSandTerrain(opts = {}) {
}
pos.needsUpdate = true;
};
- group.userData.sampleHeight = sampleHeight;
+ group.userData.sampleHeight = boundedSampler(width, depth, sampleHeight);
group.userData.update = update;
group.userData.seed = seed;
update(0);
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 e29eb6ed..83903113 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/shader.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/shader.js
@@ -304,11 +304,75 @@ export function seedLattice(seed, k = 16807, m = 9973) {
return (s * k) % m;
}
-/** Read a Vector3, an array or an {x,y,z} into a new Vector3. */
+/**
+ * A point as a new Vector3, from a THREE.Vector3, an `[x, y, z]` or an
+ * `{x, y, z}`. `null`/missing reads `(fx, fy, fz)`; a coordinate a
+ * given point leaves out is 0, so `[x, y]` lies at z = 0.
+ */
export function readVec3(p, fx = 0, fy = 0, fz = 0) {
- if (!p) return new THREE.Vector3(fx, fy, fz);
- if (Array.isArray(p)) return new THREE.Vector3(p[0], p[1], p[2]);
- return new THREE.Vector3(p.x, p.y, p.z);
+ if (p === undefined || p === null) return new THREE.Vector3(fx, fy, fz);
+ if (Array.isArray(p)) return new THREE.Vector3(p[0] ?? 0, p[1] ?? 0, p[2] ?? 0);
+ return new THREE.Vector3(p.x ?? 0, p.y ?? 0, p.z ?? 0);
+}
+
+/**
+ * The library's ONE option rule. `null` or missing reads `fallback`;
+ * anything else that is not a finite number in `[min, max]` throws a
+ * RangeError naming `label` — never a silent fallback or clamp (fire
+ * clamps on purpose, after this check). A seed is any finite number:
+ * `option(opts.seed, 7, 'makeX: seed')`.
+ */
+export function option(value, fallback, label, min = -Infinity, max = Infinity) {
+ const v = value ?? fallback;
+ if (!Number.isFinite(v) || v < min || v > max) {
+ const range = min === -Infinity ? (max === Infinity ? '' : ` <= ${max}`)
+ : max === Infinity ? ` >= ${min}` : ` in [${min}, ${max}]`;
+ throw new RangeError(`${label} must be a finite number${range}, got ${String(value)}`);
+ }
+ return v;
+}
+
+/** `option` for a count: an integer in `[min, max]`. */
+export function intOption(value, fallback, label, min = -Infinity, max = Infinity) {
+ const v = option(value, fallback, label, min, max);
+ if (!Number.isInteger(v)) throw new RangeError(`${label} must be an integer, got ${String(value)}`);
+ return v;
+}
+
+/** `option` for a size or a speed: a finite number above 0 (and <= `max`). */
+export function positive(value, fallback, label, max = Infinity) {
+ const v = option(value, fallback, label, -Infinity, max);
+ if (!(v > 0)) throw new RangeError(`${label} must be above 0, got ${String(value)}`);
+ return v;
+}
+
+/**
+ * `option` for a vector: a THREE vector or an array of `length` finite
+ * numbers, returned as a new array. `null`/missing reads `fallback`.
+ */
+export function vector(value, fallback, length, label) {
+ const w = value ?? fallback;
+ const v = w?.toArray ? w.toArray() : w;
+ if (!Array.isArray(v) || v.length !== length || !v.every(Number.isFinite)) {
+ throw new RangeError(`${label} must be ${length} finite numbers, got ${String(value)}`);
+ }
+ return v.slice();
+}
+
+/**
+ * The library's ONE `userData.sampleHeight(x, z, ...)` contract, for a
+ * `width` x `depth` patch centred on its local origin: `fn`'s height
+ * inside the patch, and `null` outside it, for a non-finite argument or
+ * where `fn` has no finite height. It never throws, so a prop just off
+ * the patch reads `null` instead of the edge's height.
+ */
+export function boundedSampler(width, depth, fn) {
+ return (x, z, ...rest) => {
+ if (!(Math.abs(x) <= width / 2 && Math.abs(z) <= depth / 2)) return null;
+ if (!rest.every((v) => v === undefined || Number.isFinite(v))) return null;
+ const y = fn(x, z, ...rest);
+ return Number.isFinite(y) ? y : null;
+ };
}
/**
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smoke.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smoke.js
index feca376a..7ea994bb 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smoke.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smoke.js
@@ -13,7 +13,7 @@
* Overlapping transparent objects use ordinary Three.js object sorting.
*/
import * as THREE from 'three';
-import { makeShaderMaterial, keepOutOfDepthPasses, makeLightProbe, readWind } from './shader.js';
+import { makeShaderMaterial, keepOutOfDepthPasses, makeLightProbe, option, positive, readWind } from './shader.js';
import { attachDisposal, snapshotResources } from './lifecycle.js';
import { bakeFbm3, dataTexture3D, mulberry32, sampleGrid3 } from './noise.js';
@@ -120,23 +120,20 @@ export function makeSteam(opts = {}) {
}
function makePlume(opts, steam) {
- const height = opts.height ?? (steam ? .7 : 3);
- const radius = opts.radius ?? height * (steam ? .09 : .047);
- const spread = opts.spread ?? (steam ? .16 : .20);
- const rise = opts.riseSpeed ?? height * (steam ? .38 : .2333333);
+ const L = steam ? 'makeSteam: ' : 'makeSmoke: ';
+ const height = option(opts.height, steam ? .7 : 3, L + 'height', .001, 10000);
+ const radius = positive(opts.radius, height * (steam ? .09 : .047), L + 'radius', height * 4);
+ const spread = option(opts.spread, steam ? .16 : .20, L + 'spread', 0, 2);
+ const rise = positive(opts.riseSpeed, height * (steam ? .38 : .2333333), L + 'riseSpeed');
const w = readWind(opts.wind, [height * .02, 0], 'makeSmoke/makeSteam wind'), wind = [w.x, w.z];
- const extinction = opts.density ?? (steam ? 2.1 : 5) / height;
- const turbulence = opts.turbulence ?? (steam ? .9 : 1);
- const dissipation = opts.dissipation ?? (steam ? 1.2 : .7);
- const anisotropy = opts.anisotropy ?? (steam ? .62 : .35);
- const quality = opts.quality ?? 'balanced', seed = opts.seed ?? 21;
- if (![height,radius,spread,rise,extinction,turbulence,dissipation,anisotropy].every(Number.isFinite) ||
- height < .001 || height > 10000 || radius <= 0 || radius > height * 4 || spread < 0 || spread > 2 ||
- rise <= 0 || extinction < 0 || turbulence < 0 || turbulence > 2 || dissipation < 0 ||
- Math.abs(anisotropy) > .9 ||
- !Number.isSafeInteger(seed) || !Object.hasOwn(TIERS,quality) || Math.hypot(...wind) / rise > 10) {
- throw new RangeError('makeSmoke/makeSteam: invalid dimensions, flow, density, scattering, seed or quality');
- }
+ const extinction = option(opts.density, (steam ? 2.1 : 5) / height, L + 'density', 0);
+ const turbulence = option(opts.turbulence, steam ? .9 : 1, L + 'turbulence', 0, 2);
+ const dissipation = option(opts.dissipation, steam ? 1.2 : .7, L + 'dissipation', 0);
+ const anisotropy = option(opts.anisotropy, steam ? .62 : .35, L + 'anisotropy', -.9, .9);
+ const seed = option(opts.seed, 21, L + 'seed');
+ const quality = opts.quality ?? 'balanced';
+ if (!Object.hasOwn(TIERS, quality)) throw new RangeError(`${L}quality must be one of ${Object.keys(TIERS)}`);
+ if (Math.hypot(...wind) / rise > 10) throw new RangeError(`${L}wind must be at most 10x riseSpeed`);
const texture = noiseTexture(seed), [steps, lightSteps] = TIERS[quality];
const maxRadius = (radius + spread * height) * (1 + turbulence * 1.9) + turbulence * height * .13;
const drift = wind.map(v => v * height / rise);
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/stream.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/stream.js
index 8974f296..cdf7919f 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/stream.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/stream.js
@@ -14,7 +14,7 @@ import * as THREE from 'three';
import { Reflector } from 'three/addons/objects/Reflector.js';
import { attachDisposal, snapshotResources } from './lifecycle.js';
import { mulberry32 } from './noise.js';
-import { GLSL_UTIL, planarCapture } from './shader.js';
+import { GLSL_UTIL, option, planarCapture } from './shader.js';
// IcosahedronGeometry duplicates triangle vertices. Preserve rounded cobble
// shading after deformation by averaging normals at coincident positions.
@@ -37,12 +37,6 @@ function smoothCobbleNormals(geometry) {
}
}
-function option(v, d, name, min, max = Infinity) {
- v = v === undefined ? d : v;
- if (!Number.isFinite(v) || v < min || v > max)
- throw new RangeError(`makeStream: ${name} must be ${min}..${max}`);
- return v;
-}
// the library's one GLSL value noise (astraHash21 / astraNoise2)
const noiseGLSL = GLSL_UTIL;
@@ -64,20 +58,20 @@ const noiseGLSL = GLSL_UTIL;
* speed/depth are constant along the path; no tributaries/overturning falls.
*/
export function makeStream(opts = {}) {
- const width = option(opts.width, 3, 'width', 0.1, 100),
- depth = option(opts.depth, 0.45, 'depth', 0.03, 10);
- const widthVariation = option(opts.widthVariation, 0, 'widthVariation', 0, 0.3);
- const speed = option(opts.speed, 1.1, 'speed', 0, 15),
- activity = option(opts.roughness, 0.5, 'roughness', 0, 1);
- const segments = Math.round(option(opts.segments, 180, 'segments', 16, 512));
- const acrossSegments = Math.round(option(opts.widthSegments, 20, 'widthSegments', 4, 96));
- const count = Math.round(option(opts.stoneCount, 220, 'stoneCount', 0, 12000));
- const attenuationDistance = option(opts.attenuationDistance, 3, 'attenuationDistance', 0.01, 10000);
- const caustics = option(opts.caustics, 0.45, 'caustics', 0, 1);
- const reflectionSize = option(opts.reflectionSize, 0, 'reflectionSize', 0, 2048);
+ const width = option(opts.width, 3, 'makeStream: width', 0.1, 100),
+ depth = option(opts.depth, 0.45, 'makeStream: depth', 0.03, 10);
+ const widthVariation = option(opts.widthVariation, 0, 'makeStream: widthVariation', 0, 0.3);
+ const speed = option(opts.speed, 1.1, 'makeStream: speed', 0, 15),
+ activity = option(opts.roughness, 0.5, 'makeStream: roughness', 0, 1);
+ const segments = Math.round(option(opts.segments, 180, 'makeStream: segments', 16, 512));
+ const acrossSegments = Math.round(option(opts.widthSegments, 20, 'makeStream: widthSegments', 4, 96));
+ const count = Math.round(option(opts.stoneCount, 220, 'makeStream: stoneCount', 0, 12000));
+ const attenuationDistance = option(opts.attenuationDistance, 3, 'makeStream: attenuationDistance', 0.01, 10000);
+ const caustics = option(opts.caustics, 0.45, 'makeStream: caustics', 0, 1);
+ const reflectionSize = option(opts.reflectionSize, 0, 'makeStream: reflectionSize', 0, 2048);
if (reflectionSize !== 0 && (!Number.isInteger(reflectionSize) || reflectionSize < 256))
throw new RangeError('makeStream: reflectionSize must be 0 or an integer from 256 to 2048');
- const seed = option(opts.seed, 42, 'seed', 0, 4294967295),
+ const seed = option(opts.seed, 42, 'makeStream: seed'),
rng = mulberry32(seed);
const points = opts.points ?? [
[-2, 0.8, -12],
@@ -109,7 +103,7 @@ export function makeStream(opts = {}) {
path.arcLengthDivisions = Math.max(400, segments * 3);
path.updateArcLengths();
const length = path.getLength();
- const endFade = option(opts.endFade, 0, 'endFade', 0, length * .5);
+ const endFade = option(opts.endFade, 0, 'makeStream: endFade', 0, length * .5);
// A spatial Catmull-Rom spline can overshoot perfectly valid flat-to-sloped
// control heights and make water run uphill. Use it only for the XZ course;
// harmonic Hermite slopes preserve each monotone height interval exactly.
@@ -144,9 +138,9 @@ export function makeStream(opts = {}) {
if (!Array.isArray(obstacles) || obstacles.length > 24)
throw new RangeError('makeStream: at most 24 obstacles');
const stones = obstacles.map((o, i) => ({
- u: option(o.u, undefined, `obstacles[${i}].u`, 0, 1),
- lateral: option(o.lateral, 0, `obstacles[${i}].lateral`, -0.95, 0.95),
- radius: option(o.radius, width * 0.1, `obstacles[${i}].radius`, 0.002, width * 0.45),
+ u: option(o.u, undefined, `makeStream: obstacles[${i}].u`, 0, 1),
+ lateral: option(o.lateral, 0, `makeStream: obstacles[${i}].lateral`, -0.95, 0.95),
+ radius: option(o.radius, width * 0.1, `makeStream: obstacles[${i}].radius`, 0.002, width * 0.45),
}));
const phase = rng() * 6.28;
const waveRng = mulberry32(seed ^ 0x57a4f319);
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/tree.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/tree.js
index 6b427402..df2c112c 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/tree.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/tree.js
@@ -27,7 +27,7 @@
import * as THREE from 'three';
import {mulberry32} from './noise.js';
import {windOf} from './grass.js';
-import {patchStandard,shadowLike,tickShaders} from './shader.js';
+import {intOption,option,patchStandard,shadowLike,tickShaders} from './shader.js';
import {patchLeafSSS} from './foliage_shade.js';
import {attachDisposal,snapshotResources} from './lifecycle.js';
@@ -40,11 +40,6 @@ const SPECIES={
willow:{radius:.46,trunk:.029,bark:0x625c45,leaf:0x607742,leafSize:.17,width:.19,
primary:11,secondary:5,twigs:5,droop:.30,crownStart:.32},
};
-const finite=(value,fallback,min,max,name)=>{
- const n=value===undefined?fallback:value;
- if(!Number.isFinite(n)||n<min||n>max)throw new RangeError(`tree: ${name} must be finite in [${min}, ${max}]`);
- return n;
-};
const V=(x=0,y=0,z=0)=>new THREE.Vector3(x,y,z);
const WIND_HEAD=/* glsl */`
@@ -396,15 +391,14 @@ function leafMaterial(config,uniforms) {
function build(opts,shrub) {
const species=opts.species===undefined?'oak':opts.species;
if(!Object.hasOwn(SPECIES,species))throw new RangeError('tree: species must be oak, birch or willow');
- const spec=SPECIES[species],height=finite(opts.height,shrub?2.2:6,.3,35,'height');
- const leafSegments=finite(opts.leafSegments,species==='birch'?16:species==='willow'?10:12,3,32,'leafSegments');
- if(!Number.isInteger(leafSegments))throw new RangeError('tree: leafSegments must be an integer');
- const config={species,spec,height,shrub,seed:finite(opts.seed,7,-2147483648,2147483647,'seed'),
- radius:finite(opts.crownRadius,height*(shrub?.58:spec.radius),.1,25,'crownRadius'),
- leafDensity:finite(opts.leafDensity,1,0,4,'leafDensity'),
- leafSize:finite(opts.leafSize,spec.leafSize,.025,.5,'leafSize'),
- maxLeaves:Math.floor(finite(opts.maxLeaves,24000,0,100000,'maxLeaves')),
- autumn:finite(opts.autumn,0,0,1,'autumn'),
+ const spec=SPECIES[species],height=option(opts.height, shrub?2.2:6, 'tree: height', .3, 35);
+ const leafSegments=intOption(opts.leafSegments, species==='birch'?16:species==='willow'?10:12, 'tree: leafSegments', 3, 32);
+ const config={species,spec,height,shrub,seed:option(opts.seed, 7, 'tree: seed'),
+ radius:option(opts.crownRadius, height*(shrub?.58:spec.radius), 'tree: crownRadius', .1, 25),
+ leafDensity:option(opts.leafDensity, 1, 'tree: leafDensity', 0, 4),
+ leafSize:option(opts.leafSize, spec.leafSize, 'tree: leafSize', .025, .5),
+ maxLeaves:Math.floor(option(opts.maxLeaves, 24000, 'tree: maxLeaves', 0, 100000)),
+ autumn:option(opts.autumn, 0, 'tree: autumn', 0, 1),
barkColor:opts.barkColor??spec.bark,leafColor:opts.leafColor??spec.leaf};
const wind=windOf(opts.wind),random=mulberry32(config.seed);
if(![wind.amp,wind.speed,wind.dir.x,wind.dir.y].every(Number.isFinite))throw new RangeError('tree: wind must be finite');
@@ -457,10 +451,10 @@ function build(opts,shrub) {
group.userData.leafCount=leaves.length;
group.userData.branches=branches.map(branch=>({id:branch.id,parent:branch.parent,at:branch.at,order:branch.order,
radius:branch.radius,start:branch.curve.v0.clone(),end:branch.curve.v3.clone(),
- sample:(u)=>pointOn(branch,finite(u,0,0,1,'branch parameter'))}));
+ sample:(u)=>pointOn(branch,option(u, 0, 'tree: branch parameter', 0, 1))}));
group.userData.leafAttachments=leaves.map(leaf=>({branch:leaf.branch,at:leaf.at,anchor:leaf.anchor.clone()}));
group.userData.sampleWind=(point,t=0)=>{
- finite(t,0,-1e9,1e9,'time');const p=point?.isVector3?point.clone():Array.isArray(point)&&point.length===3?V(...point):null;
+ option(t, 0, 'tree: time', -1e9, 1e9);const p=point?.isVector3?point.clone():Array.isArray(point)&&point.length===3?V(...point):null;
if(!p||![p.x,p.y,p.z].every(Number.isFinite))throw new RangeError('tree: sampleWind needs a finite local Vector3 or [x,y,z]');
const u=uniforms,b=THREE.MathUtils.clamp(p.y/height,0,1),time=t*wind.speed,phase=u.uTreePhase.value;
const main=(.62*Math.sin(time+phase)+.28*Math.sin(time*.53+phase*1.7))*(.65+.35*Math.sin(time*.24+phase));
@@ -470,7 +464,7 @@ function build(opts,shrub) {
p.z+=(wind.dir.y*(main+twig)+wind.dir.x*side)*amp;
return p;
};
- group.userData.update=group.userData.tick=(t=0)=>{finite(t,0,-1e9,1e9,'time');tickShaders(group,t);};
+ group.userData.update=group.userData.tick=(t=0)=>{option(t, 0, 'tree: time', -1e9, 1e9);tickShaders(group,t);};
return attachDisposal(group,snapshotResources(group));
}
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/urban.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/urban.js
index 5e9f5508..54776857 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/urban.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/urban.js
@@ -24,18 +24,11 @@ import { patchNeonSpill } from './neon.js';
import { fbm2, mulberry32, noiseDataTexture } from './noise.js';
import {
keepOutOfDepthPasses, makeShaderMaterial,
- patchStandard, seedLattice, tickShaders, toColor, unit,
+ patchStandard, readVec3, seedLattice, tickShaders, toColor, unit,
} from './shader.js';
const _UP = new THREE.Vector3(0, 1, 0);
-/** A point in any accepted spelling as its own Vector3. */
-function toVec(p) {
- if (p && p.isVector3) return p.clone();
- if (Array.isArray(p)) return new THREE.Vector3(p[0], p[1], p[2] || 0);
- return new THREE.Vector3(p.x || 0, p.y || 0, p.z || 0);
-}
-
const seedOffset = (seed) => seedLattice(seed) * 0.0517;
/** Read a `[w, h]`, `{w, h}` or single number as a metric pair. */
@@ -580,7 +573,7 @@ function resample(points, spans) {
*/
export function makePowerLines(opts = {}) {
const raw = (Array.isArray(opts.points) && opts.points.length >= 2
- ? opts.points : [[-22, 0, 0], [22, 0, 0]]).map(toVec);
+ ? opts.points : [[-22, 0, 0], [22, 0, 0]]).map((p) => readVec3(p));
const poleAt = opts.spans > 0 ? resample(raw, Math.round(opts.spans))
: raw;
const spec = Object.assign(
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/waterfall.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/waterfall.js
index f614ea7c..83a69e4a 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/waterfall.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/waterfall.js
@@ -6,7 +6,7 @@
* The caller supplies the cliff, upstream water and receiving pool.
*/
import * as THREE from 'three';
-import { patchStandard, keepOutOfDepthPasses } from './shader.js';
+import { keepOutOfDepthPasses, option, patchStandard, positive } from './shader.js';
import { attachDisposal, snapshotResources } from './lifecycle.js';
import { mulberry32 } from './noise.js';
import { makeSpray } from './watermist.js';
@@ -57,19 +57,16 @@ vec3 fallPosition(vec2 uv,float t) {
* Update once with absolute seconds; dispose releases construction-owned data.
*/
export function makeWaterfall(opts = {}) {
- const width=opts.width??2, height=opts.height??3, speed=opts.speed??1;
- const thickness=opts.thickness??.045, breakup=opts.breakup??.6, foam=opts.foam??.65;
- const seed=opts.seed??17, quality=opts.quality??'balanced';
- const attenuationDistance=opts.attenuationDistance??8;
- const sprayRate=opts.sprayRate??Math.min(500,100*width);
- if (![width,height,speed,thickness,breakup,foam].every(Number.isFinite) ||
- width<.02 || width>500 || height<.02 || height>500 || speed<.02 || speed>50 ||
- thickness<=0 || thickness>Math.min(width,height)*.5 || breakup<0 || breakup>1 || foam<0 || foam>1 ||
- !Number.isSafeInteger(seed) || !Object.hasOwn(TIERS,quality) ||
- !(attenuationDistance>0) || (!Number.isFinite(attenuationDistance) && attenuationDistance!==Infinity) ||
- !Number.isFinite(sprayRate) || sprayRate<0 || sprayRate>100000) {
- throw new RangeError('makeWaterfall: invalid dimensions, flow, foam, seed or quality');
- }
+ const L='makeWaterfall: ';
+ const width=option(opts.width,2,L+'width',.02,500), height=option(opts.height,3,L+'height',.02,500);
+ const speed=option(opts.speed,1,L+'speed',.02,50);
+ const thickness=positive(opts.thickness,.045,L+'thickness',Math.min(width,height)*.5);
+ const breakup=option(opts.breakup,.6,L+'breakup',0,1), foam=option(opts.foam,.65,L+'foam',0,1);
+ const seed=option(opts.seed,17,L+'seed'), quality=opts.quality??'balanced';
+ if(!Object.hasOwn(TIERS,quality)) throw new RangeError(`${L}quality must be one of ${Object.keys(TIERS)}`);
+ // Infinity is a valid attenuation distance: perfectly clear water.
+ const attenuationDistance=opts.attenuationDistance===Infinity?Infinity:positive(opts.attenuationDistance,8,L+'attenuationDistance');
+ const sprayRate=option(opts.sprayRate,Math.min(500,100*width),L+'sprayRate',0,100000);
const flight=Math.sqrt(2*height/GRAVITY), impactZ=speed*flight;
const random=mulberry32(seed), waves=[];
for(let i=0;i<4;i++) waves.push(new THREE.Vector4(
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 96bea2df..647530dd 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/watermist.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/watermist.js
@@ -47,21 +47,12 @@ import * as THREE from 'three';
import { attachDisposal, snapshotResources } from './lifecycle.js';
import { lehmer } from './noise.js';
-import { instancedQuad, makeShaderMaterial, tickShaders, keepOutOfDepthPasses, glslLocalDir } from './shader.js';
+import { instancedQuad, makeShaderMaterial, readVec3, tickShaders, keepOutOfDepthPasses, glslLocalDir } from './shader.js';
// Free fall. It is written twice on purpose — in the vertex shader and
// in the CPU mirror `userData.sample` — so both read this one number.
const _G = 9.81;
-/** A THREE.Vector3 from a vector, an [x,y,z] array or nothing. */
-function toVec3(v) {
- if (Array.isArray(v)) {
- return new THREE.Vector3(v[0] || 0, v[1] || 0, v[2] || 0);
- }
- if (v && v.isVector3) return v.clone();
- return new THREE.Vector3();
-}
-
/**
* The key light as a direction plus how much of it there is.
*
@@ -77,7 +68,7 @@ function toVec3(v) {
* caller with no rig to hand) and 0..1 for how far it has risen.
*/
function toSun(v) {
- const d = toVec3(v);
+ const d = readVec3(v);
if (d.lengthSq() < 1e-8) return { dir: new THREE.Vector3(0, 1, 0), gain: 1 };
d.normalize();
// 0 at the horizon, full by ten degrees up: the last of the sun
@@ -440,7 +431,7 @@ function mistMaterial(cfg) {
* the vertex shader runs.
*/
export function makeSpray(opts = {}) {
- const origin = toVec3(opts.origin);
+ const origin = readVec3(opts.origin);
const radius = Math.max(0.01,
opts.radius === undefined ? 0.7 : opts.radius);
const rate = Math.max(1, opts.rate === undefined ? 120 : opts.rate);
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 7ef6b5ed..25e7c5df 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/woodland.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/woodland.js
@@ -255,8 +255,8 @@ const BARK_FRAGMENT_BODY = [
* side, this is only what lodges in the cracks); `axis` the trunk's
* own axis in OBJECT space, THREE.Vector3 or [x, y, z] (default +Y);
* `tint` THREE.Color or hex, the bark colour (default by kind);
- * `sun` world direction TOWARD the sun, for the relief (default a day
- * sun); `seed` moves the field (default 1).
+ * `sunDir` world direction TOWARD the sun, for the relief (default a
+ * day sun; `sun` is read too); `seed` moves the field (default 1).
* @returns {THREE.Material} The same material, uniforms live on
* `material.userData.uniforms`.
*/
@@ -290,7 +290,7 @@ export function patchBark(material, opts = {}) {
uBarkAxis: { value: axis.normalize() },
uBarkTint: { value: toColor(opts.tint, kind.tint) },
uBarkMossColor: { value: toColor(opts.mossColor, 0x46551f) },
- uBarkSun: { value: readVec3(opts.sun, 0.45, 0.78, 0.35).normalize() },
+ uBarkSun: { value: readVec3(opts.sunDir ?? opts.sun, 0.45, 0.78, 0.35).normalize() },
uBarkSeed: { value: seedOffset(seed) },
},
vertexHead: BARK_VERTEX_HEAD,
diff --git a/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md b/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md
index f85eb08d..950cfaab 100644
--- a/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md
+++ b/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md
@@ -64,7 +64,7 @@ says `import { makeGrass } from '../lib/grass.js';`, `src/scene.js` says
| a neon sign, and the light it throws | `makeNeonTube` · `patchNeonSpill` · `makeLightTrails` — `lib/neon.js`; a sign that does not light its own wall is a decal |
| readable lettering on a sign | `makeText` (async — await ONCE at module top level, `.clone()` per copy) — `lib/signage.js` |
| a road, a path, a worn surface | `patchRoadSurface` · `patchSeamBand` · `patchTracks` — `lib/roadway.js` |
-| foreground cobbles or rectangular stone setts with real joints | `makePaving({ size: [4,4], stoneSize: 0.24, pattern: 'cobble', joint: 0.012, thickness: 0.10, relief: 0.014, seed })` — `lib/paving.js`; merged closed bevelled stones and a recessed joint bed, two meshes and a bounded stone count. Nominal top is y=0, bottom=-thickness. `userData.sampleHeight(x,z)` returns the exact local stone/joint height or null outside; seat props using it. Use material-only cobbles for distant surfaces. |
+| foreground cobbles or rectangular stone setts with real joints | `makePaving({ size: [4,4], stoneSize: 0.24, pattern: 'cobble', joint: 0.012, thickness: 0.10, relief: 0.014, seed })` — `lib/paving.js`; merged closed bevelled stones and a recessed joint bed, two meshes and a bounded stone count. Nominal top is y=0, bottom=-thickness. `userData.sampleHeight(x,z)` returns the exact local stone/joint height; seat props using it. Use material-only cobbles for distant surfaces. |
| a flag, a hanging banner, a wheat field | `makeFlag` · `makeBanner` · `makeWheatField` — `lib/cloth.js`; the wave TRAVELS |
| a surface that has stood somewhere | `patchDripStains` · `patchRust` · `patchDust` — `lib/aging.js` |
| any surface at all | `patchMicroBreakup` · `patchEdgeWear` — `lib/surface_wear.js` |
@@ -85,9 +85,14 @@ sand, meadow, smoke, steam, waterfall, tree, shrub, cloud volume, ice and paving
and `object.userData.dispose()`. Store the returned objects and update each ONCE
from the zone's `userData.update`. Their dimensions, paths and height queries are
LOCAL coordinates; move/rotate the whole returned object to place it. Call the
-factory before positioning props that sample its surface. These are realtime
+factory before positioning props that sample its surface: `userData.sampleHeight(x, z)`
+returns the surface height there, or `null` off the patch (and in an ice gap). It
+never throws, so test for `null` before seating a prop. These are realtime
procedural effects, not fluid/combustion solvers. Read the module's JSDoc for
-options and bounds. For older effects, follow the hooks listed below.
+options and bounds: an option left out or `null` takes its default, and an invalid
+one throws a RangeError that names it (fire clamps an out-of-range number instead).
+The direction toward the sun is `sunDir` in every factory. For older effects, follow
+the hooks listed below.
**1. `patch*` entries CHAIN.** Apply as many as a surface deserves to one
material, in any order — they are composed into one program. Two patches may
diff --git a/harness/tests/scene_runtime/lib/test_library.py b/harness/tests/scene_runtime/lib/test_library.py
index b243b779..9760ce72 100644
--- a/harness/tests/scene_runtime/lib/test_library.py
+++ b/harness/tests/scene_runtime/lib/test_library.py
@@ -379,3 +379,89 @@ def test_the_per_frame_hook_is_taught_as_update_only():
unaliased.append(p.name)
catalog = (PROMPTS_DIR / "scene_threejs" / "effects_catalog.md").read_text(encoding="utf-8")
assert not taught and not unaliased and "userData.tick" not in catalog, (taught, unaliased)
+
+
+# One option rule (audit N33): a missing/`null` option takes its default, an invalid one
+# throws a RangeError naming it, a seed is any finite number, and the sun is `sunDir`
+# everywhere. Before: the same derived seed built in one effect and threw in its
+# neighbour (null / 3.7 / 2**40 each refused by some), and ocean ignored `sunDir`.
+_OPTIONS = """
+import * as THREE from 'three';
+import { makeFire } from './lib/fire.js';
+import { makeFireField } from './lib/firefield.js';
+import { makeTree } from './lib/tree.js';
+import { makeMeadow } from './lib/meadow.js';
+import { makeOceanSurface } from './lib/ocean.js';
+import { makeStream } from './lib/stream.js';
+import { makeSmoke } from './lib/smoke.js';
+import { makeClouds } from './lib/clouds.js';
+import { makeCloudVolume } from './lib/cloudvolume.js';
+import { makeWaterfall } from './lib/waterfall.js';
+import { makeRain } from './lib/rain.js';
+import { makeSandTerrain } from './lib/sand.js';
+import { makeRock } from './lib/rock.js';
+import { makePaving } from './lib/paving.js';
+import { makeFracturedIce } from './lib/ice.js';
+import { readVec3 } from './lib/shader.js';
+const calls = {
+ fire: (o) => makeFire(o), firefield: (o) => makeFireField({ emitters: [{ position: [0, 0, 0] }], quality: 'low', ...o }),
+ tree: (o) => makeTree({ leafDensity: .05, ...o }), meadow: (o) => makeMeadow({ size: [1, 1], density: 20, ...o }),
+ ocean: (o) => makeOceanSurface({ width: 10, depth: 10, segments: 16, ...o }),
+ stream: (o) => makeStream({ points: [[0, .6, -8], [0, 0, 8]], stoneCount: 4, ...o }),
+ smoke: (o) => makeSmoke({ quality: 'low', ...o }), clouds: (o) => makeClouds({ count: 2, ...o }),
+ cloudvolume: (o) => makeCloudVolume({ quality: 'low', ...o }), waterfall: (o) => makeWaterfall(o),
+ rain: (o) => makeRain({ count: 10, ...o }), sand: (o) => makeSandTerrain({ size: [10, 10], segments: 16, ...o }),
+ rock: (o) => makeRock(o), paving: (o) => makePaving({ size: [2, 2], ...o }),
+ ice: (o) => makeFracturedIce({ size: [4, 3], ...o }),
+};
+const seeds = { null: null, big: 2 ** 40, fraction: 3.7, text: '7' };
+const run = (f) => { try { f(); return 'ok'; } catch (e) { return e instanceof RangeError ? e.message : 'not a RangeError: ' + e; } };
+const out = { seed: {} };
+for (const [name, call] of Object.entries(calls))
+ out.seed[name] = Object.fromEntries(Object.entries(seeds).map(([k, seed]) => [k, run(() => call({ seed }))]));
+const sunOf = (g) => { let v; g.traverse((o) => { const u = o.material?.uniforms; v ??= (u?.seaSun ?? u?.uSunWorld)?.value; }); return v?.toArray(); };
+out.sun = { ocean: sunOf(calls.ocean({ sunDir: [0, 1, 0] })), cloudvolume: sunOf(calls.cloudvolume({ sunDir: [0, 1, 0] })) };
+out.nullDefaults = run(() => calls.stream({ width: null, speed: null }) && calls.meadow({ height: null }) && calls.ice({ gap: null }));
+out.fireClamps = run(() => makeFire({ radius: 1e6 }));
+out.badNames = [run(() => calls.meadow({ height: 'tall' })), run(() => calls.smoke({ spread: 5 })), run(() => calls.cloudvolume({ coverage: 2 }))];
+out.point = readVec3([1, 2]).toArray().concat(readVec3(null, 4, 5, 6).toArray(), readVec3({ x: 1 }).toArray());
+console.log(JSON.stringify(out));
+"""
+
+
+def test_every_factory_reads_its_options_by_one_rule():
+ out = measure(_OPTIONS, tuple(MODULES))
+ for name, row in out["seed"].items():
+ assert row["null"] == row["big"] == row["fraction"] == "ok", (name, row)
+ assert "seed" in row["text"], (name, row)
+ assert out["sun"] == {"ocean": [0, 1, 0], "cloudvolume": [0, 1, 0]}, out["sun"]
+ assert out["nullDefaults"] == out["fireClamps"] == "ok", out
+ for phrase, message in zip(("height", "spread", "coverage"), out["badNames"], strict=True):
+ assert phrase in message, out["badNames"]
+ assert out["point"] == [1, 2, 0, 4, 5, 6, 1, 0, 0]
+
+
+def test_sample_height_is_null_off_the_patch_and_never_throws():
+ """Audit N36: sand returned its clamped edge height off the patch, ocean kept
+ extrapolating its waves (and threw on NaN), meadow returned 0."""
+ out = measure("""
+import { makeSandTerrain } from './lib/sand.js';
+import { makePaving } from './lib/paving.js';
+import { makeFracturedIce } from './lib/ice.js';
+import { makeOceanSurface } from './lib/ocean.js';
+import { makeMeadow } from './lib/meadow.js';
+const objs = { sand: makeSandTerrain({ size: [10, 10], segments: 16 }), paving: makePaving({ size: [4, 4] }),
+ ice: makeFracturedIce({ size: [8, 6] }), ocean: makeOceanSurface({ width: 10, depth: 10, segments: 16 }),
+ meadow: makeMeadow({ size: [2, 2], density: 20, heightAt: (x, z) => 0.5 + 0 * x * z }) };
+const out = {};
+for (const [k, o] of Object.entries(objs)) {
+ const f = o.userData.sampleHeight;
+ const at = (...a) => { try { return f(...a); } catch (e) { return 'THROW ' + e.message; } };
+ out[k] = { inside: at(0.3, 0.2), outside: at(50, 0), nan: at(NaN, 0), badTime: at(0.3, 0.2, NaN) };
+}
+console.log(JSON.stringify(out));
+""", tuple(MODULES))
+ for name, r in out.items():
+ assert isinstance(r["inside"], (int, float)), (name, r)
+ assert r["outside"] is None and r["nan"] is None, (name, r)
+ assert out["ocean"]["badTime"] is None and out["meadow"]["inside"] == 0.5, out