// stage.js — the 3D stage: renderer, IBL scene, entities on wrappers, gizmo, retarget cache. // Timeline (Lane B) talks to the stage ONLY through this API (PLAN §4.2). import * as THREE from 'three'; import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; import { TransformControls } from 'three/addons/controls/TransformControls.js'; import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js'; import { parseAny, captureRest, disposeRoot, stats, bakeRetarget } from './room3d.js'; const ASSET_URL = p => 'assets/file?path=' + encodeURIComponent(p); // Loose viseme matcher: map a character's morph-target names (CC "V_Open", ARKit "jawOpen", plain // "AA"…) to a canonical set the timeline drives. Detection only — Rhubarb→keyframes is Lane B's. const VISEMES = { A: [/\bah\b/, /(^|_)aa?($|_)/, /jaw[_ ]?open/, /(^|[_-])open($|[_-])/, /mouth_?open/], E: [/\bee\b/, /(^|_)e[hr]?($|_)/, /wide/, /smile/], I: [/(^|_)i[hy]?($|_)/, /affric/], O: [/\boh\b/, /(^|_)o($|_)/, /tight[_-]?o/, /round/], U: [/\boo\b/, /(^|_)u[w]?($|_)/, /pucker/, /funnel/, /w[_-]?oo/, /(^|_)tight($|_)/], MBP: [/mbp/, /b[_-]?m[_-]?p/, /explos/, /mouth_?close/, /press/, /lip[_-]?open/, /(^|_)pp($|_)/], FV: [/(^|_)f[_-]?v($|_)/, /dental[_-]?lip/, /(^|_)ff($|_)/], L: [/t[_-]?l[_-]?d[_-]?n/, /tongue/, /(^|_)l($|_)/, /(^|_)dd($|_)/, /(^|_)nn($|_)/], }; function detectVisemes(root){ const morphs = new Map(); // rawName(lower) -> [{mesh, idx}] (head, teeth, tongue often share a name) root.traverse(o => { if(o.isMesh && o.morphTargetDictionary) for(const [name, idx] of Object.entries(o.morphTargetDictionary)){ const k = name.toLowerCase(); (morphs.get(k) || morphs.set(k, []).get(k)).push({mesh:o, idx}); } }); const visemes = {}; // SYNC5: ARKit side suffixes (_L/_R) made /(^|_)l($|_)/ swallow eyeblink_l & co — // never match non-mouth regions, and match against the side-stripped name. const NONMOUTH = /eye|blink|brow|squint|look|nose|cheek/; for(const [canon, pats] of Object.entries(VISEMES)){ const hits = [...morphs.keys()].filter(k => !NONMOUTH.test(k) && pats.some(p => p.test(k.replace(/(.)[_-][lr]$/, '$1')))); if(hits.length) visemes[canon] = hits; } return { morphs, visemes }; } // runnable check for the matcher (assert-based). Call visemeSelfCheck() from the console. export function visemeSelfCheck(){ const dict = {'V_Open':0,'V_Explosive':1,'jawOpen':2,'mouthPucker':3,'mouthFunnel':4, 'mouthClose':5,'V_Dental_Lip':6,'V_Tongue_up':7,'EyeBlink_L':8,'browDown_L':9,'mouthSmile_L':10}; const mesh = { isMesh:true, morphTargetDictionary:dict, morphTargetInfluences:new Array(11).fill(0) }; const { morphs, visemes } = detectVisemes({ traverse(cb){ cb(mesh); } }); const has = v => v in visemes; const detectOk = ['A','U','MBP','FV','L'].every(has) // open/jaw, pucker/funnel, explos/close, dental, tongue && !has('I') && !has('O') // SYNC5 regression guard: side-suffixed ARKit names must land on the RIGHT viseme — // L is tongue only (no blink/brow/smile bleed), E gets the side-stripped smile. && visemes.L.length === 1 && visemes.L[0] === 'v_tongue_up' && has('E') && visemes.E.includes('mouthsmile_l'); // canonical 'A' drives every mesh morph mapped to it (jawOpen idx2 + V_Open idx0) for(const r of visemes.A) for(const {idx} of morphs.get(r)) mesh.morphTargetInfluences[idx] = 0.7; const driveOk = mesh.morphTargetInfluences[0] === 0.7 && mesh.morphTargetInfluences[2] === 0.7 && mesh.morphTargetInfluences[8] === 0; // blink untouched return { ok: detectOk && driveOk, found: Object.keys(visemes).sort().join(','), visemes }; } export class Stage { constructor(viewEl){ this.view = viewEl; this._entities = new Map(); this._selCbs = []; this._changeCbs = []; this._selected = null; this._activeCamId = null; this._mixerAuto = true; // Stage advances mixers each frame until Timeline takes over this._idc = 0; this._clipSrc = new Map(); // path -> {root, rest, anims} (parse+rest cached) this._baked = new Map(); // id|path|index -> AnimationClip const r = this.renderer = new THREE.WebGLRenderer({antialias:true, preserveDrawingBuffer:true}); r.setPixelRatio(devicePixelRatio); r.shadowMap.enabled = true; view.appendChild(r.domElement); this._paused = false; // M3 final render freezes the director loop, then drives renderActiveCamera // PiP overlay — the active camera's view (bottom-right). CSS sizes it (~24% w); the buffer // stays small. Click to swap which view is main vs inset. const pip = this._pip = document.createElement('canvas'); pip.width = 320; pip.height = 180; pip.className = 'pip'; pip.style.display = 'none'; pip.title = 'click to swap with the main view'; this._pipSwap = false; pip.addEventListener('click', () => { this._pipSwap = !this._pipSwap; }); view.appendChild(pip); const scene = this.scene = new THREE.Scene(); const cam = this._dirCam = new THREE.PerspectiveCamera(45, 1, 0.01, 3000); cam.position.set(0, 1.6, 5); const ctr = this.controls = new OrbitControls(cam, r.domElement); ctr.enableDamping = true; ctr.target.set(0, 1.0, 0); const pmrem = new THREE.PMREMGenerator(r); scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture; pmrem.dispose(); // default lights — replaced/dimmed once the scene carries light entities this._defHemi = new THREE.HemisphereLight(0xffffff, 0x555a66, 2.2); scene.add(this._defHemi); this._defKey = new THREE.DirectionalLight(0xffffff, 1.8); this._defKey.position.set(3, 5, 2); scene.add(this._defKey); const floor = new THREE.Mesh(new THREE.CircleGeometry(30, 64).rotateX(-Math.PI/2), new THREE.MeshStandardMaterial({color:0x141a20, roughness:.97})); floor.receiveShadow = true; scene.add(floor); scene.add(new THREE.GridHelper(60, 60, 0x2a323b, 0x1c232b)); // gizmo const tc = this._tc = new TransformControls(cam, r.domElement); tc.addEventListener('dragging-changed', e => { ctr.enabled = !e.value; }); tc.addEventListener('mouseUp', () => { if(this._selected) this._fireChange(this.getEntity(this._selected)); }); scene.add(tc); addEventListener('keydown', e => { if(!this._selected) return; if(e.key==='w') tc.setMode('translate'); else if(e.key==='e') tc.setMode('rotate'); else if(e.key==='r') tc.setMode('scale'); }); r.domElement.addEventListener('click', e => this._pick(e)); this.clock = new THREE.Clock(); this._resize(); addEventListener('resize', () => this._resize()); const loop = () => { requestAnimationFrame(loop); const dt = this.clock.getDelta(); if(this._paused) return; // M3: caller drives rendering deterministically ctr.update(); if(this._mixerAuto) for(const en of this._entities.values()) en.mixer && en.mixer.update(dt); // inset first (it scribbles onto the main canvas), then the main view last so it wins if(this._activeCamId && pip.style.display !== 'none') this._render(this._pipSwap ? this._dirCam : this._activeCam(), pip); this._render((this._pipSwap && this._activeCamId) ? this._activeCam() : this._dirCam, null); }; loop(); } _resize(){ const w=this.view.clientWidth, h=this.view.clientHeight; this.renderer.setSize(w, h, false); this._dirCam.aspect = w/h; this._dirCam.updateProjectionMatrix(); // size the inset here — CSS aspect-ratio/% is unreliable on a const pw = Math.max(180, Math.min(340, w*0.24)); this._pip.style.width = Math.round(pw)+'px'; this._pip.style.height = Math.round(pw*9/16)+'px'; } // ---- callbacks ---- onSelect(cb){ this._selCbs.push(cb); } onChange(cb){ this._changeCbs.push(cb); } _fireChange(en){ for(const cb of this._changeCbs) cb(en); } // ---- entity lifecycle ---- entities(){ return [...this._entities.values()]; } getEntity(id){ return this._entities.get(id); } async addEntity(desc){ const id = desc.id || ('e' + (++this._idc)); if(this._idc <= (parseInt(String(id).slice(1)) || 0)) this._idc = parseInt(String(id).slice(1)) || this._idc; const wrapper = new THREE.Group(); wrapper.userData.entityId = id; const noAsset = desc.kind === 'camera' || desc.kind === 'light'; // rig entities have no file const en = { id, kind: desc.kind, label: desc.label || desc.kind, source: desc.source || (noAsset ? {type:'none'} : null), params: {...(desc.params||{})}, wrapper, root:null, mixer:null, rest:null, cam:null, light:null, morphs:null, visemes:null, video:null }; if(desc.kind === 'character' || desc.kind === 'prop'){ const { root } = await this._loadAsset(desc); this._normalize(root, desc.kind === 'character'); root.traverse(o=>{ if(o.isMesh){ o.castShadow = true; o.receiveShadow = true; } if(o.isSkinnedMesh) o.frustumCulled=false; }); wrapper.add(root); en.root = root; if(desc.kind === 'character'){ en.rest = captureRest(root); en.mixer = new THREE.AnimationMixer(root); const v = detectVisemes(root); en.morphs = v.morphs; en.visemes = v.visemes; } } else if(desc.kind === 'backdrop'){ en.root = await this._buildBackdrop(en); wrapper.add(en.root); } else if(desc.kind === 'screen'){ en.root = await this._buildScreen(en); wrapper.add(en.root); } else if(desc.kind === 'camera'){ const fov = en.params.fov || 45; en.cam = new THREE.PerspectiveCamera(fov, 16/9, 0.05, 3000); wrapper.add(en.cam); const proxy = new THREE.Mesh(new THREE.ConeGeometry(0.18, 0.35, 4).rotateX(-Math.PI/2), new THREE.MeshBasicMaterial({color:0x43c0cf, wireframe:true})); proxy.position.z = 0.18; wrapper.add(proxy); } else if(desc.kind === 'light'){ this._buildLight(en); } else throw new Error('unknown kind: ' + desc.kind); this.scene.add(wrapper); this._entities.set(id, en); if(desc.transform) this.setTransform(id, desc.transform); this._fireChange(en); // tlui/dock build a row per entity off onChange (incl. applyState loads) return en; } removeEntity(id){ const en = this._entities.get(id); if(!en) return; if(this._selected === id) this.select(null); this._dropVideo(en); if(en.root) disposeRoot(en.root); if(en.light) en.light.parent && en.light.parent.remove(en.light); this.scene.remove(en.wrapper); this._entities.delete(id); for(const k of [...this._baked.keys()]) if(k.startsWith(id+'|')) this._baked.delete(k); if(en.kind === 'light') this._refreshDefaults(); this._fireChange(en); // trigger a row resync so the deleted entity drops out } async _loadAsset(desc){ let buf, name; if(desc.source && desc.source.type === 'upload'){ if(!desc._buf) throw new Error('upload entity has no buffer'); buf = desc._buf; name = desc.source.path; } else { const path = desc.source.path; const res = await fetch(ASSET_URL(path)); if(!res.ok) throw new Error('asset fetch ' + res.status + ': ' + path); buf = await res.arrayBuffer(); name = path; } return parseAny(buf, name); } _normalize(root, isChar){ root.updateMatrixWorld(true); const box = new THREE.Box3().setFromObject(root); if(box.isEmpty() || !isFinite(box.min.x)) return; if(isChar){ const size = box.getSize(new THREE.Vector3()); const s = 1.7 / (Math.max(size.x, size.y, size.z) || 1); root.scale.setScalar(s); root.updateMatrixWorld(true); } const b = new THREE.Box3().setFromObject(root); root.position.x -= (b.min.x + b.max.x)/2; root.position.z -= (b.min.z + b.max.z)/2; root.position.y -= b.min.y; // feet on the floor } // Backdrop plate — image OR video (M6). params.mode: plane|corner|dome|video ('video' = a // plane; the other modes also accept .mp4 sources). Video plates show their poster jpg (the // server's same-stem sidecar) until first play/seek, then swap to the live VideoTexture. async _buildBackdrop(en){ const p = en.params; const src = p.image || (en.source && en.source.path) || ''; const upload = en.source && en.source.type === 'upload'; const url = upload ? en.source._url : ASSET_URL(src); const isVideo = p.mode === 'video' || /\.(mp4|webm|mov)$/i.test(src); let tex, aspect, vidTex = null, poster = null; if(isVideo){ const { video, texture } = await this._makeVideo(url, src); en.video = video; en.videoTex = vidTex = texture; aspect = (video.videoWidth / video.videoHeight) || 16/9; poster = upload ? null : await this._posterTex(src); tex = poster || vidTex; } else { tex = await new THREE.TextureLoader().loadAsync(url); tex.colorSpace = THREE.SRGBColorSpace; aspect = (tex.image.width / tex.image.height) || 1; } const w = p.width || 10, h = w / aspect; const grp = new THREE.Group(), mats = []; if(p.mode === 'dome'){ const dm = new THREE.MeshBasicMaterial({map:tex, side:THREE.BackSide}); mats.push(dm); grp.add(new THREE.Mesh(new THREE.SphereGeometry(40, 40, 24), dm)); } else { const mat = new THREE.MeshStandardMaterial({map:tex, roughness:1, metalness:0}); mats.push(mat); const wall = new THREE.Mesh(new THREE.PlaneGeometry(w, h), mat); wall.position.y = h/2; wall.receiveShadow = true; grp.add(wall); if(p.mode === 'corner'){ // cheap "L": duplicate lower third laid flat as ground const gh = h/3, gm = mat.clone(); mats.push(gm); const g = new THREE.Mesh(new THREE.PlaneGeometry(w, gh), gm); g.rotation.x = -Math.PI/2; g.position.z = gh/2; g.receiveShadow = true; grp.add(g); wall.position.z = -gh/2; } } if(vidTex && poster) this._swapOnPlay(en.video, vidTex, mats); if(en.video && this._mixerAuto) en.video.play().catch(()=>{}); // ambient preview until a timeline owns the clock return grp; } // In-set display (M6 `screen` kind): a video plane with an emissive boost so TVs/club // screens/jumbotrons read "on" under any lighting preset. params {video, width, emissive}. // ponytail: CRT curve skipped — flat plane until a real TV asset asks for it. async _buildScreen(en){ const p = en.params; const src = p.video || (en.source && en.source.path) || ''; const upload = en.source && en.source.type === 'upload'; const { video, texture } = await this._makeVideo(upload ? en.source._url : ASSET_URL(src), src); en.video = video; en.videoTex = texture; const aspect = (video.videoWidth / video.videoHeight) || 16/9; const poster = upload ? null : await this._posterTex(src); const tex = poster || texture; const w = p.width || 3, h = w / aspect; const mat = new THREE.MeshStandardMaterial({ map:tex, emissive:0xffffff, emissiveMap:tex, emissiveIntensity: p.emissive ?? 0.6, roughness:0.4, metalness:0 }); if(poster) this._swapOnPlay(video, texture, [mat]); if(this._mixerAuto) video.play().catch(()=>{}); const mesh = new THREE.Mesh(new THREE.PlaneGeometry(w, h), mat); mesh.position.y = h/2; const grp = new THREE.Group(); grp.add(mesh); return grp; } //