Prompt specification
Build or customize the Three.js 3D scene "Mixed-row light access demonstration" 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: Mixed-row light access demonstration
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/mixed-row-light-access-demonstration-x1078
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts intercropping. Arrange two fictional crop forms in separate and mixed rows; move a sun marker to compare resulting light patches under identical geometry and explicitly stated assumptions. Voxel style.
Working Three.js Starter (mixed-row-light-access-demonstration-x1078):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Intercropping Light Lab</title>
<style>
:root {
--bg: #07141c;
--panel: rgba(9, 25, 34, 0.88);
--line: rgba(157, 214, 221, 0.18);
--text: #e9f4ef;
--muted: #9db4b8;
--helix: #42d9b4;
--ember: #ff805d;
--sun: #ffda58;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
}
canvas {
display: block;
touch-action: none;
}
.topbar {
position: fixed;
top: 20px;
left: 22px;
z-index: 5;
pointer-events: none;
text-shadow: 0 2px 18px rgba(0, 0, 0, 0.5);
}
.topbar .kicker {
margin-bottom: 5px;
color: var(--helix);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.22em;
text-transform: uppercase;
}
.topbar h1 {
margin: 0;
font-size: clamp(22px, 3vw, 38px);
font-weight: 760;
letter-spacing: -0.045em;
}
.topbar p {
max-width: 430px;
margin: 7px 0 0;
color: #bdd0d2;
font-size: 12px;
line-height: 1.45;
}
.panel {
position: fixed;
z-index: 10;
border: 1px solid var(--line);
border-radius: 16px;
background: var(--panel);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
#controls {
top: 20px;
right: 20px;
width: 306px;
padding: 16px;
}
.control-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 14px;
}
.control-title strong {
font-size: 12px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.sun-chip {
display: inline-flex;
align-items: center;
gap: 7px;
color: var(--sun);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.sun-chip::before {
width: 9px;
height: 9px;
border-radius: 2px;
background: var(--sun);
box-shadow: 0 0 14px rgba(255, 218, 88, 0.75);
content: "";
}
.control-row {
margin: 11px 0;
}
.control-row label {
display: flex;
justify-content: space-between;
margin-bottom: 7px;
color: #c9d9d9;
font-size: 11px;
}
output {
color: var(--text);
font-variant-numeric: tabular-nums;
font-weight: 700;
}
input[type="range"] {
width: 100%;
accent-color: var(--sun);
cursor: pointer;
}
.presets {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-top: 13px;
}
button {
border: 1px solid rgba(163, 210, 214, 0.19);
border-radius: 9px;
padding: 8px 5px;
background: rgba(255, 255, 255, 0.055);
color: #dce9e8;
font: inherit;
font-size: 10px;
font-weight: 750;
letter-spacing: 0.04em;
cursor: pointer;
transition: 140ms ease;
}
button:hover {
border-color: rgba(255, 218, 88, 0.5);
background: rgba(255, 218, 88, 0.09);
color: #fff2bb;
}
.hint {
margin: 13px 0 0;
padding-top: 12px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
.hint b {
color: var(--text);
}
#assumptions {
left: 20px;
bottom: 20px;
width: min(510px, calc(100vw - 40px));
padding: 15px 16px;
}
#assumptions summary {
color: var(--text);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
cursor: pointer;
}
#assumptions ul {
margin: 11px 0 0;
padding-left: 17px;
color: #b9ccce;
font-size: 10.5px;
line-height: 1.55;
}
#assumptions li + li {
margin-top: 6px;
}
#assumptions b {
color: #eff9f6;
}
#legend {
right: 20px;
bottom: 20px;
display: grid;
gap: 8px;
padding: 13px 15px;
font-size: 10px;
}
.legend-item {
display: flex;
align-items: center;
gap: 9px;
color: #c8d8d9;
}
.swatch {
width: 12px;
height: 12px;
border-radius: 3px;
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.17);
}
.swatch.helix {
background: var(--helix);
}
.swatch.ember {
background: var(--ember);
}
.swatch.sun {
background: var(--sun);
}
.swatch.lit {
background: #b9814d;
}
.swatch.shadow {
background: #142d38;
}
#labels {
position: fixed;
inset: 0;
z-index: 4;
overflow: hidden;
pointer-events: none;
}
.plot-label {
position: absolute;
width: 188px;
padding: 10px 12px;
border: 1px solid rgba(181, 222, 221, 0.2);
border-radius: 11px;
background: rgba(7, 20, 28, 0.78);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.22);
transform: translate(-50%, -100%);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
}
.plot-label .name {
display: block;
margin-bottom: 5px;
color: #dcebea;
font-size: 9px;
font-weight: 850;
letter-spacing: 0.13em;
}
.plot-label .metric {
display: flex;
align-items: baseline;
gap: 5px;
color: #fff1ad;
font-size: 17px;
font-weight: 780;
letter-spacing: -0.025em;
}
.plot-label .metric small {
color: #91aaae;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.09em;
}
.plot-label .detail {
display: block;
margin-top: 4px;
color: #92a9ad;
font-size: 8px;
font-weight: 700;
letter-spacing: 0.06em;
}
#sunTag {
position: absolute;
z-index: 6;
padding: 5px 8px;
border: 1px solid rgba(255, 218, 88, 0.38);
border-radius: 7px;
background: rgba(38, 32, 10, 0.78);
color: #ffe98d;
font-size: 8px;
font-weight: 850;
letter-spacing: 0.1em;
pointer-events: none;
transform: translate(15px, -25px);
}
@media (max-width: 760px) {
.topbar {
top: 12px;
left: 14px;
}
.topbar h1 {
font-size: 23px;
}
.topbar p {
display: none;
}
#controls {
top: 74px;
right: 12px;
left: 12px;
width: auto;
padding: 12px;
}
.control-row {
display: grid;
grid-template-columns: 88px 1fr 38px;
align-items: center;
gap: 7px;
margin: 7px 0;
}
.control-row label {
margin: 0;
}
.control-row output {
text-align: right;
}
.control-title {
margin-bottom: 9px;
}
.presets {
margin-top: 9px;
}
.hint {
margin-top: 8px;
padding-top: 8px;
}
#assumptions {
right: 12px;
bottom: 12px;
left: 12px;
width: auto;
max-height: 31vh;
overflow: auto;
padding: 12px;
}
#legend {
display: none;
}
.plot-label {
width: 145px;
padding: 8px;
}
.plot-label .metric {
font-size: 14px;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<header class="topbar">
<div class="kicker">Voxel Agronomy / Comparative Study</div>
<h1>Intercropping Light Lab</h1>
<p>
Compare two fictional crop forms under one moving sun. The beds contain the
same plants in the same planting positions; only their row assignments change.
</p>
</header>
<section id="controls" class="panel" aria-label="Sun controls">
<div class="control-title">
<strong>Directional Sun</strong>
<span class="sun-chip">Drag marker</span>
</div>
<div class="control-row">
<label for="azimuth">Azimuth <output id="azimuthValue">35°</output></label>
<input id="azimuth" type="range" min="-180" max="180" value="35" />
</div>
<div class="control-row">
<label for="elevation">Elevation <output id="elevationValue">42°</output></label>
<input id="elevation" type="range" min="15" max="78" value="42" />
</div>
<div class="presets">
<button data-az="-65" data-elev="28">Morning</button>
<button data-az="10" data-elev="68">Noon</button>
<button data-az="72" data-elev="23">Low sun</button>
</div>
<p class="hint">
<b>Drag the yellow sun</b> to move the light.<br />
<b>Drag the scene</b> to orbit. <b>Scroll / pinch</b> to zoom.
</p>
</section>
<div id="labels">
<div id="separateLabel" class="plot-label">
<span class="name">SEPARATE ROWS</span>
<span class="metric"><span id="separateLit">—</span><small>% SUNLIT</small></span>
<span class="detail">6 HELIX STALKS · 6 EMBER BUSHES</span>
</div>
<div id="mixedLabel" class="plot-label">
<span class="name">MIXED ROWS</span>
<span class="metric"><span id="mixedLit">—</span><small>% SUNLIT</small></span>
<span class="detail">6 HELIX STALKS · 6 EMBER BUSHES</span>
</div>
<div id="sunTag">DRAG SUN</div>
</div>
<aside id="assumptions" class="panel">
<details open>
<summary>Explicit model assumptions</summary>
<ul>
<li>
<b>Only arrangement changes:</b> the separate bed has one all-Helix row and
one all-Ember row. The mixed bed alternates both forms in both rows.
</li>
<li>
<b>Identical geometry:</b> both beds are 8.0 × 5.6 scene units, use the
same two row baselines, the same twelve planting positions, six plants of
each form, identical voxel dimensions, soil, and lighting direction.
</li>
<li>
<b>Light model:</b> parallel directional rays; every plant voxel is opaque;
shadows are hard-edged projections onto a flat, level soil plane.
</li>
<li>
<b>Excluded:</b> diffuse inter-reflection, penumbra, wind, growth stages,
disease, soil moisture, and below-ground effects.
</li>
<li>
<b>Coordinates:</b> azimuth 0° points toward +Z; positive azimuth rotates
toward +X. Elevation is measured above the horizontal plane.
</li>
</ul>
</details>
</aside>
<aside id="legend" class="panel">
<div class="legend-item"><span class="swatch helix"></span>Helix stalk</div>
<div class="legend-item"><span class="swatch ember"></span>Ember bush</div>
<div class="legend-item"><span class="swatch sun"></span>Sun marker</div>
<div class="legend-item"><span class="swatch lit"></span>Sunlit soil</div>
<div class="legend-item"><span class="swatch shadow"></span>Voxel shadow</div>
</aside>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
// ------------------------------------------------------------
// Scene and renderer
// ------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07141c);
scene.fog = new THREE.Fog(0x07141c, 28, 55);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
$("scene").appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0, 0.9, 0);
let cameraTheta = -0.59;
let cameraPhi = 1.02;
let cameraRadius = 23;
let userZoomed = false;
function updateCamera() {
const sinPhi = Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x + cameraRadius * sinPhi * Math.sin(cameraTheta),
cameraTarget.y + cameraRadius * Math.cos(cameraPhi),
cameraTarget.z + cameraRadius * sinPhi * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xb9e8ec, 0x24303a, 1.65);
scene.add(hemisphere);
const sunLight = new THREE.DirectionalLight(0xfff0c2, 2.4);
sunLight.castShadow = true;
sunLight.shadow.mapSize.set(2048, 2048);
sunLight.shadow.camera.left = -13;
sunLight.shadow.camera.right = 13;
sunLight.shadow.camera.top = 10;
sunLight.shadow.camera.bottom = -10;
sunLight.shadow.camera.near = 1;
sunLight.shadow.camera.far = 55;
sunLight.shadow.bias = -0.00025;
sunLight.target.position.set(0, 0, 0);
scene.add(sunLight);
scene.add(sunLight.target);
// ------------------------------------------------------------
// Ground stage
// ------------------------------------------------------------
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(42, 32),
new THREE.MeshStandardMaterial({
color: 0x10232c,
roughness: 0.96,
metalness: 0
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.49;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(40, 40, 0x31505a, 0x1a3039);
grid.position.y = -0.475;
grid.material.transparent = true;
grid.material.opacity = 0.38;
scene.add(grid);
// A restrained voxel border around the complete laboratory.
const decorMaterial = new THREE.MeshStandardMaterial({
color: 0x29454b,
roughness: 0.9
});
const decorGeometry = new THREE.BoxGeometry(1, 1, 1);
const decor = new THREE.InstancedMesh(decorGeometry, decorMaterial, 30);
const decorMatrix = new THREE.Matrix4();
const decorPosition = new THREE.Vector3();
const decorScale = new THREE.Vector3();
const decorQuaternion = new THREE.Quaternion();
let decorIndex = 0;
for (let side = -1; side <= 1; side += 2) {
for (let i = 0; i < 15; i++) {
decorPosition.set(-10.8 + i * 1.55, -0.18, side * 4.55);
const height = 0.18 + ((i * 7 + side) % 4) * 0.11;
decorScale.set(0.42 + (i % 3) * 0.09, height, 0.42 + ((i + 1) % 3) * 0.08);
decorMatrix.compose(decorPosition, decorQuaternion, decorScale);
decor.setMatrixAt(decorIndex++, decorMatrix);
}
}
decor.instanceMatrix.needsUpdate = true;
decor.castShadow = true;
decor.receiveShadow = true;
scene.add(decor);
// ------------------------------------------------------------
// Fictional crop forms
// ------------------------------------------------------------
const VOXEL_SIZE = 0.29;
const VOXEL_STEP = 0.32;
const helixVoxels = [
[0, 0, 0],
[0, 1, 0],
[0, 2, 0],
[0, 3, 0],
[0, 4, 0],
[0, 5, 0],
[0, 6, 0],
[0, 7, 0],
[0, 8, 0],
[0, 9, 0],
[-1, 3, 0],
[1, 3, 0],
[0, 5, -1],
[0, 5, 1],
[-1, 7, 0],
[1, 7, 0]
];
const emberVoxels = [];
// Stepped, broad and low.
for (let y = 0; y <= 3; y++) {
for (let x = -1; x <= 1; x++) {
for (let z = -1; z <= 1; z++) {
let include = false;
if (y === 0) include = true;
if (y === 1) include = x === 0 || z === 0;
if (y === 2) include = (x === 0 && z === 0) || (Math.abs(x) === 1 && Math.abs(z) === 1);
if (y === 3) include = x === 0 && z === 0;
if (include) emberVoxels.push([x, y, z]);
}
}
}
const cropDefinitions = {
helix: {
color: new THREE.Color(0x42d9b4),
voxels: helixVoxels
},
ember: {
color: new THREE.Color(0xff805d),
voxels: emberVoxels
}
};
const plantGeometry = new THREE.BoxGeometry(
VOXEL_SIZE,
VOXEL_SIZE,
VOXEL_SIZE
);
const plantMaterials = {
helix: new THREE.MeshStandardMaterial({
color: 0xffffff,
vertexColors: true,
roughness: 0.76,
metalness: 0.02,
flatShading: true
}),
ember: new THREE.MeshStandardMaterial({
color: 0xffffff,
vertexColors: true,
roughness: 0.8,
metalness: 0.01,
flatShading: true
})
};
// ------------------------------------------------------------
// Plot geometry and soil texture helpers
// ------------------------------------------------------------
const PLOT_WIDTH = 8;
const PLOT_DEPTH = 5.6;
const TEX_WIDTH = 512;
const TEX_HEIGHT = Math.round(TEX_WIDTH * PLOT_DEPTH / PLOT_WIDTH);
const plantingX = [-3, -1.8, -0.6, 0.6, 1.8, 3];
const rowZ = [-1.35, 1.35];
function hashNoise(x, y) {
const value = Math.sin(x * 12.9898 + y * 78.233) * 43758.5453;
return value - Math.floor(value);
}
function makeBaseCanvas() {
const canvas = document.createElement("canvas");
canvas.width = TEX_WIDTH;
canvas.height = TEX_HEIGHT;
const ctx = canvas.getContext("2d");
const image = ctx.createImageData(TEX_WIDTH, TEX_HEIGHT);
for (let y = 0; y < TEX_HEIGHT; y++) {
for (let x = 0; x < TEX_WIDTH; x++) {
const n = hashNoise(x, y);
const fine = hashNoise(x * 0.31, y * 0.47);
const index = (y * TEX_WIDTH + x) * 4;
image.data[index] = 167 + n * 20 + fine * 7;
image.data[index + 1] = 111 + n * 14 + fine * 5;
image.data[index + 2] = 61 + n * 8;
image.data[index + 3] = 255;
}
}
ctx.putImageData(image, 0, 0);
// Identical furrows in both beds.
for (const z of rowZ) {
const y = (z + PLOT_DEPTH / 2) / PLOT_DEPTH * TEX_HEIGHT;
ctx.fillStyle = "rgba(67, 43, 27, 0.22)";
ctx.fillRect(0, y - 11, TEX_WIDTH, 22);
ctx.fillStyle = "rgba(255, 221, 160, 0.10)";
ctx.fillRect(0, y - 12, TEX_WIDTH, 2);
}
// Planting-position marks are identical in both plots.
for (const z of rowZ) {
for (const x of plantingX) {
const px = (x + PLOT_WIDTH / 2) / PLOT_WIDTH * TEX_WIDTH;
const py = (z + PLOT_DEPTH / 2) / PLOT_DEPTH * TEX_HEIGHT;
const size = 24;
ctx.fillStyle = "rgba(48, 39, 27, 0.22)";
ctx.fillRect(px - size / 2, py - size / 2, size, size);
ctx.strokeStyle = "rgba(255, 232, 190, 0.15)";
ctx.lineWidth = 2;
ctx.strokeRect(px - size / 2, py - size / 2, size, size);
}
}
// Subtle inset frame.
ctx.strokeStyle = "rgba(66, 42, 28, 0.5)";
ctx.lineWidth = 12;
ctx.strokeRect(6, 6, TEX_WIDTH - 12, TEX_HEIGHT - 12);
return canvas;
}
function createPlot(id, centerX, arrangement) {
const plot = {
id,
centerX,
arrangement,
voxels: [],
baseCanvas: makeBaseCanvas(),
maskCanvas: document.createElement("canvas"),
outputCanvas: document.createElement("canvas")
};
plot.maskCanvas.width = TEX_WIDTH;
plot.maskCanvas.height = TEX_HEIGHT;
plot.outputCanvas.width = TEX_WIDTH;
plot.outputCanvas.height = TEX_HEIGHT;
// Raised voxel bed.
const bed = new THREE.Mesh(
new THREE.BoxGeometry(PLOT_WIDTH + 0.42, 0.46, PLOT_DEPTH + 0.42),
new THREE.MeshStandardMaterial({
color: 0x533827,
roughness: 0.95
})
);
bed.position.set(centerX, -0.23, 0);
bed.castShadow = true;
bed.receiveShadow = true;
scene.add(bed);
// Soil texture carries the explicitly calculated light patches.
plot.texture = new THREE.CanvasTexture(plot.outputCanvas);
plot.texture.colorSpace = THREE.SRGBColorSpace;
plot.texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(PLOT_WIDTH, PLOT_DEPTH),
new THREE.MeshBasicMaterial({
map: plot.texture,
toneMapped: false
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.set(centerX, 0.012, 0);
scene.add(ground);
// Blocky bed rails.
const railMaterial = new THREE.MeshStandardMaterial({
color: 0x795333,
roughness: 0.9
});
const railGeometryLong = new THREE.BoxGeometry(0.15, 0.16, PLOT_DEPTH + 0.25);
const railGeometryWide = new THREE.BoxGeometry(PLOT_WIDTH + 0.25, 0.16, 0.15);
for (const side of [-1, 1]) {
const rail = new THREE.Mesh(railGeometryLong, railMaterial);
rail.position.set(centerX + side * (PLOT_WIDTH / 2 + 0.08), 0.08, 0);
rail.castShadow = true;
rail.receiveShadow = true;
scene.add(rail);
const endRail = new THREE.Mesh(railGeometryWide, railMaterial);
endRail.position.set(centerX, 0.08, side * (PLOT_DEPTH / 2 + 0.08));
endRail.castShadow = true;
endRail.receiveShadow = true;
scene.add(endRail);
}
// Construct exactly twelve plants in exactly twelve positions.
for (let row = 0; row < rowZ.length; row++) {
for (let column = 0; column < plantingX.length; column++) {
let cropType;
if (arrangement === "separate") {
cropType = row === 0 ? "helix" : "ember";
} else {
cropType = (column + row) % 2 === 0 ? "helix" : "ember";
}
const definition = cropDefinitions[cropType];
for (const voxel of definition.voxels) {
plot.voxels.push({
x: plantingX[column] + voxel[0] * VOXEL_STEP,
y: (voxel[1] + 0.5) * VOXEL_STEP,
z: rowZ[row] + voxel[2] * VOXEL_STEP,
size: VOXEL_SIZE,
cropType
});
}
}
}
// One instanced mesh per crop form in each bed.
for (const cropType of ["helix", "ember"]) {
const instances = plot.voxels.filter((voxel) => voxel.cropType === cropType);
const mesh = new THREE.InstancedMesh(
plantGeometry,
plantMaterials[cropType],
instances.length
);
const matrix = new THREE.Matrix4();
const position = new THREE.Vector3();
const quaternion = new THREE.Quaternion();
const scale = new THREE.Vector3(1, 1, 1);
const color = new THREE.Color();
instances.forEach((voxel, index) => {
position.set(centerX + voxel.x, voxel.y, voxel.z);
matrix.compose(position, quaternion, scale);
mesh.setMatrixAt(index, matrix);
color.copy(cropDefinitions[cropType].color);
color.offsetHSL(
0,
0,
(hashNoise(index + 3, cropType === "helix" ? 11 : 29) - 0.5) * 0.16
);
mesh.setColorAt(index, color);
});
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
}
return plot;
}
const separatePlot = createPlot("separate", -5.2, "separate");
const mixedPlot = createPlot("mixed", 5.2, "mixed");
const plots = [separatePlot, mixedPlot];
// ------------------------------------------------------------
// Sun marker
// ------------------------------------------------------------
const sunGroup = new THREE.Group();
sunGroup.renderOrder = 10;
const sunMaterial = new THREE.MeshStandardMaterial({
color: 0xffda58,
emissive: 0xffa900,
emissiveIntensity: 1.7,
roughness: 0.38,
toneMapped: false
});
const sunCore = new THREE.Mesh(
new THREE.BoxGeometry(0.58, 0.58, 0.58),
sunMaterial
);
sunCore.renderOrder = 10;
sunGroup.add(sunCore);
const rayGeometry = new THREE.BoxGeometry(0.13, 0.13, 0.13);
const rayDirections = [
[1, 0, 0], [-1, 0, 0],
[0, 1, 0], [0, -1, 0],
[0, 0, 1], [0, 0, -1]
];
for (const direction of rayDirections) {
const ray = new THREE.Mesh(rayGeometry, sunMaterial);
ray.position.set(
direction[0] * 0.49,
direction[1] * 0.49,
direction[2] * 0.49
);
ray.renderOrder = 10;
sunGroup.add(ray);
}
const sunHalo = new THREE.Mesh(
new THREE.BoxGeometry(0.98, 0.98, 0.98),
new THREE.MeshBasicMaterial({
color: 0xffdd66,
wireframe: true,
transparent: true,
opacity: 0.42,
toneMapped: false,
depthTest: false
})
);
sunHalo.renderOrder = 11;
sunGroup.add(sunHalo);
scene.add(sunGroup);
const sunCenter = new THREE.Vector3(0, 0.85, 0);
const sunDirection = new THREE.Vector3();
const sunLineGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(),
new THREE.Vector3()
]);
const sunLine = new THREE.Line(
sunLineGeometry,
new THREE.LineDashedMaterial({
color: 0xffd968,
dashSize: 0.35,
gapSize: 0.25,
transparent: true,
opacity: 0.45,
toneMapped: false
})
);
scene.add(sunLine);
// ------------------------------------------------------------
// Directional shadow projection
// ------------------------------------------------------------
function convexHull(points) {
if (points.length < 3) return points;
const sorted = points.slice().sort((a, b) => {
return a.x === b.x ? a.y - b.y : a.x - b.x;
});
const cross = (o, a, b) =>
(a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
const lower = [];
for (const point of sorted) {
while (
lower.length >= 2 &&
cross(lower[lower.length - 2], lower[lower.length - 1], point) <= 0
) {
lower.pop();
}
lower.push(point);
}
const upper = [];
for (let i = sorted.length - 1; i >= 0; i--) {
const point = sorted[i];
while (
upper.length >= 2 &&
cross(upper[upper.length - 2], upper[upper.length - 1], point) <= 0
) {
upper.pop();
}
upper.push(point);
}
lower.pop();
upper.pop();
return lower.concat(upper);
}
function projectVoxelShadow(voxel) {
const half = voxel.size / 2;
const projected = [];
for (const sx of [-1, 1]) {
for (const sy of [-1, 1]) {
for (const sz of [-1, 1]) {
const px = voxel.x + sx * half;
const py = voxel.y + sy * half;
const pz = voxel.z + sz * half;
// Extend from the voxel away from the sun until y = 0.
const travel = -py / sunDirection.y;
const groundX = px + travel * sunDirection.x;
const groundZ = pz + travel * sunDirection.z;
projected.push({
x: (groundX + PLOT_WIDTH / 2) / PLOT_WIDTH * TEX_WIDTH,
y: (groundZ + PLOT_DEPTH / 2) / PLOT_DEPTH * TEX_HEIGHT
});
}
}
}
return convexHull(projected);
}
function updatePlotShadow(plot) {
const maskContext = plot.maskCanvas.getContext("2d");
const outputContext = plot.outputCanvas.getContext("2d");
maskContext.clearRect(0, 0, TEX_WIDTH, TEX_HEIGHT);
maskContext.fillStyle = "#07151d";
// Draw every opaque cube silhouette into one union mask.
for (const voxel of plot.voxels) {
const polygon = projectVoxelShadow(voxel);
if (polygon.length < 3) continue;
maskContext.beginPath();
maskContext.moveTo(polygon[0].x, polygon[0].y);
for (let i = 1; i < polygon.length; i++) {
maskContext.lineTo(polygon[i].x, polygon[i].y);
}
maskContext.closePath();
maskContext.fill();
}
// Recompose the soil and apply the union shadow exactly once.
outputContext.clearRect(0, 0, TEX_WIDTH, TEX_HEIGHT);
outputContext.drawImage(plot.baseCanvas, 0, 0);
outputContext.save();
outputContext.globalAlpha = 0.72;
outputContext.drawImage(plot.maskCanvas, 0, 0);
outputContext.restore();
plot.texture.needsUpdate = true;
// Fractional coverage also accounts for antialiased polygon edges.
const maskData = maskContext.getImageData(
0,
0,
TEX_WIDTH,
TEX_HEIGHT
).data;
let covered = 0;
for (let i = 3; i < maskData.length; i += 4) {
covered += maskData[i] / 255;
}
const shadowPercent = covered / (TEX_WIDTH * TEX_HEIGHT) * 100;
const litPercent = Math.max(0, 100 - shadowPercent);
plot.litPercent = litPercent;
}
function refreshAllShadows() {
updatePlotShadow(separatePlot);
updatePlotShadow(mixedPlot);
$("separateLit").textContent = separatePlot.litPercent.toFixed(1);
$("mixedLit").textContent = mixedPlot.litPercent.toFixed(1);
}
// ------------------------------------------------------------
// Sun state and controls
// ------------------------------------------------------------
let currentAzimuth = 35;
let currentElevation = 42;
let goalAzimuth = 35;
let goalElevation = 42;
let shadowUpdatePending = true;
let lastShadowUpdate = 0;
function setSunVisual() {
const azimuth = THREE.MathUtils.degToRad(currentAzimuth);
const elevation = THREE.MathUtils.degToRad(currentElevation);
sunDirection.set(
Math.cos(elevation) * Math.sin(azimuth),
Math.sin(elevation),
Math.cos(elevation) * Math.cos(azimuth)
);
sunLight.position.copy(sunDirection).multiplyScalar(24);
sunLight.intensity = 1.8 + Math.sin(elevation) * 0.8;
sunGroup.position.copy(sunCenter).addScaledVector(sunDirection, 9.4);
sunGroup.rotation.y += 0.004;
sunHalo.rotation.x += 0.003;
sunHalo.rotation.z += 0.002;
const linePositions = sunLine.geometry.attributes.position;
linePositions.setXYZ(
0,
sunGroup.position.x,
sunGroup.position.y,
sunGroup.position.z
);
linePositions.setXYZ(
1,
sunCenter.x,
sunCenter.y,
sunCenter.z
);
linePositions.needsUpdate = true;
sunLine.geometry.computeBoundingSphere();
sunLine.computeLineDistances();
shadowUpdatePending = true;
}
function syncSunControls() {
$("azimuth").value = goalAzimuth;
$("elevation").value = goalElevation;
$("azimuthValue").textContent = `${Math.round(goalAzimuth)}°`;
$("elevationValue").textContent = `${Math.round(goalElevation)}°`;
}
$("azimuth").addEventListener("input", (event) => {
goalAzimuth = Number(event.target.value);
$("azimuthValue").textContent = `${Math.round(goalAzimuth)}°`;
});
$("elevation").addEventListener("input", (event) => {
goalElevation = Number(event.target.value);
$("elevationValue").textContent = `${Math.round(goalElevation)}°`;
});
document.querySelectorAll(".presets button").forEach((button) => {
button.addEventListener("click", () => {
goalAzimuth = Number(button.dataset.az);
goalElevation = Number(button.dataset.elev);
syncSunControls();
});
});
// ------------------------------------------------------------
// Direct pointer controls: sun dragging and camera orbit
// ------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const canvas = renderer.domElement;
let dragMode = null;
let pointerStartX = 0;
let pointerStartY = 0;
let sunStartAzimuth = 0;
let sunStartElevation = 0;
function updatePointer(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function pointerHitsSun(event) {
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
return raycaster.intersectObject(sunGroup, true).length > 0;
}
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
canvas.setPointerCapture(event.pointerId);
pointerStartX = event.clientX;
pointerStartY = event.clientY;
if (pointerHitsSun(event)) {
dragMode = "sun";
sunStartAzimuth = goalAzimuth;
sunStartElevation = goalElevation;
canvas.style.cursor = "grabbing";
} else {
dragMode = "orbit";
canvas.style.cursor = "grabbing";
}
});
canvas.addEventListener("pointermove", (event) => {
if (dragMode === "sun") {
const dx = event.clientX - pointerStartX;
const dy = event.clientY - pointerStartY;
goalAzimuth = THREE.MathUtils.clamp(
sunStartAzimuth + dx * 0.22,
-180,
180
);
goalElevation = THREE.MathUtils.clamp(
sunStartElevation - dy * 0.18,
15,
78
);
syncSunControls();
} else if (dragMode === "orbit") {
const dx = event.clientX - pointerStartX;
const dy = event.clientY - pointerStartY;
cameraTheta -= dx * 0.006;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi + dy * 0.006,
0.48,
1.38
);
pointerStartX = event.clientX;
pointerStartY = event.clientY;
updateCamera();
} else {
canvas.style.cursor = pointerHitsSun(event) ? "grab" : "default";
}
});
function endDrag(event) {
dragMode = null;
canvas.style.cursor = "default";
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
13,
48
);
userZoomed = true;
updateCamera();
},
{ passive: false }
);
// ------------------------------------------------------------
// HTML labels projected from world positions
// ------------------------------------------------------------
const separateAnchor = new THREE.Vector3(-5.2, 3.72, 0);
const mixedAnchor = new THREE.Vector3(5.2, 3.72, 0);
const projected = new THREE.Vector3();
function positionLabel(element, worldPosition) {
projected.copy(worldPosition).project(camera);
const visible = projected.z > -1 && projected.z < 1;
element.style.display = visible ? "block" : "none";
if (!visible) return;
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
}
function updateOverlays() {
positionLabel($("separateLabel"), separateAnchor);
positionLabel($("mixedLabel"), mixedAnchor);
projected.copy(sunGroup.position).project(camera);
const sunVisible = projected.z > -1 && projected.z < 1;
$("sunTag").style.display = sunVisible ? "block" : "none";
if (sunVisible) {
$("sunTag").style.left =
`${(projected.x * 0.5 + 0.5) * window.innerWidth}px`;
$("sunTag").style.top =
`${(-projected.y * 0.5 + 0.5) * window.innerHeight}px`;
}
}
// ------------------------------------------------------------
// Resize and animation
// ------------------------------------------------------------
function onResize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
camera.aspect = aspect;
if (aspect < 0.85) {
camera.fov = 50;
if (!userZoomed) cameraRadius = 34;
} else {
camera.fov = 42;
if (!userZoomed) cameraRadius = 23;
}
camera.updateProjectionMatrix();
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
updateCamera();
}
window.addEventListener("resize", onResize);
function shortestAngleDifference(from, to) {
return ((to - from + 540) % 360) - 180;
}
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
const easing = 1 - Math.exp(-dt * 10);
const azimuthDelta = shortestAngleDifference(currentAzimuth, goalAzimuth);
const elevationDelta = goalElevation - currentElevation;
if (Math.abs(azimuthDelta) > 0.01 || Math.abs(elevationDelta) > 0.01) {
currentAzimuth += azimuthDelta * easing;
currentElevation += elevationDelta * easing;
setSunVisual();
}
// Limit the relatively expensive texture updates to about 30 Hz.
const now = performance.now();
if (shadowUpdatePending && now - lastShadowUpdate > 32) {
refreshAllShadows();
shadowUpdatePending = false;
lastShadowUpdate = now;
}
updateOverlays();
renderer.render(scene, camera);
}
setSunVisual();
refreshAllShadows();
syncSunControls();
onResize();
animate();
</script>
</body>
</html>
```