/* Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0. */ "use strict"; const actors = new Map(), colors = ["#79d5be", "#f5bc73", "#8eb5fc", "#dc99d6", "#becc72"]; const session = crypto.randomUUID().slice(0,8), canvas = document.querySelector("#map"), ctx = canvas.getContext("2d"); let audioContext, nextActor = 1, poseTimer, previousTime = performance.now(); let wallController,wallConnectPromise,wallPending,appliedScene,wallRetryTimer,wallRetryAttempt=0,wallRevision=0; const log = (text) => { const el=document.querySelector("#log"); el.textContent=(new Date().toLocaleTimeString()+" "+text+"\n"+el.textContent).slice(0,4000); }; async function audio() { audioContext ??= new AudioContext({sampleRate:48000}); await audioContext.resume(); return audioContext; } function setPosition(actor, key, value) { actor[key]=value; const input=actor.el.querySelector(`[data-axis="${key}"]`); input.value=value; input.closest(".axis").querySelector("output").value=Number(value).toFixed(key==="yaw"?0:1); } function addActor(initial={}) { const number=nextActor++, id=`actor-${number}-${session}`, el=document.querySelector("#actor-template").content.firstElementChild.cloneNode(true); const actor={id,number,el,x:0,y:0,z:0,yaw:0,seq:0,color:colors[(number-1)%colors.length],room:null,connected:false,connecting:false,generation:0,desiredConnected:false,retryAttempt:0}; actors.set(id,actor); el.style.setProperty("--actor-color",actor.color); el.querySelector("strong").textContent=`Актор ${number}`; for (const key of ["x","y","z","yaw"]) { setPosition(actor,key,initial[key]??0); el.querySelector(`[data-axis="${key}"]`).addEventListener("input",event=>{setPosition(actor,key,Number(event.target.value));}); } el.querySelector(".frequency").value=initial.frequency??440+number*110; el.querySelector(".frequency").addEventListener("input",()=>{if(actor.oscillator)actor.oscillator.frequency.setTargetAtTime(Number(el.querySelector(".frequency").value),audioContext.currentTime,.02);}); el.querySelector(".source").addEventListener("change",()=>{if(actor.connected)changeInput(actor);}); el.querySelector(".connect").addEventListener("click",()=>actor.desiredConnected?disconnect(actor):connect(actor)); el.querySelector(".remove").addEventListener("click",async()=>{await disconnect(actor); actors.delete(id); el.remove(); updateAudition();}); document.querySelector("#actors").append(el); updateAudition(); return actor; } function updateAudition() { const select=document.querySelector("#audition"), selected=select.value; select.replaceChildren(new Option("Тишина","")); for(const actor of actors.values())select.add(new Option(`Актор ${actor.number}`,actor.id)); select.value=actors.has(selected)?selected:""; applyAudition(); } function applyAudition() { const selected=document.querySelector("#audition").value; for(const actor of actors.values())if(actor.outputElement)actor.outputElement.volume=actor.id===selected?1:0; } function pose(actor) { const buffer=new ArrayBuffer(44), v=new DataView(buffer), yaw=actor.yaw*Math.PI/180; v.setUint8(0,1);v.setUint32(4,++actor.seq,true);v.setFloat64(8,performance.now(),true); [actor.x,actor.y,actor.z,0,0,Math.sin(yaw/2),Math.cos(yaw/2)].forEach((n,i)=>v.setFloat32(16+i*4,n,true)); return new Uint8Array(buffer); } function sendPose(actor) { if(!actor.connected||!actor.room||actor.posePending)return; actor.posePending=true; actor.room.localParticipant.publishData(pose(actor),{reliable:false,topic:"sverse.spatial.pose.v1"}) .catch(error=>{if(performance.now()-(actor.lastPoseError??-Infinity)>5000){actor.lastPoseError=performance.now();log(`${actor.id}: ${error.message}`);}}) .finally(()=>actor.posePending=false); } function startPoseTimer() { clearInterval(poseTimer); poseTimer=setInterval(()=>{for(const actor of actors.values())sendPose(actor);},Number(document.querySelector("#interval").value)); } function attachOutput(actor, track, publication) { if(publication.trackName!=="spatial_mix" || track.kind!==LivekitClient.Track.Kind.Audio)return; clearOutput(actor); // Keep a playing media element attached to the remote WebRTC track. Chrome // can leave remote audio silent when it is consumed only through Web Audio. const element=track.attach();element.autoplay=true;element.volume=0;element.hidden=true; document.body.append(element);actor.outputElement=element;actor.outputTrack=track; element.play().catch(error=>log(`Актор ${actor.number}: нажмите «Включить звук» (${error.message})`)); for(const node of actor.outputNodes??[])node.disconnect(); const source=audioContext.createMediaStreamSource(new MediaStream([track.mediaStreamTrack])), gain=audioContext.createGain(), splitter=audioContext.createChannelSplitter(2), left=audioContext.createAnalyser(), right=audioContext.createAnalyser(); left.fftSize=right.fftSize=8192;left.smoothingTimeConstant=right.smoothingTimeConstant=.1; source.connect(splitter); splitter.connect(left,0); splitter.connect(right,1); source.connect(gain);gain.gain.value=0; gain.connect(audioContext.destination); actor.outputGain=gain;actor.outputNodes=[source,gain,splitter,left,right]; actor.analyzers=[left,right];actor.meterSamples=new Float32Array(1024);actor.hasMix=true; actor.spectrum=new Float32Array(left.frequencyBinCount);actor.lastSpectrumTime=0; actor.el.querySelector(".state").textContent="Персональный стереомикс";applyAudition();log(`Актор ${actor.number}: получен spatial_mix (${track.mediaStreamTrack.getSettings().channelCount??"Opus"} канала)`); } function clearOutput(actor) { for(const node of actor.outputNodes??[])node.disconnect(); if(actor.outputElement){actor.outputTrack?.detach(actor.outputElement);actor.outputElement.pause();actor.outputElement.srcObject=null;actor.outputElement.remove();} actor.outputNodes=[];actor.outputElement=null;actor.outputTrack=null;actor.outputGain=null;actor.analyzers=null;actor.hasMix=false; for(const meter of actor.el.querySelectorAll("meter"))meter.value=0; for(const value of actor.el.querySelectorAll(".left-value,.right-value"))value.textContent="0.000"; actor.el.querySelector(".spectrum-value").textContent="—"; } function stopInput(input) { if(!input)return; if(input.oscillator){try{input.oscillator.stop();}catch{}} if(input.generator){try{input.generator.stop();}catch{}} input.track.stop();for(const node of input.nodes)node.disconnect(); } function clearMedia(actor) { stopInput(actor.input);actor.input=null;actor.inputTrack=null;actor.oscillator=null;clearOutput(actor); } async function createInput(actor, mode) { if(mode==="silent")return null; if(mode==="microphone")return {track:await LivekitClient.createLocalAudioTrack({channelCount:1,echoCancellation:true,noiseSuppression:true}),nodes:[],mode}; if(mode==="noise") { const destination=audioContext.createMediaStreamDestination(),generator=audioContext.createBufferSource(),level=audioContext.createGain(); destination.channelCount=1;level.gain.value=.12; const buffer=audioContext.createBuffer(1,audioContext.sampleRate*2,audioContext.sampleRate),samples=buffer.getChannelData(0); let seed=12345+actor.number; for(let i=0;i>>0;samples[i]=seed/2147483648-1;} generator.buffer=buffer;generator.loop=true;generator.connect(level);level.connect(destination);generator.start(); return {track:new LivekitClient.LocalAudioTrack(destination.stream.getAudioTracks()[0],undefined,true,audioContext),nodes:[generator,level,destination],generator,mode}; } const destination=audioContext.createMediaStreamDestination(),oscillator=audioContext.createOscillator(),level=audioContext.createGain(); destination.channelCount=1;level.gain.value=.16;oscillator.frequency.value=Number(actor.el.querySelector(".frequency").value); oscillator.connect(level);level.connect(destination);oscillator.start(); // This stream is generated by our oscillator, not by getUserMedia. Mark it // user-provided so SDK reconnect cannot reacquire a physical microphone. return {track:new LivekitClient.LocalAudioTrack(destination.stream.getAudioTracks()[0],undefined,true,audioContext),nodes:[oscillator,level,destination],oscillator,mode}; } const inputOptions={name:"microphone",forceStereo:false,red:false,dtx:false}; async function changeInput(actor) { actor.inputRequested=true;if(actor.inputBusy)return; actor.inputBusy=true; try { while(actor.inputRequested&&actor.connected&&actor.room) { actor.inputRequested=false; const room=actor.room,generation=actor.generation,mode=actor.el.querySelector(".source").value; let next; try { next=await createInput(actor,mode); if(actor.room!==room||generation!==actor.generation||!actor.desiredConnected){stopInput(next);continue;} const old=actor.input; if(old)await room.localParticipant.unpublishTrack(old.track,false); if(actor.room!==room||generation!==actor.generation){stopInput(next);continue;} stopInput(old);actor.input=null;actor.inputTrack=null;actor.oscillator=null; if(next) { await room.localParticipant.publishTrack(next.track,{...inputOptions,source:LivekitClient.Track.Source.Microphone}); if(actor.room!==room||generation!==actor.generation||!actor.desiredConnected){stopInput(next);continue;} actor.input=next;actor.inputTrack=next.track;actor.oscillator=next.oscillator; } log(`Актор ${actor.number}: источник ${mode==="tone"?"тестовый тон":mode==="noise"?"шум":mode==="silent"?"тишина":"микрофон"}`); }catch(error){stopInput(next);if(actor.room===room&&generation===actor.generation){log(`Источник актора ${actor.number}: ${error.message}`);actor.el.querySelector(".source").value=actor.input?.mode??"silent";}} } }finally{actor.inputBusy=false;} } function subscribeMix(room) { for(const participant of room.remoteParticipants.values())for(const publication of participant.audioTrackPublications.values())if(publication.trackName==="spatial_mix")publication.setSubscribed(true); } function scheduleRetry(actor) { if(!actor.desiredConnected||actor.retryTimer)return; const delay=Math.min(1000*2**Math.min(actor.retryAttempt++,3),8000); actor.el.querySelector(".state").textContent=`Восстановление через ${delay/1000} с`; actor.el.querySelector(".connect").textContent="Отключить"; actor.retryTimer=setTimeout(()=>{actor.retryTimer=null;if(actor.desiredConnected)connect(actor);},delay); } async function connect(actor) { if(actor.connecting||actor.room)return;actor.desiredConnected=true;actor.connecting=true; clearTimeout(actor.retryTimer);actor.retryTimer=null; const generation=++actor.generation,button=actor.el.querySelector(".connect");button.disabled=true; try { if(!window.LivekitClient)throw new Error("Не загрузился LiveKit SDK. Проверьте доступ к CDN."); if(location.protocol==="file:")throw new Error("Откройте http://127.0.0.1:8899/ вместо HTML файла."); await audio();actor.el.querySelector(".state").textContent="Подключение…"; actor.roomName??=document.querySelector("#room").value; const response=await fetch("/token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({room:actor.roomName,identity:actor.id}),signal:AbortSignal.timeout(10000)}); if(!response.ok)throw new Error(await response.text());const credentials=await response.json(); if(generation!==actor.generation||!actor.desiredConnected)return; const room=new LivekitClient.Room({adaptiveStream:false,dynacast:false});actor.room=room; const current=()=>actor.room===room&&actor.generation===generation; room.on(LivekitClient.RoomEvent.TrackPublished,pub=>{if(current()&&pub.trackName==="spatial_mix")pub.setSubscribed(true);}); room.on(LivekitClient.RoomEvent.TrackSubscribed,(track,pub)=>{if(current())attachOutput(actor,track,pub);}); room.on(LivekitClient.RoomEvent.TrackUnsubscribed,track=>{if(current()&&actor.outputTrack===track){clearOutput(actor);actor.el.querySelector(".state").textContent="Подключён · ожидание микса";}}); room.on(LivekitClient.RoomEvent.Reconnecting,()=>{if(current()){actor.connected=false;actor.el.querySelector(".state").textContent="Восстановление соединения…";}}); room.on(LivekitClient.RoomEvent.Reconnected,async()=>{ if(!current())return; actor.connected=true;actor.retryAttempt=0;sendPose(actor);subscribeMix(room);applyAudition(); actor.outputElement?.play().catch(()=>{}); actor.el.querySelector(".state").textContent=actor.hasMix?"Персональный стереомикс":"Подключён · ожидание микса"; try { const input=actor.input; if(input&&!actor.inputBusy&&![...room.localParticipant.audioTrackPublications.values()].some(pub=>pub.track?.mediaStreamTrack===input.track.mediaStreamTrack))await room.localParticipant.publishTrack(input.track,{...inputOptions,source:LivekitClient.Track.Source.Microphone}); if(current()&&actor.inputRequested)changeInput(actor); }catch(error){if(current())log(`Восстановление источника актора ${actor.number}: ${error.message}`);} log(`Актор ${actor.number}: восстановлено соединение`); }); room.on(LivekitClient.RoomEvent.Disconnected,()=>{if(current()){actor.room=null;actor.connected=false;clearMedia(actor);scheduleRetry(actor);}}); await room.connect(credentials.url,credentials.token,{autoSubscribe:false}); if(!current()||!actor.desiredConnected){await room.disconnect();return;} actor.connected=true;actor.retryAttempt=0;sendPose(actor);subscribeMix(room); if(!document.querySelector("#audition").value && ![...actors.values()].some(other=>other!==actor&&other.connected))document.querySelector("#audition").value=actor.id; applyAudition(); await changeInput(actor); if(!current())return; button.textContent="Отключить";if(!actor.hasMix)actor.el.querySelector(".state").textContent="Подключён · ожидание микса"; log(`Актор ${actor.number}: подключён к ${actor.roomName}`); }catch(error){if(generation===actor.generation&&actor.desiredConnected){log(`Ошибка актора ${actor.number}: ${error.message}`);const room=actor.room;actor.room=null;actor.connected=false;clearMedia(actor);await room?.disconnect();scheduleRetry(actor);}} finally{if(generation===actor.generation){actor.connecting=false;button.disabled=false;}} } async function disconnect(actor) { actor.generation++;actor.desiredConnected=false;actor.connected=false;actor.connecting=false;actor.inputRequested=false;actor.roomName=null; clearTimeout(actor.retryTimer);actor.retryTimer=null; const room=actor.room;actor.room=null;clearMedia(actor); await room?.disconnect();actor.el.querySelector(".state").textContent="Отключён";actor.el.querySelector(".connect").textContent="Подключить";actor.el.querySelector(".connect").disabled=false; } function frame(now) { const dt=Math.min((now-previousTime)/1000,.1);previousTime=now; ctx.clearRect(0,0,canvas.width,canvas.height);const scale=canvas.width/66,cx=canvas.width/2,cy=canvas.height/2; ctx.strokeStyle="#263b4e";ctx.lineWidth=1;ctx.fillStyle="#71879d";ctx.font="12px system-ui"; for(let n=-30;n<=30;n+=5){const x=cx+n*scale,y=cy-n*scale;ctx.beginPath();ctx.moveTo(x,0);ctx.lineTo(x,canvas.height);ctx.moveTo(0,y);ctx.lineTo(canvas.width,y);ctx.stroke();if(n)ctx.fillText(String(n),x+3,cy+15);} ctx.fillText("+X",cx+8,16);ctx.fillText("+Y",canvas.width-26,cy-8); drawWalls(scale,cx,cy); const selected=document.querySelector("#audition").value; for(const actor of actors.values()) { if(actor.el.querySelector(".moving").checked){actor.phase=(actor.phase??0)+dt*.6;setPosition(actor,"x",8*Math.cos(actor.phase));setPosition(actor,"y",8*Math.sin(actor.phase));} if(actor.el.querySelector(".turning").checked)setPosition(actor,"yaw",((actor.yaw+dt*60+180)%360)-180); const x=cx+actor.y*scale,y=cy-actor.x*scale,a=actor.yaw*Math.PI/180; if(actor.id===selected){ctx.strokeStyle=actor.color+"44";ctx.beginPath();ctx.arc(x,y,20*scale,0,2*Math.PI);ctx.stroke();} ctx.fillStyle=actor.color;ctx.beginPath();ctx.arc(x,y,8,0,2*Math.PI);ctx.fill();ctx.strokeStyle=actor.color;ctx.lineWidth=3;ctx.beginPath();ctx.moveTo(x,y);ctx.lineTo(x+Math.sin(a)*24,y-Math.cos(a)*24);ctx.stroke();ctx.fillText(String(actor.number),x+12,y+18); if(actor.analyzers) { actor.analyzers.forEach((analyzer,i)=>{analyzer.getFloatTimeDomainData(actor.meterSamples);const rms=Math.sqrt(actor.meterSamples.reduce((sum,n)=>sum+n*n,0)/actor.meterSamples.length);actor.el.querySelector(i===0?".left":".right").value=rms;actor.el.querySelector(i===0?".left-value":".right-value").textContent=rms.toFixed(3);}); if(now-actor.lastSpectrumTime>250) { const peaks=actor.analyzers.map(analyzer=>spectralPeak(analyzer,actor.spectrum)); actor.el.querySelector(".spectrum-value").textContent=`L: ${peaks[0]} · R: ${peaks[1]}`;actor.lastSpectrumTime=now; } } } requestAnimationFrame(frame); } let dragging; canvas.addEventListener("pointerdown",event=>{const rect=canvas.getBoundingClientRect(),y=(event.clientX-rect.left)/rect.width*canvas.width,x=(event.clientY-rect.top)/rect.height*canvas.height,scale=canvas.width/66;dragging=[...actors.values()].find(actor=>Math.hypot(canvas.width/2+actor.y*scale-y,canvas.height/2-actor.x*scale-x)<18);if(dragging)canvas.setPointerCapture(event.pointerId);}); canvas.addEventListener("pointermove",event=>{if(!dragging)return;const rect=canvas.getBoundingClientRect(),scale=canvas.width/66;setPosition(dragging,"y",Math.max(-30,Math.min(30,((event.clientX-rect.left)/rect.width*canvas.width-canvas.width/2)/scale)));setPosition(dragging,"x",Math.max(-30,Math.min(30,(canvas.height/2-(event.clientY-rect.top)/rect.height*canvas.height)/scale)));}); canvas.addEventListener("pointerup",()=>dragging=null);canvas.addEventListener("pointercancel",()=>dragging=null); document.querySelector("#add").addEventListener("click",()=>addActor()); document.querySelector("#demo").addEventListener("click",async()=>{await audio();for(const initial of [{x:0,y:0,frequency:440},{x:0,y:4,frequency:660},{x:0,y:-4,frequency:880}]){const actor=addActor(initial);await connect(actor);}document.querySelector("#audition").value=[...actors.keys()][0];applyAudition();}); document.querySelector("#audio").addEventListener("click",async()=>{ await audio(); if(!document.querySelector("#audition").value){const actor=[...actors.values()].find(actor=>actor.connected);if(actor)document.querySelector("#audition").value=actor.id;} applyAudition(); for(const actor of actors.values())if(actor.outputElement)actor.outputElement.play().catch(error=>log(`Не удалось включить звук: ${error.message}`)); }); document.querySelector("#interval").addEventListener("change",startPoseTimer);document.querySelector("#audition").addEventListener("change",applyAudition); startPoseTimer();requestAnimationFrame(frame); function spectralPeak(analyzer,bins) { analyzer.getFloatFrequencyData(bins); const resolution=audioContext.sampleRate/analyzer.fftSize; let peak=Math.max(1,Math.ceil(40/resolution)); for(let i=peak+1;ibins[peak])peak=i; if(!Number.isFinite(bins[peak])||bins[peak]<-65)return "—"; const a=bins[peak-1],b=bins[peak],c=bins[peak+1],denominator=a-2*b+c; const offset=Number.isFinite(denominator)&&Math.abs(denominator)>1e-8?Math.max(-.5,Math.min(.5,.5*(a-c)/denominator)):0; return `${Math.round((peak+offset)*resolution)} Гц`; } function sceneStatus(text) { document.querySelector("#walls-state").textContent=text; } function recoverScene() { if(!appliedScene||wallRetryTimer)return; const delay=Math.min(1000*2**Math.min(wallRetryAttempt++,3),8000); wallRetryTimer=setTimeout(async()=>{ wallRetryTimer=null; try{await publishScene(appliedScene.objects,appliedScene.enabled,appliedScene.roomName,appliedScene.hrtf,appliedScene.adaptive);} catch(error){sceneStatus(`Восстановление геометрии: ${error.message}`);recoverScene();} },delay); } async function sceneController(roomName) { if(wallController?.roomName===roomName&&wallController.room.state===LivekitClient.ConnectionState.Connected)return wallController.room; if(wallConnectPromise)return wallConnectPromise; wallConnectPromise=(async()=>{ if(wallController){const old=wallController;wallController=null;await old.room.disconnect();} const response=await fetch("/token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({room:roomName,identity:`scene-controller-${session}`,scene_controller:true}),signal:AbortSignal.timeout(10000)}); if(!response.ok)throw new Error(await response.text());const credentials=await response.json(); const room=new LivekitClient.Room({adaptiveStream:false,dynacast:false}),controller={room,roomName};wallController=controller; room.on(LivekitClient.RoomEvent.DataReceived,(payload,participant,kind,topic)=>{ if(wallController!==controller||topic!=="sverse.spatial.scene.ack.v1"||!wallPending)return; try { const result=JSON.parse(new TextDecoder().decode(payload)); if(result.revision!==wallPending.revision&&result.revision!==0)return; const pending=wallPending;wallPending=null;clearTimeout(pending.timer); if(!result.ok){pending.reject(new Error(result.error??"Сцена отклонена сервером"));return;} appliedScene={objects:pending.objects,enabled:pending.enabled,roomName:pending.roomName,hrtf:pending.hrtf,adaptive:pending.adaptive};wallRetryAttempt=0; sceneStatus(`HRTF разрешён: ${pending.hrtf?"да":"нет"} · адаптация: ${pending.adaptive?"вкл":"выкл"} · препятствия: ${pending.enabled?"вкл":"выкл"} · объектов: ${pending.objects.length} · сервер подтвердил`); pending.resolve(); }catch(error){log(`Ответ сервера геометрии: ${error.message}`);} }); room.on(LivekitClient.RoomEvent.Reconnected,()=>{if(wallController===controller&&appliedScene?.roomName===roomName&&!wallPending)recoverScene();}); room.on(LivekitClient.RoomEvent.Disconnected,()=>{ if(wallController!==controller)return;wallController=null; if(wallPending){clearTimeout(wallPending.timer);wallPending.reject(new Error("Соединение контроллера прервано"));wallPending=null;} sceneStatus("Контроллер отключён · восстановление геометрии");recoverScene(); }); try{await room.connect(credentials.url,credentials.token,{autoSubscribe:false});return room;} catch(error){if(wallController===controller)wallController=null;await room.disconnect();throw error;} })(); try{return await wallConnectPromise;}finally{wallConnectPromise=null;} } async function publishScene(objects,enabled,roomName,hrtf,adaptive) { const room=await sceneController(roomName); if(wallPending)throw new Error("Дождитесь подтверждения предыдущей сцены"); wallRevision=Math.max(wallRevision+1,Date.now()); const snapshot={version:1,revision:wallRevision,location_id:roomName,enabled,objects,hrtf,adaptive}; const payload=new TextEncoder().encode(JSON.stringify(snapshot)); if(payload.length>15000)throw new Error("Сцена должна быть не больше 15000 байт"); sceneStatus("Ожидание подтверждения сервера…"); return new Promise((resolve,reject)=>{ const pending={revision:wallRevision,objects,enabled,roomName,hrtf,adaptive,resolve,reject};wallPending=pending; pending.timer=setTimeout(()=>{if(wallPending===pending){wallPending=null;reject(new Error("Сервер не подтвердил сцену за 5 секунд"));}},5000); room.localParticipant.publishData(payload,{reliable:true,topic:"sverse.spatial.scene.v1"}).catch(error=>{if(wallPending===pending){clearTimeout(pending.timer);wallPending=null;reject(error);}}); }); } document.querySelector("#walls-apply").addEventListener("click",async()=>{ const button=document.querySelector("#walls-apply");button.disabled=true; try { const objects=JSON.parse(document.querySelector("#walls-json").value); if(!Array.isArray(objects))throw new Error("Ожидается массив объектов"); clearTimeout(wallRetryTimer);wallRetryTimer=null; await publishScene(objects,document.querySelector("#walls-enabled").checked,document.querySelector("#room").value,document.querySelector("#hrtf-enabled").checked,document.querySelector("#adaptive-enabled").checked); }catch(error){sceneStatus(error.message);log(`Геометрия: ${error.message}`);} finally{button.disabled=false;} }); document.querySelector("#wall-example").addEventListener("click",()=>{ document.querySelector("#walls-json").value=JSON.stringify([{id:"wall-1",center:[0,2,0],size:[12,.2,6],rotation:[0,0,0,1],transmission:.2}],null,2); document.querySelector("#walls-enabled").checked=true;sceneStatus("Пример подготовлен · нажмите «Применить к комнате»"); }); document.querySelector("#walls-clear").addEventListener("click",()=>{document.querySelector("#walls-json").value="[]";sceneStatus("Список очищен · нажмите «Применить к комнате»");}); function drawWalls(scale,cx,cy) { if(!appliedScene||appliedScene.roomName!==document.querySelector("#room").value)return; for(const object of appliedScene.objects) { const [qx,qy,qz,qw]=object.rotation,n=Math.hypot(qx,qy,qz,qw),x=qx/n,y=qy/n,z=qz/n,w=qw/n; const axes=[[1-2*(y*y+z*z),2*(x*y+z*w)],[2*(x*y-z*w),1-2*(x*x+z*z)],[2*(x*z+y*w),2*(y*z-x*w)]]; const points=[]; for(const sx of [-1,1])for(const sy of [-1,1])for(const sz of [-1,1]) { const offsets=[sx*object.size[0]/2,sy*object.size[1]/2,sz*object.size[2]/2]; const px=object.center[0]+offsets.reduce((sum,v,i)=>sum+v*axes[i][0],0),py=object.center[1]+offsets.reduce((sum,v,i)=>sum+v*axes[i][1],0); points.push([cx+py*scale,cy-px*scale]); } points.sort((a,b)=>a[0]-b[0]||a[1]-b[1]); const cross=(a,b,c)=>(b[0]-a[0])*(c[1]-a[1])-(b[1]-a[1])*(c[0]-a[0]); const half=list=>{const result=[];for(const point of list){while(result.length>1&&cross(result.at(-2),result.at(-1),point)<=0)result.pop();result.push(point);}return result;}; const hull=half(points).slice(0,-1).concat(half([...points].reverse()).slice(0,-1)); if(!hull.length)continue; ctx.fillStyle=appliedScene.enabled?"#e4a56c44":"#78839022";ctx.strokeStyle=appliedScene.enabled?"#e4a56c":"#788390";ctx.lineWidth=2; ctx.beginPath();hull.forEach((p,i)=>i?ctx.lineTo(...p):ctx.moveTo(...p));ctx.closePath();ctx.fill();ctx.stroke(); ctx.fillStyle=ctx.strokeStyle;ctx.fillText(`${object.id} · ×${object.transmission}`,cx+object.center[1]*scale+5,cy-object.center[0]*scale-7); } }