File size: 33,830 Bytes
2243bf9
fa32c20
9ceefcc
 
f2b420f
 
9ceefcc
9591b1d
 
 
 
2243bf9
 
 
 
d72d7d7
2243bf9
 
 
d72d7d7
2243bf9
 
 
 
 
 
 
d72d7d7
 
2243bf9
d72d7d7
f2b420f
2243bf9
eb8e2ec
f2b420f
d72d7d7
f2b420f
 
 
acdbd95
f2b420f
 
 
acdbd95
f2b420f
 
 
 
d72d7d7
 
 
 
 
f2b420f
d72d7d7
2243bf9
d72d7d7
f2b420f
 
 
d72d7d7
f2b420f
 
 
ebfbaf8
f2b420f
 
d72d7d7
 
 
 
83fd0a4
d72d7d7
eb8e2ec
 
d72d7d7
 
4175770
f2b420f
d72d7d7
 
f2b420f
acdbd95
eb8e2ec
2243bf9
eb8e2ec
911cadf
d72d7d7
 
 
 
 
2243bf9
07d40dd
f2b420f
ebfbaf8
f2b420f
d72d7d7
f2b420f
d72d7d7
f2b420f
d72d7d7
f2b420f
 
2243bf9
d72d7d7
eb8e2ec
 
f2b420f
eb8e2ec
f2b420f
 
 
 
 
eb8e2ec
d72d7d7
 
eb8e2ec
f2b420f
2243bf9
f2b420f
 
d72d7d7
 
f2b420f
 
d72d7d7
 
f2b420f
d72d7d7
 
f2b420f
 
 
eb8e2ec
f2b420f
 
 
 
eb8e2ec
f2b420f
 
 
 
 
 
 
 
 
d72d7d7
 
acdbd95
 
eb8e2ec
 
f2b420f
 
 
 
 
 
 
d72d7d7
f2b420f
 
 
2243bf9
f2b420f
d72d7d7
 
f2b420f
 
83fd0a4
 
 
 
f2b420f
 
 
 
 
 
 
 
63cb6aa
2243bf9
acdbd95
f2b420f
 
ebfbaf8
2243bf9
d72d7d7
 
2243bf9
 
f2b420f
d72d7d7
83fd0a4
 
 
 
 
f2b420f
 
 
 
 
d72d7d7
 
5ae05cc
eb8e2ec
f2b420f
eb8e2ec
 
 
 
 
f2b420f
 
 
 
 
ebfbaf8
 
f2b420f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ae05cc
2243bf9
eb8e2ec
911cadf
 
d72d7d7
 
5ae05cc
d72d7d7
 
acdbd95
f2b420f
 
 
 
 
 
 
 
 
 
 
 
 
 
d72d7d7
f2b420f
d72d7d7
f2b420f
 
 
 
 
 
d72d7d7
 
 
 
83fd0a4
d72d7d7
 
f2b420f
afa34e6
d72d7d7
 
 
911cadf
f2b420f
d72d7d7
 
f2b420f
2243bf9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import * as THREE from './vendor/three.module.min.js';
import { STUDIOS, stopLoops } from './widgets.js?v=50';
import { icon } from './icons.js?v=136';
import { CATS as CAT5, loadAll, prefetch, getConfig } from './registry.js?v=136';
import { GTAOPass } from './vendor/addons/postprocessing/GTAOPass.js';
import { BokehPass } from './vendor/addons/postprocessing/BokehPass.js';
import { buildWorld, makeBee, landH, MC } from './world.js?v=136';
import { EffectComposer } from './vendor/addons/postprocessing/EffectComposer.js';
import { RenderPass } from './vendor/addons/postprocessing/RenderPass.js';
import { UnrealBloomPass } from './vendor/addons/postprocessing/UnrealBloomPass.js';
import { OutputPass } from './vendor/addons/postprocessing/OutputPass.js';

const $ = (s) => document.querySelector(s);
const isMobile = matchMedia('(pointer:coarse)').matches || innerWidth < 700;
let quality = isMobile ? 'low' : 'high', qMode = 'AUTO';
const GOLD = 0xf2c94c, ORANGE = 0xfaa968, TEAL = 0x028391, CYAN = 0x8cbfb8, RED = 0xf85525;

/* ---------- sound (off by default) ---------- */
let ac = null, soundOn = false;
function beep(f = 440, d = .06, type = 'square', v = .04) {
  if (!soundOn) return; try {
    ac = ac || new (window.AudioContext || window.webkitAudioContext)();
    const o = ac.createOscillator(), g = ac.createGain(); o.type = type; o.frequency.value = f;
    g.gain.setValueAtTime(v, ac.currentTime); g.gain.exponentialRampToValueAtTime(.0001, ac.currentTime + d);
    o.connect(g).connect(ac.destination); o.start(); o.stop(ac.currentTime + d);
  } catch (e) {}
}
function toggleSound() { soundOn = !soundOn; $('#snd').innerHTML = icon(soundOn ? 'sound' : 'mute'); beep(880, .1); }
$('#snd').onclick = toggleSound; $('#snd').innerHTML = icon('mute');

