Game · project 19 of 37
Snake 3D.
The classic phone snake, rebuilt in a 3D painted valley: turn left or right, eat the lights, grow long, and do not cross your own tail.
BeforeThe same flat snake on a dark grid since the old phones: a blocky line, a red dot, GAME OVER.
AfterThe classic phone snake in a 3D painted valley: a scaled ribbon-dragon that glides, eats lights and grows long, with the old green score panel.
What it is worthThe snake game you remember, free, in 3D, with no ads, no accounts and nothing to buy. Instead of flat snake clones and app versions full of ads.
How to use it
- Pick a valley: Dawn Vale (day, fast music), Ember Canyon (sunset) or Moonlit Ruins (night, calm rain). Each one starts with its own difficulty, speed and map size. Turn the sound up: it plays even when an iPhone is on silent.
- Change the options if you like: difficulty (Zen has no game over; Easy, Normal and Hard end the run when you hit your tail, a stone or a cliff), speed, map size, and turns (Smooth, or Classic for one square 90 degree turn per press). Your choice is saved for that valley. Press Play, or tap the valley again.
- Hold the left or right side of the screen to turn, or use the arrow keys or A and D. On a PS5 controller: left stick, D-pad or L1 and R1 turn, the D-pad and ✕ work the menu, Options pauses and Circle goes back; the right stick moves the camera (left and right to look around, up and down to zoom), and R3 resets it. The snake moves forward on its own.
- All the lights are on the map as one route; eat them in any order. The small map under the score shows where they are, the nearest has a beam, and the gold arrow points to it. Each light makes the tail longer, so mind your tail. Eat lights quickly in a row for a combo worth extra points. On Zen and Easy, the dots ahead of the snake turn red when the way is blocked. On small and medium maps, stay inside the ring of light.
- About every 11 lights a teal bonus light appears: grab it before its timer ends. When the whole route is eaten you get a fanfare and a lap bonus, and a new route appears.
- Two players: connect a second controller and press ✕ on it during a flight. A second snake in other colours joins beside yours. Its lights add to the same score. Player 2 never ends the run: cliffs, stones and the ring only turn it away.
Where it helps most
- Anyone who played snake on an old phone and wants that same simple rule again, in a place worth looking at, for a few minutes on a phone, a tablet or a TV with a controller.
- Anyone who wants to see what a small team of AI agents can build in one evening, with the master prompt and the code to make their own.
- A calm few minutes: Zen mode on Slow in Moonlit Ruins has no game over, just rain and gliding. No ads, no accounts and nothing to buy.
The idea
My wife wanted the snake game she remembers from her old phone, but in 3D. The first tries the same evening went too far: a children's game, then a quest adventure with shrines and hearts. She said keep it dead simple and nostalgic, so the team cut everything except turn, eat and grow, and put that one rule in a valley worth looking at.
The build
Built in one evening by Claude with a small team of AI agents. Claude led and wrote the game core. Separate agents built the world (procedural terrain, a shader sky and water, and simple colliders for stones and cliffs), the snake (one tube mesh rebuilt every frame along its path, with a scale shader), and the music and sound, all synthesized with the Web Audio API: a different score and ambience for each valley (day, sunset, night with rain and jungle sounds) and the old-style beep. An independent QA agent tested the running build with Playwright, and a deploy agent put it on this site. A PS5 or other game controller works through the browser's Gamepad API, with rumble on eating and crashing where the browser supports it. It uses three.js r128 and no other libraries, and has no image, model or sound files: everything is made by the code. For the site it is split into index.html, game.css and game.js, so it runs under the site's strict security rules. Sound plays on an iPhone even in silent mode: the audio session is set to playback on the first tap, older iPhones get a silent same-origin MP3, and sound resumes on every tap. The best scores stay on your device; no ads or accounts. Depth aids (a soft warm tint on what blocks you, a shadow under the head, and on Zen and Easy a row of dots ahead) make the 3D space readable. The route of lights is found by a path search so it never jumps, and phones start at a lower resolution that drops faster if the frame rate falls. The next lap is built ahead of time in small slices so there is no pause at the lap change, and the game pauses itself when the page is hidden. Growth (1.8 m per light) and speed (the top speed comes after about 50 to 58 lights) were balanced so a long run stays fair. Lights are placed away from cliffs and water, and a glancing touch on a cliff slides you along it (except on Hard). Checked under the site's rules at four screen sizes. Limits, honestly: the art is procedural and low-poly; sound on a real iPhone on silent and a real PS5 controller are not yet confirmed; the frame rate on old phones has not been measured. Two-player co-op (2026-11-27): a second dragon from the same model, with its own trail, length and turning, steered by the second controller. The camera frames both bodies. Player 2 reappears beside player 1 if it flies more than 70 m away.
Free to take
Build your own.
Copy the skill, paste it into your own AI, and say what you want different. How to use a skill, step by step ›
Get the skillThe instructions your AI follows. Works in Claude, ChatGPT, Gemini or any other
# Master prompt: Snake 3D
You lead a small AI game studio: a lead who writes the game core, a world agent, a dragon agent, an audio agent, an independent QA agent and a deploy agent. Build "Snake 3D": the classic phone snake, rebuilt in a 3D painted valley, for an adult who remembers the original. Keep it dead simple and nostalgic: turn, eat, grow. Nothing else. Original design only: no phone-maker names, logos or art.
Stack: one HTML page, three.js r128 and nothing else, no image, model or sound files (except a one-second silent MP3 for iPhones), no server, no AI calls at run time. It must run under a strict Content-Security-Policy once split into index.html, game.css and game.js.
Controls: the only input is turn left or turn right, in one of two turn styles chosen on the start screen: Smooth (default; turns while held) or Classic (one press gives one square 90 degree turn; holding does not turn again). Touch: hold the left or right half of the screen. Keys: left and right arrows, or A and D. PS5 controller (Gamepad API): left stick, D-pad or L1/R1 turn; the D-pad moves through the menu, X selects, Options pauses, Circle goes back; rumble on eat and crash where the browser supports it; the right stick orbits the camera left and right and zooms up and down, the orbit eases back after release, and R3 resets it. The snake moves forward on its own, gliding over meadows and water and following the ground.
The snake: a scaled ribbon-dragon. The body is one tube mesh rebuilt each frame along the head's recorded path, with a scale shader, a glowing belly line and a small head with a crest. Each light eaten makes the tail 1.8 m longer and sends a bright pulse down the body; the speed rises and reaches its cap after about 50 to 58 lights. The camera rises and pulls back as the snake grows so it always frames the whole body.
Depth aids while playing, so it is always clear where the snake can and cannot go: a soft warm tint on cliffs and a soft warm band on stones at the snake's height, a shadow under the head, leaves, rocks, ruins and trunks between the camera and the snake become see-through, and on Zen and Easy only a row of dots ahead (mint = clear, red = blocked).
Food: all lights are on the map from the start, as one continuous route found by a path search (Large 46 to 52 lights, Medium 24 to 28, Small 13 to 15): no jumps, the first lights always ahead of the snake, land preferred, away from cliffs and water, eaten in any order. A small LCD-style mini-map (a north-up 2D canvas) under the score chip shows the lights, the head, the body and the ring edge. The nearest uneaten light has a tall beam and a gold arrow at the screen edge when it is off-screen. About every 11 lights a timed teal bonus light appears; eat it before the timer ends for extra points. When all are eaten, a fanfare plays, a "Lap N" banner shows with a lap bonus (100 × the difficulty multiplier, none in Zen), and a new route appears. A glancing touch on a cliff slides the snake along it, except on Hard.
Start screen, in this order: three valley tiles (each showing best score, best length and best laps for the current difficulty), a Play button, then the options; on a phone held sideways the tiles and Play sit in one column and the options in a second, and on narrow phones the valley names never sit on the sun or moon. The first tap on a tile selects it; a second tap or Play starts. Three valleys, all open, each a procedural painted valley (height-field terrain, water, trees, stones, ruins, a gradient sky, fog) with its own default options: Dawn Vale (day) Normal, Fast, Large; Ember Canyon (sunset) Normal, Normal, Medium; Moonlit Ruins (night) Zen, Slow, Small. Options: Turns Smooth or Classic; Difficulty Zen (no game over; the snake turns away from obstacles and passes over its tail), Easy, Normal, Hard (your own tail, stones and cliffs end the run; the score and best show on an old-style green LCD panel with an old-style beep); Speed Slow, Normal, Fast; Map Small, Medium (a ring of light marks the edge of the play area) or Large (the whole valley). A line under the options explains the current choice. A changed option is saved for that valley. Best score per valley and difficulty in localStorage.
Sound: synthesized with Web Audio: music and ambience per valley that change with the selected valley (day fast and exciting, sunset in between, night calm with rain and jungle sounds), a square-wave beep for each light like the old phone, a bonus jingle, a crash, rising notes for a combo (eating lights quickly in a row adds up to +5 points per light, with an "x3" style chip beside the score and no penalty for a miss), and a soft chime every 25 m of length. iPhone: set navigator.audioSession.type to playback in the first tap, else loop a same-origin silent MP3; resume on every tap and when the page is visible again; a sound button and a "No sound?" line.
Two players: the second connected controller steers a second snake in another valley's colours, with its own trail, length and turning. Its lights add to the shared score and grow its own tail. Player 2 never ends the run: cliffs, stones and the ring only turn it. It reappears beside player 1 when more than 70 m away, and the camera frames both bodies. Press ✕ on the second controller during a flight to join.
Finish: a compact start screen with three valley tiles showing each best, the options and a sticky Play row that stays visible without scrolling on small phones, a game-over card on the LCD showing score, length, lights and lap with Play again and Menu, the LCD shows length in metres in every mode, phones start at pixel ratio 1.5 and drop faster on a low frame rate, safe-area insets, no scrolling or zoom during play, pause when the page is hidden and return to the menu with Resume, build the next lap ahead of time in small slices so there is no pause at the lap change and rebuild laps that come out too short, start on dry land when it is open enough, keep records per valley and difficulty (best score, best length, best laps) under the same localStorage prefix, and a web app manifest with 180, 192 and 512 px icons (a square crop of the valley with the snake) so it can be added to a home screen and opens full screen. Expose window.__game (state, mode, opts, score, foods, length, start(i), select(i), setMode, setOpt, cam, guideOn, lights(), lap, target() for the nearest uneaten light, eatNearest() for tests, test input) for testing. Stress test under the strict CSP at 320x568, 393x700, 740x360 and 1366x800: 30 s of random turning in Zen, a crash on Normal shows the game-over card and Play again restarts; no console errors, no NaN, no shader errors (the warm tint and path dots must render under the CSP), no sideways scroll, AudioContext running after the first tap and again after a suspend.
Get the code3 files, exactly as they run on this site · free under the MIT license
These three files are exactly what runs at sghadimi.com/games/snake-3d. The page also needs three.js r128 (loaded from the site's own copy before game.js) and a one-second silent MP3 at audio/silence.mp3 for older iPhones. No images, models, fonts or sound files are used: the valleys, the snake and every sound are made by the code. The game was written as one HTML file and split for the site by a small script. A web app manifest and three icons (icon-180.png, icon-192.png, icon-512.png, a square crop of the valley picture) let it be added to a phone or computer home screen as its own app.
game.js (the whole game: valleys, snake, lights, modes, controls, sound)3,305 lines
(()=>{'use strict';
const VERSION='v9';
const $=id=>document.getElementById(id);
const clamp=(v,a,b)=>v<a?a:v>b?b:v;
const store={get(k,d){try{const v=localStorage.getItem('lvale.'+k);return v===null?d:JSON.parse(v)}catch(e){return d}},set(k,v){try{localStorage.setItem('lvale.'+k,JSON.stringify(v))}catch(e){}}};
const pad4=n=>String(Math.max(0,Math.floor(n))).padStart(4,'0');
/* ---- audio.js ---- */
/* ================= AUDIO (iPhone-safe) ================= */
/* Everything is synthesized. 14 voices max: 8 fixed (3 pad, bass, lead, pulse, one shared noise source
for percussion + ambience, one "critter" oscillator for birds/crickets/frogs/drips). They are always-on
and only automated, so music and ambience can never starve sfx, which keep the other 6 voices. */
let AC=null,silentEl=null,master=null,musicBus=null,sfxBus=null,voices=0,muted=store.get('muted',false);
const MAXV=14;
let mv=null,amb=null,noiseBuf=null,hornLP=null,acFails=0,ducked=false;
const live=new Set();
function iosUnlock(){
try{if(navigator.audioSession&&navigator.audioSession.type!=='playback')navigator.audioSession.type='playback'}catch(e){}
if(!('audioSession' in navigator)){
try{
if(!silentEl){silentEl=new Audio('audio/silence.mp3');silentEl.loop=true;silentEl.setAttribute('playsinline','')}
const p=silentEl.play();if(p&&p.catch)p.catch(()=>{});
}catch(e){}
}
}
function acResume(){
if(AC&&AC.state!=='running'){try{const p=AC.resume();if(p&&p.catch)p.catch(()=>{})}catch(e){}}
if(ducked&&master&&!document.hidden){ducked=false;try{master.gain.cancelScheduledValues(AC.currentTime);master.gain.setTargetAtTime(muted?0:0.9,AC.currentTime,0.08)}catch(e){}}
}
function wake(){
iosUnlock();
if(!AC){initAudio();return}
acResume();
}
['pointerdown','touchend','click','keydown'].forEach(ev=>document.addEventListener(ev,wake,{passive:true,capture:true}));
document.addEventListener('visibilitychange',()=>{
if(!AC)return;
if(document.hidden){ /* fade out, then pause, so a hidden tab is silent (music and ambience) and nothing clicks */
try{ducked=true;master.gain.cancelScheduledValues(AC.currentTime);master.gain.setTargetAtTime(0,AC.currentTime,0.012)}catch(e){}
setTimeout(()=>{if(document.hidden&&AC){try{const p=AC.suspend();if(p&&p.catch)p.catch(()=>{})}catch(e){}}},90);
}else wake();
});
window.addEventListener('pageshow',()=>{if(AC)wake()});
function initAudio(){
iosUnlock();
if(AC){acResume();return}
if(acFails>2)return;
try{
AC=new (window.AudioContext||window.webkitAudioContext)();
try{const p=AC.resume();if(p&&p.catch)p.catch(()=>{})}catch(e){}
/* master -> compressor -> trim -> soft clip (output can never reach 0 dBFS) -> speakers */
const clip=AC.createWaveShaper(),cv=new Float32Array(1025);
for(let i=0;i<1025;i++){const x=i/512-1,a=Math.abs(x);cv[i]=a<0.6?x:Math.sign(x)*(0.6+0.38*Math.tanh((a-0.6)/0.38))}
clip.curve=cv;clip.connect(AC.destination);
const trim=AC.createGain();trim.gain.value=1.1;trim.connect(clip);
const comp=AC.createDynamicsCompressor();
comp.threshold.value=-20;comp.knee.value=12;comp.ratio.value=8;comp.attack.value=0.004;comp.release.value=0.25;
comp.connect(trim);
master=AC.createGain();master.gain.value=muted?0:0.9;master.connect(comp);
realm=ambR=pendR;mood=pend;
musicBus=AC.createGain();musicBus.gain.value=REALMS[realm].vol;musicBus.connect(master);
sfxBus=AC.createGain();sfxBus.gain.value=0.8;sfxBus.connect(master);
const G=(v,to)=>{const g=AC.createGain();g.gain.value=v;if(to)g.connect(to);return g};
const F=(type,f,q,to)=>{const b=AC.createBiquadFilter();b.type=type;b.frequency.value=f;b.Q.value=q;if(to)b.connect(to);return b};
/* one cheap feedback delay gives the valley its space */
const dl=AC.createDelay(0.6),fb=G(0.36),lp=F('lowpass',2400,0.7),s1=G(0.22),s2=G(0.3);
dl.delayTime.value=0.34;sfxBus.connect(s1);s1.connect(dl);s2.connect(dl);
dl.connect(lp);lp.connect(fb);fb.connect(dl);lp.connect(master);
hornLP=F('lowpass',1100,0.7,sfxBus);
noiseBuf=AC.createBuffer(1,AC.sampleRate*2,AC.sampleRate);
const nd=noiseBuf.getChannelData(0);for(let i=0;i<nd.length;i++)nd[i]=Math.random()*2-1;
/* music voices: 3 pad, bass, lead, pulse */
const padLP=F('lowpass',600,0.5,musicBus),padL=G(0,padLP);
const pads=[57,62,65].map((m,i)=>{const o=AC.createOscillator(),g=G(i<2?0.07:0,padL);o.type='sawtooth';o.frequency.value=midi(m);o.detune.value=[-5,4,7][i];
o.connect(g);o.start();voices++;return{o,g}});
const mk=(echo,flt)=>{const o=AC.createOscillator(),g=G(0),L=G(0,musicBus);o.type='triangle';
o.connect(g);if(flt){g.connect(flt);flt.connect(L)}else g.connect(L);if(echo)L.connect(s2);o.start();voices++;return{o,g,L}};
const leadLP=F('lowpass',REALMS[realm].lead[3],0.5);
/* one noise source feeds percussion and the whole ambience bed */
const ns=AC.createBufferSource();ns.buffer=noiseBuf;ns.loop=true;ns.start();voices++;
const percL=G(0,musicBus),hat={g:G(0,percL)},clap={g:G(0,percL)};
ns.connect(F('highpass',7500,0.7,hat.g));ns.connect(F('bandpass',1700,0.9,clap.g));
mv={pads,padL,padLP,leadLP,percL,hat,clap,bass:mk(false),lead:mk(true,leadLP),pulse:mk(true)};
const ambBus=G(1,master),bedG=G(0,ambBus),bedF=F('bandpass',500,0.5,bedG),rumG=G(0,ambBus);
ns.connect(bedF);ns.connect(F('lowpass',150,0.7,rumG));
const co=AC.createOscillator(),cg=G(0,ambBus);co.connect(cg);cg.connect(s1);co.start();voices++;
amb={bedF,bedG,rumG,co,cg,next:0};
setInterval(schedule,100);
}catch(e){AC=null;mv=null;amb=null;voices=0;acFails++}
}
const now=()=>AC?AC.currentTime+0.012:0;
const midi=m=>440*Math.pow(2,(m-69)/12);
const rnd=(a,b)=>a+Math.random()*(b-a);
/* ---------- music: one original piece per valley ---------- */
const CH={Dm:[50,57,62,65],G:[55,59,62,67],C:[48,55,60,64],Am:[45,57,60,64],F:[53,57,60,65],Em:[52,55,59,64],
D:[50,57,62,66],E:[52,56,59,64],A:[45,57,61,64],Bm:[47,59,62,66]};
const NN={c:0,d:2,e:4,f:5,g:7,a:9,b:11};
const tok=k=>k==='-'?-1:k==='.'?-2:NN[k[0]]+(k[1]==='#'?1:0)+12*(+k[k.length-1]+1);
const bars=a=>a.map(s=>{const p=s.split(':');return{c:CH[p[0]],m:p[1].split(' ').map(tok)}});
const LOSE=bars(['Dm:a5 . . f5 . . d5 .','Am:e5 . . c5 . . a4 .','F:c5 . . a4 . . f4 .','Em:e4 . . . . . - -']);
/* sl = seconds per eighth; fast = how much quicker at full progress; calm = menu slow-down;
lead = [attack, mid level, mid position, filter Hz, volume]; amb = wind/rain bed [filter Hz, Q, level, wobble] */
const REALMS={
dawn:{sl:0.227,fast:0.013,calm:1.3,vol:0.36,pad:0.6,cut:1700,lead:[0.005,0.25,0.25,5200,0.2],amb:[520,0.5,0.05,0.6], /* D lydian, 132-140 BPM */
song:bars(['D:f#5 a5 d6 a5 f#5 a5 d6 -','D:e6 . d6 a5 . f#5 a5 -','E:g#5 b5 e6 b5 g#5 b5 e6 -','E:f#6 . e6 b5 . g#5 b5 -',
'D:a5 d6 f#6 d6 a5 d6 f#6 -','D:e6 . d6 . a5 . f#5 -','A:e5 a5 c#6 a5 e5 a5 c#6 e6','A:c#6 . . b5 a5 . - -',
'Bm:b5 . d6 b5 f#5 . b5 -','Bm:d6 . f#6 d6 b5 . d6 -','E:e6 . g#5 b5 e6 . g#6 -','E:f#6 e6 b5 g#5 . b5 e6 -',
'D:d6 . a5 f#5 d6 . a5 -','E:e6 . b5 g#5 e6 . g#6 -','A:a6 . e6 c#6 a5 c#6 e6 a6','D:f#6 . . d6 . . - -'])},
ember:{sl:0.3,fast:0,calm:1.15,vol:0.38,pad:0.8,cut:1000,lead:[0.05,0.7,0.6,1900,0.2],amb:[340,0.5,0.07,0.5], /* D dorian, 100 BPM */
song:bars(['Dm:d5 . a5 . . g5 f5 .','G:g5 . . . b4 . d5 .','Dm:f5 . e5 d5 . . a4 .','C:c5 . e5 . g5 . . -',
'F:a5 . . g5 f5 . c5 .','C:e5 . . . g5 . e5 .','G:d5 . b4 . g4 . b4 d5','Dm:d5 . . . . . - -',
'Dm:a5 . d6 . . c6 a5 .','G:b5 . . . g5 . d5 .','F:c6 . a5 f5 . . a5 .','C:g5 . e5 . c5 . . -',
'Am:e5 . . a5 . g5 e5 .','F:f5 . . . a5 . c6 .','G:b5 . a5 . g5 . d5 .','Dm:d5 . . . . . - -'])},
moon:{sl:0.435,fast:0,calm:1.08,vol:0.36,pad:1,cut:620,lead:[0.004,0.2,0.15,1500,0.22],ring:1,amb:[3000,0.3,0.04,0.12], /* A minor, 69 BPM */
song:bars(['Am:e5 - - - a5 - - c6','Am:- - b5 - - - e5 -','F:c6 - - - a5 - - f5','F:- - - g5 - - - -',
'C:e5 - - g5 - - c6 -','C:- - - - d6 - e6 -','G:d6 - - b5 - - g5 -','Em:- - e5 - - - b4 -',
'Am:a5 - - e5 - - c5 -','F:- - f5 - a5 - - -','C:g5 - - - e5 - - c5','G:- - d5 - - - g5 -',
'Am:e5 - a5 - - - c6 -','F:- - - a5 - - f5 -','Dm:f5 - - d5 - - a5 -','Em:- - g5 - - - - -'])}
};
const MOODMAP={menu:'menu',explore:'explore',lose:'lose',event:'explore',finale:'explore',win:'menu'};
let nextT=0,stepI=0,mood='menu',pend='menu',realm='ember',pendR='ember',ambR='ember',prog=0,stepLen=0.3,fall=0,pendFall=false,swAt=0,critT=0;
/* note envelope on a fixed voice: attack a, level falls to vol*m at fraction k, then to 0 at d */
function mnote(v,t,f,d,vol,a,m,k){
const g=v.g.gain;a=Math.min(a,d*0.3);
v.o.frequency.setValueAtTime(f,t);
g.setValueAtTime(0,t);g.linearRampToValueAtTime(vol,t+a);g.linearRampToValueAtTime(vol*m,t+a+(d-a)*k);g.linearRampToValueAtTime(0,t+d);
}
function pnote(v,t,d,vol){const g=v.g.gain;g.setValueAtTime(0,t);g.linearRampToValueAtTime(vol,t+0.003);g.linearRampToValueAtTime(0,t+d)}
function hushParam(p,t,d){
try{
if(p.cancelAndHoldAtTime)p.cancelAndHoldAtTime(t);else{const x=p.value;p.cancelScheduledValues(t);p.setValueAtTime(x,t)}
p.linearRampToValueAtTime(0,t+d);
}catch(e){}
}
function cutNotes(t){ /* end ringing notes cleanly before a new section starts */
['lead','bass','pulse'].forEach(k=>{hushParam(mv[k].g.gain,t,0.03);try{mv[k].o.frequency.cancelScheduledValues(t)}catch(e){}});
}
function barStart(t,c,R,calm,e,falling){ /* layer levels and pad chord glide: the crossfade between moods */
const T=(p,v)=>p.setTargetAtTime(v,t,0.5);
T(mv.padL.gain,R.pad*(calm?0.9:0.8+0.2*e));
T(mv.padLP.frequency,R.cut*(calm?0.75:1+0.6*e));
T(mv.pads[2].g.gain,!calm&&(realm==='dawn'||e>=0.33)?0.07:0);
T(mv.bass.L.gain,calm?0.6:0.8+0.2*e);
T(mv.lead.L.gain,calm?0.55:0.85+0.15*e);
T(mv.leadLP.frequency,falling?1800:R.lead[3]);
T(mv.pulse.L.gain,calm?0:realm==='ember'?0.3+0.5*e:realm==='dawn'?0.7+0.3*e:0.6);
T(mv.percL.gain,calm?0:0.7+0.3*e);
for(let i=0;i<3;i++)mv.pads[i].o.frequency.setTargetAtTime(midi(c[1+i]),t,0.12);
}
function playStep(t){
const R=REALMS[realm],falling=mood==='lose'&&fall>0,calm=mood!=='explore',e=calm?0:prog;
const song=falling?LOSE:R.song,sl=stepLen=falling?0.4:calm?R.sl*R.calm:R.sl-R.fast*e;
const bar=song[(stepI>>3)%song.length],s=stepI&7,c=bar.c,m=bar.m[s];
if(s===0)barStart(t,c,R,calm,e,falling);
if(m>=0){
let h=1,k=s+1;for(;k<8&&bar.m[k]===-2;k++)h++;
if(R.ring&&!falling)for(;k<8&&bar.m[k]===-1&&h<6;k++)h++; /* bell notes ring through the rests */
const L=falling?[0.05,0.7,0.6]:R.lead;
mnote(mv.lead,t,midi(m),h*sl*0.96,R.lead[4],L[0],L[1],L[2]);
}
const b=mv.bass,r=midi(c[0]);
if(calm||realm==='moon'){if(s===0)mnote(b,t,r,sl*7.7,0.22,0.15,0.75,0.6);return calm?0:moonExtra(t,s,c,sl,e)}
if(realm==='dawn'){
if(e>=0.75)mnote(b,t,[r,r,r*2,r,r,r*2,r*1.5,r*2][s],sl*0.92,0.24,0.01,0.5,0.4);
else if(s===0||s===3)mnote(b,t,r,sl*2.8,0.26,0.015,0.6,0.5);else if(s===6)mnote(b,t,r*1.5,sl*1.9,0.22,0.015,0.6,0.5);
mnote(mv.pulse,t,midi([c[1],c[2],c[3],c[2],c[1]+12,c[2],c[3],c[2]][s]),sl*0.9,s%4===0?0.17:0.12,0.005,0.3,0.3);
if(s&1)pnote(mv.hat,t,0.04,0.05);else if(e>=0.25)pnote(mv.hat,t,0.03,0.025);
if(s===4&&e>=0.5)pnote(mv.clap,t,0.09,0.07);
}else{ /* ember */
if(s===0)mnote(b,t,r,sl*3.9,0.24,0.05,0.7,0.6);else if(s===4)mnote(b,t,e>=0.66?r*1.5:r,sl*3.9,0.2,0.05,0.7,0.6);
const pn=e>=0.66?[c[1],c[2],c[3],c[2],c[1]+12,c[3],c[2],c[3]][s]:(s===0||s===3||s===6)?c[1]:0;
if(pn)mnote(mv.pulse,t,midi(pn),sl*0.9,0.13,0.006,0.3,0.3);
if(e>=0.5&&(s===2||s===6))pnote(mv.hat,t,0.04,0.02);
}
}
function moonExtra(t,s,c,sl,e){if(e>=0.5&&(s===2||s===6))mnote(mv.pulse,t,midi(c[s===2?2:3]),sl*3.5,0.07,0.005,0.25,0.2)}
/* ---------- ambience: wind / rain bed from the shared noise, creatures on one oscillator ---------- */
function cn(t,f,d,v,f2){
const g=amb.cg.gain,fr=amb.co.frequency;fr.setValueAtTime(f,t);if(f2)fr.exponentialRampToValueAtTime(f2,t+d);
g.setValueAtTime(0,t);g.linearRampToValueAtTime(v,t+Math.min(0.008,d*0.3));g.linearRampToValueAtTime(0,t+d);return t+d;
}
function cricket(t,f,v){for(let i=0;i<3;i++)cn(t+i*0.034,f,0.024,v);return t+0.11}
function critter(t){ /* schedules one little call, returns when the next may start */
const x=Math.random(),n=(Math.random()*3)|0;
if(ambR==='dawn'){ /* birds */
const b=rnd(2600,3600);
if(x<0.5)for(let i=0;i<n+2;i++)t=cn(t,b,0.07,0.045,b*1.35)+0.05;
else if(x<0.8){t=cn(t,b*1.3,0.12,0.045,b*0.9)+0.04;t=cn(t,b,0.09,0.04,b*1.25)}
else for(let i=0;i<6;i++)t=cn(t,b*(i%2?1.12:1),0.035,0.04)+0.012;
return t+rnd(1.2,4.5);
}
if(ambR==='ember'){ /* the first distant crickets, a far bird now and then */
if(x<0.85){const f=rnd(4000,4500);for(let i=0;i<=n;i++)t=cricket(t,f,0.022)+0.22;return t+rnd(0.8,3)}
t=cn(t,1900,0.18,0.025,1500)+0.1;t=cn(t,1900,0.25,0.02,1400);return t+rnd(2,4);
}
/* moon: night jungle in the rain */
if(x<0.55){const f=rnd(4300,4900);for(let i=0;i<4+n*2;i++)t=cricket(t,f,0.03)+0.3;return t+rnd(0.4,1.4)}
if(x<0.75){for(let i=0;i<=n;i++)t=cn(t,rnd(1300,1900),0.05,0.05,700)+rnd(0.15,0.4);return t+rnd(0.3,1)} /* drips */
if(x<0.9){const f=rnd(420,520);for(let k=0;k<2;k++){for(let i=0;i<5;i++)cn(t+i*0.036,f*(k?1.2:1),0.028,0.07);t+=0.32}return t+rnd(1,2.5)} /* frog */
t=cn(t,620,0.3,0.04,560)+0.12;t=cn(t,560,0.45,0.04,500);return t+rnd(1.5,3); /* night bird, soft hoo-hoo */
}
function ambTick(ct){
if(!amb)return;
if(pendR!==ambR){ /* new valley: retarget the bed now (about 2 s), quiet the old creatures */
ambR=pendR;amb.next=0;hushParam(amb.cg.gain,ct,0.05);try{amb.co.frequency.cancelScheduledValues(ct)}catch(e){}
critT=ct+1.4;
}
const A=REALMS[ambR].amb;
if(ct>=amb.next){
const first=!amb.next,d=first?1.6:rnd(1,2.2),tc=d*0.4;amb.next=ct+d;
amb.bedG.gain.setTargetAtTime(A[2]*rnd(1-A[3],1+A[3]),ct,tc);
amb.bedF.frequency.setTargetAtTime(A[0]*rnd(1-A[3]*0.6,1+A[3]*0.6),ct,tc);
if(first)amb.bedF.Q.setTargetAtTime(A[1],ct,tc);
amb.rumG.gain.setTargetAtTime(ambR==='moon'&&Math.random()<0.12?0.2:0,ct,1.2); /* a far, soft rumble now and then */
}
if(muted)return;
if(critT<ct)critT=ct+rnd(0.3,1);
while(critT<ct+0.6)critT=critter(critT);
}
function schedule(force){
if(!AC||!mv)return;
sweep();
if(force!==true&&AC.state!=='running')return;
const ct=AC.currentTime;
ambTick(ct);gusts(ct);
if(pendR!==realm&&!swAt){swAt=ct+0.8;try{musicBus.gain.cancelScheduledValues(ct);musicBus.gain.setTargetAtTime(0,ct,0.22)}catch(e){}}
if(nextT<ct+0.02)nextT=ct+0.06;
while(nextT<ct+0.6){
const sw=swAt&&nextT>=swAt;
if(sw||((stepI&3)===0&&(pend!==mood||pendFall))){ /* valleys fade through; moods change on half-bar lines */
if(sw){swAt=0;realm=pendR;musicBus.gain.setTargetAtTime(REALMS[realm].vol,nextT,0.35)}
mood=pend;fall=mood==='lose'&&(pendFall||fall>0)?32:0;pendFall=false;stepI=0;cutNotes(nextT);nextT+=0.05;
}
playStep(nextT);nextT+=stepLen;
if(fall>0&&--fall===0)stepI=0; /* the fall is over: settle into the calm version of the valley */
else stepI=(stepI+1)%((fall>0?LOSE:REALMS[realm].song).length*8);
}
}
const music={
setRealm(name){if(REALMS[name])pendR=name},
setMood(name){const m=MOODMAP[name];if(!m)return;pend=m;if(m==='lose')pendFall=true},
setProgress(p){prog=clamp(+p||0,0,1)},
tick(){schedule(true)},
get mood(){return mood},
get realm(){return realm}
};
/* ---------- sfx engine ---------- */
const SFXMIN=8; /* fixed music + ambience voices; everything above is sfx */
function room(n){
if(!AC||!sfxBus||voices+n>MAXV)return false;
return AC.state==='running'||voices+n<=SFXMIN+2; /* do not pile sounds up while the phone has us paused */
}
const lastAt={};
function gate(name,gap,n){
if(!room(n||1))return false;
const t=AC.currentTime;if(lastAt[name]!==undefined&&t-lastAt[name]<gap&&t>=lastAt[name])return false;
lastAt[name]=t;return true;
}
function track(src,end,nodes){
const r={src,end,nodes,done:false};voices++;live.add(r);
src.onended=()=>release(r);return r;
}
function release(r){
if(r.done)return;r.done=true;voices--;live.delete(r);
for(const x of r.nodes){try{x.disconnect()}catch(e){}}
}
function sweep(){ /* safety net in case an 'ended' event is ever lost */
if(!live.size)return;const ct=AC.currentTime;
live.forEach(r=>{if(ct>r.end+0.6){try{r.src.stop()}catch(e){}release(r)}});
}
/* one oscillator plays a whole phrase: notes = [offset, freq, dur, vol, slideToFreq, attack] (must not overlap).
bell=true gives a struck, fast-decaying shape; otherwise the note is sustained. */
function seq(type,notes,t0,bell,dest){
if(!room(1))return null;
const o=AC.createOscillator(),g=AC.createGain(),f=o.frequency,gg=g.gain;let end=t0;
o.type=type;gg.value=0;
for(const n of notes){
const t=t0+n[0],d=n[2],a=Math.min(n[5]||0.006,d*0.4);
f.setValueAtTime(n[1],t);if(n[4])f.exponentialRampToValueAtTime(n[4],t+d);
gg.setValueAtTime(0,t);gg.linearRampToValueAtTime(n[3],t+a);
gg.linearRampToValueAtTime(n[3]*(bell?0.22:0.7),t+a+(d-a)*(bell?0.22:0.6));gg.linearRampToValueAtTime(0,t+d);
end=Math.max(end,t+d);
}
o.connect(g);g.connect(dest||sfxBus);o.start(t0+notes[0][0]);o.stop(end+0.03);
track(o,end+0.03,[o,g]);return o;
}
/* filtered noise: bursts = [offset, dur, vol, attack]; the filter can sweep from freq to f2 */
function nz(bursts,t0,ftype,freq,q,f2){
if(!room(1))return;
const s=AC.createBufferSource(),fl=AC.createBiquadFilter(),g=AC.createGain(),gg=g.gain;let end=t0;
s.buffer=noiseBuf;s.loop=true;fl.type=ftype;fl.frequency.value=freq;fl.Q.value=q||1;gg.value=0;
for(const b of bursts){const t=t0+b[0],a=Math.min(b[3]||0.004,b[1]*0.5);
gg.setValueAtTime(0,t);gg.linearRampToValueAtTime(b[2],t+a);gg.linearRampToValueAtTime(0,t+b[1]);end=Math.max(end,t+b[1])}
if(f2){fl.frequency.setValueAtTime(freq,t0+bursts[0][0]);fl.frequency.exponentialRampToValueAtTime(f2,end)}
s.connect(fl);fl.connect(g);g.connect(sfxBus);s.start(t0+bursts[0][0],Math.random()*0.5);s.stop(end+0.03);
track(s,end+0.03,[s,fl,g]);
}
/* held noise loops (boost rush, wind) */
const loops={boost:null,wind:null};
function loop(name,on,ftype,freq,q,vol,fade){
if(!AC||!sfxBus)return;
if(on){
if(loops[name]||voices+1>MAXV)return;
const t=AC.currentTime,s=AC.createBufferSource(),fl=AC.createBiquadFilter(),g=AC.createGain();
s.buffer=noiseBuf;s.loop=true;fl.type=ftype;fl.frequency.value=freq;fl.Q.value=q;
g.gain.value=0;g.gain.setValueAtTime(0,t);g.gain.linearRampToValueAtTime(vol,t+fade);
s.connect(fl);fl.connect(g);g.connect(sfxBus);s.start(t,Math.random()*0.5);
const r=track(s,Infinity,[s,fl,g]);r.g=g;r.fl=fl;r.next=t+fade;loops[name]=r;
}else{
const r=loops[name];if(!r)return;loops[name]=null;
const t=AC.currentTime;hushParam(r.g.gain,t,fade);
try{r.src.stop(t+fade+0.04)}catch(e){}
r.end=t+fade+0.04;
}
}
function gusts(ct){ /* the wind breathes: slow random swells, driven from the music timer */
const w=loops.wind;if(!w||ct<w.next)return;
const d=rnd(0.7,1.6);w.next=ct+d;
try{w.g.gain.setTargetAtTime(rnd(0.035,0.11),ct,d*0.4);w.fl.frequency.setTargetAtTime(rnd(260,760),ct,d*0.4)}catch(e){}
}
const SC=[74,77,79,81,84,86,88,89,91,93]; /* D dorian, rising */
let wispT=0;
const sfx={
wisp(combo){ /* glass chime; combo 1..10 climbs the scale */
if(!room(1))return;
const ct=now();if(wispT>ct+1)wispT=0;
const t=Math.max(ct,wispT+0.07);if(t-ct>0.4)return;
wispT=t;
const f=midi(SC[clamp((combo|0)-1,0,9)]);
seq('sine',[[0,f,0.55,0.2]],t,true);
seq('sine',[[0,f*2.76,0.22,0.05]],t,true);
},
golden(){
if(!gate('golden',0.3,2))return;const t=now();
seq('sine',[[0,587,0.5,0.2],[0.5,1175,0.55,0.18],[1.05,1760,0.8,0.15]],t,true);
seq('sine',[[0.14,880,0.5,0.18],[0.66,1480,0.6,0.15]],t,true);
seq('triangle',[[0,147,1.5,0.16,0,0.4]],t);
},
boostLoop(on){loop('boost',!!on,'bandpass',1300,0.6,0.1,0.22)},
wind(on){loop('wind',!!on,'bandpass',420,0.5,0.07,0.6)},
dash(){if(gate('dash',0.1))nz([[0,0.36,0.22,0.1]],now(),'bandpass',500,1.4,3400)},
hit(){
if(!gate('hit',0.15,2))return;const t=now(),N=[];
seq('sine',[[0,120,0.22,0.5,45]],t);
nz([[0,0.14,0.3]],t,'lowpass',420,0.7);
let i=7+((Math.random()*3)|0);
for(let k=0;k<5;k++){N.push([0.05+k*0.075+rnd(0,0.02),midi(SC[i]+12),0.07,0.07]);i=Math.max(0,i-1-((Math.random()*2)|0))}
seq('sine',N,t,true);
},
heartLost(){
if(!gate('heartLost',0.3))return;const t=now();
seq('triangle',[[0,440,0.3,0.2,0,0.02],[0.32,349,0.3,0.19,0,0.02],[0.64,294,0.7,0.18,0,0.02]],t);
seq('sine',[[0,147,1.3,0.16,0,0.1]],t);
},
shrine(){ /* deep bell, then light blooms upward */
if(!gate('shrine',0.5,3))return;const t=now();
seq('sine',[[0,146.8,2.8,0.34]],t,true);
seq('sine',[[0,294.4,2.4,0.24]],t,true);
seq('sine',[[0,405.5,1.5,0.12]],t,true);
seq('sine',[[0.5,587,0.3,0.08],[0.8,880,0.3,0.08],[1.1,1175,0.3,0.08],[1.4,1319,0.3,0.07],[1.7,1760,0.7,0.07]],t,true);
},
event(){ /* horn call: a rising fifth */
if(!gate('event',0.6,2))return;const t=now();
seq('sawtooth',[[0,293.7,0.4,0.2,0,0.07],[0.42,440,1.1,0.22,0,0.07]],t,false,hornLP);
seq('sawtooth',[[0,146.8,0.4,0.14,0,0.07],[0.42,220,1.1,0.15,0,0.07]],t,false,hornLP);
},
meteor(){
if(!gate('meteor',0.12,2))return;const t=now();
seq('sine',[[0,rnd(2300,2700),0.6,0.1,520,0.3],[0.62,95,0.3,0.36,48]],t);
nz([[0.6,0.4,0.2,0.01]],t,'lowpass',700,0.7,180);
},
ring(n){ /* ring pass; n = 1,2,3... rises */
if(!gate('ring',0.08,2))return;const t=now(),f=midi(SC[(Math.max(1,n|0)-1)%10]);
seq('sine',[[0,f,0.13,0.18],[0.13,f*1.5,0.6,0.18]],t,true);
nz([[0,0.28,0.1,0.08]],t,'bandpass',900,1.2,2600);
},
gateOpen(){
if(!gate('gateOpen',1,3))return;const t=now(),A=[],B=[];
seq('sawtooth',[[0,146.8,2.6,0.2,0,0.7]],t,false,hornLP);
seq('sawtooth',[[0,220,2.6,0.15,0,0.9]],t,false,hornLP);
[587,740,880,1175,1480,1760,2349].forEach((f,i)=>(i%2?B:A).push([0.5+i*0.2,f,0.39,0.11]));
seq('sine',A,t,true);seq('sine',B,t,true);
nz([[0,2.2,0.09,1.4]],t,'bandpass',300,0.8,3000);
},
nearMiss(){
if(!gate('nearMiss',0.15,2))return;const t=now();
nz([[0,0.24,0.2,0.05]],t,'bandpass',2800,1.5,600);
seq('sine',[[0,980,0.2,0.07,560,0.04]],t);
},
ui(){if(gate('ui',0.03))seq('sine',[[0,1175,0.14,0.11]],now(),true)},
gameOver(){
if(!gate('gameOver',1,2))return;const t=now();
seq('triangle',[[0,587,0.5,0.2,0,0.03],[0.5,523,0.5,0.19,0,0.03],[1,440,0.5,0.18,0,0.03],[1.5,349,0.5,0.17,0,0.03],[2,294,1.6,0.18,0,0.03]],t);
seq('sine',[[0,146.8,3.6,0.16,0,0.5]],t);
},
victory(){
if(!gate('victory',1,3))return;const t=now();
seq('sawtooth',[[0,293.7,0.26,0.2,0,0.04],[0.27,440,0.26,0.2,0,0.04],[0.54,587,0.5,0.21,0,0.04],[1.06,740,1.7,0.22,0,0.05]],t,false,hornLP);
seq('sawtooth',[[0,220,0.52,0.14,0,0.05],[0.54,293.7,0.5,0.15,0,0.05],[1.06,440,1.7,0.16,0,0.05]],t,false,hornLP);
seq('triangle',[[0,146.8,1.04,0.2,0,0.05],[1.06,146.8,1.7,0.22,0,0.05]],t);
seq('sine',[[1.1,1760,0.24,0.09],[1.35,2349,0.24,0.09],[1.6,2960,0.24,0.08],[1.85,3520,0.8,0.08]],t,true);
}
};
function setMuted(m){
muted=m;store.set('muted',m);$('snd').textContent=m?'🔇':'🔊';
if(master&&AC&&!ducked){try{master.gain.cancelScheduledValues(AC.currentTime);master.gain.setTargetAtTime(m?0:0.9,AC.currentTime,0.015)}catch(e){master.gain.value=m?0:0.9}}
}
const safe=o=>new Proxy(o||{},{get:(t,k)=>typeof t[k]==='function'?t[k].bind(t):()=>{}});
const SFX=safe(typeof sfx==='object'?sfx:null),MUS=safe(typeof music==='object'?music:null);
// the old phone beep, on top of the chime
function beep(f,d,delay){try{if(!AC||AC.state!=='running'||muted)return;const t=AC.currentTime+(delay||0)+.01,o=AC.createOscillator(),g=AC.createGain();o.type='square';o.frequency.value=f;g.gain.setValueAtTime(.0001,t);g.gain.exponentialRampToValueAtTime(.05,t+.005);g.gain.setValueAtTime(.05,t+d-.01);g.gain.exponentialRampToValueAtTime(.0001,t+d);o.connect(g);g.connect(AC.destination);o.start(t);o.stop(t+d+.02)}catch(e){}}
/* ---- world.js ---- */
/* Snake 3D - world module. Defines one global: createWorld(THREE, scene, opts). three.js r128. */
function createWorld(THREE, scene, opts) {
'use strict';
opts = opts || {};
var themeName = (opts.theme === 'ember' || opts.theme === 'moon') ? opts.theme : 'dawn';
var seed = (opts.seed | 0) || 1;
var LOW = opts.quality === 'low';
var HALF = 170, CEIL = 70, WATER = 0, PI = Math.PI, TAU = PI * 2;
var added = [], textures = [];
var prevFog = scene.fog;
// ------------------------------------------------------------------ rng + noise
function mkRng(s) { return function () { s = (s + 0x6D2B79F5) | 0; var t = Math.imul(s ^ (s >>> 15), 1 | s); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
var rnd = mkRng(seed * 9973 + 7);
function rr(a, b) { return a + (b - a) * rnd(); }
var PV = new Float32Array(256), PM = new Uint8Array(512);
(function () { var i, j, t; for (i = 0; i < 256; i++) { PV[i] = rnd() * 2 - 1; PM[i] = i; } for (i = 255; i > 0; i--) { j = (rnd() * (i + 1)) | 0; t = PM[i]; PM[i] = PM[j]; PM[j] = t; } for (i = 0; i < 256; i++) PM[i + 256] = PM[i]; })();
function n2(x, y) {
var xi = Math.floor(x), yi = Math.floor(y), fx = x - xi, fy = y - yi; xi &= 255; yi &= 255;
fx = fx * fx * (3 - 2 * fx); fy = fy * fy * (3 - 2 * fy);
var a = PV[PM[PM[xi] + yi]], b = PV[PM[PM[xi + 1] + yi]], c = PV[PM[PM[xi] + yi + 1]], d = PV[PM[PM[xi + 1] + yi + 1]];
return a + (b - a) * fx + (c - a) * fy + (a - b - c + d) * fx * fy;
}
function n3(x, y, z) {
var xi = Math.floor(x), yi = Math.floor(y), zi = Math.floor(z), fx = x - xi, fy = y - yi, fz = z - zi; xi &= 255; yi &= 255; zi &= 255;
fx = fx * fx * (3 - 2 * fx); fy = fy * fy * (3 - 2 * fy); fz = fz * fz * (3 - 2 * fz);
var A = PM[xi] + yi, B = PM[xi + 1] + yi, AA = PM[A] + zi, AB = PM[A + 1] + zi, BA = PM[B] + zi, BB = PM[B + 1] + zi;
var a = PV[PM[AA]], b = PV[PM[BA]], c = PV[PM[AB]], d = PV[PM[BB]], e = PV[PM[AA + 1]], f = PV[PM[BA + 1]], g = PV[PM[AB + 1]], h = PV[PM[BB + 1]];
var l0 = a + (b - a) * fx, l1 = c + (d - c) * fx, l2 = e + (f - e) * fx, l3 = g + (h - g) * fx;
var m0 = l0 + (l1 - l0) * fy, m1 = l2 + (l3 - l2) * fy;
return m0 + (m1 - m0) * fz;
}
function fbm(x, y, o) { var s = 0, a = 0.5, t = 0; for (var i = 0; i < o; i++) { s += a * n2(x, y); t += a; a *= 0.5; x = x * 2.03 + 17.1; y = y * 2.03 - 9.3; } return s / t; }
function ridged(x, y, o) { var s = 0, a = 0.5, t = 0; for (var i = 0; i < o; i++) { var v = 1 - Math.abs(n2(x, y)); s += a * v * v; t += a; a *= 0.5; x = x * 2.1 + 5.7; y = y * 2.1 + 3.1; } return s / t; }
function sst(a, b, x) { var t = (x - a) / (b - a); t = t < 0 ? 0 : t > 1 ? 1 : t; return t * t * (3 - 2 * t); }
function hyp(a, b) { return Math.sqrt(a * a + b * b); }
function gauss(dx, dz, s) { return Math.exp(-(dx * dx + dz * dz) / (2 * s * s)); }
// ------------------------------------------------------------------ palettes
var TH = {
dawn: {
sun: [-0.64, 0.55, 0.28],
grassA: [.30, .46, .22], grassB: [.50, .58, .26], meadow: [.74, .64, .36], alp: [.60, .58, .46], sand: [.84, .74, .56], bed: [.30, .44, .42],
rockA: [.58, .46, .44], rockB: [.82, .66, .54], rockD: [.36, .30, .34], moss: [.40, .52, .25], snowC: [1, .95, .94], snow: 80, canyon: [1.0, .66, .46],
stoneA: [.76, .70, .63], stoneB: [.92, .86, .76], bark: [.36, .27, .22], barkB: [.48, .37, .29],
leaf: [[.24, .42, .22], [.38, .54, .23], [.95, .62, .70], [1.0, .80, .84]], pine: [.16, .34, .24],
glowC: [[1, .74, .34], [1, .52, .62]], shal: [.42, .76, .72], deep: [.10, .30, .46], foam: [1, .97, .93],
bird: [.20, .16, .22], mote: [1, .86, .55], cloud: .75, star: 0, aur: 0, disc: .99945, discC: [1.6, 1.4, 1.1],
k0: { zen: [.13, .17, .36], mid: [.44, .37, .56], fog: [.50, .44, .58], fogSun: [.90, .58, .54], sunC: [.56, .44, .48], amb: [.40, .43, .60], gnd: [.24, .22, .30], glow: 1.2, cloudL: [.80, .58, .62], cloudS: [.34, .31, .46], den: 1.5, lum: .62, sg: [.5, .3, .25] },
k1: { zen: [.25, .46, .82], mid: [.98, .75, .70], fog: [.93, .84, .86], fogSun: [1, .91, .72], sunC: [1.0, .80, .58], amb: [.60, .62, .80], gnd: [.50, .42, .40], glow: 1.6, cloudL: [1, .90, .82], cloudS: [.78, .60, .68], den: 1.0, lum: 1, sg: [1, .75, .45] }
},
ember: {
sun: [-0.74, 0.46, -0.49],
grassA: [.36, .42, .20], grassB: [.60, .54, .22], meadow: [.80, .58, .26], alp: [.70, .54, .38], sand: [.90, .66, .42], bed: [.36, .34, .34],
rockA: [.62, .33, .24], rockB: [.86, .54, .33], rockD: [.38, .20, .20], moss: [.56, .50, .22], snowC: [.98, .84, .68], snow: 96, canyon: [1.0, .52, .28],
stoneA: [.80, .64, .52], stoneB: [.96, .82, .64], bark: [.30, .20, .17], barkB: [.44, .29, .22],
leaf: [[.84, .44, .14], [.72, .24, .14], [.92, .66, .18], [.50, .50, .18]], pine: [.22, .30, .17],
glowC: [[1, .62, .22], [1, .40, .24]], shal: [.50, .62, .58], deep: [.14, .20, .36], foam: [1, .93, .84],
bird: [.20, .10, .12], mote: [1, .60, .25], cloud: .9, star: .15, aur: 0, disc: .9991, discC: [1.7, 1.2, .7],
k0: { zen: [.12, .10, .26], mid: [.44, .25, .36], fog: [.52, .31, .33], fogSun: [.90, .44, .27], sunC: [.62, .37, .29], amb: [.38, .32, .44], gnd: [.24, .17, .18], glow: 1.3, cloudL: [.84, .42, .32], cloudS: [.30, .20, .32], den: 1.5, lum: .62, sg: [.6, .25, .12] },
k1: { zen: [.20, .20, .52], mid: [.97, .48, .35], fog: [1, .64, .40], fogSun: [1, .82, .42], sunC: [1.12, .68, .38], amb: [.52, .42, .54], gnd: [.42, .28, .22], glow: 1.8, cloudL: [1, .70, .42], cloudS: [.60, .32, .40], den: 1.05, lum: 1, sg: [1.1, .6, .25] }
},
moon: {
sun: [-0.38, 0.74, -0.55],
grassA: [.20, .40, .42], grassB: [.28, .50, .46], meadow: [.36, .50, .58], alp: [.44, .52, .62], sand: [.60, .66, .76], bed: [.16, .30, .42],
rockA: [.40, .44, .60], rockB: [.58, .62, .78], rockD: [.24, .26, .40], moss: [.22, .48, .48], snowC: [.86, .93, 1], snow: 76, canyon: [.62, .58, .92],
stoneA: [.62, .66, .80], stoneB: [.80, .84, .96], bark: [.26, .26, .36], barkB: [.36, .36, .48],
leaf: [[.16, .40, .44], [.20, .50, .46], [.46, .36, .70], [.30, .60, .66]], pine: [.14, .34, .40],
glowC: [[.35, 1, .9], [.8, .5, 1]], shal: [.20, .50, .62], deep: [.04, .12, .28], foam: [.8, .92, 1],
bird: [.75, .9, 1], mote: [.5, 1, .8], cloud: .45, star: 1, aur: 1, disc: .9988, discC: [1.3, 1.35, 1.4],
k0: { zen: [.02, .03, .10], mid: [.05, .09, .21], fog: [.09, .15, .27], fogSun: [.18, .27, .40], sunC: [.36, .44, .64], amb: [.22, .28, .44], gnd: [.09, .12, .19], glow: 1.0, cloudL: [.22, .30, .44], cloudS: [.05, .08, .16], den: 1.4, lum: .6, sg: [.2, .25, .35] },
k1: { zen: [.03, .06, .21], mid: [.08, .19, .40], fog: [.15, .29, .46], fogSun: [.38, .54, .68], sunC: [.72, .84, 1.12], amb: [.30, .40, .60], gnd: [.12, .17, .26], glow: 2.4, cloudL: [.44, .56, .74], cloudS: [.08, .14, .26], den: 1.0, lum: 1, sg: [.4, .5, .65] }
}
};
var P = TH[themeName];
var sunDir = new THREE.Vector3(P.sun[0], P.sun[1], P.sun[2]).normalize();
var SX = sunDir.x, SY = sunDir.y, SZ = sunDir.z, SH = hyp(SX, SZ), TANEL = SY / SH;
// ------------------------------------------------------------------ layout
var HILL = { x: 84, z: 86 }, TEMPLE = { x: 4, z: 50 }, LAKE = { x: -72, z: 24, r: 52 }, ISLE = { x: -74, z: 20 };
var FALL = { x: 77.5, z: -52 }, POOL = { x: 64, z: -52 }, SHELF = { x: 70, z: -24 }, GATE = { x: -2, z: -141 }, POND = { x: -70, z: 108 };
var RA = { x: -138, z: -52 }, RB = { x: -66, z: -64 };
function spline2(c, sub) {
var out = [], n = c.length, i, s;
for (i = 0; i < n - 1; i++) {
var p0 = c[i > 0 ? i - 1 : 0], p1 = c[i], p2 = c[i + 1], p3 = c[i + 2 < n ? i + 2 : n - 1];
for (s = 0; s < sub; s++) {
var t = s / sub, t2 = t * t, t3 = t2 * t;
out.push(0.5 * (2 * p1[0] + (-p0[0] + p2[0]) * t + (2 * p0[0] - 5 * p1[0] + 4 * p2[0] - p3[0]) * t2 + (-p0[0] + 3 * p1[0] - 3 * p2[0] + p3[0]) * t3),
0.5 * (2 * p1[1] + (-p0[1] + p2[1]) * t + (2 * p0[1] - 5 * p1[1] + 4 * p2[1] - p3[1]) * t2 + (-p0[1] + 3 * p1[1] - 3 * p2[1] + p3[1]) * t3));
}
}
out.push(c[n - 1][0], c[n - 1][1]);
var x0 = 1e9, x1 = -1e9, z0 = 1e9, z1 = -1e9;
for (i = 0; i < out.length; i += 2) { if (out[i] < x0) x0 = out[i]; if (out[i] > x1) x1 = out[i]; if (out[i + 1] < z0) z0 = out[i + 1]; if (out[i + 1] > z1) z1 = out[i + 1]; }
out.bb = [x0, x1, z0, z1];
return out;
}
var _pt = 0;
function polyDist(Pl, x, z, pad) {
var bb = Pl.bb; if (x < bb[0] - pad || x > bb[1] + pad || z < bb[2] - pad || z > bb[3] + pad) return 1e9;
var best = 1e18, bt = 0, n = Pl.length / 2 - 1;
for (var i = 0; i < n; i++) {
var ax = Pl[i * 2], az = Pl[i * 2 + 1], bx = Pl[i * 2 + 2] - ax, bz = Pl[i * 2 + 3] - az;
var t = ((x - ax) * bx + (z - az) * bz) / (bx * bx + bz * bz); t = t < 0 ? 0 : t > 1 ? 1 : t;
var dx = x - ax - bx * t, dz = z - az - bz * t, d = dx * dx + dz * dz;
if (d < best) { best = d; bt = (i + t) / n; }
}
_pt = bt; return Math.sqrt(best);
}
var _px = 0, _pz = 0, _pdx = 0, _pdz = 1;
function polyAt(Pl, t) { var n = Pl.length / 2 - 1, f = t * n, i = Math.floor(f); if (i >= n) i = n - 1; if (i < 0) i = 0; f -= i; _pdx = Pl[i * 2 + 2] - Pl[i * 2]; _pdz = Pl[i * 2 + 3] - Pl[i * 2 + 1]; _px = Pl[i * 2] + _pdx * f; _pz = Pl[i * 2 + 1] + _pdz * f; var l = hyp(_pdx, _pdz) || 1; _pdx /= l; _pdz /= l; }
var CAN = spline2([[17, -44], [11, -64], [-3, -79], [-19, -90], [-23, -104], [-9, -116], [8, -122], [5, -130], [0, -136], [-2, -141]], 8);
var GDX = -0.16, GDZ = -0.987;
var RIV = spline2([[64, -52], [50, -42], [32, -22], [10, -4], [-10, 8], [-26, 16], [-44, 20]], 6);
var OUT = spline2([[-92, 60], [-90, 78], [-80, 94], [-70, 108]], 5);
function canFloor(t) { return 5.5 + 6.5 * t; }
function canW(t) { return 7.6 + 2 * Math.sin(t * 10 + 1); }
var RDX = RB.x - RA.x, RDZ = RB.z - RA.z, RLEN = hyp(RDX, RDZ); RDX /= RLEN; RDZ /= RLEN;
var TUN = { x: RA.x + RDX * RLEN * 0.5, z: RA.z + RDZ * RLEN * 0.5 };
function terr(h, n, amt) { var st = 13, v = h / st + n * 0.5, f = Math.floor(v), q = (f + sst(0.2, 0.62, v - f) - n * 0.5) * st; return h + (q - h) * amt; }
function hRaw(x, z) {
var d, t;
var nA = fbm(x * 0.011 + 3.1, z * 0.011 - 7.7, 4), nB = fbm(x * 0.04 - 11, z * 0.04 + 5, 3);
var h = 6.2 + nA * 5.5 + nB * 1.5; if (h < 2.4) h = 2.4 + (h - 2.4) * 0.25;
d = hyp(x - HILL.x, z - HILL.z); h += 23 * (1 - sst(9, 42, d));
d = hyp(x - TEMPLE.x, z - TEMPLE.z); h += (7.5 - h) * (1 - sst(22, 36, d));
// plateau with cliff
var q = (x - 72) - 10 * Math.sin((z + 52) * 0.035) - nB * 6 * sst(8, 30, Math.abs(z + 52));
var pm = sst(0, 5.5, q) * sst(16, -2, z + nA * 6);
if (pm > 0) {
var ph = 35 + nB * 2 + nA * 2, zs = -52 - (x - 76) * 0.06 + 3.5 * Math.sin(x * 0.07 - 5.32);
ph -= 2.4 * (1 - sst(1.5, 5, Math.abs(z - zs)));
h += (ph - h) * pm;
}
// rim mountains (rounded-square bowl), lower toward the sun so the valley gets light
var x2 = x * x, z2 = z * z, d4 = Math.sqrt(Math.sqrt(x2 * x2 + z2 * z2)) + fbm(x * 0.02 - 5, z * 0.02 + 5, 3) * 9;
var em = sst(122, 176, d4), rg = ridged(x * 0.013 + 1.7, z * 0.013 - 4.2, 4);
if (em > 0) {
var cs = (x * SX + z * SZ) / ((hyp(x, z) || 1) * SH); cs = cs < 0 ? 0 : cs;
h += terr(Math.pow(em, 1.5) * (98 + rg * 48) * (1 - 0.3 * cs * cs), nB, 0.75);
}
h += 11 * sst(100, 134, d4) * (0.6 + 0.4 * nA);
// canyon massif
var mm = sst(-56, -72, z + nA * 8) * sst(82, 62, Math.abs(x - 4) + nB * 6);
if (mm > 0) { var Hm = 62 + rg * 30 + nA * 5 + 40 * gauss(x + 36, z + 152, 20) + 44 * gauss(x - 32, z + 154, 20); Hm = terr(Hm, nB, 0.6); if (Hm > h) h += (Hm - h) * mm; }
if (z < -30 && x > -60 && x < 50) {
d = polyDist(CAN, x, z, 40); t = _pt;
var dg = hyp(x - GATE.x, z - GATE.z) - 18; if (dg < d) { d = dg; t = 1; }
var fl = canFloor(t), u = (d - canW(t)) / 10;
if (u < 1 && h > fl) { var pr = u <= 0 ? 0 : 0.5 * sst(0, 0.3, u) + 0.5 * sst(0.5, 1, u); h = fl + (h - fl) * pr; }
}
var gs = (x - GATE.x) * GDX + (z - GATE.z) * GDZ;
if (gs > 6 && Math.abs(x) < 90) {
var pass = canFloor(1) + sst(8, 80, gs) * 34, u2 = (Math.abs((x - GATE.x) * GDZ - (z - GATE.z) * GDX) - (9 + gs * 0.14)) / 16;
if (u2 < 1 && h > pass) h = pass + (h - pass) * sst(0, 1, u2);
}
// ridge with tunnel notch
var al = (x - RA.x) * RDX + (z - RA.z) * RDZ, pd = Math.abs((x - RA.x) * RDZ - (z - RA.z) * RDX);
if (pd < 22 && al > -25 && al < RLEN + 20) {
var rp = (1 - sst(3.5, 16, pd + nB * 2.5)) * sst(-22, -4, al) * sst(RLEN + 18, RLEN + 2, al);
h += (28 + nA * 5) * rp * sst(6.4, 9.8, Math.abs(al - RLEN * 0.5));
}
// water
d = polyDist(RIV, x, z, 12); var dp = hyp(x - POOL.x, z - POOL.z) - 3; if (dp < d) d = dp;
if (d < 10) h += (-2.6 - h) * (1 - sst(3, 10, d));
d = hyp(x - LAKE.x, (z - LAKE.z) * 1.12) + nB * 5 + nA * 4;
if (d < LAKE.r + 6) h += (-8 - h) * (1 - sst(LAKE.r - 15, LAKE.r + 4, d));
d = polyDist(OUT, x, z, 12); dp = hyp(x - POND.x, z - POND.z) - 7; if (dp < d) d = dp;
if (d < 9) h += (-2.0 - h) * (1 - sst(2.5, 9, d));
d = hyp(x - ISLE.x, z - ISLE.z); if (d < 20) { var ih = -8 + 12.8 * (1 - sst(7, 19, d)); if (ih > h) h = ih; }
var sxx = x - SHELF.x; sxx = sxx < 0 ? sxx : sxx > 16 ? sxx - 16 : 0; d = hyp(sxx, z - SHELF.z) + nB * 1.5; if (d < 14) { var sh = 19.5 * (1 - sst(9.5, 13, d)); if (sh > h) h = sh; }
return h;
}
// ------------------------------------------------------------------ height grid
var GN = 301, GS = 2, GO = 300, H = new Float32Array(GN * GN);
(function () {
var i, j, st = LOW ? 2 : 1;
for (j = 0; j < GN; j += st) for (i = 0; i < GN; i += st) H[j * GN + i] = hRaw(i * GS - GO, j * GS - GO);
if (LOW) {
for (j = 0; j < GN; j += 2) for (i = 1; i < GN; i += 2) H[j * GN + i] = 0.5 * (H[j * GN + i - 1] + H[j * GN + i + 1]);
for (j = 1; j < GN; j += 2) for (i = 0; i < GN; i++) H[j * GN + i] = 0.5 * (H[(j - 1) * GN + i] + H[(j + 1) * GN + i]);
}
})();
var GMAX = GN - 1.001;
function heightAt(x, z) {
var fx = (x + GO) * 0.5, fz = (z + GO) * 0.5; if (fx < 0) fx = 0; else if (fx > GMAX) fx = GMAX; if (fz < 0) fz = 0; else if (fz > GMAX) fz = GMAX;
var ix = fx | 0, iz = fz | 0; fx -= ix; fz -= iz; var i = iz * GN + ix, a = H[i], b = H[i + 1], c = H[i + GN], d = H[i + GN + 1];
return (a + (b - a) * fx) * (1 - fz) + (c + (d - c) * fx) * fz;
}
function slopeNy(x, z) { var e = LOW ? 4 : 2, hx = heightAt(x + e, z) - heightAt(x - e, z), hz = heightAt(x, z + e) - heightAt(x, z - e); return 1 / Math.sqrt(1 + (hx * hx + hz * hz) / (4 * e * e)); }
function sunVis(x, y, z) {
var vis = 1, t = 2.5;
for (var i = 0; i < 44; i++) {
var py = y + SY * t; if (py > 150) break;
var c = (py - heightAt(x + SX * t, z + SZ * t)) / t * 7; if (c < vis) { vis = c; if (vis <= 0) return 0; }
t += 2.5 + t * 0.07;
}
return vis;
}
var SPL = new Float32Array(GN * GN); for (var _i = 0; _i < SPL.length; _i++) SPL[_i] = 1;
function castPt(x, y, z, rad, str) {
var L = 0, g = heightAt(x, z), it;
for (it = 0; it < 3; it++) { L = Math.max(0, (y - g) / TANEL); if (L > 70) return; g = heightAt(x - SX / SH * L, z - SZ / SH * L); }
var cx = x - SX / SH * L, cz = z - SZ / SH * L, R = rad * 1.2 + 1;
var i0 = Math.max(0, Math.floor((cx - R + GO) / GS)), i1 = Math.min(GN - 1, Math.ceil((cx + R + GO) / GS)), j0 = Math.max(0, Math.floor((cz - R + GO) / GS)), j1 = Math.min(GN - 1, Math.ceil((cz + R + GO) / GS));
for (var j = j0; j <= j1; j++) for (var i = i0; i <= i1; i++) {
var d = hyp(i * GS - GO - cx, j * GS - GO - cz), v = 1 - str * (1 - sst(rad * 0.5, rad * 1.2 + 0.8, d));
if (v < SPL[j * GN + i]) SPL[j * GN + i] = v;
}
}
// ------------------------------------------------------------------ colliders
var cT = [], cD = [];
function cPush(t, a) { cT.push(t); for (var i = 0; i < 16; i++) cD.push(i < a.length ? a[i] : 0); }
function cSphere(x, y, z, r) { cPush(0, [x, y, z, r]); }
function cCaps(ax, ay, az, bx, by, bz, ra, rb) { var dx = bx - ax, dy = by - ay, dz = bz - az, l2 = dx * dx + dy * dy + dz * dz; cPush(1, [ax, ay, az, dx, dy, dz, ra, rb, l2 > 1e-9 ? 1 / l2 : 0]); }
function cBox(cx, cy, cz, A, hu, hv, hw) {
var ux = A[0], uy = A[1], uz = A[2], l = Math.sqrt(ux * ux + uy * uy + uz * uz) || 1; ux /= l; uy /= l; uz /= l;
var wx = uy * A[5] - uz * A[4], wy = uz * A[3] - ux * A[5], wz = ux * A[4] - uy * A[3]; l = Math.sqrt(wx * wx + wy * wy + wz * wz) || 1; wx /= l; wy /= l; wz /= l;
cPush(2, [cx, cy, cz, ux, uy, uz, wy * uz - wz * uy, wz * ux - wx * uz, wx * uy - wy * ux, wx, wy, wz, hu, hv, hw]);
}
function axes(yaw, pitch, roll) {
var c = Math.cos(yaw), s = Math.sin(yaw), u = [c, 0, -s], v = [0, 1, 0], w = [s, 0, c], i, a, b;
if (roll) { c = Math.cos(roll); s = Math.sin(roll); for (i = 0; i < 3; i++) { a = u[i]; b = v[i]; u[i] = a * c + b * s; v[i] = -a * s + b * c; } }
if (pitch) { c = Math.cos(pitch); s = Math.sin(pitch); for (i = 0; i < 3; i++) { a = v[i]; b = w[i]; v[i] = a * c + b * s; w[i] = -a * s + b * c; } }
return [u[0], u[1], u[2], v[0], v[1], v[2], w[0], w[1], w[2]];
}
// ------------------------------------------------------------------ geometry accumulators
function Acc() { this.p = []; this.c = []; this.f = []; this.i = []; this.n = 0; }
var CH = 3, solidAcc = [], leafAcc = [];
for (_i = 0; _i < CH * CH; _i++) { solidAcc.push(new Acc()); leafAcc.push(new Acc()); }
function accAt(arr, x, z) { var cx = Math.floor((x + HALF) / (2 * HALF) * CH), cz = Math.floor((z + HALF) / (2 * HALF) * CH); cx = cx < 0 ? 0 : cx > CH - 1 ? CH - 1 : cx; cz = cz < 0 ? 0 : cz > CH - 1 ? CH - 1 : cz; return arr[cz * CH + cx]; }
function V(a, x, y, z, r, g, b, gl, st) { a.p.push(x, y, z); a.c.push(r, g, b, gl); a.f.push(1, st); return a.n++; }
function triO(a, i0, i1, i2, dx, dy, dz) {
var p = a.p, ax = p[i0 * 3], ay = p[i0 * 3 + 1], az = p[i0 * 3 + 2];
var ux = p[i1 * 3] - ax, uy = p[i1 * 3 + 1] - ay, uz = p[i1 * 3 + 2] - az, vx = p[i2 * 3] - ax, vy = p[i2 * 3 + 1] - ay, vz = p[i2 * 3 + 2] - az;
if ((uy * vz - uz * vy) * dx + (uz * vx - ux * vz) * dy + (ux * vy - uy * vx) * dz < 0) a.i.push(i0, i2, i1); else a.i.push(i0, i1, i2);
}
var CR = 0, CG = 0, CB = 0;
function setc(c) { CR = c[0]; CG = c[1]; CB = c[2]; }
function blend(c, t) { CR += (c[0] - CR) * t; CG += (c[1] - CG) * t; CB += (c[2] - CB) * t; }
function mixc(a, b, t) { CR = a[0] + (b[0] - a[0]) * t; CG = a[1] + (b[1] - a[1]) * t; CB = a[2] + (b[2] - a[2]) * t; }
function colRock(x, y, z, ny) {
var s = n2(y * 0.21 + n2(x * 0.06, z * 0.06) * 1.4, 5.5) * 0.5 + 0.5; mixc(P.rockA, P.rockB, s);
var m = n3(x * 0.09, y * 0.09, z * 0.09); blend(P.rockD, sst(0.1, 0.7, -m) * 0.5);
if (ny > 0.3) { var top = sst(0.3, 0.75, ny + m * 0.2); if (y > P.snow + 6) blend(P.snowC, top); else blend(P.moss, top * 0.85); }
}
function colStone(x, y, z, ny) {
mixc(P.stoneA, P.stoneB, n3(x * 0.3, y * 0.3, z * 0.3) * 0.5 + 0.5);
blend(P.rockD, sst(0.2, 0.8, n2(x * 0.11 + y * 0.3, z * 0.11)) * 0.22);
if (ny > 0.5) blend(P.moss, sst(0.0, 0.6, n2(x * 0.2, z * 0.2)) * 0.6);
}
function colBark(x, y, z, ny) { mixc(P.bark, P.barkB, n3(x * 0.5, y * 0.15, z * 0.5) * 0.5 + 0.5); if (ny > 0.4) blend(P.moss, 0.55); }
var LC = P.leaf[0], LB = 1;
function colLeaf(x, y, z, ny) { var b = LB * (0.78 + 0.3 * (ny * 0.5 + 0.5) + 0.12 * n3(x * 0.4, y * 0.4, z * 0.4)); CR = LC[0] * b; CG = LC[1] * b; CB = LC[2] * b; }
var FC = [1, 1, 1];
function colFlat() { CR = FC[0]; CG = FC[1]; CB = FC[2]; }
function colIsle(x, y, z, ny) { colRock(x, y, z, ny); if (ny > 0.15) { mixc(P.grassA, P.grassB, n2(x * 0.2, z * 0.2) * 0.5 + 0.5); } else if (ny < -0.3) blend(P.rockD, 0.45); }
function rdisp(x, y, z, fq, amp, ledge) {
var s = 1 + amp * (n3(x * fq, y * fq, z * fq) + 0.5 * n3(x * fq * 2.7 + 7, y * fq * 2.7, z * fq * 2.7));
if (ledge) { var f = y * 0.21 + 0.6 * n2(x * 0.05, z * 0.05); f -= Math.floor(f); s += ledge * (sst(0, 0.12, f) - sst(0.55, 1, f) - 0.4); }
return s;
}
function sweep(acc, pts, rx, ry, sides, o) {
var n = pts.length / 3, closed = !!o.closed, col = o.col, noise = o.noise || 0, fq = o.freq || 0.15, rot = o.rot || 0, glow = o.glow || 0, st = o.st || 0;
var tp = new Float64Array(n * sides * 3), tc = new Float32Array(n * sides * 3), k, j, q, B = o.B;
if (!B) {
var Dx = pts[n * 3 - 3] - pts[0], Dy = pts[n * 3 - 2] - pts[1], Dz = pts[n * 3 - 1] - pts[2], Dl = Math.sqrt(Dx * Dx + Dy * Dy + Dz * Dz) || 1;
if (Math.abs(Dy) < 0.9 * Dl) B = [Dz / Dl, 0, -Dx / Dl]; else B = [1, 0, 0];
}
for (k = 0; k < n; k++) {
var i0 = k > 0 ? k - 1 : (closed ? n - 1 : 0), i1 = k < n - 1 ? k + 1 : (closed ? 0 : n - 1);
var tx = pts[i1 * 3] - pts[i0 * 3], ty = pts[i1 * 3 + 1] - pts[i0 * 3 + 1], tz = pts[i1 * 3 + 2] - pts[i0 * 3 + 2], tl = Math.sqrt(tx * tx + ty * ty + tz * tz) || 1; tx /= tl; ty /= tl; tz /= tl;
var bx = B[0], by = B[1], bz = B[2], dt = bx * tx + by * ty + bz * tz; bx -= tx * dt; by -= ty * dt; bz -= tz * dt;
var bl = Math.sqrt(bx * bx + by * by + bz * bz) || 1; bx /= bl; by /= bl; bz /= bl;
var nx = by * tz - bz * ty, ny = bz * tx - bx * tz, nz = bx * ty - by * tx;
var cx = pts[k * 3], cy = pts[k * 3 + 1], cz = pts[k * 3 + 2], RX = rx[k], RY = ry ? ry[k] : RX;
for (j = 0; j < sides; j++) {
var a = rot + j / sides * TAU, ca = Math.cos(a), sa = Math.sin(a); if (o.sq) { ca = (ca < 0 ? -1 : 1) * Math.pow(Math.abs(ca), o.sq); sa = (sa < 0 ? -1 : 1) * Math.pow(Math.abs(sa), o.sq); } ca *= RX; sa *= RY;
var ox = nx * ca + bx * sa, oy = ny * ca + by * sa, oz = nz * ca + bz * sa;
if (noise) { var s = rdisp(cx + ox, cy + oy, cz + oz, fq, noise, o.ledge); ox *= s; oy *= s; oz *= s; }
q = (k * sides + j) * 3; tp[q] = cx + ox; tp[q + 1] = cy + oy; tp[q + 2] = cz + oz;
var ol = Math.sqrt(ox * ox + oy * oy + oz * oz) || 1; col(tp[q], tp[q + 1], tp[q + 2], oy / ol); tc[q] = CR; tc[q + 1] = CG; tc[q + 2] = CB;
}
}
var base = acc.n, segs = closed ? n : n - 1, k2, j2, A, Bi, C, D;
if (!o.hard) {
for (q = 0; q < n * sides; q++) V(acc, tp[q * 3], tp[q * 3 + 1], tp[q * 3 + 2], tc[q * 3], tc[q * 3 + 1], tc[q * 3 + 2], glow, st);
for (k = 0; k < segs; k++) {
k2 = (k + 1) % n;
for (j = 0; j < sides; j++) {
j2 = (j + 1) % sides; A = base + k * sides + j; Bi = base + k * sides + j2; C = base + k2 * sides + j; D = base + k2 * sides + j2;
var ex = acc.p[A * 3] + acc.p[D * 3] - pts[k * 3] - pts[k2 * 3], ey = acc.p[A * 3 + 1] + acc.p[D * 3 + 1] - pts[k * 3 + 1] - pts[k2 * 3 + 1], ez = acc.p[A * 3 + 2] + acc.p[D * 3 + 2] - pts[k * 3 + 2] - pts[k2 * 3 + 2];
triO(acc, A, C, Bi, ex, ey, ez); triO(acc, Bi, C, D, ex, ey, ez);
}
}
} else {
for (k = 0; k < segs; k++) {
k2 = (k + 1) % n;
for (j = 0; j < sides; j++) {
j2 = (j + 1) % sides; var qs = [k * sides + j, k * sides + j2, k2 * sides + j, k2 * sides + j2], id = [];
for (q = 0; q < 4; q++) id.push(V(acc, tp[qs[q] * 3], tp[qs[q] * 3 + 1], tp[qs[q] * 3 + 2], tc[qs[q] * 3], tc[qs[q] * 3 + 1], tc[qs[q] * 3 + 2], glow, st));
var fx = tp[qs[0] * 3] + tp[qs[3] * 3] - pts[k * 3] - pts[k2 * 3], fy = tp[qs[0] * 3 + 1] + tp[qs[3] * 3 + 1] - pts[k * 3 + 1] - pts[k2 * 3 + 1], fz = tp[qs[0] * 3 + 2] + tp[qs[3] * 3 + 2] - pts[k * 3 + 2] - pts[k2 * 3 + 2];
triO(acc, id[0], id[2], id[1], fx, fy, fz); triO(acc, id[1], id[2], id[3], fx, fy, fz);
}
}
}
for (var e = 0; e < 2; e++) {
if (!(e ? o.capB : o.capA)) continue;
k = e ? n - 1 : 0; var kk = e ? n - 2 : 1;
var wx = pts[k * 3] - pts[kk * 3], wy = pts[k * 3 + 1] - pts[kk * 3 + 1], wz = pts[k * 3 + 2] - pts[kk * 3 + 2];
col(pts[k * 3], pts[k * 3 + 1], pts[k * 3 + 2], wy > 0 ? 1 : 0);
var ci = V(acc, pts[k * 3] + wx * 0.15, pts[k * 3 + 1] + wy * 0.15, pts[k * 3 + 2] + wz * 0.15, CR, CG, CB, glow, st), ring = [];
for (j = 0; j < sides; j++) { q = (k * sides + j) * 3; ring.push(o.hard ? V(acc, tp[q], tp[q + 1], tp[q + 2], tc[q], tc[q + 1], tc[q + 2], glow, st) : base + k * sides + j); }
for (j = 0; j < sides; j++) triO(acc, ci, ring[j], ring[(j + 1) % sides], wx, wy, wz);
}
}
function ico(det) {
var t = (1 + Math.sqrt(5)) / 2, v = [-1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, 0, -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, t, 0, -1, t, 0, 1, -t, 0, -1, -t, 0, 1];
var f = [0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1], i;
function norm() { for (i = 0; i < v.length; i += 3) { var l = Math.sqrt(v[i] * v[i] + v[i + 1] * v[i + 1] + v[i + 2] * v[i + 2]); v[i] /= l; v[i + 1] /= l; v[i + 2] /= l; } }
norm();
for (var d = 0; d < det; d++) {
var nf = [], cache = {};
var mid = function (a, b) { var key = a < b ? a + '_' + b : b + '_' + a; if (cache[key] !== undefined) return cache[key]; v.push((v[a * 3] + v[b * 3]) / 2, (v[a * 3 + 1] + v[b * 3 + 1]) / 2, (v[a * 3 + 2] + v[b * 3 + 2]) / 2); return (cache[key] = v.length / 3 - 1); };
for (i = 0; i < f.length; i += 3) { var a = f[i], b = f[i + 1], c = f[i + 2], ab = mid(a, b), bc = mid(b, c), ca = mid(c, a); nf.push(a, ab, ca, b, bc, ab, c, ca, bc, ab, bc, ca); }
f = nf; norm();
}
return { v: v, f: f };
}
var ICO = [ico(0), ico(1), ico(2)];
function blob(acc, cx, cy, cz, rx, ry, rz, yaw, det, col, o) {
o = o || {}; var I = ICO[det], base = acc.n, cs = Math.cos(yaw), sn = Math.sin(yaw), noise = o.noise || 0, fq = o.freq || 0.2, glow = o.glow || 0, st = o.st || 0, i;
for (i = 0; i < I.v.length; i += 3) {
var x = I.v[i], y = I.v[i + 1], z = I.v[i + 2], sx = x, sy = y, sz = z;
if (o.island) { if (y > 0) sy = y * 0.3; else { var tp = 1 + y * 0.85; tp = tp < 0.1 ? 0.1 : tp; sx *= tp; sz *= tp; sy = y * 1.5; } }
var px = sx * rx, py = sy * ry, pz = sz * rz, ox = px * cs + pz * sn, oz = -px * sn + pz * cs;
if (noise) { var s = rdisp(cx + ox, cy + py, cz + oz, fq, noise, o.ledge); ox *= s; oz *= s; py *= (o.island && y > 0) ? 1 + (s - 1) * 0.5 : s; }
col(cx + ox, cy + py, cz + oz, y);
V(acc, cx + ox, cy + py, cz + oz, CR, CG, CB, glow, o.sway != null ? o.sway * (y * 0.5 + 0.5) : st);
}
for (i = 0; i < I.f.length; i += 3) {
var a = base + I.f[i], b = base + I.f[i + 1], c = base + I.f[i + 2], yc = (I.v[I.f[i] * 3 + 1] + I.v[I.f[i + 1] * 3 + 1] + I.v[I.f[i + 2] * 3 + 1]) / 3;
var mx = (acc.p[a * 3] + acc.p[b * 3] + acc.p[c * 3]) / 3 - cx, mz = (acc.p[a * 3 + 2] + acc.p[b * 3 + 2] + acc.p[c * 3 + 2]) / 3 - cz;
triO(acc, a, b, c, mx / rx, o.island ? (yc > 0.2 ? 3 : yc * 0.6 - 0.25) : yc * (rx + rz) / (2 * ry), mz / rz);
}
}
function quadN(acc, c, nx, ny, nz, col, glow, st) {
var id = [];
for (var q = 0; q < 4; q++) { col(c[q * 3], c[q * 3 + 1], c[q * 3 + 2], ny); id.push(V(acc, c[q * 3], c[q * 3 + 1], c[q * 3 + 2], CR, CG, CB, glow || 0, st || 0)); }
triO(acc, id[0], id[1], id[2], nx, ny, nz); triO(acc, id[0], id[2], id[3], nx, ny, nz);
}
var BF = [[1, 3, 7, 5], [0, 2, 6, 4], [2, 3, 7, 6], [0, 1, 5, 4], [4, 5, 7, 6], [0, 1, 3, 2]];
function boxM(acc, cx, cy, cz, A, hu, hv, hw, col, o) {
o = o || {}; var c = [], su, sv, sw, f, q;
for (sw = -1; sw <= 1; sw += 2) for (sv = -1; sv <= 1; sv += 2) for (su = -1; su <= 1; su += 2) c.push(cx + A[0] * hu * su + A[3] * hv * sv + A[6] * hw * sw, cy + A[1] * hu * su + A[4] * hv * sv + A[7] * hw * sw, cz + A[2] * hu * su + A[5] * hv * sv + A[8] * hw * sw);
for (f = 0; f < 6; f++) {
if (o.noBottom && f === 3) continue;
var pts = [], ax = (f >> 1) * 3, sg = (f & 1) ? -1 : 1;
for (q = 0; q < 4; q++) pts.push(c[BF[f][q] * 3], c[BF[f][q] * 3 + 1], c[BF[f][q] * 3 + 2]);
quadN(acc, pts, A[ax] * sg, A[ax + 1] * sg, A[ax + 2] * sg, col, o.glow, o.st);
}
}
function solidBox(cx, cy, cz, A, hu, hv, hw, col, o) { boxM(accAt(solidAcc, cx, cz), cx, cy, cz, A, hu, hv, hw, col, o); cBox(cx, cy, cz, A, hu * 0.96, hv * 0.96, hw * 0.96); }
// ------------------------------------------------------------------ placement helpers
var KO = [], AN = [];
function ko(x, z, r) { KO.push(x, z, r); }
function koFree(x, z, r) { for (var i = 0; i < KO.length; i += 3) { var dx = x - KO[i], dz = z - KO[i + 1], rr2 = r + KO[i + 2]; if (dx * dx + dz * dz < rr2 * rr2) return false; } return true; }
function anchor(x, y, z) { AN.push(x, y, z); }
function rockArch(x, z, yaw, span, height, thick, depth, o) {
o = o || {}; var ax = Math.cos(yaw), az = -Math.sin(yaw), bx = Math.sin(yaw), bz = Math.cos(yaw);
var n = LOW ? 13 : 19, pts = [], rxs = [], rys = [], k, hs = span / 2, ph = rnd() * 10, wob = o.uniform ? 0 : 1;
var hl = heightAt(x - ax * hs, z - az * hs), hr = heightAt(x + ax * hs, z + az * hs); if (o.baseY != null) hl = hr = o.baseY;
for (k = 0; k < n; k++) {
var s = k / (n - 1), th = PI * (1 - s), c = Math.cos(th), sn = Math.sin(th);
var u = (c < 0 ? -1 : 1) * Math.pow(Math.abs(c), 0.75) * hs + n2(s * 3 + ph, 1.3) * span * 0.05 * wob * sn, w = n2(s * 2.5 + ph, 7.7) * depth * 0.25 * wob;
pts.push(x + ax * u + bx * w, hl + (hr - hl) * s - 2.5 + Math.pow(sn, 0.7) * height, z + az * u + bz * w);
var leg = Math.abs(c); rxs.push(thick * 0.5 * (o.uniform ? 1 : (0.72 + 0.55 * leg * leg))); rys.push(depth * 0.5 * (o.uniform ? 1 : (0.8 + 0.4 * leg)));
}
sweep(accAt(solidAcc, x, z), pts, rxs, rys, LOW ? 8 : 11, { B: [bx, 0, bz], col: colRock, noise: 0.2, freq: 0.19, st: 1, capA: true, capB: true, sq: 0.7, ledge: o.uniform ? 0.05 : 0.15 });
for (k = 0; k < n - 1; k++) {
var tx = pts[k * 3 + 3] - pts[k * 3], ty = pts[k * 3 + 4] - pts[k * 3 + 1], tz = pts[k * 3 + 5] - pts[k * 3 + 2], l = Math.sqrt(tx * tx + ty * ty + tz * tz); tx /= l; ty /= l; tz /= l;
var nx = -bz * ty, ny = bz * tx - bx * tz, nz = bx * ty;
cBox((pts[k * 3] + pts[k * 3 + 3]) / 2, (pts[k * 3 + 1] + pts[k * 3 + 4]) / 2, (pts[k * 3 + 2] + pts[k * 3 + 5]) / 2, [tx, ty, tz, nx, ny, nz, bx, 0, bz], l / 2 + 0.3, (rxs[k] + rxs[k + 1]) * 0.41, (rys[k] + rys[k + 1]) * 0.41);
castPt(pts[k * 3], pts[k * 3 + 1], pts[k * 3 + 2], rxs[k] * 1.1, 0.55);
}
ko(x - ax * hs, z - az * hs, thick + 2); ko(x + ax * hs, z + az * hs, thick + 2); ko(x, z, hs * 0.6);
if (!o.noAnchor) anchor(x, (hl + hr) / 2 + (height - thick) * 0.45, z);
}
function spire(x, z, h, r) {
var g = heightAt(x, z) - 2, n = LOW ? 9 : 13, pts = [], rads = [], rz = [], k, lx = rr(-1, 1) * h * 0.07, lz = rr(-1, 1) * h * 0.07, ph = rnd() * 20, ya = rnd() * TAU, fl = rr(0.62, 0.95);
for (k = 0; k < n; k++) {
var s = k / (n - 1);
pts.push(x + lx * s * s + n2(s * 2 + ph, 3) * r * 0.3, g + (h + 2) * s, z + lz * s * s + n2(s * 2 + ph, 9) * r * 0.3);
var rad = r * (Math.pow(1 - s, 0.62) * 0.9 + 0.13) * (1 + 0.3 * n2(s * 4.3 + ph, 5)) * (1 + 0.55 * (1 - sst(0, 0.16, s)));
rads.push(rad); rz.push(rad * (fl + (1 - fl) * (1 - s)));
}
sweep(accAt(solidAcc, x, z), pts, rads, rz, LOW ? 7 : 10, { col: colRock, noise: 0.2, freq: 0.2, st: 1, capB: true, B: [Math.sin(ya), 0, Math.cos(ya)], sq: 0.8, ledge: 0.12 });
var ia = [0, (n / 3) | 0, (2 * n / 3) | 0, n - 1];
for (k = 0; k < 3; k++) { var a = ia[k] * 3, b = ia[k + 1] * 3; cCaps(pts[a], pts[a + 1], pts[a + 2], pts[b], pts[b + 1], pts[b + 2], rz[ia[k]] * 0.86, rz[ia[k + 1]] * 0.86); }
for (k = 0; k < n; k++) castPt(pts[k * 3], pts[k * 3 + 1], pts[k * 3 + 2], rads[k] * 1.1 + 0.4, 0.55);
ko(x, z, r * 1.6 + 1);
}
function boulder(x, z, r, yoff) {
var g = heightAt(x, z) + (yoff || 0), ry = r * rr(0.6, 0.9);
blob(accAt(solidAcc, x, z), x, g + ry * 0.35, z, r * rr(0.85, 1.2), ry, r * rr(0.8, 1.1), rnd() * TAU, r > 2.2 && !LOW ? 2 : 1, colRock, { noise: 0.24, freq: 0.5 / r + 0.1, st: 1 });
cSphere(x, g + ry * 0.3, z, Math.min(r, ry + 0.4) * 0.82); castPt(x, g + ry * 0.6, z, r, 0.5);
}
function cone(acc, x, y0, z, y1, rad, sides, ph, glow) {
var base = acc.n, j;
for (j = 0; j < sides; j++) { var a = ph + j / sides * TAU, rj = rad * ((j % 2) ? 1.0 : 0.66); colLeaf(x, y0, z, (j % 2) ? -0.9 : -0.2); V(acc, x + Math.cos(a) * rj, y0 - ((j % 2) ? 0.22 : -0.1) * rad, z + Math.sin(a) * rj, CR, CG, CB, glow, 0.5); }
colLeaf(x, y1, z, 1); var ap = V(acc, x, y1, z, CR, CG, CB, glow, 1);
for (j = 0; j < sides; j++) acc.i.push(ap, base + (j + 1) % sides, base + j);
}
function conifer(x, z, s) {
var g = heightAt(x, z) - 0.3, h = (9 + rnd() * 6) * s, r = (2.1 + rnd() * 0.7) * s, a = accAt(leafAcc, x, z), ph = rnd() * TAU, t, nt = LOW ? 3 : 5;
sweep(accAt(solidAcc, x, z), [x, g, z, x, g + h * 0.3, z], [0.36 * s, 0.24 * s], null, 4, { col: colBark, B: [1, 0, 0] });
LC = P.pine; LB = rr(0.8, 1.15);
for (t = 0; t < nt; t++) { var u = t / nt; cone(a, x, g + h * (0.14 + 0.72 * u), z, g + h * (0.14 + 0.72 * u + 0.3 + 0.1 * (1 - u)), r * (1 - 0.8 * u), LOW ? 6 : 8, ph + t * 0.9, themeName === 'moon' ? 0.05 : 0); }
cCaps(x, g, z, x, g + h * 0.8, z, r * 0.4, r * 0.08); castPt(x, g + h * 0.35, z, r * 0.95, 0.42); castPt(x, g + h * 0.7, z, r * 0.55, 0.42);
}
function broadleaf(x, z, s, ci) {
var g = heightAt(x, z) - 0.3, h = (6 + rnd() * 3.5) * s, R = (2.7 + rnd() * 1.1) * s, lx = rr(-1, 1) * s, lz = rr(-1, 1) * s;
sweep(accAt(solidAcc, x, z), [x, g, z, x + lx * 0.4, g + h * 0.35, z + lz * 0.4, x + lx, g + h * 0.7, z + lz], [0.5 * s, 0.36 * s, 0.24 * s], null, 5, { col: colBark, B: [1, 0, 0] });
LC = P.leaf[ci]; LB = rr(0.85, 1.12); var gl = themeName === 'moon' ? 0.1 : 0;
blob(accAt(leafAcc, x, z), x + lx, g + h * 0.82, z + lz, R, R * 0.78, R, rnd() * TAU, 1, colLeaf, { noise: 0.3, freq: 0.45, sway: 1, glow: gl });
if (!LOW) blob(accAt(leafAcc, x, z), x + lx + rr(-1, 1) * R * 0.7, g + h * 0.72 + rr(-0.2, 0.5) * R, z + lz + rr(-1, 1) * R * 0.7, R * 0.62, R * 0.5, R * 0.62, rnd() * TAU, 0, colLeaf, { noise: 0.2, freq: 0.5, sway: 1, glow: gl });
cCaps(x, g, z, x + lx, g + h * 0.7, z + lz, 0.5 * s, 0.35 * s); cSphere(x + lx, g + h * 0.82, z + lz, R * 0.5);
castPt(x + lx, g + h * 0.8, z + lz, R * 1.05, 0.42);
}
function flora(x, z, s, ci) {
var g = heightAt(x, z); if (g < 0.3) return; var a = accAt(leafAcc, x, z), n = 3 + ((rnd() * 4) | 0), i;
for (i = 0; i < n; i++) {
var px = x + rr(-1.8, 1.8) * s, pz = z + rr(-1.8, 1.8) * s, h = rr(0.5, 1.3) * s, gy = heightAt(px, pz), bx = px + rr(-0.4, 0.4), bz = pz + rr(-0.4, 0.4);
LC = P.pine; LB = 1.1; sweep(a, [px, gy - 0.2, pz, bx, gy + h, bz], [0.06 * s, 0.04 * s], null, 3, { col: colLeaf, B: [1, 0, 0], st: 0.6 });
FC = P.glowC[ci]; blob(a, bx, gy + h + 0.15 * s, bz, 0.24 * s, 0.3 * s, 0.24 * s, 0, 0, colFlat, { glow: 1, sway: 0.6 });
}
}
function column(x, z, y0, h, r, broken) {
var prof = [[0, 1.38], [0.55, 1.38], [0.85, 1.05], [h * 0.5, 1.0], [h - 1.4, 0.88], [h - 0.9, 1.2], [h - 0.35, 1.42], [h, 1.42]], pts = [], rads = [], k;
if (broken) prof = [[0, 1.38], [0.55, 1.38], [0.85, 1.05], [h * 0.6, 1.0], [h, 0.95]];
for (k = 0; k < prof.length; k++) { pts.push(x + (broken && k === prof.length - 1 ? 0.25 : 0), y0 + prof[k][0], z); rads.push(prof[k][1] * r); }
sweep(accAt(solidAcc, x, z), pts, rads, null, LOW ? 8 : 10, { col: colStone, capB: true, B: [1, 0, 0], noise: broken ? 0.06 : 0.02, freq: 0.6, st: 0.25 });
cCaps(x, y0 + r, z, x, y0 + h - r * 0.8, z, r * 1.0, r * 0.95);
for (k = 1; k < 5; k++) castPt(x, y0 + h * k / 4, z, r * 1.3, 0.5);
}
function temple() {
var cx = TEMPLE.x, cz = TEMPLE.z, yaw = 0.42, A = axes(yaw, 0, 0), base = heightAt(cx, cz), i, row, top = base + 2.0;
function L(lu, lw) { return [cx + A[0] * lu + A[6] * lw, cz + A[2] * lu + A[8] * lw]; }
for (i = 0; i < 3; i++) solidBox(cx, base - 0.6 + i * 0.85, cz, A, 28.5 - i * 1.3, 0.9, 12.5 - i * 1.3, colStone, { noBottom: true });
var states = [];
for (row = 0; row < 2; row++) {
states.push([]);
for (i = 0; i < 8; i++) {
var q = rnd(), stt = q < 0.62 ? 1 : q < 0.9 ? 2 : 0; if ((i === 0 || i === 7) && row === 0) stt = 1; if (i === 3 || i === 4) stt = row === 0 ? 1 : 2;
states[row].push(stt); var p = L(-23.1 + i * 6.6, row ? 7.4 : -7.4);
if (stt === 1) { column(p[0], p[1], top, 14, 1.15, false); solidBox(p[0], top + 14.3, p[1], A, 1.75, 0.3, 1.75, colStone); }
else if (stt === 2) {
var bh = rr(2.5, 8.5); column(p[0], p[1], top, bh, 1.15, true);
if (rnd() < 0.7) { FC = P.glowC[0]; blob(accAt(solidAcc, p[0], p[1]), p[0], top + bh + 0.9, p[1], 0.7, 0.85, 0.7, 0, 1, colFlat, { glow: 1 }); }
}
}
for (i = 0; i < 7; i++) if (states[row][i] === 1 && states[row][i + 1] === 1) { var m = L(-23.1 + i * 6.6 + 3.3, row ? 7.4 : -7.4); solidBox(m[0], top + 15.6, m[1], A, 4.6, 1.0, 1.45, colStone); }
}
for (i = 0; i < 8; i += 7) if (states[0][i] === 1 && states[1][i] === 1) { var e = L(-23.1 + i * 6.6, 0); solidBox(e[0], top + 17.4, e[1], axes(yaw + PI / 2, 0, 0), 8.8, 0.8, 1.3, colStone); }
for (i = 0; i < (LOW ? 4 : 7); i++) {
var f = L(rr(-30, 30), (rnd() < 0.5 ? -1 : 1) * rr(15, 22)), fy = heightAt(f[0], f[1]), fa = rnd() * TAU, len = rr(2, 4.5), dx = Math.cos(fa) * len, dz = Math.sin(fa) * len;
sweep(accAt(solidAcc, f[0], f[1]), [f[0] - dx, fy + 0.8, f[1] - dz, f[0] + dx, fy + 0.9, f[1] + dz], [1.15, 1.1], null, LOW ? 8 : 10, { col: colStone, capA: true, capB: true, st: 0.25 });
cCaps(f[0] - dx, fy + 0.8, f[1] - dz, f[0] + dx, fy + 0.9, f[1] + dz, 1.05, 1.05);
var bq = L(rr(-28, 28), (rnd() < 0.5 ? -1 : 1) * rr(14, 20)); solidBox(bq[0], heightAt(bq[0], bq[1]) + 0.6, bq[1], axes(rnd() * TAU, rr(-0.3, 0.3), rr(-0.2, 0.2)), rr(1, 2.2), rr(0.6, 1), rr(0.8, 1.4), colStone);
}
ko(cx, cz, 33);
for (i = -2; i <= 2; i++) { var c = L(i * 9, 0); anchor(c[0], top + 7, c[1]); }
return { top: top, yaw: yaw };
}
function aqueduct(x0, z0, x1, z1, deckY) {
var dx = x1 - x0, dz = z1 - z0, Ltot = hyp(dx, dz); dx /= Ltot; dz /= Ltot;
var yaw = Math.atan2(-dz, dx), A = axes(yaw, 0, 0), pw = 1.7, dp = 2.3, spans = [11, 7, 15, 8, 12, 17, 7, 11], pos = 0, i, k;
var state = [1, 1, 1, 0, 1, 2, 1, 1], acc;
function W3(u, y, w) { return [x0 + dx * u + A[6] * w, y, z0 + dz * u + A[8] * w]; }
function pier(u, topY) {
var p = W3(u, 0, 0), g = heightAt(p[0], p[2]) - 2;
solidBox(p[0], (g + topY) / 2, p[2], A, pw, (topY - g) / 2, dp, colStone, { noBottom: true });
solidBox(p[0], g + 3.2, p[2], A, pw + 0.45, 1.4, dp + 0.45, colStone, { noBottom: true });
for (var q = 1; q < 5; q++) castPt(p[0], g + (topY - g) * q / 4, p[2], 2.6, 0.5);
ko(p[0], p[2], 4);
}
for (i = 0; i <= spans.length; i++) {
var lft = i > 0 ? state[i - 1] : 0, rgt = i < spans.length ? state[i] : 0;
pier(pos, (lft === 1 || rgt === 1) ? deckY : deckY - rr(3, 9));
if (i === spans.length) break;
var sp = spans[i], r = sp / 2, mid = pos + pw + r, nseg = LOW ? 8 : 12, st = state[i];
for (k = 0; k < nseg; k++) {
if (st === 0 && k > 0 && k < nseg - 1) continue;
if (st === 2 && k > 2 && k < nseg - 2) continue;
var t0 = PI * k / nseg, t1 = PI * (k + 1) / nseg, u0 = mid - r * Math.cos(t0), u1 = mid - r * Math.cos(t1), ya0 = deckY - 0.7 - r + r * Math.sin(t0), ya1 = deckY - 0.7 - r + r * Math.sin(t1);
var topy = (st === 1) ? deckY : deckY - 0.4 - rr(0, 1.2), mp = W3((u0 + u1) / 2, 0, 0); acc = accAt(solidAcc, mp[0], mp[2]);
var a = W3(u0, ya0, dp * 0.94), b = W3(u1, ya1, dp * 0.94), c = W3(u1, topy, dp * 0.94), d = W3(u0, topy, dp * 0.94), a2 = W3(u0, ya0, -dp * 0.94), b2 = W3(u1, ya1, -dp * 0.94), c2 = W3(u1, topy, -dp * 0.94), d2 = W3(u0, topy, -dp * 0.94);
quadN(acc, a.concat(b, c, d), A[6], 0, A[8], colStone, 0, 0.2); quadN(acc, a2.concat(b2, c2, d2), -A[6], 0, -A[8], colStone, 0, 0.2);
quadN(acc, a.concat(b, b2, a2), 0, -1, 0, colStone, 0, 0.2);
if (st !== 1) { quadN(acc, d.concat(c, c2, d2), 0, 1, 0, colStone, 0, 0.2); if (k === 2 || k === 0) quadN(acc, b.concat(c, c2, b2), dx, 0, dz, colStone, 0, 0.2); if (k === nseg - 3 || k === nseg - 1) quadN(acc, a.concat(d, d2, a2), -dx, 0, -dz, colStone, 0, 0.2); }
var yl = Math.min(ya0, ya1) + 0.25;
cBox(mp[0], (yl + topy) / 2, mp[2], A, (u1 - u0) / 2, (topy - yl) / 2, dp * 0.9);
castPt(mp[0], topy, mp[2], 2.6, 0.5);
}
if (st === 1) { var dm = W3(mid, 0, 0); solidBox(dm[0], deckY + 0.8, dm[2], A, r + pw, 0.8, dp + 0.35, colStone); solidBox(dm[0], deckY + 2.1, dm[2] , A, r + pw, 0.5, dp + 0.35, colStone, { noBottom: true }); anchor(dm[0], deckY - 0.7 - r * 0.55, dm[2]); }
else { var rb = W3(mid + rr(-3, 3), 0, rr(-4, 4)); boulder(rb[0], rb[2], 2.2); rb = W3(mid + rr(-4, 4), 0, rr(-5, 5)); solidBox(rb[0], heightAt(rb[0], rb[2]) + 0.7, rb[2], axes(rnd() * 3, 0.3, 0.2), 2, 0.9, 1.3, colStone); anchor(W3(mid, 0, 0)[0], deckY - 4, W3(mid, 0, 0)[2]); }
pos += pw * 2 + sp;
}
}
function giantTree(x, z, yaw, s) {
var g = heightAt(x, z), ax = Math.cos(yaw), az = -Math.sin(yaw), bx = Math.sin(yaw), bz = Math.cos(yaw), th = 13 * s, tr = 3.0 * s, Rr = 8.6 * s, k, pts = [], rads = [], sa = accAt(solidAcc, x, z), la = accAt(leafAcc, x, z);
for (k = 0; k < 7; k++) { var t = k / 6; pts.push(x + n2(t * 2, yaw) * s, g - 2 + (th + 2.6) * t, z + n2(t * 2, yaw + 9) * s); rads.push(tr * (1.6 - 0.62 * sst(0, 0.35, t)) * (1 + 0.1 * Math.sin(t * 9))); }
sweep(sa, pts, rads, null, LOW ? 8 : 10, { col: colBark, noise: 0.16, freq: 0.3, B: [1, 0, 0] });
cCaps(x, g, z, x, g + th, z, tr * 1.15, tr * 0.9);
for (k = 0; k < (LOW ? 4 : 6); k++) {
var a = k / (LOW ? 4 : 6) * TAU + yaw, c = Math.cos(a), sn = Math.sin(a), ex = x + c * tr * 3.4, ez = z + sn * tr * 3.4;
sweep(sa, [x + c * tr * 0.5, g + 4.5 * s, z + sn * tr * 0.5, x + c * tr * 1.5, g + 1.8 * s, z + sn * tr * 1.5, x + c * tr * 2.5, heightAt(x + c * tr * 2.5, z + sn * tr * 2.5) + 0.3, z + sn * tr * 2.5, ex, heightAt(ex, ez) - 0.6, ez], [1.3 * s, 1.0 * s, 0.7 * s, 0.3 * s], null, 5, { col: colBark, noise: 0.12, freq: 0.4 });
cCaps(x + c * tr * 0.8, g + 3 * s, z + sn * tr * 0.8, x + c * tr * 2.5, g + 0.4, z + sn * tr * 2.5, 0.95 * s, 0.6 * s);
}
var cy = g + th + Rr * 0.9, n = LOW ? 16 : 22, ph = rnd() * 9, rp = [], rrad = [];
function ringPt(ang, out) { var rad = Rr * (1 + 0.05 * Math.sin(ang * 3 + ph)), w = Math.sin(ang * 2 + ph) * 0.7 * s; out.push(x + ax * Math.cos(ang) * rad + bx * w, cy + Math.sin(ang) * rad * 1.03, z + az * Math.cos(ang) * rad + bz * w); }
for (k = 0; k < n; k++) { var ang = -PI / 2 + k / n * TAU; ringPt(ang, rp); rrad.push(s * (1.15 + 0.85 * (0.5 - 0.5 * Math.sin(ang)))); }
sweep(sa, rp, rrad, null, LOW ? 6 : 8, { closed: true, col: colBark, noise: 0.14, freq: 0.35, B: [bx, 0, bz] });
for (k = 0; k < n; k++) { var k2 = (k + 1) % n; cCaps(rp[k * 3], rp[k * 3 + 1], rp[k * 3 + 2], rp[k2 * 3], rp[k2 * 3 + 1], rp[k2 * 3 + 2], rrad[k] * 0.9, rrad[k2] * 0.9); castPt(rp[k * 3], rp[k * 3 + 1], rp[k * 3 + 2], 1.8, 0.45); }
var m = LOW ? 9 : 14, li = themeName === 'dawn' ? 2 : 0;
for (k = 0; k < m; k++) {
var an = (-0.35 + 1.7 * (k + rnd() * 0.6) / m) * PI, rpz = []; ringPt(an, rpz);
var out = rr(4, 7) * s, side = (k % 3 === 0 && Math.sin(an) > 0.3) ? (rnd() < 0.5 ? -1 : 1) * rr(4, 7) * s : rr(-3, 3) * s, R = rr(4.6, 7) * s;
var bxp = x + ax * Math.cos(an) * (Rr + out) + bx * side, byp = cy + Math.sin(an) * (Rr + out) * 1.03 + rr(-1, 1.5), bzp = z + az * Math.cos(an) * (Rr + out) + bz * side;
sweep(sa, [rpz[0], rpz[1], rpz[2], (rpz[0] + bxp) / 2, (rpz[1] + byp) / 2 + 0.8, (rpz[2] + bzp) / 2, bxp, byp, bzp], [0.75 * s, 0.5 * s, 0.2 * s], null, 5, { col: colBark });
LC = P.leaf[(k % 4 === 1) ? (li === 2 ? 3 : 1) : li]; LB = rr(0.85, 1.1);
blob(la, bxp, byp, bzp, R, R * 0.72, R, rnd() * TAU, (!LOW && k % 2 === 0) ? 2 : 1, colLeaf, { noise: 0.3, freq: 0.3, sway: 1, glow: themeName === 'moon' ? 0.12 : 0 });
castPt(bxp, byp, bzp, R * 1.1, 0.45);
if (k % 3 === 1) {
var lyp = byp - R * 0.72 - rr(1.5, 4); LC = P.pine; LB = 0.9;
sweep(la, [bxp, byp - R * 0.5, bzp, bxp, lyp, bzp], [0.07, 0.05], null, 3, { col: colLeaf, B: [1, 0, 0], st: 0.3 });
FC = P.glowC[k % 2]; blob(la, bxp, lyp - 0.6, bzp, 0.6 * s, 0.8 * s, 0.6 * s, 0, 1, colFlat, { glow: 1, sway: 0.3 });
}
}
for (k = 0; k < 5; k++) castPt(x, g + th * k / 4, z, tr * 1.3, 0.5);
ko(x, z, 11 * s); anchor(x, cy, z);
}
function floatIsland(x, y, z, R) {
var sa = accAt(solidAcc, x, z), yaw = rnd() * TAU, k;
blob(sa, x, y, z, R, R * 0.95, R * rr(0.8, 1), yaw, LOW ? 1 : 2, colIsle, { island: true, noise: 0.24, freq: 0.16, st: 1 });
cBox(x, y - 0.1 * R, z, axes(yaw, 0, 0), R * 0.74, R * 0.3, R * 0.66);
cCaps(x, y - 0.3 * R, z, x, y - 1.2 * R, z, R * 0.52, R * 0.14);
var nr = LOW ? 3 : 5;
for (k = 0; k < nr; k++) {
var a = rnd() * TAU, d = rr(0.15, 0.6) * R, len = rr(0.9, 2.0) * R, rx = x + Math.cos(a) * d, rz = z + Math.sin(a) * d, y0 = y - (1.25 - d / R * 0.8) * R, sw = rr(-1, 1) * 1.5, sw2 = rr(-1, 1) * 1.5;
var pts = [rx, y0 + 1.5, rz, rx + sw * 0.4, y0 - len * 0.35, rz + sw2 * 0.4, rx + sw, y0 - len * 0.7, rz + sw2, rx + sw * 0.7, y0 - len, rz + sw2 * 1.3], th = k < 2 ? 0.55 : 0.32;
sweep(sa, pts, [th, th * 0.75, th * 0.5, th * 0.15], null, 5, { col: colBark, B: [1, 0, 0] });
if (k < 2) { cCaps(pts[0], pts[1], pts[2], pts[6], pts[7], pts[8], th, th * 0.6); cCaps(pts[6], pts[7], pts[8], pts[9], pts[10], pts[11], th * 0.6, th * 0.3); }
if (k % 2 === 0) { FC = P.glowC[1]; blob(accAt(leafAcc, x, z), pts[9], pts[10] - 0.4, pts[11], 0.4, 0.55, 0.4, 0, 0, colFlat, { glow: 1, sway: 0.4 }); }
}
// top dressing
var ty = y + R * 0.27, la = accAt(leafAcc, x, z);
LC = P.leaf[themeName === 'dawn' ? 2 : 0]; LB = 1;
var tx = x + rr(-0.3, 0.3) * R, tz = z + rr(-0.3, 0.3) * R;
sweep(sa, [tx, ty - 0.5, tz, tx + 0.4, ty + R * 0.35, tz, tx + 0.9, ty + R * 0.62, tz + 0.3], [0.5, 0.36, 0.22], null, 5, { col: colBark, B: [1, 0, 0] });
blob(la, tx + 0.9, ty + R * 0.78, tz + 0.3, R * 0.5, R * 0.4, R * 0.5, rnd() * 6, 1, colLeaf, { noise: 0.3, freq: 0.45, sway: 1 });
cCaps(tx, ty, tz, tx + 0.9, ty + R * 0.7, tz + 0.3, 0.5, R * 0.3);
blob(sa, x - R * 0.4, ty + 0.3, z + R * 0.3, R * 0.2, R * 0.16, R * 0.18, rnd() * 6, 1, colRock, { noise: 0.25, freq: 0.6, st: 1 });
castPt(x, y, z, R * 0.95, 0.5);
anchor(x, y - 1.3 * R - 6, z); anchor(x, y + R * 0.3 + 7, z);
}
function vine(x, y, z, len, ci) {
var la = accAt(leafAcc, x, z), sx = rr(-0.6, 0.6), sz = rr(-0.6, 0.6); LC = P.pine; LB = 1;
sweep(la, [x, y, z, x + sx * 0.5, y - len * 0.5, z + sz * 0.5, x + sx, y - len, z + sz], [0.09, 0.07, 0.05], null, 3, { col: colLeaf, B: [1, 0, 0], st: 0.25 });
FC = P.glowC[ci]; blob(la, x + sx, y - len - 0.45, z + sz, 0.42, 0.55, 0.42, 0, 1, colFlat, { glow: 1, sway: 0.3 });
}
function menhir(x, z, h, r, lean) {
var g = heightAt(x, z) - 1, a = rnd() * TAU, lx = Math.cos(a) * lean * h, lz = Math.sin(a) * lean * h;
var pts = [x, g, z, x + lx * 0.3, g + h * 0.4, z + lz * 0.3, x + lx * 0.7, g + h * 0.8, z + lz * 0.7, x + lx, g + h + 1, z + lz], rx = [r * 1.15, r, r * 0.85, r * 0.5], ry = [r * 0.75, r * 0.65, r * 0.55, r * 0.35], ya = rnd() * TAU;
sweep(accAt(solidAcc, x, z), pts, rx, ry, LOW ? 6 : 7, { col: colStone, noise: 0.18, freq: 0.4, capB: true, B: [Math.sin(ya), 0, Math.cos(ya)], st: 0.5 });
cCaps(x, g, z, x + lx, g + h + 0.6, z + lz, r * 0.72, r * 0.45);
for (var k = 1; k < 4; k++) castPt(x + lx * k / 3, g + (h + 1) * k / 3, z + lz * k / 3, r * 1.2, 0.5);
return [x + lx, g + h + 1, z + lz];
}
// ------------------------------------------------------------------ build the world
var START = { x: 0, y: 0, z: 124, yaw: PI };
var shr1 = { x: HILL.x, y: 0, z: HILL.z, yaw: Math.atan2(HILL.x, HILL.z - 20) };
var shr2 = { x: ISLE.x, y: 0, z: ISLE.z, yaw: Math.atan2(ISLE.x - 10, ISLE.z - 60) };
var shr3 = { x: SHELF.x - 2, y: 0, z: SHELF.z, yaw: Math.atan2(1, -0.2) };
var gate = { x: GATE.x, y: 0, z: GATE.z, yaw: Math.atan2(GDX, GDZ) };
ko(START.x, START.z, 14); ko(shr1.x, shr1.z, 11); ko(shr2.x, shr2.z, 6); ko(shr3.x, shr3.z, 11); ko(GATE.x, GATE.z, 11);
ko(POOL.x, POOL.z, 10); ko(FALL.x - 3, FALL.z, 8);
(function build() {
var i, k, a, x, z, t;
// stone circle on the hill
var tops = [];
for (i = 0; i < 10; i++) { a = i / 10 * TAU + 0.2; if (i === 7) { tops.push(null); continue; } tops.push(menhir(HILL.x + Math.cos(a) * 14.2, HILL.z + Math.sin(a) * 14.2, rr(6.5, 8.5), 1.5, i === 3 ? 0.18 : 0.04)); }
for (i = 0; i < 10; i += 2) {
var p0 = tops[i], p1 = tops[i + 1]; if (!p0 || !p1 || i === 2) continue;
var my = Math.max(p0[1], p1[1]) + 0.2, lyaw = Math.atan2(-(p1[2] - p0[2]), p1[0] - p0[0]);
solidBox((p0[0] + p1[0]) / 2, my + 0.3, (p0[2] + p1[2]) / 2, axes(lyaw, 0, (p1[1] - p0[1]) * 0.02), hyp(p1[0] - p0[0], p1[2] - p0[2]) / 2 + 1.4, 0.75, 1.15, colStone, { st: 0.5 });
}
ko(HILL.x, HILL.z, 18);
// island stones + tree
for (i = 0; i < 7; i++) { a = i / 7 * TAU + 0.5; menhir(ISLE.x + Math.cos(a) * 8.6, ISLE.z + Math.sin(a) * 8.6, rr(2.2, 3.4), 0.8, 0.06); }
broadleaf(ISLE.x + 9.2, ISLE.z - 6.8, 1.25, themeName === 'dawn' ? 2 : 0);
// ledge shrine ruins
var sy = heightAt(SHELF.x, SHELF.z);
column(SHELF.x + 6.5, SHELF.z - 9.5, sy - 0.5, 9, 0.9, false); column(SHELF.x + 9.5, SHELF.z + 5.5, sy - 0.5, 5, 0.9, true); column(SHELF.x - 3.5, SHELF.z + 10.2, sy - 0.5, 3.2, 0.9, true);
FC = P.glowC[0]; blob(accAt(solidAcc, SHELF.x, SHELF.z), SHELF.x + 9.5, sy + 5.3, SHELF.z + 5.5, 0.6, 0.75, 0.6, 0, 1, colFlat, { glow: 1 });
// temple + aqueduct
temple();
aqueduct(92, 12, 26, 26, 27);
ko(59, 19, 8);
// rock arches
polyAt(RIV, 0.36); rockArch(_px, _pz, Math.atan2(_pdx, _pdz), 27, 18, 5.2, 6.5);
rockArch(0, 97, PI, 25, 17, 4.6, 5.5);
rockArch(-38, 86, 0.5, 20, 15, 4, 5);
rockArch(120, 44, 1.2, 19, 20, 4.4, 5);
polyAt(CAN, 0.03); rockArch(_px, _pz, Math.atan2(_pdx, _pdz), 25, 20, 5, 6);
rockArch(-106, -100, 0.4, 17, 13, 3.6, 4.5);
rockArch(-92, 46, 2.2, 17, 12.5, 3.6, 4.5);
if (!LOW) rockArch(34, 112, 2.4, 15, 21, 3.4, 4);
// tunnel roof through the ridge
rockArch(TUN.x, TUN.z, Math.atan2(-RDZ, RDX), 23.5, 18.5, 10, 27, { uniform: true, baseY: heightAt(TUN.x, TUN.z), noAnchor: true });
anchor(TUN.x - RDZ * 8, heightAt(TUN.x, TUN.z) + 5, TUN.z + RDX * 8); anchor(TUN.x + RDZ * 8, heightAt(TUN.x, TUN.z) + 5, TUN.z - RDX * 8);
ko(TUN.x, TUN.z, 20);
// spires
function cluster(cx, cz, n, rad, hmax) {
var pl = [], tries = 0;
while (pl.length < n && tries++ < 200) {
a = rnd() * TAU; var d = Math.sqrt(rnd()) * rad; x = cx + Math.cos(a) * d; z = cz + Math.sin(a) * d;
var ok = heightAt(x, z) > 1.2 && koFree(x, z, 5); for (k = 0; ok && k < pl.length; k++) if (hyp(pl[k][0] - x, pl[k][1] - z) < 9.5) ok = false;
if (!ok) continue; pl.push([x, z]); var hh = hmax * (1 - 0.55 * d / rad) * rr(0.75, 1.1);
spire(x, z, hh, 2.2 + hh * 0.085); if (rnd() < 0.7) boulder(x + rr(-5, 5), z + rr(-5, 5), rr(1.2, 2.4));
}
anchor(cx, heightAt(cx, cz) + 14, cz);
}
cluster(124, 18, LOW ? 6 : 9, 24, 46);
cluster(-36, -36, LOW ? 5 : 7, 18, 38);
cluster(-112, -108, LOW ? 4 : 5, 15, 34);
cluster(-132, 22, LOW ? 3 : 5, 14, 30);
cluster(44, 124, 3, 12, 24);
spire(-46, 2, 19, 3.2); spire(-84, 56, 15, 2.8); spire(-50, 50, 22, 3.4); spire(-94, 6, 13, 2.6);
// gate pylons + horns
var gx = Math.cos(gate.yaw), gz = -Math.sin(gate.yaw), gy = heightAt(GATE.x, GATE.z);
for (i = -1; i <= 1; i += 2) {
var px = GATE.x + gx * 13.6 * i, pz = GATE.z + gz * 13.6 * i, pts = [], rads = [], np = 9;
for (k = 0; k < np; k++) { t = k / (np - 1); var inw = Math.pow(t, 2.4) * 9; pts.push(px - gx * i * inw, gy - 2 + t * 36, pz - gz * i * inw); rads.push((2.5 - 1.7 * t) * 1.2); }
sweep(accAt(solidAcc, px, pz), pts, rads, null, 4, { col: colStone, hard: true, rot: PI / 4, capB: true, B: [gx, 0, gz], st: 0.3 });
for (k = 0; k < np - 1; k += 2) cCaps(pts[k * 3], pts[k * 3 + 1], pts[k * 3 + 2], pts[k * 3 + 6], pts[k * 3 + 7], pts[k * 3 + 8], rads[k] * 0.72, rads[k + 2] * 0.72);
FC = P.glowC[0];
for (k = 2; k < 7; k += 2) boxM(accAt(solidAcc, px, pz), pts[k * 3], pts[k * 3 + 1], pts[k * 3 + 2], axes(gate.yaw, 0, 0), rads[k] * 0.76, 0.22, rads[k] * 0.76, colFlat, { glow: 1 });
}
// canyon dressing
function canPt(tc) { polyAt(CAN, tc); return { x: _px, z: _pz, dx: _pdx, dz: _pdz, fl: canFloor(tc), w: canW(tc) }; }
var ohs = [[0.2, 1, 17], [0.34, -1, 22], [0.58, 1, 15], [0.8, -1, 24], [0.9, 1, 30]];
for (i = 0; i < ohs.length; i++) {
var c = canPt(ohs[i][0]), sd = ohs[i][1], ox = c.x - c.dz * sd * (c.w + 3.2), oz = c.z + c.dx * sd * (c.w + 3.2), oy = c.fl + ohs[i][2], oyaw = Math.atan2(c.dx, c.dz);
blob(accAt(solidAcc, ox, oz), ox, oy, oz, 7.2, 2.4, 6, oyaw, LOW ? 1 : 2, colRock, { noise: 0.25, freq: 0.2, st: 1 });
cBox(ox, oy, oz, axes(oyaw, 0, 0), 5.9, 1.9, 4.8);
for (k = 0; k < 3; k++) vine(ox + rr(-3.5, 3.5), oy - 1.7, oz + rr(-3.5, 3.5), rr(2, 5), k % 2);
}
(function () {
var c = canPt(0.46), hl = c.w + 8, pts = [], rx = [], ry = [], n = 11, by = c.fl + 21;
for (k = 0; k < n; k++) { var u = (k / (n - 1) * 2 - 1); pts.push(c.x - c.dz * u * hl + c.dx * n2(k * 0.6, 3) * 1.2, by + 2.4 * Math.cos(u * PI / 2) + n2(k * 0.5, 8) * 0.6, c.z + c.dx * u * hl + c.dz * n2(k * 0.6, 3) * 1.2); rx.push(1.5 + 2 * u * u); ry.push(3 + 1.2 * u * u); }
sweep(accAt(solidAcc, c.x, c.z), pts, rx, ry, LOW ? 7 : 9, { B: [c.dx, 0, c.dz], col: colRock, noise: 0.2, freq: 0.2, st: 1 });
for (k = 0; k < n - 1; k++) {
var tx = pts[k * 3 + 3] - pts[k * 3], ty = pts[k * 3 + 4] - pts[k * 3 + 1], tz = pts[k * 3 + 5] - pts[k * 3 + 2], l = Math.sqrt(tx * tx + ty * ty + tz * tz); tx /= l; ty /= l; tz /= l;
cBox((pts[k * 3] + pts[k * 3 + 3]) / 2, (pts[k * 3 + 1] + pts[k * 3 + 4]) / 2, (pts[k * 3 + 2] + pts[k * 3 + 5]) / 2, [tx, ty, tz, -c.dz * ty, c.dz * tx - c.dx * tz, c.dx * ty, c.dx, 0, c.dz], l / 2 + 0.3, (rx[k] + rx[k + 1]) * 0.42, (ry[k] + ry[k + 1]) * 0.42);
}
for (k = 2; k < n - 2; k += 2) vine(pts[k * 3], pts[k * 3 + 1] - rx[k] * 0.9, pts[k * 3 + 2], rr(2.5, 5), k % 4 ? 0 : 1);
c = canPt(0.7); var cyy = c.fl + 28, cyaw = Math.atan2(c.dx, c.dz);
blob(accAt(solidAcc, c.x, c.z), c.x, cyy, c.z, c.w + 7, 5, 6.5, cyaw, LOW ? 1 : 2, colRock, { noise: 0.25, freq: 0.15, st: 1 });
cBox(c.x, cyy, c.z, axes(cyaw, 0, 0), (c.w + 7) * 0.78, 3.8, 4.9);
for (k = 0; k < 4; k++) vine(c.x + rr(-5, 5), cyy - 4, c.z + rr(-3, 3), rr(3, 6), k % 2);
for (k = 0; k < (LOW ? 10 : 22); k++) { var cf = canPt(rr(0.04, 0.97)), sf = rnd() < 0.5 ? -1 : 1, of = cf.w - rr(1, 4); flora(cf.x - cf.dz * sf * of, cf.z + cf.dx * sf * of, rr(1, 1.5), k % 2); }
for (k = 0; k < (LOW ? 8 : 14); k++) { c = canPt(rr(0.05, 0.92)); var s2 = rnd() < 0.5 ? -1 : 1, off = c.w - rr(0.5, 2); boulder(c.x - c.dz * s2 * off, c.z + c.dx * s2 * off, rr(1, 2)); }
})();
// giant trees
var tang = [0.3, 1.5, 2.75, 3.65, 5.2];
for (i = 0; i < (LOW ? 4 : 5); i++) { x = POND.x + Math.cos(tang[i]) * 27; z = POND.z + Math.sin(tang[i]) * 27; giantTree(x, z, Math.atan2(POND.x - x, POND.z - z) + rr(-0.3, 0.3), rr(0.92, 1.1)); }
giantTree(42, 80, 0.9, 1.0);
anchor(POND.x, 8, POND.z);
// floating islands
var isl = [[-58, 40, 36, 8], [-42, 47, 24, 5.5], [-18, 48, -10, 7], [30, 52, 66, 7.5], [45, 46, 76, 5], [100, 60, -74, 8], [-112, 47, 78, 7], [-104, 44, -92, 6.5], [-6, 41, 84, 6], [-4, 53, 6, 5], [118, 52, 70, 6]];
for (i = 0; i < (LOW ? 7 : isl.length); i++) floatIsland(isl[i][0], isl[i][1], isl[i][2], isl[i][3]);
anchor(-50, 42, 30); anchor(37, 49, 71);
// boulders: river banks, cliff feet
for (i = 0; i < RIV.length / 2 - 1; i += 2) { x = RIV[i * 2]; z = RIV[i * 2 + 1]; var s3 = (i % 4) ? 1 : -1, dxr = RIV[i * 2 + 2] - x, dzr = RIV[i * 2 + 3] - z, lr = hyp(dxr, dzr) || 1; var bxp = x - dzr / lr * s3 * rr(6, 9), bzp = z + dxr / lr * s3 * rr(6, 9); if (koFree(bxp, bzp, 1)) boulder(bxp, bzp, rr(1, 2.3)); if (i % 3 === 0) anchor(x, 4.5, z); }
for (i = 0, k = 0; i < 5000 && k < (LOW ? 40 : 75); i++) {
x = rr(-160, 160); z = rr(-160, 160); var hh = heightAt(x, z); if (hh < 0.5 || hh > 50 || slopeNy(x, z) < 0.88 || !koFree(x, z, 3)) continue;
a = rnd() * TAU; if (slopeNy(x + Math.cos(a) * 6, z + Math.sin(a) * 6) > 0.6) continue;
boulder(x, z, rr(1.2, 3.2)); k++;
}
for (i = 0; i < 9; i++) { a = rnd() * TAU; x = POOL.x + Math.cos(a) * rr(8, 12); z = POOL.z + Math.sin(a) * rr(8, 12); if (x < 71 && koFree(x, z, 0) ) boulder(x, z, rr(1.2, 2.4)); }
// forests
var cell = 6.5, nt = 0, keep = LOW ? 0.5 : 0.82, cap = LOW ? 330 : 600;
for (var gxi = -162; gxi < 162; gxi += cell) for (var gzi = -162; gzi < 162; gzi += cell) {
x = gxi + rnd() * cell; z = gzi + rnd() * cell; var q1 = rnd(), q2 = rnd(), q3 = rnd(), q4 = rnd();
var h0 = heightAt(x, z); if (h0 < 1.5 || h0 > 60 || nt >= cap) continue;
var f = fbm(x * 0.017 + 20, z * 0.017 + 9, 3), grove = hyp(x - POND.x, z - POND.z) < 46, lakeS = Math.abs(hyp(x - LAKE.x, (z - LAKE.z) * 1.12) - LAKE.r - 9) < 7;
if (!(f > 0.02 || (grove && q1 < 0.45) || (lakeS && q1 < 0.3) || q1 < 0.035)) continue;
if (q2 > keep || slopeNy(x, z) < 0.8 || !koFree(x, z, 2.5) || polyDist(CAN, x, z, 16) < 15 || polyDist(RIV, x, z, 8) < 6) continue;
var sc = 0.8 + q3 * 0.5;
if (grove || lakeS || (themeName === 'ember' && q4 < 0.7) || (themeName !== 'ember' && q4 < 0.22 && h0 < 16)) broadleaf(x, z, sc, themeName === 'ember' ? ((q4 * 97) | 0) % 4 : (grove || lakeS ? (q4 < 0.5 ? 2 : (q4 < 0.7 ? 3 : 1)) : ((q4 * 50) | 0) % 2));
else conifer(x, z, sc * (h0 > 30 ? 0.8 : 1));
nt++;
}
// lantern flora
var nf = 0, fmax = LOW ? 70 : 150;
for (i = 0; i < RIV.length / 2 && nf < fmax; i++) { x = RIV[i * 2] + rr(-8, 8); z = RIV[i * 2 + 1] + rr(-8, 8); if (heightAt(x, z) > 0.4 && heightAt(x, z) < 6) { flora(x, z, rr(0.8, 1.3), i % 2); nf++; } }
for (i = 0; i < 400 && nf < fmax; i++) {
var pick = rnd(); if (pick < 0.35) { a = rnd() * TAU; var dd = rr(8, 34); x = POND.x + Math.cos(a) * dd; z = POND.z + Math.sin(a) * dd; }
else if (pick < 0.55) { x = rr(-128, -86); z = rr(-122, -74); }
else if (pick < 0.75) { a = rnd() * TAU; x = LAKE.x + Math.cos(a) * (LAKE.r + rr(-2, 6)); z = LAKE.z + Math.sin(a) * (LAKE.r + rr(-2, 6)) / 1.12; }
else { x = rr(-150, 150); z = rr(-150, 150); }
var fh = heightAt(x, z); if (fh < 0.5 || fh > 40 || slopeNy(x, z) < 0.85 || !koFree(x, z, 0.5)) continue;
flora(x, z, rr(0.8, 1.4), (i % 3 === 0) ? 1 : 0); nf++;
}
})();
// ------------------------------------------------------------------ collider finalize + spatial hash
var NP = cT.length, CTY = new Uint8Array(cT), CDD = new Float64Array(cD), CY0 = new Float32Array(NP), CY1 = new Float32Array(NP), CSTAMP = new Int32Array(NP), qid = 0;
var HC = 44, HS = 0.125, HOFF = 176, CS, CI, TMAX = new Float32Array(HC * HC);
(function () {
var i, o, x0, x1, z0, z1, cnt = new Int32Array(HC * HC + 1), bb = new Int32Array(NP * 4), ix, iz;
function ci(v) { v = Math.floor((v + HOFF) * HS); return v < 0 ? 0 : v > HC - 1 ? HC - 1 : v; }
for (i = 0; i < NP; i++) {
o = i * 16; var t = CTY[i], r;
if (t === 0) { r = CDD[o + 3]; x0 = CDD[o] - r; x1 = CDD[o] + r; z0 = CDD[o + 2] - r; z1 = CDD[o + 2] + r; CY0[i] = CDD[o + 1] - r; CY1[i] = CDD[o + 1] + r; }
else if (t === 1) { r = Math.max(CDD[o + 6], CDD[o + 7]); var bx = CDD[o] + CDD[o + 3], by = CDD[o + 1] + CDD[o + 4], bz = CDD[o + 2] + CDD[o + 5]; x0 = Math.min(CDD[o], bx) - r; x1 = Math.max(CDD[o], bx) + r; z0 = Math.min(CDD[o + 2], bz) - r; z1 = Math.max(CDD[o + 2], bz) + r; CY0[i] = Math.min(CDD[o + 1], by) - r; CY1[i] = Math.max(CDD[o + 1], by) + r; }
else { var ex = Math.abs(CDD[o + 3]) * CDD[o + 12] + Math.abs(CDD[o + 6]) * CDD[o + 13] + Math.abs(CDD[o + 9]) * CDD[o + 14], ey = Math.abs(CDD[o + 4]) * CDD[o + 12] + Math.abs(CDD[o + 7]) * CDD[o + 13] + Math.abs(CDD[o + 10]) * CDD[o + 14], ez = Math.abs(CDD[o + 5]) * CDD[o + 12] + Math.abs(CDD[o + 8]) * CDD[o + 13] + Math.abs(CDD[o + 11]) * CDD[o + 14]; x0 = CDD[o] - ex; x1 = CDD[o] + ex; z0 = CDD[o + 2] - ez; z1 = CDD[o + 2] + ez; CY0[i] = CDD[o + 1] - ey; CY1[i] = CDD[o + 1] + ey; }
bb[i * 4] = ci(x0); bb[i * 4 + 1] = ci(x1); bb[i * 4 + 2] = ci(z0); bb[i * 4 + 3] = ci(z1);
for (iz = bb[i * 4 + 2]; iz <= bb[i * 4 + 3]; iz++) for (ix = bb[i * 4]; ix <= bb[i * 4 + 1]; ix++) cnt[iz * HC + ix + 1]++;
}
for (i = 0; i < HC * HC; i++) cnt[i + 1] += cnt[i];
CS = cnt; CI = new Int32Array(cnt[HC * HC]); var fill = new Int32Array(HC * HC);
for (i = 0; i < NP; i++) for (iz = bb[i * 4 + 2]; iz <= bb[i * 4 + 3]; iz++) for (ix = bb[i * 4]; ix <= bb[i * 4 + 1]; ix++) { var c = iz * HC + ix; CI[CS[c] + fill[c]++] = i; }
for (iz = 0; iz < HC; iz++) for (ix = 0; ix < HC; ix++) {
var m = -1e9, gx0 = Math.max(0, Math.floor((ix * 8 - HOFF - 12 + GO) / GS)), gx1 = Math.min(GN - 1, Math.ceil((ix * 8 - HOFF + 20 + GO) / GS)), gz0 = Math.max(0, Math.floor((iz * 8 - HOFF - 12 + GO) / GS)), gz1 = Math.min(GN - 1, Math.ceil((iz * 8 - HOFF + 20 + GO) / GS));
for (var j = gz0; j <= gz1; j++) for (i = gx0; i <= gx1; i++) if (H[j * GN + i] > m) m = H[j * GN + i];
TMAX[iz * HC + ix] = m;
}
})();
var _th = 0, _tgx = 0, _tgz = 0;
function tS(x, z) {
var fx = (x + GO) * 0.5, fz = (z + GO) * 0.5; if (fx < 0) fx = 0; else if (fx > GMAX) fx = GMAX; if (fz < 0) fz = 0; else if (fz > GMAX) fz = GMAX;
var ix = fx | 0, iz = fz | 0; fx -= ix; fz -= iz; var i = iz * GN + ix, a = H[i], b = H[i + 1], c = H[i + GN], d = H[i + GN + 1];
_th = (a + (b - a) * fx) * (1 - fz) + (c + (d - c) * fx) * fz; _tgx = ((b - a) * (1 - fz) + (d - c) * fz) * 0.5; _tgz = ((c - a) * (1 - fx) + (d - b) * fx) * 0.5;
}
var OFX = [1, -1, 0, 0], OFZ = [0, 0, 1, -1];
function collide(p, r, out) {
var px = p.x, py = p.y, pz = p.z, best = 0, nx = 0, ny = 1, nz = 0, d, inv, k;
d = px + r - HALF; if (d > best) { best = d; nx = -1; ny = 0; nz = 0; }
d = r - px - HALF; if (d > best) { best = d; nx = 1; ny = 0; nz = 0; }
d = pz + r - HALF; if (d > best) { best = d; nx = 0; ny = 0; nz = -1; }
d = r - pz - HALF; if (d > best) { best = d; nx = 0; ny = 0; nz = 1; }
var cx = ((px + HOFF) * HS) | 0, cz = ((pz + HOFF) * HS) | 0; cx = cx < 0 ? 0 : cx > HC - 1 ? HC - 1 : cx; cz = cz < 0 ? 0 : cz > HC - 1 ? HC - 1 : cz;
if (py - r < TMAX[cz * HC + cx] || r > 11) {
tS(px, pz); inv = 1 / Math.sqrt(1 + _tgx * _tgx + _tgz * _tgz); d = r - (py - _th) * inv;
if (d > best) { best = d; nx = -_tgx * inv; ny = inv; nz = -_tgz * inv; }
var o = r * 0.75, lim = py - r * 0.25;
for (k = 0; k < 4; k++) {
var ox = OFX[k] * o, oz = OFZ[k] * o; tS(px + ox, pz + oz);
if (_th > lim) { inv = 1 / Math.sqrt(1 + _tgx * _tgx + _tgz * _tgz); d = r - ((py - _th) + _tgx * ox + _tgz * oz) * inv; if (d > best) { best = d; nx = -_tgx * inv; ny = inv; nz = -_tgz * inv; } }
}
}
var x0 = ((px - r + HOFF) * HS) | 0, x1 = ((px + r + HOFF) * HS) | 0, z0 = ((pz - r + HOFF) * HS) | 0, z1 = ((pz + r + HOFF) * HS) | 0;
if (x0 < 0) x0 = 0; if (z0 < 0) z0 = 0; if (x1 > HC - 1) x1 = HC - 1; if (z1 > HC - 1) z1 = HC - 1;
var multi = (x0 !== x1 || z0 !== z1); if (multi) qid++;
var D = CDD, yLo = py - r, yHi = py + r;
for (var iz = z0; iz <= z1; iz++) for (var ix = x0; ix <= x1; ix++) {
var c = iz * HC + ix, e = CS[c + 1];
for (k = CS[c]; k < e; k++) {
var id = CI[k]; if (yHi < CY0[id] || yLo > CY1[id]) continue;
if (multi) { if (CSTAMP[id] === qid) continue; CSTAMP[id] = qid; }
var q = id * 16, ty = CTY[id], dx, dy, dz, d2, R, dist;
if (ty === 0) { dx = px - D[q]; dy = py - D[q + 1]; dz = pz - D[q + 2]; R = r + D[q + 3]; }
else if (ty === 1) {
var bx = D[q + 3], by = D[q + 4], bz = D[q + 5], t = ((px - D[q]) * bx + (py - D[q + 1]) * by + (pz - D[q + 2]) * bz) * D[q + 8]; t = t < 0 ? 0 : t > 1 ? 1 : t;
dx = px - D[q] - bx * t; dy = py - D[q + 1] - by * t; dz = pz - D[q + 2] - bz * t; R = r + D[q + 6] + (D[q + 7] - D[q + 6]) * t;
} else {
var ex = px - D[q], ey = py - D[q + 1], ez = pz - D[q + 2];
var lu = ex * D[q + 3] + ey * D[q + 4] + ez * D[q + 5], lv = ex * D[q + 6] + ey * D[q + 7] + ez * D[q + 8], lw = ex * D[q + 9] + ey * D[q + 10] + ez * D[q + 11];
var hu = D[q + 12], hv = D[q + 13], hw = D[q + 14];
var qu = lu < -hu ? -hu : lu > hu ? hu : lu, qv = lv < -hv ? -hv : lv > hv ? hv : lv, qw = lw < -hw ? -hw : lw > hw ? hw : lw;
var du = lu - qu, dv = lv - qv, dw = lw - qw; d2 = du * du + dv * dv + dw * dw;
if (d2 >= r * r) continue;
if (d2 > 1e-10) { dist = Math.sqrt(d2); d = r - dist; du /= dist; dv /= dist; dw /= dist; }
else {
var pu = hu - Math.abs(lu), pv = hv - Math.abs(lv), pw = hw - Math.abs(lw); du = 0; dv = 0; dw = 0;
if (pu <= pv && pu <= pw) { d = r + pu; du = lu < 0 ? -1 : 1; } else if (pv <= pw) { d = r + pv; dv = lv < 0 ? -1 : 1; } else { d = r + pw; dw = lw < 0 ? -1 : 1; }
}
if (d > best) { best = d; nx = D[q + 3] * du + D[q + 6] * dv + D[q + 9] * dw; ny = D[q + 4] * du + D[q + 7] * dv + D[q + 10] * dw; nz = D[q + 5] * du + D[q + 8] * dv + D[q + 11] * dw; }
continue;
}
d2 = dx * dx + dy * dy + dz * dz;
if (d2 < R * R) { dist = Math.sqrt(d2); d = R - dist; if (d > best) { best = d; if (dist > 1e-6) { nx = dx / dist; ny = dy / dist; nz = dz / dist; } else { nx = 0; ny = 1; nz = 0; } } }
}
}
if (best <= 0) return false;
if (out) { out.x = nx; out.y = ny; out.z = nz; out.d = best; }
return true;
}
var _q = { x: 0, y: 0, z: 0 }, _fo = { x: 0, y: 0, z: 0, d: 0 };
function clearAt(x, y, z, r) { _q.x = x; _q.y = y; _q.z = z; return !collide(_q, r, _fo); }
// ------------------------------------------------------------------ landmarks
function settle(pt, minAbove, r) {
pt.y = Math.max(heightAt(pt.x, pt.z), WATER) + minAbove;
for (var i = 0; i < 60; i++) { if (clearAt(pt.x, pt.y, pt.z, r)) return; pt.y += 0.5; }
}
settle(START, 12, 10.4); settle(shr1, 11.5, 10.4); settle(shr2, 11, 10.4); settle(shr3, 11.5, 10.4); settle(gate, 14, 10.4);
var canyonPts = [];
(function () {
var n = 12, i, a, b, dys = [0, 1, -1, 2, -2, 3, 4, -3, 5, 6], dls = [0, 1, -1, 2, -2, 3, -3, 4, -4];
for (i = 0; i < n; i++) {
var t = 0.015 + 0.86 * i / (n - 1); polyAt(CAN, t);
var y = canFloor(t) + 10 + 3.5 * Math.sin(i * 1.9 + 0.5), lat = 2.2 * Math.sin(i * 2.4), found = false, px = _px, pz = _pz, dx = _pdx, dz = _pdz;
for (a = 0; a < dys.length && !found; a++) for (b = 0; b < dls.length && !found; b++) {
var x = px - dz * (lat + dls[b]), z = pz + dx * (lat + dls[b]);
if (clearAt(x, y + dys[a], z, 4.5)) { canyonPts.push({ x: x, y: y + dys[a], z: z }); found = true; }
}
if (!found) canyonPts.push({ x: px, y: y, z: pz });
anchor(canyonPts[i].x, canyonPts[i].y, canyonPts[i].z);
}
})();
function freeSpot(rand, minA, maxA) {
minA = minA == null ? 4 : minA; maxA = maxA == null ? 20 : maxA; if (maxA < minA) maxA = minA;
for (var tr = 0; tr < 120; tr++) {
var x, z, y, g;
if (tr < 60 && rand() < 0.45) {
var a = ((rand() * (AN.length / 3)) | 0) * 3; x = AN[a] + (rand() - 0.5) * 6; z = AN[a + 2] + (rand() - 0.5) * 6; g = Math.max(heightAt(x, z), WATER);
y = AN[a + 1] + (rand() - 0.5) * 3; if (y - g < minA || y - g > maxA) y = g + minA + rand() * (maxA - minA);
} else { x = (rand() * 2 - 1) * (HALF - 10); z = (rand() * 2 - 1) * (HALF - 10); g = Math.max(heightAt(x, z), WATER); y = g + minA + rand() * (maxA - minA); }
if (y > CEIL - 3.5 || Math.abs(x) > HALF - 6 || Math.abs(z) > HALF - 6) continue;
if (clearAt(x, y, z, 3.4)) return { x: x, y: y, z: z };
}
return { x: START.x, y: START.y, z: START.z };
}
// ------------------------------------------------------------------ textures
function noiseTex() {
var S = 256, data = new Uint8Array(S * S * 4), ch, o, x, y, rn = mkRng(seed + 99);
for (ch = 0; ch < 4; ch++) {
var acc = new Float32Array(S * S), amp = 0.5, tot = 0, per = ch === 0 ? 4 : ch === 1 ? 8 : ch === 2 ? 16 : 64;
for (o = 0; o < (ch === 3 ? 1 : 5); o++) {
var lat = new Float32Array(per * per); for (x = 0; x < per * per; x++) lat[x] = rn();
var sc = per / S;
for (y = 0; y < S; y++) for (x = 0; x < S; x++) {
var fx = x * sc, fy = y * sc, xi = fx | 0, yi = fy | 0, tx = fx - xi, ty = fy - yi; tx = tx * tx * (3 - 2 * tx); ty = ty * ty * (3 - 2 * ty);
var x1 = (xi + 1) % per, y1 = (yi + 1) % per, a = lat[yi * per + xi], b = lat[yi * per + x1], c = lat[y1 * per + xi], d = lat[y1 * per + x1];
acc[y * S + x] += amp * (a + (b - a) * tx + (c - a) * ty + (a - b - c + d) * tx * ty);
}
tot += amp; amp *= 0.5; per *= 2; if (per > S) break;
}
for (x = 0; x < S * S; x++) { var v = (acc[x] / tot - 0.5) * 1.7 + 0.5; data[x * 4 + ch] = v < 0 ? 0 : v > 1 ? 255 : (v * 255) | 0; }
}
var tex = new THREE.DataTexture(data, S, S, THREE.RGBAFormat); tex.wrapS = tex.wrapT = THREE.RepeatWrapping; tex.magFilter = THREE.LinearFilter; tex.minFilter = THREE.LinearMipmapLinearFilter; tex.generateMipmaps = true; tex.needsUpdate = true;
textures.push(tex); return tex;
}
function depthTex() {
var S = 256, data = new Uint8Array(S * S * 4), x, y;
for (y = 0; y < S; y++) for (x = 0; x < S; x++) { var h = heightAt((x + 0.5) / S * 384 - 192, (y + 0.5) / S * 384 - 192), v = -h / 6; v = v < 0 ? 0 : v > 1 ? 1 : v; var i = (y * S + x) * 4; data[i] = data[i + 1] = data[i + 2] = (v * 255) | 0; data[i + 3] = 255; }
var tex = new THREE.DataTexture(data, S, S, THREE.RGBAFormat); tex.magFilter = tex.minFilter = THREE.LinearFilter; tex.needsUpdate = true; textures.push(tex); return tex;
}
var NOISE = noiseTex(), DEPTH = depthTex();
// ------------------------------------------------------------------ shared uniforms + shaders
function v3(a) { return new THREE.Vector3(a ? a[0] : 0, a ? a[1] : 0, a ? a[2] : 0); }
var U = {
uTime: { value: 0 }, uNoise: { value: NOISE }, uSunDir: { value: sunDir.clone() }, uSunCol: { value: v3() }, uSkyAmb: { value: v3() }, uGndAmb: { value: v3() },
uFogCol: { value: v3() }, uFogSun: { value: v3() }, uFog: { value: new THREE.Vector4(0.012, 0.035, 0.0000022, 0) }, uGlow: { value: 1 },
uZen: { value: v3() }, uMid: { value: v3() }, uSunGlow: { value: v3() }, uCloudL: { value: v3() }, uCloudS: { value: v3() }, uLum: { value: 1 }, uK: { value: 0 }, uFocus: { value: v3() }, uAid: { value: 0 }
};
var FOG = [
'uniform vec3 uFogCol; uniform vec3 uFogSun; uniform vec3 uSunDir; uniform vec4 uFog;',
'vec3 applyFog(vec3 c, vec3 wp){',
' vec3 v = wp - cameraPosition; float dist = length(v); vec3 dir = v / max(dist, 0.001);',
' float k = dir.y * uFog.y * dist;',
' float integ = abs(k) > 0.01 ? (1.0 - exp(-k)) / k : 1.0 - k * 0.5;',
' float od = uFog.x * exp(-max(cameraPosition.y - uFog.w, -20.0) * uFog.y) * dist * integ + dist * dist * uFog.z;',
' float f = 1.0 - exp(-od);',
' float s = pow(max(dot(dir, uSunDir), 0.0), 6.0);',
' return mix(c, mix(uFogCol, uFogSun, s), clamp(f, 0.0, 1.0));',
'}'].join('\n');
function solidMat(leaf, flat, terrain) {
var m = new THREE.ShaderMaterial({
uniforms: { uTime: U.uTime, uNoise: U.uNoise, uSunDir: U.uSunDir, uSunCol: U.uSunCol, uSkyAmb: U.uSkyAmb, uGndAmb: U.uGndAmb, uFogCol: U.uFogCol, uFogSun: U.uFogSun, uFog: U.uFog, uGlow: U.uGlow, uFlat: { value: flat }, uFocus: U.uFocus, uAid: U.uAid },
defines: leaf ? { LEAF: 1 } : terrain ? { TERRAIN: 1 } : {},
vertexShader: [
'attribute vec4 aCol; attribute vec2 aFx; uniform float uTime;',
'varying vec3 vCol; varying vec3 vN; varying vec3 vW; varying vec3 vFx;',
'void main(){ vec3 p = position;',
'#ifdef LEAF',
' float sw = sin(uTime * 1.3 + p.x * 0.21 + p.z * 0.17) * 0.16 + sin(uTime * 2.3 + p.y * 0.5 + p.x * 0.3) * 0.06;',
' p.x += sw * aFx.y; p.z += sw * 0.6 * aFx.y;',
'#endif',
' vW = p; vN = normal; vCol = aCol.rgb; vFx = vec3(aFx, aCol.a);',
' gl_Position = projectionMatrix * viewMatrix * vec4(p, 1.0); }'].join('\n'),
fragmentShader: [
'uniform sampler2D uNoise; uniform vec3 uSunCol; uniform vec3 uSkyAmb; uniform vec3 uGndAmb; uniform float uGlow; uniform float uFlat; uniform vec3 uFocus; uniform float uAid; uniform float uTime;',
'varying vec3 vCol; varying vec3 vN; varying vec3 vW; varying vec3 vFx;',
FOG,
'void main(){',
' vec3 n = normalize(vN);',
' vec3 fn = normalize(cross(dFdx(vW), dFdy(vW)));',
' n = normalize(mix(n, fn, uFlat));',
' vec3 nz = texture2D(uNoise, vW.xz * 0.043 + vW.y * 0.021).rgb;',
' vec3 alb = vCol;',
'#ifndef LEAF',
' float band = texture2D(uNoise, vec2(vW.y * 0.045 + nz.r * 0.1, (vW.x + vW.z) * 0.004)).g;',
' alb *= 1.0 + (band - 0.5) * 0.7 * vFx.y;',
'#endif',
' alb *= 0.84 + 0.32 * nz.b;',
' float nl = dot(n, uSunDir);',
' float dif = clamp(nl * 0.8 + 0.2, 0.0, 1.0);',
' vec3 amb = mix(uGndAmb, uSkyAmb, n.y * 0.5 + 0.5);',
' float sh = 0.2 + 0.8 * vFx.x;',
' float fill = max(dot(n, normalize(vec3(-uSunDir.x, 0.35, -uSunDir.z))), 0.0);',
' vec3 c = alb * (amb * (0.85 + 0.15 * vFx.x) + uSkyAmb * fill * 0.4 + uSunCol * dif * sh);',
'#ifdef LEAF',
' c += alb * uSunCol * pow(max(-nl, 0.0), 2.0) * 0.3 * sh;',
'#endif',
' c = mix(c, vCol * (0.55 + 0.5 * uGlow), clamp(vFx.z, 0.0, 1.0) * 0.85);',
' // play aids: show where the snake can and cannot go',
' vec3 fd = vW - uFocus; float fxz = length(fd.xz);',
'#ifdef LEAF',
' vec3 ca = uFocus - cameraPosition; float tt = clamp(dot(vW - cameraPosition, ca) / max(dot(ca, ca), 0.001), 0.0, 1.0);',
' float dl = length(vW - cameraPosition - ca * tt);',
' float cut = (1.0 - smoothstep(5.0, 10.0, dl)) * uAid;',
' if (cut > fract(0.5 + gl_FragCoord.x * 0.7548 + gl_FragCoord.y * 0.5698)) discard;',
'#else',
'#ifdef TERRAIN',
' float nearK = (1.0 - smoothstep(26.0, 46.0, fxz)) * uAid;',
' float steep = 1.0 - smoothstep(0.44, 0.56, abs(fn.y));',
' c = mix(c, c * vec3(1.35, 0.62, 0.5) + vec3(0.1, 0.02, 0.0), steep * nearK * 0.45);',
' c *= 1.0 - 0.5 * (1.0 - smoothstep(0.5, 2.0, fxz)) * step(vW.y, uFocus.y) * uAid;',
'#else',
' vec3 ca = uFocus - cameraPosition; float tt = dot(vW - cameraPosition, ca) / max(dot(ca, ca), 0.001);',
' float dl = length(vW - cameraPosition - ca * clamp(tt, 0.0, 1.0));',
' float nb = smoothstep(-4.4, -3.4, fd.y) * (1.0 - smoothstep(2.0, 3.0, fd.y));',
' float cut = (1.0 - smoothstep(3.0, 5.0, dl)) * (1.0 - smoothstep(0.88, 0.97, tt)) * step(0.0, tt) * (1.0 - nb) * uAid;',
' if (cut > fract(0.5 + gl_FragCoord.x * 0.7548 + gl_FragCoord.y * 0.5698)) discard;',
' float hb = (1.0 - smoothstep(12.0, 24.0, fxz)) * smoothstep(-3.4, -2.2, fd.y) * (1.0 - smoothstep(0.9, 2.0, fd.y)) * uAid;',
' c = mix(c, c * vec3(1.3, 0.7, 0.6) + vec3(0.1, 0.02, 0.0), hb * 0.38);',
'#endif',
'#endif',
' gl_FragColor = vec4(applyFog(c, vW), 1.0);',
'}'].join('\n')
});
m.extensions.derivatives = true; return m;
}
var matSolid = solidMat(false, 0.55), matLeaf = solidMat(true, 0.3), matTerrain = solidMat(false, 0.4, true);
function add(o) { scene.add(o); added.push(o); return o; }
var stats = { tris: 0 };
// ------------------------------------------------------------------ finalize object meshes
function finish(acc, mat) {
if (!acc.n) return;
var g = new THREE.BufferGeometry(), pos = new Float32Array(acc.p), col = new Float32Array(acc.c), fx = new Float32Array(acc.f), i;
for (i = 0; i < acc.n; i++) {
var x = pos[i * 3], y = pos[i * 3 + 1], z = pos[i * 3 + 2], gr = y - heightAt(x, z), ao = 0.6 + 0.4 * sst(-0.5, 4.5, gr);
col[i * 4] *= ao; col[i * 4 + 1] *= ao; col[i * 4 + 2] *= ao;
fx[i * 2] = sunVis(x, y + 0.4, z);
}
g.setAttribute('position', new THREE.BufferAttribute(pos, 3)); g.setAttribute('aCol', new THREE.BufferAttribute(col, 4)); g.setAttribute('aFx', new THREE.BufferAttribute(fx, 2));
g.setIndex(new THREE.BufferAttribute(acc.n > 65535 ? new Uint32Array(acc.i) : new Uint16Array(acc.i), 1));
g.computeVertexNormals(); g.computeBoundingSphere();
stats.tris += acc.i.length / 3;
add(new THREE.Mesh(g, mat));
}
for (_i = 0; _i < CH * CH; _i++) { finish(solidAcc[_i], matSolid); finish(leafAcc[_i], matLeaf); }
solidAcc = leafAcc = null;
// ------------------------------------------------------------------ terrain mesh
function terrainCol(x, z, h, ny) {
var n = n2(x * 0.05 + 40, z * 0.05 - 17), nb = n2(x * 0.17, z * 0.17), nc = fbm(x * 0.012 + 70, z * 0.012 + 3, 3), d;
mixc(P.grassA, P.grassB, sst(-0.45, 0.45, nc * 1.6 + nb * 0.3));
blend(P.meadow, sst(0.2, 0.6, n) * 0.6);
var f = fbm(x * 0.017 + 20, z * 0.017 + 9, 3); if (f > 0.05) blend(P.grassA, sst(0.05, 0.25, f) * 0.5);
blend(P.alp, sst(36, 80, h) * 0.75);
blend(P.sand, 1 - sst(0.5, 2.4 + nb, h));
if (h < 0) blend(P.bed, sst(0, -4, h));
var dcan = polyDist(CAN, x, z, 26); if (dcan < 12 && h < 20) blend(P.sand, (1 - sst(6, 12, dcan)) * 0.8);
d = hyp(x - HILL.x, z - HILL.z); if (d < 13) blend(P.stoneA, (1 - sst(9, 13, d)) * (0.45 + 0.25 * nb));
d = hyp(x - ISLE.x, z - ISLE.z); if (d < 7.5) blend(P.stoneA, 0.5);
d = hyp(x - SHELF.x, z - SHELF.z); if (d < 11 && h > 17) blend(P.stoneA, 0.55);
d = hyp(x - GATE.x, z - GATE.z); if (d < 22) blend(P.stoneB, (1 - sst(10, 22, d)) * 0.6);
var rk = sst(0.76, 0.56, ny + nb * 0.05);
if (rk > 0) { var r0 = CR, g0 = CG, b0 = CB; mixc(P.rockA, P.rockB, n2(h * 0.2 + nb * 0.7, 3.3) * 0.5 + 0.5); blend(P.rockD, sst(0.2, 0.8, n) * 0.35); if (dcan < 26) blend(P.canyon, (1 - sst(10, 26, dcan)) * (0.55 + 0.35 * n2(h * 0.33, 1.7))); CR = r0 + (CR - r0) * rk; CG = g0 + (CG - g0) * rk; CB = b0 + (CB - b0) * rk; }
var sn = sst(P.snow, P.snow + 16, h + n * 8) * sst(0.4, 0.7, ny); blend(P.snowC, sn);
return rk * (1 - sn);
}
(function () {
var lines = [0, 8, 18, 28, 36, 44, 50, 56, 60], i, j, st = LOW ? 2 : 1; for (i = 62; i <= 238; i += st) lines.push(i); lines.push(240, 244, 250, 256, 264, 272, 282, 292, 300);
var n = lines.length, pos = new Float32Array(n * n * 3), col = new Float32Array(n * n * 4), fx = new Float32Array(n * n * 2), idx = new (n * n > 65535 ? Uint32Array : Uint16Array)((n - 1) * (n - 1) * 6), q = 0;
for (j = 0; j < n; j++) for (i = 0; i < n; i++) {
var gi = lines[i], gj = lines[j], x = gi * GS - GO, z = gj * GS - GO, h = H[gj * GN + gi], v = j * n + i;
var strata = terrainCol(x, z, h, slopeNy(x, z));
pos[v * 3] = x; pos[v * 3 + 1] = h; pos[v * 3 + 2] = z; col[v * 4] = CR; col[v * 4 + 1] = CG; col[v * 4 + 2] = CB; col[v * 4 + 3] = 0;
fx[v * 2] = sunVis(x, h + 0.8, z) * SPL[gj * GN + gi]; fx[v * 2 + 1] = strata;
}
for (j = 0; j < n - 1; j++) for (i = 0; i < n - 1; i++) { var a = j * n + i, b = a + 1, c = a + n, d = c + 1; if ((i + j) & 1) { idx[q++] = a; idx[q++] = c; idx[q++] = b; idx[q++] = b; idx[q++] = c; idx[q++] = d; } else { idx[q++] = a; idx[q++] = c; idx[q++] = d; idx[q++] = a; idx[q++] = d; idx[q++] = b; } }
var g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.BufferAttribute(pos, 3)); g.setAttribute('aCol', new THREE.BufferAttribute(col, 4)); g.setAttribute('aFx', new THREE.BufferAttribute(fx, 2)); g.setIndex(new THREE.BufferAttribute(idx, 1));
g.computeVertexNormals(); g.computeBoundingSphere(); stats.tris += idx.length / 3;
var m = add(new THREE.Mesh(g, matTerrain)); m.frustumCulled = false;
})();
SPL = null;
// ------------------------------------------------------------------ sky
var skyMat = new THREE.ShaderMaterial({
uniforms: { uTime: U.uTime, uNoise: U.uNoise, uSunDir: U.uSunDir, uFogCol: U.uFogCol, uFogSun: U.uFogSun, uZen: U.uZen, uMid: U.uMid, uSunGlow: U.uSunGlow, uCloudL: U.uCloudL, uCloudS: U.uCloudS, uK: U.uK,
uCloud: { value: P.cloud }, uStar: { value: P.star }, uAur: { value: P.aur }, uDisc: { value: P.disc }, uDiscC: { value: v3(P.discC) } },
side: THREE.BackSide, depthWrite: false, fog: false,
vertexShader: 'varying vec3 vDir; void main(){ vDir = position; vec4 p = projectionMatrix * vec4((viewMatrix * vec4(position, 0.0)).xyz, 1.0); gl_Position = vec4(p.xy, p.w * 0.99999, p.w); }',
fragmentShader: [
'uniform sampler2D uNoise; uniform float uTime; uniform vec3 uSunDir; uniform vec3 uFogCol; uniform vec3 uFogSun; uniform vec3 uZen; uniform vec3 uMid; uniform vec3 uSunGlow; uniform vec3 uCloudL; uniform vec3 uCloudS; uniform vec3 uDiscC;',
'uniform float uCloud; uniform float uStar; uniform float uAur; uniform float uDisc; uniform float uK;',
'varying vec3 vDir;',
'void main(){',
' vec3 d = normalize(vDir); float sd = max(dot(d, uSunDir), 0.0); float h = max(d.y, 0.0);',
' vec3 hor = mix(uFogCol, uFogSun, pow(sd, 6.0));',
' vec3 col = mix(hor, uMid, smoothstep(0.0, 0.2, h));',
' col = mix(col, uZen, smoothstep(0.1, 0.7, h));',
' col += uSunGlow * (pow(sd, 20.0) * 0.28 + pow(sd, 220.0) * 0.4);',
' float up = smoothstep(0.0, 0.12, d.y);',
' vec2 sp = d.xz / (1.0 + abs(d.y)) * 70.0; vec2 ic = floor(sp); vec2 fc = fract(sp) - 0.5;',
' float hs = fract(sin(dot(ic, vec2(127.1, 311.7))) * 43758.5453);',
' vec2 so = vec2(fract(hs * 17.3), fract(hs * 37.7)) - 0.5;',
' float st = step(0.86, hs) * smoothstep(0.11, 0.0, length(fc - so * 0.6)) * (0.6 + 0.4 * sin(uTime * 2.0 + hs * 60.0));',
' col += vec3(0.85, 0.92, 1.0) * st * uStar * up;',
' float az = atan(d.x, -d.z);',
' float am = smoothstep(2.7, 1.3, abs(az)) * uAur * (0.35 + 0.65 * uK);',
' vec3 au = vec3(0.0);',
' for (int i = 0; i < 2; i++) { float L = float(i);',
' float y0 = 0.16 + 0.12 * L + 0.07 * sin(az * 2.0 + uTime * 0.07 + L * 2.0) + 0.04 * sin(az * 5.0 - uTime * 0.11 + L);',
' float ray = texture2D(uNoise, vec2(az * 0.8 + L * 0.37 + uTime * 0.004, uTime * 0.013 + L * 0.5)).g;',
' float v = d.y - y0;',
' float cur = smoothstep(0.0, 0.025, v) * exp(-max(v, 0.0) * (7.0 - 2.0 * L)) * (0.25 + 1.3 * ray * ray);',
' au += mix(vec3(0.15, 1.0, 0.55), vec3(0.6, 0.3, 1.0), smoothstep(0.0, 0.3, v + L * 0.1)) * cur; }',
' col += au * am * 0.85;',
' vec2 cp = d.xz / (h + 0.16) * 0.22;',
' float n1 = texture2D(uNoise, cp * 0.55 + uTime * vec2(0.0035, 0.0012)).r;',
' float n2 = texture2D(uNoise, cp * 1.6 - uTime * vec2(0.002, 0.005)).g;',
' float dn = n1 * 0.68 + n2 * 0.32;',
' float dn2 = texture2D(uNoise, (cp + uSunDir.xz * 0.06) * 0.55 + uTime * vec2(0.0035, 0.0012)).r * 0.68 + n2 * 0.32;',
' float cov = smoothstep(0.44, 0.70, dn) * uCloud * smoothstep(0.015, 0.16, d.y);',
' float lit = clamp((dn - dn2) * 5.0 + 0.55, 0.0, 1.0);',
' vec3 cc = mix(uCloudS, uCloudL, lit) + uSunGlow * pow(sd, 6.0) * 0.45;',
' cc = mix(hor, cc, smoothstep(0.0, 0.22, d.y));',
' col = mix(col, cc, cov * 0.92);',
' col = mix(col, uDiscC, smoothstep(uDisc, uDisc + 0.0003, sd) * (1.0 - cov * 0.7));',
' gl_FragColor = vec4(col, 1.0);',
'}'].join('\n')
});
var sky = add(new THREE.Mesh(new THREE.IcosahedronGeometry(1, 3), skyMat)); sky.frustumCulled = false; sky.renderOrder = -1000;
// ------------------------------------------------------------------ water
var waterMat = new THREE.ShaderMaterial({
uniforms: { uTime: U.uTime, uNoise: U.uNoise, uDepth: { value: DEPTH }, uSunDir: U.uSunDir, uSunCol: U.uSunCol, uFogCol: U.uFogCol, uFogSun: U.uFogSun, uFog: U.uFog, uZen: U.uZen, uMid: U.uMid, uLum: U.uLum,
uShal: { value: v3(P.shal) }, uDeep: { value: v3(P.deep) }, uFoam: { value: v3(P.foam) } },
transparent: true, depthWrite: false, fog: false,
vertexShader: 'varying vec3 vW; void main(){ vec4 w = modelMatrix * vec4(position, 1.0); vW = w.xyz; gl_Position = projectionMatrix * viewMatrix * w; }',
fragmentShader: [
'uniform sampler2D uNoise; uniform sampler2D uDepth; uniform float uTime; uniform vec3 uSunCol; uniform vec3 uZen; uniform vec3 uMid; uniform vec3 uShal; uniform vec3 uDeep; uniform vec3 uFoam; uniform float uLum;',
'varying vec3 vW;', FOG,
'void main(){',
' vec2 uv = vW.xz; float dep = texture2D(uDepth, uv / 384.0 + 0.5).r;',
' vec3 a = texture2D(uNoise, uv * 0.11 + uTime * vec2(0.021, 0.009)).rgb;',
' vec3 b = texture2D(uNoise, uv * 0.29 - uTime * vec2(0.017, 0.026)).rgb;',
' vec2 nn = (a.rg + b.gb - 1.0);',
' vec3 n = normalize(vec3(nn.x * 0.22, 1.0, nn.y * 0.22));',
' vec3 v = normalize(cameraPosition - vW);',
' float fr = 0.08 + 0.92 * pow(1.0 - max(dot(v, n), 0.0), 3.0);',
' vec3 r = reflect(-v, n); r.y = abs(r.y);',
' float sd = max(dot(r, uSunDir), 0.0);',
' vec3 hor = mix(uFogCol, uFogSun, pow(sd, 6.0));',
' vec3 skyc = mix(mix(hor, uMid, smoothstep(0.0, 0.2, r.y)), uZen, smoothstep(0.1, 0.7, r.y));',
' vec3 base = mix(uShal, uDeep, smoothstep(0.03, 0.75, dep)) * uLum;',
' vec3 col = mix(base, skyc, fr * 0.8);',
' float spark = smoothstep(0.75, 1.0, b.b + a.b * 0.45);',
' col += uSunCol * (pow(sd, 120.0) * 1.6 + pow(sd, 10.0) * 0.5 * spark);',
' float fo = smoothstep(0.13, 0.0, dep + (a.r - 0.5) * 0.09 + sin(uTime * 0.9 + uv.x * 0.3 + uv.y * 0.2) * 0.012);',
' col = mix(col, uFoam * uLum, fo * 0.55);',
' float al = mix(0.5, 0.95, smoothstep(0.0, 0.35, dep)) + fr * 0.2;',
' gl_FragColor = vec4(applyFog(col, vW), clamp(al, 0.0, 1.0));',
'}'].join('\n')
});
(function () { var g = new THREE.PlaneGeometry(520, 520, 1, 1); g.rotateX(-PI / 2); var m = add(new THREE.Mesh(g, waterMat)); m.position.y = WATER; m.renderOrder = 1; stats.tris += 2; })();
// ------------------------------------------------------------------ waterfall + stream ribbon
var fallMat = new THREE.ShaderMaterial({
uniforms: { uTime: U.uTime, uNoise: U.uNoise, uFogCol: U.uFogCol, uFogSun: U.uFogSun, uFog: U.uFog, uSunDir: U.uSunDir, uLum: U.uLum, uA: { value: v3(P.shal) }, uB: { value: v3(P.foam) } },
transparent: true, depthWrite: false, side: THREE.DoubleSide, fog: false,
vertexShader: 'attribute float aS; varying vec2 vUv; varying vec3 vW; varying float vS; void main(){ vUv = uv; vS = aS; vW = position; gl_Position = projectionMatrix * viewMatrix * vec4(position, 1.0); }',
fragmentShader: [
'uniform sampler2D uNoise; uniform float uTime; uniform float uLum; uniform vec3 uA; uniform vec3 uB; varying vec2 vUv; varying vec3 vW; varying float vS;', FOG,
'void main(){',
' float sp = mix(0.25, 0.9, vS);',
' float s1 = texture2D(uNoise, vec2(vUv.x * 0.9, vUv.y * 0.05 - uTime * sp * 0.5)).g;',
' float s2 = texture2D(uNoise, vec2(vUv.x * 2.3 + 0.3, vUv.y * 0.11 - uTime * sp * 0.9)).b;',
' float w = smoothstep(0.35, 0.8, s1 * 0.6 + s2 * 0.6 + vS * 0.25);',
' vec3 col = mix(uA * 1.05, uB, w) * (0.75 + 0.25 * uLum) ;',
' float edge = sin(vUv.x * 3.14159);',
' float al = smoothstep(0.0, 0.35, edge) * mix(0.72, 0.95, w) * smoothstep(0.0, 3.0, vUv.y);',
' gl_FragColor = vec4(applyFog(col, vW), al);',
'}'].join('\n')
});
(function () {
var pts = [], x, i, lipY = 0;
for (x = 116; x >= 78; x -= 4) { var z = -52 - (x - 76) * 0.06 + 3.5 * Math.sin(x * 0.07 - 5.32); pts.push([x, heightAt(x, z) + 0.95, z, 2.4, 0]); }
lipY = pts[pts.length - 1][1];
for (i = 1; i <= 12; i++) { var t = i / 12; pts.push([77.5 - 7.6 * t, lipY - (lipY - 0.25) * t * t, FALL.z, 2.6 + 1.2 * t, 1]); }
var n = pts.length, pos = new Float32Array(n * 6), uv = new Float32Array(n * 4), as = new Float32Array(n * 2), idx = [], len = 0;
for (i = 0; i < n; i++) {
var p = pts[i], q = pts[Math.min(i + 1, n - 1)], o = pts[Math.max(i - 1, 0)], dx = q[0] - o[0], dz = q[2] - o[2], l = hyp(dx, dz) || 1, sx = -dz / l, sz = dx / l;
if (i > 0) len += Math.sqrt(Math.pow(p[0] - o[0], 2) + Math.pow(p[1] - o[1], 2) + Math.pow(p[2] - o[2], 2));
pos.set([p[0] + sx * p[3], p[1], p[2] + sz * p[3], p[0] - sx * p[3], p[1], p[2] - sz * p[3]], i * 6); uv.set([0, len, 1, len], i * 4); as[i * 2] = as[i * 2 + 1] = p[4];
if (i < n - 1) idx.push(i * 2, i * 2 + 1, i * 2 + 2, i * 2 + 1, i * 2 + 3, i * 2 + 2);
}
var g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.BufferAttribute(pos, 3)); g.setAttribute('uv', new THREE.BufferAttribute(uv, 2)); g.setAttribute('aS', new THREE.BufferAttribute(as, 1)); g.setIndex(idx); g.computeBoundingSphere();
var m = add(new THREE.Mesh(g, fallMat)); m.renderOrder = 2; stats.tris += idx.length / 3;
})();
// ------------------------------------------------------------------ sprites: mist + motes
function spriteMat(mote) {
return new THREE.ShaderMaterial({
uniforms: { uTime: U.uTime, uFocus: U.uFocus, uCol: { value: v3(mote ? P.mote : P.foam) }, uLum: U.uLum, uGlow: U.uGlow, uFogCol: U.uFogCol },
defines: mote ? { MOTE: 1 } : {}, transparent: true, depthWrite: false, fog: false, blending: mote ? THREE.AdditiveBlending : THREE.NormalBlending,
vertexShader: [
'attribute vec3 aC; attribute vec4 aR; uniform float uTime; uniform vec3 uFocus; varying vec2 vUv; varying float vA;',
'void main(){ vUv = position.xy; float size = aR.x;',
'#ifdef MOTE',
' vec3 c = aC + vec3(sin(uTime * 0.31 + aR.y * 6.28) * 1.6, uTime * aR.z, cos(uTime * 0.23 + aR.y * 4.0) * 1.6);',
' c = mod(c - uFocus + 45.0, 90.0) - 45.0;',
' vA = (1.0 - smoothstep(30.0, 44.0, max(abs(c.x), max(abs(c.y), abs(c.z))))) * (0.55 + 0.45 * sin(uTime * (1.0 + aR.w * 2.0) + aR.y * 40.0));',
' c += uFocus;',
'#else',
' float life = fract(uTime * aR.z + aR.y);',
' vec3 c = aC + vec3(aR.w * life * 5.0, life * (7.0 + aR.w * 3.0), sin(aR.y * 30.0) * life * 4.0);',
' size *= 0.55 + life * 0.9; vA = sin(life * 3.14159) * 0.5;',
'#endif',
' vec4 mv = viewMatrix * vec4(c, 1.0); mv.xy += position.xy * size; gl_Position = projectionMatrix * mv; }'].join('\n'),
fragmentShader: [
'uniform vec3 uCol; uniform float uLum; uniform float uGlow; uniform vec3 uFogCol; varying vec2 vUv; varying float vA;',
'void main(){ float r = length(vUv);',
'#ifdef MOTE',
' float a = (smoothstep(1.0, 0.0, r) * 0.35 + smoothstep(0.35, 0.0, r)) * vA; gl_FragColor = vec4(uCol * a * (0.5 + 0.35 * uGlow), 1.0);',
'#else',
' float a = smoothstep(1.0, 0.1, r) * vA; gl_FragColor = vec4(mix(uFogCol, uCol * uLum, 0.6), a);',
'#endif',
'}'].join('\n')
});
}
function sprites(n, mote, fill) {
var pos = new Float32Array(n * 12), aC = new Float32Array(n * 12), aR = new Float32Array(n * 16), idx = [], i, k, c = [0, 0, 0], r = [0, 0, 0, 0], q = [-1, -1, 1, -1, 1, 1, -1, 1];
for (i = 0; i < n; i++) { fill(i, c, r); for (k = 0; k < 4; k++) { pos.set([q[k * 2], q[k * 2 + 1], 0], (i * 4 + k) * 3); aC.set(c, (i * 4 + k) * 3); aR.set(r, (i * 4 + k) * 4); } idx.push(i * 4, i * 4 + 1, i * 4 + 2, i * 4, i * 4 + 2, i * 4 + 3); }
var g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.BufferAttribute(pos, 3)); g.setAttribute('aC', new THREE.BufferAttribute(aC, 3)); g.setAttribute('aR', new THREE.BufferAttribute(aR, 4)); g.setIndex(idx);
var m = add(new THREE.Mesh(g, spriteMat(mote))); m.frustumCulled = false; m.renderOrder = mote ? 4 : 3; stats.tris += n * 2; return m;
}
sprites(LOW ? 9 : 16, false, function (i, c, r) { c[0] = 69.5 + rr(-2, 1.5); c[1] = 0.5 + rr(0, 2); c[2] = FALL.z + rr(-4.5, 4.5); r[0] = rr(3.5, 6); r[1] = rnd(); r[2] = rr(0.12, 0.22); r[3] = rr(-1, 0.2); });
sprites(LOW ? 110 : 220, true, function (i, c, r) { c[0] = rr(0, 90); c[1] = rr(0, 90); c[2] = rr(0, 90); r[0] = rr(0.12, 0.3); r[1] = rnd(); r[2] = themeName === 'ember' ? rr(0.5, 1.4) : rr(-0.15, 0.3); r[3] = rnd(); });
// ------------------------------------------------------------------ birds
(function () {
var n = LOW ? 8 : 14, pos = new Float32Array(n * 12), aB = new Float32Array(n * 16), aO = new Float32Array(n * 8), idx = [], i, k, sh = [0, 0, 0.6, 0, 0, -0.5, -1.7, 0, -0.25, 1.7, 0, -0.25];
for (i = 0; i < n; i++) {
var fl = (i / 5) | 0, R = 60 + fl * 28 + rr(-6, 6), hgt = 66 + fl * 9 + rr(-3, 3), phs = fl * 2.1 + rr(-0.12, 0.12) * (i % 5 + 1), spd = (0.085 - fl * 0.012) * (fl % 2 ? -1 : 1), ox = rr(-20, 20), oz = rr(-20, 20);
for (k = 0; k < 4; k++) { pos.set([sh[k * 3], 0, sh[k * 3 + 2]], (i * 4 + k) * 3); aB.set([R, hgt, phs, spd], (i * 4 + k) * 4); aO.set([ox, oz], (i * 4 + k) * 2); }
idx.push(i * 4, i * 4 + 1, i * 4 + 2, i * 4, i * 4 + 3, i * 4 + 1);
}
var g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.BufferAttribute(pos, 3)); g.setAttribute('aB', new THREE.BufferAttribute(aB, 4)); g.setAttribute('aO', new THREE.BufferAttribute(aO, 2)); g.setIndex(idx);
var mat = new THREE.ShaderMaterial({
uniforms: { uTime: U.uTime, uCol: { value: v3(P.bird) }, uFogCol: U.uFogCol, uFogSun: U.uFogSun, uFog: U.uFog, uSunDir: U.uSunDir, uLum: U.uLum }, side: THREE.DoubleSide, fog: false,
vertexShader: [
'attribute vec4 aB; attribute vec2 aO; uniform float uTime; varying vec3 vW;',
'void main(){ float a = aB.z + uTime * aB.w; float sg = aB.w < 0.0 ? -1.0 : 1.0;',
' vec3 c = vec3(aO.x + cos(a) * aB.x, aB.y + sin(a * 3.0 + aB.z) * 2.5, aO.y + sin(a) * aB.x);',
' vec2 f = vec2(-sin(a), cos(a)) * sg; vec2 r = vec2(f.y, -f.x);',
' float flap = sin(uTime * 6.5 + aB.z * 9.0 + aB.x) * abs(position.x) * 0.45;',
' vec3 p = c + (vec3(r.x, 0.0, r.y) * position.x + vec3(f.x, 0.0, f.y) * position.z + vec3(0.0, flap, 0.0)) * 1.5;',
' vW = p; gl_Position = projectionMatrix * viewMatrix * vec4(p, 1.0); }'].join('\n'),
fragmentShader: ['uniform vec3 uCol; uniform float uLum; varying vec3 vW;', FOG, 'void main(){ gl_FragColor = vec4(applyFog(uCol * (0.6 + 0.4 * uLum), vW), 1.0); }'].join('\n')
});
var m = add(new THREE.Mesh(g, mat)); m.frustumCulled = false; stats.tris += n * 2;
})();
// ------------------------------------------------------------------ lights + fog for the core's own materials
var hemi = add(new THREE.HemisphereLight(0xffffff, 0x444444, 1)), dirL = add(new THREE.DirectionalLight(0xffffff, 1));
dirL.position.copy(sunDir).multiplyScalar(200);
scene.fog = new THREE.FogExp2(0xffffff, 0.004);
var fogColor = scene.fog.color, curK = -1;
function lerp3(v, a, b, k) { v.set(a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k, a[2] + (b[2] - a[2]) * k); }
function setProgress(k) {
k = k < 0 ? 0 : k > 1 ? 1 : +k || 0; if (k === curK) return; curK = k;
var a = P.k0, b = P.k1;
lerp3(U.uZen.value, a.zen, b.zen, k); lerp3(U.uMid.value, a.mid, b.mid, k); lerp3(U.uFogCol.value, a.fog, b.fog, k); lerp3(U.uFogSun.value, a.fogSun, b.fogSun, k);
lerp3(U.uSunCol.value, a.sunC, b.sunC, k); lerp3(U.uSkyAmb.value, a.amb, b.amb, k); lerp3(U.uGndAmb.value, a.gnd, b.gnd, k);
lerp3(U.uCloudL.value, a.cloudL, b.cloudL, k); lerp3(U.uCloudS.value, a.cloudS, b.cloudS, k); lerp3(U.uSunGlow.value, a.sg, b.sg, k);
U.uGlow.value = a.glow + (b.glow - a.glow) * k; U.uLum.value = a.lum + (b.lum - a.lum) * k; U.uK.value = k;
var den = a.den + (b.den - a.den) * k; U.uFog.value.x = 0.0055 * den; U.uFog.value.z = 0.0000036 * den;
fogColor.setRGB(Math.min(1, U.uFogCol.value.x), Math.min(1, U.uFogCol.value.y), Math.min(1, U.uFogCol.value.z));
scene.fog.density = 0.0034 * den;
var sc = U.uSunCol.value, am = U.uSkyAmb.value, gn = U.uGndAmb.value, mx = Math.max(sc.x, sc.y, sc.z, 0.001);
dirL.color.setRGB(sc.x / mx, sc.y / mx, sc.z / mx); dirL.intensity = mx * 0.95;
hemi.color.setRGB(Math.min(1, am.x * 1.5), Math.min(1, am.y * 1.5), Math.min(1, am.z * 1.5)); hemi.groundColor.setRGB(gn.x * 1.4, gn.y * 1.4, gn.z * 1.4); hemi.intensity = 0.95;
}
setProgress(0);
function update(dt, t, camera, focus, aid) {
U.uTime.value = t; U.uAid.value += ((aid ? 1 : 0) - U.uAid.value) * Math.min(1, 4 * dt);
if (focus) U.uFocus.value.set(focus.x, focus.y, focus.z); else if (camera) U.uFocus.value.copy(camera.position);
}
function dispose() {
for (var i = 0; i < added.length; i++) {
var o = added[i]; scene.remove(o);
if (o.geometry) o.geometry.dispose();
if (o.material) o.material.dispose();
}
for (i = 0; i < textures.length; i++) textures[i].dispose();
added.length = 0; textures.length = 0; scene.fog = prevFog || null;
}
return {
half: HALF, ceiling: CEIL, waterY: WATER, heightAt: heightAt, collide: collide,
landmarks: { start: START, shrines: [shr1, shr2, shr3], gate: gate, canyon: canyonPts },
freeSpot: freeSpot, update: update, setProgress: setProgress, fogColor: fogColor, sunDir: sunDir, dispose: dispose,
theme: themeName, stats: { tris: stats.tris, colliders: NP, anchors: AN.length / 3 }
};
}
/* ---- dragon.js ---- */
/* Snake 3D - ribbon-dragon (original design).
* Plain script, three.js r128 global-compatible. Defines one global: createDragon(THREE, scene, opts).
* opts: { maxPoints:260, quality:'high'|'low', rollSign:1, lightDir:Vector3 }
* Returns D: { update(pts,n,t,dt,st), head, setPalette(name), dispose(), group, setLight(v3), stats }
* 4 draw calls: body tube, head, ribbons (fin/mane, tail tuft, whiskers, fins, boost streaks), glow quads.
*/
function createDragon(THREE, scene, opts) {
'use strict';
opts = opts || {};
var MAXP = Math.max(14, (opts.maxPoints | 0) || 260);
var LOW = opts.quality === 'low';
var ROLL_SIGN = opts.rollSign === -1 ? -1 : 1;
var SP = 0.45; // point spacing along the flown path
var RAD = LOW ? 8 : 12; // body radial segments
var RV = RAD + 1;
var FROWS = LOW ? 2 : 3; // dorsal fin rows
var WN = LOW ? 8 : 12; // whisker nodes
var NCH = 4; // whisker chains
var TL = LOW ? 3 : 5; // tail tuft leaves
var TK = 7; // nodes per leaf
var PF = 4, PM = 7; // pectoral fins, rim points each
var SL = 4, SN = LOW ? 24 : 36; // boost streak lines, nodes each
var MAXQ = 96; // glow quads
var PI = Math.PI, TAU = PI * 2;
// ------------------------------------------------------------------ palettes
var PALS = {
dawn: {
A: [0.05, 0.50, 0.55], B: [0.30, 0.30, 0.78], C: [0.98, 0.42, 0.52],
belly: [1.00, 0.90, 0.72], rim: [1.00, 0.80, 0.55], glow: [1.00, 0.86, 0.50],
finA: [1.00, 0.46, 0.30], finB: [0.96, 0.32, 0.58], finEdge: [1.00, 0.90, 0.58],
horn: [0.96, 0.86, 0.66], hornTip: [1.00, 0.72, 0.30], eye: [1.00, 0.62, 0.10],
wisp: [1.00, 0.80, 0.36], wisp2: [1.00, 0.62, 0.50], whisk: [1.00, 0.86, 0.56]
},
ember: {
A: [0.62, 0.07, 0.08], B: [0.92, 0.34, 0.06], C: [1.00, 0.76, 0.22],
belly: [1.00, 0.84, 0.52], rim: [1.00, 0.62, 0.25], glow: [1.00, 0.70, 0.25],
finA: [1.00, 0.72, 0.16], finB: [1.00, 0.36, 0.10], finEdge: [1.00, 0.95, 0.55],
horn: [0.30, 0.16, 0.14], hornTip: [1.00, 0.55, 0.12], eye: [0.75, 1.00, 0.40],
wisp: [1.00, 0.62, 0.20], wisp2: [1.00, 0.86, 0.40], whisk: [1.00, 0.78, 0.36]
},
moon: {
A: [0.13, 0.17, 0.48], B: [0.42, 0.55, 0.92], C: [0.86, 0.82, 1.00],
belly: [0.90, 0.94, 1.00], rim: [0.66, 0.86, 1.00], glow: [0.62, 0.86, 1.00],
finA: [0.50, 0.86, 1.00], finB: [0.72, 0.62, 1.00], finEdge: [0.94, 0.98, 1.00],
horn: [0.88, 0.92, 1.00], hornTip: [0.55, 0.90, 1.00], eye: [0.60, 0.95, 1.00],
wisp: [0.66, 0.88, 1.00], wisp2: [0.90, 0.80, 1.00], whisk: [0.86, 0.94, 1.00]
}
};
var pal = PALS.dawn;
// ------------------------------------------------------------------ shared uniforms
var uTime = { value: 0 }, uLen = { value: 13 }, uBoost = { value: 0 }, uHurt = { value: 0 }, uGlow = { value: 0 }, uPulse = { value: -100 };
var uLight = { value: new THREE.Vector3(0.35, 0.85, 0.4).normalize() };
if (opts.lightDir && opts.lightDir.isVector3) uLight.value.copy(opts.lightDir).normalize();
function c3(a) { return { value: new THREE.Color(a[0], a[1], a[2]) }; }
var uA = c3(pal.A), uB = c3(pal.B), uC = c3(pal.C), uBelly = c3(pal.belly), uRim = c3(pal.rim), uGlowCol = c3(pal.glow);
var uFinA = c3(pal.finA), uFinB = c3(pal.finB), uFinEdge = c3(pal.finEdge);
function mkUniforms(extra) {
var u = {
fogColor: { value: new THREE.Color(0xffffff) }, fogNear: { value: 1e5 }, fogFar: { value: 2e5 },
fogDensity: { value: 0 },
uTime: uTime, uLen: uLen, uBoost: uBoost, uHurt: uHurt, uGlow: uGlow, uLight: uLight, uPulse: uPulse,
uA: uA, uB: uB, uC: uC, uBelly: uBelly, uRim: uRim, uGlowCol: uGlowCol,
uFinA: uFinA, uFinB: uFinB, uFinEdge: uFinEdge
};
if (extra) for (var k in extra) u[k] = extra[k];
return u;
}
// ------------------------------------------------------------------ GLSL
var FOG_F = [
'#ifdef USE_FOG',
'uniform vec3 fogColor;',
'#ifdef FOG_EXP2',
'uniform float fogDensity;',
'#else',
'uniform float fogNear; uniform float fogFar;',
'#endif',
'#endif',
'float fogAmt(float d){',
'#ifdef USE_FOG',
'#ifdef FOG_EXP2',
' return 1.0 - exp(-fogDensity*fogDensity*d*d);',
'#else',
' return smoothstep(fogNear, fogFar, d);',
'#endif',
'#else',
' return 0.0;',
'#endif',
'}',
'vec3 fogMix(vec3 c, float d, float k){',
'#ifdef USE_FOG',
' return mix(c, fogColor, fogAmt(d)*k);',
'#else',
' return c;',
'#endif',
'}'
].join('\n');
var COMMON_F = [
'uniform float uTime; uniform float uLen; uniform float uBoost; uniform float uHurt; uniform float uGlow; uniform float uPulse;',
'uniform vec3 uA; uniform vec3 uB; uniform vec3 uC; uniform vec3 uBelly; uniform vec3 uRim; uniform vec3 uGlowCol;',
'uniform vec3 uLight;',
'varying vec3 vN; varying vec3 vWN; varying vec3 vV; varying vec2 vUv; varying float vDepth;',
FOG_F,
'vec3 scalePat(vec2 p){',
' vec2 pa = fract(p) - 0.5; vec2 pb = fract(p + 0.5) - 0.5;',
' float da = dot(pa,pa); float db = dot(pb,pb);',
' float sel = step(da, db);',
' vec2 q = mix(pb, pa, sel);',
' vec2 id = mix(floor(p + 0.5) + 0.37, floor(p), sel);',
' float d = sqrt(min(da, db));',
' float h = fract(sin(dot(id, vec2(12.9898, 78.233))) * 43758.5453);',
' return vec3(smoothstep(0.27, 0.355, d), q.y, h);',
'}',
// base: albedo, em: emissive 0..1, sc: scale pattern (edge, grad, hash), scAmt, gloss, s: 0..1 along
'vec3 shade(vec3 base, float em, vec3 sc, float scAmt, float gloss, float s){',
' vec3 N = normalize(vN); vec3 V = normalize(vV);',
' if (dot(N, V) < 0.0) N = -N;',
' vec3 L = normalize((viewMatrix * vec4(uLight, 0.0)).xyz);',
' float lod = 1.0 - smoothstep(26.0, 80.0, vDepth);',
' float sa = scAmt * lod;',
' float ndv = max(dot(N, V), 0.0);',
' float fres = pow(1.0 - ndv, 3.2);',
' vec3 col = base;',
' col *= 1.0 - 0.42 * sc.x * sa;',
' col *= 1.0 + (0.85 * sc.y + 0.18 * (sc.z - 0.5)) * sa;',
' vec3 ir = 0.5 + 0.5 * cos(6.2831 * (fres * 0.85 + s * 1.3 + sc.z * 0.22 * sa + uTime * 0.04) + vec3(0.0, 2.1, 4.2));',
' col = mix(col, col * 0.55 + ir * 0.75, (0.08 + 0.40 * fres) * (0.35 + 0.65 * scAmt));',
' float ndl = dot(N, L);',
' float dif = clamp(ndl * 0.55 + 0.45, 0.0, 1.0);',
' float hemi = 0.5 + 0.5 * normalize(vWN).y;',
' vec3 light = mix(vec3(0.34, 0.34, 0.50), vec3(1.06, 1.02, 0.94), dif * dif) * (0.80 + 0.20 * hemi);',
' vec3 lit = col * light + col * 0.14;',
' float sp = pow(max(dot(N, normalize(L + V)), 0.0), 36.0) * gloss * (1.0 - 0.6 * sc.x * sa);',
' lit += vec3(1.0, 0.96, 0.86) * sp * 0.65;',
' lit += uRim * fres * (0.34 + 0.9 * uGlow + 0.45 * uBoost);',
' lit = mix(lit, base * (1.5 + 0.8 * uGlow) + vec3(0.25) * fres, em);',
' lit += uGlowCol * uGlow * 0.20;',
' float bl = uHurt * (0.5 + 0.5 * sin(uTime * 38.0));',
' lit = mix(lit, vec3(1.25, 0.50, 0.42), bl * 0.8);',
' return lit;',
'}'
].join('\n');
var BODY_V = [
'varying vec3 vN; varying vec3 vWN; varying vec3 vV; varying vec2 vUv; varying float vDepth;',
'void main(){',
' vUv = uv;',
' vec4 mv = modelViewMatrix * vec4(position, 1.0);',
' vN = normalMatrix * normal; vWN = (modelMatrix * vec4(normal, 0.0)).xyz;',
' vV = -mv.xyz; vDepth = -mv.z;',
' gl_Position = projectionMatrix * mv;',
'}'
].join('\n');
var BODY_F = [
COMMON_F,
'void main(){',
' float s = clamp(vUv.y / max(uLen, 1.0), 0.0, 1.0);',
' float ca = cos(vUv.x * 6.2831853);',
' vec3 base = mix(uA, uB, smoothstep(0.02, 0.50, s));',
' base = mix(base, uC, smoothstep(0.50, 1.0, s));',
' base *= 1.0 - 0.30 * smoothstep(0.45, 1.0, ca);',
' float belly = smoothstep(-0.42, -0.74, ca);',
' float pl = fract(vUv.y * 1.0);',
' float plate = smoothstep(0.0, 0.16, pl) * (1.0 - smoothstep(0.90, 1.0, pl));',
' vec3 bcol = uBelly * (0.74 + 0.26 * plate);',
' vec3 sc = scalePat(vec2(vUv.x * 14.0, vUv.y * 1.45));',
' base = mix(base, bcol, belly);',
// lateral line of light pearls
' float lat = abs(ca + 0.22);',
' float fv = fract(vUv.y * 0.5) - 0.5;',
' float pearl = 1.0 - smoothstep(0.045, 0.10, length(vec2(lat * 0.55, fv * 0.9)));',
' float pulse = 0.55 + 0.45 * sin(vUv.y * 0.55 - uTime * 4.2);',
' float taper = 1.0 - smoothstep(0.86, 1.0, s);',
' vec3 col = shade(base, 0.0, sc, 1.0 - belly, mix(0.75, 0.35, belly), s);',
' col += uGlowCol * pearl * taper * (0.30 + 0.60 * pulse + uGlow);',
' float band = pow(0.5 + 0.5 * sin(vUv.y * 0.21 - uTime * (2.0 + 4.0 * uBoost)), 14.0);',
' col += uRim * band * (0.22 + 0.5 * uGlow + 0.3 * uBoost);',
// growth pulse: a bright band that runs from head to tail when a light is eaten (uPulse = position in body points, < 0 when off)
' float pz = (vUv.y - uPulse) / 3.5; col += (uGlowCol * 1.1 + vec3(0.3)) * exp(-pz * pz) * step(0.0, uPulse);',
' col = fogMix(col, vDepth, 0.85);',
' gl_FragColor = vec4(col, 1.0);',
'}'
].join('\n');
var HEAD_V = [
'attribute vec3 aCol; attribute vec3 aFx;',
'varying vec3 vN; varying vec3 vWN; varying vec3 vV; varying vec2 vUv; varying float vDepth;',
'varying vec3 vCol; varying vec3 vFx;',
'void main(){',
' vUv = uv; vCol = aCol; vFx = aFx;',
' vec4 mv = modelViewMatrix * vec4(position, 1.0);',
' vN = normalMatrix * normal; vWN = (modelMatrix * vec4(normal, 0.0)).xyz;',
' vV = -mv.xyz; vDepth = -mv.z;',
' gl_Position = projectionMatrix * mv;',
'}'
].join('\n');
var HEAD_F = [
COMMON_F,
'varying vec3 vCol; varying vec3 vFx;',
'void main(){',
' vec3 sc = scalePat(vec2(vUv.x * 22.0, vUv.y * 15.0));',
' vec3 col = shade(vCol, vFx.x, sc, vFx.y, vFx.z, 0.0);',
' col = fogMix(col, vDepth, 0.85);',
' gl_FragColor = vec4(col, 1.0);',
'}'
].join('\n');
var RIB_V = [
'attribute vec4 aCol; attribute float aKind;',
'varying vec4 vCol; varying vec2 vUv; varying float vKind; varying float vDepth;',
'void main(){',
' vUv = uv; vCol = aCol; vKind = aKind;',
' vec4 mv = modelViewMatrix * vec4(position, 1.0);',
' vDepth = -mv.z;',
' gl_Position = projectionMatrix * mv;',
'}'
].join('\n');
// kind 0: dorsal fin (palette gradient), 1: solid, 2: additive streak, 3: membrane with vertex colour
var RIB_F = [
'uniform float uTime; uniform float uLen; uniform float uBoost; uniform float uHurt; uniform float uGlow;',
'uniform vec3 uFinA; uniform vec3 uFinB; uniform vec3 uFinEdge;',
'varying vec4 vCol; varying vec2 vUv; varying float vKind; varying float vDepth;',
FOG_F,
'void main(){',
' vec3 col; float a; float add;',
' float fa = fogAmt(vDepth);',
' if (vKind > 1.5 && vKind < 2.5) {',
' float u = vUv.x;',
' float prof = pow(max(sin(3.14159 * u), 0.0), 0.7) * (1.0 - abs(vUv.y * 2.0 - 1.0));',
' float fl = 0.55 + 0.45 * sin(u * 26.0 - uTime * 34.0 + vCol.a * 9.0);',
' col = vCol.rgb * prof * fl * uBoost * 0.9 * (1.0 - 0.7 * fa);',
' gl_FragColor = vec4(col, 0.0);',
' return;',
' }',
' if (vKind > 0.5 && vKind < 1.5) {',
' col = vCol.rgb * (1.0 + 0.5 * uGlow); a = vCol.a; add = 0.0;',
' } else {',
' float s = clamp(vUv.x / max(uLen, 1.0), 0.0, 1.0);',
' vec3 base = mix(uFinA, uFinB, smoothstep(0.1, 0.9, s));',
' base = mix(vCol.rgb, base, step(vKind, 0.5));',
' float v = clamp(vUv.y, 0.0, 1.0);',
' float ray = smoothstep(0.62, 1.0, abs(fract(vUv.x) - 0.5) * 2.0);',
' float sh = 0.5 + 0.5 * sin(vUv.x * 0.9 - uTime * 3.0 + v * 2.0);',
' col = base * (0.72 + 0.30 * v);',
' col = mix(col, uFinEdge, smoothstep(0.62, 1.0, v) * 0.65);',
' col += uFinEdge * ray * 0.16 + base * sh * 0.18 * v;',
' col *= 1.0 + 0.6 * uGlow;',
' a = mix(0.90, 0.55, v) + ray * 0.2;',
' a *= vCol.a;',
' add = 0.15;',
' }',
' float bl = uHurt * (0.5 + 0.5 * sin(uTime * 38.0));',
' col = mix(col, vec3(1.25, 0.50, 0.42), bl * 0.8);',
'#ifdef USE_FOG',
' col = mix(col, fogColor, fa * 0.85);',
'#endif',
' a = clamp(a, 0.0, 1.0);',
' gl_FragColor = vec4(col * a, a * (1.0 - add));',
'}'
].join('\n');
var GLOW_V = [
'attribute vec2 aCorner; attribute vec4 aCol; attribute vec2 aPrm;',
'varying vec2 vC; varying vec4 vCol; varying float vCore; varying float vDepth;',
'void main(){',
' vC = aCorner; vCol = aCol; vCore = aPrm.y;',
' vec4 mv = modelViewMatrix * vec4(position, 1.0);',
' mv.xy += aCorner * aPrm.x;',
' mv.z += min(aPrm.x * 0.25, 0.3);',
' vDepth = -mv.z;',
' gl_Position = projectionMatrix * mv;',
'}'
].join('\n');
var GLOW_F = [
'varying vec2 vC; varying vec4 vCol; varying float vCore; varying float vDepth;',
FOG_F,
'void main(){',
' float d2 = dot(vC, vC);',
' float d = sqrt(d2);',
' float halo = exp(-d2 * 5.0) * (1.0 - smoothstep(0.75, 1.0, d));',
' float core = (1.0 - smoothstep(0.10, 0.24, d)) * vCore;',
' float k = 1.0 - 0.65 * fogAmt(vDepth);',
' vec3 col = vCol.rgb * halo * vCol.a + mix(vCol.rgb, vec3(1.0), 0.55) * core;',
' gl_FragColor = vec4(col * k, core * 0.85 * k);',
'}'
].join('\n');
// ------------------------------------------------------------------ materials
var bodyMat = new THREE.ShaderMaterial({
uniforms: mkUniforms(), vertexShader: BODY_V, fragmentShader: BODY_F, fog: true
});
var headMat = new THREE.ShaderMaterial({
uniforms: mkUniforms(), vertexShader: HEAD_V, fragmentShader: HEAD_F, fog: true, side: THREE.DoubleSide
});
var ribMat = new THREE.ShaderMaterial({
uniforms: mkUniforms(), vertexShader: RIB_V, fragmentShader: RIB_F, fog: true, side: THREE.DoubleSide,
transparent: true, depthWrite: false,
blending: THREE.CustomBlending, blendEquation: THREE.AddEquation,
blendSrc: THREE.OneFactor, blendDst: THREE.OneMinusSrcAlphaFactor
});
var glowMat = new THREE.ShaderMaterial({
uniforms: mkUniforms(), vertexShader: GLOW_V, fragmentShader: GLOW_F, fog: true,
transparent: true, depthWrite: false,
blending: THREE.CustomBlending, blendEquation: THREE.AddEquation,
blendSrc: THREE.OneFactor, blendDst: THREE.OneMinusSrcAlphaFactor
});
// ------------------------------------------------------------------ body geometry
var group = new THREE.Group();
group.name = 'ribbonDragon';
var bPos = new Float32Array(MAXP * RV * 3);
var bNor = new Float32Array(MAXP * RV * 3);
var bUv = new Float32Array(MAXP * RV * 2);
var bIdx = new Uint16Array((MAXP - 1) * RAD * 6);
(function () {
var i, j, k = 0;
for (i = 0; i < MAXP; i++) for (j = 0; j < RV; j++) {
bUv[(i * RV + j) * 2] = j / RAD; bUv[(i * RV + j) * 2 + 1] = i;
bNor[(i * RV + j) * 3 + 1] = 1;
}
for (i = 0; i < MAXP - 1; i++) for (j = 0; j < RAD; j++) {
var a = i * RV + j, b = (i + 1) * RV + j, c = a + 1, d = b + 1;
bIdx[k++] = a; bIdx[k++] = b; bIdx[k++] = c; bIdx[k++] = c; bIdx[k++] = b; bIdx[k++] = d;
}
})();
var bodyGeo = new THREE.BufferGeometry();
var bPosA = new THREE.BufferAttribute(bPos, 3); bPosA.setUsage(THREE.DynamicDrawUsage);
var bNorA = new THREE.BufferAttribute(bNor, 3); bNorA.setUsage(THREE.DynamicDrawUsage);
bodyGeo.setAttribute('position', bPosA);
bodyGeo.setAttribute('normal', bNorA);
bodyGeo.setAttribute('uv', new THREE.BufferAttribute(bUv, 2));
bodyGeo.setIndex(new THREE.BufferAttribute(bIdx, 1));
bodyGeo.setDrawRange(0, 0);
var bodyMesh = new THREE.Mesh(bodyGeo, bodyMat);
bodyMesh.frustumCulled = false;
group.add(bodyMesh);
var COSJ = new Float32Array(RV), SINJ = new Float32Array(RV);
(function () { for (var j = 0; j < RV; j++) { COSJ[j] = Math.cos(j / RAD * TAU); SINJ[j] = Math.sin(j / RAD * TAU); } })();
// ------------------------------------------------------------------ head geometry (static, +Z forward, +Y up)
var hP = [], hN = [], hU = [], hPart = [], hPrm = [], hI = [];
var _a = [0, 0, 0], _b = [0, 0, 0], _c = [0, 0, 0], _d = [0, 0, 0], _p = [0, 0, 0];
function surf(fn, nu, nv, part) {
var base = hP.length / 3, iu, iv, e = 0.004;
for (iv = 0; iv <= nv; iv++) for (iu = 0; iu <= nu; iu++) {
var u = iu / nu, v = iv / nv;
fn(u, v, _p);
hP.push(_p[0], _p[1], _p[2]);
var vv = Math.min(0.975, Math.max(0.025, v));
fn(u + e, vv, _a); fn(u - e, vv, _b); fn(u, vv + e, _c); fn(u, vv - e, _d);
var ax = _a[0] - _b[0], ay = _a[1] - _b[1], az = _a[2] - _b[2];
var bx = _c[0] - _d[0], by = _c[1] - _d[1], bz = _c[2] - _d[2];
var nx = ay * bz - az * by, ny = az * bx - ax * bz, nz = ax * by - ay * bx;
var l = Math.sqrt(nx * nx + ny * ny + nz * nz);
if (l < 1e-9) { nx = 0; ny = 1; nz = 0; l = 1; }
hN.push(nx / l, ny / l, nz / l);
hU.push(u, v); hPart.push(part); hPrm.push(u, v);
}
for (iv = 0; iv < nv; iv++) for (iu = 0; iu < nu; iu++) {
var a = base + iv * (nu + 1) + iu, b = a + nu + 1;
hI.push(a, b, a + 1, a + 1, b, b + 1);
}
}
function crs(arr, t) { // catmull-rom over scalar array, t 0..1
var m = arr.length - 1, f = Math.min(Math.max(t, 0), 1) * m, i = Math.min(Math.floor(f), m - 1); f -= i;
var p0 = arr[Math.max(i - 1, 0)], p1 = arr[i], p2 = arr[i + 1], p3 = arr[Math.min(i + 2, m)];
return 0.5 * ((2 * p1) + (-p0 + p2) * f + (2 * p0 - 5 * p1 + 4 * p2 - p3) * f * f + (-p0 + 3 * p1 - 3 * p2 + p3) * f * f * f);
}
function loft(Z, W, H, Y, flat, nu, nv, part) {
surf(function (u, v, o) {
var a = u * TAU, w = Math.max(crs(W, v), 0), h = Math.max(crs(H, v), 0), ca = Math.cos(a);
o[0] = -w * Math.sin(a); o[1] = crs(Y, v) + h * ca * (ca < 0 ? flat : 1); o[2] = crs(Z, v);
}, nu, nv, part);
}
function tube(X, Y, Z, r0, r1, nu, nv, part) {
surf(function (u, v, o) {
var cx = crs(X, v), cy = crs(Y, v), cz = crs(Z, v), e = 0.01;
var tx = crs(X, v + e) - crs(X, v - e), ty = crs(Y, v + e) - crs(Y, v - e), tz = crs(Z, v + e) - crs(Z, v - e);
var tl = Math.sqrt(tx * tx + ty * ty + tz * tz) || 1; tx /= tl; ty /= tl; tz /= tl;
// reference: world X unless tangent is near X
var rx = 1, ry = 0, rz = 0; if (Math.abs(tx) > 0.9) { rx = 0; ry = 0; rz = 1; }
var dp = rx * tx + ry * ty + rz * tz; var nx = rx - tx * dp, ny = ry - ty * dp, nz = rz - tz * dp;
var nl = Math.sqrt(nx * nx + ny * ny + nz * nz) || 1; nx /= nl; ny /= nl; nz /= nl;
var bx = ty * nz - tz * ny, by = tz * nx - tx * nz, bz = tx * ny - ty * nx;
var r = r0 + (r1 - r0) * Math.pow(v, 0.85), a = u * TAU, c = Math.cos(a) * r, s = Math.sin(a) * r;
o[0] = cx + nx * c + bx * s; o[1] = cy + ny * c + by * s; o[2] = cz + nz * c + bz * s;
}, nu, nv, part);
}
function ball(cx, cy, cz, rx, ry, rz, nu, nv, part) {
surf(function (u, v, o) {
var th = v * PI, ph = u * TAU, st = Math.sin(th);
o[0] = cx + rx * st * Math.cos(ph); o[1] = cy + ry * Math.cos(th); o[2] = cz + rz * st * Math.sin(ph);
}, nu, nv, part);
}
function fan(bx, by, bz, rim, part) { // rim: array of [x,y,z]; strip with base duplicated
var base = hP.length / 3, m = rim.length, i;
var e1x = rim[0][0] - bx, e1y = rim[0][1] - by, e1z = rim[0][2] - bz;
var e2x = rim[m - 1][0] - bx, e2y = rim[m - 1][1] - by, e2z = rim[m - 1][2] - bz;
var nx = e1y * e2z - e1z * e2y, ny = e1z * e2x - e1x * e2z, nz = e1x * e2y - e1y * e2x;
var l = Math.sqrt(nx * nx + ny * ny + nz * nz) || 1; nx /= l; ny /= l; nz /= l;
for (i = 0; i < m; i++) {
hP.push(bx, by, bz, rim[i][0], rim[i][1], rim[i][2]);
hN.push(nx, ny, nz, nx, ny, nz);
hU.push(i / (m - 1), 0, i / (m - 1), 1); hPart.push(part, part); hPrm.push(i, 0, i, 1);
}
for (i = 0; i < m - 1; i++) { var a = base + i * 2; hI.push(a, a + 1, a + 2, a + 2, a + 1, a + 3); }
}
var HSC = 1.22;
var EYE = [0.445, 0.20, 0.50];
var HORN_TIP = [0.74, 1.34, -2.35];
(function buildHead() {
var q = LOW ? 0.6 : 1;
// skull + snout
loft([-0.78, -0.62, -0.25, 0.22, 0.62, 1.05, 1.42, 1.66, 1.80, 1.84],
[0.30, 0.50, 0.66, 0.62, 0.46, 0.36, 0.34, 0.27, 0.13, 0.0],
[0.30, 0.48, 0.58, 0.54, 0.36, 0.27, 0.26, 0.21, 0.10, 0.0],
[0.00, 0.00, 0.05, 0.07, 0.00, -0.05, -0.05, -0.07, -0.09, -0.10],
0.78, Math.round(18 * q), Math.round(26 * q), 0);
// lower jaw
loft([-0.45, -0.10, 0.45, 1.00, 1.42, 1.62, 1.68],
[0.40, 0.52, 0.44, 0.31, 0.24, 0.12, 0.0],
[0.14, 0.20, 0.17, 0.12, 0.10, 0.06, 0.0],
[-0.30, -0.36, -0.37, -0.32, -0.30, -0.29, -0.29],
1.0, Math.round(12 * q), Math.round(12 * q), 1);
for (var sd = -1; sd <= 1; sd += 2) {
// antler main beam, swept back with an upturned tip, plus two tines
tube([0.24 * sd, 0.40 * sd, 0.56 * sd, 0.66 * sd, HORN_TIP[0] * sd],
[0.42, 0.86, 1.06, 1.10, HORN_TIP[1]],
[-0.05, -0.45, -1.05, -1.75, HORN_TIP[2]],
0.14, 0.014, 6, Math.round(14 * q), 2);
tube([0.43 * sd, 0.62 * sd, 0.80 * sd], [0.90, 1.34, 1.72], [-0.52, -0.70, -1.12], 0.085, 0.01, 5, Math.round(7 * q), 2);
tube([0.60 * sd, 0.80 * sd, 0.98 * sd], [1.09, 1.38, 1.70], [-1.35, -1.62, -2.10], 0.07, 0.008, 5, Math.round(7 * q), 2);
// brow ridge
ball(0.40 * sd, 0.37, 0.46, 0.20, 0.10, 0.34, 8, 6, 5);
// eye + slit pupil
ball(EYE[0] * sd, EYE[1], EYE[2], 0.105, 0.135, 0.165, 10, 8, 3);
ball((EYE[0] + 0.078) * sd, EYE[1] + 0.012, EYE[2] + 0.04, 0.04, 0.115, 0.075, 6, 6, 6);
// nostril bumps
ball(0.16 * sd, 0.09, 1.62, 0.065, 0.055, 0.10, 6, 5, 5);
// small fangs
tube([0.20 * sd, 0.21 * sd, 0.21 * sd], [-0.20, -0.32, -0.42], [1.34, 1.33, 1.30], 0.035, 0.004, 4, 3, 7);
// cheek mane spikes
for (var k = 0; k < 3; k++) {
var y0 = -0.22 + 0.22 * k, ln = 0.95 - 0.12 * Math.abs(k - 1);
tube([0.50 * sd, (0.68 + 0.10 * k) * sd, (0.86 + 0.16 * k) * sd],
[y0, y0 + 0.04 + 0.08 * k, y0 + 0.16 * k + 0.08],
[-0.42, -0.42 - ln * 0.5, -0.42 - ln], 0.105, 0.008, 5, 4, 4);
}
// ear fin (webbed fan)
var rim = [], sp = [[1.02, 0.86, -0.78], [1.34, 0.58, -1.12], [1.46, 0.18, -1.30], [1.26, -0.20, -1.22], [0.92, -0.44, -0.92]];
for (var m = 0; m < sp.length; m++) {
rim.push([sp[m][0] * sd, sp[m][1], sp[m][2]]);
if (m < sp.length - 1) rim.push([(sp[m][0] + sp[m + 1][0]) * 0.5 * 0.86 * sd, (sp[m][1] + sp[m + 1][1]) * 0.5 * 0.9, (sp[m][2] + sp[m + 1][2]) * 0.5 * 0.88]);
}
fan(0.56 * sd, 0.12, -0.18, rim, 8);
}
// crest plate between the antlers leading into the mane
fan(0, 0.50, 0.55, [[0, 0.62, 0.45], [0, 0.86, 0.12], [0, 0.80, -0.02], [0, 1.02, -0.32], [0, 0.92, -0.46], [0, 1.10, -0.80], [0, 0.60, -0.80]], 8);
// chin barbel knob
ball(0, -0.42, 1.25, 0.07, 0.07, 0.10, 6, 5, 1);
})();
var HV = hP.length / 3;
var headGeo = new THREE.BufferGeometry();
headGeo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(hP), 3));
headGeo.setAttribute('normal', new THREE.BufferAttribute(new Float32Array(hN), 3));
headGeo.setAttribute('uv', new THREE.BufferAttribute(new Float32Array(hU), 2));
var hColA = new THREE.BufferAttribute(new Float32Array(HV * 3), 3);
var hFxA = new THREE.BufferAttribute(new Float32Array(HV * 3), 3);
headGeo.setAttribute('aCol', hColA);
headGeo.setAttribute('aFx', hFxA);
headGeo.setIndex(new THREE.BufferAttribute(new Uint16Array(hI), 1));
headGeo.computeBoundingSphere();
var headTris = hI.length / 3;
var head = new THREE.Group();
head.name = 'dragonHead';
var headMesh = new THREE.Mesh(headGeo, headMat);
headMesh.frustumCulled = false;
headMesh.scale.set(HSC, HSC, HSC);
head.add(headMesh);
group.add(head);
var hNorArr = headGeo.attributes.normal.array;
hP = hN = hU = hI = null;
// ------------------------------------------------------------------ ribbon geometry (dynamic, world space)
var OFF_FIN = 0, NV_FIN = MAXP * FROWS;
var OFF_TUFT = OFF_FIN + NV_FIN, NV_TUFT = TL * TK * 2;
var OFF_WH = OFF_TUFT + NV_TUFT, NV_WH = NCH * WN * 4;
var OFF_PEC = OFF_WH + NV_WH, NV_PEC = PF * PM * 2;
var OFF_ST = OFF_PEC + NV_PEC, NV_ST = SL * SN * 2;
var RVN = OFF_ST + NV_ST;
var rPos = new Float32Array(RVN * 3), rUv = new Float32Array(RVN * 2), rCol = new Float32Array(RVN * 4), rKind = new Float32Array(RVN);
var rIdxArr = [];
function stripIdx(base, cols, rows) { // cols along, rows across; vertex = base + col*rows + row
for (var c = 0; c < cols - 1; c++) for (var r = 0; r < rows - 1; r++) {
var a = base + c * rows + r, b = a + rows;
rIdxArr.push(a, b, a + 1, a + 1, b, b + 1);
}
}
(function () {
var i, r, k, l, v;
stripIdx(OFF_FIN, MAXP, FROWS);
for (i = 0; i < MAXP; i++) for (r = 0; r < FROWS; r++) {
v = OFF_FIN + i * FROWS + r;
rUv[v * 2] = i; rUv[v * 2 + 1] = r / (FROWS - 1); rKind[v] = 0;
rCol[v * 4] = 1; rCol[v * 4 + 1] = 1; rCol[v * 4 + 2] = 1; rCol[v * 4 + 3] = 1;
}
for (l = 0; l < TL; l++) {
stripIdx(OFF_TUFT + l * TK * 2, TK, 2);
for (k = 0; k < TK; k++) for (r = 0; r < 2; r++) {
v = OFF_TUFT + (l * TK + k) * 2 + r;
rUv[v * 2] = 0.5; rUv[v * 2 + 1] = k / (TK - 1); rKind[v] = 3;
}
}
for (l = 0; l < NCH; l++) {
for (k = 0; k < WN - 1; k++) {
var a = OFF_WH + (l * WN + k) * 4, b = a + 4;
rIdxArr.push(a, b, a + 1, a + 1, b, b + 1, a + 2, b + 2, a + 3, a + 3, b + 2, b + 3);
}
for (k = 0; k < WN; k++) for (r = 0; r < 4; r++) {
v = OFF_WH + (l * WN + k) * 4 + r;
rUv[v * 2] = k / (WN - 1); rUv[v * 2 + 1] = r & 1; rKind[v] = 1;
}
}
for (l = 0; l < PF; l++) {
stripIdx(OFF_PEC + l * PM * 2, PM, 2);
for (k = 0; k < PM; k++) for (r = 0; r < 2; r++) {
v = OFF_PEC + (l * PM + k) * 2 + r;
rUv[v * 2] = k; rUv[v * 2 + 1] = r; rKind[v] = 3;
}
}
for (l = 0; l < SL; l++) {
stripIdx(OFF_ST + l * SN * 2, SN, 2);
for (k = 0; k < SN; k++) for (r = 0; r < 2; r++) {
v = OFF_ST + (l * SN + k) * 2 + r;
rUv[v * 2] = k / (SN - 1); rUv[v * 2 + 1] = r; rKind[v] = 2;
}
}
})();
var ribGeo = new THREE.BufferGeometry();
var rPosA = new THREE.BufferAttribute(rPos, 3); rPosA.setUsage(THREE.DynamicDrawUsage);
var rColA = new THREE.BufferAttribute(rCol, 4);
ribGeo.setAttribute('position', rPosA);
ribGeo.setAttribute('uv', new THREE.BufferAttribute(rUv, 2));
ribGeo.setAttribute('aCol', rColA);
ribGeo.setAttribute('aKind', new THREE.BufferAttribute(rKind, 1));
ribGeo.setIndex(new THREE.BufferAttribute(new Uint16Array(rIdxArr), 1));
var ribTris = rIdxArr.length / 3; rIdxArr = null;
var ribMesh = new THREE.Mesh(ribGeo, ribMat);
ribMesh.frustumCulled = false; ribMesh.renderOrder = 2;
group.add(ribMesh);
// ------------------------------------------------------------------ glow quads
var gPos = new Float32Array(MAXQ * 12), gCorner = new Float32Array(MAXQ * 8), gCol = new Float32Array(MAXQ * 16), gPrm = new Float32Array(MAXQ * 8);
var gIdx = new Uint16Array(MAXQ * 6);
(function () {
var cs = [-1, -1, 1, -1, 1, 1, -1, 1];
for (var q = 0; q < MAXQ; q++) {
for (var k = 0; k < 8; k++) gCorner[q * 8 + k] = cs[k];
gIdx[q * 6] = q * 4; gIdx[q * 6 + 1] = q * 4 + 1; gIdx[q * 6 + 2] = q * 4 + 2;
gIdx[q * 6 + 3] = q * 4; gIdx[q * 6 + 4] = q * 4 + 2; gIdx[q * 6 + 5] = q * 4 + 3;
}
})();
var glowGeo = new THREE.BufferGeometry();
var gPosA = new THREE.BufferAttribute(gPos, 3); gPosA.setUsage(THREE.DynamicDrawUsage);
var gColA = new THREE.BufferAttribute(gCol, 4); gColA.setUsage(THREE.DynamicDrawUsage);
var gPrmA = new THREE.BufferAttribute(gPrm, 2); gPrmA.setUsage(THREE.DynamicDrawUsage);
glowGeo.setAttribute('position', gPosA);
glowGeo.setAttribute('aCorner', new THREE.BufferAttribute(gCorner, 2));
glowGeo.setAttribute('aCol', gColA);
glowGeo.setAttribute('aPrm', gPrmA);
glowGeo.setIndex(new THREE.BufferAttribute(gIdx, 1));
glowGeo.setDrawRange(0, 0);
var glowMesh = new THREE.Mesh(glowGeo, glowMat);
glowMesh.frustumCulled = false; glowMesh.renderOrder = 3;
group.add(glowMesh);
var gq = 0;
function quad(x, y, z, size, r, g, b, inten, core) {
if (gq >= MAXQ) return;
var o = gq * 12, c = gq * 16, p = gq * 8, k;
for (k = 0; k < 4; k++) {
gPos[o + k * 3] = x; gPos[o + k * 3 + 1] = y; gPos[o + k * 3 + 2] = z;
gCol[c + k * 4] = r; gCol[c + k * 4 + 1] = g; gCol[c + k * 4 + 2] = b; gCol[c + k * 4 + 3] = inten;
gPrm[p + k * 2] = size; gPrm[p + k * 2 + 1] = core;
}
gq++;
}
scene.add(group);
// ------------------------------------------------------------------ palette
function sstep(a, b, x) { var t = Math.min(Math.max((x - a) / (b - a), 0), 1); return t * t * (3 - 2 * t); }
function setPalette(name) {
var p = PALS[name] || PALS.dawn; pal = p;
uA.value.setRGB(p.A[0], p.A[1], p.A[2]); uB.value.setRGB(p.B[0], p.B[1], p.B[2]); uC.value.setRGB(p.C[0], p.C[1], p.C[2]);
uBelly.value.setRGB(p.belly[0], p.belly[1], p.belly[2]); uRim.value.setRGB(p.rim[0], p.rim[1], p.rim[2]);
uGlowCol.value.setRGB(p.glow[0], p.glow[1], p.glow[2]);
uFinA.value.setRGB(p.finA[0], p.finA[1], p.finA[2]); uFinB.value.setRGB(p.finB[0], p.finB[1], p.finB[2]);
uFinEdge.value.setRGB(p.finEdge[0], p.finEdge[1], p.finEdge[2]);
var col = hColA.array, fx = hFxA.array, i, k, r, g, b, em, sc, gl, w;
for (i = 0; i < HV; i++) {
var part = hPart[i], v = hPrm[i * 2 + 1], ny = hNorArr[i * 3 + 1];
em = 0; sc = 0; gl = 0.5;
if (part === 0) {
w = sstep(-0.62, -0.05, ny);
var dk = 1 - 0.28 * sstep(0.55, 1, ny);
var sn = sstep(0.55, 1.0, v) * 0.22;
r = (p.belly[0] * 0.92 * (1 - w) + (p.A[0] + (p.B[0] - p.A[0]) * sn) * w * dk);
g = (p.belly[1] * 0.92 * (1 - w) + (p.A[1] + (p.B[1] - p.A[1]) * sn) * w * dk);
b = (p.belly[2] * 0.92 * (1 - w) + (p.A[2] + (p.B[2] - p.A[2]) * sn) * w * dk);
sc = w; gl = 0.7;
} else if (part === 1) { r = p.belly[0] * 0.9; g = p.belly[1] * 0.9; b = p.belly[2] * 0.9; gl = 0.3; }
else if (part === 2) {
w = Math.pow(v, 1.6);
r = p.horn[0] + (p.hornTip[0] - p.horn[0]) * w; g = p.horn[1] + (p.hornTip[1] - p.horn[1]) * w; b = p.horn[2] + (p.hornTip[2] - p.horn[2]) * w;
em = 0.75 * Math.pow(v, 3); gl = 0.9;
} else if (part === 3) { r = p.eye[0]; g = p.eye[1]; b = p.eye[2]; em = 0.8; }
else if (part === 4) {
r = p.finA[0] * 0.85 + (p.finEdge[0] - p.finA[0] * 0.85) * v; g = p.finA[1] * 0.85 + (p.finEdge[1] - p.finA[1] * 0.85) * v; b = p.finA[2] * 0.85 + (p.finEdge[2] - p.finA[2] * 0.85) * v;
em = 0.15 + 0.4 * v; gl = 0.4;
} else if (part === 5) { r = p.A[0] * 0.88; g = p.A[1] * 0.88; b = p.A[2] * 0.88; sc = 1; gl = 0.8; }
else if (part === 6) { r = 0.03; g = 0.02; b = 0.05; em = 1; }
else if (part === 7) { r = 0.97; g = 0.94; b = 0.86; gl = 0.8; }
else { // 8: webbed fins, spine tips (even rim index) brighter than web dips
var even = (Math.round(hPrm[i * 2]) % 2 === 0) ? 1 : 0.62;
w = v * even;
r = p.finB[0] * 0.75 + (p.finEdge[0] - p.finB[0] * 0.75) * w; g = p.finB[1] * 0.75 + (p.finEdge[1] - p.finB[1] * 0.75) * w; b = p.finB[2] * 0.75 + (p.finEdge[2] - p.finB[2] * 0.75) * w;
em = 0.25 + 0.3 * w; gl = 0.3;
}
col[i * 3] = r; col[i * 3 + 1] = g; col[i * 3 + 2] = b;
fx[i * 3] = em; fx[i * 3 + 1] = sc; fx[i * 3 + 2] = gl;
}
hColA.needsUpdate = true; hFxA.needsUpdate = true;
// static ribbon colours
var l, vI, u;
for (l = 0; l < TL; l++) for (k = 0; k < TK * 2; k++) {
vI = OFF_TUFT + l * TK * 2 + k; u = (k >> 1) / (TK - 1);
var e = (l % 2) ? p.finA : p.finB;
rCol[vI * 4] = p.C[0] * (1 - u) + e[0] * u; rCol[vI * 4 + 1] = p.C[1] * (1 - u) + e[1] * u; rCol[vI * 4 + 2] = p.C[2] * (1 - u) + e[2] * u; rCol[vI * 4 + 3] = 1;
}
for (l = 0; l < NCH; l++) for (k = 0; k < WN * 4; k++) {
vI = OFF_WH + l * WN * 4 + k; u = (k >> 2) / (WN - 1);
rCol[vI * 4] = p.whisk[0]; rCol[vI * 4 + 1] = p.whisk[1]; rCol[vI * 4 + 2] = p.whisk[2]; rCol[vI * 4 + 3] = 1 - 0.35 * u;
}
for (l = 0; l < PF; l++) for (k = 0; k < PM * 2; k++) {
vI = OFF_PEC + l * PM * 2 + k;
var src = l < 2 ? p.finA : p.finB;
rCol[vI * 4] = src[0]; rCol[vI * 4 + 1] = src[1]; rCol[vI * 4 + 2] = src[2]; rCol[vI * 4 + 3] = 1;
}
for (l = 0; l < SL; l++) for (k = 0; k < SN * 2; k++) {
vI = OFF_ST + l * SN * 2 + k;
var sc2 = (l % 2) ? p.rim : p.finEdge;
rCol[vI * 4] = sc2[0]; rCol[vI * 4 + 1] = sc2[1]; rCol[vI * 4 + 2] = sc2[2]; rCol[vI * 4 + 3] = l * 0.37;
}
rColA.needsUpdate = true;
}
setPalette('dawn');
// ------------------------------------------------------------------ per-frame state (all preallocated)
var TT = new Float32Array(MAXP * 3), NN = new Float32Array(MAXP * 3), BB = new Float32Array(MAXP * 3);
var CC = new Float32Array(MAXP * 3), RR = new Float32Array(MAXP);
var HS = MAXP + 8, hist = new Float32Array(HS * 3), histK = 0, histCount = 0, travel = 0;
var wh = new Float32Array(NCH * WN * 3), whInit = false;
var first = true, nf = 14, finWritten = 0;
var upx = 0, upy = 1, upz = 0; // persistent (unrolled) head up
var dzx = 0, dzy = 0, dzz = 1; // head forward
var prevHx = 0, prevHy = 0, prevHz = 0;
var hxx = 1, hxy = 0, hxz = 0, hyx = 0, hyy = 1, hyz = 0;
var _m4 = new THREE.Matrix4();
// whisker chain setup: anchor (local), side, segment length, root width
var WH_AX = [0.27, -0.27, 0.15, -0.15], WH_AY = [-0.02, -0.02, -0.40, -0.40], WH_AZ = [1.50, 1.50, 1.12, 1.12];
var WH_SIDE = [1, -1, 1, -1], WH_SEG = [3.5 / (WN - 1), 3.5 / (WN - 1), 1.5 / (WN - 1), 1.5 / (WN - 1)], WH_W = [0.024, 0.024, 0.018, 0.018];
var WH_LONG = [1, 1, 0, 0];
function fin(x) { return typeof x === 'number' && x === x && x !== Infinity && x !== -Infinity; }
function clamp01(x) { return fin(x) ? (x < 0 ? 0 : (x > 1 ? 1 : x)) : 0; }
function update(pts, n, t, dt, st) {
if (!pts || !pts.length || !pts[0]) return;
var p0 = pts[0];
if (!fin(p0.x) || !fin(p0.y) || !fin(p0.z)) return;
n = n | 0; if (n > MAXP) n = MAXP; if (n > pts.length) n = pts.length; if (n < 2) n = 2;
if (!fin(t)) t = 0;
if (!(dt > 0)) dt = 0.016; if (dt > 0.1) dt = 0.1;
var boost = 0, hurt = 0, glow = 0, dash = 0, roll = 0, sdir = null;
if (st) { boost = clamp01(st.boost); hurt = clamp01(st.hurt); glow = clamp01(st.glow); dash = clamp01(st.dash); roll = fin(st.roll) ? st.roll : 0; sdir = st.dir; uPulse.value = fin(st.pulse) ? st.pulse : -100; }
var i, j, k, l, o, x, y, z, len, d;
if (first) nf = n; else { nf += (n - nf) * (1 - Math.exp(-dt * 5)); if (Math.abs(n - nf) < 0.02) nf = n; }
var L1 = Math.max(nf - 1, 1);
uTime.value = t % 3600; uLen.value = L1; uBoost.value = boost; uHurt.value = hurt; uGlow.value = glow;
// ---- head forward
x = 0; y = 0; z = 0; len = 0;
if (sdir && fin(sdir.x) && fin(sdir.y) && fin(sdir.z)) { x = sdir.x; y = sdir.y; z = sdir.z; len = Math.sqrt(x * x + y * y + z * z); }
if (len < 1e-5 && pts[1] && fin(pts[1].x) && fin(pts[1].y) && fin(pts[1].z)) { x = p0.x - pts[1].x; y = p0.y - pts[1].y; z = p0.z - pts[1].z; len = Math.sqrt(x * x + y * y + z * z); }
if (len >= 1e-5) { dzx = x / len; dzy = y / len; dzz = z / len; }
// ---- persistent up, transported with the head and eased back toward world up
d = upx * dzx + upy * dzy + upz * dzz;
upx -= dzx * d; upy -= dzy * d; upz -= dzz * d;
len = Math.sqrt(upx * upx + upy * upy + upz * upz);
var wx = -dzx * dzy, wy = 1 - dzy * dzy, wz = -dzz * dzy, wl = Math.sqrt(wx * wx + wy * wy + wz * wz);
if (len < 1e-4) {
if (wl > 1e-3) { upx = wx / wl; upy = wy / wl; upz = wz / wl; }
else { upx = 1 - dzx * dzx; upy = -dzx * dzy; upz = -dzx * dzz; len = Math.sqrt(upx * upx + upy * upy + upz * upz) || 1; upx /= len; upy /= len; upz /= len; }
} else { upx /= len; upy /= len; upz /= len; }
if (wl > 0.06) {
var kr = first ? 1 : (1 - Math.exp(-dt * 2.2)) * wl;
wx /= wl; wy /= wl; wz /= wl;
if (upx * wx + upy * wy + upz * wz < -0.98) { // exactly inverted: nudge sideways so it can roll out
upx += (dzy * upz - dzz * upy) * 0.2; upy += (dzz * upx - dzx * upz) * 0.2; upz += (dzx * upy - dzy * upx) * 0.2;
}
upx += (wx - upx) * kr; upy += (wy - upy) * kr; upz += (wz - upz) * kr;
len = Math.sqrt(upx * upx + upy * upy + upz * upz);
if (len > 1e-5) { upx /= len; upy /= len; upz /= len; } else { upx = wx; upy = wy; upz = wz; }
}
// ---- roll + dash spin about forward
var de = dash * dash * (3 - 2 * dash);
var ang = ROLL_SIGN * roll;
var ca = Math.cos(ang), sa = Math.sin(ang);
var cx = dzy * upz - dzz * upy, cy = dzz * upx - dzx * upz, cz = dzx * upy - dzy * upx; // dir x up
var bkx = upx * ca + cx * sa, bky = upy * ca + cy * sa, bkz = upz * ca + cz * sa; // banked up (no spin)
ang += TAU * de; ca = Math.cos(ang); sa = Math.sin(ang);
hyx = upx * ca + cx * sa; hyy = upy * ca + cy * sa; hyz = upz * ca + cz * sa;
hxx = hyy * dzz - hyz * dzy; hxy = hyz * dzx - hyx * dzz; hxz = hyx * dzy - hyy * dzx; // up x fwd
_m4.set(hxx, hyx, dzx, 0, hxy, hyy, dzy, 0, hxz, hyz, dzz, 0, 0, 0, 0, 1);
head.quaternion.setFromRotationMatrix(_m4);
head.position.set(p0.x, p0.y, p0.z);
// ---- frame history keyed by distance flown (keeps banking and rolls "painted" along the path)
x = p0.x - prevHx; y = p0.y - prevHy; z = p0.z - prevHz;
var move = Math.sqrt(x * x + y * y + z * z);
var mvx = x * 0.88, mvy = y * 0.88, mvz = z * 0.88;
var teleport = first || move > 6;
if (teleport) { histCount = 0; travel = 0; histK = 0; whInit = false; }
else {
travel += move;
var nk = Math.floor(travel / SP);
while (histK < nk) {
histK++; o = (histK % HS) * 3;
hist[o] = bkx; hist[o + 1] = bky; hist[o + 2] = bkz;
if (histCount < HS - 2) histCount++;
}
if (travel > 4096 * SP) { travel -= 2048 * SP; histK -= 2048; }
}
prevHx = p0.x; prevHy = p0.y; prevHz = p0.z;
var hfrac = travel / SP - histK; if (!(hfrac >= 0)) hfrac = 0; if (hfrac > 1) hfrac = 1;
// ---- pass 1: raw frames + undulated centres
var rMax = 0.42 + 0.13 * clamp01((nf - 14) / 50);
var undA = 0.20 * (1 - 0.55 * boost), ptx = dzx, pty = dzy, ptz = dzz, pnx = bkx, pny = bky, pnz = bkz;
var tx, ty, tz, nx, ny, nz, bx, by, bz, P, Pa, Pb, s;
for (i = 0; i < n; i++) {
P = pts[i];
if (i === 0) { tx = dzx; ty = dzy; tz = dzz; }
else {
Pa = pts[i - 1]; Pb = (i < n - 1) ? pts[i + 1] : P;
tx = Pa.x - Pb.x; ty = Pa.y - Pb.y; tz = Pa.z - Pb.z;
len = Math.sqrt(tx * tx + ty * ty + tz * tz);
if (len > 1e-5 && fin(len)) { tx /= len; ty /= len; tz /= len; } else { tx = ptx; ty = pty; tz = ptz; }
}
if (i === 0) { nx = bkx; ny = bky; nz = bkz; }
else {
d = pnx * tx + pny * ty + pnz * tz;
nx = pnx - tx * d; ny = pny - ty * d; nz = pnz - tz * d;
len = Math.sqrt(nx * nx + ny * ny + nz * nz);
if (len > 1e-4) { nx /= len; ny /= len; nz /= len; }
else { // previous normal parallel to tangent: pick any perpendicular
nx = 1 - tx * tx; ny = -tx * ty; nz = -tx * tz; len = Math.sqrt(nx * nx + ny * ny + nz * nz);
if (len < 1e-3) { nx = -ty * tx; ny = 1 - ty * ty; nz = -ty * tz; len = Math.sqrt(nx * nx + ny * ny + nz * nz) || 1; }
nx /= len; ny /= len; nz /= len;
}
if (i < histCount) {
var o0 = (((histK - i) % HS + HS) % HS) * 3, hx1, hy1, hz1;
if (i === 1) { hx1 = bkx; hy1 = bky; hz1 = bkz; }
else { var o1 = (((histK - i + 1) % HS + HS) % HS) * 3; hx1 = hist[o1]; hy1 = hist[o1 + 1]; hz1 = hist[o1 + 2]; }
x = hist[o0] + (hx1 - hist[o0]) * hfrac; y = hist[o0 + 1] + (hy1 - hist[o0 + 1]) * hfrac; z = hist[o0 + 2] + (hz1 - hist[o0 + 2]) * hfrac;
d = x * tx + y * ty + z * tz; x -= tx * d; y -= ty * d; z -= tz * d;
len = Math.sqrt(x * x + y * y + z * z);
if (len > 0.3 && (x * nx + y * ny + z * nz) > 0.05 * len) { nx = x / len; ny = y / len; nz = z / len; }
}
}
bx = ty * nz - tz * ny; by = tz * nx - tx * nz; bz = tx * ny - ty * nx;
ptx = tx; pty = ty; ptz = tz; pnx = nx; pny = ny; pnz = nz;
o = i * 3;
NN[o] = nx; NN[o + 1] = ny; NN[o + 2] = nz;
s = i / L1; if (s > 1) s = 1;
var ramp = sstep(3, 26, i) * (1 + 0.6 * s);
var w1 = undA * ramp * Math.sin(i * 0.31 - t * 2.7), w2 = undA * 0.45 * ramp * Math.sin(i * 0.23 - t * 1.9 + 1.3);
x = P.x + bx * w1 + nx * w2; y = P.y + by * w1 + ny * w2; z = P.z + bz * w1 + nz * w2;
if (!fin(x) || !fin(y) || !fin(z)) { x = p0.x; y = p0.y; z = p0.z; }
CC[o] = x; CC[o + 1] = y; CC[o + 2] = z;
var taper = Math.pow(Math.max(1 - Math.pow(s, 1.8), 0), 0.75);
RR[i] = rMax * (0.84 + 0.16 * sstep(0, 3, i)) * (0.03 + 0.97 * taper);
}
// ---- pass 2: final frames from the undulated centres, write body rings
ptx = dzx; pty = dzy; ptz = dzz;
for (i = 0; i < n; i++) {
o = i * 3;
if (i === 0) { tx = dzx; ty = dzy; tz = dzz; }
else {
var oa = o - 3, ob = (i < n - 1) ? o + 3 : o;
tx = CC[oa] - CC[ob]; ty = CC[oa + 1] - CC[ob + 1]; tz = CC[oa + 2] - CC[ob + 2];
len = Math.sqrt(tx * tx + ty * ty + tz * tz);
if (len > 1e-5) { tx /= len; ty /= len; tz /= len; } else { tx = ptx; ty = pty; tz = ptz; }
}
nx = NN[o]; ny = NN[o + 1]; nz = NN[o + 2];
d = nx * tx + ny * ty + nz * tz; nx -= tx * d; ny -= ty * d; nz -= tz * d;
len = Math.sqrt(nx * nx + ny * ny + nz * nz);
if (len > 1e-4) { nx /= len; ny /= len; nz /= len; }
else {
nx = 1 - tx * tx; ny = -tx * ty; nz = -tx * tz; len = Math.sqrt(nx * nx + ny * ny + nz * nz);
if (len < 1e-3) { nx = -ty * tx; ny = 1 - ty * ty; nz = -ty * tz; len = Math.sqrt(nx * nx + ny * ny + nz * nz) || 1; }
nx /= len; ny /= len; nz /= len;
}
bx = ty * nz - tz * ny; by = tz * nx - tx * nz; bz = tx * ny - ty * nx;
if (dash > 0) { // barrel roll: one full turn that ripples from the head down the body
d = dash * 1.6 - 0.6 * i / L1; d = d < 0 ? 0 : (d > 1 ? 1 : d);
d = TAU * d * d * (3 - 2 * d);
var cd = Math.cos(d), sd2 = Math.sin(d);
x = nx * cd + bx * sd2; y = ny * cd + by * sd2; z = nz * cd + bz * sd2;
bx = bx * cd - nx * sd2; by = by * cd - ny * sd2; bz = bz * cd - nz * sd2;
nx = x; ny = y; nz = z;
}
ptx = tx; pty = ty; ptz = tz;
TT[o] = tx; TT[o + 1] = ty; TT[o + 2] = tz; NN[o] = nx; NN[o + 1] = ny; NN[o + 2] = nz; BB[o] = bx; BB[o + 1] = by; BB[o + 2] = bz;
var r = RR[i], ccx = CC[o], ccy = CC[o + 1], ccz = CC[o + 2], vo = i * RV * 3;
for (j = 0; j < RV; j++) {
var cj = COSJ[j], sj = SINJ[j];
var rr = r * (1 + (cj > 0 ? 0.10 * cj * cj * cj : 0)); // slight dorsal ridge
x = nx * cj + bx * sj; y = ny * cj + by * sj; z = nz * cj + bz * sj;
bPos[vo] = ccx + x * rr; bPos[vo + 1] = ccy + y * rr; bPos[vo + 2] = ccz + z * rr;
bNor[vo] = x; bNor[vo + 1] = y; bNor[vo + 2] = z;
vo += 3;
}
}
bPosA.needsUpdate = true; bNorA.needsUpdate = true;
bodyGeo.setDrawRange(0, (n - 1) * RAD * 6);
// ---- dorsal fin / mane
var rs = rMax / 0.55, sweep = 0.55 + 0.5 * boost, fo, h, sway, fr, f;
var lastO = (n - 1) * 3;
for (i = 0; i < n; i++) {
o = i * 3; s = i / L1; if (s > 1) s = 1;
h = (0.38 + 1.10 * Math.exp(-i / 7.5) + 0.34 * sstep(0.66, 0.90, s)) * sstep(0.2, 2.6, i) * (1 - sstep(0.93, 1.0, s)) * rs;
h *= 0.78 + 0.22 * Math.abs(Math.sin(i * 0.7854));
h *= 1 - 0.22 * boost;
sway = h * (0.40 * Math.sin(i * 0.62 - t * 4.6) + 0.18 * Math.sin(i * 0.27 - t * 2.3 + 2.0));
r = RR[i];
fo = (OFF_FIN + i * FROWS) * 3;
for (fr = 0; fr < FROWS; fr++) {
f = fr / (FROWS - 1);
var up = r * 0.8 + (h + r * 0.2) * f, bk = h * sweep * f * f, sw = sway * f * f;
rPos[fo] = CC[o] + NN[o] * up - TT[o] * bk + BB[o] * sw;
rPos[fo + 1] = CC[o + 1] + NN[o + 1] * up - TT[o + 1] * bk + BB[o + 1] * sw;
rPos[fo + 2] = CC[o + 2] + NN[o + 2] * up - TT[o + 2] * bk + BB[o + 2] * sw;
fo += 3;
}
}
var fEnd = Math.min(MAXP, Math.max(finWritten, n + 1));
for (i = n; i < fEnd; i++) {
fo = (OFF_FIN + i * FROWS) * 3;
for (fr = 0; fr < FROWS; fr++) { rPos[fo] = CC[lastO]; rPos[fo + 1] = CC[lastO + 1]; rPos[fo + 2] = CC[lastO + 2]; fo += 3; }
}
finWritten = n;
// ---- tail tuft
var ttx = -TT[lastO], tty = -TT[lastO + 1], ttz = -TT[lastO + 2];
var tlen = 1.9 * rs, tsp = 0.62 * rs, u, wv, wd, pc, ps, vo2;
for (l = 0; l < TL; l++) {
var phi = l * TAU / TL + 0.5, cph = Math.cos(phi), sph = Math.sin(phi);
var ll = tlen * (l === 0 ? 1.25 : (0.85 + 0.12 * (l % 3)));
for (k = 0; k < TK; k++) {
u = k / (TK - 1);
var out = tsp * u * (1.3 - 0.5 * u) * (1 - 0.4 * boost), al = ll * u;
wv = 0.20 * u * Math.sin(t * 5.2 - u * 3.4 + l * 1.7);
pc = cph * out - sph * wv; ps = sph * out + cph * wv;
x = CC[lastO] + ttx * al + NN[lastO] * pc + BB[lastO] * ps;
y = CC[lastO + 1] + tty * al + NN[lastO + 1] * pc + BB[lastO + 1] * ps;
z = CC[lastO + 2] + ttz * al + NN[lastO + 2] * pc + BB[lastO + 2] * ps;
wd = 0.30 * rs * Math.pow(Math.sin(PI * Math.min(1, 0.06 + u * 0.94)), 0.7);
var qx = (-sph * NN[lastO] + cph * BB[lastO]) * wd, qy = (-sph * NN[lastO + 1] + cph * BB[lastO + 1]) * wd, qz = (-sph * NN[lastO + 2] + cph * BB[lastO + 2]) * wd;
vo2 = (OFF_TUFT + (l * TK + k) * 2) * 3;
rPos[vo2] = x - qx; rPos[vo2 + 1] = y - qy; rPos[vo2 + 2] = z - qz;
rPos[vo2 + 3] = x + qx; rPos[vo2 + 4] = y + qy; rPos[vo2 + 5] = z + qz;
}
}
// ---- whiskers and chin tendrils (follow-the-leader chains in world space)
var c, wo, po, seg, side, tgx, tgy, tgz, rdx, rdy, rdz, kk;
for (c = 0; c < NCH; c++) {
wo = c * WN * 3; seg = WH_SEG[c]; side = WH_SIDE[c];
var wax = WH_AX[c] * HSC, way = WH_AY[c] * HSC, waz = WH_AZ[c] * HSC;
wh[wo] = p0.x + hxx * wax + hyx * way + dzx * waz;
wh[wo + 1] = p0.y + hxy * wax + hyy * way + dzy * waz;
wh[wo + 2] = p0.z + hxz * wax + hyz * way + dzz * waz;
for (k = 1; k < WN; k++) {
u = k / (WN - 1); o = wo + k * 3; po = o - 3;
var ox, oy, oz, swv = Math.sin(t * 2.4 - k * 0.55 + c * 1.9), swh = Math.sin(t * 1.7 - k * 0.4 + c * 0.7);
if (WH_LONG[c]) { ox = side * (0.95 * (1 - u) * (1 - u) + 0.10) + 0.16 * swh * u; oy = 0.22 - 0.55 * u + 0.24 * swv * u; oz = 0.30 - 1.5 * u; }
else { ox = side * 0.12 + 0.12 * swh * u; oy = -0.75 + 0.5 * u + 0.12 * swv * u; oz = -0.25 - 1.0 * u; }
oz -= boost * 0.8;
rdx = hxx * ox + hyx * oy + dzx * oz; rdy = hxy * ox + hyy * oy + dzy * oz; rdz = hxz * ox + hyz * oy + dzz * oz;
len = Math.sqrt(rdx * rdx + rdy * rdy + rdz * rdz) || 1; rdx /= len; rdy /= len; rdz /= len;
tgx = wh[po] + rdx * seg; tgy = wh[po + 1] + rdy * seg; tgz = wh[po + 2] + rdz * seg;
if (!whInit) { wh[o] = tgx; wh[o + 1] = tgy; wh[o + 2] = tgz; continue; }
kk = 1 - Math.exp(-dt * (16 - 10 * u));
wh[o] += mvx; wh[o + 1] += mvy; wh[o + 2] += mvz;
x = wh[o] + (tgx - wh[o]) * kk - wh[po]; y = wh[o + 1] + (tgy - wh[o + 1]) * kk - wh[po + 1]; z = wh[o + 2] + (tgz - wh[o + 2]) * kk - wh[po + 2];
len = Math.sqrt(x * x + y * y + z * z);
if (len > 1e-5 && fin(len)) { x *= seg / len; y *= seg / len; z *= seg / len; } else { x = rdx * seg; y = rdy * seg; z = rdz * seg; }
wh[o] = wh[po] + x; wh[o + 1] = wh[po + 1] + y; wh[o + 2] = wh[po + 2] + z;
}
for (k = 0; k < WN; k++) {
u = k / (WN - 1); o = wo + k * 3;
var oA = wo + Math.max(k - 1, 0) * 3, oB = wo + Math.min(k + 1, WN - 1) * 3;
tx = wh[oB] - wh[oA]; ty = wh[oB + 1] - wh[oA + 1]; tz = wh[oB + 2] - wh[oA + 2];
// a1 = t x headUp, a2 = t x a1
var a1x = ty * hyz - tz * hyy, a1y = tz * hyx - tx * hyz, a1z = tx * hyy - ty * hyx;
len = Math.sqrt(a1x * a1x + a1y * a1y + a1z * a1z);
if (len < 1e-5) { a1x = hxx; a1y = hxy; a1z = hxz; len = 1; }
a1x /= len; a1y /= len; a1z /= len;
var a2x = ty * a1z - tz * a1y, a2y = tz * a1x - tx * a1z, a2z = tx * a1y - ty * a1x;
len = Math.sqrt(a2x * a2x + a2y * a2y + a2z * a2z);
if (len < 1e-5) { a2x = hyx; a2y = hyy; a2z = hyz; len = 1; }
a2x /= len; a2y /= len; a2z /= len;
wd = WH_W[c] * Math.pow(1 - u, 0.8) + 0.007;
vo2 = (OFF_WH + (c * WN + k) * 4) * 3;
x = wh[o]; y = wh[o + 1]; z = wh[o + 2];
rPos[vo2] = x - a1x * wd; rPos[vo2 + 1] = y - a1y * wd; rPos[vo2 + 2] = z - a1z * wd;
rPos[vo2 + 3] = x + a1x * wd; rPos[vo2 + 4] = y + a1y * wd; rPos[vo2 + 5] = z + a1z * wd;
rPos[vo2 + 6] = x - a2x * wd; rPos[vo2 + 7] = y - a2y * wd; rPos[vo2 + 8] = z - a2z * wd;
rPos[vo2 + 9] = x + a2x * wd; rPos[vo2 + 10] = y + a2y * wd; rPos[vo2 + 11] = z + a2z * wd;
}
}
whInit = true;
// ---- pectoral / pelvic fins
var iHind = Math.min(n - 2, Math.round(5 + 0.40 * (n - 1)));
for (l = 0; l < PF; l++) {
var fi = l < 2 ? Math.min(5, n - 1) : iHind; side = (l & 1) ? -1 : 1;
o = fi * 3; r = RR[fi];
var fl = (l < 2 ? 1.75 : 1.25) * rs * (0.75 + 0.25 * clamp01((nf - 14) / 30));
var flap = 0.30 * Math.sin(t * 3.1 + (l < 2 ? 0 : 1.6)) - 0.12 - 0.25 * boost;
var cf = Math.cos(flap), sf = Math.sin(flap);
// out' = side*B*cos(flap) + N*sin(flap)
var oxx = BB[o] * side * cf + NN[o] * sf, oxy = BB[o + 1] * side * cf + NN[o + 1] * sf, oxz = BB[o + 2] * side * cf + NN[o + 2] * sf;
var bsx = CC[o] + BB[o] * side * r * 0.78 - NN[o] * r * 0.25, bsy = CC[o + 1] + BB[o + 1] * side * r * 0.78 - NN[o + 1] * r * 0.25, bsz = CC[o + 2] + BB[o + 2] * side * r * 0.78 - NN[o + 2] * r * 0.25;
for (k = 0; k < PM; k++) {
u = k / (PM - 1);
var th = -0.15 + u * 1.25 + boost * 0.45, ct = Math.cos(th), sth = Math.sin(th);
var fl2 = fl * (0.62 + 0.38 * Math.sin(PI * (0.15 + 0.7 * u))) * ((k & 1) ? 0.80 : 1.0);
vo2 = (OFF_PEC + (l * PM + k) * 2) * 3;
rPos[vo2] = bsx - TT[o] * r * 0.5 * u; rPos[vo2 + 1] = bsy - TT[o + 1] * r * 0.5 * u; rPos[vo2 + 2] = bsz - TT[o + 2] * r * 0.5 * u;
rPos[vo2 + 3] = bsx + (oxx * ct - TT[o] * sth) * fl2;
rPos[vo2 + 4] = bsy + (oxy * ct - TT[o + 1] * sth) * fl2;
rPos[vo2 + 5] = bsz + (oxz * ct - TT[o + 2] * sth) * fl2;
}
}
// ---- boost streaks (shader fades them out when boost is 0)
if (boost > 0.003) {
for (l = 0; l < SL; l++) {
var sphi = 0.785 + l * TAU / SL + t * 0.7, cs = Math.cos(sphi), ss = Math.sin(sphi);
for (k = 0; k < SN; k++) {
i = 1 + k; if (i > n - 1) i = n - 1; o = i * 3;
var sr = RR[i] + 0.32 + 0.012 * k;
x = CC[o] + (NN[o] * cs + BB[o] * ss) * sr; y = CC[o + 1] + (NN[o + 1] * cs + BB[o + 1] * ss) * sr; z = CC[o + 2] + (NN[o + 2] * cs + BB[o + 2] * ss) * sr;
wd = 0.10 + 0.05 * boost;
var sxx = (-NN[o] * ss + BB[o] * cs) * wd, sxy = (-NN[o + 1] * ss + BB[o + 1] * cs) * wd, sxz = (-NN[o + 2] * ss + BB[o + 2] * cs) * wd;
vo2 = (OFF_ST + (l * SN + k) * 2) * 3;
rPos[vo2] = x - sxx; rPos[vo2 + 1] = y - sxy; rPos[vo2 + 2] = z - sxz;
rPos[vo2 + 3] = x + sxx; rPos[vo2 + 4] = y + sxy; rPos[vo2 + 5] = z + sxz;
}
}
}
rPosA.needsUpdate = true;
// ---- glow quads: head aura, eyes, antler tips, wisp-lanterns, body haze, tail
gq = 0;
var gc = pal.glow, ec = pal.eye, wc, hb = 1 - 0.6 * hurt * (0.5 + 0.5 * Math.sin(t * 38));
quad(p0.x + dzx * 0.4 + hyx * 0.2, p0.y + dzy * 0.4 + hyy * 0.2, p0.z + dzz * 0.4 + hyz * 0.2,
3.6 + 2.0 * glow + 1.2 * boost, gc[0], gc[1], gc[2], (0.09 + 0.55 * glow + 0.25 * boost) * hb, 0);
for (side = -1; side <= 1; side += 2) {
var ex = (EYE[0] + 0.08) * side * HSC, ey = EYE[1] * HSC, ez = (EYE[2] + 0.03) * HSC;
quad(p0.x + hxx * ex + hyx * ey + dzx * ez, p0.y + hxy * ex + hyy * ey + dzy * ez, p0.z + hxz * ex + hyz * ey + dzz * ez,
0.42, ec[0], ec[1], ec[2], 0.55 * hb, 0);
ex = HORN_TIP[0] * side * HSC; ey = HORN_TIP[1] * HSC; ez = HORN_TIP[2] * HSC;
quad(p0.x + hxx * ex + hyx * ey + dzx * ez, p0.y + hxy * ex + hyy * ey + dzy * ez, p0.z + hxz * ex + hyz * ey + dzz * ez,
0.26 + 0.5 * glow, pal.hornTip[0], pal.hornTip[1], pal.hornTip[2], 0.45 + 0.6 * glow, 0);
}
var wi = 0;
for (i = 12; i < n; i += 6) {
o = i * 3;
var ap = clamp01((nf - i) * 0.6); wi++;
var wa = t * 1.5 + wi * 2.399, wr = RR[i] + 0.46 + 0.10 * Math.sin(t * 2.1 + wi), cw = Math.cos(wa), sw2 = Math.sin(wa);
var along = 0.18 * Math.sin(t * 1.6 + wi * 1.3);
wc = (wi & 1) ? pal.wisp : pal.wisp2;
quad(CC[o] + (NN[o] * cw + BB[o] * sw2) * wr + TT[o] * along,
CC[o + 1] + (NN[o + 1] * cw + BB[o + 1] * sw2) * wr + TT[o + 1] * along,
CC[o + 2] + (NN[o + 2] * cw + BB[o + 2] * sw2) * wr + TT[o + 2] * along,
(0.62 + 0.10 * Math.sin(t * 3.3 + wi * 1.1) + 0.25 * glow) * ap, wc[0], wc[1], wc[2], 0.68 + 0.6 * glow, 1);
}
if (!LOW) {
for (i = 3; i < n - 2; i += 9) {
o = i * 3; s = i / L1; if (s > 1) s = 1;
var m1 = sstep(0.02, 0.5, s), m2 = sstep(0.5, 1, s);
x = pal.A[0] + (pal.B[0] - pal.A[0]) * m1; y = pal.A[1] + (pal.B[1] - pal.A[1]) * m1; z = pal.A[2] + (pal.B[2] - pal.A[2]) * m1;
x += (pal.C[0] - x) * m2; y += (pal.C[1] - y) * m2; z += (pal.C[2] - z) * m2;
quad(CC[o], CC[o + 1], CC[o + 2], RR[i] * 5.5 + 0.5, x * 0.6 + gc[0] * 0.4, y * 0.6 + gc[1] * 0.4, z * 0.6 + gc[2] * 0.4,
(0.06 + 0.30 * glow + 0.12 * boost) * hb, 0);
}
}
o = lastO;
quad(CC[o] + ttx * 0.7, CC[o + 1] + tty * 0.7, CC[o + 2] + ttz * 0.7, 1.7 * rs + glow, pal.finEdge[0], pal.finEdge[1], pal.finEdge[2], 0.25 + 0.4 * glow, 0);
gPosA.needsUpdate = true; gColA.needsUpdate = true; gPrmA.needsUpdate = true;
glowGeo.setDrawRange(0, gq * 6);
first = false;
}
function dispose() {
if (group.parent) group.parent.remove(group);
bodyGeo.dispose(); headGeo.dispose(); ribGeo.dispose(); glowGeo.dispose();
bodyMat.dispose(); headMat.dispose(); ribMat.dispose(); glowMat.dispose();
}
return {
update: update,
head: head,
group: group,
setPalette: setPalette,
setLight: function (v) { if (v && fin(v.x) && v.lengthSq() > 1e-8) uLight.value.copy(v).normalize(); },
dispose: dispose,
stats: {
drawCalls: 4,
maxTriangles: (MAXP - 1) * RAD * 2 + headTris + ribTris + MAXQ * 2,
buffers: { bodyPos: bPos, bodyNor: bNor, ribPos: rPos, glowPos: gPos }
}
};
}
/* ================= RENDERER ================= */
const canvas=$('c');
const MOBILE=/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)||(navigator.maxTouchPoints>1&&/Mac/.test(navigator.platform||''));
const QUALITY=MOBILE?'low':'high';
const renderer=new THREE.WebGLRenderer({canvas,antialias:!MOBILE,powerPreference:'high-performance'});
let pixR=Math.min(window.devicePixelRatio||1,MOBILE?1.5:2);renderer.setPixelRatio(pixR);
const scene=new THREE.Scene();scene.background=new THREE.Color(0x0e1420);
const camera=new THREE.PerspectiveCamera(60,1,0.3,1200);
let VW=1,VH=1;
function resize(){VW=window.innerWidth;VH=window.innerHeight;renderer.setSize(VW,VH,false);camera.aspect=VW/VH;camera.fov=VW<VH?76:60;camera.updateProjectionMatrix()}
window.addEventListener('resize',resize);window.addEventListener('orientationchange',()=>setTimeout(resize,200));resize();
function glowTex(){const c=document.createElement('canvas');c.width=c.height=64;const g=c.getContext('2d'),r=g.createRadialGradient(32,32,0,32,32,32);
r.addColorStop(0,'rgba(255,255,255,1)');r.addColorStop(.18,'rgba(255,255,255,.85)');r.addColorStop(.45,'rgba(255,255,255,.22)');r.addColorStop(1,'rgba(255,255,255,0)');g.fillStyle=r;g.fillRect(0,0,64,64);return new THREE.CanvasTexture(c)}
const GLOW=glowTex();
/* ================= WORLD + SNAKE ================= */
const VALES=[{id:'dawn',name:'Dawn Vale',seed:11},{id:'ember',name:'Ember Canyon',seed:23},{id:'moon',name:'Moonlit Ruins',seed:37}];
let W=null,D=null,vIdx=-1,LM=null;
const MAXP=420,SP=0.45,HOVER=2.3,GROW=4,GROWH=5,LAPB=100,PENT=[0,2,4,7,9,12,14,16,19];let pulseP=-1,combo=0,lastEatT=-99,comboWin=2.5,mile=0,mileP=0,lapBanT=-99;
const pts=[],trail=[];for(let i=0;i<MAXP;i++)pts.push(new THREE.Vector3());for(let i=0;i<=MAXP;i++)trail.push(new THREE.Vector3());
function loadRealm(i){
if(vIdx===i&&W)return;
if(W){try{W.dispose()}catch(e){}}
vIdx=i;W=createWorld(THREE,scene,{theme:VALES[i].id,seed:VALES[i].seed,quality:QUALITY});LM=W.landmarks;
if(!D)D=createDragon(THREE,scene,{maxPoints:MAXP,quality:QUALITY});
try{D.setPalette(VALES[i].id)}catch(e){}
try{if(D.setLight&&W.sunDir)D.setLight(W.sunDir)}catch(e){}
progK=0;MUS.setRealm(VALES[i].id);
}
const groundAt=(x,z)=>Math.max(W.heightAt(x,z),W.waterY);
/* ---------- food, bonus, particles ---------- */
// all the lights of a lap are out at once: one instanced orb mesh plus one glow point each; the bonus glow is the last point
const LTMAX=64;let ltX=new Float32Array(LTMAX),ltY=new Float32Array(LTMAX),ltZ=new Float32Array(LTMAX),ltE=new Uint8Array(LTMAX),nbX=new Float32Array(LTMAX),nbY=new Float32Array(LTMAX),nbZ=new Float32Array(LTMAX),nbE=new Uint8Array(LTMAX),nbN=0,nbW=0,nbS=0,ltN=0,ltLeft=0,lapN=0,nI=-1,nI2=-1;
const fPos=new Float32Array((LTMAX+1)*3),fCol=new Float32Array((LTMAX+1)*3);for(let i=0;i<=LTMAX;i++)fPos[i*3+1]=-9999;
const fGeo=new THREE.BufferGeometry();fGeo.setAttribute('position',new THREE.BufferAttribute(fPos,3));fGeo.setAttribute('color',new THREE.BufferAttribute(fCol,3));
const fPts=new THREE.Points(fGeo,new THREE.PointsMaterial({size:11,map:GLOW,vertexColors:true,transparent:true,blending:THREE.AdditiveBlending,depthWrite:false,fog:false,sizeAttenuation:true}));
fPts.frustumCulled=false;fPts.renderOrder=5;scene.add(fPts);
function orbMesh(col){const m=new THREE.Mesh(new THREE.IcosahedronGeometry(.75,1),new THREE.MeshBasicMaterial({color:col,fog:false}));scene.add(m);return m}
function beamMesh(col){const m=new THREE.Mesh(new THREE.CylinderGeometry(.55,.55,1,10,1,true),new THREE.MeshBasicMaterial({color:col,transparent:true,opacity:.22,blending:THREE.AdditiveBlending,depthWrite:false,fog:false,side:THREE.DoubleSide}));m.renderOrder=3;m.scale.y=90;scene.add(m);return m}
const ltOrb=new THREE.InstancedMesh(new THREE.IcosahedronGeometry(.75,1),new THREE.MeshBasicMaterial({color:0xffe9a8,fog:false}),LTMAX);ltOrb.frustumCulled=false;ltOrb.count=0;scene.add(ltOrb);const m4=new THREE.Matrix4();
// food = the nearest light not yet eaten (it carries the bright beam; the second nearest gets a faint one)
const food={x:0,y:0,z:0,beam:beamMesh(0xf2c46d),beam2:beamMesh(0xf2c46d)};
const bonus={on:false,x:0,y:0,z:0,ttl:0,orb:orbMesh(0x8ff5e6),beam:beamMesh(0x6fe0d0)};bonus.orb.visible=bonus.beam.visible=false;
const PN=420,pPos=new Float32Array(PN*3),pCol=new Float32Array(PN*3),pVel=new Float32Array(PN*3),pBase=new Float32Array(PN*3),pLife=new Float32Array(PN),pMax=new Float32Array(PN),pGrav=new Float32Array(PN);let pNext=0;
for(let i=0;i<PN;i++)pPos[i*3+1]=-9999;
const pGeo=new THREE.BufferGeometry();pGeo.setAttribute('position',new THREE.BufferAttribute(pPos,3));pGeo.setAttribute('color',new THREE.BufferAttribute(pCol,3));
const pPts=new THREE.Points(pGeo,new THREE.PointsMaterial({size:1.6,map:GLOW,vertexColors:true,transparent:true,blending:THREE.AdditiveBlending,depthWrite:false,fog:false,sizeAttenuation:true}));
pPts.frustumCulled=false;pPts.renderOrder=6;scene.add(pPts);
function emit(x,y,z,n,spd,r,g,b,life,grav){
for(let k=0;k<n;k++){const i=pNext;pNext=(pNext+1)%PN;const a=Math.random()*6.283,u=Math.random()*2-1,s=Math.sqrt(1-u*u),v=spd*(.35+Math.random()*.65);
pPos[i*3]=x;pPos[i*3+1]=y;pPos[i*3+2]=z;pVel[i*3]=Math.cos(a)*s*v;pVel[i*3+1]=u*v;pVel[i*3+2]=Math.sin(a)*s*v;pBase[i*3]=r;pBase[i*3+1]=g;pBase[i*3+2]=b;pLife[i]=pMax[i]=life*(.6+Math.random()*.4);pGrav[i]=grav||0}
}
function updParticles(dt){
for(let i=0;i<PN;i++){if(pLife[i]<=0)continue;pLife[i]-=dt;const j=i*3;
if(pLife[i]<=0){pPos[j+1]=-9999;pCol[j]=pCol[j+1]=pCol[j+2]=0;continue}
pVel[j+1]-=pGrav[i]*dt;pPos[j]+=pVel[j]*dt;pPos[j+1]+=pVel[j+1]*dt;pPos[j+2]+=pVel[j+2]*dt;const f=pLife[i]/pMax[i];pCol[j]=pBase[j]*f;pCol[j+1]=pBase[j+1]*f;pCol[j+2]=pBase[j+2]*f}
pGeo.attributes.position.needsUpdate=true;pGeo.attributes.color.needsUpdate=true;
}
const v1=new THREE.Vector3(),v2=new THREE.Vector3(),hit={x:0,y:0,z:0,d:0};
// path guide: dots on the ground ahead. Mint means clear, red means blocked.
const GN=8,guideGeo=new THREE.BufferGeometry();guideGeo.setAttribute('position',new THREE.BufferAttribute(new Float32Array(GN*3),3));guideGeo.setAttribute('color',new THREE.BufferAttribute(new Float32Array(GN*3),3));
const guide=new THREE.Points(guideGeo,new THREE.PointsMaterial({size:.6,vertexColors:true,transparent:true,opacity:.9,depthWrite:false,fog:false}));guide.frustumCulled=false;guide.visible=false;guide.renderOrder=3;scene.add(guide);
function updGuide(){
guide.visible=state==='play'&&(OPT.diff==='zen'||OPT.diff==='easy');if(!guide.visible)return;
const P=guideGeo.attributes.position.array,C=guideGeo.attributes.color.array,fx=Math.sin(yaw),fz=Math.cos(yaw);let h0=groundAt(pos.x,pos.z),bad=false;
for(let i=0;i<GN;i++){const d=2.6*(i+1),x=pos.x+fx*d,z=pos.z+fz*d,h=groundAt(x,z);
if(!bad&&(h-h0>4.2||Math.abs(x)>W.half-3||Math.abs(z)>W.half-3||(mapR>0&&Math.hypot(x-cx,z-cz)>mapR)||(W.collide({x,y:h+HOVER,z},.7,hit)&&Math.abs(hit.y)<.85)))bad=true;
P[i*3]=x;P[i*3+1]=h+.45;P[i*3+2]=z;C[i*3]=bad?1:.55;C[i*3+1]=bad?.22:1;C[i*3+2]=bad?.16:.85;h0=h}
guideGeo.attributes.position.needsUpdate=true;guideGeo.attributes.color.needsUpdate=true;
}
const wall=new THREE.Mesh(new THREE.CylinderGeometry(1,1,1,72,1,true),new THREE.MeshBasicMaterial({color:0x8fe8d8,transparent:true,opacity:.13,blending:THREE.AdditiveBlending,depthWrite:false,fog:false,side:THREE.DoubleSide}));wall.renderOrder=2;wall.visible=false;scene.add(wall);
/* ================= INPUT: left or right, nothing else ================= */
const keys={},touches=new Map();let touchSide=0;
function setSide(){touchSide=0;for(const s of touches.values())touchSide=s;}
canvas.addEventListener('pointerdown',e=>{if(state!=='play')return;touches.set(e.pointerId,e.clientX<VW/2?-1:1);setSide();press(e.clientX<VW/2?-1:1);try{canvas.setPointerCapture(e.pointerId)}catch(_){}});
function tEnd(e){if(touches.delete(e.pointerId))setSide()}
window.addEventListener('pointerup',tEnd);window.addEventListener('pointercancel',tEnd);
['gesturestart','gesturechange','gestureend'].forEach(ev=>document.addEventListener(ev,e=>e.preventDefault()));
document.addEventListener('touchmove',e=>{if(state==='play'||e.touches.length>1)e.preventDefault()},{passive:false});
let lastTE=0;document.addEventListener('touchend',e=>{const t=Date.now();if(t-lastTE<350&&state==='play')e.preventDefault();lastTE=t},{passive:false});
document.addEventListener('dblclick',e=>e.preventDefault());
canvas.addEventListener('contextmenu',e=>e.preventDefault());
function primary(){if(state==='menu'){if(paused)resume();else startRealm(selV)}else if(state==='over'&&!$('over').hidden)startRealm(vIdx)}
window.addEventListener('keydown',e=>{
const k=e.key.toLowerCase();
if([' ','arrowup','arrowdown','arrowleft','arrowright'].includes(k))e.preventDefault();
if(e.repeat)return;keys[k]=true;
if(k==='arrowleft'||k==='a')press(-1);else if(k==='arrowright'||k==='d')press(1);
if(k==='escape'||k==='h'||k==='p'){if(state==='menu'&&paused)resume();else goHome()}
if(k==='m')setMuted(!muted);
if((k==='enter'||k===' ')&&!(document.activeElement&&document.activeElement.tagName==='BUTTON'))primary();
if(state!=='play'&&['arrowup','arrowdown','arrowleft','arrowright'].includes(k))nav(k.slice(5));
});
window.addEventListener('keyup',e=>{keys[e.key.toLowerCase()]=false});
window.addEventListener('blur',()=>{for(const k in keys)keys[k]=false;touches.clear();touchSide=0});
let rsx=0,rsy=0,camOrb=0,camZoom=1,orbT=9,gpBtn=false,gpOpt=false,gpBack=false,gpUsed=false,gx=0,gpNavT=0,curPad=null;
function rumble(ms,strong,weak){try{const a=curPad&&curPad.vibrationActuator;if(a&&a.playEffect)a.playEffect('dual-rumble',{duration:ms,strongMagnitude:strong,weakMagnitude:weak})}catch(e){}}
function navRoot(){return !$('over').hidden?$('over'):$('menu')}
function nav(d){
const l=[...navRoot().querySelectorAll('button')].filter(b=>!b.hidden&&b.offsetParent!==null);if(!l.length)return;
let cur=document.activeElement;if(l.indexOf(cur)<0){(navRoot()===$('over')?$('oA'):$('r'+selV)).focus();return}
const r=cur.getBoundingClientRect(),mx=r.left+r.width/2,my=r.top+r.height/2;let best=null,bs=1e9;
for(const b of l){if(b===cur)continue;const q=b.getBoundingClientRect(),dx=q.left+q.width/2-mx,dy=q.top+q.height/2-my;let sc;
if(d==='left'){if(dx>-6||Math.abs(dy)>r.height*.7)continue;sc=-dx+Math.abs(dy)*3}else if(d==='right'){if(dx<6||Math.abs(dy)>r.height*.7)continue;sc=dx+Math.abs(dy)*3}
else if(d==='up'){if(dy>-6)continue;sc=-dy*3+Math.abs(dx)}else{if(dy<6)continue;sc=dy*3+Math.abs(dx)}
if(sc<bs){bs=sc;best=b}}
if(best)best.focus();
}
window.addEventListener('gamepadconnected',()=>{if(state==='play')tip('Controller ready.',2)});
function pollPad(){
gx=0;rsx=0;rsy=0;let pads=[];try{pads=navigator.getGamepads?navigator.getGamepads():[]}catch(e){}let gp=null;
for(const p of pads)if(p&&p.connected){gp=p;break}
curPad=gp;if(!gp){gpBtn=gpOpt=gpBack=false;return}
const a=gp.axes[0]||0,ay=gp.axes[1]||0;gx=Math.abs(a)<.2?0:a;
const b=i=>!!(gp.buttons[i]&&gp.buttons[i].pressed);
{const rx=gp.axes[2]||0,ry=gp.axes[3]||0;rsx=Math.abs(rx)<.2?0:rx;rsy=Math.abs(ry)<.25?0:ry;if(b(11)){camOrb=0;camZoom=1}}
if(b(14)||b(4)||b(6))gx=-1;if(b(15)||b(5)||b(7))gx=1;
{gpSt=a>.6?1:a<-.6?-1:Math.abs(a)<.3?0:gpSt;const bd=(b(15)||b(5)||b(7)?1:0)-(b(14)||b(4)||b(6)?1:0),gd=bd||gpSt;if(gd&&gd!==gpPrev)press(gd);gpPrev=gd}
const x=b(0),opt=b(9),back=b(1);if(gx||x||opt||back||b(12)||b(13))gpUsed=true;
if(state!=='play'){
const d=b(12)||ay<-.6?'up':b(13)||ay>.6?'down':b(14)||a<-.6?'left':b(15)||a>.6?'right':null,now=performance.now();
if(!d)gpNavT=0;else if(now>gpNavT){const rep=gpNavT;nav(d);gpNavT=performance.now()+(rep?170:380)}
if(x&&!gpBtn){const f=document.activeElement;if(f&&f.tagName==='BUTTON'&&navRoot().contains(f)&&!f.hidden)f.click();else primary()}
if(back&&!gpBack){if(state==='over')goHome();else if(paused)resume()}
}
if(opt&&!gpOpt){if(state==='menu'&&paused)resume();else goHome()}
gpBtn=x;gpOpt=opt;gpBack=back;
}
const test={on:false,x:0,press:d=>press(d)};
// classic turns: one press queues one exact quarter turn (at most 2 waiting), done as a quick ease; holding does nothing more
const CT=.15,cqA=new Int8Array(2);let cqN=0,cDir=0,cT=0,gpSt=0,gpPrev=0;
function press(d){if(OPT.turn!=='classic'||state!=='play'||!d)return;if(cqN<2)cqA[cqN++]=d>0?1:-1}
function readTurn(){
let x=((keys['arrowright']||keys['d'])?1:0)-((keys['arrowleft']||keys['a'])?1:0)+touchSide+gx;
if(test.on)x=test.x;
return clamp(x,-1,1);
}
/* ================= GAME ================= */
const VDEF={dawn:{diff:'normal',spd:'fast',size:'large',turn:'smooth'},ember:{diff:'normal',spd:'normal',size:'medium',turn:'smooth'},moon:{diff:'zen',spd:'slow',size:'small',turn:'smooth'}};
const OPT={diff:'normal',spd:'fast',size:'large',turn:'smooth'};
let selV=clamp(store.get('sel',0)|0,0,2);
// each valley has its own defaults; a choice the player makes is kept for that valley
function applyVale(i){const id=VALES[i].id,sv=(store.get('vopt',{})||{})[id]||{};for(const k in OPT){const v=sv[k];OPT[k]=typeof v==='string'&&document.querySelector('.seg[data-opt="'+k+'"] button[data-v="'+v+'"]')?v:VDEF[id][k]}}
function selectVale(i,quiet){
const ch=i!==selV;selV=i;store.set('sel',i);applyVale(i);
if(ch&&paused){paused=false;$('resume').hidden=true;MUS.setMood('menu')}
if(state==='menu'&&!paused&&booted){if(vIdx!==i){loadRealm(i);const st=LM.start;camPos.set(st.x,st.y+10,st.z+34);camLook.set(st.x,st.y,st.z);pos.set(st.x,st.y,st.z);fillTrail()}else MUS.setRealm(VALES[i].id)}
menuInfo();
}
const BASE={slow:7.5,normal:10,fast:13},RAMP={zen:.12,easy:.12,normal:.13,hard:.14},MULT={zen:1,easy:1,normal:2,hard:3},MAPR={small:42,medium:82,large:0};
let cx=0,cz=0,mapR=0;
let state='menu',paused=false,mode=OPT.diff==='zen'?'zen':'classic',foods=0,score=0,nCur=14,nTarget=14,speed=10,yaw=0,pitchV=0,roll=0,hurt=0,glow=0,shake=0,tipT=0,progK=0,menuA=0,fps=60,lowT=0,overT=0,gtime=0,safeT=0,scrapeCd=0,cliffCd=0,camR=0;
const v3=new THREE.Vector3(),pos=new THREE.Vector3(),dir=new THREE.Vector3(0,0,1),camPos=new THREE.Vector3(),camLook=new THREE.Vector3();
const bestKey=()=>VALES[vIdx].id+'.'+OPT.diff;
const nPts=()=>Math.min(MAXP,Math.floor(nCur));
function tip(s,sec){const e=$('tip');e.textContent=s;e.classList.add('show');tipT=sec||3.5}
function banner(a,b,sm){const e=$('banner');e.classList.toggle('sm',!!sm);e.textContent='';e.appendChild(document.createTextNode(a));if(b){const s=document.createElement('small');s.textContent=b;e.appendChild(s)}e.classList.remove('go');void e.offsetWidth;e.classList.add('go')}
function fillTrail(){v1.set(Math.sin(yaw),0,Math.cos(yaw));for(let i=0;i<=MAXP;i++){trail[i].copy(pos).addScaledVector(v1,-SP*(i+1));trail[i].y=groundAt(trail[i].x,trail[i].z)+HOVER}}
function advanceTrail(){
let guard=0;
while(trail[0].distanceToSquared(pos)>=SP*SP&&guard++<40){v1.subVectors(pos,trail[0]).normalize().multiplyScalar(SP).add(trail[0]);const l=trail.pop();l.copy(v1);trail.unshift(l)}
const f=1-Math.sqrt(trail[0].distanceToSquared(pos))/SP,n=nPts();pts[0].copy(pos);
for(let i=1;i<n;i++)pts[i].lerpVectors(trail[i-1],trail[i],f);
return n;
}
function gentle(x,z,wet){const h=groundAt(x,z);if(!wet&&W.heightAt(x,z)<W.waterY)return false;for(let j=0;j<8;j++){const a=j*.7854,sx=Math.sin(a),sz=Math.cos(a);if(Math.abs(groundAt(x+sx*3,z+sz*3)-h)>2.2||Math.abs(groundAt(x+sx*8,z+sz*8)-h)>3.6||groundAt(x+sx*14,z+sz*14)-h>6)return false}return true}
function clearLine(x,z){const d=Math.hypot(x-pos.x,z-pos.z),n=Math.ceil(d/3);let h0=groundAt(pos.x,pos.z);for(let i=1;i<=n;i++){const f=i/n,px=pos.x+(x-pos.x)*f,pz=pos.z+(z-pos.z)*f,h=groundAt(px,pz);if(h-h0>3.4)return false;if(i>2&&W.collide({x:px,y:h+HOVER,z:pz},1.2,hit))return false;h0=h}return true}
function placeItem(it,minD,maxD){
const lim=W.half-22;
for(let k=0;k<260;k++){
let x,z;
if(mapR){const r=(mapR-6)*Math.sqrt(Math.random()),a=Math.random()*6.283;x=cx+Math.cos(a)*r;z=cz+Math.sin(a)*r}
else if(k<150){const r=minD+Math.random()*(maxD-minD),a=Math.random()*6.283;x=pos.x+Math.cos(a)*r;z=pos.z+Math.sin(a)*r}
else{x=(Math.random()*2-1)*lim;z=(Math.random()*2-1)*lim}
if(Math.abs(x)>lim||Math.abs(z)>lim)continue;
const d=Math.hypot(x-pos.x,z-pos.z);
if(k<150&&(d<minD||d>maxD))continue;
if(d<10||!gentle(x,z))continue;
const y=groundAt(x,z)+HOVER;if(W.collide({x,y,z},3.2,hit))continue;
if(k<200&&!clearLine(x,z))continue;
let near=false;const n=nPts();for(let i=0;i<n;i+=6)if((pts[i].x-x)**2+(pts[i].z-z)**2<16){near=true;break}
if(near)continue;
it.x=x;it.y=y;it.z=z;return true}
// relaxed fallback, so a light is never left on the head
for(let k=0;k<400;k++){
const R=mapR?mapR-6:60,r=12+Math.random()*(R-12),a=Math.random()*6.283,x=(mapR?cx:pos.x)+Math.cos(a)*r,z=(mapR?cz:pos.z)+Math.sin(a)*r;
if(Math.abs(x)>lim||Math.abs(z)>lim||Math.hypot(x-pos.x,z-pos.z)<8)continue;
const h=groundAt(x,z),y=h+HOVER;if(Math.abs(groundAt(x+3,z)-h)>3||Math.abs(groundAt(x,z+3)-h)>3||W.collide({x,y,z},1.5,hit))continue;
it.x=x;it.y=y;it.z=z;return true}
return false;
}
/* ---------- the lap: a trail of lights that tours the map, all out at once ---------- */
const lq={x:0,y:0,z:0},LO={x:0,z:0,yaw:0,pre:false};let sx=0,sz=0;
// where the snake can fly from here and back: 2.5 m cells, no stone, no step over 3.6 either way (terrain grid kept per valley, flood fill per lap)
const RS=2.5;let rgV=-1,RN=0,RL=0,rgH=null,rgOk=null,rgW=null,rgS=null,rgP=null,rgSeen=null,rgQ=null;
function reachGrid(){
if(rgV!==vIdx){rgV=vIdx;RL=W.half-3;RN=Math.ceil(2*RL/RS)+1;rgH=new Float32Array(RN*RN);rgOk=new Uint8Array(RN*RN);rgW=new Uint8Array(RN*RN);rgS=new Uint8Array(RN*RN);rgP=new Uint8Array(RN*RN);rgSeen=new Uint8Array(RN*RN);rgQ=new Int32Array(RN*RN);
for(let i=0;i<RN;i++)for(let j=0;j<RN;j++){const k=i*RN+j;lq.x=-RL+i*RS;lq.z=-RL+j*RS;rgH[k]=groundAt(lq.x,lq.z);lq.y=rgH[k]+HOVER;rgOk[k]=W.collide(lq,.9,hit)&&Math.abs(hit.y)<.85?0:1;rgW[k]=W.heightAt(lq.x,lq.z)<W.waterY?1:0}
// steep cells (a rise over 2 m to a neighbour, or over 3.6 m two cells away) cost more on the route, so the trail keeps to calm ground where lights fit
for(let i=1;i<RN-1;i++)for(let j=1;j<RN-1;j++){const k=i*RN+j,h=rgH[k];let m=0;for(let d=0;d<4;d++){const n=k+(d===0?RN:d===1?-RN:d===2?1:-1);m=Math.max(m,Math.abs(rgH[n]-h))}if(i>1&&j>1&&i<RN-2&&j<RN-2)m=Math.max(m,Math.abs(rgH[k+2*RN]-h)*.55,Math.abs(rgH[k-2*RN]-h)*.55,Math.abs(rgH[k+2]-h)*.55,Math.abs(rgH[k-2]-h)*.55);rgS[k]=m>2?1:0;for(let d=0;d<8&&!(rgS[k]&2);d++)if(!rgOk[k+NBI[d]*RN+NBJ[d]])rgS[k]|=2}}
rgSeen.fill(0);const i0=clamp(Math.round((LO.x+RL)/RS),0,RN-1),j0=clamp(Math.round((LO.z+RL)/RS),0,RN-1);let qn=0;rgQ[qn++]=i0*RN+j0;rgSeen[i0*RN+j0]=1;
while(qn){const k=rgQ[--qn],i=(k/RN)|0,j=k-i*RN;
for(let d=0;d<4;d++){const a=i+(d===0?1:d===1?-1:0),c=j+(d===2?1:d===3?-1:0);if(a<0||c<0||a>=RN||c>=RN)continue;const n=a*RN+c;if(rgSeen[n]||!rgOk[n]||Math.abs(rgH[n]-rgH[k])>3.6)continue;
if(mapR&&Math.hypot(-RL+a*RS-cx,-RL+c*RS-cz)>mapR)continue;rgSeen[n]=1;rgQ[qn++]=n}}
}
function reachable(x,z){const i=Math.round((x+RL)/RS),j=Math.round((z+RL)/RS);return i>=0&&j>=0&&i<RN&&j<RN&&rgSeen[i*RN+j]===1}
// a softer slope rule for lights that keep the chain going: no cliff right at the light (3 m) or close by (6 m)
function soft(x,z){const h=groundAt(x,z);for(let j=0;j<8;j++){const a=j*.7854,sx=Math.sin(a),sz=Math.cos(a);if(Math.abs(groundAt(x+sx*3,z+sz*3)-h)>2.6||Math.abs(groundAt(x+sx*6,z+sz*6)-h)>4.6)return false}return true}
function ltOk(x,z,sf){const tight=sf===2;if(mapR){if(Math.hypot(x-cx,z-cz)>mapR-6)return false}else{const l=W.half-22;if(Math.abs(x)>l||Math.abs(z)>l)return false}
if(!reachable(x,z)||!(sf?soft(x,z):gentle(x,z,true)))return false;return ltClear(x,z,tight?1.2:sf?1.6:2.6)}
// clear of stones, trees and ruins for about 3.5 m (small probes at flying height, so the ground itself does not count)
function ltClear(x,z,rr){rr=rr||2.6;lq.x=x;lq.y=groundAt(x,z)+HOVER;lq.z=z;if(W.collide(lq,rr>2?1.2:rr>1.4?.9:.8,hit))return false;for(let k=0;k<8;k++){lq.x=x+Math.sin(k*.7854)*rr;lq.z=z+Math.cos(k*.7854)*rr;lq.y=groundAt(lq.x,lq.z)+HOVER;if(W.collide(lq,rr>2?1:rr>1.4?.8:.75,hit)&&Math.abs(hit.y)<.85)return false}return true}
function ltFree(x,z,sep){for(let j=0;j<ltN;j++)if((ltX[j]-x)**2+(ltZ[j]-z)**2<sep*sep)return false;if(LO.pre||test.noBody)return true;const n=nPts();for(let i=0;i<n;i+=4)if((pts[i].x-x)**2+(pts[i].z-z)**2<20)return false;return true}
// flyable between two lights: no step over 3.6 every 2.5 m (either way), no stone in the way
function ltSeg(ax,az,bx,bz){const n=Math.ceil(Math.hypot(bx-ax,bz-az)/2.5);let h0=groundAt(ax,az);for(let i=1;i<=n;i++){const f=i/n,x=ax+(bx-ax)*f,z=az+(bz-az)*f,h=groundAt(x,z);if(Math.abs(h-h0)>3.6)return false;lq.x=x;lq.y=h+HOVER;lq.z=z;if(W.collide(lq,.8,hit)&&Math.abs(hit.y)<.85)return false;h0=h}return true}
// nearest valid spot within R metres of (x,z), into sx,sz
function ltSnap(x,z,R,sep){if(ltOk(x,z)&<Free(x,z,sep)){sx=x;sz=z;return true}for(let r=2;r<=R;r+=2)for(let k=0;k<8;k++){const a=k*.7854+r*.4,qx=x+Math.sin(a)*r,qz=z+Math.cos(a)*r;if(ltOk(qx,qz)&<Free(qx,qz,sep)){sx=qx;sz=qz;return true}}return false}
function ltAdd(x,z){ltX[ltN]=x;ltZ[ltN]=z;ltY[ltN]=groundAt(x,z)+HOVER;ltE[ltN]=0;ltN++}
// lap sizes: light count range, spacing (m), spiral radii (m)
const LAPS={large:{n:[46,52],sp:11,ri:40,ro:118},medium:{n:[24,28],sp:10,ri:16,ro:68},small:{n:[13,15],sp:8.5,ri:6,ro:30}};
const RMAX=24000,rtX=new Float32Array(RMAX),rtZ=new Float32Array(RMAX),rtA=new Float32Array(RMAX),wpX=new Float32Array(400),wpZ=new Float32Array(400);let rtN=0,lapWet=0,lapStep=0;
function inArea(x,z,m){return mapR?Math.hypot(x-cx,z-cz)<=mapR-m:Math.abs(x)<=W.half-22&&Math.abs(z)<=W.half-22}
function cellOf(x,z){const i=Math.round((x+RL)/RS),j=Math.round((z+RL)/RS);return i<0||j<0||i>=RN||j>=RN?-1:i*RN+j}
function routable(k){return k>=0&&rgSeen[k]===1&&inArea(-RL+((k/RN)|0)*RS,-RL+(k%RN)*RS,5)}
// nearest routable cell within R cells of (x,z), or -1
// can a light sit in this cell (softer slope rule, tight clearance)? worked out once per cell and kept for the valley
function cellPl(k){if(!rgP[k]){const x=-RL+((k/RN)|0)*RS,z=-RL+(k%RN)*RS;rgP[k]=soft(x,z)&<Clear(x,z,1.2)?1:2}return rgP[k]===1}
function snapCell(x,z,R){const i0=Math.round((x+RL)/RS),j0=Math.round((z+RL)/RS);let best=-1,bd=1e9;
for(let di=-R;di<=R;di++)for(let dj=-R;dj<=R;dj++){const i=i0+di,j=j0+dj;if(i<0||j<0||i>=RN||j>=RN)continue;const d=di*di+dj*dj;if(d<bd&&routable(i*RN+j)){bd=d;best=i*RN+j}}return best}
// A* on the reach grid (8 ways, no corner cutting, no step over 3.6, water costs more): appends the cells after a up to b to the route
const NBI=[1,-1,0,0,1,1,-1,-1],NBJ=[0,0,1,-1,1,-1,1,-1];let lapSt=0,rgUse=null,rgAv=null,hpK=null,hpF=null,rgG=null,rgFrom=null,rgStamp=null,rgClosed=null,rgSt=0,rgTmp=null;
function astar(a,b){
if(!hpK||hpK.length<RN*RN*4){const n=RN*RN;hpK=new Int32Array(n*4);hpF=new Float32Array(n*4);rgG=new Float32Array(n);rgFrom=new Int32Array(n);rgStamp=new Int32Array(n);rgClosed=new Int32Array(n);rgTmp=new Int32Array(n);rgUse=new Int32Array(n);rgAv=new Int32Array(n)}
rgSt++;const bi=(b/RN)|0,bj=b-bi*RN;let hn=0,found=false,guard=0;
const hh=k=>{const di=Math.abs(((k/RN)|0)-bi),dj=Math.abs(k%RN-bj);return (Math.max(di,dj)+.414*Math.min(di,dj))*RS};
const push=(k,f)=>{let i=hn++;while(i>0){const p=(i-1)>>1;if(hpF[p]<=f)break;hpK[i]=hpK[p];hpF[i]=hpF[p];i=p}hpK[i]=k;hpF[i]=f};
const pop=()=>{const top=hpK[0],lk=hpK[--hn],lf=hpF[hn];let i=0;for(;;){let c=2*i+1;if(c>=hn)break;if(c+1<hn&&hpF[c+1]<hpF[c])c++;if(hpF[c]>=lf)break;hpK[i]=hpK[c];hpF[i]=hpF[c];i=c}hpK[i]=lk;hpF[i]=lf;return top};
rgStamp[a]=rgSt;rgG[a]=0;rgFrom[a]=-1;push(a,hh(a));
while(hn&&guard++<RN*RN*2){const k=pop();if(rgClosed[k]===rgSt)continue;rgClosed[k]=rgSt;if(k===b){found=true;break}
const i=(k/RN)|0,j=k-i*RN;
for(let d=0;d<8;d++){const a2=i+NBI[d],c2=j+NBJ[d];if(a2<0||c2<0||a2>=RN||c2>=RN)continue;const n=a2*RN+c2;if(rgClosed[n]===rgSt||!routable(n)||Math.abs(rgH[n]-rgH[k])>3.6)continue;
if(d>3&&(!routable(a2*RN+j)||!routable(i*RN+c2)))continue;
const g=rgG[k]+(d>3?1.414:1)*RS*(rgW[n]?2.5:1)*(rgS[n]&1?2:1)*(rgS[n]&2?2:1)*(cellPl(n)?1:4)*(rgUse[n]===lapSt?4:1)*(rgAv[n]===lapSt?20:1);if(rgStamp[n]===rgSt&&g>=rgG[n])continue;rgStamp[n]=rgSt;rgG[n]=g;rgFrom[n]=k;push(n,g+hh(n))}}
if(!found)return false;
let m=0;for(let k=b;k!==a&&k>=0&&m<rgTmp.length;k=rgFrom[k])rgTmp[m++]=k;
for(let q=m-1;q>=0&&rtN<RMAX;q--){const k=rgTmp[q];for(let d=0;d<8;d++){const n=k+NBI[d]*RN+NBJ[d];if(n>=0&&n<RN*RN)rgUse[n]=lapSt}rgUse[k]=lapSt;const x=-RL+((k/RN)|0)*RS,z=-RL+(k%RN)*RS;rtA[rtN]=rtN?rtA[rtN-1]+Math.hypot(x-rtX[rtN-1],z-rtZ[rtN-1]):0;rtX[rtN]=x;rtZ[rtN]=z;rtN++}
return true;
}
// the plan: a smooth curve that starts ahead of the head, bends gently, then follows a spiral with a slow wave in it
function planLap(P,N,tr){
const hx=Math.sin(LO.yaw),hz=Math.cos(LO.yaw),sm=OPT.size==='small';
let C0=mapR?cx:0,C1=mapR?cz:0;if(sm){C0=(C0+LO.x+hx*12)/2;C1=(C1+LO.z+hz*12)/2;if(tr>1){C0+=(Math.random()-.5)*12;C1+=(Math.random()-.5)*12}}
let px=LO.x+hx*6,pz=LO.z+hz*6,dir=LO.yaw;const a0=Math.atan2(pz-C1,px-C0),r0=Math.hypot(px-C0,pz-C1);
let s=hx*-Math.sin(a0)+hz*Math.cos(a0)>=0?1:-1;if(r0<5)s=Math.random()<.5?1:-1;if(tr&1)s=-s;
const rs=clamp(r0,P.ri,P.ro),re=sm?P.ro:(rs>(P.ri+P.ro)/2?P.ri+(P.ro-P.ri)*.2:P.ro),ph=Math.random()*6.283,wk=2+(Math.random()*2|0),wa=(P.ro-P.ri)*(sm?.06:.14);
const ST=6,L=N*P.sp*1.5;let arc=0,n=0,k=0;
while(arc<L&&n<400){
const u=Math.min(1,arc/(N*P.sp)),e=u*u*(3-2*u),a=Math.atan2(pz-C1,px-C0),rr=Math.max(6,Math.hypot(px-C0,pz-C1)),ta=a+s*Math.min(.9,18/rr);
const tr=clamp(rs+(re-rs)*e+wa*Math.sin(wk*ta+ph),P.ri*.5,P.ro),tx=C0+Math.cos(ta)*tr,tz=C1+Math.sin(ta)*tr;
let want=Math.atan2(tx-px,tz-pz)-dir;while(want>Math.PI)want-=6.283;while(want<-Math.PI)want+=6.283;
const lim=arc<P.sp*5?.07:sm?.32:.2;dir+=clamp(want,-lim,lim);
let nx=px+Math.sin(dir)*ST,nz=pz+Math.cos(dir)*ST;
if(!inArea(nx,nz,8)){let w2=(mapR?Math.atan2(cx-px,cz-pz):Math.atan2(-px,-pz))-dir;while(w2>Math.PI)w2-=6.283;while(w2<-Math.PI)w2+=6.283;dir+=clamp(w2,-.5,.5);nx=px+Math.sin(dir)*ST;nz=pz+Math.cos(dir)*ST}
px=nx;pz=nz;arc+=ST;if(++k%4===0){wpX[n]=px;wpZ[n]=pz;n++}}
return n;
}
// lights along the route: each step at most 1.6 x spacing, flyable in a straight line; land first, water only when nothing else fits
// drop state, kept between calls so the chain can resume after a re-route
let dlX=0,dlZ=0,dlA=0,dlQ=0,dlW=0,dlS=0;const wpQ=new Int32Array(400);
function* dropLights(P,N){
const sp=P.sp,sep=sp*.7,hx=Math.sin(LO.yaw),hz=Math.cos(LO.yaw),OF=[0,2,-2,4,-4];let gx=0,gz=0,ga=0,gq=0;
const ahead=(x,z)=>{const dx=x-LO.x,dz=z-LO.z,d=Math.hypot(dx,dz),f=dx*hx+dz*hz;return !(d<9&&f<.7*d)&&!(d<15&&f<0)};
// best spot in the arc window [a0,a1] after the last light: route cells, nudged up to 4 m sideways; pass 0 strict and dry, 1 softer and dry, 2 softer and wet, 3 also a tight gap
const pick=(a0,a1,p0,p1)=>{
for(let pass=p0;pass<=p1;pass++){let bd=1e9,ok=false;
for(let q=dlQ;q<rtN;q++){const ar=rtA[q]-dlA;if(ar<a0)continue;if(ar>a1)break;const sc=Math.abs(ar-sp);if(sc>=bd)continue;
const q0=Math.max(0,q-1),q1=Math.min(rtN-1,q+1);let tx=rtX[q1]-rtX[q0],tz=rtZ[q1]-rtZ[q0];const tl=Math.hypot(tx,tz)||1;tx/=tl;tz/=tl;
for(let o=0;o<(pass?OF.length:1);o++){const x=rtX[q]-tz*OF[o],z=rtZ[q]+tx*OF[o],d=Math.hypot(x-dlX,z-dlZ);if(ltN?d>sp*1.6:d>sp*2.2)continue;
if(pass<2&&W.heightAt(x,z)<W.waterY)continue;
if(!ahead(x,z)||!ltOk(x,z,pass>2?2:pass>0?1:0)||!ltFree(x,z,sep)||(ltN&&!ltSeg(dlX,dlZ,x,z)))continue;bd=sc;gx=x;gz=z;ga=rtA[q];gq=q;ok=true;break}}
if(ok)return true}
return false};
while(ltN<N){
// nothing fits in the window: look a little nearer and further along the route; if still nothing, stop here (never a jump)
if(!pick(sp*.5,sp*1.6,0,3)&&!pick(sp*.3,sp*2.4,1,3))return false;
if(ltN)dlS=Math.max(dlS,Math.hypot(gx-dlX,gz-dlZ));if(W.heightAt(gx,gz)<W.waterY)dlW++;ltAdd(gx,gz);dlX=gx;dlZ=gz;dlA=ga;dlQ=gq;yield}
return true;
}
// route from cell 'at' through waypoints w0.. on; wpQ[w] keeps the route index where each waypoint was reached
function* routeOn(at,w0,nw){for(let w=w0;w<nw;w++){wpQ[w]=-1;const c=snapCell(wpX[w],wpZ[w],6);if(c<0||c===at)continue;if(astar(at,c)){at=c;wpQ[w]=rtN-1}yield}}
// the lap is built by a generator: run straight through at the start, or a few milliseconds per frame ahead of time (from where the snake should end this lap)
let lg=null,lgReady=false,lgWork=0,lgI=-1,lgX=0,lgZ=0,lgY=0;const perfLap={changeMs:0,sliceMax:0,pre:0,redo:0};
function* lapGen(){
const P=LAPS[OPT.size],N=P.n[0]+Math.floor(Math.random()*(P.n[1]-P.n[0]+1)),sp=P.sp;
reachGrid();yield;
let bN=-1,bX=null,bZ=null,bW=0,bS=0;
// a lap that ends in rough ground near the rim can leave too few lights: then try again from a spot 35 m further in, facing the middle
for(let sh=0;sh<2;sh++){
if(sh){const tx=mapR?cx:0,tz=mapR?cz:0,d=Math.hypot(tx-LO.x,tz-LO.z);if(bN>=P.n[0]-2||d<40)break;const ux=(tx-LO.x)/d,uz=(tz-LO.z)/d,k=snapCell(LO.x+ux*35,LO.z+uz*35,4);if(k<0)break;LO.x=-RL+((k/RN)|0)*RS;LO.z=-RL+(k%RN)*RS;LO.yaw=Math.atan2(ux,uz);reachGrid();yield}
const t0=performance.now();
for(let tr=0;tr<8&&(tr<4||(LO.pre?lgWork:performance.now()-t0)<45);tr++){
ltN=0;rtN=0;lapSt++;const nw=planLap(P,N,tr);if(rgUse){const hx=Math.sin(LO.yaw),hz=Math.cos(LO.yaw);for(let di=-6;di<=6;di++)for(let dj=-6;dj<=6;dj++){const x=di*RS,z=dj*RS,d=Math.hypot(x,z),f=x*hx+z*hz,k=cellOf(LO.x+x,LO.z+z);if(k>=0&&d>2&&d<15&&f<.7*d)rgUse[k]=lapSt}}
let at=cellOf(LO.x,LO.z);if(at<0||rgSeen[at]!==1)at=snapCell(LO.x,LO.z,4);
if(at>=0){rtX[0]=-RL+((at/RN)|0)*RS;rtZ[0]=-RL+(at%RN)*RS;rtA[0]=0;rtN=1;yield* routeOn(at,0,nw);
dlX=LO.x;dlZ=LO.z;dlA=0;dlQ=0;dlW=0;dlS=0;
// when the chain stalls, keep the route off that stretch and route again from the last light to the waypoints beyond it
for(let fix=0;fix<5&&!(yield* dropLights(P,N));fix++){
if(!ltN)break;let w=0;while(w<nw&&!(wpQ[w]>=0&&rtA[wpQ[w]]>dlA+sp*2.6))w++;if(w>=nw)break;
for(let q=dlQ+1;q<rtN&&rtA[q]-dlA<sp*2.6;q++){const k=cellOf(rtX[q],rtZ[q]);if(k>=0)rgAv[k]=lapSt}
const c0=cellOf(dlX,dlZ);if(c0<0||rgSeen[c0]!==1)break;rtN=dlQ+1;rtX[rtN]=-RL+((c0/RN)|0)*RS;rtZ[rtN]=-RL+(c0%RN)*RS;rtA[rtN]=rtA[rtN-1]+Math.hypot(rtX[rtN]-rtX[rtN-1],rtZ[rtN]-rtZ[rtN-1]);rtN++;
const n0=rtN;yield* routeOn(c0,w,nw);if(rtN===n0)break}
lapWet=dlW;lapStep=dlS}
if(ltN>bN){bN=ltN;bX=ltX.slice(0,ltN);bZ=ltZ.slice(0,ltN);bW=lapWet;bS=lapStep}
if(ltN>=Math.max(8,P.n[0]-2))break;yield}}
ltN=0;for(let i=0;i<bN;i++)ltAdd(bX[i],bZ[i]);lapWet=bW;lapStep=bS}
function buildLap(){lapPend=-1;LO.x=pos.x;LO.z=pos.z;LO.yaw=yaw;LO.pre=false;lg=null;lgReady=false;lgI=-1;const g=lapGen();while(!g.next().done);finalLap()}
function finalLap(){
// never fewer than 8 (only if the valley around the head is tiny)
const tmp={x:0,y:0,z:0};for(let g=0;ltN<8&&g<40;g++)if(placeItem(tmp,14,70)&<Free(tmp.x,tmp.z,6))ltAdd(tmp.x,tmp.z);
ltLeft=ltN;lgI=-1;for(let i=ltN;i<LTMAX;i++){fPos[i*3+1]=-9999;fCol[i*3]=fCol[i*3+1]=fCol[i*3+2]=0}
nearL();
}
function lgSwap(){let t=ltX;ltX=nbX;nbX=t;t=ltY;ltY=nbY;nbY=t;t=ltZ;ltZ=nbZ;nbZ=t;t=ltE;ltE=nbE;nbE=t;let n=ltN;ltN=nbN;nbN=n;n=lapWet;lapWet=nbW;nbW=n;n=lapStep;lapStep=nbS;nbS=n}
// six lights left: guess where this lap ends (the last light of the trail still lit, heading from the one before it) and start the next lap from there
// lights can be eaten in any order: if the guessed last light goes early, guess again (with one light left the guess is exact)
function lapPre(){let i=-1,j=-1;for(let k=ltN-1;k>=0;k--)if(!ltE[k]){if(i<0)i=k;else{j=k;break}}if(i<0)return;lgI=i;
const ny=j>=0?Math.atan2(ltX[i]-ltX[j],ltZ[i]-ltZ[j]):Math.atan2(ltX[i]-pos.x,ltZ[i]-pos.z);
// close to the last guess: keep the work already done
if((lg||lgReady)&&Math.hypot(ltX[i]-lgX,ltZ[i]-lgZ)<14&&Math.abs(Math.atan2(Math.sin(ny-lgY),Math.cos(ny-lgY)))<1)return;
LO.x=lgX=ltX[i];LO.z=lgZ=ltZ[i];LO.yaw=lgY=ny;LO.pre=true;lgWork=0;nbN=0;lgReady=false;lg=lapGen()}
function lapSlice(ms){if(!lg)return;const t=performance.now();lgSwap();let d=false;do{d=lg.next().done}while(!d&&performance.now()-t<ms);lgSwap();const c=performance.now()-t;lgWork+=c;if(ms<99&&c>perfLap.sliceMax)perfLap.sliceMax=c;if(d){lg=null;lgReady=true}}
// the last light is eaten: use the lap built ahead if the snake ended near the guess, after a cheap head check; otherwise build it now
// a slow device may not have finished: keep building for up to 0.8 s (6 ms a frame) while the fanfare plays, then the new lights appear
let lapPend=-1;
function nextLap(force){const t=performance.now();let ok=false,lgWhy='none';
if(lg&&!force){lapPend=performance.now();return true}lapPend=-1;
if(lg)lapSlice(999);perfLap.nb=lgReady?nbN:-1;
if(lgReady){lgReady=false;let dy=yaw-lgY;while(dy>Math.PI)dy-=6.283;while(dy<-Math.PI)dy+=6.283;
lgWhy=Math.hypot(pos.x-lgX,pos.z-lgZ)>20?'far':Math.abs(dy)>=1.75?'turned':nbN<8?'few':'head';
if(lgWhy==='head'){lgSwap();ok=true;const hx=Math.sin(yaw),hz=Math.cos(yaw);let m=0,bad=0;
for(let i=0;i<ltN;i++){const dx=ltX[i]-pos.x,dz=ltZ[i]-pos.z,d=Math.hypot(dx,dz),f=dx*hx+dz*hz;if(d<9&&f<.7*d||d<15&&f<0){if(i>=4&&++bad>2){ok=false;break}continue}ltX[m]=ltX[i];ltY[m]=ltY[i];ltZ[m]=ltZ[i];ltE[m]=0;m++}
if(ok&&m>=8)ltN=m;else ok=false}}
if(ok){LO.pre=false;finalLap()}else{perfLap.redo++;perfLap.why=lgWhy;buildLap()}perfLap.used=(perfLap.used||0)+(ok?1:0);
perfLap.pre=ok?1:0;perfLap.changeMs=performance.now()-t;return false}
function nearL(){let b=1e18,b2=1e18;nI=nI2=-1;for(let i=0;i<ltN;i++){if(ltE[i])continue;const d=(ltX[i]-pos.x)**2+(ltZ[i]-pos.z)**2;if(d<b){b2=b;nI2=nI;b=d;nI=i}else if(d<b2){b2=d;nI2=i}}
if(nI>=0){food.x=ltX[nI];food.y=ltY[nI];food.z=ltZ[nI]}}
function showLcd(){$('sc').textContent=pad4(score);const m=Math.round(nPts()*SP)+' M';$('sub').textContent=mode==='zen'?'ZEN · '+m:m+' · BEST '+pad4(Math.max(score,store.get('best',{})[bestKey()]||0))}
// put the head at (x,z), centre the ring there, face the longest clear run
const stW={x:0,z:0};let stDry=false;
function stReach(x0,z0,a,max){let d;for(d=3;d<=max;d+=3){const x=x0+Math.sin(a)*d,z=z0+Math.cos(a)*d;if(Math.abs(x)>W.half-20||Math.abs(z)>W.half-20||W.collide({x,y:groundAt(x,z)+HOVER,z},2,hit)||Math.abs(groundAt(x,z)-groundAt(x-Math.sin(a)*3,z-Math.cos(a)*3))>3)break}return d}
function stAt(bx,bz){pos.set(bx,groundAt(bx,bz)+HOVER,bz);cx=bx;cz=bz;mapR=MAPR[OPT.size];wall.visible=mapR>0;if(mapR){wall.position.set(cx,groundAt(cx,cz)+12,cz);wall.scale.set(mapR,70,mapR)}
let best=-1,by=0;for(let k=0;k<24;k++){const a=k*Math.PI/12,d=stReach(bx,bz,a,120);if(d>best){best=d;by=a}}yaw=by}
function startRealm(i){
$('menu').hidden=true;$('over').hidden=true;$('hud').hidden=false;paused=false;$('resume').hidden=true;
if(selV!==i){selV=i;store.set('sel',i);applyVale(i)}
loadRealm(i);
{ // start in the most open meadow, facing the longest clear run
const reach=stReach;
// prefer dry open land: water only when no dry spot is nearly as open
let bs=-1,bx=LM.start.x,bz=LM.start.z,ds=-1,dx=0,dz=0;
const lc={x:0,y:0,z:0};
for(let k=0;k<90;k++){let c;if(k===0)c=LM.start;else if(k&1)c=W.freeSpot(Math.random,HOVER-.1,HOVER+.2);else{lc.x=(Math.random()*2-1)*W.half*.6;lc.z=(Math.random()*2-1)*W.half*.6;lc.y=groundAt(lc.x,lc.z)+HOVER;if(W.collide(lc,1.2,hit))continue;c=lc}if(Math.hypot(c.x,c.z)>W.half*.6)continue;let m=1e9;for(let j=0;j<8;j++)m=Math.min(m,reach(c.x,c.z,j*Math.PI/4,36));if(m>bs){bs=m;bx=c.x;bz=c.z}
if(m>ds&&W.heightAt(c.x,c.z)>=W.waterY+.3&&W.heightAt(c.x+6,c.z)>=W.waterY&&W.heightAt(c.x-6,c.z)>=W.waterY&&W.heightAt(c.x,c.z+6)>=W.waterY&&W.heightAt(c.x,c.z-6)>=W.waterY){ds=m;dx=c.x;dz=c.z}}
stDry=ds>=Math.max(12,bs*.6);stW.x=bx;stW.z=bz;if(stDry){bx=dx;bz=dz}
stAt(bx,bz)}
mode=OPT.diff==='zen'?'zen':'classic';foods=0;score=0;nCur=nTarget=14;speed=BASE[OPT.spd];roll=0;hurt=0;glow=0;shake=0;gtime=0;safeT=2.5;bonus.on=false;bonus.orb.visible=bonus.beam.visible=false;$('bonus').hidden=true;
fillTrail();advanceTrail();lapN=1;buildLap();
// a dry start in a pocket the trail cannot leave: go back to the most open spot (often water)
if(stDry&<N<LAPS[OPT.size].n[0]){stDry=false;stAt(stW.x,stW.z);fillTrail();advanceTrail();buildLap()}
pulseP=-1;mmT=0;combo=0;lastEatT=-99;$('cb').hidden=true;mile=Math.floor(nPts()*SP/25);mileP=0;lapBanT=-99;cqN=0;cDir=0;
camPos.set(pos.x-Math.sin(yaw)*14,pos.y+10,pos.z-Math.cos(yaw)*14);camLook.copy(pos);
state='play';MUS.setMood('explore');MUS.setProgress(0);showLcd();
banner(VALES[i].name,mode==='zen'?'Zen: glide, eat, grow. Nothing ends the flight.':OPT.diff==='easy'?'Easy: only your own tail ends the run.':'Eat the lights. Do not cross your tail.');
tip(MOBILE?'Hold the left or right side of the screen to turn.':'Left and right arrows turn. That is all.',5);
}
function resume(){if(!paused)return;paused=false;state='play';$('menu').hidden=true;$('hud').hidden=false;safeT=1.5}
function goHome(){if(state==='menu')return;if(state==='play')saveRec();paused=state==='play';$('resume').hidden=!paused;state='menu';touches.clear();touchSide=0;$('menu').hidden=false;$('over').hidden=true;$('hud').hidden=true;if(!paused)MUS.setMood('menu');menuInfo()}
const DESC={zen:'Zen: no game over. Glide, eat and grow.',easy:'Easy: stones and cliffs only turn you. Your own tail ends the run.',normal:'Normal: your tail, stones and cliffs end the run. Double points.',hard:'Hard: no mercy on stones, longer growth, faster ramp. Triple points.'};
function menuInfo(){[0,1,2].forEach(i=>$('r'+i).setAttribute('aria-pressed',i===selV));$('play').textContent='Play '+VALES[selV].name;const best=store.get('best',{});const bl=store.get('blen',{})||{};VALES.forEach((r,i)=>{$('b'+i).textContent='BEST '+pad4(best[r.id+'.'+OPT.diff]||0);const m=bl[r.id+'.'+OPT.diff]||0;$('l'+i).textContent=m?m+' M':''});
document.querySelectorAll('.seg').forEach(g=>{const k=g.dataset.opt;g.querySelectorAll('button').forEach(b=>b.setAttribute('aria-pressed',b.dataset.v===OPT[k]))});
$('optDesc').textContent=DESC[OPT.diff]+' Map: '+(OPT.size==='large'?'the whole valley.':OPT.size==='medium'?'a wide ring of light.':'a small ring of light.')+(OPT.turn==='classic'?' Classic turns: one press, a square turn.':'')}
function setOpt(k,v){if(!(k in OPT))return;OPT[k]=v;{const vo=store.get('vopt',{})||{},id=VALES[selV].id;(vo[id]=vo[id]||{})[k]=v;store.set('vopt',vo)}if(paused){paused=false;$('resume').hidden=true}menuInfo()}
function setMode(m){setOpt('diff',m==='zen'?'zen':m==='classic'?'normal':m)}
// records per valley and difficulty: best score (classic runs at game over, Zen when leaving), best length in metres, most laps
function saveRec(){
if(vIdx<0||!W)return 0;const k=bestKey(),m=Math.round(nPts()*SP),lp=lapN-1,bl=store.get('blen',{})||{},bp=store.get('blap',{})||{};let r=0;
if(m>(bl[k]||0)){bl[k]=m;store.set('blen',bl);r|=1}if(lp>(bp[k]||0)){bp[k]=lp;store.set('blap',bp);r|=2}
if(mode==='zen'){const b=store.get('best',{});if(score>(b[k]||0)){b[k]=score;store.set('best',b)}}
return r}
function crash(kind){
if(state!=='play'||safeT>0)return false;
if(mode==='zen'||(OPT.diff==='easy'&&kind!=='tail'))return false;
state='over';overT=0;hurt=1;shake=.7;SFX.hit();SFX.gameOver();MUS.setMood('lose');beep(220,.12);beep(165,.12,.14);beep(110,.3,.28);rumble(380,1,1);
emit(pos.x,pos.y,pos.z,60,13,1,.55,.3,1,5);
const best=store.get('best',{}),old=best[bestKey()]||0,rec=score>old;if(rec){best[bestKey()]=score;store.set('best',best)}
const oldLen=(store.get('blen',{})||{})[bestKey()]||0,rr=saveRec();
$('oT').textContent=rec&&score>0?'New best':rr&1&&oldLen>0?'New best length':'Game over';
$('oR').textContent='BEST '+Math.max(oldLen,Math.round(nPts()*SP))+' M · '+((store.get('blap',{})||{})[bestKey()]||0)+' LAPS';$('oS').textContent=pad4(score);$('oB').textContent='BEST '+pad4(Math.max(old,score));$('oL').textContent=Math.round(nPts()*SP)+' M · '+foods+' LIGHTS · LAP '+lapN;
$('oP').textContent=kind==='tail'?'You crossed your own tail.':kind==='cliff'?'You flew into the cliff.':kind==='edge'?'You left the ring of light.':'You struck the stone.';
touches.clear();touchSide=0;
setTimeout(()=>{if(state==='over'){$('over').hidden=false;$('hud').hidden=true}},1500);
return true;
}
function eat(isBonus,li){
if(isBonus){const pts2=(20+Math.ceil(bonus.ttl)*4)*MULT[OPT.diff];score+=pts2;rumble(160,.4,.9);bonus.on=false;bonus.orb.visible=bonus.beam.visible=false;$('bonus').hidden=true;nTarget+=OPT.diff==='hard'?GROWH:GROW;
emit(bonus.x,bonus.y,bonus.z,50,13,.4,1,.9,1,1);SFX.golden();beep(1320,.06);beep(1760,.06,.07);beep(2090,.1,.14);banner('+'+pts2,'Bonus light');glow=1}
else{foods++;
// combo: the next light within the window (about 2.5 s, longer when lights are far apart or the snake is slow)
combo=gtime-lastEatT<=comboWin?combo+1:1;lastEatT=gtime;comboWin=Math.max(2.5,2*LAPS[OPT.size].sp/speed+.8);
if(combo>1){$('cb').textContent='x'+combo;$('cb').hidden=false}
score+=(Math.min(9,3+Math.floor(foods/12))+Math.min(5,combo-1))*(MULT[OPT.diff]+(OPT.spd==='fast'?1:0));nTarget+=OPT.diff==='hard'?GROWH:GROW;speed=Math.min(BASE[OPT.spd]+7,BASE[OPT.spd]+foods*RAMP[OPT.diff]);rumble(70,0,.6);
ltE[li]=1;ltLeft--;if(ltLeft>0&<Left<=6&&!test.noPre&&(lgI<0||ltE[lgI]))lapPre();emit(ltX[li],ltY[li],ltZ[li],26,9,1,.9,.55,.8,2);SFX.wisp(1+(foods%10));beep(784*Math.pow(2,PENT[Math.min(8,combo-1)]/12),.07);glow=Math.max(glow,.6);pulseP=0;
try{if(!muted&&navigator.vibrate&&/Android/i.test(navigator.userAgent))navigator.vibrate(10)}catch(e){}
if(ltLeft<=0){ // lap done: a little fanfare, a lap bonus, then a new trail
const lb=mode==='zen'?0:LAPB*(MULT[OPT.diff]+(OPT.spd==='fast'?1:0));score+=lb;lapN++;const pend=nextLap();SFX.golden();beep(784,.09,.05);beep(988,.09,.16);beep(1175,.09,.27);beep(1568,.28,.38);rumble(260,.5,.8);glow=1;
banner('Lap '+lapN,mode==='zen'?Math.round(nTarget*SP)+' m long · '+foods+' lights':'+'+lb+' lap bonus'+(pend?'':' · '+ltN+' new lights'));lapBanT=gtime}
nearL();
if(foods%11===0&&!bonus.on&&placeItem(bonus,18,45)){bonus.on=true;bonus.ttl=OPT.diff==='hard'?11:16;bonus.orb.visible=bonus.beam.visible=true;$('bonus').hidden=false;SFX.event()}
if(foods===1)tip('Longer. Each light adds to your tail. Eat them in any order.',3.5);
if(foods===3&&mode==='classic')tip('Mind your tail. It is solid.',3.5)}
MUS.setProgress(Math.min(1,foods/60));showLcd();
}
function updPlay(dt,t){
if(lapPend>=0){lapSlice(6);if(!lg||performance.now()-lapPend>800)nextLap(true)}else lapSlice(4);gtime+=dt;safeT=Math.max(0,safeT-dt);scrapeCd-=dt;cliffCd-=dt;
let x;
if(OPT.turn==='classic'){x=0;if(!cDir&&cqN){cDir=cqA[0];cqA[0]=cqA[1];cqN--;cT=0}
// the turn is applied as a change of heading, so cliff slides and bounces during a turn still add up
if(cDir){const e0=cT/CT;cT=Math.min(CT,cT+dt);const e1=cT/CT;yaw-=cDir*1.5707963*(e1*e1*(3-2*e1)-e0*e0*(3-2*e0));x=cDir;if(cT>=CT)cDir=0}}
else{x=readTurn();yaw-=x*2.45*dt}
$('tl').classList.toggle('on',x<-.3);$('tr').classList.toggle('on',x>.3);roll+=(-x*.55-roll)*Math.min(1,5*dt);
const fx=Math.sin(yaw),fz=Math.cos(yaw),g0=groundAt(pos.x,pos.z);
// cliffs are walls
let blocked=false,side=0;
const g1=groundAt(pos.x+fx*2.6,pos.z+fz*2.6);
const out=mapR>0&&Math.hypot(pos.x+fx*1.5-cx,pos.z+fz*1.5-cz)>mapR;
if(out||g1-g0>4.2||Math.abs(pos.x)>W.half-3||Math.abs(pos.z)>W.half-3){
const border=!out&&!(g1-g0>4.2);
if(!out&&!border&&OPT.diff!=='hard'){const fl=groundAt(pos.x+Math.sin(yaw+.8)*2.6,pos.z+Math.cos(yaw+.8)*2.6)-g0<=4.2,fr=groundAt(pos.x+Math.sin(yaw-.8)*2.6,pos.z+Math.cos(yaw-.8)*2.6)-g0<=4.2;side=fl&&!fr?1:fr&&!fl?-1:fl&&fr?(x<0?1:-1):0}
if(side){yaw+=side*5*dt;blocked=true;if(scrapeCd<=0){scrapeCd=.3;emit(pos.x,pos.y,pos.z,5,5,1,.8,.5,.4,8)}}
else{
if(crash(out?'edge':'cliff'))return;
blocked=!out;
if(cliffCd<=0){cliffCd=.8;if(out)yaw=Math.atan2(cx-pos.x,cz-pos.z)+(Math.random()-.5)*.9;else if(border)yaw=Math.atan2(-pos.x,-pos.z)+(Math.random()-.5)*.9;else yaw+=Math.PI*.75;tip(out?'The ring of light turns you back.':'The cliffs turn you back.',2);SFX.dash()}
else if(!out)yaw+=4*dt;
}
}
const ox=pos.x,oy=pos.y,oz=pos.z,mv=blocked?(side?.45:0):1;
pos.x+=fx*speed*dt*mv;pos.z+=fz*speed*dt*mv;
const gy=Math.max(groundAt(pos.x,pos.z),groundAt(pos.x+fx*3,pos.z+fz*3)-.6)+HOVER;pos.y+=(gy-pos.y)*Math.min(1,7*dt);
if(pos.y<groundAt(pos.x,pos.z)+1)pos.y=groundAt(pos.x,pos.z)+1;
if(g0<=W.waterY+.01&&Math.random()<.5)emit(pos.x,W.waterY+.3,pos.z,1,4,.7,.9,1,.6,8);
// rocks, ruins, trees
if(W.collide(pos,.7,hit)&&Math.abs(hit.y)<.85){
const hl=Math.hypot(hit.x,hit.z)||1,nx=hit.x/hl,nz=hit.z/hl,dn=fx*nx+fz*nz;
pos.x+=nx*(hit.d+.2);pos.z+=nz*(hit.d+.2);
if(dn<0){
if(dn<(OPT.diff==='hard'?-.2:-.5)){if(crash('rock'))return;const rx=fx-2*dn*nx,rz=fz-2*dn*nz;yaw=Math.atan2(rx,rz);SFX.dash();shake=.25}
else{const rx=fx-1.15*dn*nx,rz=fz-1.15*dn*nz;yaw=Math.atan2(rx,rz);if(scrapeCd<=0){scrapeCd=.3;emit(pos.x,pos.y,pos.z,5,5,1,.8,.5,.4,8)}}
}
}
dir.set(pos.x-ox,pos.y-oy,pos.z-oz);if(dir.lengthSq()<1e-8)dir.set(fx,0,fz);dir.normalize();pitchV=Math.asin(clamp(dir.y,-1,1));
if(nCur<nTarget)nCur=Math.min(nTarget,nCur+26*dt);
const n=advanceTrail();
if(mode==='classic'&&safeT<=0){for(let i=22;i<n;i+=2){const dx=pts[i].x-pos.x,dz=pts[i].z-pos.z,dy=pts[i].y-pos.y;if(dx*dx+dz*dz<.72&&dy*dy<4){if(crash('tail'))return;break}}}
// food and bonus
for(let i=0;i<ltN;i++)if(!ltE[i]&&(ltX[i]-pos.x)**2+(ltZ[i]-pos.z)**2<8.5&&Math.abs(ltY[i]-pos.y)<4){eat(false,i);break}
if(bonus.on){bonus.ttl-=dt;$('bonus').textContent='Bonus light · '+Math.ceil(bonus.ttl)+' s';
if((bonus.x-pos.x)**2+(bonus.z-pos.z)**2<8.5&&Math.abs(bonus.y-pos.y)<4)eat(true);
else if(bonus.ttl<=0){bonus.on=false;bonus.orb.visible=bonus.beam.visible=false;$('bonus').hidden=true}}
if((gtime*3|0)!==((gtime-dt)*3|0))showLcd();
if(combo&>ime-lastEatT>comboWin){combo=0;$('cb').hidden=true}
// a soft chime and a small banner every 25 m, never on top of the lap banner
{const m=Math.floor(nPts()*SP/25);if(m>mile){mile=m;mileP=m}if(mileP&>ime-lapBanT>3.6){banner(mileP*25+' m','',true);beep(1047,.1);beep(1568,.18,.1);mileP=0}}
}
function updMenu(dt){
if(paused)return;
menuA+=dt*.5;const s=LM.start,cx=s.x,cz=s.z,R=11;pos.set(cx+Math.sin(menuA)*R,0,cz+Math.cos(menuA)*R);pos.y=Math.max(groundAt(pos.x,pos.z)+HOVER,s.y-6);
yaw=menuA+Math.PI/2;dir.set(Math.sin(yaw),0,Math.cos(yaw));roll=-.4;nCur=nTarget=70;advanceTrail();
}
function indicator(){
const el=$('ind');if(state!=='play'){el.hidden=true;return}
const tg=bonus.on?bonus:food;v1.set(tg.x,tg.y+1,tg.z).project(camera);
let x=v1.x,y=v1.y;const behind=v1.z>1;if(behind){x=-x;y=-y}
if(!behind&&Math.abs(x)<.9&&Math.abs(y)<.84){el.hidden=true;return}
let m=Math.max(Math.abs(x)/.9,Math.abs(y)/.84);if(m<1e-4){x=0;y=-1;m=1/.84}x/=m;y/=m;
el.hidden=false;el.style.transform='translate('+((x*.5+.5)*VW).toFixed(1)+'px,'+((-y*.5+.5)*VH).toFixed(1)+'px)';
$('indi').style.transform='rotate('+Math.atan2(-y,x).toFixed(2)+'rad)';$('indi').style.color=bonus.on?'#8ff5e6':'';
}
/* ---------- planning map: LCD pixels, north-up top view (world +x to the right, +z down), redrawn at most 6 times a second ---------- */
const mmC=$('mm'),mmX=mmC.getContext('2d');let mmT=0,mmS=52,mc0=0,mc1=0,mk=1,mo=26;const mX=x=>Math.round(mo+(x-mc0)*mk-.5),mZ=z=>Math.round(mo+(z-mc1)*mk-.5);
function drawMap(dt){
if(state==='menu'||$('hud').hidden)return;mmT-=dt;if(mmT>0)return;mmT=1/6;
{const s=Math.max(24,Math.round((mmC.clientWidth-6)/2));if(s!==mmS&&mmC.clientWidth>0){mmS=s;mmC.width=mmC.height=s}}
const S=mmS,o=S/2;mc0=mapR?cx:0;mc1=mapR?cz:0;mk=(S-2)/(2*(mapR?mapR+2:W.half-18));mo=o;
mmX.clearRect(0,0,S,S);
if(mapR){mmX.fillStyle='rgba(29,42,20,.35)';for(let a=0;a<96;a++){const an=a*.06545;mmX.fillRect(Math.round(o+Math.cos(an)*(o-1)-.5),Math.round(o+Math.sin(an)*(o-1)-.5),1,1)}}
mmX.fillStyle='rgba(29,42,20,.4)';const n=nPts();for(let i=6;i<n;i+=5)mmX.fillRect(mX(pts[i].x),mZ(pts[i].z),1,1);
mmX.fillStyle='rgba(29,42,20,.95)';for(let i=0;i<ltN;i++)if(!ltE[i])mmX.fillRect(mX(ltX[i]),mZ(ltZ[i]),1,1);
if(bonus.on&&(tAll*3|0)%2===0)mmX.fillRect(mX(bonus.x)-1,mZ(bonus.z)-1,2,2);
const hx=mX(pos.x),hz=mZ(pos.z),fx=Math.sin(yaw),fz=Math.cos(yaw);mmX.fillRect(hx-1,hz-1,3,3);mmX.fillRect(Math.round(hx+fx*2.6),Math.round(hz+fz*2.6),1,1);mmX.fillRect(Math.round(hx+fx*3.8),Math.round(hz+fz*3.8),1,1);
}
function updCamera(dt,t){
if(state==='menu'&&!paused){const s=LM.start,a=t*.07;v1.set(s.x+Math.sin(a)*34,s.y+10,s.z+Math.cos(a)*34);v1.y=Math.max(v1.y,groundAt(v1.x,v1.z)+5);camPos.lerp(v1,1-Math.exp(-1.5*dt));camLook.lerp(v2.set(s.x,s.y-5,s.z),1-Math.exp(-3*dt));camera.position.copy(camPos);camera.lookAt(camLook);return}
// the longer the snake, the higher the view, so the whole body stays in sight
const n=nPts(),len=n*SP,port=VW<VH,k=clamp((len-8)/50,0,.72);
let mx=0,mz=0,c=0;for(let i=0;i<n;i+=4){mx+=pts[i].x;mz+=pts[i].z;c++}mx/=c;mz/=c;
const ccx=pos.x+(mx-pos.x)*k,ccz=pos.z+(mz-pos.z)*k;
let R=0;for(let i=0;i<n;i+=4)R=Math.max(R,(pts[i].x-ccx)**2+(pts[i].z-ccz)**2);R=Math.min(60,Math.sqrt(R));
camR+=(R-camR)*Math.min(1,2.5*dt);
// right stick: left and right orbit the view, up and down zoom. The orbit eases back after release.
if(rsx){camOrb=clamp(camOrb+rsx*2.2*dt,-Math.PI,Math.PI);orbT=0}else{orbT+=dt;if(orbT>1.2)camOrb*=Math.exp(-2.5*dt)}
if(rsy)camZoom=clamp(camZoom*Math.exp(rsy*.9*dt),.55,1.9);
const fs=Math.sin(yaw),fc=Math.cos(yaw),os=Math.sin(yaw+camOrb),oc=Math.cos(yaw+camOrb),ah=5*(1-k)+2;
const up=(port?9:7)+camR*(port?1.75:1.6),bk=(port?11:10)+camR*.3;
v1.set(ccx+fs*ah-os*bk*camZoom,pos.y+up*camZoom,ccz+fc*ah-oc*bk*camZoom);
let kk=1;for(let i=1;i<=6;i++){v2.lerpVectors(pos,v1,i/6);if(W.collide(v2,1.3,hit)){kk=Math.max(.35,(i-1)/6);break}}
if(kk<1){v1.lerpVectors(pos,v1,kk);v1.y+=7*(1-kk)}
const gy=groundAt(v1.x,v1.z)+3;if(v1.y<gy)v1.y=gy;
camPos.lerp(v1,1-Math.exp(-(kk<1?9:rsx||rsy?7:3)*dt));if(camPos.y<groundAt(camPos.x,camPos.z)+1.5)camPos.y=groundAt(camPos.x,camPos.z)+1.5;
camLook.lerp(v2.set(ccx+fs*ah,pos.y,ccz+fc*ah),1-Math.exp(-6*dt));
camera.position.copy(camPos);
if(shake>0){shake=Math.max(0,shake-dt*1.6);camera.position.x+=(Math.random()-.5)*shake;camera.position.y+=(Math.random()-.5)*shake}
camera.lookAt(camLook);
}
const dst={dir,roll:0,boost:0,hurt:0,glow:0,dash:0,pulse:-1};
function updCommon(dt,t){
const showF=state==='play'||state==='over'||paused;
ltOrb.visible=fPts.visible=showF;if(showF)nearL();
food.beam.visible=showF&&nI>=0;food.beam2.visible=showF&&nI2>=0;
if(showF){const tw=.8+.2*Math.sin(t*6);
for(let i=0;i<ltN;i++){const j=i*3;if(ltE[i]){m4.makeScale(0,0,0);fPos[j+1]=-9999}else{const y=ltY[i]+Math.sin(t*2.4+i*.7)*.3;m4.makeRotationY(t*1.5+i);m4.setPosition(ltX[i],y,ltZ[i]);fPos[j]=ltX[i];fPos[j+1]=y;fPos[j+2]=ltZ[i];fCol[j]=tw;fCol[j+1]=.85*tw;fCol[j+2]=.5*tw}ltOrb.setMatrixAt(i,m4)}
ltOrb.count=ltN;ltOrb.instanceMatrix.needsUpdate=true;
if(nI>=0){food.beam.position.set(food.x,food.y+45,food.z);food.beam.material.opacity=.2+.07*Math.sin(t*3)}
if(nI2>=0){food.beam2.position.set(ltX[nI2],ltY[nI2]+45,ltZ[nI2]);food.beam2.material.opacity=.09}}
if(bonus.on){const bb=Math.sin(t*4)*.4,fl=bonus.ttl<4?(.4+.6*Math.abs(Math.sin(t*10))):1;bonus.orb.position.set(bonus.x,bonus.y+bb,bonus.z);bonus.orb.rotation.y=-t*2;bonus.beam.position.set(bonus.x,bonus.y+45,bonus.z);bonus.beam.material.opacity=.26*fl;
const j=LTMAX*3;fPos[j]=bonus.x;fPos[j+1]=bonus.y+bb;fPos[j+2]=bonus.z;fCol[j]=.4*fl;fCol[j+1]=1.4*fl;fCol[j+2]=1.2*fl}else fPos[LTMAX*3+1]=-9999;
fGeo.attributes.position.needsUpdate=true;fGeo.attributes.color.needsUpdate=true;
updParticles(dt);
const kT=state==='menu'&&!paused?.6:Math.min(1,.25+foods/50);progK+=(kT-progK)*Math.min(1,.5*dt);W.setProgress(progK);W.update(dt,t,camera,pos,state==='play'||state==='over');updGuide();
hurt=Math.max(0,hurt-dt*(state==='over'?.25:.9));glow=Math.max(0,glow-dt*.8);
dst.roll=-roll;dst.boost=clamp((speed-BASE[OPT.spd])/7,0,1)*.5;
wall.visible=mapR>0&&(state!=='menu'||paused);if(wall.visible)wall.material.opacity=.1+.04*Math.sin(t*2);dst.hurt=hurt;dst.glow=glow;
if(pulseP>=0){pulseP+=dt*Math.max(70,nPts()*1.3);if(pulseP>nPts()+8)pulseP=-1}dst.pulse=pulseP;
D.update(pts,nPts(),t,dt,dst);
$('vig').style.opacity=(hurt*.7).toFixed(2);
$('tapsnd').hidden=!(gpUsed&&state==='play'&&(!AC||AC.state!=='running'));
if(tipT>0){tipT-=dt;if(tipT<=0)$('tip').classList.remove('show')}
}
let last=performance.now(),tAll=0,booted=false;
function frame(ms){
requestAnimationFrame(frame);
const dt=Math.min(.066,Math.max(.001,(ms-last)/1000));last=ms;tAll+=dt;fps+=(1/dt-fps)*.1;
if(!booted)return;
pollPad();
if(state==='play')updPlay(dt,tAll);else if(state==='menu')updMenu(dt);else overT+=dt;
updCamera(dt,tAll);updCommon(dt,tAll);indicator();drawMap(dt);
renderer.render(scene,camera);
if(fps<27&&state==='play'&>ime>.6){lowT+=dt;if(lowT>(gtime<8?1.5:3)&&pixR>1){pixR=Math.max(1,pixR-.25);renderer.setPixelRatio(pixR);resize();lowT=0}}else lowT=0;
}
/* ---------- buttons ---------- */
// first tap picks the valley and shows its default options; a second tap, or Play, starts
let tapSel=null;
[0,1,2].forEach(i=>{const b=$('r'+i);
b.addEventListener('pointerdown',()=>{tapSel=selV===i});
b.addEventListener('focus',()=>{if(tapSel===null&&state==='menu'&&selV!==i)selectVale(i)});
b.addEventListener('click',()=>{initAudio();SFX.ui();const go=tapSel===null||tapSel;tapSel=null;if(selV!==i)selectVale(i);if(go)startRealm(i)})});
document.addEventListener('pointerup',()=>setTimeout(()=>{tapSel=null},0));
$('play').addEventListener('click',()=>{initAudio();SFX.ui();startRealm(selV)});
$('oA').addEventListener('click',()=>{SFX.ui();startRealm(vIdx)});
$('oC').addEventListener('click',()=>{SFX.ui();goHome()});
$('home').addEventListener('click',goHome);$('resume').addEventListener('click',()=>{SFX.ui();resume()});
$('snd').addEventListener('click',()=>setMuted(!muted));
document.querySelectorAll('.seg').forEach(g=>g.querySelectorAll('button').forEach(b=>b.addEventListener('click',()=>{SFX.ui();setOpt(g.dataset.opt,b.dataset.v)})));
document.addEventListener('click',e=>{const b=e.target&&e.target.closest&&e.target.closest('button');if(b&&e.detail>0)b.blur()});
setMuted(muted);
// leaving the page (lock, app switch) pauses the run and keeps the records
document.addEventListener('visibilitychange',()=>{if(document.hidden&&booted){if(state==='play')goHome();else if(state==='over')saveRec()}});
window.addEventListener('pagehide',()=>{if(booted&&state==='play')saveRec()});
requestAnimationFrame(frame);
setTimeout(()=>{applyVale(selV);loadRealm(selV);menuInfo();const s=LM.start;pos.set(s.x,s.y,s.z);yaw=0;fillTrail();camPos.set(s.x,s.y+10,s.z+34);camLook.set(s.x,s.y,s.z);booted=true},30);
/* QA hooks */
window.__game={version:VERSION,test,get combo(){return combo},get turning(){return cDir!==0||cqN>0},records:()=>({best:store.get('best',{}),len:store.get('blen',{}),laps:store.get('blap',{})}),vis(){const n=nPts();let c=0,m=0;for(let i=0;i<n;i+=3){v3.copy(pts[i]).project(camera);m++;if(v3.z<1&&Math.abs(v3.x)<1&&Math.abs(v3.y)<1)c++}return c/m},camIn(){return !!W.collide(camera.position,.3,hit)},get state(){return state},get mode(){return mode},get score(){return score},get foods(){return foods},get length(){return nPts()},get paused(){return paused},
get fps(){return fps},get gtime(){return gtime},get pos(){return{x:pos.x,y:pos.y,z:pos.z}},get yaw(){return yaw},get speed(){return speed},get audio(){return AC?AC.state:'none'},get voices(){return voices},
target:()=>{const t=bonus.on?bonus:food;return{x:t.x,y:t.y,z:t.z}},food:()=>({x:food.x,y:food.y,z:food.z}),lights:()=>{const o=[];for(let i=0;i<ltN;i++)if(!ltE[i])o.push({x:ltX[i],y:ltY[i],z:ltZ[i]});return o},get lap(){return lapN},get guideOn(){return guide.visible},crash:k=>{safeT=0;return crash(k||'stone')},warp:(x,z,a)=>{pos.set(x,groundAt(x,z)+HOVER,z);yaw=a;fillTrail()},eatNext:nr=>{if(state!=='play')return;let i=0;while(i<ltN&<E[i])i++;if(nr){nearL();i=nI<0?ltN:nI}if(i>=ltN)return;yaw=Math.atan2(ltX[i]-pos.x,ltZ[i]-pos.z);pos.set(ltX[i],ltY[i],ltZ[i]);fillTrail();eat(false,i)},eatNearest:()=>{nearL();if(state==='play'&&nI>=0)eat(false,nI)},lapInfo:()=>({wet:lapWet,step:lapStep,sp:LAPS[OPT.size].sp}),perfLap,buildMs:()=>{const t=performance.now();buildLap();return performance.now()-t},bonus:()=>bonus.on?{x:bonus.x,y:bonus.y,z:bonus.z,ttl:bonus.ttl}:null,
tail:()=>{const n=nPts(),o=[];for(let i=0;i<n;i+=4)o.push({x:pts[i].x,z:pts[i].z});return o},
start:i=>startRealm(i||0),select:selectVale,get cam(){return{orb:camOrb,zoom:camZoom}},get sel(){return selV},home:goHome,setMode,setOpt,get opts(){return{...OPT}},get mapR(){return mapR},get cx(){return cx},get cz(){return cz},world:()=>W,groundAt,
info:()=>({calls:renderer.info.render.calls,tris:renderer.info.render.triangles,pixelRatio:pixR,quality:QUALITY})};
})();
index.html77 lines
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
<title>Snake 3D</title>
<meta name="description" content="The classic phone snake, reborn in a 3D valley. Turn left or right, eat the lights, grow long, and do not cross your own tail.">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="Snake 3D">
<meta name="theme-color" content="#1d2f45">
<link rel="manifest" href="./manifest.webmanifest">
<link rel="apple-touch-icon" href="./icon-180.png">
<link rel="icon" href="./icon-192.png" type="image/png" sizes="192x192">
<link rel="icon" href="../../favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="./game.css">
</head>
<body>
<canvas id="c"></canvas>
<div id="hud" hidden>
<div id="vig"></div>
<div id="lcd" class="lcd"><b id="sc">0000</b><small id="sub">BEST 0000</small><i id="cb" class="lcd" hidden>x2</i></div>
<canvas id="mm" class="lcd" width="52" height="52" aria-label="Map of the lights"></canvas>
<div id="bonus" class="chip" hidden></div>
<button id="snd" class="ib" aria-label="Sound on or off">🔊</button>
<button id="home" class="ib" aria-label="Pause and menu">⌂</button>
<div id="banner"></div>
<div id="ind" hidden><i id="indi">➤</i></div>
<div id="tip" class="chip"></div>
<div id="tapsnd" class="chip" hidden>Tap the screen once for sound</div>
<div id="tl" class="turn">‹</div>
<div id="tr" class="turn">›</div>
</div>
<div id="menu" class="ov">
<div class="card">
<div class="ca">
<h1>Snake 3D</h1>
<p class="small sitelinks"><a href="/games/">All games</a> · <a href="/cases/snake-3d/">How it was made</a></p>
<p class="tag">The classic phone snake, in a 3D valley. Turn left or right. Eat the lights. Grow long. Do not cross your own tail.</p>
<div class="tiles">
<button class="tile t0" id="r0"><span class="nm">Dawn Vale<small id="b0">BEST 0000</small><small id="l0"></small></span></button>
<button class="tile t1" id="r1"><span class="nm">Ember Canyon<small id="b1">BEST 0000</small><small id="l1"></small></span></button>
<button class="tile t2" id="r2"><span class="nm">Moonlit Ruins<small id="b2">BEST 0000</small><small id="l2"></small></span></button>
</div>
<div class="row go"><button class="btn" id="play">Play Dawn Vale</button><button class="btn" id="resume" hidden>Resume</button></div>
</div>
<div class="cb">
<div class="optrow"><span>Difficulty</span><div class="seg" data-opt="diff" role="group" aria-label="Difficulty"><button data-v="zen">Zen</button><button data-v="easy">Easy</button><button data-v="normal">Normal</button><button data-v="hard">Hard</button></div></div>
<div class="optrow"><span>Speed</span><div class="seg" data-opt="spd" role="group" aria-label="Speed"><button data-v="slow">Slow</button><button data-v="normal">Normal</button><button data-v="fast">Fast</button></div></div>
<div class="optrow"><span>Map</span><div class="seg" data-opt="size" role="group" aria-label="Map size"><button data-v="small">Small</button><button data-v="medium">Medium</button><button data-v="large">Large</button></div></div>
<div class="optrow"><span>Turns</span><div class="seg" data-opt="turn" role="group" aria-label="Turns"><button data-v="smooth">Smooth</button><button data-v="classic">Classic</button></div></div>
<p class="small" id="optDesc"></p>
<p class="small hl"><b>Touch:</b> hold the left or right side of the screen to turn. <b>Keys:</b> left and right arrows, or A and D. <b>PS5 controller:</b> left stick, D-pad or L1 and R1 turn. The right stick moves the camera, and R3 resets it. ✕ selects. Options pauses. It rumbles when you eat. <b>Classic turns:</b> one press, one square turn.</p>
<p class="small hl">No sound? Turn the volume up and tap the screen once. It plays even when an iPhone is on silent.</p>
</div>
</div>
</div>
<div id="over" class="ov" hidden>
<div class="card">
<h2 id="oT">Game over</h2>
<div class="lcd"><b id="oS">0000</b><span id="oB">BEST 0000</span><br><span id="oL">LENGTH 0 M</span><br><span id="oR"></span></div>
<p class="tag" id="oP"></p>
<div class="row">
<button class="btn" id="oA">Play again</button>
<button class="btn q" id="oC">Menu</button>
</div>
</div>
</div>
<script src="../../animations/vendor/three-r128.min.js"></script>
<script src="./game.js"></script>
</body>
</html>
game.css (menus, LCD panel, HUD)98 lines
/* Layout: full-screen 3D canvas; one LCD-style score chip, two corner buttons, two turn zones; card overlays for menu and game over. */
:root{--night:#0e1420;--ink:#f3ead8;--dim:#b9b3a6;--gold:#f2c46d;--glass:rgba(14,20,32,.62);--line:rgba(243,234,216,.22);--lcd:#a9bd7e;--lcdink:#1d2a14;color-scheme:dark;
--serif:"Iowan Old Style","Palatino Linotype",Palatino,"Book Antiqua",Georgia,serif;--sans:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;--mono:"Courier New",ui-monospace,Menlo,Consolas,monospace}
[hidden]{display:none!important}
html,body{height:100%;margin:0;overflow:hidden;background:var(--night);color:var(--ink);font-family:var(--sans);
touch-action:none;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;overscroll-behavior:none;-webkit-tap-highlight-color:transparent}
#c{position:fixed;inset:0;width:100%;height:100%;display:block;touch-action:none}
button{font-family:var(--sans);color:var(--ink);cursor:pointer}
#hud{position:fixed;inset:0;pointer-events:none}
#hud button{pointer-events:auto;touch-action:none}
.chip{background:var(--glass);border:1px solid var(--line);border-radius:14px;backdrop-filter:blur(6px);-webkit-backdrop-filter:blur(6px)}
.lcd{font-family:var(--mono);font-weight:700;color:var(--lcdink);background:var(--lcd);background-image:repeating-linear-gradient(0deg,rgba(29,42,20,.09) 0 1px,transparent 1px 3px),repeating-linear-gradient(90deg,rgba(29,42,20,.09) 0 1px,transparent 1px 3px);
border:3px solid #2a3320;border-radius:10px;box-shadow:inset 0 0 0 2px rgba(255,255,255,.18),0 3px 10px rgba(0,0,0,.4);letter-spacing:.08em;font-variant-numeric:tabular-nums}
#lcd{position:absolute;top:calc(10px + env(safe-area-inset-top,0px));left:calc(12px + env(safe-area-inset-left,0px));padding:7px 12px 6px;line-height:1.15}
#lcd b{display:block;font-size:24px}
#lcd small{display:block;font-size:12px;letter-spacing:.06em}
.ib{position:absolute;top:calc(10px + env(safe-area-inset-top,0px));width:48px;height:48px;border-radius:50%;font-size:20px;display:grid;place-items:center;padding:0;background:var(--glass);border:1px solid var(--line)}
#home{right:calc(12px + env(safe-area-inset-right,0px))}
#snd{right:calc(68px + env(safe-area-inset-right,0px))}
#bonus{position:absolute;left:50%;top:calc(12px + env(safe-area-inset-top,0px));transform:translateX(-50%);padding:8px 16px;font-size:15px;color:#9ff3e6;white-space:nowrap}
#banner{position:absolute;left:0;right:0;top:24%;text-align:center;font-family:var(--serif);font-size:clamp(30px,7vw,60px);letter-spacing:.06em;text-shadow:0 2px 24px rgba(242,196,109,.8),0 0 4px rgba(0,0,0,.6);opacity:0}
#banner small{display:block;font-family:var(--sans);font-size:clamp(14px,2.6vw,19px);letter-spacing:.02em;color:var(--gold);margin-top:6px}
#banner.go{animation:ban 3.4s ease-out both}
@keyframes ban{0%{opacity:0;transform:translateY(14px) scale(.96)}12%{opacity:1;transform:none}75%{opacity:1}100%{opacity:0;transform:translateY(-10px)}}
#tip{position:absolute;left:50%;bottom:calc(120px + env(safe-area-inset-bottom,0px));transform:translateX(-50%);padding:8px 16px;font-size:15px;max-width:86vw;text-align:center;transition:opacity .4s;opacity:0}
#tip.show{opacity:1}
/* the planning map: same LCD look as the score chip, drawn in big pixels */
#mm{position:absolute;top:calc(80px + env(safe-area-inset-top,0px));left:calc(12px + env(safe-area-inset-left,0px));width:110px;height:110px;box-sizing:border-box;padding:0;image-rendering:pixelated;image-rendering:crisp-edges}
@media (max-width:600px),(max-height:500px){#mm{width:84px;height:84px}}
@media (max-width:600px) and (orientation:portrait){#tip{bottom:calc(30px + env(safe-area-inset-bottom,0px));max-width:calc(100vw - 236px);font-size:13px;padding:6px 10px}}
#tapsnd{position:absolute;left:50%;top:calc(64px + env(safe-area-inset-top,0px));transform:translateX(-50%);padding:7px 14px;font-size:14px;color:var(--gold)}
#ind{position:absolute;left:0;top:0;width:0;height:0}
#ind i{position:absolute;left:-18px;top:-18px;width:36px;height:36px;display:grid;place-items:center;font-style:normal;font-size:24px;color:var(--gold);text-shadow:0 0 10px rgba(242,196,109,.9),0 0 3px #000}
#vig{position:absolute;inset:0;opacity:0;background:radial-gradient(ellipse at center,rgba(0,0,0,0) 45%,rgba(232,90,70,.75) 100%)}
.turn{position:absolute;bottom:calc(26px + env(safe-area-inset-bottom,0px));width:84px;height:84px;border-radius:50%;display:grid;place-items:center;font-size:40px;line-height:1;color:var(--ink);border:2px solid rgba(243,234,216,.45);background:rgba(243,234,216,.08);transition:background .1s}
.turn.on{background:rgba(242,196,109,.5);border-color:var(--gold)}
#tl{left:calc(22px + env(safe-area-inset-left,0px))}#tr{right:calc(22px + env(safe-area-inset-right,0px))}
@media (hover:hover) and (pointer:fine){.turn{opacity:.4}}
.ov{position:fixed;inset:0;display:grid;place-items:center;overflow:auto;background:linear-gradient(rgba(14,20,32,.3),rgba(14,20,32,.75));
padding-block:calc(14px + env(safe-area-inset-top,0px)) calc(14px + env(safe-area-inset-bottom,0px));
padding-left:max(16px,env(safe-area-inset-left,0px));padding-right:max(16px,env(safe-area-inset-right,0px));touch-action:pan-y}
.card{max-width:700px;width:100%;box-sizing:border-box;display:flex;flex-direction:column;gap:14px;text-align:center;padding:22px;background:var(--glass);border:1px solid var(--line);border-radius:22px;backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px)}
h1{margin:0;font-family:var(--serif);font-weight:500;font-size:clamp(36px,9vw,66px);letter-spacing:.08em;line-height:1;text-wrap:balance;text-shadow:0 0 28px rgba(242,196,109,.55)}
h2{margin:0;font-family:var(--serif);font-weight:500;font-size:clamp(28px,6vw,42px);letter-spacing:.05em}
.tag{margin:0;font-size:16px;color:var(--dim);line-height:1.45;text-wrap:balance}
.tiles{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}
.tile{position:relative;min-width:0;padding:0;border-radius:16px;overflow:hidden;border:1px solid var(--line);aspect-ratio:1/.82;display:flex;flex-direction:column;justify-content:flex-end;text-align:left;touch-action:manipulation;background:#223}
.tile:hover,.tile:focus-visible{border-color:var(--gold)}
.tile[aria-pressed="true"]{border-color:var(--gold);box-shadow:0 0 0 2px var(--gold)}
.tile .nm{position:relative;padding:10px 12px;background:linear-gradient(transparent,rgba(8,10,18,.85));font-family:var(--serif);font-size:clamp(15px,3.6vw,22px);letter-spacing:.03em}
.tile .nm small{display:block;font-family:var(--mono);font-size:12px;color:var(--lcd);font-variant-numeric:tabular-nums}
.t0{background:radial-gradient(circle at calc(100% - 20px) 18px,#ffe9c2 0 9px,transparent 10px),linear-gradient(#35507c,#e8a48c 48%,#f3d7a8 58%,#5d7c62 59%,#2e4a44)}
.t1{background:radial-gradient(circle at calc(100% - 20px) 18px,#ffd27a 0 10px,transparent 11px),linear-gradient(#3a2440,#c9553f 46%,#f0a35a 58%,#7a4630 59%,#3a2222)}
.t2{background:radial-gradient(circle at calc(100% - 20px) 18px,#f4f6ff 0 8px,transparent 9px),linear-gradient(#0b1026,#1f3a5c 40%,#3fb3a2 56%,#1c2f3f 58%,#0d1722)}
.row{display:flex;gap:10px;justify-content:center;flex-wrap:wrap}
.btn{white-space:nowrap;border-radius:999px;padding:12px 24px;font-size:17px;font-weight:600;background:rgba(242,196,109,.18);border:1px solid var(--gold);touch-action:manipulation}
.btn.q{background:transparent;border-color:var(--line);font-weight:400}
.optrow{display:flex;gap:10px;align-items:center;justify-content:center;flex-wrap:wrap}.optrow>span{font-size:13px;color:var(--dim);min-width:68px;text-align:right}
.seg{display:inline-flex;border:1px solid var(--line);border-radius:999px;overflow:hidden;align-self:center}
.seg button{border:0;background:transparent;padding:9px 16px;font-size:15px;touch-action:manipulation}
@media (max-width:420px){.seg button{padding:9px 11px;font-size:14px}.optrow>span{min-width:0;width:100%;text-align:center}}
.seg button[aria-pressed="true"]{background:rgba(242,196,109,.28);font-weight:600}
.small{font-size:13px;color:var(--dim);margin:0;line-height:1.45}
#over .lcd{align-self:center;padding:14px 26px;font-size:20px;line-height:1.5;white-space:nowrap}@media (max-width:420px){#over .lcd{font-size:15px;padding:12px 16px}}
#over .lcd b{font-size:34px;display:block}
button:focus-visible{outline:2px solid var(--gold);outline-offset:3px}
@media (max-width:480px){.tile{aspect-ratio:1/1.15}.tile .nm{padding:6px 8px;font-size:15px}.tile .nm small{font-size:11px}}
@media (max-height:460px){.card{padding:12px 16px;gap:8px}.tile{aspect-ratio:1.9/1}.turn{width:70px;height:70px}}
@media (prefers-reduced-motion:reduce){#banner.go{animation-duration:.01s}}
/* the Play row stays in reach on short screens */
.row.go{position:sticky;bottom:0;z-index:1;padding:6px 0;margin:-6px 0;background:linear-gradient(rgba(20,26,40,0),rgba(20,26,40,.7) 45%)}
@media (max-height:760px){.card{padding:14px 16px;gap:9px}h1{font-size:clamp(30px,8vw,48px)}.tag{font-size:14px;line-height:1.35}.small{font-size:12px;line-height:1.35}.seg button{padding:7px 12px}}
/* the card's two halves flow as one column; in short landscape they sit side by side, Play stays with the valleys */
.ca,.cb{display:contents}
.row.go{order:1}.small.hl{order:2}
@media (max-height:460px) and (min-width:600px) and (orientation:landscape){
.card{flex-direction:row;align-items:flex-start;gap:16px;max-width:860px}
.ca,.cb{display:flex;flex-direction:column;gap:8px;flex:1;min-width:0}
.row.go{position:static;background:none;margin:0;padding:2px 0}
.tile{aspect-ratio:1/.8}.tile .nm{font-size:15px;padding:6px 8px}.tile .nm small{font-size:11px}
h1{font-size:30px}.tag{font-size:13px}.small{font-size:11px}.optrow>span{min-width:58px}.seg button{padding:6px 11px;font-size:14px}}
/* sun and moon sit a little larger on big tiles */
@media (min-width:700px) and (min-height:461px){.t0,.t1,.t2{background-size:auto}.t0{background:radial-gradient(circle at calc(100% - 30px) 28px,#ffe9c2 0 14px,transparent 15px),linear-gradient(#35507c,#e8a48c 48%,#f3d7a8 58%,#5d7c62 59%,#2e4a44)}
.t1{background:radial-gradient(circle at calc(100% - 30px) 28px,#ffd27a 0 15px,transparent 16px),linear-gradient(#3a2440,#c9553f 46%,#f0a35a 58%,#7a4630 59%,#3a2222)}
.t2{background:radial-gradient(circle at calc(100% - 30px) 28px,#f4f6ff 0 12px,transparent 13px),linear-gradient(#0b1026,#1f3a5c 40%,#3fb3a2 56%,#1c2f3f 58%,#0d1722)}}
/* narrow phones: taller tiles, a smaller sun and moon tucked in the corner, records on single lines */
.tile .nm small{white-space:nowrap}
@media (max-width:380px){.tile{aspect-ratio:1/1.3}.tile .nm{font-size:14px;padding:5px 7px}.tile .nm small{font-size:10px}
.t0{background:radial-gradient(circle at calc(100% - 13px) 13px,#ffe9c2 0 7px,transparent 8px),linear-gradient(#35507c,#e8a48c 48%,#f3d7a8 58%,#5d7c62 59%,#2e4a44)}
.t1{background:radial-gradient(circle at calc(100% - 13px) 13px,#ffd27a 0 8px,transparent 9px),linear-gradient(#3a2440,#c9553f 46%,#f0a35a 58%,#7a4630 59%,#3a2222)}
.t2{background:radial-gradient(circle at calc(100% - 13px) 13px,#f4f6ff 0 6px,transparent 7px),linear-gradient(#0b1026,#1f3a5c 40%,#3fb3a2 56%,#1c2f3f 58%,#0d1722)}}
#cb{position:absolute;left:calc(100% + 8px);top:4px;padding:3px 8px;font-size:15px;font-style:normal;letter-spacing:.04em}
#banner.sm{font-size:clamp(22px,4.5vw,34px)}
@media (max-width:420px){.optrow{flex-wrap:nowrap;gap:6px}.optrow>span{width:auto;min-width:0;font-size:12px;text-align:left}.seg button{padding:7px 8px;font-size:13px}}
/* site only */
.sitelinks a{color:inherit;font-weight:700}
Need an interactive piece for your business or audience?
A product explainer, a training walkthrough, a simulation people can play with. This one is free to take. I can build yours for a fixed price agreed up front, and the first call is free.