// Renderer, camera and the frame loop around a built scene. import * as THREE from 'three'; import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js'; import { buildScene } from './layout.js'; const SHOT = { // distance factor, elevation (radians) close: [0.72, 0.1], medium: [1.0, 0.2], wide: [1.75, 0.33], top: [1.25, 1.25], low: [0.95, 0.03], }; const FOV = 38; export class Stage { constructor(canvas) { this.canvas = canvas; this.renderer = new THREE.WebGLRenderer({ canvas, antialias: true, preserveDrawingBuffer: true }); this.renderer.setPixelRatio(Math.min(2, window.devicePixelRatio || 1)); this.renderer.shadowMap.enabled = true; this.renderer.shadowMap.type = THREE.PCFSoftShadowMap; this.renderer.toneMapping = THREE.NeutralToneMapping; this.scene = new THREE.Scene(); this.camera = new THREE.PerspectiveCamera(FOV, 1, 0.1, 600); this.controls = new OrbitControls(this.camera, canvas); this.controls.enableDamping = true; this.controls.maxPolarAngle = Math.PI / 2 - 0.01; this.t = 0; this.last = performance.now(); this.paused = false; this.built = null; this.sc = null; this.beat = 0; this.music = null; // set by main.js; without it animations run at 90 beats per minute this._p = new THREE.Vector3(); this._prev = new THREE.Vector3(); this._zoom = 1; this._pan = 0; // hand editing: click to select, drag to move this.selected = null; this.onSelect = () => {}; this.onMove = () => {}; this.ray = new THREE.Raycaster(); this.ptr = new THREE.Vector2(); this.selBox = new THREE.Box3(); this.helper = new THREE.Box3Helper(this.selBox, 0xffb454); this.helper.visible = false; this.scene.add(this.helper); this._drag = null; canvas.parentElement.addEventListener('pointerdown', (e) => this._down(e), { capture: true }); // before OrbitControls window.addEventListener('pointermove', (e) => this._dragMove(e)); window.addEventListener('pointerup', (e) => this._up(e)); new ResizeObserver(() => this.resize()).observe(canvas.parentElement); this.resize(); this.renderer.setAnimationLoop(() => this.frame()); } resize() { const el = this.canvas.parentElement, w = el.clientWidth || 800, h = el.clientHeight || 600; this.renderer.setSize(w, h, false); this.camera.aspect = w / h; this.camera.updateProjectionMatrix(); } /** * Rebuild everything from a scene description. * camera: 'reset' always reframes, 'auto' reframes when the scene's extent changes, 'keep' only when shot/zoom/cam change. */ setScene(sc, camera = 'reset') { const old = this.built, prevBox = old?.box; if (old) { this.scene.remove(old.root); old.dispose(); } const b = this.built = buildScene(sc); this.sc = sc; this.scene.add(b.root); this.scene.background = b.env.background; this.scene.fog = b.env.fog; this.controls.maxPolarAngle = sc.loc === 'space' ? Math.PI : Math.PI / 2 - 0.01; b.update(this.t, this.beat); b.root.updateMatrixWorld(true); const view = `${sc.shot}|${sc.zoom}|${sc.cam}`; const moved = !prevBox || prevBox.min.distanceTo(b.box.min) + prevBox.max.distanceTo(b.box.max) > 0.6; if (camera === 'reset' || view !== this._view || (camera === 'auto' && moved)) this.frameCamera(); if (this.selected && !sc.ents.some((e) => e.id === this.selected)) this.select(null); this._view = view; this.controls.autoRotate = sc.cam === 'orbit'; this.controls.autoRotateSpeed = 2.2; if (b.focus) b.focus.obj.getWorldPosition(this._prev); } // ---------------------------------------------------------------- selection and dragging select(id) { if (id === this.selected) return; this.selected = id; this.helper.visible = !!id; this.onSelect(id); } _pick(e) { if (!this.built) return null; const r = this.canvas.getBoundingClientRect(); this.ptr.set(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1); this.ray.setFromCamera(this.ptr, this.camera); for (const hit of this.ray.intersectObject(this.built.actors, true)) { for (let o = hit.object; o; o = o.parent) if (o.userData.entId) return { id: o.userData.entId, point: hit.point }; } return null; } /** The entity that actually owns the position: riders, orbiters and chasers move with their target. */ _anchor(id) { const ents = this.sc.ents, seen = new Set(); let e = ents.find((x) => x.id === id); while (e && e.ref && ['ride', 'on', 'around', 'over', 'chase'].includes(e.rel) && !seen.has(e.id)) { seen.add(e.id); e = ents.find((x) => x.id === e.ref) ?? e; } return e?.id; } /** Entities whose placement depends on `id` (including itself). */ _followers(id) { const ents = this.sc.ents, out = new Set(); for (const e of ents) { const seen = new Set(); for (let x = e; x && !seen.has(x.id); x = ents.find((y) => y.id === x.ref)) { seen.add(x.id); if (x.id === id) { out.add(e.id); break; } } } return out; } _down(e) { if (e.target !== this.canvas || e.button !== 0 || !e.isPrimary) return; const hit = this._pick(e); this._press = { x: e.clientX, y: e.clientY, hit: !!hit }; if (!hit) return; this.select(hit.id); const anchor = this._anchor(hit.id), movers = this._followers(anchor); const plane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -hit.point.y); const insts = this.built.insts.filter((i) => movers.has(i.ent.id) && !i.mount); for (const i of insts) i.shift = { x: 0, z: 0 }; this._drag = { anchor, plane, start: hit.point.clone(), insts, d: new THREE.Vector3(), moved: false }; this.controls.enabled = false; } _dragMove(e) { const d = this._drag; if (!d) return; if (Math.hypot(e.clientX - this._press.x, e.clientY - this._press.y) > 4) d.moved = true; const r = this.canvas.getBoundingClientRect(); this.ptr.set(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1); this.ray.setFromCamera(this.ptr, this.camera); const p = this.ray.ray.intersectPlane(d.plane, new THREE.Vector3()); if (!p) return; d.d.subVectors(p, d.start); const lim = 60; d.d.x = Math.max(-lim, Math.min(lim, d.d.x)); d.d.z = Math.max(-lim, Math.min(lim, d.d.z)); for (const i of d.insts) { i.shift.x = d.d.x; i.shift.z = d.d.z; } } _up(e) { const d = this._drag, p = this._press; this._press = null; if (d) { this._drag = null; this.controls.enabled = true; for (const i of d.insts) i.shift = null; if (d.moved) this.onMove(d.anchor, d.d.x, d.d.z); } else if (p && !p.hit && Math.hypot(e.clientX - p.x, e.clientY - p.y) < 5) { this.select(null); } } frameCamera() { const b = this.built, sc = this.sc; const tight = (sc.shot === 'close' || sc.cam === 'follow') && b.focus; const box = tight ? b.fbox.clone() : b.box; if (sc.cam === 'follow' && b.focus) { // frame the subject itself, not its whole path const g = b.focus.rig, s = b.focus.scale, p = b.focus.obj.getWorldPosition(new THREE.Vector3()); box.set(new THREE.Vector3(p.x - g.r * s * 1.6, p.y, p.z - g.r * s * 1.6), new THREE.Vector3(p.x + g.r * s * 1.6, p.y + g.h * s, p.z + g.r * s * 1.6)); } const c = box.getCenter(new THREE.Vector3()), size = box.getSize(new THREE.Vector3()); const aspect = Math.max(0.6, this.camera.aspect); const half = Math.max(size.y * 0.62, (Math.hypot(size.x, size.z) * 0.5) / aspect, 1.2) * 1.3; const [k, el] = SHOT[sc.shot] ?? SHOT.medium; const dist = (half / Math.tan((FOV * Math.PI) / 360)) * k * 1.22 ** (sc.zoom ?? 0); const az = 0.42; if (sc.shot === 'low') c.y = Math.max(c.y, size.y * 0.55); this.controls.target.copy(c); this.camera.position.set(c.x + dist * Math.sin(az) * Math.cos(el), Math.max(0.35, c.y + dist * Math.sin(el)), c.z + dist * Math.cos(az) * Math.cos(el)); if (sc.loc !== 'space' && sc.shot === 'low') this.camera.position.y = 0.4; this.camera.near = Math.max(0.05, dist / 200); this.camera.updateProjectionMatrix(); this._zoom = 1; this._pan = 0; this.controls.update(); } frame() { const now = performance.now(), dt = Math.min(0.1, (now - this.last) / 1000); this.last = now; if (!this.paused) { this.t += dt; // follow the music's clock when it is playing, otherwise keep time ourselves at its tempo this.beat = this.music?.beat() ?? this.beat + (dt * (this.music?.bpm ?? 90)) / 60; } const b = this.built; if (b) { b.update(this.t, this.beat); this.music?.frame(this.t, this.camera, this.sc.weather); const cam = this.sc.cam, tg = this.controls.target, cp = this.camera.position; if (cam === 'follow' && b.focus) { b.root.updateMatrixWorld(true); b.focus.obj.getWorldPosition(this._p); const d = this._p.clone().sub(this._prev); d.y *= 0.3; tg.add(d); cp.add(d); this._prev.copy(this._p); } else if (cam === 'pan') { const x = Math.sin(this.t * 0.45) * b.stageR * 0.7, d = x - this._pan; this._pan = x; tg.x += d; cp.x += d; } else if (cam === 'zoomin' || cam === 'zoomout') { const u = 0.5 - 0.5 * Math.cos(this.t * 0.55), z = cam === 'zoomin' ? 1 - 0.5 * u : 1 + 0.8 * u; cp.sub(tg).multiplyScalar(z / this._zoom).add(tg); this._zoom = z; } } if (this.selected && b) { b.root.updateMatrixWorld(true); this.selBox.makeEmpty(); for (const i of b.insts) if (i.ent.id === this.selected) this.selBox.expandByObject(i.obj); this.helper.visible = !this.selBox.isEmpty(); } this.controls.update(); this.renderer.render(this.scene, this.camera); } /** Static snapshot of the current frame as a .glb (animations are procedural and are not exported). */ exportGLB() { return new Promise((resolve, reject) => { if (!this.built) return reject(new Error('empty scene')); new GLTFExporter().parse(this.built.actors, (buf) => resolve(new Blob([buf], { type: 'model/gltf-binary' })), reject, { binary: true, onlyVisible: true }); }); } }