/* ---------- three setup ---------- */
let renderer = null, gl3d = true, composer = null, bloom = null, gtao = null, bokeh = null;
try {
  const tc = document.createElement('canvas'); if (!(tc.getContext('webgl2') || tc.getContext('webgl'))) throw new Error('no webgl');
  renderer = new THREE.WebGLRenderer({ canvas: $('#gl'), antialias: !isMobile, powerPreference: 'high-performance', logarithmicDepthBuffer: false });
} catch (e) { gl3d = false; console.warn('WebGL unavailable, 2D fallback'); }
let soft = false;
if (renderer) { renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = .82; renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  try { const g = renderer.getContext(), ext = g.getExtension('WEBGL_debug_renderer_info'); const nm = ext ? g.getParameter(ext.UNMASKED_RENDERER_WEBGL) : ''; if (/swiftshader|llvmpipe|software|basic render/i.test(nm)) { quality = 'low'; soft = true; } } catch (e) {} }
{ const wq = getConfig().world?.quality; if (wq === 'low' || wq === 'high') { quality = wq; qMode = wq.toUpperCase(); } }
const urlQ = new URLSearchParams(location.search).get('q'); if (urlQ === 'high' || urlQ === 'low') { quality = urlQ; qMode = urlQ.toUpperCase(); }
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(55, innerWidth / innerHeight, 1, 4e6);
const CATS = ['Alle', ...CAT5];
const colOf = (s) => s.id === 'merge' ? RED : [GOLD, 0xffd77a, ORANGE, GOLD, CYAN][CATS.indexOf(s.cat) % 5];
const W = buildWorld(scene, renderer, STUDIOS, colOf, quality);
const nodes = W.shrines.map(s => s.portal); nodes.forEach((n, i) => n.userData = { ...n.userData, s: STUDIOS[i], i });
const core = W.core;
function applyQuality() {
  if (!renderer) return;
  renderer.setPixelRatio(Math.min(AR.pr, quality === 'high' ? Math.min(devicePixelRatio, 2) : Math.min(devicePixelRatio, 1.25)));
  renderer.setSize(innerWidth, innerHeight, false);
  if (composer) { composer.setPixelRatio(renderer.getPixelRatio()); composer.setSize(innerWidth, innerHeight); }
  renderer.shadowMap.enabled = quality === 'high' || !soft; if (gtao) gtao.enabled = quality === 'high'; if (bokeh) bokeh.enabled = quality === 'high';
  $('#q').textContent = 'Q:' + (qMode === 'AUTO' ? 'AUTO·' + quality[0].toUpperCase() : quality.toUpperCase());
}
if (renderer) { try { composer = new EffectComposer(renderer); composer.addPass(new RenderPass(scene, camera));
  try { gtao = new GTAOPass(scene, camera, innerWidth, innerHeight); gtao.updateGtaoMaterial({ radius: 4, distanceExponent: 1.4, thickness: 2, scale: 1.2 }); gtao.blendIntensity = .8; composer.addPass(gtao); } catch (e) { gtao = null; }
  try { bokeh = new BokehPass(scene, camera, { focus: 12, aperture: .00012, maxblur: .006 }); composer.addPass(bokeh); } catch (e) { bokeh = null; }
  bloom = new UnrealBloomPass(new THREE.Vector2(innerWidth, innerHeight), .18, .5, .92); composer.addPass(bloom); composer.addPass(new OutputPass()); } catch (e) { composer = null; } }

/* ---------- the player bee ---------- */
const bee = makeBee(); bee.scale.setScalar(1.3); scene.add(bee);
const B = { pos: new THREE.Vector3(), vel: new THREE.Vector3(), yaw: Math.PI, bank: 0, travel: null, near: -1, armed: true };
function spawn() { const t = W.terraces[1].pos, x = t.x + 150, z = t.z + 260; B.pos.set(x, landH(x, z) + 70, z); B.vel.set(0, 0, 0); B.yaw = Math.atan2(-(t.z - 40 - z), (t.x + 120) - x); }
spawn();
window.__studiusLegacyDust = null;
/* ---------- HUD, labels ---------- */
let cat = 'Alle', sel = 0, openId = null;
const cats = $('#cats');
CATS.forEach(c => { const b = document.createElement('button'); b.textContent = c.toUpperCase(); b.dataset.c = c; b.onclick = () => setCat(c); cats.append(b); });
function setCat(c) { cat = c; [...cats.children].forEach(b => b.classList.toggle('on', b.dataset.c === c)); beep(520); const v = visible(); if (!v.includes(sel)) select(v[0]); if (c !== 'Alle' && started) focusNode(v.find(i => nodes[i].userData.s.cat === c) ?? v[0]); }
function visible() { return nodes.map((n, i) => i).filter(i => cat === 'Alle' || nodes[i].userData.s.cat === cat || nodes[i].userData.s.id === 'merge'); }
const labels = STUDIOS.map((s, i) => { const d = document.createElement('div'); d.className = 'lbl'; d.innerHTML = `${icon(s.id)}<span>${s.name}</span>`; d.dataset.cat = s.cat; d.title = s.cat + ' · ' + s.like; d.tabIndex = 0; d.setAttribute('role', 'button'); d.setAttribute('aria-label', s.name + ' öffnen – ' + s.like);
  d.onkeydown = (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); e.stopPropagation(); select(i); open(i); } }; d.onfocus = () => select(i);
  d.onmouseenter = () => select(i); d.onclick = (e) => { e.stopPropagation(); select(i); open(i); }; $('#labels').append(d); return d; });
