Prompt specification
Build or customize the Three.js 3D scene "Observer Position Changes the Apparent Phase" 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: Observer Position Changes the Apparent Phase
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/observer-position-changes-the-apparent-phase-x3792
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts lunar phases as seen from different positions. Create a geometric experiment moving an observer around a fixed illuminated sphere. Compute the visible lit region and distinguish viewpoint effects from changes in the actual illumination. Low-poly.
Working Three.js Starter (observer-position-changes-the-apparent-phase-x3792):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Lunar Phases — a viewpoint experiment</title>
<style>
:root{
--bg:#05070e; --card:#0d1426; --line:#1e2a44;
--txt:#dbe6f8; --dim:#8ba0c2; --gold:#ffb547; --cyan:#63e6ff; --mag:#ff7ac6;
}
*{box-sizing:border-box}
html,body{height:100%;margin:0}
body{
background:radial-gradient(1100px 750px at 28% 18%, #101a30, #05070e 72%);
color:var(--txt); overflow:hidden;
font:13px/1.45 ui-sans-serif,system-ui,"Segoe UI",Roboto,sans-serif;
}
#app{display:flex;height:100%}
#stage{position:relative;flex:1;min-width:0}
#main{display:block;width:100%;height:100%}
#hint{position:absolute;left:14px;bottom:12px;color:var(--dim);font-size:11.5px}
#hint b{color:#d5e5ff;font-weight:600}
#panel{
width:376px;flex:0 0 376px;height:100%;overflow-y:auto;
background:rgba(7,11,22,.86);border-left:1px solid var(--line);padding:16px 16px 30px;
}
#panel::-webkit-scrollbar{width:8px}
#panel::-webkit-scrollbar-thumb{background:#1d2942;border-radius:4px}
h1{font-size:14px;margin:0 0 3px;letter-spacing:.08em;text-transform:uppercase}
h1 span{color:var(--gold)}
.sub{color:var(--dim);font-size:11.5px;margin-bottom:14px}
.card{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:12px;margin-bottom:12px}
.card h2{font-size:10.5px;text-transform:uppercase;letter-spacing:.14em;color:var(--dim);margin:0 0 9px}
.row{display:flex;justify-content:space-between;gap:10px;padding:3px 0;font-size:12.3px}
.row span{color:var(--dim)}
.row b{font-weight:600;font-variant-numeric:tabular-nums}
.row.sep{border-top:1px dashed #1c2740;margin-top:6px;padding-top:8px}
.fixed{color:var(--gold)}
.lbl{display:flex;justify-content:space-between;font-size:11px;color:var(--dim);margin:6px 0 3px}
.bar{height:11px;border-radius:6px;background:#16203a;overflow:hidden;border:1px solid #1e2a44}
.bar i{display:block;height:100%;width:0;background:linear-gradient(90deg,#ffd08a,#ff9f3d);transition:width .05s linear}
.bar.fixed i{background:linear-gradient(90deg,#c9a227,#ffb547)}
.note{color:var(--dim);font-size:11.3px;margin:10px 0 0;line-height:1.5}
.note em{color:#cfe0ff;font-style:normal;font-weight:600}
label{font-size:11.5px;color:var(--dim);display:block;margin:9px 0 3px}
label span{float:right;color:#cfe0ff;font-variant-numeric:tabular-nums}
input[type=range]{width:100%;-webkit-appearance:none;appearance:none;height:16px;background:transparent}
input[type=range]::-webkit-slider-runnable-track{height:4px;background:#1d2942;border-radius:3px}
input[type=range]::-moz-range-track{height:4px;background:#1d2942;border-radius:3px}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:13px;height:13px;margin-top:-4.5px;border-radius:50%;background:#63e6ff;border:2px solid #08101f}
input[type=range]::-moz-range-thumb{width:13px;height:13px;border-radius:50%;background:#63e6ff;border:2px solid #08101f}
button{font:inherit;color:var(--txt);background:#16203a;border:1px solid #26355a;border-radius:7px;padding:6px 11px;cursor:pointer}
button:hover{background:#1d2a4a}
.ctl{display:flex;gap:12px;align-items:center;justify-content:space-between;margin-bottom:2px}
.chk{display:inline;flex-direction:row;gap:6px;align-items:center;color:var(--dim);font-size:11.5px;margin:0}
.seg{display:flex;gap:6px}
.seg button{flex:1;font-size:11.5px;padding:6px 4px;color:var(--dim)}
.seg button.on{background:#1b3550;border-color:#3d6c92;color:#e9f3ff}
.inset{border:1px solid var(--line);border-radius:10px;overflow:hidden;margin-bottom:12px;background:#070c18}
.ihead{font-size:10.5px;letter-spacing:.1em;text-transform:uppercase;color:var(--dim);padding:7px 10px;border-bottom:1px solid var(--line)}
.dot{display:inline-block;width:8px;height:8px;border-radius:50%;margin-right:6px;vertical-align:1px}
.dot.cyan{background:var(--cyan);box-shadow:0 0 8px var(--cyan)}
.dot.gold{background:var(--gold);box-shadow:0 0 8px var(--gold)}
.inset canvas{display:block;width:100%}
#obs{height:214px} #sun{height:150px}
@media(max-width:900px){#app{flex-direction:column}#panel{width:100%;flex:0 0 auto;height:46%;border-left:none;border-top:1px solid var(--line)}#stage{height:54%}}
</style>
</head>
<body>
<div id="app">
<div id="stage">
<canvas id="main"></canvas>
<div id="hint"><b>drag</b> orbit camera · <b>wheel</b> zoom · <b>space</b> play/pause · <b>← →</b> step the observer</div>
</div>
<aside id="panel">
<h1>Lunar phases <span>— a viewpoint experiment</span></h1>
<div class="sub">The Sun is locked in space. Only the observer moves.</div>
<div class="card">
<h2>Readout</h2>
<div class="row"><span>Phase</span><b id="rPhase">—</b></div>
<div class="row"><span>Phase angle α</span><b id="rAlpha">—</b></div>
<div class="row"><span>Observer position θ</span><b id="rTheta">—</b></div>
<div class="row"><span>Orbit inclination</span><b id="rInc">—</b></div>
<div class="row sep"><span>Apparent lit fraction of visible disk</span><b id="rKdisk">—</b></div>
<div class="row"><span>Visible-surface lit area (mesh)</span><b id="rKmesh">—</b></div>
<div class="row"><span>Total illuminated hemisphere</span><b id="rKall" class="fixed">—</b></div>
</div>
<div class="card">
<h2>Viewpoint effect vs. actual illumination</h2>
<div class="lbl"><span>apparent — changes with the observer</span><span id="lblV">0%</span></div>
<div class="bar"><i id="barV"></i></div>
<div class="lbl"><span>actual illuminated — fixed</span><span>50%</span></div>
<div class="bar fixed"><i style="width:50%"></i></div>
<p class="note">The <em>gold terminator</em> and the Sun never move: exactly half of the sphere is lit at all times. The <em>cyan silhouette</em> follows the observer, so the crescent changes only because the <em>viewpoint</em> changes. Tilt the orbit and the crescent tilts too — but the fraction stays the same.</p>
</div>
<div class="card">
<h2>Observer</h2>
<div class="ctl">
<button id="play">Pause</button>
<label class="chk"><input type="checkbox" id="ptsOn" checked> computed region points</label>
</div>
<label>θ <span id="vTheta">145°</span></label><input type="range" id="sTheta" min="0" max="360" step="1" value="145">
<label>inclination <span id="vInc">0°</span></label><input type="range" id="sInc" min="-60" max="60" step="1" value="0">
<label>speed <span id="vSpeed">6°/s</span></label><input type="range" id="sSpeed" min="1" max="24" step="1" value="6">
</div>
<div class="card">
<h2>Shading of the globe</h2>
<div class="seg">
<button data-mode="obs" class="on">observer's view</button>
<button data-mode="illum">illumination only</button>
</div>
<p class="note">“Observer's view” brightens only what is <em>both lit and visible</em>. “Illumination only” shows the true lit hemisphere — a picture that never changes, whatever the observer does.</p>
</div>
<div class="inset">
<div class="ihead"><i class="dot cyan"></i>as seen by the observer — apparent phase</div>
<canvas id="obs"></canvas>
</div>
<div class="inset">
<div class="ihead"><i class="dot gold"></i>from the Sun — actual illumination (constant)</div>
<canvas id="sun"></canvas>
</div>
</aside>
</div>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js';
/* ───────────────────────── constants ───────────────────────── */
const DEG = Math.PI/180;
const MOON_R = 1.0;
const OBS_DIST = 3.45; // observer → globe distance
const SUN_DIR = new THREE.Vector3(1,0,0); // LOCKED illumination direction
const COSG = MOON_R/OBS_DIST; // silhouette latitude: cos γ
const clamp=(v,a,b)=>Math.max(a,Math.min(b,v));
const lerp=(a,b,t)=>a+(b-a)*t;
const fract=x=>x-Math.floor(x);
function hash(i,j,k){return fract(Math.sin(i*127.1+j*311.7+k*74.7)*43758.5453123);}
function noise3(x,y,z){
const ix=Math.floor(x),iy=Math.floor(y),iz=Math.floor(z);
const fx=x-ix,fy=y-iy,fz=z-iz;
const ux=fx*fx*(3-2*fx),uy=fy*fy*(3-2*fy),uz=fz*fz*(3-2*fz);
const c=(a,b,c2)=>hash(ix+a,iy+b,iz+c2);
return lerp(lerp(lerp(c(0,0,0),c(1,0,0),ux),lerp(c(0,1,0),c(1,1,0),ux),uy),
lerp(lerp(c(0,0,1),c(1,0,1),ux),lerp(c(0,1,1),c(1,1,1),ux),uy),uz);
}
/* ───────────────────────── the low-poly moon ───────────────────────── */
const craters=[];
for(let i=0;i<20;i++){
craters.push({
d:new THREE.Vector3(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1).normalize(),
ang:0.09+Math.random()*0.22,
dep:0.010+Math.random()*0.030
});
}
function buildMoon(){
const g=new THREE.IcosahedronGeometry(MOON_R,2); // flat-shaded, non-indexed
const pos=g.attributes.position, v=new THREE.Vector3();
for(let i=0;i<pos.count;i++){
v.fromBufferAttribute(pos,i);
const dir=v.clone().normalize();
let h=0.075*(noise3(dir.x*2.3+11,dir.y*2.3+3,dir.z*2.3+7)-0.5);
for(const c of craters){
const ang=Math.acos(clamp(dir.dot(c.d),-1,1));
if(ang<c.ang){
const t=ang/c.ang;
h-=c.dep*(1-t*t);
h+=c.dep*0.55*Math.exp(-Math.pow((t-0.9)/0.13,2));
}
}
v.copy(dir).multiplyScalar(MOON_R+h);
pos.setXYZ(i,v.x,v.y,v.z);
}
g.computeVertexNormals(); // per-face normals
const n=g.attributes.position.count;
g.setAttribute('color',new THREE.BufferAttribute(new Float32Array(n*3),3));
return g;
}
const moonGeo=buildMoon();
/* per-face data (shared by all three renderings) */
const faces=[];
{
const p=moonGeo.attributes.position, nn=moonGeo.attributes.normal;
for(let f=0;f<p.count/3;f++){
const a=new THREE.Vector3().fromBufferAttribute(p,f*3);
const b=new THREE.Vector3().fromBufferAttribute(p,f*3+1);
const c=new THREE.Vector3().fromBufferAttribute(p,f*3+2);
const nrm=new THREE.Vector3().fromBufferAttribute(nn,f*3);
const cen=a.clone().add(b).add(c).multiplyScalar(1/3).normalize();
const area=0.5*new THREE.Vector3().subVectors(b,a).cross(new THREE.Vector3().subVectors(c,a)).length();
const mare=noise3(cen.x*1.7+5.2,cen.y*1.7+1.1,cen.z*1.7+9.4);
const fine=noise3(cen.x*7.1+2,cen.y*7.1+2,cen.z*7.1+2);
const base=new THREE.Color(0xb9bec8);
if(mare>0.56) base.lerp(new THREE.Color(0x5c6370),Math.min(1,(mare-0.56)*2.4));
for(const cr of craters){
if(Math.acos(clamp(cen.dot(cr.d),-1,1))<cr.ang) base.multiplyScalar(0.82);
}
base.multiplyScalar(0.88+0.24*fine);
faces.push({n:nrm,cen,area,base});
}
}
const WARM=new THREE.Color(1.14,1.00,0.80);
const NIGHT=new THREE.Color(0.055,0.062,0.092);
/* ───────────────────────── main view ───────────────────────── */
const stage=document.getElementById('stage');
const renderer=new THREE.WebGLRenderer({canvas:document.getElementById('main'),antialias:true});
renderer.setPixelRatio(Math.min(devicePixelRatio,2));
renderer.setClearColor(0x05070e,0);
const scene=new THREE.Scene();
scene.fog=new THREE.FogExp2(0x05070e,0.012);
const camera=new THREE.PerspectiveCamera(45,1,0.05,300);
/* camera controls (hand-rolled) */
const cam={az:0.62,pol:1.16,rad:7.4,tgt:new THREE.Vector3(0,0,0)};
function updateCam(){
const s=Math.sin(cam.pol),c=Math.cos(cam.pol);
camera.position.set(cam.tgt.x+cam.rad*s*Math.sin(cam.az),
cam.tgt.y+cam.rad*c,
cam.tgt.z+cam.rad*s*Math.cos(cam.az));
camera.lookAt(cam.tgt);
}
const cv=document.getElementById('main');
let drag=false,lx=0,ly=0;
cv.addEventListener('pointerdown',e=>{drag=true;lx=e.clientX;ly=e.clientY;cv.setPointerCapture(e.pointerId);});
cv.addEventListener('pointermove',e=>{if(!drag)return;
cam.az-=(e.clientX-lx)*0.006; cam.pol=clamp(cam.pol-(e.clientY-ly)*0.006,0.12,Math.PI-0.12);
lx=e.clientX;ly=e.clientY;});
cv.addEventListener('pointerup',()=>drag=false);
cv.addEventListener('pointercancel',()=>drag=false);
cv.addEventListener('wheel',e=>{e.preventDefault();cam.rad=clamp(cam.rad*Math.exp(e.deltaY*0.0012),2.6,34);},{passive:false});
/* stars */
{
const N=900,pos=new Float32Array(N*3);
for(let i=0;i<N;i++){
const v=new THREE.Vector3(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1).normalize().multiplyScalar(60+Math.random()*70);
pos.set([v.x,v.y,v.z],i*3);
}
const g=new THREE.BufferGeometry();g.setAttribute('position',new THREE.BufferAttribute(pos,3));
scene.add(new THREE.Points(g,new THREE.PointsMaterial({color:0x9fb6d8,size:0.32,sizeAttenuation:true,transparent:true,opacity:0.65})));
}
/* labels */
function makeLabel(text,color='#e8f0ff',scale=0.52){
const m=document.createElement('canvas').getContext('2d');
m.font='600 44px ui-sans-serif, system-ui, sans-serif';
const w=Math.ceil(m.measureText(text).width)+34,h=64;
const c=document.createElement('canvas');c.width=w;c.height=h;
const ctx=c.getContext('2d');
ctx.font='600 44px ui-sans-serif, system-ui, sans-serif';
ctx.textAlign='center';ctx.textBaseline='middle';
ctx.fillStyle=color;ctx.fillText(text,w/2,h/2);
const tex=new THREE.CanvasTexture(c);tex.colorSpace=THREE.SRGBColorSpace;
const s=new THREE.Sprite(new THREE.SpriteMaterial({map:tex,transparent:true,depthTest:false,depthWrite:false}));
s.scale.set(w/h*scale,scale,1);s.renderOrder=20;
return s;
}
/* the globe */
const globe=new THREE.Mesh(moonGeo,new THREE.MeshBasicMaterial({vertexColors:true}));
scene.add(globe);
/* gold terminator (fixed!) + cyan silhouette (moves with the observer) */
function circleGeom(n){const g=new THREE.BufferGeometry();g.setAttribute('position',new THREE.BufferAttribute(new Float32Array(n*3),3));return g;}
const termGeo=circleGeom(160),termLine=new THREE.LineLoop(termGeo,new THREE.LineBasicMaterial({color:0xffb547}));
{
const p=termGeo.attributes.position;
for(let i=0;i<160;i++){const t=i/160*Math.PI*2;p.setXYZ(i,0,Math.cos(t)*1.006,Math.sin(t)*1.006);}
scene.add(termLine);
}
const silGeo=circleGeom(160),silLine=new THREE.LineLoop(silGeo,new THREE.LineBasicMaterial({color:0x63e6ff}));
scene.add(silLine);
/* orbit ring + phase labels */
const orbGeo=circleGeom(200),orbit=new THREE.LineLoop(orbGeo,new THREE.LineBasicMaterial({color:0x2f4a72,transparent:true,opacity:0.85}));
scene.add(orbit);
const orbitLabels=[];
[[0,'FULL'],[90,'QUARTER'],[180,'NEW'],[270,'QUARTER']].forEach(([deg,txt],i)=>{
const s=makeLabel(txt,i===0?'#ffd08a':i===2?'#c9d8f0':'#8ba0c2',0.42);
scene.add(s);orbitLabels.push({deg,sp:s});
});
/* sun + parallel rays */
const sunPos=SUN_DIR.clone().multiplyScalar(30);
const sun=new THREE.Mesh(new THREE.IcosahedronGeometry(1.7,1),new THREE.MeshBasicMaterial({color:0xffc061}));
sun.position.copy(sunPos);scene.add(sun);
const sunLbl=makeLabel('SUN — FIXED','#ffb547',0.85);
sunLbl.position.copy(sunPos).add(new THREE.Vector3(0,2.1,0));scene.add(sunLbl);
{
const rays=[];
[[0,0],[0.62,0],[-0.62,0],[0,0.62],[0,-0.62],[0.86,0.3]].forEach(([oy,oz])=>{
const off=new THREE.Vector3(0,oy,oz);
const hit=SUN_DIR.clone().multiplyScalar(-Math.sqrt(Math.max(0.04,1-Math.min(1,off.lengthSq())))).add(off);
const len=sunPos.distanceTo(hit);
const m=new THREE.Mesh(new THREE.CylinderGeometry(0.022,0.022,len,5),
new THREE.MeshBasicMaterial({color:0xffc061,transparent:true,opacity:0.5}));
m.position.copy(sunPos).add(hit).multiplyScalar(0.5);
m.quaternion.setFromUnitVectors(new THREE.Vector3(0,1,0),hit.clone().sub(sunPos).normalize());
scene.add(m);rays.push(m);
const cone=new THREE.Mesh(new THREE.ConeGeometry(0.07,0.24,6),new THREE.MeshBasicMaterial({color:0xffc061,transparent:true,opacity:0.75}));
cone.position.copy(hit);cone.quaternion.setFromUnitVectors(new THREE.Vector3(0,1,0),SUN_DIR.clone().negate());
scene.add(cone);
});
const line=new THREE.Line(new THREE.BufferGeometry().setFromPoints([sunPos,SUN_DIR.clone().multiplyScalar(-1.6)]),
new THREE.LineDashedMaterial({color:0xffb547,dashSize:0.5,gapSize:0.35,transparent:true,opacity:0.75}));
line.computeLineDistances();scene.add(line);
}
/* observer marker */
const obsGroup=new THREE.Group();scene.add(obsGroup);
const obsBody=new THREE.Mesh(new THREE.OctahedronGeometry(0.13,0),new THREE.MeshBasicMaterial({color:0x8fe9ff}));
obsGroup.add(obsBody);
const obsNose=new THREE.Mesh(new THREE.ConeGeometry(0.07,0.34,6),new THREE.MeshBasicMaterial({color:0x63e6ff}));
obsGroup.add(obsNose);
const obsLbl=makeLabel('OBSERVER','#63e6ff',0.5);scene.add(obsLbl);
/* field-of-view cone + tangent rays */
const coneH=OBS_DIST-MOON_R*COSG;
const coneGeo=new THREE.CylinderGeometry(0.03,MOON_R,coneH,18,1,true);
coneGeo.translate(0,-coneH/2,0);
const viewCone=new THREE.Mesh(coneGeo,new THREE.MeshBasicMaterial({color:0x63e6ff,transparent:true,opacity:0.07,side:THREE.DoubleSide,depthWrite:false}));
scene.add(viewCone);
const tangGeo=new THREE.BufferGeometry();
tangGeo.setAttribute('position',new THREE.BufferAttribute(new Float32Array(4*3),3));
const tangents=new THREE.LineSegments(tangGeo,new THREE.LineBasicMaterial({color:0x63e6ff,transparent:true,opacity:0.55}));
scene.add(tangents);
/* computed "lit ∩ visible" sample points */
function makePoints(size,color){
const g=new THREE.BufferGeometry();
g.setAttribute('position',new THREE.BufferAttribute(new Float32Array(moonGeo.attributes.position.count*3),3));
const p=new THREE.Points(g,new THREE.PointsMaterial({color,size,sizeAttenuation:false,transparent:true,opacity:0.95}));
p.frustumCulled=false;return p;
}
const ptsMain=makePoints(3.2,0xffffff);
const ptsObs=makePoints(2.2,0xffffff);
scene.add(ptsMain);
/* ───────────────────────── inset views ───────────────────────── */
function makeView(canvas,ortho=false){
const r=new THREE.WebGLRenderer({canvas,antialias:true});
r.setPixelRatio(Math.min(devicePixelRatio,2));
r.setClearColor(0x05070e,1);
const s=new THREE.Scene();
const c=ortho?new THREE.OrthographicCamera(-1.3,1.3,1.25,-1.25,0.01,200)
:new THREE.PerspectiveCamera(38,1,0.02,200);
function resize(){
const w=canvas.clientWidth||300,h=canvas.clientHeight||200;
r.setSize(w,h,false);
if(c.isPerspectiveCamera){c.aspect=w/h;}else{c.left=-1.25*w/h;c.right=1.25*w/h;}
c.updateProjectionMatrix();
}
new ResizeObserver(resize).observe(canvas);resize();
return {r,s,c,resize};
}
const obsView=makeView(document.getElementById('obs'));
const sunView=makeView(document.getElementById('sun'),true);
const obsGeo=moonGeo.clone(), sunGeo=moonGeo.clone();
obsView.s.add(new THREE.Mesh(obsGeo,new THREE.MeshBasicMaterial({vertexColors:true})));
sunView.s.add(new THREE.Mesh(sunGeo,new THREE.MeshBasicMaterial({vertexColors:true})));
/* limb + terminator inside the observer's view */
const limbGeo=circleGeom(160),limbLine=new THREE.LineLoop(limbGeo,new THREE.LineBasicMaterial({color:0x63e6ff,transparent:true,opacity:0.9}));
obsView.s.add(limbLine);
const termLine2=new THREE.LineLoop(circleGeom(160),new THREE.LineBasicMaterial({color:0xffb547,transparent:true,opacity:0.85}));
{const p=termLine2.geometry.attributes.position;
for(let i=0;i<160;i++){const t=i/160*Math.PI*2;p.setXYZ(i,0,Math.cos(t)*1.008,Math.sin(t)*1.008);}}
obsView.s.add(termLine2);
obsView.s.add(ptsObs);
/* observer-azimuth marker on the terminator rim, seen from the Sun */
const azMark=new THREE.Mesh(new THREE.ConeGeometry(0.075,0.22,6),new THREE.MeshBasicMaterial({color:0x63e6ff}));
sunView.s.add(azMark);
const azRing=new THREE.LineLoop(circleGeom(160),new THREE.LineBasicMaterial({color:0xffb547,transparent:true,opacity:0.8}));
{const p=azRing.geometry.attributes.position;
for(let i=0;i<160;i++){const t=i/160*Math.PI*2;p.setXYZ(i,Math.cos(t)*1.01,Math.sin(t)*1.01,0);}}
sunView.s.add(azRing);
/* ───────────────────────── state ───────────────────────── */
let theta=145*DEG, incl=0, speed=6, playing=true, mode='obs', showPts=true;
let thetaPrev=theta;
const toObs=new THREE.Vector3();
const e1=new THREE.Vector3(),e2=new THREE.Vector3(),tmp=new THREE.Vector3();
function observerBasis(){
const inc=incl*DEG;
toObs.set(Math.cos(theta),Math.sin(theta)*Math.sin(inc),Math.sin(theta)*Math.cos(inc)).normalize();
// orthonormal basis ⟂ toObs
tmp.set(0,1,0);
if(Math.abs(toObs.dot(tmp))>0.95) tmp.set(1,0,0);
e1.crossVectors(toObs,tmp).normalize();
e2.crossVectors(toObs,e1).normalize();
}
/* ───────────────────────── shading ───────────────────────── */
function paint(geo,m){
const arr=geo.attributes.color.array;
const st={vis:0,litVis:0,lit:0,tot:0};
for(let f=0;f<faces.length;f++){
const fd=faces[f];
const lam=Math.max(0,fd.n.dot(SUN_DIR));
const lit=lam>0.001;
const vis=fd.n.dot(toObs)>COSG;
let c;
if(m==='illum'){
c=lit? new THREE.Color(fd.base.r*(0.34+0.78*lam)*WARM.r,
fd.base.g*(0.34+0.78*lam)*WARM.g,
fd.base.b*(0.34+0.78*lam)*WARM.b)
: new THREE.Color(fd.base.r*0.09+0.012,fd.base.g*0.09+0.014,fd.base.b*0.10+0.022);
}else{
if(vis){
c=lit? new THREE.Color(fd.base.r*(0.40+0.75*lam)*WARM.r,
fd.base.g*(0.40+0.75*lam)*WARM.g,
fd.base.b*(0.40+0.75*lam)*WARM.b)
: new THREE.Color(fd.base.r*0.05+0.010,fd.base.g*0.05+0.012,fd.base.b*0.06+0.020);
}else{
const k=lit?0.26:0.07;
c=new THREE.Color(fd.base.r*k+0.012,fd.base.g*k+0.014,fd.base.b*k+0.022);
}
}
for(let v=0;v<3;v++){
const o=(f*3+v)*3;
arr[o]=c.r;arr[o+1]=c.g;arr[o+2]=c.b;
}
st.tot+=fd.area; if(lit)st.lit+=fd.area;
if(vis){st.vis+=fd.area; if(lit)st.litVis+=fd.area;}
}
geo.attributes.color.needsUpdate=true;
return st;
}
/* sampled lit ∩ visible points */
function updatePoints(points){
const p=points.geometry.attributes.position;
const src=moonGeo.attributes.position;
for(let i=0;i<src.count;i++){
const x=src.getX(i),y=src.getY(i),z=src.getZ(i);
const n=tmp.set(x,y,z).normalize();
const ok=(n.dot(SUN_DIR)>0)&&(n.dot(toObs)>COSG);
if(ok)p.setXYZ(i,x*1.01,y*1.01,z*1.01);
else p.setXYZ(i,0,-999,0);
}
p.needsUpdate=true;
}
/* ───────────────────────── UI ───────────────────────── */
const $=id=>document.getElementById(id);
const sTheta=$('sTheta'),sInc=$('sInc'),sSpeed=$('sSpeed');
sTheta.addEventListener('input',()=>{theta=+sTheta.value*DEG;playing=false;syncPlay();});
sInc.addEventListener('input',()=>{incl=+sInc.value;});
sSpeed.addEventListener('input',()=>{speed=+sSpeed.value;});
$('ptsOn').addEventListener('change',e=>showPts=e.target.checked);
$('play').addEventListener('click',()=>{playing=!playing;syncPlay();});
function syncPlay(){$('play').textContent=playing?'Pause':'Play';}
document.querySelectorAll('.seg button').forEach(b=>b.addEventListener('click',()=>{
document.querySelectorAll('.seg button').forEach(x=>x.classList.remove('on'));
b.classList.add('on');mode=b.dataset.mode;
}));
window.addEventListener('keydown',e=>{
if(e.code==='Space'){e.preventDefault();playing=!playing;syncPlay();}
if(e.code==='ArrowRight'){theta=(theta+2*DEG)%(2*Math.PI);playing=false;syncPlay();}
if(e.code==='ArrowLeft'){theta=(theta-2*DEG+2*Math.PI)%(2*Math.PI);playing=false;syncPlay();}
});
/* ───────────────────────── loop ───────────────────────── */
let last=performance.now();
function frame(now){
requestAnimationFrame(frame);
const dt=Math.min(0.05,(now-last)/1000);last=now;
if(playing){theta=(theta-speed*DEG*dt+4*Math.PI)%(2*Math.PI);} // waxing direction
observerBasis();
/* phase maths */
const cosA=clamp(toObs.dot(SUN_DIR),-1,1);
const alpha=Math.acos(cosA);
const k=(1+cosA)/2; // apparent lit fraction of the visible disk
let d=theta-thetaPrev; if(d>Math.PI)d-=2*Math.PI; if(d<-Math.PI)d+=2*Math.PI;
const dk=-0.5*Math.sin(theta)*d;
const waxing=dk>=0;
thetaPrev=theta;
/* paint the three renderings */
const st=paint(obsGeo,'obs');
paint(sunGeo,'illum');
paint(moonGeo,mode);
/* update geometry: orbit, silhouette, observer */
{
const op=orbGeo.attributes.position;
for(let i=0;i<200;i++){
const t=i/200*Math.PI*2,si=Math.sin(incl*DEG),ci=Math.cos(incl*DEG);
op.setXYZ(i,OBS_DIST*Math.cos(t),OBS_DIST*Math.sin(t)*si,OBS_DIST*Math.sin(t)*ci);
}
op.needsUpdate=true;orbGeo.computeBoundingSphere();
orbitLabels.forEach(L=>{
const t=L.deg*DEG,si=Math.sin(incl*DEG),ci=Math.cos(incl*DEG);
const r=OBS_DIST+0.85;
L.sp.position.set(r*Math.cos(t),r*Math.sin(t)*si+0.30,r*Math.sin(t)*ci);
});
const sp=silGeo.attributes.position;
for(let i=0;i<160;i++){
const t=i/160*Math.PI*2;
const v=tmp.copy(toObs).multiplyScalar(COSG)
.addScaledVector(e1,Math.sin(Math.acos(COSG))*Math.cos(t))
.addScaledVector(e2,Math.sin(Math.acos(COSG))*Math.sin(t));
sp.setXYZ(i,v.x*1.008,v.y*1.008,v.z*1.008);
}
sp.needsUpdate=true;silGeo.computeBoundingSphere();
}
const O=toObs.clone().multiplyScalar(OBS_DIST);
obsGroup.position.copy(O);
obsNose.position.copy(O).addScaledVector(toObs,-0.22);
obsNose.quaternion.setFromUnitVectors(new THREE.Vector3(0,1,0),toObs.clone().negate());
obsBody.position.copy(O);
obsLbl.position.copy(O).add(new THREE.Vector3(0,0.42,0));
viewCone.position.copy(O);
viewCone.quaternion.setFromUnitVectors(new THREE.Vector3(0,1,0),toObs);
{
const tg=Math.acos(COSG),T1=tmp.copy(toObs).multiplyScalar(COSG).addScaledVector(e1,Math.sin(tg)).clone();
const T2=toObs.clone().multiplyScalar(COSG).addScaledVector(e2,Math.sin(tg));
const arr=tangGeo.attributes.position.array;
arr.set([O.x,O.y,O.z,T1.x,T1.y,T1.z, O.x,O.y,O.z,T2.x,T2.y,T2.z]);
tangGeo.attributes.position.needsUpdate=true;
}
/* inset cameras */
obsView.c.position.copy(O);obsView.c.lookAt(0,0,0);
sunView.c.position.copy(SUN_DIR).multiplyScalar(12);sunView.c.lookAt(0,0,0);
{
const lp=limbGeo.attributes.position,tg=Math.acos(COSG);
for(let i=0;i<160;i++){
const t=i/160*Math.PI*2;
const v=new THREE.Vector3().copy(toObs).multiplyScalar(COSG)
.addScaledVector(e1,Math.sin(tg)*Math.cos(t)).addScaledVector(e2,Math.sin(tg)*Math.sin(t));
lp.setXYZ(i,v.x*1.004,v.y*1.004,v.z*1.004);
}
lp.needsUpdate=true;limbGeo.computeBoundingSphere();
const q=toObs.clone().addScaledVector(SUN_DIR,-toObs.dot(SUN_DIR));
if(q.lengthSq()>1e-6){q.normalize();azMark.position.copy(q).multiplyScalar(1.03);
azMark.quaternion.setFromUnitVectors(new THREE.Vector3(0,1,0),q);}
}
/* sampled points */
if(showPts){updatePoints(ptsMain);updatePoints(ptsObs);ptsMain.visible=true;ptsObs.visible=true;}
else{ptsMain.visible=false;ptsObs.visible=false;}
/* readout */
const deg=(alpha/DEG);
let name=k>0.975?'Full':k>0.62?'Gibbous':k>0.38?'Quarter':k>0.03?'Crescent':'New';
$('rPhase').textContent=name+' ('+(waxing?'waxing':'waning')+')';
$('rAlpha').textContent=deg.toFixed(1)+'°';
$('rTheta').textContent=((theta/DEG)%360).toFixed(0)+'°';
$('rInc').textContent=(incl>0?'+':'')+incl.toFixed(0)+'°';
$('rKdisk').textContent=(k*100).toFixed(1)+'%';
$('rKmesh').textContent=(st.vis>0?(st.litVis/st.vis*100).toFixed(1):'0.0')+'%';
$('rKall').textContent=(st.lit/st.tot*100).toFixed(1)+'% (fixed)';
$('lblV').textContent=(k*100).toFixed(1)+'%';
$('barV').style.width=(k*100)+'%';
$('vTheta').textContent=((theta/DEG)%360).toFixed(0)+'°';
$('vInc').textContent=(incl>0?'+':'')+incl.toFixed(0)+'°';
$('vSpeed').textContent=speed.toFixed(0)+'°/s';
if(document.activeElement!==sTheta)sTheta.value=((theta/DEG)%360).toFixed(0);
if(document.activeElement!==sInc)sInc.value=incl;
/* render */
updateCam();
renderer.render(scene,camera);
obsView.r.render(obsView.s,obsView.c);
sunView.r.render(sunView.s,sunView.c);
}
function resizeMain(){
const w=stage.clientWidth,h=stage.clientHeight;
renderer.setSize(w,h,false);camera.aspect=w/h;camera.updateProjectionMatrix();
}
new ResizeObserver(resizeMain).observe(stage);resizeMain();
requestAnimationFrame(frame);
</script>
</body>
</html>
```