Prompt specification
Build or customize the Three.js 3D scene "Brim width and sun angle" 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: Brim width and sun angle
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/brim-width-and-sun-angle-x0590
Scene Description Prompt:
Make a low-poly Three.js scene in a self-contained HTML file using cdnjs: brim width and sun angle. Compare two hats on identical head forms while moving the light direction; shadow coverage changes visibly according to geometry, without assigning protective ratings.
Working Three.js Starter (brim-width-and-sun-angle-x0590):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Brim width × sun angle — shadow geometry comparison</title>
<style>
:root{
--panel: rgba(14,19,26,.82);
--line: rgba(255,255,255,.12);
--ink: #e9eef3;
--dim: #9fb0bd;
--a: #6ea8dc; /* hat A */
--b: #e08a4e; /* hat B */
}
*{box-sizing:border-box}
html,body{margin:0;height:100%;overflow:hidden;background:#dbe6ee;
font-family:ui-sans-serif,system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
color:var(--ink)}
#view{position:fixed;inset:0;display:block;touch-action:none;cursor:grab}
#view:active{cursor:grabbing}
#labels{position:fixed;inset:0;pointer-events:none}
.tag{position:absolute;transform:translate(-50%,-140%);white-space:nowrap;
background:rgba(10,14,19,.78);border:1px solid var(--line);border-radius:9px;
padding:4px 9px;font-size:11.5px;letter-spacing:.2px;box-shadow:0 6px 18px rgba(0,0,0,.25)}
.tag b{font-weight:650}
.panel{position:fixed;background:var(--panel);backdrop-filter:blur(9px);
border:1px solid var(--line);border-radius:14px;padding:13px 15px;
box-shadow:0 14px 40px rgba(0,0,0,.32);font-size:12.5px;line-height:1.45}
#controls{left:14px;top:14px;width:274px}
#readout{right:14px;top:14px;width:330px;max-height:calc(100vh - 28px);overflow:auto}
h1{margin:0 0 2px;font-size:14px;letter-spacing:.2px}
.sub{color:var(--dim);font-size:11px;margin:0 0 10px}
label{display:block;margin:9px 0 3px;color:var(--dim);font-size:11px;
display:flex;justify-content:space-between}
label span{color:var(--ink);font-variant-numeric:tabular-nums}
input[type=range]{width:100%;accent-color:#f0b46a;height:20px}
.btns{display:flex;gap:7px;margin-top:11px;flex-wrap:wrap}
button{flex:1 1 auto;background:rgba(255,255,255,.07);color:var(--ink);
border:1px solid var(--line);border-radius:8px;padding:7px 9px;font-size:11.5px;cursor:pointer}
button:hover{background:rgba(255,255,255,.14)}
button.on{background:#f0b46a;color:#20160a;border-color:#f0b46a;font-weight:650}
table{width:100%;border-collapse:collapse;font-size:11.5px;margin-top:4px}
th,td{padding:4px 3px;text-align:right;border-bottom:1px solid rgba(255,255,255,.07);
font-variant-numeric:tabular-nums}
th:first-child,td:first-child{text-align:left;color:var(--dim)}
th{color:var(--dim);font-weight:600;font-size:10.5px;text-transform:uppercase;letter-spacing:.4px}
td:nth-child(2){color:var(--a)} td:nth-child(3){color:var(--b)} td:nth-child(4){color:var(--dim)}
.note{margin-top:10px;color:var(--dim);font-size:10.5px;line-height:1.5;
border-top:1px solid var(--line);padding-top:8px}
h2{font-size:11px;text-transform:uppercase;letter-spacing:.5px;color:var(--dim);
margin:14px 0 4px;font-weight:600}
#chart{width:100%;height:132px;display:block;border-radius:8px;
border:1px solid var(--line);background:rgba(255,255,255,.03)}
.legend{display:flex;gap:12px;font-size:10.5px;color:var(--dim);margin-top:5px}
.sw{display:inline-block;width:9px;height:9px;border-radius:2px;margin-right:4px;vertical-align:middle}
@media(max-width:900px){
#controls{width:calc(50vw - 22px)} #readout{width:calc(50vw - 22px)}
}
@media(max-width:620px){
#controls,#readout{position:fixed;width:calc(100vw - 28px)}
#readout{top:auto;bottom:14px;max-height:46vh}
}
</style>
</head>
<body>
<canvas id="view"></canvas>
<div id="labels"></div>
<section class="panel" id="controls">
<h1>Brim width × sun angle</h1>
<p class="sub">Two hats, identical head forms, one moving light.</p>
<label>Sun azimuth <span id="azVal">28°</span></label>
<input id="az" type="range" min="0" max="360" step="1" value="28">
<label>Sun elevation <span id="elVal">46°</span></label>
<input id="el" type="range" min="5" max="85" step="1" value="46">
<div class="btns">
<button id="sweep">▶ Sweep sun</button>
<button id="reset">Reset view</button>
</div>
<div class="btns">
<button id="front">Front</button>
<button id="side">Side</button>
<button id="top">Top</button>
</div>
<p class="sub" style="margin:10px 0 0">
Azimuth 0° = sun in front of the face · 90° = right side · 180° = behind.<br>
Drag to orbit, scroll to zoom, shift-drag to pan.
</p>
</section>
<section class="panel" id="readout">
<h2>Measured geometry</h2>
<table>
<thead><tr><th>Quantity</th><th>Hat A</th><th>Hat B</th><th>B − A</th></tr></thead>
<tbody id="tbody"></tbody>
</table>
<h2>Hat-only ground footprint vs. sun azimuth</h2>
<canvas id="chart"></canvas>
<div class="legend">
<span><i class="sw" style="background:var(--a)"></i>Hat A</span>
<span><i class="sw" style="background:var(--b)"></i>Hat B</span>
<span>elevation ${ELNOTE}</span>
</div>
<p class="note" id="note">
Every number above is a direct geometric measurement of the rendered scene:
projected shadow footprint area, shadow reach, and the fraction of the head
form whose surface is occluded from the sun by the hat geometry. These
describe how shadow shape responds to brim width and sun angle only —
no protective rating, UV factor, or coverage classification is assigned
or implied. The blue overlay on the ground is the measured combined
(hat + head) shadow footprint; its amber rim marks its boundary.
</p>
</section>
<script type="importmap">
{ "imports": { "three": "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js" } }
</script>
<script type="module">
import * as THREE from 'three';
/* ------------------------------------------------------------------ setup */
const canvas = document.getElementById('view');
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.toneMapping = THREE.ACESFilmicToneMapping;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdbe6ee);
scene.fog = new THREE.Fog(0xdbe6ee, 11, 30);
const camera = new THREE.PerspectiveCamera(36, innerWidth/innerHeight, 0.05, 120);
/* ------------------------------------------------------- camera (hand-rolled) */
const cam = { theta:0.92, phi:1.02, radius:3.15, target:new THREE.Vector3(0,0.42,0) };
function updateCamera(){
const s = new THREE.Spherical(cam.radius, cam.phi, cam.theta);
camera.position.setFromSpherical(s).add(cam.target);
camera.lookAt(cam.target);
}
updateCamera();
let drag=null;
canvas.addEventListener('pointerdown', e=>{
drag = { x:e.clientX, y:e.clientY, pan:e.shiftKey||e.button===1||e.button===2 };
canvas.setPointerCapture(e.pointerId);
});
canvas.addEventListener('pointermove', e=>{
if(!drag) return;
const dx=e.clientX-drag.x, dy=e.clientY-drag.y; drag.x=e.clientX; drag.y=e.clientY;
if(drag.pan){
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix,0);
const k = 0.0013*cam.radius/3;
cam.target.addScaledVector(right,-dx*k).y += dy*k*0.6;
cam.target.y = THREE.MathUtils.clamp(cam.target.y,0.05,1.6);
}else{
cam.theta -= dx*0.006;
cam.phi = THREE.MathUtils.clamp(cam.phi - dy*0.005, 0.16, 1.44);
}
updateCamera();
});
const endDrag = ()=>{ drag=null; };
canvas.addEventListener('pointerup', endDrag);
canvas.addEventListener('pointercancel', endDrag);
canvas.addEventListener('contextmenu', e=>e.preventDefault());
canvas.addEventListener('wheel', e=>{
e.preventDefault();
cam.radius = THREE.MathUtils.clamp(cam.radius*(1+e.deltaY*0.0011), 1.3, 9);
updateCamera();
}, {passive:false});
/* ------------------------------------------------------------------ lights */
scene.add(new THREE.HemisphereLight(0xbcd6e8, 0xa98f70, 0.75));
const fill = new THREE.DirectionalLight(0xdfe9f5, 0.35);
fill.position.set(-3, 4, -2); scene.add(fill);
const sunLight = new THREE.DirectionalLight(0xfff1d6, 2.5);
sunLight.castShadow = true;
sunLight.shadow.mapSize.set(2048,2048);
const sc = sunLight.shadow.camera;
sc.left=-4; sc.right=4; sc.top=4; sc.bottom=-4; sc.near=0.1; sc.far=26;
sunLight.shadow.bias = -0.0006;
sunLight.shadow.normalBias = 0.02;
scene.add(sunLight, sunLight.target);
const sun = { az:28, el:46 };
const sunDir = new THREE.Vector3();
const sunTarget = new THREE.Vector3(0,0.35,0);
const sunMarker = new THREE.Mesh(
new THREE.SphereGeometry(0.055, 10, 7),
new THREE.MeshBasicMaterial({ color:0xffe6a8 })
);
scene.add(sunMarker);
const rayLineGeo = new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(), new THREE.Vector3()]);
const rayLine = new THREE.Line(rayLineGeo, new THREE.LineBasicMaterial({
color:0xffc46b, transparent:true, opacity:0.55 }));
scene.add(rayLine);
/* ------------------------------------------------------------------- scene */
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(40,40),
new THREE.MeshStandardMaterial({ color:0xd6c5a7, roughness:1, metalness:0 })
);
ground.rotation.x = -Math.PI/2;
ground.receiveShadow = true;
scene.add(ground);
const HEAD_R = 0.115, HEAD_Y = 0.36, BRIM_Y = 0.40, CELL = 0.0125;
const subjects = [];
function buildSubject(cfg){
const group = new THREE.Group();
group.position.x = cfg.x;
scene.add(group);
const hatMat = new THREE.MeshStandardMaterial({
color:cfg.color, flatShading:true, roughness:0.72, metalness:0.04, side:THREE.DoubleSide });
const skinMat = new THREE.MeshStandardMaterial({
color:0xe4cdb6, flatShading:true, roughness:0.92, side:THREE.DoubleSide });
const plinthMat = new THREE.MeshStandardMaterial({
color:0x9aa2a9, flatShading:true, roughness:0.85 });
const hatMeshes = [], headMeshes = [];
const brim = new THREE.Mesh(new THREE.CylinderGeometry(cfg.brimR, cfg.brimR*0.97, 0.012, 12), hatMat);
brim.position.y = BRIM_Y; brim.castShadow = true; brim.receiveShadow = true;
group.add(brim); hatMeshes.push(brim);
const crown = new THREE.Mesh(new THREE.CylinderGeometry(0.090, 0.107, 0.15, 12), hatMat);
crown.position.y = BRIM_Y + 0.006 + 0.075; crown.castShadow = true; crown.receiveShadow = true;
group.add(crown); hatMeshes.push(crown);
const head = new THREE.Mesh(new THREE.SphereGeometry(HEAD_R, 10, 7), skinMat);
head.position.y = HEAD_Y; head.castShadow = true; head.receiveShadow = true;
group.add(head); headMeshes.push(head);
const nose = new THREE.Mesh(new THREE.ConeGeometry(0.021, 0.05, 4), skinMat);
nose.rotation.x = Math.PI/2; nose.position.set(0, HEAD_Y-0.005, 0.104);
nose.castShadow = true; group.add(nose); headMeshes.push(nose);
const neck = new THREE.Mesh(new THREE.CylinderGeometry(0.048, 0.056, 0.09, 8), skinMat);
neck.position.y = 0.235; neck.castShadow = true; group.add(neck); headMeshes.push(neck);
const shoulders = new THREE.Mesh(new THREE.CylinderGeometry(0.075, 0.135, 0.12, 8), skinMat);
shoulders.position.y = 0.13; shoulders.castShadow = true; group.add(shoulders); headMeshes.push(shoulders);
const plinth = new THREE.Mesh(new THREE.CylinderGeometry(0.185, 0.2, 0.07, 12), plinthMat);
plinth.position.y = 0.035; plinth.castShadow = true; plinth.receiveShadow = true;
group.add(plinth);
// 1 m reference ring on the ground
const ring = new THREE.Mesh(
new THREE.RingGeometry(0.985, 1.0, 64),
new THREE.MeshBasicMaterial({ color:0x8e7c62, transparent:true, opacity:0.55 })
);
ring.rotation.x = -Math.PI/2; ring.position.set(cfg.x, 0.004, 0); scene.add(ring);
// measured-footprint overlay
const oc = document.createElement('canvas');
const otex = new THREE.CanvasTexture(oc); otex.colorSpace = THREE.SRGBColorSpace;
const omesh = new THREE.Mesh(
new THREE.PlaneGeometry(1,1),
new THREE.MeshBasicMaterial({ map:otex, transparent:true, depthWrite:false })
);
omesh.rotation.x = -Math.PI/2; omesh.position.y = 0.005; omesh.renderOrder = 2;
scene.add(omesh);
// world-space triangle lists (static geometry) for the projection measurement
group.updateMatrixWorld(true);
const hatTris = worldTris(hatMeshes), headTris = worldTris(headMeshes);
const s = { ...cfg, group, hatMeshes, headMeshes, hatTris, headTris,
overlay:{ canvas:oc, tex:otex, mesh:omesh }, metrics:null };
subjects.push(s);
const tag = document.createElement('div');
tag.className = 'tag';
tag.innerHTML = `<b>${cfg.name}</b> · brim ⌀${(cfg.brimR*2000).toFixed(0)} mm`;
document.getElementById('labels').appendChild(tag);
s.tag = tag;
return s;
}
function worldTris(meshes){
const out = [];
const v = new THREE.Vector3();
for(const m of meshes){
const g = m.geometry, pos = g.attributes.position, idx = g.index;
const n = pos.count;
const pts = [];
for(let i=0;i<n;i++){
v.fromBufferAttribute(pos,i).applyMatrix4(m.matrixWorld);
pts.push(v.clone());
}
if(idx){
for(let i=0;i<idx.count;i+=3)
out.push([pts[idx.getX(i)], pts[idx.getX(i+1)], pts[idx.getX(i+2)]]);
}else{
for(let i=0;i+2<n;i+=3) out.push([pts[i],pts[i+1],pts[i+2]]);
}
}
return out;
}
buildSubject({ name:'Hat A', brimR:0.155, color:0x4d83b8, x:-0.62 });
buildSubject({ name:'Hat B', brimR:0.260, color:0xc97a3c, x: 0.62 });
/* ------------------------------------------------- projection / footprint math
The shadow of an object under a directional light is exactly the union of
the projections of its surface triangles onto the ground plane along the
light direction, so we rasterise that union on a fixed 12.5 mm cell. */
function projectXZ(v, dir){
const t = v.y/dir.y;
return { x:v.x - t*dir.x, z:v.z - t*dir.z };
}
function fillTriangle(mask, w, h, ox, oz, cell, a, b, c){
const zmin = Math.min(a.z,b.z,c.z), zmax = Math.max(a.z,b.z,c.z);
let j0 = Math.max(0, Math.ceil((zmin-oz)/cell-0.5));
let j1 = Math.min(h-1, Math.floor((zmax-oz)/cell-0.5));
const E = [[a,b],[b,c],[c,a]];
for(let j=j0;j<=j1;j++){
const zc = oz+(j+0.5)*cell;
const xs = [];
for(const [p,q] of E){
if((p.z<=zc && q.z>zc)||(q.z<=zc && p.z>zc)){
const t=(zc-p.z)/(q.z-p.z);
xs.push(p.x+t*(q.x-p.x));
}
}
if(xs.length<2) continue;
xs.sort((m,n)=>m-n);
let i0=Math.max(0, Math.ceil((xs[0]-ox)/cell-0.5));
let i1=Math.min(w-1, Math.floor((xs[1]-ox)/cell-0.5));
for(let i=i0;i<=i1;i++) mask[j*w+i]=1;
}
}
function computeFootprint(tris, dir, centerX){
const proj = tris.map(t=>t.map(v=>projectXZ(v,dir)));
let minX=Infinity,maxX=-Infinity,minZ=Infinity,maxZ=-Infinity;
for(const p of proj) for(const q of p){
if(q.x<minX)minX=q.x; if(q.x>maxX)maxX=q.x;
if(q.z<minZ)minZ=q.z; if(q.z>maxZ)maxZ=q.z;
}
const cell = Math.max(CELL,(maxX-minX)/700,(maxZ-minZ)/700);
const ox = minX-cell, oz = minZ-cell;
const w = Math.max(1,Math.ceil((maxX-minX)/cell)+2);
const h = Math.max(1,Math.ceil((maxZ-minZ)/cell)+2);
const mask = new Uint8Array(w*h);
for(const p of proj) fillTriangle(mask,w,h,ox,oz,cell,p[0],p[1],p[2]);
let count=0; for(let i=0;i<mask.length;i++) count+=mask[i];
// reach / length / width measured on the projected vertices (exact, not sampled)
const hl = Math.hypot(dir.x,dir.z)||1;
const hx = dir.x/hl, hz = dir.z/hl;
let reach=0, sMax=-Infinity, sMin=Infinity, tMax=-Infinity, tMin=Infinity;
for(const p of proj) for(const q of p){
const dx=q.x-centerX;
reach = Math.max(reach, Math.hypot(dx,q.z));
const s = dx*hx + q.z*hz;
const t = dx*hz - q.z*hx;
if(s>sMax)sMax=s; if(s<sMin)sMin=s;
if(t>tMax)tMax=t; if(t<tMin)tMin=t;
}
return { area:count*cell*cell, reach, length:sMax-sMin, width:tMax-tMin,
mask, w, h, ox, oz, cell };
}
/* ------------------------------------------ head surface occlusion by the hat */
const fib = [];
{
const n = 240, ga = Math.PI*(3-Math.sqrt(5));
for(let i=0;i<n;i++){
const y = 1-(i/(n-1))*2, r = Math.sqrt(Math.max(0,1-y*y)), th = ga*i;
fib.push(new THREE.Vector3(Math.cos(th)*r, y, Math.sin(th)*r));
}
}
const raycaster = new THREE.Raycaster();
raycaster.near = 0; raycaster.far = 3;
function computeShade(s){
const o = new THREE.Vector3(), origin = new THREE.Vector3();
let shaded = 0, low = 0, lowShaded = 0;
for(const dir of fib){
origin.set(s.x,0,0).addScaledVector(dir, HEAD_R*1.002).add(new THREE.Vector3(0,HEAD_Y,0));
raycaster.set(origin, sunDir);
const hit = raycaster.intersectObjects(s.hatMeshes,false).length>0;
if(hit) shaded++;
if(origin.y < BRIM_Y-0.004){ low++; if(hit) lowShaded++; }
}
return { all: shaded/fib.length, low: low? lowShaded/low : 0 };
}
/* --------------------------------------------------------------- overlays */
function paintOverlay(s, fp){
const { canvas:oc, tex, mesh } = s.overlay;
oc.width = fp.w; oc.height = fp.h;
const ctx = oc.getContext('2d');
const img = ctx.createImageData(fp.w, fp.h);
const d = img.data;
for(let j=0;j<fp.h;j++){
for(let i=0;i<fp.w;i++){
const idx=(j*fp.w+i)*4;
if(!fp.mask[j*fp.w+i]) continue;
const edge = (i===0||j===0||i===fp.w-1||j===fp.h-1) ||
!fp.mask[j*fp.w+i-1] || !fp.mask[j*fp.w+i+1] ||
!fp.mask[(j-1)*fp.w+i] || !fp.mask[(j+1)*fp.w+i];
if(edge){ d[idx]=255; d[idx+1]=186; d[idx+2]=72; d[idx+3]=225; }
else { d[idx]=36; d[idx+1]=62; d[idx+2]=120; d[idx+3]=112; }
}
}
ctx.putImageData(img,0,0);
tex.needsUpdate = true;
mesh.scale.set(fp.w*fp.cell, fp.h*fp.cell, 1);
mesh.position.set(fp.ox+fp.w*fp.cell/2, 0.005, fp.oz+fp.h*fp.cell/2);
}
/* --------------------------------------------------------------- sun update */
function updateSun(){
const a = THREE.MathUtils.degToRad(sun.az), e = THREE.MathUtils.degToRad(sun.el);
sunDir.set(Math.cos(e)*Math.sin(a), Math.sin(e), Math.cos(e)*Math.cos(a));
sunLight.position.copy(sunDir).multiplyScalar(9).add(sunTarget);
sunLight.target.position.copy(sunTarget);
sunMarker.position.copy(sunDir).multiplyScalar(4.3).add(new THREE.Vector3(0,0.3,0));
const p = rayLine.geometry.attributes.position;
const start = new THREE.Vector3(subjects[0].x, HEAD_Y+0.18, 0);
p.setXYZ(0, start.x, start.y, start.z);
p.setXYZ(1, start.x+sunDir.x*1.5, start.y+sunDir.y*1.5, start.z+sunDir.z*1.5);
p.needsUpdate = true;
rayLine.geometry.computeBoundingSphere();
document.getElementById('azVal').textContent = sun.az.toFixed(0)+'°';
document.getElementById('elVal').textContent = sun.el.toFixed(0)+'°';
dirty = true;
}
/* --------------------------------------------------------------- read-out */
const tbody = document.getElementById('tbody');
function fmt(v,d){ return (v>=0?'+':'')+v.toFixed(d); }
function buildTable(){
const rows = [
['Brim radius', s=>`${(s.brimR*2000).toFixed(0)} mm`, null, 0],
['Overhang past head', s=>`${((s.brimR-HEAD_R)*1000).toFixed(0)} mm`, null, 0],
['Hat-only ground footprint', s=>s.metrics.footHat.area.toFixed(4)+' m²', 'footHat', 4],
['Hat + head ground footprint', s=>s.metrics.footAll.area.toFixed(4)+' m²', 'footAll', 4],
['Shadow reach from head axis', s=>s.metrics.footAll.reach.toFixed(2)+' m', 'reach', 2],
['Shadow length along sun line', s=>s.metrics.footAll.length.toFixed(2)+' m', 'length', 2],
['Shadow width across sun line', s=>s.metrics.footAll.width.toFixed(2)+' m', 'width', 2],
['Head surface shaded by hat', s=>(s.metrics.shade.all*100).toFixed(0)+' %', 'shadeAll', 0],
['Below-brim head points shaded', s=>(s.metrics.shade.low*100).toFixed(0)+' %', 'shadeLow', 0],
];
tbody.innerHTML = rows.map(r=>{
const [label,,key,d]=r;
return `<tr><td>${label}</td><td id="c0-${key||label}"></td><td id="c1-${key||label}"></td><td id="d-${key||label}"></td></tr>`;
}).join('');
}
buildTable();
function getMetric(s,key){
switch(key){
case 'footHat': return s.metrics.footHat.area;
case 'footAll': return s.metrics.footAll.area;
case 'reach': return s.metrics.footAll.reach;
case 'length': return s.metrics.footAll.length;
case 'width': return s.metrics.footAll.width;
case 'shadeAll':return s.metrics.shade.all*100;
case 'shadeLow':return s.metrics.shade.low*100;
}
return null;
}
const rowKeys = [null,null,'footHat','footAll','reach','length','width','shadeAll','shadeLow'];
function updateTable(){
const A = subjects[0], B = subjects[1];
rowKeys.forEach((key,i)=>{
if(key===null) return;
const va = getMetric(A,key), vb = getMetric(B,key);
const d = rowKeys[i] && (key==='footHat'||key==='footAll') ? 4 : (key==='shadeAll'||key==='shadeLow' ? 0 : 2);
document.getElementById('c0-'+key).textContent = key==='footHat'||key==='footAll'
? va.toFixed(4)+' m²' : key==='shadeAll'||key==='shadeLow' ? va.toFixed(0)+' %' : va.toFixed(2)+' m';
document.getElementById('c1-'+key).textContent = key==='footHat'||key==='footAll'
? vb.toFixed(4)+' m²' : key==='shadeAll'||key==='shadeLow' ? vb.toFixed(0)+' %' : vb.toFixed(2)+' m';
document.getElementById('d-'+key).textContent = fmt(vb-va,d);
});
}
/* ------------------------------------------------------------------- chart */
const chart = document.getElementById('chart');
const ctx = chart.getContext('2d');
const history = new Map();
function drawChart(){
const dpr = Math.min(devicePixelRatio,2);
const W = chart.clientWidth*dpr, H = chart.clientHeight*dpr;
if(chart.width!==W||chart.height!==H){ chart.width=W; chart.height=H; }
ctx.clearRect(0,0,W,H);
const pad = { l:40*dpr, r:8*dpr, t:10*dpr, b:22*dpr };
const pts = [...history.entries()].map(([az,v])=>({az:+az,a:v.a,b:v.b})).sort((p,q)=>p.az-q.az);
let maxV = 0.02;
for(const p of pts) maxV = Math.max(maxV,p.a,p.b);
maxV *= 1.12;
const X = az => pad.l + (az/360)*(W-pad.l-pad.r);
const Y = v => (H-pad.b) - (v/maxV)*(H-pad.t-pad.b);
ctx.strokeStyle='rgba(255,255,255,.10)'; ctx.lineWidth=1;
ctx.font = `${10*dpr}px ui-sans-serif,system-ui`; ctx.fillStyle='rgba(255,255,255,.45)';
for(let k=0;k<=4;k++){
const v = maxV*k/4, y = Y(v);
ctx.beginPath(); ctx.moveTo(pad.l,y); ctx.lineTo(W-pad.r,y); ctx.stroke();
ctx.textAlign='right'; ctx.textBaseline='middle';
ctx.fillText(v.toFixed(3), pad.l-5*dpr, y);
}
ctx.textAlign='center'; ctx.textBaseline='top';
for(let az=0;az<=360;az+=90) ctx.fillText(az+'°', X(az), H-pad.b+4*dpr);
const line = (key,color)=>{
if(!pts.length) return;
ctx.strokeStyle=color; ctx.lineWidth=2*dpr; ctx.lineJoin='round';
ctx.beginPath();
pts.forEach((p,i)=>{ const x=X(p.az), y=Y(p[key]); i?ctx.lineTo(x,y):ctx.moveTo(x,y); });
ctx.stroke();
ctx.fillStyle=color;
for(const p of pts){ ctx.beginPath(); ctx.arc(X(p.az),Y(p[key]),2.4*dpr,0,6.3); ctx.fill(); }
};
line('a','#6ea8dc'); line('b','#e08a4e');
}
document.getElementById('legend-note')?.remove();
/* --------------------------------------------------------------- recompute */
let dirty = true, lastCalc = 0;
function recompute(){
scene.updateMatrixWorld(true);
for(const s of subjects){
const footHat = computeFootprint(s.hatTris, sunDir, s.x);
const footAll = computeFootprint(s.hatTris.concat(s.headTris), sunDir, s.x);
s.metrics = { footHat, footAll, shade:computeShade(s) };
paintOverlay(s, footAll);
}
updateTable();
history.set(Math.round(sun.az)%360, {
a:subjects[0].metrics.footHat.area,
b:subjects[1].metrics.footHat.area
});
drawChart();
}
/* ---------------------------------------------------------------- controls */
const azS = document.getElementById('az'), elS = document.getElementById('el');
azS.addEventListener('input', ()=>{ sun.az=+azS.value; updateSun(); });
elS.addEventListener('input', ()=>{ sun.el=+elS.value; history.clear(); drawChart(); updateSun(); });
let sweeping=false;
const sweepBtn = document.getElementById('sweep');
sweepBtn.addEventListener('click', ()=>{
sweeping=!sweeping;
sweepBtn.classList.toggle('on',sweeping);
sweepBtn.textContent = sweeping?'■ Stop sweep':'▶ Sweep sun';
});
document.getElementById('reset').addEventListener('click', ()=>{
cam.theta=0.92; cam.phi=1.02; cam.radius=3.15; cam.target.set(0,0.42,0); updateCamera();
});
document.getElementById('front').addEventListener('click', ()=>{ cam.theta=0; cam.phi=1.05; updateCamera(); });
document.getElementById('side').addEventListener('click', ()=>{ cam.theta=Math.PI/2; cam.phi=1.05; updateCamera(); });
document.getElementById('top').addEventListener('click', ()=>{ cam.theta=0.4; cam.phi=0.22; updateCamera(); });
window.addEventListener('keydown', e=>{
if(e.key==='ArrowLeft'){ sun.az=(sun.az-2+360)%360; azS.value=sun.az; updateSun(); }
if(e.key==='ArrowRight'){ sun.az=(sun.az+2)%360; azS.value=sun.az; updateSun(); }
if(e.key==='ArrowUp'){ sun.el=Math.min(85,sun.el+1); elS.value=sun.el; history.clear(); drawChart(); updateSun(); }
if(e.key==='ArrowDown'){ sun.el=Math.max(5,sun.el-1); elS.value=sun.el; history.clear(); drawChart(); updateSun(); }
});
window.addEventListener('resize', ()=>{
renderer.setSize(innerWidth, innerHeight);
camera.aspect = innerWidth/innerHeight;
camera.updateProjectionMatrix();
drawChart();
});
/* -------------------------------------------------------------------- loop */
const tagV = new THREE.Vector3();
function updateTags(){
for(const s of subjects){
tagV.set(s.x, 0.72, 0).project(camera);
s.tag.style.left = ((tagV.x*0.5+0.5)*innerWidth)+'px';
s.tag.style.top = ((-tagV.y*0.5+0.5)*innerHeight)+'px';
s.tag.style.display = tagV.z>1 ? 'none' : 'block';
}
}
let last = performance.now();
function animate(){
requestAnimationFrame(animate);
const now = performance.now(), dt = Math.min(0.05,(now-last)/1000); last=now;
if(sweeping){
sun.az = (sun.az + dt*14) % 360;
azS.value = sun.az;
updateSun();
}
if(dirty && now-lastCalc>90){ recompute(); dirty=false; lastCalc=now; }
renderer.render(scene,camera);
updateTags();
}
updateSun();
recompute();
drawChart();
animate();
</script>
</body>
</html>
```