function select(i) { if (i == null) return; if (sel !== i) beep(660, .03); sel = i; labels.forEach((l, k) => l.classList.toggle('sel', k === i)); }
const pop = $('#pop'); if (window.ResizeObserver) new ResizeObserver(() => placePop()).observe(pop);
function open(i, here) {
  stopLoops(); openId = i; const s = STUDIOS[i]; beep(990, .08, 'triangle');
  pop.innerHTML = `<div class="ph"><span class="pi">${icon(s.id)}</span><span class="pt"><b>${s.name}</b><small>${s.cat === '+' ? 'Modul' : s.cat} · ${s.like}</small></span><button aria-label="schließen">${icon('close')}</button></div><div class="pb"></div><div class="pf"><span>STUDIO ${String(i + 1).padStart(2, '0')}/${STUDIOS.length}</span><span>● SIMULATION</span></div>`;
  pop.classList.remove('in'); void pop.offsetWidth; pop.classList.add('in'); if (!here) focusNode(i);
  pop.hidden = false; pop.setAttribute('role', 'dialog'); pop.setAttribute('aria-label', s.name + ' Studio'); pop.querySelector('.ph button').onclick = close; retFocus = document.activeElement; const pb = pop.querySelector('.pb'); const fin = () => { if (openId !== i || !pb.isConnected) return; pb.innerHTML = ''; s.build(pb); window.dispatchEvent(new CustomEvent('studius-opened', { detail: { id: s.id, el: pb } })); }; pb.innerHTML = '<p class="muted">Lade Studio…</p>'; loadAll().then(fin, e => { pb.innerHTML = '<p class="err">⚠ Laden fehlgeschlagen: ' + e.message + '</p>'; }); const bd = pop.querySelector('.pf span:last-child'); if (s.real) { bd.textContent = '● REAL · ' + s.real; bd.classList.add('real'); }
  setTimeout(() => { if (openId === i && !pop.contains(document.activeElement)) pop.querySelector('.ph button').focus({ preventScroll: true }); }, 30); placePop(); $('#wire').classList.add('on'); setTimeout(placePop, 60);
}
let retFocus = null;
function close() { if (openId == null && pop.hidden) return; try { pop.querySelector('.body')?.__unmount?.(); } catch (e) {} stopLoops(); if (openId != null) cam.tr = cam.base; const was = openId; openId = null; pop.hidden = true; pop.innerHTML = ''; if (was != null) (retFocus && retFocus.isConnected && retFocus !== document.body ? retFocus : labels[was]).focus?.({ preventScroll: true }); $('#wire').classList.remove('on'); beep(300); }
function placePop() {
  if (openId == null || innerWidth < 700) return;
  const W = pop.offsetWidth, H = pop.offsetHeight; const x = innerWidth - W - Math.max(40, innerWidth * .06);
  const y = Math.max(76, Math.min((innerHeight - H) / 2, innerHeight - H - 200));
  pop.style.left = x + 'px'; pop.style.top = y + 'px';
}

// fly the bee to a shrine (labels/keyboard/menu open → the bee travels there)
function shrineFront(i) { const g = W.shrines[i].group; g.updateMatrixWorld(); const v = new THREE.Vector3(0, 10, 32).applyMatrix4(g.matrixWorld); return v; }
function focusNode(i) { if (!started) return; const from = B.pos.clone(), to = shrineFront(i); B.travel = { from, to, t: 0, d: Math.max(1.5, Math.min(6, from.distanceTo(to) / 400)), i }; B.armed = false; }
function screenPos(o) { const v = o.getWorldPosition(new THREE.Vector3()).project(camera); return { x: (v.x + 1) / 2 * innerWidth, y: (1 - v.y) / 2 * innerHeight, z: v.z }; }
window.addEventListener('studius-merge', () => { beep(200, .3, 'sawtooth'); });

/* ---------- input: fly the bee ---------- */
const keys = {};
let started = false, lookK = 0, shotCam = null;
const FLYKEYS = { w: 'f', arrowup: 'f', s: 'b', arrowdown: 'b', a: 'l', arrowleft: 'l', d: 'r', arrowright: 'r', ' ': 'u', e: 'u', x: 'dn', control: 'dn', shift: 'boost' };
addEventListener('keydown', e => {
  if (!started) { start(); return; }
  if (e.key === 'Escape') { close(); return; }
  if (e.target.matches('input,textarea,select,[contenteditable]')) return;
  if (pop.contains(e.target)) return;
  if (e.target.classList?.contains('lbl') && (e.key === 'Enter' || e.key === ' ')) return;
  const k = FLYKEYS[e.key.toLowerCase()]; if (k) { keys[k] = 1; B.travel = null; if (e.key.startsWith('Arrow') || e.key === ' ') e.preventDefault(); return; }
  const v = visible(), ix = v.indexOf(sel);
  if (e.key === 'n' || e.key === 'N' || e.key === 'PageDown') { select(v[(ix + 1) % v.length]); focusNode(sel); }
  else if (e.key === 'p' || e.key === 'P' || e.key === 'PageUp') { select(v[(ix - 1 + v.length) % v.length]); focusNode(sel); }
  else if (e.key === 'Enter') { e.preventDefault(); open(B.near >= 0 ? B.near : sel); }
  else if (e.key === 'Backspace') close();
  else if (e.key === 'q' || e.key === 'Q') cycleQ();
  else if (e.key === 'm' || e.key === 'M') toggleSound();
  else if (e.key === 'c' || e.key === 'C') { setCat(CATS[(CATS.indexOf(cat) + 1) % CATS.length]); }
  else if (e.key === 'h' || e.key === 'H') { spawn(); }
});
addEventListener('keyup', e => { const k = FLYKEYS[e.key.toLowerCase()]; if (k) keys[k] = 0; });
addEventListener('blur', () => Object.keys(keys).forEach(k => keys[k] = 0));
const mouse = new THREE.Vector2(9, 9), ray = new THREE.Raycaster(); let drag = null;
const cv = $('#gl');
const ptrs = new Map(); let pinch0 = 0, idleT = 0; const ZMIN = 4, ZMAX = 400;
const cam = { yaw: Math.PI, pitch: .16, dist: 11, tdist: 11, free: 0 };
addEventListener('pointermove', e => { mouse.set(e.clientX / innerWidth * 2 - 1, -(e.clientY / innerHeight) * 2 + 1); });
cv.addEventListener('pointerdown', e => { if (!started) return; cv.setPointerCapture(e.pointerId); ptrs.set(e.pointerId, { x: e.clientX, y: e.clientY }); idleT = 0;
  if (ptrs.size === 1) drag = { x: e.clientX, y: e.clientY, moved: 0, pick: pickAt(e.clientX, e.clientY, e.pointerType) };
  if (ptrs.size === 2) { const [a, b] = [...ptrs.values()]; pinch0 = Math.hypot(a.x - b.x, a.y - b.y); drag = null; } });
