Prompt specification
Build or customize the Three.js 3D scene "Lifecycle resource-matching puzzle" 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: Lifecycle resource-matching puzzle
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/lifecycle-resource-matching-puzzle-x0664
Scene Description Prompt:
A low-poly butterfly life-cycle puzzle matching stages to species-appropriate host plants and resources. Three.js from cdnjs, one HTML file.
Working Three.js Starter (lifecycle-resource-matching-puzzle-x0664):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#173f35">
<title>Flutter Lab — Butterfly Life-Cycle Puzzle</title>
<style>
:root {
--ink: #173f35;
--muted: #668078;
--paper: #f7f4e9;
--cream: #fffdf5;
--green: #2f8f68;
--green-dark: #176348;
--orange: #f39a3d;
--line: #dce5db;
--shadow: 0 12px 35px rgba(23, 63, 53, 0.12);
--radius: 18px;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
}
body {
color: var(--ink);
background: var(--paper);
font-family: "Trebuchet MS", "Segoe UI", sans-serif;
overflow: hidden;
}
button {
color: inherit;
font: inherit;
}
button:focus-visible {
outline: 3px solid rgba(243, 154, 61, 0.6);
outline-offset: 3px;
}
.app {
display: grid;
grid-template-rows: 68px minmax(0, 1fr);
width: 100%;
height: 100dvh;
}
header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 22px;
color: white;
background:
radial-gradient(circle at 12% 20%, rgba(255,255,255,.09), transparent 25%),
linear-gradient(100deg, #173f35, #245d4a);
border-bottom: 1px solid rgba(255,255,255,.14);
z-index: 20;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-mark {
position: relative;
width: 38px;
height: 34px;
flex: 0 0 auto;
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
top: 3px;
width: 20px;
height: 27px;
background: var(--orange);
border: 2px solid rgba(255,255,255,.8);
border-radius: 65% 65% 45% 45%;
transform: rotate(-15deg);
}
.brand-mark::before {
left: 1px;
}
.brand-mark::after {
right: 1px;
transform: rotate(15deg) scaleX(-1);
}
.brand h1 {
margin: 0;
font-size: clamp(17px, 2vw, 24px);
line-height: 1;
letter-spacing: -0.5px;
white-space: nowrap;
}
.brand p {
margin: 5px 0 0;
color: rgba(255,255,255,.68);
font-size: 11px;
letter-spacing: 1.5px;
text-transform: uppercase;
}
.header-progress {
display: flex;
align-items: center;
gap: 18px;
min-width: 280px;
}
.progress-copy {
text-align: right;
white-space: nowrap;
}
.progress-copy strong {
display: block;
font-size: 15px;
}
.progress-copy span {
color: rgba(255,255,255,.65);
font-size: 11px;
}
.progress-track {
width: 150px;
height: 7px;
overflow: hidden;
background: rgba(255,255,255,.15);
border-radius: 99px;
}
.progress-fill {
width: 0%;
height: 100%;
background: linear-gradient(90deg, #ffd274, var(--orange));
border-radius: inherit;
transition: width .35s ease;
}
main {
display: grid;
grid-template-columns: 300px minmax(0, 1fr);
min-height: 0;
}
aside {
min-height: 0;
padding: 18px;
overflow-y: auto;
background: #fffdf7;
border-right: 1px solid var(--line);
scrollbar-width: thin;
}
.eyebrow {
margin: 0 0 7px;
color: var(--green);
font-size: 10px;
font-weight: 800;
letter-spacing: 1.7px;
text-transform: uppercase;
}
.instructions h2 {
margin: 0;
font-size: 22px;
letter-spacing: -.5px;
}
.instructions p {
margin: 8px 0 16px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.mini-steps {
display: grid;
gap: 7px;
margin-bottom: 19px;
}
.mini-step {
display: flex;
align-items: center;
gap: 9px;
padding: 8px 10px;
color: #49665e;
background: #f1f5ed;
border-radius: 10px;
font-size: 11px;
}
.mini-step b {
display: grid;
place-items: center;
width: 20px;
height: 20px;
color: white;
background: var(--green);
border-radius: 50%;
font-size: 10px;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin: 20px 0 10px;
}
.section-title h3 {
margin: 0;
font-size: 13px;
}
.section-title span {
color: var(--muted);
font-size: 10px;
}
.species-list {
display: grid;
gap: 9px;
}
.species-card {
position: relative;
width: 100%;
padding: 12px;
text-align: left;
background: white;
border: 1px solid var(--line);
border-radius: 14px;
cursor: pointer;
box-shadow: 0 4px 12px rgba(23,63,53,.04);
transition: transform .18s ease, border-color .18s ease, box-shadow .18s ease;
}
.species-card:hover,
.species-card.active {
transform: translateY(-2px);
border-color: var(--green);
box-shadow: 0 8px 18px rgba(23,63,53,.1);
}
.species-card.active::after {
content: "✓";
position: absolute;
top: 10px;
right: 10px;
display: grid;
place-items: center;
width: 20px;
height: 20px;
color: white;
background: var(--green);
border-radius: 50%;
font-size: 11px;
font-weight: bold;
}
.species-name {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
font-weight: 800;
}
.species-dot {
width: 10px;
height: 10px;
flex: 0 0 auto;
border-radius: 50%;
box-shadow: inset 0 0 0 2px rgba(255,255,255,.5);
}
.species-scientific {
margin: 3px 0 8px 18px;
color: var(--muted);
font-size: 10px;
font-style: italic;
}
.species-meta {
display: grid;
grid-template-columns: 62px 1fr;
gap: 3px 7px;
margin-left: 18px;
color: #587168;
font-size: 10px;
line-height: 1.35;
}
.species-meta strong {
color: var(--ink);
font-weight: 700;
}
.resource-list {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 6px;
}
.resource {
padding: 8px 5px;
text-align: center;
background: #f0f4eb;
border-radius: 10px;
}
.resource b {
display: block;
margin-bottom: 3px;
font-size: 10px;
}
.resource span {
display: block;
color: var(--muted);
font-size: 8px;
line-height: 1.25;
}
.play-area {
display: grid;
grid-template-rows: minmax(0, 1fr) 116px;
min-width: 0;
min-height: 0;
}
#viewport {
position: relative;
min-height: 0;
overflow: hidden;
background: #dcece4;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#viewport canvas:active {
cursor: grabbing;
}
.scene-hud {
position: absolute;
top: 14px;
left: 16px;
z-index: 4;
max-width: min(430px, calc(100% - 210px));
pointer-events: none;
}
.scene-hud .pill {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 8px 12px;
color: var(--ink);
background: rgba(255,253,245,.9);
border: 1px solid rgba(255,255,255,.8);
border-radius: 99px;
box-shadow: var(--shadow);
backdrop-filter: blur(8px);
font-size: 11px;
font-weight: 700;
}
.scene-hud .pill::before {
content: "";
width: 7px;
height: 7px;
background: var(--orange);
border-radius: 50%;
box-shadow: 0 0 0 4px rgba(243,154,61,.18);
}
.scene-hud p {
margin: 8px 3px 0;
color: rgba(23,63,53,.75);
font-size: 11px;
}
.view-tools {
position: absolute;
top: 13px;
right: 14px;
z-index: 5;
display: flex;
gap: 6px;
}
.tool-button {
display: grid;
place-items: center;
min-width: 36px;
height: 36px;
padding: 0 10px;
color: var(--ink);
background: rgba(255,253,245,.92);
border: 1px solid rgba(255,255,255,.8);
border-radius: 10px;
box-shadow: var(--shadow);
cursor: pointer;
font-size: 11px;
font-weight: 800;
backdrop-filter: blur(8px);
}
.tool-button:hover {
background: white;
transform: translateY(-1px);
}
.legend {
position: absolute;
left: 15px;
bottom: 14px;
z-index: 4;
display: flex;
flex-wrap: wrap;
gap: 7px;
max-width: calc(100% - 30px);
pointer-events: none;
}
.legend-item {
display: flex;
align-items: center;
gap: 5px;
padding: 6px 9px;
color: #48645c;
background: rgba(255,253,245,.85);
border-radius: 99px;
backdrop-filter: blur(7px);
font-size: 9px;
}
.legend-swatch {
width: 8px;
height: 8px;
border-radius: 50%;
}
#toast {
position: absolute;
left: 50%;
bottom: 54px;
z-index: 9;
max-width: min(520px, calc(100% - 28px));
padding: 11px 16px;
color: white;
background: rgba(23,63,53,.94);
border-radius: 12px;
box-shadow: 0 12px 30px rgba(23,63,53,.25);
opacity: 0;
transform: translate(-50%, 12px);
transition: opacity .2s ease, transform .2s ease;
pointer-events: none;
text-align: center;
font-size: 12px;
line-height: 1.4;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.error {
background: rgba(151,65,45,.96);
}
#toast.success {
background: rgba(31,112,78,.96);
}
.tray {
position: relative;
z-index: 8;
display: grid;
grid-template-columns: 165px 1fr;
gap: 15px;
align-items: center;
padding: 13px 17px;
background: #fffdf7;
border-top: 1px solid var(--line);
box-shadow: 0 -7px 22px rgba(23,63,53,.06);
}
.tray-title h3 {
margin: 0 0 4px;
font-size: 14px;
}
.tray-title p {
margin: 0;
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
.stage-buttons {
display: grid;
grid-template-columns: repeat(4, minmax(92px, 1fr));
gap: 9px;
min-width: 0;
}
.stage-button {
position: relative;
display: grid;
grid-template-columns: 38px 1fr;
align-items: center;
gap: 8px;
min-height: 72px;
padding: 9px;
text-align: left;
background: #f5f5eb;
border: 2px solid transparent;
border-radius: 13px;
cursor: pointer;
transition: transform .15s ease, border-color .15s ease, background .15s ease;
}
.stage-button:hover {
transform: translateY(-2px);
}
.stage-button.selected {
background: #fff2d9;
border-color: var(--orange);
box-shadow: 0 6px 15px rgba(243,154,61,.18);
}
.stage-button.complete {
background: #e7f5eb;
}
.stage-button b {
display: block;
font-size: 11px;
line-height: 1.1;
}
.stage-button small {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 8px;
line-height: 1.15;
}
.stage-count {
position: absolute;
top: 5px;
right: 7px;
color: var(--muted);
font-size: 8px;
font-weight: 800;
}
.stage-icon {
position: relative;
display: block;
width: 34px;
height: 34px;
margin: auto;
}
.stage-icon.egg::before {
content: "";
position: absolute;
left: 10px;
top: 4px;
width: 14px;
height: 23px;
background: #f3dca2;
border: 2px solid #9f7b39;
border-radius: 50%;
transform: rotate(-14deg);
}
.stage-icon.larva::before {
content: "";
position: absolute;
left: 2px;
top: 10px;
width: 30px;
height: 14px;
background: repeating-linear-gradient(
90deg,
#78aa55 0 9px,
#a8c96f 9px 12px
);
border: 2px solid #3d6e3d;
border-radius: 70% 55% 60% 70%;
}
.stage-icon.larva::after {
content: "";
position: absolute;
right: 0;
top: 8px;
width: 4px;
height: 4px;
background: #173f35;
border-radius: 50%;
}
.stage-icon.pupa::before {
content: "";
position: absolute;
left: 9px;
top: 3px;
width: 17px;
height: 27px;
background: #83a765;
border: 2px solid #4a6c3f;
border-radius: 55% 55% 65% 65% / 35% 35% 80% 80%;
transform: rotate(8deg);
}
.stage-icon.pupa::after {
content: "";
position: absolute;
left: 12px;
top: 10px;
width: 10px;
height: 2px;
background: #d8c66c;
box-shadow: 0 6px 0 #d8c66c;
}
.stage-icon.adult::before,
.stage-icon.adult::after {
content: "";
position: absolute;
top: 3px;
width: 17px;
height: 24px;
background: #f0a044;
border: 2px solid #334a40;
border-radius: 70% 70% 45% 45%;
}
.stage-icon.adult::before {
left: 1px;
transform: rotate(-18deg);
}
.stage-icon.adult::after {
right: 1px;
transform: rotate(18deg) scaleX(-1);
}
.completion {
position: absolute;
inset: 0;
z-index: 20;
display: grid;
place-items: center;
padding: 20px;
background: rgba(20,57,47,.45);
backdrop-filter: blur(8px);
opacity: 0;
pointer-events: none;
transition: opacity .3s ease;
}
.completion.show {
opacity: 1;
pointer-events: auto;
}
.completion-card {
width: min(490px, 100%);
padding: 28px;
text-align: center;
background: var(--cream);
border: 1px solid rgba(255,255,255,.9);
border-radius: 25px;
box-shadow: 0 25px 70px rgba(15,48,39,.28);
transform: translateY(12px) scale(.98);
transition: transform .3s ease;
}
.completion.show .completion-card {
transform: translateY(0) scale(1);
}
.completion-butterfly {
position: relative;
width: 76px;
height: 65px;
margin: 0 auto 12px;
}
.completion-butterfly::before,
.completion-butterfly::after {
content: "";
position: absolute;
top: 3px;
width: 38px;
height: 54px;
background: linear-gradient(135deg, #ffd166, #f18a32);
border: 4px solid #284c3f;
border-radius: 70% 70% 46% 46%;
}
.completion-butterfly::before {
left: 0;
transform: rotate(-12deg);
}
.completion-butterfly::after {
right: 0;
transform: rotate(12deg) scaleX(-1);
}
.completion h2 {
margin: 0;
font-size: 28px;
letter-spacing: -.7px;
}
.completion p {
margin: 9px auto 17px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.completion-stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin-bottom: 18px;
}
.completion-stat {
padding: 12px 6px;
background: #eef4e9;
border-radius: 12px;
}
.completion-stat strong {
display: block;
font-size: 19px;
}
.completion-stat span {
color: var(--muted);
font-size: 9px;
text-transform: uppercase;
letter-spacing: .8px;
}
.primary-button {
padding: 11px 18px;
color: white;
background: var(--green);
border: 0;
border-radius: 11px;
cursor: pointer;
font-weight: 800;
font-size: 12px;
}
.primary-button:hover {
background: var(--green-dark);
}
@media (max-width: 980px) {
main {
grid-template-columns: 250px minmax(0, 1fr);
}
aside {
padding: 14px;
}
.tray {
grid-template-columns: 115px 1fr;
}
.stage-button {
grid-template-columns: 30px 1fr;
gap: 4px;
padding: 7px;
}
.stage-icon {
transform: scale(.82);
}
}
@media (max-width: 760px) {
body {
overflow: auto;
}
.app {
height: auto;
min-height: 100dvh;
grid-template-rows: 64px auto;
}
header {
padding: 0 13px;
}
.header-progress {
min-width: 0;
}
.progress-track,
.progress-copy span,
.brand p {
display: none;
}
main {
display: grid;
grid-template-columns: 1fr;
}
aside {
max-height: 225px;
border-right: 0;
border-bottom: 1px solid var(--line);
}
.instructions,
.resource-section {
display: none;
}
.species-list {
grid-template-columns: repeat(3, minmax(190px, 1fr));
overflow-x: auto;
padding-bottom: 5px;
}
.species-card {
min-width: 190px;
}
.play-area {
height: calc(100dvh - 289px);
min-height: 570px;
grid-template-rows: minmax(0, 1fr) 122px;
}
.scene-hud {
max-width: calc(100% - 150px);
}
.scene-hud p {
display: none;
}
.tray {
grid-template-columns: 1fr;
gap: 7px;
padding: 9px;
}
.tray-title {
display: flex;
align-items: center;
justify-content: space-between;
}
.tray-title p {
display: none;
}
.stage-buttons {
gap: 5px;
}
.stage-button {
display: flex;
flex-direction: column;
justify-content: center;
gap: 1px;
min-height: 70px;
text-align: center;
}
.stage-button small {
display: none;
}
.stage-icon {
width: 27px;
height: 27px;
transform: scale(.72);
margin-top: -4px;
}
.legend {
display: none;
}
}
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>Flutter Lab</h1>
<p>Host plant life-cycle puzzle</p>
</div>
</div>
<div class="header-progress">
<div class="progress-copy">
<strong id="progressText">0 / 12 matched</strong>
<span id="statsText">0 mistakes · 00:00</span>
</div>
<div class="progress-track" aria-label="Puzzle progress">
<div class="progress-fill" id="progressFill"></div>
</div>
</div>
</header>
<main>
<aside>
<section class="instructions">
<p class="eyebrow">Field assignment</p>
<h2>Build three life cycles</h2>
<p>
Each habitat contains a host plant. Choose a butterfly stage,
then place that stage on the matching pedestal in every habitat.
The plants determine which species belongs there.
</p>
<div class="mini-steps">
<div class="mini-step"><b>1</b> Select a stage in the field kit.</div>
<div class="mini-step"><b>2</b> Click its glowing pedestal.</div>
<div class="mini-step"><b>3</b> Repeat for all three habitats.</div>
</div>
</section>
<section>
<div class="section-title">
<h3>Host plant field guide</h3>
<span>Click to focus</span>
</div>
<div class="species-list">
<button class="species-card" data-species="0" type="button">
<div class="species-name">
<span class="species-dot" style="background:#f39a3d"></span>
Monarch
</div>
<div class="species-scientific">Danaus plexippus</div>
<div class="species-meta">
<strong>Host</strong><span>Common milkweed</span>
<strong>Larva</strong><span>Milkweed foliage</span>
<strong>Adult</strong><span>Floral nectar</span>
<strong>Patch</strong><span>A</span>
</div>
</button>
<button class="species-card" data-species="1" type="button">
<div class="species-name">
<span class="species-dot" style="background:#d5748b"></span>
Painted lady
</div>
<div class="species-scientific">Vanessa cardui</div>
<div class="species-meta">
<strong>Host</strong><span>Thistle</span>
<strong>Larva</strong><span>Thistle leaves</span>
<strong>Adult</strong><span>Floral nectar</span>
<strong>Patch</strong><span>B</span>
</div>
</button>
<button class="species-card" data-species="2" type="button">
<div class="species-name">
<span class="species-dot" style="background:#e8c743"></span>
Citrus swallowtail
</div>
<div class="species-scientific">Papilio demoleus</div>
<div class="species-meta">
<strong>Host</strong><span>Citrus tree</span>
<strong>Larva</strong><span>Citrus foliage</span>
<strong>Adult</strong><span>Floral nectar</span>
<strong>Patch</strong><span>C</span>
</div>
</button>
</div>
</section>
<section class="resource-section">
<div class="section-title">
<h3>Life-cycle resources</h3>
<span>All four stages</span>
</div>
<div class="resource-list">
<div class="resource">
<b>Egg</b><span>Host leaf</span>
</div>
<div class="resource">
<b>Larva</b><span>Host foliage</span>
</div>
<div class="resource">
<b>Pupa</b><span>Safe site</span>
</div>
<div class="resource">
<b>Adult</b><span>Nectar</span>
</div>
</div>
</section>
</aside>
<section class="play-area">
<div id="viewport">
<div class="scene-hud">
<div class="pill" id="currentStagePill">Selected: EGG</div>
<p>Click a glowing pedestal. Drag to orbit and scroll to zoom.</p>
</div>
<div class="view-tools">
<button class="tool-button" id="zoomOut" type="button" aria-label="Zoom out">−</button>
<button class="tool-button" id="zoomIn" type="button" aria-label="Zoom in">+</button>
<button class="tool-button" id="homeView" type="button">Show all</button>
</div>
<div class="legend">
<div class="legend-item">
<span class="legend-swatch" style="background:#f39a3d"></span>
Selected stage
</div>
<div class="legend-item">
<span class="legend-swatch" style="background:#54b987"></span>
Correctly matched
</div>
<div class="legend-item">
<span class="legend-swatch" style="background:#63b8d1"></span>
Hint
</div>
</div>
<div id="toast" role="status" aria-live="polite"></div>
<div class="completion" id="completion">
<div class="completion-card">
<div class="completion-butterfly" aria-hidden="true"></div>
<p class="eyebrow">Field assignment complete</p>
<h2>Every habitat now has a life cycle!</h2>
<p>
Monarch → milkweed, Painted lady → thistle, and Citrus
swallowtail → citrus. Eggs and larvae depend on their host
plants; adults gain energy from nectar.
</p>
<div class="completion-stats">
<div class="completion-stat">
<strong id="finalTime">00:00</strong>
<span>Time</span>
</div>
<div class="completion-stat">
<strong id="finalAccuracy">100%</strong>
<span>Accuracy</span>
</div>
<div class="completion-stat">
<strong>12</strong>
<span>Stages</span>
</div>
</div>
<button class="primary-button" id="playAgain" type="button">
Play again
</button>
</div>
</div>
</div>
<div class="tray">
<div class="tray-title">
<div>
<p class="eyebrow">Field kit</p>
<h3>Choose a life stage</h3>
</div>
<p>Keys 1–4 select stages.<br>H gives a hint.</p>
</div>
<div class="stage-buttons" id="stageButtons">
<button class="stage-button selected" data-stage="0" type="button">
<span class="stage-icon egg" aria-hidden="true"></span>
<span>
<b>Egg</b>
<small>On a host leaf</small>
</span>
<span class="stage-count">0/3</span>
</button>
<button class="stage-button" data-stage="1" type="button">
<span class="stage-icon larva" aria-hidden="true"></span>
<span>
<b>Larva</b>
<small>Eat host foliage</small>
</span>
<span class="stage-count">0/3</span>
</button>
<button class="stage-button" data-stage="2" type="button">
<span class="stage-icon pupa" aria-hidden="true"></span>
<span>
<b>Chrysalis</b>
<small>Pupate nearby</small>
</span>
<span class="stage-count">0/3</span>
</button>
<button class="stage-button" data-stage="3" type="button">
<span class="stage-icon adult" aria-hidden="true"></span>
<span>
<b>Adult</b>
<small>Drink nectar</small>
</span>
<span class="stage-count">0/3</span>
</button>
</div>
</div>
</section>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Puzzle data
// -------------------------------------------------------------------------
const species = [
{
name: "Monarch",
scientific: "Danaus plexippus",
host: "Common milkweed",
patch: "A",
color: 0xf39a3d,
insect: 0xf0a13b
},
{
name: "Painted lady",
scientific: "Vanessa cardui",
host: "Thistle",
patch: "B",
color: 0xd5748b,
insect: 0x87a85b
},
{
name: "Citrus swallowtail",
scientific: "Papilio demoleus",
host: "Citrus tree",
patch: "C",
color: 0xe8c743,
insect: 0x86b35b
}
];
const stages = [
{ name: "Egg", resource: "On a host leaf" },
{ name: "Larva", resource: "Eat host foliage" },
{ name: "Chrysalis", resource: "Pupate nearby" },
{ name: "Adult", resource: "Drink nectar" }
];
const stageButtons = [...document.querySelectorAll(".stage-button")];
const speciesButtons = [...document.querySelectorAll(".species-card")];
const viewport = document.getElementById("viewport");
const toastElement = document.getElementById("toast");
const progressText = document.getElementById("progressText");
const progressFill = document.getElementById("progressFill");
const statsText = document.getElementById("statsText");
const currentStagePill = document.getElementById("currentStagePill");
const completion = document.getElementById("completion");
let selectedStage = 0;
let selectedSpecies = -1;
let matched = 0;
let mistakes = 0;
let hintSlot = null;
let hoveredSlot = null;
let toastTimer = 0;
let startTime = performance.now();
let finalTime = 0;
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdcece4);
scene.fog = new THREE.Fog(0xdcece4, 14, 27);
const camera = new THREE.PerspectiveCamera(
42,
viewport.clientWidth / viewport.clientHeight,
0.1,
80
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(viewport.clientWidth, viewport.clientHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
viewport.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xf5fff7, 0x7d8b68, 2.35);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff3cf, 3.2);
sun.position.set(-5, 10, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -10;
sun.shadow.camera.right = 10;
sun.shadow.camera.top = 8;
sun.shadow.camera.bottom = -8;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 25;
sun.shadow.bias = -0.0005;
scene.add(sun);
const fillLight = new THREE.DirectionalLight(0xb9ddff, 0.75);
fillLight.position.set(7, 5, -6);
scene.add(fillLight);
// Ground and a subtle central garden mat.
const ground = new THREE.Mesh(
new THREE.CircleGeometry(15, 48),
standardMaterial(0xd8e5d5, { roughness: 1 })
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.18;
ground.receiveShadow = true;
scene.add(ground);
const gardenMat = new THREE.Mesh(
new THREE.CircleGeometry(6.4, 48),
standardMaterial(0xc7d9bd, { roughness: 1 })
);
gardenMat.rotation.x = -Math.PI / 2;
gardenMat.position.y = -0.165;
gardenMat.receiveShadow = true;
scene.add(gardenMat);
// Decorative stones and flowers around the garden.
const decorGroup = new THREE.Group();
scene.add(decorGroup);
const stoneMaterial = standardMaterial(0xb8b3a2, { roughness: 1 });
const flowerStemMaterial = standardMaterial(0x4d8c55);
const flowerColors = [0xf7d15e, 0xe98286, 0xa895d8, 0xf3a14d];
for (let i = 0; i < 24; i++) {
const angle = (i / 24) * Math.PI * 2;
const radius = 6.05 + (i % 3) * 0.12;
const x = Math.cos(angle) * radius;
const z = Math.sin(angle) * radius;
if (i % 3 === 0) {
const stem = new THREE.Mesh(
new THREE.CylinderGeometry(0.018, 0.025, 0.24, 5),
flowerStemMaterial
);
stem.position.set(x, -0.03, z);
decorGroup.add(stem);
for (let p = 0; p < 5; p++) {
const petal = new THREE.Mesh(
new THREE.SphereGeometry(0.065, 5, 3),
standardMaterial(flowerColors[i % flowerColors.length])
);
const a = (p / 5) * Math.PI * 2;
petal.scale.set(1, 0.45, 1.35);
petal.position.set(
x + Math.cos(a) * 0.07,
0.11,
z + Math.sin(a) * 0.07
);
petal.rotation.y = -a;
decorGroup.add(petal);
}
} else {
const stone = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.075 + (i % 2) * 0.025, 0),
stoneMaterial
);
stone.scale.set(1.3, 0.65, 1);
stone.position.set(x, -0.105, z);
stone.rotation.set(i * 0.37, i * 0.61, i * 0.24);
decorGroup.add(stone);
}
}
const habitats = [];
const slots = [];
const hitMeshes = [];
const habitatX = [-3.35, 0, 3.35];
for (let h = 0; h < species.length; h++) {
const habitat = new THREE.Group();
habitat.position.x = habitatX[h];
scene.add(habitat);
const island = new THREE.Mesh(
new THREE.CylinderGeometry(1.28, 1.38, 0.3, 12),
standardMaterial(h === 0 ? 0xc4cf9b : h === 1 ? 0xc8c4a4 : 0xc4c99f)
);
island.position.y = 0;
island.castShadow = true;
island.receiveShadow = true;
habitat.add(island);
const soil = new THREE.Mesh(
new THREE.CylinderGeometry(1.17, 1.2, 0.08, 12),
standardMaterial(0x8d7053, { roughness: 1 })
);
soil.position.y = 0.18;
soil.receiveShadow = true;
habitat.add(soil);
const borderMaterial = standardMaterial(species[h].color, {
emissive: species[h].color,
emissiveIntensity: 0.08
});
const border = new THREE.Mesh(
new THREE.TorusGeometry(1.29, 0.035, 6, 32),
borderMaterial
);
border.rotation.x = Math.PI / 2;
border.position.y = 0.16;
habitat.add(border);
const plant = createHostPlant(h);
plant.position.set(0, 0.2, -0.52);
habitat.add(plant);
const title = makeTextSprite(
`${species[h].patch} ${species[h].host.toUpperCase()}`,
"#173f35",
"#fffdf5",
640,
112,
42
);
title.position.set(0, 2.05, -0.42);
title.scale.set(1.65, 0.29, 1);
habitat.add(title);
const subTitle = makeTextSprite(
species[h].name,
"#49665e",
"#edf4e9",
460,
88,
36
);
subTitle.position.set(0, 1.79, -0.42);
subTitle.scale.set(1.38, 0.24, 1);
habitat.add(subTitle);
const habitatRecord = {
group: habitat,
border,
borderMaterial,
title,
subTitle,
plant
};
habitats.push(habitatRecord);
const stagePositions = [
[-0.43, 0.31],
[0.43, 0.31],
[-0.43, 0.83],
[0.43, 0.83]
];
for (let s = 0; s < stages.length; s++) {
const slotGroup = new THREE.Group();
slotGroup.position.set(stagePositions[s][0], 0.22, stagePositions[s][1]);
habitat.add(slotGroup);
const base = new THREE.Mesh(
new THREE.CylinderGeometry(0.33, 0.36, 0.07, 10),
standardMaterial(0xe8e3c9, { roughness: .9 })
);
base.position.y = 0;
base.castShadow = true;
base.receiveShadow = true;
slotGroup.add(base);
const ringMaterial = standardMaterial(0xd8d8c9, {
emissive: 0x000000,
emissiveIntensity: 0
});
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.315, 0.038, 6, 24),
ringMaterial
);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.055;
ring.castShadow = true;
slotGroup.add(ring);
const hitMaterial = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false
});
const hit = new THREE.Mesh(
new THREE.CylinderGeometry(0.38, 0.38, 0.62, 10),
hitMaterial
);
hit.position.y = 0.28;
hit.userData.slotIndex = slots.length;
slotGroup.add(hit);
hitMeshes.push(hit);
const label = makeTextSprite(
stages[s].name.toUpperCase(),
"#49665e",
"#f7f4e9",
320,
72,
28
);
label.position.set(0, -0.015, 0.33);
label.scale.set(0.53, 0.12, 1);
slotGroup.add(label);
const slot = {
group: slotGroup,
ring,
ringMaterial,
label,
habitatIndex: h,
stageIndex: s,
placed: false,
model: null
};
slots.push(slot);
}
}
// -------------------------------------------------------------------------
// Materials and geometry helpers
// -------------------------------------------------------------------------
function standardMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: .82,
metalness: 0,
flatShading: true,
...options
});
}
function cylinderBetween(a, b, radius, material, radialSegments = 6) {
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius, length, radialSegments),
material
);
mesh.position.copy(a).add(b).multiplyScalar(.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.clone().normalize()
);
mesh.castShadow = true;
return mesh;
}
function makeTextSprite(text, textColor, background, width = 512, height = 112, radius = 28) {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const context = canvas.getContext("2d");
context.clearRect(0, 0, width, height);
roundedRect(
context,
4,
4,
width - 8,
height - 8,
radius
);
context.fillStyle = background;
context.fill();
context.strokeStyle = "rgba(23,63,53,.13)";
context.lineWidth = 5;
context.stroke();
context.fillStyle = textColor;
context.font = `800 ${Math.floor(height * .38)}px Trebuchet MS, sans-serif`;
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, width / 2, height / 2 + 2, width - 30);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.renderOrder = 20;
return sprite;
}
function roundedRect(context, x, y, width, height, radius) {
radius = Math.min(radius, width / 2, height / 2);
context.beginPath();
context.moveTo(x + radius, y);
context.lineTo(x + width - radius, y);
context.quadraticCurveTo(x + width, y, x + width, y + radius);
context.lineTo(x + width, y + height - radius);
context.quadraticCurveTo(
x + width,
y + height,
x + width - radius,
y + height
);
context.lineTo(x + radius, y + height);
context.quadraticCurveTo(x, y + height, x, y + height - radius);
context.lineTo(x, y + radius);
context.quadraticCurveTo(x, y, x + radius, y);
context.closePath();
}
function addLeaf(parent, material, position, scale, rotation = [0, 0, 0]) {
const leaf = new THREE.Mesh(
new THREE.SphereGeometry(0.5, 7, 4),
material
);
leaf.position.set(...position);
leaf.scale.set(...scale);
leaf.rotation.set(...rotation);
leaf.castShadow = true;
parent.add(leaf);
return leaf;
}
// -------------------------------------------------------------------------
// Host plant models
// -------------------------------------------------------------------------
function createHostPlant(type) {
if (type === 0) return createMilkweed();
if (type === 1) return createThistle();
return createCitrus();
}
function createMilkweed() {
const group = new THREE.Group();
const stemMat = standardMaterial(0x4f8b4c);
const leafMat = standardMaterial(0x5c9b52);
const flowerMat = standardMaterial(0xe981a1);
const centerMat = standardMaterial(0xf4bd49);
const stem = new THREE.Mesh(
new THREE.CylinderGeometry(.025, .04, 1.22, 7),
stemMat
);
stem.position.y = .61;
stem.castShadow = true;
group.add(stem);
const leafData = [
[-.22, .35, 0, -.1, .2],
[.22, .45, 0, .08, -.25],
[-.25, .68, 0, -.2, .08],
[.24, .78, 0, .12, .24],
[-.18, 1.01, 0, -.13, -.08]
];
for (const [x, y, z, rx, rz] of leafData) {
addLeaf(
group,
leafMat,
[x, y, z],
[.15, .045, .34],
[rx, 0, rz]
);
}
for (let i = 0; i < 6; i++) {
const angle = (i / 6) * Math.PI * 2;
const petal = new THREE.Mesh(
new THREE.SphereGeometry(.095, 6, 4),
flowerMat
);
petal.position.set(
Math.cos(angle) * .105,
1.23 + (i % 2) * .015,
Math.sin(angle) * .105
);
petal.scale.set(1, .55, 1);
petal.castShadow = true;
group.add(petal);
}
const center = new THREE.Mesh(
new THREE.SphereGeometry(.08, 7, 4),
centerMat
);
center.position.y = 1.26;
group.add(center);
return group;
}
function createThistle() {
const group = new THREE.Group();
const stemMat = standardMaterial(0x5a8d52);
const leafMat = standardMaterial(0x47784b);
const darkLeafMat = standardMaterial(0x3e6b48);
const flowerMat = standardMaterial(0x9b6eb0);
const spikeMat = standardMaterial(0x744f87);
const base = new THREE.Mesh(
new THREE.SphereGeometry(.28, 8, 5),
leafMat
);
base.scale.set(1.15, .45, 1.05);
base.position.y = .12;
base.castShadow = true;
group.add(base);
for (let i = 0; i < 9; i++) {
const angle = (i / 9) * Math.PI * 2;
const leaf = new THREE.Mesh(
new THREE.ConeGeometry(.11, .43, 4),
i % 2 ? leafMat : darkLeafMat
);
leaf.position.set(
Math.cos(angle) * .22,
.23,
Math.sin(angle) * .22
);
leaf.rotation.z = Math.PI / 2.5;
leaf.rotation.y = -angle;
leaf.castShadow = true;
group.add(leaf);
}
const stem = new THREE.Mesh(
new THREE.CylinderGeometry(.025, .035, .92, 7),
stemMat
);
stem.position.y = .58;
stem.castShadow = true;
group.add(stem);
for (let i = 0; i < 3; i++) {
const angle = i * 2.15;
const x = Math.cos(angle) * .16;
const z = Math.sin(angle) * .12;
const y = .82 + i * .1;
const branch = cylinderBetween(
new THREE.Vector3(0, y - .3, 0),
new THREE.Vector3(x, y, z),
.018,
stemMat,
5
);
group.add(branch);
const head = new THREE.Mesh(
new THREE.SphereGeometry(.15, 8, 5),
flowerMat
);
head.scale.set(1, 1.3, 1);
head.position.set(x, y + .07, z);
head.castShadow = true;
group.add(head);
for (let p = 0; p < 7; p++) {
const a = (p / 7) * Math.PI * 2;
const spike = new THREE.Mesh(
new THREE.ConeGeometry(.024, .12, 5),
spikeMat
);
spike.position.set(
x + Math.cos(a) * .095,
y + .15,
z + Math.sin(a) * .095
);
spike.rotation.z = Math.cos(a) * .32;
spike.rotation.x = Math.sin(a) * .32;
group.add(spike);
}
}
return group;
}
function createCitrus() {
const group = new THREE.Group();
const trunkMat = standardMaterial(0x806345);
const leafMat = standardMaterial(0x3f7f46);
const leafLightMat = standardMaterial(0x5c994d);
const fruitMat = standardMaterial(0xf39a35);
const fruitLeafMat = standardMaterial(0x438747);
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(.07, .12, .88, 8),
trunkMat
);
trunk.position.y = .44;
trunk.castShadow = true;
group.add(trunk);
const branchEnds = [
new THREE.Vector3(-.35, 1.02, -.02),
new THREE.Vector3(.36, 1.08, .03),
new THREE.Vector3(.02, 1.25, -.04)
];
for (const end of branchEnds) {
group.add(
cylinderBetween(
new THREE.Vector3(0, .65, 0),
end,
.035,
trunkMat,
6
)
);
}
const crowns = [
[-.33, 1.13, -.03, .3],
[.34, 1.18, .03, .31],
[.02, 1.37, -.02, .34],
[-.08, 1.02, .22, .27]
];
crowns.forEach(([x, y, z, size], index) => {
const crown = new THREE.Mesh(
new THREE.DodecahedronGeometry(size, 0),
index % 2 ? leafMat : leafLightMat
);
crown.position.set(x, y, z);
crown.scale.set(1.15, .9, 1);
crown.castShadow = true;
group.add(crown);
});
const fruitPositions = [
[-.45, .93, .12],
[.34, .9, .16],
[.13, 1.21, .19],
[-.17, 1.38, .16]
];
fruitPositions.forEach(([x, y, z]) => {
const fruit = new THREE.Mesh(
new THREE.SphereGeometry(.105, 8, 6),
fruitMat
);
fruit.position.set(x, y, z);
fruit.scale.set(1, .92, 1);
fruit.castShadow = true;
group.add(fruit);
const fruitLeaf = addLeaf(
group,
fruitLeafMat,
[x + .06, y + .11, z],
[.045, .018, .1],
[0, .4, -.5]
);
fruitLeaf.castShadow = true;
});
return group;
}
// -------------------------------------------------------------------------
// Butterfly stage models
// -------------------------------------------------------------------------
function createStageModel(speciesIndex, stageIndex) {
if (stageIndex === 0) return createEggModel(speciesIndex);
if (stageIndex === 1) return createLarvaModel(speciesIndex);
if (stageIndex === 2) return createPupaModel(speciesIndex);
return createAdultModel(speciesIndex);
}
function createEggModel(speciesIndex) {
const group = new THREE.Group();
const leafMat = standardMaterial(0x5c984e);
addLeaf(
group,
leafMat,
[0, .02, 0],
[.13, .025, .22],
[0, .18, -.08]
);
const eggColors = [0xf4e5ad, 0xd8df9a, 0xf1d35f];
const egg = new THREE.Mesh(
new THREE.SphereGeometry(.08, 9, 7),
standardMaterial(eggColors[speciesIndex])
);
egg.scale.set(.82, 1.25, .82);
egg.position.set(.015, .105, .01);
egg.castShadow = true;
group.add(egg);
if (speciesIndex === 0) {
for (let i = 0; i < 4; i++) {
const ridge = new THREE.Mesh(
new THREE.TorusGeometry(.025, .006, 4, 10),
standardMaterial(0xc6a95c)
);
ridge.rotation.x = Math.PI / 2;
ridge.position.set(.015, .11 + (i - 1.5) * .016, .01);
group.add(ridge);
}
}
return group;
}
function createLarvaModel(speciesIndex) {
const group = new THREE.Group();
const leafMat = standardMaterial(0x5d984f);
addLeaf(
group,
leafMat,
[0, .015, 0],
[.2, .025, .29],
[0, -.15, 0]
);
const bodyColors = [0xf1b348, 0x8fa65a, 0x88b15c];
const segmentCount = speciesIndex === 1 ? 6 : 5;
for (let i = 0; i < segmentCount; i++) {
const t = i / (segmentCount - 1);
const segment = new THREE.Mesh(
new THREE.SphereGeometry(.115 - t * .025, 8, 6),
standardMaterial(bodyColors[speciesIndex])
);
segment.position.set(
(t - .5) * .52,
.115 + Math.sin(t * Math.PI) * .015,
0
);
segment.scale.set(1.08, .82, .82);
segment.castShadow = true;
group.add(segment);
if (speciesIndex === 0) {
const band = new THREE.Mesh(
new THREE.TorusGeometry(.087 - t * .02, .018, 5, 12),
standardMaterial(0x263c34)
);
band.rotation.y = Math.PI / 2;
band.position.copy(segment.position);
group.add(band);
}
if (speciesIndex === 1) {
for (let spikeIndex = 0; spikeIndex < 3; spikeIndex++) {
const spike = new THREE.Mesh(
new THREE.ConeGeometry(.014, .065, 4),
standardMaterial(0xc6ad61)
);
const a = spikeIndex * 2.1;
spike.position.set(
segment.position.x,
.18,
segment.position.z + Math.cos(a) * .085
);
spike.rotation.x = Math.sin(a) * .55;
spike.rotation.z = Math.cos(a) * .55;
group.add(spike);
}
}
if (speciesIndex === 2 && i < 4) {
const spot = new THREE.Mesh(
new THREE.SphereGeometry(.018, 6, 4),
standardMaterial(0xe9e6c6)
);
spot.position.set(
segment.position.x,
.19,
segment.position.z
);
group.add(spot);
}
}
const eye = new THREE.Mesh(
new THREE.SphereGeometry(.027, 7, 5),
standardMaterial(0x20372f)
);
eye.position.set(.285, .13, .055);
group.add(eye);
return group;
}
function createPupaModel(speciesIndex) {
const group = new THREE.Group();
const twig = new THREE.Mesh(
new THREE.CylinderGeometry(.018, .022, .54, 6),
standardMaterial(0x806046)
);
twig.rotation.z = Math.PI / 2;
twig.position.y = .31;
twig.castShadow = true;
group.add(twig);
const colors = [0x7ca552, 0x8f7652, 0x8b7350];
const chrysalis = new THREE.Mesh(
new THREE.SphereGeometry(.16, 9, 7),
standardMaterial(colors[speciesIndex])
);
chrysalis.scale.set(.8, 1.85, .72);
chrysalis.position.y = .15;
chrysalis.castShadow = true;
group.add(chrysalis);
const tip = new THREE.Mesh(
new THREE.ConeGeometry(.065, .12, 7),
standardMaterial(colors[speciesIndex])
);
tip.position.y = .01;
tip.rotation.z = Math.PI;
group.add(tip);
if (speciesIndex === 0) {
for (let i = 0; i < 7; i++) {
const dot = new THREE.Mesh(
new THREE.SphereGeometry(.012, 5, 4),
standardMaterial(0xe9c85b)
);
dot.position.set(
Math.sin(i * 1.7) * .095,
.06 + i * .038,
.11
);
group.add(dot);
}
} else {
for (let i = 0; i < 4; i++) {
const stripe = new THREE.Mesh(
new THREE.TorusGeometry(.103, .008, 4, 12),
standardMaterial(speciesIndex === 1 ? 0x68513e : 0x5c4c3d)
);
stripe.rotation.x = Math.PI / 2;
stripe.scale.y = 1;
stripe.position.y = .07 + i * .06;
group.add(stripe);
}
}
return group;
}
function createAdultModel(speciesIndex) {
const group = new THREE.Group();
const palettes = [
{ base: 0x243b35, upper: 0xf39a3d, lower: 0xe98737 },
{ base: 0x2b3536, upper: 0xe18a52, lower: 0xc97778 },
{ base: 0x263b36, upper: 0xe9cf49, lower: 0xe3c343 }
];
const palette = palettes[speciesIndex];
const darkMat = standardMaterial(palette.base);
const upperMat = standardMaterial(palette.upper);
const lowerMat = standardMaterial(palette.lower);
const body = new THREE.Mesh(
new THREE.CylinderGeometry(.033, .025, .38, 8),
darkMat
);
body.position.y = .26;
body.castShadow = true;
group.add(body);
const head = new THREE.Mesh(
new THREE.SphereGeometry(.058, 8, 6),
darkMat
);
head.position.y = .48;
group.add(head);
const upperShape = createUpperWingShape();
const lowerShape = createLowerWingShape();
const rightUpper = new THREE.Mesh(
new THREE.ShapeGeometry(upperShape, 2),
darkMat
);
rightUpper.position.set(.015, .35, 0);
group.add(rightUpper);
const rightLower = new THREE.Mesh(
new THREE.ShapeGeometry(lowerShape, 2),
darkMat
);
rightLower.position.set(.015, .11, -.006);
group.add(rightLower);
const leftUpper = new THREE.Mesh(
new THREE.ShapeGeometry(upperShape, 2),
darkMat
);
leftUpper.position.set(-.015, .35, 0);
leftUpper.scale.x = -1;
group.add(leftUpper);
const leftLower = new THREE.Mesh(
new THREE.ShapeGeometry(lowerShape, 2),
darkMat
);
leftLower.position.set(-.015, .11, -.006);
leftLower.scale.x = -1;
group.add(leftLower);
const rightUpperColor = new THREE.Mesh(
new THREE.ShapeGeometry(upperShape, 2),
upperMat
);
rightUpperColor.position.set(.022, .36, .012);
rightUpperColor.scale.set(.78, .78, 1);
group.add(rightUpperColor);
const rightLowerColor = new THREE.Mesh(
new THREE.ShapeGeometry(lowerShape, 2),
lowerMat
);
rightLowerColor.position.set(.022, .115, .01);
rightLowerColor.scale.set(.78, .78, 1);
group.add(rightLowerColor);
const leftUpperColor = new THREE.Mesh(
new THREE.ShapeGeometry(upperShape, 2),
upperMat
);
leftUpperColor.position.set(-.022, .36, .012);
leftUpperColor.scale.set(-.78, .78, 1);
group.add(leftUpperColor);
const leftLowerColor = new THREE.Mesh(
new THREE.ShapeGeometry(lowerShape, 2),
lowerMat
);
leftLowerColor.position.set(-.022, .115, .01);
leftLowerColor.scale.set(-.78, .78, 1);
group.add(leftLowerColor);
// White marginal spots for monarch-like wings.
if (speciesIndex === 0) {
const whiteMat = standardMaterial(0xfff8df);
const positions = [
[.42, .73], [.5, .59], [.39, .48],
[.31, .18], [.22, .12]
];
for (const [x, y] of positions) {
const spot = new THREE.Mesh(
new THREE.SphereGeometry(.018, 6, 4),
whiteMat
);
spot.position.set(x, y, .03);
group.add(spot);
const leftSpot = spot.clone();
leftSpot.position.x = -x;
group.add(leftSpot);
}
}
// Painted lady has blue-gray spots on the lower wings.
if (speciesIndex === 1) {
const blueMat = standardMaterial(0x718895);
for (const [x, y] of [[.25, .2], [.36, .25], [.2, .14]]) {
const spot = new THREE.Mesh(
new THREE.SphereGeometry(.02, 6, 4),
blueMat
);
spot.position.set(x, y, .034);
group.add(spot);
}
}
// Swallowtail wing stripes.
if (speciesIndex === 2) {
const stripeMat = standardMaterial(0x283a35);
for (let i = 0; i < 3; i++) {
const stripe = new THREE.Mesh(
new THREE.BoxGeometry(.018, .35, .012),
stripeMat
);
stripe.position.set(.23 + i * .11, .55, .026);
stripe.rotation.z = -.2;
group.add(stripe);
const leftStripe = stripe.clone();
leftStripe.position.x *= -1;
leftStripe.rotation.z = .2;
group.add(leftStripe);
}
}
const antennaMaterial = new THREE.LineBasicMaterial({
color: 0x263b35
});
for (const direction of [-1, 1]) {
const points = [
new THREE.Vector3(direction * .018, .52, 0),
new THREE.Vector3(direction * .075, .62, .01),
new THREE.Vector3(direction * .12, .65, .02)
];
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const antenna = new THREE.Line(geometry, antennaMaterial);
group.add(antenna);
}
// A tiny nectar flower beneath the adult.
const stem = new THREE.Mesh(
new THREE.CylinderGeometry(.012, .016, .24, 5),
standardMaterial(0x4f8b4c)
);
stem.position.y = .1;
group.add(stem);
const blossom = new THREE.Mesh(
new THREE.SphereGeometry(.055, 7, 4),
standardMaterial(speciesIndex === 0 ? 0xf0bd4d : 0xdd82a0)
);
blossom.scale.set(1, .45, 1);
blossom.position.y = .23;
group.add(blossom);
group.userData.rightUpper = rightUpper;
group.userData.leftUpper = leftUpper;
group.userData.rightLower = rightLower;
group.userData.leftLower = leftLower;
return group;
}
function createUpperWingShape() {
const shape = new THREE.Shape();
shape.moveTo(0, .08);
shape.bezierCurveTo(.12, .18, .38, .28, .55, .53);
shape.bezierCurveTo(.62, .64, .54, .77, .42, .82);
shape.bezierCurveTo(.25, .87, .09, .68, 0, .48);
shape.closePath();
return shape;
}
function createLowerWingShape() {
const shape = new THREE.Shape();
shape.moveTo(0, .13);
shape.bezierCurveTo(.11, .06, .31, -.02, .41, .06);
shape.bezierCurveTo(.47, .11, .38, .29, .27, .35);
shape.bezierCurveTo(.14, .39, .04, .3, 0, .22);
shape.closePath();
return shape;
}
// -------------------------------------------------------------------------
// Puzzle interaction and UI
// -------------------------------------------------------------------------
function setStage(index, announce = true) {
selectedStage = index;
currentStagePill.textContent = `Selected: ${stages[index].name.toUpperCase()}`;
stageButtons.forEach((button, i) => {
button.classList.toggle("selected", i === index);
button.setAttribute("aria-pressed", i === index ? "true" : "false");
});
refreshSlots();
if (announce) {
showToast(
`${stages[index].name} selected. ${stages[index].resource}. Place it on each glowing pedestal.`
);
}
}
function refreshSlots() {
slots.forEach((slot) => {
const isSelected = slot.stageIndex === selectedStage;
const isHovered = hoveredSlot === slot;
const isHint = hintSlot === slot;
if (slot.placed) {
slot.ringMaterial.color.setHex(0x54b987);
slot.ringMaterial.emissive.setHex(0x287451);
slot.ringMaterial.emissiveIntensity = .23;
} else if (isHint) {
slot.ringMaterial.color.setHex(0x63b8d1);
slot.ringMaterial.emissive.setHex(0x287b95);
slot.ringMaterial.emissiveIntensity = .42;
} else if (isSelected) {
slot.ringMaterial.color.setHex(0xf39a3d);
slot.ringMaterial.emissive.setHex(0xa85313);
slot.ringMaterial.emissiveIntensity = .3;
} else if (isHovered) {
slot.ringMaterial.color.setHex(0x8bcf9f);
slot.ringMaterial.emissive.setHex(0x3e8c68);
slot.ringMaterial.emissiveIntensity = .18;
} else {
slot.ringMaterial.color.setHex(0xd8d8c9);
slot.ringMaterial.emissive.setHex(0x000000);
slot.ringMaterial.emissiveIntensity = 0;
}
slot.label.material.opacity = isSelected || slot.placed ? 1 : .52;
});
habitats.forEach((habitat, index) => {
const active = selectedSpecies === index;
habitat.borderMaterial.emissiveIntensity = active ? .42 : .08;
habitat.borderMaterial.color.setHex(
active ? 0xffc15d : species[index].color
);
});
}
function placeStage(slot) {
if (slot.placed) {
showToast(
`${species[slot.habitatIndex].name} — ${stages[slot.stageIndex].name} is already matched here.`,
"success"
);
return;
}
if (slot.stageIndex !== selectedStage) {
mistakes++;
updateStats();
slot.ringMaterial.color.setHex(0xd95f48);
slot.ringMaterial.emissive.setHex(0x9d3027);
slot.ringMaterial.emissiveIntensity = .55;
showToast(
`That pedestal is for ${stages[slot.stageIndex].name.toUpperCase()}. Select ${stages[slot.stageIndex].name.toLowerCase()} in the field kit.`,
"error"
);
window.setTimeout(refreshSlots, 650);
return;
}
const plantSpecies = species[slot.habitatIndex];
const stage = stages[slot.stageIndex];
slot.placed = true;
const model = createStageModel(slot.habitatIndex, slot.stageIndex);
model.position.y = .075;
const scales = [1.2, 1.05, 1.03, .83];
model.scale.setScalar(scales[slot.stageIndex]);
model.userData.spawnTime = performance.now();
slot.model = model;
slot.group.add(model);
matched++;
updateStats();
refreshSlots();
showToast(
`${plantSpecies.name} ${stage.name.toLowerCase()} matched with ${plantSpecies.host}.`,
"success"
);
updateStageCounts();
if (matched === slots.length) {
finishPuzzle();
return;
}
// Once a stage has been placed in all three habitats, advance to the
// next incomplete stage.
const currentStageComplete = slots
.filter(slot => slot.stageIndex === selectedStage)
.every(slot => slot.placed);
if (currentStageComplete) {
const nextStage = stages.findIndex((_, index) =>
slots.some(slot => slot.stageIndex === index && !slot.placed)
);
if (nextStage !== -1) {
window.setTimeout(() => {
setStage(nextStage, false);
showToast(
`Excellent! Now complete the ${stages[nextStage].name.toLowerCase()} stage in all three habitats.`,
"success"
);
}, 850);
}
}
}
function updateStageCounts() {
stageButtons.forEach((button, stageIndex) => {
const count = slots.filter(
slot => slot.stageIndex === stageIndex && slot.placed
).length;
button.querySelector(".stage-count").textContent = `${count}/3`;
button.classList.toggle("complete", count === 3);
});
}
function updateStats() {
progressText.textContent = `${matched} / ${slots.length} matched`;
progressFill.style.width = `${(matched / slots.length) * 100}%`;
const elapsed = finalTime || performance.now() - startTime;
const seconds = Math.floor(elapsed / 1000);
const minutes = Math.floor(seconds / 60);
const formatted = `${String(minutes).padStart(2, "0")}:${String(seconds % 60).padStart(2, "0")}`;
statsText.textContent = `${mistakes} mistake${mistakes === 1 ? "" : "s"} · ${formatted}`;
}
function showToast(message, type = "") {
window.clearTimeout(toastTimer);
toastElement.textContent = message;
toastElement.className = `show ${type}`;
toastTimer = window.setTimeout(() => {
toastElement.className = "";
}, 3100);
}
function giveHint() {
const incomplete = slots.filter(slot => !slot.placed);
if (!incomplete.length) return;
let candidates = incomplete.filter(slot => slot.stageIndex === selectedStage);
if (!candidates.length) candidates = incomplete;
hintSlot = candidates[0];
refreshSlots();
const plantSpecies = species[hintSlot.habitatIndex];
showToast(
`Hint: look for the blue pedestal in Patch ${plantSpecies.patch} (${plantSpecies.host}).`
);
}
function resetPuzzle() {
matched = 0;
mistakes = 0;
hintSlot = null;
hoveredSlot = null;
selectedSpecies = -1;
startTime = performance.now();
finalTime = 0;
slots.forEach(slot => {
slot.placed = false;
if (slot.model) {
slot.group.remove(slot.model);
slot.model = null;
}
});
speciesButtons.forEach(button => button.classList.remove("active"));
completion.classList.remove("show");
setStage(0, false);
updateStageCounts();
updateStats();
showToast("The garden is ready. Begin with the egg stage.");
}
function finishPuzzle() {
finalTime = performance.now() - startTime;
updateStats();
const seconds = Math.floor(finalTime / 1000);
const minutes = Math.floor(seconds / 60);
document.getElementById("finalTime").textContent =
`${String(minutes).padStart(2, "0")}:${String(seconds % 60).padStart(2, "0")}`;
const accuracy = Math.max(
0,
Math.round((slots.length / (slots.length + mistakes)) * 100)
);
document.getElementById("finalAccuracy").textContent = `${accuracy}%`;
window.setTimeout(() => completion.classList.add("show"), 450);
}
stageButtons.forEach(button => {
button.addEventListener("click", () => setStage(Number(button.dataset.stage)));
});
speciesButtons.forEach(button => {
button.addEventListener("click", () => {
const index = Number(button.dataset.species);
selectedSpecies = index;
speciesButtons.forEach((other, i) => {
other.classList.toggle("active", i === index);
});
focusHabitat(index);
refreshSlots();
const plantSpecies = species[index];
showToast(
`${plantSpecies.name}: eggs and larvae depend on ${plantSpecies.host}; adults visit flowers for nectar.`
);
});
});
document.getElementById("zoomIn").addEventListener("click", () => {
cameraGoal.radius = Math.max(7.6, cameraGoal.radius - .8);
});
document.getElementById("zoomOut").addEventListener("click", () => {
cameraGoal.radius = Math.min(16, cameraGoal.radius + .8);
});
document.getElementById("homeView").addEventListener("click", () => {
selectedSpecies = -1;
speciesButtons.forEach(button => button.classList.remove("active"));
cameraGoal.target.set(0, .72, 0);
cameraGoal.radius = 10.8;
refreshSlots();
});
document.getElementById("playAgain").addEventListener("click", resetPuzzle);
window.addEventListener("keydown", event => {
if (event.key >= "1" && event.key <= "4") {
setStage(Number(event.key) - 1);
} else if (event.key.toLowerCase() === "h") {
giveHint();
} else if (event.key.toLowerCase() === "r") {
resetPuzzle();
}
});
// -------------------------------------------------------------------------
// Custom orbit controls and pointer picking
// -------------------------------------------------------------------------
const cameraGoal = {
target: new THREE.Vector3(0, .72, 0),
radius: 10.8,
theta: .035,
phi: 1.07
};
const cameraCurrent = {
target: cameraGoal.target.clone(),
radius: cameraGoal.radius,
theta: cameraGoal.theta,
phi: cameraGoal.phi
};
function focusHabitat(index) {
cameraGoal.target.set(habitatX[index], .78, 0);
cameraGoal.radius = 8.7;
}
function updateCamera() {
cameraCurrent.target.lerp(cameraGoal.target, .08);
cameraCurrent.radius = THREE.MathUtils.lerp(
cameraCurrent.radius,
cameraGoal.radius,
.08
);
cameraCurrent.theta = THREE.MathUtils.lerp(
cameraCurrent.theta,
cameraGoal.theta,
.1
);
cameraCurrent.phi = THREE.MathUtils.lerp(
cameraCurrent.phi,
cameraGoal.phi,
.1
);
const { target, radius, theta, phi } = cameraCurrent;
camera.position.set(
target.x + radius * Math.sin(phi) * Math.sin(theta),
target.y + radius * Math.cos(phi),
target.z + radius * Math.sin(phi) * Math.cos(theta)
);
camera.lookAt(target);
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const pointerDown = new THREE.Vector2();
let dragging = false;
let dragMoved = false;
renderer.domElement.addEventListener("pointerdown", event => {
pointerDown.set(event.clientX, event.clientY);
dragging = true;
dragMoved = false;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (dragging) {
const dx = event.clientX - pointerDown.x;
const dy = event.clientY - pointerDown.y;
if (Math.abs(dx) + Math.abs(dy) > 5) dragMoved = true;
cameraGoal.theta -= dx * .006;
cameraGoal.phi = THREE.MathUtils.clamp(
cameraGoal.phi + dy * .004,
.72,
1.32
);
pointerDown.set(event.clientX, event.clientY);
return;
}
const hit = pickSlot(event);
const newHovered = hit ? slots[hit.object.userData.slotIndex] : null;
if (newHovered !== hoveredSlot) {
hoveredSlot = newHovered;
refreshSlots();
renderer.domElement.style.cursor = hoveredSlot ? "pointer" : "grab";
}
});
renderer.domElement.addEventListener("pointerup", event => {
dragging = false;
if (!dragMoved) {
const hit = pickSlot(event);
if (hit) {
const slot = slots[hit.object.userData.slotIndex];
placeStage(slot);
}
}
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
renderer.domElement.addEventListener("pointerleave", () => {
if (!dragging) {
hoveredSlot = null;
refreshSlots();
}
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraGoal.radius = THREE.MathUtils.clamp(
cameraGoal.radius + event.deltaY * .008,
7.6,
16
);
}, { passive: false });
function pickSlot(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(hitMeshes, false);
return intersections.length ? intersections[0] : null;
}
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
const resizeObserver = new ResizeObserver(() => {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height);
});
resizeObserver.observe(viewport);
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
updateCamera();
slots.forEach(slot => {
const isSelected = slot.stageIndex === selectedStage && !slot.placed;
const pulse = isSelected ? 1 + Math.sin(elapsed * 4) * .055 : 1;
slot.ring.scale.setScalar(pulse);
if (slot.model) {
const age = (performance.now() - slot.model.userData.spawnTime) / 1000;
const spawnScale = age < .4
? .8 + Math.sin((age / .4) * Math.PI) * .2
: 1;
const baseScale = [1.2, 1.05, 1.03, .83][slot.stageIndex];
slot.model.scale.setScalar(baseScale * spawnScale);
if (slot.stageIndex === 3) {
const flap = Math.sin(elapsed * 5 + slot.habitatIndex) * .22;
slot.model.userData.rightUpper.rotation.y = flap;
slot.model.userData.leftUpper.rotation.y = -flap;
slot.model.userData.rightLower.rotation.y = flap * .55;
slot.model.userData.leftLower.rotation.y = -flap * .55;
}
}
});
if (!finalTime) {
const seconds = Math.floor((performance.now() - startTime) / 1000);
const minutes = Math.floor(seconds / 60);
const formatted = `${String(minutes).padStart(2, "0")}:${String(seconds % 60).padStart(2, "0")}`;
statsText.textContent = `${mistakes} mistake${mistakes === 1 ? "" : "s"} · ${formatted}`;
}
renderer.render(scene, camera);
}
setStage(0, false);
updateStageCounts();
updateStats();
animate();
window.setTimeout(() => {
showToast("Welcome! Start with the egg stage, then match it across all three host-plant habitats.");
}, 450);
</script>
</body>
</html>
```