Back to the app
The code
Night Courier by Gemini 4 Neon
Exactly as the AI wrote it. Shown as text, so nothing runs on this page.
index.html
works · auto-checked (Checked by an automated pass. Not hand-played yet.)<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
<title>Sunset Courier — Lake Town Fish Delivery</title>
<style>
:root {
--glass: rgba(24, 18, 34, 0.56);
--glass-strong: rgba(20, 15, 30, 0.78);
--border: rgba(255, 224, 178, 0.24);
--gold: #ffbe5c;
--coral: #ff7e5f;
--cream: #fff5e6;
--muted: rgba(255, 236, 210, 0.76);
}
* {
box-sizing: border-box;
-webkit-tap-highlight-color: transparent;
user-select: none;
-webkit-user-select: none;
}
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
overflow: hidden;
background: #1b152a;
font-family: 'Segoe UI', system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
color: var(--cream);
touch-action: none;
}
#stage {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
touch-action: none;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
/* Pointer & Touch Steering Indicators */
#mouse-reticle {
position: fixed;
width: 34px;
height: 34px;
margin: -17px 0 0 -17px;
border-radius: 50%;
border: 2px solid rgba(255, 226, 170, 0.65);
box-shadow: 0 0 12px rgba(255, 186, 92, 0.35);
pointer-events: none;
opacity: 0;
transition: opacity 0.2s ease;
z-index: 12;
}
#mouse-reticle::after {
content: '';
position: absolute;
left: 50%;
top: 50%;
width: 6px;
height: 6px;
margin: -3px 0 0 -3px;
border-radius: 50%;
background: #ffd38a;
}
#touch-pad {
position: fixed;
width: 124px;
height: 124px;
margin: -62px 0 0 -62px;
border-radius: 50%;
border: 2px solid rgba(255, 224, 174, 0.42);
background: radial-gradient(circle, rgba(255, 198, 120, 0.14), rgba(255, 198, 120, 0.02));
pointer-events: none;
opacity: 0;
transition: opacity 0.15s ease;
z-index: 13;
}
#touch-knob {
position: absolute;
left: 50%;
top: 50%;
width: 46px;
height: 46px;
margin: -23px 0 0 -23px;
border-radius: 50%;
background: radial-gradient(circle at 35% 30%, #ffe6b8, #ff9d57);
border: 2px solid rgba(255, 250, 238, 0.7);
box-shadow: 0 4px 16px rgba(255, 145, 75, 0.45);
}
/* Ring Compass Indicator */
#ring-compass {
position: fixed;
left: 50%;
top: 50%;
width: 54px;
height: 54px;
margin: -27px 0 0 -27px;
pointer-events: none;
opacity: 0;
transition: opacity 0.18s ease;
z-index: 14;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
#ring-compass .arrow {
width: 30px;
height: 30px;
filter: drop-shadow(0 0 8px rgba(255, 194, 88, 0.85));
}
#ring-compass .dist {
margin-top: -2px;
font-size: 11px;
font-weight: 700;
color: #ffe3ab;
text-shadow: 0 1px 4px rgba(0, 0, 0, 0.85);
font-variant-numeric: tabular-nums;
}
/* Top HUD */
#hud-top {
position: fixed;
top: max(12px, env(safe-area-inset-top));
left: max(12px, env(safe-area-inset-left));
right: max(12px, env(safe-area-inset-right));
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
pointer-events: none;
z-index: 20;
}
.hud-pill {
background: var(--glass);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
border: 1px solid var(--border);
border-radius: 18px;
padding: 8px 14px;
box-shadow: 0 8px 24px rgba(10, 6, 20, 0.32);
pointer-events: auto;
}
.stats-pill {
display: flex;
align-items: center;
gap: 14px;
}
.stat-block {
display: flex;
flex-direction: column;
line-height: 1.1;
}
.stat-label {
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--muted);
font-weight: 700;
}
.stat-value {
font-size: 20px;
font-weight: 800;
color: var(--cream);
font-variant-numeric: tabular-nums;
display: flex;
align-items: center;
gap: 5px;
}
.stat-divider {
width: 1px;
height: 28px;
background: rgba(255, 224, 178, 0.22);
}
.icon-gold { color: var(--gold); }
/* Sunset Timer Pill */
.sunset-pill {
display: flex;
flex-direction: column;
align-items: center;
gap: 5px;
min-width: 138px;
padding: 8px 14px 9px;
}
.sunset-row {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
font-size: 12px;
font-weight: 700;
font-variant-numeric: tabular-nums;
}
.sunset-track {
position: relative;
width: 100%;
height: 8px;
border-radius: 99px;
background: linear-gradient(90deg, #ffbe5c 0%, #ff7a59 48%, #7357a8 80%, #242554 100%);
overflow: hidden;
box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.45);
}
#sunset-fill {
position: absolute;
right: 0;
top: 0;
bottom: 0;
width: 0%;
background: rgba(14, 10, 28, 0.72);
transition: width 0.2s linear;
}
.sunset-pill.urgent {
border-color: rgba(255, 126, 95, 0.75);
box-shadow: 0 0 18px rgba(255, 110, 80, 0.35);
}
/* Sound Button */
#btn-sound {
width: 48px;
height: 48px;
border-radius: 50%;
border: 1px solid var(--border);
background: var(--glass);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
color: var(--cream);
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
touch-action: manipulation;
pointer-events: auto;
box-shadow: 0 8px 24px rgba(10, 6, 20, 0.32);
transition: transform 0.12s ease, background 0.15s ease;
flex-shrink: 0;
}
#btn-sound:active { transform: scale(0.92); }
#btn-sound.muted { color: rgba(255, 224, 188, 0.45); }
/* Toast Notification */
#toast {
position: fixed;
top: max(76px, calc(env(safe-area-inset-top) + 64px));
left: 50%;
transform: translateX(-50%) translateY(-8px);
background: rgba(32, 20, 42, 0.8);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
border: 1px solid rgba(255, 206, 128, 0.45);
color: #ffe8c2;
padding: 8px 18px;
border-radius: 99px;
font-size: 14px;
font-weight: 700;
letter-spacing: 0.01em;
pointer-events: none;
opacity: 0;
transition: opacity 0.25s ease, transform 0.25s ease;
z-index: 22;
white-space: nowrap;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);
}
#toast.show {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
/* Demo Badge */
#demo-badge {
position: fixed;
top: max(76px, calc(env(safe-area-inset-top) + 64px));
left: 50%;
transform: translateX(-50%);
background: rgba(255, 178, 84, 0.22);
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
border: 1px solid rgba(255, 210, 140, 0.55);
color: #fff2d8;
padding: 6px 14px;
border-radius: 99px;
font-size: 12px;
font-weight: 700;
letter-spacing: 0.04em;
pointer-events: none;
display: none;
z-index: 21;
}
/* Bottom Camera Bar */
#cam-bar {
position: fixed;
bottom: max(14px, env(safe-area-inset-bottom));
left: 50%;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 8px;
padding: 6px;
border-radius: 24px;
background: var(--glass);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border: 1px solid var(--border);
box-shadow: 0 10px 28px rgba(8, 4, 18, 0.42);
z-index: 24;
max-width: calc(100vw - 20px);
}
.cam-btn {
display: flex;
align-items: center;
justify-content: center;
gap: 7px;
min-height: 48px;
min-width: 96px;
padding: 10px 16px;
border-radius: 18px;
border: 1px solid transparent;
background: transparent;
color: var(--muted);
font-family: inherit;
font-size: 14px;
font-weight: 700;
cursor: pointer;
touch-action: manipulation;
transition: background 0.16s ease, color 0.16s ease, transform 0.1s ease, box-shadow 0.16s ease;
white-space: nowrap;
}
.cam-btn svg {
width: 19px;
height: 19px;
flex-shrink: 0;
}
.cam-btn:active {
transform: scale(0.95);
}
.cam-btn.active {
background: linear-gradient(135deg, #ffb95a, #ff7c57);
color: #26141a;
border-color: rgba(255, 245, 224, 0.45);
box-shadow: 0 4px 16px rgba(255, 146, 82, 0.45);
}
/* Overlays (Title & End) */
.overlay {
position: fixed;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
background: radial-gradient(circle at 50% 42%, rgba(22, 14, 34, 0.22), rgba(14, 10, 26, 0.62));
z-index: 30;
opacity: 1;
transition: opacity 0.35s ease;
}
.overlay.hidden {
opacity: 0;
pointer-events: none;
}
.overlay-card {
width: min(410px, 100%);
background: var(--glass-strong);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
border: 1px solid rgba(255, 214, 158, 0.32);
border-radius: 28px;
padding: 26px 24px 24px;
text-align: center;
box-shadow: 0 24px 60px rgba(6, 4, 16, 0.6);
}
.cat-emblem {
width: 66px;
height: 66px;
margin: 0 auto 12px;
border-radius: 20px;
background: linear-gradient(135deg, rgba(255, 188, 92, 0.25), rgba(255, 120, 86, 0.25));
border: 1px solid rgba(255, 206, 134, 0.4);
display: flex;
align-items: center;
justify-content: center;
}
.overlay-card h1 {
margin: 0 0 6px;
font-size: 28px;
font-weight: 850;
letter-spacing: -0.02em;
background: linear-gradient(180deg, #fff8ec 20%, #ffd08a 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.overlay-sub {
margin: 0 0 18px;
font-size: 14px;
line-height: 1.48;
color: var(--muted);
}
.tips-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-bottom: 20px;
}
.tip-box {
background: rgba(255, 232, 200, 0.08);
border: 1px solid rgba(255, 224, 180, 0.14);
border-radius: 14px;
padding: 10px;
font-size: 12px;
line-height: 1.35;
color: #ffe8ca;
}
.tip-box strong {
display: block;
color: var(--gold);
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.06em;
margin-bottom: 2px;
}
.summary-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin: 16px 0 20px;
}
.summary-cell {
background: rgba(255, 230, 195, 0.09);
border: 1px solid rgba(255, 220, 175, 0.16);
border-radius: 16px;
padding: 12px 10px;
}
.summary-cell .s-lbl {
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.07em;
color: var(--muted);
font-weight: 700;
}
.summary-cell .s-val {
margin-top: 3px;
font-size: 24px;
font-weight: 850;
color: #fff6e8;
font-variant-numeric: tabular-nums;
}
.primary-btn {
width: 100%;
min-height: 56px;
border: none;
border-radius: 18px;
background: linear-gradient(135deg, #ffc15e 0%, #ff7b54 100%);
color: #241216;
font-family: inherit;
font-size: 18px;
font-weight: 850;
letter-spacing: 0.01em;
cursor: pointer;
touch-action: manipulation;
box-shadow: 0 10px 26px rgba(255, 130, 74, 0.42), inset 0 1px 0 rgba(255, 255, 255, 0.45);
transition: transform 0.12s ease, box-shadow 0.15s ease;
}
.primary-btn:active {
transform: scale(0.97);
}
.best-note {
margin-top: 12px;
font-size: 12px;
color: var(--muted);
font-variant-numeric: tabular-nums;
}
/* Responsive Tuning for Small Phones */
@media (max-width: 520px) {
#hud-top { gap: 6px; }
.hud-pill { padding: 6px 10px; border-radius: 15px; }
.stats-pill { gap: 10px; }
.stat-value { font-size: 17px; }
.sunset-pill { min-width: 108px; padding: 6px 10px 7px; }
#btn-sound { width: 44px; height: 44px; }
.cam-btn { min-width: 0; padding: 9px 12px; font-size: 13px; gap: 5px; }
.cam-btn svg { width: 17px; height: 17px; }
}
</style>
</head>
<body>
<div id="stage"></div>
<div id="mouse-reticle"></div>
<div id="touch-pad"><div id="touch-knob"></div></div>
<div id="ring-compass">
<svg class="arrow" viewBox="0 0 32 32" fill="none">
<path d="M16 3L27 25L16 19.5L5 25L16 3Z" fill="#FFD166" stroke="#FFF6DE" stroke-width="2" stroke-linejoin="round"/>
</svg>
<span class="dist" id="compass-dist">80m</span>
</div>
<div id="hud-top">
<div class="hud-pill stats-pill">
<div class="stat-block">
<span class="stat-label">Score</span>
<span class="stat-value"><span class="icon-gold">★</span><span id="hud-score">0</span></span>
</div>
<div class="stat-divider"></div>
<div class="stat-block">
<span class="stat-label">Crates Left</span>
<span class="stat-value"><span id="hud-crates">8</span><span style="font-size:15px">🐟</span></span>
</div>
</div>
<div class="hud-pill sunset-pill" id="sunset-pill">
<div class="sunset-row">
<span>☀</span>
<span id="hud-time">1:35</span>
<span>☾</span>
</div>
<div class="sunset-track"><div id="sunset-fill"></div></div>
</div>
<button id="btn-sound" type="button" aria-label="Toggle Sound">
<svg id="icon-sound-on" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
<polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon>
<path d="M15.54 8.46a5 5 0 0 1 0 7.07"></path>
<path d="M19.07 4.93a10 10 0 0 1 0 14.14"></path>
</svg>
<svg id="icon-sound-off" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" style="display:none">
<polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon>
<line x1="23" y1="9" x2="17" y2="15"></line>
<line x1="17" y1="9" x2="23" y2="15"></line>
</svg>
</button>
</div>
<div id="toast"></div>
<div id="demo-badge">DEMO FLIGHT · TOUCH OR CLICK TO STEER</div>
<div id="cam-bar" role="group" aria-label="Camera View">
<button class="cam-btn active" type="button" data-cam="behind">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round">
<path d="M2 16l10-4 10 4-10-12-10 12z"/>
<path d="M12 12v8"/>
</svg>
<span>Behind</span>
</button>
<button class="cam-btn" type="button" data-cam="cockpit">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round">
<path d="M3 16a9 9 0 0 1 18 0"/>
<rect x="3" y="16" width="18" height="4" rx="1.5"/>
<circle cx="9" cy="18" r="0.8" fill="currentColor"/>
<circle cx="15" cy="18" r="0.8" fill="currentColor"/>
</svg>
<span>Cockpit</span>
</button>
<button class="cam-btn" type="button" data-cam="above">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="9"/>
<circle cx="12" cy="12" r="3"/>
<path d="M12 3v3M12 18v3M3 12h3M18 12h3"/>
</svg>
<span>Above</span>
</button>
</div>
<!-- Start Overlay -->
<div class="overlay" id="start-overlay">
<div class="overlay-card">
<div class="cat-emblem">
<svg width="42" height="42" viewBox="0 0 48 48" fill="none">
<path d="M11 19L14 8L21 15H27L34 8L37 19C40 22 41 26 40 31C38.5 37 32.5 41 24 41C15.5 41 9.5 37 8 31C7 26 8 22 11 19Z" fill="#FF9642" stroke="#FFE6C4" stroke-width="2"/>
<path d="M14.5 11.5L18.5 15.5L13.5 17.5L14.5 11.5Z" fill="#FFCCB0"/>
<path d="M33.5 11.5L29.5 15.5L34.5 17.5L33.5 11.5Z" fill="#FFCCB0"/>
<rect x="12" y="18" width="10" height="6" rx="3" fill="#5D4238" stroke="#FFD07B" stroke-width="1.6"/>
<rect x="26" y="18" width="10" height="6" rx="3" fill="#5D4238" stroke="#FFD07B" stroke-width="1.6"/>
<line x1="22" y1="21" x2="26" y2="21" stroke="#FFD07B" stroke-width="1.8"/>
<circle cx="17" cy="27.5" r="2.2" fill="#2A1B1E"/>
<circle cx="31" cy="27.5" r="2.2" fill="#2A1B1E"/>
<path d="M22 30.5L24 32.5L26 30.5H22Z" fill="#FF6F7D"/>
<path d="M20 34.5C21.5 36 23 35.5 24 34C25 35.5 26.5 36 28 34.5" stroke="#3D241C" stroke-width="1.8" stroke-linecap="round"/>
</svg>
</div>
<h1>Sunset Courier</h1>
<p class="overlay-sub">
Fly through the glowing sky rings over the lake town to parachute fresh fish crates to every waiting cat before night falls.
</p>
<div class="tips-row">
<div class="tip-box">
<strong>Phone / Touch</strong>
Drag one finger anywhere to steer & climb
</div>
<div class="tip-box">
<strong>Desktop Mouse</strong>
Move your pointer — the plane follows it
</div>
</div>
<button class="primary-btn" id="btn-play" type="button">Take Off</button>
<div class="best-note" id="start-best"></div>
</div>
</div>
<!-- End Overlay -->
<div class="overlay hidden" id="end-overlay">
<div class="overlay-card">
<div class="cat-emblem" id="end-emblem">
<span style="font-size:34px" id="end-emoji">🐟</span>
</div>
<h1 id="end-title">All Fish Delivered!</h1>
<p class="overlay-sub" id="end-sub">Every rooftop and dock cat has dinner before dark.</p>
<div class="summary-grid">
<div class="summary-cell">
<div class="s-lbl">Final Score</div>
<div class="s-val" id="end-score">0</div>
</div>
<div class="summary-cell">
<div class="s-lbl">Crates</div>
<div class="s-val" id="end-crates">8 / 8</div>
</div>
<div class="summary-cell">
<div class="s-lbl">Sunset Bonus</div>
<div class="s-val" id="end-bonus">+0</div>
</div>
<div class="summary-cell">
<div class="s-lbl">Best Score</div>
<div class="s-val" id="end-best">0</div>
</div>
</div>
<button class="primary-btn" id="btn-replay" type="button">Play Again</button>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script>
<script>
(function () {
'use strict';
if (typeof THREE === 'undefined') {
document.body.innerHTML = '<div style="padding:40px;text-align:center;color:#ffe6c4;font-family:sans-serif"><h2>3D Library Unavailable</h2><p>Please reload when connected so Three.js can load.</p></div>';
return;
}
// ---------- Helpers ----------
const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
const lerp = (a, b, t) => a + (b - a) * t;
const smoothstep = (e0, e1, x) => {
const t = clamp((x - e0) / (e1 - e0), 0, 1);
return t * t * (3 - 2 * t);
};
const wrapAngle = (a) => {
while (a > Math.PI) a -= Math.PI * 2;
while (a < -Math.PI) a += Math.PI * 2;
return a;
};
const col = (hex) => new THREE.Color(hex).convertSRGBToLinear();
// Safe localStorage wrapper
function loadBestScore() {
try { return parseInt(localStorage.getItem('sunset_courier_best') || '0', 10) || 0; }
catch (_) { return 0; }
}
function saveBestScore(v) {
try { localStorage.setItem('sunset_courier_best', String(v)); }
catch (_) {}
}
// Seeded pseudo-random for deterministic scenic town layout
let rngState = 13379;
function rand() {
rngState = (rngState * 16807) % 2147483647;
return (rngState - 1) / 2147483646;
}
// ---------- DOM References ----------
const stageEl = document.getElementById('stage');
const hudScoreEl = document.getElementById('hud-score');
const hudCratesEl = document.getElementById('hud-crates');
const hudTimeEl = document.getElementById('hud-time');
const sunsetFillEl = document.getElementById('sunset-fill');
const sunsetPillEl = document.getElementById('sunset-pill');
const toastEl = document.getElementById('toast');
const demoBadgeEl = document.getElementById('demo-badge');
const startOverlayEl = document.getElementById('start-overlay');
const endOverlayEl = document.getElementById('end-overlay');
const startBestEl = document.getElementById('start-best');
const endTitleEl = document.getElementById('end-title');
const endSubEl = document.getElementById('end-sub');
const endEmojiEl = document.getElementById('end-emoji');
const endScoreEl = document.getElementById('end-score');
const endCratesEl = document.getElementById('end-crates');
const endBonusEl = document.getElementById('end-bonus');
const endBestEl = document.getElementById('end-best');
const btnPlay = document.getElementById('btn-play');
const btnReplay = document.getElementById('btn-replay');
const btnSound = document.getElementById('btn-sound');
const iconSoundOn = document.getElementById('icon-sound-on');
const iconSoundOff = document.getElementById('icon-sound-off');
const camButtons = Array.from(document.querySelectorAll('.cam-btn'));
const mouseReticleEl = document.getElementById('mouse-reticle');
const touchPadEl = document.getElementById('touch-pad');
const touchKnobEl = document.getElementById('touch-knob');
const ringCompassEl = document.getElementById('ring-compass');
const compassArrowEl = ringCompassEl.querySelector('.arrow');
const compassDistEl = document.getElementById('compass-dist');
let bestScore = loadBestScore();
if (bestScore > 0) startBestEl.textContent = 'Best Score: ' + bestScore;
// ---------- Synthesized Web Audio ----------
const AudioSys = {
ctx: null,
muted: false,
started: false,
propOsc: null,
propGain: null,
windGain: null,
init() {
if (this.started) {
if (this.ctx && this.ctx.state === 'suspended') {
try { this.ctx.resume(); } catch (_) {}
}
return;
}
try {
const AC = window.AudioContext || window.webkitAudioContext;
if (!AC) return;
this.ctx = new AC();
this.started = true;
// Soft warm propeller drone
const osc = this.ctx.createOscillator();
const osc2 = this.ctx.createOscillator();
const filter = this.ctx.createBiquadFilter();
const gain = this.ctx.createGain();
osc.type = 'sawtooth';
osc.frequency.value = 66;
osc2.type = 'triangle';
osc2.frequency.value = 132;
filter.type = 'lowpass';
filter.frequency.value = 195;
gain.gain.value = 0.0;
osc.connect(filter);
osc2.connect(filter);
filter.connect(gain);
gain.connect(this.ctx.destination);
osc.start();
osc2.start();
this.propOsc = osc;
this.propOsc2 = osc2;
this.propFilter = filter;
this.propGain = gain;
// Subtle breeze noise
const bufLen = this.ctx.sampleRate * 2;
const buf = this.ctx.createBuffer(1, bufLen, this.ctx.sampleRate);
const data = buf.getChannelData(0);
for (let i = 0; i < bufLen; i++) data[i] = Math.random() * 2 - 1;
const src = this.ctx.createBufferSource();
src.buffer = buf;
src.loop = true;
const wFilter = this.ctx.createBiquadFilter();
wFilter.type = 'bandpass';
wFilter.frequency.value = 420;
wFilter.Q.value = 0.8;
const wGain = this.ctx.createGain();
wGain.gain.value = 0.0;
src.connect(wFilter);
wFilter.connect(wGain);
wGain.connect(this.ctx.destination);
src.start();
this.windGain = wGain;
} catch (_) {}
},
updateEngine(speedRatio, active) {
if (!this.ctx || !this.propGain) return;
try {
const now = this.ctx.currentTime;
const vol = (this.muted || !active) ? 0.0 : 0.032;
const wVol = (this.muted || !active) ? 0.0 : 0.014;
this.propGain.gain.setTargetAtTime(vol, now, 0.12);
this.windGain.gain.setTargetAtTime(wVol, now, 0.15);
const f = 58 + speedRatio * 24;
this.propOsc.frequency.setTargetAtTime(f, now, 0.08);
this.propOsc2.frequency.setTargetAtTime(f * 2.01, now, 0.08);
this.propFilter.frequency.setTargetAtTime(160 + speedRatio * 110, now, 0.1);
} catch (_) {}
},
playRing(combo) {
if (!this.ctx || this.muted) return;
try {
const now = this.ctx.currentTime;
const base = [523.25, 659.25, 783.99, 1046.5];
const shift = Math.pow(1.06, Math.min(combo, 5));
base.forEach((freq, i) => {
const osc = this.ctx.createOscillator();
const g = this.ctx.createGain();
osc.type = 'triangle';
osc.frequency.setValueAtTime(freq * shift, now + i * 0.055);
g.gain.setValueAtTime(0.0001, now + i * 0.055);
g.gain.linearRampToValueAtTime(0.085, now + i * 0.055 + 0.015);
g.gain.exponentialRampToValueAtTime(0.0008, now + i * 0.055 + 0.42);
osc.connect(g);
g.connect(this.ctx.destination);
osc.start(now + i * 0.055);
osc.stop(now + i * 0.055 + 0.45);
});
} catch (_) {}
},
playDelivery() {
if (!this.ctx || this.muted) return;
try {
const now = this.ctx.currentTime;
// Cheerful warm chime + cute synthesized cat meow
const notes = [587.33, 880];
notes.forEach((f, idx) => {
const o = this.ctx.createOscillator();
const g = this.ctx.createGain();
o.type = 'sine';
o.frequency.setValueAtTime(f, now + idx * 0.08);
g.gain.setValueAtTime(0.0001, now + idx * 0.08);
g.gain.linearRampToValueAtTime(0.08, now + idx * 0.08 + 0.02);
g.gain.exponentialRampToValueAtTime(0.0008, now + idx * 0.08 + 0.35);
o.connect(g); g.connect(this.ctx.destination);
o.start(now + idx * 0.08); o.stop(now + idx * 0.08 + 0.38);
});
// Little cat meow glide
const m = this.ctx.createOscillator();
const mf = this.ctx.createBiquadFilter();
const mg = this.ctx.createGain();
m.type = 'triangle';
m.frequency.setValueAtTime(620, now + 0.12);
m.frequency.exponentialRampToValueAtTime(940, now + 0.22);
m.frequency.exponentialRampToValueAtTime(520, now + 0.40);
mf.type = 'bandpass';
mf.frequency.value = 1150;
mf.Q.value = 2.4;
mg.gain.setValueAtTime(0.0001, now + 0.12);
mg.gain.linearRampToValueAtTime(0.075, now + 0.18);
mg.gain.exponentialRampToValueAtTime(0.0008, now + 0.42);
m.connect(mf); mf.connect(mg); mg.connect(this.ctx.destination);
m.start(now + 0.12); m.stop(now + 0.45);
} catch (_) {}
},
playClick() {
if (!this.ctx || this.muted) return;
try {
const now = this.ctx.currentTime;
const o = this.ctx.createOscillator();
const g = this.ctx.createGain();
o.type = 'sine';
o.frequency.setValueAtTime(680, now);
o.frequency.exponentialRampToValueAtTime(420, now + 0.05);
g.gain.setValueAtTime(0.045, now);
g.gain.exponentialRampToValueAtTime(0.001, now + 0.06);
o.connect(g); g.connect(this.ctx.destination);
o.start(now); o.stop(now + 0.065);
} catch (_) {}
},
playEnd(won) {
if (!this.ctx || this.muted) return;
try {
const now = this.ctx.currentTime;
const seq = won ? [523.25, 659.25, 783.99, 1046.5, 1318.5] : [440, 392, 329.63, 293.66];
seq.forEach((f, i) => {
const o = this.ctx.createOscillator();
const g = this.ctx.createGain();
o.type = 'triangle';
o.frequency.setValueAtTime(f, now + i * 0.11);
g.gain.setValueAtTime(0.0001, now + i * 0.11);
g.gain.linearRampToValueAtTime(0.09, now + i * 0.11 + 0.02);
g.gain.exponentialRampToValueAtTime(0.0008, now + i * 0.11 + 0.65);
o.connect(g); g.connect(this.ctx.destination);
o.start(now + i * 0.11); o.stop(now + i * 0.11 + 0.68);
});
} catch (_) {}
}
};
btnSound.addEventListener('click', (e) => {
e.stopPropagation();
AudioSys.init();
AudioSys.muted = !AudioSys.muted;
btnSound.classList.toggle('muted', AudioSys.muted);
iconSoundOn.style.display = AudioSys.muted ? 'none' : 'block';
iconSoundOff.style.display = AudioSys.muted ? 'block' : 'none';
if (!AudioSys.muted) AudioSys.playClick();
});
// ---------- Procedural Canvas Textures ----------
function makeCrateTexture() {
const c = document.createElement('canvas');
c.width = 128; c.height = 128;
const g = c.getContext('2d');
g.fillStyle = '#c88b4b';
g.fillRect(0, 0, 128, 128);
// Horizontal planks
g.fillStyle = '#b17439';
for (let y = 0; y < 128; y += 32) {
g.fillRect(0, y, 128, 3);
g.fillStyle = y % 64 === 0 ? '#cf9250' : '#bc7e40';
g.fillRect(0, y + 3, 128, 29);
g.fillStyle = '#8b5424';
}
// Outer wood frame
g.strokeStyle = '#7e4a1f';
g.lineWidth = 14;
g.strokeRect(7, 7, 114, 114);
// Stenciled fish emblem
g.fillStyle = '#2d5c7f';
g.beginPath();
g.ellipse(60, 64, 24, 12, 0, 0, Math.PI * 2);
g.fill();
g.beginPath();
g.moveTo(81, 64); g.lineTo(96, 52); g.lineTo(96, 76); g.closePath();
g.fill();
g.fillStyle = '#fff2d8';
g.beginPath(); g.arc(47, 62, 3, 0, Math.PI * 2); g.fill();
const tex = new THREE.CanvasTexture(c);
tex.encoding = THREE.sRGBEncoding;
return tex;
}
function makeParachuteTexture() {
const c = document.createElement('canvas');
c.width = 256; c.height = 128;
const g = c.getContext('2d');
const stripes = 8;
const sw = c.width / stripes;
for (let i = 0; i < stripes; i++) {
g.fillStyle = i % 2 === 0 ? '#fff3dc' : '#ef5b47';
g.fillRect(i * sw, 0, sw + 1, c.height);
}
g.fillStyle = 'rgba(120, 40, 20, 0.18)';
g.fillRect(0, c.height - 14, c.width, 14);
const tex = new THREE.CanvasTexture(c);
tex.encoding = THREE.sRGBEncoding;
return tex;
}
function makeDialTexture(label, accent) {
const c = document.createElement('canvas');
c.width = 128; c.height = 128;
const g = c.getContext('2d');
g.fillStyle = '#221b18';
g.beginPath(); g.arc(64, 64, 60, 0, Math.PI * 2); g.fill();
g.strokeStyle = '#d4a156';
g.lineWidth = 6;
g.stroke();
// Tick marks
for (let i = 0; i < 12; i++) {
const a = (i / 12) * Math.PI * 2;
g.strokeStyle = i % 3 === 0 ? accent : '#cbb89d';
g.lineWidth = i % 3 === 0 ? 4 : 2;
g.beginPath();
g.moveTo(64 + Math.cos(a) * 42, 64 + Math.sin(a) * 42);
g.lineTo(64 + Math.cos(a) * 53, 64 + Math.sin(a) * 53);
g.stroke();
}
g.fillStyle = '#e7d5bc';
g.font = 'bold 16px sans-serif';
g.textAlign = 'center';
g.fillText(label, 64, 96);
const tex = new THREE.CanvasTexture(c);
tex.encoding = THREE.sRGBEncoding;
return tex;
}
function makeTailBadgeTexture() {
const c = document.createElement('canvas');
c.width = 128; c.height = 128;
const g = c.getContext('2d');
g.fillStyle = '#df4f3d';
g.fillRect(0, 0, 128, 128);
g.fillStyle = '#fff0d2';
g.beginPath(); g.arc(64, 64, 38, 0, Math.PI * 2); g.fill();
g.fillStyle = '#df4f3d';
g.beginPath(); g.ellipse(60, 64, 18, 9, 0, 0, Math.PI * 2); g.fill();
g.beginPath(); g.moveTo(76, 64); g.lineTo(88, 54); g.lineTo(88, 74); g.closePath(); g.fill();
const tex = new THREE.CanvasTexture(c);
tex.encoding = THREE.sRGBEncoding;
return tex;
}
function makePlankTexture() {
const c = document.createElement('canvas');
c.width = 128; c.height = 128;
const g = c.getContext('2d');
g.fillStyle = '#9c6e44';
g.fillRect(0, 0, 128, 128);
for (let i = 0; i < 8; i++) {
g.fillStyle = i % 2 === 0 ? '#a8784c' : '#8d613b';
g.fillRect(0, i * 16, 128, 14);
g.fillStyle = '#5d3d23';
g.fillRect(0, i * 16 + 14, 128, 2);
}
const tex = new THREE.CanvasTexture(c);
tex.wrapS = THREE.RepeatWrapping;
tex.wrapT = THREE.RepeatWrapping;
tex.repeat.set(1, 3);
tex.encoding = THREE.sRGBEncoding;
return tex;
}
// ---------- Renderer & Scene ----------
const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'high-performance' });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputEncoding = THREE.sRGBEncoding;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
stageEl.appendChild(renderer.domElement);
const scene = new THREE.Scene();
const fogColor = col('#e88b5a');
scene.fog = new THREE.FogExp2(fogColor, 0.0021);
const camera = new THREE.PerspectiveCamera(56, window.innerWidth / window.innerHeight, 0.25, 2400);
const reflCam = new THREE.PerspectiveCamera(56, window.innerWidth / window.innerHeight, 0.25, 2400);
reflCam.matrixAutoUpdate = false;
const reflClipPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0.08);
let reflRT = new THREE.WebGLRenderTarget(
Math.min(512, Math.max(256, Math.floor(window.innerWidth * 0.5))),
Math.min(512, Math.max(256, Math.floor(window.innerHeight * 0.5))),
{ minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat }
);
// ---------- Lights ----------
const hemiLight = new THREE.HemisphereLight(col('#ffc884'), col('#475c78'), 0.88);
scene.add(hemiLight);
const sunLight = new THREE.DirectionalLight(col('#ffae62'), 2.15);
sunLight.position.set(-220, 62, -90);
sunLight.castShadow = true;
sunLight.shadow.mapSize.set(1024, 1024);
sunLight.shadow.camera.near = 20;
sunLight.shadow.camera.far = 520;
const sBounds = 170;
sunLight.shadow.camera.left = -sBounds;
sunLight.shadow.camera.right = sBounds;
sunLight.shadow.camera.top = sBounds;
sunLight.shadow.camera.bottom = -sBounds;
sunLight.shadow.bias = -0.0008;
scene.add(sunLight);
const moonLight = new THREE.DirectionalLight(col('#6b8fd8'), 0.05);
moonLight.position.set(180, 120, 130);
scene.add(moonLight);
// ---------- Sunset-to-Night Sky Dome Shader ----------
const skyUniforms = {
uTopColor: { value: col('#2d4278') },
uMidColor: { value: col('#d66b65') },
uHorizonColor: { value: col('#ffad5a') },
uSunDir: { value: new THREE.Vector3(-0.91, 0.16, -0.37).normalize() },
uSunColor: { value: col('#ffda88') },
uNightMix: { value: 0.0 },
uTime: { value: 0.0 }
};
const skyMat = new THREE.ShaderMaterial({
side: THREE.BackSide,
depthWrite: false,
uniforms: skyUniforms,
vertexShader: `
varying vec3 vDir;
void main() {
vDir = normalize(position);
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
uniform vec3 uTopColor;
uniform vec3 uMidColor;
uniform vec3 uHorizonColor;
uniform vec3 uSunDir;
uniform vec3 uSunColor;
uniform float uNightMix;
uniform float uTime;
varying vec3 vDir;
float hash31(vec3 p) {
p = fract(p * vec3(443.897, 441.423, 437.195));
p += dot(p, p.yzx + 19.19);
return fract((p.x + p.y) * p.z);
}
void main() {
vec3 d = normalize(vDir);
float h = clamp(d.y, 0.0, 1.0);
vec3 sky = mix(uHorizonColor, uMidColor, smoothstep(0.0, 0.28, h));
sky = mix(sky, uTopColor, smoothstep(0.20, 0.85, h));
// Warm sunset band around sun azimuth
vec3 sDir = normalize(uSunDir);
float sunDot = max(dot(d, sDir), 0.0);
float sunVis = smoothstep(-0.10, 0.04, sDir.y);
float halo = pow(sunDot, 7.0) * 0.55 + pow(sunDot, 48.0) * 1.1;
float disc = smoothstep(0.9972, 0.9990, dot(d, sDir)) * 3.2;
sky += uSunColor * (halo + disc) * sunVis;
// Horizon atmospheric wrap
float horizGlow = exp(-abs(d.y) * 9.0) * (0.28 + 0.45 * pow(sunDot, 2.0)) * (1.0 - uNightMix * 0.72);
sky += uHorizonColor * horizGlow;
// Crescent moon in eastern sky
vec3 moonDir = normalize(vec3(0.74, 0.34 + uNightMix * 0.14, 0.48));
float mDot = dot(d, moonDir);
float mDisc = smoothstep(0.9986, 0.9992, mDot);
vec3 moonCutDir = normalize(moonDir + vec3(-0.018, 0.012, 0.01));
float mCut = smoothstep(0.9987, 0.9993, dot(d, moonCutDir));
float crescent = clamp(mDisc - mCut * 0.92, 0.0, 1.0);
float mHalo = pow(max(mDot, 0.0), 42.0) * 0.25;
float moonAlpha = smoothstep(0.22, 0.78, uNightMix);
sky += vec3(0.75, 0.85, 1.0) * (crescent * 2.2 + mHalo) * moonAlpha;
// Twinkling stars as dusk deepens
if (d.y > 0.05 && uNightMix > 0.22) {
vec3 grid = floor(d * 210.0);
float hval = hash31(grid);
if (hval > 0.9945) {
float tw = 0.65 + 0.35 * sin(uTime * 2.5 + hval * 900.0);
float starFade = smoothstep(0.22, 0.78, uNightMix) * smoothstep(0.05, 0.26, d.y);
sky += vec3(0.95, 0.94, 1.0) * tw * starFade * 1.65;
}
}
gl_FragColor = vec4(sky, 1.0);
#include <tonemapping_fragment>
#include <encodings_fragment>
}
`
});
const skyDome = new THREE.Mesh(new THREE.SphereGeometry(1650, 32, 24), skyMat);
scene.add(skyDome);
// ---------- Reflective Lake Water Shader ----------
const waterUniforms = {
uReflectionMap: { value: reflRT.texture },
uTime: { value: 0.0 },
uSunDir: { value: skyUniforms.uSunDir.value },
uSunColor: { value: col('#ffcc7a') },
uDeepColor: { value: col('#122a40') },
uShallowColor: { value: col('#23546b') },
uFogColor: { value: fogColor.clone() },
uFogDensity: { value: 0.0021 },
uNightMix: { value: 0.0 }
};
const waterMat = new THREE.ShaderMaterial({
uniforms: waterUniforms,
vertexShader: `
varying vec3 vWorldPos;
varying vec4 vClipPos;
void main() {
vec4 wp = modelMatrix * vec4(position, 1.0);
vWorldPos = wp.xyz;
vClipPos = projectionMatrix * viewMatrix * wp;
gl_Position = vClipPos;
}
`,
fragmentShader: `
uniform sampler2D uReflectionMap;
uniform float uTime;
uniform vec3 uSunDir;
uniform vec3 uSunColor;
uniform vec3 uDeepColor;
uniform vec3 uShallowColor;
uniform vec3 uFogColor;
uniform float uFogDensity;
uniform float uNightMix;
varying vec3 vWorldPos;
varying vec4 vClipPos;
void main() {
vec2 p = vWorldPos.xz;
float t = uTime;
// Multi-directional animated gentle lake ripples
float w1 = sin(p.x * 0.23 + p.y * 0.14 + t * 1.55);
float w2 = cos(p.x * -0.17 + p.y * 0.29 + t * 1.22);
float w3 = sin(p.x * 0.51 - p.y * 0.43 + t * 2.15) * 0.45;
float w4 = cos(p.x * 0.85 + p.y * 0.72 - t * 2.7) * 0.25;
vec3 N = normalize(vec3(
(w1 * 0.036 + w3 * 0.028 + w4 * 0.018),
1.0,
(w2 * 0.036 - w3 * 0.025 + w4 * 0.016)
));
vec3 toCam = cameraPosition - vWorldPos;
float dist = length(toCam);
vec3 V = toCam / max(dist, 0.0001);
// Mirrored screen-space reflection UV
vec2 ndc = (vClipPos.xy / max(vClipPos.w, 0.0001)) * 0.5 + 0.5;
float distort = mix(0.038, 0.010, clamp(dist / 260.0, 0.0, 1.0));
vec2 reflUV = vec2(ndc.x, 1.0 - ndc.y) + N.xz * distort;
reflUV = clamp(reflUV, vec2(0.004), vec2(0.996));
vec3 refl = texture2D(uReflectionMap, reflUV).rgb;
float NoV = clamp(dot(N, V), 0.0, 1.0);
float fresnel = mix(0.30, 0.92, pow(1.0 - NoV, 2.7));
vec3 baseWater = mix(uDeepColor, uShallowColor, 0.28 * (1.0 - NoV));
vec3 col = mix(baseWater, refl, fresnel);
// Sparkling golden sun reflection path
vec3 L = normalize(uSunDir);
vec3 H = normalize(L + V);
float sunVis = smoothstep(-0.08, 0.05, L.y);
float specBroad = pow(max(dot(N, H), 0.0), 34.0) * 0.55;
float specSparkle = pow(max(dot(N, H), 0.0), 260.0) * 2.8;
col += uSunColor * (specBroad + specSparkle) * sunVis;
// Moonlight ripple shimmer at twilight/night
vec3 ML = normalize(vec3(0.74, 0.44, 0.48));
vec3 MH = normalize(ML + V);
float mSpec = pow(max(dot(N, MH), 0.0), 140.0) * 0.85 * smoothstep(0.25, 0.85, uNightMix);
col += vec3(0.45, 0.65, 1.0) * mSpec;
// Exponential distance fog matching scene.fog
float fogF = 1.0 - exp(-uFogDensity * uFogDensity * dist * dist);
col = mix(col, uFogColor, clamp(fogF, 0.0, 1.0));
gl_FragColor = vec4(col, 1.0);
#include <tonemapping_fragment>
#include <encodings_fragment>
}
`
});
const waterGeo = new THREE.CircleGeometry(520, 64);
waterGeo.rotateX(-Math.PI / 2);
const waterMesh = new THREE.Mesh(waterGeo, waterMat);
waterMesh.position.y = 0;
scene.add(waterMesh);
// ---------- Procedural Valley Hills, Peninsula & Islands ----------
function getTerrainHeight(x, z) {
const r = Math.hypot(x, z);
const a = Math.atan2(z, x);
// Organic lake shore boundary (western sunset saddle slightly lower)
const coastR = 166
+ 18 * Math.sin(a * 3 + 0.5)
+ 13 * Math.cos(a * 5 - 0.7)
+ 9 * Math.sin(a * 2 + 1.8);
let h = -3.8;
// Surrounding hills rising from shore
if (r > coastR - 14) {
const t = smoothstep(coastR - 14, coastR + 140, r);
const ridge1 = 0.5 + 0.5 * Math.sin(x * 0.022 + z * 0.017);
const ridge2 = 0.5 + 0.5 * Math.cos(x * 0.041 - z * 0.036 + 1.2);
const westDip = 1.0 - 0.48 * Math.exp(-Math.pow(wrapAngle(a - Math.atan2(-0.37, -0.91)) / 0.55, 2));
const hillH = (12 + 54 * ridge1 + 26 * ridge2) * Math.pow(t, 1.32) * westDip;
h = Math.max(h, -3.5 + hillH);
}
// North Town Peninsula (centered around x=14, z=-112, jutting to z=-55)
{
const dx = (x - 10) / 76;
const dz = (z + 114) / 62;
const d = Math.hypot(dx, dz);
if (d < 1.2) {
const s = smoothstep(1.2, 0.25, d);
const slope = smoothstep(-58, -145, z) * 14.0;
const penH = -3.0 + s * (5.6 + slope);
h = Math.max(h, penH);
}
}
// West Lighthouse Island (centered around x=-72, z=-2)
{
const dx = (x + 72) / 34;
const dz = (z + 2) / 28;
const d = Math.hypot(dx, dz);
if (d < 1.15) {
const s = smoothstep(1.15, 0.15, d);
h = Math.max(h, -3.0 + s * 9.8);
}
}
// Southeast Boathouse Island (centered around x=74, z=24)
{
const dx = (x - 74) / 30;
const dz = (z - 24) / 27;
const d = Math.hypot(dx, dz);
if (d < 1.15) {
const s = smoothstep(1.15, 0.15, d);
h = Math.max(h, -3.0 + s * 7.6);
}
}
// Southwest Pine Cove Knoll (centered around x=-76, z=110)
{
const dx = (x + 76) / 36;
const dz = (z - 114) / 30;
const d = Math.hypot(dx, dz);
if (d < 1.15) {
const s = smoothstep(1.15, 0.2, d);
h = Math.max(h, -3.0 + s * 10.5);
}
}
return h;
}
// Build faceted low-poly terrain mesh
function buildTerrain() {
const size = 940;
const segs = 132;
const geo = new THREE.PlaneGeometry(size, size, segs, segs);
geo.rotateX(-Math.PI / 2);
const pos = geo.attributes.position;
const colors = new Float32Array(pos.count * 3);
const cSand = col('#d8ae74');
const cMeadow = col('#5d8448');
const cPine = col('#386144');
const cRock = col('#6e626d');
const cPeak = col('#8a7682');
const tmp = new THREE.Color();
for (let i = 0; i < pos.count; i++) {
const x = pos.getX(i);
const z = pos.getZ(i);
const y = getTerrainHeight(x, z);
pos.setY(i, y);
if (y < 1.4) {
tmp.copy(cSand);
} else if (y < 14) {
tmp.copy(cSand).lerp(cMeadow, smoothstep(1.4, 5.2, y));
} else if (y < 36) {
tmp.copy(cMeadow).lerp(cPine, smoothstep(14, 32, y));
} else {
tmp.copy(cPine).lerp(cRock, smoothstep(34, 52, y)).lerp(cPeak, smoothstep(52, 74, y));
}
// Slight organic variation
const v = 0.94 + 0.12 * Math.sin(x * 0.09) * Math.cos(z * 0.09);
colors[i * 3] = tmp.r * v;
colors[i * 3 + 1] = tmp.g * v;
colors[i * 3 + 2] = tmp.b * v;
}
geo.setAttribute('color', new THREE.BufferAttribute(colors, 3));
geo.computeVertexNormals();
const mat = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.92,
metalness: 0.02,
flatShading: true
});
const mesh = new THREE.Mesh(geo, mat);
mesh.receiveShadow = true;
scene.add(mesh);
}
buildTerrain();
// ---------- Instanced Pine & Cypress Trees ----------
function buildForest() {
const spots = [];
for (let i = 0; i < 650; i++) {
const ang = rand() * Math.PI * 2;
const dist = 50 + rand() * 270;
const x = Math.cos(ang) * dist;
const z = Math.sin(ang) * dist;
const y = getTerrainHeight(x, z);
if (y < 2.3 || y > 44) continue;
// Keep town rooftops & pier approaches clear
if (Math.hypot(x - 12, z + 82) < 38) continue;
if (Math.hypot(x - 62, z + 68) < 16) continue;
if (Math.hypot(x + 24, z + 86) < 16) continue;
if (Math.hypot(x + 72, z + 4) < 14) continue;
if (Math.hypot(x - 76, z - 20) < 14) continue;
spots.push({ x, y, z, s: 0.72 + rand() * 0.75, rot: rand() * Math.PI * 2 });
}
const count = spots.length;
const trunkGeo = new THREE.CylinderGeometry(0.28, 0.45, 2.6, 5);
trunkGeo.translate(0, 1.3, 0);
const trunkMat = new THREE.MeshStandardMaterial({ color: col('#5e3f28'), roughness: 0.95 });
const trunks = new THREE.InstancedMesh(trunkGeo, trunkMat, count);
const crownGeo = new THREE.ConeGeometry(2.2, 6.2, 6);
crownGeo.translate(0, 5.1, 0);
const crownMat = new THREE.MeshStandardMaterial({ color: col('#2f593b'), roughness: 0.9, flatShading: true });
const crowns = new THREE.InstancedMesh(crownGeo, crownMat, count);
crowns.castShadow = true;
const topGeo = new THREE.ConeGeometry(1.55, 4.4, 6);
topGeo.translate(0, 7.6, 0);
const topMat = new THREE.MeshStandardMaterial({ color: col('#3d6d46'), roughness: 0.9, flatShading: true });
const tops = new THREE.InstancedMesh(topGeo, topMat, count);
const dummy = new THREE.Object3D();
spots.forEach((p, idx) => {
dummy.position.set(p.x, p.y - 0.3, p.z);
dummy.rotation.set(0, p.rot, 0);
dummy.scale.setScalar(p.s);
dummy.updateMatrix();
trunks.setMatrixAt(idx, dummy.matrix);
crowns.setMatrixAt(idx, dummy.matrix);
tops.setMatrixAt(idx, dummy.matrix);
});
scene.add(trunks, crowns, tops);
}
buildForest();
// ---------- Dynamic Warm Materials (Windows & Lanterns glow as night falls) ----------
const windowMat = new THREE.MeshStandardMaterial({
color: col('#ffd685'),
emissive: col('#ffaa38'),
emissiveIntensity: 0.55,
roughness: 0.35
});
const lanternBulbMat = new THREE.MeshStandardMaterial({
color: col('#fff0bf'),
emissive: col('#ffb845'),
emissiveIntensity: 1.2,
roughness: 0.2
});
const plankTex = makePlankTexture();
const dockMat = new THREE.MeshStandardMaterial({ map: plankTex, roughness: 0.88 });
const postMat = new THREE.MeshStandardMaterial({ color: col('#593b25'), roughness: 0.92 });
const ironMat = new THREE.MeshStandardMaterial({ color: col('#28252d'), roughness: 0.6, metalness: 0.4 });
const crateTex = makeCrateTexture();
const chuteTex = makeParachuteTexture();
// ---------- Build Cute Stylized Cat Mesh ----------
function createCatMesh(palette) {
const g = new THREE.Group();
const furMat = new THREE.MeshStandardMaterial({ color: col(palette.fur), roughness: 0.82 });
const bellyMat = new THREE.MeshStandardMaterial({ color: col(palette.belly), roughness: 0.85 });
const earInnerMat = new THREE.MeshStandardMaterial({ color: col('#f7a2a8'), roughness: 0.8 });
const eyeMat = new THREE.MeshStandardMaterial({ color: col('#1a1418'), roughness: 0.2 });
// Sitting body
const body = new THREE.Mesh(new THREE.SphereGeometry(0.62, 10, 8), furMat);
body.scale.set(0.95, 1.15, 0.92);
body.position.y = 0.65;
g.add(body);
const chest = new THREE.Mesh(new THREE.SphereGeometry(0.45, 8, 8), bellyMat);
chest.position.set(0, 0.62, 0.26);
g.add(chest);
// Head
const head = new THREE.Mesh(new THREE.SphereGeometry(0.52, 12, 10), furMat);
head.position.set(0, 1.48, 0.08);
g.add(head);
// Ears
const earGeo = new THREE.ConeGeometry(0.2, 0.42, 4);
const earL = new THREE.Mesh(earGeo, furMat);
earL.position.set(-0.3, 1.92, 0.08); earL.rotation.z = 0.22;
const earR = new THREE.Mesh(earGeo, furMat);
earR.position.set(0.3, 1.92, 0.08); earR.rotation.z = -0.22;
g.add(earL, earR);
const inGeo = new THREE.ConeGeometry(0.11, 0.26, 4);
const inL = new THREE.Mesh(inGeo, earInnerMat);
inL.position.set(-0.29, 1.88, 0.14); inL.rotation.z = 0.22;
const inR = new THREE.Mesh(inGeo, earInnerMat);
inR.position.set(0.29, 1.88, 0.14); inR.rotation.z = -0.22;
g.add(inL, inR);
// Eyes & pink nose
const eyeGeo = new THREE.SphereGeometry(0.08, 8, 8);
const eyeL = new THREE.Mesh(eyeGeo, eyeMat);
eyeL.position.set(-0.2, 1.54, 0.52);
const eyeR = new THREE.Mesh(eyeGeo, eyeMat);
eyeR.position.set(0.2, 1.54, 0.52);
g.add(eyeL, eyeR);
const nose = new THREE.Mesh(new THREE.SphereGeometry(0.065, 6, 6), earInnerMat);
nose.position.set(0, 1.42, 0.57);
g.add(nose);
// Waving right paw
const paw = new THREE.Mesh(new THREE.SphereGeometry(0.18, 8, 8), bellyMat);
paw.scale.set(0.85, 1.35, 0.85);
paw.position.set(0.48, 1.05, 0.28);
g.add(paw);
// Curled tail
const tail = new THREE.Mesh(new THREE.CylinderGeometry(0.09, 0.11, 0.85, 6), furMat);
tail.position.set(0, 0.55, -0.58);
tail.rotation.x = -0.55;
g.add(tail);
g.scale.setScalar(1.35);
g.userData = { paw, tail, head };
return g;
}
// ---------- Build Fish Crate Mesh ----------
function createFishCrateMesh() {
const g = new THREE.Group();
const box = new THREE.Mesh(
new THREE.BoxGeometry(1.5, 1.15, 1.5),
new THREE.MeshStandardMaterial({ map: crateTex, roughness: 0.85 })
);
box.position.y = 0.58;
box.castShadow = true;
g.add(box);
// Little silver-blue fish peeking out of the top
const fishMat = new THREE.MeshStandardMaterial({ color: col('#7fb5d4'), roughness: 0.35, metalness: 0.25 });
for (let i = 0; i < 3; i++) {
const f = new THREE.Mesh(new THREE.ConeGeometry(0.22, 0.65, 5), fishMat);
f.position.set((i - 1) * 0.36, 1.24, (i % 2 ? 0.14 : -0.14));
f.rotation.z = (i - 1) * 0.32;
f.rotation.x = 0.25;
g.add(f);
}
return g;
}
// ---------- Build Lake Town Houses, Lighthouse, Docks, Boats ----------
const buildingObstacles = [];
const bobbingBoats = [];
let lighthouseBeam = null;
function addLanternPost(x, y, z, parent) {
const p = new THREE.Group();
p.position.set(x, y, z);
const pole = new THREE.Mesh(new THREE.CylinderGeometry(0.11, 0.15, 3.6, 6), ironMat);
pole.position.y = 1.8;
p.add(pole);
const arm = new THREE.Mesh(new THREE.BoxGeometry(0.85, 0.1, 0.1), ironMat);
arm.position.set(0.35, 3.55, 0);
p.add(arm);
const lamp = new THREE.Mesh(new THREE.OctahedronGeometry(0.32, 0), lanternBulbMat);
lamp.position.set(0.68, 3.3, 0);
p.add(lamp);
const halo = new THREE.Mesh(
new THREE.SphereGeometry(0.85, 8, 8),
new THREE.MeshBasicMaterial({ color: col('#ffba52'), transparent: true, opacity: 0.26, depthWrite: false, blending: THREE.AdditiveBlending })
);
halo.position.copy(lamp.position);
p.add(halo);
(parent || scene).add(p);
}
function addHouse(x, z, w, h, d, wallHex, roofHex, rotY, flatTerrace) {
const groundY = getTerrainHeight(x, z);
const baseY = Math.max(groundY - 1.2, 0.2);
const g = new THREE.Group();
g.position.set(x, baseY, z);
g.rotation.y = rotY;
const wallMat = new THREE.MeshStandardMaterial({ color: col(wallHex), roughness: 0.88 });
const roofMat = new THREE.MeshStandardMaterial({ color: col(roofHex), roughness: 0.85, flatShading: true });
const trimMat = new THREE.MeshStandardMaterial({ color: col('#f2e2c8'), roughness: 0.85 });
const body = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), wallMat);
body.position.y = h * 0.5;
body.castShadow = true;
body.receiveShadow = true;
g.add(body);
// Glowing windows on front & back
const winW = Math.min(1.4, w * 0.22);
const winH = Math.min(1.7, h * 0.26);
const cols = Math.max(1, Math.floor(w / 3.4));
const rows = Math.max(1, Math.floor(h / 4.2));
const winGeo = new THREE.PlaneGeometry(winW, winH);
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
const wx = (c - (cols - 1) * 0.5) * (w / (cols + 0.5));
const wy = h * 0.35 + r * (h * 0.38 / Math.max(1, rows - 0.3));
if (wy > h - 1.1) continue;
const wFront = new THREE.Mesh(winGeo, windowMat);
wFront.position.set(wx, wy, d * 0.5 + 0.04);
g.add(wFront);
const wBack = new THREE.Mesh(winGeo, windowMat);
wBack.position.set(wx, wy, -d * 0.5 - 0.04);
wBack.rotation.y = Math.PI;
g.add(wBack);
}
}
let roofTopY = baseY + h;
if (flatTerrace) {
// Cozy flat Mediterranean rooftop terrace with parapet & warm awning corner
const deck = new THREE.Mesh(new THREE.BoxGeometry(w + 0.7, 0.55, d + 0.7), roofMat);
deck.position.y = h + 0.25;
deck.receiveShadow = true;
g.add(deck);
// Parapet rails
const railH = 0.65;
const p1 = new THREE.Mesh(new THREE.BoxGeometry(w + 0.5, railH, 0.35), trimMat);
p1.position.set(0, h + 0.8, d * 0.5 + 0.15);
const p2 = p1.clone(); p2.position.z = -d * 0.5 - 0.15;
const p3 = new THREE.Mesh(new THREE.BoxGeometry(0.35, railH, d + 0.5), trimMat);
p3.position.set(w * 0.5 + 0.15, h + 0.8, 0);
const p4 = p3.clone(); p4.position.x = -w * 0.5 - 0.15;
g.add(p1, p2, p3, p4);
// Warm rooftop landing rug
const rug = new THREE.Mesh(
new THREE.CircleGeometry(Math.min(w, d) * 0.34, 16),
new THREE.MeshStandardMaterial({ color: col('#e6a953'), roughness: 0.9 })
);
rug.rotation.x = -Math.PI / 2;
rug.position.y = h + 0.56;
g.add(rug);
addLanternPost(w * 0.35, h + 0.52, -d * 0.34, g);
roofTopY = baseY + h + 0.55;
} else {
// Pitched terracotta roof
const roofH = Math.min(w, d) * 0.52;
const roof = new THREE.Mesh(new THREE.ConeGeometry(Math.hypot(w, d) * 0.54, roofH, 4), roofMat);
roof.position.y = h + roofH * 0.5;
roof.rotation.y = Math.PI * 0.25;
roof.castShadow = true;
g.add(roof);
// Tiny chimney
if (rand() > 0.35) {
const ch = new THREE.Mesh(new THREE.BoxGeometry(0.9, 2.2, 0.9), trimMat);
ch.position.set(w * 0.22, h + roofH * 0.55, 0);
g.add(ch);
}
roofTopY = baseY + h + roofH;
}
scene.add(g);
buildingObstacles.push({ x, z, r: Math.max(w, d) * 0.65, topY: roofTopY + 1.5 });
return roofTopY;
}
function addDock(x, z, len, width, angleY) {
const g = new THREE.Group();
g.position.set(x, 1.35, z);
g.rotation.y = angleY;
const deck = new THREE.Mesh(new THREE.BoxGeometry(width, 0.45, len), dockMat);
deck.receiveShadow = true;
deck.castShadow = true;
g.add(deck);
// Wooden pilings descending into lake
const pairs = Math.max(3, Math.floor(len / 5.5));
const pileGeo = new THREE.CylinderGeometry(0.28, 0.32, 5.2, 6);
for (let i = 0; i <= pairs; i++) {
const pz = -len * 0.45 + (i / pairs) * len * 0.9;
for (const side of [-1, 1]) {
const pile = new THREE.Mesh(pileGeo, postMat);
pile.position.set(side * (width * 0.44), -1.7, pz);
g.add(pile);
}
}
// Warm dockside lantern & landing mat near the tip
addLanternPost(width * 0.36, 0.2, len * 0.38, g);
const mat = new THREE.Mesh(
new THREE.CircleGeometry(width * 0.34, 14),
new THREE.MeshStandardMaterial({ color: col('#df9948'), roughness: 0.9 })
);
mat.rotation.x = -Math.PI / 2;
mat.position.set(0, 0.25, len * 0.3);
g.add(mat);
scene.add(g);
// Return world position of the tip of the dock where the cat waits
const tipOffset = new THREE.Vector3(0, 0.25, len * 0.32).applyAxisAngle(new THREE.Vector3(0, 1, 0), angleY);
return new THREE.Vector3(x + tipOffset.x, 1.6, z + tipOffset.z);
}
function addBoat(x, z, rotY, hullHex) {
const g = new THREE.Group();
g.position.set(x, 0.25, z);
g.rotation.y = rotY;
const hull = new THREE.Mesh(
new THREE.BoxGeometry(2.2, 0.9, 5.2),
new THREE.MeshStandardMaterial({ color: col(hullHex), roughness: 0.8 })
);
hull.position.y = 0.2;
g.add(hull);
const bow = new THREE.Mesh(
new THREE.ConeGeometry(1.2, 1.8, 4),
new THREE.MeshStandardMaterial({ color: col(hullHex), roughness: 0.8 })
);
bow.rotation.x = -Math.PI / 2;
bow.rotation.z = Math.PI / 4;
bow.position.set(0, 0.25, -3.2);
g.add(bow);
const mast = new THREE.Mesh(new THREE.CylinderGeometry(0.08, 0.1, 4.6, 5), postMat);
mast.position.set(0, 2.5, -0.3);
g.add(mast);
const sail = new THREE.Mesh(
new THREE.ConeGeometry(1.5, 3.6, 3),
new THREE.MeshStandardMaterial({ color: col('#fff2d9'), roughness: 0.9, side: THREE.DoubleSide })
);
sail.scale.set(0.12, 1, 0.95);
sail.position.set(0, 2.7, 0.3);
g.add(sail);
scene.add(g);
bobbingBoats.push({ mesh: g, phase: rand() * Math.PI * 2, baseY: 0.22 });
}
function addLighthouse(x, z) {
const gy = getTerrainHeight(x, z);
const g = new THREE.Group();
g.position.set(x, Math.max(gy - 0.8, 1.5), z);
const towerMat = new THREE.MeshStandardMaterial({ color: col('#f8efe0'), roughness: 0.8 });
const stripeMat = new THREE.MeshStandardMaterial({ color: col('#d94b3b'), roughness: 0.82 });
const base = new THREE.Mesh(new THREE.CylinderGeometry(2.5, 3.3, 14, 10), towerMat);
base.position.y = 7;
base.castShadow = true;
g.add(base);
const band = new THREE.Mesh(new THREE.CylinderGeometry(2.74, 2.95, 3.6, 10), stripeMat);
band.position.y = 8.4;
g.add(band);
const gallery = new THREE.Mesh(new THREE.CylinderGeometry(3.0, 2.8, 0.8, 10), ironMat);
gallery.position.y = 14.2;
g.add(gallery);
const lanternGlass = new THREE.Mesh(new THREE.CylinderGeometry(1.75, 1.75, 2.8, 10), lanternBulbMat);
lanternGlass.position.y = 15.8;
g.add(lanternGlass);
const cap = new THREE.Mesh(new THREE.ConeGeometry(2.3, 2.4, 10), stripeMat);
cap.position.y = 18.3;
g.add(cap);
// Soft rotating golden lighthouse beam
const beamPivot = new THREE.Group();
beamPivot.position.y = 15.8;
const beamGeo = new THREE.ConeGeometry(10, 82, 16, 1, true);
beamGeo.translate(0, -41, 0);
beamGeo.rotateX(Math.PI / 2);
const beamMat = new THREE.MeshBasicMaterial({
color: col('#ffd27d'),
transparent: true,
opacity: 0.10,
side: THREE.DoubleSide,
depthWrite: false,
blending: THREE.AdditiveBlending
});
const beam1 = new THREE.Mesh(beamGeo, beamMat);
const beam2 = new THREE.Mesh(beamGeo, beamMat);
beam2.rotation.y = Math.PI;
beamPivot.add(beam1, beam2);
g.add(beamPivot);
lighthouseBeam = { pivot: beamPivot, mat: beamMat };
scene.add(g);
buildingObstacles.push({ x, z, r: 4.5, topY: g.position.y + 21 });
}
// Build the 8 Delivery Sites (4 Rooftops + 4 Docks) & Surrounding Village
const wallPalette = ['#f7e4c8', '#f2cfa5', '#ecc198', '#f4d9c6', '#e6d8be', '#dfd2dc'];
const roofPalette = ['#c9563c', '#b84b39', '#d47144', '#a64d42', '#6a5d7b'];
const catPalettes = [
{ fur: '#f28c38', belly: '#ffe3bd', name: 'Marmalade Cat' },
{ fur: '#2b2833', belly: '#f4efe6', name: 'Tuxedo Cat' },
{ fur: '#918c96', belly: '#e4e0e6', name: 'Silver Tabby' },
{ fur: '#f5e2c4', belly: '#fff7eb', name: 'Cream Cat' },
{ fur: '#c46b3e', belly: '#fae0c3', name: 'Cinnamon Cat' },
{ fur: '#4d4147', belly: '#e8d7c5', name: 'Smokey Cat' },
{ fur: '#e8b674', belly: '#fff2db', name: 'Honey Cat' },
{ fur: '#d8764f', belly: '#ffe8ce', name: 'Calico Cat' }
];
// Decorative lake-town houses on peninsula, hillside & islands
const decoHouses = [
[4, -84, 8, 7, 7, 0.1], [24, -92, 9, 8.5, 7.5, -0.2], [40, -86, 7.5, 6.5, 7, 0.25],
[-4, -104, 10, 9.5, 8, 0.05], [16, -112, 9, 10, 8, -0.1], [38, -108, 8.5, 8, 7.5, 0.15],
[-38, -104, 8, 7.5, 7, 0.3], [-48, -86, 7, 6.5, 6.5, 0.45], [52, -96, 8, 8, 7, -0.35],
[76, -86, 7.5, 7, 6.5, -0.5], [0, -128, 11, 11, 8.5, 0.0], [28, -130, 9.5, 9, 8, -0.15],
[-22, -124, 8.5, 8.5, 7.5, 0.2], [58, -114, 9, 8.5, 7.5, -0.25],
// Lighthouse island cottages
[-86, -8, 6.5, 5.5, 6, 0.4], [-64, 12, 6.5, 5.2, 6, -0.35],
// Southeast island cottages
[88, 32, 6.5, 5.5, 6, -0.5], [64, 38, 6, 5, 5.8, 0.3],
// Southwest Pine Cove cottages
[-82, 114, 7.5, 6.5, 6.8, 0.6], [-66, 124, 6.8, 5.8, 6.2, 0.2]
];
decoHouses.forEach((h, i) => {
addHouse(h[0], h[1], h[2], h[3], h[4], wallPalette[i % wallPalette.length], roofPalette[i % roofPalette.length], h[5], false);
});
// Iconic Lighthouse on West Island
addLighthouse(-82, 6);
// Moored bobbing sailboats around the harbor
addBoat(26, -34, 0.5, '#d15a47');
addBoat(-8, -42, -0.4, '#4e7ea1');
addBoat(52, 6, 1.1, '#d89b44');
addBoat(-44, 44, -0.9, '#c75c52');
addBoat(-30, 82, 0.7, '#4c8277');
// Build the 8 Delivery Targets (4 Docks + 4 Flat Rooftops)
const dock1Tip = addDock(46, 38, 22, 5.4, -0.78); // East Bay Dock (SE Island)
const roof2Y = addHouse(76, 16, 10.5, 8.2, 9.5, '#f6dfb9', '#c9573e', -0.45, true); // Boathouse Roof
const roof3Y = addHouse(62, -68, 11.2, 9.2, 9.6, '#f2d3b0', '#b84c3a', -0.3, true); // Hillside Inn Roof
const dock4Tip = addDock(12, -60, 24, 5.8, 0.06); // Harbor Pier (Town Peninsula)
const roof5Y = addHouse(-24, -84, 10.4, 8.6, 9.4, '#f7e5cc', '#d46c42', 0.25, true); // Bakery Rooftop
const roof6Y = addHouse(-68, -6, 10.2, 8.0, 9.2, '#f0d9c2', '#be513b', 0.35, true); // Lighthouse Terrace
const dock7Tip = addDock(-46, 16, 22, 5.4, 0.85); // Sunset Wharf (West Island)
const dock8Tip = addDock(-62, 100, 22, 5.4, -2.55); // Pine Cove Pier (SW Shore)
const targetDefs = [
{ name: 'East Bay Dock', kind: 'Dock', land: dock1Tip, ringY: 22, ringYaw: -0.55 },
{ name: 'Boathouse Roof', kind: 'Rooftop', land: new THREE.Vector3(76, roof2Y, 16), ringY: 29, ringYaw: 0.15 },
{ name: 'Hillside Inn Roof', kind: 'Rooftop', land: new THREE.Vector3(62, roof3Y, -68), ringY: 35, ringYaw: 0.95 },
{ name: 'Harbor Pier', kind: 'Dock', land: dock4Tip, ringY: 23, ringYaw: 1.45 },
{ name: 'Bakery Rooftop', kind: 'Rooftop', land: new THREE.Vector3(-24, roof5Y, -84), ringY: 31, ringYaw: 1.95 },
{ name: 'Lighthouse Terrace', kind: 'Rooftop', land: new THREE.Vector3(-68, roof6Y, -6), ringY: 33, ringYaw: 2.95 },
{ name: 'Sunset Wharf', kind: 'Dock', land: dock7Tip, ringY: 23, ringYaw: -2.45 },
{ name: 'Pine Cove Pier', kind: 'Dock', land: dock8Tip, ringY: 23, ringYaw: -1.85 }
];
// ---------- Glowing Sky Rings & Waiting Cats ----------
const targets = [];
const ringMatBase = new THREE.MeshStandardMaterial({
color: col('#ffd675'),
emissive: col('#ff9d2e'),
emissiveIntensity: 1.45,
roughness: 0.25,
metalness: 0.15
});
const innerGlowMatBase = new THREE.MeshBasicMaterial({
color: col('#ffe499'),
transparent: true,
opacity: 0.28,
side: THREE.DoubleSide,
depthWrite: false,
blending: THREE.AdditiveBlending
});
const beamMatBase = new THREE.MeshBasicMaterial({
color: col('#ffcb6b'),
transparent: true,
opacity: 0.13,
side: THREE.DoubleSide,
depthWrite: false,
blending: THREE.AdditiveBlending
});
targetDefs.forEach((def, idx) => {
const ringPos = new THREE.Vector3(def.land.x, def.ringY, def.land.z);
const ringGroup = new THREE.Group();
ringGroup.position.copy(ringPos);
ringGroup.rotation.y = def.ringYaw;
const rMat = ringMatBase.clone();
const torus = new THREE.Mesh(new THREE.TorusGeometry(6.1, 0.42, 12, 36), rMat);
ringGroup.add(torus);
const innerHalo = new THREE.Mesh(new THREE.RingGeometry(4.6, 6.2, 32), innerGlowMatBase.clone());
ringGroup.add(innerHalo);
// Subtle orbiting sparkle dots around ring
const orbGroup = new THREE.Group();
const dotGeo = new THREE.OctahedronGeometry(0.35, 0);
const dotMat = new THREE.MeshBasicMaterial({ color: col('#fff2bd') });
for (let k = 0; k < 6; k++) {
const a = (k / 6) * Math.PI * 2;
const dot = new THREE.Mesh(dotGeo, dotMat);
dot.position.set(Math.cos(a) * 6.9, Math.sin(a) * 6.9, 0);
orbGroup.add(dot);
}
ringGroup.add(orbGroup);
scene.add(ringGroup);
// Vertical soft light pillar connecting ring down to the waiting cat
const beamH = Math.max(4, ringPos.y - def.land.y);
const beamGeo = new THREE.CylinderGeometry(0.75, 2.5, beamH, 12, 1, true);
const beam = new THREE.Mesh(beamGeo, beamMatBase.clone());
beam.position.set(def.land.x, def.land.y + beamH * 0.5, def.land.z);
scene.add(beam);
// Waiting cat on the rooftop or dock
const cat = createCatMesh(catPalettes[idx % catPalettes.length]);
cat.position.set(def.land.x, def.land.y, def.land.z);
// Face toward the center of the lake
cat.rotation.y = Math.atan2(-def.land.x, -def.land.z);
scene.add(cat);
// Delivered crate (hidden until parachute lands)
const landedCrate = createFishCrateMesh();
landedCrate.position.set(def.land.x + 1.5, def.land.y, def.land.z + 0.6);
landedCrate.visible = false;
scene.add(landedCrate);
targets.push({
id: idx,
name: def.name,
kind: def.kind,
catName: catPalettes[idx % catPalettes.length].name,
landPos: def.land.clone(),
ringPos,
ringGroup,
torus,
ringMat: rMat,
innerHalo,
orbGroup,
beam,
cat,
landedCrate,
triggered: false,
delivered: false,
celebrateTimer: 0
});
});
// ---------- Fluffy Stylized Sunset Clouds ----------
const clouds = [];
const cloudMat = new THREE.MeshStandardMaterial({
color: col('#fff0dc'),
emissive: col('#ff9860'),
emissiveIntensity: 0.22,
roughness: 0.96,
metalness: 0.0,
flatShading: true
});
function buildClouds() {
const puffGeo = new THREE.IcosahedronGeometry(1, 1);
for (let i = 0; i < 26; i++) {
const cg = new THREE.Group();
const puffs = 4 + Math.floor(rand() * 4);
for (let p = 0; p < puffs; p++) {
const m = new THREE.Mesh(puffGeo, cloudMat);
const s = 5.5 + rand() * 7.5;
m.scale.set(s * 1.45, s * 0.62, s * 1.08);
m.position.set((p - (puffs - 1) * 0.5) * 7.2 + (rand() - 0.5) * 3, (rand() - 0.5) * 2.2, (rand() - 0.5) * 5.2);
cg.add(m);
}
const ang = rand() * Math.PI * 2;
const dist = 55 + rand() * 340;
cg.position.set(Math.cos(ang) * dist, 62 + rand() * 44, Math.sin(ang) * dist);
cg.rotation.y = rand() * Math.PI * 2;
scene.add(cg);
clouds.push({ mesh: cg, speed: 1.2 + rand() * 1.6 });
}
}
buildClouds();
// ---------- Ambient Gliding Sunset Birds ----------
const birds = [];
function buildBirds() {
const bMat = new THREE.MeshBasicMaterial({ color: col('#382838'), side: THREE.DoubleSide });
const wingGeo = new THREE.PlaneGeometry(1.1, 0.34);
wingGeo.translate(0.55, 0, 0);
for (let i = 0; i < 8; i++) {
const bg = new THREE.Group();
const wL = new THREE.Mesh(wingGeo, bMat);
wL.rotation.x = -Math.PI / 2;
wL.rotation.z = Math.PI;
const wR = new THREE.Mesh(wingGeo, bMat);
wR.rotation.x = -Math.PI / 2;
bg.add(wL, wR);
scene.add(bg);
birds.push({
group: bg, wL, wR,
radius: 65 + rand() * 85,
height: 44 + rand() * 20,
angle: rand() * Math.PI * 2,
speed: 0.14 + rand() * 0.08,
flapPhase: rand() * 6
});
}
}
buildBirds();
// ---------- Hero: Orange Cat & Little Propeller Plane ----------
const planeGroup = new THREE.Group();
planeGroup.rotation.order = 'YXZ';
scene.add(planeGroup);
const creamMat = new THREE.MeshStandardMaterial({ color: col('#fbf0dc'), roughness: 0.48, metalness: 0.08 });
const redMat = new THREE.MeshStandardMaterial({ color: col('#dd4b39'), roughness: 0.45, metalness: 0.12 });
const brassMat = new THREE.MeshStandardMaterial({ color: col('#d8a64b'), roughness: 0.35, metalness: 0.65 });
const woodMat = new THREE.MeshStandardMaterial({ color: col('#7b4c28'), roughness: 0.68 });
const orangeFurMat = new THREE.MeshStandardMaterial({ color: col('#f58a2c'), roughness: 0.78 });
const stripeFurMat = new THREE.MeshStandardMaterial({ color: col('#b95516'), roughness: 0.82 });
const lightFurMat = new THREE.MeshStandardMaterial({ color: col('#ffe3bd'), roughness: 0.8 });
// Fuselage (forward = -Z)
const noseCone = new THREE.Mesh(new THREE.CylinderGeometry(0.48, 0.72, 1.05, 12), redMat);
noseCone.rotation.x = Math.PI / 2;
noseCone.position.set(0, 0.02, -1.62);
noseCone.castShadow = true;
planeGroup.add(noseCone);
const cowlRing = new THREE.Mesh(new THREE.TorusGeometry(0.49, 0.06, 8, 16), brassMat);
cowlRing.position.set(0, 0.02, -2.14);
planeGroup.add(cowlRing);
const bodyMid = new THREE.Mesh(new THREE.BoxGeometry(1.38, 1.02, 1.85), creamMat);
bodyMid.position.set(0, -0.04, -0.22);
bodyMid.castShadow = true;
planeGroup.add(bodyMid);
// Red side racing stripe
const stripe = new THREE.Mesh(new THREE.BoxGeometry(1.42, 0.22, 1.86), redMat);
stripe.position.set(0, -0.05, -0.22);
planeGroup.add(stripe);
// Tapered tail fuselage
const tailCone = new THREE.Mesh(new THREE.CylinderGeometry(0.24, 0.66, 2.05, 10), creamMat);
tailCone.rotation.x = -Math.PI / 2;
tailCone.position.set(0, 0.05, 1.65);
tailCone.castShadow = true;
planeGroup.add(tailCone);
// Main Wings with gentle dihedral
const wingGeo = new THREE.BoxGeometry(3.55, 0.16, 1.28);
const wingL = new THREE.Mesh(wingGeo, creamMat);
wingL.position.set(-2.35, -0.05, -0.52);
wingL.rotation.z = -0.055;
wingL.castShadow = true;
const wingR = new THREE.Mesh(wingGeo, creamMat);
wingR.position.set(2.35, -0.05, -0.52);
wingR.rotation.z = 0.055;
wingR.castShadow = true;
planeGroup.add(wingL, wingR);
// Red rounded wingtips + nav lights
const tipGeo = new THREE.BoxGeometry(0.65, 0.17, 1.22);
const tipL = new THREE.Mesh(tipGeo, redMat);
tipL.position.set(-4.35, 0.06, -0.52);
tipL.rotation.z = -0.055;
const tipR = new THREE.Mesh(tipGeo, redMat);
tipR.position.set(4.35, 0.06, -0.52);
tipR.rotation.z = 0.055;
planeGroup.add(tipL, tipR);
const navPortMat = new THREE.MeshBasicMaterial({ color: col('#ff4242') });
const navStbdMat = new THREE.MeshBasicMaterial({ color: col('#44ff78') });
const navL = new THREE.Mesh(new THREE.SphereGeometry(0.11, 8, 8), navPortMat);
navL.position.set(-4.68, 0.1, -0.52);
const navR = new THREE.Mesh(new THREE.SphereGeometry(0.11, 8, 8), navStbdMat);
navR.position.set(4.68, 0.1, -0.52);
planeGroup.add(navL, navR);
// Cute twin landing pontoons / skids underneath (lake floatplane charm!)
const floatGeo = new THREE.CylinderGeometry(0.16, 0.22, 2.6, 8);
floatGeo.rotateX(Math.PI / 2);
for (const s of [-1, 1]) {
const fl = new THREE.Mesh(floatGeo, creamMat);
fl.position.set(s * 0.95, -0.95, -0.5);
planeGroup.add(fl);
const flTip = new THREE.Mesh(new THREE.ConeGeometry(0.16, 0.5, 8), redMat);
flTip.rotation.x = -Math.PI / 2;
flTip.position.set(s * 0.95, -0.95, -2.05);
planeGroup.add(flTip);
const strut = new THREE.Mesh(new THREE.CylinderGeometry(0.045, 0.045, 0.82, 5), woodMat);
strut.position.set(s * 0.8, -0.55, -0.65);
strut.rotation.z = s * 0.25;
planeGroup.add(strut);
const strut2 = strut.clone();
strut2.position.z = -0.05;
planeGroup.add(strut2);
}
// Animated Ailerons
const aileronL = new THREE.Mesh(new THREE.BoxGeometry(1.4, 0.09, 0.34), redMat);
aileronL.position.set(-3.1, -0.02, 0.18);
const aileronR = new THREE.Mesh(new THREE.BoxGeometry(1.4, 0.09, 0.34), redMat);
aileronR.position.set(3.1, -0.02, 0.18);
planeGroup.add(aileronL, aileronR);
// Tail Stabilizer, Elevator & Rudder
const hStab = new THREE.Mesh(new THREE.BoxGeometry(2.6, 0.11, 0.65), creamMat);
hStab.position.set(0, 0.24, 2.35);
planeGroup.add(hStab);
const elevator = new THREE.Mesh(new THREE.BoxGeometry(2.4, 0.09, 0.32), redMat);
elevator.position.set(0, 0.24, 2.75);
planeGroup.add(elevator);
const vFinMat = new THREE.MeshStandardMaterial({ map: makeTailBadgeTexture(), roughness: 0.5 });
const vFin = new THREE.Mesh(new THREE.BoxGeometry(0.12, 1.15, 0.95), vFinMat);
vFin.position.set(0, 0.72, 2.3);
planeGroup.add(vFin);
const rudder = new THREE.Mesh(new THREE.BoxGeometry(0.11, 1.05, 0.42), redMat);
rudder.position.set(0, 0.72, 2.86);
planeGroup.add(rudder);
// Spinning Propeller + Blur Disc
const propGroup = new THREE.Group();
propGroup.position.set(0, 0.02, -2.26);
const spinner = new THREE.Mesh(new THREE.ConeGeometry(0.24, 0.48, 10), brassMat);
spinner.rotation.x = -Math.PI / 2;
spinner.position.z = -0.14;
propGroup.add(spinner);
const blade = new THREE.Mesh(new THREE.BoxGeometry(2.15, 0.18, 0.06), woodMat);
propGroup.add(blade);
const propBlur = new THREE.Mesh(
new THREE.CircleGeometry(1.06, 20),
new THREE.MeshBasicMaterial({ color: col('#ffe8c6'), transparent: true, opacity: 0.16, side: THREE.DoubleSide, depthWrite: false })
);
propGroup.add(propBlur);
planeGroup.add(propGroup);
// Belly Fish Crate (hidden when 0 crates left)
const bellyCrate = createFishCrateMesh();
bellyCrate.scale.setScalar(0.58);
bellyCrate.position.set(0, -1.08, -0.35);
planeGroup.add(bellyCrate);
// Cockpit Coaming, Windscreen & Working Analog Dashboard Gauges!
const cockpitTrim = new THREE.Mesh(new THREE.BoxGeometry(1.44, 0.24, 0.22), woodMat);
cockpitTrim.position.set(0, 0.54, -0.82);
planeGroup.add(cockpitTrim);
// Side cockpit rails
for (const s of [-1, 1]) {
const rail = new THREE.Mesh(new THREE.BoxGeometry(0.14, 0.22, 1.45), woodMat);
rail.position.set(s * 0.68, 0.53, -0.1);
planeGroup.add(rail);
}
// Dashboard panel facing pilot (+Z)
const dashBoard = new THREE.Mesh(new THREE.BoxGeometry(1.24, 0.42, 0.12), woodMat);
dashBoard.position.set(0, 0.46, -0.78);
planeGroup.add(dashBoard);
// 3 Working Brass-Rimmed Gauges (Compass, Altitude, Sunset)
const gaugeNeedles = {};
const gaugeSpecs = [
{ key: 'compass', x: -0.36, label: 'HDG', accent: '#ff7b57' },
{ key: 'alt', x: 0.0, label: 'ALT', accent: '#6fd8ff' },
{ key: 'sun', x: 0.36, label: 'SUN', accent: '#ffcb5c' }
];
gaugeSpecs.forEach((gs) => {
const dial = new THREE.Mesh(
new THREE.CircleGeometry(0.145, 16),
new THREE.MeshBasicMaterial({ map: makeDialTexture(gs.label, gs.accent) })
);
dial.position.set(gs.x, 0.47, -0.715);
planeGroup.add(dial);
const nPivot = new THREE.Group();
nPivot.position.set(gs.x, 0.47, -0.708);
const needle = new THREE.Mesh(
new THREE.BoxGeometry(0.018, 0.105, 0.01),
new THREE.MeshBasicMaterial({ color: col('#ff6040') })
);
needle.position.y = 0.036;
nPivot.add(needle);
planeGroup.add(nPivot);
gaugeNeedles[gs.key] = nPivot;
});
// Curved Windscreen Arch + Translucent Glass
const glassMat = new THREE.MeshStandardMaterial({
color: col('#d6f1ff'),
transparent: true,
opacity: 0.22,
roughness: 0.1,
metalness: 0.2,
side: THREE.DoubleSide,
depthWrite: false
});
const windscreen = new THREE.Mesh(new THREE.CylinderGeometry(0.62, 0.66, 0.56, 12, 1, true, -Math.PI * 0.42, Math.PI * 0.84), glassMat);
windscreen.rotation.y = Math.PI;
windscreen.rotation.x = 0.36;
windscreen.position.set(0, 0.72, -0.76);
planeGroup.add(windscreen);
const windArch = new THREE.Mesh(new THREE.TorusGeometry(0.62, 0.032, 6, 16, Math.PI * 0.86), brassMat);
windArch.position.set(0, 0.56, -0.82);
windArch.rotation.z = Math.PI * 0.07;
windArch.rotation.x = -0.35;
planeGroup.add(windArch);
// Moving Flight Control Stick + Orange Cat Paws (visible in Cockpit AND Behind views!)
const stickPivot = new THREE.Group();
stickPivot.position.set(0, 0.02, -0.45);
const stickShaft = new THREE.Mesh(new THREE.CylinderGeometry(0.035, 0.042, 0.54, 8), woodMat);
stickShaft.position.y = 0.27;
stickPivot.add(stickShaft);
const stickKnob = new THREE.Mesh(new THREE.SphereGeometry(0.068, 8, 8), redMat);
stickKnob.position.y = 0.55;
stickPivot.add(stickKnob);
// Cute orange paws gripping the stick!
const pawL = new THREE.Mesh(new THREE.SphereGeometry(0.11, 8, 8), orangeFurMat);
pawL.scale.set(0.95, 0.85, 1.3);
pawL.position.set(-0.11, 0.49, 0.04);
const pawR = pawL.clone();
pawR.position.x = 0.11;
stickPivot.add(pawL, pawR);
planeGroup.add(stickPivot);
// Orange Cat Pilot Head & Fluttering Scarf (hidden in Cockpit view so view is unobstructed!)
const catPilotGroup = new THREE.Group();
catPilotGroup.position.set(0, 0.52, 0.08);
const pilotTorso = new THREE.Mesh(new THREE.SphereGeometry(0.42, 10, 8), orangeFurMat);
pilotTorso.position.set(0, -0.08, 0.04);
catPilotGroup.add(pilotTorso);
const pilotHead = new THREE.Mesh(new THREE.SphereGeometry(0.42, 14, 12), orangeFurMat);
pilotHead.position.set(0, 0.42, 0.0);
pilotHead.castShadow = true;
catPilotGroup.add(pilotHead);
// Tabby forehead stripes
for (const sx of [-0.11, 0, 0.11]) {
const st = new THREE.Mesh(new THREE.BoxGeometry(0.055, 0.14, 0.12), stripeFurMat);
st.position.set(sx, 0.75, -0.22);
catPilotGroup.add(st);
}
// Cheeks & muzzle
const muzzle = new THREE.Mesh(new THREE.SphereGeometry(0.17, 8, 8), lightFurMat);
muzzle.scale.set(1.3, 0.85, 0.85);
muzzle.position.set(0, 0.32, -0.35);
catPilotGroup.add(muzzle);
// Pointy cat ears
const pEarGeo = new THREE.ConeGeometry(0.16, 0.34, 4);
const pEarL = new THREE.Mesh(pEarGeo, orangeFurMat);
pEarL.position.set(-0.25, 0.78, 0.0); pEarL.rotation.z = 0.25;
const pEarR = new THREE.Mesh(pEarGeo, orangeFurMat);
pEarR.position.set(0.25, 0.78, 0.0); pEarR.rotation.z = -0.25;
catPilotGroup.add(pEarL, pEarR);
// Vintage Brass Aviator Goggles perched on forehead
const gogStrap = new THREE.Mesh(new THREE.TorusGeometry(0.41, 0.045, 6, 18), woodMat);
gogStrap.rotation.x = Math.PI / 2 - 0.18;
gogStrap.position.set(0, 0.56, 0.02);
catPilotGroup.add(gogStrap);
const gogGlassMat = new THREE.MeshStandardMaterial({ color: col('#69c8ff'), roughness: 0.15, metalness: 0.4 });
for (const s of [-1, 1]) {
const rim = new THREE.Mesh(new THREE.TorusGeometry(0.12, 0.028, 6, 12), brassMat);
rim.position.set(s * 0.15, 0.57, -0.38);
catPilotGroup.add(rim);
const lens = new THREE.Mesh(new THREE.CircleGeometry(0.11, 12), gogGlassMat);
lens.position.set(s * 0.15, 0.57, -0.39);
lens.rotation.y = Math.PI;
catPilotGroup.add(lens);
}
// Cute warm fluttering red aviator scarf (5 animated segments)
const scarfSegs = [];
const scarfMat = new THREE.MeshStandardMaterial({ color: col('#e84735'), roughness: 0.75 });
const neckScarf = new THREE.Mesh(new THREE.TorusGeometry(0.32, 0.09, 6, 14), scarfMat);
neckScarf.rotation.x = Math.PI / 2;
neckScarf.position.set(0, 0.12, 0.02);
catPilotGroup.add(neckScarf);
for (let i = 0; i < 5; i++) {
const seg = new THREE.Mesh(new THREE.BoxGeometry(0.24 - i * 0.02, 0.055, 0.28), scarfMat);
seg.position.set(0.16, 0.14, 0.34 + i * 0.24);
catPilotGroup.add(seg);
scarfSegs.push(seg);
}
planeGroup.add(catPilotGroup);
// Warm plane nose light (activates as dusk deepens)
const planeGlowLight = new THREE.PointLight(col('#ffb75e'), 0.0, 26);
planeGlowLight.position.set(0, 0.2, -2.5);
planeGroup.add(planeGlowLight);
// Wingtip Ribbon Trails
const TRAIL_LEN = 26;
function createWingTrail() {
const geo = new THREE.BufferGeometry();
const positions = new Float32Array(TRAIL_LEN * 3);
geo.setAttribute('position', new THREE.BufferAttribute(positions, 3));
const mat = new THREE.LineBasicMaterial({
color: col('#ffe4b8'),
transparent: true,
opacity: 0.38
});
const line = new THREE.Line(geo, mat);
line.frustumCulled = false;
scene.add(line);
return { line, positions, pts: [] };
}
const trailL = createWingTrail();
const trailR = createWingTrail();
// ---------- Active Parachutes & Celebration Particles ----------
const activeParachutes = [];
const particles = [];
const particleGeo = new THREE.OctahedronGeometry(0.36, 0);
function spawnParticles(pos, count, hexColors, speed, life) {
for (let i = 0; i < count; i++) {
const m = new THREE.Mesh(
particleGeo,
new THREE.MeshBasicMaterial({
color: col(hexColors[i % hexColors.length]),
transparent: true,
opacity: 1.0
})
);
m.position.copy(pos);
const a = Math.random() * Math.PI * 2;
const up = (Math.random() * 0.8 + 0.3) * speed;
const hsp = (Math.random() * 0.7 + 0.3) * speed;
scene.add(m);
particles.push({
mesh: m,
vel: new THREE.Vector3(Math.cos(a) * hsp, up, Math.sin(a) * hsp),
age: 0,
life: life * (0.7 + Math.random() * 0.6),
gravity: speed * 0.85
});
}
}
function spawnParachuteDrop(target, dropStartPos) {
const group = new THREE.Group();
group.position.copy(dropStartPos);
// Fish crate at bottom
const crate = createFishCrateMesh();
crate.position.set(0, -1.1, 0);
group.add(crate);
// Parachute canopy + shroud cords
const canopyGroup = new THREE.Group();
const dome = new THREE.Mesh(
new THREE.SphereGeometry(2.35, 16, 10, 0, Math.PI * 2, 0, Math.PI * 0.56),
new THREE.MeshStandardMaterial({ map: chuteTex, roughness: 0.82, side: THREE.DoubleSide })
);
dome.position.y = 2.6;
canopyGroup.add(dome);
const cordMat = new THREE.LineBasicMaterial({ color: col('#f5e5cc') });
const cordPts = [];
for (let i = 0; i < 4; i++) {
const a = (i / 4) * Math.PI * 2 + Math.PI * 0.25;
cordPts.push(
new THREE.Vector3(Math.cos(a) * 0.6, 0.0, Math.sin(a) * 0.6),
new THREE.Vector3(Math.cos(a) * 2.15, 2.7, Math.sin(a) * 2.15)
);
}
const cordGeo = new THREE.BufferGeometry().setFromPoints(cordPts);
canopyGroup.add(new THREE.LineSegments(cordGeo, cordMat));
canopyGroup.scale.setScalar(0.15);
group.add(canopyGroup);
scene.add(group);
activeParachutes.push({
group,
canopyGroup,
target,
startPos: dropStartPos.clone(),
age: 0,
landed: false,
fadeAge: 0
});
}
// ---------- Game State ----------
const TOTAL_TIME = 95;
const plane = {
pos: new THREE.Vector3(6, 25, 96),
yaw: -0.49,
pitch: 0,
roll: 0,
speed: 26,
boostTimer: 0
};
let gameMode = 'title'; // 'title' | 'playing' | 'ended'
let demoMode = false;
let demoClock = 0;
let cameraMode = 'behind'; // 'behind' | 'cockpit' | 'above'
let score = 0;
let cratesTriggered = 0;
let cratesDelivered = 0;
let timeLeft = TOTAL_TIME;
let comboCount = 0;
let lastRingTime = -99;
let toastTimer = 0;
let pendingWinTimer = -1;
let simTime = 0;
let waterSprayCooldown = 0;
// Steering input state
const input = {
mode: 'none', // 'mouse' | 'touch'
steerX: 0,
steerY: 0,
targetX: 0,
targetY: 0,
mouseActive: false,
lastMouseX: -999,
lastMouseY: -999,
touchId: null,
originX: 0,
originY: 0,
curX: 0,
curY: 0
};
// Camera smoothing state
const camPosSmooth = new THREE.Vector3(12, 30, 108);
const camLookSmooth = new THREE.Vector3(6, 24, 70);
let camSnapNext = true;
// ---------- UI Helpers ----------
function showToast(msg) {
toastEl.textContent = msg;
toastEl.classList.add('show');
toastTimer = 2.4;
}
function updateHUD() {
hudScoreEl.textContent = String(score);
hudCratesEl.textContent = String(targets.length - cratesTriggered);
const secs = Math.max(0, Math.ceil(timeLeft));
const m = Math.floor(secs / 60);
const s = secs % 60;
hudTimeEl.textContent = m + ':' + (s < 10 ? '0' + s : s);
const progress = clamp(1 - timeLeft / TOTAL_TIME, 0, 1);
sunsetFillEl.style.width = (progress * 100).toFixed(1) + '%';
sunsetPillEl.classList.toggle('urgent', timeLeft <= 20 && gameMode === 'playing' && !demoMode);
}
function setCameraMode(mode, silent) {
cameraMode = mode;
camButtons.forEach((b) => b.classList.toggle('active', b.dataset.cam === mode));
catPilotGroup.visible = (mode !== 'cockpit');
camSnapNext = true;
if (!silent) AudioSys.playClick();
}
camButtons.forEach((btn) => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
AudioSys.init();
if (demoMode) endDemoMode();
setCameraMode(btn.dataset.cam, false);
});
});
// ---------- Reset & Start / End Flows ----------
function resetWorld(startImmediately) {
plane.pos.set(6, 25, 96);
plane.yaw = -0.49;
plane.pitch = 0;
plane.roll = 0;
plane.speed = 26;
plane.boostTimer = 0;
score = 0;
cratesTriggered = 0;
cratesDelivered = 0;
timeLeft = TOTAL_TIME;
comboCount = 0;
lastRingTime = -99;
pendingWinTimer = -1;
bellyCrate.visible = true;
trailL.pts.length = 0;
trailR.pts.length = 0;
// Clear parachutes
while (activeParachutes.length) {
const p = activeParachutes.pop();
scene.remove(p.group);
}
while (particles.length) {
const pt = particles.pop();
scene.remove(pt.mesh);
}
// Reset all 8 delivery targets
targets.forEach((t) => {
t.triggered = false;
t.delivered = false;
t.celebrateTimer = 0;
t.ringGroup.visible = true;
t.ringGroup.scale.setScalar(1);
t.beam.visible = true;
t.landedCrate.visible = false;
t.cat.position.copy(t.landPos);
});
input.targetX = 0;
input.targetY = 0;
input.steerX = 0;
input.steerY = 0;
input.mouseActive = false;
input.touchId = null;
touchPadEl.style.opacity = '0';
mouseReticleEl.style.opacity = '0';
camSnapNext = true;
updateHUD();
if (startImmediately) {
gameMode = 'playing';
startOverlayEl.classList.add('hidden');
endOverlayEl.classList.add('hidden');
}
}
function finishGame(won) {
if (gameMode === 'ended') return;
gameMode = 'ended';
touchPadEl.style.opacity = '0';
mouseReticleEl.style.opacity = '0';
ringCompassEl.style.opacity = '0';
const sunsetBonus = won ? Math.round(timeLeft * 5) : 0;
score += sunsetBonus;
if (score > bestScore) {
bestScore = score;
saveBestScore(bestScore);
}
updateHUD();
endEmojiEl.textContent = won ? '🏆' : '🌙';
endTitleEl.textContent = won ? 'All Fish Delivered!' : 'Night Has Fallen';
endSubEl.textContent = won
? 'Every rooftop and dock cat is happily feasting under the twilight sky!'
: 'The town lanterns are glowing bright — try another sunset flight to deliver them all!';
endScoreEl.textContent = String(score);
endCratesEl.textContent = cratesDelivered + ' / ' + targets.length;
endBonusEl.textContent = '+' + sunsetBonus;
endBestEl.textContent = String(bestScore);
startBestEl.textContent = bestScore > 0 ? ('Best Score: ' + bestScore) : '';
endOverlayEl.classList.remove('hidden');
AudioSys.playEnd(won);
}
btnPlay.addEventListener('click', (e) => {
e.stopPropagation();
AudioSys.init();
AudioSys.playClick();
demoMode = false;
demoBadgeEl.style.display = 'none';
resetWorld(true);
showToast('Fly through the glowing rings to drop fish crates!');
});
btnReplay.addEventListener('click', (e) => {
e.stopPropagation();
AudioSys.init();
AudioSys.playClick();
demoMode = false;
demoBadgeEl.style.display = 'none';
resetWorld(true);
showToast('Fresh crates loaded — sunset takeoff!');
});
// ---------- #demo Hands-Free 20s Loop ----------
function isDemoUrl() {
const h = (window.location.hash || '').toLowerCase();
const href = (window.location.href || '').toLowerCase();
return h === '#demo' || href.endsWith('#demo');
}
function startDemoMode() {
demoMode = true;
demoClock = 0;
demoBadgeEl.style.display = 'block';
resetWorld(true);
setCameraMode('behind', true);
}
function endDemoMode() {
if (!demoMode) return;
demoMode = false;
demoBadgeEl.style.display = 'none';
// Keep flying seamlessly with generous sunset time so the user can enjoy right away
if (timeLeft < 55) timeLeft = 75;
showToast('You have the controls!');
}
// ---------- Pointer / Touch / Mouse Input ----------
const DRAG_RADIUS = 68;
function onPointerDown(e) {
if (e.target && e.target.closest && (e.target.closest('button') || e.target.closest('.overlay-card'))) return;
AudioSys.init();
if (demoMode && e.isTrusted) {
endDemoMode();
}
if (gameMode !== 'playing') return;
if (e.pointerType === 'touch' || e.pointerType === 'pen') {
if (input.touchId !== null) return;
input.mode = 'touch';
input.touchId = e.pointerId;
input.originX = e.clientX;
input.originY = e.clientY;
input.curX = e.clientX;
input.curY = e.clientY;
input.targetX = 0;
input.targetY = 0;
mouseReticleEl.style.opacity = '0';
touchPadEl.style.left = input.originX + 'px';
touchPadEl.style.top = input.originY + 'px';
touchKnobEl.style.transform = 'translate(0px, 0px)';
touchPadEl.style.opacity = '1';
try { stageEl.setPointerCapture(e.pointerId); } catch (_) {}
} else if (e.pointerType === 'mouse') {
input.mode = 'mouse';
input.mouseActive = true;
updateMouseSteer(e.clientX, e.clientY);
}
}
function updateMouseSteer(cx, cy) {
const hw = window.innerWidth * 0.5;
const hh = window.innerHeight * 0.5;
const nx = clamp((cx - hw) / (hw * 0.85), -1, 1);
const ny = clamp((hh - cy) / (hh * 0.85), -1, 1); // Up on screen = positive (climb)
const curve = (v) => Math.sign(v) * Math.pow(Math.abs(v), 1.2);
input.targetX = curve(nx);
input.targetY = curve(ny);
mouseReticleEl.style.left = cx + 'px';
mouseReticleEl.style.top = cy + 'px';
mouseReticleEl.style.opacity = gameMode === 'playing' && !demoMode ? '1' : '0';
}
function onPointerMove(e) {
if (gameMode !== 'playing' || demoMode) return;
if (e.pointerType === 'touch' || e.pointerType === 'pen') {
if (e.pointerId !== input.touchId) return;
input.curX = e.clientX;
input.curY = e.clientY;
let dx = input.curX - input.originX;
let dy = input.curY - input.originY;
const dist = Math.hypot(dx, dy);
// Gently drag the anchor if finger stretches beyond radius for instant reversal
if (dist > DRAG_RADIUS * 1.15) {
const excess = dist - DRAG_RADIUS;
input.originX += (dx / dist) * excess;
input.originY += (dy / dist) * excess;
dx = input.curX - input.originX;
dy = input.curY - input.originY;
touchPadEl.style.left = input.originX + 'px';
touchPadEl.style.top = input.originY + 'px';
}
const clampedDist = Math.min(Math.hypot(dx, dy), DRAG_RADIUS);
const ang = Math.atan2(dy, dx);
const kx = Math.cos(ang) * clampedDist;
const ky = Math.sin(ang) * clampedDist;
touchKnobEl.style.transform = 'translate(' + kx.toFixed(1) + 'px, ' + ky.toFixed(1) + 'px)';
// Small deadzone for calm straight flight
const norm = clampedDist < 7 ? 0 : (clampedDist - 7) / (DRAG_RADIUS - 7);
input.targetX = (kx / DRAG_RADIUS) * norm;
input.targetY = (-ky / DRAG_RADIUS) * norm; // Drag up = climb
} else if (e.pointerType === 'mouse') {
if (input.mode === 'touch' && input.touchId !== null) return;
if (!input.mouseActive) {
if (input.lastMouseX < -500) {
input.lastMouseX = e.clientX;
input.lastMouseY = e.clientY;
return;
}
if (Math.hypot(e.clientX - input.lastMouseX, e.clientY - input.lastMouseY) > 6) {
input.mouseActive = true;
input.mode = 'mouse';
} else {
return;
}
}
updateMouseSteer(e.clientX, e.clientY);
}
}
function onPointerUp(e) {
if (e.pointerId === input.touchId) {
input.touchId = null;
input.targetX = 0;
input.targetY = 0;
touchPadEl.style.opacity = '0';
}
}
stageEl.addEventListener('pointerdown', onPointerDown, { passive: true });
window.addEventListener('pointermove', onPointerMove, { passive: true });
window.addEventListener('pointerup', onPointerUp, { passive: true });
window.addEventListener('pointercancel', onPointerUp, { passive: true });
window.addEventListener('pointerleave', () => {
if (input.mode === 'mouse') {
input.targetX = 0;
input.targetY = 0;
mouseReticleEl.style.opacity = '0';
}
});
// Extra safety for ending #demo on any real touchstart
window.addEventListener('touchstart', (e) => {
if (demoMode && e.isTrusted) endDemoMode();
}, { passive: true });
window.addEventListener('hashchange', () => {
if (isDemoUrl() && !demoMode) startDemoMode();
});
// ---------- Sunset-to-Night Lighting & Atmosphere Driver ----------
const skyStops = {
topSun: col('#273f78'), topDusk: col('#1c1f4c'), topNight: col('#090d22'),
midSun: col('#d4675e'), midDusk: col('#7c3a69'), midNight: col('#141c3c'),
horSun: col('#ffad59'), horDusk: col('#eb694d'), horNight: col('#1f284c'),
sunWarm: col('#ffe08c'), sunRed: col('#ff6e42'), sunGone: col('#2f3b66'),
fogSun: col('#e88a59'), fogDusk: col('#7d4662'), fogNight: col('#161e3a'),
deepSun: col('#15334a'), deepNight: col('#091324'),
shalSun: col('#2b5f73'), shalNight: col('#13243b'),
cloudSun: col('#fff0dc'), cloudDusk: col('#f0a28d'), cloudNight: col('#323c60'),
cloudEmSun:col('#ff9452'), cloudEmNgt: col('#12182d')
};
const tmpC = new THREE.Color();
function updateAtmosphere(progress) {
const p = clamp(progress, 0, 1);
const t1 = clamp(p * 1.65, 0, 1); // Sunset -> Vivid Dusk
const t2 = clamp((p - 0.52) / 0.48, 0, 1); // Vivid Dusk -> Starry Night
skyUniforms.uTopColor.value.copy(skyStops.topSun).lerp(skyStops.topDusk, t1).lerp(skyStops.topNight, t2);
skyUniforms.uMidColor.value.copy(skyStops.midSun).lerp(skyStops.midDusk, t1).lerp(skyStops.midNight, t2);
skyUniforms.uHorizonColor.value.copy(skyStops.horSun).lerp(skyStops.horDusk, t1).lerp(skyStops.horNight, t2);
skyUniforms.uSunColor.value.copy(skyStops.sunWarm).lerp(skyStops.sunRed, t1).lerp(skyStops.sunGone, t2);
skyUniforms.uNightMix.value = smoothstep(0.32, 0.96, p);
// Sun slowly sets behind the western hills
const sunElev = lerp(0.19, -0.075, p);
skyUniforms.uSunDir.value.set(-0.91, sunElev, -0.37).normalize();
sunLight.position.copy(skyUniforms.uSunDir.value).multiplyScalar(280);
sunLight.position.y = Math.max(sunLight.position.y, 8);
sunLight.color.copy(skyUniforms.uSunColor.value);
sunLight.intensity = lerp(2.25, 0.14, smoothstep(0.15, 0.92, p));
moonLight.intensity = lerp(0.05, 0.65, smoothstep(0.45, 0.95, p));
hemiLight.color.copy(skyUniforms.uHorizonColor.value);
hemiLight.groundColor.copy(skyStops.deepSun).lerp(skyStops.deepNight, p);
hemiLight.intensity = lerp(0.92, 0.42, p);
// Fog & Water tint
scene.fog.color.copy(skyStops.fogSun).lerp(skyStops.fogDusk, t1).lerp(skyStops.fogNight, t2);
waterUniforms.uFogColor.value.copy(scene.fog.color);
waterUniforms.uSunColor.value.copy(skyUniforms.uSunColor.value);
waterUniforms.uDeepColor.value.copy(skyStops.deepSun).lerp(skyStops.deepNight, p);
waterUniforms.uShallowColor.value.copy(skyStops.shalSun).lerp(skyStops.shalNight, p);
waterUniforms.uNightMix.value = skyUniforms.uNightMix.value;
// Warm clouds fading into dusky twilight
cloudMat.color.copy(skyStops.cloudSun).lerp(skyStops.cloudDusk, t1).lerp(skyStops.cloudNight, t2);
cloudMat.emissive.copy(skyStops.cloudEmSun).lerp(skyStops.cloudEmNgt, smoothstep(0.3, 0.9, p));
cloudMat.emissiveIntensity = lerp(0.28, 0.06, p);
// Village windows, dock lanterns, plane nose light & lighthouse beam warm up as night falls!
const nightGlow = smoothstep(0.12, 0.78, p);
windowMat.emissiveIntensity = lerp(0.45, 2.35, nightGlow);
lanternBulbMat.emissiveIntensity = lerp(1.0, 2.8, nightGlow);
planeGlowLight.intensity = lerp(0.0, 2.2, nightGlow);
if (lighthouseBeam) {
lighthouseBeam.mat.opacity = lerp(0.05, 0.22, nightGlow);
}
}
// ---------- Autopilot for Title Screen & #demo ----------
function computeAutopilot(dt) {
if (gameMode === 'title') {
// Gentle scenic circular orbit over the sunset lake
const targetRadius = 78;
const r = Math.hypot(plane.pos.x, plane.pos.z);
const ang = Math.atan2(plane.pos.z, plane.pos.x);
const tangYaw = Math.atan2(-(Math.cos(ang + 1.45)), -(Math.sin(ang + 1.45)));
const radAdjust = clamp((r - targetRadius) * 0.015, -0.4, 0.4);
const desiredYaw = wrapAngle(tangYaw + radAdjust);
const diff = wrapAngle(desiredYaw - plane.yaw);
input.targetX = clamp(-diff * 1.1, -0.55, 0.55);
input.targetY = clamp((28 - plane.pos.y) * 0.08, -0.35, 0.35);
return;
}
// Demo autopilot: fly smoothly through each undelivered glowing ring in order!
let nextT = null;
for (let i = 0; i < targets.length; i++) {
if (!targets[i].triggered) { nextT = targets[i]; break; }
}
if (!nextT) {
input.targetX = 0.22;
input.targetY = clamp((26 - plane.pos.y) * 0.08, -0.3, 0.3);
return;
}
const dx = nextT.ringPos.x - plane.pos.x;
const dz = nextT.ringPos.z - plane.pos.z;
const dy = nextT.ringPos.y - plane.pos.y;
const hDist = Math.max(8, Math.hypot(dx, dz));
const desiredYaw = Math.atan2(-dx, -dz);
const diff = wrapAngle(desiredYaw - plane.yaw);
input.targetX = clamp(-diff * 1.45, -0.92, 0.92);
const desiredPitch = Math.atan2(dy, hDist);
input.targetY = clamp(desiredPitch / 0.46, -0.82, 0.82);
}
// ---------- Nearest Ring Finder & Screen Compass ----------
const projVec = new THREE.Vector3();
function findNearestTarget() {
let best = null;
let bestD = Infinity;
for (let i = 0; i < targets.length; i++) {
if (targets[i].triggered) continue;
const d = targets[i].ringPos.distanceTo(plane.pos);
if (d < bestD) { bestD = d; best = targets[i]; }
}
return { target: best, dist: bestD };
}
function updateRingCompass(nearest) {
if (!nearest.target || gameMode !== 'playing') {
ringCompassEl.style.opacity = '0';
return;
}
projVec.copy(nearest.target.ringPos).project(camera);
const behind = projVec.z > 1.0;
let sx = projVec.x;
let sy = projVec.y;
if (behind) { sx = -sx; sy = -sy; }
// Only show directional chevron when ring is near or outside screen edges
if (!behind && Math.abs(sx) < 0.78 && Math.abs(sy) < 0.72) {
ringCompassEl.style.opacity = '0';
return;
}
const angle = Math.atan2(sy, sx);
const marginX = window.innerWidth * 0.41;
const marginY = window.innerHeight * 0.34;
const cx = window.innerWidth * 0.5 + Math.cos(angle) * marginX;
const cy = window.innerHeight * 0.5 - Math.sin(angle) * marginY;
ringCompassEl.style.left = clamp(cx, 44, window.innerWidth - 44) + 'px';
ringCompassEl.style.top = clamp(cy, 96, window.innerHeight - 108) + 'px';
const rotDeg = 90 - (angle * 180 / Math.PI);
compassArrowEl.style.transform = 'rotate(' + rotDeg.toFixed(1) + 'deg)';
compassDistEl.textContent = Math.round(nearest.dist) + 'm';
ringCompassEl.style.opacity = '0.92';
}
// ---------- Plane Flight Physics & Ring Collision ----------
const tmpForward = new THREE.Vector3();
const tmpRight = new THREE.Vector3();
const tmpUp = new THREE.Vector3();
const tmpWorldL = new THREE.Vector3();
const tmpWorldR = new THREE.Vector3();
function updateFlight(dt) {
if (gameMode === 'title' || demoMode) {
computeAutopilot(dt);
}
// Smooth steering response
const steerLerp = 1 - Math.exp(-7.5 * dt);
input.steerX = lerp(input.steerX, input.targetX, steerLerp);
input.steerY = lerp(input.steerY, input.targetY, steerLerp);
// Gentle valley boundary return breeze so player stays over the scenic lake
const distFromCenter = Math.hypot(plane.pos.x, plane.pos.z);
let boundaryTurn = 0;
if (distFromCenter > 195) {
const inwardYaw = Math.atan2(plane.pos.x, plane.pos.z); // toward (0,0)
const diffIn = wrapAngle(inwardYaw - plane.yaw);
const strength = smoothstep(195, 255, distFromCenter);
boundaryTurn = clamp(diffIn * 1.4, -1.0, 1.0) * strength * 1.2;
}
// In Above view, offer subtle gentle altitude trim when aligned over a ring
let altAssist = 0;
if (cameraMode === 'above' && gameMode === 'playing' && !demoMode && Math.abs(input.targetY) < 0.35) {
for (let i = 0; i < targets.length; i++) {
const t = targets[i];
if (t.triggered) continue;
const hd = Math.hypot(t.ringPos.x - plane.pos.x, t.ringPos.z - plane.pos.z);
if (hd < 24) {
altAssist = clamp((t.ringPos.y - plane.pos.y) * 0.045, -0.4, 0.4);
break;
}
}
}
// Yaw, Pitch, Roll dynamics
const maxYawRate = 1.48;
const yawRate = -input.steerX * maxYawRate + boundaryTurn;
plane.yaw = wrapAngle(plane.yaw + yawRate * dt);
let desiredPitch = clamp((input.steerY + altAssist) * 0.56, -0.56, 0.56);
// Soft ceiling leveling
if (plane.pos.y > 66) {
desiredPitch = Math.min(desiredPitch, lerp(0.15, -0.22, smoothstep(66, 76, plane.pos.y)));
}
// Safe floor / terrain / building clearance flare
let minFloor = Math.max(4.6, getTerrainHeight(plane.pos.x, plane.pos.z) + 4.8);
for (let i = 0; i < buildingObstacles.length; i++) {
const b = buildingObstacles[i];
const bd = Math.hypot(plane.pos.x - b.x, plane.pos.z - b.z);
if (bd < b.r + 5.0) {
minFloor = Math.max(minFloor, b.topY + 2.8);
}
}
if (plane.pos.y < minFloor + 6.0) {
const urg = smoothstep(minFloor + 6.0, minFloor, plane.pos.y);
desiredPitch = Math.max(desiredPitch, urg * 0.42);
}
plane.pitch = lerp(plane.pitch, desiredPitch, 1 - Math.exp(-5.8 * dt));
const targetRoll = clamp(-input.steerX * 0.78 + boundaryTurn * 0.35, -0.82, 0.82);
plane.roll = lerp(plane.roll, targetRoll, 1 - Math.exp(-6.5 * dt));
// Speed modulation (gentle dive speed-up & ring boost)
if (plane.boostTimer > 0) plane.boostTimer = Math.max(0, plane.boostTimer - dt);
const boostAdd = plane.boostTimer > 0 ? 5.5 * (plane.boostTimer / 1.1) : 0;
const targetSpeed = clamp(26.5 - plane.pitch * 8.5 + boostAdd, 21.5, 34.5);
plane.speed = lerp(plane.speed, targetSpeed, 1 - Math.exp(-3.5 * dt));
// Apply orientation & advance position
planeGroup.rotation.set(plane.pitch, plane.yaw, plane.roll, 'YXZ');
planeGroup.updateMatrixWorld();
tmpForward.set(0, 0, -1).applyQuaternion(planeGroup.quaternion).normalize();
plane.pos.addScaledVector(tmpForward, plane.speed * dt);
if (plane.pos.y < minFloor) plane.pos.y = minFloor;
if (plane.pos.y > 78) plane.pos.y = 78;
planeGroup.position.copy(plane.pos);
// Water skim sparkle spray when flying thrillingly low over the open lake!
waterSprayCooldown = Math.max(0, waterSprayCooldown - dt);
if (plane.pos.y < 7.2 && getTerrainHeight(plane.pos.x, plane.pos.z) < 0.0 && waterSprayCooldown <= 0) {
waterSprayCooldown = 0.09;
spawnParticles(new THREE.Vector3(plane.pos.x, 0.5, plane.pos.z), 3, ['#fff6e4', '#ffd79a', '#8fd6ea'], 5.5, 0.55);
}
// Animate plane parts: propeller, control surfaces, flight stick, scarf & cockpit gauges!
propGroup.rotation.z += dt * (34 + plane.speed * 0.6);
aileronL.rotation.x = input.steerX * 0.45;
aileronR.rotation.x = -input.steerX * 0.45;
elevator.rotation.x = -input.steerY * 0.42;
rudder.rotation.y = input.steerX * 0.36;
stickPivot.rotation.z = -input.steerX * 0.32;
stickPivot.rotation.x = -input.steerY * 0.28;
for (let i = 0; i < scarfSegs.length; i++) {
const wave = Math.sin(simTime * 14 - i * 0.95);
scarfSegs[i].position.y = 0.14 + wave * 0.055 * (i + 1) * 0.45;
scarfSegs[i].position.x = 0.16 + Math.cos(simTime * 10 - i * 0.8) * 0.04 * (i + 1) - input.steerX * 0.08 * i;
}
gaugeNeedles.compass.rotation.z = plane.yaw;
gaugeNeedles.alt.rotation.z = 1.6 - clamp(plane.pos.y / 78, 0, 1) * 3.2;
gaugeNeedles.sun.rotation.z = 1.4 - clamp(1 - timeLeft / TOTAL_TIME, 0, 1) * 2.8;
// Update wingtip trails
tmpWorldL.set(-4.65, 0.08, -0.5).applyMatrix4(planeGroup.matrixWorld);
tmpWorldR.set(4.65, 0.08, -0.5).applyMatrix4(planeGroup.matrixWorld);
updateTrail(trailL, tmpWorldL);
updateTrail(trailR, tmpWorldR);
// Engine sound pitch
AudioSys.updateEngine((plane.speed - 21) / 14, gameMode === 'playing' && !demoMode);
// Check glowing ring fly-throughs during active play (and #demo!)
if (gameMode === 'playing') {
for (let i = 0; i < targets.length; i++) {
const t = targets[i];
if (t.triggered) continue;
const d = plane.pos.distanceTo(t.ringPos);
if (d < 8.1) {
triggerRing(t, d);
}
}
}
}
function updateTrail(trail, pt) {
trail.pts.push(pt.clone());
if (trail.pts.length > TRAIL_LEN) trail.pts.shift();
const pos = trail.positions;
const len = trail.pts.length;
for (let i = 0; i < TRAIL_LEN; i++) {
const p = trail.pts[Math.min(i, len - 1)];
pos[i * 3] = p.x;
pos[i * 3 + 1] = p.y;
pos[i * 3 + 2] = p.z;
}
trail.line.geometry.attributes.position.needsUpdate = true;
trail.line.material.opacity = cameraMode === 'cockpit' ? 0.0 : 0.34;
}
function triggerRing(target, hitDist) {
target.triggered = true;
target.ringGroup.visible = false;
target.beam.visible = false;
cratesTriggered++;
plane.boostTimer = 1.1;
if (cratesTriggered >= targets.length) {
bellyCrate.visible = false;
}
// Score calculation: base + bullseye accuracy + cozy chain combo
const bullseye = Math.round(clamp(1 - hitDist / 8.1, 0, 1) * 50);
if (simTime - lastRingTime < 12) comboCount++;
else comboCount = 1;
lastRingTime = simTime;
const comboBonus = comboCount > 1 ? (comboCount - 1) * 25 : 0;
const pts = 100 + bullseye + comboBonus;
score += pts;
spawnParticles(target.ringPos, 24, ['#ffd76a', '#ff9248', '#fff5d6', '#ff6d6d'], 14, 0.95);
const dropPos = plane.pos.clone().add(new THREE.Vector3(0, -1.2, 0));
spawnParachuteDrop(target, dropPos);
AudioSys.playRing(comboCount - 1);
const tag = bullseye >= 35 ? 'Bullseye! ' : (comboCount > 1 ? comboCount + 'x Chain! ' : '');
showToast(tag + '+' + pts + ' · Dropping fish to ' + target.name + '!');
updateHUD();
}
// ---------- Update Parachutes, Cats, Rings & Particles ----------
function updateWorldActors(dt, nearest) {
// Animate glowing sky rings
for (let i = 0; i < targets.length; i++) {
const t = targets[i];
if (!t.triggered) {
const isNext = nearest.target && nearest.target.id === t.id;
const pulse = 1 + Math.sin(simTime * (isNext ? 4.2 : 2.5) + i) * (isNext ? 0.06 : 0.03);
t.ringGroup.scale.setScalar(pulse);
t.orbGroup.rotation.z += dt * (isNext ? 1.8 : 0.95);
t.ringMat.emissiveIntensity = isNext ? 2.05 : 1.15;
t.beam.material.opacity = isNext ? 0.18 : 0.085;
}
// Animate waiting cats (waving eagerly, or hopping joyfully once delivered!)
const ud = t.cat.userData;
if (t.celebrateTimer > 0) {
t.celebrateTimer = Math.max(0, t.celebrateTimer - dt);
t.cat.position.y = t.landPos.y + Math.abs(Math.sin(simTime * 11)) * 1.45;
t.cat.rotation.y += dt * 5.2;
ud.paw.position.y = 1.25 + Math.sin(simTime * 16) * 0.22;
} else if (t.delivered) {
t.cat.position.y = t.landPos.y + Math.abs(Math.sin(simTime * 3.5 + i)) * 0.18;
ud.tail.rotation.z = Math.sin(simTime * 6 + i) * 0.35;
} else {
t.cat.position.y = t.landPos.y;
ud.paw.position.y = 1.1 + Math.sin(simTime * 5.2 + i) * 0.16;
ud.tail.rotation.z = Math.sin(simTime * 3.2 + i) * 0.25;
}
}
// Update descending parachutes
for (let i = activeParachutes.length - 1; i >= 0; i--) {
const p = activeParachutes[i];
p.age += dt;
if (!p.landed) {
// Springy parachute bloom on open
const openT = clamp(p.age / 0.42, 0, 1);
const s = 0.15 + 0.85 * (1 - Math.pow(1 - openT, 3) * Math.cos(openT * Math.PI * 1.3));
p.canopyGroup.scale.setScalar(s);
// Smooth glide directly onto the waiting cat's rooftop or dock
const totalDropH = Math.max(4, p.startPos.y - p.target.landPos.y);
const descSpeed = 6.2;
const frac = clamp((p.age * descSpeed) / totalDropH, 0, 1);
const horizEase = 1 - Math.pow(1 - frac, 2.2);
const targetX = p.target.landPos.x + 1.5;
const targetZ = p.target.landPos.z + 0.6;
p.group.position.x = lerp(p.startPos.x, targetX, horizEase);
p.group.position.z = lerp(p.startPos.z, targetZ, horizEase);
p.group.position.y = lerp(p.startPos.y, p.target.landPos.y + 1.05, frac);
// Gentle pendulum sway in evening breeze
p.group.rotation.z = Math.sin(p.age * 2.9) * 0.16 * (1 - frac * 0.5);
p.group.rotation.x = Math.cos(p.age * 2.3) * 0.10 * (1 - frac * 0.5);
if (frac >= 1) {
p.landed = true;
p.target.delivered = true;
p.target.landedCrate.visible = true;
p.target.celebrateTimer = 3.2;
cratesDelivered++;
spawnParticles(
p.target.landPos.clone().add(new THREE.Vector3(0, 2.2, 0)),
18,
['#ff8fa3', '#ffd166', '#98e2f5', '#fff4d6'],
8.5,
1.15
);
AudioSys.playDelivery();
if (!demoMode) {
showToast(p.target.catName + ' caught the fish at ' + p.target.name + '!');
}
if (cratesDelivered >= targets.length && !demoMode && gameMode === 'playing') {
pendingWinTimer = 1.15;
}
}
} else {
// Deflate parachute cleanly after landing
p.fadeAge += dt;
const f = clamp(1 - p.fadeAge / 0.55, 0, 1);
p.canopyGroup.scale.set(f, f * 0.5, f);
p.group.children[0].visible = false; // Hand off to permanent landedCrate
if (p.fadeAge >= 0.55) {
scene.remove(p.group);
activeParachutes.splice(i, 1);
}
}
}
// Update particles
for (let i = particles.length - 1; i >= 0; i--) {
const pt = particles[i];
pt.age += dt;
if (pt.age >= pt.life) {
scene.remove(pt.mesh);
particles.splice(i, 1);
continue;
}
pt.vel.y -= pt.gravity * dt;
pt.mesh.position.addScaledVector(pt.vel, dt);
pt.mesh.rotation.x += dt * 4;
pt.mesh.rotation.y += dt * 3;
const a = 1 - pt.age / pt.life;
pt.mesh.scale.setScalar(Math.max(0.01, a));
pt.mesh.material.opacity = a;
}
// Drift clouds gently across the sunset sky
for (let i = 0; i < clouds.length; i++) {
const c = clouds[i];
c.mesh.position.x += c.speed * dt;
if (c.mesh.position.x > 420) c.mesh.position.x = -420;
}
// Bob moored harbor sailboats
for (let i = 0; i < bobbingBoats.length; i++) {
const b = bobbingBoats[i];
b.mesh.position.y = b.baseY + Math.sin(simTime * 1.9 + b.phase) * 0.14;
b.mesh.rotation.z = Math.sin(simTime * 1.5 + b.phase) * 0.055;
b.mesh.rotation.x = Math.cos(simTime * 1.3 + b.phase) * 0.035;
}
// Glide ambient birds
for (let i = 0; i < birds.length; i++) {
const b = birds[i];
b.angle += b.speed * dt;
b.group.position.set(
Math.cos(b.angle) * b.radius,
b.height + Math.sin(simTime * 1.2 + b.flapPhase) * 2.2,
Math.sin(b.angle) * b.radius
);
b.group.rotation.y = -b.angle;
const flap = Math.sin(simTime * 6.5 + b.flapPhase) * 0.55;
b.wL.rotation.y = flap;
b.wR.rotation.y = -flap;
}
// Rotate lighthouse beam
if (lighthouseBeam) {
lighthouseBeam.pivot.rotation.y += dt * 0.55;
}
}
// ---------- 3 Camera Rig Modes (Behind, Cockpit, Above) ----------
const desiredCamPos = new THREE.Vector3();
const desiredCamLook = new THREE.Vector3();
const desiredCamUp = new THREE.Vector3(0, 1, 0);
const worldUp = new THREE.Vector3(0, 1, 0);
function updateCamera(dt) {
tmpForward.set(0, 0, -1).applyQuaternion(planeGroup.quaternion).normalize();
tmpRight.set(1, 0, 0).applyQuaternion(planeGroup.quaternion).normalize();
tmpUp.set(0, 1, 0).applyQuaternion(planeGroup.quaternion).normalize();
if (gameMode === 'title') {
// Hero scenic chase angle showing the orange cat, sunset lake & town
const orbitA = simTime * 0.22;
desiredCamPos.copy(plane.pos)
.addScaledVector(tmpForward, -10.5)
.addScaledVector(tmpRight, Math.sin(orbitA) * 4.5)
.addScaledVector(worldUp, 3.6);
desiredCamLook.copy(plane.pos).addScaledVector(tmpForward, 8.0);
camera.fov = 55;
camera.updateProjectionMatrix();
camPosSmooth.lerp(desiredCamPos, 1 - Math.exp(-5 * dt));
camLookSmooth.lerp(desiredCamLook, 1 - Math.exp(-6 * dt));
camera.up.copy(worldUp);
camera.position.copy(camPosSmooth);
camera.lookAt(camLookSmooth);
return;
}
if (cameraMode === 'behind') {
if (Math.abs(camera.fov - 58) > 0.1) { camera.fov = 58; camera.updateProjectionMatrix(); }
desiredCamPos.copy(plane.pos)
.addScaledVector(tmpForward, -10.6)
.addScaledVector(worldUp, 3.45)
.addScaledVector(tmpRight, input.steerX * 1.45);
desiredCamPos.y = Math.max(desiredCamPos.y, 2.2);
desiredCamLook.copy(plane.pos)
.addScaledVector(tmpForward, 15.0)
.addScaledVector(worldUp, 0.7);
if (camSnapNext) {
camPosSmooth.copy(desiredCamPos);
camLookSmooth.copy(desiredCamLook);
camSnapNext = false;
} else {
camPosSmooth.lerp(desiredCamPos, 1 - Math.exp(-7.5 * dt));
camLookSmooth.lerp(desiredCamLook, 1 - Math.exp(-9.0 * dt));
}
camera.up.set(0, 1, 0).lerp(tmpUp, 0.22).normalize();
camera.position.copy(camPosSmooth);
camera.lookAt(camLookSmooth);
} else if (cameraMode === 'cockpit') {
if (Math.abs(camera.fov - 68) > 0.1) { camera.fov = 68; camera.updateProjectionMatrix(); }
// Inside the cozy cockpit looking over the gauges, orange paws on stick, nose & prop!
desiredCamPos.set(0, 0.96, 0.12).applyMatrix4(planeGroup.matrixWorld);
desiredCamLook.set(0, 0.64, -12.0).applyMatrix4(planeGroup.matrixWorld);
desiredCamUp.copy(worldUp).lerp(tmpUp, 0.65).normalize();
camera.position.copy(desiredCamPos);
camera.up.copy(desiredCamUp);
camera.lookAt(desiredCamLook);
camPosSmooth.copy(desiredCamPos);
camLookSmooth.copy(desiredCamLook);
camSnapNext = false;
} else {
// 'above': high bird's-eye view looking down over plane, rings, rooftops, docks & lake reflections
if (Math.abs(camera.fov - 54) > 0.1) { camera.fov = 54; camera.updateProjectionMatrix(); }
const hFwdX = -Math.sin(plane.yaw);
const hFwdZ = -Math.cos(plane.yaw);
desiredCamPos.set(
plane.pos.x - hFwdX * 20,
plane.pos.y + 68,
plane.pos.z - hFwdZ * 20
);
desiredCamLook.set(
plane.pos.x + hFwdX * 16,
Math.max(2, plane.pos.y - 16),
plane.pos.z + hFwdZ * 16
);
if (camSnapNext) {
camPosSmooth.copy(desiredCamPos);
camLookSmooth.copy(desiredCamLook);
camSnapNext = false;
} else {
camPosSmooth.lerp(desiredCamPos, 1 - Math.exp(-5.5 * dt));
camLookSmooth.lerp(desiredCamLook, 1 - Math.exp(-6.5 * dt));
}
camera.up.copy(worldUp);
camera.position.copy(camPosSmooth);
camera.lookAt(camLookSmooth);
}
}
// ---------- Planar Water Reflection Pass ----------
function renderWithWaterReflections() {
camera.updateMatrixWorld();
// Exact right-handed mirror across y = 0: R' = D * R * D, P' = D * P (D = diag(1,-1,1))
const m = camera.matrixWorld.elements;
const r = reflCam.matrixWorld.elements;
r[0] = m[0]; r[1] = -m[1]; r[2] = m[2]; r[3] = 0;
r[4] = -m[4]; r[5] = m[5]; r[6] = -m[6]; r[7] = 0;
r[8] = m[8]; r[9] = -m[9]; r[10] = m[10]; r[11] = 0;
r[12] = m[12]; r[13] = -m[13]; r[14] = m[14]; r[15] = 1;
reflCam.position.set(m[12], -m[13], m[14]);
reflCam.matrixWorldInverse.copy(reflCam.matrixWorld).invert();
reflCam.projectionMatrix.copy(camera.projectionMatrix);
reflCam.projectionMatrixInverse.copy(camera.projectionMatrixInverse);
reflCam.near = camera.near;
reflCam.far = camera.far;
// Keep sky dome centered on camera XZ with horizon locked to y = 0
skyDome.position.set(camera.position.x, 0, camera.position.z);
// Pass 1: Render mirrored scene above water into reflection texture
waterMesh.visible = false;
renderer.clippingPlanes = [reflClipPlane];
renderer.setRenderTarget(reflRT);
renderer.clear();
renderer.render(scene, reflCam);
// Pass 2: Render main scene with shimmering planar water reflections
renderer.setRenderTarget(null);
renderer.clippingPlanes = [];
waterMesh.visible = true;
renderer.render(scene, camera);
}
// ---------- Resize Handler ----------
function onResize() {
const w = window.innerWidth;
const h = window.innerHeight;
camera.aspect = w / h;
camera.updateProjectionMatrix();
renderer.setSize(w, h);
const rw = Math.min(512, Math.max(256, Math.floor(w * 0.5)));
const rh = Math.min(512, Math.max(256, Math.floor(h * 0.5)));
if (reflRT.width !== rw || reflRT.height !== rh) {
reflRT.setSize(rw, rh);
}
}
window.addEventListener('resize', onResize);
// ---------- Main Animation Loop ----------
let lastNow = performance.now();
let hudAccum = 0;
function tick(now) {
requestAnimationFrame(tick);
const dt = Math.min(0.05, Math.max(0.001, (now - lastNow) / 1000));
lastNow = now;
simTime += dt;
skyUniforms.uTime.value = simTime;
waterUniforms.uTime.value = simTime;
if (toastTimer > 0) {
toastTimer -= dt;
if (toastTimer <= 0) toastEl.classList.remove('show');
}
// Handle #demo 20-second showcase choreography
if (demoMode) {
demoClock += dt;
if (demoClock >= 20.0) {
startDemoMode();
} else {
const wantedCam = demoClock < 7.5 ? 'behind' : (demoClock < 13.5 ? 'cockpit' : 'above');
if (wantedCam !== cameraMode) setCameraMode(wantedCam, true);
// Showcase warm sunset gliding gently into dusk across the 20s loop
timeLeft = lerp(TOTAL_TIME * 0.92, TOTAL_TIME * 0.30, demoClock / 20.0);
}
} else if (gameMode === 'playing') {
timeLeft = Math.max(0, timeLeft - dt);
if (pendingWinTimer > 0) {
pendingWinTimer -= dt;
if (pendingWinTimer <= 0) finishGame(true);
} else if (timeLeft <= 0) {
finishGame(false);
}
}
// Sunset-to-night progression
const sunsetProgress = gameMode === 'title' ? 0.14 : clamp(1 - timeLeft / TOTAL_TIME, 0, 1);
updateAtmosphere(sunsetProgress);
// Physics, world actors, camera & HUD
updateFlight(dt);
const nearest = findNearestTarget();
updateWorldActors(dt, nearest);
updateCamera(dt);
updateRingCompass(nearest);
hudAccum += dt;
if (hudAccum >= 0.15) {
hudAccum = 0;
updateHUD();
}
renderWithWaterReflections();
}
// ---------- Boot ----------
resetWorld(false);
if (isDemoUrl()) {
startDemoMode();
} else {
updateAtmosphere(0.14);
}
requestAnimationFrame(tick);
})();
</script>
</body>
</html>