cv.addEventListener('pointermove', e => { const p = ptrs.get(e.pointerId); if (!p) return; p.x = e.clientX; p.y = e.clientY; idleT = 0;
  if (ptrs.size === 2) { const [a, b] = [...ptrs.values()]; const d = Math.hypot(a.x - b.x, a.y - b.y); if (pinch0) cam.tdist = Math.max(ZMIN, Math.min(ZMAX, cam.tdist * pinch0 / d)); pinch0 = d; return; }
  if (!drag) return; const dx = e.clientX - drag.x, dy = e.clientY - drag.y; drag.moved += Math.abs(dx) + Math.abs(dy); drag.x = e.clientX; drag.y = e.clientY;
  if (drag.moved > (e.pointerType === 'mouse' ? 6 : 14)) { cam.yaw -= dx * .006; cam.pitch = Math.max(-.6, Math.min(1.25, cam.pitch + dy * .004)); cam.free = 2.5; cv.style.cursor = 'grabbing'; } });
function pickAt(x, y, type) { mouse.set(x / innerWidth * 2 - 1, -(y / innerHeight) * 2 + 1); ray.setFromCamera(mouse, camera); const h = ray.intersectObjects(nodes, false)[0]; let hi = h ? h.object.userData.i : -1;
  if (hi < 0) { let bd = type === 'mouse' ? 18 : 40; nodes.forEach((n, k) => { const p = screenPos(n); const d = Math.hypot(p.x - x, p.y - y); if (p.z < 1 && d < bd && n.getWorldPosition(new THREE.Vector3()).distanceTo(camera.position) < 700) { bd = d; hi = k; } }); } return hi; }
function endPtr(e) { if (!ptrs.has(e.pointerId)) return; ptrs.delete(e.pointerId); if (ptrs.size < 2) pinch0 = 0;
  if (drag && ptrs.size === 0) { if (drag.moved <= (e.pointerType === 'mouse' ? 6 : 14)) { let hi = drag.pick; if (hi < 0) hi = pickAt(e.clientX, e.clientY, e.pointerType); if (hi >= 0) { select(hi); open(hi); navigator.vibrate?.(8); } }
    drag = null; cv.style.cursor = ''; } }
cv.addEventListener('pointerup', endPtr); cv.addEventListener('pointercancel', e => { ptrs.delete(e.pointerId); if (!ptrs.size) { drag = null; pinch0 = 0; cv.style.cursor = ''; } });
cv.addEventListener('wheel', e => { if (!started) return; e.preventDefault(); idleT = 0; cam.tdist = Math.max(ZMIN, Math.min(ZMAX, cam.tdist * Math.exp(e.deltaY * .0012))); }, { passive: false });
// touch joystick + up/down
const joy = { x: 0, y: 0, u: 0 };
if (matchMedia('(pointer:coarse)').matches || isMobile) { document.body.insertAdjacentHTML('beforeend', '<div id="joy" aria-label="Flug-Joystick"><i></i></div><div id="joyud"><button type="button" data-u="1" aria-label="steigen">▲</button><button type="button" data-u="-1" aria-label="sinken">▼</button></div>');
  const J = $('#joy'), K = J.querySelector('i'); let jid = null, c0 = null;
  J.addEventListener('pointerdown', e => { jid = e.pointerId; J.setPointerCapture(jid); const r = J.getBoundingClientRect(); c0 = { x: r.left + r.width / 2, y: r.top + r.height / 2, R: r.width / 2 }; B.travel = null; });
  J.addEventListener('pointermove', e => { if (e.pointerId !== jid) return; let dx = (e.clientX - c0.x) / c0.R, dy = (e.clientY - c0.y) / c0.R; const l = Math.hypot(dx, dy); if (l > 1) { dx /= l; dy /= l; } joy.x = dx; joy.y = dy; K.style.transform = `translate(${dx * 34}px,${dy * 34}px)`; });
  const end = () => { jid = null; joy.x = joy.y = 0; K.style.transform = ''; }; J.addEventListener('pointerup', end); J.addEventListener('pointercancel', end);
  $('#joyud').querySelectorAll('button').forEach(b => { b.onpointerdown = () => { joy.u = +b.dataset.u; B.travel = null; }; b.onpointerup = b.onpointerleave = () => joy.u = 0; }); }
