Prompt specification
Build or customize the Three.js 3D scene "Moon Phase Orbit Viewer" 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: Moon Phase Orbit Viewer
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/moon-phase-orbit-viewer-x3790
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts a voxel Moon-phase viewer. Place a planet and orbiting moon beneath a fixed distant-light direction, with one marked observer position on the planet. A top-down view shows the orbital geometry while a second viewing panel shows the moon from that observer. Keep half of the moon illuminated in space and derive the apparent lit portion from the viewing angle. Move through the orbital positions with a slider or slow animation. Avoid using the planet's shadow to create ordinary phases; this diagram is about illuminated-sphere viewing geometry, with sizes and distances deliberately enlarged for clarity.
Working Three.js Starter (moon-phase-orbit-viewer-x3790):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Moon-Phase Viewer</title>
<style>
:root {
color-scheme: dark;
--bg: #05070c;
--panel: #0b1019;
--panel-border: rgba(151, 181, 222, 0.18);
--text: #edf4ff;
--muted: #8e9bb0;
--cyan: #72e6ff;
--gold: #ffd27a;
--warm: #fff4dc;
--dark-moon: #111722;
}
* {
box-sizing: border-box;
}
html,
body {
min-height: 100%;
}
body {
margin: 0;
overflow-x: hidden;
background:
radial-gradient(circle at 18% 0%, rgba(44, 82, 133, 0.18), transparent 32rem),
radial-gradient(circle at 92% 20%, rgba(80, 49, 121, 0.12), transparent 28rem),
var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
.shell {
width: min(1500px, 100%);
margin: 0 auto;
padding: 24px clamp(14px, 2vw, 30px) 34px;
}
header {
display: flex;
align-items: end;
justify-content: space-between;
gap: 24px;
margin-bottom: 18px;
}
.eyebrow {
margin: 0 0 7px;
color: var(--cyan);
font: 700 0.72rem/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(1.65rem, 3vw, 2.65rem);
line-height: 1;
letter-spacing: -0.045em;
}
header p {
max-width: 590px;
margin: 0;
color: var(--muted);
font-size: 0.92rem;
line-height: 1.55;
}
.viewers {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16px;
}
.panel {
position: relative;
height: clamp(430px, 61vh, 650px);
min-width: 0;
overflow: hidden;
border: 1px solid var(--panel-border);
border-radius: 18px;
background: rgba(8, 12, 20, 0.82);
box-shadow:
0 24px 70px rgba(0, 0, 0, 0.28),
inset 0 1px 0 rgba(255, 255, 255, 0.025);
}
.canvas-wrap {
position: absolute;
inset: 0;
}
.canvas-wrap canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
}
#orbitCanvas {
background:
radial-gradient(circle at 50% 46%, rgba(31, 57, 91, 0.25), transparent 48%),
linear-gradient(rgba(92, 137, 190, 0.025) 1px, transparent 1px),
linear-gradient(90deg, rgba(92, 137, 190, 0.025) 1px, transparent 1px);
background-size: auto, 28px 28px, 28px 28px;
}
#observerCanvas {
background:
radial-gradient(circle at 50% 46%, rgba(23, 31, 48, 0.22), transparent 48%),
#030509;
}
.panel-heading {
position: absolute;
z-index: 4;
top: 0;
left: 0;
right: 0;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 16px 18px;
pointer-events: none;
background: linear-gradient(rgba(5, 7, 12, 0.88), transparent);
}
.panel-heading h2 {
margin: 0;
font-size: 0.92rem;
letter-spacing: 0.01em;
}
.panel-heading span {
color: var(--muted);
font: 650 0.67rem/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.scene-label {
position: absolute;
z-index: 3;
pointer-events: none;
transform: translate(-50%, -50%);
padding: 4px 7px;
border: 1px solid rgba(144, 218, 255, 0.22);
border-radius: 5px;
background: rgba(4, 10, 17, 0.75);
color: #ccefff;
font: 700 0.63rem/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.09em;
white-space: nowrap;
box-shadow: 0 5px 18px rgba(0, 0, 0, 0.3);
}
#observerLabel {
color: var(--cyan);
border-color: rgba(114, 230, 255, 0.4);
}
#alphaLabel {
color: var(--gold);
border-color: rgba(255, 210, 122, 0.35);
}
.light-note {
position: absolute;
z-index: 3;
top: 67px;
right: 18px;
display: flex;
align-items: center;
gap: 8px;
pointer-events: none;
color: var(--gold);
font: 700 0.63rem/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
}
.light-arrow {
font-size: 1.25rem;
line-height: 0;
}
.geometry-legend {
position: absolute;
z-index: 3;
left: 16px;
bottom: 15px;
display: grid;
gap: 7px;
pointer-events: none;
color: #aebbd0;
font: 600 0.65rem/1.25 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.legend-row {
display: flex;
align-items: center;
gap: 8px;
}
.swatch {
width: 22px;
height: 2px;
background: var(--cyan);
box-shadow: 0 0 8px rgba(114, 230, 255, 0.65);
}
.swatch.gold {
background: var(--gold);
box-shadow: 0 0 8px rgba(255, 210, 122, 0.55);
}
.phase-card {
position: absolute;
z-index: 4;
left: 16px;
bottom: 16px;
width: min(300px, calc(100% - 32px));
padding: 14px 15px 13px;
border: 1px solid rgba(137, 177, 225, 0.2);
border-radius: 12px;
background: rgba(7, 11, 18, 0.82);
backdrop-filter: blur(12px);
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.28);
pointer-events: none;
}
.phase-top {
display: flex;
align-items: end;
justify-content: space-between;
gap: 12px;
}
.phase-label {
color: var(--muted);
font: 700 0.62rem/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.12em;
text-transform: uppercase;
}
#phaseName {
margin-top: 5px;
font-size: 1.05rem;
font-weight: 680;
}
#fractionText {
color: var(--warm);
font: 700 1.7rem/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: -0.06em;
}
.phase-bar {
height: 7px;
margin: 13px 0 10px;
overflow: hidden;
border-radius: 99px;
background:
linear-gradient(90deg, rgba(255, 255, 255, 0.08), rgba(255, 255, 255, 0.14)),
var(--dark-moon);
}
#phaseFill {
height: 100%;
width: 50%;
border-radius: inherit;
background: linear-gradient(90deg, #d4d9df, #fff5dc);
box-shadow: 0 0 12px rgba(255, 244, 220, 0.35);
transition: width 80ms linear;
}
.phase-readout {
display: flex;
justify-content: space-between;
gap: 10px;
color: #93a2b9;
font: 600 0.63rem/1.4 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.phase-readout strong {
color: #dce8f8;
font-weight: 700;
}
.observer-footnote {
position: absolute;
z-index: 3;
right: 16px;
bottom: 16px;
max-width: 235px;
color: #7f8ca1;
text-align: right;
font: 600 0.61rem/1.45 ui-monospace, SFMono-Regular, Menlo, monospace;
pointer-events: none;
}
.controls {
display: grid;
grid-template-columns: auto minmax(220px, 1fr) auto;
align-items: center;
gap: 18px;
margin-top: 16px;
padding: 15px 17px;
border: 1px solid var(--panel-border);
border-radius: 14px;
background: rgba(10, 15, 24, 0.78);
}
.transport {
display: flex;
gap: 8px;
}
button,
select {
border: 1px solid rgba(150, 184, 226, 0.22);
border-radius: 8px;
background: #101827;
color: var(--text);
font: 700 0.73rem/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
button {
min-width: 86px;
padding: 10px 12px;
cursor: pointer;
}
button:hover,
select:hover {
border-color: rgba(114, 230, 255, 0.45);
background: #142033;
}
button.primary {
border-color: rgba(114, 230, 255, 0.42);
color: var(--cyan);
}
select {
padding: 9px 10px;
}
.slider-wrap {
display: grid;
grid-template-columns: auto minmax(120px, 1fr) 56px;
align-items: center;
gap: 12px;
}
.slider-wrap label {
color: var(--muted);
font: 700 0.68rem/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#angleValue {
color: var(--cyan);
text-align: right;
font: 700 0.78rem/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
input[type="range"] {
width: 100%;
accent-color: var(--cyan);
cursor: pointer;
}
.control-readout {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 14px;
color: var(--muted);
font: 650 0.66rem/1.4 ui-monospace, SFMono-Regular, Menlo, monospace;
text-align: right;
}
.control-readout strong {
display: block;
color: #dce8f8;
font-size: 0.78rem;
}
footer {
display: flex;
justify-content: space-between;
gap: 20px;
margin-top: 13px;
color: #68758a;
font-size: 0.73rem;
line-height: 1.5;
}
footer code {
color: #9cacbf;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
@media (max-width: 920px) {
header {
align-items: start;
flex-direction: column;
gap: 12px;
}
.viewers {
grid-template-columns: 1fr;
}
.panel {
height: 500px;
}
.controls {
grid-template-columns: 1fr;
}
.control-readout {
justify-content: flex-start;
text-align: left;
}
}
@media (max-width: 520px) {
.shell {
padding-inline: 10px;
}
.panel {
height: 440px;
border-radius: 14px;
}
.slider-wrap {
grid-template-columns: 1fr 54px;
}
.slider-wrap label {
grid-column: 1 / -1;
}
.observer-footnote {
display: none;
}
footer {
flex-direction: column;
gap: 5px;
}
}
</style>
</head>
<body>
<div class="shell">
<header>
<div>
<p class="eyebrow">Illuminated-sphere geometry</p>
<h1>Voxel Moon-Phase Viewer</h1>
</div>
<p>
The moon is always half illuminated in space. Its apparent phase comes
from the angle between the fixed light direction and the observer's
line of sight—not from a planetary shadow.
</p>
</header>
<main class="viewers">
<section class="panel" aria-label="Orbital geometry">
<div id="orbitCanvas" class="canvas-wrap"></div>
<div class="panel-heading">
<h2>Top-down orbital geometry</h2>
<span>fixed distant light</span>
</div>
<div class="light-note">
LIGHT FROM +X
<span class="light-arrow">←</span>
</div>
<div id="moonLabel" class="scene-label">MOON</div>
<div id="observerLabel" class="scene-label">OBSERVER O</div>
<div id="alphaLabel" class="scene-label">α</div>
<div class="geometry-legend">
<div class="legend-row">
<span class="swatch"></span>
<span>observer sight line</span>
</div>
<div class="legend-row">
<span class="swatch gold"></span>
<span>phase angle α = angle(L, V)</span>
</div>
<div class="legend-row">
<span style="color:#ffd27a">←</span>
<span>parallel incoming rays</span>
</div>
</div>
</section>
<section class="panel" aria-label="Moon as seen by the observer">
<div id="observerCanvas" class="canvas-wrap"></div>
<div class="panel-heading">
<h2>Apparent moon from observer O</h2>
<span>parallel sight projection</span>
</div>
<div class="phase-card">
<div class="phase-top">
<div>
<div class="phase-label">Illuminated disk</div>
<div id="phaseName">—</div>
</div>
<div id="fractionText">50.0%</div>
</div>
<div class="phase-bar">
<div id="phaseFill"></div>
</div>
<div class="phase-readout">
<span>α <strong id="alphaText">90.0°</strong></span>
<span>L·V <strong id="dotText">0.000</strong></span>
<span>f <strong id="formulaText">(1 + L·V) / 2</strong></span>
</div>
</div>
<div class="observer-footnote">
The projection direction is O → moon.<br />
Horizon and planetary occultation are omitted for clarity.
</div>
</section>
</main>
<section class="controls" aria-label="Orbit controls">
<div class="transport">
<button id="playButton" class="primary" type="button">Pause</button>
<button id="resetButton" type="button">Reset</button>
</div>
<div class="slider-wrap">
<label for="angleSlider">Orbit angle θ</label>
<input
id="angleSlider"
type="range"
min="0"
max="359.9"
step="0.1"
value="300"
>
<output id="angleValue">300.0°</output>
</div>
<div class="control-readout">
<div>
angular speed
<strong id="speedText">8° / second</strong>
</div>
<select id="speedSelect" aria-label="Animation speed">
<option value="4">4° / s</option>
<option value="8" selected>8° / s</option>
<option value="16">16° / s</option>
<option value="30">30° / s</option>
</select>
</div>
</section>
<footer>
<span>
L = direction from moon toward the distant source ·
V = direction from moon toward observer ·
illuminated fraction <code>f = (1 + L·V) / 2</code>
</span>
<span>Planet, moon size, and orbital distance are deliberately enlarged.</span>
</footer>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Shared diagram constants
// -------------------------------------------------------------------------
const PLANET_RADIUS = 2.35;
const ORBIT_RADIUS = 6.4;
const MOON_VOXEL_RADIUS = 0.92;
// Direction from the moon toward the distant light source.
// Incoming rays therefore travel in the -X direction.
const LIGHT_DIRECTION = new THREE.Vector3(1, 0, 0);
// The observer is a fixed point on the planet's +X surface.
const OBSERVER_POSITION = new THREE.Vector3(PLANET_RADIUS, 0, 0);
const orbitHost = document.getElementById("orbitCanvas");
const observerHost = document.getElementById("observerCanvas");
const moonLabel = document.getElementById("moonLabel");
const observerLabel = document.getElementById("observerLabel");
const alphaLabel = document.getElementById("alphaLabel");
const angleSlider = document.getElementById("angleSlider");
const angleValue = document.getElementById("angleValue");
const playButton = document.getElementById("playButton");
const resetButton = document.getElementById("resetButton");
const speedSelect = document.getElementById("speedSelect");
const phaseName = document.getElementById("phaseName");
const fractionText = document.getElementById("fractionText");
const phaseFill = document.getElementById("phaseFill");
const alphaText = document.getElementById("alphaText");
const dotText = document.getElementById("dotText");
const reducedMotion = window.matchMedia(
"(prefers-reduced-motion: reduce)"
).matches;
let orbitAngle = THREE.MathUtils.degToRad(300);
let angularSpeed = 8;
let playing = !reducedMotion;
// -------------------------------------------------------------------------
// Renderers
// -------------------------------------------------------------------------
function createRenderer(host) {
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setClearColor(0x000000, 0);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
// Deliberately disabled: phases are not produced by cast shadows.
renderer.shadowMap.enabled = false;
renderer.domElement.setAttribute("aria-hidden", "true");
host.appendChild(renderer.domElement);
return renderer;
}
const orbitRenderer = createRenderer(orbitHost);
const observerRenderer = createRenderer(observerHost);
// -------------------------------------------------------------------------
// Top-down orbital scene
// -------------------------------------------------------------------------
const orbitScene = new THREE.Scene();
const orbitCamera = new THREE.PerspectiveCamera(44, 1, 0.1, 80);
orbitCamera.position.set(0, 16.5, 0.001);
orbitCamera.up.set(0, 0, -1);
orbitCamera.lookAt(0, 0, 0);
orbitScene.add(new THREE.AmbientLight(0x7894b9, 0.65));
const sunlight = new THREE.DirectionalLight(0xfff0d4, 3.4);
sunlight.position.set(20, 0, 0);
sunlight.target.position.set(0, 0, 0);
sunlight.castShadow = false;
orbitScene.add(sunlight, sunlight.target);
const planet = new THREE.Mesh(
new THREE.SphereGeometry(PLANET_RADIUS, 64, 36),
new THREE.MeshStandardMaterial({
color: 0x315774,
roughness: 0.82,
metalness: 0.04
})
);
planet.castShadow = false;
planet.receiveShadow = false;
orbitScene.add(planet);
const atmosphere = new THREE.Mesh(
new THREE.SphereGeometry(PLANET_RADIUS * 1.045, 48, 28),
new THREE.MeshBasicMaterial({
color: 0x6ac7ff,
transparent: true,
opacity: 0.09,
side: THREE.BackSide,
depthWrite: false
})
);
orbitScene.add(atmosphere);
const observerMarker = new THREE.Mesh(
new THREE.SphereGeometry(0.115, 18, 12),
new THREE.MeshBasicMaterial({ color: 0x72e6ff })
);
observerMarker.position.copy(OBSERVER_POSITION);
observerMarker.position.x += 0.08;
orbitScene.add(observerMarker);
const observerRing = new THREE.Mesh(
new THREE.TorusGeometry(0.24, 0.032, 10, 40),
new THREE.MeshBasicMaterial({ color: 0x72e6ff })
);
observerRing.rotation.y = Math.PI / 2;
observerRing.position.copy(OBSERVER_POSITION);
observerRing.position.x += 0.025;
orbitScene.add(observerRing);
function makeCircle(radius, color, opacity, dashed = false) {
const points = [];
const segments = 192;
for (let i = 0; i < segments; i++) {
const a = (i / segments) * Math.PI * 2;
points.push(
new THREE.Vector3(
Math.cos(a) * radius,
0,
Math.sin(a) * radius
)
);
}
const material = dashed
? new THREE.LineDashedMaterial({
color,
transparent: true,
opacity,
dashSize: 0.15,
gapSize: 0.11
})
: new THREE.LineBasicMaterial({
color,
transparent: true,
opacity
});
const line = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints(points),
material
);
if (dashed) line.computeLineDistances();
return line;
}
orbitScene.add(makeCircle(ORBIT_RADIUS, 0x72e6ff, 0.42, true));
orbitScene.add(makeCircle(PLANET_RADIUS * 1.55, 0x6985a7, 0.16, true));
orbitScene.add(makeCircle(PLANET_RADIUS * 2.25, 0x6985a7, 0.11, true));
const tickPositions = [];
for (let i = 0; i < 24; i++) {
const a = (i / 24) * Math.PI * 2;
const r0 = ORBIT_RADIUS - (i % 6 === 0 ? 0.26 : 0.13);
const r1 = ORBIT_RADIUS + 0.08;
tickPositions.push(
Math.cos(a) * r0, 0, Math.sin(a) * r0,
Math.cos(a) * r1, 0, Math.sin(a) * r1
);
}
const tickGeometry = new THREE.BufferGeometry();
tickGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(tickPositions, 3)
);
orbitScene.add(
new THREE.LineSegments(
tickGeometry,
new THREE.LineBasicMaterial({
color: 0x7896b9,
transparent: true,
opacity: 0.35
})
)
);
// Parallel arrows show light traveling from +X toward -X.
for (const z of [-5.15, 0, 5.15]) {
const arrow = new THREE.ArrowHelper(
new THREE.Vector3(-1, 0, 0),
new THREE.Vector3(8.25, 0, z),
2.55,
0xffd27a,
0.43,
0.23
);
orbitScene.add(arrow);
}
// -------------------------------------------------------------------------
// Voxel moon
//
// Every cube face is tested against the fixed world-space light direction.
// There is no shadow map and no light tied to the observer.
// -------------------------------------------------------------------------
const voxelVertexShader = `
varying vec3 vWorldNormal;
varying vec3 vVoxelCenter;
varying vec3 vWorldPosition;
void main() {
mat4 localInstance = mat4(1.0);
#ifdef USE_INSTANCING
localInstance = instanceMatrix;
#endif
vec4 localPosition = localInstance * vec4(position, 1.0);
vec4 worldPosition = modelMatrix * localPosition;
vWorldPosition = worldPosition.xyz;
vVoxelCenter = localInstance[3].xyz;
mat3 normalTransform =
mat3(modelMatrix) * mat3(localInstance);
vWorldNormal = normalize(normalTransform * normal);
gl_Position = projectionMatrix * viewMatrix * worldPosition;
}
`;
const voxelFragmentShader = `
uniform vec3 uLightDirection;
uniform vec3 uViewDirection;
varying vec3 vWorldNormal;
varying vec3 vVoxelCenter;
varying vec3 vWorldPosition;
float hash31(vec3 p) {
p = fract(p * 0.1031);
p += dot(p, p.yzx + 33.33);
return fract((p.x + p.y) * p.z);
}
void main() {
vec3 normal = normalize(vWorldNormal);
vec3 lightDir = normalize(uLightDirection);
vec3 viewDir = normalize(uViewDirection);
float nDotL = dot(normal, lightDir);
// A hard terminator separates an exactly half-lit sphere.
float illuminated = smoothstep(-0.025, 0.025, nDotL);
float voxelNoise =
0.78 +
0.22 * hash31(floor(vVoxelCenter * 8.0));
float maria = 0.0;
maria += 1.0 - smoothstep(
0.18, 0.34,
length(vVoxelCenter - vec3(-0.24, 0.16, 0.13))
);
maria += 1.0 - smoothstep(
0.15, 0.29,
length(vVoxelCenter - vec3(0.19, -0.20, 0.27))
);
maria += 0.7 * (1.0 - smoothstep(
0.12, 0.26,
length(vVoxelCenter - vec3(0.08, 0.30, -0.25))
));
vec3 unlitColor = vec3(0.018, 0.024, 0.037);
vec3 litColor = vec3(0.80, 0.82, 0.85);
vec3 color = mix(unlitColor, litColor, illuminated);
color *= voxelNoise;
color = mix(color, color * 0.62, clamp(maria, 0.0, 1.0) * 0.7);
float facing = max(dot(normal, viewDir), 0.0);
float limb = mix(0.50, 1.0, pow(facing, 0.28));
color *= limb;
float rim = pow(1.0 - facing, 3.0) * illuminated;
color += rim * vec3(0.08, 0.11, 0.15);
gl_FragColor = vec4(color, 1.0);
}
`;
function createVoxelMoon(uniforms) {
const step = 0.145;
const radius = MOON_VOXEL_RADIUS;
const gridLimit = Math.ceil(radius / step);
const cells = [];
for (let x = -gridLimit; x <= gridLimit; x++) {
for (let y = -gridLimit; y <= gridLimit; y++) {
for (let z = -gridLimit; z <= gridLimit; z++) {
const px = x * step;
const py = y * step;
const pz = z * step;
if (
px * px + py * py + pz * pz <=
radius * radius
) {
cells.push([px, py, pz]);
}
}
}
}
const geometry = new THREE.BoxGeometry(
step * 0.94,
step * 0.94,
step * 0.94
);
const material = new THREE.ShaderMaterial({
uniforms,
vertexShader: voxelVertexShader,
fragmentShader: voxelFragmentShader
});
const mesh = new THREE.InstancedMesh(
geometry,
material,
cells.length
);
const dummy = new THREE.Object3D();
cells.forEach((position, index) => {
dummy.position.set(position[0], position[1], position[2]);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
});
mesh.instanceMatrix.needsUpdate = true;
mesh.castShadow = false;
mesh.receiveShadow = false;
mesh.frustumCulled = false;
return mesh;
}
const topMoonUniforms = {
uLightDirection: { value: LIGHT_DIRECTION.clone() },
uViewDirection: { value: new THREE.Vector3(0, 1, 0) }
};
const topMoon = createVoxelMoon(topMoonUniforms);
orbitScene.add(topMoon);
// -------------------------------------------------------------------------
// Observer sight line and phase-angle arc
// -------------------------------------------------------------------------
const sightLineGeometry = new THREE.BufferGeometry();
sightLineGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(new Float32Array(6), 3)
);
const sightLine = new THREE.Line(
sightLineGeometry,
new THREE.LineDashedMaterial({
color: 0x72e6ff,
transparent: true,
opacity: 0.78,
dashSize: 0.16,
gapSize: 0.10
})
);
orbitScene.add(sightLine);
const ARC_SEGMENTS = 40;
const arcPositions = new Float32Array((ARC_SEGMENTS + 1) * 3);
const arcGeometry = new THREE.BufferGeometry();
arcGeometry.setAttribute(
"position",
new THREE.BufferAttribute(arcPositions, 3)
);
const phaseArc = new THREE.Line(
arcGeometry,
new THREE.LineBasicMaterial({
color: 0xffd27a,
transparent: true,
opacity: 0.95
})
);
orbitScene.add(phaseArc);
// -------------------------------------------------------------------------
// Observer scene
// -------------------------------------------------------------------------
const observerScene = new THREE.Scene();
// An orthographic camera gives an exact projected disk for the smooth
// sphere. Its viewing direction is still the observer-to-moon direction.
const observerCamera = new THREE.OrthographicCamera(-1.5, 1.5, 1.5, -1.5, 0.1, 60);
observerCamera.position.copy(OBSERVER_POSITION);
observerCamera.up.set(0, 1, 0);
const observerMoonUniforms = {
uLightDirection: { value: LIGHT_DIRECTION.clone() },
uViewDirection: { value: new THREE.Vector3(1, 0, 0) }
};
const observerMoon = createVoxelMoon(observerMoonUniforms);
observerScene.add(observerMoon);
// A sparse star plane is positioned behind the moon along the sight axis.
function seededRandom(seed) {
let state = seed >>> 0;
return () => {
state = (1664525 * state + 1013904223) >>> 0;
return state / 4294967296;
};
}
const random = seededRandom(93017);
const starPositions = new Float32Array(1100 * 3);
for (let i = 0; i < 1100; i++) {
starPositions[i * 3] = (random() - 0.5) * 24;
starPositions[i * 3 + 1] = (random() - 0.5) * 24;
starPositions[i * 3 + 2] = 0;
}
const starGeometry = new THREE.BufferGeometry();
starGeometry.setAttribute(
"position",
new THREE.BufferAttribute(starPositions, 3)
);
const stars = new THREE.Points(
starGeometry,
new THREE.PointsMaterial({
color: 0xb9d2f4,
size: 1.25,
sizeAttenuation: false,
transparent: true,
opacity: 0.72,
depthWrite: false
})
);
stars.frustumCulled = false;
observerScene.add(stars);
// -------------------------------------------------------------------------
// Resizing
// -------------------------------------------------------------------------
function resize() {
const orbitWidth = Math.max(1, orbitHost.clientWidth);
const orbitHeight = Math.max(1, orbitHost.clientHeight);
orbitRenderer.setSize(orbitWidth, orbitHeight, false);
orbitCamera.aspect = orbitWidth / orbitHeight;
orbitCamera.updateProjectionMatrix();
const observerWidth = Math.max(1, observerHost.clientWidth);
const observerHeight = Math.max(1, observerHost.clientHeight);
const aspect = observerWidth / observerHeight;
// Keep the entire voxel moon visible at all aspect ratios.
const halfHeight = Math.max(1.43, 1.34 / aspect);
const halfWidth = halfHeight * aspect;
observerCamera.left = -halfWidth;
observerCamera.right = halfWidth;
observerCamera.top = halfHeight;
observerCamera.bottom = -halfHeight;
observerCamera.updateProjectionMatrix();
observerRenderer.setSize(observerWidth, observerHeight, false);
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(orbitHost);
resizeObserver.observe(observerHost);
resize();
// -------------------------------------------------------------------------
// Projection helpers
// -------------------------------------------------------------------------
function placeLabel(element, worldPosition, camera, host, offsetX = 0, offsetY = 0) {
const projected = worldPosition.clone().project(camera);
const x = (projected.x * 0.5 + 0.5) * host.clientWidth + offsetX;
const y = (-projected.y * 0.5 + 0.5) * host.clientHeight + offsetY;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
element.style.display = projected.z < 1 ? "block" : "none";
}
// -------------------------------------------------------------------------
// Phase naming and readouts
// -------------------------------------------------------------------------
function getPhaseName(fraction, angle) {
if (fraction <= 0.015) return "new moon";
if (fraction >= 0.985) return "full moon";
if (Math.abs(fraction - 0.5) <= 0.018) {
return Math.sin(angle) >= 0 ? "first quarter" : "last quarter";
}
const trend = Math.sin(angle) >= 0 ? "waxing" : "waning";
const shape = fraction < 0.5 ? "crescent" : "gibbous";
return `${trend} ${shape}`;
}
// -------------------------------------------------------------------------
// Scene update
// -------------------------------------------------------------------------
const moonPosition = new THREE.Vector3();
const directionToObserver = new THREE.Vector3();
const cameraToMoon = new THREE.Vector3();
const arcMidpoint = new THREE.Vector3();
function updateScene() {
const cosAngle = Math.cos(orbitAngle);
const sinAngle = Math.sin(orbitAngle);
moonPosition.set(
ORBIT_RADIUS * cosAngle,
0,
ORBIT_RADIUS * sinAngle
);
topMoon.position.copy(moonPosition);
observerMoon.position.copy(moonPosition);
// V points from the moon toward the observer.
directionToObserver
.copy(OBSERVER_POSITION)
.sub(moonPosition)
.normalize();
observerCamera.position.copy(OBSERVER_POSITION);
observerCamera.lookAt(moonPosition);
observerCamera.updateMatrixWorld();
observerMoonUniforms.uViewDirection.value.copy(directionToObserver);
// Top-down view vector, used only for limb shading.
topMoonUniforms.uViewDirection.value
.copy(orbitCamera.position)
.sub(moonPosition)
.normalize();
// Exact phase angle for a distant directional light.
const lightDotView = THREE.MathUtils.clamp(
LIGHT_DIRECTION.dot(directionToObserver),
-1,
1
);
const phaseAngle = Math.acos(lightDotView);
const illuminatedFraction = (1 + lightDotView) / 2;
phaseName.textContent = getPhaseName(
illuminatedFraction,
orbitAngle
);
fractionText.textContent = `${(illuminatedFraction * 100).toFixed(1)}%`;
phaseFill.style.width = `${illuminatedFraction * 100}%`;
alphaText.textContent = `${THREE.MathUtils.radToDeg(phaseAngle).toFixed(1)}°`;
dotText.textContent = lightDotView.toFixed(3);
const degrees = THREE.MathUtils.radToDeg(orbitAngle);
angleValue.textContent = `${degrees.toFixed(1)}°`;
if (document.activeElement !== angleSlider) {
angleSlider.value = degrees.toFixed(1);
}
// Observer sight line.
const sightPositions = sightLineGeometry.attributes.position.array;
sightPositions[0] = OBSERVER_POSITION.x;
sightPositions[1] = OBSERVER_POSITION.y;
sightPositions[2] = OBSERVER_POSITION.z;
sightPositions[3] = moonPosition.x;
sightPositions[4] = moonPosition.y;
sightPositions[5] = moonPosition.z;
sightLineGeometry.attributes.position.needsUpdate = true;
sightLine.computeLineDistances();
sightLine.geometry.computeBoundingSphere();
// The phase angle is measured at the moon between:
// L = +X (toward the source) and V (toward the observer).
const signedAngle = Math.atan2(
directionToObserver.z,
directionToObserver.x
);
const arcRadius = 0.48;
for (let i = 0; i <= ARC_SEGMENTS; i++) {
const t = i / ARC_SEGMENTS;
const a = signedAngle * t;
const x = moonPosition.x + Math.cos(a) * arcRadius;
const y = moonPosition.y;
const z = moonPosition.z + Math.sin(a) * arcRadius;
arcPositions[i * 3] = x;
arcPositions[i * 3 + 1] = y;
arcPositions[i * 3 + 2] = z;
if (i === Math.floor(ARC_SEGMENTS / 2)) {
arcMidpoint.set(x, y, z);
}
}
arcGeometry.attributes.position.needsUpdate = true;
phaseArc.geometry.computeBoundingSphere();
// Place the star plane behind the moon in the observer's view.
cameraToMoon
.copy(moonPosition)
.sub(OBSERVER_POSITION)
.normalize();
stars.position
.copy(moonPosition)
.addScaledVector(cameraToMoon, 18);
stars.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 0, 1),
cameraToMoon
);
}
// -------------------------------------------------------------------------
// Controls
// -------------------------------------------------------------------------
function updatePlayButton() {
playButton.textContent = playing ? "Pause" : "Play";
}
playButton.addEventListener("click", () => {
playing = !playing;
updatePlayButton();
});
resetButton.addEventListener("click", () => {
orbitAngle = THREE.MathUtils.degToRad(300);
playing = !reducedMotion;
updatePlayButton();
});
angleSlider.addEventListener("input", () => {
orbitAngle = THREE.MathUtils.degToRad(Number(angleSlider.value));
playing = false;
updatePlayButton();
});
speedSelect.addEventListener("change", () => {
angularSpeed = Number(speedSelect.value);
document.getElementById("speedText").textContent =
`${angularSpeed}° / second`;
});
updatePlayButton();
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (playing) {
orbitAngle = (
orbitAngle +
THREE.MathUtils.degToRad(angularSpeed) * delta
) % (Math.PI * 2);
}
updateScene();
orbitRenderer.render(orbitScene, orbitCamera);
observerRenderer.render(observerScene, observerCamera);
placeLabel(
moonLabel,
moonPosition,
orbitCamera,
orbitHost,
0,
-26
);
placeLabel(
observerLabel,
OBSERVER_POSITION,
orbitCamera,
orbitHost,
8,
19
);
placeLabel(
alphaLabel,
arcMidpoint,
orbitCamera,
orbitHost,
0,
-17
);
}
animate();
</script>
</body>
</html>
```