Prompt specification
Build or customize the Three.js 3D scene "Half-Lit Moon Sphere and Observer Marker" 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: Half-Lit Moon Sphere and Observer Marker
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/half-lit-moon-sphere-and-observer-marker-x3789
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing lunar phases as seen from different positions. Model a moon sphere illuminated from one side with an observer viewpoint marker. Show the illuminated half in space and its visible fraction from the observer. Stylized solid forms.
Verify the behavior against the actual geometry and data in each relevant state. Use schematic labels for deliberately synthetic elements.
Technical checks: Define solar elongation from the observer and phase angle at the Moon. New Moon has about 0% illumination and 0° elongation. Full Moon has about 100% illumination and 180° elongation.
Return one complete HTML document. The file must run in a sandbox allowing inline scripts and the cdnjs Three.js r160 module. Construct procedural assets, use local event handlers and avoid remote assets, runtime network requests besides Three.js, pointer lock and native form submission. Keep the main requested geometry visible in the initial view.
Working Three.js Starter (half-lit-moon-sphere-and-observer-marker-x3789):
```html
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#07111f">
<link rel="icon" href="data:,">
<title>Fases Lunares — Modelo Geométrico</title>
<style>
:root {
--bg: #07111f;
--panel: #0c1727;
--panel-2: #111f32;
--line: rgba(164, 196, 225, 0.18);
--text: #edf4fb;
--muted: #9fb1c5;
--gold: #ffc56d;
--cyan: #66d9df;
--blue: #75a9ff;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
min-height: 100%;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
color-scheme: dark;
}
body { overflow: hidden; }
button, input { font: inherit; }
#app {
display: grid;
grid-template-columns: minmax(0, 1fr) 390px;
width: 100vw;
height: 100vh;
}
#main-wrap {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 57% 46%, rgba(41, 74, 108, 0.22), transparent 38%),
var(--bg);
}
#main-wrap canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#main-wrap canvas:active { cursor: grabbing; }
.scene-header {
position: absolute;
z-index: 4;
top: 26px;
left: 30px;
max-width: 460px;
pointer-events: none;
text-shadow: 0 2px 14px rgba(0, 0, 0, 0.8);
}
.eyebrow {
margin: 0 0 8px;
color: var(--gold);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.scene-header h1 {
margin: 0;
max-width: 430px;
font-size: clamp(25px, 3.2vw, 44px);
line-height: 1.02;
letter-spacing: -0.04em;
}
.scene-header p {
margin: 12px 0 0;
max-width: 390px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.scene-legend {
position: absolute;
z-index: 4;
left: 30px;
bottom: 25px;
display: flex;
flex-wrap: wrap;
gap: 9px 16px;
max-width: 500px;
padding: 12px 15px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(7, 17, 31, 0.76);
backdrop-filter: blur(12px);
color: #c9d7e6;
font-size: 11px;
pointer-events: none;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 7px;
white-space: nowrap;
}
.swatch {
width: 19px;
height: 3px;
border-radius: 3px;
background: var(--gold);
}
.swatch.cyan { background: var(--cyan); }
.swatch.dashed {
height: 0;
border-top: 2px dashed var(--cyan);
background: transparent;
}
.camera-help {
position: absolute;
z-index: 4;
right: 22px;
bottom: 26px;
color: rgba(197, 214, 231, 0.65);
font-size: 11px;
pointer-events: none;
}
#labels {
position: absolute;
z-index: 3;
inset: 0;
overflow: hidden;
pointer-events: none;
}
.world-label {
position: absolute;
top: 0;
left: 0;
padding: 5px 8px;
border: 1px solid rgba(159, 190, 216, 0.2);
border-radius: 6px;
background: rgba(5, 12, 23, 0.78);
color: #dbe8f5;
font-size: 9px;
font-weight: 750;
letter-spacing: 0.08em;
line-height: 1;
text-transform: uppercase;
white-space: nowrap;
transform: translate(-50%, -50%);
backdrop-filter: blur(7px);
}
.world-label.gold {
border-color: rgba(255, 197, 109, 0.38);
color: var(--gold);
}
.world-label.cyan {
border-color: rgba(102, 217, 223, 0.38);
color: var(--cyan);
}
.world-label.angle {
min-width: 27px;
padding: 4px 7px;
border: 0;
background: rgba(7, 17, 31, 0.9);
font-family: Georgia, serif;
font-size: 17px;
font-style: italic;
text-transform: none;
}
#panel {
position: relative;
z-index: 6;
height: 100vh;
overflow-y: auto;
padding: 25px 24px 30px;
border-left: 1px solid var(--line);
background:
linear-gradient(180deg, rgba(18, 33, 53, 0.96), rgba(8, 18, 31, 0.98)),
var(--panel);
box-shadow: -20px 0 50px rgba(0, 0, 0, 0.24);
}
.panel-kicker {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 8px;
}
.panel-kicker .eyebrow { margin: 0; }
#verify-badge {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 8px;
border: 1px solid rgba(102, 217, 223, 0.26);
border-radius: 999px;
background: rgba(102, 217, 223, 0.07);
color: #8be4e8;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.05em;
text-transform: uppercase;
white-space: nowrap;
}
#verify-badge::before {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 10px rgba(102, 217, 223, 0.85);
content: "";
}
#phase-name {
margin: 0;
font-size: 31px;
line-height: 1.05;
letter-spacing: -0.035em;
}
.phase-subtitle {
margin: 8px 0 16px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
#preview-stage {
position: relative;
width: 100%;
height: 232px;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 16px;
background: #081321;
box-shadow: inset 0 0 40px rgba(0, 0, 0, 0.28);
}
#preview-stage::before {
position: absolute;
z-index: 2;
inset: 10px;
border: 1px dashed rgba(151, 184, 211, 0.14);
border-radius: 50%;
pointer-events: none;
content: "";
}
#preview-stage canvas {
display: block;
width: 100%;
height: 100%;
}
.preview-caption {
position: absolute;
z-index: 3;
left: 12px;
bottom: 9px;
color: rgba(211, 226, 239, 0.68);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
pointer-events: none;
}
.metrics {
display: grid;
grid-template-columns: 1.25fr 1fr 1fr;
gap: 8px;
margin-top: 12px;
}
.metric {
min-width: 0;
padding: 12px 10px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(6, 15, 27, 0.48);
}
.metric.primary {
border-color: rgba(255, 197, 109, 0.32);
background: rgba(255, 197, 109, 0.065);
}
.metric-label {
display: block;
overflow: hidden;
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.075em;
line-height: 1.3;
text-overflow: ellipsis;
text-transform: uppercase;
white-space: nowrap;
}
.metric-value {
display: block;
margin-top: 6px;
color: var(--text);
font-size: 22px;
font-variant-numeric: tabular-nums;
font-weight: 760;
letter-spacing: -0.035em;
}
.metric.primary .metric-value { color: var(--gold); }
.section {
margin-top: 22px;
padding-top: 19px;
border-top: 1px solid var(--line);
}
.section-title {
margin: 0 0 12px;
color: #d9e5f0;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.presets {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 6px;
}
.preset {
min-width: 0;
padding: 10px 4px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(255, 255, 255, 0.025);
color: #aebfd0;
cursor: pointer;
font-size: 9px;
font-weight: 750;
transition: 140ms ease;
}
.preset:hover {
border-color: rgba(117, 169, 255, 0.55);
background: rgba(117, 169, 255, 0.09);
color: #eef5ff;
}
.preset.active {
border-color: rgba(255, 197, 109, 0.64);
background: rgba(255, 197, 109, 0.11);
color: var(--gold);
}
.slider-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-top: 18px;
margin-bottom: 8px;
}
.slider-head label {
color: #cbd8e5;
font-size: 11px;
font-weight: 700;
}
#position-value {
color: var(--gold);
font-size: 11px;
font-variant-numeric: tabular-nums;
font-weight: 800;
}
input[type="range"] {
width: 100%;
height: 20px;
margin: 0;
accent-color: var(--gold);
cursor: pointer;
}
.range-ends {
display: flex;
justify-content: space-between;
margin-top: 4px;
color: #73879b;
font-size: 9px;
}
.convention {
margin: 13px 0 0;
padding: 11px 12px;
border-left: 2px solid var(--cyan);
border-radius: 0 8px 8px 0;
background: rgba(102, 217, 223, 0.055);
color: #aebfd0;
font-size: 10px;
line-height: 1.55;
}
.convention strong { color: #d9e7f2; }
.table-wrap {
overflow: hidden;
border: 1px solid var(--line);
border-radius: 10px;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 10px;
font-variant-numeric: tabular-nums;
}
th, td {
padding: 8px 9px;
border-bottom: 1px solid rgba(164, 196, 225, 0.11);
text-align: right;
white-space: nowrap;
}
th {
background: rgba(255, 255, 255, 0.025);
color: #8296aa;
font-size: 8px;
letter-spacing: 0.07em;
text-transform: uppercase;
}
th:first-child, td:first-child { text-align: left; }
tr:last-child td { border-bottom: 0; }
td:first-child { color: #d5e1ec; font-weight: 680; }
td:nth-child(2) { color: var(--gold); font-weight: 760; }
.schema-note {
margin: 14px 0 0;
color: #778b9e;
font-size: 9px;
line-height: 1.55;
}
@media (max-width: 900px) {
body { overflow: auto; }
#app { display: block; height: auto; }
#main-wrap { height: 68vh; min-height: 510px; }
#panel {
height: auto;
min-height: 100vh;
border-top: 1px solid var(--line);
border-left: 0;
}
.scene-header { top: 20px; left: 20px; }
.scene-legend { left: 20px; bottom: 18px; }
.camera-help { display: none; }
}
@media (max-width: 480px) {
.scene-header h1 { max-width: 300px; font-size: 28px; }
.scene-header p { max-width: 300px; }
.scene-legend { right: 16px; gap: 7px 12px; }
#panel { padding: 22px 16px 28px; }
.metrics { grid-template-columns: 1fr 1fr; }
.metric.primary { grid-column: 1 / -1; }
.presets { gap: 4px; }
.preset { font-size: 8px; }
}
</style>
</head>
<body>
<div id="app">
<main id="main-wrap" aria-label="Cena tridimensional esquemática das fases lunares">
<div class="scene-header">
<p class="eyebrow">Mecânica lunar · modelo direcional</p>
<h1>Fases vistas de diferentes posições</h1>
<p>A esfera lunar permanece no centro. O hemisfério iluminado aponta para a direção solar, enquanto a câmera esquemática do observador se desloca pela órbita.</p>
</div>
<div id="labels" aria-hidden="true">
<div id="label-sun" class="world-label gold">Sol esquemático</div>
<div id="label-moon" class="world-label gold">Lua · hemisfério iluminado</div>
<div id="label-observer" class="world-label cyan">Observador sintético</div>
<div id="label-terminator" class="world-label">Terminador</div>
<div id="label-alpha" class="world-label angle gold">α</div>
<div id="label-epsilon" class="world-label angle cyan">ε</div>
</div>
<div class="scene-legend">
<span class="legend-item"><i class="swatch"></i> direção da luz solar</span>
<span class="legend-item"><i class="swatch cyan"></i> linha de visão</span>
<span class="legend-item"><i class="swatch dashed"></i> órbita esquemática</span>
</div>
<div class="camera-help">Arraste para orbitar · roda para aproximar</div>
</main>
<aside id="panel">
<div class="panel-kicker">
<p class="eyebrow">Leitura do observador</p>
<span id="verify-badge">5/5 geometria</span>
</div>
<h2 id="phase-name" aria-live="polite">Lua crescente</h2>
<p class="phase-subtitle" id="phase-subtitle">Fração iluminada calculada a partir da geometria vetorial usada na prévia.</p>
<div id="preview-stage" aria-label="Prévia do disco lunar visto pelo observador">
<div class="preview-caption">Disco visto pelo observador</div>
</div>
<div class="metrics">
<div class="metric primary">
<span class="metric-label">Fração iluminada</span>
<span class="metric-value" id="illumination-value">25%</span>
</div>
<div class="metric">
<span class="metric-label">Elongação ε</span>
<span class="metric-value" id="elongation-value">60°</span>
</div>
<div class="metric">
<span class="metric-label">Ângulo de fase α</span>
<span class="metric-value" id="phase-value">120°</span>
</div>
</div>
<section class="section">
<h3 class="section-title">Posição do observador</h3>
<div class="presets" role="group" aria-label="Estados lunares predefinidos">
<button class="preset" type="button" data-angle="180">Nova</button>
<button class="preset active" type="button" data-angle="120">Crescente</button>
<button class="preset" type="button" data-angle="90">Quarto</button>
<button class="preset" type="button" data-angle="60">Gibosa</button>
<button class="preset" type="button" data-angle="0">Cheia</button>
</div>
<div class="slider-head">
<label for="position">Ângulo Sol–Lua–Observador</label>
<output id="position-value" for="position">α = 120°</output>
</div>
<input id="position" type="range" min="0" max="180" step="1" value="120" aria-label="Ângulo de fase e posição do observador">
<div class="range-ends"><span>Cheia · α 0°</span><span>Nova · α 180°</span></div>
<p class="convention">
<strong>Convenção do modelo:</strong> ε é o ângulo Sol–Observador–Lua, visto do observador; α é o ângulo Sol–Lua–Observador, no centro da Lua. Assim, <strong>nova = ε 0°, α 180°</strong> e <strong>cheia = ε 180°, α 0°</strong>.
</p>
</section>
<section class="section">
<h3 class="section-title">Verificação dos estados</h3>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Estado</th>
<th>Ilum.</th>
<th>ε</th>
<th>α</th>
</tr>
</thead>
<tbody id="verification-body"></tbody>
</table>
</div>
<p class="schema-note">Esquema sintético: o disco solar representa apenas uma direção de luz; tamanhos, distância e órbita não estão em escala astronômica.</p>
</section>
</aside>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const mainWrap = document.getElementById("main-wrap");
const previewStage = document.getElementById("preview-stage");
const positionInput = document.getElementById("position");
const positionValue = document.getElementById("position-value");
const phaseName = document.getElementById("phase-name");
const phaseSubtitle = document.getElementById("phase-subtitle");
const illuminationValue = document.getElementById("illumination-value");
const elongationValue = document.getElementById("elongation-value");
const phaseValue = document.getElementById("phase-value");
const verifyBadge = document.getElementById("verify-badge");
const presetButtons = [...document.querySelectorAll(".preset")];
const DEG = Math.PI / 180;
const ORBIT_RADIUS = 4.65;
const SUN_DIRECTION = new THREE.Vector3(1, 0, 0);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.FogExp2(0x07111f, 0.017);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
const cameraTarget = new THREE.Vector3(0.85, 0.15, 0);
const cameraState = {
radius: 15.6,
theta: 0.55,
phi: 1.18,
dragging: false,
pointerX: 0,
pointerY: 0
};
const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance" });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
mainWrap.prepend(renderer.domElement);
const previewRenderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance" });
previewRenderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
previewRenderer.outputColorSpace = THREE.SRGBColorSpace;
previewRenderer.toneMapping = THREE.ACESFilmicToneMapping;
previewRenderer.toneMappingExposure = 1.05;
previewStage.prepend(previewRenderer.domElement);
scene.add(new THREE.AmbientLight(0x91a9c4, 1.15));
const solarLight = new THREE.DirectionalLight(0xffd99b, 2.5);
solarLight.position.copy(SUN_DIRECTION).multiplyScalar(12);
scene.add(solarLight);
scene.add(solarLight.target);
function createMoonMaterial() {
return new THREE.ShaderMaterial({
uniforms: {
uSunDirection: { value: SUN_DIRECTION.clone() }
},
vertexShader: `
varying vec3 vWorldNormal;
varying vec3 vWorldPosition;
void main() {
vWorldNormal = normalize(mat3(modelMatrix) * normal);
vec4 worldPosition = modelMatrix * vec4(position, 1.0);
vWorldPosition = worldPosition.xyz;
gl_Position = projectionMatrix * viewMatrix * worldPosition;
}
`,
fragmentShader: `
uniform vec3 uSunDirection;
varying vec3 vWorldNormal;
varying vec3 vWorldPosition;
float craterMark(vec3 n, vec3 center, float radius) {
float d = acos(clamp(dot(n, center), -1.0, 1.0));
float basin = 1.0 - smoothstep(radius * 0.18, radius * 0.78, d);
float rim = 1.0 - smoothstep(radius * 0.05, radius * 0.16, abs(d - radius * 0.78));
return basin * 0.12 + rim * 0.10;
}
void main() {
vec3 n = normalize(vWorldNormal);
vec3 sun = normalize(uSunDirection);
float ndl = dot(n, sun);
float illumination = smoothstep(-0.045, 0.075, ndl);
vec3 nightColor = vec3(0.055, 0.078, 0.115);
vec3 dayColor = vec3(0.88, 0.84, 0.75);
vec3 color = mix(nightColor, dayColor, illumination);
float craters = 0.0;
craters += craterMark(n, normalize(vec3(-0.42, 0.63, 0.64)), 0.19);
craters += craterMark(n, normalize(vec3(0.48, 0.46, 0.74)), 0.12);
craters += craterMark(n, normalize(vec3(0.61, -0.32, 0.72)), 0.09);
craters += craterMark(n, normalize(vec3(-0.71, 0.12, 0.69)), 0.08);
craters += craterMark(n, normalize(vec3(0.12, 0.77, -0.63)), 0.07);
color *= 1.0 - clamp(craters, 0.0, 0.28);
vec3 viewDirection = normalize(cameraPosition - vWorldPosition);
float rim = pow(1.0 - max(dot(n, viewDirection), 0.0), 3.0);
color += vec3(0.12, 0.18, 0.25) * rim;
gl_FragColor = vec4(color, 1.0);
#include <tonemapping_fragment>
#include <colorspace_fragment>
}
`
});
}
const moonGeometry = new THREE.SphereGeometry(1.25, 64, 48);
const moon = new THREE.Mesh(moonGeometry, createMoonMaterial());
scene.add(moon);
const previewScene = new THREE.Scene();
previewScene.background = new THREE.Color(0x081321);
const previewMoon = new THREE.Mesh(moonGeometry, createMoonMaterial());
previewScene.add(previewMoon);
const previewCamera = new THREE.OrthographicCamera(-1.7, 1.7, 1.7, -1.7, 0.1, 30);
previewCamera.up.set(0, 0, 1);
const litShellMaterial = new THREE.ShaderMaterial({
uniforms: {
uSunDirection: { value: SUN_DIRECTION.clone() }
},
transparent: true,
depthWrite: false,
side: THREE.FrontSide,
vertexShader: `
varying vec3 vWorldNormal;
varying vec3 vWorldPosition;
void main() {
vWorldNormal = normalize(mat3(modelMatrix) * normal);
vec4 worldPosition = modelMatrix * vec4(position, 1.0);
vWorldPosition = worldPosition.xyz;
gl_Position = projectionMatrix * viewMatrix * worldPosition;
}
`,
fragmentShader: `
uniform vec3 uSunDirection;
varying vec3 vWorldNormal;
varying vec3 vWorldPosition;
void main() {
vec3 n = normalize(vWorldNormal);
if (dot(n, normalize(uSunDirection)) < 0.0) discard;
vec3 viewDirection = normalize(cameraPosition - vWorldPosition);
float edge = pow(1.0 - max(dot(n, viewDirection), 0.0), 2.0);
gl_FragColor = vec4(1.0, 0.68, 0.25, 0.025 + edge * 0.075);
#include <tonemapping_fragment>
#include <colorspace_fragment>
}
`
});
const litShell = new THREE.Mesh(new THREE.SphereGeometry(1.285, 64, 48), litShellMaterial);
scene.add(litShell);
const terminatorPoints = [];
for (let i = 0; i < 160; i++) {
const a = (i / 160) * Math.PI * 2;
terminatorPoints.push(new THREE.Vector3(0, Math.cos(a) * 1.265, Math.sin(a) * 1.265));
}
const terminator = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints(terminatorPoints),
new THREE.LineBasicMaterial({ color: 0xffc56d, transparent: true, opacity: 0.78 })
);
scene.add(terminator);
const orbitPoints = [];
for (let i = 0; i <= 192; i++) {
const a = (i / 192) * Math.PI * 2;
orbitPoints.push(new THREE.Vector3(
Math.cos(a) * ORBIT_RADIUS,
Math.sin(a) * ORBIT_RADIUS,
0
));
}
const orbit = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(orbitPoints),
new THREE.LineDashedMaterial({
color: 0x66d9df,
dashSize: 0.17,
gapSize: 0.12,
transparent: true,
opacity: 0.42
})
);
orbit.computeLineDistances();
scene.add(orbit);
const sunGroup = new THREE.Group();
sunGroup.position.set(6.45, 0, 0);
scene.add(sunGroup);
const sunDisc = new THREE.Mesh(
new THREE.CircleGeometry(0.66, 64),
new THREE.MeshBasicMaterial({ color: 0xffbf62, side: THREE.DoubleSide })
);
sunDisc.rotation.y = Math.PI / 2;
sunGroup.add(sunDisc);
const sunHalo = new THREE.Mesh(
new THREE.CircleGeometry(0.92, 64),
new THREE.MeshBasicMaterial({
color: 0xffb84f,
transparent: true,
opacity: 0.11,
side: THREE.DoubleSide,
depthWrite: false
})
);
sunHalo.rotation.y = Math.PI / 2;
sunHalo.position.x = -0.008;
sunGroup.add(sunHalo);
const sunRing = new THREE.Mesh(
new THREE.TorusGeometry(0.79, 0.018, 8, 64),
new THREE.MeshBasicMaterial({ color: 0xffd48a })
);
sunRing.rotation.y = Math.PI / 2;
sunGroup.add(sunRing);
const arrowMaterial = new THREE.LineBasicMaterial({
color: 0xffc56d,
transparent: true,
opacity: 0.42
});
const arrowGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(-1, 0, 0)
]);
[
[-1.25, 0.7],
[-1.25, -0.7],
[0.7, 1.35],
[0.7, -1.35]
].forEach(([y, z]) => {
const arrow = new THREE.Line(arrowGeometry, arrowMaterial);
arrow.position.set(5.9, y, z);
scene.add(arrow);
});
const observerRoot = new THREE.Group();
const observerRig = new THREE.Group();
observerRoot.add(observerRig);
scene.add(observerRoot);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0x7ddde1,
roughness: 0.48,
metalness: 0.2
});
const darkMaterial = new THREE.MeshStandardMaterial({
color: 0x17364a,
roughness: 0.7,
metalness: 0.1
});
const cameraBody = new THREE.Mesh(new THREE.BoxGeometry(0.54, 0.31, 0.38), bodyMaterial);
observerRig.add(cameraBody);
const cameraTop = new THREE.Mesh(new THREE.BoxGeometry(0.23, 0.10, 0.25), darkMaterial);
cameraTop.position.y = 0.20;
observerRig.add(cameraTop);
const lens = new THREE.Mesh(new THREE.CylinderGeometry(0.13, 0.15, 0.28, 28), darkMaterial);
lens.rotation.x = Math.PI / 2;
lens.position.z = 0.30;
observerRig.add(lens);
const lensGlass = new THREE.Mesh(
new THREE.CircleGeometry(0.105, 28),
new THREE.MeshBasicMaterial({ color: 0x8feaf0, side: THREE.DoubleSide })
);
lensGlass.position.z = 0.448;
observerRig.add(lensGlass);
const observerBase = new THREE.Mesh(
new THREE.CylinderGeometry(0.39, 0.48, 0.10, 32),
darkMaterial
);
observerBase.rotation.x = Math.PI / 2;
observerBase.position.z = -0.33;
observerRoot.add(observerBase);
const observerHalo = new THREE.Mesh(
new THREE.TorusGeometry(0.55, 0.025, 8, 48),
new THREE.MeshBasicMaterial({ color: 0x66d9df })
);
observerHalo.position.z = -0.37;
observerRoot.add(observerHalo);
const beacon = new THREE.Mesh(
new THREE.SphereGeometry(0.07, 16, 12),
new THREE.MeshBasicMaterial({ color: 0xb7ffff })
);
beacon.position.set(0, 0.27, 0);
observerRig.add(beacon);
const sightGeometry = new THREE.BufferGeometry();
sightGeometry.setAttribute("position", new THREE.Float32BufferAttribute(new Float32Array(6), 3));
const sightLine = new THREE.Line(
sightGeometry,
new THREE.LineDashedMaterial({
color: 0x66d9df,
dashSize: 0.14,
gapSize: 0.09,
transparent: true,
opacity: 0.88
})
);
scene.add(sightLine);
const phaseArcGeometry = new THREE.BufferGeometry();
phaseArcGeometry.setAttribute("position", new THREE.Float32BufferAttribute(new Float32Array(65 * 3), 3));
const phaseArc = new THREE.Line(
phaseArcGeometry,
new THREE.LineBasicMaterial({ color: 0xffc56d, transparent: true, opacity: 0.9 })
);
scene.add(phaseArc);
const elongationArcGeometry = new THREE.BufferGeometry();
elongationArcGeometry.setAttribute("position", new THREE.Float32BufferAttribute(new Float32Array(65 * 3), 3));
const elongationArc = new THREE.Line(
elongationArcGeometry,
new THREE.LineBasicMaterial({ color: 0x66d9df, transparent: true, opacity: 0.9 })
);
scene.add(elongationArc);
let seed = 481516;
function random() {
seed = (seed * 1664525 + 1013904223) >>> 0;
return seed / 4294967296;
}
const starPositions = [];
for (let i = 0; i < 150; i++) {
const radius = 16 + random() * 14;
const theta = random() * Math.PI * 2;
const phi = Math.acos(2 * random() - 1);
starPositions.push(
radius * Math.sin(phi) * Math.cos(theta),
radius * Math.cos(phi),
radius * Math.sin(phi) * Math.sin(theta)
);
}
const starGeometry = new THREE.BufferGeometry();
starGeometry.setAttribute("position", new THREE.Float32BufferAttribute(starPositions, 3));
const stars = new THREE.Points(
starGeometry,
new THREE.PointsMaterial({
color: 0x8aa6c1,
size: 0.035,
transparent: true,
opacity: 0.48,
depthWrite: false
})
);
scene.add(stars);
function clamp(value, minimum, maximum) {
return Math.max(minimum, Math.min(maximum, value));
}
function directionForPhase(alpha) {
return new THREE.Vector3(
Math.cos(alpha * DEG),
Math.sin(alpha * DEG),
0
);
}
function computeGeometry(alpha) {
const observerDirection = directionForPhase(alpha);
const sunDotObserver = clamp(SUN_DIRECTION.dot(observerDirection), -1, 1);
const phaseAngle = Math.acos(sunDotObserver) / DEG;
const directionToMoon = observerDirection.clone().negate();
const observerSunDotMoon = clamp(SUN_DIRECTION.dot(directionToMoon), -1, 1);
const elongation = Math.acos(observerSunDotMoon) / DEG;
const illuminatedFraction = (1 + sunDotObserver) / 2;
return {
alpha,
phaseAngle,
elongation,
illuminatedFraction,
observerDirection
};
}
function phaseNameFor(alpha) {
if (alpha > 170) return "Lua nova";
if (alpha > 100) return "Lua crescente";
if (alpha > 80) return "Lua no primeiro quarto";
if (alpha > 20) return "Lua gibosa";
return "Lua cheia";
}
function updateArc(line, center, startAngle, endAngle, radius, z = 0) {
const positions = line.geometry.attributes.position;
const segments = positions.count - 1;
for (let i = 0; i <= segments; i++) {
const t = i / segments;
const angle = THREE.MathUtils.lerp(startAngle, endAngle, t);
positions.setXYZ(
i,
center.x + Math.cos(angle) * radius,
center.y + Math.sin(angle) * radius,
center.z + z
);
}
positions.needsUpdate = true;
line.geometry.computeBoundingSphere();
}
let currentState = computeGeometry(120);
function updateScene(alpha) {
currentState = computeGeometry(alpha);
const observerPosition = currentState.observerDirection.clone().multiplyScalar(ORBIT_RADIUS);
observerRoot.position.copy(observerPosition);
observerRig.up.set(0, 0, 1);
observerRig.lookAt(0, 0, 0);
const sightPositions = sightGeometry.attributes.position;
sightPositions.setXYZ(0, observerPosition.x, observerPosition.y, observerPosition.z);
sightPositions.setXYZ(1, 0, 0, 0);
sightPositions.needsUpdate = true;
sightGeometry.computeBoundingSphere();
sightLine.computeLineDistances();
updateArc(
phaseArc,
new THREE.Vector3(0, 0, 0),
0,
currentState.phaseAngle * DEG,
1.58,
0.12
);
updateArc(
elongationArc,
observerPosition,
-currentState.elongation * DEG,
0,
0.67,
0.38
);
previewCamera.position.copy(currentState.observerDirection).multiplyScalar(8);
previewCamera.up.set(0, 0, 1);
previewCamera.lookAt(0, 0, 0);
const percentage = currentState.illuminatedFraction * 100;
illuminationValue.textContent = `${percentage.toFixed(percentage < 10 && percentage > 0 ? 1 : 0)}%`;
elongationValue.textContent = `${currentState.elongation.toFixed(0)}°`;
phaseValue.textContent = `${currentState.phaseAngle.toFixed(0)}°`;
phaseName.textContent = phaseNameFor(currentState.alpha);
positionInput.value = String(Math.round(currentState.alpha));
positionValue.textContent = `α = ${currentState.phaseAngle.toFixed(0)}°`;
phaseSubtitle.textContent =
`A prévia usa a direção exata do observador. ` +
`${currentState.illuminatedFraction * 100 < 0.5 ? "Nenhuma área iluminada" : "A área iluminada é recortada pelo terminador"} no disco visível.`;
presetButtons.forEach(button => {
const buttonAngle = Number(button.dataset.angle);
button.classList.toggle("active", Math.abs(buttonAngle - currentState.alpha) < 0.5);
});
}
const verificationStates = [
{ name: "Nova", alpha: 180, fraction: 0, elongation: 0, phase: 180 },
{ name: "Crescente", alpha: 120, fraction: 25, elongation: 60, phase: 120 },
{ name: "Quarto", alpha: 90, fraction: 50, elongation: 90, phase: 90 },
{ name: "Gibosa", alpha: 60, fraction: 75, elongation: 120, phase: 60 },
{ name: "Cheia", alpha: 0, fraction: 100, elongation: 180, phase: 0 }
];
const verificationBody = document.getElementById("verification-body");
let verifiedCount = 0;
verificationStates.forEach(expected => {
const actual = computeGeometry(expected.alpha);
const correct =
Math.abs(actual.illuminatedFraction * 100 - expected.fraction) < 0.001 &&
Math.abs(actual.elongation - expected.elongation) < 0.001 &&
Math.abs(actual.phaseAngle - expected.phase) < 0.001;
if (correct) verifiedCount++;
const row = document.createElement("tr");
row.innerHTML = `
<td>${expected.name}</td>
<td>${(actual.illuminatedFraction * 100).toFixed(0)}%</td>
<td>${actual.elongation.toFixed(0)}°</td>
<td>${actual.phaseAngle.toFixed(0)}°</td>
`;
verificationBody.appendChild(row);
});
verifyBadge.textContent = `${verifiedCount}/5 geometria`;
positionInput.addEventListener("input", event => {
updateScene(Number(event.target.value));
});
presetButtons.forEach(button => {
button.addEventListener("click", () => {
updateScene(Number(button.dataset.angle));
});
});
function updateCamera() {
const { radius, theta, phi } = cameraState;
camera.position.set(
cameraTarget.x + radius * Math.sin(phi) * Math.sin(theta),
cameraTarget.y + radius * Math.cos(phi),
cameraTarget.z + radius * Math.sin(phi) * Math.cos(theta)
);
camera.lookAt(cameraTarget);
}
renderer.domElement.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
cameraState.dragging = true;
cameraState.pointerX = event.clientX;
cameraState.pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!cameraState.dragging) return;
const dx = event.clientX - cameraState.pointerX;
const dy = event.clientY - cameraState.pointerY;
cameraState.pointerX = event.clientX;
cameraState.pointerY = event.clientY;
cameraState.theta -= dx * 0.0055;
cameraState.phi = clamp(cameraState.phi + dy * 0.0045, 0.32, 2.78);
updateCamera();
});
function endDrag(event) {
cameraState.dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = clamp(cameraState.radius * Math.exp(event.deltaY * 0.001), 9.5, 24);
updateCamera();
}, { passive: false });
function resizeMain() {
const width = Math.max(1, mainWrap.clientWidth);
const height = Math.max(1, mainWrap.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
function resizePreview() {
const width = Math.max(1, previewStage.clientWidth);
const height = Math.max(1, previewStage.clientHeight);
previewRenderer.setSize(width, height, false);
const halfHeight = 1.65;
const halfWidth = halfHeight * (width / height);
previewCamera.left = -halfWidth;
previewCamera.right = halfWidth;
previewCamera.top = halfHeight;
previewCamera.bottom = -halfHeight;
previewCamera.updateProjectionMatrix();
}
new ResizeObserver(resizeMain).observe(mainWrap);
new ResizeObserver(resizePreview).observe(previewStage);
window.addEventListener("resize", () => {
resizeMain();
resizePreview();
});
const labels = {
sun: document.getElementById("label-sun"),
moon: document.getElementById("label-moon"),
observer: document.getElementById("label-observer"),
terminator: document.getElementById("label-terminator"),
alpha: document.getElementById("label-alpha"),
epsilon: document.getElementById("label-epsilon")
};
function placeLabel(element, worldPosition) {
const projected = worldPosition.clone().project(camera);
const visible =
projected.z > -1 && projected.z < 1 &&
projected.x > -1.12 && projected.x < 1.12 &&
projected.y > -1.12 && projected.y < 1.12;
element.style.display = visible ? "block" : "none";
if (!visible) return;
const rect = renderer.domElement.getBoundingClientRect();
const x = (projected.x * 0.5 + 0.5) * rect.width;
const y = (-projected.y * 0.5 + 0.5) * rect.height;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
}
function updateLabels() {
placeLabel(labels.sun, new THREE.Vector3(6.45, 1.18, 0));
placeLabel(labels.moon, new THREE.Vector3(0.25, -1.48, 0.2));
placeLabel(
labels.observer,
currentState.observerDirection.clone().multiplyScalar(ORBIT_RADIUS).add(new THREE.Vector3(0, 0, 0.78))
);
placeLabel(labels.terminator, new THREE.Vector3(0, 1.45, 0));
const alphaMid = currentState.phaseAngle * 0.5 * DEG;
placeLabel(
labels.alpha,
new THREE.Vector3(Math.cos(alphaMid) * 1.93, Math.sin(alphaMid) * 1.93, 0.12)
);
const epsilonMid = -currentState.elongation * 0.5 * DEG;
const observerPosition = currentState.observerDirection.clone().multiplyScalar(ORBIT_RADIUS);
placeLabel(
labels.epsilon,
observerPosition.clone().add(new THREE.Vector3(
Math.cos(epsilonMid) * 0.94,
Math.sin(epsilonMid) * 0.94,
0.38
))
);
}
updateCamera();
resizeMain();
resizePreview();
updateScene(120);
function animate() {
requestAnimationFrame(animate);
const pulse = 1 + Math.sin(performance.now() * 0.0022) * 0.035;
observerHalo.scale.setScalar(pulse);
sunHalo.material.opacity = 0.10 + Math.sin(performance.now() * 0.0018) * 0.015;
renderer.render(scene, camera);
previewRenderer.render(previewScene, previewCamera);
updateLabels();
}
animate();
</script>
</body>
</html>
```