function cycleQ() { qMode = qMode === 'AUTO' ? 'HIGH' : qMode === 'HIGH' ? 'LOW' : 'AUTO'; if (qMode !== 'AUTO') quality = qMode.toLowerCase(); applyQuality(); }
$('#q').onclick = cycleQ;
window.__studiusQ = (q) => { qMode = q.toUpperCase(); if (q !== 'auto') quality = q; applyQuality(); };
window.__studiusCat = (c) => setCat(c);
let rsT = 0; const onResize = () => { camera.aspect = innerWidth / innerHeight; camera.updateProjectionMatrix(); applyQuality(); if (innerWidth < 700) { pop.style.left = ''; pop.style.top = ''; } placePop(); };
addEventListener('resize', () => { cancelAnimationFrame(rsT); rsT = requestAnimationFrame(onResize); }); addEventListener('orientationchange', () => setTimeout(onResize, 250)); screen.orientation?.addEventListener?.('change', () => setTimeout(onResize, 250));
// gamepad: left stick fly, right stick camera, A up / open near, B close, LT/RT down/up, LB/RB studio prev/next
let gpCool = 0; const pad = { x: 0, y: 0, u: 0 };
function pollPad() { const p = navigator.getGamepads ? [...navigator.getGamepads()].find(Boolean) : null; pad.x = pad.y = pad.u = 0; if (!p) return;
  const dz = (v) => Math.abs(v) > .15 ? v : 0; pad.x = dz(p.axes[0] || 0); pad.y = dz(p.axes[1] || 0); if (pad.x || pad.y) B.travel = null;
  if (dz(p.axes[2] || 0)) { cam.yaw -= p.axes[2] * .04; cam.free = 2; } if (dz(p.axes[3] || 0)) cam.pitch = Math.max(-.6, Math.min(1.25, cam.pitch + p.axes[3] * .02));
  pad.u = (p.buttons[7]?.value || 0) - (p.buttons[6]?.value || 0) + (p.buttons[0]?.pressed && B.near < 0 ? 1 : 0);
  if (gpCool-- > 0) return; const v = visible(), k = v.indexOf(sel);
  if (!started && p.buttons.some(b => b.pressed)) { start(); gpCool = 20; return; }
  if (p.buttons[5]?.pressed) { select(v[(k + 1) % v.length]); focusNode(sel); gpCool = 16; }
  else if (p.buttons[4]?.pressed) { select(v[(k - 1 + v.length) % v.length]); focusNode(sel); gpCool = 16; }
  else if (p.buttons[0]?.pressed && B.near >= 0 && openId == null) { open(B.near); gpCool = 20; } else if (p.buttons[1]?.pressed) { close(); gpCool = 20; } }

/* ---------- intro: cinematic flythrough (void → stinger shard → east land → mountain → temple → core) ---------- */
const intro = $('#intro'); let introT = 0;
const stage = (n, ms) => setTimeout(() => !started && intro.classList.add('s' + n), ms);
stage(1, 120); stage(2, 12200); stage(3, 12900); stage(4, 13600); stage(5, 14600);
const peakY = W.peak;
const SHOTS = [ // sunrise wide on the crashed stinger → along its overgrown back → the terraces → ground level
  [0, [5200, 1900, 7600], [-2800, 300, 300]], [4, [4200, 1500, 5200], [-1500, 400, 400]], [7.5, [2600, 1300, 2600], [-900, 700, 400]],
  [10.5, [900, 1050, 1300], [-1000, 650, 0]], [13, [300, 760, 500], [-700, 600, 0]], [15.5, null, null]];
const CAPS = [[0, 'Der Ahnen-Stachel · 10 km'], [4, 'Sein überwachsener Rücken'], [7.5, 'Gipfel · Tempel · Bergsee'], [10.5, 'Fünf Terrassen der Studios'], [13, 'Der Pfad']];
document.body.insertAdjacentHTML('beforeend', '<div id="cine" aria-hidden="true"><i class="lb t"></i><i class="lb b"></i><p class="cap"></p></div>');
const cine = $('#cine'), capEl = cine.querySelector('.cap'); let capI = -1;
const ease = (x) => x < .5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2;
const pA = new THREE.Vector3(), pB = new THREE.Vector3(), lA = new THREE.Vector3(), lB = new THREE.Vector3(), introLook = new THREE.Vector3();
function introCam(t) { let i = 0; while (i < SHOTS.length - 2 && t > SHOTS[i + 1][0]) i++; const [t0, p0, l0] = SHOTS[i], [t1, p1, l1] = SHOTS[i + 1];
  if (!p1) { camera.position.set(...p0); introLook.set(...l0); camera.lookAt(introLook); return; }
  const k = ease(Math.min(1, (t - t0) / (t1 - t0))); pA.set(...p0); pB.set(...p1); lA.set(...l0); lB.set(...l1); camera.position.lerpVectors(pA, pB, k); introLook.lerpVectors(lA, lB, k); camera.lookAt(introLook);
  const ci = CAPS.findLastIndex(c => t >= c[0]); if (ci !== capI) { capI = ci; capEl.classList.remove('on'); setTimeout(() => { capEl.textContent = CAPS[ci][1]; capEl.classList.add('on'); }, 250); } }
intro.addEventListener('pointermove', e => { const x = e.clientX / innerWidth - .5, y = e.clientY / innerHeight - .5; $('#reveal').style.transform = `translate(${x * -18}px,${y * -14}px) rotateY(${x * 6}deg)`; });
function start() {
  if (started) return; started = true; prefetch(); beep(110, .5, 'sine', .06);
  intro.classList.add('out'); cine.classList.add('out'); setTimeout(() => { intro.remove(); cine.remove(); }, 1100);
  ['#hud', '#hint', '#core-stats', '#frame', '#mm'].forEach(s => $(s).hidden = false); document.body.classList.add('live'); setCat('Alle'); select(0);
  camT.copy(camera.position); cam.yaw = B.yaw + Math.PI; cam.pitch = .3;
}
$('#skip').onclick = (e) => { e.stopPropagation(); start(); };
intro.addEventListener('pointerdown', (e) => { if (e.target.id !== 'skip') start(); });

