Prompt specification
Build or customize the Three.js 3D scene "Compare runoff paths with and without a vegetated strip" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Compare runoff paths with and without a vegetated strip
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/compare-runoff-paths-with-and-without-a-vegetated-stri-x3060
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts gullies and terraces on China's Loess Plateau. Let users toggle a hypothetical vegetation strip on the same slope. Show qualitative changes in runoff routing and clearly avoid predicting real sediment loss from the simplified model. Low-poly.
Working Three.js Starter (compare-runoff-paths-with-and-without-a-vegetated-stri-x3060):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Loess Plateau — gullies & terraces (schematic)</title>
<style>
:root{
--panel: rgba(18,20,24,0.82);
--edge: rgba(255,255,255,0.14);
--ink: #e8e4dc;
--dim: #a8a49b;
--warn: #f0c26b;
--flow: #5aa0cf;
}
*{box-sizing:border-box}
html,body{margin:0;height:100%;overflow:hidden;background:#0e1116;
font-family:"Inter",system-ui,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
color:var(--ink)}
canvas{display:block}
#app{position:fixed;inset:0}
#labels{position:absolute;inset:0;pointer-events:none}
.tag{position:absolute;transform:translate(-50%,-50%);
font-size:11px;letter-spacing:.04em;padding:3px 8px;border-radius:999px;
background:rgba(12,14,18,.62);border:1px solid var(--edge);color:#efe9dd;
white-space:nowrap;backdrop-filter:blur(3px);text-shadow:0 1px 2px #000}
.tag.veg{background:rgba(38,68,32,.72);border-color:rgba(140,200,120,.5)}
.tag.gully{background:rgba(66,40,28,.72);border-color:rgba(210,140,110,.45)}
.tag small{opacity:.72}
#panel{position:absolute;left:14px;top:14px;width:322px;max-height:calc(100% - 28px);
overflow:auto;background:var(--panel);border:1px solid var(--edge);border-radius:14px;
padding:14px 15px;backdrop-filter:blur(9px);box-shadow:0 12px 34px rgba(0,0,0,.42)}
#panel h1{margin:0 0 2px;font-size:15px;font-weight:650;letter-spacing:.01em}
#panel h2{margin:0 0 10px;font-size:11px;font-weight:500;color:var(--dim);letter-spacing:.05em}
.warn{background:rgba(240,194,107,.10);border:1px solid rgba(240,194,107,.42);
border-radius:9px;padding:8px 10px;font-size:11.5px;line-height:1.45;color:#f5dfae;margin:10px 0 12px}
.warn b{color:#ffd48a}
.row{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:10px}
button{font:inherit;font-size:12px;color:var(--ink);background:rgba(255,255,255,.07);
border:1px solid var(--edge);border-radius:8px;padding:7px 10px;cursor:pointer;transition:.15s}
button:hover{background:rgba(255,255,255,.14)}
button.on{background:rgba(96,150,72,.34);border-color:rgba(150,210,120,.6);color:#d9f2c8}
button small{opacity:.6;margin-left:5px}
.readout{border-top:1px solid var(--edge);padding-top:9px;margin-top:2px}
.readout .k{font-size:10.5px;letter-spacing:.07em;text-transform:uppercase;color:var(--dim)}
.readout .v{font-size:13px;margin-top:3px;font-variant-numeric:tabular-nums}
.readout .v em{font-style:normal;color:var(--warn)}
#chart{display:block;width:100%;height:74px;margin-top:6px;border-radius:6px;
background:rgba(255,255,255,.045)}
.legend{display:grid;grid-template-columns:auto 1fr;gap:4px 8px;font-size:11px;color:var(--dim);margin-top:10px}
.sw{width:12px;height:12px;border-radius:3px;margin-top:1px}
.foot{font-size:10.5px;line-height:1.45;color:#8e8a81;border-top:1px solid var(--edge);
margin-top:11px;padding-top:9px}
#hint{position:absolute;right:14px;bottom:12px;font-size:11px;color:#cfc9bd;
background:rgba(12,14,18,.55);border:1px solid var(--edge);padding:6px 11px;border-radius:999px}
#paused{position:absolute;left:50%;top:14px;transform:translateX(-50%);font-size:11px;
letter-spacing:.12em;text-transform:uppercase;color:#ffd48a;background:rgba(12,14,18,.6);
border:1px solid rgba(240,194,107,.4);padding:5px 12px;border-radius:999px;display:none}
</style>
</head>
<body>
<div id="app">
<canvas id="c"></canvas>
<div id="labels"></div>
<div id="panel">
<h1>Loess Plateau — gullies & terraces</h1>
<h2>LOW-POLY SCHEMATIC · NOT A HYDROLOGIC MODEL</h2>
<div class="warn">
<b>Schematic illustration only.</b> The particle routing below is a deliberately
simplified visual device. It is <b>not calibrated</b> to any field data and it does
<b>not</b> estimate erosion, sediment yield, or sediment loss — no such quantities are
computed here. The vegetation strip is a <b>hypothetical</b> test feature, not a
prescription for any real site.
</div>
<div class="row">
<button id="btnVeg">Vegetation strip <small id="vegState">OFF</small></button>
<button id="btnRain" class="on">Rain</button>
<button id="btnLabels" class="on">Labels</button>
<button id="btnReset">Reset view</button>
<button id="btnPause">Pause</button>
</div>
<div class="readout">
<div class="k">Surface routing below the strip</div>
<div class="v" id="routing">—</div>
<canvas id="chart" width="292" height="74"></canvas>
<div class="k" style="margin-top:5px">Schematic flow distribution across the slope</div>
</div>
<div class="readout">
<div class="k">Schematic throughflow at the toe</div>
<div class="v" id="toe">—</div>
</div>
<div class="readout">
<div class="k">Vegetation strip (hypothetical)</div>
<div class="v" id="stripState">Off — bare benches, flow organizes into gullies</div>
</div>
<div class="legend">
<span class="sw" style="background:#d8b177"></span><span>Loess slope / riser faces</span>
<span class="sw" style="background:#ada87e"></span><span>Terrace bench (cultivated, grey-olive)</span>
<span class="sw" style="background:#8b6a4b"></span><span>Incised gully floor</span>
<span class="sw" style="background:#5c8f4a"></span><span>Hypothetical vegetation strip</span>
<span class="sw" style="background:#3f8ecb"></span><span>Runoff tracer particles</span>
<span class="sw" style="background:#7fc05a"></span><span>Tracer removed at the strip (schematic interception)</span>
</div>
<div class="foot">
Chart and counters are artefacts of this toy model, used only to show the
<i>shape</i> of the routing response (concentrated vs. dispersed). They carry no
physical units, are not discharge, and must not be read as erosion or sediment-loss
estimates. Surface interception is shown as a sink; soil moisture, groundwater and
sediment processes are not represented at all.
</div>
</div>
<div id="hint">drag = orbit · shift-drag / right-drag = pan · wheel = zoom · V = strip · R = reset</div>
<div id="paused">paused</div>
</div>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js';
/* ============================================================
0. small helpers
============================================================ */
const clamp=(v,a,b)=>v<a?a:(v>b?b:v);
const lerp=(a,b,t)=>a+(b-a)*t;
function ss(a,b,x){const t=clamp((x-a)/(b-a),0,1);return t*t*(3-2*t);}
function hash2(x,y){const n=Math.sin(x*127.1+y*311.7)*43758.5453123;return n-Math.floor(n);}
function vnoise(x,y){
const xi=Math.floor(x),yi=Math.floor(y),xf=x-xi,yf=y-yi;
const u=xf*xf*(3-2*xf),v=yf*yf*(3-2*yf);
return lerp(lerp(hash2(xi,yi),hash2(xi+1,yi),u),
lerp(hash2(xi,yi+1),hash2(xi+1,yi+1),u),v);
}
function fbm(x,y){let s=0,a=0.5,f=1;for(let i=0;i<3;i++){s+=a*vnoise(x*f,y*f);f*=2.07;a*=0.5;}return s;}
/* ============================================================
1. terrain definition (analytic height field)
============================================================ */
const N=128; // grid resolution (low-poly)
const W=64, D=76, H=33; // width, depth, relief
const BLOCK_BOTTOM=-7; // diorama block base
const STEP=4.4, RAMP=0.45; // terrace step height / riser fraction
function terrace(v){
const m=Math.floor(v/STEP), f=v/STEP-m;
if(f<RAMP) return (m+ss(0,1,f/RAMP))*STEP;
return (m+1)*STEP;
}
// main incised gullies: heads start below the upper benches
const GULLIES=[
{c:-22,amp:2.6,freq:1.1,phase:0.40,depth:5.2,sig:2.6},
{c: -6,amp:3.2,freq:1.6,phase:2.10,depth:6.4,sig:3.0},
{c: 11,amp:2.4,freq:1.3,phase:4.00,depth:5.0,sig:2.4},
{c: 24,amp:1.8,freq:2.0,phase:1.20,depth:3.6,sig:2.0},
];
// shallow incipient rills on the upper slope (texture only)
const RILLS=[
{c:-14,amp:3.0,freq:1.4,phase:0.9,depth:1.0,sig:1.5},
{c: 3,amp:2.2,freq:1.8,phase:3.3,depth:0.9,sig:1.3},
{c: 17,amp:2.6,freq:1.2,phase:5.1,depth:0.8,sig:1.2},
];
function channelX(g,u){return g.c+g.amp*Math.sin(u*g.freq*6.2831+g.phase)+g.amp*0.45*Math.sin(u*12.3+g.phase*2.1);}
// smooth (un-incised) surface: terraced benches + gentle bench tilt toward gully axes
function smoothSurface(x,u){
const v=H*Math.pow(1-u,1.2);
let h=terrace(v)+1.8;
const tiltW=ss(0.45,0.62,u);
if(tiltW>0){
for(const g of GULLIES){
const d=x-channelX(g,u), w=g.sig*(2.4+2.2*u);
h-=0.95*tiltW*Math.exp(-0.5*(d/w)*(d/w));
}
}
h+=(fbm(x*0.16+11.3,u*8.0+3.7)-0.5)*0.55; // broad undulation
h+=(vnoise(x*0.55,u*26.0)-0.5)*0.10; // micro texture
return h;
}
function terrainHeight(x,u){
let h=smoothSurface(x,u);
for(const g of GULLIES){
const d=x-channelX(g,u);
const sig=g.sig*(0.55+1.05*u);
let dep=g.depth*(0.20+0.80*u)*ss(0.44,0.66,u)*(1-0.55*ss(0.88,1.0,u));
h-=dep*Math.exp(-0.5*(d/sig)*(d/sig));
}
for(const g of RILLS){
const d=x-channelX(g,u);
const sig=g.sig*(0.7+0.8*u);
h-=g.depth*(0.3+0.7*u)*Math.exp(-0.5*(d/sig)*(d/sig));
}
const toe=ss(0.90,1.0,u);
h=lerp(h,1.9+(fbm(x*0.2,7.7)-0.5)*0.45,toe);
return Math.max(h,0.15);
}
/* ============================================================
2. build the height grid
============================================================ */
const heights=new Float32Array(N*N);
const smoothH =new Float32Array(N*N);
for(let r=0;r<N;r++){
const u=r/(N-1), z=-D/2+u*D;
for(let c=0;c<N;c++){
const x=-W/2+(c/(N-1))*W;
heights[r*N+c]=terrainHeight(x,u);
smoothH [r*N+c]=smoothSurface(x,u);
}
}
function sampleH(x,z){
const fx=clamp((x+W/2)/W*(N-1),0,N-1.001);
const fz=clamp((z+D/2)/D*(N-1),0,N-1.001);
const i0=Math.floor(fx), j0=Math.floor(fz);
const tx=fx-i0, tz=fz-j0;
const h00=heights[j0*N+i0],h10=heights[j0*N+i0+1];
const h01=heights[(j0+1)*N+i0],h11=heights[(j0+1)*N+i0+1];
return lerp(lerp(h00,h10,tx),lerp(h01,h11,tx),tz);
}
const _g=new THREE.Vector3();
function gradH(x,z){
const e=0.7;
_g.set((sampleH(x+e,z)-sampleH(x-e,z))/(2*e),0,(sampleH(x,z+e)-sampleH(x,z-e))/(2*e));
return _g;
}
/* ============================================================
3. scene, lighting, sky
============================================================ */
const canvas=document.getElementById('c');
const renderer=new THREE.WebGLRenderer({canvas,antialias:true});
renderer.setPixelRatio(Math.min(devicePixelRatio,2));
renderer.setSize(innerWidth,innerHeight);
renderer.shadowMap.enabled=true;
renderer.shadowMap.type=THREE.PCFSoftShadowMap;
renderer.outputColorSpace=THREE.SRGBColorSpace;
const scene=new THREE.Scene();
scene.fog=new THREE.Fog(0xdfd3bd,150,460);
const camera=new THREE.PerspectiveCamera(48,innerWidth/innerHeight,0.5,1200);
scene.add(new THREE.HemisphereLight(0xbcd6ee,0xa08456,0.85));
const sun=new THREE.DirectionalLight(0xfff0d6,1.55);
sun.position.set(-48,78,36);
sun.castShadow=true;
sun.shadow.mapSize.set(1024,1024);
sun.shadow.camera.left=-60;sun.shadow.camera.right=60;
sun.shadow.camera.top=60;sun.shadow.camera.bottom=-60;
sun.shadow.camera.far=220;sun.shadow.bias=-0.0012;
scene.add(sun);
const rim=new THREE.DirectionalLight(0x9fc0e6,0.35); rim.position.set(60,30,-50); scene.add(rim);
// faceted sky dome
{
const g=new THREE.SphereGeometry(520,18,11);
const p=g.attributes.position, cols=[];
const top=new THREE.Color(0x8fb9e2), mid=new THREE.Color(0xd8e3ea), hor=new THREE.Color(0xe9d8bd);
const c=new THREE.Color();
for(let i=0;i<p.count;i++){
const t=clamp(p.getY(i)/520,0,1);
if(t<0.35) c.copy(hor).lerp(mid,t/0.35); else c.copy(mid).lerp(top,(t-0.35)/0.65);
cols.push(c.r,c.g,c.b);
}
g.setAttribute('color',new THREE.Float32BufferAttribute(cols,3));
const sky=new THREE.Mesh(g,new THREE.MeshBasicMaterial({vertexColors:true,side:THREE.BackSide,fog:false}));
scene.add(sky);
}
/* ============================================================
4. terrain mesh (non-indexed, flat-shaded, per-face colour)
============================================================ */
const C_BENCH=new THREE.Color(0xada87e), C_SLOPE=new THREE.Color(0xd6ae74),
C_STEEP=new THREE.Color(0xe7c994), C_GULLY=new THREE.Color(0x8b6a4b),
C_WET =new THREE.Color(0x6f5a44);
const _fc=new THREE.Color();
function faceColor(cx,cz,h,depth,slope,vary){
_fc.copy(C_BENCH).lerp(C_SLOPE,ss(0.02,0.22,slope));
_fc.lerp(C_STEEP,ss(0.34,0.80,slope));
_fc.lerp(C_GULLY,ss(0.30,1.6,depth)*0.9);
if(depth>1.2) _fc.lerp(C_WET,clamp((depth-1.2)/2.6,0,1)*0.45);
_fc.offsetHSL(0,0,vary);
return _fc;
}
function buildTerrain(){
const pos=[],col=[],nrm=[];
const e=0.9;
const push=(x,z)=>{
const h=sampleH(x,z);
pos.push(x,h,z);
const g=gradH(x,z);
nrm.push(-g.x,1,-g.z);
};
const colOf=(x,z)=>{
const h=sampleH(x,z);
const u=clamp((z+D/2)/D,0,1);
const sx=(sampleH(x+e,z)-sampleH(x-e,z))/(2*e);
const sz=(sampleH(x,z+e)-sampleH(x,z-e))/(2*e);
const slope=Math.hypot(sx,sz);
const depth=Math.max(0,smoothSurface(x,u)-h);
const vary=(hash2(x*0.9,z*0.9)-0.5)*0.075;
const c=faceColor(x,z,h,depth,slope,vary);
return [c.r,c.g,c.b];
};
for(let r=0;r<N-1;r++){
for(let c=0;c<N-1;c++){
const x0=-W/2+(c/(N-1))*W, x1=-W/2+((c+1)/(N-1))*W;
const z0=-D/2+(r/(N-1))*D, z1=-D/2+((r+1)/(N-1))*D;
const tris=[[x0,z0,x1,z0,x1,z1],[x0,z0,x1,z1,x0,z1]];
for(const t of tris){
const cx=(t[0]+t[2]+t[4])/3, cz=(t[1]+t[3]+t[5])/3;
const cc=colOf(cx,cz);
for(let k=0;k<3;k++){
push(t[k*2],t[k*2+1]);
col.push(cc[0],cc[1],cc[2]);
}
}
}
}
const g=new THREE.BufferGeometry();
g.setAttribute('position',new THREE.Float32BufferAttribute(pos,3));
g.setAttribute('normal',new THREE.Float32BufferAttribute(nrm,3));
g.setAttribute('color',new THREE.Float32BufferAttribute(col,3));
const m=new THREE.Mesh(g,new THREE.MeshLambertMaterial({vertexColors:true,flatShading:true}));
m.receiveShadow=true;
scene.add(m);
return m;
}
const terrain=buildTerrain();
// diorama block sides + bottom
{
const pos=[],col=[];
const edge=[];
for(let c=0;c<N-1;c++) edge.push([-W/2+(c/(N-1))*W,-D/2]);
for(let r=0;r<N-1;r++) edge.push([W/2,-D/2+(r/(N-1))*D]);
for(let c=N-2;c>=0;c--) edge.push([-W/2+(c/(N-1))*W,D/2]);
for(let r=N-2;r>=0;r--) edge.push([-W/2,-D/2+(r/(N-1))*D]);
const c1=new THREE.Color(0xb08d5e), c2=new THREE.Color(0x8a6a44);
for(let i=0;i<edge.length;i++){
const a=edge[i], b=edge[(i+1)%edge.length];
const ah=sampleH(a[0],a[1]), bh=sampleH(b[0],b[1]);
const v=[a[0],ah,a[1], b[0],bh,b[1], b[0],BLOCK_BOTTOM,b[1],
a[0],ah,a[1], b[0],BLOCK_BOTTOM,b[1], a[0],BLOCK_BOTTOM,a[1]];
const cl=(i%3===0)?c1:c2;
for(let k=0;k<6;k++) pos.push(v[k*3],v[k*3+1],v[k*3+2]), col.push(cl.r,cl.g,cl.b);
}
pos.push(-W/2,BLOCK_BOTTOM,-D/2, W/2,BLOCK_BOTTOM,-D/2, W/2,BLOCK_BOTTOM,D/2,
-W/2,BLOCK_BOTTOM,-D/2, W/2,BLOCK_BOTTOM,D/2, -W/2,BLOCK_BOTTOM,D/2);
for(let k=0;k<6;k++) col.push(0.42,0.33,0.24);
const g=new THREE.BufferGeometry();
g.setAttribute('position',new THREE.Float32BufferAttribute(pos,3));
g.setAttribute('color',new THREE.Float32BufferAttribute(col,3));
g.computeVertexNormals();
scene.add(new THREE.Mesh(g,new THREE.MeshLambertMaterial({vertexColors:true,flatShading:true,side:THREE.DoubleSide})));
}
/* ============================================================
5. locate a terrace bench for the hypothetical strip
============================================================ */
function findBench(targetU){
const us=[],vals=[];
for(let i=0;i<=800;i++){
const u=0.06+0.90*i/800;
us.push(u); vals.push(terrace(H*Math.pow(1-u,1.2)));
}
const groups=[]; let s=0;
for(let i=1;i<=us.length;i++){
if(i===us.length||Math.abs(vals[i]-vals[s])>0.02){
if(us[i-1]-us[s]>0.012) groups.push({u0:us[s],u1:us[i-1],mid:(us[s]+us[i-1])/2,len:us[i-1]-us[s]});
s=i;
}
}
groups.sort((a,b)=>Math.abs(a.mid-targetU)-Math.abs(b.mid-targetU));
return groups[0]||{u0:0.40,u1:0.48,mid:0.44,len:0.08};
}
const BENCH=findBench(0.44);
const STRIP_U0=BENCH.u0-0.004, STRIP_U1=BENCH.u1+0.004;
const STRIP_R0=Math.floor(STRIP_U0*N), STRIP_R1=Math.ceil(STRIP_U1*N);
const MEAS_U=Math.min(0.72,STRIP_U1+0.20);
const MEAS_Z=-D/2+MEAS_U*D;
const STRIP_Z0=-D/2+STRIP_U0*D, STRIP_Z1=-D/2+STRIP_U1*D;
function depthAt(x,z){
const u=clamp((z+D/2)/D,0,1);
return Math.max(0,smoothSurface(x,u)-sampleH(x,z));
}
function inStrip(x,z){
return vegOn && z>=STRIP_Z0 && z<=STRIP_Z1;
}
/* ============================================================
6. vegetation strip (hypothetical)
============================================================ */
const vegGroup=new THREE.Group(); vegGroup.visible=false; scene.add(vegGroup);
{
// translucent band that follows the bench
const pos=[],idx=[];
for(let r=STRIP_R0;r<=STRIP_R1;r++){
const z=-D/2+(r/(N-1))*D;
for(let c=0;c<N;c++){
const x=-W/2+(c/(N-1))*W;
pos.push(x,heights[r*N+c]+0.08,z);
}
}
for(let r=0;r<STRIP_R1-STRIP_R0;r++){
for(let c=0;c<N-1;c++){
const a=r*N+c,b=r*N+c+1,cc=(r+1)*N+c,d=(r+1)*N+c+1;
idx.push(a,cc,b, b,cc,d);
}
}
const g=new THREE.BufferGeometry();
g.setAttribute('position',new THREE.Float32BufferAttribute(pos,3));
g.setIndex(idx); g.computeVertexNormals();
const band=new THREE.Mesh(g,new THREE.MeshLambertMaterial({
color:0x5c8f4a,transparent:true,opacity:0.5,depthWrite:false,flatShading:true,side:THREE.DoubleSide}));
band.renderOrder=2;
vegGroup.add(band);
// low-poly shrubs / small trees on the bench (skipped inside gully floors)
const count=520;
const shrub=new THREE.InstancedMesh(new THREE.ConeGeometry(0.62,1.7,5),new THREE.MeshLambertMaterial({flatShading:true}),count);
shrub.castShadow=true; shrub.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
const d=new THREE.Object3D(); const col=new THREE.Color();
let n=0,guard=0;
while(n<count && guard++<count*14){
const r=STRIP_R0+Math.random()*(STRIP_R1-STRIP_R0);
const c=Math.random()*N;
const x=-W/2+(c/(N-1))*W, z=-D/2+(r/(N-1))*D;
if(depthAt(x,z)>0.75) continue; // keep gully floors clear
const h=sampleH(x,z);
const tall=Math.random()<0.22;
const s=(tall?1.1:0.62)*(0.7+Math.random()*0.7);
d.position.set(x,h+(tall?1.25:0.62)*s*0.5,z);
d.rotation.set(0,Math.random()*6.283,0);
d.scale.set(s,tall?1.35:1.0,s);
d.updateMatrix();
shrub.setMatrixAt(n,d.matrix);
col.setHSL(0.24+Math.random()*0.06,0.36+Math.random()*0.18,0.26+Math.random()*0.14);
shrub.setColorAt(n,col);
n++;
}
shrub.count=n;
vegGroup.add(shrub);
}
/* ============================================================
7. rain streaks (decorative)
============================================================ */
const RAIN_N=700;
const rainPos=new Float32Array(RAIN_N*6);
const rainData=[];
for(let i=0;i<RAIN_N;i++){
const x=(Math.random()*2-1)*(W/2+6), z=(Math.random()*2-1)*(D/2+4);
rainData.push({x,z,y:sampleH(clamp(x,-W/2,W/2),clamp(z,-D/2,D/2))+2+Math.random()*34});
}
const rainGeo=new THREE.BufferGeometry();
rainGeo.setAttribute('position',new THREE.BufferAttribute(rainPos,3));
const rain=new THREE.LineSegments(rainGeo,new THREE.LineBasicMaterial({
color:0xbcd8f2,transparent:true,opacity:0.38,depthWrite:false}));
rain.frustumCulled=false; scene.add(rain);
/* ============================================================
8. runoff tracer particles (the routing toy)
============================================================ */
const MAXP=1200;
const st=new Uint8Array(MAXP); // 0 empty, 1 flowing, 2 fading (intercepted)
const px=new Float32Array(MAXP), pz=new Float32Array(MAXP);
const pt=new Float32Array(MAXP), pseed=new Float32Array(MAXP);
const pcount=new Uint8Array(MAXP); // has it crossed the measurement line
const flowMesh=new THREE.InstancedMesh(
new THREE.TetrahedronGeometry(0.36),
new THREE.MeshLambertMaterial({flatShading:true,color:0xffffff}),
MAXP);
flowMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
flowMesh.frustumCulled=false;
scene.add(flowMesh);
const COL_FLOW=new THREE.Color(0x3f8ecb), COL_ABS=new THREE.Color(0x7fc05a);
for(let i=0;i<MAXP;i++) flowMesh.setColorAt(i,COL_FLOW);
flowMesh.instanceColor.needsUpdate=true;
let vegOn=false;
let colorDirty=false;
function spawn(i){
px[i]=(Math.random()*2-1)*(W/2-3);
pz[i]=-D/2+(0.015+Math.random()*0.26)*D;
st[i]=1; pcount[i]=0; pseed[i]=Math.random()*100;
flowMesh.setColorAt(i,COL_FLOW); colorDirty=true;
}
for(let i=0;i<MAXP;i++) spawn(i);
const dummy=new THREE.Object3D();
const BUCKETS=24;
const dist=new Float32Array(BUCKETS);
let toeRate=0, toeEMA=0, clock=0;
function updateParticles(dt){
const ABSORB_LAMBDA=0.05; // schematic interception rate inside the strip
const STRIP_SLOW=0.30; // roughness slowdown inside the strip
for(let i=0;i<MAXP;i++){
if(st[i]===0){ spawn(i); continue; }
if(st[i]===2){
pt[i]-=dt;
if(pt[i]<=0){ st[i]=0; }
continue;
}
const x=px[i], z=pz[i];
const g=gradH(x,z);
const slope=Math.hypot(g.x,g.z);
let vx=-g.x, vz=-g.z;
let m=Math.hypot(vx,vz);
if(m<1e-5){vx=0;vz=1;m=1;}
vx/=m; vz/=m;
let speed=1.6+7.0*Math.min(slope,0.8);
const prevZ=z;
if(inStrip(x,z)){
// schematic vegetation: slower, pushed along the contour, part intercepted
speed*=STRIP_SLOW;
const lx=-vz, lz=vx; // contour-parallel direction
const sign=Math.sin(pseed[i]*7.3+clock*0.5)>0?1:-1;
let nx=lx*sign*0.85+vx*0.50, nz=lz*sign*0.85+vz*0.50;
const nm=Math.hypot(nx,nz)||1;
vx=nx/nm; vz=nz/nm;
if(Math.random()<1-Math.exp(-ABSORB_LAMBDA*dt)){
st[i]=2; pt[i]=0.9;
flowMesh.setColorAt(i,COL_ABS); colorDirty=true;
continue;
}
} else if(slope<0.10){
// slight downslope creep across flat benches (keeps sheet flow progressing)
const w=0.40*(1-slope/0.10);
vx=vx*(1-w); vz=vz*(1-w)+w;
const nm=Math.hypot(vx,vz)||1; vx/=nm; vz/=nm;
speed=Math.max(speed,1.25);
}
px[i]=clamp(x+vx*speed*dt,-W/2+0.4,W/2-0.4);
pz[i]=z+vz*speed*dt;
// measurement line crossing -> distribution of flow across the slope
if(!pcount[i]&&prevZ<MEAS_Z&&pz[i]>=MEAS_Z){
pcount[i]=1;
const b=clamp(Math.floor((px[i]+W/2)/W*BUCKETS),0,BUCKETS-1);
dist[b]+=1;
}
if(pz[i]>D/2-1.0){ st[i]=0; toeRate++; }
}
// decay the memory of the distribution
const dec=Math.exp(-dt/2.2);
for(let k=0;k<BUCKETS;k++) dist[k]*=dec;
// render
for(let i=0;i<MAXP;i++){
if(st[i]===0){ dummy.scale.setScalar(0.0001); dummy.position.set(0,-999,0); dummy.updateMatrix(); flowMesh.setMatrixAt(i,dummy.matrix); continue; }
const x=px[i], z=pz[i];
const h=sampleH(x,z);
let s=1.0;
if(st[i]===2) s=Math.max(0.0001,(pt[i]/0.9));
dummy.position.set(x,h+0.30*s,z);
dummy.rotation.set(pseed[i],clock*2.4+pseed[i],pseed[i]*0.5);
dummy.scale.setScalar(s);
dummy.updateMatrix();
flowMesh.setMatrixAt(i,dummy.matrix);
}
flowMesh.instanceMatrix.needsUpdate=true;
if(colorDirty){ flowMesh.instanceColor.needsUpdate=true; colorDirty=false; }
}
/* ============================================================
9. camera controls (hand written, no addons)
============================================================ */
let camTheta=0.62, camPhi=1.02, camRadius=96;
let tTheta=camTheta, tPhi=camPhi, tRadius=camRadius;
const target=new THREE.Vector3(0,13,2), tTarget=target.clone();
function resetView(){ tTheta=0.62; tPhi=1.02; tRadius=96; tTarget.set(0,13,2); }
function updateCamera(dt){
const k=Math.min(1,dt*9);
camTheta=lerp(camTheta,tTheta,k); camPhi=lerp(camPhi,tPhi,k); camRadius=lerp(camRadius,tRadius,k);
target.lerp(tTarget,k);
const sp=Math.sin(camPhi);
camera.position.set(
target.x+camRadius*sp*Math.sin(camTheta),
target.y+camRadius*Math.cos(camPhi),
target.z+camRadius*sp*Math.cos(camTheta));
camera.lookAt(target);
}
const pointers=new Map();
let dragMode='orbit', lastX=0, lastY=0, pinchDist=0;
canvas.addEventListener('pointerdown',e=>{
canvas.setPointerCapture(e.pointerId);
pointers.set(e.pointerId,{x:e.clientX,y:e.clientY});
if(pointers.size===1){ dragMode=(e.button===2||e.shiftKey)?'pan':'orbit'; lastX=e.clientX; lastY=e.clientY; }
});
canvas.addEventListener('pointermove',e=>{
if(!pointers.has(e.pointerId)) return;
const p=pointers.get(e.pointerId); p.x=e.clientX; p.y=e.clientY;
if(pointers.size===2){
const [a,b]=[...pointers.values()];
const d=Math.hypot(a.x-b.x,a.y-b.y);
if(pinchDist>0) tRadius=clamp(tRadius*(pinchDist/d),28,300);
pinchDist=d; return;
}
const dx=e.clientX-lastX, dy=e.clientY-lastY;
lastX=e.clientX; lastY=e.clientY;
if(dragMode==='orbit'){
tTheta-=dx*0.005;
tPhi=clamp(tPhi-dy*0.004,0.16,1.50);
}else{
const right=new THREE.Vector3().setFromMatrixColumn(camera.matrix,0);
const up=new THREE.Vector3().setFromMatrixColumn(camera.matrix,1);
const s=camRadius*0.0013;
tTarget.addScaledVector(right,-dx*s).addScaledVector(up,dy*s);
tTarget.x=clamp(tTarget.x,-70,70); tTarget.y=clamp(tTarget.y,-5,40); tTarget.z=clamp(tTarget.z,-70,70);
}
});
function endPointer(e){ pointers.delete(e.pointerId); if(pointers.size<2) pinchDist=0; }
canvas.addEventListener('pointerup',endPointer);
canvas.addEventListener('pointercancel',endPointer);
canvas.addEventListener('contextmenu',e=>e.preventDefault());
canvas.addEventListener('wheel',e=>{
e.preventDefault();
tRadius=clamp(tRadius*(1+Math.sign(e.deltaY)*0.10),28,300);
},{passive:false});
/* ============================================================
10. annotations
============================================================ */
const labelBox=document.getElementById('labels');
let labelsOn=true;
function makeLabel(text,cls){const d=document.createElement('div');d.className='tag '+(cls||'');d.innerHTML=text;labelBox.appendChild(d);return d;}
const LABELS=[
{el:makeLabel('Ridge top'), pos:new THREE.Vector3(-24,0,-D/2+3)},
{el:makeLabel('Terrace bench'), pos:new THREE.Vector3(19,0,-D/2+(BENCH.mid)*D)},
{el:makeLabel('Incised gully',''), cls:'gully', pos:new THREE.Vector3(channelX(GULLIES[1],0.78),0,-D/2+0.78*D)},
{el:makeLabel('Vegetation strip <small>(hypothetical)</small>',''), cls:'veg', pos:new THREE.Vector3(-15,0,-D/2+BENCH.mid*D)},
{el:makeLabel('Toe plain'), pos:new THREE.Vector3(23,0,D/2-4)},
];
const _p=new THREE.Vector3();
function updateLabels(){
for(const L of LABELS){
const isVeg=L.el.classList.contains('veg');
if(!labelsOn || (isVeg&&!vegOn)){ L.el.style.display='none'; continue; }
const x=L.pos.x, z=L.pos.z;
_p.set(x,sampleH(x,z)+2.4,z).project(camera);
if(_p.z>1){ L.el.style.display='none'; continue; }
L.el.style.display='block';
L.el.style.left=(_p.x*0.5+0.5)*innerWidth+'px';
L.el.style.top =(-_p.y*0.5+0.5)*innerHeight+'px';
}
}
/* ============================================================
11. UI wiring + chart
============================================================ */
const btnVeg=document.getElementById('btnVeg'), vegState=document.getElementById('vegState');
const btnRain=document.getElementById('btnRain'), btnLabels=document.getElementById('btnLabels');
const btnReset=document.getElementById('btnReset'), btnPause=document.getElementById('btnPause');
const elRouting=document.getElementById('routing'), elToe=document.getElementById('routing');
const elToe2=document.getElementById('toe'), elStrip=document.getElementById('stripState');
const chart=document.getElementById('chart'), cctx=chart.getContext('2d');
let paused=false, rainOn=true;
function setVeg(v){
vegOn=v; vegGroup.visible=v;
btnVeg.classList.toggle('on',v);
vegState.textContent=v?'ON':'OFF';
elStrip.textContent=v
? 'On — benches intercept & spread surface flow (schematic)'
: 'Off — bare benches, flow organizes into gullies';
}
btnVeg.onclick=()=>setVeg(!vegOn);
btnRain.onclick=()=>{rainOn=!rainOn;btnRain.classList.toggle('on',rainOn);rain.visible=rainOn;};
btnLabels.onclick=()=>{labelsOn=!labelsOn;btnLabels.classList.toggle('on',labelsOn);};
btnReset.onclick=resetView;
btnPause.onclick=()=>{paused=!paused;btnPause.classList.toggle('on',paused);
document.getElementById('paused').style.display=paused?'block':'none';};
addEventListener('keydown',e=>{
const k=e.key.toLowerCase();
if(k==='v')setVeg(!vegOn);
if(k==='r')resetView();
if(k==='l'){labelsOn=!labelsOn;btnLabels.classList.toggle('on',labelsOn);}
if(k===' '){e.preventDefault();btnPause.click();}
});
setVeg(false);
function drawChart(){
const w=chart.width,h=chart.height;
cctx.clearRect(0,0,w,h);
let max=0.02; for(let i=0;i<BUCKETS;i++) max=Math.max(max,dist[i]);
const bw=w/BUCKETS;
for(let i=0;i<BUCKETS;i++){
const v=dist[i]/max, bh=v*(h-16);
cctx.fillStyle='rgba(90,160,210,0.88)';
cctx.fillRect(i*bw+1.2,h-13-bh,bw-2.4,bh);
}
cctx.strokeStyle='rgba(226,132,100,0.75)'; cctx.setLineDash([2,3]); cctx.lineWidth=1;
for(const g of GULLIES){
const gx=channelX(g,MEAS_U);
const x=(gx+W/2)/W*w;
cctx.beginPath(); cctx.moveTo(x,h-11); cctx.lineTo(x,h-4); cctx.stroke();
}
cctx.setLineDash([]);
cctx.strokeStyle='rgba(255,255,255,0.28)';
cctx.beginPath(); cctx.moveTo(0,h-12.5); cctx.lineTo(w,h-12.5); cctx.stroke();
}
function updateReadouts(dt){
toeEMA=lerp(toeEMA,toeRate,Math.min(1,dt*3)); toeRate=0;
let total=0; const sorted=[];
for(let i=0;i<BUCKETS;i++){total+=dist[i];sorted.push(dist[i]);}
sorted.sort((a,b)=>b-a);
let top=0; for(let i=0;i<6;i++) top+=sorted[i]||0;
const share=total>0.5?top/total:0;
let word='sparse';
if(share>0.58) word='<em>concentrated</em> in the gullies';
else if(share>0.40) word='partly concentrated';
else word='<em>dispersed</em> across the slope';
elRouting.innerHTML=word+' <span style="opacity:.6">('+(total*100).toFixed(0)+'% of tracers in top quarter)</span>';
elToe2.innerHTML='<em>'+toeEMA.toFixed(1)+'</em> tracer arrivals / s <span style="opacity:.6">— schematic, not discharge</span>';
drawChart();
}
/* ============================================================
12. main loop
============================================================ */
function updateRain(dt){
if(!rainOn) return;
for(let i=0;i<RAIN_N;i++){
const d=rainData[i];
d.y-=(30+Math.random()*10)*dt;
const h=sampleH(clamp(d.x,-W/2,W/2),clamp(d.z,-D/2,D/2));
if(d.y<h+0.05){
d.x=(Math.random()*2-1)*(W/2+6);
d.z=(Math.random()*2-1)*(D/2+4);
d.y=sampleH(clamp(d.x,-W/2,W/2),clamp(d.z,-D/2,D/2))+6+Math.random()*32;
}
const o=i*6;
rainPos[o]=d.x; rainPos[o+1]=d.y; rainPos[o+2]=d.z;
rainPos[o+3]=d.x+0.25; rainPos[o+4]=d.y-1.9; rainPos[o+5]=d.z+0.1;
}
rainGeo.attributes.position.needsUpdate=true;
}
let last=performance.now();
function animate(now){
requestAnimationFrame(animate);
const dt=Math.min(0.05,(now-last)/1000); last=now;
if(!paused){
clock+=dt;
updateParticles(dt);
updateRain(dt);
updateReadouts(dt);
}
updateCamera(dt);
updateLabels();
renderer.render(scene,camera);
}
requestAnimationFrame(animate);
addEventListener('resize',()=>{
camera.aspect=innerWidth/innerHeight; camera.updateProjectionMatrix();
renderer.setSize(innerWidth,innerHeight);
});
</script>
</body>
</html>
```