import {WIDTH,HEIGHT,RADIUS,DT,move,reconcile,sample,Clock,presentationTime,FrameClock,WORLD,clamp} from './net.mjs'; import {Controls} from './controls.mjs'; import {Renderer} from './render.mjs'; const $=id=>document.getElementById(id),canvas=document.querySelector('canvas'),renderer=new Renderer(canvas); const state={id:null,ws:null,frames:[],pending:[],position:null,seq:0,clock:new Clock(),lastSnapshot:0,offsetX:0,offsetY:0,correction:0,ackMs:0,stepMs:0,fps:60,connected:false,attempt:0,delay:0,viewAge:0,bytes:0,kbps:0,lastTraffic:performance.now(),generation:0,rendered:[],lastEvent:0,hasEvents:false,feed:[],visualNext:0,fired:new Set()}; const controls=new Controls(canvas,e=>renderer.world(e),()=>{$('hint').classList.add('used');}); let accumulator=0,lastHud=0,lastPing=0,retryTimer;const frameClock=new FrameClock(performance.now()),timers=new Set(); function later(fn,delay){const t=setTimeout(()=>{timers.delete(t);fn();},delay);timers.add(t);} function clearTimers(){for(const t of timers)clearTimeout(t);timers.clear();} function status(text,kind='connecting'){$('connection').textContent=text;$('connection').dataset.state=kind;} function scheduleReconnect(){clearTimeout(retryTimer);if(document.hidden||!navigator.onLine)return;retryTimer=setTimeout(connect,Math.min(8000,400*2**Math.min(state.attempt++,5))+Math.random()*200);} function send(message){ const ws=state.ws,generation=state.generation;if(!ws||ws.readyState!==WebSocket.OPEN)return false; const encoded=JSON.stringify(message),deliver=()=>{if(ws!==state.ws||generation!==state.generation||ws.readyState!==WebSocket.OPEN)return;if(ws.bufferedAmount>8192){ws.close(4000,'Network backlog');return;}ws.send(encoded);}; if(state.delay)later(deliver,state.delay);else deliver();return true; } function connect(){ clearTimeout(retryTimer);clearTimers();controls.clear();state.generation++; if(state.ws){state.ws.onclose=null;state.ws.close();} Object.assign(state,{id:null,connected:false,position:null,pending:[],frames:[],seq:0,offsetX:0,offsetY:0,clock:new Clock(),lastEvent:0,hasEvents:false,feed:[],visualNext:0,ackMs:0});state.fired.clear();accumulator=0;lastPing=0; if(document.hidden)return;if(!navigator.onLine){status('Offline','offline');return;}status('Connecting…'); const url=new URL('./socket',location.href);url.protocol=location.protocol==='https:'?'wss:':'ws:'; const ws=new WebSocket(url);state.ws=ws; ws.onmessage=event=>{if(ws!==state.ws)return;state.bytes+=typeof event.data==='string'?event.data.length:0;const receive=()=>{if(ws===state.ws&&ws.readyState===WebSocket.OPEN)handle(event.data);};if(state.delay)later(receive,state.delay);else receive();}; ws.onerror=()=>status('Connection interrupted','offline'); ws.onclose=event=>{if(ws!==state.ws)return;clearTimers();controls.clear();state.connected=false;state.position=null;state.pending=[];state.frames=[];status(event.code===1013?'Arena busy · retrying':document.hidden?'Paused in background':'Reconnecting…','offline');scheduleReconnect();}; } function handle(raw){ let msg;try{msg=JSON.parse(raw);}catch{return;}const now=performance.now(); if(msg.type==='welcome'){if(msg.protocol!==2){status('Refresh to update game','offline');state.ws.close(4001,'Game version changed');return;}state.id=msg.id;state.connected=true;state.attempt=0;state.clock.offset=msg.time-now;state.lastSnapshot=now;status('Connected','live');ping(now);return;} if(msg.type==='pong'){state.clock.observe(msg.sent,now,msg.time);return;} if(msg.type!=='snapshot'||!state.id)return; state.clock.arrival(now);state.lastSnapshot=now;state.stepMs=msg.stepMs; const own=msg.players.find(p=>p.id===state.id);if(!own)return; const was=state.position,acked=state.pending.find(p=>p.seq===own.ack); if(acked){const age=now-acked.sentAt;state.ackMs=state.ackMs?state.ackMs*.7+age*.3:age;} const result=reconcile(own,state.pending);state.position=result.position;state.pending=result.pending; if(was&&was.life===own.life&&own.hp>0){const dx=was.x-state.position.x,dy=was.y-state.position.y;state.correction=Math.hypot(dx,dy);if(state.correction<120){state.offsetX+=dx;state.offsetY+=dy;}else state.offsetX=state.offsetY=0;} else{state.offsetX=state.offsetY=0;state.visualNext=0;} state.frames.push(msg);if(state.frames.length>45)state.frames.shift(); for(const event of msg.events||[]){ if(event.id<=state.lastEvent)continue;state.lastEvent=event.id;if(!state.hasEvents)continue; if(event.kind==='fire'){if(event.owner!==state.id||!state.fired.has(event.seq))renderer.fire(event.owner,event.x,event.y,event.aim,now);} else{renderer.burst(event.x,event.y,event.kind,now);if(event.kind==='kill'){state.feed.push({text:`${event.owner===state.id?'You':'P'+event.ownerNumber} › ${event.victim===state.id?'you':'P'+event.victimNumber}`,at:now});if(state.feed.length>3)state.feed.shift();}} } state.hasEvents=true;for(const seq of state.fired)if(seqrenderer.resize()).observe($('arena')); function render(now,elapsed){ const newest=state.frames.at(-1),players=[],shells=[]; state.offsetX*=Math.exp(-elapsed/.06);state.offsetY*=Math.exp(-elapsed/.06); if(newest){ const mode=$('mode').value,buffer=mode==='balanced'?state.clock.buffer:0,estimatedNow=now+state.clock.offset; const time=presentationTime(state.frames,estimatedNow-(state.clock.rtt||0)/2-buffer,mode==='raw');state.viewAge=Math.max(0,estimatedNow-time); for(const person of newest.players){ const local=person.id===state.id,input=controls.command(state.position||person); const p=local&&$('prediction').checked&&state.position?{...person,...state.position,x:state.position.x+state.offsetX,y:state.position.y+state.offsetY,aim:input.aim,moving:input.mx||input.my}:sample(state.frames,person.id,time,mode==='raw'||local); if(p)players.push(p); } const previous=state.frames.length>1?state.frames.at(-2):null; for(const shell of newest.shells||[]){ const old=previous?.shells?.find(p=>p.id===shell.id); if(old&&time>=previous.time&&time<=newest.time){const t=(time-previous.time)/Math.max(1,newest.time-previous.time);shells.push({...shell,x:old.x+(shell.x-old.x)*t,y:old.y+(shell.y-old.y)*t});} else{const d=clamp(time-newest.time,0,50)/1000;shells.push({...shell,x:shell.x+shell.vx*d,y:shell.y+shell.vy*d});} } } state.rendered=players.map(p=>({id:p.id,x:p.x,y:p.y,hp:p.hp,life:p.life,aim:p.aim})); renderer.draw({now,elapsed,players,shells,localId:state.id,fade:now-state.lastSnapshot>500?.45:1}); } function hud(now){ const clock=state.clock,latest=state.frames.at(-1),own=latest?.players.find(p=>p.id===state.id),stale=state.connected&&now-state.lastSnapshot>500; if(state.connected)status(stale?'Updates delayed':'Connected',stale?'connecting':'live'); const ms=v=>Math.round(v)+' ms';$('players').textContent=state.connected&&latest?latest.players.length:'—';$('ping').textContent=clock.rtt===null?'—':ms(clock.rtt);$('jitter').textContent=clock.rtt===null?'—':ms(clock.jitter);$('rate').textContent=state.connected&&latest&&!stale?Math.round(clock.hz)+' /s':'—'; $('ack').textContent=state.ackMs?ms(state.ackMs):'—';$('view-age').textContent=latest?ms(state.viewAge):'—';$('buffer').textContent=$('mode').value==='balanced'?ms(clock.buffer):'0 ms';$('pending').textContent=state.pending.length;$('correction').textContent=state.correction.toFixed(2)+' units';$('fps').textContent=Math.round(state.fps)+' fps';$('step').textContent=state.stepMs.toFixed(3)+' ms';$('traffic').textContent=state.kbps.toFixed(1)+' kB/s'; $('notice').hidden=!state.delay;$('notice').textContent=`Test delay: +${state.delay} ms each way`; if(now-state.lastTraffic>1000){state.kbps=state.bytes/(now-state.lastTraffic);state.bytes=0;state.lastTraffic=now;} $('health').textContent=own?`${own.hp} / 100`:'—';$('health-fill').style.width=(own?.hp||0)+'%';$('kills').textContent=own?.kills||0; const gameNow=latest?latest.gameTime+Math.max(0,now+clock.offset-latest.time)/1000:0; const ready=own?clamp(1-(own.nextShot-gameNow)/WORLD.reload,0,1):0;$('reload-fill').style.transform=`scaleX(${ready})`;$('reload-label').textContent=own?.hp===0?'DESTROYED':ready>=.98?'READY':'RELOADING'; $('respawn').hidden=!own||own.hp>0;$('respawn-time').textContent=own?Math.max(0,own.respawnIn-Math.max(0,now+clock.offset-latest.time)/1000).toFixed(1)+'s':''; const ranked=[...(latest?.players||[])].sort((a,b)=>b.kills-a.kills||a.deaths-b.deaths||a.number-b.number).slice(0,5); $('leaders').replaceChildren(...ranked.map(p=>{const row=document.createElement('li'),name=document.createElement('span'),score=document.createElement('b');name.textContent=p.id===state.id?'You':`Player ${p.number}`;score.textContent=p.kills;row.classList.toggle('is-you',p.id===state.id);row.append(name,score);return row;})); state.feed=state.feed.filter(e=>now-e.at<3500);$('kill-feed').replaceChildren(...state.feed.map(e=>{const p=document.createElement('p');p.textContent=e.text;return p;})); } function frame(now){ const elapsed=frameClock.tick(now);state.fps=frameClock.fps; if(!document.hidden&&state.connected&&state.position){ if(now-state.lastSnapshot>3000||state.pending.length>=180)state.ws.close(4000,'State timeout'); else{ accumulator+=elapsed; for(let count=0;accumulator>=DT&&count<4;count++){ const input=controls.command(state.position),command={...input,seq:state.seq+1,sentAt:now}; if(!send({type:'input',seq:command.seq,mx:command.mx,my:command.my,aim:command.aim,fire:command.fire})){accumulator=0;break;} state.seq++;state.pending.push(command);state.position=move(state.position,command);accumulator-=DT; if(command.fire&&now>=state.visualNext){state.visualNext=now+WORLD.reload*1000;state.fired.add(command.seq);renderer.fire(state.id,state.position.x+Math.cos(command.aim)*(RADIUS+12),state.position.y+Math.sin(command.aim)*(RADIUS+12),command.aim,now);} } if(now-lastPing>=1000)ping(now); } } render(now,elapsed);if(now-lastHud>100){hud(now);lastHud=now;}requestAnimationFrame(frame); } $('delay').addEventListener('change',()=>{state.delay=Number($('delay').value);connect();});$('reconnect').addEventListener('click',connect);$('close-settings').addEventListener('click',()=>{$('diagnostics').open=false;}); $('share').addEventListener('click',async()=>{try{await navigator.clipboard.writeText(new URL('./',location.href).href);$('share').textContent='Copied';setTimeout(()=>{$('share').textContent='Copy link';},1500);}catch{$('share').textContent='Share this page URL';}}); const clearInput=()=>{controls.clear();accumulator=0;}; document.addEventListener('visibilitychange',()=>{frameClock.reset(performance.now());clearInput();if(document.hidden){clearTimeout(retryTimer);clearTimers();state.ws?.close(1000,'Tab hidden');status('Paused in background');}else connect();}); addEventListener('offline',()=>{clearTimeout(retryTimer);clearInput();state.ws?.close(1000,'Offline');status('Offline','offline');});addEventListener('online',connect);addEventListener('pagehide',()=>state.ws?.close(1000,'Page closed')); Object.defineProperty(window,'netplayDebug',{get:()=>({id:state.id,connected:state.connected,players:state.frames.at(-1)?.players||[],shells:state.frames.at(-1)?.shells||[],rendered:state.rendered,position:state.position,pending:state.pending.length,rtt:state.clock.rtt,jitter:state.clock.jitter,hz:state.clock.hz,buffer:state.clock.buffer,ackMs:state.ackMs,stepMs:state.stepMs,gameTime:state.frames.at(-1)?.gameTime,world:WORLD,input:state.position?controls.command(state.position):null,scale:renderer.scale,left:renderer.left,top:renderer.top,width:renderer.width,height:renderer.height})}); renderer.resize();connect();requestAnimationFrame(frame);