/* ---------- loop ---------- */
const clock = new THREE.Clock(); let frames = 0, fpsT = 0, statT = 0, mmT = 0;
const mm = $('#mm'); const mmDots = STUDIOS.map((s, i) => { const c = document.createElementNS('http://www.w3.org/2000/svg', 'circle'); c.setAttribute('r', 2.6); mm.querySelector('#mmd').append(c); return c; });
const MMS = .0105, mmX = (x) => 50 + (x + 1100) * MMS, mmY = (z) => 50 + (z - 200) * MMS;
{ const o = W.outline, pts = [...o.map(([x, z, r]) => [x, z - r]), ...o.slice().reverse().map(([x, z, r]) => [x, z + r])]; const sv = (t, a) => { const e = document.createElementNS('http://www.w3.org/2000/svg', t); for (const k in a) e.setAttribute(k, a[k]); return e; };
  mm.querySelector('#mmd').before(sv('polygon', { points: pts.map(([x, z]) => mmX(x).toFixed(1) + ',' + mmY(z).toFixed(1)).join(' '), class: 'st' }));
  W.terraces.forEach(t => mm.querySelector('#mmd').before(sv('circle', { cx: mmX(t.pos.x), cy: mmY(t.pos.z), r: 5, class: 'tr' }))); mm.querySelector('.core').setAttribute('cx', mmX(W.top.x)); mm.querySelector('.core').setAttribute('cy', mmY(W.top.z)); }
const tlbls = W.terraces.map(t => { const d = document.createElement('div'); d.className = 'tlbl'; d.textContent = t.cat; d.onclick = (e) => { e.stopPropagation(); setCat(t.cat); }; $('#labels').append(d); return d; });
let mmBee = null;
function drawMinimap(v) { const vw = mm.querySelector('#mmv'); nodes.forEach((n, i) => { const c = mmDots[i], g = W.shrines[i].group; c.setAttribute('cx', mmX(g.position.x)); c.setAttribute('cy', mmY(g.position.z)); c.setAttribute('class', i === sel ? 'sel' : v.includes(i) ? 'on' : 'off'); });
  if (!mmBee) { mmBee = document.createElementNS('http://www.w3.org/2000/svg', 'circle'); mmBee.setAttribute('r', 3.4); mmBee.setAttribute('class', 'bee'); mm.append(mmBee); }
  mmBee.setAttribute('cx', Math.max(4, Math.min(96, mmX(B.pos.x)))); mmBee.setAttribute('cy', Math.max(4, Math.min(96, mmY(B.pos.z))));
  vw.setAttribute('transform', `translate(${mmX(B.pos.x) - 50} ${mmY(B.pos.z) - 50}) rotate(${-cam.yaw * 180 / Math.PI + 180} 50 50)`); }
const stats = $('#core-stats');
const AR = { pr: 1, ema: 16.7, t: 0, slow: 0 }; let lastT = performance.now();
function setPR(p) { if (!renderer) return; AR.pr = p; renderer.setPixelRatio(p); renderer.setSize(innerWidth, innerHeight, false); if (composer) { composer.setPixelRatio(p); composer.setSize(innerWidth, innerHeight); } }
let paused = document.hidden, ctxLost = false;
document.addEventListener('visibilitychange', () => { paused = document.hidden; lastT = performance.now(); if (paused) { ac?.suspend?.(); } else if (soundOn) ac?.resume?.(); });
if (renderer) { const c = renderer.domElement;
  c.addEventListener('webglcontextlost', e => { e.preventDefault(); ctxLost = true; if (!$('#ctxmsg')) document.body.insertAdjacentHTML('beforeend', '<div id="ctxmsg" role="status" style="position:fixed;left:50%;top:70px;transform:translateX(-50%);z-index:40;padding:6px 12px;border:1px solid #faa968;background:#000c;color:#faa968;font-size:12px;border-radius:6px">GPU-Kontext verloren – stelle wieder her…</div>'); });
  c.addEventListener('webglcontextrestored', () => { ctxLost = false; $('#ctxmsg')?.remove(); applyQuality(); setPR(AR.pr); lastT = performance.now(); }); }
window.__studiusLoseCtx = () => renderer?.forceContextLoss?.();
window.__studiusRestoreCtx = () => renderer?.forceContextRestore?.();
const camT = new THREE.Vector3(), look = new THREE.Vector3(), fwd = new THREE.Vector3(), rgt = new THREE.Vector3(), acc = new THREE.Vector3(), tmpV = new THREE.Vector3();
const angLerp = (a, b, k) => { let d = b - a; d = Math.atan2(Math.sin(d), Math.cos(d)); return a + d * k; };
function updateBee(dt, t) {
  const inF = (keys.f ? 1 : 0) - (keys.b ? 1 : 0) - joy.y - pad.y, inR = (keys.r ? 1 : 0) - (keys.l ? 1 : 0) + joy.x + pad.x, inU = (keys.u ? 1 : 0) - (keys.dn ? 1 : 0) + joy.u + pad.u;
  const moving = Math.abs(inF) + Math.abs(inR) + Math.abs(inU) > .05;
  if (B.travel) { const T = B.travel; T.t += dt / T.d; const k = ease(Math.min(1, T.t)); const arc = Math.sin(k * Math.PI) * Math.min(150, T.from.distanceTo(T.to) * .15);
    const p = tmpV.lerpVectors(T.from, T.to, k); p.y += arc; B.vel.subVectors(p, B.pos).divideScalar(Math.max(dt, 1e-3)); B.pos.copy(p); const sh = W.shrines[T.i].group.position; if (B.vel.lengthSq() > 4) B.yaw = angLerp(B.yaw, Math.atan2(-B.vel.z, B.vel.x), Math.min(1, dt * 5)); if (k > .85) B.yaw = angLerp(B.yaw, Math.atan2(-(sh.z - B.pos.z), sh.x - B.pos.x), Math.min(1, dt * 4)); if (T.t >= 1) { B.travel = null; cam.pitch = .32; } }
  else { fwd.set(Math.cos(cam.yaw + Math.PI), 0, -Math.sin(cam.yaw + Math.PI)); rgt.set(-fwd.z, 0, fwd.x).multiplyScalar(-1); rgt.set(fwd.z * -1, 0, fwd.x); rgt.set(-fwd.z, 0, fwd.x);
    const sp = keys.boost ? 320 : 45; acc.set(0, 0, 0).addScaledVector(fwd, inF).addScaledVector(rgt, inR); if (acc.lengthSq() > 1) acc.normalize(); acc.multiplyScalar(sp); acc.y = inU * sp * .7;
    B.vel.lerp(acc, Math.min(1, dt * (moving ? 2.6 : 1.6))); B.pos.addScaledVector(B.vel, dt);
    const hv = Math.hypot(B.vel.x, B.vel.z); if (hv > 1.5) B.yaw = angLerp(B.yaw, Math.atan2(-B.vel.z, B.vel.x), Math.min(1, dt * 6)); }
  const g = landH(B.pos.x, B.pos.z); if (B.pos.y < g + 2.2) { B.pos.y = g + 2.2; B.vel.y = Math.max(0, B.vel.y); }
  const R = Math.hypot(B.pos.x - MC.x, B.pos.z - MC.y); if (R > 60000) B.pos.addScaledVector(tmpV.set(MC.x - B.pos.x, 0, MC.y - B.pos.z).normalize(), (R - 60000)); B.pos.y = Math.min(30000, B.pos.y);
  const hover = Math.sin(t * 3.1) * .25; bee.position.set(B.pos.x, B.pos.y + hover, B.pos.z);
  const lat = THREE.MathUtils.clamp(inR * -.5 + (B.travel ? 0 : 0), -.6, .6); B.bank = THREE.MathUtils.lerp(B.bank, lat, Math.min(1, dt * 4));
  bee.rotation.set(B.bank, B.yaw, THREE.MathUtils.clamp(B.vel.y * .012, -.4, .4) - Math.min(.25, Math.hypot(B.vel.x, B.vel.z) * .004), 'YXZ');
  const fl = Math.sin(t * 60) * .9; bee.userData.wings.forEach(w => { w.piv.rotation.x = w.s * fl; });
  // proximity: fly INTO a shrine portal → open its studio
  let near = -1, nd = 1e9; nodes.forEach((n, i) => { const d = n.getWorldPosition(tmpV).distanceTo(B.pos); if (d < nd) { nd = d; near = i; } }); B.near = nd < 90 ? near : -1; window.__near = { i: B.near, d: +nd.toFixed(1) };
  if (nd > 40) B.armed = true;
  if (B.armed && nd < 7.5 && openId == null && !B.travel && started) { B.armed = false; select(near); open(near, true); }
  if (B.near >= 0 && B.near !== sel && openId == null) select(B.near);
  return moving; }
function frame(now) {
  requestAnimationFrame(frame);
  if (paused || ctxLost) { lastT = now ?? performance.now(); window.__paused = (window.__paused || 0) + (paused ? 1 : 0); return; }
  if (renderer && !renderer.domElement.getClientRects().length) return; // canvas not displayed → nothing to draw
  if (openId != null && !pop.hidden && (now ?? performance.now()) - (frame.lr || 0) < 500) return; frame.lr = now ?? performance.now(); // studio panel open → world idles at 2 fps (CPU/battery for the studio)
  now = now ?? performance.now(); const rawMs = now - lastT; lastT = now; const dt = Math.min(rawMs / 1000, .1) || .016; clock.elapsedTime += dt; const t = clock.elapsedTime;
  frames++; fpsT += dt; if (fpsT > 1) { const fps = Math.round(frames / fpsT); $('#fps').textContent = fps + ' fps'; window.__fps = fps; frames = 0; fpsT = 0; }
  if (renderer && started && qMode === 'AUTO') { AR.ema = AR.ema * .9 + rawMs * .1; AR.t += dt;
    if (AR.t > .6) { AR.t = 0; const mxp = quality === 'high' ? Math.min(devicePixelRatio, 2) : Math.min(devicePixelRatio, 1.25); let p = AR.pr;
      if (AR.ema > 19) p = Math.max(.6, p - (AR.ema > 30 ? .15 : .08)); else if (AR.ema < 14.5) p = Math.min(mxp, p + .05); if (Math.abs(p - AR.pr) > .01) setPR(+p.toFixed(2));
      AR.slow = (AR.pr <= .8 && AR.ema > 26) || AR.ema > 45 ? AR.slow + 1 : 0; if (AR.slow > 3 && quality === 'high') { quality = 'low'; applyQuality(); AR.slow = 0; } } }
  window.__pr = AR.pr; pollPad();
  if (shotCam) { camera.position.set(...shotCam[0]); introLook.set(...shotCam[1]); camera.lookAt(introLook); }
  else if (!started) { introT += dt; introCam(introT); if (introT > 16) start(); }
  else { idleT += dt; const moving = updateBee(dt, t);
    // third-person follow camera: behind the bee, user can orbit (drag/right stick), springs back while flying
    cam.free = Math.max(0, cam.free - dt); if (moving && cam.free <= 0 && !drag) cam.yaw = angLerp(cam.yaw, B.yaw + Math.PI, Math.min(1, dt * 1.6)); if (B.travel && !drag) cam.yaw = angLerp(cam.yaw, B.yaw + Math.PI, Math.min(1, dt * 2.2));
    cam.dist = THREE.MathUtils.lerp(cam.dist, cam.tdist + (B.travel ? 30 : 0) + Math.min(30, B.vel.length() * .06), Math.min(1, dt * 3));
    const cp = Math.cos(cam.pitch); tmpV.set(Math.cos(cam.yaw) * cp, Math.sin(cam.pitch), -Math.sin(cam.yaw) * cp).multiplyScalar(cam.dist).add(B.pos); tmpV.y += 2.5;
    const gh = landH(tmpV.x, tmpV.z) + 2.5; if (tmpV.y < gh) tmpV.y = gh;
    camT.lerp(tmpV, Math.min(1, dt * 6)); camera.position.copy(camT);
    const mob = innerWidth < 700, want = openId == null ? 0 : 1; lookK += (want - lookK) * Math.min(1, dt * 4);
    look.copy(B.pos); look.y += 1.5; if (!mob && lookK > .01) { rgt.set(Math.sin(cam.yaw), 0, Math.cos(cam.yaw)); look.addScaledVector(rgt, .32 * cam.dist * camera.aspect * lookK); } camera.lookAt(look); }
  W.update(t, dt, camera, started && !shotCam ? B.pos : introLook);
  if (bokeh && quality === 'high') { const f = started ? camera.position.distanceTo(B.pos) : camera.position.distanceTo(introLook) * .9; bokeh.uniforms.focus.value = f; bokeh.uniforms.aperture.value = started ? .00002 : 0; }
  if (started && !drag && mouse.x < 5 && openId == null) { ray.setFromCamera(mouse, camera); const h = ray.intersectObjects(nodes, false)[0]; cv.style.cursor = h ? 'pointer' : 'grab'; if (h && h.object.userData.i !== sel) select(h.object.userData.i); }
  if (renderer) { if (composer && (quality === 'high' || !soft)) composer.render(); else renderer.render(scene, camera); }
  if (started) {
    const placed = []; const camP = camera.position; const v = visible();
    const blk = ['#hud', '#core-stats', '#mm', '#pop', '#hint', '#bmc', '#joy', '#joyud'].map(q => $(q)).filter(e => e && !e.hidden && e.offsetParent !== null).map(e => e.getBoundingClientRect());
    nodes.map((n, i) => ({ n, i, d: n.getWorldPosition(tmpV).distanceTo(camP) })).sort((a, b) => a.d - b.d).forEach(({ n, i, d }, rank) => {
      const p = screenPos(n); const l = labels[i]; if (p.z >= 1 || (d > 3500 && i !== sel)) { l.style.display = 'none'; return; } l.style.display = '';
      const far = (rank > 7 || d > 1500) && i !== sel && i !== openId; l.classList.toggle('far', far);
      const w = far ? 30 : l.offsetWidth || 110, h = 26; let y = p.y - 30;
      for (let k = 0; k < 6; k++) { const hit = placed.find(r => Math.abs(r.x - p.x) < (r.w + w) / 2 + 4 && Math.abs(r.y - y) < h); if (!hit) break; y = hit.y + (y >= hit.y ? h : -h); }
      placed.push({ x: p.x, y, w });
      const lx0 = p.x - w / 2, lx1 = p.x + w / 2; l.classList.toggle('hid', blk.some(r => lx0 < r.right && lx1 > r.left && y - 13 < r.bottom && y + 13 > r.top)); l.style.transform = `translate(${p.x}px,${y}px) translate(-50%,-50%)`; l.style.zIndex = 100 - rank;
      l.classList.toggle('dim', !v.includes(i)); });
    W.terraces.forEach((t, k) => { const p = t.pos.clone().project(camera), d = t.pos.distanceTo(camP), l = tlbls[k]; l.style.display = p.z < 1 && d < 6000 ? '' : 'none'; l.classList.toggle('on', cat === t.cat); l.style.transform = `translate(${(p.x + 1) / 2 * innerWidth}px,${(1 - p.y) / 2 * innerHeight}px) translate(-50%,-50%)`; });
    if ((mmT += dt) > .1) { mmT = 0; drawMinimap(v); }
    if (openId != null && !pop.hidden) { const p = screenPos(nodes[openId]); const r = pop.getBoundingClientRect(); const wl = $('#wl');
      const tx = p.x < r.left ? r.left : r.right; wl.setAttribute('x1', p.x); wl.setAttribute('y1', p.y); wl.setAttribute('x2', tx); wl.setAttribute('y2', r.top + 14); }
    if ((statT += dt) > .5) { statT = 0; const ld = (55 + Math.sin(t * .7) * 20) | 0; stats.innerHTML = `<h4>STUDIUS</h4><dl><dt>Studios</dt><dd>${STUDIOS.length}</dd><dt>Kategorien</dt><dd>${CATS.length - 1}</dd><dt>Höhe</dt><dd>${Math.round(B.pos.y)} m</dd></dl><p>⌘K / Taste „/“ = Suchen</p>`; }
  }
}
setPR(1); applyQuality();
window.__studius = { STUDIOS, open: (i) => open(i), close, select: (i) => select(i), core: () => screenPos(core), get sel() { return sel; }, get openId() { return openId; }, get zoom() { return cam.dist; }, get th() { return cam.yaw; }, nodeScreen: (i) => screenPos(nodes[i]), open: (i) => { select(i); open(i); }, close: () => close(), get paused() { return paused; }, get ctxLost() { return ctxLost; } };
window.__world = { bee: B, cam, camera, W, keys, flyTo: (i) => { select(i); focusNode(i); }, shot: (pos, at) => { shotCam = pos ? [pos, at] : null; }, get quality() { return quality; }, setQ: (q) => { qMode = q.toUpperCase(); quality = q; applyQuality(); } };
if (gl3d) requestAnimationFrame(frame); else { setTimeout(() => start(), 7800);
  document.body.insertAdjacentHTML('beforeend', '<div style="position:fixed;left:14px;top:60px;z-index:16;color:#faa968;font-size:11px">⚠ WebGL nicht verfügbar – 2D-Modus</div>');
  STUDIOS.forEach((s, i) => { labels[i].style.transform = `translate(${80 + (i % 5) * 180}px,${140 + (i / 5 | 0) * 60}px)`; });
}