diff --git a/environments/games/web/games/mario64_remake/app3d.js b/environments/games/web/games/mario64_remake/app3d.js new file mode 100644 index 0000000000000000000000000000000000000000..371c7aba84f3bed8afd59bdf787521f85ade1fc8 --- /dev/null +++ b/environments/games/web/games/mario64_remake/app3d.js @@ -0,0 +1,68 @@ +/* Human play and exact native-input recording. Game state is owned by each module. */ +(function () { + 'use strict'; + const N=NativeBench, M=window.GAME_MODULE, $=s=>document.querySelector(s), canvas=$('canvas'), context=canvas.getContext('2d'); + let session=new N.Session(M,M.cases[0].id,1,.5),running=false,last=0,accumulator=0; + // A key pressed and released between two ticks stays held until one tick has sampled it (same latch as _native/shell.js), + // so fast taps (jump, ground pound, camera steps) are never lost. + const held=new Set(),pending=new Set(),releaseAfter=new Set(),pointerHeld=new Map(),touchHeld=new Map(); let mouse=[0,0,0],replay=null,replayIndex=0,automatic=false,script=null,scriptTick=0; + const keys={KeyW:'W',KeyA:'A',KeyS:'S',KeyD:'D',Space:'Space',ShiftLeft:'Shift',ShiftRight:'Shift',KeyJ:'J',KeyK:'K',KeyL:'L',KeyQ:'Q',KeyE:'E',KeyR:'R',ArrowUp:'W',ArrowDown:'S',ArrowLeft:'A',ArrowRight:'D'}; + document.body.dataset.game=M.id; + // Public difficulty = three tiers (2026-11-02): rebuilt from Module.tiers when the game declares it. + if(M.tiers&&$('#difficulty')){const sel=$('#difficulty'),names={easy:'Easy',normal:'Normal',hard:'Hard'};sel.textContent=''; + for(const t of ['easy','normal','hard']){const op=document.createElement('option');op.value=String(M.tiers[t]);op.textContent=names[t]+' (d='+M.tiers[t]+')';if(t==='normal')op.selected=true;sel.append(op);}} + for(const def of M.cases){const option=document.createElement('option');option.value=def.id;option.textContent=def.name;$('#case').append(option);} + const controls=Array.isArray(M.controls)?M.controls.map(value=>['',value]):Object.entries(M.controls); + for(const [key,value]of controls){const dt=document.createElement('dt'),dd=document.createElement('dd');dt.textContent=key;dd.textContent=value;$('dl').append(dt,dd);} + function status(value){$('#status').textContent=value;} + function clear(){held.clear();pending.clear();releaseAfter.clear();pointerHeld.clear();touchHeld.clear();mouse=[0,0,0];accumulator=0;} + function inputKeys(){return [...new Set([...held,...[...pointerHeld.values()].flatMap(keys=>[...keys]),...touchHeld.values()])].filter(key=>N.keys.includes(key)).slice(0,4);} + function draw(){ + M.draw(session.game,context); + $('#pause').textContent=running?'Pause':'Resume'; + $('#overlay').hidden=running&&!session.game.outcome; + $('#overlay strong').textContent=session.game.outcome?{win:'Challenge Complete',loss:'Challenge Failed',timeout:'Time up'}[session.game.outcome]:replay?'Replay · Paused':session.game.t?'Paused':'Are You Ready?'; + $('#overlay span').textContent=session.game.outcome?'Restart the challenge or export the replay':session.game.t?'Click Resume to return to battle':'Click Start Challenge, then click the screen to use keyboard and mouse'; + } + function reset(id,seed,difficulty){running=false;automatic=false;replay=null;script=null;scriptTick=0;clear();session=new N.Session(M,id,seed,difficulty);draw();return session.snapshot();} + window.nativeAPI={reset,packet(packet){if(running)throw Error('Pause before a scripted packet');const value=session.packet(packet);draw();return value;}, + state(){return session.snapshot();},recording(){return session.export();}, + render(){draw();return canvas.toDataURL('image/png');}, + renderMetrics(){return M.renderMetrics?M.renderMetrics(context):{};}, + module(){return {id:M.id,hz:M.hz,version:M.version,cases:M.cases};}}; + function start(useScript){try{reset($('#case').value,Number($('#seed').value),Number($('#difficulty').value));automatic=useScript;running=true;status(useScript?'Script verification running':'Battle started; recording this match');canvas.focus();draw();}catch(error){status(error.message);}} + $('#start').onclick=()=>start(false);$('#demo').onclick=()=>start(true); + $('#pause').onclick=()=>{if(session.game.outcome)return;running=!running;clear();if(running)canvas.focus();draw();}; + $('#step').onclick=()=>{running=false;if(replay)replayTick();else session.tick();draw();}; + function openReplay(data){N.Session.import(M,data);reset(data.case,data.seed,data.difficulty);replay=data;replayIndex=0;running=true;$('#case').value=data.case;status('Replay verified; playback started');draw();} + $('#sample').onclick=()=>{try{const data=M.example?.[$('#case').value];if(!data)throw Error('No built-in replay for this fight; try the scripted demo');openReplay(data);}catch(error){status(error.message);}}; + function replayTick(){if(replayIndex{const data=session.export(),url=URL.createObjectURL(new Blob([JSON.stringify(data)],{type:'application/json'}));const link=document.createElement('a');link.href=url;link.download=M.id+'-'+session.seed+'.json';link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);status('Current replay exported');}; + $('#import').onclick=()=>$('#file').click();$('#file').onchange=async event=>{const file=event.target.files[0];if(!file)return;try{if(file.size>12e6)throw Error('Replay file is too large');openReplay(JSON.parse(await file.text()));}catch(error){status('Import failed: '+error.message);}event.target.value='';}; + function release(){clear();if(running){running=false;status('Window lost focus; battle paused');}draw();} + window.addEventListener('blur',release);document.addEventListener('visibilitychange',()=>{if(document.hidden)release();}); + window.addEventListener('keydown',event=>{if(['INPUT','SELECT','BUTTON'].includes(document.activeElement.tagName))return;if(keys[event.code]){event.preventDefault();held.add(keys[event.code]);pending.add(keys[event.code]);releaseAfter.delete(keys[event.code]);}if(event.code==='Escape'){running=false;clear();draw();}}); + window.addEventListener('keyup',event=>{const key=keys[event.code];if(key){event.preventDefault();if(pending.has(key))releaseAfter.add(key);else held.delete(key);}}); + canvas.oncontextmenu=event=>event.preventDefault();canvas.onpointerdown=event=>{if(event.button!==0&&event.button!==2)return;canvas.focus();const keys=pointerHeld.get(event.pointerId)||new Set();keys.add(event.button===2?'RMB':'LMB');pointerHeld.set(event.pointerId,keys);}; + // Pointer Events emits pointerup only after the final mouse button is released. + // pointermove carries changes to the button mask for chorded mouse presses. + function syncMouse(event){if(event.pointerType==='mouse'&&pointerHeld.has(event.pointerId)){const keys=new Set();if(event.buttons&1)keys.add('LMB');if(event.buttons&2)keys.add('RMB');if(keys.size)pointerHeld.set(event.pointerId,keys);else pointerHeld.delete(event.pointerId);}} + window.addEventListener('pointermove',syncMouse); + window.addEventListener('pointerup',event=>{if(event.pointerType==='mouse')syncMouse(event);else pointerHeld.delete(event.pointerId);touchHeld.delete(event.pointerId);}); + window.addEventListener('pointercancel',event=>{pointerHeld.delete(event.pointerId);touchHeld.delete(event.pointerId);}); + canvas.onpointermove=event=>{if(event.buttons||document.pointerLockElement===canvas){mouse[0]+=event.movementX;mouse[1]+=event.movementY;}}; + canvas.onwheel=event=>{event.preventDefault();mouse[2]+=Math.sign(event.deltaY);}; + canvas.ondblclick=()=>canvas.requestPointerLock?.(); + document.querySelectorAll('[data-key]').forEach(button=>{button.onpointerdown=event=>{event.preventDefault();button.setPointerCapture(event.pointerId);touchHeld.set(event.pointerId,button.dataset.key);};button.onpointerup=button.onpointercancel=event=>touchHeld.delete(event.pointerId);}); + function frame(now){const delta=Math.min(.1,(now-last)/1000||0);last=now;const beforeTick=session.game.t,wasRunning=running;try{ + if(running&&!session.game.outcome){accumulator+=delta;while(accumulator>=1/M.hz&&running&&!session.game.outcome){accumulator-=1/M.hz; + if(replay)replayTick();else if(automatic){const count=M.hz/5;if(scriptTick===0)script=(M.scripted||M.oracle).call(M,session.game);const sub=Math.ceil((scriptTick+1)*6/count)-1;session.tick(script.holds[sub],script.mouse.map(value=>value/count));scriptTick=(scriptTick+1)%count;} + else{session.tick(inputKeys(),mouse.map((value,index)=>N.clamp(value,index===2?-5:-1000,index===2?5:1000)));mouse=[0,0,0];pending.clear();for(const key of releaseAfter)held.delete(key);releaseAfter.clear();}} + if(session.game.outcome){running=false;status({win:'Challenge Complete',loss:'Challenge Failed',timeout:'Challenge Timed Out'}[session.game.outcome]+' · export or replay this match');}} + if(session.game.t!==beforeTick||running!==wasRunning)draw(); + }catch(error){running=false;clear();status('Runtime error: '+error.message);$('#overlay').hidden=false;$('#overlay strong').textContent='Unable to resume right now';$('#overlay span').textContent=error.message;} + requestAnimationFrame(frame); + } + window.addEventListener('pagehide',()=>M.closeRenderer?.(context)); + draw();requestAnimationFrame(frame); +})(); diff --git a/environments/games/web/games/mario64_remake/compact_actions.json b/environments/games/web/games/mario64_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..16d74f303dacffc85ace91b5c8421584f2055a70 --- /dev/null +++ b/environments/games/web/games/mario64_remake/compact_actions.json @@ -0,0 +1,1987 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "mario64_remake", + "version": "mario64-compact@4", + "heads": [ + { + "name": "move", + "options": [ + { + "label": "none" + }, + { + "label": "cam_left", + "tap": [ + "Q" + ] + }, + { + "label": "cam_right", + "tap": [ + "E" + ] + }, + { + "label": "cam_reset", + "tap": [ + "R" + ] + }, + { + "label": "w", + "keys": [ + "W" + ] + }, + { + "label": "wa", + "keys": [ + "W", + "A" + ] + }, + { + "label": "a", + "keys": [ + "A" + ] + }, + { + "label": "as", + "keys": [ + "A", + "S" + ] + }, + { + "label": "s", + "keys": [ + "S" + ] + }, + { + "label": "sd", + "keys": [ + "S", + "D" + ] + }, + { + "label": "d", + "keys": [ + "D" + ] + }, + { + "label": "wd", + "keys": [ + "W", + "D" + ] + }, + { + "label": "m_w_a_s_d_w_a", + "subs": [ + [ + "W" + ], + [ + "A" + ], + [ + "S" + ], + [ + "D" + ], + [ + "W" + ], + [ + "A" + ] + ] + }, + { + "label": "m_wa_as_sd_wd_wa_as", + "subs": [ + [ + "W", + "A" + ], + [ + "A", + "S" + ], + [ + "S", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "A" + ], + [ + "A", + "S" + ] + ] + }, + { + "label": "m_a_s_d_w_a_s", + "subs": [ + [ + "A" + ], + [ + "S" + ], + [ + "D" + ], + [ + "W" + ], + [ + "A" + ], + [ + "S" + ] + ] + }, + { + "label": "m_as_sd_wd_wa_as_sd", + "subs": [ + [ + "A", + "S" + ], + [ + "S", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "A" + ], + [ + "A", + "S" + ], + [ + "S", + "D" + ] + ] + }, + { + "label": "m_s_d_w_a_s_d", + "subs": [ + [ + "S" + ], + [ + "D" + ], + [ + "W" + ], + [ + "A" + ], + [ + "S" + ], + [ + "D" + ] + ] + }, + { + "label": "m_sd_wd_wa_as_sd_wd", + "subs": [ + [ + "S", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "A" + ], + [ + "A", + "S" + ], + [ + "S", + "D" + ], + [ + "W", + "D" + ] + ] + }, + { + "label": "m_d_w_a_s_d_w", + "subs": [ + [ + "D" + ], + [ + "W" + ], + [ + "A" + ], + [ + "S" + ], + [ + "D" + ], + [ + "W" + ] + ] + }, + { + "label": "m_wd_wa_as_sd_wd_wa", + "subs": [ + [ + "W", + "D" + ], + [ + "W", + "A" + ], + [ + "A", + "S" + ], + [ + "S", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "A" + ] + ] + }, + { + "label": "m_w_x_w_w_w_w", + "subs": [ + [ + "W" + ], + [], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ] + ] + }, + { + "label": "m_wa_x_wa_wa_wa_wa", + "subs": [ + [ + "W", + "A" + ], + [], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ] + ] + }, + { + "label": "m_a_x_a_a_a_a", + "subs": [ + [ + "A" + ], + [], + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [ + "A" + ] + ] + }, + { + "label": "m_as_x_as_as_as_as", + "subs": [ + [ + "A", + "S" + ], + [], + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [ + "A", + "S" + ] + ] + }, + { + "label": "m_s_x_s_s_s_s", + "subs": [ + [ + "S" + ], + [], + [ + "S" + ], + [ + "S" + ], + [ + "S" + ], + [ + "S" + ] + ] + }, + { + "label": "m_sd_x_sd_sd_sd_sd", + "subs": [ + [ + "S", + "D" + ], + [], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ] + ] + }, + { + "label": "m_d_x_d_d_d_d", + "subs": [ + [ + "D" + ], + [], + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [ + "D" + ] + ] + }, + { + "label": "m_wd_x_wd_wd_wd_wd", + "subs": [ + [ + "W", + "D" + ], + [], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ] + ] + }, + { + "label": "m_w_w_x_w_w_w", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ] + ] + }, + { + "label": "m_wa_wa_x_wa_wa_wa", + "subs": [ + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ] + ] + }, + { + "label": "m_a_a_x_a_a_a", + "subs": [ + [ + "A" + ], + [ + "A" + ], + [], + [ + "A" + ], + [ + "A" + ], + [ + "A" + ] + ] + }, + { + "label": "m_s_s_x_s_s_s", + "subs": [ + [ + "S" + ], + [ + "S" + ], + [], + [ + "S" + ], + [ + "S" + ], + [ + "S" + ] + ] + }, + { + "label": "m_d_d_x_d_d_d", + "subs": [ + [ + "D" + ], + [ + "D" + ], + [], + [ + "D" + ], + [ + "D" + ], + [ + "D" + ] + ] + }, + { + "label": "m_wd_wd_x_wd_wd_wd", + "subs": [ + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ] + ] + }, + { + "label": "m_w_w_w_x_w_w", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [], + [ + "W" + ], + [ + "W" + ] + ] + }, + { + "label": "m_wa_wa_wa_x_wa_wa", + "subs": [ + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [], + [ + "W", + "A" + ], + [ + "W", + "A" + ] + ] + }, + { + "label": "m_a_a_a_x_a_a", + "subs": [ + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [], + [ + "A" + ], + [ + "A" + ] + ] + }, + { + "label": "m_as_as_as_x_as_as", + "subs": [ + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [], + [ + "A", + "S" + ], + [ + "A", + "S" + ] + ] + }, + { + "label": "m_s_s_s_x_s_s", + "subs": [ + [ + "S" + ], + [ + "S" + ], + [ + "S" + ], + [], + [ + "S" + ], + [ + "S" + ] + ] + }, + { + "label": "m_sd_sd_sd_x_sd_sd", + "subs": [ + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [], + [ + "S", + "D" + ], + [ + "S", + "D" + ] + ] + }, + { + "label": "m_d_d_d_x_d_d", + "subs": [ + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [], + [ + "D" + ], + [ + "D" + ] + ] + }, + { + "label": "m_wd_wd_wd_x_wd_wd", + "subs": [ + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [], + [ + "W", + "D" + ], + [ + "W", + "D" + ] + ] + }, + { + "label": "m_w_w_w_w_x_w", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [], + [ + "W" + ] + ] + }, + { + "label": "m_wa_wa_wa_wa_x_wa", + "subs": [ + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [], + [ + "W", + "A" + ] + ] + }, + { + "label": "m_a_a_a_a_x_a", + "subs": [ + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [], + [ + "A" + ] + ] + }, + { + "label": "m_as_as_as_as_x_as", + "subs": [ + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [], + [ + "A", + "S" + ] + ] + }, + { + "label": "m_s_s_s_s_x_s", + "subs": [ + [ + "S" + ], + [ + "S" + ], + [ + "S" + ], + [ + "S" + ], + [], + [ + "S" + ] + ] + }, + { + "label": "m_sd_sd_sd_sd_x_sd", + "subs": [ + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [], + [ + "S", + "D" + ] + ] + }, + { + "label": "m_d_d_d_d_x_d", + "subs": [ + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [], + [ + "D" + ] + ] + }, + { + "label": "m_wd_wd_wd_wd_x_wd", + "subs": [ + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [], + [ + "W", + "D" + ] + ] + }, + { + "label": "m_w_w_w_w_w_x", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [] + ] + }, + { + "label": "m_wa_wa_wa_wa_wa_x", + "subs": [ + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [] + ] + }, + { + "label": "m_a_a_a_a_a_x", + "subs": [ + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [] + ] + }, + { + "label": "m_as_as_as_as_as_x", + "subs": [ + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [] + ] + }, + { + "label": "m_s_s_s_s_s_x", + "subs": [ + [ + "S" + ], + [ + "S" + ], + [ + "S" + ], + [ + "S" + ], + [ + "S" + ], + [] + ] + }, + { + "label": "m_sd_sd_sd_sd_sd_x", + "subs": [ + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [] + ] + }, + { + "label": "m_d_d_d_d_d_x", + "subs": [ + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [] + ] + }, + { + "label": "m_wd_wd_wd_wd_wd_x", + "subs": [ + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [] + ] + }, + { + "label": "m_x_x_x_w_w_w", + "subs": [ + [], + [], + [], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ] + ] + }, + { + "label": "m_w_w_x_x_x_x", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [], + [], + [], + [] + ] + }, + { + "label": "m_wd_wd_wd_d_d_d", + "subs": [ + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "D" + ], + [ + "D" + ], + [ + "D" + ] + ] + }, + { + "label": "m_wa_wa_wa_a_a_a", + "subs": [ + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "A" + ], + [ + "A" + ], + [ + "A" + ] + ] + }, + { + "label": "m_x_x_x_wd_wd_wd", + "subs": [ + [], + [], + [], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ] + ] + }, + { + "label": "m_d_d_d_sd_sd_sd", + "subs": [ + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ] + ] + }, + { + "label": "m_w_x_x_x_x_x", + "subs": [ + [ + "W" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "m_w_w_w_wa_wa_wa", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ] + ] + }, + { + "label": "m_wa_wa_wa_w_w_w", + "subs": [ + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ] + ] + }, + { + "label": "m_sd_sd_s_x_x_x", + "subs": [ + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S" + ], + [], + [], + [] + ] + }, + { + "label": "m_x_x_x_x_x_w", + "subs": [ + [], + [], + [], + [], + [], + [ + "W" + ] + ] + }, + { + "label": "m_x_x_x_x_wa_wa", + "subs": [ + [], + [], + [], + [], + [ + "W", + "A" + ], + [ + "W", + "A" + ] + ] + }, + { + "label": "m_d_d_d_wd_wd_wd", + "subs": [ + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ] + ] + }, + { + "label": "m_a_a_a_as_as_as", + "subs": [ + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [ + "A", + "S" + ] + ] + }, + { + "label": "m_a_a_a_wa_wa_wa", + "subs": [ + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ] + ] + }, + { + "label": "m_w_w_w_s_s_s", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [ + "S" + ], + [ + "S" + ], + [ + "S" + ] + ] + }, + { + "label": "m_wd_wd_wd_w_w_w", + "subs": [ + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ] + ] + }, + { + "label": "m_x_w_x_w_x_w", + "subs": [ + [], + [ + "W" + ], + [], + [ + "W" + ], + [], + [ + "W" + ] + ] + }, + { + "label": "m_w_w_w_wd_wd_wd", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ] + ] + }, + { + "label": "m_x_x_x_x_s_s", + "subs": [ + [], + [], + [], + [], + [ + "S" + ], + [ + "S" + ] + ] + }, + { + "label": "m_s_s_s_x_x_x", + "subs": [ + [ + "S" + ], + [ + "S" + ], + [ + "S" + ], + [], + [], + [] + ] + }, + { + "label": "m_x_x_wa_wa_wa_wa", + "subs": [ + [], + [], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ] + ] + }, + { + "label": "m_w_x_w_x_w_x", + "subs": [ + [ + "W" + ], + [], + [ + "W" + ], + [], + [ + "W" + ], + [] + ] + }, + { + "label": "m_s_s_s_sd_sd_sd", + "subs": [ + [ + "S" + ], + [ + "S" + ], + [ + "S" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ] + ] + }, + { + "label": "m_x_x_w_w_w_w", + "subs": [ + [], + [], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ] + ] + }, + { + "label": "m_sd_sd_sd_d_d_d", + "subs": [ + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "D" + ], + [ + "D" + ], + [ + "D" + ] + ] + }, + { + "label": "m_x_x_x_x_wd_wd", + "subs": [ + [], + [], + [], + [], + [ + "W", + "D" + ], + [ + "W", + "D" + ] + ] + }, + { + "label": "m_x_x_x_x_w_w", + "subs": [ + [], + [], + [], + [], + [ + "W" + ], + [ + "W" + ] + ] + }, + { + "label": "m_x_w_w_w_w_w", + "subs": [ + [], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ] + ] + }, + { + "label": "m_w_w_w_x_x_x", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [], + [], + [] + ] + }, + { + "label": "m_x_x_wd_wd_wd_wd", + "subs": [ + [], + [], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ] + ] + }, + { + "label": "m_wa_wa_x_x_x_x", + "subs": [ + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [], + [], + [], + [] + ] + } + ] + }, + { + "name": "action", + "options": [ + { + "label": "none" + }, + { + "label": "punch_s1", + "subs": [ + [ + "J" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "punch_s2", + "subs": [ + [], + [ + "J" + ], + [], + [], + [], + [] + ] + }, + { + "label": "punch_s3", + "subs": [ + [], + [], + [ + "J" + ], + [], + [], + [] + ] + }, + { + "label": "punch_s4", + "subs": [ + [], + [], + [], + [ + "J" + ], + [], + [] + ] + }, + { + "label": "punch_s5", + "subs": [ + [], + [], + [], + [], + [ + "J" + ], + [] + ] + }, + { + "label": "punch_s6", + "subs": [ + [], + [], + [], + [], + [], + [ + "J" + ] + ] + }, + { + "label": "jump_hold", + "keys": [ + "Space" + ] + }, + { + "label": "jump_pound_s2", + "subs": [ + [ + "Space" + ], + [ + "Shift" + ], + [], + [], + [], + [] + ] + }, + { + "label": "jump_pound_s3", + "subs": [ + [ + "Space" + ], + [ + "Space" + ], + [ + "Shift" + ], + [], + [], + [] + ] + }, + { + "label": "jump_short", + "subs": [ + [ + "Space" + ], + [ + "Space" + ], + [], + [], + [], + [] + ] + } + ] + } + ] +} diff --git a/environments/games/web/games/mario64_remake/draw.js b/environments/games/web/games/mario64_remake/draw.js new file mode 100644 index 0000000000000000000000000000000000000000..26d3947450f0860054a781e250495a3cc575828e --- /dev/null +++ b/environments/games/web/games/mario64_remake/draw.js @@ -0,0 +1,46 @@ +/* HUD for the Super Mario 64 boss trials, drawn over the WebGL frame: SM64-style 8-wedge power meter, boss hits, + * timer, native Hz and tier. Reads state only. */ +(function(root){ + 'use strict';const M=root.Mario64Game,R=root.Mario3D; + const NAMES={whomp:['Toppling Slab','TOPPLING SLAB'],king:['Grappler Orb','GRAPPLER ORB'],bully:['Horned Rammer','HORNED RAMMER'],eyerok:['Twin Sandstone Fists','TWIN SANDSTONE FISTS'],wiggler:['Frenzy Crawler','FRENZY CRAWLER'],bowser:['Fire Shell Beast','FIRE SHELL BEAST']}; + const ACT={idle:'Idle',walking:'Running',decel:'Slowing down',braking:'Braking',turnaround:'Quick turn',jump:'jump',double:'Double jump',triple:'Triple jump',backflip:'Backflip', + sideflip:'Side flip',longjump:'Long jump',freefall:'Falling',dive:'Pounce',diveslide:'Dive slide',divestop:'Rise up',jumpkick:'Jump kick',slidekick:'Slide kick',slidekickslide:'Sliding', + rollout:'Rolling up',gp:'Ground pound',gpLand:'Ground pound landing',crouchIn:'Crouching',crouch:'Crouched',crouchOut:'Rise up',crouchslide:'Crouch slide',punching:'Punching',movepunch:'Punching', + pickup:'Picking up',hold:'Holding',holdwalk:'Walking while holding',heavythrow:'Throwing',land:'Landing',kb:'Knocked back',airkb:'Launched',thrown:'Thrown',grabbed:'Grabbed', + grabbowser:'Tail grabbed',swing:'Swinging',release:'Released',shockwave:'Stunned by shockwave',burnjump:'Burning',burnfall:'Burning',burnground:'Burning',squished:'Squashed',lava:'Burned by lava',dead:'Down'}; + function text(c,s,x,y,size,color,align='left',weight='bold'){c.font=`${weight} ${size}px "Segoe UI","Microsoft YaHei",sans-serif`;c.textAlign=align;c.lineJoin='round'; + c.lineWidth=Math.max(3,size/4.5);c.strokeStyle='rgba(12,14,40,.88)';c.strokeText(s,x,y);c.fillStyle=color;c.fillText(s,x,y);} + // The SM64 power meter: eight wedges, coloured by how many remain (blue / green / yellow / red). + function power(c,x,y,r,health){const units=Math.max(0,Math.min(8,health/256)),whole=Math.floor(units+1e-6),col=whole>=7?'#3fa8ff':whole>=5?'#3cd25a':whole>=3?'#f2c230':'#ef3b2e'; + c.save();c.beginPath();c.arc(x,y,r+5,0,Math.PI*2);c.fillStyle='rgba(18,22,60,.85)';c.fill();c.lineWidth=3;c.strokeStyle='#f6f2e6';c.stroke(); + for(let i=0;i<8;i++){const a0=-Math.PI/2+i*Math.PI/4,a1=a0+Math.PI/4-.06;c.beginPath();c.moveTo(x,y);c.arc(x,y,r,a0,a1);c.closePath(); + c.fillStyle=i12){const w=230;c.fillStyle='rgba(18,22,60,.8)';c.fillRect(x-w/2,y-9,w,14);c.fillStyle=kind==='bully'?'#ff8a2a':'#ffd23a';c.fillRect(x-w/2+2,y-7,(w-4)*n/max,10); + c.strokeStyle='#f6f2e6';c.lineWidth=1.5;c.strokeRect(x-w/2,y-9,w,14);text(c,`${n} / ${max}`,x,y+22,13,'#fff','center');return;} + const gap=22,x0=x-(max-1)*gap/2;for(let i=0;i0&&b.guard>0&&b.act!=='hitmine')text(c,'He just got up. His dim tail cannot be grabbed yet; keep your distance.',427,150,15,'#fff3c4','center','600'); + else if(b.kind==='bowser'&&b.hp>0&&b.act==='walk')text(c,'Get behind him and press J near his tail to grab it.',427,150,15,'#fff3c4','center','600'); + if(b.kind==='bowser')text(c,`Mines ${b.mines.filter(q=>q.alive).length} / 4`,427,96,14,'#ffb0a0','center'); + if(m.action==='squished')text(c,'Squashed!',427,150,26,'#ffd0c0','center'); + if(b.kind==='whomp'&&b.act==='ground'&&b.sub===0&&m.action!=='squished')text(c,'Exposed back! Jump up and ground pound with Shift.',427,150,15,'#fff3c4','center','600'); + if(b.kind==='eyerok'&&b.hands.some(q=>q.act==='eye')&&m.action!=='squished')text(c,'Eye open! Face the palm and punch with J.',427,150,15,'#fff3c4','center','600'); + if(b.kind==='wiggler'&&b.act==='walk'&&b.intro===0&&b.timer<60&&b.hpR.status(ctx);M.renderMetrics=ctx=>R.metrics(ctx);M.closeRenderer=ctx=>R.close(ctx); +})(window); diff --git a/environments/games/web/games/mario64_remake/game.js b/environments/games/web/games/mario64_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..a030c082cd0b26db919004d6f9039d2d84c3f426 --- /dev/null +++ b/environments/games/web/games/mario64_remake/game.js @@ -0,0 +1,1221 @@ +/* Super Mario 64 (N64, 1996): boss trials as an independent deterministic 60 Hz simulation (rules: M.version). + * Facts come from the n64decomp/sm64 decompilation at commit 9921382a68bb0c865e5e45eb594d9c64db59b1af (read, then + * re-implemented here; no code copied) and Super Mario Wiki. SOURCES.md maps each constant to its file and marks the + * engineering approximations (animation lengths, arena sizes, camera). Units are SM64 world units and speeds keep the + * original units per 30 Hz frame. SM64 logic runs at 30 Hz (hud.c turns 30 frames into one second), so one original + * frame is two ticks here: durations x2, per-frame increments /2, per-frame factors f -> sqrt(f), turn rates /2, and + * vertical motion uses a two-substep integrator whose even ticks reproduce the 30 Hz trajectory under constant gravity. */ +(function(root){ + 'use strict'; + const N=root.NativeBench,PI=Math.PI,K=2,S16=PI*2/65536; + const fr=n=>Math.round(n*K),inc=v=>v/K,ang=s=>s*S16/K,deg=s=>s*S16,fac=f=>Math.pow(f,1/K); + const wrap=a=>N.angle(a),hd=(a,b)=>Math.hypot(a.x-b.x,a.z-b.z),yawTo=(a,b)=>Math.atan2(b.x-a.x,b.z-a.z); + const approach=(v,t,d)=>vwrap(c+N.clamp(wrap(t-c),-r,r)); + // Objects apply gravity before moving (cur_obj_move_y / calc_new_obj_vel_and_pos_y: vy -= g, then y += vy), unlike + // Mario's air step (move with the old speed, then gravity, S09). Two ticks reproduce one such 30 Hz frame exactly. + function objFall(o,g,terminal){const v0=o.vy;o.vy=Math.max(-terminal,o.vy-g/K);o.y+=o.vy/K+(o.vy-v0)*(K-1)/(2*K);} + // Mario: S05 mario.c, S06 mario_actions_airborne.c, S07 mario_actions_moving.c, S08 mario_actions_object.c, + // S09 mario_step.c, S12 mario_actions_cutscene.c, S13 behavior_data.c (hitbox 37 x 160), S20 stationary actions. + const C={radius:37,height:160,maxHealth:0x880, + jumpVy:42,doubleVy:52,tripleVy:69,flipVy:62,longVy:30,fspeedMul:.25,jumpFwd:.8,backflipFwd:-16,sideflipFwd:8,longMul:1.5, + longCap:48,diveAdd:15,diveCap:48,diveVy:20,kickVy:20,slideKickVy:12,slideKickFwd:32,rolloutVy:30,lavaVy:84, + gravity:4,terminal:75,lightGravity:2,lavaGravity:3.2,lavaTerminal:65, + walkMax:32,walkAccel:1.1,walkDiv:43,walkOver:1,speedCap:48,turn:0x800,heavyMag:.1, + airDrag:.35,airGain:1.5,airSide:10,airOver:1,airBack:2,longThreshold:48, + djFrames:5,tripleNeed:20,longNeed:10,longWindow:16,diveNeed:29,airDiveNeed:28,fastAttack:26, + backAngle:0x471C,brakeNeed:16,brakeDecel:4,decel:1,finishTurnFwd:8,landFric:.98,slideLoss:.92, + gpRise:10,gpVy:-50,kbFric:.9,kbCap:32,thrownFric:.98,airKb:16,bounceGround:-48,bounceAir:-16, + invincFrames:30,fallDamageHeight:1150,lungeFrames:[10,7,5,3,2,1,1,0], + // Animation lengths in original frames, from the decomp's animation headers (S21 assets/anims loopEnd): first punch + // 5 + fast 10, second punch 4 + fast 13, kick 26, breakdance 24, ground-pound start 11 (+4 hover, S06), ground-pound + // landing 6, crouch in/out 6/10, heavy grab 37, heavy throw 25, soft/normal knockback 24/30. Approximated (A1): + // butt-slide stop after a ground-pound landing (10), dive stop, hard knockback, death. + gpWind:15,gpLand:16,crouchIn:6,crouchOut:10,punch1:5,punchFast:10,punch2:4,punchFast2:13,kick:26,breakdance:24,pickUp:3,heavyGrab:37, + heavyThrowRelease:13,heavyThrowEnd:25,diveStop:10,kbSoft:24,kbFwd:30,kbBack:30,kbHard:36,deathFrames:45, + landFrames:{jump:4,double:4,triple:4,backflip:4,side:4,free:4,long:6}}; + // A pressed during a landing: S07 landing table / S20 landing-stop rules. + const LAND_A={jump:'double',free:'double',side:'double',double:'tripleOrJump',triple:null,backflip:'backflipIfZ',long:'longOrJump'}; + const AIR=new Set(['jump','double','triple','backflip','sideflip','longjump','freefall','dive','jumpkick','gp','slidekick','rollout','airkb','thrown','lava','burnjump','burnfall']); + const INVULNERABLE=new Set(['kb','airkb','thrown','squished','lava','dead','grabbed','shockwave','burnjump','burnfall','burnground']); + const PUNCHING=new Set(['punching','movepunch']); + // Public tiers. Each TUNE row is [1996 original, easy, normal, hard] at difficulty 0 /.2 /.5 /.8, so + // difficulty 0 replays the original values. easy keeps the original aggression and damage and only adds hits where the + // 3-hit original is shorter than the meeting's 20-30 s; normal and hard also escalate aggression and damage + // (BossBench calibration for the 1-minute / 3-minute windows, not original behaviour; SOURCES.md T1). + const TIERS={easy:.2,normal:.5,hard:.8}; + const TUNE={ + whomp:{hits:[3,5,13,40],fast:[9,9,10.5,12],turn:[0x200,0x200,0x260,0x2c0],range:[300,300,320,340],lie:[100,100,82,66],delay:[30,30,24,18],squish:[3,3,4,5]}, + king:{hits:[3,3,7,19],walk:[3,3,3.6,4.4],turn:[0x100,0x100,0x150,0x1c0],throwHurt:[0,0,1,2],touchHurt:[1,1,1,2],escape:[10,10,12,14]}, + // sight/leave: the Big Bully chases while Mario is within `leave` of his home and resumes when within `sight` (S03: + // 800/1000). On the real platform (corners 1064 from home) the original radii let a corner camper stall him, so the + // public tiers widen both to 1100 to keep the boss engaging (binding rule; deviation T2, original at d = 0). + bully:{lives:[1,2,4,19],charge:[30,30,33,36],slow:[10,10,8,6],recover:[18,18,14,11],lavaHurt:[3,3,3,4],sight:[800,1100,1100,1100],leave:[1000,1100,1100,1100]}, + // hits: both hands together, split evenly (S35 health 4 = 3 hits per hand, 6 in all). every / pounds: the double pound's period + // and length (S35 6, 8). After a double pound the counter stands at r + 7 with r in {0,1} (S35), so a period dividing 7 or 8 + // restarts it at once and chains double pounds: every must stay out of {2,4,7,8}. + eyerok:{hits:[6,7,14,40],every:[6,6,5,5],pounds:[8,8,8,8],push:[50,50,55,60],rush:[50,50,55,60],retreat:[40,40,45,50],smashWait:[20,20,16,12],squish:[3,3,3,4]}, + // hits: stomps to shrink (S40 health 4 = 3). calm / chase / fury: target walking speed before the first stomp, until the last stomp, and on the last (S40 16, 30, 40; + // extra hits keep the middle speed, T6). seek: chases from the start instead of wandering until hit, leash: how far from home he follows; 1996 values at d = 0 (T6). + wiggler:{hits:[3,6,17,46],calm:[16,16,16,16],chase:[30,30,32,34],fury:[40,40,42,44],daze:[30,30,24,24],hurt:[3,3,3,4],seek:[0,1,1,1],leash:[1200,3000,3000,3000]}, + // hits: mines he must hit (S50 sBowserHealth BitDW 1). back: frames until a spent mine returns (the original's mines never return, kept at d = 0; more than 4 hits need it: T7). turn / walk: S50 0x200, 3. + // reach: his landing hurts Mario within it and only stuns him beyond (S50 850). touch / quake: wedges from his body and from a near landing (S50 2, S29 12/4 = 3). + // guard: frames after he stands up from a mine in which his tail cannot be touched, so a chain of grabs cannot lock him out of the fight (T7; never reached at d = 0, where one hit ends the fight). + bowser:{hits:[1,2,5,14],guard:[200,200,200,200],back:[300,300,240,180],turn:[0x200,0x200,0x300,0x400],walk:[3,3,3.6,4.4],reach:[850,850,950,1050],touch:[2,2,2,3],quake:[3,3,3,4]}}; + const tv=(d,[o,e,n,h])=>d<=.2?o+(e-o)*d/.2:d<=.5?e+(n-e)*(d-.2)/.3:n+(h-n)*(d-.5)/.3; + function tune(kind,d){const o={};for(const [k,v] of Object.entries(TUNE[kind]))o[k]=tv(d,v); + for(const k of ['hits','lives','escape','every','pounds','smashWait','daze'])if(k in o)o[k]=Math.max(1,Math.round(o[k])); + for(const k of ['squish','throwHurt','touchHurt','lavaHurt','hurt','seek','touch','quake','guard'])if(k in o)o[k]=Math.max(0,Math.round(o[k]));return o;} + // Arenas measured from the pinned decomp collision (S29 levels/wf, S30 levels/bob, S31 levels/lll): each boss floor's + // outline in local units (world minus the boss's spawn point; y = 0 is that floor) and, per edge (poly[i] -> poly[i+1]), + // the floor height 200 units beyond it. Only these measured numbers are used; no collision or model data is embedded. + // The King's flat top is merged with the near-level east apron (real -3..-104, taken as 0: A2). arrive = where Mario + // reaches the floor (Whomp: the checkerboard elevator in the notch, level object 1035, 2880, -900; King: the mountain + // path's top; Bully: the octagonal mesh platform east of him, level object 1124, 0, -4607). The fight starts as the + // boss's dialog ends, so Mario starts just inside its radius (S01 600, S02 500) on the line to the arrival point. + // farBelow: Mario further below than this resets the boss (S01 1000 in the chase, S02 1200). + const ARENA={ + whomp:{poly:[[-1023,1536],[-1023,-511],[-423,-1959],[1024,-511],[1536,-1023],[1536,1024],[1024,1536]], + drop:[-1024,-1024,-1024,-1024,-1024,-2662,-1703],slip:[0,0,0,0,0,0,1],lava:false,arrive:{x:1035,z:-900},startDist:580,talk:600,farBelow:1000}, + king:{poly:[[-338,1984],[-338,-64],[1436,-1088],[3210,-64],[3210,1984],[2877,1792],[2766,1728],[1436,2496]], + drop:[-460,-604,-885,-1180,-120,-120,-171,-311],lava:false,arrive:{x:2350,z:2050},startDist:480,talk:500,farBelow:1200}, + bully:{poly:[[-767,738],[-767,-670],[768,-670],[768,738]],drop:[-307,-307,-307,-307],lava:true,arrive:{x:1124,z:-222},startDist:0}, + // Eyerok: S35/S38 top floor of the Shifting Sand Land pyramid, boss at (0,-1534,-3693). The sides and front drop 3072 to the + // death plane (deadly: a fall ends the fight); the back edge is behind the wall (handSolid). + eyerok:{poly:[[-946,-261],[-946,1838],[947,1838],[947,-261]],drop:[-3072,-3072,-3072,-3072],lava:false,deadly:true,arrive:{x:0,z:1645},startDist:480,talk:500}, + // Wiggler: S41/S42 the cave at the top of Tiny-Huge Island, walls at world x -2047..2048, z -2047..2048. Closed: nothing to fall off. Mario really drops from + // the hole at (0, 3277, 0) onto the pyramid's top and walks off; the fight starts with him on the floor just off it, at 500 (A10). + wiggler:{poly:[[-2064,-1985],[-2064,2110],[2031,2110],[2031,-1985]],drop:[0,0,0,0],lava:false,room:true,arrive:{x:0,z:1000},startDist:500}, + // Bowser: S53 regular octagon of circumradius 3072 around the world origin, floor y 307, death plane -6143; local z = world z + 1000 (he spawns at (0, 307, -1000)). Mario lands in the middle. + bowser:{poly:[[3072,1000],[2172,3172],[0,4072],[-2171,3172],[-3071,1000],[-2171,-1171],[0,-2071],[2172,-1171]],drop:[-6450,-6450,-6450,-6450,-6450,-6450,-6450,-6450],lava:false,deadly:true,arrive:{x:0,z:1000},startDist:1000}}; + for(const a of Object.values(ARENA)){let A=0,cx=0,cz=0;const P=a.poly; // polygon centroid + for(let i=0;iz)!==(zj>z)&&x<(xj-xi)*(z-zi)/(zj-zi)+xi)c=!c;}return c;} + function nearestEdge(P,x,z){let e=0,best=Infinity;for(let i=0;iMath.max(0,Math.max(Math.abs(x+16.5),Math.abs(z-62.5))-716.5)*.2307; + const wigCeil=(x,z)=>{const a=Math.abs(x+17),c=Math.abs(z-62);return Math.max(Math.abs(x+16.5),Math.abs(z-62.5))>306.5?null:410+Math.max(a,c)/306.5*205;}; + const SLAB={half:300,h0:100,h1:860,d0:-200,d1:-6,top:200}; + const KING={radius:100,height:100,holdY:170,anchorFwd:150,anchorSide:100,anchorY:60,drag:10}; // S13 SET_HITBOX(100,100), drag 1000/100, anchor 100/150 + const BULLY={radius:115,height:235,gravity:5,friction:.93,push:3392}; // S03 big bully hitbox / init, S04 + // Bowser. anim: S54 loopEnd by animation index (only 9 is no-loop). mines: S53 at world (+-2949, 589, 0), (0, 589, +-2949). tail: the anchor follows the tail bone at render time; approximated as + // tailBack behind him, tailY above his feet (A11). flames: S55 even animation frames 46..84 as [y, z, yaw, pitch]. throwF / throwL / throwY: S16 cur_obj_get_thrown_or_placed offset from Mario. + const BOWSER={anim:{0:44,2:30,3:36,6:92,8:20,9:16,10:70,12:80,13:42,14:22,15:44,25:45,26:44},mines:[[2949,1000],[0,-1949],[0,3949],[-2949,1000]],mineY:282,tailBack:200,tailY:60,grabR:400,grabH:400,bodyR:100,bodyH:300,throwF:321.577,throwL:-41.684,throwY:85.859,holdF:315,holdY:-67, + flames:[[229,139,-1,0x803],[222,147,-1,0x928],[221,149,-1,0xA16],[221,150,-1,0xAF6],[222,150,-1,0xB84],[223,149,0x524,0xB9E],[226,147,0xA3F,0xB57],[228,144,0xD00,0xAE5],[232,140,0xD8B,0xA48],[236,136,0xCED,0x96A],[239,132,0xB76,0x863],[244,128,0x970,0x74E],[248,122,0x723,0x649],[253,117,0x4D6,0x579],[256,111,0x2C9,0x509],[261,105,0x141,0x525],[264,100,0x6E,0x619],[268,95,0xC,0x8AF],[272,90,-1,0xC70],[274,86,0x14,0x10B6]]}; + const CASES=[ + {id:'mario64/whomp_king',kind:'whomp',name:'Whomp King · Stone Platform (ground pound his back)'}, + {id:'mario64/king_bobomb',kind:'king',name:'King Bob-omb · Grassy Summit (grab from behind and throw)'}, + {id:'mario64/big_bully',kind:'bully',name:'Big Bully · Lava Platform (push him into lava)'}, + {id:'mario64/eyerok',kind:'eyerok',name:'Eyerok · Desert Platform (strike the open eyes in its palms)'}, + {id:'mario64/wiggler',kind:'wiggler',name:'Wiggler · Cave Chamber (stomp its head; it speeds up each time)'}, + {id:'mario64/bowser_dark_world',kind:'bowser',name:'Bowser · Floating Octagonal Arena (grab his tail and throw him into mines)'}]; + const M=root.Mario64Game={id:'mario64_remake',version:'sm64-bosses@5',hz:60,maxSeconds:300,dimension:'3d',renderer:'webgl-mario64', + title:'Super Mario 64 · Boss Challenges',tiers:TIERS,cases:CASES.map(c=>({id:c.id,name:c.name})),tuning:C,tune:TUNE,arenas:ARENA, + controls:{'W A S D':'Move relative to the camera (full analog stick); hold K to walk slowly','Space':'A: jump; press again on landing for a double or triple jump; press while crouching for a backflip or while turning sharply for a side flip', + 'Shift / RMB':'Z: crouch; press while running to slide, then press Space for a long jump; press in midair to ground pound','J / LMB':'B: punch-punch-kick combo; dive while sprinting, kick in midair, pick up nearby grabbable objects, or throw what you hold', + 'Q / E':'Rotate the follow camera 45° left or right (C◀/C▶)','R':'snap camera behind you, facing the boss','L / Mouse wheel':'Zoom camera','Mouse drag':'Rotate camera continuously (double-click to lock pointer)', + 'When grabbed':'Tap Space or move repeatedly to escape','While holding the tail':'Press W A S D in sequence to swing faster; press J toward a mine to throw'}}; + + function newMario(x,z,yaw){return {x,y:0,z,vy:0,fwd:0,side:0,yaw,action:'idle',timer:0,state:0,arg:0,prev:'idle',health:C.maxHealth, + hurt:0,heal:0,invinc:0,djTimer:0,lastLand:null,peakY:0,squish:0,onBoss:false,punch:null,ctrlJump:false,holding:false,canGrab:false, + grabRelease:0,slowLong:false,lavaBounces:0,kbKind:null};} + function initBully(x,z,fwd,yaw,ratio){if(fwd<0){fwd=-fwd;yaw+=PI;}return {x,z,vx:fwd*Math.sin(yaw),vz:fwd*Math.cos(yaw),ratio};} + // S09 transfer_bully_speed: each body drops its own velocity component along the joining line and gains the other's, scaled. + function transferBully(a,b){const rx=b.x-a.x,rz=b.z-a.z,d2=rx*rx+rz*rz||1e-6,p1=(rx*a.vx+rz*a.vz)/d2,p2=(-rx*b.vx-rz*b.vz)/d2; + b.vx+=b.ratio*p1*rx-p2*-rx;b.vz+=b.ratio*p1*rz-p2*-rz;a.vx+=-p1*rx+a.ratio*p2*-rx;a.vz+=-p1*rz+a.ratio*p2*-rz;} + + class Game{ + constructor(id,seed,d){ + const def=CASES.find(c=>c.id===id);if(!def)throw Error('Unknown Super Mario 64 case'); + this.id=id;this.kind=def.kind;this.rng=seed||0x2545f491;this.d=d;this.t=0;this.outcome=null;this.events=[];this.effects=[];this.lastKeys=[]; + // The shared xorshift's first draws barely move for small seeds (seed 1..8 -> 0.0001..0.0005), so it is warmed up + // before the start position is drawn; otherwise seeds 1-8 would all start in the same spot. + for(let i=0;i<8;i++)N.rand(this); + this.T=tune(this.kind,d); + // Arrival: Mario reaches the boss floor at a.arrive and returns there after a fall (entry = 150 inside the edge on + // the line to the boss). Seeds vary the start along the arrival direction by up to +-14 degrees (Bully: +-100). + const a=this.arena,boss={x:0,z:0},len=Math.hypot(a.arrive.x,a.arrive.z);let e={x:a.arrive.x,z:a.arrive.z}; + for(let i=0;i<400&&!this.inside(e.x,e.z,150);i++)e={x:e.x-a.arrive.x/len*10,z:e.z-a.arrive.z/len*10}; + this.entry={x:Math.round(e.x),z:Math.round(e.z)}; + const dir=Math.atan2(a.arrive.x,a.arrive.z)+(N.rand(this)-.5)*.5; + const start=a.startDist?{x:Math.sin(dir)*a.startDist,z:Math.cos(dir)*a.startDist}:{x:this.entry.x,z:this.entry.z+(N.rand(this)-.5)*200}; + this.start={x:Math.round(start.x),z:Math.round(start.z)}; + this.mario=newMario(start.x,start.z,0);this.mario.yaw=yawTo(this.mario,boss); + this.stats={jumps:0,doubleJumps:0,tripleJumps:0,longJumps:0,backflips:0,sideFlips:0,groundPounds:0,dives:0,punches:0,kicks:0, + grabs:0,throws:0,squished:0,lavaBoosts:0,knockbacks:0,falls:0,bossHits:0,bossResets:0,damageTaken:0}; + if(this.kind==='whomp')this.boss={kind:'whomp',x:0,y:0,z:0,vy:0,fwd:0,yaw:yawTo(boss,this.mario),pitch:0,pitchVel:0, + act:'intro',timer:0,sub:0,hp:this.T.hits,maxHp:this.T.hits,shake:0,hitNow:false,squishedMario:false}; + else if(this.kind==='king')this.boss={kind:'king',x:0,y:0,z:0,vy:0,fwd:0,yaw:yawTo(boss,this.mario),act:0,sub:0,timer:0, + hp:this.T.hits,maxHp:this.T.hits,opener:0,wait:0,u104:0,escape:0,held:false,tangible:false,interact:'grab',grabbedMario:false, + homeX:0,homeZ:0,arc:null}; + else if(this.kind==='eyerok'){this.mario.onHand=-1; + const hand=(side,idx)=>({side,idx,homeX:-500*side,homeZ:300,x:224*side,y:0,z:300,vy:0,fwd:0,g:0,move:0,face:-deg(0x4000)*side,act:'sleep',prevAct:'sleep',timer:0, + hp:(side<0?Math.floor(this.T.hits/2):Math.ceil(this.T.hits/2))+1,anim:6,af:-1,open:false,ground:false,edge:false,wall:false,recv:0,pending:0,fc:0,u100:0,blink:3,gone:false,wake:0}); + this.boss={kind:'eyerok',x:0,y:0,z:0,yaw:0,act:'sleep',talk:0,timer:0,hp:this.T.hits,maxHp:this.T.hits,hands:[hand(-1,0),hand(1,1)],handsLeft:0,active:0,eyeHand:0,pound:0,lift:0,dir:0,zt:0,fc:0};} + else if(this.kind==='wiggler'){const seg=()=>({x:0,y:0,z:0,px:0,pz:0,pitch:0,yaw:0}); + this.boss={kind:'wiggler',x:0,y:0,z:0,vy:0,fwd:0,move:0,face:0,pitch:0,target:0,act:'walk',prevAct:'walk',timer:0,intro:30,hp:this.T.hits,maxHp:this.T.hits,sx:4,sy:4,sv:0,away:0,turnIn:0,pending:null,s:[seg(),seg(),seg(),seg()]};} + else if(this.kind==='bowser'){Object.assign(this.mario,{swing:0,twirl:0,burn:0,burnLoss:0,stomp:null});this.stats.burns=0;this.stats.mineHits=0; + this.boss={kind:'bowser',x:0,y:0,z:0,vy:0,fwd:0,yaw:0,drag:10,act:'wait',prev:'wait',sub:0,timer:0,btimer:0,anim:12,af:-1,react:1,hp:this.T.hits,maxHp:this.T.hits,held:false,heldT:0,skip:false,grabbable:false,tail:0,tailT:0,landed:false,onGround:true,op:255,opGoal:255,spin:0,guard:0, + mines:BOWSER.mines.map(([x,z])=>({x,y:BOWSER.mineY,z,alive:true,back:0,blast:0})),flames:[],fires:[]};} + // Act-1 Big Bully patrols at home and charges as Mario steps onto his platform (S03, initial action BULLY_ACT_PATROL). + else this.boss={kind:'bully',x:0,y:0,z:0,vy:0,fwd:0,moveYaw:0,faceYaw:0,act:'patrol',timer:0,counter:0, + lives:this.T.lives,maxLives:this.T.lives,homeX:0,homeZ:0,sinkY:0}; + this.cam={base:yawTo(this.mario,boss),offset:0,offsetTarget:0,yaw:yawTo(this.mario,boss),pitch:.38,dist:1100}; + } + get arena(){return ARENA[this.kind];} + state(){return N.copy(this);} + emit(name){this.events.push(name);} + fx(type,at,life=24,extra={}){this.effects.push({type,x:at.x,y:at.y||0,z:at.z,life,maxLife:life,...extra});} + // ---------------- world ---------------- + inside(x,z,margin=0){const P=this.arena.poly;return inPoly(P,x,z)&&(margin<=0||nearestEdge(P,x,z).d>=margin);} + edgeDist(x,z){return nearestEdge(this.arena.poly,x,z).d;} + slabLocal(x,z){const b=this.boss,fx=Math.sin(b.yaw),fz=Math.cos(b.yaw),px=x-b.x,pz=z-b.z;return {f:px*fx+pz*fz,u:-px*fz+pz*fx};} + lying(){const b=this.boss;return b&&b.kind==='whomp'&&b.pitch>deg(0x3800)&&b.act!=='dead';} + bossTop(x,z){if(!this.lying())return null;const s=this.slabLocal(x,z); + return s.f>=SLAB.h0&&s.f<=SLAB.h1&&Math.abs(s.u)<=SLAB.half?this.boss.y+SLAB.top*Math.sin(this.boss.pitch):null;} + // The boss floor at y = 0; beyond an edge, the measured floor below it (lava around the Bully's platform). + floor(x,z,y){const a=this.arena;let best;if(a.room)return {y:wigFloor(N.clamp(x,a.poly[0][0],a.poly[2][0]),N.clamp(z,a.poly[0][1],a.poly[2][1])),lava:false,boss:false,off:false}; + if(inPoly(a.poly,x,z))best={y:0,lava:false,boss:false,off:false}; + else{const e=nearestEdge(a.poly,x,z).e;best={y:a.drop[e],lava:a.lava,boss:false,off:!a.lava,slip:!!(a.slip&&a.slip[e])};} + const top=this.bossTop(x,z);if(top!==null&&y>=top-30&&top>best.y)best={y:top,lava:false,boss:true,off:false}; + if(this.kind==='eyerok'){const t=this.handTop(x,z,y);if(t!==null&&t>best.y)best={y:t,lava:false,boss:true,off:false};}return best;} + focus(){const b=this.boss;if(!b)return null; + if(b.kind==='whomp'){const f=this.lying()?480:0;return {x:b.x+Math.sin(b.yaw)*f,z:b.z+Math.cos(b.yaw)*f};} + if((b.kind==='king'||b.kind==='bowser')&&b.held)return null;return {x:b.x,z:b.z};} + // Lakitu camera: aims from behind Mario at the boss (the boss sets gSecondCameraFocus, S01/S02); Q/E add 45-degree + // C-button steps, mouse x turns freely, R recentres. The follow rates are engineering choices (SOURCES.md A3). + camera(pressed,mouse){const c=this.cam,m=this.mario,f=this.focus(); + if(pressed.has('Q'))c.offsetTarget=wrap(c.offsetTarget+PI/4);if(pressed.has('E'))c.offsetTarget=wrap(c.offsetTarget-PI/4); + if(pressed.has('R')){c.offsetTarget=0;}if(pressed.has('L'))c.dist=c.dist>1400?1100:1650; + c.offsetTarget=wrap(c.offsetTarget-mouse[0]*.0045);c.offset=wrap(c.offset+N.clamp(wrap(c.offsetTarget-c.offset),-.09,.09)); + c.pitch=N.clamp(c.pitch+mouse[1]*.0025,.14,.9);c.dist=N.clamp(c.dist+mouse[2]*70,700,2000); + if(f&&hd(m,f)>260){const d=wrap(yawTo(m,f)-c.base);c.base=wrap(c.base+N.clamp(d*.1,-.05,.05));} + c.yaw=wrap(c.base+c.offset); + } + readInput(keys,pressed){ + const f=(keys.has('W')?1:0)-(keys.has('S')?1:0),s=(keys.has('D')?1:0)-(keys.has('A')?1:0),a=this.cam.yaw,m=this.mario; + const dx=Math.sin(a)*f-Math.cos(a)*s,dz=Math.cos(a)*f+Math.sin(a)*s,len=Math.hypot(dx,dz),stickMag=len?(keys.has('K')?32:64):0; + const mag=Math.pow(stickMag/64,2)*64/(m.squish>0?8:2); // S05 update_mario_joystick_inputs + return {stickMag,mag,yaw:len?Math.atan2(dx,dz):m.yaw,aP:pressed.has('Space'),aD:keys.has('Space'),bP:pressed.has('J')||pressed.has('LMB'), + zP:pressed.has('Shift')||pressed.has('RMB'),zD:keys.has('Shift')||keys.has('RMB')}; + } + // ---------------- Mario helpers ---------------- + invulnerable(){const m=this.mario;return INVULNERABLE.has(m.action)||m.invinc>0;} + hurtMario(units){if(units<=0)return;const m=this.mario;m.hurt+=units*8;this.stats.damageTaken+=units;m.flash=24;this.emit('mario_hurt');} + setAction(name,arg=0){const m=this.mario;m.prev=m.action;m.action=name;m.timer=0;m.state=0;m.arg=arg;m.punch=null;} + go(name,arg=0){this.setAction(name,arg);this.chain=true;} + airborne(name,inp,arg=0){const m=this.mario;if(m.squish>0&&name==='double')name='jump';this.setAction(name,arg); + const yv=(v,mul)=>{m.vy=v+m.fwd*mul;if(m.squish>0)m.vy*=.5;};m.ctrlJump=false; + switch(name){ + case 'jump':yv(C.jumpVy,C.fspeedMul);m.fwd*=C.jumpFwd;m.ctrlJump=true;this.stats.jumps++;this.emit('jump');break; + case 'double':yv(C.doubleVy,C.fspeedMul);m.fwd*=C.jumpFwd;m.ctrlJump=true;this.stats.doubleJumps++;this.emit('double_jump');break; + case 'triple':yv(C.tripleVy,0);m.fwd*=C.jumpFwd;this.stats.tripleJumps++;this.emit('triple_jump');break; + case 'backflip':m.fwd=C.backflipFwd;yv(C.flipVy,0);this.stats.backflips++;this.emit('backflip');break; + case 'sideflip':yv(C.flipVy,0);m.fwd=C.sideflipFwd;m.yaw=inp.yaw;this.stats.sideFlips++;this.emit('side_flip');break; + case 'longjump':yv(C.longVy,0);m.slowLong=m.fwd<=16;m.fwd=Math.min(C.longCap,m.fwd*C.longMul);this.stats.longJumps++;this.emit('long_jump');break; + case 'dive':m.fwd=Math.min(C.diveCap,m.fwd+C.diveAdd);this.stats.dives++;this.emit('dive');break; + case 'jumpkick':m.vy=C.kickVy;this.stats.kicks++;this.emit('jump_kick');break; + case 'slidekick':m.vy=C.slideKickVy;m.fwd=Math.max(m.fwd,C.slideKickFwd);this.emit('slide_kick');break; + case 'rollout':m.vy=C.rolloutVy;break; + case 'lava':m.vy=C.lavaVy;if(!arg)m.fwd=0;m.lavaBounces=0;break; + } + m.peakY=m.y;m.side=0; + } + jumpFromLanding(inp){const m=this.mario,k=m.lastLand;this.chain=true; + if(m.djTimer===0||m.squish>0){m.djTimer=0;return this.airborne('jump',inp);}m.djTimer=0; + if(k==='jump'||k==='free'||k==='side')return this.airborne('double',inp); + if(k==='double')return this.airborne(m.fwd>C.tripleNeed?'triple':'jump',inp); + return this.airborne('jump',inp); + } + walkSpeed(m,inp,scale=1){const target=Math.min(inp.mag*scale,C.walkMax); // S07 update_walking_speed + if(m.fwd<=0)m.fwd+=inc(C.walkAccel);else if(m.fwd<=target)m.fwd+=inc(C.walkAccel-m.fwd/C.walkDiv);else m.fwd-=inc(C.walkOver); + if(m.fwd>C.speedCap)m.fwd=C.speedCap;m.yaw=turnTo(m.yaw,inp.yaw,ang(C.turn));} + airControl(m,inp,threshold=32){m.side=0;m.fwd=approach(m.fwd,0,inc(C.airDrag)); // S06 update_air_without_turn + if(inp.stickMag>0){const dy=wrap(inp.yaw-m.yaw),mag=inp.mag/32;m.fwd+=inc(C.airGain*Math.cos(dy)*mag);m.side=C.airSide*Math.sin(dy)*mag;} + if(m.fwd>threshold)m.fwd-=inc(C.airOver);if(m.fwd<-16)m.fwd+=inc(C.airBack);} + gravity(m,kind,inp){ + if(kind==='light'){m.vy=Math.max(-C.terminal,m.vy-inc(C.lightGravity));return;} + if(kind==='lava'){m.vy=Math.max(-C.lavaTerminal,m.vy-inc(C.lavaGravity));return;} + // Releasing A while rising faster than 20 divides the vertical speed by 4 once (S09 jump-ascent strengthening). + if(m.ctrlJump&&inp&&!inp.aD&&m.vy>20){m.vy/=4;m.ctrlJump=false;return;} + m.vy=Math.max(-C.terminal,m.vy-inc(C.gravity));} + // One tick of airborne motion; returns {landed, floor}. Even ticks match the 30 Hz explicit step exactly. + airMove(m,kind,inp){const sx=Math.sin(m.yaw),sz=Math.cos(m.yaw),vx=m.fwd*sx+m.side*sz,vz=m.fwd*sz-m.side*sx; + m.x+=vx/K;m.z+=vz/K;const v0=m.vy;this.gravity(m,kind,inp);m.y+=v0/K-(m.vy-v0)*(K-1)/(2*K); + if(m.vy>0||m.y>m.peakY)m.peakY=Math.max(m.peakY,m.y); + const fl=this.floor(m.x,m.z,m.y+Math.max(0,-v0/K));if(fl&&m.vy<=0&&m.y<=fl.y){m.y=fl.y;m.onBoss=fl.boss;return fl;}return null;} + groundStep(m){const ny=this.arena.room&&wigFloor(m.x,m.z)>0?.974:1,nx=m.x+ny*m.fwd*Math.sin(m.yaw)/K,nz=m.z+ny*m.fwd*Math.cos(m.yaw)/K,fl=this.floor(nx,nz,m.y);m.x=nx;m.z=nz; + if(!fl||fl.yC.fallDamageHeight&&m.vy<-55&&m.action!=='gp'){this.hurtMario(2);} + m.vy=0;m.side=0; + if(kind==='gp'){this.setAction('gpLand');this.stats.groundPounds++;this.fx('pound',m,26);this.emit('ground_pound_land'); + if(m.onBoss&&this.boss.kind==='whomp')this.boss.hitNow=true;return;} + if(kind==='dive'){this.setAction('diveslide');return;} + if(kind==='slidekick'){this.setAction('slidekickslide');return;} + if(kind==='kb'){this.setAction('kb');m.kbKind=m.fwd>=0?'fwd':'back';return;} + if(kind==='thrown'){const hurt=m.thrownHurt||0;m.thrownHurt=0;this.hurtMario(hurt);this.setAction('kb',hurt>0?1:0);m.kbKind=hurt>0?'hard':'fwd';return;} + m.lastLand=kind;m.djTimer=kind==='triple'||kind==='backflip'?0:fr(C.djFrames);this.setAction('land',0);m.landKind=kind; + } + startKnock(src,units){ // S04 take_damage_and_knock_back / determine_knockback_action; +30 frames invincibility after + const m=this.mario;if(this.invulnerable())return false;this.hurtMario(units);this.stats.knockbacks++; + const to=yawTo(m,src),inFront=Math.abs(wrap(to-m.yaw))<=PI/2;if(m.fwd<16)m.fwd=16; + if(inFront){m.yaw=to;m.fwd=-m.fwd;}else m.yaw=wrap(to+PI); + const hard=m.health-0x20*m.hurt<0x100||units>=4; + if(m.holding)this.dropHeld(); + if(AIR.has(m.action)){this.setAction('airkb',units>0?1:0);}else{this.setAction('kb',units>0?1:0);m.kbKind=hard?'hard':units>=2?(inFront?'back':'fwd'):'soft';} + return true;} + // ---------------- interactions (before Mario's action, as in SM64's mario_process_interactions) ---------------- + attackType(o){const m=this.mario,A=m.action,dy=Math.abs(wrap(yawTo(m,o)-m.yaw));let it=null; // S04 determine_interaction + if(PUNCHING.has(A)||A==='jumpkick'){if(m.punch==='punch'&&dy<=deg(0x2aaa))it='punch';if(m.punch==='kick'&&dy<=deg(0x2aaa))it='kick';if(m.punch==='trip'&&dy<=PI/2)it='trip';} + else if(A==='gp'){if(m.state===1&&m.vy<0)it='pound';} + else if(A==='gpLand'){if(m.timer===0)it='pound';} + else if(A==='slidekick'||A==='slidekickslide')it='slidekick'; + else if((A==='dive'||A==='diveslide')&&Math.abs(m.fwd)>=C.fastAttack)it='fast'; + if(!it&&AIR.has(A)){if(m.vy<0&&m.y>o.y)it='above';else if(m.vy>0&&m.y=min)return; + const nx=d>1e-6?(m.x-o.x)/d:Math.sin(m.yaw+PI),nz=d>1e-6?(m.z-o.z)/d:Math.cos(m.yaw+PI);m.x=o.x+nx*min;m.z=o.z+nz*min;} + interact(inp){const b=this.boss,m=this.mario;if(!b||m.action==='dead')return;m.canGrab=false; + if(b.kind==='king'){ + if(b.held||!b.tangible||m.action==='grabbed')return; + const touch=hd(m,b)<=KING.radius+C.radius+2&&m.y=p.r+C.radius||m.y>p.y+p.h||m.y+C.heightHAND.hitR+C.radius||m.y>=h.y+HAND.hitH||h.y>=m.y+C.height)continue; + const it=this.attackType(h);if(!it||it==='below')continue;h.pending=1; + if(it==='punch'||it==='kick'||it==='trip'){if(m.action==='punching')m.action='movepunch';m.fwd=AIR.has(m.action)?C.bounceAir:C.bounceGround;} + if(it==='above'){m.y=h.y+HAND.hitH;m.vy=30;} + this.fx('hit_star',{x:(m.x+h.x)/2,y:m.y+90,z:(m.z+h.z)/2},18);break;} + }else if(b.kind==='bully'){ + if(b.act==='fall'||b.act==='sink')return; + const touch=hd(m,b)<=BULLY.radius+C.radius&&m.yPI/2;if(back){m.yaw=wrap(m.yaw+PI);m.fwd=-m.fwd;}if(m.holding)this.dropHeld(); + b.act='knockback';b.counter=0;b.timer=0; // both interact_bully branches set INT_STATUS_INTERACTED -> knockback + this.stats.knockbacks++;this.emit('mario_bullied');this.fx('bump',m,16); + if(AIR.has(m.action))this.setAction('airkb',0);else{this.setAction('kb',0);m.kbKind='soft';} + } + } + } + // ---------------- Mario actions ---------------- + marioUpdate(inp){const m=this.mario; + if(m.invinc>0)m.invinc--;if(m.djTimer>0)m.djTimer--;if(m.squish>0&&m.action!=='squished')m.squish--;if(m.flash>0)m.flash--; + if(m.health>=0x100){if(m.hurt>0){m.health-=0x20;m.hurt--;}else if(m.heal>0){m.health+=0x20;m.heal--;}} // S05: 0x40 per frame + m.health=Math.min(C.maxHealth,m.health);if(m.health<0x100)m.health=Math.min(m.health,0xff); + if(m.action!=='dead'){this.interact(inp);for(let i=0;i<4;i++){this.chain=false;this.action(inp);if(!this.chain||m.action==='dead')break;}this.chain=false;}else if(++m.timer>=fr(C.deathFrames))this.outcome='loss'; + if(m.health<0x100&&!['dead','kb','airkb','squished','thrown','grabbed'].includes(m.action)&&(!AIR.has(m.action)||m.action==='lava')){ + this.setAction('dead');m.fwd=0;this.emit('mario_dead');} + if(m.y<-2500&&m.action!=='dead')this.fellOff({y:m.y,failsafe:true}); // failsafe; landings below an edge are handled in land() + } + // Mario landed on the floor below the boss floor (measured per edge). Fall damage follows check_fall_damage (S06): + // falling faster than 55, more than 3000 below the jump peak costs 4 wedges (16, cap on), more than 1150 costs 2 (8), + // but the 1150 rule is skipped on a slippery landing floor (mario_floor_is_slippery, S05) such as the slope north of + // the Whomp summit. The boss resets to full health when Mario is further below him than his far-below distance + // (S01 Whomp King 1000, S02 King Bob-omb 1200). In SM64 that check runs every frame while Mario climbs back (the WF + // elevator, the BOB mountain path); the climb is not simulated, so it is made once, at the landing (A2). + fellOff(fl){const m=this.mario,a=this.arena,b=this.boss,fall=m.peakY-fl.y,above=(b.held?0:b.y||0)-fl.y,fast=m.vy<-55||fl.failsafe; + if(a.deadly){this.stats.falls++;this.emit('fell_off');m.health=0xff;m.hurt=0;m.vy=0;m.fwd=0;m.side=0;m.onBoss=false;this.setAction('dead');this.emit('mario_dead');return;} + if(fast&&fall>3000)this.hurtMario(4);else if(fast&&fall>C.fallDamageHeight&&!fl.slip)this.hurtMario(2); + this.stats.falls++;this.emit('fell_off');if(m.holding)this.dropHeld(); + if(a.farBelow&&above>a.farBelow){if(b.kind==='king'&&b.act!==7)this.kingReset();else if(b.kind==='whomp'&&b.act!=='die'&&b.act!=='dead')this.whompReset();} + // Back on top: the fight-start spot, inside the boss's talk radius, standing for the climb and the walk back to him; + // a reset boss therefore always restarts his speech and the fight (binding rule: the boss must engage). + Object.assign(m,{x:this.start.x,z:this.start.z,y:0,vy:0,fwd:0,side:0,peakY:0,onBoss:false});m.yaw=yawTo(m,this.boss); + this.setAction(m.health<0x100?'dead':'idle');if(m.action==='dead')this.emit('mario_dead');} + whompReset(){const b=this.boss;Object.assign(b,{x:0,y:0,z:0,vy:0,fwd:0,pitch:0,pitchVel:0,act:'intro',timer:0,sub:0,hp:b.maxHp,shake:0,hitNow:false}); + this.stats.bossResets++;this.emit('whomp_reset');} + action(inp){const m=this.mario,A=m.action,stick=inp.stickMag>0; + switch(A){ + case 'idle':m.fwd=0; + if(m.holding)return this.go('hold'); + if(inp.aP)return this.jumpFromLanding(inp); + if(stick){m.yaw=inp.yaw;return this.go('walking');} + if(inp.bP)return this.startPunch('punching'); + if(inp.zD)return this.go('crouchIn'); + return; + case 'walking': + if(inp.aP)return this.jumpFromLanding(inp); + if(inp.bP){if(m.fwd>=C.diveNeed&&inp.stickMag>48){this.goAir('dive',inp,1);m.vy=C.diveVy;return;}return this.startPunch('movepunch');} + if(!stick)return this.go(m.fwd>=C.brakeNeed?'braking':'decel'); + if(Math.abs(wrap(inp.yaw-m.yaw))>deg(C.backAngle)&&m.fwd>=16)return this.go('turnaround'); + if(inp.zP)return this.go('crouchslide'); + this.walkSpeed(m,inp);if(!this.groundStep(m))this.leaveGround(inp);return; + case 'decel':case 'braking': + if(inp.aP)return this.jumpFromLanding(inp);if(inp.bP)return this.startPunch('movepunch'); + if(stick){m.yaw=turnTo(m.yaw,inp.yaw,ang(C.turn));return this.go('walking');} + if(A==='decel'&&inp.zP)return this.go('crouchslide'); // S07 act_decelerating: Z starts a crouch slide + m.fwd=approach(m.fwd,0,inc(A==='braking'?C.brakeDecel:C.decel));if(!this.groundStep(m))return this.leaveGround(inp); + if(m.fwd===0)this.setAction('idle');return; + case 'turnaround': + if(inp.aP)return this.goAir('sideflip',inp); + if(!stick)return this.go('braking'); + if(Math.abs(wrap(inp.yaw-m.yaw))<=deg(C.backAngle))return this.go('walking'); + m.fwd=approach(m.fwd,0,inc(C.brakeDecel));if(!this.groundStep(m))return this.leaveGround(inp); + if(m.fwd===0){m.yaw=inp.yaw;m.fwd=C.finishTurnFwd;this.setAction('walking');}return; + case 'crouchslide':m.timer++; + if(inp.aP)return this.goAir(m.timerC.longNeed?'longjump':'jump',inp); + if(inp.bP){if(m.fwd>=10)return this.goAir('slidekick',inp);return this.startPunch('punching',9);} + {const dy=stick?Math.cos(wrap(inp.yaw-m.yaw))*inp.mag/32:0;m.fwd*=fac(C.slideLoss+.02*dy);} + if(!this.groundStep(m))return this.leaveGround(inp); + if(Math.abs(m.fwd)<4){m.fwd=0;this.setAction(inp.zD?'crouch':'idle');}return; + case 'crouchIn':case 'crouch':case 'crouchOut':m.fwd=0;m.timer++; + if(inp.aP)return this.goAir('backflip',inp); + if(A==='crouchIn'){if(m.timer>=fr(C.crouchIn))this.setAction('crouch');return;} + if(A==='crouchOut'){if(m.timer>=fr(C.crouchOut))this.setAction('idle');return;} + if(!inp.zD)return this.go('crouchOut'); + if(inp.bP)return this.startPunch('punching',9); + return; + case 'punching':case 'movepunch':return this.punchStep(inp); + case 'pickup':m.fwd=0;m.timer++;if(m.timer===fr(C.pickUp))this.grabKing();if(m.timer>=fr(C.pickUp+C.heavyGrab))this.setAction('hold');return; + case 'hold':case 'holdwalk': + if(!m.holding)return this.setAction('idle'); + if(inp.bP)return this.go('heavythrow'); + if(stick){this.walkSpeed(m,inp,C.heavyMag);m.action='holdwalk';}else{m.fwd=0;m.action='hold';} + if(!this.groundStep(m)){this.dropHeld();this.leaveGround(inp);}return; + case 'heavythrow':m.fwd=0;m.timer++;if(m.timer===fr(C.heavyThrowRelease))this.dropHeld(true);if(m.timer>=fr(C.heavyThrowEnd))this.setAction('idle');return; + case 'land':{m.timer++;const k=m.landKind; + // S07 common_landing_cancels refreshes the double-jump timer on every landing frame (0 after triple jump / backflip); + // the landing then ends in a LAND_STOP whose stationary step zeroes the speed (S20 landing_step). Leaving it with the + // stick held goes on to walking, where set_jump_from_landing sees prevAction = *_LAND_STOP: only a side flip keeps + // its double jump there. + m.djTimer=k==='triple'||k==='backflip'?0:fr(C.djFrames); + if(m.timer>=fr(C.landFrames[k]||4)){if(stick){if(k!=='side')m.lastLand=null;return this.setAction('walking');}m.fwd=0;return this.setAction('idle');} + if(inp.aP&&LAND_A[k]){const a=LAND_A[k];m.djTimer=0; + if(a==='tripleOrJump')return this.goAir(m.fwd>C.tripleNeed?'triple':'jump',inp); + if(a==='longOrJump')return this.goAir(inp.zD&&m.fwd>C.longNeed?'longjump':'jump',inp); + if(a==='backflipIfZ')return inp.zD?this.goAir('backflip',inp):undefined; + return this.goAir(a,inp);} + if(inp.bP)return this.startPunch('movepunch'); + if(stick)m.fwd*=fac(C.landFric);else if(m.fwd>=16)m.fwd=approach(m.fwd,0,inc(C.brakeDecel)); + if(!this.groundStep(m))this.leaveGround(inp);return;} + case 'gpLand':m.timer++;m.fwd=0;if(m.timer>=fr(C.gpLand))this.setAction('idle');return; + case 'diveslide':case 'slidekickslide':m.timer++; + if(m.timer>fr(2)&&(inp.aP||inp.bP))return this.goAir('rollout',inp); + m.fwd=approach(m.fwd*fac(C.slideLoss),0,inc(.5));if(!this.groundStep(m))return this.leaveGround(inp); + if(Math.abs(m.fwd)<4){m.fwd=0;this.setAction('divestop');}return; + case 'divestop':m.timer++;if(m.timer>=fr(C.diveStop))this.setAction('idle');return; + case 'kb':return this.groundKnock(inp); + case 'squished':return this.kind==='eyerok'?this.handSquishStep():this.squishedStep(); + case 'grabbed':return; // positioned by King Bob-omb + // S08 act_picking_up_bowser (anim B5 20 frames), act_holding_bowser, act_releasing_bowser (anim B7 40 frames). The spin runs on the 30 Hz frames the decomp counts in. + case 'grabbowser':m.fwd=0;m.timer++;if(m.timer>=fr(20))this.setAction('swing',0);return; + case 'swing':m.fwd=0; + if(inp.bP){this.dropHeld(true);return this.go('release');} + if(this.t%K===0){ + if(m.swing===0){if(m.timer++>120){this.dropHeld(false);return this.go('release');}}else m.timer=0; + if(inp.mag>20){if(m.arg===0){m.arg=1;m.twirl=inp.yaw;}else{const spin=N.clamp(Math.trunc(Math.round(wrap(inp.yaw-m.twirl)/S16)/0x80),-0x80,0x80);m.twirl=inp.yaw;m.swing=N.clamp(m.swing+spin,-0x1000,0x1000);}} + else{m.arg=0;m.swing=approach(m.swing,0,64);}} + m.yaw=wrap(m.yaw+m.swing*S16/K);return; + case 'release':m.fwd=0;m.swing=0;m.timer++;if(m.timer>=fr(40))this.setAction('idle');return; + // S20 act_shockwave_bounce: 48 frames unable to move. The little bounce is only drawn. + case 'shockwave':m.fwd=0;m.timer++;if(m.timer>=fr(48))this.setAction('idle');return; + // S06 act_burning_jump / fall: no air control, burn timer +3 a frame, 10 health a frame, cannot die in the air. S07 act_burning_ground: +2 a frame, out above 160. + case 'burnjump':case 'burnfall':{m.burn+=1.5;this.burnTick();m.health=Math.max(m.health,0xff);m.side=0;const fl=this.airMove(m,'normal',inp);if(!fl)return; + if(fl.off)return this.fellOff(fl);m.vy=0;this.setAction('burnground');return;} + case 'burnground': + if(inp.aP){this.setAction('burnjump');m.vy=31.5;m.fwd=8;m.ctrlJump=false;m.peakY=m.y;return;} + m.burn+=1;if(m.burn>160)return this.setAction('walking'); + m.fwd=N.clamp(m.fwd,8,48);m.fwd=m.fwd<32?Math.min(32,m.fwd+inc(4)):Math.max(32,m.fwd-inc(1));if(stick)m.yaw=turnTo(m.yaw,inp.yaw,ang(0x600)); + if(!this.groundStep(m)){this.setAction('burnfall');m.vy=0;return;} + this.burnTick();return; + case 'gp':return this.gpStep(inp); + case 'lava':return this.lavaStep(inp); + default:return this.airStep(inp); + } + } + startPunch(kind,arg=0){this.go(kind,arg);this.stats.punches++;this.emit(arg===9?'breakdance':'punch');} + goAir(name,inp,arg=0){this.airborne(name,inp,arg);this.chain=true;} + // S08 mario_update_punch_sequence: arg 0 first punch, 2 its follow-up window, 3 second punch, 5 window, 6 kick, 9 breakdance. + punchStep(inp){const m=this.mario,F=Math.floor(m.timer/K);m.punch=null; + if(m.action==='punching'){if(m.arg===0)m.fwd=C.lungeFrames[Math.min(7,F)]; + if(inp.aP)return this.jumpFromLanding(inp);if(inp.stickMag>0&&m.arg!==0&&m.arg!==3&&m.arg!==6&&m.arg!==9){m.yaw=inp.yaw;return this.setAction('walking');}} + else{if(m.fwd>=0)m.fwd=approach(m.fwd,0,inc(1));else m.fwd=Math.min(0,m.fwd+inc(8));} + const end=()=>this.setAction(inp.stickMag>0?'walking':'idle'); + switch(m.arg){ + case 0:if(F>=2){if(m.canGrab){if(this.kind==='bowser')this.grabBowser();else this.setAction('pickup');return;}m.punch='punch';}if(++m.timer>=fr(C.punch1)){m.arg=2;m.timer=0;}break; + case 2:if(F<=0)m.punch='punch';if(inp.bP){m.arg=3;m.timer=0;this.stats.punches++;this.emit('punch');break;}if(++m.timer>=fr(C.punchFast))return end();break; + case 3:if(F>0)m.punch='punch';if(++m.timer>=fr(C.punch2)){m.arg=5;m.timer=0;}break; + case 5:if(F===0)m.punch='punch';if(inp.bP){m.arg=6;m.timer=0;this.stats.kicks++;this.emit('kick');break;}if(++m.timer>=fr(C.punchFast2))return end();break; + case 6:if(F<=7)m.punch='kick';if(++m.timer>=fr(C.kick))return end();break; + case 9:if(F>=2&&F<=7)m.punch='trip';if(++m.timer>=fr(C.breakdance))return this.setAction(inp.zD?'crouch':'idle');break; + } + if(!this.groundStep(m))this.leaveGround(inp); + } + airStep(inp){const m=this.mario,A=m.action; + const canGP=['jump','double','triple','backflip','sideflip','freefall'].includes(A); + if(canGP&&inp.zP){this.go('gp');m.vy=C.gpVy;m.fwd=0;m.side=0;this.emit('ground_pound');return;} + if(inp.bP){if(A==='jump'||A==='double'){this.goAir(m.fwd>C.airDiveNeed?'dive':'jumpkick',inp);return;} + if(A==='triple'||A==='sideflip'){this.goAir('dive',inp);return;}} + m.timer++; + if(A==='jumpkick')m.punch=Math.floor((m.timer-1)/K)<=7?'kick':null; + if(A==='airkb'){m.fwd=(m.fwd>=0?1:-1)*C.airKb;m.side=0;} + else if(A==='thrown'){m.fwd*=fac(C.thrownFric);m.side=0;} + else this.airControl(m,inp,A==='longjump'?C.longThreshold:32); + const fl=this.airMove(m,A==='longjump'||A==='slidekick'?'light':'normal',inp);if(!fl)return; + const kind={jump:'jump',double:'double',triple:'triple',backflip:'backflip',sideflip:'side',longjump:'long',dive:'dive',slidekick:'slidekick', + airkb:'kb',thrown:'thrown'}[A]||'free'; + if(A==='airkb'&&!fl.lava){const arg=m.arg;this.land('kb',inp,fl);m.arg=arg;return;} + this.land(kind,inp,fl); + } + gpStep(inp){const m=this.mario; // S06 act_ground_pound: 10-frame rise (20-2t per frame), hover, then fall from -50 + if(m.state===0){const f=Math.floor(m.timer/K);if(f=fr(C.gpWind))m.state=1;return;} + const fl=this.airMove(m,'normal',inp);if(fl)this.land('gp',inp,fl); + } + lavaStep(inp){const m=this.mario; // S06 act_lava_boost steering and bounces + if(inp.stickMag>0){const dy=wrap(inp.yaw-m.yaw),mag=inp.mag/32;m.fwd+=inc(Math.cos(dy)*mag);m.yaw=wrap(m.yaw+ang(1024*Math.sin(dy)*mag)); + if(m.fwd<0){m.yaw=wrap(m.yaw+PI);m.fwd=-m.fwd;}if(m.fwd>32)m.fwd-=inc(2);}else m.fwd=approach(m.fwd,0,inc(C.airDrag)); + m.side=0;m.timer++;const fl=this.airMove(m,'lava',inp);if(!fl)return; + if(fl.lava){m.lavaBounces=0;this.hurtMario(this.kind==='bully'?this.T.lavaHurt:3);m.vy=C.lavaVy;this.stats.lavaBoosts++;this.fx('lava_burst',m,30);this.emit('lava_boost');return;} + if(m.lavaBounces<2&&m.vy<0){m.vy=-m.vy*.4;m.fwd/=2;m.lavaBounces++;return;} + this.land('free',inp,fl); + } + groundKnock(inp){const m=this.mario,k=m.kbKind||'soft'; // S07 common_ground_knockback_action + const cut={soft:100,fwd:20,back:22,hard:21}[k],len={soft:C.kbSoft,fwd:C.kbFwd,back:C.kbBack,hard:C.kbHard}[k]; + m.fwd=N.clamp(m.fwd,-C.kbCap,C.kbCap);if(Math.floor(m.timer/K)=0?.1:-.1; + m.timer++;if(!this.groundStep(m)){const arg=m.arg;this.setAction('airkb',arg);m.vy=0;return;} + if(m.timer>=fr(len)){if(m.arg>0)m.invinc=fr(C.invincFrames);this.setAction('idle');} + } + squishedStep(){const m=this.mario,b=this.boss;m.fwd=0;m.vy=0;m.timer++; // S12 act_squished states 1-2 + const room=!b||b.kind!=='whomp'||b.act==='chase'||(b.act==='ground'&&b.sub===10&&b.pitchfr(300)){m.health=0xff;m.hurt=0;this.setAction('dead');}return;} + if(m.timer>=fr(15)){if(m.health<0x100){this.setAction('dead');this.emit('mario_dead');}else if(m.hurt===0){m.squish=fr(30);this.setAction('idle');}} + } + squishMario(units){const m=this.mario;if(['squished','dead'].includes(m.action))return;if(m.holding)this.dropHeld(); + const safe=m.invinc>0;this.setAction('squished');m.fwd=0;m.vy=0;m.side=0;m.y=0;m.squish=fr(30); + if(!safe)this.hurtMario(units);this.stats.squished++;this.emit('mario_squished');this.boss.squishedMario=true;} + // ---------------- King Bob-omb (S02 king_bobomb.inc.c, S14 chuckya.inc.c anchor, S15 act_grabbed, S16 object_helpers) ---- + kingGrabsMario(){const m=this.mario,k=this.boss;this.setAction('grabbed');m.yaw=k.yaw;m.fwd=0;m.vy=0;m.side=0;m.grabRelease=0; + k.act=3;k.sub=0;k.timer=0;k.escape=0;k.u104=0;k.grabbedMario=true;this.emit('king_grabs_mario');} + kingReleasesMario(fwd,vy){const m=this.mario,k=this.boss;k.grabbedMario=false;m.yaw=k.yaw;this.setAction('thrown',0);m.fwd=fwd;m.vy=vy;m.peakY=m.y; + m.thrownHurt=fwd>=40?this.T.throwHurt:0;this.emit(fwd>=40?'king_throws_mario':'mario_escapes');} + grabKing(){const m=this.mario,k=this.boss;if(k.kind!=='king')return;m.holding=true;k.held=true;k.tangible=false;k.act=6;k.sub=0;k.timer=0; + this.stats.grabs++;this.emit('grab_king');} + dropHeld(thrown=false){const m=this.mario,k=this.boss;if(!m.holding)return;m.holding=false; + if(k.kind==='bowser')return this.bowserLetGo(thrown); + if(k.kind!=='king')return;k.held=false; + // The heavy throw drops him (mario_drop_held_object: hands' x/z, Mario's own y); being dropped or thrown he gets + // 20 forward / 50 up, one vertical step (gravity 4: vy 46, y + 46), +20 height, action 4, intangible (S02 loop, S16). + // That first frame has no horizontal move, so his flight from here is 23 more frames, 388 units (A01). + k.x=m.x+Math.sin(m.yaw)*30;k.z=m.z+Math.cos(m.yaw)*30;k.y=m.y+66;k.yaw=m.yaw;k.fwd=20;k.vy=46; + k.act=4;k.sub=0;k.timer=0;k.tangible=false;k.skip=K-1;this.stats.throws++;this.emit(thrown?'throw_king':'drop_king');} + kingReset(){const k=this.boss;Object.assign(k,{x:k.homeX,z:k.homeZ,y:0,vy:0,fwd:0,act:0,sub:0,timer:0,hp:k.maxHp,opener:0,wait:0,held:false,tangible:false,interact:'grab',grabbedMario:false}); + this.stats.bossResets++;this.emit('king_reset');} + kingStep(k){const nx=k.x+Math.sin(k.yaw)*k.fwd/K,nz=k.z+Math.cos(k.yaw)*k.fwd/K;if(this.inside(nx,nz,60)){k.x=nx;k.z=nz;}} + kingUpdate(){const k=this.boss,m=this.mario,T=this.T;k.timer++; + if(k.held){k.x=m.x+Math.sin(m.yaw)*30;k.z=m.z+Math.cos(m.yaw)*30;k.y=m.y+KING.holdY;k.yaw=m.yaw;return;} + switch(k.act){ + // Waits at home until Mario comes within 500 (textbox check, S02 act 0), then his speech (dialog skipped: 1 s). + case 0:k.tangible=false;k.fwd=0;if(hd(k,m)>=this.arena.talk&&k.sub===0){k.timer=0;return;}k.sub=1; + k.yaw=turnTo(k.yaw,yawTo(k,m),ang(0x400));if(k.timer>=fr(30)){k.act=2;k.sub=0;k.timer=0;k.tangible=true;k.interact='grab';}return; + case 1:k.fwd=0;k.yaw=turnTo(k.yaw,yawTo(k,m),ang(0x200));if(hd(k,m)<2500){k.act=2;k.timer=0;}return; + case 2:k.tangible=true;k.interact='grab'; + // Opening stomp: anim 4 (26 frames, S18) once per fight, then anim 11 walking. + if(k.opener<2){k.fwd=0;if(k.opener===0&&k.timer>=fr(25)){k.opener=2;k.timer=0;}} + else if(k.wait>0){k.fwd=0;k.wait--;}else{k.fwd=T.walk;k.yaw=turnTo(k.yaw,yawTo(k,m),ang(T.turn));} + this.kingStep(k);return; + case 3: // carrying Mario, then turns to world yaw 0 and throws him 50 forward / 50 up (S02 act 3, S14 case 2) + if(k.sub===0){k.fwd=0;k.u104=0;k.escape=0;if(k.timer>=fr(23)){k.sub=1;k.timer=0;}} // anim 0 = 24 frames (S18) + else if(k.sub===1){ + if(k.escape>T.escape){k.act=2;k.wait=fr(35);k.timer=0;this.anchorMario();this.kingReleasesMario(10,10);return;} + k.fwd=3;if(k.u104>fr(20)){k.yaw=turnTo(k.yaw,0,ang(0x400));if(Math.abs(k.yaw)<1e-9){k.yaw=0;k.sub=2;k.timer=0;}}k.u104++;} + else{if(k.timer===fr(9)){this.anchorMario();this.kingReleasesMario(50,50);}if(k.timer>=fr(26)){k.act=1;k.timer=0;k.sub=0;}} // anim 9 frames 22..48, release at 31 + this.kingStep(k);if(k.grabbedMario)this.anchorMario();return; + case 4:{ // thrown: drag 10 (S13 physics) on each velocity axis, gravity 4, terminal -78 (cur_obj_move_standard, S16) + if(k.skip>0){k.skip--;return;} // rest of the release frame (already stepped in dropHeld) + const vx=Math.sin(k.yaw)*k.fwd,vz=Math.cos(k.yaw)*k.fwd,dk=KING.drag*1e-4/K,nvx=vx-dk*vx*Math.abs(vx),nvz=vz-dk*vz*Math.abs(vz); + k.fwd=Math.hypot(nvx,nvz);k.x+=nvx/K;k.z+=nvz/K;const v0=k.vy;objFall(k,4,78); + if(k.sub===0){const fl=this.floor(k.x,k.z,k.y+40); + if(k.y<=fl.y&&v0<=0){k.y=fl.y;k.vy=0;k.fwd=0; + if(fl.y>-100){k.hp--;this.stats.bossHits++;this.fx('impact',k,30);this.emit('king_hit'); // landed on his summit + if(k.hp<=0){k.act=7;k.timer=0;this.emit('king_defeated');}else{k.act=6;k.sub=0;k.timer=0;k.tangible=true;k.interact='damage';}} + else{k.sub=1;k.timer=0;this.emit('king_off_summit');}}} // landed below it: no damage, gets up (anim 10) then jumps home + else if(k.timer>=fr(24)){k.act=5;k.timer=0;k.arc={x:k.x,y:k.y,z:k.z};} + return;} + case 5:{const T5=fr(50),p=Math.min(1,k.timer/T5),a=k.arc;k.tangible=false;k.x=a.x+(k.homeX-a.x)*p;k.z=a.z+(k.homeZ-a.z)*p; // velY 100, gravity 4: 50 frames + k.y=a.y*(1-p)+Math.sin(PI*p)*900;k.yaw=yawTo(k,m);if(k.timer>=T5+fr(20)){k.y=0;k.act=2;k.timer=0;k.wait=0;}return;} + case 6: // hurt: damaging to touch for four loops of anim 2 (8 frames) and anim 10 (26), then intangible turn (S02 act 6) + if(k.sub===0){k.interact='damage';k.tangible=true;if(k.timer>=fr(32)){k.sub=1;k.timer=0;}} + else if(k.sub===1){if(k.timer>=fr(25)){k.sub=2;k.timer=0;k.interact='grab';k.tangible=false;}} + else{k.yaw=turnTo(k.yaw,yawTo(k,m),ang(0x800));if(Math.abs(wrap(yawTo(k,m)-k.yaw))<1e-6||k.timer>fr(60)){k.act=2;k.timer=0;k.tangible=true;}} + return; + case 7:k.tangible=false;if(k.timer>=fr(30)){this.outcome='win';this.emit('star');}return; + } + } + anchorMario(){const k=this.boss,m=this.mario,fx=Math.sin(k.yaw),fz=Math.cos(k.yaw); + m.x=k.x+fx*KING.anchorFwd+fz*KING.anchorSide;m.z=k.z+fz*KING.anchorFwd-fx*KING.anchorSide;m.y=k.y+KING.anchorY;m.yaw=k.yaw;} + escapeActions(inp){const m=this.mario;let n=0; // S16 player_performed_grab_escape_action + if(inp.stickMag<30)m.grabRelease=0;if(m.grabRelease===0&&inp.stickMag>40){m.grabRelease=1;n=1;}if(inp.aP)n=1;return n;} + // ---------------- Whomp King (S01 whomp.inc.c) ---------------- + whompUpdate(){const b=this.boss,m=this.mario,T=this.T;b.timer++;b.hitNow=b.hitNow&&b.act==='ground'; + const face=yawTo(b,m),inCone=Math.abs(wrap(face-b.yaw))=this.arena.talk&&b.sub===0){b.timer=0;return;}b.sub=1; + b.yaw=turnTo(b.yaw,face,ang(0x200));if(b.timer>=fr(30)){b.act='chase';b.sub=0;b.timer=0;}return; + case 'chase':b.fwd=3;b.yaw=turnTo(b.yaw,face,ang(T.turn)); + if(b.timer>fr(T.delay)&&inCone&&m.action!=='dead'){if(d<1500)b.fwd=T.fast;if(d=fr(14)){b.act='jump';b.timer=0;b.vy=40;this.emit('whomp_slam');}return; // anim 1 = 15 frames (S17), "near end" + case 'jump':case 'land':{objFall(b,4,78);if(b.y<0)b.y=0; + if(b.act==='jump'&&b.timer>=fr(8)){b.pitchVel+=0x100/K;b.pitch+=deg(b.pitchVel/K+0x100/(4*K)); + if(b.pitch>=deg(0x4000)){b.pitch=deg(0x4000);b.pitchVel=0;b.act='land';}} + if(b.act==='land'&&b.y<=0&&b.vy<=0){b.y=0;b.vy=0;b.act='ground';b.sub=0;b.timer=0;b.squishedMario=false;this.fx('slam_dust',this.slabCenter(),30);this.emit('whomp_landed'); + // SM64 squishes through the ceiling over Mario's centre point; a cylinder only clipping the edge is pushed out by the walls. + const s=this.slabLocal(m.x,m.z); + if(s.f>=SLAB.h0&&s.f<=SLAB.h1&&Math.abs(s.u)<=SLAB.half&&m.yfr(T.lie)||(m.action==='squished'&&b.timer>fr(30)))b.sub=10;return;} + if(b.sub===1){b.shake=b.timer%K===0?(Math.floor(b.timer/K)%2?8:-8):b.shake;if(b.timer>=fr(10)){b.shake=0;b.sub=10;}return;} + b.pitch-=ang(0x200); // rises at 0x200 per frame + if(m.onBoss&&b.pitch=fr(30)){b.act='dead';this.outcome='win';this.emit('star');}return; + } + } + slabCenter(){const b=this.boss;return {x:b.x+Math.sin(b.yaw)*480,y:100,z:b.z+Math.cos(b.yaw)*480};} + ejectFromBack(){const m=this.mario,b=this.boss;m.onBoss=false;m.yaw=wrap(b.yaw+PI);this.airborne('freefall',null);m.vy=18;m.fwd=14;} + whompSolid(){const b=this.boss,m=this.mario;if(b.kind!=='whomp'||b.act==='dead'||m.action==='grabbed')return; + const s=this.slabLocal(m.x,m.z),r=C.radius;let lo,hi,top; + // While the slab is coming down it is not a wall: whoever is under it at touchdown is squished (S12). + if(b.pitch=top||m.action==='squished')return; + const cf=N.clamp(s.f,lo,hi),cu=N.clamp(s.u,-SLAB.half,SLAB.half),df=s.f-cf,du=s.u-cu,dist=Math.hypot(df,du);if(dist>=r)return; + let nf,nu;if(dist>1e-6){nf=s.f+df/dist*(r-dist);nu=s.u+du/dist*(r-dist);} + else{const pens=[[s.f-lo+r,'f',lo-r],[hi-s.f+r,'f',hi+r],[s.u+SLAB.half+r,'u',-SLAB.half-r],[SLAB.half-s.u+r,'u',SLAB.half+r]].sort((p,q)=>p[0]-q[0])[0]; + nf=pens[1]==='f'?pens[2]:s.f;nu=pens[1]==='u'?pens[2]:s.u;} + const fx=Math.sin(b.yaw),fz=Math.cos(b.yaw);m.x=b.x+nf*fx-nu*fz;m.z=b.z+nf*fz+nu*fx;} + // ---------------- Big Bully (S03 bully.inc.c) ---------------- + bullyUpdate(){const b=this.boss,m=this.mario,T=this.T,home={x:b.homeX,z:b.homeZ},lavaY=this.arena.drop[0];b.timer++; + if(b.act!=='patrol')b.noBackup=false; + if(b.act==='fall'){objFall(b,BULLY.gravity,75); + if(b.y<=0){b.y=0;b.vy=0;b.act='chase';b.timer=0;this.fx('slam_dust',b,24);this.emit('bully_lands');}return;} + if(b.act==='sink'){b.y-=inc(10);if(b.timer>=fr(31)){b.lives--;this.emit('bully_burned'); + if(b.lives<=0){b.act='dead';this.outcome='win';this.emit('star');return;} + Object.assign(b,{act:'fall',x:b.homeX,z:b.homeZ,y:1800,vy:0,fwd:0,timer:0,counter:0});}return;} + if(b.act==='dead')return; + const old={x:b.x,z:b.z},face=yawTo(b,m); + if(b.act==='chase'){ + // S03: 10 frames at speed 3 turning 0x1000/frame toward Mario (0xA000 = 225 degrees in all), then the charge. The + // tiers shorten the wind-up (`slow`); the turn rate scales with it so the aim budget stays 0xA000 (T1). + if(b.timerfr(35))b.timer=0;if(hd(m,home)>T.leave&&m.action!=='lava'){b.act='patrol';b.timer=0;} + }else if(b.act==='patrol'){b.fwd=5;if(hd(m,home)=fr(T.recover)){b.act='chase';b.timer=0;b.counter=0;}} + else b.fwd*=fac(BULLY.friction);} + }else if(b.act==='backup'){ // S03 bully_act_back_up: reverse, walk backward at 5 for 15 frames, then patrol + if(b.timer===1){let rev=wrap(b.moveYaw+PI);b.backFace=b.faceYaw; + // T3: in a corner the reversed heading leaves by the other edge within the 75-unit back-up; SM64 then stalls + // there for good (with the end-of-back-up bug below). He heads home instead, so he keeps engaging. + if(!this.inside(b.x+Math.sin(rev)*80,b.z+Math.cos(rev)*80))rev=yawTo(b,home);b.moveYaw=rev;} + b.fwd=5;if(b.timer>fr(15)){b.act='patrol';b.timer=0;b.moveYaw=b.backFace;b.noBackup=true;}} + b.x+=Math.sin(b.moveYaw)*b.fwd/K;b.z+=Math.cos(b.moveYaw)*b.fwd/K; + if(b.act!=='knockback'&&b.act!=='backup')b.faceYaw=b.moveYaw; // he backs up facing the edge (flag cleared, S03) + if(!this.inside(b.x,b.z)){ + // S03 bully_backup_check: starting to fall (not in knockback) undoes the step and starts the back-up; already + // backing up, it only blocks (the action does not restart). T3: the decomp's //! bug, re-entering the back-up on + // the frame it ends (which leaves him stuck in it), is not reproduced. + if(b.act!=='knockback'&&b.y===0){b.x=old.x;b.z=old.z;if(b.act!=='backup'&&!b.noBackup){b.act='backup';b.timer=0;}} + else{objFall(b,BULLY.gravity,75); + if(b.y<=lavaY){b.y=lavaY;b.vy=0;b.fwd=0;b.act='sink';b.timer=0;this.stats.bossHits++;this.fx('lava_burst',b,40);this.emit('bully_in_lava');}} + } + } + // ---------------- Eyerok (S35 eyerok.inc.c; hand collision S36; squish S12 act_squished + S05 mario.c 1344) ---------- + // The hands run the original 30 Hz object logic once per two ticks, so every per-frame constant below is the decomp's + // own. Only a squish hurts: the hands deal no contact damage (hitbox damage 0, hurtbox 1 x 1, S35). + handBox(h){return h.open?HAND.open:HAND.fist;} + handLocal(h,x,z){const s=Math.sin(h.face),c=Math.cos(h.face),rx=x-h.x,rz=z-h.z;return {x:rx*c-rz*s,z:rx*s+rz*c};} + handWorld(h,lx,lz){const s=Math.sin(h.face),c=Math.cos(h.face);return {x:h.x+lx*c+lz*s,z:h.z-lx*s+lz*c};} + handOverPoint(h,x,z){const B=this.handBox(h),l=this.handLocal(h,x,z);return l.x>=B.x0&&l.x<=B.x1&&l.z>=B.z0&&l.z<=B.z1;} + solidHands(){return this.boss.hands.filter(h=>!h.gone&&h.act!=='sleep');} + // A hand's top is a floor: Mario can stand on it and is carried (S36 dynamic collision). + handTop(x,z,y){let best=null;for(const h of this.solidHands())if(this.handOverPoint(h,x,z)){const t=h.y+this.handBox(h).y1;if(y>=t-78&&(best===null||t>best))best=t;}return best;} + // Ceiling-to-floor distance over Mario's point, the only quantity act_squished reads (S05 mario.c 1344). The query starts at + // floor + 80 and S39 find_ceil keeps surfaces at least 2 above the floor; a top within 78 of Mario's feet is his floor instead. + // Only the fist has an underside: the open hand's collision has no bottom triangles (S36 070282F8), so it can never squish. + ceilGap(){const m=this.mario,fy=m.onBoss?m.y:0;let gap=Infinity;if(!inPoly(this.arena.poly,m.x,m.z))return gap; + for(const h of this.solidHands())if(!h.open&&this.handOverPoint(h,m.x,m.z)){const B=HAND.fist,under=h.y+B.y0; + if(m.y+78=fy+2)gap=Math.min(gap,under-fy);}return gap;} + handSquishStep(){const m=this.mario,gap=this.ceilGap();m.fwd=0;m.vy=0;m.side=0; // S12 act_squished + if(m.arg++>fr(300)){m.health=0xff;m.hurt=0;this.setAction('dead');this.emit('mario_dead');return;} + if(m.state===0){if(gap>160){m.squish=0;return this.setAction('idle');} + if(gap<10.1){if(m.invinc===0){this.hurtMario(this.T.squish);this.stats.squished++;this.emit('mario_squished');}m.state=1;}return;} + if(m.state===1){if(gap>=30){m.state=2;m.timer=0;}return;} + if(++m.timer>=fr(15)){if(m.health<0x100){this.setAction('dead');this.emit('mario_dead');}else if(m.hurt===0){m.squish=fr(30);this.setAction('idle');}}} + // Hands are walls for Mario: S09 checks (offset 60, radius 50) and (30, 24) on the ground, (150, 50) and (30, 50) in the air, and + // S39 find_wall only acts within the radius, so Mario deep under a fist is not pushed out (that is what lets it squish him). + // A push past the rim drops him to his death (S35 fist push). Boxes approximate the hand's four-sided hull (A7). + handSolid(inp){const m=this.mario;if(m.action==='dead')return;const air=AIR.has(m.action); + for(const h of this.solidHands()){const B=this.handBox(h),lo=h.y+B.y0-5,hi=h.y+B.y1+5; + for(const [off,r] of air?[[150,50],[30,50]]:[[60,50],[30,24]]){const y=m.y+off;if(yhi)continue; + const l=this.handLocal(h,m.x,m.z),cx=N.clamp(l.x,B.x0,B.x1),cz=N.clamp(l.z,B.z0,B.z1),dx=l.x-cx,dz=l.z-cz,dist=Math.hypot(dx,dz);if(dist>=r)continue; + let nx,nz;if(dist>1e-6){nx=l.x+dx/dist*(r-dist);nz=l.z+dz/dist*(r-dist);} + else{const p=[[l.x-B.x0,B.x0-r,l.z],[B.x1-l.x,B.x1+r,l.z],[l.z-B.z0,l.x,B.z0-r],[B.z1-l.z,l.x,B.z1+r]].sort((a,b)=>a[0]-b[0])[0];if(p[0]>r)continue;nx=p[1];nz=p[2];} + const w=this.handWorld(h,nx,nz);m.x=w.x;m.z=w.z;}} + if(m.z=deg(0x3000))return false; + h.hp--;b.hp--;this.stats.bossHits++;this.fx('impact',{x:h.x,y:h.y+150,z:h.z},30);this.emit('eyerok_hit'); + if(h.hp>=2){h.act='attacked';h.vy=30;}else{b.handsLeft--;h.act='die';h.vy=50;this.emit('eyerok_hand_dead');} + h.fwd*=.2;h.move=wrap(h.face+PI);h.ground=false;h.edge=false;h.g=-4;h.blink=3;return true;} + handPound(h){this.fx('slam_dust',{x:h.x,y:0,z:h.z},30);this.emit('eyerok_pound');} + handFrame(h){const b=this.boss,m=this.mario,T=this.T,z400=m.z<400,toM=yawTo(h,m),S=h.side,carry=m.onBoss&&m.onHand===h.idx,ox=h.x,oz=h.z; + switch(h.act){ + case 'sleep': + if(b.act!=='sleep'&&++h.wake>-3*S){ + if(this.animEnd(h,6)){b.handsLeft++;h.act='idle';break;} + h.x=approach(h.x,h.homeX,15);h.y=(200*S+400)*Math.sin(Math.abs(h.x-h.homeX)/724*PI);h.face=turnTo(h.face,h.move,deg(400));h.af++;} + return; // placed directly until awake: no floor or wall step + case 'idle':this.animEnd(h,2); + if(b.act==='fight'){ + if(b.pound!==0){if(b.pound!==1){h.act='begin';h.g=0;}} + else if(b.eyeHand===0&&b.active!==0){ + if(b.active===S){this.emit('eyerok_attack');if(z400||N.rand(this)<.5){h.act='target';h.move=toM;h.g=0;} + else{h.act='push';h.move=wrap(toM+deg(b.x-m.x<0?-0x800:0x800));h.g=-4;}} + else h.act='open';} + }else h.y=b.lift; + break; + case 'open':b.eyeHand=S; + if(this.animEnd(h,4)){h.act='eye';h.fc=2;h.u100=60;h.open=true;this.emit('eyerok_eye'); + if(b.handsLeft!==2){h.move=N.clamp(toM,-deg(0x3000),deg(0x3000));h.fwd=T.rush;}else h.move=0;} + break; + case 'eye':this.animEnd(h,5); + if(!this.handAttacked(h)){ + if(b.active===0){if(h.blink<3)h.blink++;else if(h.af===EYEROK.anim[5]-2)h.act='close';} + else{if(h.u100-->0){if(h.fc!==0)h.fc--;h.blink=EYEROK.blink[h.fc];}else{h.fc=5;h.u100=20+Math.trunc(50*N.rand(this));} + if(b.handsLeft!==2){h.face=turnTo(h.face,h.move,deg(0x800));if(h.timer>10&&(h.z-m.z>0||h.edge)){b.active=0;h.fwd=0;}}}} + break; + case 'close':if(h.anim!==7){h.anim=7;h.af=-1;} // S37 anim 7 is anim 4 played backward from frame 29; the check is frame 1, 28 frames in + if(h.timer>=28){h.open=false; + if(b.handsLeft!==2){h.act='retreat';b.active=S;}else if(b.active===0){h.act='idle';b.eyeHand=0;}} + break; + case 'attacked':if(this.animEnd(h,3)){h.act='recover';h.open=false;}if(h.ground)h.fwd=0;break; + case 'recover':if(this.animEnd(h,0))h.act='become';break; + case 'become':if(b.active===0||b.handsLeft!==2){h.act='retreat';b.active=S;}break; + case 'die':if(this.animEnd(h,1)){b.eyeHand=0;h.gone=true;this.fx('mist',{x:h.x,y:h.y+150,z:h.z},40);this.emit('eyerok_hand_gone');return;} + if(h.ground)h.fwd=0;break; + case 'retreat':{let dist=Math.hypot(h.x-h.homeX,h.z-h.homeZ);const a=Math.atan2(h.x-h.homeX,h.z-h.homeZ);dist=Math.max(0,dist-T.retreat); + h.x=h.homeX+dist*Math.sin(a);h.z=h.homeZ+dist*Math.cos(a);h.face=turnTo(h.face,0,deg(400));h.y=approach(h.y,0,20); + if(h.y===0&&dist===0&&Math.abs(h.face)<1e-9){h.face=0;h.act='idle';b.active-=S;if(b.eyeHand===S)b.eyeHand=0;}break;} + case 'target': + if(z400||h.z-m.z>0||h.z-b.z>1700||Math.abs(h.x-b.x)>900||h.wall){h.fwd=0;h.y=approach(h.y,300,20);if(h.y===300){h.act='smash';this.emit('eyerok_smash');}} + else{h.fwd=approach(h.fwd,50,5);h.y=approach(h.y,300,20);h.move=turnTo(h.move,toM,deg(4000));} + break; + case 'smash':if(h.timer>T.smashWait){ + if(h.ground){if(h.g<-4){this.handPound(h);h.g=-4;} + else{const a=Math.abs(wrap(h.face-toM)); + if(Math.hypot(m.x-h.x,m.y-h.y,m.z-h.z)<300&&a>deg(0x2000)&&a5&&(h.z-m.z>0||h.edge)){h.act='sweep';h.fwd=0;h.move=h.x-m.x<0?deg(0x4000):-deg(0x4000);this.emit('eyerok_sweep');}else h.fwd=T.push;break; + case 'sweep':if(h.z-b.z<1000||h.edge){h.act='retreat';h.fwd=0;}else{h.fwd=approach(h.fwd,5,.02)*1.08;h.timer=0;}break; + case 'begin': + if(b.pound<0||b.active===S){h.act='pound';h.move=wrap(h.face-deg(0x4000)*b.dir);} + else{const tx=b.x+400*b.dir-180*S;h.x=h.homeX+(tx-h.homeX)*b.lift;h.y=300*b.lift;h.z=h.homeZ+(b.zt-h.homeZ)*b.lift;} + break; + case 'pound':if(b.handsLeft!==2)b.active=S; + if(b.pound===1){h.act='retreat';b.eyeHand=S;} + else if(b.active===S){ + if(h.ground){if(h.g<-15){b.active=0;this.handPound(h);h.fwd=0;h.g=-15;}else{h.fwd=30*Math.abs(b.dir);h.vy=100;h.ground=false;h.edge=false;}} + else if(h.vy<=0)h.g=-20;} + break; + } + if(h.act!==h.prevAct){h.prevAct=h.act;h.timer=0;}else h.timer++; + h.af=EYEROK.noloop.has(h.anim)?Math.min(EYEROK.anim[h.anim]-1,h.af+1):(h.af+1)%EYEROK.anim[h.anim]; + // S16 cur_obj_move_standard(-78): a grounded hand stops at an edge, an airborne one may pass it; no drag, no bounce. + const nx=h.x+h.fwd*Math.sin(h.move),nz=h.z+h.fwd*Math.cos(h.move);h.edge=false; + if(h.fwd!==0&&h.ground&&!inPoly(this.arena.poly,nx,nz))h.edge=true;else{h.x=nx;h.z=nz;} + h.wall=h.z=30){b.act='fight';this.emit('eyerok_fight');}break; // dialog 117 skipped: 1 s + case 'fight':if(b.handsLeft===0){b.act='die';b.timer=0;this.emit('eyerok_defeated');break;} + if(b.eyeHand!==0||b.active!==0)break; + if(b.pound!==0){b.lift=approach(b.lift,1,.02); + if(b.lift===1){if(b.pound<0){if(m.z>=400&&++b.pound===0)b.pound=1;}else b.pound--; + if(b.pound!==0&&b.pound!==1){b.fc++;b.active=b.fc&1?1:-1;}}} + else{b.fc++; + if(m.z<400){b.pound=-8;b.lift=1;b.dir=0;} + else if(b.handsLeft===2&&b.fc%T.every===0){b.pound=T.pounds;b.lift=0;b.fc=N.rand(this)<.5?1:0;b.dir=b.fc?-1:1;b.zt=N.clamp(m.z,400,1600);this.emit('eyerok_double');} + else b.active=b.fc&1?1:-1;} + break; + case 'die':if(++b.timer>=30){b.act='dead';this.outcome='win';this.emit('star');}break; // S35 waits 60 frames for dialog 118, then the star (dialog skipped) + } + } + eyerokUpdate(inp){const b=this.boss,m=this.mario; + if(this.t%K===0){for(const h of b.hands)if(!h.gone)this.handFrame(h);this.eyerokBoss();} + if(m.onBoss&&!AIR.has(m.action)&&m.action!=='squished'){const t=this.handTop(m.x,m.z,m.y); + if(t===null||tthis.handOverPoint(q,m.x,m.z)&&q.y+this.handBox(q).y1===t);m.onHand=h?h.idx:-1;}} + else if(!m.onBoss)m.onHand=-1; + this.handSolid(inp); + if(!['squished','dead'].includes(m.action)&&this.ceilGap()<=150){if(m.holding)this.dropHeld();this.setAction('squished');m.fwd=0;m.vy=0;m.side=0;m.y=m.onBoss?m.y:0;} // S05 INPUT_SQUISHED + } + // ---------------- Wiggler (S40 wiggler.inc.c, S43 obj_behaviors_2.c, S04 interact_bounce_top, S41 room) ----------------- + // One object frame every two ticks, as for Eyerok (T5), so every per-frame constant below is the decomp's own. + wigglerParts(){const b=this.boss,s=b.s,h={x:b.x,y:b.y,z:b.z,head:true,r:60*b.sx,h:50*b.sy,hr:30*b.sx,hh:40*b.sy}; // S16 obj_set_hitbox scales the head by scale[1]; the body parts stay at scale[0] (S40) + return [h,...[1,2,3].map(i=>({x:s[i].px,y:s[i].y,z:s[i].pz,head:false,r:20*b.sx,h:20*b.sx,hr:20*b.sx,hh:10*b.sx}))];} + wigglerSpeed(){const b=this.boss,T=this.T;return b.hp===b.maxHp?T.calm:b.hp===1?T.fury:T.chase;} // S40 sWigglerSpeeds by health; extra hits keep the middle speed (T6) + wigglerFrame(){const b=this.boss,m=this.mario,T=this.T,R=this.arena.poly,x0=R[0][0]+60,x1=R[2][0]-60,z0=R[0][1]+60,z1=R[2][1]-60; + // S43 treat_far_home_as_mario, home at the origin; S16 wall resolve flags a wall only while moving into it. + const far=Math.hypot(b.x,b.y,b.z)>T.leash,toM=far?Math.atan2(-b.x,-b.z):yawTo(b,m);let wall=null; + if(b.xx1){b.x=x1;wall=-PI/2;}if(b.zz1){b.z=z1;wall=PI;} + if(wall!==null&&Math.abs(wrap(wall-b.move))<=PI/2)wall=null; + const attack=b.pending;b.pending=null; + switch(b.act){ + case 'walk': + if(b.intro>0){b.intro--;break;} // dialog 150 skipped: 1 s (A9) + b.fwd=approach(b.fwd,this.wigglerSpeed(),1); + if(b.away>0)b.away--; + else{if(far)b.target=toM; + if(wall!==null){b.target=wrap(2*wall-b.move+PI);b.away=30+Math.trunc(30*N.rand(this));} + else if(b.hp0)b.turnIn--; + else{b.target=wrap(b.move+(N.rand(this)<.5?-1:1)*deg(0x4000));b.turnIn=30+Math.trunc(50*N.rand(this));}} + {const turn=deg(30*b.fwd);b.move=turnTo(b.move,b.target,turn);b.face=turnTo(b.face,b.move,2*turn);b.pitch=approach(b.pitch,0,deg(0x320));} + if(b.timer>=60&&attack){ // S40: the first 60 frames of each walk only bounce Mario off + if(attack==='above'||attack==='pound'){b.act='jumped';b.fwd=0;b.vy=0;b.sv=.4;this.stats.bossHits++;this.fx('impact',{x:b.x,y:b.y+120,z:b.z},30);this.emit('wiggler_stomped');} + else{b.act='knockback';const up=attack!=='punch';b.fwd=up?20:50;b.vy=up?50:30;b.move=yawTo(m,b);this.emit('wiggler_knocked');} // S43 obj_set_knockback_action + b.away=0;} + break; + case 'jumped': + b.sv=approach(b.sv,0,.05);if(b.sv===0)b.sy=approach(b.sy,4,.2);else b.sy-=b.sv; + if(b.sy>=4){if(b.timer>T.daze){b.hp--;this.emit('wiggler_hit'); // S40 dialogs 152, 168, 151 skipped + if(b.hp<=0){b.act='shrink';this.emit('wiggler_defeated');} + else{b.act='walk';b.move=b.face;b.target=b.face;if(b.hp===1){b.fwd=10;b.vy=70;this.emit('wiggler_jump');}}}} + else b.timer=-1; + break; + case 'knockback': + if(b.vy>0)b.pitch-=deg(b.vy*30);else b.pitch=approach(b.pitch,0,deg(0x190)); + b.fwd=approach(b.fwd,0,1);if(b.fwd===0&&b.pitch===0){b.act='walk';b.move=b.face;} + break; + case 'shrink':if(b.timer>=20){b.sx=approach(b.sx,1,.1);b.sy=b.sx;if(b.sx===1){b.act='dead';this.outcome='win';this.emit('star');return;}}break; + case 'dead':return; + } + if(b.act!==b.prevAct){b.prevAct=b.act;b.timer=0;}else b.timer++; + // S16 cur_obj_move_standard(-78): drag per axis (S13 strength 10), then x/z, then y with gravity 4 and no bounce. The drag is why speed 40 never reads 40. + const vx0=Math.sin(b.move)*b.fwd,vz0=Math.cos(b.move)*b.fwd,vx=vx0-.001*vx0*Math.abs(vx0),vz=vz0-.001*vz0*Math.abs(vz0); + b.fwd=Math.hypot(vx,vz);b.x+=vx;b.z+=vz;b.vy=Math.max(-78,b.vy-4);b.y+=b.vy; + {const fl=wigFloor(b.x,b.z);if(b.ytop){m.y=top-C.height;if(m.vy>0)m.vy=0;}} // S09: the head stops under the hanging pyramid + } + // ---------------- Bowser in the Dark World (S50 bowser.inc.c, S51 bowser_flame.inc.c, S52 bowser_bomb.inc.c, S16 object_helpers.c) ---------------- + // One object frame every two ticks, as for Eyerok and Wiggler (T5), so every per-frame constant below is the decomp's own. + grabBowser(){const m=this.mario,b=this.boss;m.holding=true;m.yaw=b.yaw;m.fwd=0;m.vy=0;m.side=0;m.y=0;m.swing=0;b.held=true;b.heldT=0;b.grabbable=false;b.act='held';b.prev='held';this.setAction('grabbowser');this.stats.grabs++;this.emit('grab_bowser');} + // S16 cur_obj_get_thrown_or_placed, S50 bowser_thrown_dropped_update: both a throw and a drop leave at the speed of the spin. + bowserLetGo(thrown){const m=this.mario,b=this.boss,fx=Math.sin(m.yaw),fz=Math.cos(m.yaw);let spd=Math.abs(m.swing)/3000*70;if(spd>90)spd*=2.5; + Object.assign(b,{x:m.x+BOWSER.throwF*fx+BOWSER.throwL*fz,y:Math.max(0,m.y+BOWSER.throwY-2),z:m.z+BOWSER.throwF*fz-BOWSER.throwL*fx,yaw:m.yaw,fwd:spd,vy:0,held:false,act:'thrown',prev:'thrown',sub:0,timer:0,btimer:0,landed:false,onGround:false,tail:1,tailT:0,grabbable:false,skip:true}); + if(thrown){this.stats.throws++;this.emit('throw_bowser');}else this.emit('drop_bowser');m.swing=0;} + burnTick(){const m=this.mario;m.health-=5;m.burnLoss+=5;if(m.burnLoss>=0x100){m.burnLoss-=0x100;this.stats.damageTaken++;}} + burnMario(){const m=this.mario,fall=AIR.has(m.action)&&m.vy<=0;if(m.holding)this.dropHeld();m.burn=0;m.flash=24;this.stats.burns++;this.emit('mario_hurt');this.emit('mario_burned'); + this.setAction(fall?'burnfall':'burnjump');if(!fall){m.vy=31.5;m.fwd=8;m.ctrlJump=false;m.peakY=m.y;}m.side=0;} + // Runs in Mario's turn, like every other interaction here. + bowserContact(){const m=this.mario,b=this.boss,T=this.T,box=(o,r,h,down=0)=>hd(m,o)0&&box(q,150,150,150)&&this.startKnock(q,2))return;} + if(b.held||b.act==='dead')return; + if(b.op>=100&&box(b,BOWSER.bodyR,BOWSER.bodyH)&&!this.invulnerable()){m.fwd=40;this.startKnock(b,T.touch);this.emit('bowser_touch');return;} // S50 body anchor, S13 big knockback + if(!b.grabbable||!box(b,BOWSER.grabR,BOWSER.grabH))return; + if(Math.abs(wrap(m.yaw-b.yaw))>deg(0x5555))return; // S04 mario_check_object_grab: Mario must face the way he faces, so never from the front + if(PUNCHING.has(m.action)&&m.arg<2)m.canGrab=true;else if(m.action==='dive'||m.action==='diveslide')this.grabBowser();} // S04 able_to_grab_object + bowserFloor(x,z){return inPoly(this.arena.poly,x,z)?0:this.arena.drop[0];} + bowserAnim(i){const b=this.boss;if(b.anim!==i){b.anim=i;b.af=-1;}} + bowserNear(i){const b=this.boss;this.bowserAnim(i);const L=BOWSER.anim[i];return b.af===L-2||(i===9&&b.af===L-1);} // S16 cur_obj_check_if_near_animation_end + bowserExtend(){const b=this.boss;if(b.af===BOWSER.anim[b.anim]-2)b.af--;} // S16 cur_obj_extend_animation_if_at_end + bowserLand(dist){const b=this.boss,m=this.mario;if(!b.landed)return false;b.fwd=0;b.vy=0;this.bowserAnim(8);b.af=0;this.fx('slam_dust',b,30);this.emit('bowser_land');m.stomp=dist{f.s+=.5;if(f.p>0x800)f.p-=0x200;const c=Math.cos(f.p*S16);f.x+=Math.sin(f.yaw)*c*30;f.y-=Math.sin(f.p*S16)*30;f.z+=Math.cos(f.yaw)*c*30;if(f.s>30)return false; + const fl=this.bowserFloor(f.x,f.z);if(f.y>=fl)return true;b.fires.push({x:f.x,y:fl,z:f.z,yaw:N.rand(this)*PI*2-PI,vy:N.rand(this)<.2?80:20,fwd:10,s:N.rand(this)+1,act:0,t:0,g:4});return false;}); + const wob=Math.sin(((this.t/K)&0x3f)*1024*S16)*4; + b.fires=b.fires.filter(f=>{const vx=Math.sin(f.yaw)*f.fwd,vz=Math.cos(f.yaw)*f.fwd,dx=vx-.001*vx*Math.abs(vx),dz=vz-.001*vz*Math.abs(vz),fl=this.bowserFloor(f.x,f.z);f.x+=dx;f.z+=dz;f.fwd=Math.hypot(dx,dz);f.vy=Math.max(-78,f.vy-f.g);f.y+=f.vy; + const hit=f.yf.s*10+5){f.s-=.15;if(f.s<=0)return false;} + f.t++;return f.y>-600;});} + bowserFrame(){const b=this.boss,m=this.mario,T=this.T,c=this.arena.centre; + this.bowserFlames(); + for(const q of b.mines){if(q.blast>0)q.blast--;if(!q.alive&&this.d>0&&--q.back<=0){q.alive=true;this.emit('mine_back');}} + if(b.held){b.heldT++;return;} + if(b.skip){b.skip=false;return;} + if(b.act!==b.prev){b.prev=b.act;b.timer=0;b.sub=0;} + const dist=Math.hypot(m.x-b.x,m.y-b.y,m.z-b.z),toM=yawTo(b,m),off=Math.abs(wrap(toM-b.yaw)),toC=Math.atan2(c.x-b.x,c.z-b.z),distC=Math.hypot(c.x-b.x,c.z-b.z),flr=this.bowserFloor(b.x,b.z),ready=off=30)b.act='default';break; // the arena cutscene and dialog 67 skipped: 1 s (A12) + case 'default':{this.bowserAnim(12);b.fwd=0;b.vy=0;const r=N.rand(this); // S50 bowser_bitdw_actions: reacts every other time + if(!b.react){b.act=ready?(dist<1500?'breath':'quickjump'):'walk';b.react=1;}else{b.react=0;b.act=r<.1?'dance':'walk';}break;} + case 'breath':b.fwd=0;if(b.timer===0)this.emit('bowser_breath');if(this.bowserNear(6))b.act='default';break; + case 'walk': + b.yaw=turnTo(b.yaw,toM,deg(T.turn)); + if(b.sub===0){b.btimer=0;this.bowserAnim(15);if(b.af===21)b.fwd=T.walk;if(this.bowserNear(15))b.sub=1;} + else if(b.sub===1){b.fwd=T.walk;if(this.bowserNear(13)){b.btimer++;if(ready)b.sub=2;}} + else{this.bowserAnim(14);if(b.af===20)b.fwd=0;if(this.bowserNear(14))b.act='default';} + break; + case 'quickjump': + if(b.sub===0){this.bowserAnim(9);if(b.af===11){b.vy=60;b.fwd=50;b.btimer=0;b.sub=1;this.emit('bowser_jump');}} + else if(b.sub===1){if(this.bowserLand(dist))b.sub=2;} + else if(this.bowserNear(8))b.act='default'; + break; + case 'dance':if(this.bowserNear(10))b.act='default';break; + case 'thrown': // S50 bowser_act_thrown + if(b.timer<2)b.btimer=0; + if(b.sub===0){this.bowserAnim(2);if(b.landed){b.btimer++;this.fx('bump',b,16);}if(b.onGround){b.fwd=0;b.sub=1;}} + else if(this.bowserNear(0))b.act='default'; + this.bowserHitMine();break; + case 'hitmine': // S50 bowser_act_hit_mine: the original's own branch for health left (BitDW never reaches it) + if(b.timer===0){b.fwd=-400;b.vy=100;b.yaw=wrap(toC+PI);} + if(b.sub===0){this.bowserAnim(25);b.sub=1;b.btimer=0;} + else if(b.sub===1){this.bowserAnim(25);this.bowserExtend();if(b.landed){b.btimer++;this.fx('bump',b,16);}if(b.btimer>2){this.bowserAnim(26);b.vy=0;b.fwd=0;b.sub=2;}} + else if(this.bowserNear(26))b.act=b.hp===1?'dance':'default'; + break; + case 'jumpstage': // S50 bowser_act_jump_onto_stage + if(b.sub===0){b.spin+=0x800;if(!(b.spin&0xffff))b.sub=1;this.bowserHide();} + else if(b.sub===1){this.bowserAnim(9);if(b.af===11){b.yaw=toC;b.vy=150;b.btimer=0;b.sub=2;}else this.bowserHide();} + else if(b.sub===2){ + if(b.y>0){b.drag=0;if(distC<2500&&Math.abs(flr)<100)b.fwd=Math.max(0,b.fwd-5);else b.fwd=b.fwd>=150?150:b.fwd+2;} + if(this.bowserLand(dist)){b.drag=10;b.sub=3;} + else if(b.vy<0&&b.y<-300){b.x=c.x;b.z=c.z;b.y=2000;b.vy=0;b.fwd=0;}} + else if(this.bowserNear(8))b.act='default'; + break; + case 'dead': // S50 bowser_act_dead up to the end of his bounce; dialog 119, the walk up to him and the key are skipped + if(b.sub===0){this.bowserAnim(25);b.fwd=-200;b.vy=100;b.yaw=wrap(toC+PI);b.btimer=0;b.sub=1;} + else if(b.onGround){b.fwd=0;this.outcome='win';this.emit('star');return;} + break; + } + {const neg=b.fwd<0,D=b.drag*1e-4,drag=v=>{if(v===0)return 0;const a=v*v*D;if(v>0){v-=a;return v<.001?0:v;}v+=a;return v>-.001?0:v;}; // S16 cur_obj_move_standard(-78), gravity 4, bounciness -0.7 + const vx=drag(Math.sin(b.yaw)*b.fwd),vz=drag(Math.cos(b.yaw)*b.fwd),nx=b.x+vx,nz=b.z+vz; + if(!(this.bowserFloor(nx,nz)-flr<-50&&b.onGround)){b.x=nx;b.z=nz;} + b.vy=Math.max(-78,b.vy-4);b.y+=b.vy; + if(b.y45&&f<85&&!(f&1)){const [y,z,yaw,p]=BOWSER.flames[(f-46)/2];b.flames.push({x:b.x+z*Math.sin(b.yaw)+N.rand(this)*80-40,y:b.y+y,z:b.z+z*Math.cos(b.yaw)+N.rand(this)*80-40,yaw:wrap(b.yaw+yaw*S16),p:p+0xc00,s:3});}} + if(b.guard>0){if(b.act!=='hitmine')b.guard--;} + else if(b.tail===0){const dx=m.x-(b.x-Math.sin(b.yaw)*BOWSER.tailBack),dz=m.z-(b.z-Math.cos(b.yaw)*BOWSER.tailBack),ay=b.y+BOWSER.tailY; // S50 tail anchor: r100 h50, 50 up + if(Math.hypot(dx,dz)<100+C.radius&&m.y30)b.tail=0;} + if(b.op!==b.opGoal)b.op=b.opGoal>b.op?Math.min(255,b.op+20):Math.max(0,b.op-20); + {const L=BOWSER.anim[b.anim];b.af=b.anim===9?Math.min(L-1,b.af+1):(b.af+1)%L;} + b.timer++; + } + bowserUpdate(){const b=this.boss,m=this.mario;if(this.t%K===0)this.bowserFrame();if(this.outcome)return; + if(b.held){b.x=m.x+Math.sin(m.yaw)*BOWSER.holdF;b.z=m.z+Math.cos(m.yaw)*BOWSER.holdF;b.y=m.y+BOWSER.holdY;b.yaw=m.yaw;}} + // ---------------- tick ---------------- + update(keys,pressed,mouse){if(this.outcome)return; + this.camera(pressed,mouse);const inp=this.readInput(keys,pressed),m=this.mario,b=this.boss; + if(b.kind==='king'&&b.act===3&&b.sub===1&&m.action==='grabbed')b.escape+=this.escapeActions(inp); + this.marioUpdate(inp);if(this.outcome){this.lastKeys=[...keys].sort();return;} + if(b.kind==='whomp')this.whompUpdate();else if(b.kind==='king')this.kingUpdate();else if(b.kind==='eyerok')this.eyerokUpdate(inp);else if(b.kind==='wiggler')this.wigglerUpdate(inp);else if(b.kind==='bowser')this.bowserUpdate();else this.bullyUpdate(); + if(b.kind==='whomp')this.whompSolid(); + if(m.onBoss&&!this.lying()&&b.kind!=='eyerok')m.onBoss=false; + if(m.onBoss&&b.kind==='whomp'&&!AIR.has(m.action)){const top=this.bossTop(m.x,m.z);if(top===null){this.leaveGround(inp);}else m.y=top;} + this.effects=this.effects.filter(fx=>--fx.life>0);this.lastKeys=[...keys].sort(); + } + health(){const m=this.mario,b=this.boss,hp=b.kind==='bully'?b.lives:b.hp,max=b.kind==='bully'?b.maxLives:b.maxHp; + return [Math.max(0,Math.floor(m.health/0x100)),8,this.outcome==='win'?0:Math.max(0,hp),max];} + } + M.Game=Game;M.SLAB=SLAB;M.KING=KING;M.BULLY=BULLY;M.HAND=HAND;M.EYEROK=EYEROK;M.BOWSER=BOWSER;M.wigFloor=wigFloor;M.wigCeil=wigCeil;M.helpers={fr,inc,ang,deg,wrap,hd,yawTo}; + + /* Standard scripted reference controller (bossbench scripted hook). Called once per 200 ms packet with the live game; + * it plans each of the six hold sets on a deep copy (two ticks each), may test candidate inputs on further copies, and + * returns only legal holds (<= 4 keys). Deterministic; never touches the live game or its RNG. Mouse stays 0: the + * Lakitu camera's own boss focus is enough, so the script steers with the 8 stick directions relative to cam.yaw. */ + function cloneGame(g){return Object.assign(Object.create(Game.prototype),N.copy(g));} + function simTick(h,keys,mouse=[0,0,0]){const prev=new Set(h.lastKeys);h.events=[];h.update(new Set(keys),new Set(keys.filter(k=>!prev.has(k))),mouse);N.quantize(h);h.t++;} + const STICK=[['W'],['W','A'],['A'],['S','A'],['S'],['S','D'],['D'],['W','D']]; + function stickTo(h,yaw){const r=wrap(yaw-h.cam.yaw),i=((Math.round(r/(PI/4))%8)+8)%8;return STICK[i];} + function toward(h,p){return stickTo(h,yawTo(h.mario,p));} + function tap(h,k){return h.lastKeys.includes(k)?[]:[k];} + // Run a candidate input sequence on a copy and report the first event of interest. + function probe(h,seq,ticks,watch){const s=cloneGame(h);for(let i=0;i!AIR.has(m.action)&&!['squished','grabbed','dead','kb'].includes(m.action); + const free=m=>['idle','walking','decel','braking','land','turnaround'].includes(m.action); + + function planWhomp(h){const m=h.mario,b=h.boss,T=h.T; + if(['squished','dead','kb','airkb'].includes(m.action))return []; + if(b.act==='intro'&&b.sub===0)return toward(h,b); // walk up to him to start the fight + const fx=Math.sin(b.yaw),fz=Math.cos(b.yaw),pt=(f,u)=>({x:b.x+f*fx-u*fz,z:b.z+f*fz+u*fx}),s=h.slabLocal(m.x,m.z); + const danger=s.f>SLAB.h0-C.radius-40&&s.f 377, or back to the gap at his feet. + const exits=[[s.f,SLAB.half+C.radius+60],[s.f,-SLAB.half-C.radius-60],[SLAB.h0-C.radius-35,s.u]].map(([f,u])=>pt(f,u)) + .filter(p=>h.inside(p.x,p.z,50)).map(p=>{const dy=Math.abs(wrap(yawTo(m,p)-m.yaw));return {p,cost:hd(m,p)*(1+(m.fwd>8?dy*.35:0))};}); + if(!exits.length)return toward(h,pt(s.f,0));exits.sort((a,c)=>a.cost-c.cost);return toward(h,exits[0].p); + } + if(b.act==='ground'&&b.sub===0){ + const target=pt(470,0); + if(m.action==='gp'||m.action==='gpLand')return []; + const onTop=m.onBoss&&grounded(m); + if(onTop)return m.action==='land'||m.action==='idle'||m.action==='walking'?tap(h,'Space'):[]; + if(AIR.has(m.action)){const over=s.f>SLAB.h0+30&&s.fSLAB.top+12&&m.action!=='gp')return [...toward(h,target).slice(0,2),...tap(h,'Shift')]; + return [...toward(h,target),'Space'];} + const edge=Math.max(SLAB.h0-s.f,s.f-SLAB.h1,Math.abs(s.u)-SLAB.half); + if(edge<130&&free(m))return [...toward(h,target),...tap(h,'Space')]; + return toward(h,target); + } + if(b.act==='ground'||b.act==='die'||b.act==='dead')return b.act==='ground'&&m.onBoss?toward(h,pt(SLAB.h1+260,0)):[]; + // Chase: stand in his trigger cone, about 30 degrees off his centre line, so the slam can be side-stepped. + const side=s.u>=0?1:-1,f0=Math.max(150,T.range*.78),want=pt(f0,side*f0*.55); + if(!h.inside(want.x,want.z,90)){const alt=pt(f0,-side*f0*.55);return hd(m,alt)>40?toward(h,alt):[];} + return hd(m,want)>45?toward(h,want):[]; + } + // Rim guard for the open summit: keep a 220-unit lookahead on the plateau, turning toward the centre when needed. + function rimSafe(h,yaw){const m=h.mario,ok=y=>h.inside(m.x+Math.sin(y)*220,m.z+Math.cos(y)*220,110);if(ok(yaw))return yaw; + for(const d of [.4,-.4,.8,-.8,1.2,-1.2,1.6,-1.6])if(ok(wrap(yaw+d)))return wrap(yaw+d);const c=h.arena.centre;return Math.atan2(c.x-m.x,c.z-m.z);} + function planKing(h){const keys=planKingRaw(h),m=h.mario;if(!keys.some(k=>'WASD'.includes(k))||!grounded(m))return keys; + const f=(keys.includes('W')?1:0)-(keys.includes('S')?1:0),sd=(keys.includes('D')?1:0)-(keys.includes('A')?1:0),a=h.cam.yaw; + const yaw=Math.atan2(Math.sin(a)*f-Math.cos(a)*sd,Math.cos(a)*f+Math.sin(a)*sd),safe=rimSafe(h,yaw); + return safe===yaw?keys:[...stickTo(h,safe),...keys.filter(k=>!'WASD'.includes(k))];} + function planKingRaw(h){const m=h.mario,k=h.boss,C0=h.arena.centre; + if(m.action==='grabbed')return h.lastKeys.includes('Space')?[]:['Space']; + if(['dead','kb','airkb','thrown','pickup','heavythrow'].includes(m.action))return []; + if(m.holding){ + // His flight is ~530 units straight ahead; aim at the summit centre unless a throw from here already lands well inside. + const land=y=>h.inside(m.x+Math.sin(y)*530,m.z+Math.cos(y)*530,250),goal=land(m.yaw)?m.yaw:Math.atan2(C0.x-m.x,C0.z-m.z); + if(Math.abs(wrap(goal-m.yaw))>.22)return stickTo(h,goal);return tap(h,'J');} + const d=hd(m,k),fx=Math.sin(k.yaw),fz=Math.cos(k.yaw),rel=wrap(yawTo(k,m)-k.yaw),centre=Math.atan2(C0.x-k.x,C0.z-k.z),kc=hd(k,C0); + if(k.act===0)return k.sub===0?toward(h,k):[]; // walk into his 500 talk radius, then wait out the speech + if(k.act!==2||!k.tangible){ // hurt, thrown, returning: keep clear, wait between him and the centre + const away=Math.atan2(m.x-k.x,m.z-k.z);if(d<420)return stickTo(h,away); + const spot={x:C0.x+(k.x-C0.x)*.4,z:C0.z+(k.z-C0.z)*.4};return hd(m,spot)>200&&d>500?toward(h,spot):[]; + } + // His own throw sends Mario toward world yaw 0 (+z): only lure him back toward the middle when a throw from where + // he stands would carry Mario (~900 units) past the summit's far edge. + if(!h.inside(k.x,k.z+900,0)&&kc>500){const lure={x:k.x+Math.sin(centre)*400,z:k.z+Math.cos(centre)*400}; + if(d<330)return stickTo(h,wrap(yawTo(k,m)+(wrap(yawTo(k,m)-centre)>0?-1:1)*(PI/2+.3)));return hd(m,lure)>60?toward(h,lure):[];} // around him, not away + const behind={x:k.x-fx*150,z:k.z-fz*150}; + // Inside his grab reach at 31 units/frame Mario cannot brake (a 16+ turnaround slides ~60): if he is turning toward + // Mario's side and Mario is not already behind him, cut speed by releasing the stick for this hold. + if(d<300&&Math.abs(rel)20&&m.action==='walking')return []; + if(Math.abs(rel)>deg(0x5800)&&d<190){ + if(Math.abs(wrap(yawTo(m,k)-m.yaw))>.35)return toward(h,k); + if(free(m)){const p=probe(h,(s,i)=>i<2?['J']:[],26,['grab_king','king_grabs_mario']);if(p.event==='grab_king')return tap(h,'J');} + return toward(h,k);} + // Orbit at radius ~330 (tangent plus a radial correction) until he is turned away, then close in from behind. + // Dead ahead of him, the orbit side is the one passing between him and the summit centre, so it never dithers. + if(Math.abs(rel)460){ + const out=yawTo(k,m),R=330,inner=wrap(out-centre)>0?-1:1; + // Tangent to the circle, turned inward when outside radius R (toward him) and outward when inside it. + const radial=N.clamp((d-R)/160,-1,1)*.9,cand=s=>wrap(out+s*(PI/2+radial)); + // Short way round to his back; dead ahead of him, keep the side Mario is already running toward (no dithering). + let sgn=Math.abs(rel)>.6?(rel>=0?1:-1):m.fwd>8?(Math.abs(wrap(cand(1)-m.yaw))60?toward(h,centre):[]; + // Hold the middle: he always charges at Mario, so from the centre every counter-punch (pushing along Mario's + // facing, S04) sends him outward, and a lost exchange (soft knockback ~300 units, S07) cannot reach the lava. + const punch=()=>{const p=probe(h,(s,i)=>i<2?[...stickTo(s,yawTo(s.mario,s.boss)),'J']:[],24,['bully_pushed','mario_bullied']);return p.event==='bully_pushed';}; + const ready=free(m)||m.action==='crouch',outward=Math.cos(wrap(toB-Math.atan2(b.x,b.z)))>.2||bc<150; + if(ready&&d<360&&(outward||b.act==='chase')&&punch())return [...stickTo(h,toB),...tap(h,'J')]; + // Follow him outward while he slides or recovers, up to a standing line ~250 inside the rim: from there the next + // counter-punch lands with him beyond Mario, so the push carries him over the edge. + const rad=Math.atan2(b.x,b.z);let follow={x:b.x-Math.sin(rad)*180,z:b.z-Math.cos(rad)*180}; + for(let i=0;i<60&&!h.inside(follow.x,follow.z,250);i++)follow={x:follow.x*.95,z:follow.z*.95}; + if(b.act==='knockback'&&outward)return hd(m,follow)>40?toward(h,follow):stickTo(h,toB).slice(0,1); + if(b.act==='chase'&&d<700){if(!h.inside(m.x,m.z,210))return toward(h,centre);return Math.abs(wrap(toB-m.yaw))>.5&&m.action!=='idle'?stickTo(h,toB):[];} + const home={x:Math.sin(rad)*120,z:Math.cos(rad)*120}; + return hd(m,home)>60?toward(h,home):(Math.abs(wrap(toB-m.yaw))>.5?stickTo(h,toB):[]); + } + // Eyerok: goal selection plus a safety filter. Every candidate stick is played out on a copy whose RNG was replaced in M.scripted by + // planRng (a hand's next attack is not decided yet, so the planner must not see it); already-decided state (which hand is open, a hand + // hovering overhead) is fair to read. + function eyeSafe(h,keys,ticks,hold=ticks){const s=cloneGame(h);for(let i=0;i=30&&!hit)return false;} + return hit;} + function eyeSteer(h,yaw,extra=[],dist=Infinity){const H=56,run=Math.min(H,Math.ceil(dist/12)+4);let best=null,bestT=-1; + const offs=[0,.785,-.785,1.571,-1.571,2.356,-2.356,3.142]; + for(const o of offs){const keys=stickTo(h,wrap(yaw+o)),t=eyeSafe(h,keys,H,o===0?run:H);if(t>=H)return [...keys,...extra];if(t>bestT){bestT=t;best=keys;}} + const t0=eyeSafe(h,[],H);return t0>bestT?[]:[...best,...extra];} + function planEyerok(h){const m=h.mario,b=h.boss; + if(['squished','dead','kb','airkb','gpLand','punching','movepunch','divestop','diveslide'].includes(m.action))return []; + if(AIR.has(m.action))return []; + const brake=p=>m.fwd>16&&hd(m,p)=56; + const go=(p,near=30)=>brake(p)?[]:hd(m,p)>near?eyeSteer(h,yawTo(m,p),[],hd(m,p)):(eyeSafe(h,[],56)>=56?[]:eyeSteer(h,yawTo(m,{x:0,z:700}))); + if(b.act==='sleep')return toward(h,{x:0,z:0}); + if(b.act!=='fight')return go({x:m.x,z:Math.max(m.z,650)}); + // Double pound: leave the band the hands walk along (zt, footprint -201..220 plus Mario's wall radius and a margin). + if(b.pound>1){const lo=b.zt-320,hi=b.zt+340;return go({x:N.clamp(m.x,-500,500),z:lo>=450?Math.min(m.z,lo):Math.max(m.z,hi)});} + // The hand that is opening or open is already decided (b.eyeHand): wait in front of its eye, inside punch reach. + const over=b.hands.find(q=>!q.gone&&!q.open&&q.y>40&&h.handOverPoint(q,m.x,m.z)&&['target','smash','begin','pound'].includes(q.act)); + if(over){const B=HAND.fist,l=h.handLocal(over,m.x,m.z),out=[{x:B.x0-90,z:l.z},{x:B.x1+90,z:l.z},{x:l.x,z:B.z1+90},{x:l.x,z:B.z0-90}].map(p=>h.handWorld(over,p.x,p.z)).filter(p=>h.inside(p.x,p.z,120)&&p.z>=420); + if(out.length){out.sort((p,q)=>hd(m,p)-hd(m,q));return toward(h,out[0]);}} + const eye=b.hands.find(q=>!q.gone&&(q.act==='eye'||q.act==='open')); + if(eye){const toE=yawTo(m,eye),d=hd(m,eye),solo=b.handsLeft!==2; + if(eye.act==='eye'&&d<(solo?760:400)&&(free(m)||m.action==='crouch')){if(eyeStrike(h,eye))return [...stickTo(h,toE),...tap(h,'J')];} + if(solo){ // the last hand rushes faster than Mario runs and only an attack facing it lands: wait turned toward it, never run ahead of it + const face=Math.abs(wrap(toE-m.yaw))<.5?[]:stickTo(h,toE); + if(eye.act==='eye'&&eye.fwd>0&&m.z>eye.z)return face; + if(eye.act==='eye')return go({x:eye.x,z:Math.min(1600,eye.z+190)},24); + const spot={x:N.clamp(eye.homeX*.6,-500,500),z:860};return hd(m,spot)>40?go(spot,40):face;} + const clear=p=>h.inside(p.x,p.z,120)&&!b.hands.some(q=>q!==eye&&!q.gone&&[[0,0],[60,0],[-60,0],[0,60],[0,-60]].some(([a,c])=>h.handOverPoint(q,p.x+a,p.z+c))); + const spots=[{x:eye.x,z:Math.max(450,eye.z+190)},{x:eye.x-150,z:Math.max(430,eye.z+130)},{x:eye.x+150,z:Math.max(430,eye.z+130)}].filter(clear).sort((p,q)=>hd(m,p)-hd(m,q)); + return go(clear({x:eye.x,z:Math.max(450,eye.z+190)})?{x:eye.x,z:Math.max(450,eye.z+190)}:spots[0]||{x:0,z:700},24);} + // Nothing to hit yet: wait in front of the hand that is due to open next (the attacker alternates by b.fc, S35). + const next=b.handsLeft===2?(b.fc+1)&1?-1:1:0,alive=b.hands.find(q=>!q.gone); + return b.handsLeft===2?go({x:-500*next*.55,z:640}):go({x:N.clamp(alive.homeX*.6,-500,500),z:860},40); + } + // Wiggler: wait out his invulnerable 60 frames at a distance, then jump onto his head. Every committed jump and every step is played out on a copy + // whose RNG is planRng (his wander is not decided yet); his state, including the walk timer, is already decided and fair to read. + function wigSafe(h,keys,ticks){const s=cloneGame(h);for(let i=0;i=H)return keys;if(t>bestT){bestT=t;best=keys;}} + return best;} + function wigStrike(h){const p=probe(h,(s,i)=>[...toward(s,s.boss),...(i<30?['Space']:[])],70,['wiggler_stomped','mario_hurt']);return p.event==='wiggler_stomped';} + function planWiggler(h){const m=h.mario,b=h.boss,c=h.arena.centre,d=hd(m,b); + if(['squished','dead','kb','airkb','gpLand','punching','movepunch','divestop','diveslide'].includes(m.action))return []; + const soon=b.act==='walk'&&b.intro===0&&b.timer>=38; + if(AIR.has(m.action)){const rising=m.vy>0&&m.ctrlJump?['Space']:[]; + return soon?[...toward(h,b),...rising]:[...stickTo(h,yawTo(b,m)),...rising];} + if(soon&&free(m)&&d<700&&!h.lastKeys.includes('Space')&&wigStrike(h))return [...toward(h,b),'Space']; + if(soon&&d>360)return wigSteer(h,yawTo(m,b)); + // Otherwise stay out of his reach, turning toward the middle of the room as a wall comes up; he keeps chasing, so this is a slow circle. + const away=yawTo(b,m),ahead={x:m.x+Math.sin(away)*420,z:m.z+Math.cos(away)*420}; + if(d>620&&!soon)return Math.abs(wrap(yawTo(m,b)-m.yaw))>.5&&m.fwd<4?stickTo(h,yawTo(m,b)).slice(0,2):[]; + if(h.inside(ahead.x,ahead.z,120))return wigSteer(h,away); + const side=wrap(yawTo(m,c)-away)>=0?1:-1;return wigSteer(h,wrap(away+side*1.2)); + } + // Bowser: run round to his tail while he breathes or turns, punch, spin at the full rate, let go the moment a copy says the throw reaches a mine. Copies use planRng: flames not yet + // breathed and his next action are not decided; flames in the air, a jump in progress and the mines are. + function bowSafe(h,keys,ticks){const s=cloneGame(h);for(let i=0;i=H)return keys;if(t>bestT){bestT=t;best=keys;}} + return best;} + function bowSpin(h){const m=h.mario,b=h.boss,keys=stickTo(h,m.arg===0?m.yaw:wrap(m.twirl+PI/2)); + if(Math.abs(m.swing)>=0x800&&probe(h,(s,i)=>i===0?['J']:[],110,['mine_explodes']).event)return [...keys,'J']; + // At full spin the 16 headings repeat, so a mine at the edge of the range can stay out of reach for good: after about two turns throw him toward the nearest live mine and grab him closer to it. + if(b.heldT>52&&Math.abs(m.swing)>=0xf11){const live=b.mines.filter(q=>q.alive).sort((p,q)=>hd(m,p)-hd(m,q));if(!live.length||Math.abs(wrap(yawTo(m,live[0])-m.yaw))<.25)return [...keys,'J'];} + return keys;} + // Where a Bowser in flight comes down: his path is already decided (no draw until he has landed), so a copy can follow it. + function bowLanding(h){const s=cloneGame(h);for(let i=0;i<220&&!s.outcome;i++){simTick(s,[]);const b=s.boss;if(b.onGround&&!b.landed&&b.fwd===0)return b;}return s.boss;} + function planBowser(h){const m=h.mario,b=h.boss,c=h.arena.centre,d=hd(m,b); + if(m.action==='swing')return bowSpin(h); + if(m.action==='burnground')return bowSteer(h,yawTo(m,c)); + if(AIR.has(m.action))return m.vy>0&&m.ctrlJump?['Space']:[]; + if(['dead','kb','grabbowser','release','shockwave','punching','movepunch','divestop','diveslide','gpLand'].includes(m.action)||b.act==='dead')return []; + // The landing shakes the whole arena: be in the air on that frame (a jump lasts 42 ticks). + if(free(m)&&!h.lastKeys.includes('Space')&&(b.act==='quickjump'||b.act==='jumpstage')){const p=probe(h,()=>[],30,['bowser_land']);if(p.event)return ['Space'];} + // Flying (thrown, or off a mine): he lands facing the way he faces now, so wait where his tail will be. + if(b.act==='hitmine'||(b.act==='thrown'&&b.sub===0)){const L=bowLanding(h),p={x:L.x-Math.sin(L.yaw)*250,z:L.z-Math.cos(L.yaw)*250},q=h.inside(p.x,p.z,170)?p:c;return hd(m,q)>70?bowSteer(h,yawTo(m,q)):[];} + // Guarded: wait in front at breath range so that he stops to attack; go round him only as the guard runs out, or once he has begun a breath. + if(b.guard>45&&b.act!=='breath'){const out=yawTo(b,m),p={x:b.x+Math.sin(out)*1300,z:b.z+Math.cos(out)*1300},q=h.inside(p.x,p.z,250)?p:c;return hd(m,q)>120?bowSteer(h,yawTo(m,q)):[];} + if(free(m)&&d<430&&b.tail!==1&&Math.abs(wrap(m.yaw-b.yaw))<1.9){const p=probe(h,(s,i)=>i<2?['J']:[],24,['grab_bowser','mario_hurt']);if(p.event==='grab_bowser')return tap(h,'J');} + const fx=Math.sin(b.yaw),fz=Math.cos(b.yaw),back={x:b.x-fx*250,z:b.z-fz*250}; + if(!h.inside(back.x,back.z,170))return d>700?bowSteer(h,yawTo(m,b)):bowSteer(h,yawTo(m,c)); // his back is over the edge: draw him inward + const out=yawTo(b,m),rel=wrap(out-b.yaw),toBack=wrap(b.yaw+PI-out); + if(Math.abs(toBack)<.5)return bowSteer(h,yawTo(m,back)); + // Round him: tight while he walks (he turns as fast as Mario circles at about 330, and only stands still to breathe); wide of the flames once a breath has begun in front of him. + const R=b.act==='breath'&&Math.abs(rel)<1.3?560:330; + // Keep the way round Mario is already running; a change of mind at speed costs a turnaround. + const way=sg=>{const a=wrap(out+sg*Math.min(1.1,Math.abs(sg>0?wrap(toBack+PI*2)%(PI*2)||0:toBack)+.2));return {x:b.x+Math.sin(a)*R,z:b.z+Math.cos(a)*R};}; + const pS=toBack>=0?1:-1,head=sg=>Math.abs(wrap(yawTo(m,way(sg))-m.yaw)); + let sg=m.fwd>12&&Math.abs(toBack)<2.6?(head(1)>>0;x=Math.imul(x^(x>>>16),0x85ebca6b)>>>0;x=Math.imul(x^(x>>>13),0xc2b2ae35)>>>0;return (x^(x>>>16))>>>0||1;} + M.helpers.planRng=planRng; + M.scripted=function(game){const h=cloneGame(game),holds=[];if(h.boss.kind==='eyerok'||h.boss.kind==='wiggler'||h.boss.kind==='bowser')h.rng=planRng(h.rng); + for(let j=0;j<6;j++){const keys=plan(h);holds.push(keys);for(let n=0;n<2&&!h.outcome;n++)simTick(h,keys);} + return {holds,mouse:[0,0,0]};}; + M.oracle=M.scripted; // legacy tool name + // Which stretch of the difficulty table d falls in (a pure function of d): the tuning slope changes at the three tiers. + M.difficultyBand=d=>d===0?'1996':d<=.2?'1996-easy':d<=.5?'easy-normal':d<=.8?'normal-hard':'beyond-hard'; +})(typeof window==='undefined'?globalThis:window); diff --git a/environments/games/web/games/mario64_remake/index.html b/environments/games/web/games/mario64_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..0dc051d755ff10a535140321452d6828d0c35f76 --- /dev/null +++ b/environments/games/web/games/mario64_remake/index.html @@ -0,0 +1,7 @@ +Super Mario 64 · Boss Challenges
+
Super Mario 64 · 1996 · Boss Trials

Super Mario 64 · Boss Challenges

Face Whomp King, King Bob-omb, Big Bully, Eyerok, Wiggler, and Bowser. Triple jump, ground pound, grab and throw, knock foes into lava, strike exposed palms, stomp heads, and swing Bowser into mines. Mechanics follow the public SM64 decompilation; the low-poly art is original.

Back to Game Lobby ↗
+
Are You Ready?Click Start Challenge
+

The scripted demo reads internal state to verify each fight can be completed. Replays save real inputs, reproduce the entire fight, and verify the final state.

+
+
+ diff --git a/environments/games/web/games/mario64_remake/manifest.json b/environments/games/web/games/mario64_remake/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..8781f4ca00acba32436beb9ac09e226c2ee2200a --- /dev/null +++ b/environments/games/web/games/mario64_remake/manifest.json @@ -0,0 +1,34 @@ +{ + "schema": "bossbench/game-manifest@1", + "engine": "independent", + "game": "mario64_remake", + "module": "Mario64Game", + "title": "Super Mario 64: Boss Challenges", + "dimension": "3d", + "native_hz": 60, + "max_seconds": 300, + "renderer": "webgl-mario64", + "rules": "sm64-bosses@5", + "cases": [ + "mario64/whomp_king", + "mario64/king_bobomb", + "mario64/big_bully", + "mario64/eyerok", + "mario64/wiggler", + "mario64/bowser_dark_world" + ], + "scripts": [ + "_native/runtime.js", + "_boss3d/vendor/three.min.js", + "mario64_remake/renderer3d.js", + "mario64_remake/game.js", + "mario64_remake/draw.js" + ], + "sim_scripts": [ + "_native/runtime.js", + "mario64_remake/game.js" + ], + "play_page": "web/games/mario64_remake/index.html", + "original_clock": "SM64 logic runs at 30 Hz (n64decomp/sm64 src/game/hud.c: 30 frames per second); this port runs 60 Hz, two ticks per original frame", + "scripted_controller": "Mario64Game.scripted(game) -> {holds:[6 key arrays], mouse:[0,0,0]} (plans on deep copies, deterministic; .oracle is an alias)" +} diff --git a/environments/games/web/games/mario64_remake/renderer3d.js b/environments/games/web/games/mario64_remake/renderer3d.js new file mode 100644 index 0000000000000000000000000000000000000000..387405b8cc7bb5631b11b2e4ad2e5770f9d3fdd3 --- /dev/null +++ b/environments/games/web/games/mario64_remake/renderer3d.js @@ -0,0 +1,387 @@ +/* Original low-poly, N64-flavoured art for the Super Mario 64 boss trials. Three.js 0.160.1 is the vendored shared copy + * (MIT, web/games/_boss3d/vendor, read-only). Every mesh and texture below is built procedurally in this file; no + * Nintendo model, texture or sound is used (ASSET_RIGHTS.md). Rendering only reads game state: the Lakitu camera, + * every pose clock and every effect come from the simulation, so a frame is a pure function of the state. */ +(function(root){ + 'use strict'; + const T=root.THREE,R=root.Mario3D={}; + if(!T)throw Error('Offline Three.js renderer library is missing'); + const U=.01,byCanvas=new WeakMap(),clamp=(x,a,b)=>Math.max(a,Math.min(b,x)),items=a=>Array.isArray(a)?a:[],PI=Math.PI; + function hash(x,y,s){let n=Math.imul(x*73856093^y*19349663^s*83492791,1274126177);n^=n>>>15;n=Math.imul(n,2246822519);return ((n^(n>>>13))>>>0)/4294967295;} + function canvasTex(w,h,draw,repeat){const c=document.createElement('canvas');c.width=w;c.height=h;draw(c.getContext('2d'),w,h); + const t=new T.CanvasTexture(c);t.colorSpace=T.SRGBColorSpace;if(repeat){t.wrapS=t.wrapT=T.RepeatWrapping;t.repeat.set(repeat[0],repeat[1]);}return t;} + const rgb=(r,g,b)=>`rgb(${r|0},${g|0},${b|0})`; + // Stone tiles: blocks with per-block brightness and a mortar line (Whomp's Fortress, the Bully platform). + function tiles(q,w,h,base,mortar,cols,rows,seed,offset=true){q.fillStyle=mortar;q.fillRect(0,0,w,h);const bw=w/cols,bh=h/rows; + for(let j=0;jcanvasTex(256,256,(q,w,h)=>{tiles(q,w,h,[206,190,160],'#8e806a',4,8,3);speckle(q,w,h,700,4,'rgba(80,60,40,.18)','rgba(255,255,240,.16)');},[9,9]), + wall:()=>canvasTex(256,256,(q,w,h)=>{tiles(q,w,h,[176,160,132],'#776a57',4,8,9);speckle(q,w,h,500,5,'rgba(60,50,40,.2)','rgba(255,250,230,.1)');},[9,4]), + grass:()=>canvasTex(256,256,(q,w,h)=>{q.fillStyle='#4f9a33';q.fillRect(0,0,w,h);speckle(q,w,h,2600,7,'#3f8628','#69b443'); + for(let i=0;i<220;i++){const x=hash(i,8,7)*w,y=hash(i,9,7)*h;q.strokeStyle=hash(i,10,7)<.5?'#2f6e1f':'#7cc452';q.beginPath();q.moveTo(x,y);q.lineTo(x+2-hash(i,11,7)*4,y-4-hash(i,12,7)*5);q.stroke();}},[14,14]), + slope:()=>canvasTex(128,256,(q,w,h)=>{const g=q.createLinearGradient(0,0,0,h);g.addColorStop(0,'#4c8e31');g.addColorStop(.35,'#6f6a3c');g.addColorStop(1,'#5b4b33');q.fillStyle=g;q.fillRect(0,0,w,h); + speckle(q,w,h,1400,13,'rgba(40,30,20,.25)','rgba(255,240,200,.12)');for(let y=30;ycanvasTex(256,256,(q,w,h)=>{tiles(q,w,h,[132,124,118],'#3e3533',4,4,21,false); + q.strokeStyle='rgba(30,24,22,.55)';q.lineWidth=3;for(let i=0;i<=4;i++){q.beginPath();q.moveTo(i*w/4,0);q.lineTo(i*w/4,h);q.stroke();q.beginPath();q.moveTo(0,i*h/4);q.lineTo(w,i*h/4);q.stroke();} + for(let i=0;i<4;i++)for(let j=0;j<4;j++){q.fillStyle='#d9cfc3';q.beginPath();q.arc(i*w/4+10,j*h/4+10,3,0,PI*2);q.fill();}},[6,6]), + lava:()=>canvasTex(256,256,(q,w,h)=>{q.fillStyle='#a3200c';q.fillRect(0,0,w,h); + for(let i=0;i<150;i++){const x=hash(i,1,31)*w,y=hash(i,2,31)*h,r=4+hash(i,3,31)*18;const g=q.createRadialGradient(x,y,0,x,y,r);g.addColorStop(0,'rgba(255,214,90,.95)');g.addColorStop(.5,'rgba(255,120,30,.55)');g.addColorStop(1,'rgba(255,80,10,0)'); + for(const ox of [-w,0,w])for(const oy of [-h,0,h]){q.fillStyle=g;q.save();q.translate(ox,oy);q.beginPath();q.arc(x,y,r,0,PI*2);q.fill();q.restore();}} + speckle(q,w,h,600,33,'rgba(80,10,0,.35)','rgba(255,240,150,.25)');},[24,24]), + sand:()=>canvasTex(256,256,(q,w,h)=>{tiles(q,w,h,[214,178,112],'#9a7a48',4,4,71);speckle(q,w,h,1200,72,'rgba(90,60,20,.2)','rgba(255,240,190,.18)');},[8,8]), + stone:()=>canvasTex(128,128,(q,w,h)=>{q.fillStyle='#a9a8a2';q.fillRect(0,0,w,h);speckle(q,w,h,900,41,'rgba(70,70,70,.28)','rgba(255,255,255,.18)'); + q.strokeStyle='rgba(60,60,60,.35)';for(let i=0;i<5;i++){q.beginPath();const x=hash(i,1,42)*w,y=hash(i,2,42)*h;q.moveTo(x,y);q.lineTo(x+10-hash(i,3,42)*20,y+12);q.lineTo(x+18-hash(i,4,42)*30,y+26);q.stroke();}},[1,1]), + face:()=>canvasTex(256,320,(q,w,h)=>{q.fillStyle='#b3b1aa';q.fillRect(0,0,w,h);speckle(q,w,h,1500,51,'rgba(70,70,70,.25)','rgba(255,255,255,.16)'); + for(const s of [-1,1]){const cx=w/2+s*58,cy=88;q.fillStyle='#fafaf2';q.beginPath();q.ellipse(cx,cy,34,40,0,0,PI*2);q.fill();q.strokeStyle='#2c2b2a';q.lineWidth=5;q.stroke(); + q.fillStyle='#1d1c1c';q.beginPath();q.ellipse(cx-s*6,cy+6,13,18,0,0,PI*2);q.fill();q.fillStyle='#fff';q.fillRect(cx-s*6-4,cy-4,5,6); + q.fillStyle='#3d3b39';q.beginPath();q.moveTo(cx-s*46,cy-50);q.lineTo(cx+s*40,cy-30);q.lineTo(cx+s*38,cy-18);q.lineTo(cx-s*46,cy-36);q.closePath();q.fill();} + q.fillStyle='#3a2a26';q.beginPath();q.moveTo(w/2-60,182);q.quadraticCurveTo(w/2,158,w/2+60,182);q.lineTo(w/2+52,202);q.quadraticCurveTo(w/2,186,w/2-52,202);q.closePath();q.fill(); + q.fillStyle='#ebe6da';for(let i=0;i<5;i++)q.fillRect(w/2-44+i*19,180,13,9); + q.strokeStyle='rgba(50,50,50,.45)';q.lineWidth=3;q.strokeRect(10,10,w-20,h-20);}), + back:()=>canvasTex(256,320,(q,w,h)=>{q.fillStyle='#a7a59e';q.fillRect(0,0,w,h);speckle(q,w,h,1500,61,'rgba(70,70,70,.25)','rgba(255,255,255,.16)'); + q.save();q.translate(w/2,h*.46);for(const a of [-.62,.62]){q.save();q.rotate(a);q.fillStyle='#efe6cf';q.fillRect(-26,-128,52,256);q.fillStyle='rgba(150,130,100,.5)';for(let y=-120;y<128;y+=22)q.fillRect(-26,y,52,3);q.restore();}q.restore(); + q.strokeStyle='rgba(50,50,50,.45)';q.lineWidth=3;q.strokeRect(10,10,w-20,h-20);}), + blob:()=>canvasTex(64,64,(q,w,h)=>{const g=q.createRadialGradient(32,32,2,32,32,31);g.addColorStop(0,'rgba(0,0,0,.62)');g.addColorStop(.7,'rgba(0,0,0,.42)');g.addColorStop(1,'rgba(0,0,0,0)');q.fillStyle=g;q.fillRect(0,0,w,h);}), + cloud:()=>canvasTex(128,64,(q,w,h)=>{for(const [x,y,r] of [[40,38,24],[64,30,28],[90,38,22],[60,44,22]]){const g=q.createRadialGradient(x,y,2,x,y,r);g.addColorStop(0,'rgba(255,255,255,.95)');g.addColorStop(1,'rgba(255,255,255,0)');q.fillStyle=g;q.beginPath();q.arc(x,y,r,0,PI*2);q.fill();}}), + sky:(top,mid,bottom)=>canvasTex(16,256,(q,w,h)=>{const g=q.createLinearGradient(0,0,0,h);g.addColorStop(0,top);g.addColorStop(.55,mid);g.addColorStop(1,bottom);q.fillStyle=g;q.fillRect(0,0,w,h);}) + }; + const COL={red:0xd8262b,blue:0x2a4ed0,skin:0xffc9a0,white:0xf4f4f0,brown:0x7a4422,hair:0x3a2414,yellow:0xf2c230,gold:0xe2aa2a,black:0x1d1e24,stone:0xc9c7bf,iron:0x30333a,horn:0xf3eee0}; + class Scene{ + constructor(canvas){ + this.canvas=canvas;this.resources=new Set();this.times=[];this.ready=false;this.error=null;this.closed=false;this.kind=null; + this.view=document.createElement('canvas');this.view.width=854;this.view.height=480; + this.renderer=new T.WebGLRenderer({canvas:this.view,alpha:false,antialias:true,preserveDrawingBuffer:true,powerPreference:'low-power'}); + this.renderer.setPixelRatio(1);this.renderer.setSize(854,480,false);this.renderer.outputColorSpace=T.SRGBColorSpace; + this.renderer.toneMapping=T.ACESFilmicToneMapping;this.renderer.toneMappingExposure=1.08;this.renderer.info.autoReset=false; + this.view.addEventListener('webglcontextlost',e=>{e.preventDefault();this.ready=false;this.error='WebGL context lost';}); + this.world=new T.Scene();this.camera=new T.PerspectiveCamera(50,854/480,.1,420); + this.hemi=new T.HemisphereLight(0xdcefff,0x6a6250,2.1);this.world.add(this.hemi); + this.sun=new T.DirectionalLight(0xfff1d6,2.6);this.sun.position.set(-30,60,25);this.world.add(this.sun); + this.geo={box:this.keep(new T.BoxGeometry(1,1,1)),sphere:this.keep(new T.SphereGeometry(1,14,10)),half:this.keep(new T.SphereGeometry(1,14,6,0,PI*2,0,PI/2)), + cyl:this.keep(new T.CylinderGeometry(1,1,1,12)),cone:this.keep(new T.ConeGeometry(1,1,10)),disc:this.keep(new T.CircleGeometry(1,24)),ring:this.keep(new T.RingGeometry(.82,1,32)), + ico:this.keep(new T.IcosahedronGeometry(1,0)),oct:this.keep(new T.OctahedronGeometry(1,0)),plane:this.keep(new T.PlaneGeometry(1,1)),torus:this.keep(new T.TorusGeometry(1,.18,6,14))}; + const L=(c,o={})=>this.keep(new T.MeshLambertMaterial({color:c,flatShading:o.flat!==false,...o.extra})); + this.mat={red:L(COL.red),blue:L(COL.blue),skin:L(COL.skin),white:L(COL.white),brown:L(COL.brown),hair:L(COL.hair),yellow:L(COL.yellow), + gold:this.keep(new T.MeshStandardMaterial({color:COL.gold,roughness:.35,metalness:.75,flatShading:true})),black:this.keep(new T.MeshStandardMaterial({color:COL.black,roughness:.38,metalness:.25})), + iron:this.keep(new T.MeshStandardMaterial({color:COL.iron,roughness:.42,metalness:.65,flatShading:true})),horn:L(COL.horn),eye:L(0xffffff),pupil:L(0x101014),orange:L(0xf08a24), + stone:L(0xffffff,{extra:{map:this.keep(TEX.stone())}}),face:L(0xffffff,{flat:false,extra:{map:this.keep(TEX.face())}}),back:L(0xffffff,{flat:false,extra:{map:this.keep(TEX.back())}})}; + this.fxMat={dust:this.keep(new T.MeshLambertMaterial({color:0xe9e2d2,transparent:true,opacity:.8,depthWrite:false})),star:this.keep(new T.MeshBasicMaterial({color:0xffe24a})), + ring:this.keep(new T.MeshBasicMaterial({color:0xfff6d8,transparent:true,opacity:.55,side:T.DoubleSide,depthWrite:false})), + fire:this.keep(new T.MeshBasicMaterial({color:0xff7a1a,transparent:true,opacity:.85,depthWrite:false})),ember:this.keep(new T.MeshBasicMaterial({color:0xffb347}))}; + this.blobMat=this.keep(new T.MeshBasicMaterial({map:this.keep(TEX.blob()),transparent:true,depthWrite:false})); + this.slabShadowMat=this.keep(new T.MeshBasicMaterial({color:0x1a1410,transparent:true,opacity:.0,depthWrite:false})); + this.landMat=this.keep(new T.MeshBasicMaterial({color:0x7a1c10,transparent:true,opacity:0,depthWrite:false})); + this.arenas={};this.mario=this.buildMario();this.world.add(this.mario.root); + this.handShadowMat=this.keep(new T.MeshBasicMaterial({color:0x1a1008,transparent:true,opacity:.42,depthWrite:false})); + this.bosses={whomp:this.buildWhomp(),king:this.buildKing(),bully:this.buildBully(),eyerok:this.buildEyerok(),wiggler:this.buildWiggler(),bowser:this.buildBowser()};for(const b of Object.values(this.bosses)){b.root.visible=false;this.world.add(b.root);} + this.marioBlob=this.blob(.42);this.bossBlob=this.blob(1);this.slabShadow=new T.Mesh(this.geo.plane,this.slabShadowMat);this.slabShadow.rotation.x=-PI/2;this.world.add(this.slabShadow); + this.landZone=new T.Mesh(this.geo.plane,this.landMat);this.landZone.renderOrder=2;this.world.add(this.landZone); + this.pools={dust:this.pool(this.geo.ico,this.fxMat.dust,96),star:this.pool(this.geo.oct,this.fxMat.star,64),ring:this.pool(this.geo.ring,this.fxMat.ring,16),fire:this.pool(this.geo.ico,this.fxMat.fire,220),ember:this.pool(this.geo.box,this.fxMat.ember,48)}; + this.o=new T.Object3D(); + } + keep(x){this.resources.add(x);return x;} + mesh(geo,mat,parent,pos=[0,0,0],scale=[1,1,1],rot=[0,0,0]){const m=new T.Mesh(geo,mat);m.position.set(pos[0],pos[1],pos[2]);m.scale.set(scale[0],scale[1],scale[2]);m.rotation.set(rot[0],rot[1],rot[2]);parent.add(m);return m;} + group(parent,pos=[0,0,0]){const g=new T.Group();g.position.set(pos[0],pos[1],pos[2]);parent.add(g);return g;} + pool(geo,mat,n){const m=new T.InstancedMesh(geo,mat,n);m.count=0;m.frustumCulled=false;this.world.add(m);this.keep(m);return m;} + blob(r){const m=new T.Mesh(this.geo.disc,this.blobMat);m.rotation.x=-PI/2;m.scale.set(r,r,1);m.renderOrder=1;this.world.add(m);return m;} + // ---------------- characters (original low-poly designs) ---------------- + buildMario(){const M=this.mat,g=this.geo,root=new T.Group(),body=this.group(root,[0,.78,0]); + this.mesh(g.sphere,M.blue,body,[0,-.12,0],[.34,.30,.29]);this.mesh(g.sphere,M.red,body,[0,.12,0],[.31,.27,.26]); + for(const s of [-1,1]){this.mesh(g.box,M.blue,body,[s*.12,.13,.2],[.07,.26,.05]);this.mesh(g.sphere,M.yellow,body,[s*.12,.02,.25],[.045,.045,.03]);} + const head=this.group(body,[0,.48,0]);this.mesh(g.sphere,M.skin,head,[0,0,0],[.25,.24,.24]); + this.mesh(g.half,M.red,head,[0,.04,0],[.265,.2,.265]);this.mesh(g.cyl,M.red,head,[0,.05,.16],[.2,.025,.17]); + this.mesh(g.disc,M.white,head,[0,.14,.235],[.07,.07,1],[-.35,0,0]);this.mesh(g.box,M.red,head,[0,.14,.237],[.05,.05,.01],[-.35,0,0]); + this.mesh(g.sphere,M.skin,head,[0,-.02,.24],[.075,.07,.08]);this.mesh(g.box,M.hair,head,[0,-.09,.21],[.22,.05,.05]); + for(const s of [-1,1]){this.mesh(g.sphere,M.eye,head,[s*.075,.06,.2],[.05,.065,.03]);this.mesh(g.sphere,M.blue,head,[s*.07,.055,.225],[.025,.035,.012]); + this.mesh(g.box,M.hair,head,[s*.21,-.02,-.02],[.04,.12,.12]);this.mesh(g.sphere,M.skin,head,[s*.235,-.02,0],[.04,.06,.04]);} + const arms=[],legs=[]; + for(const s of [-1,1]){const sh=this.group(body,[s*.3,.24,0]);this.mesh(g.cyl,M.red,sh,[0,-.14,0],[.07,.28,.07]);const fore=this.group(sh,[0,-.28,0]); + this.mesh(g.cyl,M.red,fore,[0,-.08,0],[.06,.16,.06]);this.mesh(g.sphere,M.white,fore,[0,-.2,0],[.095,.09,.095]);arms.push({sh,fore}); + const hip=this.group(body,[s*.13,-.3,0]);this.mesh(g.cyl,M.blue,hip,[0,-.17,0],[.085,.34,.085]);const shin=this.group(hip,[0,-.32,0]); + this.mesh(g.sphere,M.brown,shin,[0,-.12,.05],[.1,.07,.16]);legs.push({hip,shin});} + return {root,body,head,arms,legs};} + buildWhomp(){const M=this.mat,g=this.geo,s=200*U*1,root=new T.Group(),tilt=this.group(root),slab=this.group(tilt); + // Collision box x -150..150, y 50..430, z -100..-3 at scale 2 (S11): 6 m wide, 1.0..8.6 m high, 1.94 m deep. + const W=6,H0=1,H1=8.6,D0=-2,D1=-.06,cy=(H0+H1)/2,cz=(D0+D1)/2; + this.mesh(g.box,[M.stone,M.stone,M.stone,M.stone,M.face,M.back],slab,[0,cy,cz],[W,H1-H0,D1-D0]); + this.mesh(g.box,M.stone,slab,[0,H1+.12,cz],[W*.92,.24,(D1-D0)*.9]); + const arms=[];for(const sd of [-1,1]){const sh=this.group(slab,[sd*(W/2+.15),5.6,cz]);this.mesh(g.box,M.stone,sh,[sd*.55,-1.2,0],[1.0,2.6,1.0]);this.mesh(g.box,M.stone,sh,[sd*.6,-2.75,.15],[1.2,.8,1.25]);arms.push(sh);} + const feet=[];for(const sd of [-1,1]){const f=this.group(root,[sd*1.6,0,cz+.5]);this.mesh(g.box,M.stone,f,[0,.45,0],[1.25,.9,1.6]);this.mesh(g.box,M.stone,f,[0,.18,.55],[1.35,.36,.9]);feet.push(f);} + return {root,tilt,slab,arms,feet,size:s};} + buildKing(){const M=this.mat,g=this.geo,root=new T.Group(),body=this.group(root,[0,1.32,0]); + this.mesh(g.sphere,M.black,body,[0,0,0],[1.16,1.12,1.16]); + for(const sd of [-1,1]){this.mesh(g.sphere,M.eye,body,[sd*.34,.25,.98],[.25,.36,.15]);this.mesh(g.sphere,M.pupil,body,[sd*.32,.22,1.1],[.1,.17,.06]); + this.mesh(g.sphere,M.white,body,[sd*.33,-.26,1.04],[.42,.15,.16],[0,0,sd*.25]);} + const crown=this.group(body,[0,1.02,0]);this.mesh(g.cyl,M.gold,crown,[0,0,0],[.62,.42,.62]); + for(let i=0;i<6;i++){const a=i*PI/3;this.mesh(g.cone,M.gold,crown,[Math.sin(a)*.5,.36,Math.cos(a)*.5],[.17,.38,.17]);this.mesh(g.sphere,M.red,crown,[Math.sin(a)*.62,.02,Math.cos(a)*.62],[.07,.07,.07]);} + const key=this.group(body,[0,.15,-1.12]);this.mesh(g.cyl,M.gold,key,[0,0,-.18],[.08,.36,.08],[PI/2,0,0]);for(const sd of [-1,1])this.mesh(g.torus,M.gold,key,[sd*.26,0,-.42],[.28,.28,.28],[0,PI/2,0]); + const arms=[];for(const sd of [-1,1]){const sh=this.group(body,[sd*1.08,.05,.1]);this.mesh(g.cyl,M.black,sh,[sd*.25,0,0],[.12,.5,.12],[0,0,PI/2]);this.mesh(g.sphere,M.white,sh,[sd*.6,0,0],[.26,.26,.26]);arms.push(sh);} + const feet=[];for(const sd of [-1,1]){const f=this.group(root,[sd*.55,0,.1]);this.mesh(g.sphere,M.orange,f,[0,.18,.15],[.36,.2,.5]);feet.push(f);} + return {root,body,arms,feet,key};} + buildBully(){const M=this.mat,g=this.geo,root=new T.Group(),body=this.group(root,[0,1.18,0]); + this.mesh(g.sphere,M.iron,body,[0,0,0],[1.15,1.15,1.15]); + for(const sd of [-1,1]){const h=this.mesh(g.cone,M.horn,body,[sd*.62,.92,.05],[.2,.75,.2],[0,0,-sd*.6]); + this.mesh(g.sphere,M.eye,body,[sd*.32,.22,1.0],[.22,.27,.12]);this.mesh(g.sphere,M.pupil,body,[sd*.3,.2,1.09],[.1,.14,.05]); + this.mesh(g.box,M.black,body,[sd*.32,.52,.98],[.34,.08,.08],[0,0,sd*.35]);} + const feet=[];for(const sd of [-1,1]){const f=this.group(root,[sd*.5,0,.05]);this.mesh(g.sphere,M.black,f,[0,.16,.2],[.32,.18,.46]);feet.push(f);} + return {root,body,feet};} + // ---------------- arenas ---------------- + // Extruded outline (local world units): top face at y0, walls down by depth; [top, side] materials. + prism(poly,depth,top,side,y0=0){const s=new T.Shape();poly.forEach(([x,z],i)=>i?s.lineTo(x*U,z*U):s.moveTo(x*U,z*U)); + const m=new T.Mesh(this.keep(new T.ExtrudeGeometry(s,{depth:depth*U,bevelEnabled:false,curveSegments:1})),[top,side]);m.rotation.x=PI/2;m.position.y=y0*U;return m;} + tex(make,rep){const t=this.keep(make());t.repeat.set(rep,rep);return t;} + // Arenas follow the measured outlines (game.js ARENA: decomp collision of WF / BOB / LLL). Beyond each edge a ledge + // is drawn at that edge's measured drop, so a fall looks like the floor the simulation lands Mario on. + // Eyerok's two stone hands. The fist and palm blocks use the measured collision boxes (S36 x 1.5), so what is drawn is what + // squishes or blocks Mario; the model is unmirrored for the same reason. Each hand throws a footprint shadow on the floor. + buildEyerok(){const M=this.mat,g=this.geo,root=new T.Group(),sand=this.keep(new T.MeshLambertMaterial({color:0xb4764a,flatShading:true})),dark=this.keep(new T.MeshLambertMaterial({color:0x7c4a2c,flatShading:true})); + const lid=this.keep(new T.MeshLambertMaterial({color:0x96603a,flatShading:true})),iris=this.keep(new T.MeshLambertMaterial({color:0xd8362a})); + const hands=[];for(const side of [-1,1]){const h=this.group(root); + const fist=this.group(h);this.mesh(g.box,sand,fist,[-.1425,1.5525,.0975],[2.325,3.015,4.215]); + for(let i=0;i<4;i++)this.mesh(g.box,dark,fist,[-1.0+i*.58,2.85,2.05],[.5,.72,.46]); + this.mesh(g.box,dark,fist,[-.1425,.28,-1.75],[2.45,.56,.8]); + const palm=this.group(h);this.mesh(g.box,sand,palm,[.3825,2.535,0],[3.825,5.07,1.53]); + for(let i=0;i<4;i++)this.mesh(g.box,dark,palm,[-1.1+i*.98,5.45,0],[.72,.9,1.16]); + this.mesh(g.box,dark,palm,[.3825,.22,0],[3.95,.44,1.7]); + const eye=this.group(palm,[.3825,2.6,.77]);this.mesh(g.sphere,M.eye,eye,[0,0,0],[1.05,1.05,.22]);const pupil=this.group(eye); + this.mesh(g.sphere,iris,pupil,[0,0,.16],[.5,.5,.12]);this.mesh(g.sphere,M.pupil,pupil,[0,0,.25],[.24,.24,.06]); + const upper=this.mesh(g.box,lid,eye,[0,.55,.27],[2.3,1.1,.16]),lower=this.mesh(g.box,lid,eye,[0,-.55,.27],[2.3,1.1,.16]); + const shadow=new T.Mesh(g.plane,this.handShadowMat);shadow.rotation.x=-PI/2;shadow.renderOrder=1;root.add(shadow); + hands.push({h,fist,palm,eye,pupil,upper,lower,shadow,side});} + return {root,hands};} + // Wiggler: a yellow caterpillar with a flower on his head; his eyes and mouth turn angry after the first stomp, as the walking speed rises (S40). + buildWiggler(){const M=this.mat,g=this.geo,root=new T.Group(),L=c=>this.keep(new T.MeshLambertMaterial({color:c})),body=L(0xf2c230),belly=L(0xf7dd7a),foot=L(0xe8872a),petal=L(0xf0568c),stem=L(0x3f9a3a),angry=L(0xe8562a); + const head=this.group(root),hb=this.group(head);this.mesh(g.sphere,body,hb,[0,1.0,0],[1.2,1.0,1.2]);this.mesh(g.sphere,belly,hb,[0,.78,.72],[.8,.55,.5]); + const eyes=[];for(const s of [-1,1]){const e=this.group(hb,[s*.45,1.3,.92]);this.mesh(g.sphere,M.eye,e,[0,0,0],[.28,.36,.16]);this.mesh(g.sphere,M.pupil,e,[-s*.04,-.03,.13],[.11,.15,.06]);eyes.push(this.mesh(g.box,M.pupil,e,[0,.33,.12],[.5,.1,.08],[0,0,s*.12]));} + this.mesh(g.box,M.pupil,hb,[0,.72,1.17],[.5,.07,.05]);this.mesh(g.cyl,stem,hb,[0,2.1,0],[.07,.3,.07]); + for(let i=0;i<5;i++){const a=i*PI*.4;this.mesh(g.sphere,petal,hb,[Math.sin(a)*.32,2.28,Math.cos(a)*.32],[.26,.11,.26]);}this.mesh(g.sphere,M.yellow,hb,[0,2.32,0],[.15,.1,.15]); + const parts=[];for(let i=0;i<3;i++){const p=this.group(root),q=this.group(p);this.mesh(g.sphere,body,q,[0,.8,0],[.8,.8,.8]);this.mesh(g.sphere,belly,q,[0,.62,.3],[.5,.42,.5]);const feet=[];for(const s of [-1,1])feet.push(this.mesh(g.sphere,foot,p,[s*.5,.2,.1],[.3,.2,.42]));parts.push({p,q,feet});} + const hf=[-1,1].map(s=>this.mesh(g.sphere,foot,head,[s*.7,.2,.2],[.36,.22,.5])); + return {root,head,hb,parts,hf,eyes,mats:[body,angry]};} + // Bowser: a green shell with spikes, a pale belly, horns, a red mane and a bright tail tip (where to grab him). Mines: black spheres with spikes on a post (the post is scenery). Original procedural art. + buildBowser(){const M=this.mat,g=this.geo,root=new T.Group(),L=c=>this.keep(new T.MeshLambertMaterial({color:c})),shell=L(0x2f8a3a),skin=L(0xe2a92c),belly=L(0xf2dc9a),rim=L(0xf4efe0),hair=L(0xd6402a),horn=L(0xf0ead8),dark=L(0x20242c),post=L(0x4a4458); + const body=this.group(root,[0,0,0]);this.mesh(g.sphere,skin,body,[0,1.5,0],[1.35,1.45,1.3]);this.mesh(g.sphere,belly,body,[0,1.4,.72],[1.0,1.15,.72]);this.mesh(g.sphere,shell,body,[0,1.65,-.55],[1.5,1.5,1.15]);this.mesh(g.torus,rim,body,[0,1.65,-.5],[1.42,1.42,1.1]); + for(let i=0;i<9;i++){const a=i*PI*2/9,r=.75;this.mesh(g.cone,horn,body,[Math.sin(a)*r,1.7+Math.cos(a)*r,-1.45],[.2,.55,.2],[-PI/2,0,0]);} + const head=this.group(body,[0,2.75,.65]);this.mesh(g.sphere,skin,head,[0,0,0],[.72,.68,.72]);this.mesh(g.sphere,belly,head,[0,-.18,.55],[.62,.34,.55]); + for(const s of [-1,1]){const e=this.group(head,[s*.3,.25,.56]);this.mesh(g.sphere,M.eye,e,[0,0,0],[.2,.25,.12]);this.mesh(g.sphere,M.pupil,e,[-s*.03,0,.1],[.09,.12,.05]);this.mesh(g.cone,horn,head,[s*.55,.72,-.05],[.16,.55,.16],[0,0,-s*.45]);} + for(let i=0;i<5;i++)this.mesh(g.sphere,hair,head,[(i-2)*.2,.62-Math.abs(i-2)*.08,-.28],[.2,.34,.26]); + const limbs=[[-.95,.42,.25],[.95,.42,.25],[-1.2,1.9,.45],[1.2,1.9,.45]].map(([x,y,z],i)=>{const p=this.group(body,[x,y,z]);this.mesh(g.sphere,skin,p,[0,i<2?-.15:-.25,i<2?.1:.1],i<2?[.48,.48,.68]:[.3,.55,.3]);return p;}); + const tail=this.group(body,[0,.62,-1.05]);this.mesh(g.cone,skin,tail,[0,0,-.65],[.42,1.5,.42],[-PI/2,0,0]);const tip=this.mesh(g.sphere,L(0xffc83a),tail,[0,0,-1.45],[.2,.2,.3]),tipOff=L(0x4a4458),tipOn=tip.material; + const mines=[0,1,2,3].map(()=>{const p=this.group(root.parent||this.world);const q=this.group(p,[0,0,0]);this.mesh(g.sphere,dark,q,[0,0,0],[.5,.5,.5]);for(let i=0;i<8;i++){const a=i*PI/4;this.mesh(g.cone,horn,q,[Math.sin(a)*.5,0,Math.cos(a)*.5],[.1,.3,.1],[PI/2,0,a]);}this.mesh(g.cone,horn,q,[0,.52,0],[.1,.3,.1]);this.mesh(g.cyl,post,p,[0,-1.4,0],[.12,2.8,.12]);p.visible=false;return {p,q};}); + return {root,body,head,limbs,tail,mines,tip,tipOn,tipOff};} + arena(kind,A){if(this.arenas[kind])return this.arenas[kind];const g=new T.Group(),G=this.geo,L=(c,map)=>this.keep(new T.MeshLambertMaterial({color:c,map:map||null})); + const clouds=[],cloudMat=this.keep(new T.SpriteMaterial({map:this.keep(TEX.cloud()),transparent:true,depthWrite:false,fog:false})); + const addClouds=(n,r,y)=>{for(let i=0;i{for(let i=0;i{for(let i=0;i{const p=this.keep(new T.BufferGeometry()),v=[...a,...b,...c,...a,...c,...d],uv=[];for(let i=0;i[hx+q[0]*r,y,hz+q[1]*r],m=quad(pt(a,R,y0),pt(b,R,y0),pt(b,O,H),pt(a,O,H));g.add(m);} + for(let i=0;i<4;i++){const a=i*PI/2;this.mesh(G.box,rock,g,[hx+Math.sin(a)*O,8,hz+Math.cos(a)*O],[Math.abs(Math.cos(a))*41+.3,16,Math.abs(Math.sin(a))*41+.3]);} + this.mesh(G.plane,dark,g,[hx,16,hz],[42,42,1],[PI/2,0,0]); + const px=-.17,pz=.62,tip=this.keep(new T.ConeGeometry(4.33,2.05,4));tip.rotateY(PI/4);tip.rotateX(PI);this.mesh(tip,rock,g,[px,5.125,pz]);this.mesh(G.box,rock,g,[px,6.66,pz],[6.13,1.02,6.13]); + this.mesh(G.cyl,dark,g,[px,12,pz],[.5,8,.5]);} + else{ // Lethal Lava Land: the Big Bully's 1535 x 1408 platform, 307 above the lava; the volcano at the level centre + g.add(this.prism(P,307,L(0xffffff,this.tex(TEX.grate,.3)),L(0x5d524d)));trim(this.mat.iron); + const lavaTex=this.keep(TEX.lava());this.lavaTex=lavaTex; + this.mesh(G.plane,this.keep(new T.MeshBasicMaterial({map:lavaTex,color:0xffffff,fog:true})),g,[0,-3.07,0],[700,700,1],[-PI/2,0,0]); + this.mesh(this.keep(new T.ConeGeometry(16,26,12,1,true)),L(0x3a2622),g,[0,9.9,43.85]);this.mesh(G.sphere,this.keep(new T.MeshBasicMaterial({color:0xffa040})),g,[0,22.5,43.85],[3.4,1.2,3.4]); + for(let i=0;i<8;i++){const a=i*.8+.3,d=40+hash(i,1,19)*60;this.mesh(G.ico,L(0x4a3a35),g,[Math.sin(a)*d,-3,Math.cos(a)*d],[4+hash(i,2,19)*4,2+hash(i,3,19)*3,4]);}} + g.visible=false;this.world.add(g);this.arenas[kind]={group:g,clouds};return this.arenas[kind];} + setKind(kind,A){if(this.kind===kind)return;this.kind=kind;for(const [k,a] of Object.entries(this.arenas))a.group.visible=k===kind;this.arena(kind,A).group.visible=true; + for(const [k,b] of Object.entries(this.bosses))b.root.visible=k===kind; + this.bosses.bowser.mines.forEach(q=>{q.p.visible=false;}); + const sky={whomp:['#3f8be0','#8fc4f2','#e6f3fb'],king:['#3a86e6','#91c9f5','#eaf6fb'],bully:['#2a0d0b','#7a2412','#d9682a'],eyerok:['#1b120a','#4f3518','#a97e42'],wiggler:['#141a10','#2a3320','#4c5a38'],bowser:['#07060f','#120d24','#2c1f47']}[kind]; + if(this.skyTex)this.skyTex.dispose();this.skyTex=TEX.sky(...sky);this.world.background=this.skyTex; + this.world.fog=kind==='bowser'?new T.Fog(0x1a1430,70,240):kind==='wiggler'?new T.Fog(0x2a3320,40,110):kind==='eyerok'?new T.Fog(0x4f3518,60,150):kind==='bully'?new T.Fog(0x8a3418,40,190):new T.Fog(kind==='king'?0xcfe6f6:0xd6eaf7,70,260); + this.hemi.color.set(kind==='eyerok'?0xffe2b0:kind==='bully'?0xffc49a:0xdcefff);this.hemi.groundColor.set(kind==='bully'?0x6a2412:0x6a6250);this.sun.color.set(kind==='bully'?0xffb27a:0xfff1d6);} + // ---------------- poses (pure functions of the game state) ---------------- + poseMario(g){const P=this.mario,m=g.mario,t=g.t,a=m.action; + P.root.position.set(m.x*U,m.y*U,m.z*U);P.root.rotation.set(0,m.yaw,0);P.root.scale.set(1,1,1);P.root.visible=!(m.invinc>0&&m.invinc%6<3&&a!=='dead'); + const B=P.body;B.position.set(0,.78,0);B.rotation.set(0,0,0);P.head.rotation.set(0,0,0); + const arm=(i,x,z=0,fx=0)=>{P.arms[i].sh.rotation.set(x,0,z);P.arms[i].fore.rotation.set(fx,0,0);},leg=(i,x,k=0)=>{P.legs[i].hip.rotation.set(x,0,0);P.legs[i].shin.rotation.set(k,0,0);}; + arm(0,0,.12);arm(1,0,-.12);leg(0,0);leg(1,0); + const run=f=>{const ph=t*(.11+Math.abs(m.fwd)*.009),s=Math.sin(ph),amp=Math.min(1.05,.2+Math.abs(m.fwd)/30);leg(0,s*amp,Math.max(0,-s)*.6);leg(1,-s*amp,Math.max(0,s)*.6);arm(0,-s*amp*.8,.15,-.4);arm(1,s*amp*.8,-.15,-.4); + B.position.y=.78+Math.abs(Math.cos(ph))*.05*amp;B.rotation.x=Math.min(.35,Math.abs(m.fwd)/90);}; + const air=m.y>0?Math.min(1,(m.timer||0)/16):0,tk=m.timer||0; + switch(a){ + case 'walking':run();break; + case 'holdwalk':run();arm(0,-3.0,.3);arm(1,-3.0,-.3);break; + case 'decel':case 'braking':B.rotation.x=-.25;leg(0,.5,.2);leg(1,-.2);arm(0,-.6,.3);arm(1,-.6,-.3);break; + case 'turnaround':B.rotation.x=-.35;B.rotation.z=.2;leg(0,.7,.3);leg(1,-.3);break; + case 'jump':case 'freefall':case 'rollout':leg(0,-.9,1.2);leg(1,.35,.3);arm(0,-2.6,.3);arm(1,.5,-.5);if(a==='rollout')B.rotation.x=tk*.25;break; + case 'double':leg(0,-1.1,1.4);leg(1,-.3,.9);arm(0,-2.8,.2);arm(1,-2.8,-.2);break; + case 'triple':B.rotation.x=Math.min(PI*2,tk*.24);leg(0,-1.3,1.8);leg(1,-1.3,1.8);arm(0,-.4,.9);arm(1,-.4,-.9);break; + case 'backflip':B.rotation.x=-Math.min(PI*2,tk*.2);leg(0,-1.2,1.6);leg(1,-1.2,1.6);arm(0,-2.6,.4);arm(1,-2.6,-.4);break; + case 'sideflip':B.rotation.z=Math.min(PI*2,tk*.22);leg(0,-.6,1);leg(1,.2,.4);arm(0,-.4,1.4);arm(1,-.4,-1.4);break; + case 'longjump':B.rotation.x=1.05;leg(0,.9,0);leg(1,1.1,0);arm(0,-2.9,.15);arm(1,-2.9,-.15);break; + case 'dive':case 'diveslide':case 'divestop':B.rotation.x=1.45;B.position.y=a==='dive'?.78:.32;leg(0,.25);leg(1,.25);arm(0,-3,.2);arm(1,-3,-.2);break; + case 'jumpkick':leg(0,-1.4,0);leg(1,.5,.8);arm(0,-.8,.9);arm(1,-.8,-.9);B.rotation.x=-.25;break; + case 'slidekick':case 'slidekickslide':B.rotation.x=-1.0;B.position.y=.45;leg(0,-1.5,0);leg(1,-1.2,.4);arm(0,-2.2,.6);arm(1,-2.2,-.6);break; + case 'gp':if(m.state===0){B.rotation.x=Math.min(PI*2,tk*.42);leg(0,-1.5,2);leg(1,-1.5,2);arm(0,-.3,.8);arm(1,-.3,-.8);}else{leg(0,-1.6,1.9);leg(1,-1.6,1.9);arm(0,-2.7,.5);arm(1,-2.7,-.5);B.position.y=.95;}break; + case 'gpLand':B.position.y=.55;leg(0,-1.4,1.8);leg(1,-1.4,1.8);arm(0,-.2,1.2);arm(1,-.2,-1.2);break; + case 'crouchIn':case 'crouch':case 'crouchOut':case 'crouchslide':B.position.y=.5;B.rotation.x=a==='crouchslide'?.35:.2;leg(0,-1.2,1.9);leg(1,-1.2,1.9);arm(0,-.4,.2);arm(1,-.4,-.2);break; + case 'punching':case 'movepunch':{const k=m.arg>=6&&m.arg<9,sec=m.arg>=3&&m.arg<6,e=Math.min(1,tk/4); + if(m.arg===9){B.position.y=.4;B.rotation.y=tk*.35;leg(0,-1.6,0);leg(1,.9,0);arm(0,-1.4,.6);arm(1,-1.4,-.6);break;} + if(k){leg(0,-1.5*e,0);arm(0,-.6,.6);arm(1,.4,-.6);B.rotation.x=-.2;}else if(sec){arm(0,-1.55*e,0,0);arm(1,.4,-.3);B.rotation.y=-.3*e;}else{arm(1,-1.55*e,0,0);arm(0,.4,.3);B.rotation.y=.3*e;}break;} + case 'pickup':B.rotation.x=tk<16?.6:.1;arm(0,-1.2-(tk>16?1.2:0),.2);arm(1,-1.2-(tk>16?1.2:0),-.2);break; + case 'hold':arm(0,-3.0,.3);arm(1,-3.0,-.3);break; + case 'heavythrow':{const e=Math.min(1,tk/26);arm(0,-3+e*1.6,.3);arm(1,-3+e*1.6,-.3);B.rotation.x=-.3+e*.6;break;} + case 'grabbowser':B.rotation.x=tk<20?.5:-.1;B.position.y=.6;arm(0,-1.5,.2);arm(1,-1.5,-.2);break; + case 'swing':B.rotation.x=-.35;B.position.y=.72;arm(0,-1.57,.1);arm(1,-1.57,-.1);leg(0,.5,.3);leg(1,-.5,.3);break; + case 'release':{const e=Math.min(1,tk/20);B.rotation.x=-.35+e*.6;arm(0,-1.57+e*.6,.4);arm(1,-1.57+e*.6,-.4);break;} + case 'shockwave':B.position.y=.78+Math.abs(Math.sin(tk*.2))*.25;arm(0,-.2,1.3);arm(1,-.2,-1.3);leg(0,.25);leg(1,-.25);break; + case 'burnjump':case 'burnfall':leg(0,-.9,1.2);leg(1,.35,.3);arm(0,-2.6,.6);arm(1,-2.6,-.6);B.rotation.x=-.2;break; + case 'burnground':run();arm(0,-2.6,.5);arm(1,-2.6,-.5);break; + case 'grabbed':arm(0,-1.5,1.2);arm(1,-1.5,-1.2);leg(0,.4);leg(1,-.4);B.rotation.z=Math.sin(t*.4)*.25;break; + case 'thrown':case 'airkb':B.rotation.x=a==='thrown'?-tk*.15:-.6;arm(0,-2.6,1.1);arm(1,-2.6,-1.1);leg(0,.6,.8);leg(1,-.4,.6);break; + case 'kb':B.rotation.x=(m.fwd<0?-1:1)*Math.min(1.3,tk*.08);B.position.y=.78-Math.min(.35,tk*.02);arm(0,-2,.9);arm(1,-2,-.9);break; + case 'squished':P.root.scale.set(1.8,.06,1.8);break; + case 'lava':B.rotation.x=-.4;leg(0,Math.sin(t*.9)*.9,.6);leg(1,-Math.sin(t*.9)*.9,.6);arm(0,-2.6,.6);arm(1,.6,-.4);break; + case 'dead':B.rotation.x=-1.5;B.position.y=.25;arm(0,-2.8,.6);arm(1,-2.8,-.6);break; + case 'land':B.position.y=.66;leg(0,-.6,1.0);leg(1,-.6,1.0);break; + default:{const br=Math.sin(t*.06)*.015;B.position.y=.78+br;} + } + if(m.squish>0&&a!=='squished'){const k=1-m.squish/120;P.root.scale.set(1+.5*(1-k),Math.max(.3,k),1+.5*(1-k));} + } + poseWhomp(g){const b=g.boss,P=this.bosses.whomp,t=g.t;P.root.position.set(b.x*U,(b.y+(b.shake||0))*U,b.z*U);P.root.rotation.set(0,b.yaw,0);P.tilt.rotation.set(b.pitch,0,0); + P.root.visible=b.act!=='dead';const walk=b.act==='chase'&&b.fwd>0,ph=t*(.04+b.fwd*.012),prep=b.act==='prepare'?Math.min(1,b.timer/26):b.act==='jump'||b.act==='land'?1:0; + P.feet.forEach((f,i)=>{f.position.y=walk?Math.max(0,Math.sin(ph+i*PI))*.5:0;f.rotation.x=0;}); + P.arms.forEach((s,i)=>s.rotation.set(prep*1.1+(walk?Math.sin(ph+i*PI)*.25:0),0,(i?1:-1)*prep*.9)); // arms swing back and out for the dive + if(b.act==='die'){const k=Math.min(1,b.timer/60);P.root.scale.set(1-k*.6,1-k*.9,1-k*.6);}else P.root.scale.set(1,1,1); + // The slab's vertical projection is its own shadow: as it tips forward this rectangle is exactly where it will land. + const p=b.pitch,fs=[100*Math.sin(p)-200*Math.cos(p),860*Math.sin(p)-200*Math.cos(p),100*Math.sin(p)-6*Math.cos(p),860*Math.sin(p)-6*Math.cos(p)]; + const f0=Math.min(...fs),f1=Math.max(...fs),fc=(f0+f1)/2,fx=Math.sin(b.yaw),fz=Math.cos(b.yaw),S=this.slabShadow; + S.visible=b.act!=='dead';S.position.set((b.x+fx*fc)*U,.02,(b.z+fz*fc)*U);S.rotation.set(-PI/2,0,b.yaw);S.scale.set(600*U,(f1-f0)*U,1); + this.slabShadowMat.opacity=b.act==='die'?0:.18+.32*clamp(p/(PI/2),0,1); + // Readability aid (not in the 1996 game): during the wind-up and fall, the exact squish footprint f 100..860, |u|<=300. + const warn=b.act==='prepare'?clamp(b.timer/28,0,1):b.act==='jump'||b.act==='land'?1:0,L=this.landZone;L.visible=warn>0; + if(warn>0){L.position.set((b.x+fx*480)*U,.035,(b.z+fz*480)*U);L.rotation.set(-PI/2,0,b.yaw);L.scale.set(600*U,760*U,1);this.landMat.opacity=.10+.22*warn;}} + poseKing(g){const k=g.boss,P=this.bosses.king,t=g.t;P.root.position.set(k.x*U,k.y*U,k.z*U);P.root.rotation.set(0,k.yaw,0);P.body.rotation.set(0,0,0);P.body.position.set(0,1.32,0); + const walk=k.act===2&&k.fwd>0||(k.act===3&&k.sub===1),ph=t*.12;P.feet.forEach((f,i)=>{f.position.set(f.position.x,walk?Math.max(0,Math.sin(ph+i*PI))*.25:0,walk?Math.sin(ph+i*PI)*.2+.1:.1);}); + P.arms.forEach((s,i)=>s.rotation.set(k.act===3?-1.1:walk?Math.sin(ph+i*PI)*.3:0,0,0)); + if(k.held){P.body.rotation.x=-.3;P.arms.forEach((s,i)=>s.rotation.set(-.8,0,(i?-1:1)*.6));} + if(k.act===4)P.body.rotation.x=-k.timer*.12; + const hurt=k.act===6&&k.sub===0;P.body.children[0].material=hurt&&(t>>2)%2?this.mat.red:this.mat.black; + if(k.act===7){const e=Math.min(1,k.timer/60);P.root.scale.setScalar(1-e*.7);}else P.root.scale.setScalar(1); + P.root.visible=!(k.act===7&&k.timer>55);} + poseBully(g){const b=g.boss,P=this.bosses.bully,t=g.t;P.root.position.set(b.x*U,b.y*U,b.z*U);P.root.rotation.set(0,b.faceYaw,0); + const charge=b.act==='chase'&&b.fwd>10,ph=t*(charge?.5:.15);P.body.rotation.set(charge?.35:b.act==='knockback'&&b.fwd>2?-.35:0,0,0); + P.feet.forEach((f,i)=>{f.position.y=(b.act==='chase'||b.act==='patrol'||b.act==='backup')?Math.max(0,Math.sin(ph+i*PI))*.22:0;}); + P.root.visible=b.act!=='dead'&&!(b.act==='sink'&&b.timer>58);P.body.children[0].material=b.act==='sink'?this.mat.red:this.mat.iron;} + poseEyerok(g){const b=g.boss,P=this.bosses.eyerok,m=g.mario,t=g.t,HB=root.Mario64Game.HAND; + b.hands.forEach((h,i)=>{const H=P.hands[i],dying=h.act==='die',shake=h.act==='attacked'||dying?Math.sin(t*1.7)*.05:0;H.h.visible=!h.gone&&(h.act!=='sleep'||b.act!=='sleep'); + H.h.position.set(h.x*U,h.y*U,h.z*U);H.h.rotation.set(dying?-Math.min(1,(h.af+1)/40)*.5:0,h.face,shake); + // Opening takes anim 4 (30 frames), closing anim 7 (28 frames up to its check), S37: the fist folds into the raised palm. + const p=h.act==='open'?clamp((h.af+1)/30,0,1):h.act==='close'?clamp(1-h.timer/28,0,1):h.open?1:0; + H.fist.visible=p<1;H.palm.visible=p>0;H.fist.scale.set(1,Math.max(.02,1-p),1);H.palm.scale.set(1,Math.max(.02,p),1); + const c=h.blink/3;H.upper.position.y=.55+(1-c)*.95;H.lower.position.y=-.55-(1-c)*.95;const l=Math.atan2(m.x-h.x,m.z-h.z)-h.face;H.pupil.position.set(clamp(Math.sin(l),-1,1)*.4,clamp((m.y-h.y-260)*.001,-.3,.3),0); + const B=h.open?HB.open:HB.fist,w=B.x1-B.x0,dp=B.z1-B.z0,cx=(B.x0+B.x1)/2,cz=(B.z0+B.z1)/2,s=Math.sin(h.face),co=Math.cos(h.face); + H.shadow.visible=H.h.visible;H.shadow.position.set((h.x+cx*co+cz*s)*U,.035,(h.z-cx*s+cz*co)*U);H.shadow.scale.set(w*U,dp*U,1);H.shadow.rotation.z=h.face;});} + poseWiggler(g){const b=g.boss,P=this.bosses.wiggler,t=g.t,run=b.act==='walk'?t*(.05+b.fwd*.012):0,angry=b.hp{e.visible=angry;});P.hb.children[0].material=P.mats[angry?1:0]; + P.hf.forEach((f,i)=>{f.position.y=.2+Math.max(0,Math.sin(run+i*PI))*.25;}); + P.parts.forEach((q,i)=>{const s=b.s[i+1];q.p.position.set((s.px??s.x)*U,s.y*U,(s.pz??s.z)*U);q.p.rotation.set(0,s.yaw,0);q.p.scale.set(sx,sx,sx);q.q.rotation.x=s.pitch;q.q.children[0].material=P.mats[angry?1:0]; + q.feet.forEach((f,j)=>{f.position.y=.2+Math.max(0,Math.sin(run+(i+1)*1.4+j*PI))*.22;});});} + poseBowser(g){const b=g.boss,P=this.bosses.bowser,t=g.t,B=P.body;P.tip.material=b.guard>0||b.tail===1?P.tipOff:P.tipOn;P.root.visible=b.op>=30;P.root.position.set(b.x*U,b.y*U,b.z*U);P.root.rotation.set(0,b.yaw,0);B.rotation.set(0,0,0);B.position.set(0,0,0);P.head.rotation.set(0,0,0);P.tail.rotation.set(0,0,0); + const f=Math.max(0,b.af),walk=(b.act==='walk'&&b.fwd>0)?Math.sin(t*.09):0;P.limbs[0].rotation.x=walk*.5;P.limbs[1].rotation.x=-walk*.5;P.limbs[2].rotation.x=-.6-walk*.3;P.limbs[3].rotation.x=-.6+walk*.3;P.tail.rotation.y=Math.sin(t*.05)*.2; + switch(b.act){ + case 'breath':{const e=f<46?-Math.min(1,f/30)*.5:Math.min(1,(f-46)/8)*.3;P.head.rotation.x=e;B.rotation.x=e*.3;break;} + case 'dance':B.rotation.z=Math.sin(f*.18)*.22;P.limbs[2].rotation.x=-2.5;P.limbs[3].rotation.x=-2.5;break; + case 'quickjump':P.limbs[0].rotation.x=.6;P.limbs[1].rotation.x=.6;break; + case 'held':B.rotation.x=-1.2;B.position.y=.9;B.rotation.z=Math.sin(t*.5)*.08;break; + case 'thrown':if(b.sub===0){B.rotation.x=-1.2+Math.sin(t*.6)*.25;B.position.y=.7;}else{const e=Math.min(1,f/30);B.rotation.x=-1.2*(1-e);B.position.y=.7*(1-e);}break; + case 'hitmine':case 'dead':B.rotation.x=b.sub<2?-(t*.25)%(PI*2):-Math.max(0,1-f/30)*1.5;B.position.y=.9;break; + case 'jumpstage':B.rotation.x=(b.spin&0xffff)/65536*PI*2;break; + } + P.mines.forEach((q,i)=>{const n=b.mines[i];q.p.visible=this.kind==='bowser'&&n.alive;q.p.position.set(n.x*U,n.y*U,n.z*U);q.q.rotation.y=t*.01;});} + // ---------------- effects ---------------- + effects(g){const pools=this.pools,o=this.o,n={dust:0,star:0,ring:0,fire:0,ember:0}; + const put=(pool,x,y,z,s,rx=0,ry=0)=>{const P=pools[pool];if(n[pool]>=P.instanceMatrix.count)return;o.position.set(x,y,z);o.rotation.set(rx,ry,0);o.scale.set(s,s,s);o.updateMatrix();P.setMatrixAt(n[pool]++,o.matrix);}; + const putRing=(x,y,z,r)=>{const P=pools.ring;if(n.ring>=P.instanceMatrix.count)return;o.position.set(x,y,z);o.rotation.set(-PI/2,0,0);o.scale.set(r,r,r);o.updateMatrix();P.setMatrixAt(n.ring++,o.matrix);}; + items(g.effects).forEach((e,idx)=>{const age=1-e.life/e.maxLife,x=e.x*U,y=(e.y||0)*U,z=e.z*U; + switch(e.type){ + case 'pound':case 'slam_dust':case 'bump':{const big=e.type==='slam_dust'?3.2:e.type==='pound'?1.4:.6;putRing(x,y+.05,z,.3+big*age*1.6); + for(let i=0;i<10;i++){const a=i*PI/5+idx,r=.2+big*age*1.4;put('dust',x+Math.sin(a)*r,y+.25+age*.6*big*.3,z+Math.cos(a)*r,(.28+.25*big*.3)*(1-age*.6));} + if(e.type==='pound')for(let i=0;i<6;i++){const a=i*PI/3,r=.4+age*1.5;put('star',x+Math.sin(a)*r,y+.5+Math.sin(age*PI)*.8,z+Math.cos(a)*r,.16,age*6,a);}break;} + case 'impact':case 'hit_star':for(let i=0;i<8;i++){const a=i*PI/4+idx*.3,r=.3+age*1.8;put('star',x+Math.sin(a)*r,y+1.2+Math.cos(a*2)*.4+age*.6,z+Math.cos(a)*r,.2*(1-age*.5),age*8,a);}break; + case 'lava_burst':for(let i=0;i<12;i++){const a=i*PI/6+idx,r=.2+age*1.2;put('fire',x+Math.sin(a)*r,y+.3+age*2.2*(.5+hash(i,idx,3)),z+Math.cos(a)*r,.35*(1-age));}break; + case 'mist':for(let i=0;i<18;i++){const a=i*.7+idx,r=.8+age*3;put('dust',x+Math.sin(a)*r,y+1+age*2+(i%4)*.5,z+Math.cos(a)*r,.9*(1-age*.7));}break; + }}); + if(this.kind==='bowser'){const b=g.boss; + b.flames.forEach((f,i)=>{const r=f.s*.1;put('fire',f.x*U,f.y*U,f.z*U,r,g.t*.1,i);}); + b.fires.forEach((f,i)=>{const r=f.s*.1,k=1+Math.sin(g.t*.3+i)*.15;put('fire',f.x*U,(f.y+f.s*14)*U,f.z*U,r*k,g.t*.08,i);put('fire',f.x*U,(f.y+f.s*30)*U,f.z*U,r*.6/k,g.t*.1,i+1);}); + if(['burnjump','burnfall','burnground'].includes(g.mario.action))for(let i=0;i<7;i++){const a=i*.9+g.t*.25,m=g.mario;put('fire',m.x*U+Math.sin(a)*.3,m.y*U+.5+(i%4)*.35,m.z*U+Math.cos(a)*.3,.2,g.t*.2,i);}} + if(this.kind==='bully')for(let i=0;i<24;i++){const ph=((g.t*.004+hash(i,1,91))%1),a=hash(i,2,91)*PI*2,d=10+hash(i,3,91)*40;put('ember',Math.sin(a)*d,-3+ph*14,Math.cos(a)*d,.12*(1-ph),ph*9,a);} + for(const k of Object.keys(pools)){pools[k].count=n[k];pools[k].instanceMatrix.needsUpdate=true;}} + shadows(g){const m=g.mario,b=g.boss,fl=typeof g.floor==='function'?g.floor(m.x,m.z,m.y+1):{y:0};const my=fl?fl.y:-1e4; + this.marioBlob.visible=!!fl&&m.action!=='squished'&&m.y-my<2500;this.marioBlob.position.set(m.x*U,my*U+.04,m.z*U);const k=clamp(1-(m.y-my)/1600,.35,1);this.marioBlob.scale.set(.45*k,.45*k,1); + const r=b.kind==='whomp'||b.kind==='eyerok'?0:b.kind==='bowser'?(b.op<100||b.held?0:1.9):b.kind==='wiggler'?1.3:b.kind==='king'?1.25:1.2;this.bossBlob.visible=r>0&&b.y>-50&&!(b.kind==='king'&&b.held)&&b.act!=='dead';this.bossBlob.position.set(b.x*U,(b.kind==='wiggler'?g.floor(b.x,b.z,b.y).y*U:0)+.03,b.z*U);this.bossBlob.scale.set(r,r,1);} + render(g,ctx){ + if(this.closed||this.renderer.getContext().isContextLost()){this.ready=false;this.error=this.closed?'3D renderer is closed':'WebGL context lost';throw Error(this.error);}const start=performance.now(); + try{const kind=g.boss.kind;this.setKind(kind,g.arena);this.poseMario(g); + if(kind==='whomp')this.poseWhomp(g);else if(kind==='king')this.poseKing(g);else if(kind==='eyerok')this.poseEyerok(g);else if(kind==='wiggler')this.poseWiggler(g);else if(kind==='bowser')this.poseBowser(g);else this.poseBully(g); + this.slabShadow.visible=kind==='whomp'&&this.slabShadow.visible;this.landZone.visible=kind==='whomp'&&this.landZone.visible;this.shadows(g);this.effects(g); + if(this.lavaTex)this.lavaTex.offset.set((g.t*.0006)%1,(g.t*.0004)%1); + const c=g.cam,m=g.mario,d=c.dist*U,p=c.pitch,tx=m.x*U,ty=Math.max(m.y*U,-2.5)+.95,tz=m.z*U; + this.camera.position.set(tx-Math.sin(c.yaw)*d*Math.cos(p),ty+d*Math.sin(p),tz-Math.cos(c.yaw)*d*Math.cos(p)); + if(kind==='wiggler'){const P=this.camera.position,cl=(v,a,b)=>clamp(v,a+.4,b-.4);P.x=cl(P.x,-20.64,20.31);P.z=cl(P.z,-19.85,21.1);P.y=clamp(P.y,g.floor(P.x/U,P.z/U,1e4).y*U+.6,15.6);} // closed room (S41): the view stays inside its walls + this.camera.lookAt(tx+Math.sin(c.yaw)*1.4,ty+.15,tz+Math.cos(c.yaw)*1.4); + this.renderer.info.reset();this.renderer.render(this.world,this.camera);ctx.drawImage(this.view,0,0,854,480); + this.times.push(performance.now()-start);if(this.times.length>120)this.times.shift();this.ready=true;this.error=null; + }catch(e){this.ready=false;this.error=String(e);throw e;} + } + metrics(){const info=this.renderer.info,sorted=[...this.times].sort((a,b)=>a-b);let geometryBytes=0,textureBytes=0; + for(const r of this.resources){if(r.isBufferGeometry){for(const a of Object.values(r.attributes))geometryBytes+=a.array.byteLength;if(r.index)geometryBytes+=r.index.array.byteLength;} + if(r.isTexture&&r.image)textureBytes+=(r.image.width||0)*(r.image.height||0)*4;if(r.isInstancedMesh)geometryBytes+=r.instanceMatrix.array.byteLength;} + return {renderer:'webgl-mario64',webglVersion:this.renderer.capabilities.isWebGL2?2:1,drawCalls:info.render.calls,triangles:info.render.triangles,geometries:info.memory.geometries, + textures:info.memory.textures,geometryBytes,textureBytes,canvasBytes:854*480*4,resourceBytesEstimate:geometryBytes+textureBytes+854*480*8,staticAssetBytes:669884, + renderSamples:sorted.length,cpuRenderMsP50:sorted.length?sorted[Math.floor((sorted.length-1)*.5)]:null,cpuRenderMsP95:sorted.length?sorted[Math.floor((sorted.length-1)*.95)]:null, + shadows:'blob shadows (N64 style) + projected slab footprint; no shadow maps',postprocess:false};} + close(){if(this.closed)return;this.closed=true;this.ready=false;if(this.skyTex)this.skyTex.dispose();this.resources.forEach(r=>r.dispose?.());this.renderer.dispose();this.renderer.forceContextLoss();this.resources.clear();} + } + R.render=function(g,ctx){let s=byCanvas.get(ctx.canvas);if(!s||s.closed){s=new Scene(ctx.canvas);byCanvas.set(ctx.canvas,s);}s.render(g,ctx);return s;}; + R.status=function(ctx){const s=ctx&&byCanvas.get(ctx.canvas);if(s&&!s.closed&&s.renderer.getContext().isContextLost()){s.ready=false;s.error='WebGL context lost';} + return {renderer:'webgl-mario64',kind:'perspective',ready:!!s?.ready&&!s.closed,error:s?.error||null};}; + R.metrics=function(ctx){const s=ctx&&byCanvas.get(ctx.canvas);return s?s.metrics():null;}; + R.scene=function(ctx){return ctx&&byCanvas.get(ctx.canvas)||null;}; + R.close=function(ctx){const s=ctx&&byCanvas.get(ctx.canvas);if(s){s.close();byCanvas.delete(ctx.canvas);}}; +})(window); diff --git a/environments/games/web/games/mario64_remake/style3d.css b/environments/games/web/games/mario64_remake/style3d.css new file mode 100644 index 0000000000000000000000000000000000000000..ec39215c7a394dd8d0d0758490acf67ca7ec50f9 --- /dev/null +++ b/environments/games/web/games/mario64_remake/style3d.css @@ -0,0 +1 @@ +:root{color-scheme:dark;--bg:#14191a;--panel:#1d2425;--edge:#354141;--text:#ebe7dc;--muted:#a5b2ad;--accent:#dfb676}*{box-sizing:border-box}body{margin:0;background:radial-gradient(ellipse at top,#29312b,transparent 60%),var(--bg);color:var(--text);font:14px/1.7 'Segoe UI','Microsoft YaHei',sans-serif}body[data-game=genshin_remake]{--bg:#101822;--panel:#1b2530;--edge:#374754;--accent:#baacff;background:radial-gradient(ellipse at top,#2b2942,transparent 60%),var(--bg)}body[data-game=mario64_remake]{--bg:#0f1530;--panel:#18214a;--edge:#34407a;--text:#f3f1ea;--muted:#aeb7dd;--accent:#ffd23a;background:radial-gradient(ellipse at top,#2b3a8a,transparent 62%),radial-gradient(ellipse at bottom right,#5a1616,transparent 55%),var(--bg)}body[data-game=mario64_remake] h1{font-family:"Segoe UI","Microsoft YaHei",sans-serif;font-weight:800;letter-spacing:.5px;text-shadow:0 3px 0 #b81d22,0 6px 14px #0008}body[data-game=mario64_remake] button.primary{background:#e52521;color:#fff}body[data-game=mario64_remake] .stage{border-color:#ffd23a55}main{max-width:1220px;margin:auto;padding:28px 24px 40px}header{display:flex;align-items:center;justify-content:space-between;margin-bottom:22px;gap:20px}.eyebrow{color:var(--accent);font-size:11px;letter-spacing:2.5px;text-transform:uppercase}h1{font:500 32px/1.35 Georgia,'Microsoft YaHei',serif;letter-spacing:1px;margin:6px 0}header p{color:var(--muted);margin:0;font-size:13px}a{color:var(--accent);text-decoration:none}a:hover{text-decoration:underline}.layout{display:grid;grid-template-columns:minmax(0,854px) 245px;gap:24px;align-items:start}.stage{position:relative;border:1px solid var(--edge);box-shadow:0 22px 55px #0005;background:#111b1c}canvas{display:block;width:100%;aspect-ratio:854/480;touch-action:none;outline:none}canvas:focus-visible{outline:2px solid var(--accent);outline-offset:3px}#overlay{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:#10171b30;pointer-events:none}#overlay[hidden]{display:none}#overlay div{background:#111b23de;padding:19px 32px;border:1px solid #9ba6a655;max-width:80%;text-align:center}#overlay strong{font:500 24px Georgia,'Microsoft YaHei',serif;display:block}#overlay span{display:block;color:var(--muted);font-size:12px;margin-top:7px}.toolbar{display:flex;gap:8px;flex-wrap:wrap;padding:12px;background:var(--panel);border-top:1px solid var(--edge)}button,select,input{font:inherit;background:var(--panel);color:var(--text);border:1px solid var(--edge);border-radius:4px;padding:7px 11px}button{cursor:pointer}button:hover{border-color:var(--accent);background:#ffffff09}button.primary{background:var(--accent);color:var(--bg);font-weight:600}button:focus-visible,select:focus-visible,input:focus-visible,a:focus-visible{outline:2px solid var(--accent);outline-offset:3px}aside{padding:19px;border:1px solid var(--edge);background:var(--panel)}h2{font-size:16px;margin:0 0 8px}label{display:block;font-size:12px;color:var(--muted);margin:12px 0 5px}select,input{width:100%}dl{border-top:1px solid var(--edge);padding-top:16px;margin:18px 0 0}dt{color:var(--accent);font:12px/1.8 Consolas,monospace}dd{color:var(--muted);font-size:12px;margin:0 0 10px}.note{color:var(--muted);font-size:12px}#status{min-height:25px;margin:10px 0;color:var(--accent);overflow-wrap:anywhere}.record-toolbar{border:1px solid var(--edge);padding:10px;background:transparent}.record-toolbar button{font-size:12px}#file{display:none}.mobile{display:none}footer{display:flex;flex-wrap:wrap;gap:22px;border-top:1px solid var(--edge);margin-top:28px;padding-top:15px;font-size:12px}@media(max-width:950px){main{padding:14px}.layout{grid-template-columns:1fr}aside{display:grid;grid-template-columns:1fr 1fr;gap:0 18px}aside dl,aside .note{grid-column:1/-1}dl{columns:2}.mobile{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}.mobile button{min-width:45px;touch-action:none}header{align-items:start}h1{font-size:26px}}@media(max-width:500px){header{display:block}header a{font-size:12px}aside{padding:14px}#overlay div{padding:14px 20px}#overlay strong{font-size:19px}.toolbar{gap:6px;padding:8px}button{font-size:12px}h1{font-size:25px}} diff --git a/environments/games/web/games/megaman_remake/arena.js b/environments/games/web/games/megaman_remake/arena.js new file mode 100644 index 0000000000000000000000000000000000000000..1f6121d5054a2002fe2c8f875b83e823ce4484ac --- /dev/null +++ b/environments/games/web/games/megaman_remake/arena.js @@ -0,0 +1,118 @@ +// Mega Man (NES, 1987) on the BB.Case engine: shared rules for the Robot Master rooms. +// World units are NES pixels. A room is 256 x 240 with the origin at the top-left and y growing downward, as the +// original stores positions; one 60 Hz tick is one NES frame. Speeds are px/frame written as the original 8.8 +// fixed-point values (MM.fx(0x4DF) = 4.87109375), so every constant can be checked against the disassembly cited +// in SOURCES.md. Energy and damage are NES units (one bar = 28 units); hit points are reported as points = +// units x 18, so one full NES bar is 504 points (the 2026-11-02 meeting asks for ~500 on easy). +// Update order of one tick follows the original main loop (bank 5 $915E): player update -> weapon flight +// services -> boss AI -> player i-frame countdown -> player contact -> shot collision -> entity motion -> +// render-time counters (boss i-frames, animation timers). body_megaman.js resolveInteractions() runs the part +// after the boss AI. +(function (g) { + var B = g.BB; + B.ARENA = { W: 256, H: 240 }; + var MM = B.MM = {}; + + MM.fx = function (hex) { return hex / 256; }; // 8.8 fixed point -> px/frame + MM.FLOOR = 192; // floor top of every boss room; a standing 24 px body has its centre at y = 180 + MM.WALL_L = 16; MM.WALL_R = 240; // inner faces of the side walls + MM.UNIT = 18; MM.BAR = 28; + MM.GRAVITY = MM.fx(0x40); // -0.25 px/frame^2 for the player and every entity with gravity + MM.FALL_MAX = 12; // terminal velocity -0C.00 + MM.TOP_EXIT = 4; MM.BOTTOM_EXIT = 0xE8; // entity y outside [4, $E8) has left the screen + + MM.box = function (x, y, hw, hh) { return { x: x, y: y, hw: hw, hh: hh }; }; + // hitbox_overlap_test ($C9BE) on integer pixel positions: e = the tested entity (boss, boss shot), b = the + // probing box (a player shot or the player's touch box). Top/bottom compare strict/inclusive, sides inclusive. + MM.overlap = function (e, b) { + var ex = Math.floor(e.x), ey = Math.floor(e.y), bx = Math.floor(b.x), by = Math.floor(b.y); + return ey - e.hh < by + b.hh && ey + e.hh >= by - b.hh && ex - e.hw <= bx + b.hw && ex + e.hw >= bx - b.hw; + }; + MM.offscreen = function (o) { return o.x < 0 || o.x >= 256 || o.y < MM.TOP_EXIT || o.y >= MM.BOTTOM_EXIT; }; + MM.r = function (v) { return B.r4(v); }; + MM.snapshot = function (v) { + if (typeof v === 'number') return B.r4(v); + if (Array.isArray(v)) return v.map(MM.snapshot); + if (v && typeof v === 'object') { var o = {}; Object.keys(v).forEach(function (k) { o[k] = MM.snapshot(v[k]); }); return o; } + return v; + }; + // tier knobs: spec rows are [easy, normal, hard] at d = 0 / 0.5 / 1, the values BB.GAME.tiers declares, + // so the public tiers read the spec rows exactly and any d in between interpolates (BB.knobs). + MM.knobs = function (spec, d) { return B.knobs(spec.difficulty, d); }; + + // Shared entity physics (boss_walk_tick $EDF8 + vertical_collision $9BC4): x moves by |vx| along dir with a + // wall clamp (o.blocked = the $2A wall probe); y -= vy (up = positive); a falling body that reaches the floor + // snaps onto it with the grounded hold velocity $FF.40 (o.landed = the $2B probe, set again every frame it + // stands); otherwise gravity applies if o.grav. Ice Man's descent relies on the hold value being negative. + MM.GROUND_VY = -(1 - MM.fx(0x40)); + MM.step = function (o) { + o.blocked = false; o.landed = false; + if (o.vx) { + var nx = o.x + o.vx * o.dir, lo = MM.WALL_L + o.hw, hi = MM.WALL_R - o.hw; + if (nx < lo) { nx = lo; o.blocked = true; } else if (nx > hi) { nx = hi; o.blocked = true; } + if (o.room && o.room.length) { var cx = MM.clampX(o.room, o.x, nx, o.hw, o.y, o.hh); if (cx !== nx) { nx = cx; o.blocked = true; } } + o.x = nx; + } + var ny = o.y - o.vy, floor = o.room && o.room.length ? MM.floorUnder(o.room, o.x - o.hw + 1, o.x + o.hw - 1, o.y + o.hh) : MM.FLOOR; + if (o.vy < 0 && ny + o.hh >= floor) { o.y = floor - o.hh; o.vy = MM.GROUND_VY; o.landed = true; o.grounded = true; return; } + o.y = ny; o.grounded = false; + if (o.grav) o.vy = Math.max(-MM.FALL_MAX, o.vy - MM.GRAVITY); + }; + + // Room solids beyond the side walls and the floor: the scene's collision override records and solid step tiles, + // as rectangles {x0, x1, y0, y1} (x1/y1 exclusive). The flat rooms have none (MM.ROOMS has no entry), and every + // caller skips these helpers for an empty list, so their arithmetic is exactly the flat-room one. + MM.ROOMS = {}; + MM.roomOf = function (caseId) { return MM.ROOMS[caseId] || []; }; + // Cut Man's and Guts Man's rooms have the same step: solid tiles x 16-32 and two liftable blocks x 32-64, 64-96 (override + // type 2), top y 160. A lifted block leaves the body's and the boss's own copy of the list, never this table. + MM.blockRoom = function (caseId) { + MM.ROOMS[caseId] = [{ x0: 16, x1: 32, y0: 160, y1: 192 }, { x0: 32, x1: 64, y0: 160, y1: 192, block: true }, { x0: 64, x1: 96, y0: 160, y1: 192, block: true }]; + }; + // override_search on the record bounds: x0 <= x < x1, y0 <= y < y1; returns the liftable block there or null + MM.blockAt = function (room, x, y) { + for (var i = 0; i < room.length; i++) { + var r = room[i]; + if (r.block && r.x0 <= x && x < r.x1 && r.y0 <= y && y < r.y1) return r; + } + return null; + }; + // top of the highest surface under the span [x0, x1] at or below a body whose bottom is at `bottom` + // (vertical_collision probes the two side edges of the body: x +- (half-width - 1) for entities, x +- 7 for Mega Man) + MM.floorUnder = function (room, x0, x1, bottom) { + var f = MM.FLOOR; + for (var i = 0; i < room.length; i++) { + var r = room[i]; + if (x1 >= r.x0 && x0 < r.x1 && r.y0 >= bottom - 1e-9 && r.y0 < f) f = r.y0; + } + return f; + }; + // wall probe against the room solids (move_right/move_left): a body whose bottom is below a solid's top is pushed + // back out to the side it came from + MM.clampX = function (room, x, nx, hw, y, hh) { + for (var i = 0; i < room.length; i++) { + var r = room[i]; + if (y + hh > r.y0 + 1e-9 && y - hh < r.y1 && nx - hw < r.x1 && nx + hw > r.x0) nx = x >= (r.x0 + r.x1) / 2 ? r.x1 + hw : r.x0 - hw; + } + return nx; + }; + + // proportional_velocity ($F8C6) with fraction_divide / divide_24_16: the major axis gets the full speed, the minor one + // speed x minor / major through two 8.8 divisions (truncating like the 16-step long division). dy = source - target + // y; a target below takes |dy| with EOR #$FF (one less, as the original) and a downward Y speed. speedRaw is 8.8 raw. + MM.propVel = function (speedRaw, adx, dy) { + var up = dy >= 0, ady = up ? dy & 0xFF : (~dy) & 0xFF; + function frac(a, divRaw) { return divRaw ? Math.floor(a * 65536 / divRaw) & 0xFFFF : 0xFFFF; } + var major = speedRaw, minor; + if (adx >= ady) minor = frac(ady, frac(adx, major)); else minor = frac(adx, frac(ady, major)); + var vx = (adx >= ady ? major : minor) / 256, vy = (adx >= ady ? minor : major) / 256; + return { vx: vx, vy: up ? vy : -vy, ady: ady }; + }; + + // Boss projectiles live in enemy slots $10-$1F (find_free_slot from $10); the player's contact check tests + // only the slots whose parity matches the frame counter (player_contact_service $A18B). + MM.freeSlot = function (list) { + for (var s = 16; s < 32; s++) if (!list.some(function (p) { return p.slot === s; })) return s; + return -1; + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/art/scenes.js b/environments/games/web/games/megaman_remake/art/scenes.js new file mode 100644 index 0000000000000000000000000000000000000000..96032b48b718d00961cf4113d1c61a9650351164 --- /dev/null +++ b/environments/games/web/games/megaman_remake/art/scenes.js @@ -0,0 +1,15 @@ +// Scene hooks the shared renderer expects (ART.scene / ART.ambient). Mega Man draws its whole picture in +// draw/hud.js (BODY_DRAW.megaman.fullHud), so the background and foreground here are empty 1x1 layers. +(function (g) { + var B = g.BB, A = B.ART; + var blank = {}; + A.scene = function (doc, id) { + if (!blank[id]) { + var bg = doc.createElement('canvas'), fg = doc.createElement('canvas'); + bg.width = bg.height = fg.width = fg.height = 1; + blank[id] = { bg: bg, fg: fg }; + } + return blank[id]; + }; + A.ambient = function () {}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/body_megaman.js b/environments/games/web/games/megaman_remake/body_megaman.js new file mode 100644 index 0000000000000000000000000000000000000000..b1e590450c91e78817c917d1a1ad1521787a8470 --- /dev/null +++ b/environments/games/web/games/megaman_remake/body_megaman.js @@ -0,0 +1,471 @@ +// Mega Man, the player body (NES 1987 rules; no slide and no charge shot - those arrived in Mega Man 3 and 4). +// Constants are the ROM's 8.8 values (bank 5 player_update $94A8, TASVideos Rockman data for RM1): +// walk 01.60 after a start-up of 9 frames at 00.20; releasing the d-pad at top speed slides 13 frames at 00.80; +// air X 01.50 (00.20 on the first frame of a fresh press); jump 04.DF up, gravity 00.40, fall cap 12; +// releasing jump while still rising at 02.00 or more sets the rise to 01.00 (player_fall_cap). +// Touch box 14 x 22 (x +-7, y +-11); the wall/floor body is 16 x 24. +// A hit costs the damage, starts 29 frames of knockback (a 01.40 hop, drifting 00.90 along the attacker's facing, +// no control) and 111 ($6F) frames of blinking invulnerability. Weapons: Buster (3 shots, 4 px/frame), Thunder +// Beam (three-way crawling bolt), Ice Slasher (piercing), Fire Storm (wave + 32-frame orbit shield), Hyper Bomb +// (three bounces, 146-frame fuse, 12-way flames), Rolling Cutter (piercing, flies out 42 frames and homes back), Super Arm +// (lifts a block of the room, throws it, it shatters into 4 chunks); 28 units each. +(function (g) { + var B = g.BB, MM = B.MM, fx = MM.fx; + var WALK = fx(0x160), START = fx(0x20), SLIDE = fx(0x80), AIR = fx(0x150); + // knockback (special state 3, $9742): anim $12 runs 30 frames; entering it sets Y velocity 01.40 (a small hop) + // and the speed row for anim $12 ($9DDD list index 5 -> $9DE6 row 9 -> $8643 = 00.90) drifts him along the + // attacker's facing + var JUMP = fx(0x4DF), KNOCK = fx(0x90), KNOCK_VY = fx(0x140); + // anim $12 (30-frame cycle) starts at frame 1 on the frame after the hit, so it wraps after 29 frames and control + // returns on the 30th (player_state_exit). knockT is set on the hit frame and counted down at its end too. + var START_T = 9, SLIDE_T = 13, KNOCK_T = 30, IFRAMES = 0x6F, HW = 7, HH = 11, BODY_HW = 8, BODY_HH = 12; + // Thunder Beam crawl chain (thunder_flight, tables $A5A9 x / $A5B1 y / $A5B9 next anim): when a forward piece's + // 10-frame animation wraps it jumps ahead and changes shape; row = animation - $62. Half sizes from $FAB5/$FB83. + MM.PLAYER_BOLT = { jx: [28, 32, 32, 28, 24, 28, 28, 28], jy: [-4, -24, 0, 28, 16, -12, -4, -4], + next: [5, 6, 7, 1, 2, 3, 4, 5], hw: [4, 8, 4, 4, 4, 8, 8, 4], hh: [8, 4, 8, 8, 8, 4, 4, 8] }; + // records 6-$0A (dx, dy) and the frames until the first wrap: start frames $40,$30,$20,$10,$01 stagger it + var THUNDER = [[16, -4, 2], [20, 8, 4], [24, -4, 6], [32, -20, 8], [40, -20, 9]]; + // Fire Storm shield orbit ($A4FA y / $A502 x): offset index = frames since the shot & 7, gone at 32 + var ORBIT_Y = [20, 14, 0, -14, -20, -14, 0, 14], ORBIT_X = [0, -14, -20, -14, 0, 14, 20, 14]; + // spread_shot_spawn rows 0..11 ($F88A-$F8BA), shared by the boss bomb's shrapnel and the Hyper Bomb's flames: + // [X speed, Y speed (+ = up), facing right ($40 in $F8BA)] + var D = fx(0x160); + MM.SPREAD = [[0, 2, 0], [2, 0, 1], [0, -2, 0], [2, 0, 0], [D, D, 1], [D, -D, 1], [D, -D, 0], [D, D, 0], + [0, fx(0xC0), 0], [fx(0xC0), 0, 1], [0, -fx(0xC0), 0], [fx(0xE0), 0, 0]]; + // Hyper Bomb: record $0D (anim $5D, Y 03.00, X 01.80, dy -4, dx +12); bomb_flight bursts at $61 = $92, cleans up at $A0 + var BOMB_FUSE = 0x92, BOMB_END = 0xA0; + // the quake's stun is special state 2 (anim $13, rate $57 = 48 frames from frame byte 1): 47 frames without control, moving + // backwards at 00.20 (row 1 of $9DE6), with Y velocity 00.E0 re-applied at frame bytes $01, $21, $41 (stunT 47, 31, 15) + var STUN_T = 47, STUN_VY = fx(0xE0); + // Super Arm: block half size by stage ($A888: anim $6C 16 x 16 for Cut Man, $32 14 x 14 for Guts Man); thrown block + // (record 3) Y 03.00, X 03.A0, dy -16, dx +16; chunks ($F826-$F832: x, y, X speed, Y speed), half size 4 x 4 + var BLOCK_HALF = { 'megaman/cut_man': 16, 'megaman/guts_man': 14 }, THROW_VX = fx(0x3A0), THROW_VY = 3, ARM_LIFT = 26; + var CHUNKS = [[8, 8, 4, 2], [24, 8, 4, 0], [8, 24, 3, 2], [24, 24, 3, 0]]; + + function MegaMan() {} + var P = MegaMan.prototype; + P.id = 'megaman'; + P.keys = { left: 'A', right: 'D', up: 'W', down: 'S', jump: 'Space', fire: 'J|LMB', prev: 'Q', next: 'E' }; + P.NAIL = 0; P.HITSTOP = 0; P.slashFacing = 1; + P.manual = [ + 'A/D move left and right (9 slow startup frames and 13 frames of sliding after release, as in the NES original). Space jumps; hold it to jump higher. Releasing while rising immediately slows the ascent', + 'J or left mouse button fires one shot per press; at most three Arm Gun shots can be on screen. The first game has neither sliding nor charged shots', + 'Q/E cycles acquired special weapons (Returning Blade / Pierce Dart / Fuse Lob / Orbit Guard / Tri Arc / Rock Throw). Each shot costs one energy unit, except Fuse Lob and Rock Throw, which cost two; each weapon has 28 units. You cannot switch while a timed bomb or rock remains active', + 'Rock Throw: face a nearby rock and press fire to lift it, then press again to throw it (only the Blade Tosser and Quake Hurler rooms contain rocks). When Quake Hurler lands, grounded players are stunned for about 0.8 seconds; jump to avoid it', + 'Health: 28 units (504 points). Taking damage causes 0.5 seconds of knockback and 1.85 seconds of flashing invulnerability. Defeat a boss to acquire its weapon; bosses have weapon weaknesses' + ]; + P.reset = function (c) { + var o = c.options || {}, self = this; + // entry position: in the original it depends on how the player walked through the boss door; here the seed + // picks it (28..68 px), which also makes the RNG-free Ice Man and Fire Man fights differ between seeds + this.room = MM.roomOf(c.id); + this.x = 28 + c.rng.int(41); this.y = MM.FLOOR - BODY_HH; this.vy = 0; this.facing = 1; this.grounded = true; + if (this.room.length) this.y = MM.floorUnder(this.room, this.x - 7, this.x + 7, 0) - BODY_HH; // walked in onto the step + this.speed = 0; this.walkT = 0; this.slideT = 0; this.airHeld = false; + this.max_hp = this.hp = MM.BAR * MM.UNIT; + this.iframes = 0; this.knockT = 0; this.knockDir = 0; this.shootT = 0; this.stunT = 0; this.airHit = false; this.blockTarget = null; this.blocksGone = []; + this.weapons = MM.loadout(o); this.weapon = 'P'; this.energy = {}; + this.weapons.forEach(function (w) { if (w !== 'P') self.energy[w] = MM.BAR; }); + this.shots = []; this.nextShot = 1; this.shieldN = 0; + this.prev = {}; this.fired = false; this.anyInput = false; this.hits = 0; this.slashHits = {}; + }; + P.hurtBox = function () { return MM.box(this.x, this.y, HW, HH); }; + P.box = P.hurtBox; + P.centre = function () { return { x: this.x, y: this.y }; }; + P.slashBox = function () { return null; }; + P.onSlashContact = function () {}; + + // weapon menu (bank 6 weapon_menu_main): MM1 switches in the SELECT menu, which freezes the world and hides + // entity slot 5 (STA $0605 = F8: the special-weapon slot); Buster shots in slots 2-4 and the other pieces keep + // flying. Here Q/E switch instantly with the same effect on the shots. + P.cycle = function (step) { + var i = this.weapons.indexOf(this.weapon), n = this.weapons.length; + if (n < 2) return; + if (this.count('hyper_bomb') || this.count('hyper_flame') || this.blockOut()) return; // main_select: no menu while $60 is set + this.weapon = this.weapons[(i + step + n) % n]; + // slot 5 is hidden by the menu; the Fire Storm shield (slot 6) loses its orbit service and would hang in + // place forever in the original (an orphan that also blocks the Thunder Beam) - it is dropped here instead + this.shots = this.shots.filter(function (s) { return s.slot !== 5 && s.kind !== 'fire_shield'; }); + }; + // shot_collision_service ($A261) tests the slot range of the CURRENT weapon, whatever occupies it: Buster 2-4, + // Ice 5, Fire 5-6, Thunder 5-11; damage is looked up for the current weapon. A shot left over from another + // weapon outside that range flies on harmlessly. + var HIT_SLOTS = { P: [2, 4], C: [5, 5], I: [5, 5], F: [5, 6], E: [5, 11], G: [5, 7] }; + P.collides = function (s) { + if (this.weapon === 'B') return s.kind === 'hyper_flame'; // shotcoll_bomb: only the explosion window + if (s.kind === 'held_block') return false; // flags $24: bit 5 keeps it out of the collision + if (s.kind === 'block_chunk') return s.slot <= 7; // shotcoll_guts, and thunder_spent after a beam broke a block + var r = HIT_SLOTS[this.weapon]; return s.slot >= r[0] && s.slot <= r[1]; }; + P.spendable = function (w) { return w === 'P' || (this.energy[w] || 0) >= MM.WEAPONS[w].cost; }; + P.spend = function (w) { if (w !== 'P') this.energy[w] = Math.max(0, this.energy[w] - MM.WEAPONS[w].cost); }; + P.count = function (kind) { var n = 0; this.shots.forEach(function (s) { if (s.kind === kind) n++; }); return n; }; + P.slotUsed = function (slot) { return this.shots.some(function (s) { return s.slot === slot; }); }; + P.addShot = function (s) { s.id = this.nextShot++; s.dir = this.facing; s.vy = s.vy || 0; s.age = 0; this.shots.push(s); return s; }; + // $60 "a shot is out" stays set until every player-shot slot (2-15) is empty (shots_gone_check); the Thunder + // Beam's fire handler refuses while it is set, so even a Buster shot still on screen blocks it + P.shotOut = function () { return this.shots.length > 0; }; + P.blockOut = function () { return this.count('held_block') > 0 || this.count('thrown_block') > 0 || this.count('block_chunk') > 0; }; + + // fire_weapon ($A71E) and the per-weapon fire handlers ($A999 spawn records: slot, offset, velocity) + P.fire = function (c) { + var w = this.weapon, f = this.facing, x = this.x, y = this.y, self = this; + if (!this.spendable(w)) return; + if (w === 'P') { + var free = [2, 3, 4].filter(function (k) { return !self.slotUsed(k); })[0]; + if (!free) return; // three shots out + this.addShot({ kind: 'buster', w: 'P', slot: free, x: x + 16 * f, y: y, vx: 4 * f, hw: 4, hh: 4, pierce: false }); + c.emit('mm_shot', x + 16 * f, y); + } else if (w === 'E') { + if (this.shotOut()) return; // one beam at a time + THUNDER.forEach(function (r, i) { // records 6-$0A -> slots 5-9 + self.addShot({ kind: 'thunder', w: 'E', slot: 5 + i, x: x + r[0] * f, y: y + r[1], vx: AIR * f, row: i, t: r[2], + hw: MM.PLAYER_BOLT.hw[i], hh: MM.PLAYER_BOLT.hh[i], pierce: true }); + }); + this.addShot({ kind: 'thunder_v', w: 'E', slot: 10, x: x + 16 * f, y: y - 16, vx: 0, vy: 6, hw: 8, hh: 16, pierce: true }); + this.addShot({ kind: 'thunder_v', w: 'E', slot: 11, x: x + 16 * f, y: y + 16, vx: 0, vy: -6, hw: 8, hh: 16, pierce: true }); + this.spend(w); c.emit('mm_thunder', x, y); + } else if (w === 'I') { + if (this.slotUsed(5)) return; // record 5 needs slot 5 + this.addShot({ kind: 'slasher', w: 'I', slot: 5, x: x + 16 * f, y: y, vx: 4 * f, hw: 8, hh: 8, pierce: true }); + this.spend(w); c.emit('mm_slasher', x, y); + } else if (w === 'F') { + if (this.slotUsed(5)) return; // the wave (record 0) needs slot 5 + this.addShot({ kind: 'fire_wave', w: 'F', slot: 5, x: x + 16 * f, y: y, vx: 4 * f, hw: 8, hh: 8, pierce: true }); + if (!this.slotUsed(6)) this.addShot({ kind: 'fire_shield', w: 'F', slot: 6, x: x, y: y - 20, vx: 0, hw: 8, hh: 8, pierce: true }); + this.shieldN = 0; this.spend(w); c.emit('mm_fire', x, y); // re-firing restarts the 32-frame shield + } else if (w === 'C') { + if (this.shotOut()) return; // single_shot_gate: $60; record $0E, kick 02.80 + this.addShot({ kind: 'cutter', w: 'C', slot: 5, x: x + 12 * f, y: y - 4, vx: 2 * f, vy: 2, hw: 8, hh: 8, pierce: true, n: 0, ret: 0, kick: 0x280 }); + this.spend(w); c.emit('mm_cutter', x, y); + } else if (w === 'B') { + if (this.shotOut()) return; // single_shot_gate: $60 + this.addShot({ kind: 'hyper_bomb', w: 'B', slot: 5, x: x + 12 * f, y: y - 4, vx: fx(0x180) * f, vy: 3, hw: 8, hh: 8, pierce: true, fuse: 0, bounces: 3 }); + this.spend(w); c.emit('mm_hyper_bomb', x, y); + } else if (w === 'G') { // fire_super_arm + var held = this.shots.filter(function (s) { return s.kind === 'held_block'; })[0]; + if (!held) { // lifting costs nothing and has no firing pose + if (this.shotOut() || !this.blockTarget) return; + this.takeBlock(c, this.blockTarget); + this.addShot({ kind: 'held_block', w: 'G', slot: 5, x: x + 16 * f, y: y - 16, vx: 0, hw: BLOCK_HALF[c.id], hh: BLOCK_HALF[c.id], pierce: true, n: 0 }); + c.emit('mm_lift', x, y); + return; + } + this.shots = this.shots.filter(function (s) { return s !== held; }); // the throw replaces it, and only the throw costs energy + this.addShot({ kind: 'thrown_block', w: 'G', slot: 5, x: x + 16 * f, y: y - 16, vx: THROW_VX * f, vy: THROW_VY, hw: held.hw, hh: held.hh, pierce: true, n: 0 }); + this.spend(w); c.emit('mm_throw', x, y); + } + this.shootT = 15; + }; + + // horizontal speed (player_hspeed $9CE7 with the anim -> speed rows $9DDD/$9DE6): the walk-start anim $03 runs + // 9 frames at 00.20, then the walk anim $06 at 01.60. On the release frame the speed of the current anim still + // applies; releasing from $06 starts the stop-step anim $0C (13 more frames at 00.80), from $03 he just stands. + P.walk = function (dx) { + var was = this.prev.left || this.prev.right; + if (this.grounded) { + if (dx) { + if (!was) this.walkT = 0; // from a stop or mid-slowdown: start-up + this.facing = dx; this.slideT = 0; + this.speed = this.walkT < START_T ? START : WALK; this.walkT++; + } else if (was) { // release frame: the current anim's speed + this.speed = this.walkT >= START_T ? WALK : START; + this.slideT = this.walkT >= START_T ? SLIDE_T : 0; this.walkT = 0; + } else if (this.slideT > 0) { this.speed = SLIDE; this.slideT--; } + else this.speed = 0; + this.airHeld = !!dx; + } else { + if (dx) { this.facing = dx; this.speed = this.airHeld ? AIR : START; this.airHeld = true; } + else { this.speed = 0; this.airHeld = false; } + this.slideT = 0; this.walkT = dx ? START_T + 1 : 0; // landing with the d-pad held keeps full walk speed + } + this.moveX(this.speed * this.facing); + }; + P.moveX = function (v) { + var nx = this.x + v, lo = MM.WALL_L + BODY_HW, hi = MM.WALL_R - BODY_HW; + nx = nx < lo ? lo : nx > hi ? hi : nx; + if (this.room.length) nx = MM.clampX(this.room, this.x, nx, BODY_HW, this.y, BODY_HH); + this.x = nx; + }; + // vertical_collision for the player; returns true on the frame it lands + P.fall = function () { + var ny = this.y - this.vy, air = !this.grounded; + var floor = this.room.length ? MM.floorUnder(this.room, this.x - 7, this.x + 7, this.y + BODY_HH) : MM.FLOOR; + if (this.vy <= 0 && ny + BODY_HH >= floor) { this.y = floor - BODY_HH; this.vy = 0; this.grounded = true; return air; } + this.y = ny; this.grounded = false; + this.vy = Math.max(-MM.FALL_MAX, this.vy - MM.GRAVITY); + return false; + }; + + P.update = function (c, i) { + var p = this.prev, dx = (i.right ? 1 : 0) - (i.left ? 1 : 0), landed = false, exit = this.exitKnock; + this.fired = false; this.exitKnock = false; + this.anyInput = !!(i.left || i.right || i.up || i.down || i.jump || i.fire || i.prev || i.next); + if (c.boss.intro > 0 || this.hp <= 0) { this.prev = {}; this.fall(); this.flight(c); return; } // input locked + this.fired = !!i.fire && !p.fire; // p1_new_presses & B: bosses read it even in knockback + if (i.prev && !p.prev) this.cycle(-1); + if (i.next && !p.next) this.cycle(1); + if (exit) this.prev = { jump: p.jump, fire: p.fire }; // player_state_exit clears p1_prev_buttons this frame only + if (this.knockT > 0) { // special state 3: knockback, no control + this.moveX(KNOCK * this.knockDir); + this.speed = 0; this.walkT = 0; this.slideT = 0; this.airHeld = false; + landed = this.fall(); + } else if (this.stunT > 0) { // special state 2 (the quake): no control, drifts backwards + if ((this.stunT & 15) === 15) { this.vy = STUN_VY; this.grounded = false; } + this.moveX(-START * this.facing); + this.speed = 0; this.walkT = 0; this.slideT = 0; this.airHeld = false; + landed = this.fall(); + } else { + this.walk(dx); + if (this.fired) this.fire(c); + if (this.vy < 0 || this.grounded) { // falling or standing: land first, then the jump check + landed = this.fall(); + if (this.grounded && i.jump && !p.jump) { this.vy = JUMP; this.grounded = false; c.emit('mm_jump', this.x, this.y); } + } else { // rising: step, then releasing jump feathers the rise + this.fall(); + if (!this.grounded && !i.jump && this.vy >= 2) this.vy = 1; // player_fall_cap + } + } + if (landed) c.emit('mm_land', this.x, MM.FLOOR); + this.flight(c); + this.prev = { left: !!i.left, right: !!i.right, up: !!i.up, down: !!i.down, jump: !!i.jump, fire: !!i.fire, prev: !!i.prev, next: !!i.next }; + }; + + // weapon flight services, run before the boss AI ($A35C, dispatched by the CURRENT weapon): Thunder Beam crawl + // jumps (thunder_flight; pieces left over after a switch only drift), Fire Storm shield orbit + // (fire_storm_flight: INC the timer, drop the shield at 32, else orbit at offset timer & 7) + P.flight = function (c) { + var self = this, T = MM.PLAYER_BOLT; + this.hyperFlight(); + this.cutterFlight(); + this.armFlight(); + if (this.count('fire_shield') && ++this.shieldN === 32) { + this.shots = this.shots.filter(function (s) { return s.kind !== 'fire_shield'; }); + } + this.shots.forEach(function (s) { + if (s.kind === 'thunder' && s.t <= 0 && self.weapon === 'E') { + s.x += T.jx[s.row] * s.dir; s.y += T.jy[s.row]; s.row = T.next[s.row]; s.hw = T.hw[s.row]; s.hh = T.hh[s.row]; s.t = 10; + } else if (s.kind === 'fire_shield') { + var k = self.shieldN & 7; s.x = self.x + ORBIT_X[k]; s.y = self.y + ORBIT_Y[k]; + } + }); + this.thunderBlocks(c); + }; + + // guts_flight / guts_block_detect: the held block settles for one frame, then floats 26 px over the player. With no + // shot out the Super Arm probes one tile ahead at the player's y (+8 facing right, -9 facing left) for a liftable block. + // guts_thrown: while the throw's $61 runs from $10 to $1F, an airborne player takes the firing pose $6F, one count per frame. + P.armFlight = function () { + if (this.weapon !== 'G') return; + var s = this.shots.filter(function (q) { return q.kind === 'held_block'; })[0]; + if (s) { + if (!s.n) { s.n = 1; return; } + s.x = this.x; s.y = this.y - ARM_LIFT; s.dir = this.facing; + return; + } + if (!this.grounded && this.knockT === 0 && this.stunT === 0) this.shots.forEach(function (q) { if (q.kind === 'thrown_block' && q.n < 15) q.n++; }); + if (this.shotOut()) return; + this.blockTarget = MM.blockAt(this.room, Math.floor(this.x) + (this.facing > 0 ? 8 : -9), Math.floor(this.y)); + }; + // the record becomes type 4: the block is gone for the rest of the fight, for the player and the boss alike + P.takeBlock = function (c, block) { + var rest = function (r) { return r.x0 !== block.x0; }; + this.room = this.room.filter(rest); c.boss.room = c.boss.room.filter(rest); + this.blocksGone.push(block.x0); this.blockTarget = null; + }; + // guts_block_shatter: 4 chunks in slots 5-8 around (x0, y0), the facing of slot 5, slots 9-$F cleared. Chunks move straight + // without tile collision, and pierce: only the block itself breaks on a hit. + P.placeChunks = function (x0, y0, dir, keep) { + var self = this; + this.shots = this.shots.filter(keep); + CHUNKS.forEach(function (r, i) { + self.shots.push({ kind: 'block_chunk', w: 'G', slot: 5 + i, x: x0 + r[0], y: y0 + r[1], vx: r[2] * dir, vy: r[3], hw: 4, hh: 4, pierce: true, + id: self.nextShot++, dir: dir, age: 0 }); + }); + }; + // block_impact_shatter: the fragments start 16 px up-left of the impact + P.blockShatter = function (c, s) { + this.placeChunks(s.x - 16, s.y - 16, s.dir, function (q) { return q !== s; }); + c.emit('mm_block_shatter', s.x, s.y); + }; + // thunder_block_scan: every frame the live beam pieces of one parity probe the override records; a liftable block under one + // breaks (guts_block_pickup), which ends the beam: the chunks take slots 5-8, slots 9-$F are cleared + P.thunderBlocks = function (c) { + if (this.weapon !== 'E' || !this.room.length || (!this.count('thunder') && !this.count('thunder_v'))) return; + var hit = null, self = this; + for (var slot = 5 + (c.t & 1); slot < 12 && !hit; slot += 2) { + this.shots.forEach(function (s) { + if (hit || s.slot !== slot) return; + var b = MM.blockAt(self.room, Math.floor(s.x), Math.floor(s.y)); + if (b) hit = b; + }); + } + if (!hit) return; + this.takeBlock(c, hit); + var five = this.shots.filter(function (q) { return q.slot === 5; })[0]; // the chunks take slot 5's facing + this.placeChunks(hit.x0, hit.y0, five ? five.dir : this.facing, function (q) { return q.slot < 5 || q.slot > 11; }); + c.emit('mm_block_shatter', hit.x0 + 16, hit.y0 + 16); + }; + + // cutter_flight: 42 frames out with Y velocity falling 00.1A per frame, then it homes on the player at 02.80 + 0.08 + // per frame, caught within 12 px on both axes; the throw kick (02.80, -0.20 per frame) comes off the Y velocity. The + // service is dispatched by the current weapon, and a switch removes slot 5, so only the Cutter selected reaches here. + P.cutterFlight = function () { + var s = this.shots.filter(function (q) { return q.kind === 'cutter'; })[0]; + if (!s) return; + if (s.n < 0x2A) { s.n++; s.vy -= fx(0x1A); return; } + if (s.n === 0x2A) { s.n++; s.ret = 0x280; } + var dx = Math.floor(this.x) - Math.floor(s.x), adx = Math.abs(dx); + s.ret += 8; + var v = MM.propVel(s.ret, adx, Math.floor(s.y) - Math.floor(this.y)); + s.vx = v.vx * (dx >= 0 ? 1 : -1); s.vy = v.vy; s.dir = dx >= 0 ? 1 : -1; + if (v.ady < 12 && adx < 12) { s.dead = true; this.shots = this.shots.filter(function (q) { return q !== s; }); return; } + if (s.kick) { s.kick -= 0x20; s.vy -= s.kick / 256; } + }; + + // bomb_flight: the fuse ($61) counts from the firing frame; at $92 slot 5 becomes 12 flames in slots 2-13 (row 11 + // first), which fly straight and are cleared at $A0. The counter lives on the shots, so fights without the bomb + // keep exactly the same state. + P.hyperFlight = function () { + var burst = null; + this.shots.forEach(function (s) { + if (s.kind !== 'hyper_bomb' && s.kind !== 'hyper_flame') return; + s.fuse++; + if (s.kind === 'hyper_bomb' && s.fuse === BOMB_FUSE) burst = s; + }); + if (burst) { + this.shots = this.shots.filter(function (s) { return s !== burst; }); + for (var row = 11; row >= 0; row--) { + var r = MM.SPREAD[row], dir = r[2] ? 1 : -1; + this.shots.push({ kind: 'hyper_flame', w: 'B', slot: 13 - row, x: burst.x, y: burst.y, vx: r[0] * dir, vy: r[1], hw: 8, hh: 8, pierce: false, + fuse: BOMB_FUSE, id: this.nextShot++, dir: dir, age: 0 }); + } + } + if (this.count('hyper_flame')) this.shots = this.shots.filter(function (s) { return s.kind !== 'hyper_flame' || s.fuse < BOMB_END; }); + }; + // entity_pass + react_bubble for the fused bomb: tile collision and gravity. A wall only pushes it out; each landing + // halves the X speed and bounces with Y speed n.n while the counter $62 (3) runs down to 0. + P.hyperMove = function (s) { + var lo = MM.WALL_L + s.hw, hi = MM.WALL_R - s.hw, room = this.room; + s.x = Math.min(hi, Math.max(lo, s.x + s.vx)); s.age++; + if (room.length) s.x = MM.clampX(room, s.x - s.vx, s.x, s.hw, s.y, s.hh); + var ny = s.y - s.vy, floor = room.length ? MM.floorUnder(room, s.x - s.hw + 1, s.x + s.hw - 1, s.y + s.hh) : MM.FLOOR; + if (s.vy < 0 && ny + s.hh >= floor) { + var n = s.bounces; s.y = floor - s.hh; s.vy = n + n / 256; if (n > 0) s.bounces--; + s.vx = (s.vx < 0 ? -1 : 1) * Math.floor(Math.abs(s.vx) * 128) / 256; + return; + } + s.y = ny; s.vy = Math.max(-MM.FALL_MAX, s.vy - MM.GRAVITY); + }; + + // entity_pass for the thrown block (flags $15: tile collision, gravity): a wall or the floor shatters it; at the top of the + // screen a rising block only slows down, a falling one vanishes (react_floater) + P.blockMove = function (c, s) { + var lo = MM.WALL_L + s.hw, hi = MM.WALL_R - s.hw, room = this.room, nx = s.x + s.vx, stop = false; + s.age++; + if (nx < lo) { nx = lo; stop = true; } else if (nx > hi) { nx = hi; stop = true; } + if (room.length) { var cx = MM.clampX(room, s.x, nx, s.hw, s.y, s.hh); if (cx !== nx) { nx = cx; stop = true; } } + s.x = nx; + if (stop) { this.blockShatter(c, s); return; } + var ny = s.y - s.vy, floor = room.length ? MM.floorUnder(room, s.x - s.hw + 1, s.x + s.hw - 1, s.y + s.hh) : MM.FLOOR; + if (ny < MM.TOP_EXIT) { if (s.vy < 0) s.dead = true; else s.vy -= MM.GRAVITY; return; } + if (s.vy < 0 && ny + s.hh >= floor) { s.y = floor - s.hh; this.blockShatter(c, s); return; } + s.y = ny; s.vy = Math.max(-MM.FALL_MAX, s.vy - MM.GRAVITY); + }; + + // ---- the part of the tick after the boss AI (arena.js lists the order) ---- + P.resolveInteractions = function (c) { + var b = c.boss, j; + if (this.iframes > 0) this.iframes--; + if (b.fight && this.hp > 0 && b.hp > 0) { + // player contact (player_contact_service $A18B): boss body every frame, boss shots by slot parity + var hb = this.hurtBox(); + if (this.iframes === 0 && MM.overlap(b.hitBox(), hb)) this.hurt(c, b.contactDamage(), b.dir, b.id + '_body'); + else if (this.iframes === 0) { + for (j = 0; j < b.projectiles.length; j++) { + var q = b.projectiles[j]; + if (q.harmless || (q.slot & 1) !== (c.t & 1)) continue; + if (MM.overlap(q, hb)) { this.hurt(c, q.dmg, q.dir, q.kind); break; } + } + } + // shots vs boss ($C8B2): only the current weapon's slots, skipped while the boss blinks; the damage row is + // the CURRENT weapon (current_weapon indexes $FDEE); a non-piercing shot is consumed by a hit + for (j = 0; j < this.shots.length && b.hp > 0 && this.hp > 0; j++) { + var s = this.shots[j]; + if (b.iframes > 0 || s.dead || !this.collides(s)) continue; + if (MM.overlap(b.hitBox(), s)) { + b.takeHit(c, this.weapon, s.x, s.y); if (!s.pierce) s.dead = true; + if (s.kind === 'thrown_block') { this.blockShatter(c, s); break; } // gutscoll_hit: the service ends here + } + } + } + // entity pass: player shots drift and leave the screen; the boss moves its own projectiles + var self = this; + this.shots.forEach(function (s) { + if (s.dead || s.kind === 'fire_shield') return; + if (s.kind === 'hyper_bomb') { self.hyperMove(s); return; } + if (s.kind === 'held_block') return; + if (s.kind === 'thrown_block') { self.blockMove(c, s); return; } + s.x += s.vx; s.y -= s.vy; s.age++; + if (MM.offscreen(s)) s.dead = true; + }); + this.shots = this.shots.filter(function (s) { return !s.dead; }); + b.entityPass(c); + // render-time counters: animation timers and poses, the boss's blink + this.shots.forEach(function (s) { if (s.kind === 'thunder') s.t--; }); + if (this.shootT > 0) this.shootT--; + if (this.knockT > 0 && --this.knockT === 0) this.exitKnock = true; + if (this.stunT > 0 && --this.stunT === 0) this.exitKnock = true; + b.renderTick(c); + }; + + P.hurt = function (c, dmg, fromDir, kind) { + if (this.iframes > 0 || this.hp <= 0 || !(dmg > 0)) return false; + this.hp = Math.max(0, this.hp - dmg); this.hits++; + c.events.push({ t: c.t, name: 'hurt_by', by: kind }); + if (this.hp <= 0) { this.knockT = 0; this.stunT = 0; this.shots = []; this.shieldN = 0; c.emit('mm_player_dead', this.x, this.y); return true; } + if (this.stunT > 0 && c.boss.shake > 0) { // the NMI rewrites the state to 2 this very frame: anim $13 never changed, so no knockback starts + if (fromDir) this.facing = -fromDir; + this.iframes = IFRAMES; c.emit('mm_hurt', this.x, this.y); + return true; + } + this.stunT = 0; + this.airHit = !this.grounded && !!c.boss.shake; // anim $09 still reads airborne to this frame's NMI: the stun comes one frame later + this.knockDir = fromDir || -this.facing; this.facing = -this.knockDir; + this.knockT = KNOCK_T; this.iframes = IFRAMES; this.speed = 0; this.walkT = 0; this.slideT = 0; + this.vy = KNOCK_VY; this.grounded = false; + c.emit('mm_hurt', this.x, this.y); + return true; + }; + + // The quake (nmi_shake_palette, one call per shake_timer frame at the end of the tick, Guts Man's renderTick): the player + // is forced into special state 2 unless his anim is $09 or $6F, the airborne poses. Knockback is anim $12, so it is + // overwritten, including its last frame (the state exit only runs next frame). An already stunned player does not restart. + P.quake = function () { + if (this.hp <= 0 || this.stunT > 0) return; + if (this.airHit) { this.airHit = false; return; } + if (!this.grounded && this.knockT === 0 && !this.exitKnock) return; + this.stunT = STUN_T; this.knockT = 0; this.exitKnock = false; + }; + + // the player's jump/fall pose anim $09 (player_air_pose); Cut Man reads it. Knockback is anim $12, and for the first + // 15 frames of a thrown Cutter or Hyper Bomb an airborne player is in the firing variant $6F; Buster shots keep $09 + P.airPose = function () { + if (this.grounded || this.knockT > 0 || this.stunT > 0) return false; + return !this.shots.some(function (s) { return (s.kind === 'cutter' && s.n < 0x0F) || (s.kind === 'hyper_bomb' && s.fuse < 0x0F) || (s.kind === 'thrown_block' && s.n < 0x0F); }); + }; + + P.state = function () { + var o = { x: this.x, y: this.y, vy: this.vy, facing: this.facing, grounded: this.grounded, + speed: this.speed, walk_t: this.walkT, slide_t: this.slideT, air_held: this.airHeld, + hp: this.hp, max_hp: this.max_hp, iframes: this.iframes, knock_t: this.knockT, knock_dir: this.knockDir, + shoot_t: this.shootT, weapon: this.weapon, weapons: this.weapons, energy: this.energy, + shots: this.shots, next_shot: this.nextShot, shield_n: this.shieldN, previous: this.prev, + fired: this.fired, any_input: this.anyInput, hits: this.hits }; + // only while they differ from their initial values, so fights without a quake or the Super Arm keep the same state hash + if (this.stunT) o.stun_t = this.stunT; + if (this.blockTarget) o.block_target = this.blockTarget.x0; + if (this.blocksGone.length) o.blocks_gone = this.blocksGone; + return MM.snapshot(o); + }; + B.MegaMan = MegaMan; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/bosses/bomb_man.js b/environments/games/web/games/megaman_remake/bosses/bomb_man.js new file mode 100644 index 0000000000000000000000000000000000000000..fca257b6b6c93bd927a3afdd5a5776eb86d88864 --- /dev/null +++ b/environments/games/web/games/megaman_remake/bosses/bomb_man.js @@ -0,0 +1,162 @@ +// Bomb Man (game mode 2, fixed bank $DFF0). Port of the original 18-state table $E0ED: +// jump_pick face the player, rng & 1 picks jump variant 0 (big leap toward, 02.90 / 07.60) or 1 (hop toward, +// 01.09 / 05.B0) from $E03B; the variant's state number sends the table to walk_idle at index 8 or 17 +// walk_idle fly the jump; landing stops him (X speed 0) -> pattern_roll +// pattern_roll random_mod 6 walks the table back: r odd -> 3 bombs, r 0/4 -> 2, r 2 -> 1 +// throw / land_throw a 15-frame windup ($0641 = $1F: draw_entity counts the low nibble), then a bomb; the next windup waits until the bomb burst +// wait_bomb wait for the last bomb; the second set (index 10) then leap_away: turn away, variant 2 (01.09/05.B0) +// guard during pattern_roll / land_throw / throw, the player within 48 px aborts the state and jumps at once +// Boss bomb (record 0): anim $27 8x8, gravity, X speed (|dx| - 24) / 51, Y 05.B0, dy -11, dx +8 along his look. +// It bursts on the floor or a wall into 12 shrapnel pieces ($F88A-$F8BA, no gravity, no tile collision); a piece +// flies 7-8 frames, turns into dust (still harmful) for 7 more and vanishes. Player shots pass through bombs and +// pieces (no flag bit 2); touching a bomb hurts but does not set it off. Bomb Man has no hit reaction. +// Tier knobs (specs/bomb_man.yaml): hp, bomb/shrapnel damage, contact damage, windup frames. +(function (g) { + var B = g.BB, BB = B, MM = B.MM, RM = MM.RobotMaster, fx = MM.fx; + // $E03B variant table: table index after the jump (state - 5), X speed, Y speed + var VARIANTS = [[8, fx(0x290), fx(0x760)], [17, fx(0x109), fx(0x5B0)], [8, fx(0x109), fx(0x5B0)]]; + var SEQ = ['jump_pick', 'wait_bomb', 'throw', 'land_throw', 'throw', 'land_throw', 'throw', 'pattern_roll', 'walk_idle', + 'leap_away', 'wait_bomb', 'throw', 'land_throw', 'throw', 'land_throw', 'throw', 'pattern_roll', 'walk_idle']; + var GUARD = 0x30, LEAD = 0x18, DIV = 0x33, BOMB_VY = fx(0x5B0); + // the shrapnel uses the spread_shot_spawn rows MM.SPREAD (body_megaman.js); the facing also sets a hit's knockback + // anim $39 (9 one-tick frames) starts at frame 1 and wraps to 0 after 8 renders: the pass that sees frame 0 turns + // it into dust $54 (8 one-tick frames from 0), which wraps after 8 more renders and is removed. A piece moves once + // per pass: 7 steps as shrapnel (8 if its slot comes after the bomb's, so the burst pass moves it too), 7 as dust. + var DUST_AT = 8, GONE_AT = 16; + // drop-in: the boss animation reaches frame byte $3C about 51 frames into the 94-frame intro (anim $1E, 13 ticks + // per frame, started at $01); the type $0C bomb (Y 03.30, dy -20, dx +6, no contact flag) only decorates the intro + var INTRO_BOMB_AT = 51, INTRO_BOMB_LIFE = 27; + + function BombMan() {} + var P = BombMan.prototype; + RM.install(P, 'bomb_man', B.SPECS.bomb_man); + P.reset = function (c) { + this.base(c); this.n = 0; this.variant = -1; this.roll = -1; this.lastDx = 0; + this.jumps = 0; this.leaps = 0; this.guards = 0; this.bombs = 0; this.bursts = 0; + }; + P.onFight = function () { this.n = 0; this.st = SEQ[0]; }; + P.go = function (n) { this.n = n; this.st = SEQ[n]; }; + P.back = function () { this.go(this.n - 1); }; + + // bombman_guard_range: |dx| < $30 resets the table to jump_pick and aborts the caller (PLA PLA) + P.guard = function (c) { + var d = this.lastDx = this.face(c); + if (d >= GUARD) return false; + this.go(0); this.guards++; return true; + }; + P.windupStart = function () { this.back(); this.setPose('windup'); this.windup = Math.round(this.k.windup); }; + P.jump = function (c, v) { + var row = VARIANTS[v]; + this.windup = 0; this.variant = v; this.vx = row[1]; this.vy = row[2]; this.grounded = false; + this.setPose(v === 2 ? 'leap' : 'jump'); this.go(row[0]); + c.emit('mm_jump', this.x, this.y); + }; + + P.update = function (c) { + if (this.hp <= 0) return; + if (this.introTick()) { + if (RM.INTRO - this.intro === INTRO_BOMB_AT) this.spawnBomb(c, 'intro_bomb', this.x + 6 * this.look, this.y - 20, 0, fx(0x330)); + MM.step(this); return; + } + switch (this.st) { + case 'jump_pick': + this.updateFacing(c); this.jumps++; + this.jump(c, c.rng.int(2)); break; + case 'leap_away': + this.updateFacing(c); this.dir = -this.dir; this.leaps++; + this.jump(c, 2); break; + case 'walk_idle': + if (this.walkTick(c)) { this.vx = 0; this.setPose('stand'); this.back(); c.emit('mm_land', this.x, MM.FLOOR); } + break; + case 'pattern_roll': { + if (this.guard(c)) break; + var r = this.roll = c.rng.int(6); + if (r & 1) { this.windupStart(); break; } // 3 bombs + this.go(this.n - 2); + if (!(r & 2)) { this.windupStart(); break; } // r 0 / 4: 2 bombs + this.go(this.n - 2); this.windupStart(); // r 2: 1 bomb + break; + } + case 'land_throw': + if (this.guard(c)) break; + if (this.out === 0) this.windupStart(); + break; + case 'wait_bomb': + if (this.out === 0) this.back(); + break; + case 'throw': { + if (this.guard(c)) break; + if (this.windup > 0) break; + this.back(); + var d = this.lastDx >= LEAD ? this.lastDx - LEAD : this.lastDx; + var vx = Math.floor(d * 256 / DIV) / 256; // divide_16 quotient in 8.8 + if (this.spawnBomb(c, 'bomb', this.x + 8 * this.look, this.y - 11, vx, BOMB_VY)) { this.bombs++; this.setPose('throw'); } + break; + } + } + }; + P.spawnBomb = function (c, kind, x, y, vx, vy) { + var p = this.spawn({ kind: kind, x: x, y: y, dir: this.look, vx: vx, vy: vy, hw: 8, hh: 8, grav: true, + dmg: this.shotDamage(), harmless: kind === 'intro_bomb' }); + if (!p) return null; + this.out++; + if (kind === 'bomb') c.emit('mm_boss_bomb', p.x, p.y); + return p; + }; + // react_boss_bomb: $44--, in the fight the bomb becomes piece 11 in its own slot and pieces 10..0 fill free slots + P.burst = function (c, p) { + this.out = Math.max(0, this.out - 1); + if (!this.fight || p.kind === 'intro_bomb') { p.dead = true; return; } + this.bursts++; + var self = this; + function shard(q, row) { + q.kind = 'shrapnel'; q.row = row; q.vx = MM.SPREAD[row][0]; q.vy = MM.SPREAD[row][1]; q.grav = false; q.age = 0; + q.hw = 8; q.hh = 8; q.dir = MM.SPREAD[row][2] ? 1 : -1; return q; + } + shard(p, 11); + for (var row = 10; row >= 0; row--) { + var q = this.spawn({ x: p.x, y: p.y, dmg: this.shotDamage() }); + if (!q) break; // no free slot: the burst is cut short + shard(q, row); + } + c.emit('mm_boss_burst', p.x, p.y); + }; + // entity_pass over the boss's slots in slot order (pieces spawned into a later slot move in the same pass): + // bombs move x (wall probe, reason 3) then y with gravity (floor probe, reason 4); pieces float straight + P.entityPass = function (c) { + var self = this; + for (var slot = 16; slot < 32; slot++) this.passSlot(c, slot); + this.projectiles = this.projectiles.filter(function (p) { return !p.dead; }); + }; + P.passSlot = function (c, slot) { + var self = this, p = null; + this.projectiles.forEach(function (q) { if (q.slot === slot && !q.dead) p = q; }); + if (!p) return; + (function () { + if (p.kind === 'bomb' || p.kind === 'intro_bomb') { + if (p.kind === 'intro_bomb' && p.age >= INTRO_BOMB_LIFE) { self.burst(c, p); return; } + var nx = p.x + p.vx * p.dir, lo = MM.WALL_L + p.hw, hi = MM.WALL_R - p.hw; + if (nx < lo || nx > hi) { p.x = nx < lo ? lo : hi; self.burst(c, p); return; } + p.x = nx; + var ny = p.y - p.vy; + if (p.vy < 0 && ny + p.hh >= MM.FLOOR) { p.y = MM.FLOOR - p.hh; self.burst(c, p); return; } + p.y = ny; p.vy = Math.max(-MM.FALL_MAX, p.vy - MM.GRAVITY); + return; + } + // shrapnel / dust: the one-shot animation ending (age counts renders since the burst) raises reason 0 + if (p.age === DUST_AT) { p.kind = 'dust'; return; } + if (p.age >= GONE_AT) { p.dead = true; return; } + p.x += p.vx * p.dir; + var y = p.y - p.vy; + if (y < MM.TOP_EXIT || y >= MM.BOTTOM_EXIT || p.x < 0 || p.x >= 256) { p.dead = true; return; } + p.y = y; + })(); + }; + P.state = function () { + return this.baseState({ n: this.n, variant: this.variant, roll: this.roll, last_dx: this.lastDx, jumps: this.jumps, + leaps: this.leaps, guards: this.guards, bombs: this.bombs, bursts: this.bursts }); + }; + B.CASES = B.CASES || {}; + BB.CASES['megaman/bomb_man'] = { title: 'Shard Lobber', Body: B.MegaMan, Boss: BombMan }; + B.BombMan = BombMan; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/bosses/cut_man.js b/environments/games/web/games/megaman_remake/bosses/cut_man.js new file mode 100644 index 0000000000000000000000000000000000000000..472a28d6020afb427d0970f8f4647ed457027cad --- /dev/null +++ b/environments/games/web/games/megaman_remake/bosses/cut_man.js @@ -0,0 +1,193 @@ +// Cut Man (game mode 0, fixed bank $DC8B). Port of the original 21-entry table $DFC0 ( 1.3): +// 5 retarget |dx| >= 64: walk; else jump - unless the player stands at another height (not in the air): chase +// 6 walk 01.20 toward the player; a wall (the step) -> jump +// 7 jump 06.40 up; random_mod 6 picks the landing class 2 (1/2, 32 px past), 1 (1/3, on him), 0 (1/6, 32 px short); +// X speed = (|dx| + $DFED[class]) / 50 with the original's 8-bit sign quirk +// 8/9/$C the frame after take-off: 2 in 3 (cutter home) the pose timer runs and he throws in mid-air +// $A-$D landing branches (a short 04.E0 hop near the player, coin flips) +// $E/$F land, then the throw stance $43: the cutter leaves on its 16th frame +// $10-$17 timed pose / mid-air throw pairs (timers 8, $12, $12, $15) +// $18 chase: stand 63 frames while the player is on another level, then throw +// hit for the first 32 of his 63 blink frames: turn away and hop (01.40 / 01.20), then state $E +// The Rolling Cutter (record 6, 6x6, no tile collision) is aimed at the player at 02.60 (proportional_velocity), turns +// back outside x [24, 232) / y [24, 216), and homes on him at 02.60 + 0.04 per retarget every 4th frame, caught within +// 8 px; one cutter at a time. AI timing reads the boss animation frame byte ($0441), so the animation counter is kept. +// Tier knobs (specs/cut_man.yaml): hp, cutter/contact damage, cutter speed scale, chase wait. +(function (g) { + var B = g.BB, BB = B, MM = B.MM, RM = MM.RobotMaster, fx = MM.fx; + // $DFC0 by seq_step - 5; entry 20 is the forced hit reaction (Y = $28), handled by react() + var SEQ = ['retarget', 'walk', 'jump', 'air_high', 'air_flip', 'descend', 'walk_until_blocked', 'air_land', 'walk_coinflip', + 'land_settle', 'throw_windup', 'timed_pose', 'walk_throw', 'timed_pose', 'walk_throw', 'timed_pose', 'walk_throw', + 'timed_pose', 'walk_throw', 'chase']; + var LAND = [0x08, 0x09, 0x0C], ADJUST = [-0x20, 0, 0x20], AFTER_THROW = [0x0E, 0x0A, 0x05, 0x05]; + // animation rate bytes (advance_anim_counters $D2F8: low nibble = ticks per frame - 1, high nibble = last frame slot) + var RATE = { 0x1B: 0, 0x3F: 0x36, 0x41: 0x00, 0x43: 0x1F, 0x46: 0x18, 0x57: 0x00 }; + var REACT = 0x1F, CUT_SPEED = 0x260, CHASE = 0x3F; + + function CutMan() {} + var P = CutMan.prototype; + RM.install(P, 'cut_man', B.SPECS.cut_man); + var baseRender = P.renderTick; + // the step at the left of the room: tiles x 0-31 and the two liftable blocks x 32-96 (override type 2), top y 160 + MM.blockRoom('megaman/cut_man'); + P.reset = function (c) { + this.base(c); this.seq = 5; this.anim = 0x1B; this.af = 0; this.cut = 0; this.ret = 0; this.timer = 0; + this.jumps = 0; this.throws = 0; this.catches = 0; this.chases = 0; this.reacts = 0; this.lastClass = -1; + }; + P.onFight = function () { this.go(5); }; + P.go = function (n) { this.seq = n; this.st = SEQ[n - 5]; }; + // same height ($0601 == ent_y_px) or the player in the air pose $09: the throw goes ahead; otherwise chase + P.level = function (c) { return Math.floor(this.y) === Math.floor(c.body.y) || c.body.airPose(); }; + P.cutterHome = function () { return this.cut === 0; }; + + P.update = function (c) { + if (this.hp <= 0) return; + if (this.introTick()) { MM.step(this); return; } + this.trackCutter(c); + if (this.iframes >= REACT) { this.react(c); return; } + this[this.st](c); + }; + // ---- the cutter service that runs before the state ---- + P.trackCutter = function (c) { + if (!this.cut) return; + var p = this.projectiles.filter(function (q) { return q.kind === 'rolling_cutter'; })[0]; + if (!p) return; + if (this.cut === 1) { + var px = Math.floor(p.x), py = Math.floor(p.y); + if (py < 0x18 || py >= 0xD8 || px < 0x18 || px >= 0xE8) { + this.cut = 2; p.dir = -p.dir; p.vy = -p.vy; this.ret = Math.round(CUT_SPEED * this.k.speed); + } + return; + } + if (c.t & 3) return; // returning: retarget the boss every 4th frame + var dx = Math.floor(this.x) - Math.floor(p.x); + p.dir = dx >= 0 ? 1 : -1; this.ret += 4; + var v = MM.propVel(this.ret, Math.abs(dx), Math.floor(p.y) - Math.floor(this.y)); + p.vx = v.vx; p.vy = v.vy; + if (v.ady < 8 && Math.abs(dx) < 8) { p.dead = true; this.projectiles = this.projectiles.filter(function (q) { return !q.dead; }); this.cut = 0; this.catches++; } + }; + // record 6 inherits the sprite flip at spawn time; the aim afterwards only sets the speeds (proportional_velocity) + P.throwCutter = function (c) { + var f = this.look, p = this.spawn({ kind: 'rolling_cutter', x: this.x + 8 * f, y: this.y - 10, dir: f, vx: 0, vy: 0, hw: 6, hh: 6, dmg: this.shotDamage() }); + if (!p) return; + var adx = this.face(c), v = MM.propVel(Math.round(CUT_SPEED * this.k.speed), adx, Math.floor(this.y) - 10 - Math.floor(c.body.y)); + p.vx = v.vx; p.vy = v.vy; + this.cut = 1; this.throws++; this.setPose('throw'); + c.emit('mm_boss_cutter', p.x, p.y); + }; + // throw stance: anim $43 without resetting the frame byte (the original leaves $0441 alone) + P.throwStance = function () { this.anim = 0x43; this.vx = 0; this.setPose('stance'); this.go(this.seq + 1); }; + + // ---- states ---- + P.retarget = function (c) { + var n = 6; + if (this.face(c) < 0x40) n = this.level(c) ? 7 : 0x18; + this.go(n); + }; + P.walk = function (c) { + this.updateFacing(c); + if (this.anim !== 0x3F) { this.anim = 0x3F; this.af = 0; this.vx = fx(0x120); this.setPose('walk'); } + this.walkTick(c); + if (this.blocked) this.go(7); else this.retarget(c); + }; + P.jump = function (c) { + this.updateFacing(c); this.anim = 0x41; this.af = 0; this.setPose('jump'); + var r = c.rng.int(6), k = 2; + if (!(r & 1)) { k = 1; if (r & 2) k = 0; } + this.lastClass = k; this.jumps++; + this.go(LAND[k]); this.vy = fx(0x640); this.grounded = false; + var v = (this.face(c) + ADJUST[k]) & 0xFF; + if (v & 0x80) v = (256 - v) & 0xFF; // BPL / EOR #$FF / ADC #1 on the 8-bit sum + this.vx = Math.floor(v * 256 / 50) / 256; // divide_16: X speed = v / 50 in 8.8 + }; + P.walkRandom = function (c) { this.walkTick(c); return c.rng.int(3); }; + P.air_high = function (c) { + var r = this.walkRandom(c); + if (!(r & 1) && this.cutterHome()) { this.go(0x10); this.timer = 8; } else this.go(0x0E); + }; + P.air_flip = function (c) { + var r = this.walkRandom(c); + if (!(r & 1) && this.cutterHome()) { this.go(0x12); this.timer = 0x12; } else this.go(this.seq + 1); + }; + P.air_land = function (c) { + var r = this.walkRandom(c); + if (!(r & 1) && this.cutterHome()) { this.go(0x16); this.timer = 0x15; } else this.go(0x0D); + }; + P.descend = function (c) { + if (!this.walkTick(c)) return; + this.go(this.seq + 1); + if (this.face(c) >= 0x0E) { this.go(5); return; } + if ((c.rng.int(3) & 1) && this.cutterHome()) { this.go(0x14); this.timer = 0x12; } + this.vy = fx(0x4E0); this.vx = fx(0xC0); this.grounded = false; // short hop + }; + P.walk_until_blocked = function (c) { if (this.walkTick(c)) this.go(5); }; + P.walk_coinflip = function (c) { + if (!this.walkTick(c)) return; + if (c.rng.int(2)) this.go(5); else this.go(this.seq + 1); + }; + P.land_settle = function (c) { + if (!this.walkTick(c)) return; + if (!this.cutterHome()) { this.go(5); return; } + if (!this.level(c)) { this.go(0x18); return; } + this.throwStance(); + }; + P.throw_windup = function (c) { + this.walkTick(c); + if (this.af === 0) { this.go(5); return; } + if (this.af === 0x10) this.throwCutter(c); + }; + P.timed_pose = function (c) { + this.walkTick(c); + if (--this.timer > 0) return; + this.anim = 0x43; this.af = 0; this.setPose('stance'); this.go(this.seq + 1); + }; + P.walk_throw = function (c) { + if (this.af === 0) this.anim = 0x41; + else if (this.af === 0x10) this.throwCutter(c); + if (!this.walkTick(c)) return; + if (!this.level(c)) { this.go(0x18); return; } + this.go(AFTER_THROW[(this.seq & 7) >> 1]); + }; + P.chase = function (c) { + if (this.anim !== 0x46) { this.anim = 0x46; this.af = 0; this.timer = Math.round(this.k.wait); this.vx = 0; this.chases++; this.setPose('chase'); } + this.walkTick(c); + var same = Math.floor(this.y) === Math.floor(c.body.y); + if (!same || c.body.airPose()) { + if (this.timer > 0 && --this.timer > 0) return; + } + if (!this.cutterHome()) return; + this.go(0x0E); this.throwStance(); + }; + // boss_anim_hop: the first reaction frame turns away and hops; mode 0 restarts at state $E + P.react = function (c) { + if (this.anim !== 0x57) { + this.anim = 0x57; this.af = 0; this.updateFacing(c); this.dir = -this.dir; + this.vy = fx(0x140); this.vx = fx(0x120); this.grounded = false; this.go(0x0E); this.reacts++; this.setPose('hurt'); + } + this.walkTick(c); + }; + + // entity pass: the cutter flies straight (no gravity, no tile collision) and is removed if it leaves the screen + P.entityPass = function () { + var self = this; + this.projectiles.forEach(function (p) { + p.x += p.vx * p.dir; p.y -= p.vy; + if (MM.offscreen(p)) p.dead = true; + }); + this.projectiles = this.projectiles.filter(function (p) { return !p.dead; }); + }; + // render: the shared counters, then the animation frame byte the AI reads + P.renderTick = function (c) { + baseRender.call(this, c); + var rate = RATE[this.anim] || 0, lo = this.af & 15; + if (lo < (rate & 15)) this.af++; + else this.af = (this.af & 0xF0) >= (rate & 0xF0) ? 0 : (this.af & 0xF0) + 0x10; + }; + P.state = function () { + return this.baseState({ seq: this.seq, anim: this.anim, af: this.af, cutter: this.cut, ret: this.ret, jumps: this.jumps, + throws: this.throws, catches: this.catches, chases: this.chases, reacts: this.reacts, last_class: this.lastClass }); + }; + B.CASES = B.CASES || {}; + BB.CASES['megaman/cut_man'] = { title: 'Blade Tosser', Body: B.MegaMan, Boss: CutMan }; + B.CutMan = CutMan; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/bosses/elec_man.js b/environments/games/web/games/megaman_remake/bosses/elec_man.js new file mode 100644 index 0000000000000000000000000000000000000000..34c82025a5f78f019b7c8cbd1fc79dc0e98ab5e2 --- /dev/null +++ b/environments/games/web/games/megaman_remake/bosses/elec_man.js @@ -0,0 +1,117 @@ +// Elec Man (game mode 4, fixed bank $E434). Port of the original state machine: +// guard walk at 02.00 toward the wall position $E550[step] (176, 128, 48, 128) looking where he goes; +// arriving starts the shot; the player pressing fire (or a wall) makes him leap at once +// halt stop and wind up (15 frames) fire release the Thunder Beam, then wait until it has left +// leap jump 04.00 up / 01.E0 forward toward the player, 1 in 4 a feint away; pressing fire while he is in +// the air makes him wind up and fire in mid-air; landing restarts the pattern +// react for the first 32 of his 63 blink frames after a hit: turn away and hop (01.40 up, 01.20) +// The Thunder Beam (records 7-$0B, 01.50 px/frame) is five pieces that crawl: each time a piece's 10-frame +// animation wraps it jumps ahead and changes shape ($9AF4 x, $9AFC y, $9B04 next; staggered first wraps). +// Tier knobs (specs/elec_man.yaml): hp, beam/contact damage, walk speed, windup, chance to counter a shot. +(function (g) { + var B = g.BB, BB = B, MM = B.MM, RM = MM.RobotMaster, fx = MM.fx; + var WALLS = [0xB0, 0x80, 0x30, 0x80]; + MM.ELEC_BOLT = { jx: [29, 33, 33, 29, 25, 29, 29, 29], jy: [-4, -24, 0, 28, 16, -12, -4, -4], + next: [5, 6, 7, 1, 2, 3, 4, 5], hw: [4, 8, 4, 4, 4, 8, 8, 4], hh: [8, 4, 8, 8, 8, 4, 4, 8] }; + var PIECES = [[20, -4, 2], [24, 8, 4], [28, -4, 6], [36, -20, 8], [44, -20, 9]]; // dx, dy, first wrap + var REACT = 0x1F; + + function ElecMan() {} + var P = ElecMan.prototype; + RM.install(P, 'elec_man', B.SPECS.elec_man); + P.reset = function (c) { this.base(c); this.step = 0; this.leaps = 0; this.feints = 0; this.bolts = 0; this.counters = 0; }; + P.onFight = function () { this.st = 'guard'; }; + + P.fireBolt = function (c) { + var self = this, f = this.look, made = 0; + PIECES.forEach(function (r, i) { + var p = self.spawn({ kind: 'thunder_beam', x: self.x + r[0] * f, y: self.y + r[1], dir: f, vx: fx(0x150), row: i, t: r[2], + hw: MM.ELEC_BOLT.hw[i], hh: MM.ELEC_BOLT.hh[i], dmg: self.shotDamage() }); + if (p) made++; + }); + this.out += made; this.bolts++; + c.emit('mm_boss_bolt', this.x, this.y); + }; + P.countered = function (c) { + if (!c.body.fired) return false; + var k = this.k.counter; + return k >= 1 || (k > 0 && c.rng.chance(k)); + }; + P.halt = function () { this.vx = 0; }; + + P.update = function (c) { + if (this.hp <= 0) return; + if (this.introTick()) { MM.step(this); return; } + if (this.iframes >= REACT) { this.react(c); return; } + switch (this.st) { + case 'guard': { + if (this.pose !== 'walk') { this.setPose('walk'); this.vx = this.k.walk; } + var target = WALLS[this.step & 3], d = this.faceTo(target); + if (d < 3) this.st = 'halt'; + this.dir = this.look; // boss_update_facing toward the wall position + this.walkNoFace(); + if (this.blocked || this.countered(c)) { this.st = 'leap'; this.counters++; } + break; + } + case 'halt': + this.halt(); this.setPose('fire'); this.windup = this.k.windup; this.st = 'fire'; + this.walkTick(c); break; + case 'fire': + if (this.windup <= 0) { this.fireBolt(c); this.st = 'wait'; } + this.walkTick(c); break; + case 'wait': + this.walkTick(c); + if (this.out <= 0) { this.step = (this.step + 1) & 3; this.st = 'guard'; } + break; + case 'leap': + this.setPose('leap'); this.vx = fx(0x1E0); this.vy = 4; + this.updateFacing(c); this.leaps++; + if (c.rng.int(4) === 0) { this.dir = -this.dir; this.feints++; } + this.st = 'air'; break; + case 'air': + if (this.walkTick(c)) { this.st = 'guard'; break; } + if (c.body.fired) this.st = 'air_pose'; + break; + case 'air_pose': + this.setPose('fire'); this.windup = this.k.windup; this.st = 'air_fire'; + if (this.walkTick(c)) this.halt(); + break; + case 'air_fire': + if (this.windup <= 0) { this.fireBolt(c); this.st = 'air_land'; } + if (this.walkTick(c)) this.halt(); + break; + case 'air_land': + if (this.out <= 0) this.st = 'guard'; + if (this.walkTick(c)) this.halt(); + break; + } + }; + // boss_anim_hop: on the first react frame turn away from the player and hop, the pattern restarts at guard + P.react = function (c) { + if (this.pose !== 'hurt') { + this.setPose('hurt'); this.updateFacing(c); this.dir = -this.dir; + this.vy = fx(0x140); this.vx = fx(0x120); this.st = 'guard'; + } + this.walkTick(c); + }; + + // entity pass for the Thunder Beam pieces (react_pickup $9AF4 chain): wrap -> jump, otherwise drift + P.entityPass = function () { + var self = this, T = MM.ELEC_BOLT; + this.projectiles.forEach(function (p) { + if (p.t <= 0) { + p.x += T.jx[p.row] * p.dir + (p.dir > 0 ? fx(0x50) : 0); p.y += T.jy[p.row]; + p.row = T.next[p.row]; p.hw = T.hw[p.row]; p.hh = T.hh[p.row]; p.t = 10; + } else p.x += p.vx * p.dir; + if (MM.offscreen(p)) { p.dead = true; self.out--; } + }); + this.projectiles = this.projectiles.filter(function (p) { return !p.dead; }); + }; + + P.state = function () { + return this.baseState({ step: this.step, leaps: this.leaps, feints: this.feints, bolts: this.bolts, counters: this.counters }); + }; + B.CASES = B.CASES || {}; + BB.CASES['megaman/elec_man'] = { title: 'Pouncer', Body: B.MegaMan, Boss: ElecMan }; + B.ElecMan = ElecMan; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/bosses/fire_man.js b/environments/games/web/games/megaman_remake/bosses/fire_man.js new file mode 100644 index 0000000000000000000000000000000000000000..a136b06c75e05ebbe5f1ad534b534ebf1e03e3e0 --- /dev/null +++ b/environments/games/web/games/megaman_remake/bosses/fire_man.js @@ -0,0 +1,119 @@ +// Fire Man (game mode 3, fixed bank $E2E4). Port of the original state machine: +// pace keep |dx| to the player inside the band [95, 97): walk toward him at 01.20 when farther, turn and +// walk away when closer; backed into a wall he turns and walks at (and past) the player +// volley five Fire Storm waves, each followed by a 63-frame stance; after the first 15 stance frames, +// leaving the band cancels the volley; after the fifth wave he holds a pose until the player +// presses anything or leaves the band. Deviation: the original holds that pose forever while the +// player stays perfectly still; BossBench requires a boss to keep engaging, so the pose ends after +// POSE_MAX = 90 frames (1.5 s) and he resumes pacing. +// retaliate 14 frames into his 30 blink frames after a hit he starts a new volley at once +// A wave (record 1) forms at his hand for 23 frames at 00.20, then runs at 05.10 ($37 X-speed row 6). When a +// running wave passes within 8 px of the player, a fire pillar (record 4, 16 x 16) rises there at floor level +// and burns for 131 frames (anim $38, 12 slots x 11 ticks) unless the next wave puts it out. +// Tier knobs (specs/fire_man.yaml): hp, wave/contact damage, stance length, retaliation on/off. +(function (g) { + var B = g.BB, BB = B, MM = B.MM, RM = MM.RobotMaster, fx = MM.fx; + var BAND_LO = 0x5F, BAND_HI = 0x61, FORM_T = 23, PILLAR_T = 131, EARLY = 15, POSE_MAX = 90; + var SEQ = ['pace', 'walk_far', 'summon', 'hold', 'spawn', 'hold', 'spawn', 'hold', 'spawn', 'hold', 'spawn', 'pose']; + + function FireMan() {} + var P = FireMan.prototype; + RM.install(P, 'fire_man', B.SPECS.fire_man); + P.reset = function (c) { this.base(c); this.n = 0; this.waves = 0; this.pillars = 0; this.volleys = 0; this.retaliations = 0; }; + P.onFight = function () { this.go(0); }; + P.go = function (n) { this.n = n; this.st = SEQ[n]; }; + P.inBand = function (d) { return d >= BAND_LO && d < BAND_HI; }; + P.hold = function () { return Math.round(this.k.hold); }; + + // record 1 (wave) at 8 px ahead, 8 px above centre; spawning a wave puts out the old pillar + P.spawnWave = function (c) { + this.face(c); + var f = this.look, p = this.spawn({ kind: 'fire_wave', x: this.x + 8 * f, y: this.y - 8, dir: f, vx: fx(0x20), + t: FORM_T, running: false, hw: 8, hh: 16, dmg: this.shotDamage() }); + if (!p) return false; + this.timer = this.hold(); this.waves++; + this.projectiles = this.projectiles.filter(function (q) { return q.kind !== 'fire_pillar'; }); + c.emit('mm_boss_wave', p.x, p.y); + return true; + }; + // pre-dispatch: a running wave within 8 px of the player raises (or moves) the pillar under it + P.tendWaves = function (c) { + for (var i = 0; i < this.projectiles.length; i++) { + var w = this.projectiles[i]; + if (w.kind !== 'fire_wave' || !w.running || Math.abs(c.body.x - w.x) >= 8) continue; + var pillar = null; + this.projectiles.forEach(function (q) { if (q.kind === 'fire_pillar') pillar = q; }); + if (pillar) { pillar.x = w.x; pillar.y = this.y + 4; pillar.t = PILLAR_T; pillar.age = 0; } + else if (this.spawn({ kind: 'fire_pillar', x: w.x, y: this.y + 4, dir: this.look, vx: 0, t: PILLAR_T, hw: 8, hh: 8, dmg: this.shotDamage() })) { + this.pillars++; c.emit('mm_boss_pillar', w.x, this.y + 4); + } + return; + } + }; + P.walkPace = function () { + this.dir = this.look; // sync facing memory + if (this.pose !== 'walk') { this.setPose('walk'); this.vx = fx(0x120); } + this.walkNoFace(); + }; + + P.update = function (c) { + if (this.hp <= 0) return; + if (this.introTick()) { MM.step(this); return; } + if (this.iframes === 0x10 && this.k.retaliate >= 0.5) { this.go(2); this.retaliations++; } + this.tendWaves(c); + var d; + switch (this.st) { + case 'pace': + d = this.face(c); + if (this.inBand(d)) { this.go(2); break; } + if (d < BAND_LO) this.look = -this.look; // too close: turn away + this.walkPace(); + if (this.blocked) { this.updateFacing(c); this.go(1); } + break; + case 'walk_far': + var keep = this.look; d = this.face(c); + if (d >= BAND_HI) { this.go(0); break; } + this.look = keep; this.walkNoFace(); + if (this.blocked) { this.updateFacing(c); this.go(0); } + break; + case 'summon': + this.vx = 0; this.setPose('summon'); this.volleys++; + if (this.spawnWave(c)) this.go(this.n + 1); + break; + case 'spawn': + this.vx = 0; this.setPose('summon'); + if (this.spawnWave(c)) this.go(this.n + 1); + break; + case 'hold': + if (this.timer < this.hold() - EARLY) { // original: range check once the timer is below $30 + d = this.face(c); + if (!this.inBand(d)) { this.go(0); break; } + } + if (--this.timer <= 0) this.go(this.n + 1); + break; + case 'pose': // stand down after the volley + d = this.face(c); + if (this.pose !== 'pose') { this.setPose('pose'); this.timer = POSE_MAX; } + if (!this.inBand(d) || c.body.anyInput || --this.timer <= 0) this.go(0); + break; + } + }; + + // entity pass: waves form then run; pillars burn down + P.entityPass = function () { + this.projectiles.forEach(function (p) { + if (p.kind === 'fire_wave') { + if (!p.running && p.t <= 0) { p.running = true; p.vx = fx(0x510); } // react_hyper_bomb: $36 -> $37, row 6 + else p.x += p.vx * p.dir; + } else if (p.kind === 'fire_pillar' && p.t <= 0) p.dead = true; + if (MM.offscreen(p)) p.dead = true; + }); + this.projectiles = this.projectiles.filter(function (p) { return !p.dead; }); + }; + P.state = function () { + return this.baseState({ n: this.n, waves: this.waves, pillars: this.pillars, volleys: this.volleys, retaliations: this.retaliations }); + }; + B.CASES = B.CASES || {}; + BB.CASES['megaman/fire_man'] = { title: 'Wave Keeper', Body: B.MegaMan, Boss: FireMan }; + B.FireMan = FireMan; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/bosses/guts_man.js b/environments/games/web/games/megaman_remake/bosses/guts_man.js new file mode 100644 index 0000000000000000000000000000000000000000..29b38c85e286f8a1ac785aaf41c5020ae9b1db05 --- /dev/null +++ b/environments/games/web/games/megaman_remake/bosses/guts_man.js @@ -0,0 +1,160 @@ +// Guts Man (game mode 5, fixed bank $E56E). Port of the original 21-entry table $E6CA: +// 5 leap a 15-frame crouch ($0641 = $1F), then straight up at 04.30 -> $19 +// $19 in the air without X speed; landing quakes, and a ceiling rock (record 3) falls into his hands +// $18 / $17 wait for that rock and the quake, 15-frame windup, throw the rock (record 2) at the player +// $16 wait for the rock to shatter; random_mod 3: 0 throw again, 1 three leaps toward, 2 a leap away +// airborne X speed 01.09; the walk tick runs only 3 of every 4 frames (x, y and gravity alike) +// landing shake_timer = $20: the land_* states wait it out, and the NMI stuns a player who is not in the jump +// pose (body_megaman.js quake(); the player's special state 2) +// The thrown rock (anim $32, 14 x 14 half size, no gravity, cannot be shot) flies at 04.00 at the player's feet and +// shatters on any tile or screen edge into 4 chunks (anim $56, 4 x 4, no gravity, no tile collision) placed at the rock's +// position + (8,8) (24,8) (8,24) (24,24): the rock path does not take off the 16 px the player's block path does. +// The ceiling rock has no contact flag: it only decorates the 23 frames before he can throw. Guts Man has no hit reaction. +// Tier knobs (specs/guts_man.yaml): hp, rock/chunk damage, contact damage, windup frames, rock speed scale. +(function (g) { + var B = g.BB, BB = B, MM = B.MM, RM = MM.RobotMaster, fx = MM.fx; + // $E6CA by seq_step - 5 + var SEQ = ['leap', 'land_wait', 'airborne', 'land_b', 'airborne', 'land_a', 'airborne', 'land_rehop', 'airborne', 'land_rehop', + 'airborne', 'land_wait', 'airborne', 'land_rehop', 'airborne', 'land_roll', 'airborne', 'pattern_roll', 'throw_rock', + 'windup_rock', 'ceiling_rock']; + var LEAP_VY = fx(0x430), AIR_VX = fx(0x109), SHAKE = 0x20, ROCK_SPEED = 0x400; + // record 3 starts at anim frame byte $19 unless he stands at y $C0, which this room's floor never gives (y $B0): + // anim $32 (rate $2F) wraps after 23 renders, and the pass that sees frame 0 ends it + var CEILING_LIFE = 23, CEILING_VY = -fx(0xC0); + var CHUNKS = [[8, 8, 4, 2], [24, 8, 4, 0], [8, 24, 3, 2], [24, 24, 3, 0]]; // $F826 x, $F82A y, $F82E X speed, $F832 Y speed + + function GutsMan() {} + var P = GutsMan.prototype; + RM.install(P, 'guts_man', B.SPECS.guts_man); + var baseRender = P.renderTick; + MM.blockRoom('megaman/guts_man'); + P.reset = function (c) { + this.base(c); this.y = 0xB0; this.hw = 16; this.hh = 16; this.seq = 5; this.shake = 0; this.roll = -1; + this.leaps = 0; this.quakes = 0; this.rocks = 0; this.ceilings = 0; this.shatters = 0; + }; + P.onFight = function () { this.go(5); }; + P.go = function (n) { this.seq = n; this.st = SEQ[n - 5]; }; + + P.update = function (c) { + if (this.hp <= 0) return; + if (this.introTick()) { MM.step(this); return; } + this[this.st](c); + }; + // gutsman_leap: every leap starts from this crouch and goes to $19 unless the caller picks another airborne state + P.startLeap = function () { + this.windup = Math.round(this.k.windup); this.vx = 0; this.vy = LEAP_VY; this.setPose('crouch'); this.leaps++; + this.go(0x19); + }; + // gutsman_leap_away: face the player, leap, but move away from him + P.leapAway = function (c) { this.updateFacing(c); this.startLeap(); this.dir = -this.dir; this.go(0x13); }; + // gutsman_air_tick: returns true on the landing frame (one state back, the quake starts) + P.airTick = function (c) { + if (this.windup > 0 || !(c.t & 3)) return false; + this.setPose('air'); + if (!this.walkTick(c)) return false; + this.go(this.seq - 1); this.setPose('land'); this.shake = SHAKE; this.quakes++; + c.emit('mm_quake', this.x, this.y + this.hh); + return true; + }; + + // ---- states ---- + P.leap = function () { this.startLeap(); }; + P.airborne = function (c) { this.vx = AIR_VX; this.airTick(c); }; + P.land_wait = function () { if (!this.shake) this.go(5); }; + P.land_b = function (c) { if (this.shake) return; this.leapAway(c); this.go(7); }; + P.land_a = function (c) { + if (this.shake) return; + if (c.rng.int(2)) { this.leapAway(c); this.go(9); } else this.go(5); + }; + P.land_rehop = function (c) { + if (this.shake) return; + var s = this.seq; this.updateFacing(c); this.startLeap(); this.go(s - 1); + }; + P.land_roll = function (c) { + if (this.shake) return; + if (c.rng.int(2)) this.go(5); else this.leapAway(c); + }; + P.pattern_roll = function (c) { + if (this.out) return; + this.updateFacing(c); + var r = this.roll = c.rng.int(3); + if (r === 0) { this.go(5); return; } + this.startLeap(); + if (r === 1) this.go(0x0F); else { this.go(0x15); this.dir = -this.dir; } + }; + P.throw_rock = function (c) { + if (this.windup > 0) return; + var adx = this.face(c), f = this.look; this.go(0x16); + var p = this.spawn({ kind: 'rock', x: this.x + 16 * f, y: this.y - 24, dir: f, vx: 0, vy: 0, hw: 14, hh: 14, dmg: this.shotDamage() }); + if (!p) return; + // aimed from the height of the rock over his head at the player's feet (ent_y_px + 12) + var v = MM.propVel(Math.round(ROCK_SPEED * this.k.speed), adx, Math.floor(this.y) - 24 - (Math.floor(c.body.y) + 12)); + p.vx = v.vx; p.vy = v.vy; this.out++; this.rocks++; this.setPose('throw'); + c.emit('mm_boss_rock', p.x, p.y); + }; + // gutsman_windup rewrites $0641 every frame until the rock is gone and the quake over, so the 15 frames start then + P.windup_rock = function () { + if (this.out) return; + this.setPose('lift'); this.windup = Math.round(this.k.windup); + if (!this.shake) this.go(0x17); + }; + P.ceiling_rock = function (c) { + if (!this.airTick(c)) return; + this.setPose('lift'); + var p = this.spawn({ kind: 'ceiling_rock', x: this.x - 10 * this.look, y: 0x20, dir: this.look, vx: 0, vy: CEILING_VY, hw: 14, hh: 14, harmless: true, t: CEILING_LIFE, dmg: 0 }); + if (p) { this.out++; this.ceilings++; } + }; + + // react_thrown_block: $44--, the rock's slot is free for the chunks, which fill free slots from $10 + P.shatter = function (c, p) { + var self = this; + this.out = Math.max(0, this.out - 1); this.shatters++; + this.projectiles = this.projectiles.filter(function (q) { return q !== p; }); + CHUNKS.forEach(function (r) { + self.spawn({ kind: 'rock_chunk', x: p.x + r[0], y: p.y + r[1], dir: p.dir, vx: r[2], vy: r[3], hw: 4, hh: 4, dmg: self.shotDamage() }); + }); + c.emit('mm_boss_shatter', p.x, p.y); + }; + // entity_pass in slot order, so chunks spawned into a later slot than the rock's move in the same pass + P.entityPass = function (c) { + for (var slot = 16; slot < 32; slot++) this.passSlot(c, slot); + this.projectiles = this.projectiles.filter(function (p) { return !p.dead; }); + }; + P.passSlot = function (c, slot) { + var p = null; + this.projectiles.forEach(function (q) { if (q.slot === slot && !q.dead) p = q; }); + if (!p) return; + if (p.kind === 'ceiling_rock') { + if (p.t <= 0) { p.dead = true; this.out = Math.max(0, this.out - 1); return; } + p.y -= p.vy; p.vy = Math.max(-MM.FALL_MAX, p.vy - MM.GRAVITY); + return; + } + if (p.kind === 'rock_chunk') { + p.x += p.vx * p.dir; p.y -= p.vy; + if (MM.offscreen(p)) p.dead = true; + return; + } + // the rock: X with the wall probes, then Y with the floor probe while falling; any stop shatters it + var nx = p.x + p.vx * p.dir, lo = MM.WALL_L + p.hw, hi = MM.WALL_R - p.hw, stop = false; + if (nx < lo) { nx = lo; stop = true; } else if (nx > hi) { nx = hi; stop = true; } + if (this.room.length) { var cx = MM.clampX(this.room, p.x, nx, p.hw, p.y, p.hh); if (cx !== nx) { nx = cx; stop = true; } } + p.x = nx; + if (stop) { this.shatter(c, p); return; } + var ny = p.y - p.vy, floor = this.room.length ? MM.floorUnder(this.room, p.x - p.hw + 1, p.x + p.hw - 1, p.y + p.hh) : MM.FLOOR; + if (p.vy < 0 && ny + p.hh >= floor) { p.y = floor - p.hh; this.shatter(c, p); return; } + if (ny < MM.TOP_EXIT || ny >= MM.BOTTOM_EXIT) { this.shatter(c, p); return; } // the vertical exit keeps the old y + p.y = ny; + }; + // render: the shared counters, then the NMI: each shake frame stuns the player and counts down ($20 NMIs) + P.renderTick = function (c) { + baseRender.call(this, c); + if (this.shake > 0) { c.body.quake(); this.shake--; } + }; + P.state = function () { + return this.baseState({ seq: this.seq, shake: this.shake, roll: this.roll, leaps: this.leaps, quakes: this.quakes, + rocks: this.rocks, ceilings: this.ceilings, shatters: this.shatters }); + }; + B.CASES = B.CASES || {}; + BB.CASES['megaman/guts_man'] = { title: 'Quake Hurler', Body: B.MegaMan, Boss: GutsMan }; + B.GutsMan = GutsMan; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/bosses/ice_man.js b/environments/games/web/games/megaman_remake/bosses/ice_man.js new file mode 100644 index 0000000000000000000000000000000000000000..8c4231bc5515626e4c54d504049ac5aefc7f1896 --- /dev/null +++ b/environments/games/web/games/megaman_remake/bosses/ice_man.js @@ -0,0 +1,93 @@ +// Ice Man (game mode 1, fixed bank $E111). Port of the original state machine: +// walk to the waypoint $E2C8[n] (208, 168, 128, 168) at 01.20, stance (15-frame windup), hop straight up +// (04.DF); falling past y 148 / 164 / 180 he fires an Ice Slasher at each level and, with gravity switched +// off, sinks at a slow speed; he hovers $E2D8 frames (48/46/38/27), fires at the bottom, then rises back +// through 164 and 148 firing again - six slashers per cycle in a V; finally gravity returns with a 02.C0 pop +// and he lands. Every landing advances the waypoint and the pattern counter (0..9); counter / 3 picks the +// slasher speed (01.60 / 01.80 / 02.00 / 02.E0), hover time and sink speed, so the pattern speeds up. +// Ice Man has no hit reaction. Tier knobs (specs/ice_man.yaml): hp, slasher/contact damage, slasher speed +// scale, hover scale, stance windup. +(function (g) { + var B = g.BB, BB = B, MM = B.MM, RM = MM.RobotMaster, fx = MM.fx; + var WAYPOINTS = [0xD0, 0xA8, 0x80, 0xA8]; + var SPEEDS = [fx(0x160), fx(0x180), fx(0x200), fx(0x2E0)]; + var HOVER = [0x30, 0x2E, 0x26, 0x1B]; + var SINK = [-(1 - fx(0x60)), -(1 - fx(0x50)), -(1 - fx(0x2C)), -(2 - fx(0xE0))]; // $FF.60 $FF.50 $FF.2C $FE.E0 + var DOWN = [0x94, 0xA4, 0xB4], UP = [0xA5, 0x95]; + // the 19 states of the mode 1 table, in order + var SEQ = ['leg_start', 'leg_walk', 'stance', 'hop', 'rise', 'fire', 'rise', 'fire', 'rise', 'fire', 'set_timer', + 'hover', 'fire', 'climb', 'fire', 'climb', 'fire', 'drop', 'land']; + + function IceMan() {} + var P = IceMan.prototype; + RM.install(P, 'ice_man', B.SPECS.ice_man); + P.reset = function (c) { this.base(c); this.n = 0; this.wp = 0; this.counter = 0; this.level = 0; this.volleys = 0; this.slashers = 0; }; + P.onFight = function () { this.n = 0; this.st = SEQ[0]; }; + P.next = function () { this.n++; this.st = SEQ[this.n]; }; + P.q = function () { return Math.floor(this.counter / 3); }; + + P.update = function (c) { + if (this.hp <= 0) return; + if (this.introTick()) { MM.step(this); return; } + var wx = WAYPOINTS[this.wp & 3], q = this.q(); + switch (this.st) { + case 'leg_start': + this.setPose('walk'); this.vx = fx(0x120); + this.faceTo(wx); this.dir = this.look; this.next(); break; + case 'leg_walk': + if (this.faceTo(wx) < 2) { // fire stance: anim + 1, nearly stop + this.setPose('stance'); this.windup = this.k.windup; this.vx = fx(0x10); this.next(); + } else this.walkNoFace(); + break; + case 'stance': + if (this.windup > 0) this.walkNoFace(); else this.next(); + break; + case 'hop': + this.face(c); this.vx = 0; this.vy = fx(0x4DF); this.setPose('jump'); this.level = 0; this.next(); break; + case 'rise': // falling past the next level: sink slowly + this.walkTick(c); + if (this.vy < 0 && this.y >= DOWN[this.level]) { this.vy = SINK[q]; this.grav = false; this.level++; this.next(); } + break; + case 'fire': + this.face(c); this.fireSlasher(c, q); this.next(); break; + case 'set_timer': + this.timer = Math.round(HOVER[q] * this.k.hover); this.next(); break; + case 'hover': + this.updateFacing(c); + if (--this.timer <= 0) { this.vy = -this.vy; this.level = 0; this.next(); } + break; + case 'climb': + this.walkTick(c); + if (this.y < UP[this.level]) { this.level++; this.next(); } + break; + case 'drop': + this.grav = true; this.vy = fx(0x2C0); this.next(); break; + case 'land': + if (this.walkTick(c)) { + if (this.counter < 9) this.counter++; + this.wp = (this.wp + 1) & 3; this.volleys++; + this.n = 0; this.st = SEQ[0]; + } + break; + } + }; + // record 5: Ice Slasher 2 px above centre, 8 px ahead, speed $E2CC[counter / 3] + P.fireSlasher = function (c, q) { + var f = this.look; + var p = this.spawn({ kind: 'ice_slasher', x: this.x + 8 * f, y: this.y - 2, dir: f, vx: SPEEDS[q] * this.k.speed, + hw: 4, hh: 4, dmg: this.shotDamage() }); + if (p) { this.slashers++; c.emit('mm_boss_slasher', p.x, p.y); } + this.setPose('shoot'); + }; + P.entityPass = function () { + this.projectiles.forEach(function (p) { p.x += p.vx * p.dir; if (MM.offscreen(p)) p.dead = true; }); + this.projectiles = this.projectiles.filter(function (p) { return !p.dead; }); + }; + P.state = function () { + return this.baseState({ n: this.n, waypoint: this.wp, counter: this.counter, level: this.level, + volleys: this.volleys, slashers: this.slashers }); + }; + B.CASES = B.CASES || {}; + BB.CASES['megaman/ice_man'] = { title: 'V Gunner', Body: B.MegaMan, Boss: IceMan }; + B.IceMan = IceMan; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/bosses/robot_master.js b/environments/games/web/games/megaman_remake/bosses/robot_master.js new file mode 100644 index 0000000000000000000000000000000000000000..8e2b160271080e524589b65f913b74ad576780fd --- /dev/null +++ b/environments/games/web/games/megaman_remake/bosses/robot_master.js @@ -0,0 +1,90 @@ +// Shared parts of a Robot Master fight (boss_fight_controller $DB8C and the fixed-bank boss services $EDC2-$EF36). +// A boss keeps two facings like the original: `look` is the sprite flip ($0421 bit 6, set by boss_face_player) +// and `dir` is the movement memory ($43 bit 6, copied from the flip by boss_update_facing). Bosses stand at +// x $C0 / y $B4 when the fight starts ($ED9A/$EDA3), have gravity, and blink for a per-mode number of frames after +// every hit, during which the player's shots pass through ($C994). The intro locks the player's input while the +// boss drops in and its bar fills (one unit every other frame, boss_hp_fill_tick $F39B). +(function (g) { + var B = g.BB, MM = B.MM; + // intro timer $5E = 94 frames from the drop-in to the fight (boss_fight_controller $DB8C); the bar fills one unit + // every other frame once the timer is below $3A, i.e. 28 units over the last 56 frames + var DROP = 0x5E - 0x3A + 2, FILL = 0x3A - 2; + + var RM = MM.RobotMaster = {}; + RM.install = function (P, id, spec) { + P.id = id; P.spec = spec; P.info = MM.ROBOT_MASTERS[id]; + P.base = function (c) { + var k = this.k = MM.knobs(spec, c.d); + this.room = MM.roomOf(c.id); + this.x = 0xC0; this.y = 0xB4; this.vx = 0; this.vy = 0; this.dir = -1; this.look = -1; + this.hw = 8; this.hh = 12; this.grav = true; this.grounded = true; this.blocked = false; this.landed = false; + this.max_hp = this.hp = Math.round(k.hp) * MM.UNIT; + this.iframes = 0; this.intro = DROP + FILL; this.fight = false; + this.projectiles = []; this.nextId = 1; this.out = 0; + this.windup = 0; this.pose = 'stand'; this.poseT = 0; this.timer = 0; + this.st = 'intro'; this.hitsBy = {}; this.damageBy = {}; this.lastHit = null; + this.dmg = MM.CONTACT * MM.UNIT; + }; + P.introTick = function () { + if (this.intro <= 0) return false; + this.intro--; + if (this.intro === 0) { this.fight = true; this.onFight(); } + return true; + }; + P.hitBox = function () { return MM.box(this.x, this.y, this.hw, this.hh); }; + P.bodyBox = P.hitBox; + P.contactDamage = function () { return Math.round(this.k.contact * MM.UNIT); }; + P.shotDamage = function () { return Math.round(this.k.shot * MM.UNIT); }; + // boss_face_player: sprite flip toward px (default: the player), returns |dx| in whole pixels (the original + // subtracts the integer pixel bytes, so band and arrival checks are integer comparisons) + P.faceTo = function (px) { var d = Math.floor(px) - Math.floor(this.x); this.look = d >= 0 ? 1 : -1; return Math.abs(d); }; + P.face = function (c) { return this.faceTo(c.body.x); }; + P.updateFacing = function (c, px) { this.faceTo(px == null ? c.body.x : px); this.dir = this.look; }; + P.walkNoFace = function () { MM.step(this); return this.landed; }; + P.walkTick = function (c) { this.face(c); return this.walkNoFace(); }; + P.setPose = function (name) { if (this.pose !== name) { this.pose = name; this.poseT = 0; } }; + P.spawn = function (p) { + var slot = MM.freeSlot(this.projectiles); + if (slot < 0) return null; + p.slot = slot; p.id = this.nextId++; p.age = 0; this.projectiles.push(p); return p; + }; + // shot hit on the boss ($C8B2): damage from the table (0 still blinks), lethal hits end the fight + P.takeHit = function (c, w, sx, sy) { + var units = MM.DAMAGE[id][w] || 0, dmg = units * MM.UNIT; + this.hitsBy[w] = (this.hitsBy[w] || 0) + 1; this.damageBy[w] = (this.damageBy[w] || 0) + dmg; + this.lastHit = { t: c.t, w: w, units: units }; + if (dmg >= this.hp) { + this.hp = 0; this.st = 'dead'; this.fight = false; this.projectiles = []; + c.emit('mm_boss_dead', this.x, this.y); return; + } + this.hp -= dmg; this.iframes = this.info.iframes; + c.emit(units ? 'mm_hit' : 'mm_clank', sx, sy); + if (this.onHit) this.onHit(c, w); + }; + // render-time counters: the blink ($56 is ticked by draw_entity), anim-control windups, pose clocks + P.renderTick = function () { + if (this.iframes > 0) this.iframes--; + if (this.windup > 0) this.windup--; + this.poseT++; + this.projectiles.forEach(function (p) { if (p.t != null) p.t--; p.age++; }); + }; + P.baseState = function (extra) { + var o = { x: this.x, y: this.y, vx: this.vx, vy: this.vy, dir: this.dir, look: this.look, grav: this.grav, + grounded: this.grounded, hp: this.hp, max_hp: this.max_hp, iframes: this.iframes, intro: this.intro, + fight: this.fight, fsm: this.st, timer: this.timer, windup: this.windup, pose: this.pose, pose_t: this.poseT, + out: this.out, projectiles: this.projectiles, next_id: this.nextId, hits_by: this.hitsBy, + damage_by: this.damageBy, last_hit: this.lastHit }; + Object.keys(extra || {}).forEach(function (key) { o[key] = extra[key]; }); + return MM.snapshot(o); + }; + // the shared Case wiring (default interact() is replaced by the body's resolveInteractions) + P.onNailHit = function () { return null; }; + P.hazards = function () { + if (this.hp <= 0) return []; + var out = [{ kind: id + '_body', box: { x: this.x, y: this.y, w: this.hw * 2, h: this.hh * 2 }, dmg: this.contactDamage() }]; + this.projectiles.forEach(function (p) { if (!p.harmless) out.push({ kind: p.kind, box: { x: p.x, y: p.y, w: p.hw * 2, h: p.hh * 2 }, dmg: p.dmg }); }); + return out; + }; + }; + RM.INTRO = DROP + FILL; RM.DROP = DROP; RM.FILL = FILL; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/compact_actions.json b/environments/games/web/games/megaman_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..15fb166cafa09cf670ee69601ee970f09e0c2bc6 --- /dev/null +++ b/environments/games/web/games/megaman_remake/compact_actions.json @@ -0,0 +1,373 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "megaman_remake", + "version": "megaman-compact@1", + "heads": [ + { + "name": "move", + "options": [ + { + "label": "none" + }, + { + "label": "left", + "keys": [ + "A" + ] + }, + { + "label": "right", + "keys": [ + "D" + ] + }, + { + "label": "left_half", + "subs": [ + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [], + [], + [] + ] + }, + { + "label": "right_half", + "subs": [ + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [], + [], + [] + ] + }, + { + "label": "left_4", + "subs": [ + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [], + [] + ] + }, + { + "label": "right_4", + "subs": [ + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [], + [] + ] + } + ] + }, + { + "name": "jump", + "options": [ + { + "label": "none" + }, + { + "label": "hold", + "keys": [ + "Space" + ] + }, + { + "label": "tap", + "subs": [ + [ + "Space" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "from_2", + "subs": [ + [], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ] + ] + }, + { + "label": "from_3", + "subs": [ + [], + [], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ] + ] + }, + { + "label": "from_4", + "subs": [ + [], + [], + [], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ] + ] + }, + { + "label": "from_5", + "subs": [ + [], + [], + [], + [], + [ + "Space" + ], + [ + "Space" + ] + ] + }, + { + "label": "at_6", + "subs": [ + [], + [], + [], + [], + [], + [ + "Space" + ] + ] + }, + { + "label": "first_2", + "subs": [ + [ + "Space" + ], + [ + "Space" + ], + [], + [], + [], + [] + ] + }, + { + "label": "first_5", + "subs": [ + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [] + ] + }, + { + "label": "first_3", + "subs": [ + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [], + [], + [] + ] + }, + { + "label": "first_4", + "subs": [ + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [], + [] + ] + }, + { + "label": "tap_rehold", + "subs": [ + [ + "Space" + ], + [], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ] + ] + }, + { + "label": "tap_tap6", + "subs": [ + [ + "Space" + ], + [], + [], + [], + [], + [ + "Space" + ] + ] + }, + { + "label": "tap_hold5", + "subs": [ + [ + "Space" + ], + [], + [], + [], + [ + "Space" + ], + [ + "Space" + ] + ] + } + ] + }, + { + "name": "fire", + "options": [ + { + "label": "none" + }, + { + "label": "fire", + "subs": [ + [ + "J" + ], + [], + [ + "J" + ], + [], + [ + "J" + ], + [] + ] + }, + { + "label": "next_weapon", + "tap": [ + "E" + ] + }, + { + "label": "prev_weapon", + "tap": [ + "Q" + ] + } + ] + } + ] +} diff --git a/environments/games/web/games/megaman_remake/data/weapons.js b/environments/games/web/games/megaman_remake/data/weapons.js new file mode 100644 index 0000000000000000000000000000000000000000..f053f692d8583efb9eef0b431abb876b00d13878 --- /dev/null +++ b/environments/games/web/games/megaman_remake/data/weapons.js @@ -0,0 +1,62 @@ +// Data-driven weapon x boss tables of Mega Man (NES, 1987), transcribed from the ROM via the annotated +// disassembly (plasticsmoke/megaman1-disassembly-ca65 @2771fb3, see SOURCES.md S-DASM): +// $FDEE weapon damage vs boss, 8 weapons (P C I B F E G M) x game mode (0 Cut 1 Ice 2 Bomb 3 Fire 4 Elec 5 Guts) +// $C994 boss post-hit invulnerability frames per mode +// $FEBB damage a boss projectile deals per mode; boss body contact is a flat 4 (player_contact_service) +// $A8DE weapon energy units per shot ($A8D7 shots-per-charge is 1 for every weapon) +// Every Robot Master is listed so scenes 4-6 plug in later; `built` marks what this round implements. +(function (g) { + var MM = g.BB.MM; + MM.WEAPON_ORDER = ['P', 'C', 'I', 'B', 'F', 'E', 'G', 'M']; + MM.WEAPONS = { + P: { name: 'Arm Gun', zh: 'Arm Gun', from: null, cost: 0, built: true }, + C: { name: 'Return Blade', zh: 'Returning blade', from: 'cut_man', cost: 1, built: true }, + I: { name: 'Pierce Dart', zh: 'Pierce Dart', from: 'ice_man', cost: 1, built: true }, + B: { name: 'Fuse Lob', zh: 'Fuse Lob', from: 'bomb_man', cost: 2, built: true }, + F: { name: 'Orbit Guard', zh: 'Orbit Guard', from: 'fire_man', cost: 1, built: true }, + E: { name: 'Tri Arc', zh: 'Tri Arc', from: 'elec_man', cost: 1, built: true }, + G: { name: 'Block Toss', zh: 'Boulder throw', from: 'guts_man', cost: 2, built: true }, + M: { name: 'Bridge Ray', zh: 'Bridge Ray', from: null, cost: 2, built: false } + }; + MM.ROBOT_MASTERS = { + cut_man: { mode: 0, zh: 'Blade Tosser', en: 'BLADE TOSSER', weapon: 'C', iframes: 0x3F, shot: 4 }, + ice_man: { mode: 1, zh: 'V Gunner', en: 'V GUNNER', weapon: 'I', iframes: 0x1E, shot: 10 }, + bomb_man: { mode: 2, zh: 'Shard Lobber', en: 'SHARD LOBBER', weapon: 'B', iframes: 0x1E, shot: 4 }, + fire_man: { mode: 3, zh: 'Wave Keeper', en: 'WAVE KEEPER', weapon: 'F', iframes: 0x1E, shot: 4 }, + elec_man: { mode: 4, zh: 'Pouncer', en: 'POUNCER', weapon: 'E', iframes: 0x3F, shot: 10 }, + guts_man: { mode: 5, zh: 'Quake Hurler', en: 'QUAKE HURLER', weapon: 'G', iframes: 0x1E, shot: 4 } + }; + MM.CONTACT = 4; + // P C I B F E G M + var ROWS = { + cut_man: [3, 1, 0, 2, 3, 1, 14, 0], + ice_man: [1, 2, 0, 4, 1, 10, 0, 0], + bomb_man: [2, 2, 0, 1, 4, 2, 0, 0], + fire_man: [2, 2, 4, 1, 1, 1, 0, 0], + elec_man: [1, 10, 0, 2, 1, 1, 4, 0], + guts_man: [2, 1, 0, 10, 2, 1, 1, 0] + }; + MM.DAMAGE = {}; + Object.keys(ROWS).forEach(function (boss) { + var row = MM.DAMAGE[boss] = {}; + MM.WEAPON_ORDER.forEach(function (w, i) { row[w] = ROWS[boss][i]; }); + }); + // the boss a weapon is strongest against (ties are impossible in the table) + MM.weakTo = function (boss) { + var row = MM.DAMAGE[boss], best = 'P'; + MM.WEAPON_ORDER.forEach(function (w) { if (row[w] > row[best]) best = w; }); + return best; + }; + // reset option {weapons: ['E', 'I', ...]}: weapons won from earlier bosses (the Buster is always owned) + MM.loadout = function (options) { + var list = (options && options.weapons) || [], out = ['P']; + if (!Array.isArray(list)) throw new Error('options.weapons must be a list of weapon letters'); + list.forEach(function (w) { + w = String(w).toUpperCase(); + if (!MM.WEAPONS[w]) throw new Error('unknown weapon ' + JSON.stringify(w) + ' (use ' + MM.WEAPON_ORDER.join(' ') + ')'); + if (!MM.WEAPONS[w].built) throw new Error('weapon ' + w + ' (' + MM.WEAPONS[w].name + ') is not implemented in this build'); + if (out.indexOf(w) < 0) out.push(w); + }); + return MM.WEAPON_ORDER.filter(function (w) { return out.indexOf(w) >= 0; }); + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/draw/compose.js b/environments/games/web/games/megaman_remake/draw/compose.js new file mode 100644 index 0000000000000000000000000000000000000000..fe4a17c1d1e5062398938544dfed11d12dfe7496 --- /dev/null +++ b/environments/games/web/games/megaman_remake/draw/compose.js @@ -0,0 +1,83 @@ +// Frame compositor for Mega Man: every frame is drawn at the NES's native 256x240 into an offscreen canvas with +// integer-pixel rects only, then scaled 2x (nearest neighbour) into the middle of the 854x480 frame. The side +// panels carry the readable HUD (weapon menu, bars, boss, timer, tier, native Hz); the original's vertical +// energy bars are also drawn inside the room where the NES put them. The shared renderer's layer hooks are +// routed here (BODY_DRAW.megaman.fullHud runs last and owns the whole picture), so one pass draws the room in +// the original's order: background, boss shots, boss, player shots, player, effects, HUD bars. +// Pure presentation: reads the case, never writes it; effects are a function of (event tick, current tick). +(function (g) { + var B = g.BB, MM = B.MM, P = MM.PAL, S = MM.SCREEN; + var low = null, lx = null; + function lowCanvas(doc) { + if (!low) { low = doc.createElement('canvas'); low.width = 256; low.height = 240; lx = low.getContext('2d'); } + return lx; + } + function px(x, X, Y, w, h, col) { x.fillStyle = col; x.fillRect(Math.round(X), Math.round(Y), w, h); } + MM.px = px; + + // ---------- effects from the event log (deterministic: age = c.t - e.t) ---------- + function recent(c, names, maxAge, fn) { + for (var i = c.events.length - 1; i >= 0; i--) { + var e = c.events[i]; if (c.t - e.t > maxAge) break; + if (names.indexOf(e.name) >= 0) fn(e, c.t - e.t); + } + } + function effects(x, c) { + recent(c, ['mm_hit', 'mm_clank'], 8, function (e, a) { // hit spark (anim $19) + var col = e.name === 'mm_clank' ? P.light : P.white, r = 2 + a; + px(x, e.x - r, e.y - 1, r * 2, 2, col); px(x, e.x - 1, e.y - r, 2, r * 2, col); + }); + recent(c, ['mm_hurt'], 10, function (e, a) { // the player's hit spark (knockback entry) + var r = 4 + a; px(x, e.x - r, e.y - 1, r * 2, 2, P.white); px(x, e.x - 1, e.y - r, 2, r * 2, P.white); + px(x, e.x - r + 2, e.y - r + 2, 3, 3, P.yellow); px(x, e.x + r - 5, e.y + r - 5, 3, 3, P.yellow); + }); + recent(c, ['mm_land'], 6, function (e, a) { // landing dust + px(x, e.x - 6 - a, e.y - 2, 3, 2, P.light); px(x, e.x + 3 + a, e.y - 2, 3, 2, P.light); + }); + recent(c, ['mm_boss_dead', 'mm_player_dead'], 120, function (e, a) { // 8-orb radial burst (two speeds) + for (var k = 0; k < 16; k++) { + var ang = k * Math.PI / 8, sp = k < 8 ? 1.5 : 0.75, r = 6 + a * sp, ox = e.x + Math.cos(ang) * r, oy = e.y + Math.sin(ang) * r; + if (oy < 0 || oy > 240) continue; + var ph = (a >> 2) & 1, col = e.name === 'mm_boss_dead' ? (ph ? P.white : P.yellow) : (ph ? P.white : P.sky); + px(x, ox - 3, oy - 3, 6, 6, col); px(x, ox - 1, oy - 1, 2, 2, ph ? P.yellow : P.white); + } + }); + } + + // ---------- NES-style vertical bars (28 units, 7 cells of 4) ---------- + function bar(x, X, units, fill) { + px(x, X, 16, 8, 57, P.black); + for (var u = 0; u < MM.BAR; u++) { + var yy = 16 + 56 - (u + 1) * 2; + if (u < units) { px(x, X + 1, yy + 1, 6, 1, fill); px(x, X + 3, yy + 1, 2, 1, P.white); } + } + } + + function compose(x, c, t) { + var doc = x.canvas.ownerDocument || g.document, L = lowCanvas(doc), bossDraw = B.BOSS_DRAW[c.id]; + L.setTransform(1, 0, 0, 1, 0, 0); + MM.drawRoom(L, c, t); + if (bossDraw && bossDraw.projectiles) bossDraw.projectiles(L, c, t); + if (bossDraw && bossDraw.boss) bossDraw.boss(L, c, t); + MM.drawPlayerShots(L, c, t); + MM.drawPlayer(L, c, t); + effects(L, c); + var b = c.body, o = c.boss, R = MM.RobotMaster; + bar(L, 24, Math.ceil(MM.BAR * b.hp / b.max_hp), P.gold); // life bar + if (b.weapon !== 'P') bar(L, 16, b.energy[b.weapon] || 0, MM.weaponColor(b.weapon)); + // boss bar: the whole tier bar mapped onto 28 cells; it fills during the intro like boss_hp_fill_tick + var fillK = o.fight || o.hp <= 0 ? 1 : Math.max(0, Math.min(1, 1 - o.intro / R.FILL)); + if (o.fight || o.intro < R.FILL || o.hp <= 0) bar(L, 40, Math.ceil(MM.BAR * fillK * o.hp / o.max_hp), P.orange); + x.save(); x.setTransform(1, 0, 0, 1, 0, 0); x.imageSmoothingEnabled = false; + // the quake moves the picture: PPUSCROLL + $D583/$D588[(timer / 2) & 3] on odd timer values, nothing on even ones (o.shake has + // already counted this frame down); a positive scroll moves the picture the other way, and the side panels cover the edges + var sh = o.shake > 0 ? o.shake + 1 : 0, ph = sh & 1 ? (sh >> 1) & 3 : 4; + if (ph !== 4) { x.fillStyle = '#000000'; x.fillRect(S.OX, S.OY, 256 * S.SCALE, 240 * S.SCALE); } + x.drawImage(low, S.OX - [0, 8, 0, -8, 0][ph] * S.SCALE, S.OY - [-24, 0, 8, 0, 0][ph] * S.SCALE, 256 * S.SCALE, 240 * S.SCALE); + x.restore(); + } + MM.compose = compose; + MM.weaponColor = function (w) { + return { P: P.sky, E: P.yellow, I: P.ice, F: P.ember, C: P.light, B: P.green, G: P.orange, M: P.red }[w] || P.white; + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/draw/hud.js b/environments/games/web/games/megaman_remake/draw/hud.js new file mode 100644 index 0000000000000000000000000000000000000000..f1b85bf1096a375719be5c72e24e5cc0fe42f971 --- /dev/null +++ b/environments/games/web/games/megaman_remake/draw/hud.js @@ -0,0 +1,78 @@ +// HUD side panels around the 512x480 room: left = player (life, weapon menu with energy, counter chain hint), +// right = boss (name, health in points and NES units, state, timer, tier, native Hz). The whole picture is drawn +// by BODY_DRAW.megaman.fullHud, which the shared renderer calls last (renderer.js hud()). +(function (g) { + var B = g.BB, MM = B.MM, P = MM.PAL, S = MM.SCREEN; + var W = 854, H = 480, L = S.OX, R = S.OX + 512; + var FONT = '"Press Start 2P", "Lucida Console", Consolas, monospace'; + function txt(x, s, X, Y, col, size, align) { + x.font = (size || 11) + 'px ' + FONT; x.textAlign = align || 'left'; x.textBaseline = 'alphabetic'; + x.fillStyle = '#000000'; x.fillText(s, X + 1, Y + 1); x.fillStyle = col || '#fcfcfc'; x.fillText(s, X, Y); + } + function hbar(x, X, Y, w, frac, col) { + x.fillStyle = '#000000'; x.fillRect(X, Y, w, 10); + x.fillStyle = '#202020'; x.fillRect(X + 1, Y + 1, w - 2, 8); + var n = 28, cw = (w - 2) / n, k = Math.round(frac * n); + for (var i = 0; i < k; i++) { x.fillStyle = col; x.fillRect(X + 1 + i * cw, Y + 1, cw - 1, 8); x.fillStyle = 'rgba(255,255,255,.55)'; x.fillRect(X + 1 + i * cw, Y + 2, cw - 1, 2); } + } + function panel(x, X) { + x.fillStyle = '#0c0c18'; x.fillRect(X, 0, 171, H); + x.fillStyle = '#1c1c34'; for (var y = 0; y < H; y += 4) x.fillRect(X, y, 171, 1); + x.fillStyle = '#3c3c64'; x.fillRect(X === 0 ? 169 : X, 0, 2, H); + } + function hud(x, c, V, extra) { + var b = c.body, o = c.boss, G = B.GAME; + MM.VIEW_LAST = c; // read-only handle for page tests (never written back) + MM.compose(x, c, c.t / B.FPS); + x.save(); x.setTransform(1, 0, 0, 1, 0, 0); + panel(x, 0); panel(x, R); + // ---- left: player ---- + txt(x, 'BLUE GUNNER', 12, 26, '#3cbcfc', 12); + txt(x, 'LIFE ' + b.hp + '/' + b.max_hp, 12, 46, '#fcfcfc', 9); + hbar(x, 12, 52, 146, b.hp / b.max_hp, '#fce0a8'); + txt(x, 'WEAPON (Q/E)', 12, 84, '#bcbcbc', 9); + MM.WEAPON_ORDER.forEach(function (w, i) { + if (b.weapons.indexOf(w) < 0) return; + var row = b.weapons.indexOf(w), Y = 100 + row * 34, on = w === b.weapon, info = MM.WEAPONS[w]; + if (on) { x.fillStyle = '#28285c'; x.fillRect(6, Y - 12, 158, 32); x.fillStyle = MM.weaponColor(w); x.fillRect(6, Y - 12, 3, 32); } + txt(x, w + ' ' + info.name.toUpperCase(), 14, Y, on ? MM.weaponColor(w) : '#7c7c7c', 8); + if (w === 'P') txt(x, 'UNLIMITED', 14, Y + 14, '#7c7c7c', 7); + else hbar(x, 14, Y + 5, 140, (b.energy[w] || 0) / MM.BAR, MM.weaponColor(w)); + }); + var dmg = MM.DAMAGE[o.id][b.weapon], best = MM.weakTo(o.id), bestHave = b.weapons.indexOf(best) >= 0; + txt(x, 'VS ' + MM.ROBOT_MASTERS[o.id].en + ': ' + dmg + ' / HIT', 12, 380, dmg >= 4 ? '#f8b800' : dmg === 0 ? '#f87858' : '#bcbcbc', 8); + txt(x, 'WEAK: ' + MM.WEAPONS[best].name.toUpperCase() + (bestHave ? '' : ' (X)'), 12, 396, '#7c7c7c', 7); + txt(x, 'A/D MOVE SPACE JUMP', 12, 444, '#5c5c7c', 7); + txt(x, 'J / LMB FIRE P PAUSE', 12, 458, '#5c5c7c', 7); + // ---- right: boss ---- + var info2 = MM.ROBOT_MASTERS[o.id], name = info2.en; + txt(x, name, R + 12, 26, '#f87858', 12); + txt(x, (info2.zh || '') , R + 12, 44, '#bcbcbc', 10); + txt(x, o.hp + '/' + o.max_hp, R + 12, 64, '#fcfcfc', 9); + hbar(x, R + 12, 70, 146, o.max_hp ? o.hp / o.max_hp : 0, '#f87858'); + txt(x, 'NES ' + Math.ceil(o.hp / MM.UNIT) + '/' + Math.round(o.max_hp / MM.UNIT) + ' UNITS', R + 12, 96, '#7c7c7c', 7); + txt(x, 'STATE ' + String(o.st).toUpperCase(), R + 12, 116, '#bcbcbc', 8); + // pattern position, the Robot Masters' equivalent of a phase (all read from the boss state) + var phase = o.id === 'elec_man' ? 'WALL POS ' + ((o.step & 3) + 1) + '/4' + : o.id === 'ice_man' ? 'SPEED LV ' + (Math.floor(o.counter / 3) + 1) + '/4' + : o.id === 'cut_man' ? 'BLADE ' + (o.cut === 0 ? 'HOME' : o.cut === 1 ? 'OUT' : 'BACK') + ' / ' + o.throws + ' THROWN' + : o.id === 'bomb_man' ? 'BOMBS ' + o.out + ' OUT / ' + o.bursts + ' BURST' + : o.id === 'guts_man' ? (b.stunT > 0 ? 'STUNNED ' + b.stunT : 'QUAKES ' + o.quakes + ' / ROCKS ' + o.rocks) + : 'VOLLEY ' + (o.n >= 2 ? Math.min(5, Math.floor((o.n - 2) / 2) + 1) : 0) + '/5'; + txt(x, phase, R + 12, 132, '#bcbcbc', 8); + var secs = c.t / B.FPS, mm = Math.floor(secs / 60), ss = Math.floor(secs % 60), cs = Math.floor((secs * 10) % 10); + txt(x, 'TIME ' + mm + ':' + (ss < 10 ? '0' : '') + ss + '.' + cs, R + 12, 150, '#fcfcfc', 10); + var tier = null; if (G.tiers) Object.keys(G.tiers).forEach(function (k) { if (Math.abs(G.tiers[k] - c.d) < 1e-9) tier = k; }); + txt(x, (tier ? tier.toUpperCase() : 'D=' + c.d.toFixed(2)), R + 12, 172, '#f8b800', 10); + txt(x, (G.hz || B.FPS) + 'Hz', R + 158, 466, '#3cbcfc', 12, 'right'); + txt(x, 'NES 1987 RULES', R + 12, 444, '#5c5c7c', 7); + if (extra) txt(x, extra, R + 12, 200, '#f8b800', 8); + // ---- banners over the room ---- + if (o.intro > 0 && !c.result) txt(x, 'READY', W / 2, 220, (c.t >> 3) & 1 ? '#fcfcfc' : '#3cbcfc', 18, 'center'); + if (c.result === 'win') { txt(x, 'BOSS DEFEATED', W / 2, 200, '#f8b800', 18, 'center'); txt(x, 'YOU GOT ' + MM.WEAPONS[info2.weapon].name.toUpperCase(), W / 2, 232, '#fcfcfc', 11, 'center'); } + else if (c.result === 'loss') txt(x, 'GAME OVER', W / 2, 220, '#f87858', 18, 'center'); + else if (c.result === 'timeout') txt(x, 'TIME UP', W / 2, 220, '#f87858', 18, 'center'); + x.restore(); + } + B.BODY_DRAW.megaman = { draw: function () {}, fullHud: hud }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/draw/palette.js b/environments/games/web/games/megaman_remake/draw/palette.js new file mode 100644 index 0000000000000000000000000000000000000000..261fccbdced8254e4c6bcc5d7bd765225c6a1390 --- /dev/null +++ b/environments/games/web/games/megaman_remake/draw/palette.js @@ -0,0 +1,22 @@ +// Original procedural NES-style art for the three Robot Master rooms (no ROM graphics are used or shipped). +// The renderer maps NES pixels to the 854x480 frame with an integer 2x scale: the 256x240 room is drawn at +// 512x480, centred with 171 px side panels that carry the HUD (weapon menu, bars, timer, native Hz). +// Pure presentation: reads the case, never writes it; animation uses presentation time t only. +(function (g) { + var B = g.BB, A = B.ART, MM = B.MM, V = B.VIEW; + var SCALE = 2, OX = 171, OY = 0; + // the shared renderer computed its own layout from BB.ARENA; replace it with the NES room mapping + V.S = SCALE; V.OX = OX; V.FLOOR = OY + MM.FLOOR * SCALE; + V.sx = function (x) { return OX + x * SCALE; }; + V.sy = function (y) { return OY + y * SCALE; }; + V.PAL = { boss: '#3c7cf0', tele: '#f8d878' }; + // NES-like master palette subset (hand-picked RGB, not copied from any emulator palette file) + var NES = MM.PAL = { + black: '#000000', white: '#fcfcfc', grey: '#7c7c7c', light: '#bcbcbc', + blue: '#0078f8', sky: '#3cbcfc', navy: '#0000bc', cyan: '#00e8d8', skin: '#fcd8a8', + red: '#d82800', orange: '#f87858', yellow: '#f8b800', gold: '#fce0a8', green: '#00b800', teal: '#008888', + purple: '#6844fc', ice: '#a4e4fc', frost: '#e4f8fc', fire: '#f83800', ember: '#fca044', brick: '#a81000' + }; + MM.SCREEN = { SCALE: SCALE, OX: OX, OY: OY }; + A.view = { W: 854, H: 480, OX: OX, FLOOR: V.FLOOR, ROOF: OY, S: SCALE }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/draw/player.js b/environments/games/web/games/megaman_remake/draw/player.js new file mode 100644 index 0000000000000000000000000000000000000000..3bf3baa1739ecd0ee6eb967c4e491435ec537411 --- /dev/null +++ b/environments/games/web/games/megaman_remake/draw/player.js @@ -0,0 +1,130 @@ +// Original NES-style pixel sprites for Mega Man and the shots, drawn at native resolution (1 unit = 1 NES pixel). +// Shapes are hand-authored here as small character grids; they are not traced from any Capcom sprite sheet. +(function (g) { + var B = g.BB, MM = B.MM, P = MM.PAL, px = MM.px; + // grid painter: each string row is one pixel row; '.' = transparent, other chars index the colour map. + // With `dup` (row indexes to draw twice) the trailing blank rows are dropped and the picture is bottom-aligned + // to a 24-pixel box starting at Y, so a stretched figure stands exactly on the floor line of its hitbox. + function sprite(x, rows, map, X, Y, flip, dup) { + if (dup) { + var keep = rows.slice(), out = []; + while (keep.length && !/[^.]/.test(keep[keep.length - 1])) keep.pop(); + keep.forEach(function (row, i) { out.push(row); if (dup.indexOf(i) >= 0) out.push(row); }); + Y += 24 - out.length; rows = out; + } + var w = rows[0].length; + for (var r = 0; r < rows.length; r++) { + var row = rows[r]; + for (var c = 0; c < w; c++) { + var ch = row.charAt(flip ? w - 1 - c : c); + if (ch === '.') continue; + x.fillStyle = map[ch]; x.fillRect(X + c, Y + r, 1, 1); + } + } + } + MM.sprite = sprite; + // 24 x 24 player frames (body box 16 x 24 centred); k = outline, b = dark armour, l = light armour, s = skin, + // w = eye white, e = pupil + var STAND = [ + '........kkkkk...........', '......kkbbbbbkk.........', '.....kbbbllllbbk........', '....kbbblllllllbk.......', + '....kbbllllwwwlbk.......', '....kbblswwwewwsk.......', '....kbblswwweswsk.......', '.....kbbssssssssk.......', + '......kbbsskkssk........', '.....kkbbbsssskkk.......', '....klllbbbkkbbllk......', '...kllllbbbbbbbllk......', + '...kllkllbbbbbbkllk.....', '...kssk.kbbbbbbkssk.....', '....kk..klllllbk.kk.....', '........kllklllk........', + '.......kbbbk.kbbbk......', '......kbbbbk.kbbbbk.....', '.....kbbbbbk.kbbbbbk....', '.....kkkkkkk.kkkkkkk....', + '........................', '........................', '........................', '........................']; + var SHOOT = [ + '........kkkkk...........', '......kkbbbbbkk.........', '.....kbbbllllbbk........', '....kbbblllllllbk.......', + '....kbbllllwwwlbk.......', '....kbblswwwewwsk.......', '....kbblswwweswsk.......', '.....kbbssssssssk.......', + '......kbbsskkssk........', '.....kkbbbsssskkkkkkk...', '....klllbbbkkbbllbbbbk..', '...kllllbbbbbbbllbbbbbk.', + '...kllkllbbbbbbkllbbbbk.', '...kssk.kbbbbbbk.kkkkk..', '....kk..klllllbk........', '........kllklllk........', + '.......kbbbk.kbbbk......', '......kbbbbk.kbbbbk.....', '.....kbbbbbk.kbbbbbk....', '.....kkkkkkk.kkkkkkk....', + '........................', '........................', '........................', '........................']; + var RUN = [ + '........kkkkk...........', '......kkbbbbbkk.........', '.....kbbbllllbbk........', '....kbbblllllllbk.......', + '....kbbllllwwwlbk.......', '....kbblswwwewwsk.......', '....kbblswwweswsk.......', '.....kbbssssssssk.......', + '......kbbsskkssk........', '....kkkbbbsssskk........', '...kllllbbbkkbbllk......', '..kllllkbbbbbbbllk......', + '..kssk.klbbbbbbkllk.....', '...kk..kbbbbbbkssk......', '......klllllbbkkk.......', '.....kllkkklllbk........', + '....kbbbk..kkbbbk.......', '...kbbbbk...kbbbbk......', '..kbbbbk.....kbbbbk.....', '..kkkkk.......kkkkk.....', + '........................', '........................', '........................', '........................']; + var JUMP = [ + '........kkkkk...........', '......kkbbbbbkk.....kk..', '.....kbbbllllbbk...kssk.', '....kbbblllllllbk..kllk.', + '....kbbllllwwwlbk.kllk..', '....kbblswwwewwsk.kllk..', '....kbblswwweswsk.kbk...', '.....kbbssssssssk.kbk...', + '......kbbsskkssk.kbbk...', '.....kkbbbsssskkkbbk....', '....klllbbbkkbbllbk.....', '...kllllbbbbbbbllk......', + '..kllk.kbbbbbbbbk.......', '..kssk.klllllllbk.......', '...kk..kllllllbbk.......', '......kbbbkk.kbbk.......', + '.....kbbbbk...kbbk......', '.....kbbbk.....kbbk.....', '.....kkkk.......kkk.....', '........................', + '........................', '........................', '........................', '........................']; + var HURT = [ + '...k...kkkkk...k........', '....k.kbbbbbkk.k........', '.....kbbbllllbbk........', '....kbbblllllllbk.......', + '....kbblkkllkkkbk.......', '....kbblskwkskwsk.......', '....kbblswkkswksk.......', '.....kbbssssssssk.......', + '..kk..kbsskkkssk..kk....', '.kssk.kbbbsssskk.kssk...', '.kllkkllbbbkkbbllkllk...', '..kllllbbbbbbbbllllk....', + '...kkkllbbbbbbbllkk.....', '......kbbbbbbbbk........', '.....kllllkkllllk.......', '....kbbbbk..kbbbbk......', + '...kbbbbk....kbbbbk.....', '...kkkkk......kkkkk.....', '........................', '........................', + '........................', '........................', '........................', '........................']; + function colours(w) { + var dark = { P: P.blue, E: '#a87800', I: '#0058f8', F: P.red }[w] || P.blue; + var light = { P: P.sky, E: P.yellow, I: P.frost, F: P.ember }[w] || P.sky; + return { k: P.black, b: dark, l: light, s: P.skin, w: P.white, e: P.black }; + } + MM.drawPlayer = function (x, c, t) { + var b = c.body; + if (b.hp <= 0) return; + if (b.iframes > 0 && (b.iframes & 2)) return; // blink: hidden while bit 1 of the i-frame timer is set + var frame = b.knockT > 0 || b.stunT > 0 ? HURT : !b.grounded ? JUMP : b.shootT > 0 ? SHOOT : b.speed > 0.5 ? RUN : STAND; + if (frame === RUN && (Math.floor(c.t / 8) & 1)) frame = STAND; // two-step run cycle + var map = colours(b.weapon); + // 20-row figure stretched to 22 rows (= the 14x22 touch box) and standing on the 16x24 body's floor line + sprite(x, frame, map, Math.round(b.x) - 12, Math.round(b.y) - 12, b.facing < 0, [10, 16]); + }; + + // ---------- player shots ---------- + MM.drawPlayerShots = function (x, c, t) { + var b = c.body; + b.shots.forEach(function (s) { + var X = Math.round(s.x), Y = Math.round(s.y); + if (s.kind === 'buster') { px(x, X - 3, Y - 2, 6, 4, P.yellow); px(x, X - 2, Y - 3, 4, 6, P.yellow); px(x, X - 1, Y - 1, 2, 2, P.white); } + else if (s.kind === 'slasher') MM.drawSlasher(x, s, 8); + else if (s.kind === 'fire_wave' || s.kind === 'fire_shield') MM.drawFlame(x, X, Y + 8, 16, 16, c.t >> 2, false); + else if (s.kind === 'thunder' || s.kind === 'thunder_v') MM.drawBolt(x, s, c.t, true); + else if (s.kind === 'cutter') MM.drawCutter(x, X, Y, c.t, s.hw); + else if (s.kind === 'hyper_bomb') MM.drawBomb(x, X, Y, c.t, s.fuse > 110); + else if (s.kind === 'hyper_flame') MM.drawFlame(x, X, Y + 8, 16, 16, c.t >> 1, false); + else if (s.kind === 'held_block' || s.kind === 'thrown_block') MM.drawBlock(x, X, Y, s.hw); + else if (s.kind === 'block_chunk') MM.drawChunk(x, X, Y, '#7c7c7c', '#bcbcbc'); + }); + }; + // zigzag electric segment covering the hitbox (hw x hh), flickering between two shapes + MM.drawBolt = function (x, s, tick, player) { + var X = Math.round(s.x), Y = Math.round(s.y), hw = s.hw, hh = s.hh, ph = (tick >> 1) & 1; + var core = ph ? P.white : P.yellow, edge = player ? P.yellow : P.gold, pts = [], k; + // a jagged polyline that spans the hitbox along its long axis, so the picture covers exactly what hurts + if (hh >= hw) for (k = -hh; k <= hh; k += 4) pts.push([X + (((k + hh) >> 2) & 1 ? hw - 1 : 1 - hw) * (ph ? 1 : -1), Y + k]); + else for (k = -hw; k <= hw; k += 4) pts.push([X + k, Y + (((k + hw) >> 2) & 1 ? hh - 1 : 1 - hh) * (ph ? 1 : -1)]); + for (k = 1; k < pts.length; k++) MM.seg(x, pts[k - 1][0], pts[k - 1][1], pts[k][0], pts[k][1], edge, 3); + for (k = 1; k < pts.length; k++) MM.seg(x, pts[k - 1][0], pts[k - 1][1], pts[k][0], pts[k][1], core, 1); + }; + // pixel line: squares of size w stepped along the segment + MM.seg = function (x, x0, y0, x1, y1, col, w) { + var n = Math.max(Math.abs(x1 - x0), Math.abs(y1 - y0)) || 1, h = w >> 1; + x.fillStyle = col; + for (var i = 0; i <= n; i++) x.fillRect(Math.round(x0 + (x1 - x0) * i / n) - h, Math.round(y0 + (y1 - y0) * i / n) - h, w, w); + }; + // Ice Slasher: a chevron of three ice blades pointing along its flight, filling the hitbox (half = half-size) + MM.drawSlasher = function (x, s, half) { + var X = Math.round(s.x), Y = Math.round(s.y), f = s.dir || 1, h = half; + for (var r = -h; r < h; r++) { + var d = Math.abs(r + 0.5), len = Math.max(2, Math.round(2 * h - d * 1.6)), tip = f > 0 ? X + h - Math.round(d * 0.8) : X - h + Math.round(d * 0.8); + px(x, f > 0 ? tip - len : tip, Y + r, len, 1, d < 1 ? P.white : (r & 1) ? P.ice : '#3cbcfc'); + } + px(x, f > 0 ? X + h - 2 : X - h, Y - 1, 2, 2, P.white); + }; + // a flame of exactly w x h pixels standing on (X, bottom); `ph` animates the tongues + MM.drawFlame = function (x, X, bottom, w, h, ph, dim) { + var outer = dim ? '#a81000' : P.fire, mid = dim ? P.fire : P.ember, core = dim ? P.ember : P.yellow; + for (var c2 = 0; c2 < w; c2++) { + var k = Math.abs(c2 - (w - 1) / 2) / (w / 2), tongue = Math.round(h * (1 - 0.35 * k * k) - (((c2 + ph) & 3) === 0 ? 3 : 0)); + px(x, X - (w >> 1) + c2, bottom - tongue, 1, tongue, outer); + if (k < 0.75) px(x, X - (w >> 1) + c2, bottom - Math.round(tongue * 0.75), 1, Math.round(tongue * 0.75), mid); + if (k < 0.35) px(x, X - (w >> 1) + c2, bottom - Math.round(tongue * 0.45), 1, Math.round(tongue * 0.45), core); + } + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/draw/rooms.js b/environments/games/web/games/megaman_remake/draw/rooms.js new file mode 100644 index 0000000000000000000000000000000000000000..1bb1e0f903a506e5e7697d49a3d2e43b2d934d1a --- /dev/null +++ b/environments/games/web/games/megaman_remake/draw/rooms.js @@ -0,0 +1,241 @@ +// Original procedural backgrounds for the Robot Master rooms at NES resolution, and the boss sprites. +// Rooms: Elec Man's generator hall (circuit panels, conduit), Ice Man's frozen hangar (snow blocks, icicles), +// Fire Man's furnace (brick, lava glow), Bomb Man's demolition yard (girders, hazard stripes, the open roof at +// x 96-159 of the original room). Static layers are cached per case; flicker/scroll uses time only. +(function (g) { + var B = g.BB, MM = B.MM, P = MM.PAL, px = MM.px, sprite = MM.sprite; + var cache = {}; + function H(i) { var s = Math.sin(i * 91.7 + 17.3) * 43758.5453; return s - Math.floor(s); } + + function roomElec(x) { + px(x, 0, 0, 256, 240, '#000000'); + for (var cx = 0; cx < 256; cx += 32) for (var cy = 16; cy < 192; cy += 32) { // circuit panels + px(x, cx + 1, cy + 1, 30, 30, '#00285c'); px(x, cx + 3, cy + 3, 26, 26, '#00184a'); + for (var k = 0; k < 4; k++) { var lx = cx + 5 + Math.floor(H(cx * 7 + cy + k) * 20), ly = cy + 5 + k * 6; px(x, lx, ly, 6, 1, '#0058a8'); px(x, lx + 5, ly, 1, 4, '#0058a8'); } + px(x, cx + 14, cy + 14, 4, 4, '#a87800'); + } + px(x, 0, 0, 256, 16, '#202020'); for (var i = 0; i < 256; i += 8) px(x, i, 12, 6, 2, '#a87800'); + floor(x, '#585858', '#a8a8a8', '#202020'); + walls(x, '#404040', '#787878'); + } + function roomIce(x) { + px(x, 0, 0, 256, 240, '#000028'); + for (var s = 0; s < 70; s++) px(x, Math.floor(H(s) * 256), 16 + Math.floor(H(s + 99) * 170), 1, 1, s % 3 ? '#3cbcfc' : '#fcfcfc'); + for (var cx = 0; cx < 256; cx += 16) { var h = 6 + Math.floor(H(cx) * 18); for (var y = 0; y < h; y += 2) px(x, cx + 4 + (y >> 2), 16 + y, Math.max(1, 8 - y / 2), 2, y < 4 ? '#fcfcfc' : '#a4e4fc'); } + px(x, 0, 0, 256, 16, '#a4e4fc'); for (var i = 0; i < 256; i += 16) px(x, i, 0, 15, 15, '#e4f8fc'); + floor(x, '#a4e4fc', '#fcfcfc', '#3cbcfc'); + walls(x, '#3cbcfc', '#e4f8fc'); + } + function roomFire(x) { + px(x, 0, 0, 256, 240, '#280000'); + for (var cy = 16; cy < 192; cy += 8) for (var cx = ((cy >> 3) & 1) * 8; cx < 256; cx += 16) px(x, cx + 1, cy + 1, 14, 6, (cx + cy) % 48 ? '#580000' : '#781800'); + px(x, 0, 0, 256, 16, '#a81000'); for (var i = 0; i < 256; i += 16) px(x, i + 2, 4, 12, 8, '#d82800'); + floor(x, '#a81000', '#f87858', '#500000'); + walls(x, '#781800', '#d82800'); + } + function roomBomb(x) { + px(x, 0, 0, 256, 240, '#001800'); + for (var cx = 16; cx < 240; cx += 48) { // steel girders + px(x, cx, 32, 6, 160, '#005800'); px(x, cx + 1, 32, 1, 160, '#00a800'); + for (var gy = 40; gy < 192; gy += 24) { px(x, cx + 6, gy, 18, 2, '#005800'); px(x, cx + 6 + ((gy >> 3) % 3) * 4, gy + 2, 2, 10, '#004000'); } + } + for (var s = 0; s < 30; s++) px(x, 96 + Math.floor(H(s) * 64), Math.floor(H(s + 7) * 30), 1, 1, '#fcfcfc'); // sky through the roof gap + [[0, 96], [160, 96]].forEach(function (r) { + px(x, r[0], 0, r[1], 32, '#7c7c7c'); + for (var i = r[0]; i < r[0] + r[1]; i += 16) { px(x, i, 0, 16, 1, '#bcbcbc'); px(x, i + 15, 0, 1, 32, '#3c3c3c'); px(x, i, 16, 16, 1, '#3c3c3c'); } + for (var j = r[0]; j < r[0] + r[1]; j += 8) px(x, j, 28, 4, 4, '#f8b800'); // hazard stripe + }); + floor(x, '#7c7c7c', '#bcbcbc', '#3c3c3c'); + for (var k = 0; k < 256; k += 8) px(x, k, 194, 4, 2, '#f8b800'); + walls(x, '#3c3c3c', '#7c7c7c'); + } + function roomCut(x) { + px(x, 0, 0, 256, 240, '#2c1c00'); + for (var cy = 32; cy < 192; cy += 32) for (var cx = 0; cx < 256; cx += 32) { // timber frames of the logging yard + px(x, cx + 1, cy + 1, 30, 30, '#4c3000'); px(x, cx + 2, cy + 15, 28, 2, '#2c1c00'); px(x, cx + 15, cy + 2, 2, 28, '#2c1c00'); + } + px(x, 0, 0, 256, 32, '#7c5c00'); for (var i = 0; i < 256; i += 16) { px(x, i, 0, 15, 15, '#a87800'); px(x, i + 8, 16, 15, 15, '#a87800'); } + floor(x, '#7c5c00', '#d8a038', '#3c2800'); + walls(x, '#4c3000', '#a87800'); + px(x, 16, 160, 16, 32, '#3c3c3c'); px(x, 16, 160, 16, 2, '#7c7c7c'); // the solid tiles beside the wall + } + function roomGuts(x) { + px(x, 0, 0, 256, 240, '#1c1408'); + for (var cy = 0; cy < 192; cy += 16) for (var cx = ((cy >> 4) & 1) * 12; cx < 256; cx += 24) { // quarry face: offset courses of rough stone + var v = H(cx * 3 + cy); px(x, cx + 1, cy + 1, 22, 14, v < 0.33 ? '#3c2c14' : v < 0.66 ? '#30220e' : '#463418'); + px(x, cx + 3 + Math.floor(v * 12), cy + 4, 5, 1, '#5c4820'); + } + for (var tx = 40; tx < 240; tx += 64) { px(x, tx, 0, 6, 192, '#5c3c10'); px(x, tx + 1, 0, 1, 192, '#8c6420'); } // timber props + floor(x, '#5c4820', '#a88c48', '#2c2008'); + [0, 240].forEach(function (wx) { + px(x, wx, 0, 16, 192, '#463418'); + for (var y = 0; y < 192; y += 16) { px(x, wx, y, 16, 1, '#8c6c30'); px(x, wx + 15, y, 1, 16, '#000000'); } + }); + px(x, 16, 160, 16, 32, '#463418'); px(x, 16, 160, 16, 2, '#a88c48'); // the solid tiles beside the wall + } + // one liftable block (override type 2): 32 x 32 of cracked stone, also what the player carries and throws + MM.drawBlock = function (x, X, Y, h) { + px(x, X - h, Y - h, h * 2, h * 2, '#000000'); px(x, X - h + 1, Y - h + 1, h * 2 - 2, h * 2 - 2, '#7c7c7c'); + px(x, X - h + 1, Y - h + 1, h * 2 - 2, 2, '#bcbcbc'); px(x, X - h + 1, Y - h + 1, 2, h * 2 - 2, '#bcbcbc'); + px(x, X - h + 8, Y - 6, 8, 2, '#3c3c3c'); px(x, X + 2, Y + 2, 8, 2, '#3c3c3c'); + }; + // Guts Man's boulder (28 x 28 hitbox) and a chunk of it (8 x 8): every pixel of the box is drawn, so what you see is what hurts + MM.drawRock = function (x, X, Y, h, t) { + px(x, X - h, Y - h + 3, h * 2, h * 2 - 6, '#000000'); px(x, X - h + 3, Y - h, h * 2 - 6, h * 2, '#000000'); + px(x, X - h + 1, Y - h + 4, h * 2 - 2, h * 2 - 8, '#a87800'); px(x, X - h + 4, Y - h + 1, h * 2 - 8, h * 2 - 2, '#a87800'); + px(x, X - h + 4, Y - h + 3, h - 2, 3, '#f8d878'); px(x, X - 2, Y + 2, 8, 2, '#5c3c10'); px(x, X - 8, Y - 3, 5, 2, '#5c3c10'); + }; + MM.drawChunk = function (x, X, Y, a, b) { px(x, X - 4, Y - 4, 8, 8, '#000000'); px(x, X - 3, Y - 3, 6, 6, a); px(x, X - 3, Y - 3, 3, 2, b); }; + function floor(x, base, top, dark) { + px(x, 0, 192, 256, 48, base); + for (var i = 0; i < 256; i += 16) { px(x, i, 192, 16, 2, top); px(x, i + 15, 192, 1, 16, dark); px(x, i, 207, 16, 1, dark); px(x, i + 7, 208, 1, 16, dark); px(x, i, 223, 16, 1, dark); } + } + function walls(x, base, top) { + [0, 240].forEach(function (wx) { + px(x, wx, 16, 16, 176, base); + for (var y = 16; y < 192; y += 16) { px(x, wx, y, 16, 1, top); px(x, wx + 15, y, 1, 16, '#000000'); } + }); + } + var ROOMS = { 'megaman/elec_man': roomElec, 'megaman/ice_man': roomIce, 'megaman/fire_man': roomFire, 'megaman/bomb_man': roomBomb, 'megaman/cut_man': roomCut, 'megaman/guts_man': roomGuts }; + MM.drawRoom = function (x, c, t) { + var key = c.id, img = cache[key]; + if (!img) { + var doc = x.canvas.ownerDocument || g.document, cv = doc.createElement('canvas'); cv.width = 256; cv.height = 240; + ROOMS[key](cv.getContext('2d')); img = cache[key] = cv; + } + x.drawImage(img, 0, 0); + c.body.room.forEach(function (r) { if (r.block) MM.drawBlock(x, r.x0 + 16, r.y0 + 16, 16); }); // lifted blocks leave the list + if (key === 'megaman/fire_man') { // furnace glow rising from the floor seams + for (var i = 0; i < 16; i++) { var f = (Math.floor(t * 8) + i * 3) % 6; px(x, i * 16 + 6, 186 - f, 3, 2, f < 3 ? P.ember : P.fire); } + } else if (key === 'megaman/elec_man') { + var on = Math.floor(t * 6) % 8; px(x, on * 32 + 14, 30, 4, 4, P.yellow); + } + }; + + // ---------- bosses: 24 x 24 grids, k outline ---------- + var ELEC = [ + '...........kk...........', '..........kyyk..........', '.........kyyyyk.........', '........kkrrrrkk........', + '.......kddrrrrddk.......', '.......kdwwkwwkdk.......', '.......kdswswssdk.......', '.......kdssssssdk.......', + '........kdsskssk........', '......kkkdddddkkkk......', '.....kyyddkkkddyyyk.....', '....kyyyddddddddyyyk....', + '....kyykddddddddkyyk....', '....kssk.kddddddkssk....', '.....kk..kyyyyyyk.kk....', '.........kyykkyyk.......', + '........kdddk.kdddk.....', '.......kddddk.kddddk....', '......kyyyyyk.kyyyyyk...', '......kkkkkkk.kkkkkkk...', + '........................', '........................', '........................', '........................']; + var ICE = [ + '........................', '.........kkkkkk.........', '.......kkbbbbbbkk.......', '......kbbffffffbbk......', + '.....kbbfkkkkkkfbbk.....', '.....kbfkswwswwkfbk.....', '.....kbfkswesweskfbk....', '.....kbfksssssskfbk.....', + '.....kbbfkkkkkkfbbk.....', '......kbbffffffbbk......', '.....kkbbbbbbbbbbkk.....', '....kffbbbbbbbbbbffk....', + '....kffkbbbbbbbbkffk....', '....kssk.kbbbbbbkssk....', '.....kk..kffffffk.kk....', '.........kffkkffk.......', + '........kbbbk.kbbbk.....', '.......kbbbbk.kbbbbk....', '.......kffffk.kffffk....', '.......kkkkkk.kkkkkk....', + '........................', '........................', '........................', '........................']; + var FIRE = [ + '.........y..y...........', '........yoyyoy..........', '.......yooooooy.........', '.......kkookookk........', + '......kgggkkkgggk.......', '......kgwwkkwwkgk.......', '......kgwekkewkgk.......', '......kgkkkkkkkgk.......', + '.......kgggggggk........', '......kkrrrrrrrkkk......', '.....krrrrkkkrrrrrk.....', '....krrrgrrrrrgrrrrk....', + '....krrkrrrrrrrrkrrk....', '....kook.krrrrrrkook....', '.....kk..kgggggok.kk....', '.........kggkkggk.......', + '........krrrk.krrrk.....', '.......krrrrk.krrrrk....', '.......kggggk.kggggk....', '.......kkkkkk.kkkkkk....', + '........................', '........................', '........................', '........................']; + var BOMB = [ + '..........kkk...........', '.........kwwwk..........', '.........kkkkk..........', '.......kkggggkk.........', + '......kgggggggggk.......', '......kgwwkkwwkgk.......', '......kgwekkewkgk.......', '......kgkssssskgk.......', + '.......kgggggggk........', '......kkllllllllkk......', '.....kllllkkkllllk......', '....kllgllllllllgllk....', + '....kllkllllllllkllk....', '....kssk.kllllllkssk....', '.....kk..kggggggk.kk....', '.........kggkkggk.......', + '........klllk.klllk.....', '.......kllllk.kllllk....', '.......kggggk.kggggk....', '.......kkkkkk.kkkkkk....', + '........................', '........................', '........................', '........................']; + var CUT = [ + '..........k....k........', '.........krk..krk.......', '..........krkkrk........', '...........krrk.........', + '.......kkkkkkkkkk.......', '......krrrrrrrrrrk......', '......krwwkrrwwkrk......', '......krwekssewkrk......', + '.......kssssssssk.......', '......kkrrrrrrrrkkk.....', '.....krrrrkkkrrrrrk.....', '....krrrwrrrrrwrrrrk....', + '....krrkrrrrrrrrkrrk....', '....kssk.krrrrrrkssk....', '.....kk..kwwwwwwk.kk....', '.........kwwkkwwk.......', + '........krrrk.krrrk.....', '.......krrrrk.krrrrk....', '.......kwwwwk.kwwwwk....', '.......kkkkkk.kkkkkk....', + '........................', '........................', '........................', '........................']; + var MAPS = { + elec_man: { k: '#000000', y: '#f8b800', r: '#d82800', d: '#a87800', w: '#fcfcfc', s: '#fcd8a8', e: '#000000' }, + ice_man: { k: '#000000', b: '#0078f8', f: '#fcfcfc', w: '#fcfcfc', s: '#fcd8a8', e: '#000000' }, + fire_man: { k: '#000000', y: '#f8b800', o: '#f87858', r: '#d82800', g: '#7c7c7c', w: '#fcfcfc', e: '#000000' }, + bomb_man: { k: '#000000', g: '#00a800', l: '#b8f818', w: '#fcfcfc', s: '#fcd8a8', e: '#000000' }, + cut_man: { k: '#000000', r: '#d82800', w: '#fcfcfc', s: '#fcd8a8', e: '#000000' } + }; + var GRIDS = { elec_man: ELEC, ice_man: ICE, fire_man: FIRE, bomb_man: BOMB, cut_man: CUT }; + var WHITE = {}; 'kyrdwsebfogl'.split('').forEach(function (ch) { WHITE[ch] = '#fcfcfc'; }); + // bosses stand on the floor with a 16x24 body box: the 20-row grids are stretched to 24 rows by doubling the + // torso and leg rows, so the drawn body covers the hitbox exactly (feet on the floor, head at the box top) + var BOSS_DUP = [10, 11, 16, 17]; + // Guts Man fills his 32 x 32 hitbox (anims $25-$30 are 16 x 16 half size), so he is drawn from rectangles, not the 24-grid + function gutsBody(x, o, white) { + var X = Math.round(o.x), Y = Math.round(o.y), f = o.look, crouch = o.pose === 'crouch' || o.pose === 'land' ? 3 : 0, up = o.pose === 'lift' || o.pose === 'air'; + function r(rx, ry, w, h, col) { px(x, f > 0 ? X + rx : X - rx - w, Y + ry, w, h, white ? '#fcfcfc' : col); } + r(-11, 8, 10, 8, '#000000'); r(1, 8, 10, 8, '#000000'); r(-10, 9, 8, 6, '#d82800'); r(2, 9, 8, 6, '#d82800'); // boots + r(-12, -4 + crouch, 24, 13 - crouch, '#000000'); r(-11, -3 + crouch, 22, 11 - crouch, '#a81000'); r(-5, 0 + crouch, 10, 4, '#f8b800'); // torso, belt plate + r(-16, up ? -16 : -4 + crouch, 5, up ? 14 : 12, '#000000'); r(-15, up ? -15 : -3 + crouch, 3, up ? 12 : 10, '#fcd8a8'); // back arm + r(11, up ? -16 : -4 + crouch, 5, up ? 14 : 12, '#000000'); r(12, up ? -15 : -3 + crouch, 3, up ? 12 : 10, '#fcd8a8'); // front arm + r(-10, -16 + crouch, 20, 13, '#000000'); r(-9, -15 + crouch, 18, 11, '#f8b800'); r(-9, -15 + crouch, 18, 2, '#fce0a8'); // helmet + r(-2, -13 + crouch, 4, 2, '#d82800'); + r(-5, -10 + crouch, 13, 7, '#fcd8a8'); r(1, -9 + crouch, 2, 2, '#000000'); r(6, -9 + crouch, 2, 2, '#000000'); r(-3, -5 + crouch, 11, 2, '#fcfcfc'); // face, jaw + } + function bossSprite(x, c, t) { + var o = c.boss, id = o.id; + if (o.hp <= 0) return; + var R = MM.RobotMaster, since = R.INTRO - o.intro; + if (o.intro > 0 && since < 24 && ((since >> 2) & 1)) return; // the boss materialises during its intro + if (id === 'guts_man') { + if (o.pose === 'lift' && o.st === 'throw_rock') MM.drawRock(x, Math.round(o.x) + 16 * o.look, Math.round(o.y) - 24, 14, c.t); // the boulder he is about to throw + gutsBody(x, o, ((o.iframes + 1) & 2) !== 0); + return; + } + // white flash: draw_entity tests bit 1 of boss_iframes BEFORE its render-time decrement; the simulation has + // already decremented it at the end of the tick, so the pre-decrement value is iframes + 1 + if ((o.iframes + 1) & 2) { sprite(x, GRIDS[id], WHITE, Math.round(o.x) - 12, Math.round(o.y) + 12 - 24, o.look < 0, BOSS_DUP); return; } + sprite(x, GRIDS[id], MAPS[id], Math.round(o.x) - 12, Math.round(o.y) + 12 - 24, o.look < 0, BOSS_DUP); + if (id === 'bomb_man' && o.pose === 'windup') { // the bomb held over his head while he winds up + MM.drawBomb(x, Math.round(o.x) - 4 * o.look, Math.round(o.y) - 18, c.t, o.windup < 8); + } + if (o.windup > 0 && (o.pose === 'fire' || o.pose === 'stance' || o.pose === 'summon' || o.pose === 'windup')) { // telegraph glint + var gx = Math.round(o.x) + 10 * o.look, gy = Math.round(o.y) - 4; + if ((o.windup >> 1) & 1) { px(x, gx - 2, gy - 2, 4, 4, '#fcfcfc'); px(x, gx - 4, gy, 8, 1, '#fcfcfc'); px(x, gx, gy - 4, 1, 8, '#fcfcfc'); } + } + } + // every hazard is drawn to its exact hitbox (hw x hh around its centre), so what you see is what hurts + function projectiles(x, c, t) { + c.boss.projectiles.forEach(function (p) { + var X = Math.round(p.x), Y = Math.round(p.y); + if (p.kind === 'thunder_beam') MM.drawBolt(x, p, c.t, false); + else if (p.kind === 'ice_slasher') { px(x, X - 6, Y - 5, 12, 10, 'rgba(0,0,40,.55)'); MM.drawSlasher(x, p, 4); } + else if (p.kind === 'fire_wave') MM.drawFlame(x, X, Y + p.hh, p.hw * 2, p.hh * 2, (c.t >> 2) + p.id, false); // harmful while forming too + else if (p.kind === 'bomb' || p.kind === 'intro_bomb') MM.drawBomb(x, X, Y, c.t, false); + else if (p.kind === 'shrapnel' || p.kind === 'dust') MM.drawShard(x, p, c.t); + else if (p.kind === 'rolling_cutter') MM.drawCutter(x, X, Y, c.t, p.hw); + else if (p.kind === 'rock' || p.kind === 'ceiling_rock') MM.drawRock(x, X, Y, p.hw, c.t); + else if (p.kind === 'rock_chunk') MM.drawChunk(x, X, Y, '#a87800', '#f8d878'); + else if (p.kind === 'fire_pillar') { + MM.drawFlame(x, X, Y + p.hh, p.hw * 2, p.hh * 2, (c.t >> 1) + 1, p.t < 30 && (c.t & 4)); + } + }); + } + // the Rolling Cutter: open scissors spinning through four shapes, filling its hitbox + MM.drawCutter = function (x, X, Y, t, h) { + var k = (t >> 2) & 3, a = [[1, 1], [1, 0], [1, -1], [0, 1]][k], n = h + 1; + for (var i = -n; i <= n; i++) { + px(x, X + i * a[0] - 1, Y + i * a[1] - 1, 3, 3, i < 0 ? '#fcfcfc' : '#bcbcbc'); + px(x, X - i * a[1] - 1, Y + i * a[0] - 1, 3, 3, '#fcfcfc'); + } + px(x, X - 1, Y - 1, 3, 3, '#d82800'); + }; + // the boss bomb: an 8x8-radius black sphere with a fuse spark (16x16 hitbox drawn as 14 px + outline) + MM.drawBomb = function (x, X, Y, t, flash) { + px(x, X - 6, Y - 5, 12, 12, '#000000'); px(x, X - 7, Y - 3, 14, 8, '#000000'); px(x, X - 5, Y - 7, 10, 2, '#000000'); + px(x, X - 5, Y - 4, 10, 9, flash && (t & 2) ? '#fcfcfc' : '#3c3c3c'); px(x, X - 3, Y - 3, 3, 2, '#bcbcbc'); + px(x, X + 1, Y - 9, 2, 3, '#7c7c7c'); px(x, X + 2, Y - 11, 2, 2, (t >> 1) & 1 ? '#f8b800' : '#fcfcfc'); + }; + // shrapnel: a white-hot star; dust: an orange-brown puff (both harmful, both drawn to the 16x16 box) + MM.drawShard = function (x, p, t) { + var X = Math.round(p.x), Y = Math.round(p.y), dust = p.kind === 'dust', k = (t + p.slot) & 1; + var hot = dust ? '#c84c0c' : '#fcfcfc', mid = dust ? '#7c3c00' : '#f8b800'; + px(x, X - 2, Y - 7, 4, 14, mid); px(x, X - 7, Y - 2, 14, 4, mid); + px(x, X - 4, Y - 4, 8, 8, hot); if (!dust) { px(x, X - 5 - k, Y - 5 - k, 2, 2, mid); px(x, X + 3 + k, Y + 3 + k, 2, 2, mid); } + else px(x, X - 6, Y - 6 + k, 3, 3, '#7c3c00'); + }; + ['megaman/elec_man', 'megaman/ice_man', 'megaman/fire_man', 'megaman/bomb_man', 'megaman/cut_man', 'megaman/guts_man'].forEach(function (id) { + B.BOSS_DRAW[id] = { hazards: function () {}, body: function () {}, boss: bossSprite, projectiles: projectiles, + bar: function () { return '#f87858'; } }; + }); +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/game.js b/environments/games/web/games/megaman_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..2d9a543599322e0f66989acfe82f6403b0aa66b4 --- /dev/null +++ b/environments/games/web/games/megaman_remake/game.js @@ -0,0 +1,34 @@ +// Mega Man (NES, 1987) · Robot Masters - game manifest for the BB.Case shell (engine/app.js). +// Public difficulty is three tiers; the spec rows (specs/*.yaml) are written at exactly these values, so +// tier = spec column and any d in between interpolates. Rule version bumps whenever rules or tiers change. +(function (g) { + var B = g.BB, MM = B.MM; + B.GAME = { + id: 'megaman_remake', + title: 'Mega Man · Boss Rush', + rules: 'megaman-nes-20261105-r4', + tiers: { easy: 0, normal: 0.5, hard: 1 }, + hz: 60, + defaultCase: 'megaman/elec_man', + hitstop: false, // the NES game has no hit-stop + results: { win: 'BOSS DEFEATED', loss: 'GAME OVER', timeout: 'TIME UP' }, + roster: [ + { id: 'megaman/elec_man', name: 'POUNCER · Counterattack Unit', arch: 'Fast movement · Counters every shot · Crawling zigzag arcs (10 damage). Weak to the returning blade' }, + { id: 'megaman/ice_man', name: 'V GUNNER · V-Shot Unit', arch: 'Fixed barrage · Jumps straight up and fires six blades in a V, faster as the fight goes on. Weak to the tri arc (10 damage)' }, + { id: 'megaman/fire_man', name: 'WAVE KEEPER · Ground-Wave Unit', arch: 'Keeps 96 px away · Ground-hugging fire waves and flames beneath your feet · Counterattacks when hit. Weak to the pierce dart (4 damage)' }, + { id: 'megaman/bomb_man', name: 'SHARD LOBBER · Bomb Unit', arch: 'Random jumps · Throws 1–3 bombs that burst into 12-way shrapnel on landing · Leaps away at close range. Weak to orbit guard (4 damage)' }, + { id: 'megaman/cut_man', name: 'BLADE TOSSER · Returning-Blade Unit', arch: 'Random jumps · Throws a blade that returns · The room has steps and two liftable rocks. Weak to the rock throw (14 damage)' }, + { id: 'megaman/guts_man', name: 'QUAKE HURLER · Ground-Shock Unit', arch: 'Landing shakes the screen and stuns grounded players · Catches falling ceiling rocks and throws them, splitting each into four · Two rocks can be lifted. Weak to the timed bomb (10 damage)' } + ], + // weapon x boss damage, the demonstrable counter chain of this round (data/weapons.js is the source) + chain: [['elec_man', 'E', 'ice_man'], ['ice_man', 'I', 'fire_man'], ['fire_man', 'F', 'bomb_man'], ['cut_man', 'C', 'elec_man'], ['guts_man', 'G', 'cut_man'], ['bomb_man', 'B', 'guts_man']], + // human play on the page: the weapons won so far (page.js keeps them); the harness passes options itself + resetOptions: function () { return { weapons: (B.MM_PAGE && B.MM_PAGE.loadout()) || [] }; } + }; + B.GAME.skillText = {}; + B.GAME.roster.forEach(function (r) { + var id = r.id.split('/')[1], spec = B.SPECS[id], text = B.GAME.skillText[r.id] = {}; + spec.moves.forEach(function (m) { text[m.name] = m.cue + ' → ' + m.punish; }); + }); + MM.caseBoss = function (caseId) { return String(caseId).split('/')[1]; }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/index.html b/environments/games/web/games/megaman_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..2be478d8db63f371ef1ea108c6aaad64f819999d --- /dev/null +++ b/environments/games/web/games/megaman_remake/index.html @@ -0,0 +1,14 @@ +Mega Man · Boss Rush — BossBench +
BOSSBENCH / 2DNES 1987 · 60 Hz

MEGA MAN BOSS RUSH

Boss battles recreated from the 1987 NES rules. Defeat bosses to acquire their weapons and follow the weakness chain. No slide or charge shot.

+

STAGE SELECT · Select Boss

0.50

Select acquired weapons to bring them into the challenge. Defeating a boss unlocks its weapon. Hard uses original values (boss projectile damage: 10 units; contact damage: 4 units).

+
+ +

Controls · CONTROLS

  • AD / arrow keys to move; Space / Z to jump; hold for more height
  • J / X / left mouse button to fire (one shot per press, up to three Arm Gun shots on screen)
  • Q / E switch weapons (replaces the original pause menu: switching recalls the active special shot; fired Arm Gun shots continue moving but no longer deal damage)
  • P/Esc to pause; then Q to go back; after a result, press R to retry. Scripted Demo runs reference script BB.GAME.scripted
  • Sliding was added in Mega Man 3 and charge shots in Mega Man 4; neither is available here

Weapon × boss damage table (NES units)

Skill list

    +
    Replay and step playback
    One packet every 200 ms; replays are deterministic with the same seed, options, and rules
    +
    Independent mechanics recreation: boss state machines, damage tables, invulnerability frames, and physics constants follow public annotated disassemblies of the first game. Visuals are original pixel art drawn in code; no original ROM images or audio are used.
    + + + + diff --git a/environments/games/web/games/megaman_remake/page.js b/environments/games/web/games/megaman_remake/page.js new file mode 100644 index 0000000000000000000000000000000000000000..4e51a86ab7b93d2fcfbadd0289873182a135e0fe --- /dev/null +++ b/environments/games/web/games/megaman_remake/page.js @@ -0,0 +1,71 @@ +// Play-page extras (browser only; harmless in Node and in the policy-env page, where the DOM nodes are absent): +// the weapon loadout chooser (weapons won so far, unlocked automatically by a win), the weapon x boss damage +// table rendered from data/weapons.js, and the "YOU GOT ..." line on the result screen. +(function (g) { + var B = g.BB, MM = B.MM; + var owned = {}; + try { owned = JSON.parse(g.localStorage && g.localStorage.getItem('bb.megaman.weapons') || '{}') || {}; } catch (e) { owned = {}; } + function save() { try { g.localStorage.setItem('bb.megaman.weapons', JSON.stringify(owned)); } catch (e) { /* file:// may refuse */ } } + B.MM_PAGE = { loadout: function () { return MM.WEAPON_ORDER.filter(function (w) { return owned[w] && MM.WEAPONS[w].built; }); } }; + var doc = g.document; + if (!doc || !doc.getElementById || !doc.getElementById('loadout')) return; + var $ = function (id) { return doc.getElementById(id); }; + + function renderLoadout() { + var host = $('loadout'); host.textContent = ''; + var lab = doc.createElement('span'); lab.textContent = 'Acquired weapons: '; host.appendChild(lab); + MM.WEAPON_ORDER.forEach(function (w) { + var info = MM.WEAPONS[w]; + if (!info.from || !info.built) return; + var l = doc.createElement('label'), cb = doc.createElement('input'); + cb.type = 'checkbox'; cb.checked = !!owned[w]; cb.dataset.weapon = w; + cb.addEventListener('change', function () { owned[w] = cb.checked; save(); }); + l.appendChild(cb); l.appendChild(doc.createTextNode(info.name + ' (defeat ' + MM.ROBOT_MASTERS[info.from].zh + ')')); + host.appendChild(l); + }); + } + function renderTable() { + var bosses = ['elec_man', 'ice_man', 'fire_man', 'cut_man', 'bomb_man', 'guts_man']; + var weapons = MM.WEAPON_ORDER.filter(function (w) { return w !== 'M'; }); + var t = doc.createElement('table'); t.className = 'dmg'; + var head = doc.createElement('tr'); head.appendChild(doc.createElement('th')); + weapons.forEach(function (w) { var th = doc.createElement('th'); th.textContent = MM.WEAPONS[w].zh; th.title = MM.WEAPONS[w].name; head.appendChild(th); }); + t.appendChild(head); + bosses.forEach(function (id) { + var tr = doc.createElement('tr'), th = doc.createElement('th'), weak = MM.weakTo(id); + th.textContent = MM.ROBOT_MASTERS[id].zh + (B.CASES['megaman/' + id] ? '' : '*'); tr.appendChild(th); + weapons.forEach(function (w) { + var td = doc.createElement('td'), v = MM.DAMAGE[id][w]; td.textContent = v; + if (w === weak) td.className = 'weak'; else if (v === 0) td.className = 'zero'; + tr.appendChild(td); + }); + t.appendChild(tr); + }); + var note = doc.createElement('p'); note.className = 'note'; + note.textContent = 'Each cell is one NES energy unit (a boss has 28 at full health). Gold marks a weakness. Values come from the original ROM. Weakness chain: Pouncer → Tri Arc → V Gunner → Pierce Dart → Wave Keeper → Orbit Guard → Shard Lobber → Fuse Lob → Quake Hurler → Rock Throw → Blade Tosser → Returning Blade → Pouncer.'; + $('dmgtable').appendChild(t); $('dmgtable').appendChild(note); + } + // the subtitle names the scenes from the roster, so the count never drifts from the code (hand-written counts did) + function renderSub() { + var el = $('mmsub'), names = B.GAME.roster.map(function (r) { return MM.ROBOT_MASTERS[MM.caseBoss(r.id)].zh; }); + var chain = B.GAME.chain.filter(function (k) { return MM.WEAPONS[k[1]].built && B.CASES['megaman/' + k[2]]; }) + .map(function (k) { return MM.WEAPONS[k[1]].zh + ' is strong against ' + MM.ROBOT_MASTERS[k[2]].zh; }); + if (el) el.textContent = 'Faithful to the 1987 NES rules across ' + names.length + ' boss battles: ' + names.join(', ') + + '. Defeat bosses to acquire their weapons. The weakness chain is: ' + chain.join(', ') + '. There is no slide or charge shot.'; + } + renderLoadout(); renderTable(); renderSub(); + // a win unlocks the boss's weapon for later fights (only for human or demo play on this page) + var result = $('result'), seen = null; + new g.MutationObserver(function () { + if (result.classList.contains('hidden')) return; + var run = g.BossBench && g.BossBench.lastRun; + if (!run || run === seen) return; + seen = run; + var boss = MM.caseBoss(run.case), info = MM.ROBOT_MASTERS[boss], w = info && info.weapon; + if (run.verifier && run.verifier.outcome === 'win' && w && MM.WEAPONS[w].built) { + var fresh = !owned[w]; owned[w] = true; save(); renderLoadout(); + $('rweapon').textContent = (fresh ? 'New weapon acquired: ' : 'Already owned: ') + MM.WEAPONS[w].name + '. Strong against: ' + + Object.keys(MM.DAMAGE).filter(function (id) { return MM.weakTo(id) === w; }).map(function (id) { return MM.ROBOT_MASTERS[id].zh; }).join(', '); + } else $('rweapon').textContent = ''; + }).observe(result, { attributes: true, attributeFilter: ['class'] }); +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/scripted.js b/environments/games/web/games/megaman_remake/scripted.js new file mode 100644 index 0000000000000000000000000000000000000000..f1626ada2d0bb006c3ad49c1258f7654b1f9d62c --- /dev/null +++ b/environments/games/web/games/megaman_remake/scripted.js @@ -0,0 +1,163 @@ +// Standard scripted reference controller for the Mega Man cases (BossBench protocol section 3). +// BB.GAME.scripted(c) is called once per 200 ms packet with the live BB.Case. It plans by receding-horizon +// search: a systematic set of action sequences (direction x jump start x jump height x fire pattern), 48 ticks +// long, plus the previous best plan shifted by one packet, is simulated on deep copies of the case (the live +// case, its RNG and its event list are never touched) and scored on damage taken (dominant), damage dealt and a +// small positional heuristic; the first packet of the best sequence is played. +// Deterministic (no Math.random, no clock); emits legal packets (<= 4 keys per hold set). It reads privileged +// state and simulates the boss, but rolls not yet made are re-drawn from a synthetic RNG: a trusted demo/recording +// tool, not a policy. +(function (g) { + var B = g.BB, MM = B.MM; + if (!B || !B.GAME) return; + var SUBS = 24, TICKS = 2; // horizon: 24 hold sets x 2 ticks = 48 ticks = 4 packets + var MEMORY = typeof WeakMap === 'function' ? new WeakMap() : null; + var JUMP_AT = [0, 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 18], JUMP_LEN = [14, 5]; + + function clone(o) { return JSON.parse(JSON.stringify(o)); } + function copyCase(c, k) { + var n = Object.create(Object.getPrototypeOf(c)); Object.assign(n, c); + n.body = Object.assign(Object.create(Object.getPrototypeOf(c.body)), clone(c.body)); + n.boss = Object.assign(Object.create(Object.getPrototypeOf(c.boss)), clone(c.boss)); + // the look-ahead gets its own RNG: decisions already taken are readable, rolls not yet made are not (EXPAND_TO_6.md 2.4) + n.rng = new B.RNG(((c.t + 1) * 2654435761 + 97 + k * 40503) >>> 0); + n.events = []; return n; + } + function blank() { var a = []; for (var i = 0; i < SUBS; i++) a.push(0); return a; } + function fill(a, from, to, v) { for (var i = Math.max(0, from); i < Math.min(SUBS, to); i++) a[i] = v; return a; } + function pulses(from, every) { var a = blank(); for (var i = from; i < SUBS; i += every) a[i] = 1; return a; } + function plan(dir, jump, fire) { return { dir: dir, jump: jump, fire: fire }; } + function holdSet(p, i) { + var k = {}; + if (p.dir[i] < 0) k.A = true; else if (p.dir[i] > 0) k.D = true; + if (p.jump[i]) k.Space = true; + if (p.fire[i]) k.J = true; + return k; + } + + // ---------------- scoring ---------------- + // The plan's 48 ticks are followed by a short continuation (keep the direction, release jump, keep firing) so a + // jump that lands on a pillar or into a shot just past the horizon is still seen; its damage counts half. + var EXTRA = 24, STUN_COST = 1.5; + function evaluate(c, p, k) { + var sim = copyCase(c, k), b = sim.body, o = sim.boss, score = 0, hp = b.hp, bhp = o.hp, t; + for (var i = 0; i < SUBS; i++) { + var keys = holdSet(p, i); + for (var k = 0; k < TICKS; k++) { + sim.tick(keys); t = i * TICKS + k; + if (b.hp < hp) { score -= (hp - b.hp) / MM.UNIT * 400 * (1 - t / 200); hp = b.hp; } + if (b.stunT > 0) score -= STUN_COST; // a stunned player cannot dodge the rock that follows (Guts Man only) + if (o.hp < bhp) { score += (bhp - o.hp) / MM.UNIT * 40 * (1 - t / 120); bhp = o.hp; } + if (sim.result === 'loss') return score - 1e6; + if (sim.result === 'win') return score + 1e6 - t * 10; + } + } + var last = p.dir[SUBS - 1], tail = {}; + if (last < 0) tail.A = true; else if (last > 0) tail.D = true; + for (var e = 0; e < EXTRA && !sim.result; e++) { + tail.J = !(e & 2); + sim.tick(tail); + if (b.hp < hp) { score -= (hp - b.hp) / MM.UNIT * 200; hp = b.hp; } + } + if (sim.result === 'loss') return score - 5e5; + // terminal heuristic: margin from boss shots, room from the boss and the walls, shots on their way to hit + var hb = b.hurtBox(), margin = 40; + o.projectiles.forEach(function (q) { + if (q.harmless) return; + var dx = Math.max(0, Math.abs(q.x - hb.x) - q.hw - hb.hw), dy = Math.max(0, Math.abs(q.y - hb.y) - q.hh - hb.hh); + margin = Math.min(margin, Math.max(dx, dy)); + }); + score += margin * 1.2; + if (o.hp > 0) score -= Math.max(0, 52 - Math.abs(o.x - b.x)) * (Math.abs(o.y - b.y) < 40 ? 7 : 2); + score -= Math.max(0, 32 - Math.min(b.x - MM.WALL_L, MM.WALL_R - b.x)) * 0.8; + b.shots.forEach(function (s) { + if (Math.abs(s.y - o.y) < o.hh + s.hh && (o.x - s.x) * (s.vx || 0) > 0) score += 6; + }); + if (b.knockT > 0) score -= 20; + return score; + } + + // ---------------- candidate sequences ---------------- + function candidates(c, mem) { + var b = c.body, out = [], grounded = b.grounded, held = !!b.prev.jump; + var fireAll = pulses(0, 2), fireNone = blank(); + if (mem.best) { // previous best, shifted one packet + var s = mem.best, keep = plan(s.dir.slice(6), s.jump.slice(6), s.fire.slice(6)); + while (keep.dir.length < SUBS) { keep.dir.push(keep.dir[keep.dir.length - 1]); keep.jump.push(0); keep.fire.push(keep.fire.length % 2 ? 0 : 1); } + out.push(keep); + } + [-1, 0, 1].forEach(function (d) { + var dir = fill(blank(), 0, SUBS, d); + [fireAll, fireNone].forEach(function (fire) { + // no new jump: keep holding Space while airborne (full height) or release now (feather) + out.push(plan(dir, !grounded && held ? fill(blank(), 0, 14, 1) : blank(), fire)); + if (!grounded && held) out.push(plan(dir, blank(), fire)); + JUMP_AT.forEach(function (at) { + JUMP_LEN.forEach(function (len) { + var jump = blank(), start = at; + if (start === 0 && held) start = 1; // a new press needs a released sub-step first + fill(jump, start, start + len, 1); + if (!grounded && held && at > 0) fill(jump, 0, 1, 1); + out.push(plan(dir, jump, fire)); + }); + }); + }); + }); + // move-then-stop plans (step out of the way, then hold position), with and without a jump + [-1, 1].forEach(function (d) { + [3, 6, 10].forEach(function (k) { + [blank(), fill(blank(), held ? 1 : 0, 14, 1), fill(blank(), k, k + 14, 1)].forEach(function (jump) { + [fireAll, fireNone].forEach(function (fire) { out.push(plan(fill(fill(blank(), 0, k, d), k, SUBS, 0), jump, fire)); }); + }); + }); + }); + // a few two-segment plans (turn around mid-horizon) + [-1, 1].forEach(function (d) { + [6, 12].forEach(function (cut) { + out.push(plan(fill(fill(blank(), 0, cut, d), cut, SUBS, -d), fill(blank(), held ? 1 : 0, 14, 1), fireAll)); + out.push(plan(fill(fill(blank(), 0, cut, d), cut, SUBS, -d), blank(), fireAll)); + }); + }); + return out; + } + + // the owned weapon with the best damage RATE against this boss that still has energy: shots are limited by the boss's + // blink, the Hyper Bomb by its 160-frame fuse-and-flames cycle, the Rolling Cutter by its roughly 64-frame round trip + function bestWeapon(c) { + var b = c.body, row = MM.DAMAGE[c.boss.id], blink = c.boss.info.iframes + 1, best = 'P'; + function rate(w) { return row[w] / Math.max(blink, w === 'B' ? 160 : w === 'C' ? 64 : 0); } + // the Super Arm needs a block: one left in the room, or one held, thrown or broken into chunks + function usable(w) { return b.spendable(w) && (w !== 'G' || b.blockOut() || b.room.some(function (r) { return r.block; })); } + var weak = MM.weakTo(c.boss.id); + if (b.weapons.indexOf(weak) >= 0 && usable(weak)) return weak; // the counter chain: the boss's weakness first + b.weapons.forEach(function (w) { if (usable(w) && rate(w) > rate(best)) best = w; }); + return best; + } + + // Bosses whose AI rolls dice get several sampled futures per plan, scored half worst case, half mean, so a plan is + // not chosen for surviving only one outcome of a roll not yet made. RNG-free bosses need a single evaluation. + var ROLLS = { elec_man: 3, bomb_man: 3, cut_man: 3, guts_man: 3 }; + function robust(c, p) { + var n = ROLLS[c.boss.id] || 1, worst = Infinity, sum = 0; + for (var k = 0; k < n; k++) { var v = evaluate(c, p, k); sum += v; if (v < worst) worst = v; } + return n === 1 ? worst : 0.5 * worst + 0.5 * sum / n; + } + + B.GAME.scripted = function (c) { + var mem = MEMORY ? MEMORY.get(c) : null; + if (!mem || c.t === 0 || mem.t > c.t) { mem = { t: c.t, best: null }; if (MEMORY) MEMORY.set(c, mem); } + mem.t = c.t; + var b = c.body, o = c.boss, idle = [{}, {}, {}, {}, {}, {}]; + if (o.intro > 0 || b.hp <= 0 || o.hp <= 0) { mem.best = null; return idle; } + if (b.weapon !== bestWeapon(c) && !b.count('hyper_bomb') && !b.count('hyper_flame')) { mem.best = null; return [{ E: true }, {}, {}, {}, {}, {}]; } // one step per press + var cands = candidates(c, mem), bestScore = -Infinity, best = null; + for (var i = 0; i < cands.length; i++) { + var s = robust(c, cands[i]); + if (s > bestScore + 1e-9) { bestScore = s; best = cands[i]; } + } + mem.best = best; + var out = []; + for (var k = 0; k < 6; k++) out.push(holdSet(best, k)); + return out; + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/specs/bomb_man.spec.js b/environments/games/web/games/megaman_remake/specs/bomb_man.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..fe07d7889eeb7d5d0afa5763e719a42cac50cdfa --- /dev/null +++ b/environments/games/web/games/megaman_remake/specs/bomb_man.spec.js @@ -0,0 +1,117 @@ +// GENERATED from bomb_man.yaml by tools/gen_spec.py - edit the YAML, not this file. +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["bomb_man"] = { + "schema": "bossbench/boss-spec@1", + "id": "bomb_man", + "dims": "2d", + "family": "megaman_nes", + "archetype": "Mega Man (NES 1987) Bomb Man: random leap toward the player, lobs 1-3 bombs that burst into 12-way shrapnel, jumps at a player who closes in", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "walk_idle", + "telegraph": "throw", + "active": "land_throw", + "recovery": "wait_bomb" + }, + "timing": { + "telegraph": { + "knob": "windup", + "min": 1 + }, + "recovery": { + "knob": "windup", + "until": "timer" + } + }, + "locomotion": { + "knob": "windup", + "when": "before_select", + "speed_by_state": { + "idle": 1.0, + "telegraph": 0.0, + "active": 0.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "pattern_step", + "policy": "first", + "face_target": true + }, + "moves": [ + { + "name": "lob_bomb", + "atoms": [ + "projectile" + ], + "damage": 4, + "cue": "After landing he raises a bomb and charges for about 0.25 seconds, then throws it at you. The bomb lands after 49 frames, about 20 px short of you. He waits for each bomb to explode before throwing the next, 1-3 per volley", + "punish": "The bomb itself cannot be shot (bullets pass through). Read the landing spot, jump over the horizontal fragments, or back out of their range (about 30 px)" + }, + { + "name": "shrapnel", + "atoms": [ + "burst" + ], + "damage": 4, + "cue": "The bomb explodes into 12 pieces when it lands or hits a wall: fast pieces about 30 px up, down, left, and right, diagonal pieces about 20 px, plus four slow pieces", + "punish": "The ground-level horizontal pieces are only 16 px tall, so a jump clears them. Do not stand directly above the landing spot" + }, + { + "name": "leap", + "atoms": [ + "leap" + ], + "damage": 4, + "cue": "Each volley starts with a random jump: a long pounce toward you (about 154 px) or a short hop closer (about 49 px). After a short-hop volley he jumps away with his back to you", + "punish": "The long jump carries him over you, so walk under him. He only starts charging after he lands and settles, which is the damage window" + }, + { + "name": "close_guard", + "atoms": [ + "leap" + ], + "damage": 4, + "cue": "If you walk within 48 px, he drops the current bomb and jumps at you immediately", + "punish": "You can use this to break his throw rhythm, but he jumps over your head, so watch the contact damage" + } + ], + "difficulty": { + "hp": [ + 66, + 180, + 520 + ], + "shot": [ + 2, + 3, + 4 + ], + "contact": [ + 2, + 3, + 4 + ], + "windup": [ + 30, + 20, + 15 + ] + }, + "skills_tested": [ + "read_telegraph", + "timing_jump", + "spacing", + "hazard_avoid", + "aim", + "weapon_choice" + ], + "provenance": { + "source": "plasticsmoke/megaman1-disassembly-ca65 @2771fb3 src/fixed/fixed_game_modes.asm mode 2 ($DFF0); see SOURCES.md", + "license": "Original procedural art and implementation; mechanics read from the annotated disassembly (MIT annotations), no ROM data or assets shipped" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/specs/cut_man.spec.js b/environments/games/web/games/megaman_remake/specs/cut_man.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..c5e5669ee4e593845d372f711242ed81ef790a0c --- /dev/null +++ b/environments/games/web/games/megaman_remake/specs/cut_man.spec.js @@ -0,0 +1,122 @@ +// GENERATED from cut_man.yaml by tools/gen_spec.py - edit the YAML, not this file. +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["cut_man"] = { + "schema": "bossbench/boss-spec@1", + "id": "cut_man", + "dims": "2d", + "family": "megaman_nes", + "archetype": "Mega Man (NES 1987) Cut Man: random leaps at the player, a homing Rolling Cutter that flies out and back, a step and two blocks in the room", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "retarget", + "telegraph": "land_settle", + "active": "throw_windup", + "recovery": "chase" + }, + "timing": { + "telegraph": { + "knob": "wait", + "min": 1 + }, + "recovery": { + "knob": "wait", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 1.0, + "telegraph": 0.0, + "active": 0.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "pattern_step", + "policy": "first", + "face_target": true + }, + "moves": [ + { + "name": "return_blade", + "atoms": [ + "boomerang" + ], + "damage": 4, + "cue": "After landing he stands, raises the cutter for about 16 frames, and throws it at you. It turns around at the room edge and speeds back to his hand, and the return pass sweeps through where you are", + "punish": "While the cutter is out he has no weapon, so close in and shoot. The return path follows him; do not stand between him and the blade" + }, + { + "name": "leap", + "atoms": [ + "leap" + ], + "damage": 4, + "cue": "Within 64 px he jumps (6.4 px/frame upward): a 1/2 chance to land 32 px past you, 1/3 to land on you, and 1/6 to land in front of you", + "punish": "When he jumps, walk under him or the other way. He may throw the cutter in the air" + }, + { + "name": "chase", + "atoms": [ + "wait" + ], + "damage": 4, + "cue": "If you are on a ledge and he is on the ground, he runs in place for about 1 second, then throws the cutter", + "punish": "The ledge is a safe place to watch, but the cutter flies at you when the wait ends" + }, + { + "name": "hop_back", + "atoms": [ + "hop" + ], + "damage": 4, + "cue": "After a hit he flashes for 63 frames and hops away with his back to you for the first 32 frames", + "punish": "Bullets pass through him while he is flashing" + } + ], + "difficulty": { + "hp": [ + 60, + 170, + 520 + ], + "shot": [ + 2, + 3, + 4 + ], + "contact": [ + 2, + 3, + 4 + ], + "speed": [ + 0.8, + 0.9, + 1.0 + ], + "wait": [ + 63, + 63, + 63 + ] + }, + "skills_tested": [ + "read_telegraph", + "timing_jump", + "spacing", + "hazard_avoid", + "aim", + "weapon_choice" + ], + "provenance": { + "source": "plasticsmoke/megaman1-disassembly-ca65 @2771fb3 src/fixed/fixed_game_modes.asm mode 0 ($DC8B); see SOURCES.md", + "license": "Original procedural art and implementation; mechanics read from the annotated disassembly (MIT annotations), no ROM data or assets shipped" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/specs/elec_man.spec.js b/environments/games/web/games/megaman_remake/specs/elec_man.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..dcf248c175607e4856e5ead1ccd763ebd8dae4ae --- /dev/null +++ b/environments/games/web/games/megaman_remake/specs/elec_man.spec.js @@ -0,0 +1,129 @@ +// GENERATED from elec_man.yaml by tools/gen_spec.py - edit the YAML, not this file. +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["elec_man"] = { + "schema": "bossbench/boss-spec@1", + "id": "elec_man", + "dims": "2d", + "family": "megaman_nes", + "archetype": "Mega Man (NES 1987) Elec Man: wall-position patrol, counter-leap on the player's shot, crawling Thunder Beam", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "guard", + "telegraph": "halt", + "active": "fire", + "recovery": "wait" + }, + "timing": { + "telegraph": { + "knob": "windup", + "min": 1 + }, + "recovery": { + "knob": "windup", + "until": "timer" + } + }, + "locomotion": { + "knob": "walk", + "when": "before_select", + "speed_by_state": { + "idle": 1.0, + "telegraph": 0.0, + "active": 0.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "pattern_step", + "policy": "first", + "face_target": true + }, + "moves": [ + { + "name": "zigzag_arc", + "atoms": [ + "crawling_bolt" + ], + "damage": 10, + "cue": "He stops, raises his hand for 15 frames, then fires a five-segment jagged arc. Each segment hops forward and changes shape every 10 frames, averaging about 4 px/frame", + "punish": "The high arc arrives first and you can let it pass while standing. Jump before the low arc arrives; jumping toward him makes it easier to pass through" + }, + { + "name": "counter_leap", + "atoms": [ + "leap" + ], + "damage": 4, + "cue": "If you press fire while he is walking, he immediately jumps at you (a 1/4 chance it is a feint the other way)", + "punish": "Do not fire while he is repositioning. Wait until he stands and fires the arc" + }, + { + "name": "air_arc", + "atoms": [ + "crawling_bolt" + ], + "damage": 10, + "cue": "If you fire again while he is in the air, he charges in the air and releases one arc", + "punish": "The air arc stays at his height, so watch where he lands" + }, + { + "name": "hop_back", + "atoms": [ + "hop" + ], + "damage": 4, + "cue": "After a hit he flashes for 63 frames and jumps away with his back to you for the first 32 frames", + "punish": "Bullets pass through him while he flashes, so save shots until the flash ends" + } + ], + "difficulty": { + "hp": [ + 19, + 40, + 150 + ], + "shot": [ + 4, + 7, + 10 + ], + "contact": [ + 2, + 3, + 4 + ], + "walk": [ + 1.5, + 1.75, + 2.0 + ], + "windup": [ + 30, + 20, + 15 + ], + "counter": [ + 0.35, + 0.7, + 1.0 + ] + }, + "kinds": { + "counter": "continuous" + }, + "skills_tested": [ + "read_telegraph", + "timing_jump", + "bait_counter", + "spacing", + "weapon_choice" + ], + "provenance": { + "source": "plasticsmoke/megaman1-disassembly-ca65 @2771fb3 src/fixed/fixed_game_modes.asm mode 4 ($E434); see SOURCES.md", + "license": "Original procedural art and implementation; mechanics read from the annotated disassembly (MIT annotations), no ROM data or assets shipped" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/specs/fire_man.spec.js b/environments/games/web/games/megaman_remake/specs/fire_man.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..28b1c7a20724b57e916cf61f083e01863f5bbad6 --- /dev/null +++ b/environments/games/web/games/megaman_remake/specs/fire_man.spec.js @@ -0,0 +1,133 @@ +// GENERATED from fire_man.yaml by tools/gen_spec.py - edit the YAML, not this file. +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["fire_man"] = { + "schema": "bossbench/boss-spec@1", + "id": "fire_man", + "dims": "2d", + "family": "megaman_nes", + "archetype": "Mega Man (NES 1987) Fire Man: keeps a 96 px band, five-wave Fire Storm volleys, floor pillars, retaliates when hit", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "pace", + "telegraph": "summon", + "active": "hold", + "recovery": "pose" + }, + "timing": { + "telegraph": { + "knob": "hold", + "min": 1 + }, + "recovery": { + "knob": "hold", + "until": "timer" + } + }, + "locomotion": { + "knob": "hold", + "when": "before_select", + "speed_by_state": { + "idle": 1.0, + "telegraph": 0.0, + "active": 0.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "distance_band", + "policy": "first", + "face_target": true + }, + "moves": [ + { + "name": "ground_wave", + "atoms": [ + "projectile" + ], + "damage": 4, + "cue": "He stands about 96 px away. The flame in his hand forms for 23 frames, then rushes along the ground at 5 px/frame. A volley is at most five shots, about 1 second apart", + "punish": "Get ready to jump when the flame forms. The wave is 32 px tall, so clear it near the top of the jump" + }, + { + "name": "fire_pillar", + "atoms": [ + "hazard" + ], + "damage": 4, + "cue": "Where a fire wave passes under you, a pillar rises and lasts about 2.2 seconds", + "punish": "Avoid the pillar when you land. The old pillar goes out when he fires the next wave" + }, + { + "name": "keep_distance", + "atoms": [ + "walk" + ], + "damage": 4, + "cue": "He backs away when you close in and advances when you retreat, holding about 96 px. Cornered against a wall, he turns and walks straight through you", + "punish": "Shoot while he is backing up. Watch the contact damage when he is against the wall" + }, + { + "name": "retaliate", + "atoms": [ + "projectile" + ], + "damage": 4, + "cue": "About 14 frames (0.23 seconds) after a hit, he immediately starts a new fire volley", + "punish": "Get ready to jump right after a hit connects" + }, + { + "name": "stand_down", + "atoms": [ + "pose" + ], + "damage": 0, + "cue": "After five shots he poses and stops firing. Any key you press, or leaving the distance band, makes him start again", + "punish": "Original behavior: if you do not move at all, he will not attack again" + } + ], + "difficulty": { + "hp": [ + 66, + 86, + 270 + ], + "shot": [ + 2, + 3, + 4 + ], + "contact": [ + 2, + 3, + 4 + ], + "hold": [ + 90, + 75, + 63 + ], + "retaliate": [ + 0, + 1, + 1 + ] + }, + "kinds": { + "retaliate": "unlock" + }, + "skills_tested": [ + "timing_jump", + "spacing", + "hazard_avoid", + "aim", + "weapon_choice" + ], + "provenance": { + "source": "plasticsmoke/megaman1-disassembly-ca65 @2771fb3 src/fixed/fixed_game_modes.asm mode 3 ($E2E4); see SOURCES.md", + "license": "Original procedural art and implementation; mechanics read from the annotated disassembly (MIT annotations), no ROM data or assets shipped" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/specs/guts_man.spec.js b/environments/games/web/games/megaman_remake/specs/guts_man.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..2914dad5c0d27b33c0d61de47e3c225765bc42a2 --- /dev/null +++ b/environments/games/web/games/megaman_remake/specs/guts_man.spec.js @@ -0,0 +1,113 @@ +// GENERATED from guts_man.yaml by tools/gen_spec.py - edit the YAML, not this file. +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["guts_man"] = { + "schema": "bossbench/boss-spec@1", + "id": "guts_man", + "dims": "2d", + "family": "megaman_nes", + "archetype": "Mega Man (NES 1987) Guts Man: heavy leaps that quake the room and stun anyone standing on the floor, a boulder from the ceiling thrown at you that shatters into four chunks", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "land_wait", + "telegraph": "windup_rock", + "active": "throw_rock", + "recovery": "pattern_roll" + }, + "timing": { + "telegraph": { + "knob": "windup", + "min": 1 + }, + "recovery": { + "knob": "windup", + "until": "timer" + } + }, + "locomotion": { + "knob": "windup", + "when": "before_select", + "speed_by_state": { + "idle": 1.0, + "telegraph": 0.0, + "active": 0.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "pattern_step", + "policy": "first", + "face_target": true + }, + "moves": [ + { + "name": "quake_leap", + "atoms": [ + "leap" + ], + "damage": 4, + "cue": "He crouches for about 0.25 seconds, then leaps. The landing shakes the screen for about 0.5 seconds, and if you are on the ground (or were just knocked back) you are stuck for about 0.8 seconds", + "punish": "Jump as he is about to land, and stay off the ground until the shake ends, or you will be stuck. His rise and fall are slow, so you can walk under him" + }, + { + "name": "boulder_throw", + "atoms": [ + "projectile" + ], + "damage": 4, + "cue": "He jumps in place. On landing a rock drops from the ceiling into his hands. He holds it for about 0.25 seconds, then throws it in a straight line at your feet", + "punish": "The rock cannot be shot (bullets pass through). While he stands holding it, that is the damage window. Jump or move the moment he throws" + }, + { + "name": "chunks", + "atoms": [ + "burst" + ], + "damage": 4, + "cue": "The rock shatters into four pieces on a wall, the ground, or a step. They keep flying the original way at 3-4 px/frame, and two of them rise", + "punish": "The pieces appear at the lower right of the impact (they are not mirrored with direction) and fly the original way. After the rock lands, walk back or jump" + } + ], + "skills_tested": [ + "read_telegraph", + "timing_jump", + "spacing", + "hazard_avoid", + "aim", + "weapon_choice" + ], + "difficulty": { + "hp": [ + 56, + 165, + 470 + ], + "shot": [ + 2, + 3, + 4 + ], + "contact": [ + 2, + 3, + 4 + ], + "windup": [ + 30, + 20, + 15 + ], + "speed": [ + 0.8, + 0.9, + 1.0 + ] + }, + "provenance": { + "source": "plasticsmoke/megaman1-disassembly-ca65 @2771fb3 src/fixed/fixed_game_modes.asm mode 5 ($E56E); see SOURCES.md", + "license": "Original procedural art and implementation; mechanics read from the annotated disassembly (MIT annotations), no ROM data or assets shipped" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/specs/ice_man.spec.js b/environments/games/web/games/megaman_remake/specs/ice_man.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..6d7ee3974a67779dbf8374ba504e92c105275853 --- /dev/null +++ b/environments/games/web/games/megaman_remake/specs/ice_man.spec.js @@ -0,0 +1,107 @@ +// GENERATED from ice_man.yaml by tools/gen_spec.py - edit the YAML, not this file. +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["ice_man"] = { + "schema": "bossbench/boss-spec@1", + "id": "ice_man", + "dims": "2d", + "family": "megaman_nes", + "archetype": "Mega Man (NES 1987) Ice Man: four-waypoint patrol, vertical hop firing a six-shot V of Ice Slashers that speeds up", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "leg_walk", + "telegraph": "stance", + "active": "fire", + "recovery": "land" + }, + "timing": { + "telegraph": { + "knob": "windup", + "min": 1 + }, + "recovery": { + "knob": "hover", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 1.0, + "telegraph": 0.0, + "active": 0.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "waypoint_cycle", + "policy": "first", + "face_target": true + }, + "moves": [ + { + "name": "v_volley", + "atoms": [ + "projectile" + ], + "damage": 10, + "cue": "He walks to a stance, charges 15 frames, and jumps straight up. On the way down he fires one blade at each of three heights, hovers at the ground, then rises in reverse and fires three more (six blades in a V)", + "punish": "Only the ground-level blade needs a jump. The middle and high blades can be let past while standing. Jumping too high hits the upper blade" + }, + { + "name": "patrol", + "atoms": [ + "walk" + ], + "damage": 4, + "cue": "He walks back and forth among the stances at 208, 168, 128, and 168. Every third landing raises the blade speed and the hover and sink timing by one level, up to four", + "punish": "Walking and charging are the safest windows to shoot. He has no hit reaction" + } + ], + "difficulty": { + "hp": [ + 29, + 85, + 245 + ], + "shot": [ + 4, + 7, + 10 + ], + "contact": [ + 2, + 3, + 4 + ], + "speed": [ + 0.8, + 0.9, + 1.0 + ], + "hover": [ + 1.4, + 1.2, + 1.0 + ], + "windup": [ + 30, + 20, + 15 + ] + }, + "skills_tested": [ + "pattern_gaps", + "timing_jump", + "aim", + "weapon_choice" + ], + "provenance": { + "source": "plasticsmoke/megaman1-disassembly-ca65 @2771fb3 src/fixed/fixed_game_modes.asm mode 1 ($E111); see SOURCES.md", + "license": "Original procedural art and implementation; mechanics read from the annotated disassembly (MIT annotations), no ROM data or assets shipped" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/minecraft_remake/compact_actions.json b/environments/games/web/games/minecraft_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..21868930586fa555c44f5c17d06f429a98df9a65 --- /dev/null +++ b/environments/games/web/games/minecraft_remake/compact_actions.json @@ -0,0 +1,224 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "minecraft", + "version": "minecraft-compact@2", + "heads": [ + { + "name": "move", + "options": [ + { + "label": "none" + }, + { + "label": "forward", + "keys": [ + "W" + ] + }, + { + "label": "back", + "keys": [ + "S" + ] + }, + { + "label": "left", + "keys": [ + "A" + ] + }, + { + "label": "right", + "keys": [ + "D" + ] + }, + { + "label": "sprint", + "keys": [ + "W", + "Shift" + ] + } + ] + }, + { + "name": "action", + "options": [ + { + "label": "none" + }, + { + "label": "swing", + "tap": [ + "LMB" + ] + }, + { + "label": "swing_late", + "subs": [ + [], + [], + [], + [], + [ + "LMB" + ], + [] + ] + }, + { + "label": "draw", + "keys": [ + "RMB" + ] + }, + { + "label": "jump", + "subs": [ + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [], + [], + [] + ] + }, + { + "label": "switch", + "dz": 1 + } + ] + }, + { + "name": "aim", + "options": [ + { + "label": "none" + }, + { + "label": "r8_c0", + "dx": 8 + }, + { + "label": "l8_c0", + "dx": -8 + }, + { + "label": "c0_d40", + "dy": 40 + }, + { + "label": "c0_u40", + "dy": -40 + }, + { + "label": "r25_c0", + "dx": 25 + }, + { + "label": "r25_d40", + "dx": 25, + "dy": 40 + }, + { + "label": "r25_u40", + "dx": 25, + "dy": -40 + }, + { + "label": "l25_c0", + "dx": -25 + }, + { + "label": "l25_d40", + "dx": -25, + "dy": 40 + }, + { + "label": "l25_u40", + "dx": -25, + "dy": -40 + }, + { + "label": "r60_c0", + "dx": 60 + }, + { + "label": "r60_d40", + "dx": 60, + "dy": 40 + }, + { + "label": "r60_u40", + "dx": 60, + "dy": -40 + }, + { + "label": "l60_c0", + "dx": -60 + }, + { + "label": "l60_d40", + "dx": -60, + "dy": 40 + }, + { + "label": "l60_u40", + "dx": -60, + "dy": -40 + }, + { + "label": "r150_c0", + "dx": 150 + }, + { + "label": "r150_d40", + "dx": 150, + "dy": 40 + }, + { + "label": "r150_u40", + "dx": 150, + "dy": -40 + }, + { + "label": "l150_c0", + "dx": -150 + }, + { + "label": "l150_d40", + "dx": -150, + "dy": 40 + }, + { + "label": "l150_u40", + "dx": -150, + "dy": -40 + }, + { + "label": "r300_c0", + "dx": 300 + }, + { + "label": "l300_c0", + "dx": -300 + }, + { + "label": "r600_c0", + "dx": 600 + }, + { + "label": "l600_c0", + "dx": -600 + } + ] + } + ] +} diff --git a/environments/games/web/games/minecraft_remake/index.html b/environments/games/web/games/minecraft_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..f78c356a461522ebe8fb26f4a1bf973fdb0a0b60 --- /dev/null +++ b/environments/games/web/games/minecraft_remake/index.html @@ -0,0 +1,86 @@ + + + + + + +Minecraft · Voxel Arena + + + +
    +
    +

    Minecraft · Voxel Arena

    +

    Java Edition 1.21 combat subset · Six boss arenas · Three public difficulty tiers · ModernGL rendering · 60 Hz · Recording and replay · Rules minecraft-arena@7

    + Back to Game Lobby +
    +
    +
    +
    + Game screen rendered by the local Python server +
    +
    Select a boss to start
    + +
    +
    + + + + + + + +
    +
    + + + +
    +

    Connecting to local server…

    +

    Every 200 ms, your input becomes a standard action packet: six 33 ms key windows, each with up to four keys plus mouse movement. The packet goes to the same simulation as make_policy_env. Pausing stops the world. Replays use bossbench/policy-replay@1; import simulates each packet again and checks the final-state hash. Scripted Demo is a reference controller that reads internal state, not a trained model; it does not start RL training.

    +
    + +
    +
    +
    + + + diff --git a/environments/games/web/games/minecraft_remake/manifest.json b/environments/games/web/games/minecraft_remake/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..b56ce3c6ed48e5eefb5170c2b5cda5ae09d63ca2 --- /dev/null +++ b/environments/games/web/games/minecraft_remake/manifest.json @@ -0,0 +1,79 @@ +{ + "schema": "bossbench/game-manifest@1", + "engine": "python", + "game": "minecraft_remake", + "title": "Minecraft: Voxel Arena", + "dimension": "3d", + "native_hz": 60, + "max_seconds": { + "3d/minecraft_iron_golem": 300, + "3d/minecraft_zombie": 90, + "3d/minecraft_ender_dragon": 300, + "3d/minecraft_wither": 300, + "3d/minecraft_warden": 300, + "3d/minecraft_skeleton": 300, + "3d/minecraft_zombie_leader": 300 + }, + "renderer": "moderngl", + "rules": "minecraft-arena@7", + "tiers": { + "easy": 0.0, + "normal": 0.5, + "hard": 1.0 + }, + "tiers_source": "prototype/bossbench/mc4d.py TIERS (read by bossbench.make_policy_env and the play server)", + "cases": [ + "3d/minecraft_iron_golem", + "3d/minecraft_ender_dragon", + "3d/minecraft_wither", + "3d/minecraft_warden", + "3d/minecraft_skeleton", + "3d/minecraft_zombie_leader" + ], + "retired_cases": { + "3d/minecraft_zombie": "2026-11-10 user request: remove the green-skinned grappler. It remains registered in FORMAL_CASES under frozen @4 rules, but is excluded from the benchmark list (scope.BENCH_RETIRED). Its media was moved to archived history." + }, + "formal_cases": [ + "3d/minecraft_iron_golem", + "3d/minecraft_zombie", + "3d/minecraft_ender_dragon", + "3d/minecraft_wither" + ], + "formal_note": "FORMAL_CASES (prototype/bossbench/scope.py): their rules stay exactly @4 (difficulty tables, behaviour, arena, kit, time limit, observation layout); d = 0.5 of each was evaluated 16 times in reports/mc-bow-comparison-20261020. 3d/minecraft_zombie stays exactly as in @4 and is reported \"uncalibrated\" against the tier windows (1.4-3.2 s fights); the user decided on 2026-11-04 to keep it at @4 (no re-calibration).", + "round_20261102_scenes": [ + "3d/minecraft_iron_golem", + "3d/minecraft_ender_dragon", + "3d/minecraft_wither" + ], + "round_20261103_scenes": [ + "3d/minecraft_warden", + "3d/minecraft_skeleton", + "3d/minecraft_zombie_leader" + ], + "kits": { + "diamond": "diamond sword 7 + full diamond armor 20 / 8 (flung giant, green-skinned grappler, purple-breathing flyer, triple-headed floating cannon, shockwave beast)", + "iron": "iron sword 6 + full iron armor 15 / 0 (mobile archer, summoner)", + "source": "prototype/bossbench/mc4d.py KITS / SCENE_KIT (the same on every tier)" + }, + "options": { + "weapon": [ + "sword", + "bow" + ], + "camera": [ + "first", + "third" + ] + }, + "play_page": "web/games/minecraft_remake/index.html", + "server": "prototype/bossbench/play_server.py", + "launch": "powershell -NoProfile -ExecutionPolicy Bypass -File web/games/minecraft_remake/run_server.ps1", + "url": "http://127.0.0.1:8765/", + "simulation": [ + "prototype/bossbench/mc4d.py", + "prototype/bossbench/mcskin.py", + "prototype/bossbench/rig.py" + ], + "scripted_controller": "bossbench.mc_scripted.scripted(case) -> packet text (prototype/bossbench/mc_scripted.py)", + "golden": "prototype/tests/mc4d_golden_20261107_arena7.json (rules minecraft-arena@7); frozen guards: mc4d_golden_20261103_arena6.json (@6), mc4d_golden_20261103.json (@5), mc4d_golden_20261102.json (@4), mc4d_golden_20261031.json (@3), mc4d_golden.json (@1, MD5 e778e5d30f6941ab44a91c86da8bd115)" +} diff --git a/environments/games/web/games/minecraft_remake/play.js b/environments/games/web/games/minecraft_remake/play.js new file mode 100644 index 0000000000000000000000000000000000000000..61f3eafee5055c40b294fa984737d8c5bd755019 --- /dev/null +++ b/environments/games/web/games/minecraft_remake/play.js @@ -0,0 +1,338 @@ +/* Minecraft remake play page client: samples real keyboard/mouse input into standard 200 ms packets + (6 hold sets of <= 4 keys + mouse dx dy dz), sends them to the local Python play server, and plays back the + 6 frames per packet that the real ModernGL renderer returns. The page itself simulates nothing. */ +(function () { + 'use strict'; + const $ = s => document.querySelector(s); + const KEYS = ['W', 'A', 'S', 'D', 'Space', 'Shift', 'J', 'K', 'L', 'Q', 'E', 'R', 'LMB', 'RMB']; + const CODE = {KeyW: 'W', KeyA: 'A', KeyS: 'S', KeyD: 'D', Space: 'Space', ShiftLeft: 'Shift', ShiftRight: 'Shift', + KeyJ: 'J', KeyK: 'RMB'}; + const SUB_MS = 200 / 6; + const view = $('#view'), capture = $('#capture'); + let API = '', sid = null, meta = null, state = null, running = false, mode = 'idle'; // idle | play | demo | replay + let down = new Set(), taps = new Set(), mouse = [0, 0, 0], subs = [], timer = null; + let queue = [], sending = false, clock0 = 0, subsDone = 0; + let frames = [], lastShown = 0, replayQueue = [], replayExpect = null, pending = false, epoch = 0; + + function status(text) { $('#status').textContent = text; } + function overlay(text) { + $('#overlay').hidden = !text; + $('#overlay-text').textContent = text || ''; + } + + // ------------------------------------------------------------------ server connection + async function api(path, body) { + const opt = body === undefined ? {} : {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(body)}; + const r = await fetch(API + path, opt); + const data = await r.json(); + if (!r.ok) throw Error(data.error || r.statusText); + return data; + } + async function connect() { + const bases = location.protocol.startsWith('http') && location.port === '8765' ? [''] : + ['', 'http://127.0.0.1:8765']; + for (const base of bases) { + try { + const r = await fetch(base + '/api/meta', {cache: 'no-store'}); + if (!r.ok) continue; + meta = await r.json(); + API = base; + $('#offline').hidden = true; + $('#rules').textContent = meta.rules; + const sel = $('#case'); + if (!sel.options.length) for (const c of meta.cases) { + const o = document.createElement('option'); + o.value = c.id; o.textContent = c.name; sel.appendChild(o); + } + tierControl(); + $('#hz').textContent = meta.native_hz + ' Hz'; + status('Connected to local server (' + meta.rules + ' · ' + meta.native_hz + ' Hz). Select a boss, then click Start Challenge.'); + overlay('Select a boss to start'); + return true; + } catch (e) { /* try next */ } + } + $('#offline').hidden = false; + overlay(''); + status('Could not connect. Start the local Python server using the command shown on screen.'); + return false; + } + $('#retry').onclick = connect; + + // ------------------------------------------------------------------ public difficulty: three tiers (2026-11-02) + // Rebuilt from the server's declaration (mc4d.TIERS via /api/meta), the same source make_policy_env reads, so the + // page can never offer a difficulty the public interface does not. Each option shows the meeting's target window. + function tierControl() { + const sel = $('#difficulty'), keep = sel.value || meta.default_tier; + if (!meta.tiers || !meta.tiers.length) return; + sel.textContent = ''; + for (const t of meta.tiers) { + const o = document.createElement('option'); + o.value = t.name; o.textContent = t.label + '(d=' + t.difficulty + ')'; + o.selected = t.name === keep; sel.appendChild(o); + } + tierHint(); + } + function tierInfo(name) { return meta && meta.tiers ? meta.tiers.find(t => t.name === name) : null; } + function tierHint() { + const t = tierInfo($('#difficulty').value); + $('#tier-hint').textContent = t ? 'Reference script target: ' + t.target_seconds[0] + '–' + t.target_seconds[1] + ' seconds to win' : ''; + } + $('#difficulty').onchange = tierHint; + + // ------------------------------------------------------------------ input sampling + function heldNow() { + const all = new Set([...down, ...taps]); + taps.clear(); + const out = []; + for (const k of ['W', 'S', 'A', 'D']) if (all.has(k)) { out.push(k); break; } + for (const k of ['Space', 'Shift', 'LMB', 'J', 'RMB']) if (all.has(k) && out.length < 4) out.push(k); + return out; + } + function packetText(sets, m) { + const mx = m.map((v, i) => Math.max(i === 2 ? -5 : -1000, Math.min(i === 2 ? 5 : 1000, Math.round(v)))); + return '<|action_start|> ' + mx.join(' ') + ' ; ' + sets.map(s => s.join(',')).join(' ; ') + ' <|action_end|>'; + } + function takePacket() { + while (subs.length < 6) subs.push(heldNow()); + const p = packetText(subs, mouse); + subs = []; mouse = [0, 0, 0]; + return p; + } + // Wall-clock scheduler: one hold set per 33.3 ms of real time, whatever the timer jitter, so the world runs at + // real speed; packets go out in order, one request at a time (a lagging server gets up to 5 per request). + function sampleClock() { + if (!running || mode !== 'play') return; + const due = Math.floor((performance.now() - clock0) / SUB_MS); + if (due - subsDone > 18) subsDone = due - 6; // tab stalled: drop the backlog instead of a burst + while (subsDone < due) { + if (arrows.has('ArrowLeft')) mouse[0] -= 7; + if (arrows.has('ArrowRight')) mouse[0] += 7; + if (arrows.has('ArrowUp')) mouse[1] -= 4; + if (arrows.has('ArrowDown')) mouse[1] += 4; + subs.push(heldNow()); + subsDone++; + if (subs.length >= 6) queue.push(takePacket()); + } + pump(); + } + async function pump() { + if (sending || !queue.length || !sid) return; + sending = true; + const batch = queue.splice(0, 5), my = epoch; + try { + const r = await api('/api/step', {sid, packets: batch, frames: true}); + if (my === epoch) accept(r); + } catch (e) { status('Server error: ' + e.message); pause(); } + finally { sending = false; if (queue.length && my === epoch) pump(); } + } + function lock() { + try { const p = capture.requestPointerLock && capture.requestPointerLock(); if (p && p.catch) p.catch(() => {}); } catch (e) { /* headless */ } + } + document.addEventListener('pointerlockchange', () => { + if (document.pointerLockElement !== capture && running && mode === 'play') { + pause(); status('Mouse unlocked (Esc) · Paused. Click Resume to continue.'); + } + }); + const arrows = new Set(); + window.addEventListener('keydown', e => { + if (['INPUT', 'SELECT', 'TEXTAREA'].includes(document.activeElement.tagName)) return; + if (e.code === 'Escape' || e.code === 'KeyP') { if (running) pause(); return; } + if (e.code.startsWith('Arrow')) { arrows.add(e.code); e.preventDefault(); return; } + if (e.code === 'KeyQ' || e.code === 'Digit1' || e.code === 'Digit2') { + const want = e.code === 'Digit1' ? 'sword' : e.code === 'Digit2' ? 'bow' : null; + if (!want || (state && state.player.weapon !== want)) mouse[2] += 1; + e.preventDefault(); return; + } + const k = CODE[e.code]; + if (k) { e.preventDefault(); down.add(k); taps.add(k); } + }); + window.addEventListener('keyup', e => { + if (e.code.startsWith('Arrow')) arrows.delete(e.code); + const k = CODE[e.code]; + if (k) down.delete(k); + }); + capture.addEventListener('contextmenu', e => e.preventDefault()); + capture.addEventListener('pointerdown', e => { + capture.focus(); + if (running && mode === 'play' && document.pointerLockElement !== capture) lock(); + const k = e.button === 2 ? 'RMB' : e.button === 0 ? 'LMB' : null; + if (k) { down.add(k); taps.add(k); } + e.preventDefault(); + }); + window.addEventListener('pointerup', e => { down.delete(e.button === 2 ? 'RMB' : 'LMB'); }); + window.addEventListener('mousemove', e => { + if (document.pointerLockElement === capture) { mouse[0] += e.movementX; mouse[1] += e.movementY; } + else if (e.buttons && e.target === capture) { mouse[0] += e.movementX; mouse[1] += e.movementY; } + }); + capture.addEventListener('wheel', e => { e.preventDefault(); mouse[2] += e.deltaY > 0 ? 1 : -1; }, {passive: false}); + document.querySelectorAll('[data-key]').forEach(b => { + b.onpointerdown = e => { e.preventDefault(); b.setPointerCapture(e.pointerId); down.add(b.dataset.key); taps.add(b.dataset.key); }; + b.onpointerup = b.onpointercancel = () => down.delete(b.dataset.key); + }); + document.querySelectorAll('[data-wheel]').forEach(b => { b.onclick = () => { mouse[2] += 1; }; }); + function releaseAll() { down.clear(); taps.clear(); arrows.clear(); } + window.addEventListener('blur', () => { releaseAll(); if (running && mode === 'play') { pause(); status('Window lost focus · Paused. Click Resume to continue.'); } }); + document.addEventListener('visibilitychange', () => { if (document.hidden) { releaseAll(); if (running) pause(); } }); + + // ------------------------------------------------------------------ stepping and frames + function accept(r) { + state = r.state || r; + if (r.frames && r.frames.length) { + if (frames.length > 12) frames = frames.slice(-6); // keep latency bounded + frames.push(...r.frames); + } + panel(); + if (state.outcome) finish(); + } + function showFrames(now) { + if (frames.length && now - lastShown >= SUB_MS - 2) { + view.src = frames.shift(); + lastShown = now; + } + requestAnimationFrame(showFrames); + } + requestAnimationFrame(showFrames); + async function still() { + if (!sid) return; + const r = await api('/api/still', {sid}); + frames = [r.frame]; + state = r.state; panel(); + } + function panel() { + if (!state) return; + const p = state.player, b = state.boss; + $('#time').textContent = state.t.toFixed(1) + ' / ' + state.max_seconds + ' s'; + const o = state.options || {}, tier = tierInfo(o.resolved_from_tier); + $('#tier').textContent = tier ? tier.label + ' · d=' + o.difficulty : 'd=' + o.difficulty; + $('#php').textContent = p.hp.toFixed(1) + ' / ' + p.max_hp + (p.wither_effect_s > 0 ? ' (Wither damage for ' + p.wither_effect_s.toFixed(0) + 's)' : ''); + $('#wpn').textContent = (p.kit === 'iron' ? 'Iron ' : 'Diamond ') + (p.weapon === 'sword' ? 'sword ' + Math.round(p.attack_charge * 100) + '%' : + 'Bow ' + (p.bow_drawing ? Math.round(p.bow_charge * 100) + '%' : 'ready') + ' · Hits ' + p.arrows_hit + '/' + p.arrows_fired); + $('#bname').textContent = b.name; + $('#bhp').textContent = b.hp.toFixed(1) + ' / ' + b.max_hp; + $('#bphase').textContent = b.phase + (b.armored ? ' · Half-health armor' : '') + (b.crystals !== null ? ' · Crystals ' + b.crystals : '') + + (b.minions !== null && b.minions !== undefined ? ' · Minions ' + b.minions : '') + + (b.darkness_s ? ' · Darkness ' + b.darkness_s.toFixed(0) + 's' : ''); + } + function finish() { + stopLoop(); + // Show the terminal frame at once: frames play back ~0.2 s behind the simulation, so the result overlay would + // otherwise sit on a frame where the boss still has health left. + if (frames.length) { view.src = frames[frames.length - 1]; frames = []; } + window.__bbOutcome = state.outcome; // read by web/tools/bench_media.py ui + const label = {win: 'Victory', loss: 'Failure', timeout: 'Time up'}[state.outcome] || state.outcome; + overlay(label + ' · ' + state.t.toFixed(2) + ' seconds'); + if (mode === 'replay' && replayExpect) verifyReplay(); + else status('Match over: ' + label + ' · ' + state.packets + ' action packets. You can export the replay.'); + } + + // ------------------------------------------------------------------ loop control + function stopLoop() { running = false; clearInterval(timer); timer = null; $('#pause').textContent = 'Resume'; } + function startLoop() { + if (!sid || (state && state.outcome)) return; + running = true; $('#pause').textContent = 'Pause'; overlay(''); + clearInterval(timer); + if (mode === 'play') { subs = []; mouse = [0, 0, 0]; clock0 = performance.now(); subsDone = 0; timer = setInterval(sampleClock, 8); } + else timer = setInterval(tickAuto, 200); + } + function pause() { stopLoop(); releaseAll(); if (document.pointerLockElement) document.exitPointerLock(); overlay(state && state.outcome ? $('#overlay-text').textContent : 'Paused'); } + async function tickAuto() { + if (pending || !running) return; + pending = true; + const my = epoch; + try { + if (mode === 'demo') { + const r = await api('/api/scripted', {sid, n: 1, frames: true}); + if (my === epoch) accept(r); + } else if (mode === 'replay') { + if (!replayQueue.length) { if (state && !state.outcome) { stopLoop(); verifyReplay(); } } + else { const r = await api('/api/step', {sid, packets: [replayQueue.shift()], frames: true}); if (my === epoch) accept(r); } + } + } catch (e) { status('Server error: ' + e.message); stopLoop(); } + finally { pending = false; } + } + async function newSession(caseId, useMode, tier) { + if (!meta && !(await connect())) return false; + epoch++; stopLoop(); frames = []; replayQueue = []; replayExpect = null; queue = []; window.__bbOutcome = null; + if (sid) api('/api/close', {sid}).catch(() => {}); + const body = {case: caseId || $('#case').value, seed: Number($('#seed').value), tier: tier || $('#difficulty').value, + weapon: $('#weapon').value, camera: $('#camera').value}; + $('#case').value = body.case; + $('#difficulty').value = body.tier; tierHint(); + const r = await api('/api/new', body); + sid = r.sid; state = r.state; mode = useMode; panel(); + await still(); + return true; + } + $('#start').onclick = async () => { + try { + if (!(await newSession(null, 'play'))) return; + status('Match in progress: click the screen to lock the mouse (Esc unlocks and pauses). One action packet every 200 ms.'); + capture.focus(); startLoop(); + } catch (e) { status('Unable to start: ' + e.message); } + }; + $('#pause').onclick = () => { + if (running) pause(); + else if (sid && state && !state.outcome) { startLoop(); capture.focus(); if (mode === 'play') lock(); } + }; + $('#step').onclick = async () => { + if (!sid || (state && state.outcome)) return; + if (running) pause(); + overlay('Step'); + const sets = Array.from({length: 6}, () => heldNow()); + if (mode === 'demo') { accept(await api('/api/scripted', {sid, n: 1, frames: true})); } + else if (mode === 'replay') { if (replayQueue.length) accept(await api('/api/step', {sid, packets: [replayQueue.shift()], frames: true})); } + else { const p = packetText(sets, mouse); mouse = [0, 0, 0]; accept(await api('/api/step', {sid, packets: [p], frames: true})); } + }; + async function demo(caseId, tier) { + if (!(await newSession(caseId, 'demo', tier))) return false; + status('Scripted Demo: a reference controller reads internal state and emits valid 200 ms action packets.'); + startLoop(); + return true; + } + $('#demo').onclick = () => demo(null).catch(e => status('Demo failed: ' + e.message)); + $('#export').onclick = async () => { + if (!sid) { status('No match is available to export yet.'); return; } + const data = await api('/api/replay?sid=' + sid); + const blob = new Blob([JSON.stringify(data, null, 1)], {type: 'application/json'}); + const a = document.createElement('a'); + a.href = URL.createObjectURL(blob); + a.download = data.case_id.replace('/', '__') + '-seed' + data.engine_seed + '.replay.json'; + a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 1000); + status('Exported ' + data.steps + ' action packets (' + data.rules + ') · Final-state hash: ' + data.final_hash.slice(0, 12)); + }; + $('#import').onclick = () => $('#file').click(); + $('#file').onchange = async e => { + const file = e.target.files[0]; e.target.value = ''; + if (!file) return; + try { + if (file.size > 12e6) throw Error('Replay must be 12 MB or smaller'); + await importReplay(JSON.parse(await file.text())); + } catch (err) { status('Import failed: ' + err.message); } + }; + async function importReplay(data) { + if (!meta && !(await connect())) return; + epoch++; stopLoop(); frames = []; + const r = await api('/api/import', {replay: data}); + if (sid) api('/api/close', {sid}).catch(() => {}); + sid = r.sid; state = r.state; mode = 'replay'; panel(); + replayQueue = data.packets.slice(); replayExpect = r.expect; + $('#case').value = data.case_id; + await still(); + status('Replay rules verified (' + data.rules + ') · Playing back ' + replayQueue.length + ' action packets…'); + startLoop(); + } + async function verifyReplay() { + const v = await api('/api/verify', {sid}); + const ok = v.final_hash === replayExpect.final_hash && v.outcome === replayExpect.outcome && v.ticks === replayExpect.ticks; + status('Replay finished: ' + ({win: 'Victory', loss: 'Failure', timeout: 'Time up'}[v.outcome] || 'Replay ended before the match concluded') + ' · ' + v.ticks + ' ticks · ' + (ok ? 'Final-state hash matches ✓' : 'Final state differs from replay ✗ (' + v.final_hash.slice(0, 10) + ' vs ' + String(replayExpect.final_hash).slice(0, 10) + ')')); + replayExpect = null; + } + + // ------------------------------------------------------------------ harness hook (web/tools/bench_media.py ui) + window.bossbenchUI = { + demo: (caseId, tier) => demo(caseId, tier), + start: (caseId, tier) => newSession(caseId, 'play', tier).then(() => { startLoop(); return true; }), + state: () => state, connected: () => !!meta, + }; + connect(); +})(); diff --git a/environments/games/web/games/minecraft_remake/style.css b/environments/games/web/games/minecraft_remake/style.css new file mode 100644 index 0000000000000000000000000000000000000000..44bae1e3b5b021f240b86cb2bcba75afd399786f --- /dev/null +++ b/environments/games/web/games/minecraft_remake/style.css @@ -0,0 +1,44 @@ +:root{color-scheme:dark;--paper:#ece6d6;--muted:#a7b3a2;--accent:#8fd16a;--bg:#1b1f17;--panel:#262c21;--edge:#4a5940;--warn:#e7b35d} +*{box-sizing:border-box} +body{margin:0;background:var(--bg) radial-gradient(circle at 20% -10%,#2f3a26 0,transparent 55%);color:var(--paper);font:15px/1.6 'Segoe UI','Microsoft YaHei',sans-serif} +main{max-width:1180px;margin:auto;padding:24px 24px 40px} +header{display:flex;gap:24px;align-items:baseline;justify-content:space-between;margin-bottom:18px} +h1{font-family:Georgia,'Microsoft YaHei',serif;font-size:29px;font-weight:600;line-height:1.3;margin:6px 0;letter-spacing:.5px} +header p{margin:0;color:var(--muted);font-size:13px} +code{font-family:Consolas,monospace;font-size:12px;color:var(--accent)} +a{color:var(--accent)} +a:focus-visible,button:focus-visible,input:focus-visible,select:focus-visible,#capture:focus-visible{outline:3px solid var(--accent);outline-offset:3px} +.layout{display:grid;grid-template-columns:minmax(0,854px) 240px;gap:20px} +.stage{position:relative;align-self:start;border:2px solid #10130d;box-shadow:0 0 0 1px var(--edge);background:#0b0d09;aspect-ratio:854/480} +#view{display:block;width:100%;height:100%;image-rendering:pixelated;user-select:none} +#capture{position:absolute;inset:0;cursor:crosshair;touch-action:none} +#overlay{pointer-events:none;position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:#0d110a55} +#overlay[hidden]{display:none} +#overlay div{padding:12px 25px;background:#141a10ee;text-align:center;border:2px solid var(--edge);font-size:22px;font-family:Georgia,'Microsoft YaHei',serif} +#offline{position:absolute;inset:0;display:flex;flex-direction:column;justify-content:center;padding:28px 40px;background:#12160fef;font-size:14px} +#offline[hidden]{display:none} +#offline h2{margin:0 0 8px;font-size:20px;color:var(--warn)} +#offline pre{white-space:pre-wrap;background:#0a0c08;border:1px solid var(--edge);padding:10px 12px;font:13px Consolas,monospace;color:#d8f0c4} +.toolbar{display:flex;flex-wrap:wrap;gap:9px;padding:12px;background:var(--panel);border:1px solid var(--edge);border-top:0} +button,select,input{font:inherit;border:1px solid var(--edge);border-radius:2px;background:#30382a;color:var(--paper);padding:7px 10px} +button{cursor:pointer;box-shadow:inset 0 -3px 0 #1d2318} +button:hover{border-color:var(--accent)} +button.primary{background:#5d8f3c;color:#0f140b;font-weight:700;box-shadow:inset 0 -3px 0 #3d6524} +select,input[type=number]{width:100%} +aside label{display:block;margin:12px 0 5px;color:var(--muted);font-size:13px} +.hint{margin:5px 0 0;color:var(--muted);font-size:12px} +aside h2{font-size:17px;margin:18px 0 10px} +aside>div:first-child h2{margin-top:0} +.panel{margin-top:16px;padding:10px 12px;background:var(--panel);border:1px solid var(--edge)} +.row{display:flex;justify-content:space-between;gap:10px;font-size:13px;color:var(--muted)} +.row b{color:var(--paper);font-weight:600;text-align:right} +dl{margin:8px 0} +dt{color:var(--accent);font-family:Consolas,monospace;font-size:12px} +dd{margin:0 0 10px;font-size:13px;color:var(--muted)} +#status{min-height:28px;margin:10px 0;color:var(--warn);font-size:13px;overflow-wrap:anywhere} +.note{color:var(--muted);font-size:13px} +.mobile{display:none;gap:6px;flex-wrap:wrap;padding:10px;background:var(--panel);border:1px solid var(--edge);border-top:0} +.mobile button{flex:1 1 22%;padding:12px 4px} +footer{border-top:1px solid var(--edge);margin-top:25px;padding-top:14px;display:flex;gap:18px;flex-wrap:wrap;font-size:13px} +@media (max-width:900px){.layout{grid-template-columns:1fr}main{padding:14px}header{flex-direction:column;gap:6px}.mobile{display:flex}} +@media (pointer:coarse){.mobile{display:flex}} diff --git a/environments/games/web/games/nfsmw_remake/compact_actions.json b/environments/games/web/games/nfsmw_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..248e057098e2b89933c8ac97b286c905e54fb338 --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/compact_actions.json @@ -0,0 +1,269 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "nfsmw_remake", + "version": "nfsmw-compact@1", + "note": "Four heads, 4 x 13 x 2 x 6 = 624 actions, each held for one 200 ms packet (6 sub-steps of 2 native ticks). No mouse: this game reads none. Pedal and steering are duty cycles over the 6 sub-steps because the car model integrates them: the wheel slews towards the key held and back to centre at the same rate (nfscore.js carStep), so a steering key held for 3 of 6 sub-steps keeps the current angle, 4 or 6 winds it on, 2 lets it come back slowly, none returns it to centre. Options chosen from the reference controller (harness/duty_stats.js: 16001 packets, all six events x three tiers x seeds 1-2) and tested by projecting every reference packet onto this set (harness/compact_sim.js, the same projection as compact.py): versions with 11 steering options lost speed-trap hard 4->2 and the final normal 3->2; the 2/6 ease options brought them back.", + "heads": [ + { + "name": "pedal", + "options": [ + { + "label": "none" + }, + { + "label": "throttle_light", + "note": "the reference's corner exit: drive force limited by the friction circle", + "subs": [ + [], + [], + [], + [], + [], + [ + "W" + ] + ] + }, + { + "label": "throttle", + "keys": [ + "W" + ] + }, + { + "label": "brake", + "keys": [ + "S" + ] + } + ], + "note": "full throttle 65% of the reference packets, brake 16%, one sub-step in six 11% (corner exits, where the friction circle leaves little drive). A half throttle option was tried and dropped: it changed no result (v6 vs v7)." + }, + { + "name": "steer", + "options": [ + { + "label": "none" + }, + { + "label": "left_tap", + "note": "drag series: A and D are lane changes on a press (modes_drag.js input), so one press per packet", + "tap": [ + "A" + ] + }, + { + "label": "left_ease", + "subs": [ + [], + [], + [ + "A" + ], + [], + [ + "A" + ], + [] + ] + }, + { + "label": "left_hold", + "subs": [ + [ + "A" + ], + [], + [ + "A" + ], + [], + [ + "A" + ], + [] + ] + }, + { + "label": "left_hold_late", + "subs": [ + [], + [ + "A" + ], + [], + [ + "A" + ], + [], + [ + "A" + ] + ] + }, + { + "label": "left_more", + "subs": [ + [ + "A" + ], + [ + "A" + ], + [], + [ + "A" + ], + [], + [ + "A" + ] + ] + }, + { + "label": "left_full", + "keys": [ + "A" + ] + }, + { + "label": "right_tap", + "tap": [ + "D" + ] + }, + { + "label": "right_ease", + "subs": [ + [], + [], + [ + "D" + ], + [], + [ + "D" + ], + [] + ] + }, + { + "label": "right_hold", + "subs": [ + [ + "D" + ], + [], + [ + "D" + ], + [], + [ + "D" + ], + [] + ] + }, + { + "label": "right_hold_late", + "subs": [ + [], + [ + "D" + ], + [], + [ + "D" + ], + [], + [ + "D" + ] + ] + }, + { + "label": "right_more", + "subs": [ + [ + "D" + ], + [ + "D" + ], + [], + [ + "D" + ], + [], + [ + "D" + ] + ] + }, + { + "label": "right_full", + "keys": [ + "D" + ] + } + ], + "note": "left_tap / right_tap: one press per packet, the lane change of the drag series (modes_drag.js reads pressed A / D there). The duty options steer everywhere else." + }, + { + "name": "nitrous", + "options": [ + { + "label": "none" + }, + { + "label": "nitrous", + "note": "only burns while the throttle is down (nfscore.js carStep)", + "keys": [ + "Shift" + ] + } + ], + "note": "only burns while the throttle is down (nfscore.js carStep: engaged needs thr > 0)" + }, + { + "name": "press", + "note": "J (slow motion), K / L (gears, drag series only) and R (reset) act on a press (pressed.has in game.js), so each is one press at the start of the packet. The handbrake is held, and it shares this head because a handbrake turn and a gear change or a reset are never wanted in the same 200 ms.", + "options": [ + { + "label": "none" + }, + { + "label": "shift_up", + "tap": [ + "K" + ] + }, + { + "label": "shift_down", + "tap": [ + "L" + ] + }, + { + "label": "slowmo", + "tap": [ + "J" + ] + }, + { + "label": "reset", + "tap": [ + "R" + ] + }, + { + "label": "handbrake", + "note": "held, not a press: carStep reads it every tick. The reference controller never uses it; kept because it is a basic control of the event. It shares this head with the single presses because a handbrake turn and a gear change or a reset are never wanted in the same 200 ms", + "keys": [ + "Space" + ] + } + ] + } + ] +} diff --git a/environments/games/web/games/nfsmw_remake/cops.js b/environments/games/web/games/nfsmw_remake/cops.js new file mode 100644 index 0000000000000000000000000000000000000000..7c4d43a227d7de5861b5401ab8effb10b5e53439 --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/cops.js @@ -0,0 +1,158 @@ +/* Police. Rules read from AI/Common/AIPursuit.cpp unless noted (all values in the VLT pursuitlevels table are approximations, by tier): + - busted meter: :1887-1940, up while a cop sees the player, the player is under BustSpeed and the nearest cop is within 15 m, down twice + as fast otherwise, busted above 5 (kBustedTimeout, kBustedCopDistance :1607-8; Sim/Common/Simulation.cpp:345 for the task rates); + - during a manual-reset flash the distance is x6 and the rate x4 (:1895-1909); + - sight: 150 m ahead of the cop, 50 m behind it, and the world ray must be clear (AIVehicleCopCar.cpp:88-168), helicopter 250 m (AIVehicleHelicopter.cpp:114); + - evade: more than 7 s unseen, then (unseen + hidden time) / evadetimeout reaches 1 (:2027-2061); seen again, it decays x0.93 per task (:2097); + - roadblocks: a request every 8-12 s with a probability (:2459-2507); a roadblock's cops join the chase after a spike hit (SpikesHit :2791); + - formations: FOLLOW, ROLLING_BLOCK, BOX_IN, PIT (:976-1010), cops within 60 m qualify (kFormationCandidateDistance :1221); + - spikes: a tyre over the strip punctures and blows 0.5 s later (DamageRacer.cpp:12), grip x0.3 (SuspensionRacer.cpp:1569); + - destroying cops: bonus multiplier up to 3 inside DestroyCopBonusTime (IncNumCopsDestroyed :917). + A cop is a free body, not on rails: with sight it drives straight at its slot (sight means the straight line is clear), without sight it follows + the route towards where the player was last seen. All decisions draw from the game RNG, and the controller never copies the game. */ +(function (root) { + 'use strict'; + const M = root.NfsmwGame, C = M.C, N = root.NativeBench, clamp = C.clamp, P = C.PLAYER; + const BUST_MAX = 5, BUST_DIST = 15, FRONT_LOS = 150, REAR_LOS = 50, HELI_LOS = 250, EVADE_AFTER = 7, RESET_DIST = 6, RESET_RATE = 4, RECYCLE_DIST = 320, RECYCLE_S = 6, BARRIER_R = 2.6, BARRIER_KEEP = 0.62; + const wrapTo = (R, v, ref) => { if (!R.loop) return v; let ds = (v - ref) % R.L; if (ds > R.L / 2) ds -= R.L; else if (ds < -R.L / 2) ds += R.L; return ref + ds; }; + M.wrapTo = wrapTo; + // o: copsMax, top, grip, accel, spawnGap, formations, rbChance, spikeChance, heli, heliAfter, heliFuel, heliGap, bustKph + M.initPolice = (g, o) => { + g.pol = Object.assign({ bust: 0, seen: 0, sinceSeen: 0, evade: 0, spawnT: o.spawnGap, rbT: 9, formT: 4, formation: 'FOLLOW', pursuitT: 0, destroyed: 0, bonusT: 0, bonusMult: 1, lockT: 0, lastS: g.s, heliT: o.heliAfter, combo: 0, sawNow: 1, inSight: 1 }, o); + g.cops = []; g.props = []; g.blocks = []; g.heli = null; g.puncT = 0; g.punc = 0; + }; + M.spawnCop = (g, s, lat, dir, state = 'chase', h) => { + const R = g.route, a = C.routeAt(R, s, lat), c = { x: a.x, y: a.y, h: h !== undefined ? h : dir > 0 ? a.h : a.h + Math.PI, v: state === 'rb' ? 0 : 20, s, lat, hp: 100, state, chasing: state === 'chase' ? 1 : 0, dead: 0, gone: 0, slot: g.cops.length, sees: 0, hitT: 0, deadT: 0, lostT: 0 }; + g.cops.push(c); return c; + }; + const destroy = (g, c, why) => { + c.dead = 1; c.chasing = 0; c.deadT = 4; const p = g.pol; p.destroyed++; + p.bonusMult = p.bonusT > 0 ? Math.min(3, p.bonusMult + 1) : 1; p.bonusT = 8; p.combo = p.bonusMult; + g.events.push({ type: 'cop_destroyed', why, mult: p.bonusMult }); + }; + M.destroyCop = destroy; + // Slot offsets in the player's frame: [metres ahead, metres to the left]. Numbers are original: the formation classes' tables are VLT-driven. + const SLOTS = { FOLLOW: [[-11, -2.5], [-11, 2.5], [-22, 0], [-30, -4], [-30, 4]], ROLLING_BLOCK: [[14, -3.2], [14, 3.2], [24, 0], [-12, 0], [-22, 3]], BOX_IN: [[-6, -4.2], [-6, 4.2], [12, 0], [-14, 0], [-22, 0]], PIT: [[-3, -3.4], [-3, 3.4], [-12, 0], [-22, 3], [-22, -3]] }; + function stepCop(g, c, wdt, losTick) { + const p = g.pol, R = g.route, car = g.car; + if (c.deadT > 0) { c.deadT -= wdt; c.v = Math.max(0, c.v - 12 * wdt); c.x += Math.cos(c.h) * c.v * wdt; c.y += Math.sin(c.h) * c.v * wdt; if (c.deadT <= 0) c.gone = 1; return; } + const dx = car.x - c.x, dy = car.y - c.y, dist = Math.hypot(dx, dy); + c.s = C.routeNear(R, c.x, c.y, wrapTo(R, c.s, g.s), 30, 30); c.lat = C.routeLat(R, c.x, c.y, c.s); + if (losTick) { const dot = (Math.cos(c.h) * dx + Math.sin(c.h) * dy) / (dist || 1); c.sees = (dist < REAR_LOS || (dist < FRONT_LOS && dot > 0)) && C.lineClear(c.x, c.y, car.x, car.y) ? 1 : 0; } + if (c.state === 'rb') { // parked across the road; joins in once the player is past or a strip was hit + if (g.s - c.s > 12 || c.join) { c.state = 'chase'; c.chasing = 1; } + else return; + } + let tx, ty; + if (c.sees && dist < 60) { // in formation (kFormationCandidateDistance) + const slots = SLOTS[p.formation], sl = slots[c.slot % slots.length], ch = Math.cos(car.h), sh = Math.sin(car.h), lead = C.speed(car) * 0.25; + tx = car.x + ch * (sl[0] + lead) - sh * sl[1]; ty = car.y + sh * (sl[0] + lead) + ch * sl[1]; + if (p.formation === 'PIT' && (c.slot % slots.length) < 2 && dist < 9) { tx = car.x + ch * lead; ty = car.y + sh * lead; } // the ram itself + } else if (c.sees) { const lead = C.speed(car) * 0.35; tx = car.x + Math.cos(car.h) * lead; ty = car.y + Math.sin(car.h) * lead; } + else { // search: along the route towards the last known position (the route is where the sim keeps its cops) + const dS = wrapTo(R, p.lastS, c.s) - c.s, dirn = dS >= 0 ? 1 : -1, a = C.routeAt(R, c.s + dirn * Math.max(10, c.v * 0.6), clamp(c.lat, -3, 3)); tx = a.x; ty = a.y; + } + let want = Math.atan2(ty - c.y, tx - c.x) - c.h; want = Math.atan2(Math.sin(want), Math.cos(want)); + const grip = P.grip * p.grip, rate = grip / Math.max(c.v, 6); + c.h += clamp(want, -rate * wdt, rate * wdt); + // Speed: the road's limit ahead, its class top, and the gap to its slot when it has sight (it has to hold station, not overshoot). + const prof = C.profile(R, grip, P.aero, P.brake * 0.9, p.top); let lim = Math.min(C.profileAt(R, prof, c.s + c.v * 0.3), C.profileAt(R, prof, c.s - c.v * 0.3)); + if (Math.abs(want) > 0.9) lim = Math.min(lim, 12); + if (!c.sees) lim = Math.min(lim, p.searchTop); + else if (dist < 60) { const sd = Math.hypot(tx - c.x, ty - c.y), ahead = Math.cos(want) > 0; lim = Math.min(lim, Math.max(4, C.speed(car) + (ahead ? clamp(sd * 0.5, -6, p.close) : -6))); } + if (c.v > lim) c.v = Math.max(lim, c.v - P.brake * 0.9 * wdt); + else c.v = Math.min(lim, c.v + Math.max(0.5, C.driveAt(c.v) * p.accel - P.drag * c.v * c.v - P.roll) * wdt); + c.x += Math.cos(c.h) * c.v * wdt; c.y += Math.sin(c.h) * c.v * wdt; + const q = C.road(c.x, c.y), over = q.d + 1.2; if (over > 0) { c.x -= q.nx * over; c.y -= q.ny * over; c.v *= 1 - Math.min(0.4, 2 * wdt); } + } + // Contact with the player: equal masses along the normal, closing speed scrapes the cop's damage (DamageVehicle::OnImpact; the table is VLT). + function contact(g, c) { + const car = g.car, dx = car.x - c.x, dy = car.y - c.y, d2 = dx * dx + dy * dy, R2 = M.carRadius * 2; if (d2 >= R2 * R2) return; + const d = Math.max(0.01, Math.sqrt(d2)), nx = dx / d, ny = dy / d, cvx = Math.cos(c.h) * c.v, cvy = Math.sin(c.h) * c.v, rel = (car.vx - cvx) * nx + (car.vy - cvy) * ny, push = R2 - d; + car.x += nx * push * 0.5; car.y += ny * push * 0.5; c.x -= nx * push * 0.5; c.y -= ny * push * 0.5; + if (rel >= 0) return; + const j = -0.75 * rel; car.vx += nx * j; car.vy += ny * j; c.v = Math.max(0, c.v - j * (Math.cos(c.h) * -nx + Math.sin(c.h) * -ny) * -1); if (c.v > 90) c.v = 90; + if (c.hitT <= 0 && -rel > 3) { + c.hitT = 0.4; g.lastHit = 0.25; g.hits++; const dmg = -rel * g.pol.copFrail; c.hp -= dmg; + if (c.state === 'rb') { c.join = 1; for (const o of g.cops) if (o.state === 'rb') o.join = 1; } + g.events.push({ type: 'cop_contact', speed: -rel, hp: c.hp }); + if (c.hp <= 0) destroy(g, c, 'ram'); + } + } + const spawnAway = (g) => { + const p = g.pol, R = g.route, ahead = (p.sawNow || p.aheadBlind) && N.rand(g) < p.aheadChance, S = g.s + (ahead ? 320 + N.rand(g) * 120 : -(210 + N.rand(g) * 90)), lat = (N.rand(g) < 0.5 ? -1 : 1) * R.halfW * 0.4; + if (!R.loop && (S < 20 || S > R.L - 20)) return; + const c = M.spawnCop(g, S, lat, ahead ? -1 : 1, 'chase'); + c.slot = p.nextSlot = (p.nextSlot || 0) + 1; + }; + function stepRoadblocks(g, wdt) { + const p = g.pol, R = g.route; p.rbT -= wdt; + // AIPursuit.cpp:2459: a request every 8-12 s; the probability and the spike chance are the heat level's VLT values (approximations). + if (p.rbT <= 0) { + p.rbT = 8 + N.rand(g) * 4; + if (!g.props.some(x => x.type === 'barrier') && p.rbChance > 0 && N.rand(g) < p.rbChance && C.speed(g.car) > 15 && !p.lockT) { + const S = g.s + Math.max(180, C.speed(g.car) * 5.5), a = C.routeAt(R, S), h = a.h, kN = Math.abs(a.k); if (kN < 0.012) { + const hw = R.halfW, gapSide = N.rand(g) < 0.5 ? -1 : 1, gapW = p.rbGap, block = []; for (let l = -hw + 1.8; l < hw - 1.6; l += 4.3) if (gapSide * l < hw - gapW || Math.abs(l) < 0) block.push(l); + block.forEach((l, i) => { if (i % 2 === 0) { const c = M.spawnCop(g, S, l, 1, 'rb', h + Math.PI / 2); c.slot = i; } else { const b = C.routeAt(R, S, l); g.props.push({ type: 'barrier', x: b.x, y: b.y, h: h + Math.PI / 2, s: S, lat: l, ttl: 40 }); } g.blocks.push({ s: S, lat: l }); }); + if (N.rand(g) < p.spikeChance) { const S2 = S - 26, side = -gapSide, L = hw + 3, l0 = gapSide * (hw - gapW) + side * 0 - gapSide * L / 2, b = C.routeAt(R, S2, l0); g.props.push({ type: 'spike', x: b.x, y: b.y, h: h, s: S2, lat: l0, len: L, ttl: 40 }); } + g.events.push({ type: 'roadblock', s: S, gap: gapSide }); + } + } + } + for (const o of g.props) if (o.ttl !== undefined) { o.ttl -= wdt; if (o.ttl <= 0 || g.s - wrapTo(R, o.s, g.s) > 160) o.gone = 1; } + g.props = g.props.filter(o => !o.gone); + g.blocks = g.blocks.filter(b => g.s - wrapTo(R, b.s, g.s) < 40); + for (const o of g.props) if (o.type === 'barrier' && !o.gone) { const dx = g.car.x - o.x, dy = g.car.y - o.y; if (dx * dx + dy * dy < BARRIER_R * BARRIER_R) { const v = C.speed(g.car); g.car.vx *= BARRIER_KEEP; g.car.vy *= BARRIER_KEEP; o.gone = 1; g.hits++; g.lastHit = 0.3; g.events.push({ type: 'barrier', speed: v }); for (const k of g.cops) if (k.state === 'rb') k.join = 1; } } + // Spikes: wheels are ±0.9 m off the centreline; each side over the strip is two tyres, punctured now and blown 0.5 s later. + const c = g.car; + for (const o of g.props) if (o.type === 'spike' && !o.used) { + const a = C.routeAt(R, o.s), ds = (c.x - a.x) * Math.cos(a.h) + (c.y - a.y) * Math.sin(a.h); + if (Math.abs(ds) < C.speed(c) * wdt + 0.6) { let n = 0; for (const w of [-0.9, 0.9]) if (Math.abs(g.lat + w - o.lat) < o.len / 2) n += 2; if (n && !g.flash) { o.used = 1; g.punc = Math.max(g.punc, n); g.puncT = 0.5; for (const k of g.cops) if (k.state === 'rb') k.join = 1; g.events.push({ type: 'spikes', tyres: n }); } } + } + if (g.puncT > 0) { g.puncT -= wdt; if (g.puncT <= 0) c.tires = Math.max(c.tires, g.punc); } + } + function stepHeli(g, wdt) { + const p = g.pol, car = g.car; if (!p.heli) return; + if (!g.heli) { p.heliT -= wdt; if (p.heliT <= 0 && !p.lockT) { g.heli = { x: car.x - Math.cos(car.h) * 200, y: car.y - Math.sin(car.h) * 200, z: 34, h: car.h, fuel: p.heliFuel, sees: 0, gone: 0 }; g.events.push({ type: 'helicopter' }); } return; } + const h = g.heli, sp = C.speed(car), lead = sp * 0.4 + 30, ch = Math.cos(car.h), sh = Math.sin(car.h), tx = car.x + ch * lead, ty = car.y + sh * lead, dx = tx - h.x, dy = ty - h.y, d = Math.hypot(dx, dy) || 1, v = Math.min(85, d * 1.4); // AIActionHeliPursuit.cpp:26,leadDist + h.x += dx / d * v * wdt; h.y += dy / d * v * wdt; h.h = Math.atan2(dy, dx); h.fuel -= wdt; h.sees = Math.hypot(car.x - h.x, car.y - h.y) < HELI_LOS ? 1 : 0; + if (h.fuel <= 0) { g.heli = null; p.heliT = p.heliGap; g.events.push({ type: 'helicopter_leaves' }); } + } + // Returns nothing; updates sight, the bust meter, spawns and contacts. evadeOn: whether the evade meter runs (pursuit only). + M.stepPolice = (g, wdt, evadeOn) => { + const p = g.pol, car = g.car, R = g.route, losTick = g.t % 4 === 0; + if (p.bonusT > 0) p.bonusT = Math.max(0, p.bonusT - wdt); + if (p.lockT > 0) p.lockT = Math.max(0, p.lockT - wdt); + p.formT -= wdt; if (p.formT <= 0) { p.formT = 9 + N.rand(g) * 6; p.formation = p.formations[Math.floor(N.rand(g) * p.formations.length) % p.formations.length]; } + let seen = 0, near = Infinity; + for (const c of g.cops) { if (c.gone) continue; c.hitT = Math.max(0, c.hitT - wdt); stepCop(g, c, wdt, losTick); if (!c.dead && c.state !== 'rb') { if (c.sees) seen = 1; near = Math.min(near, Math.hypot(car.x - c.x, car.y - c.y)); } contact(g, c); } + // Out of sight and far behind for a while: gone, so the slot can spawn a cop that can still engage (RemoveUnwantedVehicles / StartFlee; the distances are approximations). + for (const c of g.cops) { if (c.dead || c.state === 'rb') continue; const far = !c.sees && Math.hypot(car.x - c.x, car.y - c.y) > RECYCLE_DIST; c.lostT = far ? c.lostT + wdt : 0; if (c.lostT > RECYCLE_S) c.gone = 1; } + g.cops = g.cops.filter(c => !c.gone); + for (let i = 0; i < g.cops.length; i++) for (let j = i + 1; j < g.cops.length; j++) { const a = g.cops[i], b = g.cops[j]; if (a.dead || b.dead) continue; const dx = a.x - b.x, dy = a.y - b.y, d2 = dx * dx + dy * dy; if (d2 < 10 && d2 > 1e-4 && a.state !== 'rb' && b.state !== 'rb') { const d = Math.sqrt(d2), pu = (3.2 - d) * 0.5; a.x += dx / d * pu; a.y += dy / d * pu; b.x -= dx / d * pu; b.y -= dy / d * pu; } } + stepHeli(g, wdt); if (g.heli && g.heli.sees) seen = 1; + stepRoadblocks(g, wdt); + p.sawNow = seen; + const active = g.cops.filter(c => !c.dead && c.state !== 'rb').length; + p.spawnT -= wdt; if (p.spawnT <= 0 && active < p.copsMax && !p.lockT) { p.spawnT = p.spawnGap; spawnAway(g); } + // Bust meter (AIPursuit.cpp:1889-1940, the flash rules at :1895-1909). + const flashing = g.flash > 0, bdist = BUST_DIST * (flashing ? RESET_DIST : 1), slow = flashing || C.speed(car) < p.bustSpeed; + if (seen) { p.seen += wdt; p.sinceSeen = 0; p.lastS = g.s; p.pursuitT += wdt; } else p.sinceSeen += wdt; + // mIsPerpInSight is "a cop saw the perp within the last 7 s" (AIPursuit.cpp:2000), not "a cop sees the perp now". + p.inSight = p.sinceSeen < EVADE_AFTER ? 1 : 0; + p.bust = Math.max(0, p.bust + (p.inSight && slow && near < bdist ? (flashing ? RESET_RATE : 1) : -2) * wdt); + if (evadeOn) { + if (seen) p.evade *= Math.pow(0.93, wdt * 15); + else if (p.sinceSeen > EVADE_AFTER) p.evade = Math.max(p.evade, Math.min(1, p.sinceSeen / p.evadeTimeout)); + } + if (p.bust > BUST_MAX) { p.bust = BUST_MAX; g.lose('busted'); } + }; + M.BUST_MAX = BUST_MAX; + M.bustHp = g => Math.round((BUST_MAX - g.pol.bust) * 10); + // Road users for the controller: decided poses only. + M.copUsers = (g, R, out) => { + const add = (s, lat, vs, cop, vl = 0) => out.push({ s: wrapTo(R, s, g.s), lat, vs, r: 2, cop, vl }); + for (const c of g.cops) { if (c.gone) continue; const dh = c.h - C.routeAt(R, c.s).h, still = c.dead || c.state === 'rb'; add(c.s, c.lat, still ? 0 : c.v * Math.cos(dh), still ? 0 : 1, still ? 0 : c.v * Math.sin(dh)); } + for (const o of g.props) if (o.type === 'barrier') add(o.s, o.lat, 0); else if (o.type === 'spike' && !o.used) for (let l = -o.len / 2; l <= o.len / 2 + 0.01; l += 2) add(o.s, o.lat + l, 0); + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/nfsmw_remake/draw.js b/environments/games/web/games/nfsmw_remake/draw.js new file mode 100644 index 0000000000000000000000000000000000000000..09c5cd581b317a7f8c194d576c34cad689dcc524 --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/draw.js @@ -0,0 +1,166 @@ +/* NFS Most Wanted events - Module.draw: the WebGL chase view plus an original Canvas 2D HUD (speed, gear, nitrous and Speedbreaker + gauges, route minimap, event panel). BossBench additions: both public health bars, fight timer and the native tick rate. + Read-only on the game state. + 2026-11-08: what the agent needs from the picture alone. + - Threat telegraphs: a warning strip when a roadblock or spike strip is on the road ahead, when a cop holds a ramming slot + beside the car, when the helicopter's light is on the car, when the bust meter rises; edge arrows for cops and rivals + outside the picture (behind, round a corner); a frame around the rear-view mirror when a cop is in it. + - The drag series' manual box: a tachometer with the shift window (the perfect-shift band of carStep) and a light that turns + green there, the launch band during staging, and the keys to press. A player who only holds W knew none of this. + - HUD panels keep to the screen edges and are smaller, so more of the road and the cars stays visible. + Everything here is drawn from state the simulation already decided this tick; nothing is written back. */ +(function (root) { + 'use strict'; + const M = root.NfsmwGame, C = M.C, R = M.R3; + const W = 854, H = 480; + const panel = (c, x, y, w, h, a = 0.58) => { c.fillStyle = `rgba(10,14,22,${a})`; c.beginPath(); c.roundRect(x, y, w, h, 6); c.fill(); }; + const bar = (c, x, y, w, h, v, col, back = 'rgba(255,255,255,.14)') => { c.fillStyle = back; c.fillRect(x, y, w, h); c.fillStyle = col; c.fillRect(x, y, w * C.clamp(v, 0, 1), h); }; + const LABEL = { time: 'Time expired', gap: 'Rival pulled away', blown: 'Engine blown', totaled: 'Crash wreck', busted: 'Busted', knocked: 'Eliminated in last place', score: 'Lost on total score' }; + // HUD rectangles [x0, y0, x1, y1]; the view metric counts a target under one of these as not visible. + const RECT = { tier: [8, 8, 150, 46], event: [158, 8, 696, 46], clock: [704, 8, 846, 46], speedo: [708, 392, 846, 472], map: [10, 372, 108, 470], tach: [708, 352, 846, 382] }; + M.hudRects = Object.values(RECT); + const FONT = '"Microsoft YaHei",Consolas,sans-serif'; + function minimap(g, c) { + const R0 = g.route, size = 98, x0 = RECT.map[0], y0 = RECT.map[1], big = R0.name === 'downtown', span = R0.name === 'strip' ? 700 : big ? 200 : 460, k = size / 2 / span; + panel(c, x0, y0, size, size, 0.62); c.save(); c.beginPath(); c.rect(x0, y0, size, size); c.clip(); + const car = g.car, tx = u => x0 + size / 2 + (u - car.x) * k, ty = v => y0 + size / 2 - (v - car.y) * k; + c.lineWidth = Math.max(2.4, 8 * k * 6); c.strokeStyle = 'rgba(190,200,215,.28)'; + for (const st of C.streets) { c.beginPath(); st.forEach((p, i) => i ? c.lineTo(tx(p[0]), ty(p[1])) : c.moveTo(tx(p[0]), ty(p[1]))); c.stroke(); } + c.strokeStyle = 'rgba(245,240,225,.85)'; c.beginPath(); for (let i = 0; i <= R0.n; i += 6) { const u = i % R0.n; const px = tx(R0.x[u]), py = ty(R0.y[u]); i ? c.lineTo(px, py) : c.moveTo(px, py); } if (R0.loop) c.closePath(); c.stroke(); + const dot = (x, y, col, r = 3) => { c.fillStyle = col; c.beginPath(); c.arc(tx(x), ty(y), r, 0, 7); c.fill(); }; + for (const gt of g.gates || []) if (!gt.done) { const a = C.routeAt(R0, gt.s !== undefined ? gt.s : g.s0 + gt.at); dot(a.x, a.y, gt.kind === 'trap' ? '#ffb037' : '#7dff9a', 3.2); } + for (const r of g.rivals) if (!r.gone) dot(r.x, r.y, r.name === 'champion' ? '#ff4a3a' : '#ffffff'); + for (const b of g.breakers || []) if (!(b.rearm > 0)) dot(b.x, b.y, '#ff8a3c', 3); + for (const p of g.cops) if (!p.gone && !p.dead) dot(p.x, p.y, (g.t >> 4) % 2 ? '#4a8cff' : '#ff4a5a'); + for (const p of g.props || []) if (!p.gone && p.type !== 'cone') dot(p.x, p.y, p.type === 'spike' ? '#ffd020' : '#ffe030', 2.4); + if (g.heli && !g.heli.gone) dot(g.heli.x, g.heli.y, '#ffffff', 2.6); + c.translate(tx(car.x), ty(car.y)); c.rotate(-car.h); c.fillStyle = '#ffb060'; c.beginPath(); c.moveTo(7, 0); c.lineTo(-4, 4); c.lineTo(-4, -4); c.closePath(); c.fill(); c.restore(); + } + // ---- telegraphs: everything here is a fact the sim decided already (a placed prop, a cop's position, the formation) ---- + const warnings = []; + function threats(g, info) { + warnings.length = 0; info.warn = []; info.arrows = []; info.flames = []; info.cover = []; + const car = g.car, R = g.route, sp = Math.max(C.speed(car), 5), ch = Math.cos(car.h), sh = Math.sin(car.h); + if (g.outcome) return; + // roadblock / spikes on the road ahead (cops.js places them max(180, 5.5 v) m ahead; the original 250 m) + let rb = null, sk = null; + for (const p of g.props || []) { if (p.gone || p.used) continue; const ds = M.wrapTo ? M.wrapTo(R, p.s, g.s) - g.s : p.s - g.s; if (ds <= 0 || ds > 320) continue; if (p.type === 'spike') { if (!sk || ds < sk.ds) sk = { ds, p }; } else if (p.type === 'barrier') { if (!rb || ds < rb.ds) rb = { ds, p }; } } + if (rb) { warnings.push({ col: '#ffb020', text: `Roadblock ahead: ${Math.round(rb.ds)} m (${(rb.ds / sp).toFixed(1)} s)` }); info.warn.push('roadblock'); } + if (sk) { warnings.push({ col: '#ffd020', text: `Spike strip: ${Math.round(sk.ds)} m · on the ${sk.p.lat > 0 ? 'left' : 'right'} side` }); info.warn.push('spikes'); } + // ramming formation: a cop with sight inside 12 m while PIT or BOX_IN is the formation + if (g.pol) { + const close = g.cops.filter(k => !k.dead && !k.gone && k.state !== 'rb' && k.sees && Math.hypot(k.x - car.x, k.y - car.y) < 12); + if (close.length && (g.pol.formation === 'PIT' || g.pol.formation === 'BOX_IN')) { const k = close[0], side = (-(k.x - car.x) * sh + (k.y - car.y) * ch) > 0 ? 'left' : 'right'; warnings.push({ col: '#ff4a5a', text: g.pol.formation === 'PIT' ? `Police car ${side} rear ready to ram` : 'Police car box-in' }); info.warn.push('pit'); } + if (g.heli && !g.heli.gone && g.heli.sees) { warnings.push({ col: '#cfe0ff', text: 'Helicopter spotlight locked on' }); info.warn.push('heli'); } + if (g.pol.bust > 0.03) info.warn.push('bust'); + } + // edge arrows: cops within 160 m and rivals within 200 m that are not in the main picture + const sc = R3sc(g); + const arrow = (kind, ref, x, y, col) => { + if (!sc) return; const p = sc.project(x, y, 0.8); const inside = p.front && p.x > 8 && p.x < W - 8 && p.y > 50 && p.y < H - 8; if (inside) return; + // direction in the car's frame -> a point on an ellipse around the screen centre + const dx = x - car.x, dy = y - car.y, fwd = dx * ch + dy * sh, left = -dx * sh + dy * ch, ang = Math.atan2(-left, fwd); // 0 = ahead, +pi/2 = right + info.arrows.push({ kind, ref, ang, dist: Math.hypot(dx, dy), col }); + }; + g.cops.forEach((k, i) => { if (!k.gone && !k.dead && Math.hypot(k.x - car.x, k.y - car.y) < 160) arrow('cop', i, k.x, k.y, (g.t >> 3) % 2 ? '#ff4a5a' : '#4a8cff'); }); + g.rivals.forEach((r, i) => { if (!r.gone && !r.out && Math.hypot(r.x - car.x, r.y - car.y) < 200) arrow('rival', i, r.x, r.y, r.name === 'champion' ? '#ff4a3a' : '#ffffff'); }); + g.rivals.forEach((r, i) => { if (!r.gone && !r.out && (r.nosT > 0 || r.trapNos > 0) && r.nos > 0.02) info.flames.push(i); }); + if (g.heli && !g.heli.gone) arrow('heli', 0, g.heli.x, g.heli.y, '#e8f0ff'); + } + let cur = null; const R3sc = () => cur; // the scene this frame was rendered with (R3.render returns it) + function drawArrows(c, info) { + // one arrow per side of the screen at most: overlapping arrows (two rivals right behind) read as one, the nearest wins + const drawn = []; + for (const a of [...info.arrows].sort((p, q) => p.dist - q.dist)) { + const s = Math.sin(a.ang), co = Math.cos(a.ang), x = W / 2 + s * 380, y = H / 2 + 24 - co * 200; + let cx = C.clamp(x, 26, W - 26), cy = C.clamp(y, 64, H - 70); + if (cy >= H - 100 && Math.abs(cx - W / 2) < 130) cx = W / 2 + (s >= 0 ? 130 : -130); // behind: either side of the car, not over it + if (cy > 350 && (cx < 122 || cx > 696)) cy = 350; // clear of the minimap and the speedometer + if (drawn.some(d => Math.hypot(d[0] - cx, d[1] - cy) < 34)) continue; drawn.push([cx, cy]); + const near = C.clamp(1 - a.dist / 160, 0.25, 1), size = 9 + 9 * near; + c.save(); c.translate(cx, cy); c.rotate(a.ang); c.globalAlpha = 0.55 + 0.45 * near; c.fillStyle = 'rgba(0,0,0,.6)'; c.beginPath(); c.moveTo(0, -size - 3); c.lineTo(size * 0.85 + 3, size * 0.6 + 2); c.lineTo(-size * 0.85 - 3, size * 0.6 + 2); c.closePath(); c.fill(); + c.fillStyle = a.col; c.beginPath(); c.moveTo(0, -size); c.lineTo(size * 0.85, size * 0.6); c.lineTo(-size * 0.85, size * 0.6); c.closePath(); c.fill(); c.restore(); + c.globalAlpha = 1; c.font = 'bold 10px Consolas,monospace'; c.fillStyle = '#ffffff'; c.textAlign = 'center'; c.fillText(Math.round(a.dist) + 'm', cx, cy + (cy > H / 2 ? -14 : 22)); c.textAlign = 'left'; + } + } + // One row at the bottom centre, on the road just in front of the bumper: the horizon band (y 150-190), where a roadblock + // 200 m ahead appears, stays clear. + function drawWarnings(c, g) { + if (!warnings.length) return; + c.font = `bold 14px ${FONT}`; const widths = warnings.map(w => c.measureText(w.text).width + 30), total = widths.reduce((a, b) => a + b, 0) + 8 * (warnings.length - 1), y = H - 32; + let x = W / 2 - total / 2; + M.hudInfo.cover.push([x, y, x + total, y + 24]); + for (const [i, w] of warnings.entries()) { + const tw = widths[i], on = (g.t >> 3) % 2 === 0; + c.fillStyle = 'rgba(10,10,14,.72)'; c.beginPath(); c.roundRect(x, y, tw, 24, 4); c.fill(); c.strokeStyle = w.col; c.lineWidth = on ? 3 : 1.5; c.stroke(); + c.fillStyle = w.col; c.beginPath(); c.moveTo(x + 9, y + 18); c.lineTo(x + 15, y + 6); c.lineTo(x + 21, y + 18); c.closePath(); c.fill(); c.fillStyle = '#111'; c.fillRect(x + 14.2, y + 10, 1.6, 4.5); + c.fillStyle = '#ffffff'; c.textAlign = 'left'; c.fillText(w.text, x + 25, y + 17); x += tw + 8; + } + } + // mirror frame (renderer3d draws the mirror image itself); red border while a cop is in it + function mirrorFrame(c, g) { + const sc = R3sc(g); if (!sc || !sc.mirrorOn) return; const [x0, y0, x1, y1] = sc.mirrorRect; + const copIn = g.cops.some(k => { if (k.gone || k.dead) return false; const dx = k.x - g.car.x, dy = k.y - g.car.y, fwd = dx * Math.cos(g.car.h) + dy * Math.sin(g.car.h); return fwd < 0 && Math.hypot(dx, dy) < 120; }); + c.strokeStyle = copIn && (g.t >> 3) % 2 ? '#ff4a5a' : 'rgba(230,236,245,.85)'; c.lineWidth = 2.5; c.strokeRect(x0 - 1, y0 - 1, x1 - x0 + 2, y1 - y0 + 2); + c.font = `10px ${FONT}`; c.fillStyle = 'rgba(230,236,245,.85)'; c.fillText('Rearview mirror', x0 + 3, y1 + 11); + } + // tachometer: fraction of the current gear's top speed (carStep's u), shift band 0.88-0.99, limiter at 1 + function tach(g, c) { + const car = g.car, [x, y, x1, y1] = RECT.tach, w = x1 - x, h = y1 - y, staging = g.pre > 0 && g.rev !== undefined; + const fwd = Math.max(0, car.vx * Math.cos(car.h) + car.vy * Math.sin(car.h)), u = staging ? g.rev : C.clamp(fwd / C.TOPS[car.gear], 0, 1.05); + const band = staging ? [0.62, 0.86] : [0.88, 0.99], inBand = u >= band[0] && u <= band[1]; + panel(c, x, y, w, h, 0.7); const bx = x + 6, bw = w - 12, by = y + 6; + c.fillStyle = 'rgba(255,255,255,.12)'; c.fillRect(bx, by, bw, 9); + c.fillStyle = 'rgba(90,255,140,.55)'; c.fillRect(bx + bw * band[0], by, bw * (band[1] - band[0]), 9); + if (!staging) { c.fillStyle = 'rgba(255,70,60,.55)'; c.fillRect(bx + bw * 0.99, by, bw * 0.01 + 2, 9); } + c.fillStyle = inBand ? '#7dff9a' : u > band[1] ? '#ff5a4a' : '#ffd08a'; c.fillRect(bx, by + 2, bw * C.clamp(u, 0, 1), 5); + c.font = `bold 11px ${FONT}`; c.fillStyle = inBand ? '#7dff9a' : '#c6d0dc'; + c.fillText(staging ? (inBand ? 'Launch RPM ✓ Hold steady' : g.rev < band[0] ? 'Hold W to raise RPM into the green zone' : 'RPM too high; release W briefly') : car.gear >= 5 ? 'Top gear · Stay below the redline' : inBand ? '▶ Press K to upshift' : u > band[1] ? 'Press K to upshift now!' : `RPM → Green zone: press K`, bx, by + 21); + if (inBand && !staging && car.gear < 5 && (g.t >> 2) % 2) { c.strokeStyle = '#7dff9a'; c.lineWidth = 2; c.strokeRect(x + 1, y + 1, w - 2, h - 2); } + } + M.draw = function (g, c) { + const sc = R.render(g, c), info = {}; cur = sc; + M.hudInfo = info; + const car = g.car, kmh = C.speed(car) * 3.6, h = g.health(), hud = (M.MODES[g.key].hud || (() => ({ label: '', detail: '' })))(g); + threats(g, info); + // knockout: the mode's text measures the last rival still in, and after the win none is left ( 11-06 item 7) + if (g.key === 'knockout' && g.outcome === 'win') hud.detail = `${g.laps} / ${g.laps} laps · All rivals eliminated`; + if (g.sb) { const v = c.createRadialGradient(W / 2, H / 2, 150, W / 2, H / 2, 520); v.addColorStop(0, 'rgba(120,170,255,0)'); v.addColorStop(1, 'rgba(70,110,220,.42)'); c.fillStyle = v; c.fillRect(0, 0, W, H); } + // hit: a red vignette at the edges, not a full-screen wash, so the road stays readable + if (g.lastHit > 0) { const v = c.createRadialGradient(W / 2, H / 2, 170, W / 2, H / 2, 500); v.addColorStop(0, 'rgba(220,40,30,0)'); v.addColorStop(1, `rgba(220,40,30,${Math.min(0.75, g.lastHit * 1.6)})`); c.fillStyle = v; c.fillRect(0, 0, W, H); } + if (g.flash > 0 && (g.t >> 3) % 2) { c.fillStyle = 'rgba(255,255,255,.1)'; c.fillRect(0, 0, W, H); } + mirrorFrame(c, g); + info.cover.push(RECT.tier, RECT.event, RECT.clock, RECT.speedo, RECT.map); if (g.manual) info.cover.push(RECT.tach); if (sc && sc.mirrorOn) info.cover.push(sc.mirrorRect); + // event panel: boss_hp and player_hp under their event-specific names + const [ex0, ey0, ex1] = RECT.event; panel(c, ex0, ey0, ex1 - ex0, 38); + c.font = `bold 12px ${FONT}`; c.fillStyle = '#f2ecdc'; c.textAlign = 'left'; c.fillText(hud.label || '', ex0 + 8, ey0 + 14); + c.font = `11px ${FONT}`; c.fillStyle = '#c6d0dc'; c.textAlign = 'right'; c.fillText(hud.detail || '', ex1 - 8, ey0 + 14); c.textAlign = 'left'; + bar(c, ex0 + 8, ey0 + 20, ex1 - ex0 - 16, 5, h[3] ? h[2] / h[3] : 0, '#ff8a3c'); + bar(c, ex0 + 8, ey0 + 28, ex1 - ex0 - 16, 5, h[1] ? h[0] / h[1] : 0, h[0] / (h[1] || 1) < 0.25 ? '#ff4a3a' : '#5bd18a'); + // clock and tier + const [cx0, cy0, cx1] = RECT.clock; panel(c, cx0, cy0, cx1 - cx0, 38); c.textAlign = 'right'; c.font = 'bold 16px Consolas,monospace'; c.fillStyle = '#f2ecdc'; c.fillText((g.t / M.hz).toFixed(1) + ' s', cx1 - 8, cy0 + 18); + c.font = 'bold 10px Consolas,monospace'; c.fillStyle = '#9fd0ff'; c.fillText(M.hz + 'Hz · tick ' + g.t, cx1 - 8, cy0 + 32); c.textAlign = 'left'; + const [tx0, ty0, tx1] = RECT.tier; panel(c, tx0, ty0, tx1 - tx0, 38); c.font = 'bold 11px Consolas,monospace'; c.fillStyle = '#ffd08a'; c.fillText((g.tier || '').toUpperCase() + ' d=' + g.d, tx0 + 8, ty0 + 16); c.fillStyle = '#b8c2cc'; c.font = '10px Consolas,monospace'; c.fillText(M.version, tx0 + 8, ty0 + 30); + // speedometer + const [sx0, sy0, sx1, sy1] = RECT.speedo; panel(c, sx0, sy0, sx1 - sx0, sy1 - sy0); c.textAlign = 'right'; c.font = 'bold 32px Consolas,monospace'; c.fillStyle = '#ffffff'; c.fillText(String(Math.round(kmh)), sx1 - 40, sy0 + 34); + c.font = '10px Consolas,monospace'; c.fillStyle = '#a8b4c0'; c.fillText('KM/H', sx1 - 8, sy0 + 34); + c.font = 'bold 18px Consolas,monospace'; c.fillStyle = car.over ? '#ff5a4a' : '#ffd08a'; c.textAlign = 'center'; c.fillText(String(car.gear + 1), sx0 + 14, sy0 + 26); c.textAlign = 'left'; + c.font = '9px Consolas,monospace'; c.fillStyle = '#9fc8ff'; c.fillText('NOS', sx0 + 6, sy0 + 52); bar(c, sx0 + 34, sy0 + 45, sx1 - sx0 - 42, 7, car.nos, car.nosOn ? '#bfe4ff' : '#4aa0ff'); + c.fillStyle = '#ffd08a'; c.fillText('SLOW', sx0 + 6, sy0 + 64); bar(c, sx0 + 34, sy0 + 57, sx1 - sx0 - 42, 7, g.sbMeter, g.sb ? '#ffffff' : '#ffb84a'); + if (g.manual) { c.fillStyle = '#ff9a7a'; c.fillText('HEAT', sx0 + 6, sy0 + 76); bar(c, sx0 + 34, sy0 + 70, sx1 - sx0 - 42, 6, car.heat, car.heat > 0.6 ? '#ff4a3a' : '#ffa14a'); } + if (g.manual) tach(g, c); + minimap(g, c); + if (M.MODES[g.key].hudExtra) M.MODES[g.key].hudExtra(g, c, { panel, bar, W, H }); + drawArrows(c, info); drawWarnings(c, g); + if (g.pre > 0) { + c.font = 'bold 54px Consolas,monospace'; c.textAlign = 'center'; c.fillStyle = '#ffe28a'; c.fillText(String(Math.ceil(g.pre)), W / 2, 210); + if (g.manual) { c.font = `bold 14px ${FONT}`; c.fillStyle = '#ffffff'; c.fillText('Manual gears: K upshift · L downshift · A / D change lanes', W / 2, 238); } + c.textAlign = 'left'; + } + if (g.outcome) { c.fillStyle = 'rgba(0,0,0,.42)'; c.fillRect(0, H / 2 - 44, W, 88); c.font = 'bold 36px "Microsoft YaHei",sans-serif'; c.textAlign = 'center'; c.fillStyle = g.outcome === 'win' ? '#7dff9a' : '#ff6a5a'; c.fillText(g.outcome === 'win' ? 'Challenge complete' : g.outcome === 'timeout' ? 'Time up' : (LABEL[g.lossReason] || 'Challenge Failed'), W / 2, H / 2 + 13); c.textAlign = 'left'; } + return sc; + }; + M.renderStatus = ctx => R.status(ctx); + M.renderMetrics = ctx => R.metrics(ctx); + M.closeRenderer = ctx => R.close(ctx); +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/nfsmw_remake/game.js b/environments/games/web/games/nfsmw_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..12729d0a847f5fc40c0639ed862c3cc00d348efc --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/game.js @@ -0,0 +1,167 @@ +/* Need for Speed: Most Wanted (2005) events, rules nfsmw-arena@2 - the module: cases, tiers, the tick, the health mapping. + A race has no health bars, so the public contract maps onto the event's own win and loss conditions: + boss_hp is what is left of the event (route metres from a high-water mark, so it never jumps back), and player_hp + is what the opponent still needs to beat you (clock, gap, score margin, bust meter). See + Independent reimplementation; facts read from the CC0 decompilation dbalatoni13/nfsmw@80993f3 are cited as file:line + in that repository. All art is procedural; no game data (VLT attributes, models, textures, audio, maps) is used. */ +(function (root) { + 'use strict'; + const N = root.NativeBench, M = root.NfsmwGame, C = M.C; + const HZ = 60, DT = 1 / HZ; + // Tiers are one fight at three paces: event length, opponent skill, traffic and police pressure all scale continuously. + // The original has no mode gate on these values (GRace.h: Easy/Medium/Hard is a per-event parameter), so hard stays 0.85. + const TIERS = { easy: 0.2, normal: 0.5, hard: 0.85 }; + // Piecewise linear through the three tier values, extrapolated beyond them, so any d in [0,1] is a valid fight. + const tierValue = (d, [e, n, h]) => d <= TIERS.normal ? n + (e - n) * (TIERS.normal - d) / (TIERS.normal - TIERS.easy) : n + (h - n) * (d - TIERS.normal) / (TIERS.hard - TIERS.normal); + const tierOf = d => d <= (TIERS.easy + TIERS.normal) / 2 ? 'easy' : d <= (TIERS.normal + TIERS.hard) / 2 ? 'normal' : 'hard'; + M.MODES = M.MODES || {}; + + const CASES = [ + { id: 'nfsmw/tollbooth', name: 'Tollbooth Race (Coastal Highway)' }, + { id: 'nfsmw/drag', name: 'Drag Series (Highway 99)' }, + { id: 'nfsmw/speedtrap', name: 'Speed Trap (Coastal Highway)' }, + { id: 'nfsmw/knockout', name: 'Lap Knockout (Downtown Night Race)' }, + { id: 'nfsmw/pursuit', name: 'Police Pursuit (Bounty + Escape)' }, + { id: 'nfsmw/street_champion', name: 'Street Champion Showdown (Multi-leg Race + Police)' }, + ]; + Object.assign(M, { + id: 'nfsmw_remake', version: 'nfsmw-arena@2', hz: HZ, maxSeconds: 300, dimension: '3d', renderer: 'webgl-nfsmw', + title: 'Need for Speed: Most Wanted · Street Challenges', cases: CASES, tiers: TIERS, tierValue, tierOf, DT, + controls: { + 'W': 'throttle', 'S': 'brake; reverse at low speed', 'A / D': 'Steer left / right (steering increases while held and decreases at higher speed)', 'Space': 'Handbrake (drift)', + 'Shift': 'nitrous', 'J': 'Toggle slow motion (time slows and downforce increases)', 'K / L': 'Manual upshift / downshift in drag races (A / D change lanes)', 'R': 'Reset onto the route (easier to bust during the 2-second flashing period)', + }, + }); + + // SB: world time scale is in the ITimeManager data (not in the repository), approximation 0.45; the handling side is + // SuspensionRacer.cpp:936 Tweak_GameBreakerExtraGs (-2 g of extra downforce) with a 1/3 s physics ramp-out (:937). + const SB_SCALE = 0.45, SB_GRIP = 2 * 9.81, SB_RAMP = 1 / 3, SB_SECONDS = 6; + const RESET_INVULN = 2; // ResetCar.cpp:26 Tweak_ResetInvulnerablitiyTime + + class Game { + constructor(id, seed, d) { + this.id = id; this.key = id.split('/')[1]; this.d = d; this.tier = tierOf(d); + this.t = 0; this.outcome = null; this.events = []; this.seed = seed; + // The multiply decorrelates neighbouring seeds; xorshift has a fixed point at zero. + this.rng = (Math.imul((seed >>> 0) + 1, 2654435761) >>> 0) || 1; + this.pre = 1.2; this.clock = 0; // staging countdown; event clock in world seconds + this.sb = 0; this.sbMeter = 1; this.sbRamp = 0; // Speedbreaker + this.flash = 0; this.resets = 0; this.hits = 0; this.nearMisses = 0; this.manual = 0; this.lastHit = 0; + this.slowT = 0; this.s = 0; this.s0 = 0; this.prog = 0; this.total = 1; this.lat = 0; this.offRoute = 0; + this.traffic = []; this.rivals = []; this.cops = []; this.props = []; this.gates = []; this.status = ''; + const mode = M.MODES[this.key]; if (!mode) throw Error('Unknown event ' + id); + this.routeKey = mode.route(d); + mode.init(this, d); + this.camH = this.car.h; this.heldBrake = 0; this.flashT = 0; this.heli = null; + } + get route() { return C.routes[this.routeKey]; } + placeCar(s, lat, speed = 0) { + const a = C.routeAt(this.route, s, lat), c = C.newCar(a.x, a.y, a.h); + c.vx = Math.cos(a.h) * speed; c.vy = Math.sin(a.h) * speed; + this.car = c; this.s = s; this.lat = lat; + } + update(keys, pressed) { + const mode = M.MODES[this.key], car = this.car; + this.heldBrake = keys.has('S') ? 1 : 0; + // Chase camera: lags the heading (state only the renderer reads; it cannot affect the simulation). + { let dh = car.h - this.camH; dh = Math.atan2(Math.sin(dh), Math.cos(dh)); this.camH += dh * Math.min(1, DT * 5.5); } + if (this.lastHit > 0) this.lastHit = Math.max(0, this.lastHit - DT); + if (this.flash > 0) this.flash = Math.max(0, this.flash - DT); + if (pressed.has('J') && (this.sb || this.sbMeter > 0.05)) { this.sb = this.sb ? 0 : 1; if (!this.sb) this.sbRamp = SB_RAMP; this.events.push({ type: this.sb ? 'slowmo_on' : 'slowmo_off' }); } + if (this.sb) { this.sbMeter = Math.max(0, this.sbMeter - DT / SB_SECONDS); if (this.sbMeter <= 0) { this.sb = 0; this.sbRamp = SB_RAMP; } } + else if (this.sbRamp > 0) this.sbRamp = Math.max(0, this.sbRamp - DT); + const wdt = DT * (this.sb ? SB_SCALE : 1); + if (this.pre > 0) { // staging: the world runs, the car is held at the line + this.pre = Math.max(0, this.pre - DT); + if (mode.staging) mode.staging(this, keys, pressed, DT); + M.stepTraffic(this, wdt); if (mode.idle) mode.idle(this, wdt); + return; + } + if (pressed.has('R')) this.resetCar(); + const speed = C.speed(car), fwd = car.vx * Math.cos(car.h) + car.vy * Math.sin(car.h); + const inp = { + thr: keys.has('W') ? 1 : 0, brk: keys.has('S'), steer: (keys.has('A') ? 1 : 0) - (keys.has('D') ? 1 : 0), hb: keys.has('Space'), nos: keys.has('Shift'), + up: this.manual && pressed.has('K'), down: this.manual && pressed.has('L'), manual: !!this.manual, reverse: keys.has('S') && fwd < 2 && speed < 6, + sbGrip: this.sb ? SB_GRIP : SB_GRIP * this.sbRamp / SB_RAMP, + }; + if (mode.input) mode.input(this, inp, keys, pressed); + C.carStep(car, inp, wdt, this.P || C.PLAYER); + if (car.hit > 3) { this.hits++; if (car.hit > 6) this.lastHit = 0.4; this.events.push({ type: 'wall', speed: car.hit }); } + if (!this.sb && speed > 35) this.sbMeter = Math.min(1, this.sbMeter + wdt * 0.02); + this.slowT = C.speed(car) < 2 ? this.slowT + DT : 0; + this.clock += wdt; + this.trackProgress(); + M.stepTraffic(this, wdt); + mode.tick(this, wdt); + } + // Progress is route distance from a high-water mark, inside a short window so a junction can't jump to another leg. + trackProgress() { + const R = this.route, c = this.car; + this.s = C.routeNear(R, c.x, c.y, this.s); + this.lat = C.routeLat(R, c.x, c.y, this.s); + this.offRoute = Math.abs(this.lat) > R.halfW + 3 ? 1 : 0; + if (!this.offRoute && this.s - this.s0 > this.prog) this.prog = Math.min(this.total, this.s - this.s0); + } + resetCar() { + const s = this.s0 + this.prog, a = C.routeAt(this.route, s, 0), keep = this.car; + Object.assign(keep, { x: a.x, y: a.y, h: a.h, vx: 0, vy: 0, r: 0, steer: 0, gear: 0, clutch: 0, tires: 0 }); // tyres: approximation, see SOURCES.md + this.s = s; this.lat = 0; this.slowT = 0; this.flash = RESET_INVULN; this.resets++; + this.events.push({ type: 'reset' }); + } + win() { if (!this.outcome) { this.outcome = 'win'; this.events.push({ type: 'win' }); } } + lose(why) { if (!this.outcome) { this.outcome = 'loss'; this.lossReason = why; this.events.push({ type: 'loss', why }); } } + health() { return M.MODES[this.key].health(this); } + } + Object.assign(M, { Game, DT, copyGame: g => Object.assign(Object.create(Game.prototype), N.copy(g)) }); + + // ---------------- traffic (AIActionTraffic: stays in lane at the speed limit, does not race, does not dodge) ---------------- + const carRadius = 1.6; + M.carRadius = carRadius; + M.spawnTraffic = (g, n, opt = {}) => { + g.trafficOpt = { ahead: opt.ahead || 420, spread: opt.spread || 620, opposing: opt.opposing === undefined ? 0.35 : opt.opposing, lanes: opt.lanes || null }; + for (let i = 0; i < n; i++) { + const t = { s: 0, lat: 0, dir: 1, v: 0, x: 0, y: 0, h: 0, crash: 0, vx: 0, vy: 0, nm: 0, paint: i % 6 }; + placeTraffic(g, t, g.s + 90 + (g.trafficOpt.spread + g.trafficOpt.ahead) * (i + N.rand(g)) / n); + g.traffic.push(t); + } + }; + const lanesOf = (R, dir) => dir > 0 ? [-R.halfW * 0.25, -R.halfW * 0.72] : [R.halfW * 0.25, R.halfW * 0.72]; + function placeTraffic(g, t, s) { + const R = g.route, o = g.trafficOpt; + t.dir = N.rand(g) < o.opposing ? -1 : 1; t.nm = 0; t.crash = 0; t.vx = 0; t.vy = 0; + const lanes = o.lanes || lanesOf(R, t.dir); t.lat = lanes[Math.floor(N.rand(g) * lanes.length) % lanes.length]; + t.v = t.dir * (17 + N.rand(g) * 9); t.s = s; + if (!R.loop) t.s = C.clamp(s, 40, R.L - 40); + const a = C.routeAt(R, t.s, t.lat); t.x = a.x; t.y = a.y; t.h = t.dir > 0 ? a.h : a.h + Math.PI; + } + M.stepTraffic = (g, wdt) => { + const R = g.route, c = g.car; + for (const t of g.traffic) { + if (t.crash) { // knocked out of lane: a free body that coasts to a stop + t.x += t.vx * wdt; t.y += t.vy * wdt; const f = Math.max(0, 1 - 1.6 * wdt); t.vx *= f; t.vy *= f; t.h += t.crash * wdt; t.crash *= f; + const q = C.road(t.x, t.y), over = q.d + 1.2; if (over > 0) { t.x -= q.nx * over; t.y -= q.ny * over; t.vx = 0; t.vy = 0; } + t.s = C.routeNear(R, t.x, t.y, t.s, 10, 10); t.lat = C.routeLat(R, t.x, t.y, t.s); + } else { + t.s += t.v * wdt; const a = C.routeAt(R, t.s, t.lat); t.x = a.x; t.y = a.y; t.h = t.dir > 0 ? a.h : a.h + Math.PI; + } + const rel = t.s - g.s; + if (rel < -140 || rel > g.trafficOpt.ahead + g.trafficOpt.spread + 60 || (!R.loop && (t.s < 30 || t.s > R.L - 30))) { placeTraffic(g, t, g.s + g.trafficOpt.ahead + N.rand(g) * g.trafficOpt.spread); continue; } + const dx = c.x - t.x, dy = c.y - t.y, dist2 = dx * dx + dy * dy; + if (dist2 < 30 && !t.nm && C.speed(c) > 25) { const d = Math.sqrt(dist2); if (d > carRadius * 2 + 0.4 && d < 4.6) { t.nm = 1; g.nearMisses++; g.sbMeter = Math.min(1, g.sbMeter + 0.04); } } + if (dist2 < (carRadius * 2) * (carRadius * 2)) M.bump(g, t, dx, dy, dist2, 0.8); + } + }; + // Player against a lighter body: momentum exchange along the contact normal. Returns the closing speed. + M.bump = (g, o, dx, dy, dist2, mass) => { + const c = g.car, d = Math.max(0.01, Math.sqrt(dist2)), nx = dx / d, ny = dy / d; + const moving = o.v !== undefined && !o.crash, ovx = moving ? Math.cos(o.h) * Math.abs(o.v) : o.vx, ovy = moving ? Math.sin(o.h) * Math.abs(o.v) : o.vy; + const rel = (c.vx - ovx) * nx + (c.vy - ovy) * ny, push = carRadius * 2 - d; + c.x += nx * push * 0.6; c.y += ny * push * 0.6; + if (rel >= 0) return 0; + const j = -(1.3) * rel * mass / (1 + mass); + c.vx += nx * j; c.vy += ny * j; c.r += ((nx * c.vy - ny * c.vx) > 0 ? 1 : -1) * Math.min(0.8, -rel * 0.02); + o.vx = ovx - nx * j / mass * 1.0; o.vy = ovy - ny * j / mass * 1.0; if (o.v !== undefined && !o.crash) o.crash = nx * Math.sin(o.h) - ny * Math.cos(o.h) > 0 ? 0.8 : -0.8; + if (-rel > 4) { g.hits++; g.lastHit = 0.4; g.events.push({ type: 'crash', speed: -rel }); } + return -rel; + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/nfsmw_remake/index.html b/environments/games/web/games/nfsmw_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..521187bc57cc47a4e32109e72d3d0d01aaf2cf6f --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/index.html @@ -0,0 +1,7 @@ + +Need for Speed: Most Wanted · Street Challenges(nfsmw-arena@2)
    +

    Need for Speed: Most Wanted · Street Challenges

    2005 original rules, independently recreated from CC0 decompilation · Native 60 Hz · Third-person WebGL · Original procedural city

    Back to Game Lobby
    +
    Select an event, then start the challenge

    Replays save inputs and the seed, then simulate the match again and verify the final state. Scripted Demo reads internal state for verification; it does not start RL training.

    +
    +
    + diff --git a/environments/games/web/games/nfsmw_remake/manifest.json b/environments/games/web/games/nfsmw_remake/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..9efed7b0533c3de38c643ebf3fbc091dea3a88c3 --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/manifest.json @@ -0,0 +1,55 @@ +{ + "schema": "bossbench/game-manifest@1", + "engine": "independent", + "game": "nfsmw_remake", + "module": "NfsmwGame", + "title": "Need for Speed Most Wanted: Street Challenges", + "dimension": "3d", + "native_hz": 60, + "max_seconds": 300, + "renderer": "webgl-nfsmw", + "rules": "nfsmw-arena@2", + "cases": [ + "nfsmw/tollbooth", + "nfsmw/drag", + "nfsmw/speedtrap", + "nfsmw/knockout", + "nfsmw/pursuit", + "nfsmw/street_champion" + ], + "scripts": [ + "_native/runtime.js", + "_boss3d/vendor/three.min.js", + "nfsmw_remake/nfscore.js", + "nfsmw_remake/game.js", + "nfsmw_remake/rivals.js", + "nfsmw_remake/modes_tollbooth.js", + "nfsmw_remake/modes_drag.js", + "nfsmw_remake/modes_speedtrap.js", + "nfsmw_remake/modes_knockout.js", + "nfsmw_remake/cops.js", + "nfsmw_remake/modes_pursuit.js", + "nfsmw_remake/scripted.js", + "nfsmw_remake/renderer3d.js", + "nfsmw_remake/draw.js" + ], + "sim_scripts": [ + "_native/runtime.js", + "nfsmw_remake/nfscore.js", + "nfsmw_remake/game.js", + "nfsmw_remake/rivals.js", + "nfsmw_remake/modes_tollbooth.js", + "nfsmw_remake/modes_drag.js", + "nfsmw_remake/modes_speedtrap.js", + "nfsmw_remake/modes_knockout.js", + "nfsmw_remake/cops.js", + "nfsmw_remake/modes_pursuit.js", + "nfsmw_remake/scripted.js" + ], + "play_page": "web/games/nfsmw_remake/index.html", + "scripted_controller": "NfsmwGame.scripted(game) -> {holds:[6 key arrays], mouse:[0,0,0]}; pure car-model look-ahead, others extrapolated at constant speed (NfsmwGame.oracle is an alias)", + "tests": [ + "nfsmw_remake/tests/mechanics.js" + ], + "source": "https://github.com/dbalatoni13/nfsmw/tree/80993f35224c61d2f1b135beba76c6f8234c7940 (CC0-1.0)" +} diff --git a/environments/games/web/games/nfsmw_remake/modes_drag.js b/environments/games/web/games/nfsmw_remake/modes_drag.js new file mode 100644 index 0000000000000000000000000000000000000000..560f4e8b7775bbe6f015ed4effd1be8ebbaa8511 --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/modes_drag.js @@ -0,0 +1,113 @@ +/* Drag (GRace.h kRaceType_Drag), run as a series the way a Blacklist rival is fought (Wikipedia: "win against the racer in a + successive series of races"). Rules that exist only here, all from the decompilation: + - manual gearbox with a perfect-shift bonus (EngineRacer EPerfectShift; the window width is VLT, approximation); + - over-rev heat, EngineRacer.cpp:1340-1345: +0.45/s on the limiter, -0.1/s otherwise, torque -25% from 0.6, blown at 1; + - the car steers itself and the driver changes lanes (AIVehicle.cpp IsDragSteering, ChangeDragLanes); + - total on hard contact, DamageDragster.cpp: above 100 mph, losing more than 40 mph in one impact destroys the car; + - launch: GetPerfectLaunchRange, EngineRacer.cpp:127-135 (a band a quarter of the rev range below the redline). + boss_hp = metres left in the whole series; player_hp = metres the rival still needs in this heat. */ +(function (root) { + 'use strict'; + const M = root.NfsmwGame, C = M.C, clamp = C.clamp; + const MPH = C.MPH, KILL_SPEED = 100 * MPH, KILL_DELTA = 40 * MPH, STAGE = 2.5; // AIActionRace.cpp:99 Tweak_UnstageTime + const LANES = [-7.5, -2.5, 2.5, 7.5], REV_UP = 1.5, REV_DOWN = 1.1, LAUNCH = [0.62, 0.86], START_S = 60, LANE_RATE = 7, LANE_GAIN = 2.2; + const startHeat = g => { + const lane = g.heat % 2 ? 2 : 1, rl = g.heat % 2 ? 1 : 2; + g.placeCar(START_S, LANES[lane]); g.s0 = START_S; g.lane = lane; g.pre = STAGE; g.rev = 0; g.prevV = 0; g.heatProg = 0; + g.gates = [{ s: START_S + g.heatLen, at: g.heatLen, done: 0 }]; + g.rivals = [M.newRival(g, { s: START_S, lat: LANES[rl], skill: clamp(g.rivalSkill + M.formOf(g), 0, 1), drag: true, paint: 1 })]; + g.traffic = []; M.spawnTraffic(g, g.trafficN, { opposing: 0, lanes: LANES, spread: Math.max(0, g.heatLen - 240), ahead: 140 }); + // highwater across heats: every heat restarts the car at the line, and prog is measured from heatBase + g.prog = 0; g.total = g.heatLen; + }; + M.MODES.drag = { + route: () => 'strip', + init(g, d) { + g.P = Object.assign({}, C.PLAYER, { overheat: true }); + g.manual = 1; g.noGlue = 1; + g.heats = Math.round(M.tierValue(d, [1, 2, 6])); g.heatLen = M.tierValue(d, [1000, 1500, 1500]); g.seriesLen = g.heats * g.heatLen; + g.rivalSkill = M.tierValue(d, [0.2, 0.5, 0.8]); g.trafficN = Math.round(M.tierValue(d, [3, 6, 10])); + g.heat = 0; g.launch = 0; + startHeat(g); + }, + staging(g, keys, pressed, dt) { + g.rev = clamp(g.rev + (keys.has('W') ? REV_UP : -REV_DOWN) * dt, 0, 1); + if (g.pre <= 0) { const inBand = g.rev >= LAUNCH[0] && g.rev <= LAUNCH[1]; g.launch = inBand ? 1 : 0; if (inBand) { g.car.bonus = 1.2; g.events.push({ type: 'perfect_launch' }); } else if (g.rev > LAUNCH[1]) g.car.clutch = 0.45; } + g.prevV = 0; + }, + idle(g) { for (const r of g.rivals) { const a = C.routeAt(g.route, r.s, r.lat); r.x = a.x; r.y = a.y; r.h = a.h; } }, + input(g, inp, keys, pressed) { + if (pressed.has('A') && g.lane < LANES.length - 1) g.lane++; + if (pressed.has('D') && g.lane > 0) g.lane--; + // Lane keeper: the driver has no wheel here (IsDragSteering), a fixed servo turns the lane error into steering. + const R = g.route, c = g.car, a = C.routeAt(R, g.s), lat = C.routeLat(R, c.x, c.y, g.s), v = Math.max(C.speed(c), 6); + let dh = c.h - a.h; dh = Math.atan2(Math.sin(dh), Math.cos(dh)); + // Lateral error -> a heading limited to LANE_RATE across the road -> the yaw rate that reaches it -> the wheel for that rate. + const lim = LANE_RATE / v, want = clamp((LANES[g.lane] - lat) * LANE_GAIN / v, -lim, lim), full = v * Math.tan(C.steerRange(v / C.MPH) * Math.PI / 180) / C.PLAYER.wheelbase; + inp.steer = clamp((want - dh) * 3 / full, -1, 1); inp.hb = false; + }, + tick(g, wdt) { + const c = g.car, v = C.speed(c); + if (g.prevV > KILL_SPEED && g.prevV - v > KILL_DELTA) return g.lose('totaled'); + g.prevV = v; + if (c.blown) return g.lose('blown'); + for (const r of g.rivals) M.stepRival(g, r, wdt); + const rv = g.rivals[0]; + if (g.prog >= g.heatLen) { + g.events.push({ type: 'heat_won', heat: g.heat, gap: g.heatLen - rv.prog }); + g.heat++; + if (g.heat >= g.heats) return g.win(); + startHeat(g); + return; + } + if (rv.prog >= g.heatLen) g.lose('gap'); + }, + health(g) { + const rv = g.rivals[0], left = Math.max(0, g.heatLen - rv.prog), done = g.outcome === 'win' ? g.seriesLen : g.heat * g.heatLen + g.prog; + return [g.outcome === 'loss' ? 0 : left, g.heatLen, Math.max(0, g.seriesLen - done), g.seriesLen]; + }, + hud(g) { const rv = g.rivals[0]; return { label: 'Drag Race', detail: `Heat ${Math.min(g.heat + 1, g.heats)} / ${g.heats} · Rival needs ${Math.max(0, g.heatLen - rv.prog).toFixed(0)} m · ${g.pre > 0 ? 'RPM ' + Math.round(g.rev * 100) + '%' : 'Gear ' + (g.car.gear + 1)}` }; }, + // Reference: launch inside the band, shift inside the window, change lanes for traffic, nitrous when nothing is close. + scripted(g) { + const holds = [[], [], [], [], [], []], c = g.car; + if (g.pre > 0) { // feather the throttle so the revs sit in the launch band when the lights go + let rev = g.rev, left = g.pre; + for (let i = 0; i < 6; i++) { const on = rev < (LAUNCH[0] + LAUNCH[1]) / 2 - 0.02 && left < 1.2; if (on) holds[i].push('W'); rev = clamp(rev + (on ? REV_UP : -REV_DOWN) * (2 / 60), 0, 1); left -= 2 / 60; } + return { holds, mouse: [0, 0, 0] }; + } + const P = g.P, k = M.ctl.copyCar(c), fwd0 = Math.max(0, c.vx * Math.cos(c.h) + c.vy * Math.sin(c.h)); let press = -1; + // After a hit the box is still in a tall gear with almost no drive: one gear down per packet until the revs are useful. + const lug = c.gear > 0 && c.clutch <= 0 && fwd0 < C.TOPS[c.gear - 1] * 0.8; + for (let i = 0; i < 6; i++) { + const u = Math.max(0, k.vx * Math.cos(k.h) + k.vy * Math.sin(k.h)) / C.TOPS[k.gear]; + if (press < 0 && k.gear < 5 && u >= 0.9) press = i; + C.carStep(k, { thr: 1, brk: false, steer: 0, hb: false, nos: false, manual: true, up: false, down: false, sbGrip: 0 }, 1 / 30, P); + } + // Lane plan: for each lane and a short wait before moving, the time until first contact with anything on the road. + const users = M.ctl.roadUsers(g, g.route), v = C.speed(c), lane = g.lane, HORIZON_S = 6, STAY_S = 3.4; + const contact = (target, wait) => { + // The same first-order lane servo the car runs (rate capped, gain LANE_GAIN), started 0.2 s late for the wheel to slew. + let lat = g.lat; + for (let t = 0.1; t < HORIZON_S; t += 0.1) { + if (t > wait + 0.2) lat += clamp((LANES[target] - lat) * LANE_GAIN, -LANE_RATE, LANE_RATE) * 0.1; + const sp = g.s + v * t; + for (const o of users) { const ds = o.s + o.vs * t - sp, ds0 = o.s + o.vs * (t - 0.1) - (g.s + v * (t - 0.1)); if (o.s > g.s + 1 && Math.abs(o.lat - lat) < 3.6 && ((ds > 1 && ds < 6.5) || (ds0 > 1 && ds <= 1))) return t; } + } + return HORIZON_S; + }; + const here = contact(lane, 0); + let bestT = here, go = lane; + // Stay put until contact is near: a move costs nothing only if nothing else is decided on the way. Then take the lane + // that stays clear longest, nearer lanes first on a tie. A wrong late move is cheaper than weaving through everything. + if (here < STAY_S) { let bs = here; for (let l = 0; l < LANES.length; l++) { if (l === lane) continue; const t = contact(l, 0), v2 = t - 0.25 * Math.abs(l - lane); if (t > here + 0.5 && v2 > bs) { bs = v2; bestT = t; go = l; } } } + const move = Math.sign(go - lane); + // A blocked lane with nowhere to go: braking costs seconds on this gearing, a total above 100 mph costs the event. + const blocked = bestT < 0.8 && !move, coast = bestT < 1.2 && !move; + // Top gear on the limiter only cooks the engine (EngineRacer.cpp:1340): lift until the speed is back under it. + const onLimiter = c.gear === 5 && Math.max(0, c.vx * Math.cos(c.h) + c.vy * Math.sin(c.h)) >= C.TOPS[5] * 0.995; + const nos = c.nos > 0.02 && v > 30 && here > 3 && c.clutch <= 0 && !c.over && v < C.TOPS[5] * 0.97; + for (let i = 0; i < 6; i++) { if (blocked) holds[i].push('S'); else if (!onLimiter && !coast) holds[i].push('W'); if (nos && !blocked) holds[i].push('Shift'); if (i === press && !lug) holds[i].push('K'); if (i === 0 && lug) holds[i].push('L'); if (i === 0 && move) holds[i].push(move > 0 ? 'A' : 'D'); } + return { holds, mouse: [0, 0, 0] }; + }, + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/nfsmw_remake/modes_knockout.js b/environments/games/web/games/nfsmw_remake/modes_knockout.js new file mode 100644 index 0000000000000000000000000000000000000000..9df70caef60df4591c69ff873679bef1d6cbec5c --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/modes_knockout.js @@ -0,0 +1,57 @@ +/* Lap Knockout (GRace.h kRaceType_Knockout; GRaceStatus.h GRacerInfo::KnockOut, mKnockedOut). A short downtown circuit at night: + when every car but one has finished the lap, that last car is out. One lap per rival, so the field sets the length. + boss_hp = route metres left in the whole event; player_hp = metres the slowest remaining rival still needs to finish this + lap (at 0 every rival is home and the player is the one knocked out). The field and the circuit are original: race data is VLT. */ +(function (root) { + 'use strict'; + const M = root.NfsmwGame, C = M.C, S0 = 40, ROW = 9; + M.MODES.knockout = { + route: () => 'downtown', + init(g, d) { + const R = g.route, field = Math.round(M.tierValue(d, [1, 2, 5])); + // The grid is short of the line, so lap 1 is partial and its length is part of the event's pace. + const first = Math.min(R.L, M.tierValue(d, [420, 520, 694])), start = R.L - first + S0; + g.L = R.L; g.first = first; g.laps = field; g.total = first + (field - 1) * R.L; g.lap = 0; g.s0 = start; g.placeCar(start, -2.2); + const lo = M.tierValue(d, [0.12, 0.2, 0.3]), hi = M.tierValue(d, [0.12, 0.34, 0.62]); + g.rivals = []; + // Two columns, a full row apart: the player is alone on the last row. Skill runs from the back of the grid to the front, as a Blacklist field does. + for (let i = 0; i < field; i++) { + const r = M.newRival(g, { s: start + ROW * (Math.floor(i / 2) + 1), lat: i % 2 ? -2.2 : 2.2, skill: C.clamp((field > 1 ? C.lerp(lo, hi, i / (field - 1)) : lo) + M.formOf(g), 0, 1), paint: i % 4 }); + r.s0 = start; r.prog = r.s - start; g.rivals.push(r); + } + g.gates = [{ s: R.L + S0, at: 0, kind: 'line', keep: 1, done: 0 }]; + M.spawnTraffic(g, Math.round(M.tierValue(d, [0, 2, 3])), { ahead: 120, spread: 260, opposing: 0 }); + }, + idle() {}, + tick(g, wdt) { + const alive = g.rivals.filter(r => !r.out); + for (const r of alive) M.stepRival(g, r, wdt); + // Rivals ride rails, so they part sideways here rather than drive through each other. + for (let i = 0; i < alive.length; i++) for (let j = i + 1; j < alive.length; j++) { + const a = alive[i], b = alive[j], ds = a.s - b.s, dl = a.lat - b.lat; + if (Math.abs(ds) < 6 && Math.abs(dl) < 3.2) { const push = (dl >= 0 ? 1 : -1) * 2.4 * wdt, e = g.route.halfW - 2.1; a.lat = C.clamp(a.lat + push, -e, e); b.lat = C.clamp(b.lat - push, -e, e); if (Math.abs(ds) < 4.4 && a.v !== b.v) { const back = ds < 0 ? a : b; back.v = Math.max(0, back.v - 6 * wdt); } } + } + const end = g.first + g.lap * g.L, pending = alive.filter(r => r.prog < end), youIn = g.prog >= end; + if (!youIn && pending.length === 0) return g.lose('knocked'); + // <= 1, not === 1: two rivals crossing on the same tick take pending from 2 to 0, and the last car still goes out. + if (youIn && pending.length <= 1) { + const out = pending[0] || alive.reduce((a, b) => b.prog < a.prog ? b : a); out.out = 1; out.gone = 1; g.events.push({ type: 'knockout', lap: g.lap }); g.lap++; + if (g.rivals.every(r => r.out)) { g.prog = g.total; g.win(); } + } + }, + health(g) { + const end = g.first + g.lap * g.L; let worst = 0; + for (const r of g.rivals) if (!r.out) worst = Math.max(worst, end - r.prog); + // A win knocks out the last rival, so no rival is left to measure: player_hp stays full rather than reading as a loss. + return [g.outcome === 'loss' ? 0 : g.outcome === 'win' ? g.L : C.clamp(worst, 0, g.L), g.L, g.outcome === 'win' ? 0 : Math.max(0, g.total - g.prog), g.total]; + }, + hud(g) { const alive = g.rivals.filter(r => !r.out); const place = 1 + alive.filter(r => r.prog > g.prog).length; return { label: 'Lap Knockout', detail: `Lap ${Math.min(g.lap + 1, g.laps)} / ${g.laps} · Place ${place} / ${alive.length + 1} · Last-place rival needs ${M.MODES.knockout.health(g)[0].toFixed(0)} m` }; }, // draw.js calls hud unbound: no `this` + // Reference: a tighter line, and slow motion (J, the public Speedbreaker key: +2 g of downforce) only while it would brake, + // for a corner or for a car ahead. Seeds 1-32: normal 22 -> 32, hard 24 -> 32. + scripted(g) { + const opt = { margin: 0.96 }, pk = M.ctl.drive(g, opt); + if (g.pre <= 0) { const why = M.ctl.planDrive(g, opt).why, want = why === 'speed' || why === 'contact'; if (want !== !!g.sb && (g.sb || g.sbMeter > 0.15) && pk.holds[0].length < 4) pk.holds[0].push('J'); } + return pk; + }, + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/nfsmw_remake/modes_pursuit.js b/environments/games/web/games/nfsmw_remake/modes_pursuit.js new file mode 100644 index 0000000000000000000000000000000000000000..a08fa3edb87bbff291e51d8d8269fb695deae952 --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/modes_pursuit.js @@ -0,0 +1,437 @@ +/* Free-roam pursuit (AI/Common/AIPursuit.cpp, rules listed in cops.js). The event is the Blacklist's own gate: raise a bounty, then get away. + Bounty accrues only while a cop can see the player (:1920 AddToPendingRepPointsNormal runs inside the in-sight branch) and in lumps for + destroying cops, with the multiplier up to 3 (:917). Then the evade meter must fill. Clearing a stage raises the heat: after the lock-out + (:2061 LockoutCops) a new pursuit starts at the next level. The heat values are VLT data, so every number below is an approximation. + Pursuit Breakers: EPursuitBreaker exists in the decompilation, the placement and radius are map data; here two per lap, original. + boss_hp = stages x 200 minus bounty and evade progress, both from high-water marks, so it never jumps back; player_hp = the bust meter. */ +(function (root) { + 'use strict'; + const M = root.NfsmwGame, C = M.C, N = root.NativeBench, clamp = C.clamp; + const BOUNTY_UNITS = 100, EVADE_UNITS = 100, S0 = 5560, BREAKER_R = 46; + const heat = (g, d) => { + const lvl = g.stage / Math.max(1, g.stages - 1); // inside the event the heat climbs a little, tier sets the base + return { copsMax: Math.round(M.tierValue(d, [2, 3, 5])) + (g.stage > 1 ? 1 : 0), top: M.tierValue(d, [52, 66, 70]) + lvl * 4 }; + }; + const startStage = (g, d) => { + const p = g.pol, h = heat(g, d); + p.copsMax = h.copsMax; p.top = h.top; p.seen = 0; p.sinceSeen = 0; p.evade = 0; p.lockT = g.stage ? 3 : 0; p.spawnT = g.stage ? 3.5 : p.spawnGap; + g.stageBounty = 0; g.stageEvadeHW = 0; + if (!g.stage) { const c = M.spawnCop(g, g.s - 85, 2, 1); c.slot = 0; c.v = 34; } + else g.events.push({ type: 'heat_up', stage: g.stage }); + }; + // ---------------- Reference controllers for these two events (2026-11-11 recalibration). Only these two events call them; the shared + // planDrive / drive in scripted.js are untouched. Read decided state only (poses, timers, the episode seed), never the live RNG: the + // champion's look-ahead rolls copies forward in a fixed independent scenario. Both keep a little memory per game object (WeakMap); a + // repeated call on the same state returns the same packet (tests/leak_probe.js asks five times per packet). + + // Pursuit. The strategy follows whether this heat level brings a helicopter (g.pol.heli, fixed when the pursuit starts; the HUD shows + // helicopter once one is up). In the block's tight corners the cops lose sight within seconds, so without a helicopter (250 m sight) the bounty + // stops growing there: d = 0.65-0.7 timed out 8/8 when the switch was the stage count instead. + // - no helicopter: the 11-06 controller. While bounty is owed, hold station just ahead of the chase so it keeps sight; once the 7 s in-sight + // grace (cops.js inSight, AIPursuit.cpp:2000) covers what is owed with 5 s to spare, or the bounty is full, run on the racing line with + // nitrous, through any Pursuit Breaker with a cop near. Same rule at every tier (the 11-06 version started early on easy only). + // - helicopter: the downtown block, ported from the 600-hour dataset pipeline's tools/trajectory_dataset/pursuit_recovery_source_v87.js + // (read-only there; its route table, path smoothing and follower, config speed 42, owed 34, lane spread 3). Into the block by one of + // five connector streets, laps of its tight corners until the stage clears, back out to the coast between stages. + // Added to both: blown tyres are reset once no chasing cop is within 95 m (11-06 rule); on the block, a cop within 6 m with the car under + // BustSpeed + 2 means it is pinned, so it floors it instead of braking for the corner. + const pursuitPolicy = (() => { + const HIDE = true, HIDE_GAP = 175, HIDE_SEE = 520, SPEED = 42, OWED = 34, REENTER_OWED = 8, LANE_SPREAD = 3, EARLY_MARGIN = 5, RESET_NEAR = 95, UNPIN_R = 6, FAR_COP = 110, MID_COP = 70, TOP_FAR = 20, TOP_MID = 30; + const memory = new WeakMap(); + function choice(g) { let n = g.seed ^ Math.imul(g.stage + 1, 0x9e3779b1); n = Math.imul(n ^ (n >>> 16), 0x21f0aaad); n = Math.imul(n ^ (n >>> 15), 0x735a2d97); return ((n ^ (n >>> 15)) >>> 0) / 4294967296; } + const lane = g => (choice(g) - 0.5) * 2 * LANE_SPREAD; + // Connector streets from the coast road into the downtown block (nfscore.js STREETS), outer end first. + const routes = [[[0, -520], [0, -80]], [[420, -520], [420, 3], [46, 3]], [[-400, -520], [-400, 0], [-85, 0]], [[0, 400], [0, 80]], [[-400, 560], [-400, 0], [-85, 0]]]; + const nearestCop = g => { let near = Infinity; for (const k of g.cops) if (!k.dead && k.state !== 'rb') near = Math.min(near, Math.hypot(g.car.x - k.x, g.car.y - k.y)); return near; }; + function sixSteer(c, target, sp, scale) { + const rate = (sp < 15 ? 7 : sp < 40 ? 5 : 3.6) * scale / 30, keys = []; let st = c.steer; + for (let i = 0; i < 6; i++) { let k0 = 0, error = Infinity; for (const k of [0, 1, -1]) { const n = st + clamp(k - st, -rate, rate), e = Math.abs(n - target); if (e < error) { error = e; k0 = k; } } keys.push(k0); st += clamp(k0 - st, -rate, rate); } + return keys; + } + // Drop collinear points, then round each corner with the largest arc (16, 12, 8 m) that stays on the road. + function smooth(points) { + const sparse = [points[0]]; + for (let i = 1; i < points.length - 1; i++) { + const a = sparse[sparse.length - 1], b = points[i], c = points[i + 1], ux = b[0] - a[0], uy = b[1] - a[1], vx = c[0] - b[0], vy = c[1] - b[1], L = Math.hypot(ux, uy) * Math.hypot(vx, vy); + if (L < 0.01) continue; + if (Math.abs(ux * vy - uy * vx) / L < 0.01 && (ux * vx + uy * vy) / L > 0.999) continue; + sparse.push(b); + } + sparse.push(points[points.length - 1]); points = sparse; + const out = [points[0]]; + for (let i = 1; i < points.length - 1; i++) { + const a = points[i - 1], b = points[i], c = points[i + 1], la = Math.hypot(b[0] - a[0], b[1] - a[1]), lc = Math.hypot(c[0] - b[0], c[1] - b[1]); + if (la < 30 || lc < 30) { out.push(b); continue; } + const ux = (a[0] - b[0]) / la, uy = (a[1] - b[1]) / la, vx = (c[0] - b[0]) / lc, vy = (c[1] - b[1]) / lc; + const theta = Math.acos(clamp(ux * vx + uy * vy, -1, 1)); if (theta < 0.3 || theta > 2.9) { out.push(b); continue; } + let arc = null; + for (const radius of [16, 12, 8]) { + const tangent = radius / Math.tan(theta / 2); if (tangent > Math.min(la, lc) * 0.4) continue; + const hl = Math.hypot(ux + vx, uy + vy), distance = radius / Math.sin(theta / 2), cx = b[0] + (ux + vx) / hl * distance, cy = b[1] + (uy + vy) / hl * distance; + const ax = b[0] + ux * tangent, ay = b[1] + uy * tangent, angle = Math.atan2(ay - cy, ax - cx), sign = -Math.sign(ux * vy - uy * vx), sweep = Math.PI - theta; + const n = Math.ceil(radius * sweep / 2), candidate = []; + for (let j = 0; j <= n; j++) { const t = angle + sign * sweep * j / n; candidate.push([cx + Math.cos(t) * radius, cy + Math.sin(t) * radius]); } + if (candidate.every(p => C.road(p[0], p[1]).d < -1.8)) { arc = candidate; break; } + } + out.push(...(arc || [b])); + } + out.push(points[points.length - 1]); return out; + } + // Pure pursuit along mem.points, speed limited by the path's curvature and the tyres; null at the end of the path. + function follow(g, mem) { + if (mem.rawPoints !== mem.points) { mem.points = smooth(mem.points); mem.rawPoints = mem.points; } + const c = g.car, sp = C.speed(c), points = mem.points; let i = mem.i; + while (i < points.length - 1) { const a = points[i], b = points[i + 1], dx = b[0] - a[0], dy = b[1] - a[1], l2 = dx * dx + dy * dy; const t = ((c.x - a[0]) * dx + (c.y - a[1]) * dy) / l2; if (t > 1 || Math.hypot(c.x - b[0], c.y - b[1]) < 3.5) { i++; continue; } break; } + mem.i = i; + if (i >= points.length - 1) return null; + const a = points[i], b = points[i + 1], dx = b[0] - a[0], dy = b[1] - a[1], length = Math.hypot(dx, dy); + const t = clamp(((c.x - a[0]) * dx + (c.y - a[1]) * dy) / (length * length), 0, 1), remaining = length * (1 - t); + let look = Math.max(5, sp * 0.45), x = a[0] + dx * t, y = a[1] + dy * t, j = i; + while (look > 0 && j < points.length - 1) { const dest = points[j + 1], d = Math.hypot(dest[0] - x, dest[1] - y); if (d >= look) { x += (dest[0] - x) * look / d; y += (dest[1] - y) * look / d; break; } look -= d; x = dest[0]; y = dest[1]; j++; } + const lag = 0.1 * (g.sb ? 0.45 : 1); let angle = Math.atan2(y - c.y - c.vy * lag, x - c.x - c.vx * lag) - c.h - c.r * lag; angle = Math.atan2(Math.sin(angle), Math.cos(angle)); + const L = Math.max(3, Math.hypot(x - c.x, y - c.y)), kappa = 2 * Math.sin(angle) / L; + const nose = C.road(c.x + Math.cos(c.h) * 3.2, c.y + Math.sin(c.h) * 3.2).d > -0.5; + if (sp < 7 && (Math.abs(angle) > 0.9 || nose)) { + const clear = C.road(c.x - Math.cos(c.h) * 3.5, c.y - Math.sin(c.h) * 3.5).d < -0.6, side = angle > 0 ? 1 : -1; + const pk = M.ctl.toPacket({ keys: sixSteer(c, clear ? -side : side, sp, g.sb ? 0.45 : 1), thr: clear ? 0 : 6, brk: clear, nos: false }); + if (g.sb) pk.holds[0].push('J'); return pk; + } + const target = clamp(Math.atan(kappa * C.PLAYER.wheelbase) / (C.steerRange(sp / C.MPH) * Math.PI / 180), -1, 1); + const end = !mem.continuous && i + 1 === points.length - 1; + let future = SPEED, ds = -length * t, upcoming = 0; + const grip = (C.PLAYER.grip + (g.sb ? 19.62 : 0)) * C.tireFactor(c) * 0.78; + for (let k = i; k < points.length - 2 && ds < 150; k++) { + const a = points[k], b = points[k + 1], c0 = points[k + 2], d1 = Math.hypot(b[0] - a[0], b[1] - a[1]), d2 = Math.hypot(c0[0] - b[0], c0[1] - b[1]), d3 = Math.hypot(c0[0] - a[0], c0[1] - a[1]); + ds += d1; const curv = Math.abs(2 * ((b[0] - a[0]) * (c0[1] - b[1]) - (b[1] - a[1]) * (c0[0] - b[0])) / Math.max(0.001, d1 * d2 * d3)); + if (ds < sp * 1.5 + 10) upcoming = Math.max(upcoming, curv); + if (curv > 0.0001) future = Math.min(future, Math.sqrt(grip / curv + 2 * 8 * Math.max(0, ds - 6))); + } + const limit = Math.min(future, Math.sqrt(grip / (Math.abs(kappa) + 0.0001)), end ? Math.sqrt(2 * 8 * Math.max(0, remaining - 3)) : SPEED); + const brk = sp > limit + 0.8, keys = sixSteer(c, brk ? target / 1.45 : target, sp, g.sb ? 0.45 : 1); + const spare = Math.max(0, 1 - sp * sp * Math.abs(kappa) / grip); + const thr = Math.max(1, Math.min(6, Math.round(6 * spare / 0.55))); + let pinned = false; for (const k of g.cops) if (!k.dead && k.state !== 'rb' && Math.hypot(c.x - k.x, c.y - k.y) < UNPIN_R) pinned = true; + pinned = pinned && sp < g.pol.bustSpeed + 2; + const pk = pinned ? M.ctl.toPacket({ keys: sixSteer(c, target, sp, g.sb ? 0.45 : 1), thr: 6, brk: false, nos: c.nos > 0.02 }) : M.ctl.toPacket({ keys, thr: brk ? 0 : thr, brk, nos: false }); + const want = (upcoming > 0.035 || Math.abs(angle) > 0.3) && sp > 10; + if (want !== !!g.sb && (g.sb || g.sbMeter > 0.2) && pk.holds[0].length < 4) pk.holds[0].push('J'); + return pk; + } + const nearestS = (R, x, y) => { let best = 0, dist = Infinity; for (let i = 0; i < R.n; i++) { const d = Math.hypot(R.x[i] - x, R.y[i] - y); if (d < dist) { dist = d; best = i * R.ds; } } return best; }; + // One lap of the downtown block starting at the point nearest (x, y). routeAt returns one shared object: copy before the next call. + function lapFrom(x, y) { const R = C.routes.downtown, best = nearestS(R, x, y), pts = []; for (let s = 4; s < R.L + 4; s += 4) { const p = C.routeAt(R, best + s); pts.push([p.x, p.y]); } const last = C.routeAt(R, best); pts.push([last.x, last.y]); return pts; } + function startReturn(g, mem, escape, entryS) { + const join = { ...C.routeAt(g.route, entryS + 35) }; + mem.points = [[g.car.x, g.car.y], ...escape.slice(0, -1).reverse(), [join.x, join.y]]; mem.i = 0; mem.mode = 'return'; mem.continuous = false; mem.returnPending = false; + mem.escape = escape; mem.entryS = entryS; + } + // One heat stage: the 11-06 coast run. + function coastRun(g, owed, p) { + const R = g.route, nearest = nearestCop(g), opt = { ram: true }, covered = 7 - p.sinceSeen - EARLY_MARGIN > owed; + // Hide: bounty full, nobody sees the car, and a roadblock is already set up ahead (g.blocks, decided state). Driving past it re-sights the + // car (50 m all round, AIVehicleCopCar.cpp:88-89) and restarts the 7 s + evade clock; instead stop HIDE_GAP m short of it, outside its + // 150 m view, and let the evade meter run. A car under 15 m/s draws no new roadblock (cops.js stepRoadblocks). + if (HIDE && owed <= 0 && !p.sawNow) { let ahead = Infinity; for (const b of g.blocks) { const ds = M.wrapTo(R, b.s, g.s) - g.s; if (ds > 0 && ds < ahead) ahead = ds; } + if (ahead < HIDE_SEE) { const room = ahead - HIDE_GAP, sp = C.speed(g.car); if (room < 3) return M.ctl.toPacket({ thr: 0, brk: sp > 2, nos: false }); return M.ctl.drive(g, { ram: true, nos: false, top: Math.max(4, Math.sqrt(2 * 8 * Math.max(0, room - 3))) }); } } + if (owed > 0 && !covered) { opt.nos = false; if (nearest > FAR_COP || !p.sawNow) opt.top = TOP_FAR; else if (nearest > MID_COP) opt.top = TOP_MID; } + if (owed <= 0 || covered) for (const b of g.breakers) { const ds = M.wrapTo(R, b.s, g.s) - g.s; if (ds > 0 && ds < 130 && !b.rearm && nearest < 90) opt.lat = b.lat; } + return M.ctl.drive(g, opt); + } + return function policy(g) { + let mem = memory.get(g); if (!mem) { mem = { stage: g.stage, mode: 'coast' }; memory.set(g, mem); } + if (g.car.tires > 0 && g.flash <= 0 && nearestCop(g) > RESET_NEAR) { mem.mode = 'coast'; mem.reenter = mem.reenter || g.bountyNeed - g.stageBounty > 0; return { holds: [['R'], [], [], [], [], []], mouse: [0, 0, 0] }; } + const owed = g.bountyNeed - g.stageBounty, p = g.pol; + if (!g.pol.heli) return coastRun(g, owed, p); + if (g.stage !== mem.stage) { + mem.stage = g.stage; + if (mem.mode === 'city') mem.returnPending = false; + else if (mem.mode !== 'coast') startReturn(g, mem, mem.escape, mem.entryS); + } + if (mem.mode === 'city') { + const pk = follow(g, mem); if (pk) return pk; + if (mem.returnPending) { startReturn(g, mem, mem.escape, mem.entryS); return follow(g, mem); } + mem.points = [[g.car.x, g.car.y], ...mem.cityPoints]; mem.i = 0; return follow(g, mem); + } + if (mem.mode === 'return' || mem.mode === 'inside') { + if (mem.mode === 'inside' && mem.i >= mem.points.length - 2) mem.continuous = true; + const pk = follow(g, mem); if (pk) return pk; + mem.continuous = false; mem.mode = 'coast'; + } + if (mem.mode === 'coast' && owed <= (mem.reenter ? REENTER_OWED : OWED)) { + mem.reenter = false; + const R = g.route, choices = routes.map(points => { const best = nearestS(R, points[0][0], points[0][1]); let ds = (best - g.s) % R.L; if (ds < 30) ds += R.L; return { points, s: g.s + ds, ds }; }); + const ranked = choices.sort((a, b) => a.ds - b.ds), options = ranked.filter(r => r.ds < ranked[0].ds + 1100).slice(0, 3); + const target = options[Math.min(options.length - 1, Math.floor(choice(g) * options.length))]; + mem.escape = target.points.map(q => q.slice()); mem.entryS = target.s; mem.mode = 'approach'; + } + if (mem.mode === 'approach') { + const distance = mem.entryS - g.s; + if (distance < 100) { + const approach = { ...C.routeAt(g.route, mem.entryS - 150) }, end = mem.escape[mem.escape.length - 1]; + mem.cityPoints = lapFrom(end[0], end[1]); + mem.points = [[approach.x, approach.y], ...mem.escape, ...mem.cityPoints]; mem.i = 0; mem.mode = 'city'; mem.continuous = true; + return follow(g, mem); + } + return M.ctl.drive(g, { ram: true, lat: lane(g), margin: 0.9, top: Math.min(70, Math.sqrt(12 * 12 + 2 * 8 * Math.max(0, distance - 12))) }); + } + return M.ctl.drive(g, { ram: true, lat: lane(g), margin: 0.9 }); + }; + })(); + + // Street champion. Ported from the dataset pipeline's tools/trajectory_dataset/street_interaction_source_v42.js (read-only there). v42 + // replaced the page's M.ctl with a modified copy of scripted.js; here that copy is private to this event. Kept from v42: lane choice with + // hysteresis, Speedbreaker grip in the racing line and friction circle, and each packet picks one of nine driving choices by rolling copies + // of the game 120 ticks forward with the RNG set to one fixed scenario (never the live RNG). Added: blown tyres are reset once no chasing + // cop is within 95 m (the 11-06 rule v42 dropped), and a roadblock already placed ahead (g.blocks, decided state) adds its widest gap as a + // candidate lane and pulls the score towards it: a 2 s rollout cannot see a block 300 m away, and at 55 m/s the car cannot cross the + // road in the 2 s it does see (seeds 4, 8, 13, 22, 24 hard: busted or out-run behind a block). + const championPolicy = (() => { + const HOLD_SETS = 6, DT = 1 / 60, CONTACT = 3.5, RESET_NEAR = 95, GAP_AHEAD = 360, GAP_CLEAR = 3.3, GAP_EDGE = 1.6, GAP_PULL = 8; + const laneMem = new WeakMap(); + function laneTarget(g, R, S, others, speed, base) { + const edge = R.halfW - 2.2, prev = laneMem.get(g) ?? g.lat; + const lanes = [clamp(prev, -edge, edge), base, -edge, edge, -edge * .5, 0, edge * .5]; + let best = lanes[0], bs = -Infinity; + for (const lat of lanes) { + let sc = -Math.abs(lat - prev) * 3 - .15 * Math.abs(lat - base); + for (const o of others) { + const ds = o.s - S; if (ds < -10 || ds > 200) continue; + const closing = speed - o.vs, tt = closing > 1 ? Math.max(0, ds) / closing : ds < 30 ? 0.5 : 99; + if (tt > 4) continue; + const gap = Math.abs(o.lat + (o.vl || 0) * Math.min(tt, 1) - lat); + if (gap < 3.8) sc -= (3.8 - gap) * (5 - tt) * 5; + } + if (sc > bs) { bs = sc; best = lat; } + } + laneMem.set(g, best); return best; + } + function roadUsers(g, R) { + const out = [], L = R.L; + const near = v => { if (!R.loop) return v; let ds = (v - g.s) % L; if (ds > L / 2) ds -= L; else if (ds < -L / 2) ds += L; return Math.abs(v - g.s) <= L / 2 ? v : g.s + ds; }; + for (const t of g.traffic) out.push({ s: near(t.s), lat: t.lat, vs: t.crash ? 0 : t.v, r: 2 }); + for (const r of g.rivals) if (!r.out) out.push({ s: near(r.s), lat: r.lat, vs: r.v, r: 2, a: r.v < 25 ? 5 : 0 }); + M.copUsers(g, R, out); + return out; + } + const lines = new Map(); + function racingLine(R, P, grip, brake, top) { + let L = lines.get(R.name); + if (!L) { + const n = R.n, lat = new Float64Array(n), edge = R.halfW - 2.4, wrap = i => R.loop ? (i + n) % n : Math.max(0, Math.min(n - 1, i)), K = Math.max(2, Math.round(10 / R.ds)); + const nx = i => -Math.sin(R.h[i]), ny = i => Math.cos(R.h[i]), px = i => R.x[i] + nx(i) * lat[i], py = i => R.y[i] + ny(i) * lat[i]; + for (let it = 0; it < 400; it++) for (let i = 0; i < n; i++) { const a = wrap(i - K), b = wrap(i + K), tx = (px(a) + px(b)) / 2 - px(i), ty = (py(a) + py(b)) / 2 - py(i); lat[i] = clamp(lat[i] + 0.5 * (tx * nx(i) + ty * ny(i)), -edge, edge); } + const kap = new Float64Array(n); + for (let i = 0; i < n; i++) { const a = wrap(i - K), b = wrap(i + K), x1 = px(i) - px(a), y1 = py(i) - py(a), x2 = px(b) - px(i), y2 = py(b) - py(i), l1 = Math.hypot(x1, y1), l2 = Math.hypot(x2, y2), l3 = Math.hypot(x1 + x2, y1 + y2); kap[i] = l1 && l2 && l3 ? Math.abs(2 * (x1 * y2 - y1 * x2) / (l1 * l2 * l3)) : 0; } + L = { lat, kap, prof: new Map() }; lines.set(R.name, L); + } + const key = [grip, brake, top].map(v => v.toFixed(3)).join('|'); let v = L.prof.get(key); + if (!v) { + v = new Float64Array(R.n); + for (let i = 0; i < R.n; i++) v[i] = L.kap[i] > P.aero + 1e-5 ? Math.min(top, Math.sqrt(grip / (L.kap[i] - P.aero))) : top; + for (let p = 0; p < (R.loop ? 2 : 1); p++) for (let i = R.n - 1; i >= 0; i--) { const j = i + 1 < R.n ? i + 1 : R.loop ? 0 : i, lim = Math.sqrt(v[j] * v[j] + 2 * brake * R.ds); if (lim < v[i]) v[i] = lim; } + L.prof.set(key, v); + } + return { lat: L.lat, prof: v }; + } + const lineLat = (R, lat, s) => { let i = Math.round(s / R.ds); if (R.loop) { i %= R.n; if (i < 0) i += R.n; } else i = clamp(i, 0, R.n - 1); return lat[i]; }; + function contactTime(g, others, S, speed, lat) { + const rate = 4, HORIZON_S = 3; + for (let t = 0.1; t < HORIZON_S; t += 0.1) { + const dl = lat - g.lat, l = g.lat + Math.sign(dl) * Math.min(Math.abs(dl), rate * t), sp = S + speed * t; + for (const o of others) { + if (o.s <= S) continue; + const ol = o.lat + (o.vl || 0) * Math.min(t, 2), ds = o.s + o.vs * t + 0.5 * (o.a || 0) * t * t - sp, t0 = t - 0.1, ds0 = o.s + o.vs * t0 + 0.5 * (o.a || 0) * t0 * t0 - (S + speed * t0); + if (Math.abs(ol - l) < CONTACT && ((ds > 0 && Math.hypot(ds, ol - l) < CONTACT) || (ds0 > 0 && ds <= 0))) return t; + } + } + return HORIZON_S; + } + function steerKeys(c, target, speed, wscale) { + const rate = (speed < 15 ? 7 : speed < 40 ? 5 : 3.6) * wscale * 2 * DT, out = []; let st = c.steer; + for (let i = 0; i < HOLD_SETS; i++) { + let best = 0, bd = Infinity; + for (const k of [0, 1, -1]) { const n = st + clamp(k - st, -rate, rate), e = Math.abs(n - target); if (e < bd - 1e-9) { bd = e; best = k; } } + out.push(best); st += clamp(best - st, -rate, rate); + } + return out; + } + function planDrive(g, opt = {}) { + const R = g.route, c = g.car, P = g.P || C.PLAYER, S = g.s, speed = C.speed(c), tire = C.tireFactor(c); + const margin = opt.margin || 0.92, top = opt.top || C.TOPS[5], wscale = g.sb ? 0.45 : 1; + const line = racingLine(R, P, (P.grip + 19.62 * (g.sb ? 1 : g.sbRamp / (1 / 3))) * tire * margin, P.brake * 0.8, top), prof = line.prof; + const others = roadUsers(g, R), base = opt.lat !== undefined ? opt.lat : lineLat(R, line.lat, S + speed * 0.8), lat = opt.fixedLane ? base : laneTarget(g, R, S, others, speed, base), onLine = lat === base && opt.lat === undefined; + const lag = 0.1 * wscale, px = c.x + c.vx * lag, py = c.y + c.vy * lag, ph = c.h + c.r * lag, Ld = Math.max(7, speed * 0.62); + const sNear = C.routeNear(R, px, py, S, 8, 16), aim = C.routeAt(R, sNear + Ld, onLine ? lineLat(R, line.lat, sNear + Ld) : lat); + let alpha = Math.atan2(aim.y - py, aim.x - px) - ph; alpha = Math.atan2(Math.sin(alpha), Math.cos(alpha)); + const far = C.routeAt(R, S + 18, lat); let off = Math.atan2(far.y - c.y, far.x - c.x) - c.h; off = Math.atan2(Math.sin(off), Math.cos(off)); + const nose = C.road(c.x + Math.cos(c.h) * 3.2, c.y + Math.sin(c.h) * 3.2).d > -0.5; + if (speed < 7 && (Math.abs(off) > 0.9 || nose)) { + const clearBehind = C.road(c.x - Math.cos(c.h) * 3.5, c.y - Math.sin(c.h) * 3.5).d < -0.6, side = off > 0 ? 1 : -1; + return { keys: steerKeys(c, clearBehind ? -side : side, speed, wscale), thr: clearBehind ? 0 : HOLD_SETS, brk: clearBehind, nos: false, lat, contact: 3, why: 'recover' }; + } + const kappa = 2 * Math.sin(alpha) / Ld, delta = Math.atan(kappa * P.wheelbase), range = C.steerRange(speed / C.MPH) * Math.PI / 180; + const vlim = Math.min(C.profileAt(R, prof, S + speed * 0.2), C.profileAt(R, prof, S + speed * 0.45)); + const contact = contactTime(g, opt.ram ? others.filter(o => !o.cop) : others, S, speed, lat), over = speed > vlim + 0.8, brk = over || contact < 0.8, coast = !brk && contact < 1.2; + const grip = (P.grip + 19.62 * (g.sb ? 1 : g.sbRamp / (1 / 3)) + P.aero * speed * speed) * tire, ay = speed * speed * Math.abs(kappa), spare = Math.max(0, 1 - ay / grip); + const allowed = spare / 0.55 * grip * 1.1, drive = Math.max(1, C.driveAt(speed) * P.accel), thr = coast ? 0 : Math.round(HOLD_SETS * clamp(allowed / drive, 0.17, 1)); + const nos = !brk && !coast && (opt.forceNos ? c.nos > 0.02 && speed > 12 : c.nos > 0.02 && speed > 18 && opt.nos !== false && thr === HOLD_SETS && C.profileAt(R, prof, S + speed * 1.8) > speed + 8); + return { keys: steerKeys(c, clamp(delta / range, -1, 1), speed, wscale), thr: brk ? 0 : thr, brk, nos, lat, contact, why: over ? 'speed' : contact < 0.8 ? 'contact' : coast ? 'coast' : 'drive' }; + } + function toPacket(plan) { + const holds = []; + for (let i = 0; i < HOLD_SETS; i++) { + const h = [], k = plan.keys ? plan.keys[i] : 0; + if (plan.brk) h.push('S'); else if (plan.thr >= HOLD_SETS || Math.floor((i + 1) * plan.thr / HOLD_SETS) > Math.floor(i * plan.thr / HOLD_SETS)) h.push('W'); + if (k) h.push(k > 0 ? 'A' : 'D'); + if (plan.nos) h.push('Shift'); + holds.push(h); + } + return { holds, mouse: [0, 0, 0] }; + } + function packet(g, choice) { + if (g.pre > .21) return toPacket({ thr: HOLD_SETS, brk: false, nos: false }); + const opt = { ram: true, margin: 1.02 }; if (choice.lat !== null) { opt.lat = choice.lat; opt.fixedLane = true; } + const p = planDrive(g, opt), sp = C.speed(g.car); + if (choice.gas && p.why !== 'recover') { p.brk = false; p.thr = 6; p.nos = g.car.nos > .02 && sp > 18; } + const pk = toPacket(p); + const sb = choice.sb === undefined ? (sp > 18 && (p.why === 'speed' || Math.abs(g.car.steer) > .65)) : choice.sb; + if (sb !== !!g.sb && (g.sb || g.sbMeter > .2) && pk.holds[0].length < 4) pk.holds[0].push('J'); + return pk; + } + // Keys held at the end of the last packet, kept per game tick so a repeated call on one state starts every rollout from the same keys. + const heldMem = new WeakMap(); + const heldBefore = g => { const m = heldMem.get(g); return !m ? [] : m.t === g.t ? m.prev : m.next; }; + const heldAfter = (g, next) => heldMem.set(g, { t: g.t, prev: heldBefore(g), next }); + function session(g, held) { + const s = Object.create(N.Session.prototype); s.module = M; s.game = M.copyGame(g); + s.game.rng = 2463534242; s.game.seed = 0; s.held = held.slice(); s.inputs = []; s.recording = false; s.events = []; // one fixed scenario, not the live draws + return s; + } + // The widest free stretch across the next roadblock within GAP_AHEAD m: between parked cars, barriers and the road edges. + function roadblockGap(g) { + const R = g.route, hw = R.halfW; let S = Infinity; + for (const b of g.blocks) { const bs = M.wrapTo(R, b.s, g.s); if (bs > g.s + 3 && bs < S) S = bs; } + if (S === Infinity || S - g.s > GAP_AHEAD) return null; + const occ = []; for (const b of g.blocks) if (Math.abs(M.wrapTo(R, b.s, g.s) - S) < 1) occ.push([b.lat - GAP_CLEAR, b.lat + GAP_CLEAR]); + occ.sort((x, y) => x[0] - y[0]); + let lo = -hw + GAP_EDGE, best = null; const hi = hw - GAP_EDGE; + for (const [x, y] of occ) { if (x > lo && (!best || Math.min(x, hi) - lo > best[1] - best[0])) best = [lo, Math.min(x, hi)]; lo = Math.max(lo, y); } + if (hi > lo && (!best || hi - lo > best[1] - best[0])) best = [lo, hi]; + return best && best[1] > best[0] ? { s: S, lat: (best[0] + best[1]) / 2 } : null; + } + return function policy(g) { + if (g.car.tires > 0 && g.flash <= 0) { + let near = Infinity; for (const k of g.cops) if (!k.dead && k.state !== 'rb') near = Math.min(near, Math.hypot(g.car.x - k.x, g.car.y - k.y)); + if (near > RESET_NEAR) { heldAfter(g, []); return { holds: [['R'], [], [], [], [], []], mouse: [0, 0, 0] }; } + } + const held = heldBefore(g), edge = g.route.halfW - 2.6; + const choices = [{ lat: null }, { lat: g.lat }, { lat: -edge * .85 }, { lat: edge * .85 }, { lat: -edge * .4 }, { lat: edge * .4 }, + { lat: null, gas: true }, { lat: g.lat, gas: true }, { lat: null, sb: true }]; + const gap = roadblockGap(g); if (gap) choices.push({ lat: gap.lat }, { lat: gap.lat, gas: true }); + let best = null, bestScore = -Infinity; + for (const choice of choices) { + const s = session(g, held), first = packet(s.game, choice); let proximity = 0; + for (let t = 0; t < 120 && !s.game.outcome; t += 12) { + s.packet(t === 0 ? first : packet(s.game, choice)); + const z = s.game, sp = C.speed(z.car); + for (const cop of z.cops) if (!cop.dead && !cop.gone) { const d = Math.hypot(z.car.x - cop.x, z.car.y - cop.y); proximity = Math.max(proximity, Math.max(0, 4 - d) * (sp < 15 ? 3 : 1)); } + } + const z = s.game, road = C.routeAt(z.route, z.s), a = N.angle(z.car.h - road.h); + const score = (z.prog - g.prog) * 3 + C.speed(z.car) * .65 - (z.hits - g.hits) * 8 + - (z.pol.bust - g.pol.bust) * 90 - (z.car.tires - g.car.tires) * 200 - proximity * 12 + - Math.max(0, Math.abs(z.lat) - edge) * 10 - a * a * 5 + (z.car.nos - g.car.nos) * 8 + + (z.outcome === 'win' ? 100000 : 0) - (z.outcome && z.outcome !== 'win' ? 100000 : 0) + - (gap && z.s < gap.s ? Math.abs(z.lat - gap.lat) * GAP_PULL : 0); + if (score > bestScore) { bestScore = score; best = first; } + } + heldAfter(g, best.holds[5].slice().sort()); return best; + }; + })(); + + M.MODES.pursuit = { + route: () => 'coast', + init(g, d) { + g.s0 = S0; g.total = 1e9; g.pre = 0; g.placeCar(S0, -2.5, 34); g.car.gear = 3; // spotted at speed: a pursuit has no starting grid + g.stages = Math.round(M.tierValue(d, [1, 1, 3])); g.stage = 0; g.diff = d; + g.bountyNeed = M.tierValue(d, [10, 32, 34]); g.prog = 0; + M.initPolice(g, { copsMax: 2, top: 60, grip: M.tierValue(d, [0.78, 0.85, 0.92]), accel: M.tierValue(d, [0.8, 0.95, 1.05]), spawnGap: M.tierValue(d, [12, 9, 7]), formations: d < 0.35 ? ['FOLLOW'] : d < 0.7 ? ['FOLLOW', 'ROLLING_BLOCK', 'PIT'] : ['FOLLOW', 'ROLLING_BLOCK', 'BOX_IN', 'PIT'], + rbChance: M.tierValue(d, [0, 0.45, 0.7]), spikeChance: M.tierValue(d, [0, 0.25, 0.5]), rbGap: M.tierValue(d, [8, 7, 6]), heli: d > 0.7, heliAfter: 30, heliFuel: 22, heliGap: 30, bustSpeed: M.tierValue(d, [7, 10, 13]), searchTop: M.tierValue(d, [34, 42, 50]), close: M.tierValue(d, [8, 11, 14]), copFrail: 3.2, aheadChance: M.tierValue(d, [0.25, 0.35, 0.45]), evadeTimeout: M.tierValue(d, [8, 13, 15]) }); + g.breakers = []; const R = g.route; + for (const off of [500, 1500, 2600, 3600, 4600]) { for (const side of [1]) { const s = (S0 + off) % R.L, a = C.routeAt(R, s, side * (R.halfW - 1.5)); g.breakers.push({ s, lat: side * (R.halfW - 2.5), x: a.x, y: a.y, h: a.h, fired: 0, rearm: 0 }); } } + g.bountyTotal = 0; + startStage(g, d); + M.spawnTraffic(g, Math.round(M.tierValue(d, [4, 7, 10]))); + }, + idle(g) { for (const c of g.cops) { const a = C.routeAt(g.route, c.s, c.lat); c.x = a.x; c.y = a.y; c.h = a.h; } }, + tick(g, wdt) { + const p = g.pol, R = g.route, before = p.destroyed; + M.stepPolice(g, wdt, g.stageBounty >= g.bountyNeed); + if (g.outcome) return; + // Pursuit Breaker: driving through the structure brings it down on whatever is around it. + for (const b of g.breakers) { + if (b.rearm > 0) b.rearm -= wdt; + const bs = M.wrapTo(R, b.s, g.s); + if (!b.rearm && Math.abs(g.s - bs) < C.speed(g.car) * wdt + 2 && Math.abs(g.lat - b.lat) < 3.4) { + b.rearm = 60; g.events.push({ type: 'trap_collapse' }); + for (const c of g.cops) if (!c.dead && c.state !== 'rb' && Math.hypot(c.x - b.x, c.y - b.y) < BREAKER_R) M.destroyCop(g, c, 'breaker'); + for (const t of g.traffic) if (!t.crash && Math.hypot(t.x - b.x, t.y - b.y) < 14) { t.crash = 0.6; t.vx = Math.cos(t.h) * Math.abs(t.v) * 0.4; t.vy = Math.sin(t.h) * Math.abs(t.v) * 0.4; } + } + } + // Bounty: seconds in sight, plus a lump per destroyed cop x the multiplier. + if (g.stageBounty < g.bountyNeed) { + if (p.inSight) g.stageBounty += wdt; + if (p.destroyed > before) g.stageBounty += 1.5 * p.bonusMult * (p.destroyed - before); + g.stageBounty = Math.min(g.bountyNeed, g.stageBounty); + } + g.stageEvadeHW = Math.max(g.stageEvadeHW, g.stageBounty >= g.bountyNeed ? p.evade : 0); + if (p.evade >= 1 && g.stageBounty >= g.bountyNeed) { + g.events.push({ type: 'evaded', stage: g.stage }); g.stage++; + if (g.stage >= g.stages) return g.win(); + for (const c of g.cops) c.gone = 1; g.cops = []; + p.evade = 0; startStage(g, g.diff); + } + }, + health(g) { + const total = g.stages * (BOUNTY_UNITS + EVADE_UNITS); + if (g.outcome === 'win') return [M.bustHp(g), 50, 0, total]; + const done = g.stage * (BOUNTY_UNITS + EVADE_UNITS) + BOUNTY_UNITS * g.stageBounty / g.bountyNeed + EVADE_UNITS * g.stageEvadeHW; + return [g.outcome === 'loss' ? 0 : M.bustHp(g), 50, Math.max(0, total - done), total]; + }, + hud(g) { const p = g.pol, s = Math.min(g.stage + 1, g.stages); return { label: 'Police pursuit', detail: `Heat ${s} / ${g.stages} · Bounty ${(100 * g.stageBounty / g.bountyNeed).toFixed(0)}% · Escape ${(100 * p.evade).toFixed(0)}% · Cops ${g.cops.filter(c => !c.dead).length}${g.heli ? ' · Helicopter' : ''}` }; }, + // Reference controller: pursuitPolicy above. + scripted(g) { return pursuitPolicy(g); }, + hudExtra(g, c, u) { const p = g.pol; if (p.bust > 0.03) { c.font = 'bold 13px "Microsoft YaHei",sans-serif'; c.fillStyle = '#ff6a5a'; c.textAlign = 'center'; c.fillText('Busted ' + Math.round(100 * p.bust / M.BUST_MAX) + '%', u.W / 2, 78); c.textAlign = 'left'; } }, + }; + // Razor. GRace kRaceType_P2P with GetIsPursuitRace: the rival and the police at once. Wikipedia: the rematch is "another 5-street racing pink + // slip". Streets are legs of the route here; the player must keep ahead of Razor while the chase is on. + // boss_hp = route metres left; player_hp = the lesser of Razor's remaining share and the bust meter's, per mille. + M.MODES.street_champion = { + route: () => 'coast', + init(g, d) { + const S = 1500; g.s0 = S; g.total = Math.max(120, M.tierValue(d, [920, 2500, 7000])); g.legs = Math.max(1, Math.round(M.tierValue(d, [1, 2, 5]))); /* floors: d < 0.05 extrapolated to a negative route and 0 streets */ g.placeCar(S, -2.2); + g.rivals = [M.newRival(g, { s: S + 9, lat: 2.2, skill: C.clamp(M.tierValue(d, [0.1, 0.3, 0.5]) + M.formOf(g), 0, 1), paint: 3, name: 'champion' })]; + g.rivals[0].s0 = S; g.rivals[0].prog = 9; g.glue = 0.7; + M.initPolice(g, { copsMax: Math.round(M.tierValue(d, [1, 2, 4])), top: M.tierValue(d, [56, 62, 66]), grip: M.tierValue(d, [0.75, 0.82, 0.9]), accel: M.tierValue(d, [0.75, 0.9, 1]), spawnGap: M.tierValue(d, [16, 12, 9]), formations: d < 0.35 ? ['FOLLOW'] : ['FOLLOW', 'ROLLING_BLOCK', 'PIT'], rbChance: M.tierValue(d, [0, 0.35, 0.6]), spikeChance: M.tierValue(d, [0, 0.15, 0.4]), rbGap: M.tierValue(d, [8, 7.5, 6.5]), heli: false, heliAfter: 1e6, heliFuel: 0, heliGap: 1e6, bustSpeed: M.tierValue(d, [6, 9, 12]), searchTop: 40, close: M.tierValue(d, [6, 9, 12]), copFrail: 3.2, aheadChance: M.tierValue(d, [0.2, 0.5, 0.6]), aheadBlind: 1, evadeTimeout: 1e9 }); + g.gates = []; for (let i = 1; i <= g.legs; i++) g.gates.push({ at: g.total * i / g.legs, done: 0, kind: 'line' }); + g.next = 0; + M.spawnTraffic(g, Math.round(M.tierValue(d, [5, 8, 11]))); + }, + idle(g) { for (const r of g.rivals) { const a = C.routeAt(g.route, r.s, r.lat); r.x = a.x; r.y = a.y; r.h = a.h; } }, + tick(g, wdt) { + const r = g.rivals[0]; + M.stepRival(g, r, wdt); M.stepPolice(g, wdt, false); + if (g.outcome) return; + while (g.next < g.gates.length && g.prog >= g.gates[g.next].at) { g.gates[g.next].done = 1; g.next++; g.events.push({ type: 'leg', leg: g.next }); } + if (g.prog >= g.total) return g.win(); + if (r.prog >= g.total) g.lose('gap'); + }, + health(g) { + const r = g.rivals[0], a = clamp((g.total - r.prog) / g.total, 0, 1), b = M.bustHp(g) / 50, hp = g.outcome === 'loss' ? 0 : Math.round(Math.min(a, b) * 1000); + return [hp, 1000, g.outcome === 'win' ? 0 : Math.max(0, g.total - g.prog), g.total]; + }, + hud(g) { const r = g.rivals[0], lead = g.prog - r.prog; return { label: 'Street Champion Showdown', detail: `Leg ${Math.min(g.next + 1, g.legs)} / ${g.legs} · ${lead >= 0 ? 'Ahead by' : 'Behind by'} ${Math.abs(lead).toFixed(0)} m · Cops ${g.cops.filter(c => !c.dead).length}` }; }, + scripted(g) { return championPolicy(g); }, + hudExtra(g, c, u) { M.MODES.pursuit.hudExtra(g, c, u); }, + }; + void N; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/nfsmw_remake/modes_speedtrap.js b/environments/games/web/games/nfsmw_remake/modes_speedtrap.js new file mode 100644 index 0000000000000000000000000000000000000000..9b700bd358225027132863b0ab9f116d4c67a5c1 --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/modes_speedtrap.js @@ -0,0 +1,62 @@ +/* Speed Trap (GRace.h kRaceType_SpeedTrap). Crossing order does not matter: "each checkpoint's total speed is accumulated to + determine the winner" (Wikipedia). The speed at each camera is what counts, so the driver saves nitrous for the camera, and the + rival does the same (AIActionRace.cpp CheckSpeedTraps: nitrous 1-3 s ahead by skill, Tweak_SpeedTrapSkillBoost :50), with + half the usual catch-up glue (AIVehicle.cpp:2053 Tweak_SpeedTrapCatchupGlue 0.5). GRaceStatus.h keeps one speed per trap. + boss_hp = route metres left to the last camera; player_hp = cushion + score lead over the traps both cars have crossed. The + camera positions and the cushion are original (the race database is VLT data): cameras sit on the fastest ground nearby. */ +(function (root) { + 'use strict'; + const M = root.NfsmwGame, C = M.C, P = C.PLAYER, KMH = 3.6, S0 = 900; + M.MODES.speedtrap = { + route: () => 'coast', + init(g, d) { + const R = g.route, v = C.profile(R, P.grip, P.aero, P.brake, C.TOPS[5]); + g.total = M.tierValue(d, [900, 3100, 7800]); g.s0 = S0; g.placeCar(S0, -2.1); g.glue = 0.5; + const count = Math.max(2, Math.round(g.total / 480)), reach = C.reachable(R, v, S0, g.total + 100, P); + g.gates = []; + for (let i = 1; i <= count; i++) { + let at = g.total * i / count; + if (i < count) { let best = at, bv = -1; for (let x = at - 150; x <= at + 150; x += 6) { const u = reach[Math.round(x / R.ds)]; if (u > bv) { bv = u; best = x; } } at = best; } + g.gates.push({ at, kind: 'trap', done: 0, you: 0, them: 0, themDone: 0 }); + } + // Pretraining engineering target from the existing deterministic vehicle/route + // reachability profile. No policy, sampled rival score or evaluation result is used. + // Freeze once at reset; keep health(), HUD, finish and win/loss rules unchanged. + g.reward_target_version = 'speedtrap-reachable-profile@1'; + g.reward_target_cameras = g.gates.map(t => Math.round(reach[Math.round(t.at / R.ds)] * KMH * 1e6) / 1e6); + g.reward_target_score = Math.round(g.reward_target_cameras.reduce((a,b) => a+b, 0) * 1e6) / 1e6; + if (!Number.isFinite(g.reward_target_score) || g.reward_target_score <= 0) throw Error('invalid fixed speedtrap target'); + g.next = 0; g.rNext = 0; g.you = 0; g.them = 0; g.flashT = 0; g.cushion = M.tierValue(d, [130, 95, 70]); + g.rivals = [M.newRival(g, { s: S0, lat: 2.1, skill: C.clamp(M.tierValue(d, [0.15, 0.42, 0.68]) + M.formOf(g), 0, 1), paint: 2 })]; + M.spawnTraffic(g, Math.round(M.tierValue(d, [6, 9, 13]))); + }, + idle() {}, + lead(g) { let lead = 0; for (let i = 0; i < g.gates.length; i++) { const t = g.gates[i]; if (t.done && t.themDone) lead += t.you - t.them; } return lead; }, + tick(g, wdt) { + if (g.flashT > 0) g.flashT = Math.max(0, g.flashT - wdt); + const r = g.rivals[0]; + while (g.rNext < g.gates.length && r.prog >= g.gates[g.rNext].at) { const t = g.gates[g.rNext]; t.them = r.v * KMH; t.themDone = 1; g.them += t.them; g.rNext++; } + if (g.rNext < g.gates.length) { const ahead = g.gates[g.rNext].at - r.prog, tt = ahead / Math.max(r.v, 5); if (tt < C.lerp(1, 3, r.skill)) r.trapNos = 0.2; } + M.stepRival(g, r, wdt); + while (g.next < g.gates.length && g.prog >= g.gates[g.next].at) { const t = g.gates[g.next]; t.done = 1; t.keep = 0; t.you = C.speed(g.car) * KMH; g.you += t.you; g.next++; g.flashT = 0.15; g.events.push({ type: 'speedtrap', kmh: t.you }); } + if (g.next >= g.gates.length) { + // The player's last camera ends the event. Cameras the rival has not reached yet are scored at the speed it would carry there. + let them = g.them; for (let i = g.rNext; i < g.gates.length; i++) them += M.projectRival(g, r, g.s0 + g.gates[i].at) * KMH; + g.themFinal = them; + if (g.you >= them) g.win(); else g.lose('score'); + return; + } + if (g.cushion + this.lead(g) <= 0) g.lose('score'); + }, + health(g) { + const max = g.cushion * 2, hp = g.outcome === 'loss' ? 0 : C.clamp(g.cushion + this.lead(g), 0, max); + return [hp, max, g.outcome === 'win' ? 0 : Math.max(0, g.total - g.prog), g.total]; + }, + hud(g) { return { label: 'Speed Trap', detail: `Checkpoint ${Math.min(g.next + 1, g.gates.length)} / ${g.gates.length} · You: ${g.you.toFixed(0)} · Rival: ${g.them.toFixed(0)} km/h` }; }, + // Reference: drive the line, and spend nitrous only in the last seconds before a camera. + scripted(g) { + const v = Math.max(C.speed(g.car), 5), t = g.gates[g.next], ahead = t ? (t.at - g.prog) / v : 99; + return M.ctl.drive(g, ahead < 2.8 ? { forceNos: true } : { nos: false }); + }, + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/nfsmw_remake/modes_tollbooth.js b/environments/games/web/games/nfsmw_remake/modes_tollbooth.js new file mode 100644 index 0000000000000000000000000000000000000000..eabf8c7729cf21c7acaf61587589c8e0de6da1cb --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/modes_tollbooth.js @@ -0,0 +1,41 @@ +/* Tollbooth (GRace.h kRaceType_Tollbooth): a solo run against the clock. Each gate grants more time and leftover seconds + carry over (Wikipedia, "Need for Speed: Most Wanted (2005)": "a checkpoint-styled solo race, in which players must hit + a set of checkpoints, each one within a set amount of time"; GRaceStatus.h NotifyTollboothCrossed counts them). + boss_hp = route metres left to the last gate; player_hp = clock in tenths of a second. The gate timings live in the + game's race database (VLT), so the allowance here is an approximation: slack x the car's own ideal time. */ +(function (root) { + 'use strict'; + const M = root.NfsmwGame, C = M.C; + const P = C.PLAYER, TOP = C.TOPS[5]; + M.MODES.tollbooth = { + route: () => 'coast', + init(g, d) { + const R = g.route, S0 = 3640; + g.total = M.tierValue(d, [860, 3250, 8000]); + g.s0 = S0; g.placeCar(S0, -2.1); + const slack = M.tierValue(d, [1.55, 1.34, 1.2]), v = C.profile(R, P.grip, P.aero, P.brake, TOP), spacing = 620; + const count = Math.max(2, Math.round(g.total / spacing)); + g.gates = []; + let at = 0; + for (let i = 1; i <= count; i++) { const end = g.total * i / count; g.gates.push({ at: end, grant: C.driveTime(R, v, S0 + at, end - at, P, i === 1 ? 0 : 30) * slack, done: 0 }); at = end; } + g.next = 0; g.bank = g.gates[0].grant + 3; g.bankMax = g.bank; + M.spawnTraffic(g, Math.round(M.tierValue(d, [7, 11, 16]))); + }, + idle() {}, + tick(g, wdt) { + g.bank -= wdt; + while (g.next < g.gates.length && g.prog >= g.gates[g.next].at) { + const gate = g.gates[g.next]; gate.done = 1; g.next++; + g.events.push({ type: 'gate', left: g.bank }); + if (g.next < g.gates.length) { g.bank += g.gates[g.next].grant; g.bankMax = Math.max(g.bankMax, g.bank); } + } + if (g.prog >= g.total) return g.win(); + if (g.bank <= 0) { g.bank = 0; g.lose('time'); } + }, + health(g) { + const left = Math.max(0, g.total - g.prog); + return [Math.max(0, g.outcome === 'loss' ? 0 : Math.round(g.bank * 10)), Math.ceil(g.bankMax * 10), g.outcome === 'win' ? 0 : left, g.total]; + }, + hud(g) { return { label: 'Tollbooth', detail: `Gate ${Math.min(g.next + 1, g.gates.length)} / ${g.gates.length} · Time left: ${g.bank.toFixed(1)} s` }; }, + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/nfsmw_remake/nfscore.js b/environments/games/web/games/nfsmw_remake/nfscore.js new file mode 100644 index 0000000000000000000000000000000000000000..18d40d12f4a47c22f7a74eaf9811a0f7ba14edd7 --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/nfscore.js @@ -0,0 +1,237 @@ +/* Need for Speed: Most Wanted (2005) events, rules nfsmw-arena@1 - world and vehicle core. + Original procedural city: the roads are a union of capsules around authored polylines, so a car is free inside the + union and everything outside is a wall; sight lines sample the same function. Routes are rounded polylines sampled + every 2 m and measured along their own length (progress is route distance, never distance to a target). + Vehicle rules read from the CC0 decompilation dbalatoni13/nfsmw@80993f3 are cited inline; values that live in the + game's VLT data (mass, torque, grip) are not in that repository and are original approximations (see SOURCES.md). + Nothing here touches a game's RNG: every function is pure except for the car it is handed. */ +(function (root) { + 'use strict'; + const M = root.NfsmwGame = root.NfsmwGame || {}, C = M.C = {}; + const q4 = v => Math.round(v * 1e4) / 1e4; // static geometry is rounded once so trig ULPs cannot reach a replay + const clamp = (v, a, b) => v < a ? a : v > b ? b : v; + C.clamp = clamp; C.lerp = (a, b, t) => a + (b - a) * t; + C.MPH = 0.44704; C.KPH = 1 / 3.6; + + // ---------------- authored routes: [x, y, corner radius] (original layout) ---------------- + const ROUTES = { + // Coastal loop: the 1.5 km highway along the south shore, sweepers in the east, a chicane in the north, hills west. + coast: { loop: true, width: 17, pts: [[-760, -520, 90], [860, -520, 220], [980, -120, 160], [760, 260, 120], [820, 520, 100], [300, 560, 80], [220, 400, 45], [-60, 400, 45], [-140, 560, 70], [-620, 560, 120], [-820, 260, 90], [-640, 60, 70], [-860, -140, 90]] }, + // Downtown block: the short circuit for the knockout, four fast corners and an inner chicane. + downtown: { loop: true, width: 15, pts: [[-85, -80, 26], [90, -80, 22], [90, -22, 15], [46, -22, 13], [46, 28, 13], [90, 28, 15], [90, 80, 22], [-85, 80, 26]] }, + // Highway 99 drag strip: dead straight, four lanes, not connected to the city. + strip: { loop: false, width: 22, pts: [[-1500, -1000, 0], [1500, -1000, 0]] }, + }; + // Cross streets: never raced, they are what the pursuit is about (sight breaks, cops arriving from the side). + const STREETS = [ + [[0, -520], [0, -80]], [[0, 80], [0, 400]], [[46, 3], [420, 3], [420, 260], [760, 260]], [[-85, 0], [-400, 0], [-400, 60], [-640, 60]], + [[420, 0], [420, -520]], [[-400, 0], [-400, -520]], [[420, 260], [300, 560]], [[-400, 60], [-400, 560]], + ]; + const STREET_W = 13, DS = 2; + + function buildRoute(name, def) { + const P = def.pts, n = P.length; // each corner becomes a tangent arc between two straights + const corner = i => { + const [x, y, r] = P[i], a = P[(i + n - 1) % n], b = P[(i + 1) % n]; + const ax = a[0] - x, ay = a[1] - y, bx = b[0] - x, by = b[1] - y, la = Math.hypot(ax, ay), lb = Math.hypot(bx, by); + const ux = ax / la, uy = ay / la, vx = bx / lb, vy = by / lb, cos = clamp(ux * vx + uy * vy, -1, 1), th = Math.acos(cos); + const t = r / Math.tan(th / 2); + if (t > Math.min(la, lb) * 0.5 + 1e-6) throw Error(`${name}: corner ${i} radius too large`); + const hx = ux + vx, hy = uy + vy, hl = Math.hypot(hx, hy), dist = r / Math.sin(th / 2); + const cx = x + hx / hl * dist, cy = y + hy / hl * dist, sx = x + ux * t, sy = y + uy * t, ex = x + vx * t, ey = y + vy * t; + const turn = -Math.sign(ux * vy - uy * vx); // +1 = counter-clockwise + return { sx, sy, ex, ey, cx, cy, r, sweep: Math.PI - th, turn }; + }; + const out = { x: [], y: [], h: [], k: [] }; + const push = (x, y, h, k) => { out.x.push(q4(x)); out.y.push(q4(y)); out.h.push(q4(h)); out.k.push(Math.round(k * 1e7) / 1e7); }; + const dense = []; // 0.25 m polyline with curvature, resampled to DS below + const line = (ax, ay, bx, by) => { const L = Math.hypot(bx - ax, by - ay), m = Math.max(1, Math.ceil(L / 0.25)), h = Math.atan2(by - ay, bx - ax); for (let i = 0; i < m; i++) dense.push([ax + (bx - ax) * i / m, ay + (by - ay) * i / m, h, 0]); }; + if (def.loop) { + const cs = P.map((_, i) => corner(i)); + for (let i = 0; i < n; i++) { + const c = cs[i], d = cs[(i + 1) % n], a0 = Math.atan2(c.sy - c.cy, c.sx - c.cx), m = Math.max(1, Math.ceil(c.r * c.sweep / 0.25)); + for (let j = 0; j < m; j++) { const a = a0 + c.turn * c.sweep * j / m; dense.push([c.cx + Math.cos(a) * c.r, c.cy + Math.sin(a) * c.r, a + c.turn * Math.PI / 2, c.turn / c.r]); } + line(c.ex, c.ey, d.sx, d.sy); + } + } else { for (let i = 0; i + 1 < n; i++) line(P[i][0], P[i][1], P[i + 1][0], P[i + 1][1]); dense.push([P[n - 1][0], P[n - 1][1], dense[dense.length - 1][2], 0]); } + let acc = 0, next = 0, last = dense[0]; + dense.forEach((p, i) => { if (i) acc += Math.hypot(p[0] - last[0], p[1] - last[1]); last = p; while (acc >= next - 1e-9) { push(p[0], p[1], p[2], p[3]); next += DS; } }); + const L = out.x.length * DS; + return { name, loop: !!def.loop, width: def.width, halfW: def.width / 2, ds: DS, n: out.x.length, L, x: out.x, y: out.y, h: out.h, k: out.k }; + } + C.routes = {}; for (const [k, d] of Object.entries(ROUTES)) C.routes[k] = buildRoute(k, d); + // Route position (s is unbounded on a loop). Writes to a shared scratch object: copy the fields you keep. + const at = { x: 0, y: 0, h: 0, k: 0, nx: 0, ny: 0 }; + C.routeAt = (R, s, lat = 0) => { + let u = s / R.ds; if (R.loop) { u %= R.n; if (u < 0) u += R.n; } else u = clamp(u, 0, R.n - 1.0001); + const i = Math.floor(u), f = u - i, j = (i + 1) % R.n; + let dh = R.h[j] - R.h[i]; if (dh > Math.PI) dh -= 2 * Math.PI; else if (dh < -Math.PI) dh += 2 * Math.PI; + at.h = R.h[i] + dh * f; at.k = R.k[i]; at.nx = -Math.sin(at.h); at.ny = Math.cos(at.h); + at.x = R.x[i] + (R.x[j] - R.x[i]) * f + at.nx * lat; at.y = R.y[i] + (R.y[j] - R.y[i]) * f + at.ny * lat; + return at; + }; + // Nearest route distance within a window around a guess: junctions can never teleport progress to another leg. + C.routeNear = (R, x, y, guess, back = 40, fwd = 60) => { + let best = guess, bd = Infinity; + const g0 = Math.round(guess / R.ds) * R.ds; + for (let s = g0 - back; s <= g0 + fwd; s += R.ds) { + if (!R.loop && (s < 0 || s > R.L)) continue; + let u = Math.round(s / R.ds); if (R.loop) { u %= R.n; if (u < 0) u += R.n; } else u = clamp(u, 0, R.n - 1); + const dx = x - R.x[u], dy = y - R.y[u], d = dx * dx + dy * dy; if (d < bd) { bd = d; best = s; } + } + // refine inside the winning 2 m cell with the segment projection + const a = C.routeAt(R, best), ax = Math.cos(a.h), ay = Math.sin(a.h); + return best + clamp((x - a.x) * ax + (y - a.y) * ay, -R.ds, R.ds); + }; + C.routeLat = (R, x, y, s) => { const a = C.routeAt(R, s); return (x - a.x) * a.nx + (y - a.y) * a.ny; }; + + // ---------------- the road union: 10 m grid of candidate capsules ---------------- + const SEGS = []; const addPoly = (pts, hw, closed) => { const m = closed ? pts.length : pts.length - 1; for (let i = 0; i < m; i++) { const a = pts[i], b = pts[(i + 1) % pts.length]; SEGS.push({ ax: a[0], ay: a[1], bx: b[0], by: b[1], hw }); } }; + for (const R of Object.values(C.routes)) { const pts = []; const step = R.name === 'strip' ? 50 : R.name === 'downtown' ? 2 : 4; for (let i = 0; i < R.n; i += step) pts.push([R.x[i], R.y[i]]); if (!R.loop) pts.push([R.x[R.n - 1], R.y[R.n - 1]]); addPoly(pts, R.halfW, R.loop); } + for (const st of STREETS) addPoly(st, STREET_W / 2, false); + C.streets = STREETS; C.streetW = STREET_W; + const CELL = 10, X0 = -1560, Y0 = -1060, NX = 310, NY = 180, GRID = new Array(NX * NY); + SEGS.forEach((g, gi) => { + const pad = g.hw + CELL * 1.5, x0 = Math.floor((Math.min(g.ax, g.bx) - pad - X0) / CELL), x1 = Math.floor((Math.max(g.ax, g.bx) + pad - X0) / CELL), y0 = Math.floor((Math.min(g.ay, g.by) - pad - Y0) / CELL), y1 = Math.floor((Math.max(g.ay, g.by) + pad - Y0) / CELL); + for (let j = Math.max(0, y0); j <= Math.min(NY - 1, y1); j++) for (let i = Math.max(0, x0); i <= Math.min(NX - 1, x1); i++) { const px = X0 + (i + 0.5) * CELL, py = Y0 + (j + 0.5) * CELL, dx = g.bx - g.ax, dy = g.by - g.ay, t = clamp(((px - g.ax) * dx + (py - g.ay) * dy) / (dx * dx + dy * dy || 1), 0, 1); if (Math.hypot(px - g.ax - t * dx, py - g.ay - t * dy) <= pad) { const c = i + j * NX; (GRID[c] || (GRID[c] = [])).push(gi); } } + }); + // d > 0 means d metres outside the union; (nx, ny) points from the road centre towards the car. + const hit = { d: 0, nx: 0, ny: 0 }; + C.road = (x, y) => { + const i = Math.floor((x - X0) / CELL), j = Math.floor((y - Y0) / CELL); + hit.d = 99; hit.nx = 0; hit.ny = 0; + if (i < 0 || j < 0 || i >= NX || j >= NY) return hit; + const c = GRID[i + j * NX]; if (!c) return hit; + for (let k = 0; k < c.length; k++) { + const g = SEGS[c[k]], dx = g.bx - g.ax, dy = g.by - g.ay, t = clamp(((x - g.ax) * dx + (y - g.ay) * dy) / (dx * dx + dy * dy || 1), 0, 1), px = x - g.ax - t * dx, py = y - g.ay - t * dy, l = Math.sqrt(px * px + py * py), d = l - g.hw; + if (d < hit.d) { hit.d = d; if (l > 1e-6) { hit.nx = px / l; hit.ny = py / l; } else { hit.nx = 0; hit.ny = 0; } } + } + return hit; + }; + C.onRoad = (x, y, margin = 0) => C.road(x, y).d < -margin; + // Sight line: buildings stand everywhere the road is not (AIVehicleCopCar::CanSeeTarget's world ray, sampled). + C.lineClear = (ax, ay, bx, by) => { const L = Math.hypot(bx - ax, by - ay), m = Math.ceil(L / 5); for (let i = 1; i < m; i++) if (C.road(ax + (bx - ax) * i / m, ay + (by - ay) * i / m).d > 2) return false; return true; }; + C.bounds = { X0, Y0, NX, NY, CELL }; + + // ---------------- vehicle ---------------- + const lookup = (tab, v, max) => { const u = clamp(v / max, 0, 1) * (tab.length - 1), i = Math.min(tab.length - 2, Math.floor(u)); return tab[i] + (tab[i + 1] - tab[i]) * (u - i); }; + // SuspensionRacer.cpp:1077 SteeringRangeData, degrees over 0..160 mph; :1072 BrakeSteeringRangeMultiplier 1.45. + const STEER_RANGE = [40, 20, 10, 5.5, 4.5, 3.25, 2.9, 2.9, 2.9, 2.9], BRAKE_STEER = 1.45; + // Approximation (VLT transmission/engine data is not in the repository): an original six-speed road car. + const TOPS = [17, 30, 43, 55, 67, 84], DRIVE = [10.5, 8.2, 6.4, 5.0, 4.0, 3.1]; + const PLAYER = { wheelbase: 2.7, grip: 12.5, aero: 0.0012, drag: 0.00039, roll: 0.25, brake: 13, accel: 1, radius: 1.5, nosBoost: 0.35, nosSeconds: 6, overheat: false }; + C.PLAYER = PLAYER; C.TOPS = TOPS; + C.newCar = (x, y, h) => ({ x, y, h, vx: 0, vy: 0, r: 0, steer: 0, gear: 0, clutch: 0, bonus: 0, perfect: 0, nos: 1, nosOn: 0, heat: 0, blown: 0, tires: 0, hit: 0, drift: 0, over: 0 }); + const NOS_MIN_MPH = 10; // EngineRacer.cpp:926 Tweak_MinSpeedForNosMPH; half of it keeps nitrous engaged (:950) + // Over-rev heat, EngineRacer.cpp:1340-1345: +0.45/s on the limiter, -0.1/s otherwise, blown at 1, -25% torque from 0.6. + const HEAT_UP = 0.45, HEAT_DOWN = -0.1, HEAT_PENALTY = 0.6, HEAT_TORQUE = 0.75; + const CLUTCH = 0.25, CLUTCH_FIRST = 0.05; // EngineRacer.cpp:34-35 + C.steerRange = mph => lookup(STEER_RANGE, mph, 160); + C.tireFactor = c => 1 - 0.7 * (c.tires / 4); // SuspensionRacer.cpp:1569 Tweak_BlownTireTraction 0.3 on all four + // One step. inp: {thr, brk, steer in [-1,1] (+ = left), hb, nos, up, down, manual, reverse, sbGrip}. dt is world time. + C.carStep = (c, inp, dt, P = PLAYER) => { + const ch = Math.cos(c.h), sh = Math.sin(c.h); + let vf = c.vx * ch + c.vy * sh, vl = -c.vx * sh + c.vy * ch; + const speed = Math.hypot(vf, vl), mph = speed / C.MPH, tire = C.tireFactor(c); + // steering: input slews, range comes from the speed table + const rate = speed < 15 ? 7 : speed < 40 ? 5 : 3.6, want = clamp(inp.steer, -1, 1); + c.steer += clamp(want - c.steer, -rate * dt, rate * dt); + const range = lookup(STEER_RANGE, mph, 160) * (inp.hb || inp.brk ? BRAKE_STEER : 1), delta = c.steer * range * Math.PI / 180; + const grip0 = (P.grip + P.aero * speed * speed + (inp.sbGrip || 0)) * tire; + let target = vf * Math.tan(delta) / P.wheelbase, rmax = grip0 * 1.05 / Math.max(speed, 3); + if (inp.hb) rmax *= 1.9; + target = clamp(target, -rmax, rmax); + c.r += (target - c.r) * Math.min(1, dt * 9); + c.h += c.r * dt; + // gearbox and drive + if (c.clutch > 0) c.clutch = Math.max(0, c.clutch - dt); + if (c.bonus > 0) c.bonus = Math.max(0, c.bonus - dt); + const u = Math.max(vf, 0) / TOPS[c.gear]; + if (inp.manual) { + if (inp.up && c.gear < 5) { const perfect = u >= 0.88 && u <= 0.99; c.clutch = perfect ? CLUTCH_FIRST : CLUTCH; if (perfect) { c.bonus = 1; c.perfect++; } c.gear++; } + else if (inp.down && c.gear > 0) { c.gear--; c.clutch = CLUTCH; } + } else if (c.clutch <= 0) { + if (u > 0.97 && c.gear < 5) { c.clutch = c.gear === 0 ? CLUTCH_FIRST : CLUTCH; c.gear++; } + else if (c.gear > 0 && vf < TOPS[c.gear - 1] * 0.82) c.gear--; + } + // nitrous, EngineRacer::DoNos + let boost = 1; + const engaged = !!inp.nos && inp.thr > 0 && c.nos > 0 && !c.blown && (mph >= NOS_MIN_MPH || (c.nosOn && mph >= NOS_MIN_MPH / 2)); + if (engaged) { c.nos = Math.max(0, c.nos - dt / P.nosSeconds); boost = 1 + P.nosBoost; c.nosOn = 1; } + else { c.nosOn = 0; if (speed > 10) c.nos = Math.min(1, c.nos + dt * (speed > 50 ? 0.07 : 0.035)); } + const uNow = Math.max(vf, 0) / TOPS[c.gear], limiter = uNow >= 1; + c.over = limiter && inp.thr > 0 ? 1 : 0; + if (P.overheat && c.gear > 0) { c.heat = Math.max(0, c.heat + (c.over ? HEAT_UP : HEAT_DOWN) * dt); if (c.heat >= 1) c.blown = 1; } + let drive = 0; + if (!c.blown && c.clutch <= 0 && inp.thr > 0) { + const curve = uNow < 0.35 ? 0.75 + 0.25 * uNow / 0.35 : uNow < 0.9 ? 1 : uNow < 1 ? 1 - (uNow - 0.9) * 2 : 0; + drive = DRIVE[c.gear] * curve * inp.thr * boost * P.accel * tire * (c.heat > HEAT_PENALTY ? HEAT_TORQUE : 1) * (c.bonus > 0 ? 1.1 : 1); + } + // re-express velocity in the turned frame; rear tyres scrub the lateral part (handbrake drops them) + const ch2 = Math.cos(c.h), sh2 = Math.sin(c.h); + vf = c.vx * ch2 + c.vy * sh2; vl = -c.vx * sh2 + c.vy * ch2; + let ax = drive - P.drag * vf * Math.abs(vf) - P.roll * (Math.abs(vf) > 0.2 ? Math.sign(vf) : 0); + if (inp.brk) { if (vf > 0.3) ax -= P.brake * tire; else if (inp.reverse) ax -= 4.5; } + if (inp.hb && Math.abs(vf) > 0.3) ax -= 6 * Math.sign(vf); + const longLim = grip0 * 1.1; ax = clamp(ax, -longLim, longLim); + const used = Math.min(0.75, Math.abs(ax) / longLim * 0.55), latCap = grip0 * (inp.hb ? 0.42 : 1) * (1 - used); + vf += ax * dt; + if (inp.brk && !inp.reverse && vf < 0) vf = 0; + const dl = clamp(vl, -latCap * dt, latCap * dt); vl -= dl; + c.drift = Math.abs(vl) > 2.5 ? 1 : 0; + if (c.drift) vf -= Math.sign(vf) * Math.min(Math.abs(vf), 0.8 * dt); + c.vx = vf * ch2 - vl * sh2; c.vy = vf * sh2 + vl * ch2; + c.x += c.vx * dt; c.y += c.vy * dt; + // walls: everything outside the road union + const q = C.road(c.x, c.y), over = q.d + 1; + c.hit = 0; + if (over > 0) { + c.x -= q.nx * over; c.y -= q.ny * over; + const vn = c.vx * q.nx + c.vy * q.ny; + if (vn > 0) { + c.vx -= 1.25 * vn * q.nx; c.vy -= 1.25 * vn * q.ny; + const scrub = 1 - Math.min(0.3, vn * 0.012); c.vx *= scrub; c.vy *= scrub; c.hit = vn; if (vn > 3) c.r *= 0.3; + } else { c.vx *= 1 - 0.3 * dt; c.vy *= 1 - 0.3 * dt; } + } + }; + C.speed = c => Math.hypot(c.vx, c.vy); + // Point-mass speed profile along a route: curvature limit with a backward braking pass. grip follows + // AIActionRace::GetPotentialSpeed (grip scaled by skill); the player's controller uses the player's own numbers. + const profiles = new Map(); + C.profile = (R, grip, aero, brake, top) => { + const key = R.name + '|' + [grip, aero, brake, top].map(v => v.toFixed(3)).join('|'); + let v = profiles.get(key); if (v) return v; + v = new Float64Array(R.n); + // Curvature is taken over +-6 m: a car starts turning before the arc begins and has not finished when it ends. + for (let i = 0; i < R.n; i++) { + let k = 0; for (let j = -3; j <= 3; j++) { const m = R.loop ? (i + j + R.n) % R.n : clamp(i + j, 0, R.n - 1); k = Math.max(k, Math.abs(R.k[m])); } + // k * v^2 = grip + aero v^2 -> v^2 = grip / (k - aero) + v[i] = k > aero + 1e-5 ? Math.min(top, Math.sqrt(grip / (k - aero))) : top; + } + const passes = R.loop ? 2 : 1; + for (let p = 0; p < passes; p++) for (let i = R.n - 1; i >= 0; i--) { + const j = i + 1 < R.n ? i + 1 : R.loop ? 0 : i; + const lim = Math.sqrt(v[j] * v[j] + 2 * brake * R.ds); if (lim < v[i]) v[i] = lim; + } + profiles.set(key, v); return v; + }; + // Drive force at a speed in the gear an automatic box would hold: the same curve as carStep. Rivals and estimates use it. + C.driveAt = u => { let gear = 0; while (gear < 5 && u > TOPS[gear] * 0.97) gear++; const un = u / TOPS[gear], curve = un < 0.35 ? 0.75 + 0.25 * un / 0.35 : un < 0.9 ? 1 : Math.max(0, 1 - (un - 0.9) * 2); return DRIVE[gear] * curve; }; + // Speed a car can actually carry along a stretch: forward pass over the limits. The profile alone reads top speed on the exit of any corner. + C.reachable = (R, v, s0, len, P = PLAYER, v0 = 0) => { + const out = []; let u = v0; + for (let s = 0; s <= len; s += R.ds) { const a = Math.max(0, C.driveAt(u) * P.accel - P.drag * u * u - P.roll); u = Math.min(C.profileAt(R, v, s0 + s), Math.sqrt(u * u + 2 * a * R.ds)); out.push(u); } + return out; + }; + // Time for the car to cover a stretch: the profile's corner and braking limits with the gearbox's acceleration on top. + C.driveTime = (R, v, s0, len, P = PLAYER, v0 = 0) => { + let t = 0, u = v0; + for (let s = 0; s < len; s += R.ds) { + const vmax = C.profileAt(R, v, s0 + s), a = Math.max(0.2, C.driveAt(u) * P.accel - P.drag * u * u - P.roll); + u = Math.min(vmax, Math.sqrt(u * u + 2 * a * R.ds)); + t += R.ds / Math.max(u, 3); + } + return t; + }; + C.profileAt = (R, v, s) => { let i = Math.round(s / R.ds); if (R.loop) { i %= R.n; if (i < 0) i += R.n; } else i = clamp(i, 0, R.n - 1); return v[i]; }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/nfsmw_remake/page.js b/environments/games/web/games/nfsmw_remake/page.js new file mode 100644 index 0000000000000000000000000000000000000000..15efa5035cf621d8e32f9cc8666348c607eea8b7 --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/page.js @@ -0,0 +1,135 @@ +/* Page-only layer for the human play page. Not listed in manifest.json: the public interface, the recordings and the source + fingerprint never load it, so nothing here can change a fight. The shared shell (_native/shell.js) owns the loop, the session, + the keys, and since 2026-11-08 also: restart after a result (click on the picture, Enter, R; not after a replay), focus back + to the picture after a button, a frame loop that survives a throw from M.draw (pause + reason in the status bar), and the + Module.pointerLock opt-out. This file only adds what the shell does not do ("only one race"): + - a panel over the picture before a race, while paused and after the result, with buttons that stay on the picture + (retry / next event), the event's control hints, and a hint for the reason a race was lost; + - N for the next event, Enter to start from the idle panel and to resume from the pause panel; + - focus back to the picture after picking an event or a tier in the lists, and when a game key is pressed on a button; + - pointer lock off (this game never uses the mouse; a locked cursor could not reach the buttons); + - a new 3D scene after a renderer failure: the shell pauses the race, but the old scene keeps its dead WebGL context. + It drives the shell only through its own buttons, so a race started here is exactly a race started from the toolbar. + Restart keys and clicks are never handled twice: Enter / R after a result are the shell's (its capture listener runs first + and stops the event), and the panel covers the canvas, so the shell's canvas click and the panel's click never both fire. */ +(function () { + 'use strict'; + const M = window.GAME_MODULE, $ = s => document.querySelector(s), canvas = $('canvas'), panel = $('#nfs-panel'); + if (!M || !canvas || !panel) return; + M.pointerLock = false; // read by the shell's double-click handler (shell.js, 2026-11-08) + let game = null, resultAt = 0, shown = '', broken = null, retryAt = 0; + const HINT = { + tollbooth: ['Passing a tollbooth adds time; you lose when the timer reaches zero', 'Release W or tap S before turns; use Shift for nitrous on straights'], + drag: ['Manual gears: press K to upshift when the RPM needle reaches green (L downshifts)', 'Hold W during the countdown to keep RPM in the green launch zone', 'Use A / D to change lanes and avoid traffic. Staying in the red zone blows the engine; a high-speed crash totals the car'], + speedtrap: ['Your speed is added at each checkpoint; beat the rival’s total to win', 'Use nitrous (Shift) 2–3 seconds before a speed checkpoint'], + knockout: ['The last-place driver is eliminated each lap; stay ahead', 'J toggles slow motion for stronger grip; use it before entering a turn'], + pursuit: ['Build the required bounty while police can see you, then lose them', 'The escape meter starts filling after seven seconds out of sight; nearby cops can bust you at low speed', 'Drive through orange pursuit breakers to crush nearby police cars'], + street_champion: ['Reach the final leg’s finish before your rival', 'Avoid arrest too: keep moving and never stop beside police cars'], + }; + const TIP = { + 'drag|gap': 'Drag races use manual gears: press K when RPM enters green. Holding only W leaves you in first gear.', + 'drag|blown': 'Staying in the red zone overheats and blows the engine. Upshift with K promptly or release W briefly.', + 'drag|totaled': 'A high-speed collision totals the car. Change lanes with A / D before reaching traffic.', + 'tollbooth|time': 'Ease off the throttle before turns and use nitrous (Shift) on straights. Hitting walls wastes the most time.', + 'speedtrap|score': 'Save nitrous for speed checkpoints and cross each one as fast as possible.', + 'knockout|knocked': 'Press J before a turn for slow motion, better grip, and easier passing.', + 'pursuit|busted': 'The bust meter rises only when police are close and you are moving slowly. Keep moving and use orange pursuit breakers.', + 'street_champion|busted': 'The bust meter rises only when police are close and you are moving slowly. Keep your speed up.', + 'street_champion|gap': 'Your rival uses nitrous. Hold Shift on straights and take the inside line through turns.', + }; + const LOSS = { time: 'Time expired', gap: 'Rival reached the finish first', blown: 'Engine blown', totaled: 'Crash wreck', busted: 'Busted', knocked: 'Eliminated in last place', score: 'Lost on total score' }; + const nameOf = id => (M.cases.find(c => c.id === id) || { name: id }).name; + const running = () => $('#pause').textContent === 'Pause'; + // Replay or race: the shell keeps that in a closure. Its status line says which one started (a replay: 'Replay verified…'; + // a race or the demo: 'Recording this match…' / 'Scripted demo running…'), so a flag follows only those two kinds of message; anything else the + // status shows later (an export, an error) leaves it alone. After a replay the shell does not restart on Enter / R or on a + // click, so neither does the panel. (2026-11-08: reading the status text directly broke after an export rewrote it.) + let inReplay = false; + new MutationObserver(() => { const t = $('#status').textContent; if (/^Replay verified/.test(t)) inReplay = true; else if (/^(Recording this match|Scripted demo running)/.test(t)) inReplay = false; }) + .observe($('#status'), { childList: true, characterData: true, subtree: true }); + const replayMode = () => inReplay; + // A different event picked in the list after a result or while paused: the panel offers that event, not the old race. + const state = () => !game ? 'idle' : running() ? 'run' : $('#case').value !== game.id ? 'idle' : game.outcome ? 'result' : game.t > 0 ? 'paused' : 'idle'; + const again = () => $('#start').click(); + const resume = () => $('#pause').click(); + function next() { const s = $('#case'); s.selectedIndex = (s.selectedIndex + 1) % s.options.length; s.dispatchEvent(new Event('change')); again(); } + const esc = s => String(s).replace(/[&<>]/g, ch => ({ '&': '&', '<': '<', '>': '>' })[ch]); + + // ---- renderer failure (WebGL context lost). The shell catches a throw from M.draw and pauses the race with the reason in the + // status bar; the old scene, though, keeps its dead context and would fail on every frame. Here the scene is closed so the + // next draw builds a new one with a new context, at most once a second, and the error is passed on to the shell. ---- + const draw0 = M.draw; + let lastT = -1; + M.draw = function (g, ctx) { + const advanced = g === game && g.t !== lastT; // the race ran since the last picture of this game + game = g; lastT = g.t; + if (broken && performance.now() < retryAt) { + paintBroken(ctx); + // Resumed before the new scene is up: pause again through the shell's own lost-focus path (it pauses only a running race). + if (advanced) { window.dispatchEvent(new Event('blur')); $('#status').textContent = 'Rebuilding 3D scene. Please wait before resuming.'; } + return; + } + try { + draw0.call(this, g, ctx); + if (broken) { broken = null; shown = ''; $('#status').textContent = '3D scene restored. Press Enter or click Resume to continue.'; } + } catch (e) { + broken = String(e && e.message || e).slice(0, 120); retryAt = performance.now() + 1000; shown = ''; + try { M.closeRenderer(ctx); } catch (_) { /* a lost context cannot be cleaned further */ } + paintBroken(ctx); + throw e; // the shell's frame loop catches it: it pauses the race and shows the reason + } + }; + function paintBroken(ctx) { + ctx.fillStyle = '#0b1016'; ctx.fillRect(0, 0, 854, 480); ctx.fillStyle = '#ffd08a'; ctx.font = 'bold 20px "Microsoft YaHei",sans-serif'; ctx.textAlign = 'center'; + ctx.fillText('Screen error. Rebuilding 3D scene…', 427, 220); ctx.font = '13px Consolas,monospace'; ctx.fillStyle = '#a8b4c0'; ctx.fillText(broken || '', 427, 250); ctx.textAlign = 'left'; + } + + function render(st) { + const k = st === 'idle' ? ($('#case').value || '').split('/')[1] : game.key, title = st === 'idle' ? nameOf($('#case').value) : nameOf(game.id); + const hints = (HINT[k] || []).map(h => `
  • ${esc(h)}
  • `).join(''), base = '
  • W accelerate · S brake / reverse · A / D steer · Space handbrake · Shift nitrous · J slow motion · R reset
  • '; + let html = ''; + if (st === 'idle') html = `

    ${esc(title)}

      ${hints}${base}

    You can also click the screen to start

    `; + else if (st === 'paused') html = `

    ${broken ? 'Screen error; paused' : 'Paused'}

    ${broken ? '

    The 3D scene is rebuilding. When the picture returns, press Enter or click Resume.

    ' : ''}
      ${hints}${base}
    `; + else if (st === 'result' && replayMode()) { + html = `

    Replay Finished

    ${esc(title)} · ${(game.t / M.hz).toFixed(2)} seconds · Result: ${esc(game.outcome)}

    `; + } else if (st === 'result') { + const win = game.outcome === 'win', why = game.lossReason, tip = !win && TIP[k + '|' + why]; + html = `

    ${win ? 'Challenge complete' : game.outcome === 'timeout' ? 'Time up' : esc(LOSS[why] || 'Challenge Failed')}

    ${esc(title)} · ${(game.t / M.hz).toFixed(2)} seconds

    ${tip ? `

    Tip: ${esc(tip)}

    ` : ''}

    You can also click anywhere on the screen to retry

    `; + } + panel.querySelector('.nfs-card').innerHTML = html; + } + function tick() { + const st = state(); + if (st === 'result' && !resultAt) resultAt = performance.now(); + if (st !== 'result') resultAt = 0; + const tag = [st, $('#case').value, game && game.id, game && game.outcome, game && game.lossReason, !!broken, replayMode()].join('|'); + if (tag !== shown) { shown = tag; panel.hidden = st === 'run'; if (st !== 'run') render(st); } + requestAnimationFrame(tick); + } + panel.addEventListener('click', e => { + const b = e.target.closest('button'), st = state(); + if (b) { const a = b.dataset.act; if (a === 'again') again(); else if (a === 'next') next(); else if (a === 'resume') resume(); return; } + if (e.target.closest('.nfs-card') && st !== 'result') return; + if (st === 'result' && (replayMode() || performance.now() - resultAt < 600)) return; // after a replay: buttons only; and never a click meant for the race + if (st === 'paused') resume(); else again(); + }); + // A game key while a button has focus (reached with Tab): the shell ignores keys on a BUTTON, so the key would be lost. Move the + // focus to the picture first; this capture listener runs before the shell's own key listener, which then sees the canvas. + // Enter and Space keep their button meaning. + const GAME_KEYS = new Set(['KeyW', 'KeyA', 'KeyS', 'KeyD', 'ShiftLeft', 'ShiftRight', 'KeyJ', 'KeyK', 'KeyL', 'KeyQ', 'KeyE', 'KeyR', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight']); + window.addEventListener('keydown', e => { const a = document.activeElement; if (a && a.tagName === 'BUTTON' && GAME_KEYS.has(e.code)) canvas.focus(); }, true); + // Enter / R after a result are the shell's; N (next event), Enter on the idle panel and Enter on the pause panel are added here. + window.addEventListener('keydown', e => { + const tag = document.activeElement && document.activeElement.tagName; + if (tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA' || (tag === 'BUTTON' && (e.code === 'Enter' || e.code === 'Space')) || e.repeat) return; + const st = state(), enter = e.code === 'Enter' || e.code === 'NumpadEnter'; + let act = null; + if (st === 'result' && e.code === 'KeyN' && performance.now() - resultAt >= 600) act = next; + else if (st === 'idle' && enter) act = again; + else if (st === 'paused' && enter) act = resume; + if (act) { e.preventDefault(); e.stopImmediatePropagation(); act(); } + }, true); + for (const id of ['#case', '#difficulty']) $(id).addEventListener('change', () => { shown = ''; canvas.focus(); }); + $('#seed').addEventListener('change', () => { shown = ''; }); // typing a seed: keep the focus in the box + requestAnimationFrame(tick); +})(); diff --git a/environments/games/web/games/nfsmw_remake/renderer3d.js b/environments/games/web/games/nfsmw_remake/renderer3d.js new file mode 100644 index 0000000000000000000000000000000000000000..c850ea9f050d84dd863b669fe607e4c847a671fa --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/renderer3d.js @@ -0,0 +1,385 @@ +/* NFS Most Wanted events - WebGL renderer (three.js r160, vendored): third-person chase view of an original procedural city. + Everything is built from code at start-up: road ribbons from the route samples, barriers along the real collision edge of + the road union (what you see is what you hit), instanced buildings, palms, lamps, and original low-poly cars. A render is a + pure function of the game state; the only local randomness is a fixed-seed generator for scenery. No original game art. + 2026-11-08: police light bars on every live cop (roadblocks flash too), blinking barrier + lamps and spike-strip beacons, rival markers and rival nitrous flames, a light column over the next gate, glossy paint, + car head/tail light glows, street-lamp halos at night, sparks on impact, tyre smoke while sliding, camera shake on a hit, + the helicopter's spot on the ground. Particles are placed from the current state only (no history), so a frame is still a + pure function of the game state and the page, the recordings and the agent see the same picture. */ +(function (root) { + 'use strict'; + const T = root.THREE, M = root.NfsmwGame, C = M && M.C; + if (!T || !M) return; + const R3 = M.R3 = {}, byCanvas = new WeakMap(); + const STYLE = { // sky top, sky mid, horizon, sun colour, sun [azimuth, elevation], hemisphere sky/ground/intensity, sun intensity, fog, window glow, lamp glow + tollbooth: { sky: ['#2a4f8c', '#e8926a', '#ffd9a0'], sun: 0xffc48a, dir: [-0.75, 0.18], hemi: [0xffe2c4, 0x51402f, 1.25], sunI: 2.6, fog: [0xefb48c, 240, 1300], win: 0.55, lamp: 0.5 }, + drag: { sky: ['#2f74c8', '#8fc3ea', '#e6f1f2'], sun: 0xfff4e0, dir: [0.4, 0.7], hemi: [0xdcebff, 0x8a8066, 1.5], sunI: 2.5, fog: [0xd6e6ee, 500, 2400], win: 0, lamp: 0 }, + speedtrap: { sky: ['#3c6fb4', '#a7c6dc', '#f4e6cf'], sun: 0xffedd0, dir: [0.7, 0.42], hemi: [0xe7eeff, 0x6f6a52, 1.4], sunI: 2.5, fog: [0xdfe2d8, 320, 1600], win: 0.05, lamp: 0 }, + knockout: { sky: ['#070b1e', '#17204a', '#5a3b66'], sun: 0x9fb4ff, dir: [0.3, 0.6], hemi: [0x5f6fa8, 0x201a26, 1.15], sunI: 0.75, fog: [0x2a2542, 90, 620], win: 1.5, lamp: 1.5 }, + pursuit: { sky: ['#141a44', '#7a3f73', '#ff9a62'], sun: 0xff9d73, dir: [-0.6, 0.08], hemi: [0xb09ac8, 0x2b2430, 1.15], sunI: 1.5, fog: [0x8a5a70, 170, 950], win: 1.15, lamp: 1.2 }, + street_champion: { sky: ['#222a3e', '#6e7a8c', '#d9cdb4'], sun: 0xffe2bc, dir: [0.8, 0.22], hemi: [0xc6d0dc, 0x4c4a44, 1.3], sunI: 1.6, fog: [0xaeb0ac, 170, 1000], win: 0.5, lamp: 0.6 }, + }; + const rngOf = seed => () => { seed = (seed + 0x6D2B79F5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; + const canvasTex = (w, h, paint, repeat, srgb = true) => { const c = document.createElement('canvas'); c.width = w; c.height = h; paint(c.getContext('2d'), w, h); const t = new T.CanvasTexture(c); if (repeat) t.wrapS = t.wrapT = T.RepeatWrapping; t.anisotropy = 4; if (srgb) t.colorSpace = T.SRGBColorSpace; return t; }; + const qv = (x, y, z, v) => (v || new T.Vector3()).set(x, z, -y); // sim (x, y, up) -> three (x, up, -y); heading h is rotation.y + const speckle = (q, w, h, n, a, seed) => { const r = rngOf(seed); for (let i = 0; i < n; i++) { const v = r() < 0.5 ? 255 : 0; q.fillStyle = `rgba(${v},${v},${v},${a * r()})`; q.fillRect(r() * w, r() * h, 1 + r() * 2, 1 + r() * 2); } }; + // Non-indexed merge with per-part vertex colours: every car is one draw call. + function merge(parts) { + let n = 0; const list = parts.map(([g, col]) => { const q = g.index ? g.toNonIndexed() : g; n += q.attributes.position.count; return [q, new T.Color(col)]; }); + const pos = new Float32Array(n * 3), nor = new Float32Array(n * 3), colr = new Float32Array(n * 3); let o = 0; + for (const [q, c] of list) { const m = q.attributes.position.count; pos.set(q.attributes.position.array, o * 3); nor.set(q.attributes.normal.array, o * 3); for (let i = 0; i < m; i++) { colr[(o + i) * 3] = c.r; colr[(o + i) * 3 + 1] = c.g; colr[(o + i) * 3 + 2] = c.b; } o += m; } + const g = new T.BufferGeometry(); g.setAttribute('position', new T.BufferAttribute(pos, 3)); g.setAttribute('normal', new T.BufferAttribute(nor, 3)); g.setAttribute('color', new T.BufferAttribute(colr, 3)); return g; + } + const moved = (g, x, y, z, rx = 0, ry = 0, rz = 0) => { const q = g.clone(); if (rx || ry || rz) q.rotateX(rx).rotateY(ry).rotateZ(rz); q.translate(x, y, z); q.computeVertexNormals(); return q; }; + const boxG = (x, y, z, w, h, d) => moved(new T.BoxGeometry(w, h, d), x, y, z); + // Side profile extruded across the car; +X is forward. L = length, W = width. `pts` run around the silhouette. + const profile = (pts, W) => { const s = new T.Shape(); pts.forEach((p, i) => i ? s.lineTo(p[0], p[1]) : s.moveTo(p[0], p[1])); const g = new T.ExtrudeGeometry(s, { depth: W, bevelEnabled: false, curveSegments: 1 }); g.translate(0, 0, -W / 2); g.computeVertexNormals(); return g; }; + const CAR_SHAPES = { + // Original wedge coupe, fastback sedan, tall van, police interceptor: silhouettes drawn for this project, no real vehicle. + coupe: { w: 1.86, body: [[-2.2, 0.34], [2.25, 0.3], [2.3, 0.56], [1.05, 0.82], [-1.9, 0.92], [-2.25, 0.86]], glass: [[0.82, 0.8], [0.05, 1.2], [-0.95, 1.2], [-1.75, 0.9]], wing: true }, + sedan: { w: 1.82, body: [[-2.3, 0.34], [2.25, 0.34], [2.3, 0.68], [1.0, 0.9], [-1.9, 0.96], [-2.32, 0.9]], glass: [[0.92, 0.88], [0.2, 1.38], [-1.2, 1.38], [-1.85, 0.94]] }, + van: { w: 1.95, body: [[-2.5, 0.38], [2.4, 0.38], [2.45, 0.9], [1.75, 1.08], [1.35, 1.9], [-2.5, 2.0]], glass: [[1.74, 1.06], [1.36, 1.72], [0.4, 1.76], [0.4, 1.06]] }, + cop: { w: 1.88, body: [[-2.35, 0.34], [2.35, 0.32], [2.4, 0.66], [1.05, 0.9], [-1.95, 0.96], [-2.35, 0.9]], glass: [[0.9, 0.88], [0.2, 1.34], [-1.15, 1.34], [-1.88, 0.94]] }, + }; + function carGeometry(kind) { + const S = CAR_SHAPES[kind], W = S.w, parts = [[profile(S.body, W), 0xffffff], [profile(S.glass, W - 0.14), 0x1c2733]]; + parts.push([boxG(0, 0.26, 0, 4.1, 0.14, W - 0.1), 0x15151a]); + for (const [x, z] of [[1.42, W / 2 - 0.12], [1.42, -W / 2 + 0.12], [-1.42, W / 2 - 0.12], [-1.42, -W / 2 + 0.12]]) { parts.push([moved(new T.CylinderGeometry(0.36, 0.36, 0.26, 12), x, 0.36, z, Math.PI / 2), 0x121215]); parts.push([moved(new T.CylinderGeometry(0.2, 0.2, 0.27, 8), x, 0.36, z, Math.PI / 2), 0xb9bdc4]); } + if (S.wing) { parts.push([boxG(-2.05, 1.14, 0, 0.42, 0.05, W - 0.1), 0xffffff]); parts.push([boxG(-2.05, 1.0, 0.62, 0.2, 0.26, 0.06), 0x24242a], [boxG(-2.05, 1.0, -0.62, 0.2, 0.26, 0.06), 0x24242a]); } + if (kind === 'cop') { parts.push([boxG(0.1, 0.66, W / 2 + 0.002, 1.7, 0.42, 0.01), 0xf4f4f4], [boxG(0.1, 0.66, -W / 2 - 0.002, 1.7, 0.42, 0.01), 0xf4f4f4]); parts.push([boxG(-0.45, 1.42, 0, 0.3, 0.1, 1.2), 0x22232a]); parts.push([boxG(2.42, 0.42, 0, 0.12, 0.34, W * 0.7), 0x18181c]); } + // 2026-11-08 details: side mirrors, a dark lower body line, front splitter, twin exhaust tips, number plate recess (original shapes) + if (kind !== 'van') { + const tip = new T.CylinderGeometry(0.07, 0.07, 0.16, 8); + parts.push([boxG(0.62, 0.86, W / 2 + 0.08, 0.16, 0.1, 0.16), 0x15151a], [boxG(0.62, 0.86, -W / 2 - 0.08, 0.16, 0.1, 0.16), 0x15151a]); + parts.push([boxG(0, 0.37, W / 2 - 0.02, 3.4, 0.1, 0.06), 0x202024], [boxG(0, 0.37, -W / 2 + 0.02, 3.4, 0.1, 0.06), 0x202024]); + parts.push([boxG(2.26, 0.3, 0, 0.18, 0.05, W - 0.2), 0x121214]); + parts.push([moved(tip, -2.3, 0.36, 0.42, 0, 0, Math.PI / 2), 0xc8ccd2], [moved(tip, -2.3, 0.36, -0.42, 0, 0, Math.PI / 2), 0xc8ccd2]); + parts.push([boxG(-2.26, 0.56, 0, 0.03, 0.14, 0.5), 0xe8e8e0]); + } + return merge(parts); + } + function lampGeometry(kind) { + const W = CAR_SHAPES[kind].w, x = kind === 'van' ? 2.42 : 2.3, y = kind === 'van' ? 0.72 : 0.5, b = kind === 'van' ? -2.52 : -2.3, by = kind === 'van' ? 0.95 : 0.74; + return merge([[boxG(x, y, W * 0.34, 0.06, 0.13, 0.4), 0xfff4d0], [boxG(x, y, -W * 0.34, 0.06, 0.13, 0.4), 0xfff4d0], [boxG(b, by, W * 0.32, 0.06, 0.12, 0.5), 0xff2614], [boxG(b, by, -W * 0.32, 0.06, 0.12, 0.5), 0xff2614]]); + } + const PAINT = [0x2c6fd1, 0xc33a2c, 0xd9d9d6, 0x1f2024, 0x4c8c5a, 0xd9a73a]; + class Scene { + constructor(canvas) { + this.canvas = canvas; this.res = []; this.times = []; this.ready = false; this.error = null; this.closed = false; this.pools = {}; this.skies = {}; + this.view = document.createElement('canvas'); this.view.width = 854; this.view.height = 480; + const r = this.renderer = new T.WebGLRenderer({ canvas: this.view, antialias: true, preserveDrawingBuffer: true, powerPreference: 'low-power' }); + r.setPixelRatio(1); r.setSize(854, 480, false); r.outputColorSpace = T.SRGBColorSpace; r.toneMapping = T.ACESFilmicToneMapping; r.toneMappingExposure = 1.0; + this.view.addEventListener('webglcontextlost', e => { e.preventDefault(); this.ready = false; this.error = 'WebGL context lost'; }); + this.world = new T.Scene(); this.world.fog = new T.Fog(0xffffff, 200, 1200); + this.camera = new T.PerspectiveCamera(58, 854 / 480, 0.5, 3200); + // Rear-view mirror: a second camera on the roof looking back, drawn into a strip at the top centre of the same frame. + // Shown only where something can come from behind (police events, rivals); MIRROR is that strip in canvas pixels. + this.mirrorCam = new T.PerspectiveCamera(50, 260 / 62, 0.5, 3200); this.mirrorRect = [297, 64, 557, 126]; this.mirrorOn = false; + this.hemi = new T.HemisphereLight(0xffffff, 0x444444, 1); this.world.add(this.hemi); + this.sun = new T.DirectionalLight(0xffffff, 2); this.world.add(this.sun); + this.buildSky(); this.buildGround(); this.buildRoads(); this.buildCity(); this.buildCars(); this.buildProps(); this.buildFx(); this.buildChevrons(); + } + keep(x) { this.res.push(x); return x; } + lam(o) { return this.keep(new T.MeshLambertMaterial(o)); } + paint(color) { return this.keep(new T.MeshPhongMaterial({ color, vertexColors: true, shininess: 60, specular: 0x4a4a4a })); } + basic(o) { return this.keep(new T.MeshBasicMaterial(o)); } + buildSky() { this.sky = new T.Mesh(this.keep(new T.SphereGeometry(2600, 20, 12)), this.basic({ side: T.BackSide, fog: false, depthWrite: false })); this.sky.renderOrder = -10; this.world.add(this.sky); } + skyTex(key) { + if (this.skies[key]) return this.skies[key]; + const st = STYLE[key], t = canvasTex(1024, 512, (q, w, h) => { + const g = q.createLinearGradient(0, 0, 0, h / 2); g.addColorStop(0, st.sky[0]); g.addColorStop(0.72, st.sky[1]); g.addColorStop(1, st.sky[2]); q.fillStyle = g; q.fillRect(0, 0, w, h); + const sx = ((Math.atan2(st.dir[0], Math.sqrt(1 - st.dir[0] * st.dir[0])) / (2 * Math.PI) + 1.0) % 1) * w, sy = h / 2 - st.dir[1] * h * 0.5, c = new T.Color(st.sun).getStyle(); + for (const ox of [-w, 0, w]) { const glow = q.createRadialGradient(sx + ox, sy, 2, sx + ox, sy, 170); glow.addColorStop(0, 'rgba(255,250,235,.95)'); glow.addColorStop(0.08, c.replace('rgb', 'rgba').replace(')', ',.65)')); glow.addColorStop(1, 'rgba(255,200,150,0)'); q.fillStyle = glow; q.fillRect(0, 0, w, h / 2); } + const rr = rngOf(key.length * 977 + 5); const nightly = st.win > 1; + if (nightly) for (let i = 0; i < 260; i++) { q.fillStyle = `rgba(255,255,255,${0.2 + rr() * 0.7})`; q.fillRect(rr() * w, rr() * h * 0.36, 1, 1); } + for (let i = 0; i < 44; i++) { const cx = rr() * w, cy = h * (0.2 + rr() * 0.26), cw = 40 + rr() * 150; q.fillStyle = nightly ? 'rgba(120,110,160,.08)' : 'rgba(255,240,226,.14)'; for (let j = 0; j < 7; j++) { q.beginPath(); q.ellipse(cx + (rr() - 0.5) * cw, cy + (rr() - 0.5) * 7, cw * (0.2 + rr() * 0.3), 3 + rr() * 6, 0, 0, 7); q.fill(); } } + for (const [base, amp, col] of [[0.5, 26, st.sky[1]], [0.502, 14, st.sky[0]]]) { q.fillStyle = col; q.globalAlpha = 0.55; q.beginPath(); q.moveTo(0, h); for (let x = 0; x <= w; x += 6) q.lineTo(x, h * base - amp * (0.55 + 0.45 * Math.sin(x * 0.012 + base * 40) * Math.sin(x * 0.031))); q.lineTo(w, h); q.fill(); q.globalAlpha = 1; } + q.fillStyle = st.sky[2]; q.fillRect(0, h / 2, w, h / 2); + }); + return (this.skies[key] = this.keep(t)); + } + buildGround() { + const grass = this.keep(canvasTex(256, 256, (q, w, h) => { q.fillStyle = '#6d7a52'; q.fillRect(0, 0, w, h); speckle(q, w, h, 3200, 0.16, 7); for (let i = 0; i < 12; i++) { q.fillStyle = 'rgba(120,108,70,.1)'; q.beginPath(); q.arc(i * 37 % w, i * 91 % h, 20 + i * 2, 0, 7); q.fill(); } }, true)); grass.repeat.set(70, 40); + const land = new T.Mesh(this.keep(new T.PlaneGeometry(3600, 1650)), this.lam({ map: grass })); land.rotation.x = -Math.PI / 2; qv(0, 280, -0.06, land.position); this.world.add(land); + const sand = new T.Mesh(this.keep(new T.PlaneGeometry(3600, 26)), this.lam({ color: 0xd8c394 })); sand.rotation.x = -Math.PI / 2; qv(0, -558, -0.05, sand.position); this.world.add(sand); + this.seaTex = this.keep(canvasTex(256, 256, (q, w, h) => { q.fillStyle = '#2d6f8f'; q.fillRect(0, 0, w, h); const r = rngOf(9); for (let i = 0; i < 240; i++) { q.fillStyle = `rgba(190,232,240,${0.04 + r() * 0.1})`; q.fillRect(r() * w, r() * h, 8 + r() * 34, 1); } }, true)); this.seaTex.repeat.set(26, 8); + const sea = new T.Mesh(this.keep(new T.PlaneGeometry(4400, 1700)), this.lam({ map: this.seaTex })); sea.rotation.x = -Math.PI / 2; qv(0, -1410, -1.4, sea.position); this.world.add(sea); + } + // A ribbon following samples [x, y]; `sides` gives the half width. v runs along the road in metres / tile length. + ribbon(pts, hw, closed, z, tile) { + const n = pts.length, N = closed ? n + 1 : n, pos = new Float32Array(N * 6), nor = new Float32Array(N * 6), uv = new Float32Array(N * 4), idx = []; let along = 0; + for (let i = 0; i < N; i++) { + const p = pts[i % n], a = pts[(i - 1 + n) % n], b = pts[(i + 1) % n], f = !closed && i === 0 ? p : a, t = !closed && i === n - 1 ? p : b, dx = t[0] - f[0], dy = t[1] - f[1], l = Math.hypot(dx, dy) || 1, nx = -dy / l, ny = dx / l; + if (i) along += Math.hypot(p[0] - pts[(i - 1) % n][0], p[1] - pts[(i - 1) % n][1]); + pos.set([p[0] + nx * hw, z, -(p[1] + ny * hw), p[0] - nx * hw, z, -(p[1] - ny * hw)], i * 6); nor.set([0, 1, 0, 0, 1, 0], i * 6); uv.set([0, along / tile, 1, along / tile], i * 4); + if (i < N - 1) idx.push(i * 2, i * 2 + 1, i * 2 + 2, i * 2 + 1, i * 2 + 3, i * 2 + 2); + } + const g = new T.BufferGeometry(); g.setAttribute('position', new T.BufferAttribute(pos, 3)); g.setAttribute('normal', new T.BufferAttribute(nor, 3)); g.setAttribute('uv', new T.BufferAttribute(uv, 2)); g.setIndex(idx); return this.keep(g); + } + buildRoads() { + const asphalt = (lanes, edge, yellow = true) => this.keep(canvasTex(256, 512, (q, w, h) => { + q.fillStyle = '#34363b'; q.fillRect(0, 0, w, h); speckle(q, w, h, 5200, 0.09, lanes * 13 + 1); + for (let i = 0; i < 3; i++) { q.fillStyle = 'rgba(16,16,18,.18)'; q.fillRect(w * (0.2 + i * 0.3), 0, 12, h); } + q.fillStyle = '#d8d6cc'; q.fillRect(edge, 0, 4, h); q.fillRect(w - edge - 4, 0, 4, h); + if (yellow) { q.fillStyle = '#d6a32e'; q.fillRect(w / 2 - 5, 0, 3, h); q.fillRect(w / 2 + 2, 0, 3, h); } else { q.fillStyle = '#d8d6cc'; for (let y = 0; y < h; y += 256) q.fillRect(w / 2 - 2, y, 4, 128); } + q.fillStyle = '#d8d6cc'; for (let k = 1; k < lanes; k++) { const u = (w / 2) * k / lanes; for (let y = 0; y < h; y += 256) { q.fillRect(w / 2 + u - 2, y, 4, 128); q.fillRect(w / 2 - u - 2, y, 4, 128); } } + }, true)); + const walkTex = this.keep(canvasTex(64, 64, (q, w, h) => { q.fillStyle = '#9d9a90'; q.fillRect(0, 0, w, h); speckle(q, w, h, 300, 0.1, 3); q.fillStyle = 'rgba(40,40,40,.28)'; q.fillRect(0, 0, w, 1); }, true)); + const walkMat = this.lam({ map: walkTex }), wallTex = this.keep(canvasTex(128, 32, (q, w, h) => { q.fillStyle = '#b7b4aa'; q.fillRect(0, 0, w, h); speckle(q, w, h, 300, 0.1, 21); q.fillStyle = 'rgba(30,30,32,.55)'; q.fillRect(0, h - 5, w, 5); for (let i = 0; i < 8; i++) { q.fillStyle = i % 2 ? '#c8452c' : '#e8e4da'; q.fillRect(i * 16, 2, 16, 6); } }, true)); + const wallMat = this.lam({ map: wallTex }), wallPos = [], wallUv = [], wallIdx = []; + const wall = (ax, ay, bx, by, len) => { const n = wallPos.length / 3, h = 1.05, low = -1.5; wallPos.push(ax, low, -ay, bx, low, -by, bx, h, -by, ax, h, -ay); wallUv.push(0, 0, len / 8, 0, len / 8, 1, 0, 1); wallIdx.push(n, n + 1, n + 2, n, n + 2, n + 3, n, n + 2, n + 1, n, n + 3, n + 2); }; + const edge = (pts, hw, closed) => { + for (let i = 0; i + (closed ? 0 : 1) < pts.length; i++) { + const p = pts[i], q = pts[(i + 1) % pts.length], dx = q[0] - p[0], dy = q[1] - p[1], l = Math.hypot(dx, dy) || 1, nx = -dy / l, ny = dx / l, mx = (p[0] + q[0]) / 2, my = (p[1] + q[1]) / 2; + for (const sgn of [1, -1]) if (C.road(mx + sgn * nx * (hw + 0.45), my + sgn * ny * (hw + 0.45)).d > 0.1) wall(p[0] + sgn * nx * hw, p[1] + sgn * ny * hw, q[0] + sgn * nx * hw, q[1] + sgn * ny * hw, l); + } + }; + for (const R of Object.values(C.routes)) { + const step = R.name === 'strip' ? 50 : 3, pts = []; for (let i = 0; i < R.n; i += step) pts.push([R.x[i], R.y[i]]); if (!R.loop) pts.push([R.x[R.n - 1], R.y[R.n - 1]]); + const tile = R.name === 'strip' ? 24 : 16, mesh = new T.Mesh(this.ribbon(pts, R.halfW, R.loop, R.name === 'downtown' ? 0.024 : 0.02, tile), this.lam({ map: asphalt(2, 9, R.name !== 'strip') })); this.world.add(mesh); + if (R.name !== 'strip') { const w = new T.Mesh(this.ribbon(pts, R.halfW + 4.5, R.loop, 0.006, 4), walkMat); this.world.add(w); } + edge(pts, R.halfW, R.loop); + } + const stMat = this.lam({ map: asphalt(1, 7) }); + for (const st of C.streets) { + const pts = []; for (let i = 0; i + 1 < st.length; i++) { const a = st[i], b = st[i + 1], L = Math.hypot(b[0] - a[0], b[1] - a[1]), m = Math.ceil(L / 6); for (let j = 0; j < m; j++) pts.push([a[0] + (b[0] - a[0]) * j / m, a[1] + (b[1] - a[1]) * j / m]); } pts.push(st[st.length - 1]); + this.world.add(new T.Mesh(this.ribbon(pts, C.streetW / 2, false, 0.012, 16), stMat)); this.world.add(new T.Mesh(this.ribbon(pts, C.streetW / 2 + 4, false, 0.004, 4), walkMat)); edge(pts, C.streetW / 2, false); + } + const g = new T.BufferGeometry(); g.setAttribute('position', new T.BufferAttribute(new Float32Array(wallPos), 3)); g.setAttribute('uv', new T.BufferAttribute(new Float32Array(wallUv), 2)); g.setIndex(wallIdx); g.computeVertexNormals(); this.keep(g); this.world.add(new T.Mesh(g, wallMat)); + } + buildCity() { + const r = rngOf(20051116), towers = { low: [], mid: [], tall: [] }, palms = [], lamps = []; + const facade = (cols, rows, lit, base) => { const paint = emit => (q, w, h) => { const rr = rngOf(cols * 31 + rows); q.fillStyle = emit ? '#000' : base; q.fillRect(0, 0, w, h); const cw = w / cols, ch = h / rows; for (let j = 0; j < rows; j++) for (let i = 0; i < cols; i++) { const on = rr() < lit; q.fillStyle = emit ? (on ? (rr() < 0.3 ? '#a8d8ff' : '#ffd48a') : '#000') : (on ? '#5a6878' : '#2c3644'); q.fillRect(i * cw + cw * 0.18, j * ch + ch * 0.2, cw * 0.64, ch * 0.6); } if (!emit) { q.fillStyle = '#3a3a3e'; q.fillRect(w - 8, 0, 8, 8); } else { q.fillStyle = '#000'; q.fillRect(w - 8, 0, 8, 8); } }; return this.lam({ map: this.keep(canvasTex(256, 256, paint(false))), emissive: 0xffffff, emissiveMap: this.keep(canvasTex(256, 256, paint(true))), emissiveIntensity: 1 }); }; + const X = C.bounds.X0, Y = C.bounds.Y0; + for (let y = -500; y < 960; y += 34) for (let x = -1320; x < 1320; x += 34) { + const px = x + (r() - 0.5) * 12, py = y + (r() - 0.5) * 12, w = 16 + r() * 16, d = 16 + r() * 16, gap = C.road(px, py).d - Math.hypot(w, d) / 2 - 4.5; if (gap < 0) continue; + if (C.road(px, py).d > 150) continue; + const down = Math.max(0, 1 - Math.hypot(px, py) / 480), h = 7 + r() * 10 + r() * r() * 90 * down + (r() < 0.04 ? 30 : 0); + (h < 16 ? towers.low : h < 36 ? towers.mid : towers.tall).push([px, py, w, h, d, r()]); + } + const box = new T.BoxGeometry(1, 1, 1); box.translate(0, 0.5, 0); const uv = box.attributes.uv; for (const i of [8, 9, 10, 11, 12, 13, 14, 15]) uv.setXY(i, 0.995, 0.995); this.keep(box); + this.mats = { win: [] }; const mk = (list, mat) => { const m = new T.InstancedMesh(box, mat, list.length), o = new T.Object3D(), c = new T.Color(); list.forEach((b, i) => { qv(b[0], b[1], 0, o.position); o.rotation.y = 0; o.scale.set(b[2], b[3], b[4]); o.updateMatrix(); m.setMatrixAt(i, o.matrix); c.setHSL(0.07 + b[5] * 0.1, 0.12 + b[5] * 0.18, 0.46 + b[5] * 0.34); m.setColorAt(i, c); }); this.world.add(m); this.mats.win.push(mat); this.keep(m); }; + mk(towers.low, facade(4, 3, 0.45, '#b9ad98')); mk(towers.mid, facade(6, 8, 0.4, '#a8a39a')); mk(towers.tall, facade(8, 22, 0.42, '#8f9aa8')); + const R = C.routes.coast; + for (let i = 0; i < R.n; i += 9) { const a = C.routeAt(R, i * R.ds), side = i % 18 ? 1 : -1, off = R.halfW + 2.6; const lx = a.x + a.nx * side * off, ly = a.y + a.ny * side * off; if (C.road(lx, ly).d > 0.6) (a.y < -300 || a.x > 700 ? palms : lamps).push([lx, ly, side * a.h]); } + for (const key of ['downtown']) { const D = C.routes[key]; for (let i = 0; i < D.n; i += 12) { const a = C.routeAt(D, i * D.ds), off = D.halfW + 2.2; for (const s of [1, -1]) { const lx = a.x + a.nx * s * off, ly = a.y + a.ny * s * off; if (C.road(lx, ly).d > 0.6) lamps.push([lx, ly, 0]); } } } + const inst = (geo, mat, list, sy = 1) => { const m = new T.InstancedMesh(this.keep(geo), mat, list.length), o = new T.Object3D(); list.forEach((p, i) => { qv(p[0], p[1], 0, o.position); o.rotation.y = p[2] || 0; const k = 0.85 + ((i * 7) % 5) * 0.08; o.scale.set(k, k * sy, k); o.updateMatrix(); m.setMatrixAt(i, o.matrix); }); this.world.add(this.keep(m)); return m; }; + const trunk = new T.CylinderGeometry(0.16, 0.3, 9, 6); trunk.translate(0, 4.5, 0); inst(trunk, this.lam({ color: 0x705a40 }), palms); + const fronds = []; for (let k = 0; k < 7; k++) { const g = new T.ConeGeometry(0.62, 4.6, 4); g.translate(0, 2.3, 0); g.rotateZ(-1.9); g.rotateY(k * Math.PI * 2 / 7); g.translate(0, 9, 0); fronds.push(g); } inst(merge(fronds.map(g => [g, 0xffffff])), this.lam({ color: 0x4a7a3c, vertexColors: true }), palms); + const pole = new T.CylinderGeometry(0.07, 0.1, 7.5, 5); pole.translate(0, 3.75, 0); inst(pole, this.lam({ color: 0x45484e }), lamps); + const head = new T.BoxGeometry(0.5, 0.12, 0.28); head.translate(0, 7.5, 0); this.lampMat = this.basic({ color: 0xffdca0 }); inst(head, this.lampMat, lamps); this.lampSpots = lamps; + const haloTex = this.keep(canvasTex(64, 64, (q, w, h) => { const g = q.createRadialGradient(32, 32, 1, 32, 32, 32); g.addColorStop(0, 'rgba(255,255,255,1)'); g.addColorStop(0.4, 'rgba(255,255,255,.28)'); g.addColorStop(1, 'rgba(255,255,255,0)'); q.fillStyle = g; q.fillRect(0, 0, w, h); })); this.haloTex = haloTex; + } + buildCars() { + this.carGeo = {}; this.lampGeo = {}; for (const k of Object.keys(CAR_SHAPES)) { this.carGeo[k] = this.keep(carGeometry(k)); this.lampGeo[k] = this.keep(lampGeometry(k)); } + this.lampMatCar = this.basic({ vertexColors: true }); + this.shadowTex = this.keep(canvasTex(64, 64, (q, w, h) => { const g = q.createRadialGradient(32, 32, 6, 32, 32, 32); g.addColorStop(0, 'rgba(0,0,0,.62)'); g.addColorStop(0.7, 'rgba(0,0,0,.38)'); g.addColorStop(1, 'rgba(0,0,0,0)'); q.fillStyle = g; q.fillRect(0, 0, w, h); })); + this.shadowMat = this.basic({ map: this.shadowTex, transparent: true, depthWrite: false }); this.shadowGeo = this.keep(new T.PlaneGeometry(5.6, 2.9)); this.shadowGeo.rotateX(-Math.PI / 2); + this.paints = PAINT.map(c => this.paint(c)); + this.playerMat = this.paint(0xe8701f); this.rivalMat = this.paint(0xc8cdd8); this.copMat = this.paint(0x17181d); + // Police light bar: two lamps per cop, swapped between a lit and a dark material every 8 ticks (red and blue out of phase). + this.barMat = { r1: this.basic({ color: 0xff2a3a }), r0: this.basic({ color: 0x3a0c10 }), b1: this.basic({ color: 0x3a78ff }), b0: this.basic({ color: 0x0c1438 }) }; + this.barGeo = this.keep(new T.BoxGeometry(0.34, 0.13, 0.52)); + this.halo = col => this.keep(new T.SpriteMaterial({ map: this.haloTex, color: col, blending: T.AdditiveBlending, depthWrite: false, transparent: true, fog: false })); + this.player = this.spawnCar('coupe', this.playerMat); + const flame = this.basic({ color: 0x7fc4ff, transparent: true, opacity: 0.85, blending: T.AdditiveBlending, depthWrite: false }); const cone = new T.ConeGeometry(0.13, 1.1, 8); cone.rotateZ(Math.PI / 2); this.keep(cone); this.flames = [0.45, -0.45].map(z => { const m = new T.Mesh(cone, flame); m.position.set(-2.82, 0.55, z); m.visible = false; this.player.add(m); return m; }); + const brk = this.basic({ color: 0xff3020 }); this.brake = new T.Mesh(this.keep(new T.BoxGeometry(0.03, 0.09, 1.5)), brk); this.brake.position.set(-2.34, 0.76, 0); this.player.add(this.brake); + } + spawnCar(kind, mat) { + const g = new T.Group(); g.add(new T.Mesh(this.carGeo[kind], mat)); g.add(new T.Mesh(this.lampGeo[kind], this.lampMatCar)); const s = new T.Mesh(this.shadowGeo, this.shadowMat); s.position.y = 0.05; g.add(s); + if (kind === 'cop') { const r = new T.Mesh(this.barGeo, this.barMat.r1), b = new T.Mesh(this.barGeo, this.barMat.b0); r.position.set(-0.45, 1.5, 0.3); b.position.set(-0.45, 1.5, -0.3); g.add(r, b); g.userData.bar = [r, b]; } + this.world.add(g); return g; + } + pool(name, make) { return this.pools[name] || (this.pools[name] = { list: [], make, used: 0 }); } + take(p) { if (p.used === p.list.length) p.list.push(p.make()); const o = p.list[p.used++]; o.visible = true; return o; } + buildProps() { + const steel = this.lam({ color: 0x585c63 }), glow = this.basic({ color: 0x7dff9a }), red = this.basic({ color: 0xff4632 }), amber = this.basic({ color: 0xffb037 }); + const col = this.keep(new T.BoxGeometry(0.7, 8, 0.7)); col.translate(0, 4, 0); const beam = this.keep(new T.BoxGeometry(0.9, 0.9, 1)), strip = this.keep(new T.BoxGeometry(0.2, 0.5, 1)), cone = this.keep(new T.ConeGeometry(0.35, 0.9, 8)), rail = this.keep(new T.BoxGeometry(0.5, 0.9, 3)), spike = this.keep(new T.BoxGeometry(0.9, 0.1, 1)), tooth = this.keep(new T.ConeGeometry(0.1, 0.34, 4)); + this.gateMake = kind => { const g = new T.Group(), hw = 10; const a = new T.Mesh(col, steel); a.position.z = hw; const b = new T.Mesh(col, steel); b.position.z = -hw; const top = new T.Mesh(beam, steel); top.position.y = 8; top.scale.z = hw * 2 + 0.7; const bar = new T.Mesh(strip, glow); bar.position.set(-0.55, 8, 0); bar.scale.z = hw * 2 - 1; g.add(a, b, top, bar); g.userData.bar = bar; this.world.add(g); return g; }; + this.redDark = this.basic({ color: 0x401010 }); + this.barrierMake = () => { const g = new T.Group(); const m = new T.Mesh(rail, this.lam({ color: 0xe8d030 })); m.position.y = 0.45; g.add(m); const l = new T.Mesh(this.keep(new T.BoxGeometry(0.1, 0.15, 2.6)), red); l.position.set(0.28, 0.75, 0); g.add(l); g.userData.lamp = l; g.userData.red = red; this.world.add(g); return g; }; + const hazard = this.keep(canvasTex(64, 16, (q, w, h) => { q.fillStyle = '#e8c020'; q.fillRect(0, 0, w, h); q.fillStyle = '#18181a'; for (let x = -16; x < w; x += 16) { q.beginPath(); q.moveTo(x, h); q.lineTo(x + 8, 0); q.lineTo(x + 16, 0); q.lineTo(x + 8, h); q.fill(); } }, true)); + this.spikeMake = () => { const g = new T.Group(); const m = new T.Mesh(spike, this.lam({ map: hazard })); m.position.y = 0.06; g.add(m); g.userData.base = m; const teeth = new T.InstancedMesh(tooth, this.lam({ color: 0xe8ecf2, emissive: 0x303438 }), 16); g.add(teeth); g.userData.teeth = teeth; this.keep(teeth); this.world.add(g); return g; }; + this.haloMake = () => { const s = new T.Sprite(this.halo(0xffffff)); this.world.add(s); return s; }; + this.coneMake = () => { const m = new T.Mesh(cone, this.lam({ color: 0xff7a1e })); this.world.add(m); return m; }; + this.lightAmber = amber; + } + // ---- effects: three point clouds rebuilt per frame (one draw call each), sprites for markers, a beacon, light pools ---- + buildFx() { + const pts = (n, size, blending, opacity) => { const g = this.keep(new T.BufferGeometry()); g.setAttribute('position', new T.BufferAttribute(new Float32Array(n * 3), 3)); g.setAttribute('color', new T.BufferAttribute(new Float32Array(n * 3), 3)); g.setDrawRange(0, 0); const m = new T.Points(g, this.keep(new T.PointsMaterial({ size, map: this.haloTex, vertexColors: true, transparent: true, opacity, depthWrite: false, blending, fog: false }))); m.frustumCulled = false; m.renderOrder = 5; this.world.add(m); return { m, g, n, used: 0 }; }; + this.glow = pts(260, 1.5, T.AdditiveBlending, 1); this.spark = pts(80, 0.42, T.AdditiveBlending, 1); this.smoke = pts(60, 3.2, T.NormalBlending, 0.38); + const lamps = this.lampSpots || []; this.lampHalo = pts(lamps.length, 3.6, T.AdditiveBlending, 0.55); for (const l of lamps) this.pushPt(this.lampHalo, l[0], l[1], 7.35, 1, 0.82, 0.55); this.flushPts(this.lampHalo); + // rival marker: a downward chevron, constant size on screen + const chev = this.keep(canvasTex(64, 64, (q, w, h) => { q.fillStyle = 'rgba(0,0,0,.55)'; q.beginPath(); q.moveTo(6, 10); q.lineTo(58, 10); q.lineTo(32, 56); q.closePath(); q.fill(); q.fillStyle = '#ffffff'; q.beginPath(); q.moveTo(12, 14); q.lineTo(52, 14); q.lineTo(32, 48); q.closePath(); q.fill(); })); + this.markerMake = () => { const sp = new T.Sprite(this.keep(new T.SpriteMaterial({ map: chev, sizeAttenuation: false, depthWrite: false, transparent: true, fog: false }))); sp.scale.set(0.045, 0.045, 1); sp.renderOrder = 6; this.world.add(sp); return sp; }; + // next-gate beacon: a tall additive column that rises above the roofs + const beamTex = this.keep(canvasTex(8, 128, (q, w, h) => { const g = q.createLinearGradient(0, 0, 0, h); g.addColorStop(0, 'rgba(255,255,255,0)'); g.addColorStop(0.5, 'rgba(255,255,255,.55)'); g.addColorStop(1, 'rgba(255,255,255,.9)'); q.fillStyle = g; q.fillRect(0, 0, w, h); })); + this.beaconMake = () => { const m = new T.Mesh(this.keep(new T.CylinderGeometry(1.1, 1.1, 70, 10, 1, true)), this.keep(new T.MeshBasicMaterial({ map: beamTex, color: 0x7dff9a, transparent: true, opacity: 0.5, depthWrite: false, side: T.DoubleSide, fog: false }))); m.position.y = 35; const g = new T.Group(); g.add(m); g.userData.beam = m; this.world.add(g); return g; }; + // rival nitrous flame + const cone = this.keep(new T.ConeGeometry(0.13, 1.1, 8)); cone.rotateZ(Math.PI / 2); const flame = this.basic({ color: 0x7fc4ff, transparent: true, opacity: 0.85, blending: T.AdditiveBlending, depthWrite: false }); + this.rflameMake = () => { const g = new T.Group(); for (const z of [0.45, -0.45]) { const m = new T.Mesh(cone, flame); m.position.set(-2.82, 0.55, z); g.add(m); } this.world.add(g); return g; }; + // light pools on the road: player headlights at night, the helicopter's searchlight + const pool = this.keep(canvasTex(64, 64, (q, w, h) => { const g = q.createRadialGradient(32, 32, 2, 32, 32, 32); g.addColorStop(0, 'rgba(255,255,255,.75)'); g.addColorStop(1, 'rgba(255,255,255,0)'); q.fillStyle = g; q.fillRect(0, 0, w, h); })); + const quad = this.keep(new T.PlaneGeometry(1, 1)); quad.rotateX(-Math.PI / 2); + this.headPool = new T.Mesh(quad, this.keep(new T.MeshBasicMaterial({ map: pool, color: 0xfff0c8, transparent: true, opacity: 0.28, blending: T.AdditiveBlending, depthWrite: false }))); this.headPool.scale.set(12, 1, 22); this.headPool.visible = false; this.world.add(this.headPool); + this.heliSpot = new T.Mesh(quad, this.keep(new T.MeshBasicMaterial({ map: pool, color: 0xd8e8ff, transparent: true, opacity: 0.7, blending: T.AdditiveBlending, depthWrite: false }))); this.heliSpot.scale.set(18, 1, 18); this.heliSpot.visible = false; this.world.add(this.heliSpot); + } + pushPt(p, x, y, z, r, g, b) { if (p.used >= p.n) return; const i = p.used++; const a = p.g.attributes.position.array, c = p.g.attributes.color.array; a[i * 3] = x; a[i * 3 + 1] = z; a[i * 3 + 2] = -y; c[i * 3] = r; c[i * 3 + 1] = g; c[i * 3 + 2] = b; } + flushPts(p) { p.g.setDrawRange(0, p.used); p.g.attributes.position.needsUpdate = true; p.g.attributes.color.needsUpdate = true; } + // head and tail lights of one car in world space; night sets how strong the headlights read + carLights(x, y, h, kind, braking, night) { + const ch = Math.cos(h), sh = Math.sin(h), W = CAR_SHAPES[kind].w * 0.34, f = kind === 'van' ? 2.5 : 2.36, b = kind === 'van' ? -2.56 : -2.36, fy = kind === 'van' ? 0.72 : 0.5, by = kind === 'van' ? 0.95 : 0.74; + for (const s of [1, -1]) { + const lx = -sh * W * s, ly = ch * W * s; + if (night > 0) this.pushPt(this.glow, x + ch * f + lx, y + sh * f + ly, fy, night, night * 0.94, night * 0.78); + const k = braking ? 1 : 0.42; this.pushPt(this.glow, x + ch * b + lx, y + sh * b + ly, by, k, k * 0.1, k * 0.06); + } + } + drawFx(g, st) { + const night = st.lamp > 0 ? Math.min(1, 0.45 + st.lamp * 0.35) : 0.18, c = g.car, sp = C.speed(c), t = g.t; + this.glow.used = 0; this.spark.used = 0; this.smoke.used = 0; + this.carLights(c.x, c.y, c.h, 'coupe', g.heldBrake || sp < 0.5, night); + for (const o of g.traffic) this.carLights(o.x, o.y, o.h, o.paint % 6 === 3 ? 'van' : 'sedan', o.crash, night * 0.8); + for (const r of g.rivals) if (!r.gone) this.carLights(r.x, r.y, r.h, 'coupe', 0, night * 0.9); + for (const k of g.cops) if (!k.gone) this.carLights(k.x, k.y, k.h, 'cop', k.state === 'rb', k.dead ? 0 : night * 0.9); + for (const k of g.cops) if (k.dead && !k.gone) for (let i = 0; i < 5; i++) { const gr = 0.2 + i * 0.05; this.pushPt(this.smoke, k.x + Math.sin(i * 2.1 + t * 0.05) * 0.5, k.y + Math.cos(i * 1.7 + t * 0.04) * 0.5, 1.2 + i * 0.9 + ((t * 0.04 + i * 0.3) % 1), gr, gr, gr); } + // nitrous glow behind the player's exhausts + if (c.nosOn) { const ch = Math.cos(c.h), sh = Math.sin(c.h); for (let i = 1; i <= 4; i++) this.pushPt(this.glow, c.x - ch * (2.6 + i * 0.55), c.y - sh * (2.6 + i * 0.55), 0.55, 0.35, 0.6, 1); } + // sparks: a hit sets lastHit (0.25-0.4 s); 14 sparks thrown from the front corners along fixed pseudo-random paths + if (g.lastHit > 0) { + const age = 0.4 - g.lastHit, ch = Math.cos(c.h), sh = Math.sin(c.h); + for (let i = 0; i < 14; i++) { const u = Math.sin(i * 12.9898 + (t >> 4) * 78.233) * 43758.5453, r1 = u - Math.floor(u), r2 = (u * 7.13) - Math.floor(u * 7.13), side = i % 2 ? 1 : -1, sx = 2.1, sy = side * 0.9, a = c.h + side * (0.6 + r1 * 1.2) + Math.PI * (r2 < 0.3 ? 1 : 0), v = 6 + r2 * 9, d = v * age; + this.pushPt(this.spark, c.x + ch * sx - sh * sy + Math.cos(a) * d, c.y + sh * sx + ch * sy + Math.sin(a) * d, 0.4 + 3 * age - 9 * age * age + r1 * 0.3, 1, 0.75 + r2 * 0.25, 0.3); } + } + // tyre smoke while the rear slides (carStep drift); puffs trail back along the velocity + if (c.drift && sp > 4) { const vx = c.vx / sp, vy = c.vy / sp, ch = Math.cos(c.h), sh = Math.sin(c.h); for (let i = 0; i < 8; i++) for (const s of [1, -1]) { const back = 1.4 + i * 1.1, lx = -sh * 0.8 * s, ly = ch * 0.8 * s, gr = 0.62 + i * 0.03; this.pushPt(this.smoke, c.x - ch * 1.4 + lx - vx * back, c.y - sh * 1.4 + ly - vy * back, 0.5 + i * 0.12, gr, gr, gr); } } + this.flushPts(this.glow); this.flushPts(this.spark); this.flushPts(this.smoke); + this.lampHalo.m.visible = st.lamp > 0; + this.headPool.visible = st.lamp > 0; if (this.headPool.visible) { qv(c.x + Math.cos(c.h) * 9, c.y + Math.sin(c.h) * 9, 0.05, this.headPool.position); this.headPool.rotation.y = c.h; } + const hl = g.heli; this.heliSpot.visible = !!(hl && !hl.gone && hl.sees); if (this.heliSpot.visible) qv(c.x + (hl.x - c.x) * 0.15, c.y + (hl.y - c.y) * 0.15, 0.06, this.heliSpot.position); + } + // Corner boards: a red board with white chevrons on the outside wall of every corner tighter than 90 m, one every 9 m of arc, + // facing the car that is about to turn. They are what shows where the road goes when the road itself is behind a building. + buildChevrons() { + const tex = dir => this.keep(canvasTex(128, 64, (q, w, h) => { q.fillStyle = '#c8261c'; q.fillRect(0, 0, w, h); q.fillStyle = '#ffffff'; q.fillRect(0, 0, w, 4); q.fillRect(0, h - 4, w, 4); + for (let i = 0; i < 3; i++) { const x0 = 18 + i * 34; q.beginPath(); if (dir < 0) { q.moveTo(x0 + 20, 10); q.lineTo(x0, h / 2); q.lineTo(x0 + 20, h - 10); q.lineTo(x0 + 30, h - 10); q.lineTo(x0 + 10, h / 2); q.lineTo(x0 + 30, 10); } else { q.moveTo(x0, 10); q.lineTo(x0 + 20, h / 2); q.lineTo(x0, h - 10); q.lineTo(x0 + 10, h - 10); q.lineTo(x0 + 30, h / 2); q.lineTo(x0 + 10, 10); } q.closePath(); q.fill(); } })); + const geo = this.keep(new T.PlaneGeometry(2.6, 1.3)); geo.translate(0, 2.0, 0); + const post = this.keep(new T.BoxGeometry(0.12, 1.4, 0.12)); post.translate(0, 0.7, 0); + const lists = { left: [], right: [] }; this.chevrons = []; + for (const R of [C.routes.coast, C.routes.downtown]) { + for (let i = 0; i < R.n; i += Math.max(1, Math.round(9 / R.ds))) { + const k = R.k[i]; if (Math.abs(k) < 1 / 90) continue; + const a = C.routeAt(R, i * R.ds), out = k > 0 ? -1 : 1, lat = out * (R.halfW + 0.7), x = a.x + a.nx * lat, y = a.y + a.ny * lat; + if (C.road(x, y).d < 0.1) continue; // another road joins here: no wall, no board + (k > 0 ? lists.left : lists.right).push([x, y, a.h]); this.chevrons.push({ x, y, s: i * R.ds, route: R.name }); + } + } + const o = new T.Object3D(); + for (const [side, list] of Object.entries(lists)) { + if (!list.length) continue; + const board = new T.InstancedMesh(geo, this.basic({ map: tex(side === 'left' ? -1 : 1), side: T.DoubleSide }), list.length), legs = new T.InstancedMesh(post, this.lam({ color: 0x3a3c40 }), list.length); + list.forEach((p, j) => { qv(p[0], p[1], 0, o.position); o.rotation.set(0, p[2] - Math.PI / 2, 0); o.updateMatrix(); board.setMatrixAt(j, o.matrix); legs.setMatrixAt(j, o.matrix); }); + this.world.add(this.keep(board), this.keep(legs)); + } + } + // Screen position of a sim point with the frame's camera: {x, y} in canvas pixels, front = in front of the camera. + project(x, y, z) { const v = qv(x, y, z, this.tmpV || (this.tmpV = new T.Vector3())); v.applyMatrix4(this.camera.matrixWorldInverse); const front = v.z < -0.3; qv(x, y, z, v).project(this.camera); return { x: (v.x * 0.5 + 0.5) * 854, y: (-v.y * 0.5 + 0.5) * 480, front }; } + breakerMake() { const g = new T.Group(), steel = this.lam({ color: 0x8a5a30 }), red = this.basic({ color: 0xff5a2a }); for (const [x, z] of [[-1.8, -1.8], [1.8, -1.8], [-1.8, 1.8], [1.8, 1.8]]) { const m = new T.Mesh(this.keep(new T.BoxGeometry(0.4, 9, 0.4)), steel); m.position.set(x, 4.5, z); g.add(m); } const top = new T.Mesh(this.keep(new T.BoxGeometry(5, 1.6, 5)), steel); top.position.y = 9.5; g.add(top); const sign = new T.Mesh(this.keep(new T.BoxGeometry(5.2, 0.5, 5.2)), red); sign.position.y = 8.5; g.add(sign); this.world.add(g); return g; } + // ---------------- per-frame ---------------- + placeCar(o, x, y, h, lift = 0) { qv(x, y, lift, o.position); o.rotation.y = h; } + drawProps(g) { + for (const p of Object.values(this.pools)) { for (const o of p.list) o.visible = false; p.used = 0; } + const R = g.route; + const blink = (g.t >> 3) % 2 === 0, nextGate = (g.gates || []).find(q => !q.done); + if (nextGate && !g.outcome) { const gs = nextGate.s !== undefined ? nextGate.s : g.s0 + nextGate.at, ds = R.loop && M.wrapTo ? M.wrapTo(R, gs, g.s) - g.s : gs - g.s; if (ds > 12 && ds < 900) { const a = C.routeAt(R, g.s + ds), o = this.take(this.pool('beacon', () => this.beaconMake())); this.placeCar(o, a.x, a.y, a.h); o.userData.beam.material.color.setHex(nextGate.kind === 'trap' ? 0xffb037 : nextGate.kind === 'line' ? 0xffffff : 0x7dff9a); } } + for (const gate of g.gates || []) { + const a = C.routeAt(R, (gate.s !== undefined ? gate.s : g.s0 + gate.at)); if (gate.done && !gate.keep) continue; + const o = this.take(this.pool(gate.kind === 'trap' ? 'gateT' : 'gate', () => this.gateMake(gate.kind === 'trap' ? 'trap' : 'toll'))); + this.placeCar(o, a.x, a.y, a.h); const bar = o.userData.bar; bar.material.color.setHex(gate.kind === 'trap' ? (g.flashT > 0 ? 0xffffff : 0xffb037) : (gate.next ? 0x7dff9a : 0x7dff9a)); + } + for (const t of g.traffic) { const o = this.take(this.pool('tr' + (t.paint % 6), () => this.spawnCar(t.paint % 6 === 3 ? 'van' : 'sedan', this.paints[t.paint % 6]))); this.placeCar(o, t.x, t.y, t.h); } + for (const r of g.rivals) { + if (r.gone) continue; const o = this.take(this.pool('rv' + (r.paint || 0), () => this.spawnCar('coupe', this.paint([0x9fb0c8, 0xb0242c, 0x28402c, 0x4b3d84][(r.paint || 0) % 4])))); this.placeCar(o, r.x, r.y, r.h); + // marker: the champion red, every other rival white; nitrous flames while its boost runs (rivals.js nosT / trapNos) + const mk = this.take(this.pool('marker', () => this.markerMake())); qv(r.x, r.y, 2.5, mk.position); mk.material.color.setHex(r.name === 'champion' ? 0xff4a3a : 0xffffff); + if ((r.nosT > 0 || r.trapNos > 0) && r.nos > 0.02 && !r.out) { const f = this.take(this.pool('rflame', () => this.rflameMake())); this.placeCar(f, r.x, r.y, r.h); f.scale.set(1 + ((g.t * 7) % 3) * 0.2, 1, 1); } + } + for (const c of g.cops) { + if (c.gone) continue; const o = this.take(this.pool('cop', () => this.spawnCar('cop', this.copMat))); this.placeCar(o, c.x, c.y, c.h); + const live = !c.dead, ph = (c.slot || 0) % 2 ? !blink : blink, bar = o.userData.bar; bar[0].material = live && ph ? this.barMat.r1 : this.barMat.r0; bar[1].material = live && !ph ? this.barMat.b1 : this.barMat.b0; + if (live) { const s = this.take(this.pool('halo', () => this.haloMake())); qv(c.x, c.y, 1.7, s.position); s.scale.setScalar(c.state === 'rb' ? 6 : 4.4); s.material.color.setHex(ph ? 0xff2a3a : 0x3a70ff); } + } + for (const b of g.breakers || []) { if (b.rearm > 0) continue; const o = this.take(this.pool('breaker', () => this.breakerMake())); this.placeCar(o, b.x, b.y, b.h); } + for (const p of g.props) { + if (p.gone) continue; const a = { x: p.x, y: p.y, h: p.h || 0 }; + if (p.type === 'spike') { const o = this.take(this.pool('spike', () => this.spikeMake())), L = p.len || 14; this.placeCar(o, a.x, a.y, a.h); o.userData.base.scale.z = L; const t = o.userData.teeth, m = new T.Object3D(); for (let i = 0; i < 16; i++) { m.position.set((i % 2) * 0.3 - 0.15, 0.2, (i / 15 - 0.5) * L); m.updateMatrix(); t.setMatrixAt(i, m.matrix); } t.instanceMatrix.needsUpdate = true; + if (!p.used) for (const e of [-1, 1]) { const b = this.take(this.pool('halo', () => this.haloMake())), ex = a.x - Math.sin(a.h) * e * (L / 2 + 0.6), ey = a.y + Math.cos(a.h) * e * (L / 2 + 0.6); qv(ex, ey, 0.5, b.position); b.scale.setScalar(blink ? 3.4 : 1.6); b.material.color.setHex(0xffb020); } } + else if (p.type === 'barrier') { const o = this.take(this.pool('barrier', () => this.barrierMake())); this.placeCar(o, a.x, a.y, a.h, p.lift || 0); o.rotation.x = p.spin || 0; o.userData.lamp.material = blink ? o.userData.red : this.redDark; } + else if (p.type === 'cone') { const o = this.take(this.pool('cone', () => this.coneMake())); qv(a.x, a.y, 0.45, o.position); } + } + } + render(g, ctx) { + if (this.closed || this.renderer.getContext().isContextLost()) { this.ready = false; this.error = this.closed ? '3D renderer is closed' : 'WebGL context lost'; throw Error(this.error); } + const t0 = performance.now(); + try { + const key = g.key, st = STYLE[key] || STYLE.tollbooth, c = g.car; + if (this.key !== key) { + this.key = key; this.world.fog.color.setHex(st.fog[0]); this.world.fog.near = st.fog[1]; this.world.fog.far = st.fog[2]; + this.hemi.color.setHex(st.hemi[0]); this.hemi.groundColor.setHex(st.hemi[1]); this.hemi.intensity = st.hemi[2]; this.sun.color.setHex(st.sun); this.sun.intensity = st.sunI; + this.sun.position.set(st.dir[0], Math.max(0.12, st.dir[1]) + 0.25, -0.5); this.sky.material.map = this.skyTex(key); this.sky.material.needsUpdate = true; + for (const m of this.mats.win) m.emissiveIntensity = st.win; this.lampMat.color.setHex(st.lamp > 0 ? 0xffdca0 : 0x77767a); + } + this.seaTex.offset.x = g.t * 0.0006; this.seaTex.offset.y = g.t * 0.0003; + this.placeCar(this.player, c.x, c.y, c.h); const sp = C.speed(c); + // Body motion: roll outward in a turn (local +X is forward, so YXZ order makes x roll and z pitch), nose dive under braking. + // (Before 2026-11-08 this set rotation.z from the steering, which pitched the nose instead of rolling the body.) + this.player.rotation.order = 'YXZ'; this.player.rotation.x = C.clamp(c.r * sp * 0.006, -0.07, 0.07); this.player.rotation.z = g.heldBrake && sp > 3 ? -0.022 : c.nosOn ? 0.012 : 0; + this.flames.forEach(f => { f.visible = !!c.nosOn; f.scale.set(1 + ((g.t * 7) % 3) * 0.2, 1, 1); }); + this.brake.visible = g.heldBrake || sp < 0.5; + this.drawProps(g); this.drawHeli(g); this.drawFx(g, st); + const yaw = g.camH === undefined ? c.h : g.camH, back = 6.6 + Math.min(1.8, sp * 0.022), up = 2.45 + Math.min(0.5, sp * 0.006); + qv(c.x - Math.cos(yaw) * back, c.y - Math.sin(yaw) * back, up, this.camera.position); + const hit = Math.max(0, g.lastHit || 0), shake = (c.nosOn ? 0.03 * Math.sin(g.t * 1.7) : 0) + hit * 0.5 * Math.sin(g.t * 2.9); + if (hit > 0) { this.camera.position.x += hit * 0.35 * Math.sin(g.t * 3.7); this.camera.position.y += hit * 0.25 * Math.cos(g.t * 4.3); } + this.camera.lookAt(qv(c.x + Math.cos(yaw) * 7, c.y + Math.sin(yaw) * 7, 1.15 + shake)); + this.camera.fov = 58 + Math.min(16, sp * 0.2) + (c.nosOn ? 4 : 0) - (g.sb ? 5 : 0); this.camera.updateProjectionMatrix(); + this.sky.position.copy(this.camera.position); + this.renderer.setScissorTest(false); this.renderer.setViewport(0, 0, 854, 480); + this.renderer.render(this.world, this.camera); + this.mirrorOn = !!(g.cops.length || g.rivals.length || g.pol); + if (this.mirrorOn) { + const [x0, y0, x1, y1] = this.mirrorRect, mh = c.h; + qv(c.x + Math.cos(mh) * 0.4, c.y + Math.sin(mh) * 0.4, 1.75, this.mirrorCam.position); + this.mirrorCam.lookAt(qv(c.x - Math.cos(mh) * 30, c.y - Math.sin(mh) * 30, 0.9)); + this.mirrorCam.updateMatrixWorld(); this.sky.position.copy(this.mirrorCam.position); + const vy = 480 - y1; this.renderer.setViewport(x0, vy, x1 - x0, y1 - y0); this.renderer.setScissor(x0, vy, x1 - x0, y1 - y0); this.renderer.setScissorTest(true); + // the player's own car, its light glows and the particles sit right in front of the mirror camera: hidden for this pass + const fx = [this.player, this.glow.m, this.spark.m, this.smoke.m, this.headPool], was = fx.map(o => o.visible); fx.forEach(o => { o.visible = false; }); + this.renderer.render(this.world, this.mirrorCam); fx.forEach((o, i) => { o.visible = was[i]; }); + this.renderer.setScissorTest(false); this.renderer.setViewport(0, 0, 854, 480); this.sky.position.copy(this.camera.position); + } + ctx.drawImage(this.view, 0, 0, 854, 480); + this.times.push(performance.now() - t0); if (this.times.length > 120) this.times.shift(); + this.ready = true; this.error = null; + } catch (e) { this.ready = false; this.error = String(e && e.stack || e); throw e; } + } + drawHeli(g) { + if (!g.heli || g.heli.gone) { if (this.heliObj) this.heliObj.visible = false; return; } + if (!this.heliObj) { + const H = this.heliObj = new T.Group(), body = this.lam({ color: 0x1c2230, vertexColors: true }); + H.add(new T.Mesh(this.keep(merge([[moved(new T.SphereGeometry(1.5, 10, 8), 0.6, 0, 0), 0xffffff], [moved(new T.BoxGeometry(4.2, 0.5, 0.45), -2.4, 0.2, 0), 0xffffff], [boxG(-4.5, 0.75, 0, 0.5, 1.2, 0.12), 0xffffff], [boxG(0.4, -1.45, 0.9, 2.8, 0.1, 0.12), 0x777777], [boxG(0.4, -1.45, -0.9, 2.8, 0.1, 0.12), 0x777777], [moved(new T.SphereGeometry(0.9, 8, 6), 1.5, 0.15, 0), 0x223a55]])), body)); + const rotor = this.heliRotor = new T.Mesh(this.keep(new T.BoxGeometry(9, 0.05, 0.3)), this.lam({ color: 0x26282c })); rotor.position.y = 1.65; H.add(rotor); + const beam = this.heliBeam = new T.Mesh(this.keep(new T.ConeGeometry(4.5, 26, 16, 1, true)), this.basic({ color: 0xd8e8ff, transparent: true, opacity: 0.13, blending: T.AdditiveBlending, depthWrite: false, side: T.DoubleSide })); beam.position.y = -13.5; H.add(beam); this.world.add(H); + } + const h = g.heli; this.heliObj.visible = true; qv(h.x, h.y, h.z, this.heliObj.position); this.heliObj.rotation.y = h.h; this.heliRotor.rotation.y = g.t * 1.1; + this.heliBeam.visible = !!h.sees; + } + metrics() { const s = [...this.times].sort((a, b) => a - b), i = this.renderer.info; return { renderer: 'webgl-nfsmw', drawCalls: i.render.calls, triangles: i.render.triangles, samples: s.length, cpuRenderMsP50: s.length ? s[Math.floor((s.length - 1) * 0.5)] : null, cpuRenderMsP95: s.length ? s[Math.floor((s.length - 1) * 0.95)] : null }; } + close() { if (this.closed) return; this.closed = true; this.ready = false; for (const r of this.res) r.dispose && r.dispose(); this.renderer.dispose(); this.renderer.forceContextLoss(); this.res = []; } + } + R3.render = (g, ctx) => { let s = byCanvas.get(ctx.canvas); if (!s || s.closed) { s = new Scene(ctx.canvas); byCanvas.set(ctx.canvas, s); } s.render(g, ctx); return s; }; + R3.status = ctx => { const s = ctx && byCanvas.get(ctx.canvas); if (s && !s.closed && s.renderer.getContext().isContextLost()) { s.ready = false; s.error = 'WebGL context lost'; } return { renderer: 'webgl-nfsmw', kind: 'perspective', ready: !!(s && s.ready && !s.closed), error: s ? s.error : null }; }; + R3.metrics = ctx => { const s = ctx && byCanvas.get(ctx.canvas); return s && !s.closed ? s.metrics() : null; }; + R3.close = ctx => { const s = ctx && byCanvas.get(ctx.canvas); if (s) { s.close(); byCanvas.delete(ctx.canvas); } }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/nfsmw_remake/rivals.js b/environments/games/web/games/nfsmw_remake/rivals.js new file mode 100644 index 0000000000000000000000000000000000000000..a4e4bd687cf4e9101e1dbacc8047a309486b7536 --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/rivals.js @@ -0,0 +1,66 @@ +/* Rival racers. The driver model is AIActionRace with its own skill tables (AI/Actions/AIActionRace.cpp): speed scale {0.85, 1}, + acceleration scale {0.65, 1} (drag {0.82, 1}), catch-up acceleration table {1, 1.33, 1.66, 2} (:70), nitrous availability + {0.33, 1} (:42-43), on for 2-4 s (:38-39) and off for 20-4 s by skill (:36-37), speed-trap nitrous 1-3 s ahead (:40-41). + Catch-up gain by skill {0.33, 0.66, 1} and slow-down {1, 1, 0.66} are AI/Common/AIVehicle.cpp:2053-2059; the error scale + that feeds them lives in GRaceStatus::ComputeCatchUpSkill (body not in the repository), so the gaps below are approximations. + A rival rides route coordinates (s, lat), so it can never leave the road or get lost. Nothing here reads the RNG. */ +(function (root) { + 'use strict'; + const M = root.NfsmwGame, C = M.C, P = C.PLAYER, lerp = C.lerp, clamp = C.clamp; + const tableAt = (t, x) => { const u = clamp(x, 0, 1) * (t.length - 1), i = Math.min(t.length - 2, Math.floor(u)); return t[i] + (t[i + 1] - t[i]) * (u - i); }; + // A rival's form on the day: drawn once at the start of a heat from the game RNG, so a seed is a different race, not a relabelled one. + M.formOf = g => (root.NativeBench.rand(g) - 0.5) * 0.06; + M.newRival = (g, o) => { + const a = C.routeAt(g.route, o.s, o.lat); + return { s: o.s, s0: o.s, lat: o.lat, latGoal: o.lat, v: 0, x: a.x, y: a.y, h: a.h, skill: o.skill, drag: !!o.drag, paint: o.paint || 0, out: 0, gone: 0, + nos: lerp(0.33, 1, o.skill), nosT: 0, nosCool: 2, trapNos: 0, prog: 0, finished: 0, top: o.top || 84, grip: o.grip || lerp(0.74, 0.98, o.skill), name: o.name || '' }; + }; + // Speed a rival would carry past a route point, integrated from where it is now: its own limits and drive, no glue, no nitrous, + // no traffic. Used only to score a camera the event ended before it reached. + M.projectRival = (g, r, target) => { + const R = g.route, accelScale = lerp(0.65, 1, r.skill), prof = C.profile(R, P.grip * r.grip, P.aero, P.brake * 0.9, r.top * lerp(0.85, 1, r.skill)); + let v = r.v; + for (let s = r.s; s < target; s += R.ds) { const a = Math.max(0, C.driveAt(v) * accelScale - P.drag * v * v - P.roll); v = Math.min(C.profileAt(R, prof, s + R.ds), Math.sqrt(v * v + 2 * a * R.ds)); } + return v; + }; + M.stepRival = (g, r, wdt) => { + if (r.out || r.finished) r.v = Math.max(0, r.v - 7 * wdt); + const R = g.route, skill = r.skill, speedScale = lerp(0.85, 1, skill), accelScale = r.drag ? lerp(0.82, 1, skill) : lerp(0.65, 1, skill); + const prof = C.profile(R, P.grip * r.grip, P.aero, P.brake * 0.9, r.top * speedScale), vlim = Math.min(C.profileAt(R, prof, r.s + r.v * 0.25), C.profileAt(R, prof, r.s + r.v * 0.5)); + // Catch-up glue: acceleration up to x2 when behind the player, a gentler speed limit when ahead (it never parks and waits). + const gap = (g.s - g.s0) - (r.s - r.s0), glue = g.glue === undefined ? 1 : g.glue, behind = glue * clamp(gap / 120, 0, 1) * tableAt([0.33, 0.66, 1], skill), ahead = glue * clamp(-gap / 240, 0, 1) * tableAt([1, 1, 0.66], skill); + const catchup = g.noGlue ? 1 : tableAt([1, 1.33, 1.66, 2], behind), limit = vlim * (g.noGlue ? 1 : 1 - 0.1 * ahead); + // Nitrous: skill sets how often and how much; a coming speed trap overrides the cool-down (CheckSpeedTraps). + if (r.nosT > 0) r.nosT -= wdt; else if (r.nosCool > 0) r.nosCool -= wdt; + const trapNear = r.trapNos > 0 && r.nos > 0.02; + if (!r.out && r.nosT <= 0 && r.nosCool <= 0 && r.nos > 0.02 && r.v > 10 && limit > r.v + 5) { r.nosT = lerp(2, 4, skill); r.nosCool = lerp(20, 4, skill); } + const on = (r.nosT > 0 || trapNear) && r.nos > 0 && r.v < limit - 1 && !r.out && !r.finished; + if (on) r.nos = Math.max(0, r.nos - wdt / P.nosSeconds); + if (r.trapNos > 0) r.trapNos -= wdt; + if (!r.out && !r.finished) { + if (r.v > limit) r.v = Math.max(limit, r.v - P.brake * 0.9 * wdt); + else { const a = C.driveAt(r.v) * accelScale * catchup * (on ? 1 + P.nosBoost : 1) - P.drag * r.v * r.v - P.roll; r.v = Math.min(limit, r.v + Math.max(0, a) * wdt); } + } + r.s += r.v * wdt; + // Lane: separation from the player and from traffic within two seconds; otherwise back to its own line. + const edge = R.halfW - 2.1; + if (!g.laneLocked) { + let goal = r.latGoal; + const clear = lat => { for (const t of g.traffic) { let ds = t.s - r.s; if (R.loop) { ds %= R.L; if (ds > R.L / 2) ds -= R.L; else if (ds < -R.L / 2) ds += R.L; } const cl = r.v - t.v; if (ds > -6 && ds < 8 + Math.max(cl, 0) * 2 && Math.abs(t.lat - lat) < 3.6) return false; } for (const b of g.blocks || []) { const ds = b.s - r.s; if (ds > -6 && ds < 10 + r.v * 2 && Math.abs(b.lat - lat) < 3.6) return false; } const ds = g.s - r.s; return !(ds > -6 && ds < 14 && Math.abs(g.lat - lat) < 3.4); }; + if (!clear(r.lat)) { let best = r.lat, bd = Infinity; for (let lat = -edge; lat <= edge + 1e-6; lat += edge / 2.5) if (clear(lat) && Math.abs(lat - r.lat) < bd) { bd = Math.abs(lat - r.lat); best = lat; } goal = best; } + const rate = Math.min(4.2, 0.6 + r.v * 0.09), dl = clamp(goal - r.lat, -rate * wdt, rate * wdt); r.lat = clamp(r.lat + dl, -edge, edge); + } + const a = C.routeAt(R, r.s, r.lat); r.x = a.x; r.y = a.y; r.h = a.h; + r.prog = r.s - r.s0; + // Contact. A rail car takes the impulse as a speed change and a sideways shove. + if (r.gone || g.pre > 0) return; + for (const t of g.traffic) { if (t.crash) continue; const dx = r.x - t.x, dy = r.y - t.y; if (dx * dx + dy * dy < 9) { r.v *= 0.55; t.crash = r.lat > t.lat ? -0.8 : 0.8; t.vx = Math.cos(t.h) * Math.abs(t.v); t.vy = Math.sin(t.h) * Math.abs(t.v); g.events.push({ type: 'rival_crash' }); } } + const c = g.car, dx = c.x - r.x, dy = c.y - r.y, d2 = dx * dx + dy * dy, R2 = M.carRadius * 2; + if (d2 < R2 * R2) { + const d = Math.max(0.01, Math.sqrt(d2)), nx = dx / d, ny = dy / d, rvx = Math.cos(r.h) * r.v, rvy = Math.sin(r.h) * r.v, rel = (c.vx - rvx) * nx + (c.vy - rvy) * ny, push = R2 - d; + c.x += nx * push * 0.5; c.y += ny * push * 0.5; + const nl = -Math.sin(r.h) * nx + Math.cos(r.h) * ny; r.lat = clamp(r.lat - nl * push * 0.5, -edge, edge); + if (rel < 0) { const j = -0.65 * rel; c.vx += nx * j; c.vy += ny * j; r.v = Math.max(0, r.v - (Math.cos(r.h) * nx + Math.sin(r.h) * ny) * j); if (-rel > 4) { g.hits++; g.lastHit = 0.4; g.events.push({ type: 'rival_contact', speed: -rel }); } } + } + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/nfsmw_remake/scripted.js b/environments/games/web/games/nfsmw_remake/scripted.js new file mode 100644 index 0000000000000000000000000000000000000000..7e6f6297406ce22bd5d6e1e3b200ad94f5343dfa --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/scripted.js @@ -0,0 +1,147 @@ +/* The standard scripted reference controller (BossBench, not part of the original game). NfsmwGame.scripted(game) runs once per + 200 ms packet. It reads already-decided state (poses, speeds, gates) and looks ahead only with the pure car model on a + copy of the player's car: other vehicles are extrapolated at constant speed, so it has no channel to a future random + draw at all (tests/leak_probe.js swaps the live RNG and checks the packet does not change). + Scoring is speed-weighted route progress minus wall and traffic risk. Never distance to a target (a target switch would + punish reaching it). Deterministic: no Math.random, no clock. */ +(function (root) { + 'use strict'; + const M = root.NfsmwGame, C = M.C, N = root.NativeBench; + const PACKET_TICKS = 12, HOLD_SETS = 6, DT = 1 / 60; + // Cars collide as two circles (game.js carRadius 1.6, 3.2 m between centres). A car alongside at 3.3 m is passing, not crashing. + const CONTACT = 3.5, LANE_GAP = 3.7; + // Duty-cycle steering: digital keys held for k of the 6 hold sets. The wheel slews towards the key and back to centre at + // the same rate, so duty 3 holds whatever angle it has, above 3 winds on, below 3 unwinds. + const STEER = [-6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6]; + const copyCar = c => Object.assign({}, c); + + // Same input mapping as Game.update; `plan` = {steer duty, thr, brk, hb, nos}. Mutates c. + function rollout(g, c, plan, ticks, P, wscale) { + for (let i = 0; i < ticks; i++) { + const set = Math.floor(i * HOLD_SETS / PACKET_TICKS) % HOLD_SETS, on = set < Math.abs(plan.duty); + C.carStep(c, { thr: plan.thr, brk: plan.brk, steer: on ? Math.sign(plan.duty) : 0, hb: plan.hb, nos: plan.nos, manual: false, sbGrip: 0 }, DT * wscale, P); + } + } + // Lateral target for the next stretch: keep off traffic that will be alongside, otherwise hold the racing line. + function laneTarget(g, R, S, others, speed, base) { + const edge = R.halfW - 2.2, lanes = [base, -edge * 0.75, edge * 0.75, -edge * 0.35, edge * 0.35, -edge, edge]; + let best = base, bs = -Infinity; + for (const lat of lanes) { + let sc = -Math.abs(lat - g.lat) * 0.5 - Math.abs(lat - base) * 0.2; + for (const o of others) { + const ds = o.s - S; if (ds < -8 || ds > 200) continue; // a car behind the door mirrors is not a reason to change lane + // A car close ahead at matching speed blocks the lane however small the closing speed is. + const closing = speed - o.vs, tt = ds < 30 && ds > -8 ? Math.max(0, ds) / Math.max(closing, 8) : closing > 1 ? ds / closing : 99; if (tt > 5) continue; + const gap = Math.abs(o.lat + (o.vl || 0) * Math.min(tt, 2) - lat); if (gap < LANE_GAP) sc -= (LANE_GAP - gap) * (6 - tt) * 2.4; + } + if (sc > bs) { bs = sc; best = lat; } + } + return best; + } + // Decided state of everything on the road, projected onto route coordinates. + function roadUsers(g, R) { + const out = [], L = R.L; + // On a circuit every position is one lap from itself: put each car on the player's lap so distances are real. + const near = v => { if (!R.loop) return v; let ds = (v - g.s) % L; if (ds > L / 2) ds -= L; else if (ds < -L / 2) ds += L; return Math.abs(v - g.s) <= L / 2 ? v : g.s + ds; }; + for (const t of g.traffic) out.push({ s: near(t.s), lat: t.lat, vs: t.crash ? 0 : t.v, r: 2 }); + for (const r of g.rivals) if (!r.out) out.push({ s: near(r.s), lat: r.lat, vs: r.v, r: 2, a: r.v < 25 ? 5 : 0 }); // a car pulling away is not a parked car + if (M.copUsers) M.copUsers(g, R, out); + return out; + } + // Minimum-curvature line: an elastic band pulled tight between the road edges. Controller-only and a pure function of the route, so + // it is cached outside the game state. Returns the lateral offset per sample and the speed profile on that line's own curvature. + const lines = new Map(); + function racingLine(R, P, grip, brake, top) { + let L = lines.get(R.name); + if (!L) { + const n = R.n, lat = new Float64Array(n), edge = R.halfW - 2.4, wrap = i => R.loop ? (i + n) % n : Math.max(0, Math.min(n - 1, i)), K = Math.max(2, Math.round(10 / R.ds)); + const nx = i => -Math.sin(R.h[i]), ny = i => Math.cos(R.h[i]), px = i => R.x[i] + nx(i) * lat[i], py = i => R.y[i] + ny(i) * lat[i]; + for (let it = 0; it < 400; it++) for (let i = 0; i < n; i++) { const a = wrap(i - K), b = wrap(i + K), tx = (px(a) + px(b)) / 2 - px(i), ty = (py(a) + py(b)) / 2 - py(i); lat[i] = C.clamp(lat[i] + 0.5 * (tx * nx(i) + ty * ny(i)), -edge, edge); } + const kap = new Float64Array(n); + for (let i = 0; i < n; i++) { const a = wrap(i - K), b = wrap(i + K), x1 = px(i) - px(a), y1 = py(i) - py(a), x2 = px(b) - px(i), y2 = py(b) - py(i), l1 = Math.hypot(x1, y1), l2 = Math.hypot(x2, y2), l3 = Math.hypot(x1 + x2, y1 + y2); kap[i] = l1 && l2 && l3 ? Math.abs(2 * (x1 * y2 - y1 * x2) / (l1 * l2 * l3)) : 0; } + L = { lat, kap, prof: new Map() }; lines.set(R.name, L); + } + const key = [grip, brake, top].map(v => v.toFixed(3)).join('|'); let v = L.prof.get(key); + if (!v) { + v = new Float64Array(R.n); + for (let i = 0; i < R.n; i++) v[i] = L.kap[i] > P.aero + 1e-5 ? Math.min(top, Math.sqrt(grip / (L.kap[i] - P.aero))) : top; + for (let p = 0; p < (R.loop ? 2 : 1); p++) for (let i = R.n - 1; i >= 0; i--) { const j = i + 1 < R.n ? i + 1 : R.loop ? 0 : i, lim = Math.sqrt(v[j] * v[j] + 2 * brake * R.ds); if (lim < v[i]) v[i] = lim; } + L.prof.set(key, v); + } + return { lat: L.lat, prof: v }; + } + const lineLat = (R, lat, s) => { let i = Math.round(s / R.ds); if (R.loop) { i %= R.n; if (i < 0) i += R.n; } else i = C.clamp(i, 0, R.n - 1); return lat[i]; }; + // Speed comes from the profile, steering from pure pursuit on the wanted line. Nothing here scores "slower is safer". + // First contact on the way to a lane, in route coordinates, with the other cars at their current speed. + function contactTime(g, others, S, speed, lat) { + const rate = 4, HORIZON_S = 3; + for (let t = 0.1; t < HORIZON_S; t += 0.1) { + const dl = lat - g.lat, l = g.lat + Math.sign(dl) * Math.min(Math.abs(dl), rate * t), sp = S + speed * t; + for (const o of others) { + if (o.s <= S) continue; + const ol = o.lat + (o.vl || 0) * Math.min(t, 2), ds = o.s + o.vs * t + 0.5 * (o.a || 0) * t * t - sp, t0 = t - 0.1, ds0 = o.s + o.vs * t0 + 0.5 * (o.a || 0) * t0 * t0 - (S + speed * t0); + // Inside the window now, or it went from ahead of the bumper to behind it during this step: sampling alone misses a fast closing car. + if (Math.abs(ol - l) < CONTACT && ((ds > 0 && Math.hypot(ds, ol - l) < CONTACT) || (ds0 > 0 && ds <= 0))) return t; + } + } + return HORIZON_S; + } + // The wheel slews towards the key held and back to centre (nfscore carStep), so a target angle is tracked one substep at a time. + function steerKeys(c, target, speed, wscale) { + const rate = (speed < 15 ? 7 : speed < 40 ? 5 : 3.6) * wscale * 2 * DT, out = []; let st = c.steer; + for (let i = 0; i < HOLD_SETS; i++) { + let best = 0, bd = Infinity; + for (const k of [0, 1, -1]) { const n = st + C.clamp(k - st, -rate, rate), e = Math.abs(n - target); if (e < bd - 1e-9) { bd = e; best = k; } } + out.push(best); st += C.clamp(best - st, -rate, rate); + } + return out; + } + function planDrive(g, opt = {}) { + const R = g.route, c = g.car, P = g.P || C.PLAYER, S = g.s, speed = C.speed(c), tire = C.tireFactor(c); + const margin = opt.margin || 0.92, top = opt.top || C.TOPS[5], wscale = g.sb ? 0.45 : 1; + const line = racingLine(R, P, P.grip * tire * margin, P.brake * 0.8, top), prof = line.prof; + const others = roadUsers(g, R), base = opt.lat !== undefined ? opt.lat : lineLat(R, line.lat, S + speed * 0.8), lat = laneTarget(g, R, S, others, speed, base), onLine = lat === base && opt.lat === undefined; + // Pure pursuit from where the car will be when this packet lands, at a lookahead that grows with speed. + const lag = 0.1 * wscale, px = c.x + c.vx * lag, py = c.y + c.vy * lag, ph = c.h + c.r * lag, Ld = Math.max(7, speed * 0.62); + const sNear = C.routeNear(R, px, py, S, 8, 16), aim = C.routeAt(R, sNear + Ld, onLine ? lineLat(R, line.lat, sNear + Ld) : lat); + let alpha = Math.atan2(aim.y - py, aim.x - px) - ph; alpha = Math.atan2(Math.sin(alpha), Math.cos(alpha)); + // Nose in a wall or a cop, too slow for the front wheels to turn it: back out on opposite lock (or, with a wall behind, full lock forward). + const far = C.routeAt(R, S + 18, lat); let off = Math.atan2(far.y - c.y, far.x - c.x) - c.h; off = Math.atan2(Math.sin(off), Math.cos(off)); + const nose = C.road(c.x + Math.cos(c.h) * 3.2, c.y + Math.sin(c.h) * 3.2).d > -0.5; + if (speed < 7 && (Math.abs(off) > 0.9 || nose)) { + const clearBehind = C.road(c.x - Math.cos(c.h) * 3.5, c.y - Math.sin(c.h) * 3.5).d < -0.6, side = off > 0 ? 1 : -1; + return { keys: steerKeys(c, clearBehind ? -side : side, speed, wscale), thr: clearBehind ? 0 : HOLD_SETS, brk: clearBehind, nos: false, lat, contact: 3, why: 'recover' }; + } + const kappa = 2 * Math.sin(alpha) / Ld, delta = Math.atan(kappa * P.wheelbase), range = C.steerRange(speed / C.MPH) * Math.PI / 180; + const vlim = Math.min(C.profileAt(R, prof, S + speed * 0.2), C.profileAt(R, prof, S + speed * 0.45)); + // In a chase, slowing down is what a rolling block wants: a moving cop is steered round or rammed, never braked for. + const contact = contactTime(g, opt.ram ? others.filter(o => !o.cop) : others, S, speed, lat), over = speed > vlim + 0.8, brk = over || contact < 0.8, coast = !brk && contact < 1.2; + // Friction circle (carStep): drive force eats lateral capacity, so in a corner the throttle is only what the tyres can spare. + const grip = (P.grip + P.aero * speed * speed) * tire, ay = speed * speed * Math.abs(kappa), spare = Math.max(0, 1 - ay / grip); + const allowed = spare / 0.55 * grip * 1.1, drive = Math.max(1, C.driveAt(speed) * P.accel), thr = coast ? 0 : Math.round(HOLD_SETS * C.clamp(allowed / drive, 0.17, 1)); + const nos = !brk && !coast && (opt.forceNos ? c.nos > 0.02 && speed > 12 : c.nos > 0.02 && speed > 18 && opt.nos !== false && thr === HOLD_SETS && C.profileAt(R, prof, S + speed * 1.8) > speed + 8); + return { keys: steerKeys(c, C.clamp(delta / range, -1, 1), speed, wscale), thr: brk ? 0 : thr, brk, nos, lat, contact, why: over ? 'speed' : contact < 0.8 ? 'contact' : coast ? 'coast' : 'drive' }; + } + function toPacket(plan, extra = []) { + const holds = []; + for (let i = 0; i < HOLD_SETS; i++) { + const h = [], k = plan.keys ? plan.keys[i] : 0; + // Throttle is spread evenly through the packet: both ticks of a set see the same keys. + if (plan.brk) h.push('S'); else if (plan.thr >= HOLD_SETS || Math.floor((i + 1) * plan.thr / HOLD_SETS) > Math.floor(i * plan.thr / HOLD_SETS)) h.push('W'); + if (k) h.push(k > 0 ? 'A' : 'D'); + if (plan.nos) h.push('Shift'); + for (const [key, set] of extra) if (set === i && h.length < 4) h.push(key); + holds.push(h); + } + return { holds, mouse: [0, 0, 0] }; + } + // Staging, then the line. Pinned for a while: the original's manual reset, which costs the speed that was left, so never a first resort. + const drive = (g, opt) => { if (g.pre > 0.21) return toPacket({ thr: HOLD_SETS, brk: false, nos: false }); let cop = Infinity; for (const k of g.cops) if (!k.dead && !k.gone) cop = Math.min(cop, Math.hypot(g.car.x - k.x, g.car.y - k.y)); return toPacket(planDrive(g, opt), g.slowT > 2.5 && cop > 90 ? [['R', 0]] : []); }; // a reset near a cop flashes the car: bust distance x6, rate x4 (AIPursuit.cpp:1895-1909) + M.ctl = { planDrive, toPacket, rollout, roadUsers, copyCar, drive }; + M.scripted = function (g) { + const mode = M.MODES[g.key]; + if (mode.scripted) return mode.scripted(g); // an event with its own rules plans its own staging too + return drive(g, {}); + }; + M.oracle = M.scripted; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/quake2_remake/compact_actions.json b/environments/games/web/games/quake2_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..a752763b48276bdd912007f6e867920eaedd8354 --- /dev/null +++ b/environments/games/web/games/quake2_remake/compact_actions.json @@ -0,0 +1,165 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "quake2_remake", + "version": "quake2-compact@1", + "note": "ViZDoom-style button set: 8-way movement with run held (Shift, held in 100% of reference packets), yaw by fixed angles, a small pitch head (freelook), and one head for fire / late fire / jump / next weapon (never needed together). Late fire presses J only in sub-steps 5-6, the way the reference controller starts every burst. Previous weapon (R), crouch (L) and keyboard turn (Q/E) are left out: the weapon order cycles, so next alone reaches every weapon. One action = one 200 ms packet. Mouse: 1 count = m_yaw 0.022 x sensitivity 3 = 0.066 deg (same for pitch), so dx 152 = 10 deg; dy > 0 looks down. Sizes 9 x 7 x 3 x 5 = 945.", + "heads": [ + { + "name": "move", + "options": [ + { + "label": "none" + }, + { + "label": "forward", + "keys": [ + "W", + "Shift" + ] + }, + { + "label": "back", + "keys": [ + "S", + "Shift" + ] + }, + { + "label": "left", + "keys": [ + "A", + "Shift" + ] + }, + { + "label": "right", + "keys": [ + "D", + "Shift" + ] + }, + { + "label": "forward_left", + "keys": [ + "W", + "A", + "Shift" + ] + }, + { + "label": "forward_right", + "keys": [ + "W", + "D", + "Shift" + ] + }, + { + "label": "back_left", + "keys": [ + "S", + "A", + "Shift" + ] + }, + { + "label": "back_right", + "keys": [ + "S", + "D", + "Shift" + ] + } + ] + }, + { + "name": "turn", + "options": [ + { + "label": "none" + }, + { + "label": "left_3", + "dx": -45 + }, + { + "label": "right_3", + "dx": 45 + }, + { + "label": "left_10", + "dx": -152 + }, + { + "label": "right_10", + "dx": 152 + }, + { + "label": "left_30", + "dx": -455 + }, + { + "label": "right_30", + "dx": 455 + } + ] + }, + { + "name": "pitch", + "options": [ + { + "label": "none" + }, + { + "label": "up_2", + "dy": -30 + }, + { + "label": "down_2", + "dy": 30 + } + ] + }, + { + "name": "action", + "options": [ + { + "label": "none" + }, + { + "label": "fire", + "keys": [ + "J" + ] + }, + { + "label": "fire_late", + "subs": [ + [], + [], + [], + [], + [ + "J" + ], + [ + "J" + ] + ] + }, + { + "label": "jump", + "tap": [ + "Space" + ] + }, + { + "label": "next_weapon", + "tap": [ + "K" + ] + } + ] + } + ] +} diff --git a/environments/games/web/games/quake2_remake/draw.js b/environments/games/web/games/quake2_remake/draw.js new file mode 100644 index 0000000000000000000000000000000000000000..c229ea1575676fc75d33d2976645824d29fda8cd --- /dev/null +++ b/environments/games/web/games/quake2_remake/draw.js @@ -0,0 +1,95 @@ +/* Quake II boss arenas - Module.draw: the WebGL first-person view plus a Canvas 2D HUD in the Quake II layout + (health / ammo / armor numbers along the bottom, pickup string, pain flash), with BossBench additions: boss name, + health bar and phase, fight timer, skill / tier and the native tick rate. Read-only on the game state. */ +(function (root) { + 'use strict'; + const M = root.Quake2Game, Q = M.Q, R = M.R3; + const WEAPON_LABEL = { blaster: 'ENERGY PISTOL', shotgun: 'SHOTGUN', supershotgun: 'DOUBLE SHOTGUN', machinegun: 'MACHINEGUN', chaingun: 'CHAINGUN', + rocketlauncher: 'ROCKET LAUNCHER', hyperblaster: 'PULSE CANNON', railgun: 'COILGUN' }; + const AMMO_LABEL = { shells: 'SHELLS', bullets: 'BULLETS', rockets: 'ROCKETS', cells: 'CELLS', slugs: 'SLUGS' }; + const ITEM_LABEL = { health: 'Health', health_large: 'Large Health', stimpack: 'Med Injector', armor_shard: 'Armor Shard', armor_jacket: 'Jacket Armor', + armor_combat: 'Combat Armor', armor_body: 'Body Armor', ammo_shells: 'Shells', ammo_bullets: 'Bullets', ammo_cells: 'Cells', ammo_rockets: 'Rockets', ammo_slugs: 'Slugs' }; + const MOVE_LABEL = { + monster_supertank: { attack1: 'Chain-gun burst', end_attack1: 'Chain-gun cooldown', attack2: 'Triple rockets', pain1: 'Hurt', pain2: 'Hurt', pain3: 'Hurt', death: 'Explosion' }, + monster_boss2: { attack_pre_mg: 'Twin guns spin up', attack_mg: 'Twin machine guns', attack_post_mg: 'Machine guns wind down', attack_rocket: 'Rocket salvo', pain_light: 'Hurt', pain_heavy: 'Heavy hit', death: 'Crash' }, + monster_jorg: { start_attack1: 'Twin chain guns spin up', attack1: 'Twin chain guns', end_attack1: 'Chain guns wind down', attack2: 'Energy orb', pain1: 'Hurt', pain2: 'Hurt', pain3: 'Heavy hit', death: 'Collapse' }, + monster_makron: { sight: 'Leap out', attack3: 'Energy orb', attack4: 'Energy burst', attack5: 'Railgun aiming', pain4: 'Hurt', pain5: 'Hurt', pain6: 'Heavy hit', death2: 'Fall' }, + monster_tank_commander: { attack_blast: 'Triple blaster shot', reattack_blast: 'Blaster follow-up', attack_post_blast: 'Weapon lowered', attack_pre_rocket: 'Rockets ready', attack_fire_rocket: 'Triple rockets', + attack_post_rocket: 'Rockets end', attack_chain: 'Chain-gun sweep', attack_strike: 'heavy punch', start_run: 'Launch', pain1: 'Hurt', pain2: 'Hurt', pain3: 'Heavy hit', death: 'Fall' }, + monster_gladiator: { attack_melee: 'Blade slash', attack_gun: 'Railgun aiming', pain: 'Hurt', pain_air: 'Hurt', death: 'Fall' }, + monster_mutant: { attack: 'Claw combo', jump: 'Pounce', pain1: 'Hurt', pain2: 'Hurt', pain3: 'Hurt', death1: 'Fall', death2: 'Fall' }, + }; + function panel(c, x, y, w, h) { c.fillStyle = 'rgba(14,12,10,0.62)'; c.fillRect(x, y, w, h); c.strokeStyle = 'rgba(180,150,90,0.45)'; c.lineWidth = 1; c.strokeRect(x + 0.5, y + 0.5, w - 1, h - 1); } + function bigNumber(c, value, x, y, color, label) { + c.textAlign = 'right'; c.font = 'bold 34px Consolas, "Courier New", monospace'; c.fillStyle = '#000a'; c.fillText(String(value), x + 2, y + 2); + c.fillStyle = color; c.fillText(String(value), x, y); + c.font = '11px Consolas, monospace'; c.fillStyle = '#c8b88a'; c.fillText(label, x, y + 14); c.textAlign = 'left'; + } + M.draw = function (g, c) { + R.render(g, c); + const p = g.ents[1], W = 854, H = 480; + // pain / pickup blend (SV_CalcBlend damage_alpha, bonus_alpha) + if (p.damage_alpha > 0) { c.fillStyle = 'rgba(200,20,10,' + Math.min(0.55, p.damage_alpha) + ')'; c.fillRect(0, 0, W, H); } + if (p.bonus_alpha > 0) { c.fillStyle = 'rgba(255,230,120,' + Math.min(0.3, p.bonus_alpha) + ')'; c.fillRect(0, 0, W, H); } + if (p.health <= 0) { c.fillStyle = 'rgba(90,0,0,0.35)'; c.fillRect(0, 0, W, H); } + // crosshair + if (p.health > 0) { c.strokeStyle = 'rgba(255,240,200,0.85)'; c.lineWidth = 1.5; c.beginPath(); c.moveTo(W / 2 - 7, H / 2); c.lineTo(W / 2 - 2, H / 2); c.moveTo(W / 2 + 2, H / 2); c.lineTo(W / 2 + 7, H / 2); + c.moveTo(W / 2, H / 2 - 7); c.lineTo(W / 2, H / 2 - 2); c.moveTo(W / 2, H / 2 + 2); c.lineTo(W / 2, H / 2 + 7); c.stroke(); } + // direction of the last hit: relative yaw (Quake yaw grows to the left) -> rotation of an "ahead" marker + if (p.damage_alpha > 0.05 && p.damage_from_dir) { + const yaw = Math.atan2(p.damage_from_dir[1], p.damage_from_dir[0]) * 180 / Math.PI - p.v_angle[1], a = -yaw * Math.PI / 180; + c.save(); c.translate(W / 2, H / 2); c.rotate(a); c.fillStyle = 'rgba(255,60,40,' + Math.min(0.9, p.damage_alpha * 1.6) + ')'; + c.beginPath(); c.moveTo(0, -120); c.lineTo(-14, -98); c.lineTo(14, -98); c.closePath(); c.fill(); c.restore(); + } + // bottom status bar (Quake II order: ammo | health | armor) + panel(c, 8, H - 58, 838, 50); + const it = Q.ITEMS[p.weapon] || {}, ammo = it.ammo ? p.inv[it.ammo] : null; + bigNumber(c, ammo === null ? '--' : ammo, 120, H - 22, ammo !== null && ammo < 5 ? '#ff7050' : '#f0d070', it.ammo ? AMMO_LABEL[it.ammo] : 'NO AMMO'); + bigNumber(c, Math.max(0, p.health), 300, H - 22, p.health < 25 ? '#ff5040' : '#f0d070', 'HEALTH'); + const ak = Q.armorIndex(p); + bigNumber(c, ak ? p.inv[ak] : 0, 470, H - 22, '#9fd27a', ak ? ak.toUpperCase() + ' ARMOR' : 'ARMOR'); + c.font = 'bold 13px Consolas, monospace'; c.fillStyle = '#e8dcb8'; c.fillText(WEAPON_LABEL[p.weapon] || '', 500, H - 36); + c.font = '11px Consolas, monospace'; c.fillStyle = '#a99e84'; + const inv = Q.WEAPON_ORDER.filter(w => p.inv[w]).map(w => (w === p.weapon ? '[' : ' ') + WEAPON_LABEL[w].split(' ')[0].slice(0, 7) + (w === p.weapon ? ']' : ' ')).join(''); + c.fillText(inv, 500, H - 19); + // clock: fight timer and the native tick rate (meeting rule: HUD shows the Hz) + panel(c, 676, 8, 170, 46); c.textAlign = 'right'; c.font = 'bold 18px Consolas, monospace'; c.fillStyle = '#f0e4c0'; + c.fillText((g.t / M.hz).toFixed(1) + ' s', 838, 30); c.font = 'bold 12px Consolas, monospace'; c.fillStyle = '#9fd0ff'; c.fillText(M.hz + 'Hz · tick ' + g.t, 838, 46); c.textAlign = 'left'; + // boss bar + const h = g.health(), bi = g.bossEnt(), b = g.ents[bi], def = Q.MONSTERS[b.classname] || {}; + panel(c, 187, 8, 480, 46); + const frac = h[3] ? h[2] / h[3] : 0; + c.fillStyle = '#2a1410'; c.fillRect(197, 30, 460, 14); + c.fillStyle = b.classname === 'monster_makron' ? '#c040e0' : '#d23a20'; c.fillRect(197, 30, 460 * frac, 14); + if (g.bossClass === 'monster_jorg') { const split = g.makronHealth / h[3]; c.fillStyle = '#f2e6c0'; c.fillRect(197 + 460 * split - 1, 28, 2, 18); } + c.font = 'bold 14px "Segoe UI", "Microsoft YaHei", sans-serif'; c.fillStyle = '#f2e6c0'; + const phase = g.bossClass === 'monster_jorg' ? (b.classname === 'monster_makron' ? 'Second form' : 'First form') : 'Single phase'; + c.fillText((def.name || '') + ' · ' + phase, 197, 24); + const mv = (b.monsterinfo && MOVE_LABEL[b.classname] && MOVE_LABEL[b.classname][b.monsterinfo.currentmove]) || (b.deadflag ? 'Fall' : 'Chase'); + c.textAlign = 'right'; c.font = '12px "Segoe UI", "Microsoft YaHei", sans-serif'; c.fillStyle = '#e8b070'; + c.fillText(mv + ' ' + Math.ceil(h[2]) + ' / ' + h[3], 657, 24); c.textAlign = 'left'; + // skill / tier tag + panel(c, 8, 8, 170, 46); + c.font = 'bold 12px Consolas, monospace'; c.fillStyle = '#f0d070'; c.fillText('QUAKE II · ' + M.skillNames[g.skill].toUpperCase(), 16, 26); + c.font = '11px Consolas, monospace'; c.fillStyle = '#a99e84'; c.fillText('skill ' + g.skill + (g.tier ? ' · tier ' + g.tier : '') + ' · d=' + g.d, 16, 44); + // pickup message (3 s, like STAT_PICKUP_STRING) + if (p.pickup && g.ms < p.pickup_time) { c.font = '14px "Segoe UI", sans-serif'; c.fillStyle = '#f2e6c0'; c.textAlign = 'center'; c.fillText(ITEM_LABEL[p.pickup] || p.pickup, W / 2, H - 70); c.textAlign = 'left'; } + // telegraphs: railguns lock the shot ahead of time (Makron one frame, Gladiator 0.4 s); the Mutant's leap + const tele = (text, color) => { c.font = 'bold 15px "Segoe UI", "Microsoft YaHei", sans-serif'; c.fillStyle = color; c.textAlign = 'center'; c.fillText(text, W / 2, 78); c.textAlign = 'left'; }; + const mvName = b.monsterinfo && !b.deadflag ? b.monsterinfo.currentmove : null; + if (b.classname === 'monster_makron' && mvName === 'attack5' && b.frame >= 235 && b.frame <= 242) tele(b.frame >= 241 ? 'Railgun locked on! Strafe!' : 'Railgun charging', '#7fc8ff'); + if (b.classname === 'monster_gladiator' && mvName === 'attack_gun' && b.frame <= 48) tele('Railgun aimed at your previous position — strafe!', '#7fc8ff'); + if (b.classname === 'monster_mutant' && mvName === 'jump' && b.frame <= 4) tele('Pounce!', '#ff9a60'); + if (b.classname === 'monster_tank_commander' && mvName === 'attack_chain') tele('Chain-gun sweep: get behind cover', '#ffd070'); + // result banner: above the centre, where the play page puts its own result box over the canvas + if (g.outcome) { + c.fillStyle = 'rgba(8,6,4,0.55)'; c.fillRect(0, 96, W, 80); + c.textAlign = 'center'; c.font = 'bold 30px "Segoe UI", "Microsoft YaHei", sans-serif'; + c.fillStyle = g.outcome === 'win' ? '#f0d070' : '#ff6a50'; + c.fillText(g.outcome === 'win' ? 'Boss defeated · ' + (g.t / M.hz).toFixed(1) + ' s' : g.outcome === 'loss' ? 'You died' : 'Time up', W / 2, 147); c.textAlign = 'left'; + } + }; + M.renderStatus = ctx => R.status(ctx); + M.renderMetrics = ctx => R.metrics(ctx); + M.closeRenderer = ctx => R.close(ctx); +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/quake2_remake/game.js b/environments/games/web/games/quake2_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..ec68fae185173ffa6973b916f0d8146c37299ae0 --- /dev/null +++ b/environments/games/web/games/quake2_remake/game.js @@ -0,0 +1,292 @@ +/* Quake II (1997) boss arenas, rules q2-arena@4 - the BossBench module: cases, tiers, original arenas, the server + frame (sv_main.c SV_Frame -> SV_RunGameFrame -> g_main.c G_RunFrame) and the public declaration. + Native clock (q2-arena@3, 2026-11-06): 60 Hz, the original client at cl_maxfps 60. One BossBench tick = one host + frame of 16/17 ms: one usercmd (ClientThink -> Pmove, cmd.msec 16/17) and entity physics for that slice. Game + logic keeps the original 10 Hz server frame (g_local.h FRAMETIME 0.1): thinks fire on nextthink in ms, and the + server-frame parts run on every sixth tick. A 200 ms action packet is twelve ticks. See + Independent reimplementation from id Software's GPL-2.0 source release (commit + 372afde46e7defc9dd2d719a1732b8ace1fa096e). Arenas, items placement and loadouts are original; all art is + procedural; no game data (pak, models, textures, sounds, maps) is used. */ +(function (root) { + 'use strict'; + const N = root.NativeBench, M = root.Quake2Game, Q = M.Q; + const { copy3 } = Q; + + // ---------------- public tiers (2026-11-02) ---------------- + // Tiers on Quake II's skill cvar: easy = skill 0 Easy (the player takes half damage, the default M_CheckAttack + // chance is halved), normal = skill 1 Medium, hard = skill 3 Hard+ (no boss pain animations and a 5 s pain lock-out: + // the only skill rule that raises the aggression of every boss; it includes the skill >= 2 rules: attack chance + // doubled, the Super Tank and the Tank Commander ignore pain while firing, the Tank Commander refires). d in [0.6, 0.8) + // is skill 2 Hard. All of this is the original game's own skill cvar with its own parameters, the same fight on every + // tier, so hard stays at 0.9. Boss spawn health per tier is a BossBench extension (Quake II never scales monster + // health), calibrated to the script windows, which are the criterion (easy 20-30 s, normal 45-90 s, hard 150-240 s; the + // meeting's ~500 health is only an order of magnitude): anchors at the three tier values, linear between them, held outside. + const TIERS = { easy: 0.15, normal: 0.45, hard: 0.9 }, TIER_D = [TIERS.easy, TIERS.normal, TIERS.hard]; + const HEALTH = { + monster_supertank: [650, 4500, 10400], + monster_boss2: [620, 5000, 12500], + monster_jorg: [260, 2700, 6600], + monster_makron: [220, 2250, 5500], + monster_tank_commander: [750, 5000, 10500], + monster_gladiator: [780, 5000, 14000], + monster_mutant: [800, 5500, 13000], + }; + const SKILL_NAMES = ['Easy', 'Medium', 'Hard', 'Hard+']; + const skillOf = d => d < 0.3 ? 0 : d < 0.6 ? 1 : d < 0.8 ? 2 : 3; + const tierOf = d => Object.keys(TIERS).find(t => Math.abs(TIERS[t] - d) < 1e-9) || null; + function healthOf(classname, d) { + const h = HEALTH[classname]; + if (d <= TIER_D[0]) return h[0]; + if (d >= TIER_D[2]) return h[2]; + const k = d <= TIER_D[1] ? 0 : 1, f = (d - TIER_D[k]) / (TIER_D[k + 1] - TIER_D[k]); + return Math.round(h[k] + (h[k + 1] - h[k]) * f); + } + + // ---------------- original arenas (Quake II map units, z up; brushes are axis-aligned boxes) ---------------- + const B = (x0, y0, z0, x1, y1, z1, mat, extra) => Object.assign({ mins: [x0, y0, z0], maxs: [x1, y1, z1], contents: Q.CONTENTS_SOLID, mat }, extra || {}); + function shell(w, h, height, opts) { // floor, four walls, ceiling (sky or roof) + const t = 64, out = [B(-t, -t, -t, w + t, h + t, 0, opts.floor || 'floor')]; + out.push(B(-t, -t, 0, 0, h + t, height, opts.wall || 'wall'), B(w, -t, 0, w + t, h + t, height, opts.wall || 'wall')); + out.push(B(0, -t, 0, w, 0, height, opts.wall || 'wall'), B(0, h, 0, w, h + t, height, opts.wall || 'wall')); + out.push(B(-t, -t, height, w + t, h + t, height + t, opts.sky ? 'sky' : 'roof', opts.sky ? { sky: true } : null)); + return out; + } + const ARENAS = { + // Super Tank: a walled Strogg supply yard under an open sky; crate stacks and two pylons give cover against the + // hitscan chaingun, the open middle lets the rockets be side-stepped. + supertank: { + title: 'Walled supply yard (original layout)', size: [1664, 1664, 384], sky: 'dusk', + brushes: () => [...shell(1664, 1664, 384, { sky: true, wall: 'wall' }), + B(360, 520, 0, 456, 616, 96, 'crate'), B(1208, 520, 0, 1304, 616, 96, 'crate'), + B(360, 1048, 0, 456, 1144, 96, 'crate'), B(1208, 1048, 0, 1304, 1144, 96, 'crate'), + B(392, 552, 96, 456, 616, 160, 'crate'), B(1208, 1080, 96, 1272, 1144, 160, 'crate'), + B(768, 780, 0, 896, 884, 320, 'pylon'), + B(96, 760, 0, 160, 904, 64, 'tech'), B(1504, 760, 0, 1568, 904, 64, 'tech'), + B(560, 300, 0, 736, 340, 80, 'barrier'), B(928, 300, 0, 1104, 340, 80, 'barrier'), + ], + player: { origin: [832, 200, 24], yaw: 90 }, + boss: { classname: 'monster_supertank', origin: [832, 1430, 0], yaw: 270 }, + loadout: { weapons: ['blaster', 'shotgun', 'supershotgun', 'machinegun', 'rocketlauncher'], weapon: 'rocketlauncher', + ammo: { shells: 100, bullets: 200, rockets: 50 }, armor: ['combat', 50] }, + items: [['health_large', 160, 160], ['health_large', 1504, 160], ['health', 160, 1504], ['health', 1504, 1504], + ['health_large', 408, 832], ['health_large', 1256, 832], ['health', 832, 230], ['armor_jacket', 832, 1300], + ['ammo_rockets', 120, 832], ['ammo_rockets', 1544, 832], ['ammo_rockets', 832, 1544], ['ammo_rockets', 600, 120], ['ammo_rockets', 1064, 120], + ['ammo_shells', 832, 120], ['ammo_bullets', 120, 1200], ['ammo_bullets', 1544, 1200], ['armor_shard', 408, 680], ['armor_shard', 1256, 680], + ['armor_shard', 408, 984], ['armor_shard', 1256, 984], ['stimpack', 640, 160], ['stimpack', 1024, 160]], + }, + // Hornet: a tall hangar bay; the boss flies at the player's eye level, cargo blocks can hide the player from + // the twin machineguns but not from rockets over the top. + hornet: { + title: 'Hangar bay (original layout)', size: [1792, 1792, 512], sky: 'none', + brushes: () => [...shell(1792, 1792, 512, { sky: false, wall: 'hangar' }), + B(380, 640, 0, 572, 736, 128, 'cargo'), B(1220, 640, 0, 1412, 736, 128, 'cargo'), + B(380, 1056, 0, 572, 1152, 128, 'cargo'), B(1220, 1056, 0, 1412, 1152, 128, 'cargo'), + B(832, 832, 0, 960, 960, 512, 'pylon'), + B(0, 1600, 0, 1792, 1792, 48, 'tech'), + ], + player: { origin: [896, 220, 24], yaw: 90 }, + boss: { classname: 'monster_boss2', origin: [896, 1380, 72], yaw: 270 }, + loadout: { weapons: ['blaster', 'machinegun', 'chaingun', 'hyperblaster', 'railgun'], weapon: 'chaingun', + ammo: { bullets: 200, cells: 200, slugs: 50 }, armor: ['combat', 50] }, + items: [['health_large', 160, 160], ['health_large', 1632, 160], ['health', 160, 896], ['health', 1632, 896], + ['ammo_bullets', 896, 120], ['ammo_bullets', 896, 1500], ['ammo_slugs', 120, 520], ['ammo_slugs', 1672, 520], ['ammo_slugs', 120, 1300], ['ammo_slugs', 1672, 1300], + ['ammo_cells', 896, 600], ['ammo_cells', 300, 900], + ['armor_shard', 476, 600], ['armor_shard', 1316, 600], ['stimpack', 680, 160], ['stimpack', 1112, 160]], + }, + // Jorg + Makron: the final showdown chamber; four broad pillars for the chaingun stream, enough room for the + // 160-unit Jorg to walk around them and for BFG orbs to be outrun. + makron: { + title: 'Final showdown chamber (original layout)', size: [1920, 1920, 448], sky: 'none', + brushes: () => [...shell(1920, 1920, 448, { sky: false, wall: 'strogg' }), + B(480, 480, 0, 640, 640, 448, 'pillar'), B(1280, 480, 0, 1440, 640, 448, 'pillar'), + B(480, 1280, 0, 640, 1440, 448, 'pillar'), B(1280, 1280, 0, 1440, 1440, 448, 'pillar'), + B(864, 864, 0, 1056, 1056, 24, 'dais'), + ], + player: { origin: [960, 200, 24], yaw: 90 }, + boss: { classname: 'monster_jorg', origin: [960, 1560, 0], yaw: 270 }, + loadout: { weapons: ['blaster', 'supershotgun', 'chaingun', 'rocketlauncher', 'hyperblaster', 'railgun'], weapon: 'railgun', + ammo: { shells: 50, bullets: 200, rockets: 50, cells: 200, slugs: 50 }, armor: ['body', 100] }, + items: [['health_large', 160, 160], ['health_large', 1760, 160], ['health_large', 160, 1760], ['health_large', 1760, 1760], + ['health', 960, 140], ['ammo_slugs', 300, 960], ['ammo_slugs', 1620, 960], ['ammo_rockets', 960, 360], ['ammo_cells', 960, 1760], + ['armor_shard', 560, 720], ['armor_shard', 1360, 720], ['armor_shard', 560, 1200], ['armor_shard', 1360, 1200], + ['stimpack', 760, 160], ['stimpack', 1160, 160]], + }, + // Tank Commander: a Strogg factory floor. Machine blocks stop the chaingun sweep (19 hitscan bullets of 20 fired + // along a fixed +-40 degree arc), the open aisles leave room to side-step blaster bolts and rockets. + tank_commander: { + title: 'Factory floor (original layout)', size: [1792, 1792, 448], sky: 'none', + brushes: () => [...shell(1792, 1792, 448, { sky: false, wall: 'factory' }), + B(352, 560, 0, 608, 688, 160, 'machine'), B(1184, 560, 0, 1440, 688, 160, 'machine'), + B(352, 1104, 0, 608, 1232, 160, 'machine'), B(1184, 1104, 0, 1440, 1232, 160, 'machine'), + B(832, 832, 0, 960, 960, 448, 'pylon'), + B(640, 320, 0, 800, 352, 72, 'barrier'), B(992, 320, 0, 1152, 352, 72, 'barrier'), + ], + player: { origin: [896, 180, 24], yaw: 90 }, + boss: { classname: 'monster_tank_commander', origin: [896, 1500, 24], yaw: 270 }, + loadout: { weapons: ['blaster', 'shotgun', 'supershotgun', 'machinegun', 'chaingun', 'rocketlauncher'], weapon: 'rocketlauncher', + ammo: { shells: 100, bullets: 200, rockets: 50 }, armor: ['combat', 50] }, + items: [['health_large', 160, 160], ['health_large', 1632, 160], ['health', 160, 1632], ['health', 1632, 1632], + ['health_large', 480, 896], ['health_large', 1312, 896], ['ammo_rockets', 120, 896], ['ammo_rockets', 1672, 896], + ['ammo_rockets', 896, 1672], ['ammo_rockets', 560, 120], ['ammo_rockets', 1232, 120], ['ammo_bullets', 896, 120], + ['ammo_shells', 480, 1400], ['ammo_shells', 1312, 1400], ['armor_shard', 480, 760], ['armor_shard', 1312, 760], + ['armor_shard', 480, 1032], ['armor_shard', 1312, 1032], ['stimpack', 720, 200], ['stimpack', 1072, 200]], + }, + // Gladiator: an open-sky fighting pit. A ring of six columns breaks the railgun's line (aimed at the spot the + // player stood on 0.4 s before the shot); the floor is flat so the cleaver can always be out-run. + gladiator: { + title: 'Fighting pit (original layout)', size: [1664, 1664, 384], sky: 'dusk', + brushes: () => [...shell(1664, 1664, 384, { sky: true, wall: 'arena' }), + B(800, 400, 0, 864, 464, 320, 'column'), B(800, 1200, 0, 864, 1264, 320, 'column'), + B(456, 600, 0, 520, 664, 320, 'column'), B(1144, 600, 0, 1208, 664, 320, 'column'), + B(456, 1000, 0, 520, 1064, 320, 'column'), B(1144, 1000, 0, 1208, 1064, 320, 'column'), + B(96, 96, 0, 224, 224, 64, 'arena'), B(1440, 96, 0, 1568, 224, 64, 'arena'), + B(96, 1440, 0, 224, 1568, 64, 'arena'), B(1440, 1440, 0, 1568, 1568, 64, 'arena'), + ], + player: { origin: [832, 180, 24], yaw: 90 }, + boss: { classname: 'monster_gladiator', origin: [832, 1480, 32], yaw: 270 }, + loadout: { weapons: ['blaster', 'shotgun', 'supershotgun', 'chaingun', 'rocketlauncher', 'hyperblaster'], weapon: 'rocketlauncher', + ammo: { shells: 50, bullets: 200, rockets: 50, cells: 200 }, armor: ['combat', 50] }, + items: [['health_large', 300, 300], ['health_large', 1364, 300], ['health', 300, 1364], ['health', 1364, 1364], + ['health_large', 832, 832], ['ammo_rockets', 120, 832], ['ammo_rockets', 1544, 832], ['ammo_rockets', 832, 1544], + ['ammo_rockets', 600, 120], ['ammo_rockets', 1064, 120], ['ammo_cells', 832, 640], ['ammo_cells', 832, 1024], + ['ammo_bullets', 640, 832], ['ammo_bullets', 1024, 832], ['armor_shard', 488, 760], ['armor_shard', 1176, 760], + ['armor_shard', 488, 904], ['armor_shard', 1176, 904], ['stimpack', 640, 200], ['stimpack', 1024, 200]], + }, + // Mutant: a containment lab. No ranged attack: the mutant claws at 80 units and leaps (600 forward, 250 up) from + // 100 units out; the long benches (48 high: above the 18 step, above its 39-unit leap) and the pillars are what the + // player kites it around. + mutant: { + title: 'Containment lab (original layout)', size: [1920, 1600, 384], sky: 'none', + brushes: () => [...shell(1920, 1600, 384, { sky: false, wall: 'lab' }), + B(480, 560, 0, 864, 624, 48, 'bench'), B(1056, 560, 0, 1440, 624, 48, 'bench'), + B(480, 976, 0, 864, 1040, 48, 'bench'), B(1056, 976, 0, 1440, 1040, 48, 'bench'), + B(272, 768, 0, 368, 864, 384, 'column'), B(1552, 768, 0, 1648, 864, 384, 'column'), + B(912, 768, 0, 1008, 832, 384, 'column'), + ], + player: { origin: [960, 200, 24], yaw: 90 }, + boss: { classname: 'monster_mutant', origin: [960, 1380, 32], yaw: 270 }, + loadout: { weapons: ['blaster', 'shotgun', 'supershotgun', 'machinegun', 'chaingun'], weapon: 'supershotgun', + ammo: { shells: 100, bullets: 200 }, armor: ['combat', 50] }, + items: [['health_large', 160, 160], ['health_large', 1760, 160], ['health', 160, 1440], ['health', 1760, 1440], + ['health_large', 960, 700], ['ammo_shells', 120, 800], ['ammo_shells', 1800, 800], ['ammo_shells', 960, 1480], + ['ammo_shells', 640, 120], ['ammo_shells', 1280, 120], ['ammo_bullets', 640, 1480], ['ammo_bullets', 1280, 1480], + ['armor_shard', 672, 800], ['armor_shard', 1248, 800], ['stimpack', 800, 200], ['stimpack', 1120, 200]], + }, + }; + for (const [key, a] of Object.entries(ARENAS)) { a.key = key; Q.worlds[key] = { brushes: a.brushes() }; } + const caseKey = id => id.split('/')[1]; + // 60 Hz clock (q2-arena@3): tick t ends at floor(t * 100 / 6) ms, so host frames are 16, 17, 17 ms and every sixth + // tick lands exactly on a 100 ms server frame. + const HZ = 60, msAt = t => Math.floor(t * 100 / 6); + const STARTER = { weapons: ['blaster', 'shotgun'], weapon: 'shotgun', ammo: { shells: 50 }, armor: null }; + + const CASES = [ + { id: 'quake2/supertank', name: 'Tracked Gun Carrier' }, + { id: 'quake2/hornet', name: 'Flying Gunship' }, + { id: 'quake2/makron', name: 'Twin-Cannon Mech → Armoured Pilot' }, + { id: 'quake2/tank_commander', name: 'Chain-Gun Heavy Trooper' }, + { id: 'quake2/gladiator', name: 'Blade-Arm Gunner' }, + { id: 'quake2/mutant', name: 'Clawed Pouncer' }, + ]; + Object.assign(M, { + id: 'quake2_remake', version: 'q2-arena@4', hz: HZ, maxSeconds: 300, dimension: '3d', renderer: 'webgl-quake2', + title: 'Quake II · Boss Arena', cases: CASES, tiers: TIERS, pointerLock: true, + controls: { + 'W / S': 'Forward / backward (cl_forwardspeed 200; Pmove maximum 300)', 'A / D': 'Strafe left / right', 'Shift': 'Run (+speed doubles movement input, capped by pm_maxspeed 300)', + 'mouse dx / dy': 'Turn / pitch (freelook; sensitivity 3 × m_yaw 0.022 = 0.066° per count; pitch ±89°)', 'Q / E': 'Turn left / right with keyboard (cl_yawspeed 140°/s)', + 'Space': 'Jump (+moveup; takeoff speed 270)', 'L': 'Crouch (+movedown; speed capped at 100)', 'J / LMB': 'Fire (hold for repeated shots)', + 'K / RMB / wheel up': 'Next weapon (weapnext)', 'R / wheel down': 'Previous weapon (weapprev)', + }, + }); + + class Game { + constructor(id, seed, d) { + this.id = id; this.key = caseKey(id); this.d = d; this.skill = skillOf(d); this.tier = tierOf(d); + this.t = 0; this.framenum = 0; this.ms = 0; this.dt = 0; this.outcome = null; this.events = []; this.fx = []; this.damageLog = []; + this.rnd = seed >>> 0; this.ai = { enemy_vis: false, enemy_infront: false, enemy_range: 0, enemy_yaw: 0 }; + this.sight_entity = -1; this.sight_entity_framenum = -10; this.sound_entity = -1; this.sound_entity_framenum = -10; this.sound2_entity = -1; this.sound2_entity_framenum = -10; + this.sight_client = -1; this.bossKilled = 0; this.fxSeq = 0; + const a = ARENAS[this.key]; + // Edict layout of a single-player level: 0 world, 1 the client, 2..9 the body queue (SP_worldspawn), then the + // map entities in map order, then the eight player trail markers (PlayerTrail_Init at the end of SpawnEntities). + this.ents = [Object.assign(Q.blankEdict(), { classname: 'worldspawn', solid: Q.SOLID_BSP, movetype: 'push' }), { inuse: false, freetime: 0, classname: 'client', solid: 0 }]; + for (let k = 0; k < 8; k++) { const i = Q.spawn(this); this.ents[i].classname = 'bodyque'; } + // ED_SpawnEntities inhibits entities by SPAWNFLAG_NOT_EASY / _NOT_MEDIUM / _NOT_HARD (skill 2 and 3 are hard). + const inhibit = this.skill === 0 ? 256 : this.skill === 1 ? 512 : 1024; + for (const [type, x, y, flags] of a.items) if (!((flags || 0) & inhibit)) Q.spawnItem(this, type, [x, y, 15]); + this.bossClass = a.boss.classname; + this.makronHealth = healthOf('monster_makron', d); + const final = a.boss.classname !== 'monster_jorg'; + this.boss = Q.spawnMonster(this, a.boss.classname, a.boss.origin, a.boss.yaw, { health: healthOf(a.boss.classname, d), engage: true, final }); + this.bossMax = this.ents[this.boss].health + (final ? 0 : this.makronHealth); + for (let k = 0; k < 8; k++) { const i = Q.spawn(this); this.ents[i].classname = 'player_trail'; } + Q.playerTrailInit(this); + // skill 0 starts with Quake II's new-game inventory (InitClientPersistant: Blaster, 100 health, no armor) plus + // the first weapon of unit 1, the Shotgun with 50 shells; higher skills carry the arena kit (BossBench practice + // loadouts). + const L = this.skill === 0 ? STARTER : a.loadout, inv = { jacket: 0, combat: 0, body: 0, shells: 0, bullets: 0, rockets: 0, cells: 0, slugs: 0 }; + for (const w of L.weapons) inv[w] = 1; + Object.assign(inv, L.ammo); if (L.armor) inv[L.armor[0]] = L.armor[1]; + Q.spawnPlayer(this, { origin: a.player.origin, yaw: a.player.yaw, inventory: inv, weapon: L.weapon }); + } + // One native tick (60 Hz, q2-arena@3): a host frame of 16 or 17 ms (SV_Frame draws one rand() per host frame), + // the client's usercmd for it (ClientThink -> Pmove with cmd.msec 16/17, the original client at cl_maxfps 60), + // then entity physics for this slice of time. Thinks still fire on their nextthink in ms, so monster frames, AI + // and weapon frames keep the original 100 ms server frame; the server-frame-only parts (ClientBeginServerFrame, + // AI_SetSightClient, old_origin, ClientEndServerFrame) run on the tick that crosses a 100 ms boundary. + update(keys, pressed, mouse) { + const prevMs = this.ms, nextMs = msAt(this.t + 1), frame = nextMs % Q.FRAMETIME_MS === 0; + this.dt = (nextMs - prevMs) / 1000; + this.fx = this.fx.filter(f => nextMs - f.t0 < (f.life || 300)); + if (this.damageLog.length > 64) this.damageLog = this.damageLog.slice(-64); + Q.rand(this); + const p = this.ents[1]; + if (p.health > 0) { + this.framenum = Math.floor(prevMs / Q.FRAMETIME_MS); // usercmds run before the tick advances level.time + const cmd = Q.buildUsercmd(this, keys, pressed, mouse, nextMs - prevMs); + Q.clientThink(this, cmd); + } + this.ms = nextMs; this.framenum = Math.floor(nextMs / Q.FRAMETIME_MS); + if (frame) this.sight_client = p.inuse && p.health > 0 ? 1 : -1; // AI_SetSightClient (one client) + for (let i = 0; i < this.ents.length; i++) { + const e = this.ents[i]; + if (!e.inuse) continue; + if (frame) e.old_origin = copy3(e.origin); + if (i === 0) continue; + if (i === 1) { if (frame) Q.clientBeginServerFrame(this); continue; } + if (e.movetype === 'step') Q.physicsStep(this, i); + else if (e.movetype === 'flymissile' || e.movetype === 'toss' || e.movetype === 'bounce') Q.physicsToss(this, i); + else Q.runThink(this, i); + } + if (frame) Q.clientEndServerFrame(this); + if (!this.outcome && p.health <= 0) this.outcome = 'loss'; + else if (!this.outcome && this.bossKilled) this.outcome = 'win'; + } + health() { + const p = this.ents[1]; + let boss = 0; + for (const e of this.ents) if (e.inuse && e.svflags & Q.SVF_MONSTER && e.deadflag !== Q.DEAD_DEAD) boss += Math.max(0, e.health); + if (this.bossClass === 'monster_jorg' && !this.ents.some(e => e.inuse && e.classname === 'monster_makron')) { + const jorg = this.ents[this.boss]; + boss = (jorg.inuse && jorg.classname === 'monster_jorg' && jorg.deadflag !== Q.DEAD_DEAD ? Math.max(0, jorg.health) : 0) + this.makronHealth; + } + // Stimpacks ignore max_health (HEALTH_IGNORE_MAX), so health can exceed 100; the reported maximum follows it so + // the normalized value stays in [0, 1] as the engine contract requires. + return [Math.max(0, p.health), Math.max(100, p.health), boss, this.bossMax]; + } + bossEnt() { // the boss currently fighting (Makron once he has been spawned) + const mak = this.ents.findIndex(e => e.inuse && e.classname === 'monster_makron'); + return mak >= 0 ? mak : this.boss; + } + } + // Cosmetic effects live in the state so renders are a pure function of it; they never touch the RNG. + Q.fx = (g, kind, origin, normal, extra) => { + const life = { tracer: 100, rail: 900, explosion: 500, blood: 300, puff: 300, spark: 250, mflash: 100, gibs: 1600, railcharge: 800, blasterhit: 250, bfgblast: 600 }[kind] || 300; + g.fx.push(Object.assign({ kind, o: copy3(origin), n: normal ? copy3(normal) : null, t0: g.ms, life, id: g.fxSeq++ }, extra || {})); + if (g.fx.length > 160) g.fx.splice(0, g.fx.length - 160); + }; + Object.assign(M, { + msAt, Game, arenas: ARENAS, health: HEALTH, skillOf, tierOf, healthOf, skillNames: SKILL_NAMES, + copyGame: g => Object.assign(Object.create(Game.prototype), N.copy(g)), + }); +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/quake2_remake/index.html b/environments/games/web/games/quake2_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..a17d056d7b6e1a00d42c4bd50075dd21ba58ed32 --- /dev/null +++ b/environments/games/web/games/quake2_remake/index.html @@ -0,0 +1,7 @@ + +Quake II · Boss Arena(q2-arena@4)
    +

    Quake II · Boss Arena

    1997 original rules, independently recreated from id Software GPL source · 60 Hz simulation (10 Hz server frames) · First-person WebGL

    Back to Game Lobby
    +
    Select a boss to start

    Replays save inputs and the seed, then simulate the match again and verify the final state. Scripted Demo reads internal state for verification; it does not start RL training.

    +
    +
    + diff --git a/environments/games/web/games/quake2_remake/input-hold.js b/environments/games/web/games/quake2_remake/input-hold.js new file mode 100644 index 0000000000000000000000000000000000000000..ddd345da59abd0bfe426b052dd508a251a5160f7 --- /dev/null +++ b/environments/games/web/games/quake2_remake/input-hold.js @@ -0,0 +1,30 @@ +/* The shared shell (_native/shell.js) latches a tapped key only until the next macrotask, so a tap released before + the next native tick is lost. Since q2-arena@3 the tick is 16.7 ms (60 Hz), so a 20 ms minimum hold is enough: + this page delays every key / pointer release until 20 ms after the press. Page input only: the rules, the policy interface and recordings are + unaffected (a recording stores the keys each tick actually saw). */ +(function () { + 'use strict'; + const HOLD = 20, down = new Map(), pdown = new Map(); + const tracked = e => /^(Key[WASDJKLQER]|Space|ShiftLeft|ShiftRight|Arrow(Up|Down|Left|Right))$/.test(e.code); + const late = new WeakSet(); + window.addEventListener('keydown', e => { if (tracked(e) && !down.has(e.code)) down.set(e.code, performance.now()); }, true); + window.addEventListener('keyup', e => { + if (late.has(e) || !tracked(e)) return; + const t0 = down.get(e.code); down.delete(e.code); + const wait = t0 === undefined ? 0 : HOLD - (performance.now() - t0); + if (wait <= 0) return; + e.stopImmediatePropagation(); e.preventDefault(); + const target = e.target || window; + setTimeout(() => { const ev = new KeyboardEvent('keyup', { code: e.code, key: e.key, bubbles: true, cancelable: true }); late.add(ev); target.dispatchEvent(ev); }, wait); + }, true); + window.addEventListener('pointerdown', e => { pdown.set(e.pointerId, performance.now()); }, true); + window.addEventListener('pointerup', e => { + if (late.has(e)) return; + const t0 = pdown.get(e.pointerId); pdown.delete(e.pointerId); + const wait = t0 === undefined ? 0 : HOLD - (performance.now() - t0); + if (wait <= 0) return; + e.stopImmediatePropagation(); + const target = e.target || window; + setTimeout(() => { const ev = new PointerEvent('pointerup', { bubbles: true, button: e.button, pointerId: e.pointerId }); late.add(ev); target.dispatchEvent(ev); }, wait); + }, true); +})(); diff --git a/environments/games/web/games/quake2_remake/manifest.json b/environments/games/web/games/quake2_remake/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..1ac7979746881a63dd2c1b633a0993d092698b20 --- /dev/null +++ b/environments/games/web/games/quake2_remake/manifest.json @@ -0,0 +1,45 @@ +{ + "schema": "bossbench/game-manifest@1", + "engine": "independent", + "game": "quake2_remake", + "module": "Quake2Game", + "title": "Quake II: Boss Arena", + "dimension": "3d", + "native_hz": 60, + "max_seconds": 300, + "renderer": "webgl-quake2", + "rules": "q2-arena@4", + "cases": [ + "quake2/supertank", + "quake2/hornet", + "quake2/makron", + "quake2/tank_commander", + "quake2/gladiator", + "quake2/mutant" + ], + "scripts": [ + "_native/runtime.js", + "_boss3d/vendor/three.min.js", + "quake2_remake/q2core.js", + "quake2_remake/q2player.js", + "quake2_remake/q2monsters.js", + "quake2_remake/game.js", + "quake2_remake/scripted.js", + "quake2_remake/renderer3d.js", + "quake2_remake/draw.js" + ], + "sim_scripts": [ + "_native/runtime.js", + "quake2_remake/q2core.js", + "quake2_remake/q2player.js", + "quake2_remake/q2monsters.js", + "quake2_remake/game.js", + "quake2_remake/scripted.js" + ], + "play_page": "web/games/quake2_remake/index.html", + "scripted_controller": "Quake2Game.scripted(game) -> {holds:[6 key arrays], mouse:[dx,dy,0]}; deterministic look-ahead on copies (Quake2Game.oracle is an alias)", + "tests": [ + "quake2_remake/tests/mechanics.js" + ], + "source": "https://github.com/id-Software/Quake-2/tree/372afde46e7defc9dd2d719a1732b8ace1fa096e (GPL-2.0)" +} diff --git a/environments/games/web/games/quake2_remake/q2core.js b/environments/games/web/games/quake2_remake/q2core.js new file mode 100644 index 0000000000000000000000000000000000000000..f39a7c09ac900861aa7e0cd8b34076dfc4c8a858 --- /dev/null +++ b/environments/games/web/games/quake2_remake/q2core.js @@ -0,0 +1,264 @@ +/* Quake II (1997) boss arenas - core rules: units, Win32 CRT rand(), Quake II vector/angle helpers, the + axis-aligned brush world, box traces with CM_ClipBoxToBrush semantics and the edict slot allocator. + Independent JavaScript reimplementation written from id Software's GPL-2.0 source release + (github.com/id-Software/Quake-2, commit 372afde46e7defc9dd2d719a1732b8ace1fa096e): q_shared.c (AngleVectors, + anglemod), g_utils.c (vectoyaw, vectoangles, G_ProjectSource, G_Spawn, findradius), qcommon/cmodel.c + (CM_ClipBoxToBrush, CM_TestBoxInBrush), server/sv_world.c (SV_Trace, SV_ClipMoveToEntities). No engine code is + copied. Game data (pak files, models, textures, sounds, maps) is not part of the GPL release and none is used. */ +(function (root) { + 'use strict'; + const M = root.Quake2Game = root.Quake2Game || {}; + const Q = M.Q = M.Q || {}; + + // ---------------- constants (q_shared.h / g_local.h) ---------------- + Q.FRAMETIME_MS = 100; // g_local.h FRAMETIME 0.1, sv_main.c sv.time = framenum*100 + Q.CONTENTS_SOLID = 1; Q.CONTENTS_WINDOW = 2; Q.CONTENTS_LAVA = 8; Q.CONTENTS_SLIME = 16; Q.CONTENTS_WATER = 32; + Q.CONTENTS_PLAYERCLIP = 0x10000; Q.CONTENTS_MONSTERCLIP = 0x20000; Q.CONTENTS_MONSTER = 0x2000000; Q.CONTENTS_DEADMONSTER = 0x4000000; + Q.MASK_SOLID = Q.CONTENTS_SOLID | Q.CONTENTS_WINDOW; + Q.MASK_PLAYERSOLID = Q.CONTENTS_SOLID | Q.CONTENTS_PLAYERCLIP | Q.CONTENTS_WINDOW | Q.CONTENTS_MONSTER; + Q.MASK_MONSTERSOLID = Q.CONTENTS_SOLID | Q.CONTENTS_MONSTERCLIP | Q.CONTENTS_WINDOW | Q.CONTENTS_MONSTER; + Q.MASK_SHOT = Q.CONTENTS_SOLID | Q.CONTENTS_MONSTER | Q.CONTENTS_WINDOW | Q.CONTENTS_DEADMONSTER; + Q.MASK_OPAQUE = Q.CONTENTS_SOLID | Q.CONTENTS_SLIME | Q.CONTENTS_LAVA; + Q.MASK_WATER = Q.CONTENTS_WATER | Q.CONTENTS_LAVA | Q.CONTENTS_SLIME; + Q.SOLID_NOT = 0; Q.SOLID_TRIGGER = 1; Q.SOLID_BBOX = 2; Q.SOLID_BSP = 3; + Q.SVF_NOCLIENT = 1; Q.SVF_DEADMONSTER = 2; Q.SVF_MONSTER = 4; + Q.FL_FLY = 1; Q.FL_SWIM = 2; Q.FL_IMMUNE_LASER = 4; Q.FL_PARTIALGROUND = 256; Q.FL_NO_KNOCKBACK = 2048; + Q.DAMAGE_NO = 0; Q.DAMAGE_YES = 1; Q.DAMAGE_AIM = 2; + Q.DAMAGE_RADIUS = 1; Q.DAMAGE_NO_ARMOR = 2; Q.DAMAGE_ENERGY = 4; Q.DAMAGE_NO_KNOCKBACK = 8; Q.DAMAGE_BULLET = 16; + Q.DEAD_NO = 0; Q.DEAD_DYING = 1; Q.DEAD_DEAD = 2; + Q.STEPSIZE = 18; Q.MELEE_DISTANCE = 80; Q.DIST_EPSILON = 0.03125; + Q.RANGE_MELEE = 0; Q.RANGE_NEAR = 1; Q.RANGE_MID = 2; Q.RANGE_FAR = 3; + Q.SV_GRAVITY = 800; Q.SV_MAXVELOCITY = 2000; Q.SV_STOPSPEED = 100; Q.SV_FRICTION = 6; + Q.YAW = 1; Q.PITCH = 0; Q.ROLL = 2; + + // ---------------- Win32 CRT rand() (the shipped 1997 build is MSVC; Quake II never calls srand) ---------------- + // holdrand = holdrand * 214013 + 2531011; return (holdrand >> 16) & 0x7fff. The BossBench engine seed is the + // initial holdrand. random() and crandom() are the g_local.h macros. + Q.rand = g => { g.rnd = (Math.imul(g.rnd, 214013) + 2531011) >>> 0; return (g.rnd >>> 16) & 0x7fff; }; + Q.random = g => (Q.rand(g) & 0x7fff) / 0x7fff; + Q.crandom = g => 2 * (Q.random(g) - 0.5); + Q.drawRand = (g, n) => { for (let i = 0; i < n; i++) Q.rand(g); }; // RNG draws of cosmetic effects (debris/gibs) + + // ---------------- vectors (vec3_t as [x, y, z]) ---------------- + // Deterministic trigonometry. Math.sin / Math.cos / Math.atan2 can differ in the last bit between V8 builds + // (Node vs Chrome, measured in this project), and the simulation must replay bit-identically in Node + // (calibration, page example recordings) and in the browser (harness, play page). These are fdlibm's kernels + // (k_sin.c, k_cos.c, s_atan.c, e_atan2.c) evaluated with + - * / only, Cody-Waite range reduction for |x| < 2^20. + const PIO2_1 = 1.57079632673412561417e+00, PIO2_1T = 6.07710050650619224932e-11, INVPIO2 = 6.36619772367581382433e-01; + const S1 = -1.66666666666666324348e-01, S2 = 8.33333333332248946124e-03, S3 = -1.98412698298579493134e-04, + S4 = 2.75573137070700676789e-06, S5 = -2.50507602534068634195e-08, S6 = 1.58969099521155010221e-10; + const C1 = 4.16666666666666019037e-02, C2 = -1.38888888888741095749e-03, C3 = 2.48015872894767294178e-05, + C4 = -2.75573143513906633035e-07, C5 = 2.08757232129817482790e-09, C6 = -1.13596475577881948265e-11; + const ksin = x => { const z = x * x; return x + x * z * (S1 + z * (S2 + z * (S3 + z * (S4 + z * (S5 + z * S6))))); }; + const kcos = x => { const z = x * x; return 1 - 0.5 * z + z * z * (C1 + z * (C2 + z * (C3 + z * (C4 + z * (C5 + z * C6))))); }; + function reduce(x) { const k = Math.round(x * INVPIO2); return [k & 3, (x - k * PIO2_1) - k * PIO2_1T]; } + Q.sin = x => { const [q, r] = reduce(x); return q === 0 ? ksin(r) : q === 1 ? kcos(r) : q === 2 ? -ksin(r) : -kcos(r); }; + Q.cos = x => { const [q, r] = reduce(x); return q === 0 ? kcos(r) : q === 1 ? -ksin(r) : q === 2 ? -kcos(r) : ksin(r); }; + const ATANHI = [4.63647609000806093515e-01, 7.85398163397448278999e-01, 9.82793723247329054082e-01, 1.57079632679489655800e+00]; + const ATANLO = [2.26987774529616870924e-17, 3.06161699786838301793e-17, 1.39033110312309984516e-17, 6.12323399573676603587e-17]; + const AT = [3.33333333333329318027e-01, -1.99999999998764832476e-01, 1.42857142725034663711e-01, -1.11111104054623557880e-01, + 9.09088713343650656196e-02, -7.69187620504482999495e-02, 6.66107313738753120669e-02, -5.83357013379057348645e-02, + 4.97687799461593236017e-02, -3.65315727442169155270e-02, 1.62858201153657823623e-02]; + function atan(x) { + const neg = x < 0; let a = neg ? -x : x, id = -1; + if (a !== a) return a; + if (a >= 7.378697629483821e+19) return neg ? -(ATANHI[3] + ATANLO[3]) : ATANHI[3] + ATANLO[3]; // >= 2^66 + if (a < 0.4375) { if (a < 1.862645149230957e-09) return x; } + else if (a < 1.1875) { if (a < 0.6875) { id = 0; a = (2 * a - 1) / (2 + a); } else { id = 1; a = (a - 1) / (a + 1); } } + else if (a < 2.4375) { id = 2; a = (a - 1.5) / (1 + 1.5 * a); } + else { id = 3; a = -1 / a; } + const z = a * a, w = z * z; + const s1 = z * (AT[0] + w * (AT[2] + w * (AT[4] + w * (AT[6] + w * (AT[8] + w * AT[10]))))); + const s2 = w * (AT[1] + w * (AT[3] + w * (AT[5] + w * (AT[7] + w * AT[9])))); + if (id < 0) { const r = a - a * (s1 + s2); return neg ? -r : r; } + const r = ATANHI[id] - ((a * (s1 + s2) - ATANLO[id]) - a); + return neg ? -r : r; + } + const PI = 3.1415926535897931160e+00, PI_LO = 1.2246467991473531772e-16; + Q.atan2 = (y, x) => { + if (x !== x || y !== y) return NaN; + if (y === 0) return (x > 0 || (x === 0 && 1 / x > 0)) ? y : (1 / y > 0 ? PI : -PI); + if (x === 0) return y > 0 ? PI / 2 : -PI / 2; + const z = atan(Math.abs(y / x)); + if (x > 0) return y > 0 ? z : -z; + return y > 0 ? PI - (z - PI_LO) : (z - PI_LO) - PI; + }; + const DEG = Math.PI / 180; + Q.add = (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]]; + Q.sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; + Q.scale = (a, s) => [a[0] * s, a[1] * s, a[2] * s]; + Q.ma = (a, s, b) => [a[0] + s * b[0], a[1] + s * b[1], a[2] + s * b[2]]; // VectorMA + Q.dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + Q.len = a => Math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]); + Q.cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; + Q.norm = a => { const l = Q.len(a); return l ? [a[0] / l, a[1] / l, a[2] / l] : [0, 0, 0]; }; // VectorNormalize + Q.eq = (a, b) => a[0] === b[0] && a[1] === b[1] && a[2] === b[2]; + Q.copy3 = a => [a[0], a[1], a[2]]; + Q.angleVectors = angles => { + const y = angles[1] * DEG, p = angles[0] * DEG, r = angles[2] * DEG; + const sy = Q.sin(y), cy = Q.cos(y), sp = Q.sin(p), cp = Q.cos(p), sr = Q.sin(r), cr = Q.cos(r); + return { + forward: [cp * cy, cp * sy, -sp], + right: [-1 * sr * sp * cy + -1 * cr * -sy, -1 * sr * sp * sy + -1 * cr * cy, -1 * sr * cp], + up: [cr * sp * cy + -sr * -sy, cr * sp * sy + -sr * cy, cr * cp], + }; + }; + // anglemod: 16-bit wrap; vectoyaw / vectoangles truncate to whole degrees exactly as g_utils.c does. + Q.anglemod = a => (360 / 65536) * (Math.trunc(a * (65536 / 360)) & 65535); + Q.vectoyaw = v => { + if (v[0] === 0) return v[1] > 0 ? 90 : v[1] < 0 ? -90 : 0; + let yaw = Math.trunc(Q.atan2(v[1], v[0]) * 180 / Math.PI); + if (yaw < 0) yaw += 360; + return yaw; + }; + Q.vectoangles = v => { + let yaw, pitch; + if (v[1] === 0 && v[0] === 0) { yaw = 0; pitch = v[2] > 0 ? 90 : 270; } + else { + if (v[0]) yaw = Math.trunc(Q.atan2(v[1], v[0]) * 180 / Math.PI); else yaw = v[1] > 0 ? 90 : -90; + if (yaw < 0) yaw += 360; + const forward = Math.sqrt(v[0] * v[0] + v[1] * v[1]); + pitch = Math.trunc(Q.atan2(v[2], forward) * 180 / Math.PI); + if (pitch < 0) pitch += 360; + } + return [-pitch, yaw, 0]; + }; + Q.projectSource = (point, d, forward, right) => [ // G_ProjectSource + point[0] + forward[0] * d[0] + right[0] * d[1], + point[1] + forward[1] * d[0] + right[1] * d[1], + point[2] + forward[2] * d[0] + right[2] * d[1] + d[2]]; + Q.ANGLE2SHORT = x => { const s = Math.trunc(x * 65536 / 360) & 65535; return s > 32767 ? s - 65536 : s; }; + Q.SHORT2ANGLE = x => x * (360 / 65536); + + // ---------------- world: axis-aligned brushes ---------------- + // A brush is {mins, maxs, contents, mat}. The world of a case is static, so it is kept outside the game state + // (looked up by case key) and never copied or hashed per tick. + Q.worlds = {}; + // CM_ClipBoxToBrush on the six axial planes of one box brush, with the trace box pushed into each plane. + function clipBoxToBox(tr, start, end, mins, maxs, bmin, bmax, contents, isPoint, sky) { + let enterfrac = -1, leavefrac = 1, clip = -1, getout = false, startout = false; + for (let k = 0; k < 6; k++) { + const axis = k >> 1, positive = (k & 1) === 0; + let dist = positive ? bmax[axis] : -bmin[axis]; + if (!isPoint) dist -= positive ? mins[axis] : -maxs[axis]; + const d1 = (positive ? start[axis] : -start[axis]) - dist, d2 = (positive ? end[axis] : -end[axis]) - dist; + if (d2 > 0) getout = true; + if (d1 > 0) startout = true; + if (d1 > 0 && d2 >= d1) return false; // completely in front of this face + if (d1 <= 0 && d2 <= 0) continue; + if (d1 > d2) { const f = (d1 - Q.DIST_EPSILON) / (d1 - d2); if (f > enterfrac) { enterfrac = f; clip = k; } } + else { const f = (d1 + Q.DIST_EPSILON) / (d1 - d2); if (f < leavefrac) leavefrac = f; } + } + if (!startout) { tr.startsolid = true; if (!getout) tr.allsolid = true; return true; } + if (enterfrac < leavefrac && enterfrac > -1 && enterfrac < tr.fraction) { + if (enterfrac < 0) enterfrac = 0; + tr.fraction = enterfrac; const axis = clip >> 1, n = [0, 0, 0]; n[axis] = (clip & 1) === 0 ? 1 : -1; + tr.normal = n; tr.contents = contents; tr.sky = !!sky; return true; + } + return false; + } + // CM_TestBoxInBrush (start == end): inside unless outside some pushed plane. + function testBoxInBox(tr, p, mins, maxs, bmin, bmax, contents) { + for (let axis = 0; axis < 3; axis++) { + if (p[axis] + mins[axis] - bmax[axis] > 0) return false; // pushed +axis plane: dot(p) - (bmax - mins) + if (bmin[axis] - (p[axis] + maxs[axis]) > 0) return false; + } + tr.startsolid = tr.allsolid = true; tr.fraction = 0; tr.contents = contents; return true; + } + function boxTrace(brushes, start, mins, maxs, end, mask) { + const tr = { fraction: 1, startsolid: false, allsolid: false, normal: [0, 0, 0], contents: 0, ent: 0, sky: false }; + const isPoint = !mins[0] && !mins[1] && !mins[2] && !maxs[0] && !maxs[1] && !maxs[2]; + const position = start[0] === end[0] && start[1] === end[1] && start[2] === end[2]; + for (const b of brushes) { + if (!(b.contents & mask)) continue; + if (position) { if (testBoxInBox(tr, start, mins, maxs, b.mins, b.maxs, b.contents)) return tr; continue; } + clipBoxToBox(tr, start, end, mins, maxs, b.mins, b.maxs, b.contents, isPoint, b.sky); + if (!tr.fraction) return tr; // CM_TraceToLeaf stops once something is hit at 0 + } + return tr; + } + const Z3 = [0, 0, 0]; + // SV_Trace: world first, then SOLID_BBOX edicts (owner/passent rules of SV_ClipMoveToEntities). + Q.trace = (g, start, mins, maxs, end, passent, mask) => { + mins = mins || Z3; maxs = maxs || Z3; + const tr = boxTrace(Q.worlds[g.key].brushes, start, mins, maxs, end, mask); + if (tr.fraction !== 0 && (mask & (Q.CONTENTS_MONSTER | Q.CONTENTS_DEADMONSTER))) { + const pass = passent >= 0 ? g.ents[passent] : null; + for (let i = 1; i < g.ents.length; i++) { + const e = g.ents[i]; + if (!e.inuse || e.solid !== Q.SOLID_BBOX || i === passent) continue; + if (tr.allsolid) break; + if (pass && (e.owner === passent || pass.owner === i)) continue; + if (!(mask & Q.CONTENTS_DEADMONSTER) && (e.svflags & Q.SVF_DEADMONSTER)) continue; + if (!(mask & Q.CONTENTS_MONSTER)) continue; + const t2 = { fraction: 1, startsolid: false, allsolid: false, normal: [0, 0, 0], contents: 0, ent: i }; + const bmin = Q.add(e.origin, e.mins), bmax = Q.add(e.origin, e.maxs); + if (start[0] === end[0] && start[1] === end[1] && start[2] === end[2]) testBoxInBox(t2, start, mins, maxs, bmin, bmax, Q.CONTENTS_MONSTER); + else clipBoxToBox(t2, start, end, mins, maxs, bmin, bmax, Q.CONTENTS_MONSTER, !mins[0] && !mins[1] && !mins[2] && !maxs[0] && !maxs[1] && !maxs[2]); + if (t2.allsolid || t2.startsolid || t2.fraction < tr.fraction) { + const wasStart = tr.startsolid; + tr.fraction = t2.fraction; tr.normal = t2.normal; tr.contents = t2.contents; tr.ent = i; tr.allsolid = t2.allsolid; tr.sky = false; + tr.startsolid = wasStart || t2.startsolid; + } else if (t2.startsolid) tr.startsolid = true; + } + } + tr.endpos = tr.fraction === 1 ? Q.copy3(end) : [start[0] + tr.fraction * (end[0] - start[0]), start[1] + tr.fraction * (end[1] - start[1]), start[2] + tr.fraction * (end[2] - start[2])]; + return tr; + }; + Q.pointcontents = (g, p) => { + let c = 0; + for (const b of Q.worlds[g.key].brushes) + if (p[0] >= b.mins[0] && p[0] <= b.maxs[0] && p[1] >= b.mins[1] && p[1] <= b.maxs[1] && p[2] >= b.mins[2] && p[2] <= b.maxs[2]) c |= b.contents; + return c; + }; + // SV_LinkEdict absolute bounds, expanded by one unit on every side. + Q.absmin = e => [e.origin[0] + e.mins[0] - 1, e.origin[1] + e.mins[1] - 1, e.origin[2] + e.mins[2] - 1]; + Q.absmax = e => [e.origin[0] + e.maxs[0] + 1, e.origin[1] + e.maxs[1] + 1, e.origin[2] + e.maxs[2] + 1]; + Q.boxesOverlap = (a, b) => { + const amin = Q.absmin(a), amax = Q.absmax(a), bmin = Q.absmin(b), bmax = Q.absmax(b); + return amin[0] <= bmax[0] && amax[0] >= bmin[0] && amin[1] <= bmax[1] && amax[1] >= bmin[1] && amin[2] <= bmax[2] && amax[2] >= bmin[2]; + }; + Q.center = e => [e.origin[0] + (e.mins[0] + e.maxs[0]) * 0.5, e.origin[1] + (e.mins[1] + e.maxs[1]) * 0.5, e.origin[2] + (e.mins[2] + e.maxs[2]) * 0.5]; + // findradius: inuse, not SOLID_NOT, centre of the box within rad. + Q.findradius = (g, org, rad) => { + const out = []; + for (let i = 1; i < g.ents.length; i++) { + const e = g.ents[i]; + if (!e.inuse || e.solid === Q.SOLID_NOT) continue; + if (Q.len(Q.sub(org, Q.center(e))) > rad) continue; + out.push(i); + } + return out; + }; + + // ---------------- edicts ---------------- + // Slot 0 is the world, slot 1 the player (maxclients 1). G_Spawn reuses a free slot freed more than 0.5 s ago + // (or at level start); the slot index decides the think order inside G_RunFrame. + Q.blankEdict = () => ({ + inuse: true, classname: '', origin: [0, 0, 0], old_origin: [0, 0, 0], velocity: [0, 0, 0], avelocity: [0, 0, 0], angles: [0, 0, 0], + mins: [0, 0, 0], maxs: [0, 0, 0], solid: Q.SOLID_NOT, clipmask: 0, svflags: 0, flags: 0, movetype: 'none', owner: -1, enemy: -1, + takedamage: 0, health: 0, max_health: 0, mass: 0, deadflag: 0, think: null, nextthink: 0, touch: null, groundentity: -1, + freetime: 0, viewheight: 0, frame: 0, dmg: 0, radius_dmg: 0, dmg_radius: 0, count: 0, spawnflags: 0, gravity: 1, waterlevel: 0, linkcount: 0, + }); + Q.spawn = g => { + for (let i = 2; i < g.ents.length; i++) { + const e = g.ents[i]; + if (!e.inuse && (e.freetime < 2000 || g.ms - e.freetime > 500)) { g.ents[i] = Q.blankEdict(); return i; } + } + g.ents.push(Q.blankEdict()); return g.ents.length - 1; + }; + Q.freeEdict = (g, i) => { g.ents[i] = { inuse: false, freetime: g.ms, classname: 'freed', solid: Q.SOLID_NOT }; }; + // SV_RunThink: nextthink in ms; think when nextthink <= level.time (+1 ms tolerance of the 0.001 s epsilon). + Q.runThink = (g, i) => { + const e = g.ents[i]; + if (!e.nextthink || e.nextthink <= 0 || e.nextthink > g.ms + 1) return true; + e.nextthink = 0; + const fn = Q.THINK[e.think]; + if (!fn) throw Error('NULL think ' + e.think); + fn(g, i); + return false; + }; + Q.THINK = { G_FreeEdict: (g, i) => Q.freeEdict(g, i) }; + Q.TOUCH = {}; + Q.event = (g, type, data) => { g.events.push(Object.assign({ type, t: g.t }, data || {})); }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/quake2_remake/q2monsters.js b/environments/games/web/games/quake2_remake/q2monsters.js new file mode 100644 index 0000000000000000000000000000000000000000..f3e237a05dcb5fcf747aed8805d4b0727a27764a --- /dev/null +++ b/environments/games/web/games/quake2_remake/q2monsters.js @@ -0,0 +1,1181 @@ +/* Quake II (1997) boss arenas - monsters: the monster framework (g_monster.c M_MoveFrame, monster_think, + monster_start_go, M_CheckGround, monster_fire_*; g_ai.c ai_stand / ai_run / ai_charge / ai_move, + ai_checkattack, M_CheckAttack, FoundTarget / HuntTarget, visible / infront / range; m_move.c SV_movestep for + walking and flying monsters, M_CheckBottom, M_ChangeYaw, SV_StepDirection, SV_NewChaseDir, M_MoveToGoal; + g_phys.c SV_Physics_Step / SV_FlyMove; g_combat.c M_ReactToDamage) and the six boss fights of this game: + Super Tank (m_supertank.c, models/monsters/boss1), Hornet (m_boss2.c, boss2), Jorg + Makron (m_boss31.c / + m_boss32.c, boss3), Tank Commander (m_tank.c), Gladiator (m_gladiator.c) and Mutant (m_mutant.c). Move tables keep the original absolute frame numbers (m_*.h) because the code tests them. + Independent reimplementation from the GPL-2.0 source release, commit 372afde46e7defc9dd2d719a1732b8ace1fa096e. */ +(function (root) { + 'use strict'; + const M = root.Quake2Game, Q = M.Q; + const { add, sub, scale, ma, dot, len, norm, copy3 } = Q; + const AI_STAND_GROUND = 1, AI_TEMP_STAND_GROUND = 2, AI_SOUND_TARGET = 4, AI_LOST_SIGHT = 8, AI_PURSUIT_LAST_SEEN = 16, + AI_PURSUE_NEXT = 32, AI_PURSUE_TEMP = 64, AI_HOLD_FRAME = 128, AI_GOOD_GUY = 256, AI_BRUTAL = 512, AI_DUCKED = 2048, AI_COMBAT_POINT = 4096; + const AS_STRAIGHT = 1, AS_SLIDING = 2, AS_MELEE = 3, AS_MISSILE = 4; + Q.AS = { AS_STRAIGHT, AS_SLIDING, AS_MELEE, AS_MISSILE }; + + // ---------------- move tables ---------------- + // name: [firstframe, lastframe, frames, endfunc]; frame token [:][x], ai s/w/r/c/m/t/n. + const AI_OF = { s: 'stand', w: 'walk', r: 'run', c: 'charge', m: 'move', t: 'turn', n: null }; + function moves(spec) { + const out = {}; + for (const [name, [first, last, frames, end]] of Object.entries(spec)) { + const list = []; + for (const tok of frames.trim().split(/\s+/)) { + const m = /^([swrcmtn])(-?\d+(?:\.\d+)?)(?::(\w+?))?(?:x(\d+))?$/.exec(tok); + if (!m) throw Error('bad frame token ' + tok); + for (let n = Number(m[4] || 1); n > 0; n--) list.push([AI_OF[m[1]], Number(m[2]), m[3] && m[3] !== 'NULL' ? m[3] : null]); + } + if (list.length !== last - first + 1) throw Error('frame count ' + name); + out[name] = { first, last, frames: list, end }; + } + return out; + } + const DEFS = Q.MONSTERS = {}; + + // ---------------- helpers (g_ai.c) ---------------- + const eye = e => [e.origin[0], e.origin[1], e.origin[2] + e.viewheight]; + Q.visible = (g, self, other) => { + const tr = Q.trace(g, eye(g.ents[self]), null, null, eye(g.ents[other]), self, Q.MASK_OPAQUE); + return tr.fraction === 1.0; + }; + Q.visiblePoint = (g, self, point) => Q.trace(g, eye(g.ents[self]), null, null, point, self, Q.MASK_OPAQUE).fraction === 1.0; + Q.infront = (g, self, other) => { + const s = g.ents[self], forward = Q.angleVectors(s.angles).forward; + return dot(norm(sub(g.ents[other].origin, s.origin)), forward) > 0.3; + }; + Q.range = (g, self, other) => { + const l = len(sub(g.ents[self].origin, g.ents[other].origin)); + return l < Q.MELEE_DISTANCE ? Q.RANGE_MELEE : l < 500 ? Q.RANGE_NEAR : l < 1000 ? Q.RANGE_MID : Q.RANGE_FAR; + }; + const link = (g, i) => { g.ents[i].linkcount++; }; + const def = e => DEFS[e.classname]; + const setMove = (e, name) => { e.monsterinfo.currentmove = name; }; + const call = (g, i, fn, ...args) => { const f = def(g.ents[i])[fn]; if (f) f(g, i, ...args); }; + + // ---------------- movement (m_move.c) ---------------- + function checkBottom(g, i) { + const e = g.ents[i], mins = add(e.origin, e.mins), maxs = add(e.origin, e.maxs); + let easy = true; + for (let x = 0; x <= 1 && easy; x++) for (let y = 0; y <= 1; y++) { + const p = [x ? maxs[0] : mins[0], y ? maxs[1] : mins[1], mins[2] - 1]; + if (Q.pointcontents(g, p) !== Q.CONTENTS_SOLID) { easy = false; break; } + } + if (easy) return true; + const start = [(mins[0] + maxs[0]) * 0.5, (mins[1] + maxs[1]) * 0.5, mins[2]], stop = [start[0], start[1], start[2] - 2 * Q.STEPSIZE]; + let tr = Q.trace(g, start, null, null, stop, i, Q.MASK_MONSTERSOLID); + if (tr.fraction === 1.0) return false; + const mid = tr.endpos[2]; + for (let x = 0; x <= 1; x++) for (let y = 0; y <= 1; y++) { + const s = [x ? maxs[0] : mins[0], y ? maxs[1] : mins[1], mins[2]], t = [s[0], s[1], stop[2]]; + tr = Q.trace(g, s, null, null, t, i, Q.MASK_MONSTERSOLID); + if (tr.fraction === 1.0 || mid - tr.endpos[2] > Q.STEPSIZE) return false; + } + return true; + } + function movestep(g, i, move, relink) { + const e = g.ents[i], oldorg = copy3(e.origin); + if (e.flags & (Q.FL_SWIM | Q.FL_FLY)) { + for (let k = 0; k < 2; k++) { + const neworg = add(e.origin, move); + if (k === 0 && e.enemy >= 0) { + if (e.goalentity < 0) e.goalentity = e.enemy; + const goal = g.ents[e.goalentity], dz = e.origin[2] - goal.origin[2]; + if (goal.client) { if (dz > 40) neworg[2] -= 8; if (dz < 30) neworg[2] += 8; } + else { if (dz > 8) neworg[2] -= 8; else if (dz > 0) neworg[2] -= dz; else if (dz < -8) neworg[2] += 8; else neworg[2] += dz; } + } + const tr = Q.trace(g, e.origin, e.mins, e.maxs, neworg, i, Q.MASK_MONSTERSOLID); + if (tr.fraction === 1) { e.origin = copy3(tr.endpos); if (relink) link(g, i); return true; } + if (e.enemy < 0) break; + } + return false; + } + const stepsize = (e.monsterinfo.aiflags & 0) ? 1 : Q.STEPSIZE; + const neworg = add(e.origin, move); neworg[2] += stepsize; + const end = copy3(neworg); end[2] -= stepsize * 2; + let tr = Q.trace(g, neworg, e.mins, e.maxs, end, i, Q.MASK_MONSTERSOLID); + if (tr.allsolid) return false; + if (tr.startsolid) { + neworg[2] -= stepsize; + tr = Q.trace(g, neworg, e.mins, e.maxs, end, i, Q.MASK_MONSTERSOLID); + if (tr.allsolid || tr.startsolid) return false; + } + if (tr.fraction === 1) { + if (e.flags & Q.FL_PARTIALGROUND) { e.origin = add(e.origin, move); if (relink) link(g, i); e.groundentity = -1; return true; } + return false; // walked off an edge + } + e.origin = copy3(tr.endpos); + if (!checkBottom(g, i)) { + if (e.flags & Q.FL_PARTIALGROUND) { if (relink) link(g, i); return true; } + e.origin = oldorg; return false; + } + e.flags &= ~Q.FL_PARTIALGROUND; + e.groundentity = tr.ent; + if (relink) link(g, i); + return true; + } + Q.changeYaw = (g, i) => { // M_ChangeYaw + const e = g.ents[i], current = Q.anglemod(e.angles[1]), ideal = e.ideal_yaw; + if (current === ideal) return; + let move = ideal - current; const speed = e.yaw_speed; + if (ideal > current) { if (move >= 180) move -= 360; } else { if (move <= -180) move += 360; } + if (move > 0) { if (move > speed) move = speed; } else { if (move < -speed) move = -speed; } + e.angles[1] = Q.anglemod(current + move); + }; + function stepDirection(g, i, yaw, dist) { + const e = g.ents[i]; + e.ideal_yaw = yaw; Q.changeYaw(g, i); + const r = yaw * Math.PI * 2 / 360, move = [Q.cos(r) * dist, Q.sin(r) * dist, 0], old = copy3(e.origin); + if (movestep(g, i, move, false)) { + const delta = e.angles[1] - e.ideal_yaw; + if (delta > 45 && delta < 315) e.origin = old; // not turned far enough, so don't take the step + link(g, i); + return true; + } + link(g, i); + return false; + } + function newChaseDir(g, i, goal, dist) { + const e = g.ents[i]; + if (goal < 0) return; + const olddir = Q.anglemod(Math.trunc(e.ideal_yaw / 45) * 45), turnaround = Q.anglemod(olddir - 180); + const gorg = g.ents[goal].origin, deltax = gorg[0] - e.origin[0], deltay = gorg[1] - e.origin[1], d = [0, 0, 0]; + d[1] = deltax > 10 ? 0 : deltax < -10 ? 180 : -1; + d[2] = deltay < -10 ? 270 : deltay > 10 ? 90 : -1; + if (d[1] !== -1 && d[2] !== -1) { + const tdir = d[1] === 0 ? (d[2] === 90 ? 45 : 315) : (d[2] === 90 ? 135 : 215); + if (tdir !== turnaround && stepDirection(g, i, tdir, dist)) return; + } + if (((Q.rand(g) & 3) & 1) || Math.abs(Math.trunc(deltay)) > Math.abs(Math.trunc(deltax))) { const t = d[1]; d[1] = d[2]; d[2] = t; } + if (d[1] !== -1 && d[1] !== turnaround && stepDirection(g, i, d[1], dist)) return; + if (d[2] !== -1 && d[2] !== turnaround && stepDirection(g, i, d[2], dist)) return; + if (olddir !== -1 && stepDirection(g, i, olddir, dist)) return; + if (Q.rand(g) & 1) { for (let t = 0; t <= 315; t += 45) if (t !== turnaround && stepDirection(g, i, t, dist)) return; } + else { for (let t = 315; t >= 0; t -= 45) if (t !== turnaround && stepDirection(g, i, t, dist)) return; } + if (turnaround !== -1 && stepDirection(g, i, turnaround, dist)) return; + e.ideal_yaw = olddir; // can't move + if (!checkBottom(g, i)) e.flags |= Q.FL_PARTIALGROUND; + } + function closeEnough(g, i, goal, dist) { + const e = g.ents[i], t = g.ents[goal], amin = Q.absmin(e), amax = Q.absmax(e), gmin = Q.absmin(t), gmax = Q.absmax(t); + for (let k = 0; k < 3; k++) { if (gmin[k] > amax[k] + dist) return false; if (gmax[k] < amin[k] - dist) return false; } + return true; + } + function moveToGoal(g, i, dist) { + const e = g.ents[i], goal = e.goalentity; + if (e.groundentity < 0 && !(e.flags & (Q.FL_FLY | Q.FL_SWIM))) return; + if (e.enemy >= 0 && closeEnough(g, i, e.enemy, dist)) return; + if ((Q.rand(g) & 3) === 1 || !stepDirection(g, i, e.ideal_yaw, dist)) { if (g.ents[i].inuse) newChaseDir(g, i, goal, dist); } + } + const walkmove = (g, i, yaw, dist) => { + const e = g.ents[i]; + if (e.groundentity < 0 && !(e.flags & (Q.FL_FLY | Q.FL_SWIM))) return false; + const r = yaw * Math.PI * 2 / 360; + return movestep(g, i, [Q.cos(r) * dist, Q.sin(r) * dist, 0], true); + }; + Q.walkmove = walkmove; + function checkGround(g, i) { // M_CheckGround + const e = g.ents[i]; + if (e.flags & (Q.FL_SWIM | Q.FL_FLY)) return; + if (e.velocity[2] > 100) { e.groundentity = -1; return; } + const point = [e.origin[0], e.origin[1], e.origin[2] - 0.25]; + const tr = Q.trace(g, e.origin, e.mins, e.maxs, point, i, Q.MASK_MONSTERSOLID); + if (tr.normal[2] < 0.7 && !tr.startsolid) { e.groundentity = -1; return; } + if (!tr.startsolid && !tr.allsolid) { e.origin = copy3(tr.endpos); e.groundentity = tr.ent; e.velocity[2] = 0; } + } + + // ---------------- AI (g_ai.c) ---------------- + function foundTarget(g, i) { + const e = g.ents[i], mi = e.monsterinfo; + if (g.ents[e.enemy].client) { g.sight_entity = i; g.sight_entity_framenum = g.framenum; } + e.show_hostile = g.ms + 1000; + mi.last_sighting = copy3(g.ents[e.enemy].origin); mi.trail_time = g.ms; + huntTarget(g, i); + } + function huntTarget(g, i) { + const e = g.ents[i], mi = e.monsterinfo; + e.goalentity = e.enemy; + if (mi.aiflags & AI_STAND_GROUND) call(g, i, 'stand'); else call(g, i, 'run'); + e.ideal_yaw = Q.vectoyaw(sub(g.ents[e.enemy].origin, e.origin)); + if (!(mi.aiflags & AI_STAND_GROUND)) mi.attack_finished = g.ms + 1000; // AttackFinished (self, 1) + } + // FindTarget: the sight entity (a monster that just found the player), the player's own noise (firing, jumping), + // impact noise for idle monsters, else the sight client checked by range / visibility / facing. Arena light is + // above light_level 5 everywhere, the arena is one PHS / area, and no monster here is an ambusher. + function findTarget(g, i) { + const e = g.ents[i], mi = e.monsterinfo; + let client, heardit = false; + if (g.sight_entity_framenum >= g.framenum - 1) { + client = g.sight_entity; + if (g.ents[client].enemy === e.enemy) return false; + } else if (g.sound_entity_framenum >= g.framenum - 1) { client = g.sound_entity; heardit = true; } + else if (e.enemy < 0 && g.sound2_entity_framenum >= g.framenum - 1) { client = g.sound2_entity; heardit = true; } + else { client = g.sight_client; if (client < 0) return false; } + const c = g.ents[client]; + if (!c || !c.inuse) return false; + if (client === e.enemy) return true; + if (c.client) { /* FL_NOTARGET is never set */ } + else if (c.svflags & Q.SVF_MONSTER) { if (c.enemy < 0) return false; } + else if (!heardit) return false; + if (!heardit) { + const r = Q.range(g, i, client); + if (r === Q.RANGE_FAR) return false; + if (!Q.visible(g, i, client)) return false; + if (r === Q.RANGE_NEAR) { if ((c.show_hostile || 0) < g.ms && !Q.infront(g, i, client)) return false; } + else if (r === Q.RANGE_MID) { if (!Q.infront(g, i, client)) return false; } + e.enemy = client; + if (c.classname !== 'player_noise') { + mi.aiflags &= ~AI_SOUND_TARGET; + if (!g.ents[e.enemy].client) { + e.enemy = g.ents[e.enemy].enemy; + if (e.enemy < 0 || !g.ents[e.enemy].client) { e.enemy = -1; return false; } + } + } + } else { + const temp = sub(c.origin, e.origin); + if (len(temp) > 1000) return false; // too far to hear + e.ideal_yaw = Q.vectoyaw(temp); Q.changeYaw(g, i); + mi.aiflags |= AI_SOUND_TARGET; + e.enemy = client; + } + foundTarget(g, i); + if (!(mi.aiflags & AI_SOUND_TARGET)) call(g, i, 'sight'); + return true; + } + const AIF = { + stand(g, i, dist) { + const e = g.ents[i], mi = e.monsterinfo; + if (dist) walkmove(g, i, e.angles[1], dist); + if (mi.aiflags & AI_STAND_GROUND) { + if (e.enemy >= 0) { + e.ideal_yaw = Q.vectoyaw(sub(g.ents[e.enemy].origin, e.origin)); + if (e.angles[1] !== e.ideal_yaw && (mi.aiflags & AI_TEMP_STAND_GROUND)) { mi.aiflags &= ~(AI_STAND_GROUND | AI_TEMP_STAND_GROUND); call(g, i, 'run'); } + Q.changeYaw(g, i); + aiCheckAttack(g, i, 0); + } else findTarget(g, i); + return; + } + if (findTarget(g, i)) return; + // pausetime is set far ahead in every path here, so the walk branch never runs; idle sounds do not exist. + }, + walk(g, i, dist) { moveToGoal(g, i, dist); findTarget(g, i); }, + turn(g, i, dist) { if (dist) walkmove(g, i, g.ents[i].angles[1], dist); if (findTarget(g, i)) return; Q.changeYaw(g, i); }, + move(g, i, dist) { walkmove(g, i, g.ents[i].angles[1], dist); }, + charge(g, i, dist) { + const e = g.ents[i]; + e.ideal_yaw = Q.vectoyaw(sub(g.ents[e.enemy].origin, e.origin)); + Q.changeYaw(g, i); + if (dist) walkmove(g, i, e.angles[1], dist); + }, + run(g, i, dist) { aiRun(g, i, dist); }, + }; + // M_CheckAttack (default) with the skill scaling of the attack chance. + Q.M_CheckAttack = (g, i) => { + const e = g.ents[i], mi = e.monsterinfo, en = g.ents[e.enemy]; + if (en.health > 0) { + const tr = Q.trace(g, eye(e), null, null, eye(en), i, Q.CONTENTS_SOLID | Q.CONTENTS_MONSTER | Q.CONTENTS_SLIME | Q.CONTENTS_LAVA | Q.CONTENTS_WINDOW); + if (tr.ent !== e.enemy) return false; + } + if (g.ai.enemy_range === Q.RANGE_MELEE) { + if (g.skill === 0 && (Q.rand(g) & 3)) return false; + mi.attack_state = def(e).melee ? AS_MELEE : AS_MISSILE; return true; + } + if (!def(e).attack) return false; + if (g.ms < mi.attack_finished) return false; + if (g.ai.enemy_range === Q.RANGE_FAR) return false; + let chance; + if (mi.aiflags & AI_STAND_GROUND) chance = 0.4; + else if (g.ai.enemy_range === Q.RANGE_NEAR) chance = 0.1; + else if (g.ai.enemy_range === Q.RANGE_MID) chance = 0.02; + else return false; + if (g.skill === 0) chance *= 0.5; else if (g.skill >= 2) chance *= 2; + if (Q.random(g) < chance) { mi.attack_state = AS_MISSILE; mi.attack_finished = g.ms + 2000 * Q.random(g); return true; } + if (e.flags & Q.FL_FLY) mi.attack_state = Q.random(g) < 0.3 ? AS_SLIDING : AS_STRAIGHT; + return false; + }; + // Boss2_CheckAttack / Jorg_CheckAttack / Makron_CheckAttack share one shape: no skill scaling, own chances. + function bossCheckAttack(near, mid) { + return (g, i) => { + const e = g.ents[i], mi = e.monsterinfo, en = g.ents[e.enemy]; + if (en.health > 0) { + const tr = Q.trace(g, eye(e), null, null, eye(en), i, Q.CONTENTS_SOLID | Q.CONTENTS_MONSTER | Q.CONTENTS_SLIME | Q.CONTENTS_LAVA); + if (tr.ent !== e.enemy) return false; + } + const range = Q.range(g, i, e.enemy); + e.ideal_yaw = Q.vectoyaw(sub(en.origin, e.origin)); + if (range === Q.RANGE_MELEE) { mi.attack_state = def(e).melee ? AS_MELEE : AS_MISSILE; return true; } + if (!def(e).attack) return false; + if (g.ms < mi.attack_finished) return false; + if (range === Q.RANGE_FAR) return false; + let chance; + if (mi.aiflags & AI_STAND_GROUND) chance = 0.4; + else if (range === Q.RANGE_NEAR) chance = near; + else if (range === Q.RANGE_MID) chance = mid; + else return false; + if (Q.random(g) < chance) { mi.attack_state = AS_MISSILE; mi.attack_finished = g.ms + 2000 * Q.random(g); return true; } + if (e.flags & Q.FL_FLY) mi.attack_state = Q.random(g) < 0.3 ? AS_SLIDING : AS_STRAIGHT; + return false; + }; + } + const facingIdeal = e => { const d = Q.anglemod(e.angles[1] - e.ideal_yaw); return !(d > 45 && d < 315); }; + function aiCheckAttack(g, i, dist) { + const e = g.ents[i], mi = e.monsterinfo; + if (e.goalentity >= 0 && (mi.aiflags & AI_SOUND_TARGET)) { + if (g.ms - (g.ents[e.enemy].teleport_time || 0) > 5000) { + if (e.goalentity === e.enemy) e.goalentity = -1; // no movetarget in these arenas + mi.aiflags &= ~AI_SOUND_TARGET; + if (mi.aiflags & AI_TEMP_STAND_GROUND) mi.aiflags &= ~(AI_STAND_GROUND | AI_TEMP_STAND_GROUND); + } else { e.show_hostile = g.ms + 1000; return false; } + } + g.ai.enemy_vis = false; + const en = e.enemy >= 0 ? g.ents[e.enemy] : null; + // hesDeadJim: AI_BRUTAL monsters (the Tank) keep going until the enemy is below -80; a player_noise target has + // no health either. + const dead = !en || !en.inuse || (en.health || 0) <= ((mi.aiflags & AI_BRUTAL) ? -80 : 0); + if (dead) { + e.enemy = -1; + if (e.oldenemy >= 0 && g.ents[e.oldenemy].inuse && g.ents[e.oldenemy].health > 0) { e.enemy = e.oldenemy; e.oldenemy = -1; huntTarget(g, i); } + else { mi.pausetime = g.ms + 100000000000; call(g, i, 'stand'); return true; } + } + e.show_hostile = g.ms + 1000; + g.ai.enemy_vis = Q.visible(g, i, e.enemy); + if (g.ai.enemy_vis) { mi.search_time = g.ms + 5000; mi.last_sighting = copy3(g.ents[e.enemy].origin); } + g.ai.enemy_infront = Q.infront(g, i, e.enemy); + g.ai.enemy_range = Q.range(g, i, e.enemy); + g.ai.enemy_yaw = Q.vectoyaw(sub(g.ents[e.enemy].origin, e.origin)); + if (mi.attack_state === AS_MISSILE) { // ai_run_missile + e.ideal_yaw = g.ai.enemy_yaw; Q.changeYaw(g, i); + if (facingIdeal(e)) { call(g, i, 'attack'); mi.attack_state = AS_STRAIGHT; } + return true; + } + if (mi.attack_state === AS_MELEE) { + e.ideal_yaw = g.ai.enemy_yaw; Q.changeYaw(g, i); + if (facingIdeal(e)) { call(g, i, 'melee'); mi.attack_state = AS_STRAIGHT; } + return true; + } + if (!g.ai.enemy_vis) return false; + return (def(e).checkattack || Q.M_CheckAttack)(g, i); + } + function aiRun(g, i, dist) { + const e = g.ents[i], mi = e.monsterinfo; + if (mi.aiflags & AI_SOUND_TARGET) { + if (len(sub(e.origin, g.ents[e.enemy].origin)) < 64) { mi.aiflags |= AI_STAND_GROUND | AI_TEMP_STAND_GROUND; call(g, i, 'stand'); return; } + moveToGoal(g, i, dist); + if (!findTarget(g, i)) return; + } + if (aiCheckAttack(g, i, dist)) return; + if (mi.attack_state === AS_SLIDING) { // ai_run_slide + e.ideal_yaw = g.ai.enemy_yaw; Q.changeYaw(g, i); + const ofs = mi.lefty ? 90 : -90; + if (walkmove(g, i, e.ideal_yaw + ofs, dist)) return; + mi.lefty = 1 - mi.lefty; + walkmove(g, i, e.ideal_yaw - ofs, dist); + return; + } + if (g.ai.enemy_vis) { + moveToGoal(g, i, dist); + mi.aiflags &= ~AI_LOST_SIGHT; + mi.last_sighting = copy3(g.ents[e.enemy].origin); mi.trail_time = g.ms; + mi.stall_pos = copy3(e.origin); mi.stall_t = g.ms; mi.chase_until = 0; + return; + } + // BossBench engagement rule (not in Quake II; meeting rule "a boss must never stop pursuing"): the lost-sight + // pursuit below can ping-pong between two course-correction targets when a large boss is flush against a pillar, + // and since every PURSUE_NEXT renews search_time the original 20 s fallback never fires. If the boss has neither + // seen the player nor moved 48 units for 3 s, it takes that original fallback early: 2 s of M_MoveToGoal straight + // at its enemy (SV_NewChaseDir steps around the obstacle). + if (mi.chase_until > g.ms) { moveToGoal(g, i, dist); return; } + if (!mi.stall_pos || len(sub(e.origin, mi.stall_pos)) > 48) { mi.stall_pos = copy3(e.origin); mi.stall_t = g.ms; } + else if (g.ms - mi.stall_t >= 3000) { + mi.chase_until = g.ms + 2000; mi.stall_pos = null; + mi.aiflags &= ~(AI_LOST_SIGHT | AI_PURSUIT_LAST_SEEN | AI_PURSUE_NEXT | AI_PURSUE_TEMP); + Q.event(g, 'boss_unstick', { classname: e.classname }); + moveToGoal(g, i, dist); + return; + } + if (mi.search_time && g.ms > mi.search_time + 20000) { moveToGoal(g, i, dist); mi.search_time = 0; return; } + // Lost sight: chase last_sighting, then the player trail, with the course correction traces. + const save = e.goalentity, tempgoal = Q.spawn(g); + e.goalentity = tempgoal; + let fresh = false; + if (!(mi.aiflags & AI_LOST_SIGHT)) { mi.aiflags |= AI_LOST_SIGHT | AI_PURSUIT_LAST_SEEN; mi.aiflags &= ~(AI_PURSUE_NEXT | AI_PURSUE_TEMP); fresh = true; } + if (mi.aiflags & AI_PURSUE_NEXT) { + mi.aiflags &= ~AI_PURSUE_NEXT; + mi.search_time = g.ms + 5000; + let marker = null; + if (mi.aiflags & AI_PURSUE_TEMP) { mi.aiflags &= ~AI_PURSUE_TEMP; mi.last_sighting = copy3(mi.saved_goal); fresh = true; } + else if (mi.aiflags & AI_PURSUIT_LAST_SEEN) { mi.aiflags &= ~AI_PURSUIT_LAST_SEEN; marker = Q.trailPick(g, i, true); } + else marker = Q.trailPick(g, i, false); + if (marker) { mi.last_sighting = copy3(marker.origin); mi.trail_time = marker.timestamp; e.angles[1] = e.ideal_yaw = marker.yaw; fresh = true; } + } + let d1 = len(sub(e.origin, mi.last_sighting)); + if (d1 <= dist) { mi.aiflags |= AI_PURSUE_NEXT; dist = d1; } + g.ents[tempgoal].origin = copy3(mi.last_sighting); + if (fresh) { + let tr = Q.trace(g, e.origin, e.mins, e.maxs, mi.last_sighting, i, Q.MASK_PLAYERSOLID); + if (tr.fraction < 1) { + const v = sub(g.ents[tempgoal].origin, e.origin); + d1 = len(v); + let center = tr.fraction; + const d2 = d1 * ((center + 1) / 2); + e.angles[1] = e.ideal_yaw = Q.vectoyaw(v); + const av = Q.angleVectors(e.angles); + let left_target = Q.projectSource(e.origin, [d2, -16, 0], av.forward, av.right); + tr = Q.trace(g, e.origin, e.mins, e.maxs, left_target, i, Q.MASK_PLAYERSOLID); + const left = tr.fraction; + let right_target = Q.projectSource(e.origin, [d2, 16, 0], av.forward, av.right); + tr = Q.trace(g, e.origin, e.mins, e.maxs, right_target, i, Q.MASK_PLAYERSOLID); + const right = tr.fraction; + center = (d1 * center) / d2; + if (left >= center && left > right) { + if (left < 1) left_target = Q.projectSource(e.origin, [d2 * left * 0.5, -16, 0], av.forward, av.right); + mi.saved_goal = copy3(mi.last_sighting); mi.aiflags |= AI_PURSUE_TEMP; + g.ents[tempgoal].origin = copy3(left_target); mi.last_sighting = copy3(left_target); + e.angles[1] = e.ideal_yaw = Q.vectoyaw(sub(g.ents[tempgoal].origin, e.origin)); + } else if (right >= center && right > left) { + if (right < 1) right_target = Q.projectSource(e.origin, [d2 * right * 0.5, 16, 0], av.forward, av.right); + mi.saved_goal = copy3(mi.last_sighting); mi.aiflags |= AI_PURSUE_TEMP; + g.ents[tempgoal].origin = copy3(right_target); mi.last_sighting = copy3(right_target); + e.angles[1] = e.ideal_yaw = Q.vectoyaw(sub(g.ents[tempgoal].origin, e.origin)); + } + } + } + moveToGoal(g, i, dist); + Q.freeEdict(g, tempgoal); + if (g.ents[i].inuse) g.ents[i].goalentity = save; + } + // M_ReactToDamage: the player is the only other combatant; damage from the monster itself is ignored. + Q.reactToDamage = (g, targ, attacker) => { + const t = g.ents[targ], a = g.ents[attacker]; + if (!a || (!a.client && !(a.svflags & Q.SVF_MONSTER))) return; + if (attacker === targ || attacker === t.enemy) return; + if (a.client) { + t.monsterinfo.aiflags &= ~AI_SOUND_TARGET; + if (t.enemy >= 0 && g.ents[t.enemy].client) { + if (Q.visible(g, targ, t.enemy)) { t.oldenemy = attacker; return; } + t.oldenemy = t.enemy; + } + t.enemy = attacker; + if (!(t.monsterinfo.aiflags & AI_DUCKED)) foundTarget(g, targ); + } + }; + Q.AI_DUCKED = AI_DUCKED; + Q.monsterPain = (g, i, attacker, kick, damage) => call(g, i, 'pain', attacker, kick, damage); + Q.monsterDie = (g, i, inflictor, attacker, damage, point) => call(g, i, 'die', inflictor, attacker, damage, point); + // monster_death_use: fliers drop out of the air; the case decides what the death triggers (Makron's spawn, the win). + Q.monsterDeathUse = (g, i) => { + const e = g.ents[i]; + e.flags &= ~(Q.FL_FLY | Q.FL_SWIM); + e.monsterinfo.aiflags &= AI_GOOD_GUY; + Q.event(g, 'boss_killed', { classname: e.classname }); + if (e.final) g.bossKilled = g.t + 1; + }; + + // ---------------- framework (g_monster.c) ---------------- + function moveFrame(g, i) { + const e = g.ents[i], mi = e.monsterinfo; + let move = def(e).moves[mi.currentmove]; + e.nextthink = g.ms + Q.FRAMETIME_MS; + if (mi.nextframe && mi.nextframe >= move.first && mi.nextframe <= move.last) { e.frame = mi.nextframe; mi.nextframe = 0; } + else { + if (e.frame === move.last && move.end) { + call(g, i, move.end); + move = def(e).moves[mi.currentmove]; + if (e.svflags & Q.SVF_DEADMONSTER) return; + } + if (e.frame < move.first || e.frame > move.last) { mi.aiflags &= ~AI_HOLD_FRAME; e.frame = move.first; } + else if (!(mi.aiflags & AI_HOLD_FRAME)) { e.frame++; if (e.frame > move.last) e.frame = move.first; } + } + const [ai, dist, think] = move.frames[e.frame - move.first]; + if (ai) AIF[ai](g, i, (mi.aiflags & AI_HOLD_FRAME) ? 0 : dist * mi.scale); + if (think && g.ents[i].inuse) call(g, i, think); + } + Q.THINK.monster_think = (g, i) => { + moveFrame(g, i); + const e = g.ents[i]; + if (!e.inuse) return; + if (e.linkcount !== e.monsterinfo.linkcount) { e.monsterinfo.linkcount = e.linkcount; checkGround(g, i); } + }; + // SV_Physics_Step: gravity, fly / ground friction and SV_FlyMove for a monster with velocity, then think. At 60 Hz + // (q2-arena@3) the physics runs every host frame with that frame's length (g.dt); the think still fires on its + // nextthink, i.e. every 100 ms server frame. lerp keeps the displacement of the last think for the renderer, which + // spreads it over the next 100 ms like the original client (cl_ents.c lerpfrac); it never feeds back into the rules. + // Friction in SV_Physics_Step is speed * (1 - frametime * friction) once per 100 ms server frame (x0.4 on the + // ground, x0.8 for a flier's vertical speed). Applied per 16/17 ms host frame it keeps the per-second decay with + // k^(ms/100) (precomputed, so Node and the browser agree bit for bit); below stopspeed the original subtracts a + // constant per second, which the linear form already keeps. + const FRICTION_K = { 16: [0.86363373567437107, 0.96492686487423818], 17: [0.85575648417344741, 0.96277609334680192] }; + const frictionK = (g, fly) => { const k = FRICTION_K[Math.round(g.dt * 1000)]; if (!k) throw Error('host frame ' + g.dt); return k[fly ? 1 : 0]; }; + Q.physicsStep = (g, i) => { + let e = g.ents[i]; + if (e.groundentity < 0) checkGround(g, i); + for (let k = 0; k < 3; k++) e.velocity[k] = Math.max(-Q.SV_MAXVELOCITY, Math.min(Q.SV_MAXVELOCITY, e.velocity[k])); + const wasonground = e.groundentity >= 0, ft = g.dt; + if (!wasonground && !(e.flags & Q.FL_FLY)) e.velocity[2] -= e.gravity * Q.SV_GRAVITY * ft; + if ((e.flags & Q.FL_FLY) && e.velocity[2] !== 0) { + const speed = Math.abs(e.velocity[2]), control = speed < Q.SV_STOPSPEED ? Q.SV_STOPSPEED : speed; + let ns = speed < Q.SV_STOPSPEED ? speed - ft * control * Q.SV_FRICTION / 3 : speed * frictionK(g, true); if (ns < 0) ns = 0; e.velocity[2] *= ns / speed; + } + if (e.velocity[0] || e.velocity[1] || e.velocity[2]) { + if ((wasonground || (e.flags & (Q.FL_SWIM | Q.FL_FLY))) && !(e.health <= 0 && !checkBottom(g, i))) { + const speed = Math.sqrt(e.velocity[0] ** 2 + e.velocity[1] ** 2); + if (speed) { + const control = speed < Q.SV_STOPSPEED ? Q.SV_STOPSPEED : speed; + let ns = speed < Q.SV_STOPSPEED ? speed - ft * control * Q.SV_FRICTION : speed * frictionK(g, false); if (ns < 0) ns = 0; ns /= speed; + e.velocity[0] *= ns; e.velocity[1] *= ns; + } + } + flyMove(g, i, ft, (e.svflags & Q.SVF_MONSTER) ? Q.MASK_MONSTERSOLID : Q.MASK_SOLID); + link(g, i); + if (!g.ents[i].inuse) return; + } + const before = copy3(g.ents[i].origin); + if (Q.runThink(g, i) || !g.ents[i].inuse) return; + const after = g.ents[i].origin; + g.ents[i].lerp = [before[0] - after[0], before[1] - after[1], before[2] - after[2], g.ms]; + }; + function flyMove(g, i, time, mask) { // SV_FlyMove + const e = g.ents[i], primal = copy3(e.velocity), planes = []; + let original = copy3(e.velocity), time_left = time; + e.groundentity = -1; + for (let bump = 0; bump < 4; bump++) { + const end = [0, 1, 2].map(k => e.origin[k] + time_left * e.velocity[k]); + const tr = Q.trace(g, e.origin, e.mins, e.maxs, end, i, mask); + if (tr.allsolid) { e.velocity = [0, 0, 0]; return 3; } + if (tr.fraction > 0) { e.origin = copy3(tr.endpos); original = copy3(e.velocity); planes.length = 0; } + if (tr.fraction === 1) break; + if (tr.normal[2] > 0.7 && tr.ent === 0) e.groundentity = 0; + Q.impact(g, i, tr); + if (!g.ents[i].inuse) break; + time_left -= time_left * tr.fraction; + if (planes.length >= 5) { e.velocity = [0, 0, 0]; return 3; } + planes.push(tr.normal); + let k; + for (k = 0; k < planes.length; k++) { + const backoff = dot(original, planes[k]), nv = [0, 1, 2].map(c => { const v = original[c] - planes[k][c] * backoff; return v > -0.1 && v < 0.1 ? 0 : v; }); + let j; + for (j = 0; j < planes.length; j++) if (j !== k && !Q.eq(planes[k], planes[j]) && dot(nv, planes[j]) < 0) break; + if (j === planes.length) { e.velocity = nv; break; } + } + if (k === planes.length) { + if (planes.length !== 2) { e.velocity = [0, 0, 0]; return 7; } + const dir = Q.cross(planes[0], planes[1]); e.velocity = scale(dir, dot(dir, e.velocity)); + } + if (dot(e.velocity, primal) <= 0) { e.velocity = [0, 0, 0]; return 0; } + } + return 0; + } + // Spawn: SP_monster_* + monster_start; the first think is walkmonster_start_go / flymonster_start_go. + Q.spawnMonster = (g, classname, origin, yaw, opts) => { + const i = Q.spawn(g), e = g.ents[i], d = DEFS[classname]; + Object.assign(e, { + classname, origin: copy3(origin), old_origin: copy3(origin), angles: [0, yaw, 0], ideal_yaw: yaw, mins: copy3(d.mins), maxs: copy3(d.maxs), + movetype: 'step', solid: Q.SOLID_BBOX, health: opts.health, gib_health: d.gib_health, mass: d.mass, flags: d.fly ? Q.FL_FLY : 0, + svflags: Q.SVF_MONSTER, takedamage: Q.DAMAGE_AIM, clipmask: Q.MASK_MONSTERSOLID, yaw_speed: 0, viewheight: 0, final: !!opts.final, + goalentity: -1, oldenemy: -1, movetarget: -1, show_hostile: 0, pain_debounce_time: 0, skinnum: 0, pos1: [0, 0, 0], count: 0, + think: d.fly ? 'flymonster_start_go' : 'walkmonster_start_go', nextthink: g.ms + Q.FRAMETIME_MS, + monsterinfo: { currentmove: d.startMove || 'stand', nextframe: 0, aiflags: 0, scale: 1, pausetime: 0, attack_finished: 0, attack_state: 0, lefty: 0, + search_time: 0, trail_time: 0, last_sighting: [0, 0, 0], saved_goal: [0, 0, 0], linkcount: 0, idle_time: 0, + stall_pos: null, stall_t: 0, chase_until: 0 }, + }); + if (d.immuneLaser) e.flags |= Q.FL_IMMUNE_LASER; + e.max_health = e.health; + const mv = d.moves[e.monsterinfo.currentmove]; + e.frame = mv.first + (Q.rand(g) % (mv.last - mv.first + 1)); // monster_start picks a random first frame + if (opts.engage) e.engage = true; + return i; + }; + function dropToFloor(g, i) { // M_droptofloor: lift one unit, trace 256 down, rest DIST_EPSILON above the floor + const e = g.ents[i]; + e.origin[2] += 1; + const end = copy3(e.origin); end[2] -= 256; + const tr = Q.trace(g, e.origin, e.mins, e.maxs, end, i, Q.MASK_MONSTERSOLID); + if (tr.fraction === 1 || tr.allsolid) return; + e.origin = copy3(tr.endpos); link(g, i); + checkGround(g, i); + } + function startGo(g, i, fly) { + const e = g.ents[i]; + if (!fly) { if (g.ms < 1000) dropToFloor(g, i); } else walkmove(g, i, 0, 0); + if (!e.yaw_speed) e.yaw_speed = fly ? 10 : 20; + e.viewheight = 25; + if (e.health <= 0) return; // monster_start_go: killed before it ever thought + e.monsterinfo.pausetime = 100000000000; call(g, i, 'stand'); + e.think = 'monster_think'; e.nextthink = g.ms + Q.FRAMETIME_MS; + // monster_use by the arena trigger: an alerted boss hunts the player from the first frame. + if (e.engage && g.ents[1].health > 0) { e.enemy = 1; foundTarget(g, i); } + } + Q.THINK.walkmonster_start_go = (g, i) => startGo(g, i, false); + Q.THINK.flymonster_start_go = (g, i) => startGo(g, i, true); + // Muzzle helpers (G_ProjectSource with monster_flash_offset, monster yaw only). + const muzzle = (e, ofs) => { const av = Q.angleVectors(e.angles); return Q.projectSource(e.origin, ofs, av.forward, av.right); }; + const aimAt = (g, start, target) => norm(sub(target, start)); + const enemyEye = (g, e, lag) => { const en = g.ents[e.enemy], t = ma(en.origin, lag, en.velocity); t[2] += en.viewheight; return t; }; + function flash(g, i, weapon, at, extra) { Q.fx(g, 'mflash', at, null, Object.assign({ weapon, owner: i }, extra || {})); } + Q.monsterFireBullet = (g, i, start, dir, damage, kick) => Q.fireBullet(g, i, start, dir, damage, kick, 300, 500, 'monster'); + Q.monsterFireRocket = (g, i, start, dir, damage, speed) => Q.fireRocket(g, i, start, dir, damage, speed, damage + 20, damage); + // BossExplode: nine explosions a frame apart around the body, then the gibs (cosmetic; their RNG draws kept). + Q.THINK.BossExplode = (g, i) => { + const e = g.ents[i]; + e.think = 'BossExplode'; + const org = copy3(e.origin); org[2] += 24 + (Q.rand(g) & 15); + const OFS = [[-24, -24], [24, 24], [24, -24], [-24, 24], [-48, -48], [48, 48], [-48, 48], [48, -48]]; + const n = e.count++; + if (n < 8) { + org[0] += OFS[n][0]; org[1] += OFS[n][1]; + Q.fx(g, 'explosion', org, null, { big: true }); + e.nextthink = g.ms + Q.FRAMETIME_MS; + return; + } + // case 8: four meat chunks, eight metal chunks, the chest, then the boss itself becomes the gear head. + for (let k = 0; k < 4; k++) Q.throwGib(g, i, 'meat', 500, true); + for (let k = 0; k < 8; k++) Q.throwGib(g, i, 'metal', 500, false); + Q.throwGib(g, i, 'chest', 500, true); + Q.throwHead(g, i, 'gear', 500, false); + g.ents[i].deadflag = Q.DEAD_DEAD; g.ents[i].gibbed = true; + Q.fx(g, 'gibs', Q.center(g.ents[i]), null, { size: 64 }); + }; + function bossDead(mins, maxs) { + return (g, i) => { const e = g.ents[i]; e.mins = mins; e.maxs = maxs; e.movetype = 'toss'; e.svflags |= Q.SVF_DEADMONSTER; e.nextthink = 0; }; + } + const stand = (g, i) => setMove(g.ents[i], 'stand'); + const runOrStand = (g, i) => setMove(g.ents[i], (g.ents[i].monsterinfo.aiflags & AI_STAND_GROUND) ? 'stand' : 'run'); + const debounced = (g, e) => g.ms < e.pain_debounce_time; + const sound = () => {}; + + // ================= Super Tank (m_supertank.c) ================= + DEFS.monster_supertank = { + name: 'Tracked Gun Carrier', health: 1500, gib_health: -500, mass: 800, mins: [-64, -64, 0], maxs: [64, 64, 112], gibs: 13, + moves: moves({ + stand: [194, 253, 's0x60', null], + run: [128, 145, 'r12:TreadSound r12x17', null], + forward: [128, 145, 'w4:TreadSound w4x17', null], + pain3: [172, 175, 'm0x4', 'run'], pain2: [168, 171, 'm0x4', 'run'], pain1: [164, 167, 'm0x4', 'run'], + death: [98, 121, 'm0x23 m0:BossExplode', 'dead'], + attack2: [20, 46, 'c0x7 c0:supertankRocket m0x2 m0:supertankRocket m0x2 m0:supertankRocket m0x13', 'run'], + attack1: [0, 5, 'c0:supertankMachineGunx6', 'reattack1'], + end_attack1: [6, 19, 'm0x14', 'run'], + }), + stand, walk: (g, i) => setMove(g.ents[i], 'forward'), run: runOrStand, TreadSound: sound, + reattack1(g, i) { + const e = g.ents[i]; + if (Q.visible(g, i, e.enemy)) setMove(e, Q.random(g) < 0.9 ? 'attack1' : 'end_attack1'); else setMove(e, 'end_attack1'); + }, + pain(g, i, other, kick, damage) { + const e = g.ents[i]; + if (e.health < e.max_health / 2) e.skinnum = 1; + if (debounced(g, e)) return; + if (damage <= 25 && Q.random(g) < 0.2) return; // lessen the chance of pain frames + if (g.skill >= 2 && e.frame >= 20 && e.frame <= 33) return; // no pain while firing rockets + e.pain_debounce_time = g.ms + 3000; + if (g.skill === 3) return; // no pain anims in nightmare + setMove(e, damage <= 10 ? 'pain1' : damage <= 25 ? 'pain2' : 'pain3'); + }, + supertankRocket(g, i) { + const e = g.ents[i]; + const ofs = e.frame === 27 ? [16.0, -22.5, 91.2] : e.frame === 30 ? [16.0, -33.4, 86.7] : [16.0, -42.8, 83.3]; + const start = muzzle(e, ofs); + Q.monsterFireRocket(g, i, start, aimAt(g, start, enemyEye(g, e, 0)), 50, 500); + flash(g, i, 'rocket', start); + }, + supertankMachineGun(g, i) { + const e = g.ents[i], av = Q.angleVectors([0, e.angles[1], 0]); + const start = Q.projectSource(e.origin, [30.0, 30.0, 88.5], av.forward, av.right); + let forward = av.forward; + if (e.enemy >= 0) forward = aimAt(g, start, enemyEye(g, e, 0)); + Q.monsterFireBullet(g, i, start, forward, 6, 4); + flash(g, i, 'mg', start); + }, + attack(g, i) { + const e = g.ents[i], range = len(sub(g.ents[e.enemy].origin, e.origin)); + if (range <= 160) setMove(e, 'attack1'); + else setMove(e, Q.random(g) < 0.3 ? 'attack1' : 'attack2'); // fire rockets more often at distance + }, + die(g, i) { const e = g.ents[i]; e.deadflag = Q.DEAD_DEAD; e.takedamage = Q.DAMAGE_NO; e.count = 0; setMove(e, 'death'); }, + dead: bossDead([-60, -60, 0], [60, 60, 72]), + BossExplode: (g, i) => Q.THINK.BossExplode(g, i), + }; + + // ================= Hornet (m_boss2.c) ================= + DEFS.monster_boss2 = { + name: 'Flying Gunship', health: 2000, gib_health: -200, mass: 1000, mins: [-56, -56, 0], maxs: [56, 56, 80], fly: true, immuneLaser: true, gibs: 13, + moves: moves({ + stand: [0, 20, 's0x21', null], + walk: [50, 69, 'w8x20', null], + run: [50, 69, 'r8x20', null], + attack_pre_mg: [70, 78, 'c1x8 c1:boss2_attack_mg', null], + attack_mg: [79, 84, 'c1:Boss2MachineGunx5 c1:boss2_reattack_mg', null], + attack_post_mg: [85, 88, 'c1x4', 'run'], + attack_rocket: [89, 109, 'c1x12 m-20:Boss2Rocket c1x8', 'run'], + pain_heavy: [110, 127, 'm0x18', 'run'], + pain_light: [128, 131, 'm0x4', 'run'], + death: [132, 180, 'm0x48 m0:BossExplode', 'dead'], + }), + stand, walk: (g, i) => setMove(g.ents[i], 'walk'), run: runOrStand, + checkattack: bossCheckAttack(0.8, 0.8), + attack(g, i) { + const e = g.ents[i], range = len(sub(g.ents[e.enemy].origin, e.origin)); + if (range <= 125) setMove(e, 'attack_pre_mg'); else setMove(e, Q.random(g) <= 0.6 ? 'attack_pre_mg' : 'attack_rocket'); + }, + boss2_attack_mg: (g, i) => setMove(g.ents[i], 'attack_mg'), + boss2_reattack_mg(g, i) { + const e = g.ents[i]; + if (Q.infront(g, i, e.enemy)) setMove(e, Q.random(g) <= 0.7 ? 'attack_mg' : 'attack_post_mg'); else setMove(e, 'attack_post_mg'); + }, + Boss2MachineGun(g, i) { + const e = g.ents[i]; + for (const ofs of [[32, -40, 70], [32, 40, 70]]) { // boss2_firebullet_left, then _right + const start = muzzle(e, ofs); + Q.monsterFireBullet(g, i, start, aimAt(g, start, enemyEye(g, e, -0.2)), 6, 4); + flash(g, i, 'mg', start); + } + }, + Boss2Rocket(g, i) { + const e = g.ents[i]; + for (const ofs of [[22.0, 16.0, 10.0], [22.0, 8.0, 10.0], [22.0, -8.0, 10.0], [22.0, -16.0, 10.0]]) { + const start = muzzle(e, ofs); + Q.monsterFireRocket(g, i, start, aimAt(g, start, enemyEye(g, e, 0)), 50, 500); + flash(g, i, 'rocket', start); + } + }, + pain(g, i, other, kick, damage) { + const e = g.ents[i]; + if (e.health < e.max_health / 2) e.skinnum = 1; + if (debounced(g, e)) return; + e.pain_debounce_time = g.ms + 3000; + setMove(e, damage < 30 ? 'pain_light' : 'pain_heavy'); + }, + die(g, i) { const e = g.ents[i]; e.deadflag = Q.DEAD_DEAD; e.takedamage = Q.DAMAGE_NO; e.count = 0; setMove(e, 'death'); }, + dead: bossDead([-56, -56, 0], [56, 56, 80]), + BossExplode: (g, i) => Q.THINK.BossExplode(g, i), + }; + + // ================= Jorg (m_boss31.c), first form of the final boss ================= + DEFS.monster_jorg = { + name: 'Twin-Cannon Mech', health: 3000, gib_health: -2000, mass: 1000, mins: [-80, -80, 0], maxs: [80, 80, 140], gibs: 13, + moves: moves({ + stand: [112, 162, 's0:jorg_idle s0x32 s19 s11:jorg_step_left s0x2 s6 s9:jorg_step_right s0x7 s-2 s-17:jorg_step_left s0 s-12 s-14:jorg_step_right', null], + run: [168, 181, 'r17:jorg_step_left r0x3 r12 r8 r10 r33:jorg_step_right r0x3 r9x3', null], + walk: [168, 181, 'w17 w0x3 w12 w8 w10 w33 w0x3 w9x3', null], + pain3: [87, 111, 'm-28 m-6 m-3:jorg_step_left m-9 m0:jorg_step_right m0x3 m-7 m1 m-11 m-4 m0x2 m10 m11 m0 m10 m3 m10 m7:jorg_step_left m17 m0x2 m0:jorg_step_right', 'run'], + pain2: [84, 86, 'm0x3', 'run'], pain1: [81, 83, 'm0x3', 'run'], + death: [31, 80, 'm0x48 m0:MakronToss m0:BossExplode', 'dead'], + attack2: [18, 30, 'c0x6 c0:jorgBFG m0x6', 'run'], + start_attack1: [0, 7, 'c0x8', 'attack1'], + attack1: [8, 13, 'c0:jorg_firebulletx6', 'reattack1'], + end_attack1: [14, 17, 'm0x4', 'run'], + }), + stand, walk: (g, i) => setMove(g.ents[i], 'walk'), run: runOrStand, jorg_idle: sound, jorg_step_left: sound, jorg_step_right: sound, + checkattack: bossCheckAttack(0.4, 0.2), + attack(g, i) { setMove(g.ents[i], Q.random(g) <= 0.75 ? 'start_attack1' : 'attack2'); }, + attack1: (g, i) => setMove(g.ents[i], 'attack1'), + reattack1(g, i) { + const e = g.ents[i]; + if (Q.visible(g, i, e.enemy)) setMove(e, Q.random(g) < 0.9 ? 'attack1' : 'end_attack1'); else setMove(e, 'end_attack1'); + }, + jorg_firebullet(g, i) { + const e = g.ents[i]; + for (const ofs of [[78.5, -47.1, 96], [78.5, 46.7, 96]]) { // jorg_firebullet_left, then _right + const start = muzzle(e, ofs); + Q.monsterFireBullet(g, i, start, aimAt(g, start, enemyEye(g, e, -0.2)), 6, 4); + flash(g, i, 'mg', start); + } + }, + jorgBFG(g, i) { + const e = g.ents[i], start = muzzle(e, [6.3, -9, 111.2]); + Q.fireBFG(g, i, start, aimAt(g, start, enemyEye(g, e, 0)), 50, 300, 200); + flash(g, i, 'bfg', start); + }, + pain(g, i, other, kick, damage) { + const e = g.ents[i]; + if (e.health < e.max_health / 2) e.skinnum = 1; + if (debounced(g, e)) return; + if (damage <= 40 && Q.random(g) <= 0.6) return; + if (e.frame >= 0 && e.frame <= 7 && Q.random(g) <= 0.005) return; + if (e.frame >= 8 && e.frame <= 13 && Q.random(g) <= 0.00005) return; + if (e.frame >= 18 && e.frame <= 25 && Q.random(g) <= 0.005) return; + e.pain_debounce_time = g.ms + 3000; + if (g.skill === 3) return; + if (damage <= 50) setMove(e, 'pain1'); else if (damage <= 100) setMove(e, 'pain2'); else if (Q.random(g) <= 0.3) setMove(e, 'pain3'); + }, + die(g, i) { const e = g.ents[i]; e.deadflag = Q.DEAD_DEAD; e.takedamage = Q.DAMAGE_NO; e.count = 0; setMove(e, 'death'); }, + dead: bossDead([-60, -60, 0], [60, 60, 72]), + MakronToss(g, i) { // spawn Makron 0.8 s later at Jorg's origin + const k = Q.spawn(g), t = g.ents[k]; + Object.assign(t, { classname: 'makron_spawner', origin: copy3(g.ents[i].origin), think: 'MakronSpawn', nextthink: g.ms + 800 }); + }, + BossExplode: (g, i) => Q.THINK.BossExplode(g, i), + }; + // MakronSpawn: SP_monster_makron on the spawner edict, then jump at the player (400 forward, 200 up). + Q.THINK.MakronSpawn = (g, i) => { + const origin = copy3(g.ents[i].origin), d = DEFS.monster_makron, e = g.ents[i]; + Object.assign(e, Q.blankEdict(), { + classname: 'monster_makron', origin, old_origin: copy3(origin), mins: copy3(d.mins), maxs: copy3(d.maxs), movetype: 'step', solid: Q.SOLID_BBOX, + health: g.makronHealth, gib_health: d.gib_health, mass: d.mass, svflags: Q.SVF_MONSTER, takedamage: Q.DAMAGE_AIM, clipmask: Q.MASK_MONSTERSOLID, + final: true, goalentity: -1, oldenemy: -1, movetarget: -1, show_hostile: 0, pain_debounce_time: 0, skinnum: 0, pos1: [0, 0, 0], count: 0, + yaw_speed: 0, viewheight: 0, think: 'walkmonster_start_go', nextthink: g.ms + Q.FRAMETIME_MS, angles: [0, 0, 0], ideal_yaw: 0, + monsterinfo: { currentmove: 'sight', nextframe: 0, aiflags: 0, scale: 1, pausetime: 0, attack_finished: 0, attack_state: 0, lefty: 0, + search_time: 0, trail_time: 0, last_sighting: [0, 0, 0], saved_goal: [0, 0, 0], linkcount: 0, idle_time: 0, + stall_pos: null, stall_t: 0, chase_until: 0 }, + }); + e.max_health = e.health; + const mv = d.moves.sight; e.frame = mv.first + (Q.rand(g) % (mv.last - mv.first + 1)); + const p = g.ents[1]; + if (p.health <= 0) return; + let vec = sub(p.origin, e.origin); + e.angles[1] = Q.vectoyaw(vec); // ideal_yaw stays 0 until HuntTarget + vec = norm(vec); + e.velocity = scale(vec, 400); e.velocity[2] = 200; e.groundentity = -1; + Q.event(g, 'makron_spawn'); + }; + + // ================= Makron (m_boss32.c), second form ================= + const MAKRON_BLASTER = [[-3.6, -24.1, 59.5], [-1.6, -19.3, 59.5], [-0.1, -14.4, 59.5], [2.0, -7.6, 59.5], [3.4, 1.3, 59.5], [3.7, 11.1, 59.5], + [-0.3, 22.3, 59.5], [-6, 33, 59.5], [-9.3, 36.4, 59.5], [-7, 35, 59.5], [-2.1, 29, 59.5], [3.9, 17.3, 59.5], [6.1, 5.8, 59.5], [5.9, -4.4, 59.5], + [4.2, -14.1, 59.5], [2.4, -18.8, 59.5], [-1.8, -25.5, 59.5]]; + DEFS.monster_makron = { + name: 'Armored Pilot', health: 3000, gib_health: -2000, mass: 500, mins: [-30, -30, 0], maxs: [30, 30, 90], gibs: 5, startMove: 'sight', + moves: moves({ + stand: [414, 473, 's0x60', null], + run: [477, 486, 'r3:makron_step_left r12 r8x2 r8:makron_step_right r6 r12 r9 r6 r12', null], + walk: [477, 486, 'r3:makron_step_left r12 r8x2 r8:makron_step_right r6 r12 r9 r6 r12', null], + pain6: [387, 413, 'm0x15 m0:makron_popup m0x7 m0:makron_taunt m0x3', 'run'], + pain5: [383, 386, 'm0x4', 'run'], pain4: [379, 382, 'm0x4', 'run'], + death2: [251, 345, 'm-15 m3 m-12 m0:makron_step_left m0x11 m11 m12 m11:makron_step_right m0x15 m5 m7 m6:makron_step_left m0x2 m-1 m2 m0x13 m-6 m-4 m-6:makron_step_right m-4 m-4:makron_step_left m0x4 m-2 m-5 m-3:makron_step_right m-8 m-3:makron_step_left m-7 m-4 m-4:makron_step_right m-6 m-7 m0:makron_step_left m0x12 m-2 m0x2 m2 m0 m27:makron_hit m26 m0:makron_brainsplorch m0x2', 'dead'], + sight: [188, 200, 'm0x13', 'run'], + attack3: [201, 208, 'c0x3 c0:makronBFG m0x4', 'run'], + attack4: [209, 234, 'c0x4 m0:MakronHyperblasterx17 m0x5', 'run'], + attack5: [235, 250, 'c0:makron_prerailgun c0x6 c0:MakronSaveloc m0:MakronRailgun m0x7', 'run'], + }), + stand, walk: (g, i) => setMove(g.ents[i], 'walk'), run: runOrStand, sight: (g, i) => setMove(g.ents[i], 'sight'), + makron_step_left: sound, makron_step_right: sound, makron_popup: sound, makron_hit: sound, makron_brainsplorch: sound, + makron_taunt: (g) => { Q.random(g); }, makron_prerailgun: (g, i) => Q.fx(g, 'railcharge', g.ents[i].origin, null, { owner: i }), + checkattack: bossCheckAttack(0.4, 0.2), + attack(g, i) { + const r = Q.random(g), e = g.ents[i]; + setMove(e, r <= 0.3 ? 'attack3' : r <= 0.6 ? 'attack4' : 'attack5'); + }, + makronBFG(g, i) { + const e = g.ents[i], start = muzzle(e, [17, -19.5, 62.9]); + Q.fireBFG(g, i, start, aimAt(g, start, enemyEye(g, e, 0)), 50, 300, 300); + flash(g, i, 'bfg', start); + }, + MakronSaveloc(g, i) { const e = g.ents[i], en = g.ents[e.enemy]; e.pos1 = copy3(en.origin); e.pos1[2] += en.viewheight; }, + MakronRailgun(g, i) { + const e = g.ents[i], start = muzzle(e, [-17.3, 7.8, 72.4]); + Q.fireRail(g, i, start, norm(sub(e.pos1, start)), 50, 100); + flash(g, i, 'rail', start); + }, + MakronHyperblaster(g, i) { + const e = g.ents[i], start = muzzle(e, MAKRON_BLASTER[e.frame - 213]); + const dir = [0, 0, 0]; + if (e.enemy >= 0) { const v = enemyEye(g, e, 0); dir[0] = Q.vectoangles(sub(v, start))[0]; } + dir[1] = e.frame <= 221 ? e.angles[1] - 10 * (e.frame - 221) : e.angles[1] + 10 * (e.frame - 229); + Q.fireBlaster(g, i, start, Q.angleVectors(dir).forward, 15, 1000, 'blaster', false); + flash(g, i, 'blaster', start); + }, + pain(g, i, other, kick, damage) { + const e = g.ents[i]; + if (e.health < e.max_health / 2) e.skinnum = 1; + if (debounced(g, e)) return; + if (damage <= 25 && Q.random(g) < 0.2) return; + e.pain_debounce_time = g.ms + 3000; + if (g.skill === 3) return; + if (damage <= 40) setMove(e, 'pain4'); + else if (damage <= 110) setMove(e, 'pain5'); + else if (damage <= 150) { // C's dangling else: the 0.35 retry belongs to this branch, >150 gives no pain + if (Q.random(g) <= 0.45) setMove(e, 'pain6'); else if (Q.random(g) <= 0.35) setMove(e, 'pain6'); + } + }, + die(g, i) { + const e = g.ents[i]; + if (e.deadflag === Q.DEAD_DEAD) return; + e.deadflag = Q.DEAD_DEAD; e.takedamage = Q.DAMAGE_YES; setMove(e, 'death2'); + }, + dead: bossDead([-60, -60, 0], [60, 60, 72]), + }; + + // ---------------- shared helpers of the three unit monsters ---------------- + // fire_hit (g_weapon.c), the melee hit of the Gladiator and the Mutant. Kept as in the source: `dir` is not + // normalized before VectorMA, so the trace runs from the attacker's origin far past the enemy along that line. + Q.fireHit = (g, i, aim, damage, kick) => { + const self = g.ents[i], en = g.ents[self.enemy]; + let dir = sub(en.origin, self.origin); + let range = len(dir); + if (range > aim[0]) return false; + aim = copy3(aim); + if (aim[1] > self.mins[0] && aim[1] < self.maxs[0]) range -= en.maxs[0]; // straight on: back up to the box edge + else aim[1] = aim[1] < 0 ? en.mins[0] : en.maxs[0]; // side hit: out to the box edge + let point = ma(self.origin, range, dir); + const tr = Q.trace(g, self.origin, null, null, point, i, Q.MASK_SHOT); + let target = tr.ent; + if (tr.fraction < 1) { + const h = g.ents[tr.ent]; + if (!h.takedamage) return false; + if ((h.svflags & Q.SVF_MONSTER) || h.client) target = self.enemy; // whatever it hits, it hits the enemy + } + const av = Q.angleVectors(self.angles); + point = ma(ma(ma(self.origin, range, av.forward), aim[1], av.right), aim[2], av.up); + dir = sub(point, en.origin); + Q.damage(g, target, i, i, dir, point, [0, 0, 0], damage, Math.trunc(kick / 2), Q.DAMAGE_NO_KNOCKBACK, 'hit'); + const t = g.ents[target]; + if (!(t.svflags & Q.SVF_MONSTER) && !t.client) return false; + // the special knockback: from the hit point towards the middle of the enemy's absolute box + const mid = [Q.absmin(en)[0] + 0.5 * (en.maxs[0] - en.mins[0]), Q.absmin(en)[1] + 0.5 * (en.maxs[1] - en.mins[1]), Q.absmin(en)[2] + 0.5 * (en.maxs[2] - en.mins[2])]; + en.velocity = ma(en.velocity, kick, norm(sub(mid, point))); + if (en.velocity[2] > 0) en.groundentity = -1; + Q.fx(g, 'slash', point, null, { owner: i }); + return true; + }; + // Regular (non-boss) death: gib below gib_health, else the death move; the corpse can still take damage. + function unitDie(gibs, deathMove) { + return (g, i, inflictor, attacker, damage) => { + const e = g.ents[i]; + if (e.health <= e.gib_health) { + for (const [kind, n, organic] of gibs.body) for (let k = 0; k < n; k++) Q.throwGib(g, i, kind, damage, organic); + Q.throwHead(g, i, gibs.head[0], damage, gibs.head[1]); + e.deadflag = Q.DEAD_DEAD; e.gibbed = true; + Q.fx(g, 'gibs', Q.center(e), null, { size: 32 }); + return; + } + if (e.deadflag === Q.DEAD_DEAD) return; + e.deadflag = Q.DEAD_DEAD; e.takedamage = Q.DAMAGE_YES; + setMove(e, typeof deathMove === 'function' ? deathMove(g, e) : deathMove); + }; + } + // M_FlyCheck / M_FliesOn / M_FliesOff: flies around a corpse (an effect, with its own random draws). + function flyCheck(g, i) { + const e = g.ents[i]; + if (Q.random(g) > 0.5) return; + e.think = 'M_FliesOn'; e.nextthink = g.ms + 5000 + 10000 * Q.random(g); + } + Q.THINK.M_FliesOn = (g, i) => { const e = g.ents[i]; e.flies = true; e.think = 'M_FliesOff'; e.nextthink = g.ms + 60000; }; + Q.THINK.M_FliesOff = (g, i) => { g.ents[i].flies = false; }; + + // ================= Tank Commander (m_tank.c, monster_tank_commander: the Tank with 1000 health, skin 2) ================= + const TANK_MG = [[22.9, -0.7, 25.3], [22.2, 6.2, 22.3], [19.4, 13.1, 18.6], [19.4, 18.8, 18.6], [17.9, 25.0, 18.6], [14.1, 30.5, 20.6], + [9.3, 35.3, 22.1], [4.7, 38.4, 22.1], [-1.1, 40.4, 24.1], [-6.5, 41.2, 24.1], [3.2, 40.1, 24.7], [11.7, 36.7, 26.0], [18.9, 31.3, 26.0], + [24.4, 24.4, 26.4], [27.1, 17.1, 27.2], [28.5, 9.1, 28.0], [27.1, 2.2, 28.0], [24.9, -2.8, 28.0], [21.6, -7.0, 26.4]]; + DEFS.monster_tank_commander = { + name: 'Chain-Gun Heavy Trooper', health: 1000, gib_health: -225, mass: 500, mins: [-32, -32, -16], maxs: [32, 32, 72], skin: 2, + moves: moves({ + stand: [0, 29, 's0x30', null], + start_walk: [30, 33, 'w0 w6x2 w11:tank_footstep', 'walk'], + walk: [34, 49, 'w4 w5 w3 w2 w5x2 w4 w4:tank_footstep w3 w5 w4 w5 w7x2 w6 w6:tank_footstep', null], + start_run: [30, 33, 'r0 r6x2 r11:tank_footstep', 'run'], + run: [34, 49, 'r4 r5 r3 r2 r5x2 r4 r4:tank_footstep r3 r5 r4 r5 r7x2 r6 r6:tank_footstep', null], + pain1: [197, 200, 'm0x4', 'run'], pain2: [201, 205, 'm0x5', 'run'], + pain3: [206, 221, 'm-7 m0x3 m2 m0x2 m3 m0 m2 m0x5 m0:tank_footstep', 'run'], + attack_blast: [55, 70, 'c0x4 c-1 c-2 c-1x2 c0 c0:TankBlaster c0x2 c0:TankBlaster c0x2 c0:TankBlaster', 'reattack_blaster'], + reattack_blast: [65, 70, 'c0x2 c0:TankBlaster c0x2 c0:TankBlaster', 'reattack_blaster'], + attack_post_blast: [71, 76, 'm0x2 m2 m3 m2 m-2:tank_footstep', 'run'], + attack_strike: [77, 114, 'm3 m2x2 m1 m6 m7 m9:tank_footstep m2 m1 m2 m2:tank_footstep m2 m0x4 m-2x2 m0:tank_windup m0x6 m0:TankStrike m0 m-1x5 m-3 m-10x2 m-2 m-3 m-2:tank_footstep', 'poststrike'], + attack_pre_rocket: [115, 135, 'c0x11 c1 c2 c7x2 c7:tank_footstep c0x4 c-3', 'doattack_rocket'], + attack_fire_rocket: [136, 144, 'c-3 c0 c0:TankRocket c0x2 c0:TankRocket c0x2 c-1:TankRocket', 'refire_rocket'], + attack_post_rocket: [145, 167, 'c0 c-1x2 c0 c2 c3 c4 c2 c0x3 c-9 c-8 c-7 c-1 c-1:tank_footstep c0x7', 'run'], + attack_chain: [168, 196, 'c0x5 n0:TankMachineGunx19 c0x5', 'run'], + death: [222, 253, 'm-7 m-2x2 m1 m3 m6 m1x2 m2 m0x3 m-2 m0x2 m-3 m0x6 m-4 m-6 m-4 m-5 m-7 m-15:tank_thud m-5 m0x3', 'dead'], + }), + stand, walk: (g, i) => setMove(g.ents[i], 'walk'), sight: sound, + tank_footstep: sound, tank_thud: sound, tank_windup: sound, TankStrike: sound, + // tank_run: AI_BRUTAL against a client; from walk / start_run straight into run, otherwise via start_run. + run(g, i) { + const e = g.ents[i], mi = e.monsterinfo; + if (e.enemy >= 0 && g.ents[e.enemy].client) mi.aiflags |= AI_BRUTAL; else mi.aiflags &= ~AI_BRUTAL; + if (mi.aiflags & AI_STAND_GROUND) { setMove(e, 'stand'); return; } + setMove(e, mi.currentmove === 'walk' || mi.currentmove === 'start_run' ? 'run' : 'start_run'); + }, + pain(g, i, other, kick, damage) { + const e = g.ents[i]; + if (e.health < e.max_health / 2) e.skinnum |= 1; + if (damage <= 10) return; + if (debounced(g, e)) return; + if (damage <= 30 && Q.random(g) > 0.2) return; + if (g.skill >= 2 && ((e.frame >= 115 && e.frame <= 144) || (e.frame >= 55 && e.frame <= 70))) return; // not while attacking + e.pain_debounce_time = g.ms + 3000; + if (g.skill === 3) return; + setMove(e, damage <= 30 ? 'pain1' : damage <= 60 ? 'pain2' : 'pain3'); + }, + TankBlaster(g, i) { + const e = g.ents[i], ofs = e.frame === 64 ? [20.7, -18.5, 28.7] : e.frame === 67 ? [16.6, -21.5, 30.1] : [11.8, -23.9, 32.1]; + const start = muzzle(e, ofs); + Q.fireBlaster(g, i, start, sub(enemyEye(g, e, 0), start), 30, 800, 'blaster', false); + flash(g, i, 'blaster', start); + }, + TankRocket(g, i) { + const e = g.ents[i], ofs = e.frame === 138 ? [6.2, 29.1, 49.1] : e.frame === 141 ? [6.9, 23.8, 49.1] : [8.3, 17.8, 49.5]; + const start = muzzle(e, ofs); + Q.monsterFireRocket(g, i, start, aimAt(g, start, enemyEye(g, e, 0)), 50, 550); + flash(g, i, 'rocket', start); + }, + // The chaingun sweep: pitch at the enemy's eye, yaw by frame from +40 to -32 and back to +40 degrees off the facing + // it had when the burst started (the 19 firing frames have no AI function, so the Tank does not turn meanwhile). + TankMachineGun(g, i) { + const e = g.ents[i], start = muzzle(e, TANK_MG[e.frame - 173]), dir = [0, 0, 0]; + if (e.enemy >= 0) dir[0] = Q.vectoangles(sub(enemyEye(g, e, 0), start))[0]; + dir[1] = e.frame <= 182 ? e.angles[1] - 8 * (e.frame - 178) : e.angles[1] + 8 * (e.frame - 186); + Q.monsterFireBullet(g, i, start, Q.angleVectors(dir).forward, 20, 4); + flash(g, i, 'mg', start); + }, + reattack_blaster(g, i) { // skill >= 2 only: 60 % another two bolts while the enemy is visible and alive + const e = g.ents[i]; + if (g.skill >= 2 && Q.visible(g, i, e.enemy) && g.ents[e.enemy].health > 0 && Q.random(g) <= 0.6) { setMove(e, 'reattack_blast'); return; } + setMove(e, 'attack_post_blast'); + }, + doattack_rocket: (g, i) => setMove(g.ents[i], 'attack_fire_rocket'), + refire_rocket(g, i) { // skill >= 2 only: 40 % another volley + const e = g.ents[i]; + if (g.skill >= 2 && g.ents[e.enemy].health > 0 && Q.visible(g, i, e.enemy) && Q.random(g) <= 0.4) { setMove(e, 'attack_fire_rocket'); return; } + setMove(e, 'attack_post_rocket'); + }, + poststrike(g, i) { g.ents[i].enemy = -1; DEFS.monster_tank_commander.run(g, i); }, + attack(g, i) { + const e = g.ents[i], mi = e.monsterinfo; + if (g.ents[e.enemy].health < 0) { setMove(e, 'attack_strike'); mi.aiflags &= ~AI_BRUTAL; return; } + const range = len(sub(g.ents[e.enemy].origin, e.origin)), r = Q.random(g); + if (range <= 125) setMove(e, r < 0.4 ? 'attack_chain' : 'attack_blast'); + else if (range <= 250) setMove(e, r < 0.5 ? 'attack_chain' : 'attack_blast'); + else if (r < 0.33) setMove(e, 'attack_chain'); + else if (r < 0.66) { setMove(e, 'attack_pre_rocket'); e.pain_debounce_time = g.ms + 5000; } // no pain for a while + else setMove(e, 'attack_blast'); + }, + die: unitDie({ body: [['meat', 1, true], ['metal', 4, false], ['chest', 1, true]], head: ['gear', false] }, 'death'), + dead: bossDead([-16, -16, -16], [16, 16, 0]), + }; + + // ================= Gladiator (m_gladiator.c) ================= + DEFS.monster_gladiator = { + name: 'Blade-Arm Gunner', health: 400, gib_health: -175, mass: 400, mins: [-32, -32, -24], maxs: [32, 32, 64], + moves: moves({ + stand: [0, 6, 's0x7', null], + walk: [7, 22, 'w15 w7 w6 w5 w2 w0 w2 w8 w12 w8 w5x2 w2x2 w1 w8', null], + run: [23, 28, 'r23 r14x2 r21 r12 r13', null], + attack_melee: [29, 45, 'c0x4 c0:gladiator_cleaver_swing c0 c0:GaldiatorMelee c0x3 c0:gladiator_cleaver_swing c0x2 c0:GaldiatorMelee c0x3', 'run'], + attack_gun: [46, 54, 'c0x3 c0:GladiatorGun c0x5', 'run'], + pain: [55, 60, 'm0x6', 'run'], + pain_air: [83, 89, 'm0x7', 'run'], + death: [61, 82, 'm0x22', 'dead'], + }), + stand, walk: (g, i) => setMove(g.ents[i], 'walk'), run: runOrStand, sight: sound, gladiator_cleaver_swing: sound, + melee: (g, i) => setMove(g.ents[i], 'attack_melee'), + GaldiatorMelee(g, i) { Q.fireHit(g, i, [Q.MELEE_DISTANCE, g.ents[i].mins[0], -4], 20 + (Q.rand(g) % 5), 300); }, + // gladiator_attack: nothing inside MELEE_DISTANCE + 32 (a small safe zone); otherwise the eye position is saved + // NOW and the railgun fires along it on the fourth frame of attack_gun (0.4 s later). + attack(g, i) { + const e = g.ents[i], en = g.ents[e.enemy]; + if (len(sub(e.origin, en.origin)) <= Q.MELEE_DISTANCE + 32) return; + e.pos1 = copy3(en.origin); e.pos1[2] += en.viewheight; + setMove(e, 'attack_gun'); + }, + GladiatorGun(g, i) { + const e = g.ents[i], start = muzzle(e, [30.0, 18.0, 28.0]); + Q.fireRail(g, i, start, norm(sub(e.pos1, start)), 50, 100); + flash(g, i, 'rail', start); + }, + pain(g, i, other, kick, damage) { + const e = g.ents[i]; + if (e.health < e.max_health / 2) e.skinnum = 1; + if (debounced(g, e)) { + if (e.velocity[2] > 100 && e.monsterinfo.currentmove === 'pain') setMove(e, 'pain_air'); + return; + } + e.pain_debounce_time = g.ms + 3000; + Q.random(g); // which pain sound + if (g.skill === 3) return; + setMove(e, e.velocity[2] > 100 ? 'pain_air' : 'pain'); + }, + die: unitDie({ body: [['bone', 2, true], ['meat', 4, true]], head: ['head', true] }, 'death'), + dead: bossDead([-16, -16, -24], [16, 16, -8]), + }; + + // ================= Mutant (m_mutant.c) ================= + function mutantCheckJump(g, i) { + const e = g.ents[i], en = g.ents[e.enemy], esize = en.maxs[2] - en.mins[2], emin = Q.absmin(en)[2]; + if (Q.absmin(e)[2] > emin + 0.75 * esize) return false; + if (Q.absmax(e)[2] < emin + 0.25 * esize) return false; + const d = Math.sqrt((e.origin[0] - en.origin[0]) ** 2 + (e.origin[1] - en.origin[1]) ** 2); + if (d < 100) return false; + if (d > 100 && Q.random(g) < 0.9) return false; + return true; + } + DEFS.monster_mutant = { + name: 'Clawed Pouncer', health: 300, gib_health: -120, mass: 300, mins: [-32, -32, -24], maxs: [32, 32, 48], + moves: moves({ + stand: [62, 112, 's0x51', null], + start_walk: [126, 129, 'w5x2 w-2 w1', 'mutant_walk_loop'], + walk: [130, 141, 'w3 w1 w5 w10 w13 w10 w0 w5 w6 w16 w15 w6', null], + run: [56, 61, 'r40 r40:mutant_step r24 r5:mutant_step r17 r10', null], + attack: [8, 14, 'c0x2 c0:mutant_hit_left c0x2 c0:mutant_hit_right c0:mutant_check_refire', 'run'], + jump: [0, 7, 'c0 c17 c15:mutant_jump_takeoff c15 c15:mutant_check_landing c0 c3 c0', 'run'], + pain1: [34, 38, 'm4 m-3 m-8 m2 m5', 'run'], pain2: [39, 44, 'm-24 m11 m5 m-2 m6 m4', 'run'], + pain3: [45, 55, 'm-22 m3x2 m2 m1x2 m6 m3 m2 m0 m1', 'run'], + death1: [15, 23, 'm0x9', 'dead'], death2: [24, 33, 'm0x10', 'dead'], + }), + stand, walk: (g, i) => setMove(g.ents[i], 'start_walk'), mutant_walk_loop: (g, i) => setMove(g.ents[i], 'walk'), run: runOrStand, + sight: sound, + mutant_step: g => { Q.rand(g); }, // (rand() + 1) % 3 picks a footstep sound + melee: (g, i) => setMove(g.ents[i], 'attack'), + mutant_hit_left(g, i) { Q.fireHit(g, i, [Q.MELEE_DISTANCE, g.ents[i].mins[0], 8], 10 + (Q.rand(g) % 5), 100); }, + mutant_hit_right(g, i) { Q.fireHit(g, i, [Q.MELEE_DISTANCE, g.ents[i].maxs[0], 8], 10 + (Q.rand(g) % 5), 100); }, + mutant_check_refire(g, i) { // claw again while in melee range (and half the time anyway on skill 3) + const e = g.ents[i], en = e.enemy >= 0 ? g.ents[e.enemy] : null; + if (!en || !en.inuse || en.health <= 0) return; + if ((g.skill === 3 && Q.random(g) < 0.5) || Q.range(g, i, e.enemy) === Q.RANGE_MELEE) e.monsterinfo.nextframe = 8; + }, + attack: (g, i) => setMove(g.ents[i], 'jump'), + // The leap: 600 forward and 250 up from the facing at takeoff; AI_DUCKED suppresses pain until it lands. + mutant_jump_takeoff(g, i) { + const e = g.ents[i], forward = Q.angleVectors(e.angles).forward; + e.origin[2] += 1; + e.velocity = scale(forward, 600); e.velocity[2] = 250; + e.groundentity = -1; + e.monsterinfo.aiflags |= AI_DUCKED; + e.monsterinfo.attack_finished = g.ms + 3000; + e.touch = 'mutant_jump_touch'; + Q.event(g, 'mutant_leap'); + }, + mutant_check_landing(g, i) { // hold this frame until landing; after 3 s in the air jump again + const e = g.ents[i], mi = e.monsterinfo; + if (e.groundentity >= 0) { mi.attack_finished = 0; mi.aiflags &= ~AI_DUCKED; return; } + mi.nextframe = g.ms > mi.attack_finished ? 1 : 4; + }, + checkattack(g, i) { // mutant_checkattack: melee range first, then the 10 % leap check + const e = g.ents[i], mi = e.monsterinfo; + if (e.enemy < 0 || g.ents[e.enemy].health <= 0) return false; + if (Q.range(g, i, e.enemy) === Q.RANGE_MELEE) { mi.attack_state = AS_MELEE; return true; } + if (mutantCheckJump(g, i)) { mi.attack_state = AS_MISSILE; return true; } + return false; + }, + pain(g, i) { + const e = g.ents[i]; + if (e.health < e.max_health / 2) e.skinnum = 1; + if (debounced(g, e)) return; + e.pain_debounce_time = g.ms + 3000; + if (g.skill === 3) return; + const r = Q.random(g); + setMove(e, r < 0.33 ? 'pain1' : r < 0.66 ? 'pain2' : 'pain3'); + }, + die: unitDie({ body: [['bone', 2, true], ['meat', 4, true]], head: ['head', true] }, (g, e) => { e.skinnum = 1; return Q.random(g) < 0.5 ? 'death1' : 'death2'; }), + dead(g, i) { + const e = g.ents[i]; + e.mins = [-16, -16, -24]; e.maxs = [16, 16, -8]; e.movetype = 'toss'; e.svflags |= Q.SVF_DEADMONSTER; + flyCheck(g, i); + }, + }; + // mutant_jump_touch: a hit at more than 400 u/s does 40 + 10 * random() with as much knockback. + Q.TOUCH.mutant_jump_touch = (g, i, other, plane) => { + const e = g.ents[i]; + if (e.health <= 0) { e.touch = null; return; } + if (other > 0 && g.ents[other].takedamage && len(e.velocity) > 400) { + const normal = norm(e.velocity), point = ma(e.origin, e.maxs[0], normal); + const damage = Math.trunc(40 + 10 * Q.random(g)); + Q.damage(g, other, i, i, e.velocity, point, normal, damage, damage, 0, 'mutant_leap'); + } + if (!checkBottom(g, i)) { + if (e.groundentity >= 0) { e.monsterinfo.nextframe = 1; e.touch = null; } + return; + } + e.touch = null; + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/quake2_remake/q2player.js b/environments/games/web/games/quake2_remake/q2player.js new file mode 100644 index 0000000000000000000000000000000000000000..35a029bd1577602e9fc1934a3450bdbd3fd9631e --- /dev/null +++ b/environments/games/web/games/quake2_remake/q2player.js @@ -0,0 +1,852 @@ +/* Quake II (1997) boss arenas - the player: client input (cl_input.c CL_BaseMove, in_win.c IN_MouseMove), + player movement (qcommon/pmove.c Pmove), ClientThink / ClientBeginServerFrame (p_client.c), ClientEndServerFrame + (p_view.c falling damage, damage feedback), weapons (p_weapon.c Weapon_Generic and the eight weapons used here), + projectiles and hitscan (g_weapon.c), damage (g_combat.c T_Damage / T_RadiusDamage / CheckArmor / CanDamage) and + items (g_items.c armor, health, ammo). Independent reimplementation from the GPL-2.0 source release, commit + 372afde46e7defc9dd2d719a1732b8ace1fa096e; see q2core.js. */ +(function (root) { + 'use strict'; + const M = root.Quake2Game, Q = M.Q; + const { add, sub, scale, ma, dot, len, norm, copy3 } = Q; + + // ---------------- pmove.c constants and client cvar defaults (cl_main.c) ---------------- + const PM = { stopspeed: 100, maxspeed: 300, duckspeed: 100, accelerate: 10, airaccelerate: 0, friction: 6 }; + const PMF_DUCKED = 1, PMF_JUMP_HELD = 2, PMF_ON_GROUND = 4, PMF_TIME_WATERJUMP = 8, PMF_TIME_LAND = 16, PMF_TIME_TELEPORT = 32; + const CL = { forwardspeed: 200, sidespeed: 200, upspeed: 200, yawspeed: 140, anglespeedkey: 1.5, sensitivity: 3, m_yaw: 0.022, m_pitch: 0.022 }; + const MIN_STEP_NORMAL = 0.7, STOP_EPSILON = 0.1, MAX_CLIP_PLANES = 5; + Q.PM = PM; Q.CL = CL; + const PLAYER_MINS = [-16, -16, -24], PLAYER_MAXS = [16, 16, 32]; + + // ---------------- items (g_items.c itemlist order; weapnext walks down the list, weapprev up) ---------------- + const ITEMS = { + blaster: { index: 7, kind: 'weapon', name: 'Energy Pistol', ammo: null, quantity: 0 }, + shotgun: { index: 8, kind: 'weapon', name: 'Shotgun', ammo: 'shells', quantity: 1 }, + supershotgun: { index: 9, kind: 'weapon', name: 'Double Shotgun', ammo: 'shells', quantity: 2 }, + machinegun: { index: 10, kind: 'weapon', name: 'Machinegun', ammo: 'bullets', quantity: 1 }, + chaingun: { index: 11, kind: 'weapon', name: 'Chaingun', ammo: 'bullets', quantity: 1 }, + rocketlauncher: { index: 14, kind: 'weapon', name: 'Rocket Launcher', ammo: 'rockets', quantity: 1 }, + hyperblaster: { index: 15, kind: 'weapon', name: 'Pulse Cannon', ammo: 'cells', quantity: 1 }, + railgun: { index: 16, kind: 'weapon', name: 'Coilgun', ammo: 'slugs', quantity: 1 }, + }; + const WEAPON_ORDER = Object.keys(ITEMS).sort((a, b) => ITEMS[a].index - ITEMS[b].index); + const AMMO_MAX = { bullets: 200, shells: 100, rockets: 50, cells: 200, slugs: 50 }; + const AMMO_PICKUP = { shells: 10, bullets: 50, cells: 50, rockets: 5, slugs: 10 }; + // gitem_armor_t: base_count, max_count, normal_protection, energy_protection. ArmorIndex checks jacket, combat, body. + const ARMOR = { jacket: [25, 50, 0.30, 0.00], combat: [50, 100, 0.60, 0.30], body: [100, 200, 0.80, 0.60] }; + const ARMOR_ORDER = ['jacket', 'combat', 'body']; + Q.ITEMS = ITEMS; Q.ARMOR = ARMOR; Q.AMMO_MAX = AMMO_MAX; Q.WEAPON_ORDER = WEAPON_ORDER; + Q.armorIndex = p => ARMOR_ORDER.find(a => p.inv[a] > 0) || null; + + // ---------------- player spawn (PutClientInServer + ChangeWeapon) ---------------- + Q.spawnPlayer = (g, spec) => { + const p = g.ents[1] = Q.blankEdict(); + Object.assign(p, { + classname: 'player', client: true, origin: copy3(spec.origin), old_origin: copy3(spec.origin), mins: copy3(PLAYER_MINS), maxs: copy3(PLAYER_MAXS), + viewheight: 22, health: 100, max_health: 100, mass: 200, takedamage: Q.DAMAGE_AIM, solid: Q.SOLID_BBOX, clipmask: Q.MASK_PLAYERSOLID, + movetype: 'walk', pain_debounce_time: 0, air_finished: 12000, + viewangles: [0, spec.yaw, 0], v_angle: [0, spec.yaw, 0], + pm: { origin: spec.origin.map(v => Math.trunc(v * 8)), velocity: [0, 0, 0], flags: 0, time: 0 }, old_pmove: null, + buttons: 0, oldbuttons: 0, latched: 0, weapon_thunk: false, inv: Object.assign({}, spec.inventory), + weapon: null, newweapon: spec.weapon, lastweapon: null, weaponstate: 0, gunframe: 0, machinegun_shots: 0, + kick_angles: [0, 0, 0], kick_origin: [0, 0, 0], oldvelocity: [0, 0, 0], damage_blood: 0, damage_armor: 0, damage_knockback: 0, + damage_from: [0, 0, 0], damage_alpha: 0, bonus_alpha: 0, fall_value: 0, fall_time: 0, mynoise: -1, mynoise2: -1, pickup: null, pickup_time: 0, fired: 0, + }); + changeWeapon(g, p); + }; + + // ---------------- client side: usercmd from held keys and the per-tick mouse delta ---------------- + // keys: Set of held key names, pressed: newly pressed keys, mouse: [dx, dy, dz] for this tick. msec is this host + // frame (16 or 17 ms at 60 Hz, q2-arena@3): one usercmd per client frame, as the original client at cl_maxfps 60. + Q.buildUsercmd = (g, keys, pressed, mouse, msec) => { + const p = g.ents[1], frametime = msec / 1000, speed = keys.has('Shift'); + // CL_AdjustAngles: keyboard turning, cl_yawspeed 140 deg/s, x1.5 with the speed key held. + const turn = (speed ? frametime * CL.anglespeedkey : frametime) * CL.yawspeed; + if (keys.has('E')) p.viewangles[1] -= turn; + if (keys.has('Q')) p.viewangles[1] += turn; + // IN_MouseMove with freelook: yaw -= m_yaw*sensitivity*dx, pitch += m_pitch*sensitivity*dy. + p.viewangles[1] -= CL.m_yaw * CL.sensitivity * (mouse[0] || 0); + p.viewangles[0] += CL.m_pitch * CL.sensitivity * (mouse[1] || 0); + p.viewangles[1] = ((p.viewangles[1] % 360) + 360) % 360; // client angles stay unquantized; ANGLE2SHORT wraps + // CL_ClampPitch (delta_angles are zero here): +-89 degrees. + if (p.viewangles[0] > 89) p.viewangles[0] = 89; + if (p.viewangles[0] < -89) p.viewangles[0] = -89; + const cmd = { msec, buttons: 0, angles: p.viewangles.map(Q.ANGLE2SHORT), forwardmove: 0, sidemove: 0, upmove: 0 }; + if (keys.has('D')) cmd.sidemove += CL.sidespeed; + if (keys.has('A')) cmd.sidemove -= CL.sidespeed; + if (keys.has('Space')) cmd.upmove += CL.upspeed; + if (keys.has('L')) cmd.upmove -= CL.upspeed; + if (keys.has('W')) cmd.forwardmove += CL.forwardspeed; + if (keys.has('S')) cmd.forwardmove -= CL.forwardspeed; + if (speed) { cmd.forwardmove *= 2; cmd.sidemove *= 2; cmd.upmove *= 2; } // (in_speed ^ cl_run 0) + if (keys.has('J') || keys.has('LMB')) cmd.buttons |= 1; // BUTTON_ATTACK + // Console commands bound to keys arrive before the move: weapnext (K / RMB / wheel up), weapprev (R / wheel down). + const next = pressed.has('K') || pressed.has('RMB') || (mouse[2] || 0) > 0, prev = pressed.has('R') || (mouse[2] || 0) < 0; + if (next) Q.cmdWeapCycle(g, -1); else if (prev) Q.cmdWeapCycle(g, +1); + return cmd; + }; + // Cmd_WeapNext_f / Cmd_WeapPrev_f walk itemlist away from the current weapon and call Use_Weapon on every owned + // weapon; the loop only stops when it comes back to pers.weapon (Use_Weapon sets newweapon, not weapon), so the + // last successful use wins: weapnext ends on the nearest higher-index weapon (wrapping), weapprev on the nearest + // lower one. dir -1 = weapnext, +1 = weapprev (the order the C loop visits indices). + Q.cmdWeapCycle = (g, dir) => { + const p = g.ents[1]; + if (!p.weapon || p.health <= 0) return; + const cur = WEAPON_ORDER.indexOf(p.weapon), n = WEAPON_ORDER.length; + for (let k = 1; k < n; k++) { + const w = WEAPON_ORDER[(cur + dir * k + n * 2) % n]; + if (p.inv[w]) useWeapon(g, p, w); + } + }; + function useWeapon(g, p, w) { // Use_Weapon + if (w === p.weapon) return; + const it = ITEMS[w]; + if (it.ammo && (!p.inv[it.ammo] || p.inv[it.ammo] < it.quantity)) return; + p.newweapon = w; + } + Q.useWeapon = useWeapon; + + // ---------------- Pmove ---------------- + function pmTrace(g, start, mins, maxs, end) { return Q.trace(g, start, mins, maxs, end, 1, Q.MASK_PLAYERSOLID); } + function clipVelocity(v, n, overbounce) { + const backoff = dot(v, n) * overbounce, out = [0, 0, 0]; + for (let i = 0; i < 3; i++) { out[i] = v[i] - n[i] * backoff; if (out[i] > -STOP_EPSILON && out[i] < STOP_EPSILON) out[i] = 0; } + return out; + } + function stepSlideMove_(g, pm, pml) { + const primal = copy3(pml.velocity), planes = []; + let time_left = pml.frametime; + for (let bump = 0; bump < 4; bump++) { + const end = [0, 1, 2].map(i => pml.origin[i] + time_left * pml.velocity[i]); + const tr = pmTrace(g, pml.origin, pm.mins, pm.maxs, end); + if (tr.allsolid) { pml.velocity[2] = 0; return; } + if (tr.fraction > 0) { pml.origin = copy3(tr.endpos); planes.length = 0; } + if (tr.fraction === 1) break; + if (pm.touch.length < 32) pm.touch.push(tr.ent); + time_left -= time_left * tr.fraction; + if (planes.length >= MAX_CLIP_PLANES) { pml.velocity = [0, 0, 0]; break; } + planes.push(tr.normal); + let i; + for (i = 0; i < planes.length; i++) { + pml.velocity = clipVelocity(pml.velocity, planes[i], 1.01); + let j; + for (j = 0; j < planes.length; j++) if (j !== i && dot(pml.velocity, planes[j]) < 0) break; + if (j === planes.length) break; + } + if (i === planes.length) { + if (planes.length !== 2) { pml.velocity = [0, 0, 0]; break; } + const dir = Q.cross(planes[0], planes[1]); pml.velocity = scale(dir, dot(dir, pml.velocity)); + } + if (dot(pml.velocity, primal) <= 0) { pml.velocity = [0, 0, 0]; break; } + } + if (pm.s.time) pml.velocity = primal; + } + function stepSlideMove(g, pm, pml) { + const start_o = copy3(pml.origin), start_v = copy3(pml.velocity); + stepSlideMove_(g, pm, pml); + const down_o = copy3(pml.origin), down_v = copy3(pml.velocity); + const up = copy3(start_o); up[2] += Q.STEPSIZE; + let tr = pmTrace(g, up, pm.mins, pm.maxs, up); + if (tr.allsolid) return; // can't step up + pml.origin = up; pml.velocity = copy3(start_v); + stepSlideMove_(g, pm, pml); + const down = copy3(pml.origin); down[2] -= Q.STEPSIZE; + tr = pmTrace(g, pml.origin, pm.mins, pm.maxs, down); + if (!tr.allsolid) pml.origin = copy3(tr.endpos); + const down_dist = (down_o[0] - start_o[0]) ** 2 + (down_o[1] - start_o[1]) ** 2; + const up_dist = (pml.origin[0] - start_o[0]) ** 2 + (pml.origin[1] - start_o[1]) ** 2; + if (down_dist > up_dist || tr.normal[2] < MIN_STEP_NORMAL) { pml.origin = down_o; pml.velocity = down_v; return; } + pml.velocity[2] = down_v[2]; + } + function friction(pm, pml) { + const v = pml.velocity, speed = Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); + if (speed < 1) { v[0] = 0; v[1] = 0; return; } + let drop = 0; + // SV_Trace always reports a ground surface (CM_BoxTrace starts from nullsurface); no slick surfaces here. + if (pm.groundentity >= 0) { const control = speed < PM.stopspeed ? PM.stopspeed : speed; drop += control * PM.friction * pml.frametime; } + let newspeed = speed - drop; if (newspeed < 0) newspeed = 0; newspeed /= speed; + v[0] *= newspeed; v[1] *= newspeed; v[2] *= newspeed; + } + function accelerate(pml, wishdir, wishspeed, accel) { + const currentspeed = dot(pml.velocity, wishdir), addspeed = wishspeed - currentspeed; + if (addspeed <= 0) return; + let accelspeed = accel * pml.frametime * wishspeed; if (accelspeed > addspeed) accelspeed = addspeed; + for (let i = 0; i < 3; i++) pml.velocity[i] += accelspeed * wishdir[i]; + } + function airMove(g, pm, pml) { + const fmove = pm.cmd.forwardmove, smove = pm.cmd.sidemove; + let wishvel = [pml.forward[0] * fmove + pml.right[0] * smove, pml.forward[1] * fmove + pml.right[1] * smove, 0]; + let wishspeed = len(wishvel); const wishdir = norm(wishvel); + const maxspeed = (pm.s.flags & PMF_DUCKED) ? PM.duckspeed : PM.maxspeed; + if (wishspeed > maxspeed) { wishvel = scale(wishvel, maxspeed / wishspeed); wishspeed = maxspeed; } + if (pm.groundentity >= 0) { + pml.velocity[2] = 0; + accelerate(pml, wishdir, wishspeed, PM.accelerate); + pml.velocity[2] = 0; // gravity > 0 + if (!pml.velocity[0] && !pml.velocity[1]) return; + stepSlideMove(g, pm, pml); + } else { + accelerate(pml, wishdir, wishspeed, 1); // pm_airaccelerate 0 + pml.velocity[2] -= Q.SV_GRAVITY * pml.frametime; + stepSlideMove(g, pm, pml); + } + } + function catagorizePosition(g, pm, pml) { + const point = [pml.origin[0], pml.origin[1], pml.origin[2] - 0.25]; + if (pml.velocity[2] > 180) { pm.s.flags &= ~PMF_ON_GROUND; pm.groundentity = -1; } + else { + const tr = pmTrace(g, pml.origin, pm.mins, pm.maxs, point); + pml.groundsurface = tr.fraction < 1 || tr.startsolid; + if (tr.normal[2] < 0.7 && !tr.startsolid) { pm.groundentity = -1; pm.s.flags &= ~PMF_ON_GROUND; } + else { + pm.groundentity = tr.ent; + if (pm.s.flags & PMF_TIME_WATERJUMP) { pm.s.flags &= ~(PMF_TIME_WATERJUMP | PMF_TIME_LAND | PMF_TIME_TELEPORT); pm.s.time = 0; } + if (!(pm.s.flags & PMF_ON_GROUND)) { + pm.s.flags |= PMF_ON_GROUND; + if (pml.velocity[2] < -200) { pm.s.flags |= PMF_TIME_LAND; pm.s.time = pml.velocity[2] < -400 ? 25 : 18; } + } + } + if (pm.touch.length < 32) pm.touch.push(tr.ent); + } + pm.waterlevel = 0; + } + function checkJump(pm, pml) { + if (pm.s.flags & PMF_TIME_LAND) return; + if (pm.cmd.upmove < 10) { pm.s.flags &= ~PMF_JUMP_HELD; return; } + if (pm.s.flags & PMF_JUMP_HELD) return; + if (pm.groundentity < 0) return; + pm.s.flags |= PMF_JUMP_HELD; pm.groundentity = -1; + pml.velocity[2] += 270; if (pml.velocity[2] < 270) pml.velocity[2] = 270; + } + function checkDuck(g, pm, pml) { + pm.mins = [-16, -16, -24]; pm.maxs = [16, 16, 32]; + if (pm.cmd.upmove < 0 && (pm.s.flags & PMF_ON_GROUND)) pm.s.flags |= PMF_DUCKED; + else if (pm.s.flags & PMF_DUCKED) { const tr = pmTrace(g, pml.origin, pm.mins, [16, 16, 32], pml.origin); if (!tr.allsolid) pm.s.flags &= ~PMF_DUCKED; } + if (pm.s.flags & PMF_DUCKED) { pm.maxs[2] = 4; pm.viewheight = -2; } else { pm.maxs[2] = 32; pm.viewheight = 22; } + } + const goodPosition = (g, pm) => { const o = pm.s.origin.map(v => v * 0.125); return !pmTrace(g, o, pm.mins, pm.maxs, o).allsolid; }; + function snapPosition(g, pm, pml) { + const JITTER = [0, 4, 1, 2, 3, 5, 6, 7], sign = [0, 0, 0]; + pm.s.velocity = pml.velocity.map(v => Math.trunc(v * 8)); + for (let i = 0; i < 3; i++) { + sign[i] = pml.origin[i] >= 0 ? 1 : -1; + pm.s.origin[i] = Math.trunc(pml.origin[i] * 8); + if (pm.s.origin[i] * 0.125 === pml.origin[i]) sign[i] = 0; + } + const base = copy3(pm.s.origin); + for (let j = 0; j < 8; j++) { + const bits = JITTER[j]; pm.s.origin = copy3(base); + for (let i = 0; i < 3; i++) if (bits & (1 << i)) pm.s.origin[i] += sign[i]; + if (goodPosition(g, pm)) return; + } + pm.s.origin = copy3(pml.previous_origin); + } + function initialSnapPosition(g, pm, pml) { + const OFS = [0, -1, 1], base = copy3(pm.s.origin); + for (let z = 0; z < 3; z++) for (let y = 0; y < 3; y++) for (let x = 0; x < 3; x++) { + pm.s.origin = [base[0] + OFS[x], base[1] + OFS[y], base[2] + OFS[z]]; + if (goodPosition(g, pm)) { pml.origin = pm.s.origin.map(v => v * 0.125); pml.previous_origin = copy3(pm.s.origin); return; } + } + } + function pmove(g, pm) { + pm.touch = []; pm.viewangles = [0, 0, 0]; pm.viewheight = 0; pm.groundentity = -1; pm.waterlevel = 0; + const pml = { origin: pm.s.origin.map(v => v * 0.125), velocity: pm.s.velocity.map(v => v * 0.125), previous_origin: copy3(pm.s.origin), frametime: pm.cmd.msec * 0.001, groundsurface: false }; + // PM_ClampAngles (delta_angles 0) + pm.viewangles = pm.cmd.angles.map(Q.SHORT2ANGLE); + if (pm.viewangles[0] > 89 && pm.viewangles[0] < 180) pm.viewangles[0] = 89; + else if (pm.viewangles[0] < 271 && pm.viewangles[0] >= 180) pm.viewangles[0] = 271; + let av = Q.angleVectors(pm.viewangles); pml.forward = av.forward; pml.right = av.right; + checkDuck(g, pm, pml); + if (pm.snapinitial) initialSnapPosition(g, pm, pml); + catagorizePosition(g, pm, pml); + if (pm.s.time) { + let msec = pm.cmd.msec >> 3; if (!msec) msec = 1; + if (msec >= pm.s.time) { pm.s.flags &= ~(PMF_TIME_WATERJUMP | PMF_TIME_LAND | PMF_TIME_TELEPORT); pm.s.time = 0; } else pm.s.time -= msec; + } + checkJump(pm, pml); + friction(pm, pml); + const angles = copy3(pm.viewangles); + if (angles[0] > 180) angles[0] -= 360; + angles[0] /= 3; + av = Q.angleVectors(angles); pml.forward = av.forward; pml.right = av.right; + airMove(g, pm, pml); + catagorizePosition(g, pm, pml); + snapPosition(g, pm, pml); + } + + // ---------------- ClientThink ---------------- + Q.clientThink = (g, cmd) => { + const p = g.ents[1]; + const pm = { s: { origin: p.origin.map(v => Math.trunc(v * 8)), velocity: p.velocity.map(v => Math.trunc(v * 8)), flags: p.pm.flags, time: p.pm.time }, cmd }; + pm.snapinitial = !p.old_pmove || JSON.stringify(p.old_pmove) !== JSON.stringify(pm.s); + pmove(g, pm); + p.pm = { origin: copy3(pm.s.origin), velocity: copy3(pm.s.velocity), flags: pm.s.flags, time: pm.s.time }; + p.old_pmove = JSON.parse(JSON.stringify(p.pm)); + p.origin = pm.s.origin.map(v => v * 0.125); p.velocity = pm.s.velocity.map(v => v * 0.125); + p.mins = copy3(pm.mins); p.maxs = copy3(pm.maxs); + if (p.groundentity >= 0 && pm.groundentity < 0 && cmd.upmove >= 10) { Q.playerNoise(g, p.origin, 'self'); Q.event(g, 'jump'); } + p.viewheight = pm.viewheight; p.groundentity = pm.groundentity; + p.v_angle = copy3(pm.viewangles); + touchTriggers(g, 1); + const seen = new Set(); + for (const other of pm.touch) { + if (other <= 0 || seen.has(other)) continue; seen.add(other); + const o = g.ents[other]; + if (o && o.inuse && o.touch && Q.TOUCH[o.touch]) Q.TOUCH[o.touch](g, other, 1, null); + } + p.oldbuttons = p.buttons; p.buttons = cmd.buttons; p.latched |= p.buttons & ~p.oldbuttons; + if ((p.latched & 1) && !p.weapon_thunk) { p.weapon_thunk = true; thinkWeapon(g); } + }; + function touchTriggers(g, i) { // G_TouchTriggers for the player: item triggers overlapping the absolute box + const e = g.ents[i]; + for (let k = 1; k < g.ents.length; k++) { + const t = g.ents[k]; + if (!t.inuse || t.solid !== Q.SOLID_TRIGGER || !t.touch) continue; + if (Q.boxesOverlap(e, t)) Q.TOUCH[t.touch](g, k, i, null); + if (!e.inuse) return; + } + } + + // ---------------- ClientBeginServerFrame / ClientEndServerFrame ---------------- + Q.clientBeginServerFrame = g => { + const p = g.ents[1]; + if (!p.weapon_thunk) thinkWeapon(g); else p.weapon_thunk = false; + if (p.deadflag) return; + if (!Q.visiblePoint(g, 1, Q.trailLastSpot(g).origin)) Q.playerTrailAdd(g, p.old_origin); + p.latched = 0; + }; + Q.clientEndServerFrame = g => { + const p = g.ents[1]; + fallingDamage(g, p); + damageFeedback(g, p); + // SV_CalcBlend drops the flashes after P_DamageFeedback added to them. + p.damage_alpha = Math.max(0, p.damage_alpha - 0.06); p.bonus_alpha = Math.max(0, p.bonus_alpha - 0.1); + p.oldvelocity = copy3(p.velocity); + p.kick_origin = [0, 0, 0]; p.kick_angles = [0, 0, 0]; + }; + function fallingDamage(g, p) { // P_FallingDamage + let delta; + if (p.oldvelocity[2] < 0 && p.velocity[2] > p.oldvelocity[2] && p.groundentity < 0) delta = p.oldvelocity[2]; + else { if (p.groundentity < 0) return; delta = p.velocity[2] - p.oldvelocity[2]; } + delta = delta * delta * 0.0001; + if (delta < 15) return; + p.fall_value = Math.min(40, delta * 0.5); p.fall_time = g.ms + 300; + if (delta > 30) { + p.pain_debounce_time = g.ms; + let damage = Math.trunc((delta - 30) / 2); if (damage < 1) damage = 1; + Q.damage(g, 1, 0, 0, [0, 0, 1], p.origin, [0, 0, 0], damage, 0, 0, 'falling'); + } + } + function damageFeedback(g, p) { // P_DamageFeedback: screen flash, and one rand() for the pain sound + let count = p.damage_blood + p.damage_armor; + if (!count) return; + if (count < 10) count = 10; // always make a visible effect + if (g.ms > p.pain_debounce_time) { Q.rand(g); p.pain_debounce_time = g.ms + 700; } + if (p.damage_alpha < 0) p.damage_alpha = 0; + p.damage_alpha = Math.min(0.6, Math.max(0.2, p.damage_alpha + count * 0.01)); + p.damage_from_dir = sub(p.damage_from, p.origin); + p.damage_blood = 0; p.damage_armor = 0; p.damage_knockback = 0; + } + // PlayerNoise: the first call spawns the two player noise edicts (they hold slots in the edict list). Weapon + // and self noise (firing, jumping) go to mynoise / level.sound_entity, impact noise to mynoise2 / sound2_entity. + Q.playerNoise = (g, where, type) => { + const p = g.ents[1]; + if (p.mynoise < 0) { + for (const k of ['mynoise', 'mynoise2']) { p[k] = Q.spawn(g); Object.assign(g.ents[p[k]], { classname: 'player_noise', svflags: Q.SVF_NOCLIENT, owner: 1, mins: [-8, -8, -8], maxs: [8, 8, 8], solid: Q.SOLID_NOT }); } + } + const n = type === 'impact' ? p.mynoise2 : p.mynoise; + if (type === 'impact') { g.sound2_entity = n; g.sound2_entity_framenum = g.framenum; } else { g.sound_entity = n; g.sound_entity_framenum = g.framenum; } + g.ents[n].origin = copy3(where || p.origin); g.ents[n].teleport_time = g.ms; + }; + + // ---------------- weapons ---------------- + const READY = 0, ACTIVATING = 1, DROPPING = 2, FIRING = 3; + // Weapon_Generic(FRAME_ACTIVATE_LAST, FRAME_FIRE_LAST, FRAME_IDLE_LAST, FRAME_DEACTIVATE_LAST, pause, fire) + const WDEF = { + blaster: { frames: [4, 8, 52, 55], pause: [19, 32], fire: [5], fn: 'blaster' }, + shotgun: { frames: [7, 18, 36, 39], pause: [22, 28, 34], fire: [8, 9], fn: 'shotgun' }, + supershotgun: { frames: [6, 17, 57, 61], pause: [29, 42, 57], fire: [7], fn: 'supershotgun' }, + machinegun: { frames: [3, 5, 45, 49], pause: [23, 45], fire: [4, 5], fn: 'machinegun' }, + chaingun: { frames: [4, 31, 61, 64], pause: [38, 43, 51, 61], fire: [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21], fn: 'chaingun' }, + rocketlauncher: { frames: [4, 12, 50, 54], pause: [25, 33, 42, 50], fire: [5], fn: 'rocket' }, + hyperblaster: { frames: [5, 20, 49, 53], pause: [], fire: [6, 7, 8, 9, 10, 11], fn: 'hyperblaster' }, + railgun: { frames: [3, 18, 56, 61], pause: [56], fire: [4], fn: 'railgun' }, + }; + Q.WDEF = WDEF; + function changeWeapon(g, p) { + p.lastweapon = p.weapon; p.weapon = p.newweapon; p.newweapon = null; p.machinegun_shots = 0; + if (!p.weapon) return; + p.weaponstate = ACTIVATING; p.gunframe = 0; + } + function noAmmoWeaponChange(g, p) { + const has = (w, ammo, n = 1) => p.inv[w] && p.inv[ammo] >= n; + p.newweapon = has('railgun', 'slugs') ? 'railgun' : has('hyperblaster', 'cells') ? 'hyperblaster' : has('chaingun', 'bullets') ? 'chaingun' + : has('machinegun', 'bullets') ? 'machinegun' : has('supershotgun', 'shells', 2) ? 'supershotgun' : has('shotgun', 'shells') ? 'shotgun' : 'blaster'; + } + function thinkWeapon(g) { + const p = g.ents[1]; + if (p.health < 1) { p.newweapon = null; changeWeapon(g, p); } + if (p.weapon) weaponGeneric(g, p, WDEF[p.weapon]); + } + function weaponGeneric(g, p, w) { + const [ACT_LAST, FIRE_LAST, IDLE_LAST, DEACT_LAST] = w.frames; + const FIRE_FIRST = ACT_LAST + 1, IDLE_FIRST = FIRE_LAST + 1, DEACT_FIRST = IDLE_LAST + 1; + if (p.deadflag) return; + if (p.weaponstate === DROPPING) { if (p.gunframe === DEACT_LAST) { changeWeapon(g, p); return; } p.gunframe++; return; } + if (p.weaponstate === ACTIVATING) { if (p.gunframe === ACT_LAST) { p.weaponstate = READY; p.gunframe = IDLE_FIRST; return; } p.gunframe++; return; } + if (p.newweapon && p.weaponstate !== FIRING) { p.weaponstate = DROPPING; p.gunframe = DEACT_FIRST; return; } + if (p.weaponstate === READY) { + if ((p.latched | p.buttons) & 1) { + p.latched &= ~1; + const it = ITEMS[p.weapon]; + if (!it.ammo || p.inv[it.ammo] >= it.quantity) { p.gunframe = FIRE_FIRST; p.weaponstate = FIRING; } + else { if (g.ms >= p.pain_debounce_time) p.pain_debounce_time = g.ms + 1000; noAmmoWeaponChange(g, p); } + } else { + if (p.gunframe === IDLE_LAST) { p.gunframe = IDLE_FIRST; return; } + for (const f of w.pause) if (p.gunframe === f && (Q.rand(g) & 15)) return; + p.gunframe++; return; + } + } + if (p.weaponstate === FIRING) { + let fired = false; + for (const f of w.fire) if (p.gunframe === f) { FIRE[w.fn](g, p); fired = true; break; } + if (!fired) p.gunframe++; + if (p.gunframe === IDLE_FIRST + 1) p.weaponstate = READY; + } + } + // P_ProjectSource (right handed), from the eye height. + const projectSource = (p, offset, forward, right) => Q.projectSource(p.origin, offset, forward, right); + const FIRE = { + blaster(g, p) { blasterFire(g, p, [0, 0, 0], 10, false, 'blaster'); p.gunframe++; }, + hyperblaster(g, p) { + if (!(p.buttons & 1)) p.gunframe++; + else { + if (!p.inv.cells) { if (g.ms >= p.pain_debounce_time) p.pain_debounce_time = g.ms + 1000; noAmmoWeaponChange(g, p); } + else { + const rotation = (p.gunframe - 5) * 2 * Math.PI / 6; + blasterFire(g, p, [-4 * Q.sin(rotation), 0, 4 * Q.cos(rotation)], 20, true, 'hyperblaster'); + p.inv.cells--; + } + p.gunframe++; + if (p.gunframe === 12 && p.inv.cells) p.gunframe = 6; + } + }, + machinegun(g, p) { + if (!(p.buttons & 1)) { p.machinegun_shots = 0; p.gunframe++; return; } + p.gunframe = p.gunframe === 5 ? 4 : 5; + if (p.inv.bullets < 1) { p.gunframe = 6; if (g.ms >= p.pain_debounce_time) p.pain_debounce_time = g.ms + 1000; noAmmoWeaponChange(g, p); return; } + for (let i = 1; i < 3; i++) { p.kick_origin[i] = Q.crandom(g) * 0.35; p.kick_angles[i] = Q.crandom(g) * 0.7; } + p.kick_origin[0] = Q.crandom(g) * 0.35; p.kick_angles[0] = p.machinegun_shots * -1.5; + p.machinegun_shots = Math.min(9, p.machinegun_shots + 1); + const av = Q.angleVectors(add(p.v_angle, p.kick_angles)); + const start = projectSource(p, [0, 8, p.viewheight - 8], av.forward, av.right); + Q.fireBullet(g, 1, start, av.forward, 8, 2, 300, 500, 'machinegun'); + Q.playerNoise(g, start, 'weapon'); muzzle(g, p, 'machinegun'); p.inv.bullets--; + }, + chaingun(g, p) { + if (p.gunframe === 14 && !(p.buttons & 1)) { p.gunframe = 32; return; } + else if (p.gunframe === 21 && (p.buttons & 1) && p.inv.bullets) p.gunframe = 15; + else p.gunframe++; + let shots = p.gunframe <= 9 ? 1 : p.gunframe <= 14 ? ((p.buttons & 1) ? 2 : 1) : 3; + if (p.inv.bullets < shots) shots = p.inv.bullets; + if (!shots) { if (g.ms >= p.pain_debounce_time) p.pain_debounce_time = g.ms + 1000; noAmmoWeaponChange(g, p); return; } + for (let i = 0; i < 3; i++) { p.kick_origin[i] = Q.crandom(g) * 0.35; p.kick_angles[i] = Q.crandom(g) * 0.7; } + for (let i = 0; i < shots; i++) { + const av = Q.angleVectors(p.v_angle), r = 7 + Q.crandom(g) * 4, u = Q.crandom(g) * 4; + const start = projectSource(p, [0, r, u + p.viewheight - 8], av.forward, av.right); + Q.fireBullet(g, 1, start, av.forward, 8, 2, 300, 500, 'chaingun'); + } + Q.playerNoise(g, p.origin, 'weapon'); muzzle(g, p, 'chaingun'); p.inv.bullets -= shots; + }, + shotgun(g, p) { + if (p.gunframe === 9) { p.gunframe++; return; } + const av = Q.angleVectors(p.v_angle); + p.kick_origin = scale(av.forward, -2); p.kick_angles[0] = -2; + const start = projectSource(p, [0, 8, p.viewheight - 8], av.forward, av.right); + Q.fireShotgun(g, 1, start, av.forward, 4, 8, 500, 500, 12, 'shotgun'); + p.gunframe++; Q.playerNoise(g, start, 'weapon'); muzzle(g, p, 'shotgun'); p.inv.shells--; + }, + supershotgun(g, p) { + const av = Q.angleVectors(p.v_angle); + p.kick_origin = scale(av.forward, -2); p.kick_angles[0] = -2; + const start = projectSource(p, [0, 8, p.viewheight - 8], av.forward, av.right); + let f = Q.angleVectors([p.v_angle[0], p.v_angle[1] - 5, p.v_angle[2]]).forward; + Q.fireShotgun(g, 1, start, f, 6, 12, 1000, 500, 10, 'sshotgun'); + f = Q.angleVectors([p.v_angle[0], p.v_angle[1] + 5, p.v_angle[2]]).forward; + Q.fireShotgun(g, 1, start, f, 6, 12, 1000, 500, 10, 'sshotgun'); + p.gunframe++; Q.playerNoise(g, start, 'weapon'); muzzle(g, p, 'supershotgun'); p.inv.shells -= 2; + }, + rocket(g, p) { + const damage = 100 + Math.trunc(Q.random(g) * 20.0); + const av = Q.angleVectors(p.v_angle); + p.kick_origin = scale(av.forward, -2); p.kick_angles[0] = -1; + const start = projectSource(p, [8, 8, p.viewheight - 8], av.forward, av.right); + Q.fireRocket(g, 1, start, av.forward, damage, 650, 120, 120); + p.gunframe++; Q.playerNoise(g, start, 'weapon'); muzzle(g, p, 'rocketlauncher'); p.inv.rockets--; + }, + railgun(g, p) { + const av = Q.angleVectors(p.v_angle); + p.kick_origin = scale(av.forward, -3); p.kick_angles[0] = -3; + const start = projectSource(p, [0, 7, p.viewheight - 8], av.forward, av.right); + Q.fireRail(g, 1, start, av.forward, 150, 250); + p.gunframe++; Q.playerNoise(g, start, 'weapon'); muzzle(g, p, 'railgun'); p.inv.slugs--; + }, + }; + function blasterFire(g, p, g_offset, damage, hyper, effect) { + const av = Q.angleVectors(p.v_angle); + const start = projectSource(p, add([24, 8, p.viewheight - 8], g_offset), av.forward, av.right); + p.kick_origin = scale(av.forward, -2); p.kick_angles[0] = -1; + Q.fireBlaster(g, 1, start, av.forward, damage, 1000, effect, hyper); + Q.playerNoise(g, start, 'weapon'); muzzle(g, p, hyper ? 'hyperblaster' : 'blaster'); + } + function muzzle(g, p, weapon) { p.fired = g.ms; p.firedWeapon = weapon; } + + // ---------------- hitscan and projectiles (g_weapon.c) ---------------- + // check_dodge: skill 0 skips three out of four checks; no monster here has a dodge function. + function checkDodge(g, self) { if (g.skill === 0 && Q.random(g) > 0.25) return; } + function fireLead(g, self, start, aimdir, damage, kick, hspread, vspread, mod) { + const se = g.ents[self]; + let tr = Q.trace(g, se.origin, null, null, start, self, Q.MASK_SHOT); + let end = null; + if (!(tr.fraction < 1.0)) { + const av = Q.angleVectors(Q.vectoangles(aimdir)); + const r = Q.crandom(g) * hspread, u = Q.crandom(g) * vspread; + end = ma(ma(ma(start, 8192, av.forward), r, av.right), u, av.up); + tr = Q.trace(g, start, null, null, end, self, Q.MASK_SHOT); + } + if (tr.fraction < 1.0 && !tr.sky) { + const hit = g.ents[tr.ent]; + if (tr.ent > 0 && hit.takedamage) Q.damage(g, tr.ent, self, self, aimdir, tr.endpos, tr.normal, damage, kick, Q.DAMAGE_BULLET, mod); + else { Q.fx(g, 'puff', tr.endpos, tr.normal); if (g.ents[self].client) Q.playerNoise(g, tr.endpos, 'impact'); } + } + Q.fx(g, 'tracer', start, null, { to: tr.endpos, from: self === 1 ? 'player' : 'monster' }); + } + Q.fireBullet = (g, self, start, aimdir, damage, kick, hspread, vspread, mod) => fireLead(g, self, start, aimdir, damage, kick, hspread, vspread, mod); + Q.fireShotgun = (g, self, start, aimdir, damage, kick, hspread, vspread, count, mod) => { for (let i = 0; i < count; i++) fireLead(g, self, start, aimdir, damage, kick, hspread, vspread, mod); }; + Q.fireBlaster = (g, self, start, dir, damage, speed, effect, hyper) => { + dir = norm(dir); + const i = Q.spawn(g), b = g.ents[i]; + Object.assign(b, { classname: 'bolt', svflags: Q.SVF_DEADMONSTER, origin: copy3(start), old_origin: copy3(start), angles: Q.vectoangles(dir), velocity: scale(dir, speed), + movetype: 'flymissile', clipmask: Q.MASK_SHOT, solid: Q.SOLID_BBOX, effect, owner: self, touch: 'blaster_touch', nextthink: g.ms + 2000, think: 'G_FreeEdict', dmg: damage, spawnflags: hyper ? 1 : 0 }); + if (g.ents[self].client) checkDodge(g, self); + const tr = Q.trace(g, g.ents[self].origin, null, null, b.origin, i, Q.MASK_SHOT); + if (tr.fraction < 1.0) { b.origin = ma(b.origin, -10, dir); Q.TOUCH.blaster_touch(g, i, tr.ent, null); } + }; + Q.TOUCH.blaster_touch = (g, i, other, plane, sky) => { + const b = g.ents[i]; + if (other === b.owner) return; + if (sky) { Q.freeEdict(g, i); return; } + if (g.ents[b.owner] && g.ents[b.owner].client) Q.playerNoise(g, b.origin, 'impact'); + const o = g.ents[other]; + if (other > 0 && o.takedamage) Q.damage(g, other, i, b.owner, b.velocity, b.origin, plane || [0, 0, 0], b.dmg, 1, Q.DAMAGE_ENERGY, b.spawnflags & 1 ? 'hyperblaster' : 'blaster'); + else Q.fx(g, 'blasterhit', b.origin, plane); + Q.freeEdict(g, i); + }; + Q.fireRocket = (g, self, start, dir, damage, speed, damage_radius, radius_damage) => { + const i = Q.spawn(g), r = g.ents[i]; + Object.assign(r, { classname: 'rocket', origin: copy3(start), old_origin: copy3(start), movedir: copy3(dir), angles: Q.vectoangles(dir), velocity: scale(dir, speed), + movetype: 'flymissile', clipmask: Q.MASK_SHOT, solid: Q.SOLID_BBOX, effect: 'rocket', owner: self, touch: 'rocket_touch', nextthink: g.ms + 8000000 / speed, think: 'G_FreeEdict', + dmg: damage, radius_dmg: radius_damage, dmg_radius: damage_radius }); + if (g.ents[self].client) checkDodge(g, self); + }; + Q.TOUCH.rocket_touch = (g, i, other, plane, sky) => { + const r = g.ents[i]; + if (other === r.owner) return; + if (sky) { Q.freeEdict(g, i); return; } + if (g.ents[r.owner] && g.ents[r.owner].client) Q.playerNoise(g, r.origin, 'impact'); + const o = g.ents[other]; + if (other > 0 && o.takedamage) Q.damage(g, other, i, r.owner, r.velocity, r.origin, plane || [0, 0, 0], r.dmg, 0, 0, 'rocket'); + else if (other === 0) { let n = Q.rand(g) % 5; while (n--) Q.throwDebris(g, i, 2, r.origin); } // single player only + Q.radiusDamage(g, i, r.owner, r.radius_dmg, other, r.dmg_radius, 'r_splash'); + Q.fx(g, 'explosion', ma(r.origin, -0.02, r.velocity), null, { big: r.dmg > 60 }); + Q.freeEdict(g, i); + }; + Q.fireRail = (g, self, start, aimdir, damage, kick) => { + const end = ma(start, 8192, aimdir); + let from = copy3(start), ignore = self, tr = null; + const mask = Q.MASK_SHOT; + let guard = 0; + while (ignore >= 0 && guard++ < 16) { + tr = Q.trace(g, from, null, null, end, ignore, mask); + const hit = g.ents[tr.ent]; + if (tr.ent > 0 && (hit.svflags & Q.SVF_MONSTER || hit.client)) ignore = tr.ent; else ignore = -1; + if (tr.ent !== self && tr.ent > 0 && hit.takedamage) Q.damage(g, tr.ent, self, self, aimdir, tr.endpos, tr.normal, damage, kick, 0, 'railgun'); + from = copy3(tr.endpos); + if (tr.fraction === 1) break; + } + if (g.ents[self].client) Q.playerNoise(g, tr.endpos, 'impact'); + Q.fx(g, 'rail', start, null, { to: tr.endpos, from: self === 1 ? 'player' : 'monster' }); + }; + Q.fireBFG = (g, self, start, dir, damage, speed, damage_radius) => { + const i = Q.spawn(g), b = g.ents[i]; + Object.assign(b, { classname: 'bfg blast', origin: copy3(start), old_origin: copy3(start), movedir: copy3(dir), angles: Q.vectoangles(dir), velocity: scale(dir, speed), + movetype: 'flymissile', clipmask: Q.MASK_SHOT, solid: Q.SOLID_BBOX, effect: 'bfg', owner: self, touch: 'bfg_touch', radius_dmg: damage, dmg_radius: damage_radius, + think: 'bfg_think', nextthink: g.ms + Q.FRAMETIME_MS, lasers: [] }); + if (g.ents[self].client) checkDodge(g, self); + }; + Q.TOUCH.bfg_touch = (g, i, other, plane, sky) => { + const b = g.ents[i]; + if (other === b.owner) return; + if (sky) { Q.freeEdict(g, i); return; } + const o = g.ents[other]; + if (other > 0 && o.takedamage) Q.damage(g, other, i, b.owner, b.velocity, b.origin, plane || [0, 0, 0], 200, 0, 0, 'bfg_blast'); + Q.radiusDamage(g, i, b.owner, 200, other, 100, 'bfg_blast'); + b.solid = Q.SOLID_NOT; b.touch = null; + b.origin = ma(b.origin, -0.1, b.velocity); b.velocity = [0, 0, 0]; + b.effect = 'bfgexplode'; b.frame = 0; b.think = 'bfg_explode'; b.nextthink = g.ms + Q.FRAMETIME_MS; b.enemy = other; b.lasers = []; + Q.fx(g, 'bfgblast', b.origin); + }; + Q.THINK.bfg_explode = (g, i) => { + const b = g.ents[i]; + if (b.frame === 0) { + for (const k of Q.findradius(g, b.origin, b.dmg_radius)) { + const e = g.ents[k]; + if (!e.takedamage || k === b.owner) continue; + if (!Q.canDamage(g, k, i) || !Q.canDamage(g, k, b.owner)) continue; + const dist = len(sub(b.origin, Q.center(e))); + const points = b.radius_dmg * (1.0 - Math.sqrt(dist / b.dmg_radius)); + Q.damage(g, k, i, b.owner, b.velocity, e.origin, [0, 0, 0], Math.trunc(points), 0, Q.DAMAGE_ENERGY, 'bfg_effect'); + } + } + b.nextthink = g.ms + Q.FRAMETIME_MS; b.frame++; + if (b.frame === 5) b.think = 'G_FreeEdict'; + }; + Q.THINK.bfg_think = (g, i) => { + const b = g.ents[i], dmg = 10; + b.lasers = []; + for (const k of Q.findradius(g, b.origin, 256)) { + const e = g.ents[k]; + if (k === i || k === b.owner || !e.takedamage) continue; + if (!(e.svflags & Q.SVF_MONSTER) && !e.client) continue; + const point = Q.center(e), dir = norm(sub(point, b.origin)); + let ignore = i, start = copy3(b.origin), end = ma(start, 2048, dir), tr = null, guard = 0; + while (guard++ < 8) { + tr = Q.trace(g, start, null, null, end, ignore, Q.CONTENTS_SOLID | Q.CONTENTS_MONSTER | Q.CONTENTS_DEADMONSTER); + if (tr.fraction === 1 && tr.ent === 0) break; + const h = g.ents[tr.ent]; + if (tr.ent > 0 && h.takedamage && !(h.flags & Q.FL_IMMUNE_LASER) && tr.ent !== b.owner) Q.damage(g, tr.ent, i, b.owner, dir, tr.endpos, [0, 0, 0], dmg, 1, Q.DAMAGE_ENERGY, 'bfg_laser'); + if (tr.ent <= 0 || (!(h.svflags & Q.SVF_MONSTER) && !h.client)) break; + ignore = tr.ent; start = copy3(tr.endpos); + } + b.lasers.push(tr.endpos); + } + b.nextthink = g.ms + Q.FRAMETIME_MS; + }; + // SV_Physics_Toss for MOVETYPE_FLYMISSILE (no gravity), MOVETYPE_TOSS and MOVETYPE_BOUNCE (gibs, debris). + Q.physicsToss = (g, i) => { + Q.runThink(g, i); + let e = g.ents[i]; + if (!e.inuse) return; + if (e.velocity[2] > 0) e.groundentity = -1; + if (e.groundentity >= 0) return; + for (let k = 0; k < 3; k++) e.velocity[k] = Math.max(-Q.SV_MAXVELOCITY, Math.min(Q.SV_MAXVELOCITY, e.velocity[k])); + const ft = g.dt; // 60 Hz host frame (q2-arena@3) + if (e.movetype !== 'flymissile') e.velocity[2] -= e.gravity * Q.SV_GRAVITY * ft; + e.angles = add(e.angles, scale(e.avelocity, ft)); + const move = scale(e.velocity, ft); + const start = copy3(e.origin), end = add(start, move); + for (let retry = 0; retry < 2; retry++) { + const tr = Q.trace(g, start, e.mins, e.maxs, end, i, e.clipmask || Q.MASK_SOLID); + e.origin = copy3(tr.endpos); + if (tr.fraction !== 1.0) { + impact(g, i, tr); + if (!g.ents[i].inuse) return; + e = g.ents[i]; + if (tr.ent > 0 && !g.ents[tr.ent].inuse) { e.origin = copy3(start); continue; } + e.velocity = clipVelocity(e.velocity, tr.normal, e.movetype === 'bounce' ? 1.5 : 1); + if (tr.normal[2] > 0.7 && (e.velocity[2] < 60 || e.movetype !== 'bounce')) { e.groundentity = tr.ent; e.velocity = [0, 0, 0]; e.avelocity = [0, 0, 0]; } + } + break; + } + }; + // g_misc.c ThrowGib / ThrowHead / ThrowDebris: real edicts (they hold slots and draw the same rand() calls). + function velocityForDamage(g, damage) { + const v = [100.0 * Q.crandom(g), 100.0 * Q.crandom(g), 200.0 + 100.0 * Q.random(g)]; + return scale(v, damage < 50 ? 0.7 : 1.2); + } + const clipGibVelocity = v => [Math.max(-300, Math.min(300, v[0])), Math.max(-300, Math.min(300, v[1])), Math.max(200, Math.min(500, v[2]))]; + Q.throwGib = (g, self, kind, damage, organic) => { + const s = g.ents[self], size = scale(sub(s.maxs, s.mins), 0.5), base = add(Q.absmin(s), size); + const i = Q.spawn(g), e = g.ents[i]; + e.classname = 'gib'; e.gib = kind; + e.origin = [base[0] + Q.crandom(g) * size[0], base[1] + Q.crandom(g) * size[1], base[2] + Q.crandom(g) * size[2]]; + e.old_origin = copy3(e.origin); + Object.assign(e, { solid: Q.SOLID_NOT, flags: Q.FL_NO_KNOCKBACK, takedamage: Q.DAMAGE_YES, movetype: organic ? 'toss' : 'bounce', touch: organic ? 'gib_touch' : null }); + e.velocity = clipGibVelocity(ma(s.velocity, organic ? 0.5 : 1.0, velocityForDamage(g, damage))); + e.avelocity = [Q.random(g) * 600, Q.random(g) * 600, Q.random(g) * 600]; + e.think = 'G_FreeEdict'; e.nextthink = g.ms + 10000 + Q.random(g) * 10000; + }; + Q.throwHead = (g, self, kind, damage, organic) => { + const e = g.ents[self]; + Object.assign(e, { skinnum: 0, frame: 0, mins: [0, 0, 0], maxs: [0, 0, 0], solid: Q.SOLID_NOT, flags: e.flags | Q.FL_NO_KNOCKBACK, takedamage: Q.DAMAGE_YES, + movetype: organic ? 'toss' : 'bounce', touch: organic ? 'gib_touch' : null, classname: 'gib', gib: kind, head: true }); + e.svflags &= ~Q.SVF_MONSTER; + e.velocity = clipGibVelocity(ma(e.velocity, organic ? 0.5 : 1.0, velocityForDamage(g, damage))); + e.avelocity = [0, Q.crandom(g) * 600, 0]; + e.think = 'G_FreeEdict'; e.nextthink = g.ms + 10000 + Q.random(g) * 10000; + }; + Q.TOUCH.gib_touch = (g, i) => { const e = g.ents[i]; if (e.groundentity < 0) return; e.touch = null; }; + Q.throwDebris = (g, self, speed, origin) => { + const s = g.ents[self], i = Q.spawn(g), e = g.ents[i]; + const v = [100 * Q.crandom(g), 100 * Q.crandom(g), 100 + 100 * Q.crandom(g)]; + Object.assign(e, { classname: 'debris', origin: copy3(origin), old_origin: copy3(origin), velocity: ma(s.velocity, speed, v), movetype: 'bounce', solid: Q.SOLID_NOT, takedamage: Q.DAMAGE_YES }); + e.avelocity = [Q.random(g) * 600, Q.random(g) * 600, Q.random(g) * 600]; + e.think = 'G_FreeEdict'; e.nextthink = g.ms + 5000 + Q.random(g) * 5000; e.flags = 0; + }; + function impact(g, i, tr) { // SV_Impact + const e1 = g.ents[i], e2 = g.ents[tr.ent]; + if (e1.touch && e1.solid !== Q.SOLID_NOT) Q.TOUCH[e1.touch](g, i, tr.ent, tr.normal, tr.sky); + if (tr.ent > 0 && e2.inuse && e2.touch && e2.solid !== Q.SOLID_NOT && g.ents[i].inuse) Q.TOUCH[e2.touch](g, tr.ent, i, null, false); + } + Q.impact = impact; + + // ---------------- damage (g_combat.c) ---------------- + Q.canDamage = (g, targ, inflictor) => { + const t = g.ents[targ], from = g.ents[inflictor].origin; + const test = d => Q.trace(g, from, null, null, d, inflictor, Q.MASK_SOLID).fraction === 1.0; + if (test(t.origin)) return true; + for (const [dx, dy] of [[15, 15], [15, -15], [-15, 15], [-15, -15]]) if (test([t.origin[0] + dx, t.origin[1] + dy, t.origin[2]])) return true; + return false; + }; + function checkArmor(g, ent, damage, dflags) { + if (!damage || !ent.client || (dflags & Q.DAMAGE_NO_ARMOR)) return 0; + const a = Q.armorIndex(ent); + if (!a) return 0; + let save = Math.ceil(((dflags & Q.DAMAGE_ENERGY) ? ARMOR[a][3] : ARMOR[a][2]) * damage); + if (save >= ent.inv[a]) save = ent.inv[a]; + if (!save) return 0; + ent.inv[a] -= save; + return save; + } + Q.damage = (g, targ, inflictor, attacker, dir, point, normal, damage, knockback, dflags, mod) => { + const t = g.ents[targ]; + if (!t.takedamage) return; + if (g.skill === 0 && t.client) { damage = Math.trunc(damage * 0.5); if (!damage) damage = 1; } // easy mode takes half damage + dir = norm(dir); + const a = g.ents[attacker]; + if (!(dflags & Q.DAMAGE_RADIUS) && (t.svflags & Q.SVF_MONSTER) && a && a.client && t.enemy < 0 && t.health > 0) damage *= 2; + if (t.flags & Q.FL_NO_KNOCKBACK) knockback = 0; + if (!(dflags & Q.DAMAGE_NO_KNOCKBACK) && knockback && t.movetype !== 'none') { + const mass = t.mass < 50 ? 50 : t.mass; + const kvel = scale(dir, (t.client && attacker === targ ? 1600.0 : 500.0) * knockback / mass); + t.velocity = add(t.velocity, kvel); + } + let take = damage; + const asave = checkArmor(g, t, take, dflags); // no power armor, god mode or invulnerability in these arenas + take -= asave; + if (asave) Q.fx(g, 'spark', point, normal); + g.damageLog.push([targ, attacker, take, asave, mod]); + if (take) { + Q.fx(g, (t.svflags & Q.SVF_MONSTER) || t.client ? 'blood' : 'spark', point, normal); + t.health -= take; + if (t.health <= 0) { + if ((t.svflags & Q.SVF_MONSTER) || t.client) t.flags |= Q.FL_NO_KNOCKBACK; + killed(g, targ, inflictor, attacker, take, point); + return; + } + } + if (t.svflags & Q.SVF_MONSTER) { + Q.reactToDamage(g, targ, attacker); + // AI_DUCKED (the Mutant in mid-leap) suppresses the pain reaction + if (!(t.monsterinfo.aiflags & Q.AI_DUCKED) && take) { Q.monsterPain(g, targ, attacker, knockback, take); if (g.skill === 3) g.ents[targ].pain_debounce_time = g.ms + 5000; } + } + if (t.client) { t.damage_blood += take; t.damage_armor += asave; t.damage_knockback += knockback; t.damage_from = copy3(point); } + }; + function killed(g, targ, inflictor, attacker, damage, point) { + const t = g.ents[targ]; + if (t.health < -999) t.health = -999; + t.enemy = attacker; + if (t.client) { t.deadflag = Q.DEAD_DEAD; t.takedamage = Q.DAMAGE_NO; Q.event(g, 'player_die'); return; } + if ((t.svflags & Q.SVF_MONSTER) && t.deadflag !== Q.DEAD_DEAD) { t.touch = null; Q.monsterDeathUse(g, targ); } + Q.monsterDie(g, targ, inflictor, attacker, damage, point); + } + Q.radiusDamage = (g, inflictor, attacker, damage, ignore, radius, mod) => { + const inf = g.ents[inflictor]; + for (const k of Q.findradius(g, inf.origin, radius)) { + if (k === ignore) continue; + const e = g.ents[k]; + if (!e.takedamage) continue; + let points = damage - 0.5 * len(sub(inf.origin, Q.center(e))); + if (k === attacker) points *= 0.5; + if (points > 0 && Q.canDamage(g, k, inflictor)) { + const dir = sub(e.origin, inf.origin); + Q.damage(g, k, inflictor, attacker, dir, inf.origin, [0, 0, 0], Math.trunc(points), Math.trunc(points), Q.DAMAGE_RADIUS, mod); + } + } + }; + + // ---------------- items (Touch_Item) ---------------- + Q.spawnItem = (g, type, origin) => { + const i = Q.spawn(g), e = g.ents[i]; + Object.assign(e, { classname: type, item: type, origin: copy3(origin), mins: [-15, -15, -15], maxs: [15, 15, 15], solid: Q.SOLID_TRIGGER, touch: 'Touch_Item', movetype: 'toss', groundentity: 0 }); // droptofloor done + return i; + }; + const PICKUP = { + health: (p) => healthPickup(p, 10, false), health_large: (p) => healthPickup(p, 25, false), stimpack: (p) => healthPickup(p, 2, true), + armor_shard: (p) => { const a = Q.armorIndex(p); if (!a) p.inv.jacket = 2; else p.inv[a] += 2; return true; }, + armor_jacket: p => armorPickup(p, 'jacket'), armor_combat: p => armorPickup(p, 'combat'), armor_body: p => armorPickup(p, 'body'), + ammo_shells: p => ammoPickup(p, 'shells'), ammo_bullets: p => ammoPickup(p, 'bullets'), ammo_cells: p => ammoPickup(p, 'cells'), + ammo_rockets: p => ammoPickup(p, 'rockets'), ammo_slugs: p => ammoPickup(p, 'slugs'), + }; + Q.PICKUP = PICKUP; + function healthPickup(p, count, ignoreMax) { + if (!ignoreMax && p.health >= p.max_health) return false; + p.health += count; + if (!ignoreMax && p.health > p.max_health) p.health = p.max_health; + return true; + } + function armorPickup(p, kind) { // Pickup_Armor with salvage + const old = Q.armorIndex(p), info = ARMOR[kind]; + if (!old) { p.inv[kind] = info[0]; return true; } + const oldinfo = ARMOR[old]; + if (info[2] > oldinfo[2]) { + const salvagecount = Math.trunc((oldinfo[2] / info[2]) * p.inv[old]); + let newcount = info[0] + salvagecount; if (newcount > info[1]) newcount = info[1]; + p.inv[old] = 0; p.inv[kind] = newcount; + } else { + const salvagecount = Math.trunc((info[2] / oldinfo[2]) * info[0]); + let newcount = p.inv[old] + salvagecount; if (newcount > oldinfo[1]) newcount = oldinfo[1]; + if (p.inv[old] >= newcount) return false; + p.inv[old] = newcount; + } + return true; + } + function ammoPickup(p, ammo) { + if (p.inv[ammo] === AMMO_MAX[ammo]) return false; + p.inv[ammo] = Math.min(AMMO_MAX[ammo], (p.inv[ammo] || 0) + AMMO_PICKUP[ammo]); + return true; + } + // Touch_Item. Health and armor are single-player items: taken once, then freed (G_FreeEdict), never respawned + // (q2-arena@4, 2026-11-07: a respawning medkit lets a player stand and trade hits with the boss). Ammo keeps the + // deathmatch timer (SetRespawn 30 s, original DoRespawn) so a three-minute fight cannot run out of rounds; ammo + // heals nothing. q2-arena@1-3 also respawned health (30 s) and armor (20 s). + const RESPAWN = { ammo_shells: 30, ammo_bullets: 30, ammo_cells: 30, ammo_rockets: 30, ammo_slugs: 30 }; + Q.TOUCH.Touch_Item = (g, i, other) => { + const it = g.ents[i], p = g.ents[other]; + if (!p.client || p.health < 1) return; + if (!PICKUP[it.item](p)) return; + p.bonus_alpha = 0.25; p.pickup = it.item; p.pickup_time = g.ms + 3000; + Q.event(g, 'pickup', { item: it.item }); + if (!RESPAWN[it.item]) { Q.freeEdict(g, i); return; } + it.svflags |= Q.SVF_NOCLIENT; it.solid = Q.SOLID_NOT; it.nextthink = g.ms + RESPAWN[it.item] * 1000; it.think = 'DoRespawn'; + }; + Q.THINK.DoRespawn = (g, i) => { const it = g.ents[i]; it.svflags &= ~Q.SVF_NOCLIENT; it.solid = Q.SOLID_TRIGGER; Q.event(g, 'item_respawn', { item: it.item }); }; + + // ---------------- player trail (p_trail.c) ---------------- + Q.playerTrailInit = g => { g.trail = { head: 0, spots: Array.from({ length: 8 }, () => ({ origin: [0, 0, 0], timestamp: 0, yaw: 0 })) }; }; + Q.playerTrailAdd = (g, spot) => { + const tr = g.trail, prev = tr.spots[(tr.head - 1) & 7]; + tr.spots[tr.head] = { origin: copy3(spot), timestamp: g.ms, yaw: Q.vectoyaw(sub(spot, prev.origin)) }; + tr.head = (tr.head + 1) & 7; + }; + Q.trailLastSpot = g => g.trail.spots[(g.trail.head - 1) & 7]; + Q.trailPick = (g, self, first) => { + const tr = g.trail, mi = g.ents[self].monsterinfo; + let marker = tr.head; + for (let n = 8; n; n--) { if (tr.spots[marker].timestamp <= mi.trail_time) marker = (marker + 1) & 7; else break; } + if (!first) return tr.spots[marker]; + if (Q.visiblePoint(g, self, tr.spots[marker].origin)) return tr.spots[marker]; + const prev = tr.spots[(marker - 1) & 7]; + if (Q.visiblePoint(g, self, prev.origin)) return prev; + return tr.spots[marker]; + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/quake2_remake/renderer3d.js b/environments/games/web/games/quake2_remake/renderer3d.js new file mode 100644 index 0000000000000000000000000000000000000000..1e233d3c6cdbf1d8c7d1f02a60f3d702ae345b8e --- /dev/null +++ b/environments/games/web/games/quake2_remake/renderer3d.js @@ -0,0 +1,503 @@ +/* Quake II boss arenas - original procedural 3D art on Three.js r160 (MIT, shared read-only vendor copy in + web/games/_boss3d/vendor). First-person perspective from the player's eye with Quake II's 90 degree horizontal + field of view. Rendering is a pure function of the game state: it never writes the simulation and never draws + gameplay RNG; animation time comes from the state's tick counter. No Quake II models, skins or textures are used. */ +(function (root) { + 'use strict'; + const T = root.THREE, M = root.Quake2Game, Q = M && M.Q; + if (!T) throw Error('Three.js is missing (web/games/_boss3d/vendor/three.min.js)'); + const R = M.R3 = {}; + const S = 1 / 32; // one Quake II unit = 1/32 scene unit + const byCanvas = new WeakMap(); + const DEG = Math.PI / 180; + const qv = (x, y, z, out) => (out || new T.Vector3()).set(x * S, z * S, -y * S); // Quake (x fwd, y left, z up) -> three + function hash(x, y, s) { let n = Math.imul(x + 374761393 * s, 668265263) ^ Math.imul(y + s, 2246822519); n = Math.imul(n ^ (n >>> 13), 1274126177); return ((n ^ (n >>> 16)) >>> 0) / 4294967295; } + + // ---------------- procedural textures (deterministic, generated once per scene) ---------------- + function canvasTex(w, h, paint, opts = {}) { + const c = document.createElement('canvas'); c.width = w; c.height = h; + const q = c.getContext('2d'); paint(q, w, h); + const t = new T.CanvasTexture(c); t.colorSpace = T.SRGBColorSpace; t.wrapS = t.wrapT = T.RepeatWrapping; t.anisotropy = 2; + if (opts.nearest) { t.magFilter = T.NearestFilter; } + return t; + } + function noiseFill(q, w, h, base, amp, seed, grain = 1) { + const im = q.createImageData(w, h); + for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { + const n = (hash(Math.floor(x / grain), Math.floor(y / grain), seed) - 0.5) * amp + (hash(x >> 3, y >> 3, seed + 7) - 0.5) * amp * 0.6; + const i = (y * w + x) * 4; im.data[i] = base[0] + n; im.data[i + 1] = base[1] + n; im.data[i + 2] = base[2] + n * 0.9; im.data[i + 3] = 255; + } + q.putImageData(im, 0, 0); + } + const rivets = (q, xs, ys, col) => { q.fillStyle = col; for (const x of xs) for (const y of ys) { q.fillRect(x - 2, y - 2, 4, 4); } }; + const PAINT = { + floor(q, w, h) { noiseFill(q, w, h, [74, 70, 62], 26, 3); q.strokeStyle = '#2b2925'; q.lineWidth = 3; for (let k = 0; k <= w; k += 64) { q.beginPath(); q.moveTo(k, 0); q.lineTo(k, h); q.stroke(); q.beginPath(); q.moveTo(0, k); q.lineTo(w, k); q.stroke(); } + q.strokeStyle = '#5c584e'; q.lineWidth = 1; for (let k = 8; k < w; k += 16) { q.beginPath(); q.moveTo(k, 0); q.lineTo(k, h); q.stroke(); } rivets(q, [6, 58, 70, 122, 134, 186, 198, 250], [6, 58, 70, 122, 134, 186, 198, 250], '#8e8778'); }, + wall(q, w, h) { noiseFill(q, w, h, [96, 72, 52], 30, 11); q.fillStyle = '#3a2b20'; for (let y = 0; y < h; y += 64) q.fillRect(0, y, w, 5); q.fillStyle = '#6e5440'; + for (let x = 0; x < w; x += 128) q.fillRect(x + 60, 0, 8, h); rivets(q, [12, 116, 140, 244], [14, 50, 78, 114, 142, 178, 206, 242], '#b29470'); q.fillStyle = 'rgba(40,24,12,.35)'; q.fillRect(0, h - 40, w, 40); }, + crate(q, w, h) { noiseFill(q, w, h, [72, 82, 58], 22, 21); q.strokeStyle = '#3a4430'; q.lineWidth = 10; q.strokeRect(5, 5, w - 10, h - 10); q.lineWidth = 8; q.beginPath(); q.moveTo(10, 10); q.lineTo(w - 10, h - 10); q.moveTo(w - 10, 10); q.lineTo(10, h - 10); q.stroke(); + q.fillStyle = '#c9b34a'; q.font = 'bold 34px monospace'; q.fillText('S-7', w * 0.36, h * 0.56); }, + pylon(q, w, h) { noiseFill(q, w, h, [104, 100, 92], 24, 31); for (let x = -h; x < w; x += 40) { q.fillStyle = '#d9a722'; q.beginPath(); q.moveTo(x, h); q.lineTo(x + 20, h); q.lineTo(x + 60, h - 40); q.lineTo(x + 40, h - 40); q.fill(); } + q.fillStyle = '#2a2826'; q.fillRect(0, h - 44, w, 4); q.fillStyle = '#5b5852'; for (let y = 16; y < h - 50; y += 48) q.fillRect(0, y, w, 4); }, + tech(q, w, h) { noiseFill(q, w, h, [46, 52, 58], 18, 41); q.fillStyle = '#1a1f24'; q.fillRect(20, 30, w - 40, 90); q.fillRect(20, 150, w - 40, 70); + for (let k = 0; k < 9; k++) { q.fillStyle = k % 3 ? '#2fa36b' : '#7be0a8'; q.fillRect(30 + k * 22, 44 + (k * 37 % 50), 14, 8); } q.fillStyle = '#d9a722'; q.fillRect(0, 0, w, 8); }, + techGlow(q, w, h) { q.fillStyle = '#000'; q.fillRect(0, 0, w, h); for (let k = 0; k < 9; k++) { q.fillStyle = k % 3 ? '#1c7a4c' : '#5ce9a0'; q.fillRect(30 + k * 22, 44 + (k * 37 % 50), 14, 8); } q.fillStyle = '#123'; q.fillRect(20, 150, w - 40, 70); }, + hangar(q, w, h) { noiseFill(q, w, h, [78, 86, 94], 20, 51); q.fillStyle = '#2f353b'; for (let y = 0; y < h; y += 128) q.fillRect(0, y, w, 6); for (let x = 0; x < w; x += 128) q.fillRect(x, 0, 6, h); + q.fillStyle = '#c99a2a'; q.fillRect(0, h - 26, w, 10); rivets(q, [16, 112, 144, 240], [16, 112, 144, 240], '#a9b3bb'); }, + cargo(q, w, h) { noiseFill(q, w, h, [150, 78, 34], 22, 61); for (let x = 0; x < w; x += 16) { q.fillStyle = x % 32 ? 'rgba(0,0,0,.18)' : 'rgba(255,220,180,.08)'; q.fillRect(x, 0, 8, h); } + q.strokeStyle = '#4a2a14'; q.lineWidth = 8; q.strokeRect(4, 4, w - 8, h - 8); q.fillStyle = '#efe3c8'; q.font = 'bold 26px monospace'; q.fillText('CRG 4410', 40, 70); }, + strogg(q, w, h) { noiseFill(q, w, h, [104, 66, 58], 30, 71); q.fillStyle = '#3e2420'; for (let y = 24; y < h; y += 64) q.fillRect(0, y, w, 10); q.fillStyle = '#a06a58'; + for (let x = 16; x < w; x += 64) { q.fillRect(x, 0, 6, h); q.fillRect(x + 12, 0, 3, h); } rivets(q, [40, 104, 168, 232], [8, 72, 136, 200], '#b5806a'); }, + pillar(q, w, h) { noiseFill(q, w, h, [92, 80, 78], 24, 81); q.fillStyle = '#3a3032'; for (let x = 0; x < w; x += 64) q.fillRect(x, 0, 10, h); q.fillStyle = '#ff7a1a'; for (let y = 40; y < h; y += 96) q.fillRect(0, y, w, 6); }, + pillarGlow(q, w, h) { q.fillStyle = '#000'; q.fillRect(0, 0, w, h); q.fillStyle = '#ff6a10'; for (let y = 40; y < h; y += 96) q.fillRect(0, y, w, 6); }, + dais(q, w, h) { noiseFill(q, w, h, [66, 58, 56], 22, 91); q.strokeStyle = '#a3241a'; q.lineWidth = 6; q.beginPath(); q.arc(w / 2, h / 2, w * 0.4, 0, Math.PI * 2); q.stroke(); q.lineWidth = 3; q.beginPath(); q.arc(w / 2, h / 2, w * 0.28, 0, Math.PI * 2); q.stroke(); + for (let k = 0; k < 6; k++) { const a = k * Math.PI / 3; q.beginPath(); q.moveTo(w / 2 + Math.cos(a) * w * 0.28, h / 2 + Math.sin(a) * w * 0.28); q.lineTo(w / 2 + Math.cos(a) * w * 0.4, h / 2 + Math.sin(a) * w * 0.4); q.stroke(); } }, + roof(q, w, h) { noiseFill(q, w, h, [40, 40, 44], 16, 101); q.fillStyle = '#1b1b1e'; for (let k = 0; k < w; k += 128) { q.fillRect(k, 0, 8, h); q.fillRect(0, k, w, 8); } q.fillStyle = '#e8dcb0'; q.fillRect(48, 48, 32, 32); q.fillRect(176, 176, 32, 32); }, + roofGlow(q, w, h) { q.fillStyle = '#000'; q.fillRect(0, 0, w, h); q.fillStyle = '#c9b98a'; q.fillRect(48, 48, 32, 32); q.fillRect(176, 176, 32, 32); }, + metal(q, w, h) { noiseFill(q, w, h, [92, 92, 96], 22, 111); q.fillStyle = '#3c3c40'; q.fillRect(0, h / 2 - 3, w, 6); rivets(q, [10, w - 10], [10, h - 10], '#b8b8bc'); }, + factory(q, w, h) { noiseFill(q, w, h, [96, 92, 84], 24, 131); q.fillStyle = '#4a4640'; for (let y = 0; y < h; y += 64) q.fillRect(0, y, w, 6); + for (let x = 0; x < w; x += 128) { q.fillStyle = '#d9a722'; q.fillRect(x + 8, h - 30, 48, 10); q.fillStyle = '#2a2826'; q.fillRect(x + 56, h - 30, 48, 10); } rivets(q, [24, 104, 152, 232], [24, 88, 152, 216], '#c0b8a6'); }, + machine(q, w, h) { noiseFill(q, w, h, [70, 84, 92], 20, 141); q.fillStyle = '#1e262c'; q.fillRect(24, 24, w - 48, h - 48); q.fillStyle = '#ff8a2a'; + for (let k = 0; k < 6; k++) q.fillRect(40 + k * 30, 40, 18, 6); q.fillStyle = '#5ad0ff'; q.fillRect(40, h - 70, w - 80, 8); q.strokeStyle = '#9aa8b0'; q.lineWidth = 4; q.strokeRect(8, 8, w - 16, h - 16); }, + machineGlow(q, w, h) { q.fillStyle = '#000'; q.fillRect(0, 0, w, h); q.fillStyle = '#ff8a2a'; for (let k = 0; k < 6; k++) q.fillRect(40 + k * 30, 40, 18, 6); q.fillStyle = '#5ad0ff'; q.fillRect(40, h - 70, w - 80, 8); }, + arena(q, w, h) { noiseFill(q, w, h, [124, 104, 80], 26, 151); q.fillStyle = '#6a5440'; for (let y = 0; y < h; y += 48) { const o = (y / 48 % 2) * 64; for (let x = -64 + o; x < w; x += 128) q.fillRect(x, y, 4, 48); q.fillRect(0, y, w, 4); } }, + column(q, w, h) { noiseFill(q, w, h, [150, 138, 120], 20, 161); q.fillStyle = 'rgba(60,44,30,.35)'; for (let x = 0; x < w; x += 32) q.fillRect(x, 0, 8, h); q.fillStyle = '#7a3020'; q.fillRect(0, 16, w, 10); q.fillRect(0, h - 26, w, 10); }, + lab(q, w, h) { noiseFill(q, w, h, [176, 184, 176], 14, 171); q.fillStyle = '#7a8a86'; for (let y = 0; y < h; y += 64) q.fillRect(0, y, w, 3); for (let x = 0; x < w; x += 64) q.fillRect(x, 0, 3, h); + q.fillStyle = '#3a8a5a'; q.fillRect(0, h - 40, w, 14); q.fillStyle = '#d8d040'; for (let x = 0; x < w; x += 32) q.fillRect(x, h - 44, 16, 4); }, + bench(q, w, h) { noiseFill(q, w, h, [130, 140, 146], 16, 181); q.fillStyle = '#3c464c'; q.fillRect(0, 0, w, 10); q.fillStyle = '#60c890'; for (let k = 0; k < 4; k++) q.fillRect(20 + k * 56, 30, 34, 20); }, + flesh(q, w, h) { noiseFill(q, w, h, [120, 62, 58], 36, 121, 2); q.strokeStyle = 'rgba(60,20,20,.6)'; q.lineWidth = 3; for (let k = 0; k < 10; k++) { q.beginPath(); q.moveTo(hash(k, 1, 9) * w, 0); q.bezierCurveTo(hash(k, 2, 9) * w, h * 0.3, hash(k, 3, 9) * w, h * 0.7, hash(k, 4, 9) * w, h); q.stroke(); } }, + }; + + // Box geometry with world-scaled UVs (one texture tile = 128 Quake units) so walls never stretch. + function brushGeometry(b) { + const [x0, y0, z0] = b.mins, [x1, y1, z1] = b.maxs, pos = [], uv = [], nor = [], idx = []; + const face = (corners, n, ua, va) => { + const base = pos.length / 3; + for (const c of corners) { const p = qv(c[0], c[1], c[2]); pos.push(p.x, p.y, p.z); uv.push(c[ua] / 128, c[va] / 128); nor.push(n.x, n.y, n.z); } + idx.push(base, base + 1, base + 2, base, base + 2, base + 3); + }; + const N = (x, y, z) => qv(x / S, y / S, z / S).normalize(); + face([[x0, y0, z1], [x1, y0, z1], [x1, y1, z1], [x0, y1, z1]], N(0, 0, 1), 0, 1); // top + face([[x0, y1, z0], [x1, y1, z0], [x1, y0, z0], [x0, y0, z0]], N(0, 0, -1), 0, 1); // bottom + face([[x0, y0, z0], [x1, y0, z0], [x1, y0, z1], [x0, y0, z1]], N(0, -1, 0), 0, 2); // -y + face([[x1, y1, z0], [x0, y1, z0], [x0, y1, z1], [x1, y1, z1]], N(0, 1, 0), 0, 2); // +y + face([[x0, y1, z0], [x0, y0, z0], [x0, y0, z1], [x0, y1, z1]], N(-1, 0, 0), 1, 2); // -x + face([[x1, y0, z0], [x1, y1, z0], [x1, y1, z1], [x1, y0, z1]], N(1, 0, 0), 1, 2); // +x + const geo = new T.BufferGeometry(); + geo.setAttribute('position', new T.Float32BufferAttribute(pos, 3)); geo.setAttribute('uv', new T.Float32BufferAttribute(uv, 2)); + geo.setAttribute('normal', new T.Float32BufferAttribute(nor, 3)); geo.setIndex(idx); + // Inward faces of the arena shell are what the camera sees; render both sides. + return geo; + } + + // ---------------- the scene ---------------- + const ARENA_STYLE = { + supertank: { fog: 0x2c2420, near: 900, far: 3400, hemi: [0xffd2a6, 0x3a2a20, 1.35], sun: [0xffb070, 1.6, [-0.5, 1, 0.35]], sky: ['#1c1424', '#5a2e3a', '#d0773a'], lamps: [] }, + hornet: { fog: 0x161b20, near: 700, far: 3000, hemi: [0xb9cde0, 0x282624, 1.15], sun: null, sky: null, lamps: [[896, 900, 470, 0xfff2d2, 1.6, 2400], [300, 300, 300, 0xffb050, 1.0, 1200], [1500, 1500, 300, 0x9fd0ff, 1.0, 1200]] }, + makron: { fog: 0x2a1a16, near: 1100, far: 3600, hemi: [0xffd0c0, 0x4a3028, 2.3], sun: null, sky: null, lamps: [[960, 960, 420, 0xff7a4a, 2.4, 2600], [560, 560, 300, 0xff9a50, 1.4, 1300], [1360, 1360, 300, 0xff9a50, 1.4, 1300], [560, 1360, 300, 0xffc890, 1.2, 1300], [1360, 560, 300, 0xffc890, 1.2, 1300]] }, + tank_commander: { fog: 0x24201c, near: 1000, far: 3400, hemi: [0xffe2c0, 0x3a342c, 2.0], sun: null, sky: null, lamps: [[896, 896, 420, 0xffd8a0, 2.0, 2600], [480, 620, 300, 0xff9a40, 1.2, 1200], [1312, 620, 300, 0xff9a40, 1.2, 1200], [480, 1170, 300, 0x9ad0ff, 1.2, 1200], [1312, 1170, 300, 0x9ad0ff, 1.2, 1200]] }, + gladiator: { fog: 0x3a2a22, near: 1200, far: 3400, hemi: [0xffd8b0, 0x4a3426, 1.5], sun: [0xffb070, 1.6, [0.4, 1, -0.3]], sky: ['#241828', '#6a3a3a', '#e08a4a'], lamps: [] }, + mutant: { fog: 0x1e2624, near: 1100, far: 3400, hemi: [0xe0fff0, 0x2a3430, 1.9], sun: null, sky: null, lamps: [[960, 800, 360, 0xd8fff0, 2.0, 2400], [480, 400, 300, 0x8affc0, 1.0, 1200], [1440, 400, 300, 0x8affc0, 1.0, 1200], [480, 1200, 300, 0xfff0c0, 1.0, 1200], [1440, 1200, 300, 0xfff0c0, 1.0, 1200]] }, + }; + class Scene { + constructor(key, canvas) { + this.key = key; this.canvas = canvas; this.resources = []; this.times = []; this.ready = false; this.error = null; this.closed = false; + this.view = document.createElement('canvas'); this.view.width = 854; this.view.height = 480; + this.renderer = new T.WebGLRenderer({ canvas: this.view, antialias: true, preserveDrawingBuffer: true, powerPreference: 'low-power' }); + this.renderer.setPixelRatio(1); this.renderer.setSize(854, 480, false); this.renderer.outputColorSpace = T.SRGBColorSpace; + this.renderer.toneMapping = T.ACESFilmicToneMapping; this.renderer.toneMappingExposure = 1.15; this.renderer.autoClear = false; this.renderer.info.autoReset = false; + this.view.addEventListener('webglcontextlost', e => { e.preventDefault(); this.ready = false; this.error = 'WebGL context lost'; }); + const st = ARENA_STYLE[key]; + this.world = new T.Scene(); this.world.fog = new T.Fog(st.fog, st.near * S, st.far * S); + this.world.background = st.sky ? this.keep(canvasTex(8, 256, (q, w, h) => { const gr = q.createLinearGradient(0, 0, 0, h); gr.addColorStop(0, st.sky[0]); gr.addColorStop(0.55, st.sky[1]); gr.addColorStop(1, st.sky[2]); q.fillStyle = gr; q.fillRect(0, 0, w, h); })) : new T.Color(st.fog); + // Quake II fov 90 is horizontal: vertical = 2*atan(tan(45)*480/854) = 58.7 degrees. + this.camera = new T.PerspectiveCamera(2 * Math.atan(Math.tan(45 * DEG) * 480 / 854) / DEG, 854 / 480, 2 * S, 6000 * S); + this.world.add(new T.HemisphereLight(st.hemi[0], st.hemi[1], st.hemi[2])); + if (st.sun) { const sun = new T.DirectionalLight(st.sun[0], st.sun[1]); sun.position.set(st.sun[2][0], st.sun[2][1], st.sun[2][2]); this.world.add(sun); } + for (const [x, y, z, c, i, d] of st.lamps) { const l = new T.PointLight(c, i, d * S, 1.2); qv(x, y, z, l.position); this.world.add(l); } + this.flashLight = new T.PointLight(0xffc070, 0, 500 * S, 1.5); this.world.add(this.flashLight); + this.boomLight = new T.PointLight(0xff8a30, 0, 600 * S, 1.4); this.world.add(this.boomLight); + this.tex = {}; this.mat = {}; + const tex = name => this.tex[name] || (this.tex[name] = this.keep(canvasTex(256, 256, PAINT[name]))); + const lam = (name, color = 0xffffff, glow) => { const m = new T.MeshLambertMaterial({ map: tex(name), color, side: T.DoubleSide }); if (glow) { m.emissive = new T.Color(0xffffff); m.emissiveMap = tex(glow); m.emissiveIntensity = 1.3; } return this.keep(m); }; + this.mat.brush = { floor: lam('floor'), wall: lam('wall'), crate: lam('crate'), pylon: lam('pylon'), tech: lam('tech', 0xffffff, 'techGlow'), hangar: lam('hangar'), cargo: lam('cargo'), + strogg: lam('strogg'), pillar: lam('pillar', 0xffffff, 'pillarGlow'), dais: lam('dais'), roof: lam('roof', 0xffffff, 'roofGlow'), barrier: lam('pylon', 0xc8c4bc), + factory: lam('factory'), machine: lam('machine', 0xffffff, 'machineGlow'), arena: lam('arena'), column: lam('column'), lab: lam('lab'), bench: lam('bench') }; + for (const b of Q.worlds[key].brushes) { + if (b.sky) continue; + const mesh = new T.Mesh(this.keep(brushGeometry(b)), this.mat.brush[b.mat] || this.mat.brush.wall); + this.world.add(mesh); + } + this.buildShared(); this.buildBosses(); this.buildWeapons(); + } + keep(r) { this.resources.push(r); return r; } + std(color, opts = {}) { return this.keep(new T.MeshLambertMaterial(Object.assign({ color }, opts))); } + glow(color, opacity = 1) { return this.keep(new T.MeshBasicMaterial({ color, transparent: opacity < 1, opacity, depthWrite: opacity >= 1, blending: opacity < 1 ? T.AdditiveBlending : T.NormalBlending, fog: false })); } + buildShared() { + const G = this.geo = { + box: this.keep(new T.BoxGeometry(1, 1, 1)), sphere: this.keep(new T.SphereGeometry(1, 14, 10)), lowSphere: this.keep(new T.SphereGeometry(1, 8, 6)), + cyl: this.keep(new T.CylinderGeometry(1, 1, 1, 12)), cyl6: this.keep(new T.CylinderGeometry(1, 1, 1, 6)), cone: this.keep(new T.ConeGeometry(1, 1, 10)), + ico: this.keep(new T.IcosahedronGeometry(1, 0)), ring: this.keep(new T.TorusGeometry(1, 0.06, 6, 24)), plane: this.keep(new T.PlaneGeometry(1, 1)), + }; + const pool = (n, make) => { const out = []; for (let k = 0; k < n; k++) { const o = make(); o.visible = false; this.world.add(o); out.push(o); } return out; }; + this.mats = { + rocketBody: this.std(0x5b5f58), flame: this.glow(0xffa040, 0.9), smoke: this.keep(new T.MeshBasicMaterial({ color: 0x8a8580, transparent: true, opacity: 0.32, depthWrite: false })), + bolt: this.glow(0xffe060, 0.95), boltCore: this.glow(0xfff8d0), bfg: this.glow(0x5cff6a, 0.85), bfgCore: this.glow(0xe8ffe0), bfgHalo: this.keep(new T.MeshBasicMaterial({ color: 0x40ff60, transparent: true, opacity: 0.08, depthWrite: false, wireframe: true })), + boom: this.glow(0xff8a30, 0.8), boomCore: this.glow(0xfff0b0, 0.9), blood: this.keep(new T.MeshBasicMaterial({ color: 0x8a0d08, transparent: true, opacity: 0.8, depthWrite: false })), + puff: this.keep(new T.MeshBasicMaterial({ color: 0x9a948a, transparent: true, opacity: 0.6, depthWrite: false })), spark: this.glow(0xffd070, 0.9), + meat: this.std(0x7a1c16), gibMetal: this.std(0x6a6a70), debris: this.std(0x4a4440), mflash: this.glow(0xffd890, 0.95), warn: this.glow(0xff2a20, 0.65), + tracer: this.keep(new T.LineBasicMaterial({ color: 0xffe0a0, transparent: true, opacity: 0.55 })), railCore: this.keep(new T.LineBasicMaterial({ color: 0xe8f4ff, transparent: true, opacity: 0.9 })), + railSpiral: this.keep(new T.LineBasicMaterial({ color: 0x3a7cff, transparent: true, opacity: 0.9 })), laser: this.keep(new T.LineBasicMaterial({ color: 0x6aff70, transparent: true, opacity: 0.85 })), + aimLine: this.keep(new T.LineBasicMaterial({ color: 0xff3020, transparent: true, opacity: 0.85 })), + }; + this.rockets = pool(24, () => { const g = new T.Group(); const body = new T.Mesh(G.cyl, this.mats.rocketBody); body.scale.set(2.2 * S, 18 * S, 2.2 * S); body.rotation.z = Math.PI / 2; g.add(body); + const fl = new T.Mesh(G.cone, this.mats.flame); fl.scale.set(3.4 * S, 14 * S, 3.4 * S); fl.rotation.z = Math.PI / 2; fl.position.x = -15 * S; g.add(fl); + for (let k = 0; k < 4; k++) { const sm = new T.Mesh(G.lowSphere, this.mats.smoke); sm.position.x = -(28 + k * 16) * S; sm.scale.setScalar((4 + k * 2.2) * S); g.add(sm); } return g; }); + this.bolts = pool(48, () => { const g = new T.Group(); const a = new T.Mesh(G.sphere, this.mats.bolt); a.scale.set(16 * S, 3.2 * S, 3.2 * S); g.add(a); const c = new T.Mesh(G.sphere, this.mats.boltCore); c.scale.set(9 * S, 1.6 * S, 1.6 * S); g.add(c); return g; }); + this.bfgs = pool(4, () => { const g = new T.Group(); const a = new T.Mesh(G.sphere, this.mats.bfg); a.scale.setScalar(14 * S); g.add(a); const c = new T.Mesh(G.sphere, this.mats.bfgCore); c.scale.setScalar(7 * S); g.add(c); + const h = new T.Mesh(G.lowSphere, this.mats.bfgHalo); h.scale.setScalar(256 * S); g.add(h); return g; }); + this.booms = pool(24, () => { const g = new T.Group(); const a = new T.Mesh(G.ico, this.mats.boom); g.add(a); const c = new T.Mesh(G.sphere, this.mats.boomCore); c.scale.setScalar(0.5); g.add(c); return g; }); + this.puffs = pool(64, () => new T.Mesh(G.lowSphere, this.mats.puff)); + this.gibs = pool(40, () => new T.Mesh(G.ico, this.mats.meat)); + this.flashes = pool(12, () => new T.Mesh(G.sphere, this.mats.mflash)); + const lines = (n, mat, pts) => pool(n, () => { const geo = this.keep(new T.BufferGeometry()); geo.setAttribute('position', new T.BufferAttribute(new Float32Array(pts * 3), 3)); return new T.Line(geo, mat); }); + this.tracers = lines(40, this.mats.tracer, 2); this.railCores = lines(6, this.mats.railCore, 2); this.railSpirals = lines(6, this.mats.railSpiral, 96); + this.lasers = lines(12, this.mats.laser, 2); this.aimLines = lines(2, this.mats.aimLine, 2); + this.items = {}; + const itemMat = { health: this.std(0xe8e4dc), health_large: this.std(0xf2eee6), stimpack: this.std(0xd0f0ff), armor_shard: this.glow(0x4ae07a, 0.95), armor_jacket: this.std(0x6e7b4a), + armor_combat: this.std(0x8a8f96), armor_body: this.std(0xc0a246), ammo_shells: this.std(0xa0382a), ammo_bullets: this.std(0xb89a34), ammo_rockets: this.std(0x3c5a34), ammo_cells: this.std(0x3a6aa8), ammo_slugs: this.std(0x5a6a5a) }; + this.itemMat = itemMat; this.crossMat = this.glow(0xd01818); + } + // ---------------- boss models (original silhouettes after the Quake II designs) ---------------- + // Quake-local position (fwd, left, up) and sizes in units; rx rolls about forward, ry turns a vertical cylinder to + // point forward (three z), rz yaws about up. + part(parent, geo, mat, x, y, z, sx, sy, sz, rx = 0, ry = 0, rz = 0) { + const m = new T.Mesh(geo, mat); qv(x, y, z, m.position); m.scale.set(sx * S, sz * S, sy * S); m.rotation.set(rx, rz, ry); parent.add(m); return m; + } + group(parent, x = 0, y = 0, z = 0) { const g = new T.Group(); qv(x, y, z, g.position); parent.add(g); return g; } + buildBosses() { + const G = this.geo, P = this.part.bind(this); + const steel = this.std(0x9a9ea6), dark = this.std(0x4a4d52), rust = this.std(0xa06a44), olive = this.std(0x76844f), flesh = this.std(0xc07a62, { map: this.keep(canvasTex(128, 128, PAINT.flesh)) }); + const red = this.glow(0xff3010), amber = this.glow(0xffa030), green = this.glow(0x60ff70), cyan = this.glow(0x60c8ff), purple = this.std(0x7a5a88); + this.bossMats = { steel, dark, rust, olive, flesh, red, amber, green, cyan }; + this.models = {}; + // Super Tank (boss1): tracked base, armoured hull, chaingun arm on the right, triple rocket pod on the left. + { const root = new T.Group(), m = { root }; this.world.add(root); + for (const s of [1, -1]) { const tr = this.group(root, 0, s * 44, 0); P(tr, G.box, dark, 0, 0, 22, 132, 34, 44); for (let k = -2; k <= 2; k++) P(tr, G.cyl, steel, k * 26, 0, 18, 13, 13, 37, Math.PI / 2, 0, 0); m['tread' + (s > 0 ? 'L' : 'R')] = tr; } + const hull = this.group(root, 0, 0, 44); P(hull, G.box, olive, 0, 0, 16, 104, 80, 32); P(hull, G.box, steel, 46, 0, 10, 16, 70, 18); m.hull = hull; + const torso = this.group(hull, -6, 0, 32); P(torso, G.box, olive, 0, 0, 20, 66, 62, 40); P(torso, G.box, dark, 0, 0, 42, 40, 40, 8); P(torso, G.box, rust, 18, 0, 34, 20, 24, 18); + m.eye = P(torso, G.box, red, 29, 0, 36, 3, 14, 4); m.torso = torso; + const gun = this.group(torso, 30, -30, 12); P(gun, G.cyl, dark, 0, 0, 0, 16, 16, 30, 0, Math.PI / 2, 0); for (let k = 0; k < 6; k++) { const a = k * Math.PI / 3; P(gun, G.cyl6, steel, 26, Math.cos(a) * 4.5, Math.sin(a) * 4.5, 2.6, 2.6, 34, 0, Math.PI / 2, 0); } m.gun = gun; + const pod = this.group(torso, 12, 32, 18); P(pod, G.box, rust, 0, 0, 0, 30, 30, 22); for (let k = 0; k < 3; k++) P(pod, G.cyl, dark, 12, -10 + k * 10, 2, 6, 6, 20, 0, Math.PI / 2, 0); m.podGlow = P(pod, G.box, amber, 16, 0, 2, 2, 28, 10); m.pod = pod; + this.models.monster_supertank = m; } + // Hornet (boss2): flying insectoid gunship, two wing pairs, twin machinegun pods, rocket rack under the nose. + { const root = new T.Group(), m = { root }; this.world.add(root); + const body = this.group(root, 0, 0, 40); P(body, G.sphere, rust, 0, 0, 0, 62, 34, 24); P(body, G.sphere, flesh, -40, 0, -4, 46, 26, 22); P(body, G.sphere, dark, 34, 0, 4, 26, 22, 18); + m.eyes = [P(body, G.sphere, red, 52, 8, 8, 4, 4, 4), P(body, G.sphere, red, 52, -8, 8, 4, 4, 4)]; + for (const s of [1, -1]) { P(body, G.cyl, steel, 22, s * 40, 30, 7, 7, 34, 0, Math.PI / 2, 0); P(body, G.box, dark, 6, s * 30, 22, 24, 20, 10); } + for (let k = 0; k < 4; k++) P(body, G.cyl, dark, 22, [16, 8, -8, -16][k], -24, 4, 4, 22, 0, Math.PI / 2, 0); + m.wings = []; const wingMat = this.keep(new T.MeshLambertMaterial({ color: 0x9fb2a0, transparent: true, opacity: 0.55, side: T.DoubleSide })); + for (const s of [1, -1]) for (const f of [12, -18]) { const w = this.group(body, f, s * 22, 18); const blade = P(w, G.box, wingMat, 0, s * 44, 0, 34, 88, 1.5); m.wings.push({ w, s, f }); } + for (const s of [1, -1]) for (const f of [20, 0, -20]) P(body, G.cyl6, dark, f, s * 18, -26, 2.5, 2.5, 22, s * 0.4, 0, 0); + m.body = body; this.models.monster_boss2 = m; } + // Jorg (boss3 walker): huge bipedal mech with twin chainguns and the Makron rider on top. + { const root = new T.Group(), m = { root }; this.world.add(root); + m.legs = []; + for (const s of [1, -1]) { const hip = this.group(root, -6, s * 46, 78); const thigh = P(hip, G.box, steel, 0, 0, -18, 34, 30, 44); const knee = this.group(hip, 0, 0, -38); + P(knee, G.box, dark, 8, 0, -16, 30, 26, 40); const foot = P(knee, G.box, steel, 14, 0, -38, 56, 36, 10); m.legs.push({ hip, knee, s }); } + const body = this.group(root, 0, 0, 84); P(body, G.box, steel, 0, 0, 22, 112, 104, 44); P(body, G.box, dark, 0, 0, 48, 80, 72, 12); P(body, G.box, rust, 50, 0, 18, 18, 60, 30); + m.vents = P(body, G.box, amber, 58, 0, 24, 2, 40, 6); + for (const s of [1, -1]) { const arm = this.group(body, 40, s * 47, 12); P(arm, G.box, dark, 0, 0, 0, 40, 26, 30); for (let k = 0; k < 4; k++) { const a = k * Math.PI / 2 + 0.785; P(arm, G.cyl6, steel, 34, Math.cos(a) * 7, Math.sin(a) * 7, 4, 4, 44, 0, Math.PI / 2, 0); } m['arm' + (s > 0 ? 'L' : 'R')] = arm; } + m.bfg = P(body, G.sphere, green, 6, -9, 27, 9, 9, 9); + const rider = this.group(body, -10, 0, 54); P(rider, G.box, purple, 0, 0, 14, 22, 30, 30); P(rider, G.sphere, flesh, 0, 0, 36, 10, 10, 12); P(rider, G.box, dark, 6, 18, 18, 14, 10, 26); m.rider = rider; + m.body = body; this.models.monster_jorg = m; } + // Makron: armoured cyborg; railgun on the right arm, BFG / hyperblaster cannon on the left. + { const root = new T.Group(), m = { root }; this.world.add(root); + m.legs = []; + for (const s of [1, -1]) { const hip = this.group(root, 0, s * 12, 46); P(hip, G.box, dark, 0, 0, -10, 16, 14, 26); const knee = this.group(hip, 0, 0, -24); P(knee, G.box, steel, 2, 0, -10, 14, 12, 24); P(knee, G.box, dark, 6, 0, -22, 24, 16, 6); m.legs.push({ hip, knee, s }); } + const torso = this.group(root, 0, 0, 48); P(torso, G.box, purple, 0, 0, 14, 28, 38, 30); P(torso, G.box, steel, 2, 0, 30, 22, 30, 10); P(torso, G.sphere, flesh, 4, 0, 42, 9, 9, 11); m.eyes = P(torso, G.box, red, 12, 0, 43, 2, 10, 3); + const rail = this.group(torso, -6, -8, 24); P(rail, G.box, dark, 0, 0, 0, 22, 12, 12); P(rail, G.cyl, steel, 22, 0, 0, 5, 5, 34, 0, Math.PI / 2, 0); m.railGlow = P(rail, G.cyl, cyan, 22, 0, 0, 2.5, 2.5, 36, 0, Math.PI / 2, 0); m.rail = rail; + const cannon = this.group(torso, 8, 20, 14); P(cannon, G.box, rust, 0, 0, 0, 26, 14, 16); P(cannon, G.cyl, dark, 16, 0, 0, 9, 9, 16, 0, Math.PI / 2, 0); m.cannonGlow = P(cannon, G.sphere, green, 25, 0, 0, 6, 6, 6); m.cannon = cannon; + m.torso = torso; this.models.monster_makron = m; } + // Tank Commander: a heavy biped (box -32..32 x -16..72), blaster on the right forearm, chaingun on the left, a + // rocket pack on the shoulder; skin 2 is the commander's darker red plating. + { const root = new T.Group(), m = { root }; this.world.add(root); const plate = this.std(0x8a3a2c), plateD = this.std(0x5a2a22); + m.legs = []; + for (const s of [1, -1]) { const hip = this.group(root, 0, s * 16, 22); P(hip, G.box, plateD, 0, 0, -10, 22, 18, 26); const knee = this.group(hip, 0, 0, -22); P(knee, G.box, steel, 4, 0, -8, 18, 16, 20); P(knee, G.box, dark, 10, 0, -16, 34, 22, 8); m.legs.push({ hip, knee, s }); } + const torso = this.group(root, 0, 0, 26); P(torso, G.box, plate, 0, 0, 18, 46, 56, 38); P(torso, G.box, plateD, -8, 0, 40, 34, 44, 12); P(torso, G.sphere, flesh, 14, 0, 44, 8, 9, 9); m.eye = P(torso, G.box, red, 22, 0, 46, 2, 10, 3); + const mgArm = this.group(torso, 8, 34, 14); P(mgArm, G.box, dark, 0, 0, 0, 30, 14, 14); const mg = this.group(mgArm, 22, 0, 0); for (let k = 0; k < 6; k++) { const a = k * Math.PI / 3; P(mg, G.cyl6, steel, 14, Math.cos(a) * 3.5, Math.sin(a) * 3.5, 2.2, 2.2, 26, 0, Math.PI / 2, 0); } m.mg = mg; m.mgArm = mgArm; + const blast = this.group(torso, 10, -32, 12); P(blast, G.box, steel, 0, 0, 0, 34, 14, 14); m.blastGlow = P(blast, G.sphere, amber, 18, 0, 0, 5, 5, 5); + const pod = this.group(torso, -14, 20, 46); P(pod, G.box, plateD, 0, 0, 0, 24, 20, 18); for (let k = 0; k < 3; k++) P(pod, G.cyl, dark, 8, -6 + k * 6, 2, 3.5, 3.5, 14, 0, Math.PI / 2, 0); m.podGlow = P(pod, G.box, amber, 14, 0, 2, 2, 18, 8); m.pod = pod; + m.torso = torso; this.models.monster_tank_commander = m; } + // Gladiator: a lanky biped (box -32..32 x -24..64) with a cleaver on the right arm and a railgun on the left. + { const root = new T.Group(), m = { root }; this.world.add(root); const hide = this.std(0x8a7a5a), armour = this.std(0x5a6a74); + m.legs = []; + for (const s of [1, -1]) { const hip = this.group(root, 0, s * 12, 6); P(hip, G.box, armour, 0, 0, -14, 12, 12, 28); const knee = this.group(hip, 0, 0, -26); P(knee, G.box, dark, 4, 0, -2, 12, 10, 10); m.legs.push({ hip, knee, s }); } + const torso = this.group(root, 0, 0, 8); P(torso, G.box, hide, 0, 0, 22, 26, 34, 34); P(torso, G.box, armour, 4, 0, 34, 22, 40, 12); P(torso, G.sphere, flesh, 6, 0, 48, 8, 8, 10); P(torso, G.box, red, 13, 0, 50, 2, 8, 2); + const cleaver = this.group(torso, 6, -26, 30); P(cleaver, G.box, armour, 0, 0, -8, 10, 10, 22); P(cleaver, G.box, steel, 14, 0, -18, 30, 3, 18); m.cleaver = cleaver; + const rail = this.group(torso, 8, 24, 26); P(rail, G.box, dark, 0, 0, 0, 22, 10, 10); P(rail, G.cyl, steel, 18, 0, 0, 3.5, 3.5, 26, 0, Math.PI / 2, 0); m.railGlow = P(rail, G.cyl, cyan, 18, 0, 0, 2.5, 2.5, 28, 0, Math.PI / 2, 0); + m.torso = torso; this.models.monster_gladiator = m; } + // Mutant: a hunched quadruped-ish brute (box -32..32 x -24..48), long clawed arms, no weapon. + { const root = new T.Group(), m = { root }; this.world.add(root); const skin = this.std(0xd8a882), bone = this.std(0xf4ead0); + m.legs = []; + for (const s of [1, -1]) { const hip = this.group(root, -10, s * 16, -2); P(hip, G.box, skin, 0, 0, -10, 14, 14, 24); P(hip, G.box, bone, 6, 0, -22, 18, 12, 4); m.legs.push({ hip, s }); } + const body = this.group(root, 0, 0, 4); P(body, G.sphere, skin, 0, 0, 18, 30, 26, 20); P(body, G.sphere, skin, 18, 0, 30, 16, 16, 14); P(body, G.sphere, flesh, 30, 0, 34, 9, 10, 9); P(body, G.box, red, 38, 4, 36, 2, 3, 2); P(body, G.box, red, 38, -4, 36, 2, 3, 2); + for (let k = 0; k < 5; k++) P(body, G.cone, bone, -10 + k * 7, 0, 36 - k * 1.5, 3, 3, 8); + for (const s of [1, -1]) { const arm = this.group(body, 16, s * 24, 28); P(arm, G.box, skin, 6, 0, -12, 10, 10, 28); for (let k = -1; k <= 1; k++) P(arm, G.cone, bone, 12, k * 3, -28, 2, 2, 10, Math.PI, 0, 0); m[s > 0 ? 'armL' : 'armR'] = arm; } + m.body = body; this.models.monster_mutant = m; } + for (const m of Object.values(this.models)) m.root.visible = false; + } + buildWeapons() { // first-person view models, drawn in their own pass over the world + this.vscene = new T.Scene(); this.vcam = new T.PerspectiveCamera(52, 854 / 480, 0.01, 10); + this.vscene.add(new T.HemisphereLight(0xfff0e0, 0x302820, 1.5)); const key = new T.DirectionalLight(0xffffff, 1.2); key.position.set(-0.4, 1, 0.6); this.vscene.add(key); + const G = this.geo, dark = this.std(0x2a2b2e), steel = this.std(0x7a7d82), brass = this.std(0x9a7a3a), wood = this.std(0x5a3c24), blue = this.glow(0x6ab8ff), orange = this.glow(0xffa040); + const box = (g, x, y, z, sx, sy, sz, m) => { const o = new T.Mesh(G.box, m); o.position.set(x, y, z); o.scale.set(sx, sy, sz); g.add(o); return o; }; + const tube = (g, x, y, z, r, l, m) => { const o = new T.Mesh(G.cyl, m); o.position.set(x, y, z); o.scale.set(r, l, r); o.rotation.x = Math.PI / 2; g.add(o); return o; }; + const W = this.vweapons = {}; + const mk = (name, build) => { const g = new T.Group(), inner = new T.Group(); build(inner); inner.scale.setScalar(0.62); g.add(inner); g.userData.spin = inner.userData.spin; g.visible = false; this.vscene.add(g); W[name] = g; }; + mk('blaster', g => { box(g, 0, 0, 0, 0.07, 0.09, 0.26, dark); tube(g, 0, 0.02, -0.17, 0.022, 0.12, steel); box(g, 0, -0.08, 0.06, 0.05, 0.12, 0.07, wood); box(g, 0, 0.055, -0.02, 0.03, 0.02, 0.12, orange); }); + mk('shotgun', g => { tube(g, 0, 0.02, -0.12, 0.022, 0.5, steel); box(g, 0, -0.01, 0.1, 0.06, 0.07, 0.24, wood); box(g, 0, -0.025, -0.12, 0.05, 0.035, 0.18, wood); }); + mk('supershotgun', g => { tube(g, -0.022, 0.02, -0.12, 0.022, 0.5, steel); tube(g, 0.022, 0.02, -0.12, 0.022, 0.5, steel); box(g, 0, -0.01, 0.12, 0.08, 0.08, 0.22, wood); }); + mk('machinegun', g => { box(g, 0, 0, 0, 0.07, 0.08, 0.34, dark); tube(g, 0, 0.01, -0.24, 0.018, 0.16, steel); box(g, 0, -0.09, -0.02, 0.04, 0.12, 0.05, brass); }); + mk('chaingun', g => { const spin = new T.Group(); for (let k = 0; k < 6; k++) { const a = k * Math.PI / 3; tube(spin, Math.cos(a) * 0.035, Math.sin(a) * 0.035, -0.18, 0.012, 0.42, steel); } g.add(spin); g.userData.spin = spin; box(g, 0, -0.02, 0.1, 0.12, 0.12, 0.2, dark); }); + mk('rocketlauncher', g => { tube(g, 0, 0.03, -0.08, 0.055, 0.6, this.std(0x44523a)); box(g, 0, -0.06, 0.08, 0.06, 0.1, 0.12, dark); tube(g, 0, 0.03, -0.39, 0.06, 0.03, steel); }); + mk('hyperblaster', g => { const spin = new T.Group(); for (let k = 0; k < 4; k++) { const a = k * Math.PI / 2; tube(spin, Math.cos(a) * 0.03, Math.sin(a) * 0.03, -0.2, 0.012, 0.38, steel); } g.add(spin); g.userData.spin = spin; box(g, 0, -0.03, 0.08, 0.1, 0.1, 0.2, dark); box(g, 0, 0.06, 0.06, 0.04, 0.02, 0.16, orange); }); + mk('railgun', g => { box(g, 0, 0, -0.06, 0.07, 0.07, 0.6, dark); tube(g, 0, 0.0, -0.06, 0.03, 0.62, blue); box(g, 0, -0.07, 0.12, 0.05, 0.1, 0.1, steel); }); + this.vflash = new T.Mesh(G.sphere, this.glow(0xffd890, 0.9)); this.vflash.scale.setScalar(0.045); this.vflash.visible = false; this.vscene.add(this.vflash); + } + // ---------------- per-frame update ---------------- + render(g, ctx) { + if (this.closed || this.renderer.getContext().isContextLost()) { this.ready = false; this.error = this.closed ? '3D renderer is closed' : 'WebGL context lost'; throw Error(this.error); } + const t0 = performance.now(); + try { + const p = g.ents[1], time = g.ms / 1000; + const eye = [p.origin[0], p.origin[1], p.origin[2] + (p.viewheight || 22)]; + const ang = p.health > 0 ? p.v_angle : [-15, p.v_angle[1], 40]; + qv(eye[0], eye[1], eye[2] - (p.health > 0 ? 0 : 16), this.camera.position); + const cp = Math.cos(ang[0] * DEG), sp = Math.sin(ang[0] * DEG), cy = Math.cos(ang[1] * DEG), sy = Math.sin(ang[1] * DEG); + const look = qv(eye[0] + cp * cy * 100, eye[1] + cp * sy * 100, eye[2] - sp * 100); + this.camera.up.set(0, 1, 0); this.camera.lookAt(look); + this.camera.rotateZ(-(ang[2] || 0) * DEG); + this.updateBosses(g, time); this.updateMissiles(g, time); this.updateFx(g, time); this.updateItems(g, time); + this.renderer.info.reset(); this.renderer.clear(); this.renderer.render(this.world, this.camera); + this.updateViewWeapon(g, p, time); + this.renderer.clearDepth(); this.renderer.render(this.vscene, this.vcam); + ctx.drawImage(this.view, 0, 0, 854, 480); + this.times.push(performance.now() - t0); if (this.times.length > 120) this.times.shift(); + this.ready = true; this.error = null; + } catch (e) { this.ready = false; this.error = String(e && e.stack || e); throw e; } + } + updateBosses(g, time) { + for (const m of Object.values(this.models)) m.root.visible = false; + for (let i = 2; i < g.ents.length; i++) { + const e = g.ents[i]; + if (!e.inuse || !this.models[e.classname] || e.gibbed) continue; + const m = this.models[e.classname], def = Q.MONSTERS[e.classname], mi = e.monsterinfo || {}, mv = def.moves[mi.currentmove] || def.moves.stand; + const f = Math.max(0, e.frame - mv.first), n = mv.last - mv.first + 1, ph = f / n, move = mi.currentmove || 'stand'; + // A monster moves its ai_run distance on its 100 ms think; the original client spreads that step over the next + // server frame (cl_ents.c lerpfrac). The state keeps the step as e.lerp, read-only here. + const lf = e.lerp ? Math.max(0, 1 - (g.ms - e.lerp[3]) / Q.FRAMETIME_MS) : 0, lo = lf ? e.lerp : [0, 0, 0]; + m.root.visible = true; qv(e.origin[0] + lo[0] * lf, e.origin[1] + lo[1] * lf, e.origin[2] + lo[2] * lf, m.root.position); m.root.rotation.set(0, e.angles[1] * DEG, 0); + const dying = e.deadflag === Q.DEAD_DEAD, hurt = e.skinnum === 1; + if (e.classname === 'monster_supertank') { + const walk = move === 'run' || move === 'forward'; + m.treadL.position.y = (walk ? Math.sin(ph * Math.PI * 4) * 1.2 : 0) * S; m.treadR.position.y = (walk ? -Math.sin(ph * Math.PI * 4) * 1.2 : 0) * S; + m.torso.rotation.y = move.startsWith('pain') ? Math.sin(ph * Math.PI) * 0.18 : 0; + m.gun.rotation.x = move === 'attack1' ? time * 9 : 0; + const charging = move === 'attack2' && e.frame >= 20 && e.frame < 34; + m.pod.rotation.z = charging ? -0.25 : 0; m.podGlow.visible = charging; m.podGlow.material.opacity = 1; + m.hull.rotation.z = dying ? Math.min(1, ph * 1.3) * 0.3 : 0; m.root.position.y -= dying ? ph * 22 * S : 0; + m.eye.visible = !dying; + } else if (e.classname === 'monster_boss2') { + for (const w of m.wings) w.w.rotation.x = w.s * (Math.sin(time * 38 + w.f) * 0.5 + 0.2); + const pitch = move === 'attack_rocket' ? -0.12 : move.startsWith('pain') ? Math.sin(ph * Math.PI) * 0.3 : 0; + m.body.rotation.z = pitch + (dying ? -ph * 0.8 : 0); m.body.rotation.x = Math.sin(time * 2.1) * 0.05 + (dying ? ph * 0.6 : 0); + m.body.position.y = (40 + Math.sin(time * 3) * 2) * S; + } else if (e.classname === 'monster_jorg') { + const walk = move === 'run' || move === 'walk'; + for (const L of m.legs) { const a = walk ? Math.sin(ph * Math.PI * 2 + (L.s > 0 ? 0 : Math.PI)) : 0; L.hip.rotation.z = a * 0.35; L.knee.rotation.z = -Math.max(0, a) * 0.5; } + const fire = move === 'attack1' || move === 'start_attack1'; + m.armL.rotation.x = fire ? time * 6 : 0; m.armR.rotation.x = fire ? -time * 6 : 0; + m.bfg.visible = !dying; m.bfg.scale.setScalar((move === 'attack2' && e.frame < 25 ? 9 + (e.frame - 18) * 1.6 : 6) * S); + m.body.rotation.z = move.startsWith('pain') ? Math.sin(ph * Math.PI) * 0.12 : dying ? Math.min(1, ph * 1.2) * 0.35 : 0; + m.root.position.y -= dying ? Math.max(0, ph - 0.5) * 50 * S : 0; + m.rider.visible = !(dying && e.frame >= 79); + } else if (e.classname === 'monster_makron') { + const walk = move === 'run' || move === 'walk'; + for (const L of m.legs) { const a = walk ? Math.sin(ph * Math.PI * 2 + (L.s > 0 ? 0 : Math.PI)) : 0; L.hip.rotation.z = a * 0.5; L.knee.rotation.z = -Math.max(0, a) * 0.6; } + const railCharge = move === 'attack5' && e.frame <= 243, sweep = move === 'attack4' && e.frame >= 213 && e.frame <= 229, bfgCharge = move === 'attack3' && e.frame <= 204; + m.railGlow.visible = railCharge; m.railGlow.scale.set(2.5 * S * (1 + (e.frame - 235) * 0.12), 36 * S, 2.5 * S * (1 + (e.frame - 235) * 0.12)); + m.rail.rotation.z = railCharge ? 0.1 : 0; + m.cannon.rotation.y = sweep ? (e.frame <= 221 ? -(221 - e.frame) * 10 : (229 - e.frame) * 10) * DEG : 0; + m.cannonGlow.visible = bfgCharge || sweep; m.cannonGlow.scale.setScalar((bfgCharge ? 6 + (e.frame - 201) * 2 : 4) * S); + m.torso.rotation.z = move === 'sight' ? Math.sin(ph * Math.PI) * -0.2 : move.startsWith('pain') ? Math.sin(ph * Math.PI) * 0.25 : dying ? Math.min(1, ph * 1.4) * 1.2 : 0; + m.root.position.y -= dying ? Math.max(0, ph - 0.6) * 40 * S : 0; + } else if (e.classname === 'monster_tank_commander') { + const walk = move === 'run' || move === 'start_run' || move === 'walk'; + for (const L of m.legs) { const a = walk ? Math.sin(ph * Math.PI * 2 + (L.s > 0 ? 0 : Math.PI)) : 0; L.hip.rotation.z = a * 0.4; L.knee.rotation.z = -Math.max(0, a) * 0.5; } + m.mg.rotation.x = move === 'attack_chain' ? time * 12 : 0; + m.mgArm.rotation.y = move === 'attack_chain' && e.frame >= 173 && e.frame <= 191 ? (e.frame <= 182 ? -(e.frame - 178) * 8 : (e.frame - 186) * 8) * DEG : 0; + m.blastGlow.visible = move === 'attack_blast' || move === 'reattack_blast'; + const pre = move === 'attack_pre_rocket' || move === 'attack_fire_rocket'; m.podGlow.visible = pre; m.pod.rotation.z = pre ? -0.3 : 0; + m.torso.rotation.z = move.startsWith('pain') ? Math.sin(ph * Math.PI) * 0.2 : dying ? Math.min(1, ph * 1.3) * 0.9 : 0; + m.root.position.y -= dying ? Math.max(0, ph - 0.5) * 30 * S : 0; + } else if (e.classname === 'monster_gladiator') { + const walk = move === 'run' || move === 'walk'; + for (const L of m.legs) { const a = walk ? Math.sin(ph * Math.PI * 2 + (L.s > 0 ? 0 : Math.PI)) : 0; L.hip.rotation.z = a * 0.6; L.knee.rotation.z = -Math.max(0, a) * 0.7; } + const swing = move === 'attack_melee', railing = move === 'attack_gun' && e.frame <= 49; + m.cleaver.rotation.z = swing ? Math.sin(ph * Math.PI * 4) * 1.1 : 0.2; + const charge = 1 + Math.max(0, Math.min(3, e.frame - 46)) * 0.35; m.railGlow.visible = railing; m.railGlow.scale.set(2.5 * S * charge, 30 * S, 2.5 * S * charge); + m.torso.rotation.z = move.startsWith('pain') ? Math.sin(ph * Math.PI) * 0.3 : dying ? Math.min(1, ph * 1.4) * 1.3 : 0; + m.root.position.y -= dying ? Math.max(0, ph - 0.6) * 40 * S : 0; + } else if (e.classname === 'monster_mutant') { + const walk = move === 'run' || move === 'walk' || move === 'start_walk'; + for (const L of m.legs) { const a = walk ? Math.sin(ph * Math.PI * 2 + (L.s > 0 ? 0 : Math.PI)) : 0; L.hip.rotation.z = a * 0.7; } + const claw = move === 'attack', leap = move === 'jump'; + m.armL.rotation.z = claw ? Math.sin(ph * Math.PI * 2) * 1.2 : leap ? -1.2 : 0.3; m.armR.rotation.z = claw ? -Math.sin(ph * Math.PI * 2 + 1) * 1.2 : leap ? -1.2 : 0.3; + m.body.rotation.z = leap ? -0.5 : move.startsWith('pain') ? Math.sin(ph * Math.PI) * 0.4 : dying ? Math.min(1, ph * 1.5) * 1.4 : 0; + m.root.position.y -= dying ? Math.max(0, ph - 0.5) * 30 * S : 0; + } + for (const mat of [this.bossMats.red]) mat.color.setHex(hurt ? 0xff8040 : 0xff3010); + } + // Railgun aim lines once the target point is locked (Makron: MakronSaveloc on frame 242, fires on 243; Gladiator: + // gladiator_attack saves pos1 in the tick it picks attack_gun, still on the previous move's frame, and fires on frame + // 49, four ticks later). The line is the exact shot line. + for (const l of this.aimLines) l.visible = false; + let ai = 0; + for (let i = 2; i < g.ents.length && ai < this.aimLines.length; i++) { + const e = g.ents[i]; + if (!e.inuse || e.deadflag || !e.monsterinfo) continue; + let ofs = null; + if (e.classname === 'monster_makron' && e.monsterinfo.currentmove === 'attack5' && e.frame === 242) ofs = [-17.3, 7.8, 72.4]; + else if (e.classname === 'monster_gladiator' && e.monsterinfo.currentmove === 'attack_gun' && e.frame <= 48) ofs = [30.0, 18.0, 28.0]; + if (!ofs) continue; + const av = Q.angleVectors(e.angles), start = Q.projectSource(e.origin, ofs, av.forward, av.right), dir = Q.norm(Q.sub(e.pos1, start)), end = Q.ma(start, 2400, dir); + this.setLine(this.aimLines[ai++], start, end); + } + } + setLine(line, a, b) { + const arr = line.geometry.attributes.position.array, A = qv(a[0], a[1], a[2]), Bv = qv(b[0], b[1], b[2]); + arr[0] = A.x; arr[1] = A.y; arr[2] = A.z; arr[3] = Bv.x; arr[4] = Bv.y; arr[5] = Bv.z; + line.geometry.attributes.position.needsUpdate = true; line.geometry.computeBoundingSphere(); line.visible = true; + } + orient(obj, origin, vel) { + qv(origin[0], origin[1], origin[2], obj.position); + const yaw = Math.atan2(vel[1], vel[0]), pitch = Math.atan2(vel[2], Math.hypot(vel[0], vel[1])); + obj.rotation.set(0, yaw, pitch, 'YZX'); + } + updateMissiles(g, time) { + let r = 0, b = 0, f = 0, l = 0; + for (const o of [...this.rockets, ...this.bolts, ...this.bfgs, ...this.lasers]) o.visible = false; + for (let i = 2; i < g.ents.length; i++) { + const e = g.ents[i]; + if (!e.inuse) continue; + if (e.classname === 'rocket' && r < this.rockets.length) { const o = this.rockets[r++]; this.orient(o, e.origin, e.velocity); o.visible = true; } + else if (e.classname === 'bolt' && b < this.bolts.length) { const o = this.bolts[b++]; this.orient(o, e.origin, e.velocity); o.visible = true; } + else if (e.classname === 'bfg blast' && f < this.bfgs.length) { + const o = this.bfgs[f++]; qv(e.origin[0], e.origin[1], e.origin[2], o.position); o.visible = true; + const exploding = e.think === 'bfg_explode' || e.effect === 'bfgexplode'; + o.children[0].scale.setScalar((exploding ? 40 + (e.frame || 0) * 30 : 14 + Math.sin(time * 20) * 2) * S); o.children[2].visible = !exploding; + for (const end of e.lasers || []) if (l < this.lasers.length) this.setLine(this.lasers[l++], e.origin, end); + } + } + } + updateFx(g, time) { + let bo = 0, pu = 0, tr = 0, rc = 0, gi = 0, fl = 0; + for (const o of [...this.booms, ...this.puffs, ...this.tracers, ...this.railCores, ...this.railSpirals, ...this.gibs, ...this.flashes]) o.visible = false; + let flash = 0, boom = 0, flashPos = null, boomPos = null; + for (const fx of g.fx) { + const age = (g.ms - fx.t0) / fx.life; + if (age < 0 || age > 1) continue; + if (fx.kind === 'explosion' && bo < this.booms.length) { + const o = this.booms[bo++], s = (fx.big ? 70 : 48) * (0.35 + age * 0.8); + qv(fx.o[0], fx.o[1], fx.o[2], o.position); o.scale.setScalar(s * S); o.rotation.set(fx.id, fx.id * 1.3, 0); o.visible = true; + o.children[0].material.opacity = 0.85 * (1 - age); if (1 - age > boom) { boom = 1 - age; boomPos = fx.o; } + } else if ((fx.kind === 'blood' || fx.kind === 'puff' || fx.kind === 'spark' || fx.kind === 'blasterhit') && pu < this.puffs.length) { + const o = this.puffs[pu++]; qv(fx.o[0], fx.o[1], fx.o[2] + age * 10, o.position); o.scale.setScalar((fx.kind === 'blood' ? 5 : 3.5) * (1 + age) * S); + o.material = fx.kind === 'blood' ? this.mats.blood : fx.kind === 'puff' ? this.mats.puff : this.mats.spark; o.visible = true; + } else if (fx.kind === 'tracer' && fx.from === 'monster' && tr < this.tracers.length) { + this.setLine(this.tracers[tr++], fx.o, fx.to); + } else if (fx.kind === 'rail' && rc < this.railCores.length) { + this.setLine(this.railCores[rc], fx.o, fx.to); + const sp = this.railSpirals[rc++], arr = sp.geometry.attributes.position.array, d = Q.sub(fx.to, fx.o), L = Q.len(d), dir = Q.norm(d); + const side = Q.norm(Q.cross(dir, Math.abs(dir[2]) < 0.9 ? [0, 0, 1] : [1, 0, 0])), up = Q.cross(side, dir), n = arr.length / 3, v = new T.Vector3(); + for (let k = 0; k < n; k++) { const t = k / (n - 1), a = t * L / 18, rr = 5 + age * 6, p = Q.ma(Q.ma(Q.ma(fx.o, t * L, dir), Math.cos(a) * rr, side), Math.sin(a) * rr, up); qv(p[0], p[1], p[2], v); arr[k * 3] = v.x; arr[k * 3 + 1] = v.y; arr[k * 3 + 2] = v.z; } + sp.geometry.attributes.position.needsUpdate = true; sp.geometry.computeBoundingSphere(); sp.visible = true; + sp.material.opacity = 0.9 * (1 - age); this.railCores[rc - 1].material.opacity = 0.9 * (1 - age); + } else if (fx.kind === 'mflash' && fl < this.flashes.length) { + const o = this.flashes[fl++]; qv(fx.o[0], fx.o[1], fx.o[2], o.position); o.scale.setScalar((fx.weapon === 'bfg' ? 14 : fx.weapon === 'rocket' ? 9 : 6) * S); o.visible = true; + flash = 1; flashPos = fx.o; + } else if (fx.kind === 'railcharge' && fl < this.flashes.length) { + const e = g.ents[fx.owner]; if (!e || !e.inuse) continue; + } + } + for (let i = 2; i < g.ents.length && gi < this.gibs.length; i++) { + const e = g.ents[i]; + if (!e.inuse || (e.classname !== 'gib' && e.classname !== 'debris')) continue; + const o = this.gibs[gi++]; qv(e.origin[0], e.origin[1], e.origin[2], o.position); o.rotation.set(e.angles[0] * DEG, e.angles[1] * DEG, e.angles[2] * DEG); + o.scale.setScalar((e.classname === 'debris' ? 3 : e.head ? 9 : e.gib === 'chest' ? 8 : 5) * S); + o.material = e.classname === 'debris' ? this.mats.debris : e.gib === 'metal' || e.gib === 'gear' ? this.mats.gibMetal : this.mats.meat; o.visible = true; + } + this.flashLight.intensity = flash ? 2.2 : 0; if (flashPos) qv(flashPos[0], flashPos[1], flashPos[2], this.flashLight.position); + this.boomLight.intensity = boom * 3.2; if (boomPos) qv(boomPos[0], boomPos[1], boomPos[2] + 24, this.boomLight.position); + } + updateItems(g, time) { + const seen = new Set(); + for (let i = 2; i < g.ents.length; i++) { + const e = g.ents[i]; + if (!e.inuse || e.solid !== Q.SOLID_TRIGGER || !e.item) continue; + let o = this.items[i]; + if (!o || o.userData.item !== e.item) { if (o) this.world.remove(o); o = this.items[i] = this.itemModel(e.item); this.world.add(o); } + seen.add(String(i)); o.visible = true; + qv(e.origin[0], e.origin[1], e.origin[2] - 6 + Math.sin(time * 2.4 + i) * 3, o.position); o.rotation.y = time * 1.6 + i; + } + for (const k of Object.keys(this.items)) if (!seen.has(k)) this.items[k].visible = false; + } + itemModel(item) { + const g = new T.Group(); g.userData.item = item; const G = this.geo, m = this.itemMat[item] || this.itemMat.health; + const add = (geo, mat, x, y, z, sx, sy, sz) => { const o = new T.Mesh(geo, mat); o.position.set(x * S, z * S, -y * S); o.scale.set(sx * S, sz * S, sy * S); g.add(o); return o; }; + if (item.startsWith('health') || item === 'stimpack') { + const s = item === 'health_large' ? 1.3 : item === 'stimpack' ? 0.55 : 1; + add(G.box, m, 0, 0, 0, 22 * s, 16 * s, 14 * s); add(G.box, this.crossMat, 0, 0, 7.5 * s, 14 * s, 4 * s, 1); add(G.box, this.crossMat, 0, 0, 7.5 * s, 4 * s, 14 * s, 1); + } else if (item === 'armor_shard') { add(G.ico, m, 0, 0, 2, 7, 7, 10); } + else if (item.startsWith('armor')) { add(G.box, m, 0, 0, 0, 10, 26, 24); add(G.box, m, 4, 0, 10, 8, 30, 6); } + else { add(G.box, m, 0, 0, 0, 18, 14, 12); add(G.box, this.std(0xd8d0b0), 0, 0, 6.5, 12, 10, 1); } + return g; + } + updateViewWeapon(g, p, time) { + for (const w of Object.values(this.vweapons)) w.visible = false; + this.vflash.visible = false; + if (p.health <= 0 || !p.weapon) return; + const w = this.vweapons[p.weapon]; if (!w) return; + const def = Q.WDEF[p.weapon], [act, fireLast, idleLast, deact] = def.frames; + let drop = 0; + if (p.weaponstate === 2) drop = (p.gunframe - idleLast) / Math.max(1, deact - idleLast); + else if (p.weaponstate === 1) drop = 1 - p.gunframe / Math.max(1, act); + const speed = Math.hypot(p.velocity[0], p.velocity[1]), bob = p.groundentity >= 0 ? Math.min(1, speed / 300) : 0; + const since = g.ms - (p.fired || -9999), recoil = since >= 0 && since < 200 ? (1 - since / 200) : 0; + w.visible = true; + w.position.set(0.15 + Math.cos(time * 7.5) * 0.008 * bob, -0.13 - drop * 0.25 + Math.abs(Math.sin(time * 7.5)) * 0.008 * bob, -0.34 + recoil * 0.035); + w.rotation.set(recoil * 0.12, 0, 0); + if (w.userData.spin && p.weaponstate === 3) w.userData.spin.rotation.z = time * 14; + if (since >= 0 && since < 100) { this.vflash.visible = true; this.vflash.position.set(0.15, -0.11 - drop * 0.25, -0.55); this.vflash.scale.setScalar(0.03); } + } + metrics() { + const sorted = [...this.times].sort((a, b) => a - b), info = this.renderer.info; + return { renderer: 'webgl-quake2', drawCalls: info.render.calls, triangles: info.render.triangles, samples: sorted.length, + cpuRenderMsP50: sorted.length ? sorted[Math.floor((sorted.length - 1) * 0.5)] : null, cpuRenderMsP95: sorted.length ? sorted[Math.floor((sorted.length - 1) * 0.95)] : null }; + } + close() { if (this.closed) return; this.closed = true; this.ready = false; for (const r of this.resources) r.dispose && r.dispose(); this.renderer.dispose(); this.renderer.forceContextLoss(); this.resources = []; } + } + R.render = (g, ctx) => { + let m = byCanvas.get(ctx.canvas); if (!m) { m = new Map(); byCanvas.set(ctx.canvas, m); } + let s = m.get(g.key); if (!s || s.closed) { s = new Scene(g.key, ctx.canvas); m.set(g.key, s); } + s.render(g, ctx); m.last = s; return s; + }; + R.status = ctx => { + const m = ctx && byCanvas.get(ctx.canvas); let ready = false, error = null; + if (m) for (const s of m.values()) { if (!s.closed && s.renderer.getContext().isContextLost()) { s.ready = false; s.error = 'WebGL context lost'; } ready = ready || (s.ready && !s.closed); error = error || s.error; } + return { renderer: 'webgl-quake2', kind: 'perspective', ready, error }; + }; + R.metrics = ctx => { const m = ctx && byCanvas.get(ctx.canvas); return m && m.last && !m.last.closed ? m.last.metrics() : null; }; + R.close = ctx => { const m = ctx && byCanvas.get(ctx.canvas); if (!m) return; for (const s of m.values()) s.close(); byCanvas.delete(ctx.canvas); }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/quake2_remake/scripted.js b/environments/games/web/games/quake2_remake/scripted.js new file mode 100644 index 0000000000000000000000000000000000000000..0c1eeeae75349a99dc7a2dde5e32b6d82914e73b --- /dev/null +++ b/environments/games/web/games/quake2_remake/scripted.js @@ -0,0 +1,308 @@ +/* Quake II boss arenas - the standard scripted reference controller (BossBench, not part of the original game). + Quake2Game.scripted(game) is called once per 200 ms packet with the live simulation. It reads privileged state, + looks ahead on deep copies (M.copyGame never touches the live RNG or state), and returns only legal packets: + six hold sets of at most four keys and one mouse delta. Deterministic: no Math.random, no clock. + At 60 Hz (q2-arena@3) a packet is twelve ticks, two per hold set; the controller holds its move keys in all six + sets and taps weapon keys in sets 1-3 so the press lands on the first tick and is released after 100 ms. */ +(function (root) { + 'use strict'; + const N = root.NativeBench, M = root.Quake2Game, Q = M.Q; + const MOUSE_DEG = Q.CL.m_yaw * Q.CL.sensitivity; // 0.066 degrees per mouse count + const memory = new WeakMap(); + const angleDiff = a => ((a % 360) + 540) % 360 - 180; + const MOVES = [[], ['W'], ['S'], ['A'], ['D'], ['W', 'A'], ['W', 'D'], ['S', 'A'], ['S', 'D']]; + const SPEED = { rocketlauncher: 650, hyperblaster: 1000, blaster: 1000 }; + const LOOK = Math.round(1.4 * M.hz); // look-ahead per candidate move: 1.4 s (14 ticks at @2) + M.LOOK_K = 1; // blinded futures per candidate move (see M.scripted) + + // The copies get their own rand() state, so the controller plans with the rules but without knowing the live dice + // (bullet spread, the boss's next attack choice): it cannot dodge by reading the future RNG. Since q2-arena@3 the + // copy's state is a function of the tick only, not of the live holdrand: with it derived from the live value the + // packet still depended on the real dice (leak probe: decision invariance 0.63-0.75, tools/leak60.js). + function simulate(g, keys, mouseTicks, ticks, k = 0) { + const h = M.copyGame(g), ks = new Set(keys), none = new Set(); + let x = Math.imul((g.t + 0x9e3779b9 + Math.imul(k, 0x632be5ab)) >>> 0, 0x85ebca6b) >>> 0; x ^= x >>> 13; x = Math.imul(x, 0xc2b2ae35) >>> 0; x ^= x >>> 16; + h.rnd = x >>> 0; + // At 60 Hz the shared per-tick quantize (a walk over the whole state) was 87 % of the controller's time; the copy is + // a plan, not a replay, so it is quantized once at the end (still deterministic; off by micro-units at most). + for (let t = 0; t < ticks && !h.outcome; t++) { + h.events = []; + h.update(ks, none, mouseTicks[t] || [0, 0, 0]); // the turn happens in the first packet only + h.t++; + } + N.quantize(h); + return h; + } + const center = e => Q.center(e); + const eyeOf = p => [p.origin[0], p.origin[1], p.origin[2] + p.viewheight]; + function lineOfFire(g, from, to, boss) { + const tr = Q.trace(g, from, null, null, to, 1, Q.MASK_SHOT); + return tr.ent === boss || tr.fraction === 1; + } + // Weapon wanted for this target: highest-value weapon with ammo whose range rule holds. + function wantWeapon(g, p, b, dist) { + const has = (w, ammo, n = 1) => p.inv[w] && (!ammo || p.inv[ammo] >= n); + const surface = dist - (b.maxs[0] || 0); + const order = []; + if (b.classname === 'monster_supertank') { + // Rockets from RANGE_MID, then the machinegun from mid range; the shotguns are the last resort: their range puts + // the player in RANGE_NEAR (attack checks 5x as often) or inside 160 units (always the chaingun). + if (surface > 150) order.push(['rocketlauncher', 'rockets']); + order.push(['machinegun', 'bullets'], ['supershotgun', 'shells', 2], ['shotgun', 'shells']); + } else if (b.classname === 'monster_boss2') { + // Railgun first: hitscan 150 suits peek-shoot-hide against a flier (rockets and bolts miss it often). + order.push(['railgun', 'slugs'], ['chaingun', 'bullets'], ['hyperblaster', 'cells']); + } else if (b.classname === 'monster_jorg') { + if (dist < 800) order.push(['chaingun', 'bullets', 20]); + order.push(['hyperblaster', 'cells'], ['railgun', 'slugs']); + if (surface > 190) order.push(['rocketlauncher', 'rockets']); + } else if (b.classname === 'monster_tank_commander') { + // Rockets from range (750 health per hit-set is a lot of 8-damage bullets); the chaingun when it is close. + if (surface > 150) order.push(['rocketlauncher', 'rockets']); + order.push(['chaingun', 'bullets', 20], ['supershotgun', 'shells', 2], ['machinegun', 'bullets']); + } else if (b.classname === 'monster_gladiator') { + // Keep outside the cleaver: rockets and the hyperblaster from mid range. + if (surface > 150) order.push(['rocketlauncher', 'rockets']); + order.push(['hyperblaster', 'cells'], ['chaingun', 'bullets', 20], ['supershotgun', 'shells', 2]); + } else if (b.classname === 'monster_mutant') { + // No ranged attack to answer: shotguns at close range, the chaingun while kiting. + if (dist < 420) order.push(['supershotgun', 'shells', 2]); + order.push(['chaingun', 'bullets', 20], ['machinegun', 'bullets'], ['supershotgun', 'shells', 2]); + } else { + order.push(['railgun', 'slugs'], ['hyperblaster', 'cells'], ['chaingun', 'bullets']); + if (surface > 190) order.push(['rocketlauncher', 'rockets']); + } + order.push(['machinegun', 'bullets'], ['shotgun', 'shells'], ['supershotgun', 'shells', 2], ['blaster', null]); + for (const [w, ammo, n] of order) if (has(w, ammo, n || 1)) return w; + return 'blaster'; + } + // Hitscan streams that keep firing while the boss can see the player: the counter is to break line of sight. The + // Hornet's 0.9 s pre-mg windup deals no damage, so the controller keeps shooting through it and hides on attack_mg. + const STREAM = { monster_supertank: ['attack1'], monster_boss2: ['attack_mg'], monster_jorg: ['start_attack1', 'attack1'], + monster_tank_commander: ['attack_chain'] }; + const PREFERRED = { + monster_supertank: [['rocketlauncher', 'rockets'], ['machinegun', 'bullets']], + monster_boss2: [['railgun', 'slugs'], ['chaingun', 'bullets'], ['hyperblaster', 'cells']], + monster_jorg: [['chaingun', 'bullets'], ['hyperblaster', 'cells'], ['railgun', 'slugs'], ['rocketlauncher', 'rockets']], + monster_makron: [['railgun', 'slugs'], ['hyperblaster', 'cells'], ['chaingun', 'bullets'], ['rocketlauncher', 'rockets']], + monster_tank_commander: [['rocketlauncher', 'rockets'], ['chaingun', 'bullets']], + monster_gladiator: [['rocketlauncher', 'rockets'], ['hyperblaster', 'cells'], ['chaingun', 'bullets']], + monster_mutant: [['supershotgun', 'shells'], ['chaingun', 'bullets']], + }; + // Cover spots: points beside the arena's cover brushes (not the shell) that the boss's eye cannot see. + function hiddenSpots(g, b) { + const be = [b.origin[0], b.origin[1], b.origin[2] + b.viewheight], out = [], brushes = Q.worlds[g.key].brushes; + for (let k = 6; k < brushes.length; k++) { + const br = brushes[k]; + if (br.maxs[2] < 64) continue; // too low to hide behind + const cx = (br.mins[0] + br.maxs[0]) / 2, cy = (br.mins[1] + br.maxs[1]) / 2; + for (const [px, py] of [[br.mins[0] - 40, cy], [br.maxs[0] + 40, cy], [cx, br.mins[1] - 40], [cx, br.maxs[1] + 40], + [br.mins[0] - 40, br.mins[1] - 40], [br.maxs[0] + 40, br.mins[1] - 40], [br.mins[0] - 40, br.maxs[1] + 40], [br.maxs[0] + 40, br.maxs[1] + 40]]) { + const pt = [px, py, br.mins[2] + 24]; + if (Q.pointcontents(g, pt) & Q.CONTENTS_SOLID) continue; + if (Q.trace(g, be, null, null, [px, py, pt[2] + 22], -1, Q.MASK_OPAQUE).fraction < 1) out.push(pt); + } + } + return out; + } + // Stalemate breaker (5 s without sight, while the normal seek after 1 s has not found the boss): the nearest point the + // player can walk to in a straight line from which the boss's eye is visible now. Without it, player and boss can + // mirror each other on the two sides of a full-height pillar (each one's distance term only matches the other's + // position along the pillar, and a 1.4 s straight look-ahead never comes out of it). + function sightSpot(g, b, p) { + const be = [b.origin[0], b.origin[1], b.origin[2] + b.viewheight]; + let best = null, bestD = 1e9; + for (const r of [96, 192, 288, 384]) { + for (let k = 0; k < 16; k++) { + const a = k * Math.PI / 8, pt = [p.origin[0] + Q.cos(a) * r, p.origin[1] + Q.sin(a) * r, p.origin[2]]; + if (r >= bestD) continue; + if (Q.trace(g, p.origin, [-16, -16, -24], [16, 16, 32], pt, 1, Q.MASK_SOLID).fraction < 1) continue; + if (Q.trace(g, [pt[0], pt[1], pt[2] + p.viewheight], null, null, be, -1, Q.MASK_OPAQUE).fraction < 1) continue; + best = pt; bestD = r; + } + if (best) break; + } + return best; + } + // The boss's view of a candidate player position: eye-to-eye trace through the world only. + const seenBy = (g, b, q) => Q.trace(g, [b.origin[0], b.origin[1], b.origin[2] + b.viewheight], null, null, [q.origin[0], q.origin[1], q.origin[2] + q.viewheight], -1, Q.MASK_OPAQUE).fraction === 1; + function threats(h) { // enemy projectiles and BFG orbs near the player at the end of a look-ahead + const p = h.ents[1]; let s = 0; + for (const e of h.ents) { + if (!e.inuse || e.owner === 1 || e.owner < 0) continue; + if (e.classname === 'rocket') { + const v = Q.norm(e.velocity), rel = Q.sub(p.origin, e.origin), along = Q.dot(rel, v); + if (along > 0) { const off = Q.len(Q.sub(rel, Q.scale(v, along))); s += Math.max(0, 110 - off) * (along < 700 ? 1 : 0.3); } + } else if (e.classname === 'bfg blast') { + const dd = Q.len(Q.sub(p.origin, e.origin)); s += Math.max(0, 420 - dd) * 2.5; + } else if (e.classname === 'bolt') { + const v = Q.norm(e.velocity), rel = Q.sub(p.origin, e.origin), along = Q.dot(rel, v); + if (along > 0) { const off = Q.len(Q.sub(rel, Q.scale(v, along))); s += Math.max(0, 60 - off) * 0.5; } + } + } + return s; + } + M.scripted = function (g) { + const noop = { holds: Array.from({ length: 6 }, () => []), mouse: [0, 0, 0] }; + const p = g.ents[1]; + if (g.outcome || p.health <= 0) return noop; + // Memory across packets (hysteresis, time out of sight) is rolled once per tick, so asking twice about the same + // state gives the same packet; a new episode (tick 0) starts fresh. + let mem = memory.get(g); + if (!mem || (g.t === 0 && mem.t !== 0)) { mem = { t: -1, move: 0, unseen: 0, base: null }; memory.set(g, mem); } + if (mem.t !== g.t) { mem.base = { move: mem.move, unseen: mem.unseen }; mem.t = g.t; } + const bi = g.bossEnt(), b = g.ents[bi]; + const alive = b && b.inuse && (b.svflags & Q.SVF_MONSTER) && b.deadflag !== Q.DEAD_DEAD && b.health > 0; + const eye = eyeOf(p); + let dx = 0, dy = 0, fire = false, want = p.weapon, dist = 1e9; + if (alive) { + const c = center(b); + dist = Q.len(Q.sub(c, p.origin)); + want = wantWeapon(g, p, b, dist); + // Aim: the centre of the body, led by the boss's last-frame motion for projectile weapons. + let aim = [c[0], c[1], b.origin[2] + (b.maxs[2] - b.mins[2]) * 0.45]; + const speed = SPEED[p.weapon]; + if (speed) { const vel = Q.scale(Q.sub(b.origin, b.old_origin), 10), tf = Q.len(Q.sub(aim, eye)) / speed; aim = Q.ma(aim, tf, vel); } + const dvec = Q.sub(aim, eye), yaw = Q.atan2(dvec[1], dvec[0]) * 180 / Math.PI; + // Machinegun climb: each held shot adds machinegun_shots * -1.5 degrees of pitch kick; pull down to match. + const climb = p.weapon === 'machinegun' && (p.buttons & 1) ? Math.min(9, p.machinegun_shots + 0.5) * 1.5 : 0; + const pitch = -Q.atan2(dvec[2], Math.sqrt(dvec[0] * dvec[0] + dvec[1] * dvec[1])) * 180 / Math.PI + climb; + const dyaw = angleDiff(yaw - p.viewangles[1]), dpitch = pitch - p.viewangles[0]; + dx = Math.max(-1000, Math.min(1000, Math.round(-dyaw / MOUSE_DEG))); + dy = Math.max(-1000, Math.min(1000, Math.round(dpitch / MOUSE_DEG))); + const residual = Math.abs(dyaw + dx * MOUSE_DEG) + Math.abs(dpitch - dy * MOUSE_DEG); + const radius = Math.max(b.maxs[0], 24), tol = Q.atan2(radius * 0.8, Math.max(1, dist)) * 180 / Math.PI; + const clear = lineOfFire(g, eye, aim, bi); + const selfSplash = p.weapon === 'rocketlauncher' && dist - b.maxs[0] < 170; + // Pellet spread is +-hspread/8192 radians (shotgun 500, super shotgun 1000 plus +-5 degrees per barrel): against + // the 128-unit Super Tank or 160-unit Jorg most pellets still land at 900 units, against Makron (60) they do not. + const outOfRange = /shotgun/.test(p.weapon) && dist > (b.maxs[0] >= 60 ? 1000 : 640); + fire = clear && residual < tol + 2 && !selfSplash && !outOfRange && Math.abs(dyaw) < 60; + } + // Weapon switch: tap weapnext / weapprev toward the wanted weapon when idle. + let tap = null; + const switching = !!p.newweapon || p.weaponstate === 1 || p.weaponstate === 2; + if (!switching && want && want !== p.weapon && p.weaponstate !== 3) { + const owned = Q.WEAPON_ORDER.filter(w => p.inv[w]), cur = owned.indexOf(p.weapon), tgt = owned.indexOf(want); + if (tgt >= 0) tap = ((tgt - cur + owned.length) % owned.length) <= owned.length / 2 ? 'K' : 'R'; + } + // Movement: one-second look-ahead per candidate move on copies; score survival, damage, range and threats. + const fireKeys = fire ? ['J'] : []; + const PT = M.hz / 5, mouseTicks = Array.from({ length: PT }, () => [dx / PT, dy / PT, 0]); // the packet's split + const hp0 = p.health + armor(p) * 0.6, boss0 = g.health()[2]; + // Super Tank: rockets from the edge of RANGE_FAR. M_CheckAttack never attacks at >= 1000 units and only at 0.02 + // per frame (x2 on hard) in RANGE_MID, against 0.1 (x2) in RANGE_NEAR; the tank walks 120 u/s, the player runs 300. + const stBand = p.weapon === 'rocketlauncher' ? [880, 1250] : [650, 1000]; + const band = !alive ? [400, 900] : b.classname === 'monster_supertank' ? stBand : /shotgun/.test(p.weapon) ? [170, 380] + : b.classname === 'monster_boss2' ? [260, 620] : b.classname === 'monster_jorg' ? [360, 760] + : b.classname === 'monster_tank_commander' ? (p.weapon === 'rocketlauncher' ? [560, 900] : [300, 600]) + : b.classname === 'monster_gladiator' ? [420, 780] : b.classname === 'monster_mutant' ? [200, 420] : [320, 700]; + let best = 0, bestScore = -Infinity; + const stream = alive && (STREAM[b.classname] || []).includes(b.monsterinfo.currentmove); + const fragile = p.health + armor(p) * 0.6 < 70; + // Hiding is a tactic, not a plan: after 1 s without line of sight (and no burst in progress) the controller goes + // looking for the boss; cover is only taken while a hitscan burst is actually running. + const visNow = alive && Q.visible(g, bi, 1); + mem.unseen = visNow ? 0 : mem.base.unseen + 1; + const seek = alive && mem.unseen >= 5 && !fragile && !(STREAM[b.classname] || []).includes(b.monsterinfo.currentmove); + const spot = seek && mem.unseen >= 25 ? sightSpot(g, b, p) : null; + // Against hitscan bosses stay within a short dash of cover at all times (peek, shoot, step back): the burst only + // continues while the boss can see the player at its reattack check. + const hitscanBoss = alive && STREAM[b.classname]; + const spots = alive && (stream || fragile || hitscanBoss) ? hiddenSpots(g, b) : []; + // Ammo the preferred weapons of this fight are short of (below half of the carry limit); the main weapon first. + const needAmmo = []; + if (alive) for (const [w, ammo] of PREFERRED[b.classname] || []) if (p.inv[w] && p.inv[ammo] < Q.AMMO_MAX[ammo] / 2) needAmmo.push('ammo_' + ammo); + const main = alive && (PREFERRED[b.classname] || []).find(([w]) => p.inv[w]); + const lowMain = !!main && p.inv[main[1]] < Q.AMMO_MAX[main[1]] * 0.5; + // Out of the preferred weapons' ammo (while owning one of them): only the close-range fallbacks are left, so + // restocking comes first. The easy kit owns none of them and is never starving. + const owned = alive ? (PREFERRED[b.classname] || []).filter(([w]) => p.inv[w]) : []; + const starving = owned.length > 0 && !owned.some(([w, ammo]) => p.inv[ammo] >= 6); + for (let m = 0; m < MOVES.length; m++) { + const keys = ['Shift', ...MOVES[m], ...fireKeys]; + const scores = []; + for (let k = 0; k < M.LOOK_K; k++) { + const h = simulate(g, keys, mouseTicks, LOOK, k), q = h.ents[1]; + let score = -(hp0 - (q.health + armor(q) * 0.6)) * 25 + (boss0 - h.health()[2]) * 0.4; + if (h.outcome === 'loss' || q.health <= 0) score -= 1e6; + if (h.outcome === 'win') score += 1e5; + if (alive) { + const hb = h.ents[h.bossEnt()], nd = Q.len(Q.sub(Q.center(hb), q.origin)); + const seen = hb.inuse && hb.health > 0 && Q.visible(h, 1, h.bossEnt()); + if (!starving) score -= Math.max(0, band[0] - nd) * 0.5 + Math.max(0, nd - band[1]) * 0.25; + else score -= Math.max(0, 480 - nd) * 1.0; // restocking: stay out of RANGE_NEAR / the chaingun + if (seen) score += stream ? -90 : fragile ? 5 : (/shotgun/.test(p.weapon) && b.maxs[0] < 60 && nd > 640 ? -30 : 20); + if (seek) { if (seen) score += 80; score -= nd * 0.04; if (spot) score -= Math.sqrt((spot[0] - q.origin[0]) ** 2 + (spot[1] - q.origin[1]) ** 2) * 0.25; } + // During a hitscan stream the live boss does not move (attack1 is ai_charge 0): judge cover against it too. + if (stream && !seenBy(h, b, q)) score += 60; + if (spots.length) { + let near = 1e9; for (const s of spots) near = Math.min(near, Math.sqrt((s[0] - q.origin[0]) ** 2 + (s[1] - q.origin[1]) ** 2)); + score -= stream || fragile ? near * (stream ? 0.4 : 0.08) : seek ? 0 : Math.max(0, near - 140) * 0.06; + } + } + score -= threats(h) * 1.5; + // Room to manoeuvre: free distance in eight directions (corners trap the player in a hitscan stream). + let room = 0; + for (let k = 0; k < 8; k++) { + const a = k * Math.PI / 4, to = [q.origin[0] + Q.cos(a) * 200, q.origin[1] + Q.sin(a) * 200, q.origin[2]]; + room += Q.trace(h, q.origin, [-16, -16, -24], [16, 16, 32], to, 1, Q.MASK_SOLID).fraction; + } + score -= (8 - room) * 14; + if (m === mem.base.move) score += 6; + if (q.health < 90 || armor(q) < 40) { + // Health and armor pickups (and the ones about to respawn): strong pull when hurt, a mild one otherwise. + let near = 1e9; + for (const e of h.ents) { + if (!e.inuse || !e.item) continue; + const useful = /health/.test(e.item) ? q.health < 100 : e.item === 'stimpack' || (e.item === 'armor_shard' && armor(q) < 100); + if (!useful) continue; + const soon = e.solid !== Q.SOLID_TRIGGER && e.think === 'DoRespawn' && e.nextthink - h.ms < 3000; + if (e.solid === Q.SOLID_TRIGGER || soon) near = Math.min(near, Q.len(Q.sub(e.origin, q.origin)) + (soon ? 60 : 0)); + } + // Like the ammo boxes below: a health or armor item taken inside the look-ahead is gone from the floor (q2-arena@4 + // frees it), so "nearest item" would measure the next one and punish the move that heals. Taking one counts as + // distance 0 plus a bonus that grows with the damage taken. + let healed = 0; + for (let k = 0; k < h.ents.length && k < g.ents.length; k++) { + const ge = g.ents[k], he = h.ents[k]; + if (ge.inuse && ge.solid === Q.SOLID_TRIGGER && /^(health|stimpack|armor)/.test(ge.item || '') && !(he.inuse && he.item === ge.item && he.solid === Q.SOLID_TRIGGER)) healed++; + } + if (healed) score += (q.health < 50 ? 160 : q.health < 80 ? 60 : 20) * healed; + else if (near < 1e9) score -= near * (q.health < 50 ? 0.2 : q.health < 80 ? 0.08 : 0.03); + } + if (needAmmo.length) { + // Boxes on the floor, and boxes that respawn within the next 3 s (waiting next to them is the restock). + let near = 1e9; + for (const e of h.ents) { + if (!e.inuse || !needAmmo.includes(e.item)) continue; + const soon = e.solid !== Q.SOLID_TRIGGER && e.think === 'DoRespawn' && e.nextthink - h.ms < 3000; + if (e.solid === Q.SOLID_TRIGGER || soon) near = Math.min(near, Q.len(Q.sub(e.origin, q.origin)) + (soon ? 60 : 0)); + } + // A box taken inside the look-ahead has left the floor, so "nearest box" would then measure the next one and + // punish the very move that restocks: taking a needed box counts as distance 0 plus a bonus. + let taken = 0; + for (let k = 0; k < h.ents.length && k < g.ents.length; k++) if (needAmmo.includes(h.ents[k].item) && h.ents[k].solid !== Q.SOLID_TRIGGER && g.ents[k].solid === Q.SOLID_TRIGGER) taken++; + // During a hitscan burst cover beats restocking (the burst stops at the first reattack check without sight). + if (taken) score += stream ? 30 : starving ? 200 : lowMain ? 120 : 40; + else if (near < 1e9) score -= near * (stream ? 0.03 : starving ? 0.5 : lowMain ? 0.22 : 0.07); + } + scores.push(score); + } + // Several blinded futures per move (M.LOOK_K): half the worst, half the mean, so one lucky draw cannot pick a move. + const score = scores.length > 1 ? 0.5 * Math.min(...scores) + 0.5 * scores.reduce((x, y) => x + y, 0) / scores.length : scores[0]; + if (score > bestScore) { bestScore = score; best = m; } + } + mem.move = best; + const holds = Array.from({ length: 6 }, (_, k) => { + const ks = ['Shift', ...MOVES[best]]; + // A new press fires at once inside ClientThink while the packet's turn is still under way (60 Hz); start it on hold + // set 5 (turn 2/3 done), close to the 10 Hz packet whose first sample came half-way. Held fire stays in every set. + if (tap && k < 3) ks.push(tap); else if (fire && (k >= 4 || (p.buttons & 1))) ks.push('J'); + return ks.slice(0, 4); + }); + return { holds, mouse: [dx, dy, 0] }; + }; + const armor = p => p.inv.jacket + p.inv.combat + p.inv.body; + M.oracle = M.scripted; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/sekiro_remake/app3d.js b/environments/games/web/games/sekiro_remake/app3d.js new file mode 100644 index 0000000000000000000000000000000000000000..c64424a0a24d601db0647f4097e14145a10863e2 --- /dev/null +++ b/environments/games/web/games/sekiro_remake/app3d.js @@ -0,0 +1,78 @@ +/* Human play and exact native-input recording. Game state is owned by each module. */ +(function () { + 'use strict'; + const N=NativeBench, M=window.GAME_MODULE, $=s=>document.querySelector(s), canvas=$('canvas'), context=canvas.getContext('2d'); + let session=new N.Session(M,M.cases[0].id,1,.5),running=false,last=0,accumulator=0; + // A key pressed and released between two ticks stays latched until one tick has sampled it (same rule as + // _native/shell.js since 2026-11-01), so fast taps, macro keys and Playwright press() are never lost. Until 2026-11-09 this + // page released the key on a setTimeout(0), which can run before the next tick and drop the tap; now it is the tick that releases it. + const held=new Set(),pending=new Set(),releaseAfterTick=new Set(),pointerHeld=new Map(),touchHeld=new Map(); let mouse=[0,0,0],replay=null,replayIndex=0,automatic=false,script=null,scriptTick=0; + const keys={KeyW:'W',KeyA:'A',KeyS:'S',KeyD:'D',Space:'Space',ShiftLeft:'Shift',ShiftRight:'Shift',KeyJ:'J',KeyK:'K',KeyL:'L',KeyQ:'Q',KeyE:'E',KeyR:'R',ArrowUp:'W',ArrowDown:'S',ArrowLeft:'A',ArrowRight:'D'}; + document.body.dataset.game=M.id; + // Public difficulty = three tiers (2026-11-02): rebuilt from Module.tiers when the game declares it. + if(M.tiers&&$('#difficulty')){const sel=$('#difficulty'),names={easy:'Easy',normal:'Normal',hard:'Hard'};sel.textContent=''; + for(const t of ['easy','normal','hard']){const op=document.createElement('option');op.value=String(M.tiers[t]);op.textContent=names[t]+'(d='+M.tiers[t]+')';if(t==='normal')op.selected=true;sel.append(op);}} + for(const def of M.cases){const option=document.createElement('option');option.value=def.id;option.textContent=def.name;$('#case').append(option);} + const controls=Array.isArray(M.controls)?M.controls.map(value=>['',value]):Object.entries(M.controls); + for(const [key,value]of controls){const dt=document.createElement('dt'),dd=document.createElement('dd');dt.textContent=key;dd.textContent=value;$('dl').append(dt,dd);} + function status(value){$('#status').textContent=value;} + function clear(){held.clear();pending.clear();releaseAfterTick.clear();pointerHeld.clear();touchHeld.clear();mouse=[0,0,0];accumulator=0;} + function inputKeys(){return [...new Set([...held,...[...pointerHeld.values()].flatMap(keys=>[...keys]),...touchHeld.values()])].filter(key=>N.keys.includes(key)).slice(0,4);} + function draw(){ + M.draw(session.game,context); + $('#pause').textContent=running?'Pause':'Resume'; + $('#overlay').hidden=running&&!session.game.outcome; + $('#overlay strong').textContent=session.game.outcome?{win:'Challenge Complete',loss:'Challenge Failed',timeout:'Time up'}[session.game.outcome]:replay?'Replay · Paused':session.game.t?'Paused':'Are You Ready?'; + $('#overlay span').textContent=session.game.outcome?'Restart the challenge or export this replay':session.game.t?'Click the screen or press Resume to return to battle':'Click Start Challenge, then click the screen to lock the mouse and turn the camera'; + } + function reset(id,seed,difficulty){running=false;automatic=false;replay=null;script=null;scriptTick=0;clear();session=new N.Session(M,id,seed,difficulty);draw();return session.snapshot();} + window.nativeAPI={reset,packet(packet){if(running)throw Error('Pause before a scripted packet');const value=session.packet(packet);draw();return value;}, + state(){return session.snapshot();},recording(){return session.export();}, + render(){draw();return canvas.toDataURL('image/png');}, + renderMetrics(){return M.renderMetrics?M.renderMetrics(context):{};}, + module(){return {id:M.id,hz:M.hz,version:M.version,cases:M.cases};}}; + // PC-style mouse look (2026-11-09): the first click on the canvas during a fight locks the pointer, after which plain mouse + // movement turns the camera and the buttons stay attack / guard. Not on the start / resume buttons: while the pointer is + // locked every click goes to the canvas, so the toolbar would be unreachable until Esc. Dragging still works without a lock. + function lockPointer(){if(document.pointerLockElement===canvas||!canvas.requestPointerLock)return;try{const r=canvas.requestPointerLock();if(r&&r.catch)r.catch(()=>{});}catch(error){}} + document.addEventListener('pointerlockchange',()=>{if(document.pointerLockElement===canvas)status('Mouse locked · Press Esc to unlock');else if(running&&!automatic&&!replay){running=false;clear();status('Paused (mouse unlocked) · Click the screen to resume and lock the mouse');draw();} + else if(!running&&!automatic&&!replay&&!session.game.outcome&&session.game.t>0)status('Paused (Esc) · Click the screen to resume and lock the mouse');}); + function start(useScript){try{reset($('#case').value,Number($('#seed').value),Number($('#difficulty').value));automatic=useScript;running=true;status(useScript?'Verification script running':'Battle started · Recording this match · Click the screen to lock the mouse; move it to turn the camera');canvas.focus();draw();}catch(error){status(error.message);}} + $('#start').onclick=()=>start(false);$('#demo').onclick=()=>start(true); + $('#pause').onclick=()=>{if(session.game.outcome)return;running=!running;clear();if(running)canvas.focus();draw();}; + $('#step').onclick=()=>{running=false;if(replay)replayTick();else session.tick();draw();}; + function openReplay(data){N.Session.import(M,data);reset(data.case,data.seed,data.difficulty);replay=data;replayIndex=0;running=true;$('#case').value=data.case;status('Replay verified · Starting playback');draw();} + $('#sample').onclick=()=>{try{const data=M.example?.[$('#case').value];if(!data)throw Error('No built-in replay for this challenge yet. Try Verify Script first.');openReplay(data);}catch(error){status(error.message);}}; + function replayTick(){if(replayIndex{const data=session.export(),url=URL.createObjectURL(new Blob([JSON.stringify(data)],{type:'application/json'}));const link=document.createElement('a');link.href=url;link.download=M.id+'-'+session.seed+'.json';link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);status('Current replay exported');}; + $('#import').onclick=()=>$('#file').click();$('#file').onchange=async event=>{const file=event.target.files[0];if(!file)return;try{if(file.size>12e6)throw Error('Replay file is too large');openReplay(JSON.parse(await file.text()));}catch(error){status('Import failed: '+error.message);}event.target.value='';}; + function release(){clear();if(running){running=false;status('Window lost focus · Battle paused');}draw();} + window.addEventListener('blur',release);document.addEventListener('visibilitychange',()=>{if(document.hidden)release();}); + window.addEventListener('keydown',event=>{if(['INPUT','SELECT','BUTTON'].includes(document.activeElement.tagName))return;if(keys[event.code]){event.preventDefault();held.add(keys[event.code]);pending.add(keys[event.code]);releaseAfterTick.delete(keys[event.code]);}if(event.code==='Escape'){const wasRunning=running;running=false;clear();if(document.pointerLockElement===canvas)document.exitPointerLock?.();if(wasRunning&&!automatic&&!replay&&!session.game.outcome)status('Paused (Esc) · Click the screen to resume and lock the mouse');draw();}}); + window.addEventListener('keyup',event=>{const key=keys[event.code];if(key){event.preventDefault();if(pending.has(key))releaseAfterTick.add(key);else held.delete(key);}}); + canvas.oncontextmenu=event=>event.preventDefault();canvas.onpointerdown=event=>{if(event.button!==0&&event.button!==2)return;canvas.focus(); + // A click on the canvas while the pointer is free re-locks it and resumes a paused fight; that click is not an attack. + if(document.pointerLockElement!==canvas&&!automatic&&!replay&&!session.game.outcome&&session.game.t>0&&!running){lockPointer();running=true;clear();draw();return;} + if(document.pointerLockElement!==canvas&&running&&!automatic&&!replay)lockPointer();const keys=pointerHeld.get(event.pointerId)||new Set();keys.add(event.button===2?'RMB':'LMB');pointerHeld.set(event.pointerId,keys);}; + // Pointer Events emits pointerup only after the final mouse button is released. + // pointermove carries changes to the button mask for chorded mouse presses. + function syncMouse(event){if(event.pointerType==='mouse'&&pointerHeld.has(event.pointerId)){const keys=new Set();if(event.buttons&1)keys.add('LMB');if(event.buttons&2)keys.add('RMB');if(keys.size)pointerHeld.set(event.pointerId,keys);else pointerHeld.delete(event.pointerId);}} + window.addEventListener('pointermove',syncMouse); + window.addEventListener('pointerup',event=>{if(event.pointerType==='mouse')syncMouse(event);else pointerHeld.delete(event.pointerId);touchHeld.delete(event.pointerId);}); + window.addEventListener('pointercancel',event=>{pointerHeld.delete(event.pointerId);touchHeld.delete(event.pointerId);}); + canvas.onpointermove=event=>{if(event.buttons||document.pointerLockElement===canvas){mouse[0]+=event.movementX;mouse[1]+=event.movementY;}}; + canvas.onwheel=event=>{event.preventDefault();mouse[2]+=Math.sign(event.deltaY);}; + canvas.ondblclick=()=>canvas.requestPointerLock?.(); + document.querySelectorAll('[data-key]').forEach(button=>{button.onpointerdown=event=>{event.preventDefault();button.setPointerCapture(event.pointerId);touchHeld.set(event.pointerId,button.dataset.key);};button.onpointerup=button.onpointercancel=event=>touchHeld.delete(event.pointerId);}); + function frame(now){const delta=Math.min(.1,(now-last)/1000||0);last=now;const beforeTick=session.game.t,wasRunning=running;try{ + if(running&&!session.game.outcome){accumulator+=delta;while(accumulator>=1/M.hz&&running&&!session.game.outcome){accumulator-=1/M.hz; + if(replay)replayTick();else if(automatic){const count=M.hz/5;if(scriptTick===0)script=(M.scripted||M.oracle).call(M,session.game);const sub=Math.ceil((scriptTick+1)*6/count)-1;session.tick(script.holds[sub],script.mouse.map(value=>value/count));scriptTick=(scriptTick+1)%count;} + else{session.tick(inputKeys(),mouse.map((value,index)=>N.clamp(value,index===2?-5:-1000,index===2?5:1000)));mouse=[0,0,0];pending.clear();for(const key of releaseAfterTick)held.delete(key);releaseAfterTick.clear();}} + if(session.game.outcome){running=false;status({win:'Challenge Complete',loss:'Challenge Failed',timeout:'Challenge Timed Out'}[session.game.outcome]+' · You can export or replay this match');}} + if(session.game.t!==beforeTick||running!==wasRunning)draw(); + }catch(error){running=false;clear();status('Runtime error: '+error.message);$('#overlay').hidden=false;$('#overlay strong').textContent='Unable to resume right now';$('#overlay span').textContent=error.message;} + requestAnimationFrame(frame); + } + window.addEventListener('pagehide',()=>M.closeRenderer?.(context)); + draw();requestAnimationFrame(frame); +})(); diff --git a/environments/games/web/games/sekiro_remake/compact_actions.json b/environments/games/web/games/sekiro_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..13d86ba2c536855ddacfcdd53c2e68c6a2f5dbf1 --- /dev/null +++ b/environments/games/web/games/sekiro_remake/compact_actions.json @@ -0,0 +1,1135 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "sekiro_remake", + "version": "sekiro-compact@1", + "heads": [ + { + "name": "move", + "options": [ + { + "label": "none" + }, + { + "label": "forward", + "keys": [ + "W" + ] + }, + { + "label": "forward_start", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [], + [], + [] + ] + }, + { + "label": "forward_end", + "subs": [ + [], + [], + [], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ] + ] + }, + { + "label": "forward_tap", + "subs": [ + [ + "W" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "back", + "keys": [ + "S" + ] + }, + { + "label": "left", + "keys": [ + "A" + ] + }, + { + "label": "right", + "keys": [ + "D" + ] + }, + { + "label": "back_left", + "keys": [ + "S", + "A" + ] + }, + { + "label": "back_right", + "keys": [ + "S", + "D" + ] + }, + { + "label": "turn_left_30", + "dx": -175 + }, + { + "label": "turn_right_30", + "dx": 175 + } + ] + }, + { + "name": "act", + "options": [ + { + "label": "none" + }, + { + "label": "attack_0", + "subs": [ + [ + "J" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "attack_1", + "subs": [ + [], + [ + "J" + ], + [], + [], + [], + [] + ] + }, + { + "label": "attack_2", + "subs": [ + [], + [], + [ + "J" + ], + [], + [], + [] + ] + }, + { + "label": "attack_3", + "subs": [ + [], + [], + [], + [ + "J" + ], + [], + [] + ] + }, + { + "label": "attack_4", + "subs": [ + [], + [], + [], + [], + [ + "J" + ], + [] + ] + }, + { + "label": "attack_5", + "subs": [ + [], + [], + [], + [], + [], + [ + "J" + ] + ] + }, + { + "label": "deflect_0", + "subs": [ + [ + "RMB" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "deflect_1", + "subs": [ + [], + [ + "RMB" + ], + [], + [], + [], + [] + ] + }, + { + "label": "deflect_2", + "subs": [ + [], + [], + [ + "RMB" + ], + [], + [], + [] + ] + }, + { + "label": "deflect_3", + "subs": [ + [], + [], + [], + [ + "RMB" + ], + [], + [] + ] + }, + { + "label": "deflect_4", + "subs": [ + [], + [], + [], + [], + [ + "RMB" + ], + [] + ] + }, + { + "label": "deflect_5", + "subs": [ + [], + [], + [], + [], + [], + [ + "RMB" + ] + ] + }, + { + "label": "deflect_attack_0_1", + "subs": [ + [ + "RMB" + ], + [ + "J" + ], + [], + [], + [], + [] + ] + }, + { + "label": "deflect_attack_0_2", + "subs": [ + [ + "RMB" + ], + [], + [ + "J" + ], + [], + [], + [] + ] + }, + { + "label": "deflect_attack_0_3", + "subs": [ + [ + "RMB" + ], + [], + [], + [ + "J" + ], + [], + [] + ] + }, + { + "label": "deflect_attack_0_4", + "subs": [ + [ + "RMB" + ], + [], + [], + [], + [ + "J" + ], + [] + ] + }, + { + "label": "deflect_attack_0_5", + "subs": [ + [ + "RMB" + ], + [], + [], + [], + [], + [ + "J" + ] + ] + }, + { + "label": "deflect_attack_1_2", + "subs": [ + [], + [ + "RMB" + ], + [ + "J" + ], + [], + [], + [] + ] + }, + { + "label": "deflect_attack_1_3", + "subs": [ + [], + [ + "RMB" + ], + [], + [ + "J" + ], + [], + [] + ] + }, + { + "label": "deflect_attack_1_4", + "subs": [ + [], + [ + "RMB" + ], + [], + [], + [ + "J" + ], + [] + ] + }, + { + "label": "deflect_attack_1_5", + "subs": [ + [], + [ + "RMB" + ], + [], + [], + [], + [ + "J" + ] + ] + }, + { + "label": "deflect_attack_2_3", + "subs": [ + [], + [], + [ + "RMB" + ], + [ + "J" + ], + [], + [] + ] + }, + { + "label": "deflect_attack_2_4", + "subs": [ + [], + [], + [ + "RMB" + ], + [], + [ + "J" + ], + [] + ] + }, + { + "label": "deflect_attack_2_5", + "subs": [ + [], + [], + [ + "RMB" + ], + [], + [], + [ + "J" + ] + ] + }, + { + "label": "deflect_attack_3_4", + "subs": [ + [], + [], + [], + [ + "RMB" + ], + [ + "J" + ], + [] + ] + }, + { + "label": "deflect_attack_3_5", + "subs": [ + [], + [], + [], + [ + "RMB" + ], + [], + [ + "J" + ] + ] + }, + { + "label": "deflect_attack_4_5", + "subs": [ + [], + [], + [], + [], + [ + "RMB" + ], + [ + "J" + ] + ] + }, + { + "label": "deflect_0_4", + "subs": [ + [ + "RMB" + ], + [], + [], + [], + [ + "RMB" + ], + [] + ] + }, + { + "label": "deflect_0_5", + "subs": [ + [ + "RMB" + ], + [], + [], + [], + [], + [ + "RMB" + ] + ] + }, + { + "label": "deflect_2_4", + "subs": [ + [], + [], + [ + "RMB" + ], + [], + [ + "RMB" + ], + [] + ] + }, + { + "label": "deflect_2_5", + "subs": [ + [], + [], + [ + "RMB" + ], + [], + [], + [ + "RMB" + ] + ] + }, + { + "label": "deflect_3_5", + "subs": [ + [], + [], + [], + [ + "RMB" + ], + [], + [ + "RMB" + ] + ] + }, + { + "label": "step_alt_0", + "subs": [ + [ + "Shift" + ], + [], + [ + "Shift" + ], + [], + [ + "Shift" + ], + [] + ] + }, + { + "label": "step_alt_1", + "subs": [ + [], + [ + "Shift" + ], + [], + [ + "Shift" + ], + [], + [ + "Shift" + ] + ] + }, + { + "label": "deflect_2_4_5", + "subs": [ + [], + [], + [ + "RMB" + ], + [], + [ + "RMB" + ], + [ + "RMB" + ] + ] + }, + { + "label": "step_0", + "subs": [ + [ + "Shift" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "step_1", + "subs": [ + [], + [ + "Shift" + ], + [], + [], + [], + [] + ] + }, + { + "label": "step_2", + "subs": [ + [], + [], + [ + "Shift" + ], + [], + [], + [] + ] + }, + { + "label": "step_3", + "subs": [ + [], + [], + [], + [ + "Shift" + ], + [], + [] + ] + }, + { + "label": "step_4", + "subs": [ + [], + [], + [], + [], + [ + "Shift" + ], + [] + ] + }, + { + "label": "jump_0", + "subs": [ + [ + "Space" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "jump_1", + "subs": [ + [], + [ + "Space" + ], + [], + [], + [], + [] + ] + }, + { + "label": "jump_2", + "subs": [ + [], + [], + [ + "Space" + ], + [], + [], + [] + ] + }, + { + "label": "jump_3", + "subs": [ + [], + [], + [], + [ + "Space" + ], + [], + [] + ] + }, + { + "label": "jump_4", + "subs": [ + [], + [], + [], + [], + [ + "Space" + ], + [] + ] + }, + { + "label": "jump_5", + "subs": [ + [], + [], + [], + [], + [], + [ + "Space" + ] + ] + }, + { + "label": "jump_kick_0", + "subs": [ + [ + "Space" + ], + [], + [ + "Space" + ], + [], + [], + [] + ] + }, + { + "label": "jump_kick_1", + "subs": [ + [], + [ + "Space" + ], + [], + [ + "Space" + ], + [], + [] + ] + }, + { + "label": "jump_kick_2", + "subs": [ + [], + [], + [ + "Space" + ], + [], + [ + "Space" + ], + [] + ] + }, + { + "label": "jump_kick_3", + "subs": [ + [], + [], + [], + [ + "Space" + ], + [], + [ + "Space" + ] + ] + }, + { + "label": "jump_attack_0_1", + "subs": [ + [ + "Space" + ], + [ + "J" + ], + [], + [], + [], + [] + ] + }, + { + "label": "jump_attack_0_2", + "subs": [ + [ + "Space" + ], + [], + [ + "J" + ], + [], + [], + [] + ] + }, + { + "label": "jump_attack_0_3", + "subs": [ + [ + "Space" + ], + [], + [], + [ + "J" + ], + [], + [] + ] + }, + { + "label": "jump_attack_1_2", + "subs": [ + [], + [ + "Space" + ], + [ + "J" + ], + [], + [], + [] + ] + }, + { + "label": "jump_attack_1_3", + "subs": [ + [], + [ + "Space" + ], + [], + [ + "J" + ], + [], + [] + ] + }, + { + "label": "jump_attack_1_4", + "subs": [ + [], + [ + "Space" + ], + [], + [], + [ + "J" + ], + [] + ] + }, + { + "label": "jump_attack_2_3", + "subs": [ + [], + [], + [ + "Space" + ], + [ + "J" + ], + [], + [] + ] + }, + { + "label": "jump_attack_2_4", + "subs": [ + [], + [], + [ + "Space" + ], + [], + [ + "J" + ], + [] + ] + }, + { + "label": "jump_attack_2_5", + "subs": [ + [], + [], + [ + "Space" + ], + [], + [], + [ + "J" + ] + ] + }, + { + "label": "jump_attack_3_4", + "subs": [ + [], + [], + [], + [ + "Space" + ], + [ + "J" + ], + [] + ] + }, + { + "label": "jump_attack_3_5", + "subs": [ + [], + [], + [], + [ + "Space" + ], + [], + [ + "J" + ] + ] + }, + { + "label": "jump_attack_4_5", + "subs": [ + [], + [], + [], + [], + [ + "Space" + ], + [ + "J" + ] + ] + }, + { + "label": "guard_hold_2", + "subs": [ + [ + "RMB" + ], + [ + "RMB" + ], + [], + [], + [], + [] + ] + }, + { + "label": "guard_hold_3", + "subs": [ + [ + "RMB" + ], + [ + "RMB" + ], + [ + "RMB" + ], + [], + [], + [] + ] + }, + { + "label": "guard_hold_6", + "subs": [ + [ + "RMB" + ], + [ + "RMB" + ], + [ + "RMB" + ], + [ + "RMB" + ], + [ + "RMB" + ], + [ + "RMB" + ] + ] + }, + { + "label": "guard_hold_late", + "subs": [ + [], + [], + [], + [ + "RMB" + ], + [ + "RMB" + ], + [ + "RMB" + ] + ] + }, + { + "label": "run", + "keys": [ + "Shift" + ] + }, + { + "label": "heal_0", + "subs": [ + [ + "Q" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "heal_2", + "subs": [ + [], + [], + [ + "Q" + ], + [], + [], + [] + ] + }, + { + "label": "heal_4", + "subs": [ + [], + [], + [], + [], + [ + "Q" + ], + [] + ] + }, + { + "label": "revive", + "tap": [ + "R" + ] + }, + { + "label": "lock_toggle", + "tap": [ + "E" + ] + } + ] + } + ] +} diff --git a/environments/games/web/games/sekiro_remake/draw.js b/environments/games/web/games/sekiro_remake/draw.js new file mode 100644 index 0000000000000000000000000000000000000000..79e2772e37593cb5bd20356ab26a1bef3c932e9e --- /dev/null +++ b/environments/games/web/games/sekiro_remake/draw.js @@ -0,0 +1,70 @@ +/* Sekiro HUD drawn over the WebGL frame: boss name, deathblow markers and vitality at the top left, posture gauges + * growing from the centre (boss at the top, Sekiro at the bottom), Sekiro's vitality, resurrection nodes, gourd and + * ailment gauges at the bottom left, the red perilous kanji above Sekiro, the deathblow mark on the target, the blue lock-on + * reticle (only while locked) and an edge arrow toward an off-screen boss, native Hz. */ +(function(root){ + 'use strict';const M=root.SekiroGame,B=root.Boss3D,clamp=(x,a,b)=>Math.max(a,Math.min(b,x)); + const TIER_NAMES={easy:'Easy',normal:'Normal',hard:'Hard'}; + function font(c,size,weight='',serif=false){c.font=`${weight} ${size}px ${serif?'"Noto Serif SC","Songti SC","SimSun","Microsoft YaHei",serif':'"Segoe UI","Microsoft YaHei",sans-serif'}`;} + function text(c,s,x,y,size,color,align='left',o={}){font(c,size,o.weight||'',o.serif);c.textAlign=align;c.textBaseline='alphabetic'; + if(o.glow){c.shadowColor=o.glow;c.shadowBlur=o.blur||12;}c.fillStyle='rgba(6,8,10,.75)';c.fillText(s,x+1,y+1.5);c.fillStyle=color;c.fillText(s,x,y);c.shadowBlur=0;} + function bar(c,x,y,w,h,v,fill,back='rgba(10,12,14,.72)'){c.fillStyle=back;c.fillRect(x,y,w,h);c.fillStyle=fill;c.fillRect(x+1,y+1,Math.max(0,(w-2)*clamp(v,0,1)),h-2); + c.strokeStyle='rgba(220,205,170,.55)';c.lineWidth=1;c.strokeRect(x+.5,y+.5,w-1,h-1);} + // Posture grows outward from the middle; it turns hotter as it nears a break and darker while low vitality slows recovery. + function posture(c,cx,y,w,h,v,slow,flash){if(v<=0.002)return;const half=w/2*clamp(v,0,1);c.fillStyle='rgba(10,10,12,.7)';c.fillRect(cx-w/2,y,w,h); + const hot=v>.85&&flash,col=hot?'#ff4f1f':v>.6?'#f08a2a':'#e6b143';const g=c.createLinearGradient(cx-half,0,cx+half,0);g.addColorStop(0,col);g.addColorStop(.5,'#ffe5a0');g.addColorStop(1,col); + c.fillStyle=g;c.fillRect(cx-half,y+1,half*2,h-2);if(slow){c.fillStyle='rgba(120,20,10,.35)';c.fillRect(cx-half,y+1,half*2,h-2);} + c.fillStyle='rgba(255,240,200,.9)';c.fillRect(cx-1,y-2,2,h+4);c.strokeStyle='rgba(230,200,150,.5)';c.strokeRect(cx-w/2+.5,y+.5,w-1,h-1);} + function dot(c,x,y,r,full,color){c.beginPath();c.arc(x,y,r,0,Math.PI*2);c.fillStyle=full?color:'rgba(30,26,26,.85)';c.fill();c.lineWidth=1.5;c.strokeStyle=full?'rgba(255,190,170,.9)':'rgba(140,120,118,.8)';c.stroke();} + // Lock-on aids, drawn in 2D over the frame so walls and pillars never hide them (as zelda_oot_remake/draw.js reticle / edgeArrow). + // Cool blue, so the lock never reads as the red deathblow dot or the red perilous kanji; the ring sits at the deathblow height and circles that dot. + const LOCK='#8fdcff',PI2=Math.PI*2; + function reticle(c,x,y,r,a,dot){c.save();c.translate(x,y);c.lineWidth=4;c.strokeStyle='rgba(8,12,20,.85)';c.beginPath();c.arc(0,0,r,0,PI2);c.stroke(); + c.lineWidth=2;c.strokeStyle=LOCK;c.beginPath();c.arc(0,0,r,0,PI2);c.stroke(); + for(let i=0;i<4;i++){c.save();c.rotate(a+i*PI2/4);c.beginPath();c.moveTo(0,-r-2);c.lineTo(-5,-r-11);c.lineTo(5,-r-11);c.closePath();c.fillStyle=LOCK;c.fill();c.lineWidth=1.2;c.strokeStyle='rgba(8,12,20,.85)';c.stroke();c.restore();} + if(dot){c.beginPath();c.arc(0,0,3,0,PI2);c.fillStyle=LOCK;c.fill();c.lineWidth=1.2;c.strokeStyle='rgba(8,12,20,.85)';c.stroke();}c.restore();} + function edgeArrow(c,ax,ay,col,label){const m=36,k=Math.min((427-m)/Math.max(1e-6,Math.abs(ax)),(240-m)/Math.max(1e-6,Math.abs(ay))),x=427+ax*k,y=240+ay*k,a=Math.atan2(ay,ax); + c.save();c.translate(x,y);c.rotate(a);c.beginPath();c.moveTo(18,0);c.lineTo(-10,-13);c.lineTo(-4,0);c.lineTo(-10,13);c.closePath();c.fillStyle=col;c.fill();c.lineWidth=2.5;c.strokeStyle='rgba(8,12,20,.92)';c.stroke();c.restore(); + text(c,label,x-Math.cos(a)*30,y-Math.sin(a)*30+5,12,col,'center');} + function gourd(c,x,y){c.fillStyle='#9a5a28';c.beginPath();c.arc(x,y+5,6.5,0,Math.PI*2);c.arc(x,y-4,4.5,0,Math.PI*2);c.fill();c.fillStyle='#d9b56a';c.fillRect(x-1.5,y-12,3,4);c.fillStyle='rgba(255,240,200,.3)';c.beginPath();c.arc(x-2,y+3,2,0,Math.PI*2);c.fill();} + M.draw=function(g,c){const scene=B.render('sekiro',g,c),p=g.player,b=g.boss,kind=g.kind||'genichiro',K=M.bosses[kind],tm=g.t/M.hz; + // ---- boss: deathblow markers, name and vitality (top left) + const [shown,left]=K.markers(b),name=K.names[Math.min(K.names.length-1,(b.phase||1)-1)]; + for(let i=0;i0){c.strokeStyle='#1a1214';c.lineWidth=3;c.beginPath();c.moveTo(30,414);c.lineTo(62,405);c.stroke();text(c,'Resurrection sealed',70,414,11,'#c9b0bb');} + bar(c,30,422,236,8,(p.hp||0)/(p.maxHp||1),p.poisoned>0?'#7d9a3a':'#c7392f'); + let gy=416;for(const [v,label,col] of [[p.poison||0,'Poison',p.poisoned>0?'#a8d050':'#7da040'],[p.terror||0,'Terror','#9b1a2a'],...(p.burn!==undefined?[[p.burning>0?100:p.burn,'Burn',p.burning>0?'#ff7a2a':'#d4602a']]:[])]){if(v<=0.5&&!(label==='Poison'&&p.poisoned>0))continue;gy-=13;text(c,label,272,gy+8,11,col);bar(c,286,gy,70,6,label==='Poison'&&p.poisoned>0?1:v/100,col);} + gourd(c,40,452);text(c,'× '+(p.gourds??0),52,458,14,'#e8d9b8'); + posture(c,427,446,300,7,(p.posture||0)/(p.maxPosture||100),(p.hp||0)/(p.maxHp||1)<.5,Math.floor(g.t/6)%2===0); + // ---- perilous kanji above Sekiro, deathblow mark on the target + if(scene&&b.perilous&&b.telegraph&&!p.dead){const s=scene.project(p.x,(p.y||0)+2.05,p.z),pulse=1+.08*Math.sin(g.t*.5); + c.save();c.globalAlpha=.85;const rg=c.createRadialGradient(s.x,s.y-14,2,s.x,s.y-14,36*pulse);rg.addColorStop(0,'rgba(255,40,20,.55)');rg.addColorStop(1,'rgba(255,40,20,0)');c.fillStyle=rg;c.fillRect(s.x-40,s.y-56,80,84);c.restore(); + text(c,'PERIL',s.x,s.y,Math.round(40*pulse),'#ff3b26','center',{weight:'bold',serif:true,glow:'rgba(255,40,10,.9)',blur:14});} + // Lock reticle while locked; when the boss is out of the picture (behind the camera, or past an edge) an arrow at the edge points to it. + if(scene&&b.state!=='dead'&&!g.outcome&&!p.dead){const h=kind==='ape'?2.1:kind==='gyoubu'?2.7:kind==='demon'?3.6:1.2,s=scene.project(b.x,(b.y||0)+h,b.z),on=s.visible&&s.x>8&&s.x<846&&s.y>8&&s.y<472; + if(on&&g.lockOn)reticle(c,s.x,s.y,20,g.t*.04,!b.deathblowAvailable); + else if(!on){const yaw=g.cameraYaw||0,dx=b.x-p.x,dz=b.z-p.z,right=-dx*Math.cos(yaw)+dz*Math.sin(yaw),ahead=dx*Math.sin(yaw)+dz*Math.cos(yaw); + // In front: the projected direction; behind the camera the projection flips, so use the camera frame (screen-right, and down for behind). + const [ax,ay]=s.visible&&ahead>0?[s.x-427,s.y-240]:[right,-ahead];edgeArrow(c,ax,ay,g.lockOn?LOCK:'#ffcf8a',g.lockOn?'Lock':'Boss');}} + if(scene&&b.deathblowAvailable){const h=kind==='ape'?2.1:kind==='gyoubu'?2.7:kind==='demon'?3.6:1.2,s=scene.project(b.x,(b.y||0)+h,b.z),r=7+Math.sin(g.t*.25)*1.5; + c.beginPath();c.arc(s.x,s.y,r+7,0,Math.PI*2);c.strokeStyle='rgba(255,60,40,.5)';c.lineWidth=2;c.stroke();c.beginPath();c.arc(s.x,s.y,r,0,Math.PI*2);c.fillStyle='#e0261c';c.shadowColor='#ff3020';c.shadowBlur=12;c.fill();c.shadowBlur=0;} + if(p.lightning>0&&!p.dead){const s=scene?scene.project(p.x,(p.y||0)+2.2,p.z):{x:427,y:200};text(c,'Lightning strike',s.x,s.y,20,'#ffe39a','center',{weight:'bold',glow:'rgba(255,220,120,.9)'});} + // ---- Shinobi Execution banner (the guardian ape's first one is a deception, S14) + const banner=(b.executing>0&&(b.phase===b.bars||kind==='ape'))||g.outcome==='win'||(b.state==='dead'&&(b.deadTicks||0)>110); + if(banner){const u=g.outcome==='win'?1:clamp(b.state==='dead'?((b.deadTicks||0)-110)/40:(58-(b.executing||0))/14,0,1);c.save();c.globalAlpha=u; + c.fillStyle='rgba(0,0,0,.35)';c.fillRect(0,196,854,92);text(c,'DEATHBLOW',427,262,62,'#e9e2d2','center',{weight:'bold',serif:true,glow:'rgba(180,20,20,.9)',blur:18}); + text(c,kind==='isshin'?'FINAL EXECUTION':'EXECUTION',427,282,12,'#c9b9a0','center');c.restore();} + if(p.dead&&!g.outcome){c.fillStyle='rgba(30,0,0,.28)';c.fillRect(0,0,854,480);text(c,'DEAD',427,252,92,'#c7261e','center',{weight:'bold',serif:true,glow:'rgba(200,0,0,.8)',blur:20}); + text(c,p.terrorDeath?'Killed by terror · Cannot resurrect':lives>0&&!p.resurrectionLocked?'Press R to resurrect':'Cannot resurrect',427,296,17,'#efe0d1','center');} + // ---- clock, tier and native rate (bottom right) + const tierName=Object.entries(M.tiers).find(([,v])=>Math.abs(v-g.d)<1e-9)?.[0]; + text(c,`${M.hz}Hz`,826,442,13,'#e8c983','right',{weight:'bold'});text(c,(tierName?TIER_NAMES[tierName]+' · ':'d='+(+g.d).toFixed(2)+' · ')+tm.toFixed(1)+'s',826,460,12,'#d6d2c6','right'); + }; + M.renderStatus=ctx=>B.status('sekiro',ctx);M.renderMetrics=ctx=>B.metrics('sekiro',ctx);M.closeRenderer=ctx=>B.close('sekiro',ctx); +})(window); diff --git a/environments/games/web/games/sekiro_remake/game.js b/environments/games/web/games/sekiro_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..cb4aa2d4abdaa34ed332a0c1193703d8955e1f48 --- /dev/null +++ b/environments/games/web/games/sekiro_remake/game.js @@ -0,0 +1,1167 @@ +/* Sekiro: Shadows Die Twice - six boss duels in one deterministic 60 Hz engine (rules sekiro@10). + * sekiro/genichiro Ashina Castle top: two armored bars, then Way of Tomoe (three deathblows) + * sekiro/guardian_ape Sunken Valley watering hole: the white beast, a false Shinobi Execution, the headless apparition + * sekiro/lady_butterfly Hirata Estate audience chamber: threads and kunai, then illusions and spirit butterflies + * sekiro/isshin Silvergrass field: Way of Tomoe Genichiro, then Isshin with sword, spear and matchlock, lightning (four deathblows) + * sekiro/gyoubu Ashina Castle Gate: the mounted Gyoubu, charges past and away, rope spear, hind-leg kick (two deathblows) + * sekiro/demon The burning gate: the Demon of Hatred, fire arms, fireballs, the fire ring and Burn (three deathblows) + * Mechanics follow public guides (Fextralife, BWIKI parameter pages, GameWith/VGR guides). + * The hard tier's vitality / posture / recovery anchors are BWIKI base parameters; move timings, reaches, speeds and the + * player's numbers are calibration values, not extracted FromSoftware data. See SOURCES.md. */ +(function(root){ + 'use strict'; + const N=root.NativeBench,A=(x,z)=>Math.atan2(x,z),dist=(a,b)=>Math.hypot(a.x-b.x,a.z-b.z); + // Public tiers (2026-11-02). Boss magnitudes run geometrically through the easy / normal / hard anchors. + const TIERS={easy:.2,normal:.5,hard:.8}; + function tier(d,[e,n,h]){return d>=TIERS.normal?n*Math.pow(h/n,(d-TIERS.normal)/(TIERS.hard-TIERS.normal)):n*Math.pow(e/n,(TIERS.normal-d)/(TIERS.normal-TIERS.easy));} + const C={playerHP:100,posture:100,move:.075,run:.125,dodge:.2,dodgeFrames:16,dodgeInv:6, + deflectFrames:12,spamFloor:3,spamInterval:24,spamReset:60, + // Sekiro waits about a second before posture recovers; enemy posture has no delay (S04). + playerPostureDelay:60,postureRate:.26,guardRecovery:2.7,deflectChainWindow:40,deflectChainBonus:.06,deflectChainMax:.3, + jumpSpeed:.215,gravity:.0115,sweepHeight:.55,grabJumpHeight:.6, + slashWind:7,slashEnd:25,thrustCharge:25,thrustWind:10,thrustEnd:34, + // Kusabimaru normal cut at Attack Power 1 deals 80 vitality (S13: 80 at AP 1, +20 per point). Posture numbers are + // percent units of Genichiro's armored posture (660, S22): postureUnit converts them to absolute posture. + slashDamage:80,thrustDamage:120,slashPosture:9,thrustPosture:12,blockPosture:7,thrustBlockPosture:9,postureUnit:3.3, + mikiriPosture:25,mikiriStun:30,stompPosture:22,hitStun:20, + deathblowWindow:180,deathblowMissFraction:.75,executionFrames:58,deathblowReach:2.15, + guardBreakStagger:58,safetyRollAfter:14,safetyRollRemain:12, + gourdStock:7,gourdHeal:45,gourdFrames:66,gourdApply:26,resurrectionNodes:2,reviveFrames:50,reviveFraction:.5, + // Status ailments: buildup gauges decay when not fed; a full poison gauge drains vitality for a while, a full + // terror gauge kills outright (S20/S21; rates are calibration). + poisonDecay:.08,poisonTicks:360,poisonDrain:.06,terrorDecay:.12}; + // Posture recovery cut by remaining vitality. Bosses: BWIKI per-boss tables (S22, S16, S18); Sekiro: S04 quartiles. + const REGEN={gen12:[[.8,1],[.6,.5],[.4,.167],[0,.083]],std:[[.8,1],[.6,.6],[.4,.3],[0,.1]],player:[[.75,1],[.5,.66],[.25,.33],[0,.01]]}; + // Small seeds give nearly identical first xorshift draws; scramble the seed so seeds 1..8 differ from the start. + function mixSeed(seed){let x=(seed>>>0)^0x9e3779b9;x=Math.imul(x^(x>>>16),0x85ebca6b);x=Math.imul(x^(x>>>13),0xc2b2ae35);x^=x>>>16;return (x>>>0)||0x6d2b79f5;} + function regenFactor(table,h){for(const [at,f] of REGEN[table])if(h>at||at===0)return f;return 0;} + const H=(t,o={})=>Object.assign({t,type:'slash',reach:2.8,hp:12,posture:15},o); + // One draw per choice; entries listed in w get that relative weight (all 1 = the plain uniform pick). + function pickW(g,list,w={}){const ws=list.map(n=>w[n]??1),total=ws.reduce((a,b)=>a+b,0);let r=N.rand(g)*total;for(let i=0;iH(t,{reach:2.9,hp:i===8?18:10,posture:i===8?25:11,parry:i===8?14:6,push:i===8?.7:0,final:i===8}))}, + jump_slam:{duration:57,hits:[{t:42,type:'slam',reach:2.65,hp:19,posture:23}],whiff:[[42,57]]}, + tomoe_slash:{duration:44,hits:[H(16,{reach:3.0,hp:14,posture:17})]}, + swipe5:{duration:100,hits:[16,30,44,58,74].map(t=>H(t,{reach:2.9,hp:10,posture:12,parry:9})),open:[[86,100]]}, + thrust:{duration:58,perilous:'thrust',hits:[{t:33,type:'thrust',reach:3.4,hp:25,posture:27}],open:[[46,58]]}, + sweep:{duration:61,perilous:'sweep',hits:[{t:34,type:'sweep',reach:3.5,hp:25,posture:29}],open:[[42,61]]}, + grab:{duration:68,perilous:'grab',hits:[{t:34,type:'grab',dodge:true,reach:1.95,hp:34,posture:20}],whiff:[[40,68]]}, + running_grab:{duration:78,perilous:'grab',hits:[{t:48,type:'grab',dodge:true,reach:2.05,hp:36,posture:25}],whiff:[[54,78]]}, + leap_thrust:{duration:67,perilous:'thrust',hits:[{t:40,type:'thrust',reach:3.1,hp:28,posture:30}],whiff:[[48,67]]}, + dive_ready:{duration:G.diveReady,hits:[],next:'leap_thrust'}, + bow:{duration:53,hits:[],shots:[22],open:[[0,53]]}, + bow_roll:{duration:96,hits:[H(70,{hp:14,posture:16})],shots:[20],open:[[0,46]]}, + quick_bow:{duration:36,hits:[],shots:[10],open:[[0,36]]}, + charged_bow:{duration:96,hits:[],shots:[70],heavy:[70],open:[[0,96]]}, + volley:{duration:88,hits:[],shots:[30,38,46,65],open:[[0,88]]}, + lightning_slash:{duration:125,perilous:'lightning',hits:[{t:100,type:'lightning',reach:10,hp:0,posture:0,arc:.42}],open:[[0,100],[104,125]]}, + lightning_sweep:{duration:125,perilous:'lightning',hits:[{t:100,type:'lightning',reach:8.5,hp:0,posture:0,arc:1.7}],open:[[0,100],[104,125]]}, + lightning_bow:{duration:125,perilous:'lightning',hits:[],shots:[96],open:[[0,125]]}, + tomoe_awaken:{duration:72,hits:[],invulnerable:true,next:'leap_thrust'} + }; + const GENICHIRO={moves:GEN_MOVES,radius:.5,height:1.95,kickRange:2.15,names:['Bow-and-Blade Swordsman','Bow-and-Blade Swordsman','Lightning Swordsman'],forms:['genichiro','genichiro','tomoe'], + // [easy, normal, hard] pools, calibrated to the meeting's tier windows with the reference controller. BWIKI base (S22) + // fixes the shape: bars 1-2 HP 1598 / posture 660 / 60 per s (full recovery 11 s), bar 3 x1.6 HP, x1.36 posture, 22.5 s. + anchors:{hp:[170,1129,3768],posture:[371,903,1556],recover:11,tomoeHP:1.6,tomoePosture:1.36,tomoeRecover:22.5,rest:[70,32,20],restStun:[18,11,6],dmg:[.6,.85,1],chase:[.85,1,1.15]}, + tune(d){const a=this.anchors,hp=tier(d,a.hp),posture=tier(d,a.posture); + const armored={hp:Math.round(hp),posture:Math.round(posture),regen:Math.round(posture)/(a.recover*60),table:'gen12'},tp=Math.round(posture*a.tomoePosture); + return {bars:[armored,{...armored},{hp:Math.round(hp*a.tomoeHP),posture:tp,regen:tp/(a.tomoeRecover*60),table:'std'}], + rest:Math.round(tier(d,a.rest)),restStun:Math.round(tier(d,a.restStun)),dmg:tier(d,a.dmg),chase:tier(d,a.chase)};}, + extra:()=>({lightning:false,lastLightningAt:-999,extraShot:0}), + start(g){g.startMove('opening');}, + idle(g){const b=g.boss,p=g.player;g.face(b,p);if(dist(b,p)>2.25)g.advance(.058*g.tune.chase,2.2); + if(p.healTick>0||--b.cooldown<=0)g.startMove(this.choose(g));}, + choose(g){const b=g.boss,p=g.player,d=dist(b,p),tomoe=b.form_id==='tomoe'; + // If idle, he always answers healing: a charged shot (armored) or a sword-dive thrust (Way of Tomoe) (S01). + if(p.healTick>0){g.stats.healPunishes++;g.emit('heal_punish');return tomoe?'dive_ready':'charged_bow';} + const r=N.rand(g); + // Way of Tomoe keeps returning to lightning; the pacing rule is an engineering calibration, not a measured rate. + if(tomoe&&r<(g.t-b.lastLightningAt>G.lightningDue?G.lightningDueChance:G.lightningChance))return ['lightning_slash','lightning_sweep','lightning_bow'][Math.floor(N.rand(g)*3)]; + if(g.t-b.attackedAt<90){const q=N.rand(g);if(q<.3)return 'jump_slam';if(q<.45&&!tomoe)return 'volley';} + if(d>5)return tomoe?(r<.6?'leap_thrust':'volley'):b.healthbar_phase===2?(r<.4?'charged_bow':r<.7?'volley':r<.85?'bow':'bow_roll'):(r<.45?'charged_bow':r<.75?'volley':'bow_roll'); + const list=b.healthbar_phase===1?['slash','double','kick_arrow','passage','jump_slam','grab','thrust','bow_roll','volley']: + b.healthbar_phase===2?['slash','double','kick_arrow','passage','jump_slam','sweep','grab','thrust','bow_roll','volley','bow_roll','bow']: + ['double','passage','swipe5','jump_slam','leap_thrust','running_grab','sweep','thrust','kick_arrow','bow_roll']; + return list[Math.floor(r*list.length)];}, + onStart(g,name){const b=g.boss;b.lightning=name.startsWith('lightning');if(b.lightning)b.lastLightningAt=g.t;b.extraShot=name==='bow_roll'&&N.rand(g)<.5?36:0;}, + followUp(g,move){const b=g.boss; + if(b.chainNext==='thrust_followup')return dist(b,g.player)>G.thrustFollowRange?'quick_bow':'running_grab'; + if(b.chainNext)return b.chainNext; + if(GEN_MOVES[move].next)return GEN_MOVES[move].next; + if(move==='jump_slam')return b.healthbar_phase===1?'thrust':b.healthbar_phase===2?(N.rand(g)=18&&t<80)g.advance(.025*ch,1.6); + if(move==='opening'&&t>=32&&t<58)g.advance(.17,1.9); + if(move==='bow_roll'&&t>=46&&t<62)g.advance(.16,1.8); + if(move==='jump_slam'){b.y=t<42?Math.max(0,Math.sin(Math.PI*N.clamp((t-12)/30,0,1))*2.1):0;if(t>=15&&t<38)g.advance(.17,1.7);} + if(move==='leap_thrust'){b.y=t<40?Math.max(0,Math.sin(Math.PI*N.clamp((t-13)/27,0,1))*1.5):0;if(t>=19&&t<40)g.advanceCommitted(.32,1.1);} + if(move==='running_grab'&&t<46){if(t<35)g.advance(.13*ch,1.1);else g.advanceCommitted(.13,1.1);} + if((move==='grab'||move==='sweep')&&t<18){const side=move==='grab'?-1:1;g.move(b,Math.cos(b.yaw)*.035*side,-Math.sin(b.yaw)*.035*side);} + if(move==='thrust'&&t>=25&&t<=33)g.advanceCommitted(.17,1.15); + if(move==='volley'){b.y=Math.max(0,Math.sin(Math.PI*N.clamp((t-12)/66,0,1))*1.8);if(t<20)g.move(b,-Math.sin(b.yaw)*.05,-Math.cos(b.yaw)*.05);} + // Lightning of Tomoe: grip and crouch, leap, the bolt meets the blade, then the strike ~1.4 s after takeoff (S05). + if(move.startsWith('lightning'))b.y=Math.max(0,Math.sin(Math.PI*N.clamp((t-16)/90,0,1))*2.6); + }, + afterHits(g,move,m,t){const b=g.boss,p=g.player; + for(const hit of m.hits)if(t===hit.t&&hit.type==='lightning')g.hazards.push({type:move==='lightning_sweep'?'lightning_arc':'lightning_line',x:b.x,y:.3,z:b.z,yaw:b.yaw,radius:hit.reach,age:0,life:14}); + for(const shot of m.shots||[])if(t===shot)g.arrow(!!m.heavy?.includes(shot),move==='lightning_bow'); + if(move==='bow_roll'&&b.extraShot&&t===b.extraShot)g.arrow(false,false); + // Floating Passage cancel: a distant player gets a fast bow shot, usually only after he lost a bar (S01). + if(move==='passage'&&t===92&&b.healthbar_phase>=2&&dist(b,p)>4.5){g.stats.passageCancels++;g.emit('passage_cancel');g.startMove('quick_bow');} + }, + // His guard: two blocks, then a perfect parry that starts the Floating Passage string (S01) or a quick counter. + playerHit(g,kind,open){const b=g.boss,p=g.player,busy=b.state==='attack'; + if(open){g.damageBoss(kind==='thrust'?C.thrustDamage:C.slashDamage,(kind==='thrust'?C.thrustPosture:C.slashPosture)*C.postureUnit);g.interruptBoss(C.hitStun);g.fx('cut',b);return;} + b.guardCount++; + if(b.guardCount>=3){b.guardCount=0;g.stats.bossDeflects++;p.posture=Math.min(p.maxPosture,p.posture+4);p.postureDelay=C.playerPostureDelay;g.fx('boss_deflect',b);g.emit('boss_deflect'); + if(!busy||b.moveTick<9)g.startMove(N.rand(g)b.phase<3?[2,3-b.phase]:[1,1] + }; + + /* ---------------------------------------------------------------- Guardian Ape (Sunken Valley watering hole) */ + const P={fakeDeath:330,flinchSmall:44,flinchBig:118,flinchRoll:46,poiseReset:1500,poiseSlash:50,poiseThrust:75,headPosture:2, + smallFlinchPosture:6,bigFlinchPosture:4.5,neckBonus:2,turn:.07,turnHeadless:.055,screamDeflectChance:.45}; + const APE_MOVES={ + // Phase 1: the white beast roams on all fours; nearly all its blows can be guarded, the grabs cannot (S14/S15). + slam_combo:{duration:100,hits:[30,44,58,74].map(t=>H(t,{type:'slam',reach:3.4,arc:1.3,hp:13,posture:16,parry:7})),open:[[84,100]]}, + swipe_leap:{duration:110,hits:[H(26,{reach:3.5,arc:1.5,hp:14,posture:17}),H(42,{reach:3.5,arc:1.5,hp:14,posture:17}),H(84,{type:'slam',reach:3.2,arc:3.2,hp:22,posture:26})],open:[[88,110]]}, + swipe_grab:{duration:86,perilous:'grab',hits:[{t:42,type:'grab',reach:3.8,arc:1.7,hp:34,posture:20}],whiff:[[46,86]]}, + belly_flop:{duration:102,perilous:'grab',hits:[{t:58,type:'grab',noJump:true,reach:2.2,arc:3.2,hp:36,posture:24}],whiff:[[62,102]]}, + back_thrash:{duration:118,hits:[26,38,50,62,74].map(t=>H(t,{type:'slam',reach:3.1,arc:3.2,hp:11,posture:14,parry:6})),open:[[98,118]],head:[[14,98]]}, + fart:{duration:52,hits:[],gas:[22],next:'flee_poo'}, + flee_poo:{duration:134,hits:[],poo:[66],open:[[88,134]]}, + roar:{duration:86,hits:[],open:[[26,86]]}, + bound:{duration:58,hits:[]}, + roll_away:{duration:46,hits:[]}, + // Phase 2: the headless apparition, sword in the right hand and its head in the left (S14, S15). + sword4:{duration:114,hits:[28,46,62,82].map((t,i)=>H(t,{reach:4.6,arc:1.6,hp:15,posture:18,parry:12,window:4,ltr:i===1})),open:[[96,114]]}, + diving_lunge:{duration:126,hits:[H(36,{reach:4.1,arc:1.1,hp:22,posture:24,parry:14,window:4})],open:[[46,114]],neck:[[46,114]]}, + jump_sweep:{duration:74,perilous:'sweep',hits:[{t:54,type:'sweep',reach:4.9,arc:1.8,hp:26,posture:28}],next:'overhead_slam'}, + overhead_slam:{duration:82,hits:[H(56,{type:'slam',reach:4.3,arc:.8,hp:28,posture:30,parry:30,window:8,stun:96})],whiff:[[62,82]]}, + scream_long:{duration:226,perilous:'terror',hits:[],scream:{from:62,to:206,radius:8.5,rate:1.3,drain:.11},open:[[206,226]]}, + scream_short:{duration:102,perilous:'terror',hits:[],scream:{from:20,to:72,radius:6.2,rate:1.6,drain:.12},open:[[74,102]]}, + headless_rise:{duration:140,hits:[],invulnerable:true} + }; + APE_MOVES.rising=APE_MOVES.headless_rise; + const APE={moves:APE_MOVES,radius:1.2,height:3.0,kickRange:2.9,kickAnyHeight:true,names:['Valley Giant Ape','Valley Giant Ape'],forms:['ape','headless'], + // [easy, normal, hard] pools, calibrated like Genichiro's. BWIKI base (S16): HP 3520, posture 1140, 60 per s (19 s), poise + // 400 then 520; the risen apparition gets x1.1 HP and posture. + anchors:{hp:[480,2327,10012],posture:[860,1810,3242],recover:19,poise:[220,300,400],poise2:1.3,rise:1.1,pressure:[.4,1,1],rest:[120,34,22],restStun:[20,12,6],dmg:[.6,.85,1],chase:[.85,1,1.12]}, + tune(d){const a=this.anchors,hp=Math.round(tier(d,a.hp)),posture=Math.round(tier(d,a.posture)),poise=Math.round(tier(d,a.poise)),p2=Math.round(posture*a.rise); + return {bars:[{hp,posture,regen:posture/(a.recover*60),table:'std',poise},{hp:Math.round(hp*a.rise),posture:p2,regen:p2/(a.recover*60),table:'std',poise:Math.round(poise*a.poise2)}],pressure:tier(d,a.pressure), + rest:Math.round(tier(d,a.rest)),restStun:Math.round(tier(d,a.restStun)),dmg:tier(d,a.dmg),chase:tier(d,a.chase)};}, + extra:()=>({poise:0,poiseMax:0,poiseAt:-9999,flinch:0,deadTicks:0,roam:1}), + start(g){const b=g.boss;b.poise=b.poiseMax=g.tune.bars[0].poise;b.state='idle';b.action='idle';b.cooldown=40;}, + // The beast roams around Sekiro on all fours at a middle distance and answers anyone who closes in (S14); the + // headless apparition walks in to sword range. + idle(g){const b=g.boss,p=g.player,d=dist(b,p),head=b.form_id==='headless',to=A(p.x-b.x,p.z-b.z),ch=g.tune.chase; + g.turn(b,to,head?P.turnHeadless:P.turn); + if(head){if(d>3.4)g.advance(.062*ch,3.2);} + else{if(d>5)g.advance(.1*ch,4.6);else{const out=d<3.8?-.05:0,side=b.roam*.06*ch;g.move(b,Math.sin(to)*out+Math.cos(to)*side,Math.cos(to)*out-Math.sin(to)*side);if(room(g,b.x,b.z)a[Math.floor(N.rand(g)*a.length)]; + // An easier tier screams less often (the long blood scream is its deadliest and longest move). + if(b.form_id==='headless'){const w={scream_long:g.tune.pressure}; + if(d>9)return r<.55?'jump_sweep':'diving_lunge'; + if(d>5)return pickW(g,['diving_lunge','jump_sweep','scream_long','sword4'],w); + return pickW(g,['sword4','sword4','overhead_slam','scream_long','jump_sweep','diving_lunge'],w);} + // The fart is often used when Sekiro is behind it, and is always followed by the flight and the poo throw (S14). + const behind=Math.abs(N.angle(A(p.x-b.x,p.z-b.z)-b.yaw))>1.9; + if(behind&&d<5&&r<.6)return 'fart'; + if(d>9)return r<.6?'bound':'belly_flop'; + if(d>6)return pick(['belly_flop','swipe_leap','roar','bound','flee_poo']); + if(d>3.2)return pick(['slam_combo','swipe_leap','belly_flop','swipe_grab','slam_combo','roar']); + return pick(['slam_combo','swipe_leap','swipe_grab','back_thrash','slam_combo','swipe_grab','fart']);}, + onStart(g,name){const b=g.boss,p=g.player;b.aimX=p.x;b.aimZ=p.z;}, + followUp(g,move){const b=g.boss;if(b.chainNext)return b.chainNext;return APE_MOVES[move].next||null;}, + step(g,move,m,t){const b=g.boss,p=g.player,to=A(p.x-b.x,p.z-b.z),ch=g.tune.chase; + const track=(until,rate=.09)=>{if(t=56&&t<84?Math.sin(Math.PI*(t-56)/28)*2.6:0;if(t>=56&&t<84)g.advanceCommitted(.2,1.6);} + if(move==='swipe_grab'){track(30,.08);} + if(move==='belly_flop'){track(20,.12);b.y=t>=20&&t<58?Math.sin(Math.PI*(t-20)/38)*3.6:0;if(t>=20&&t<58)g.toward(b,b.aimX,b.aimZ,.26,.4);} + if(move==='back_thrash'){track(10,.1);} + if(move==='flee_poo'){if(t<40){g.turn(b,to+Math.PI,.2);g.move(b,-Math.sin(to)*.2,-Math.cos(to)*.2);} + else{track(66,.2);b.y=t>=44&&t<80?Math.sin(Math.PI*(t-44)/36)*4.2:0;}} + if(move==='roar'){if(t<20)g.move(b,-Math.sin(to)*.12,-Math.cos(to)*.12);track(26,.1);} + if(move==='roll_away'){if(t<30){const away=A(b.x-p.x,b.z-p.z);g.move(b,Math.sin(away)*.2,Math.cos(away)*.2);}b.y=t<30?Math.abs(Math.sin(Math.PI*t/15))*.8:0;} + if(move==='bound'){track(14,.15);b.y=t>=14&&t<50?Math.sin(Math.PI*(t-14)/36)*3.2:0;if(t>=14&&t<50)g.toward(b,b.aimX,b.aimZ,.28,3.2);} + if(move==='sword4'){track(76,.05);if(t<84)g.advance(.03*ch,3.0);} + if(move==='diving_lunge'){track(18,.1);if(t>=18&&t<40)g.advanceCommitted(.3,1.3);} + if(move==='jump_sweep'){track(10,.12);b.y=t>=6&&t<54?Math.sin(Math.PI*(t-6)/48)*3.6:0;if(t>=6&&t<50)g.toward(b,b.aimX,b.aimZ,.22,2.6);} + if(move==='overhead_slam'){track(40,.06);} + if(m.scream&&t>=m.scream.from&&tb.moveTick>=w[0]&&b.moveTick0||(b.state==='attack'&&(m?.neck||[]).some(w=>b.moveTick>=w[0]&&b.moveTick0)b.neckExposed--; + // A big flinch that ends unbroken resets the ladder; a recorded small flinch lasts until the poise resets (S16). + if(b.flinch===2&&b.state!=='stunned')b.flinch=0; + if(b.flinch&&g.t-b.poiseAt>P.poiseReset)b.flinch=0; + if(g.t-b.poiseAt>P.poiseReset)b.poise=b.poiseMax; + if(b.state!=='dead')return false; + if(--b.deadTicks<=0){g.nextBar();b.form_id='headless';b.source_phase=2;b.poise=b.poiseMax=g.tune.bars[1].poise;b.flinch=0;g.emit('form:headless');g.startMove('headless_rise');} + return true;}, + // The first deathblow decapitates it and shows SHINOBI EXECUTION, a deception: it rises with a hidden bar (S14). + finish(g){const b=g.boss;if(b.phase===2){g.win();return;} + b.state='dead';b.action='fake_death';b.actionTick=0;b.deadTicks=P.fakeDeath;b.hp=0;b.posture=0;g.hazards=[];g.stats.falseExecutions++;g.emit('false_execution');}, + markers:b=>[1,b.state==='dead'?0:1] + }; + + /* ---------------------------------------------------------------- Lady Butterfly (Hirata Estate) */ + const L={hover:3.8,guardReset:90,spell:720,interrupted:240,respawn:24,cooldown:900,runDispel:150,illusions:4,kick:34,hitFlinch:14, + illusionSpeed:.032,butterflySpeed:.105,butterflyTurn:.05,butterflyLaunch:26,butterflyHoming:110,butterflyLife:260,dartSpeed:.2,dartTurn:.03,dartLaunch:12,dartHoming:24,kunaiSpeed:.42}; + const BUT_MOVES={ + // Phase 1: kunai, threads strung between the pillars and an aerial grab (S17, S19). + kunai_throw:{duration:66,hits:[],kunai:[[24,3],[40,3]],open:[[48,66]]}, + three_strike:{duration:84,hits:[H(16,{reach:2.5,hp:9,posture:12}),H(28,{reach:2.5,hp:9,posture:12}),H(54,{type:'slam',reach:2.3,arc:1.6,hp:14,posture:18})],open:[[58,84]]}, + leg_drop:{duration:80,hits:[H(50,{type:'slam',reach:2.1,arc:3.2,hp:16,posture:20})],open:[[56,80]]}, + kunai_dash:{duration:124,hits:[H(54,{reach:2.4,hp:10,posture:13}),H(80,{reach:2.4,hp:10,posture:13})],kunai:[[14,3],[30,3]],whiff:[[86,124]]}, + sweep:{duration:76,perilous:'sweep',hits:[{t:34,type:'sweep',reach:3.0,arc:1.5,hp:20,posture:22},{t:46,type:'sweep',reach:3.0,arc:1.5,hp:20,posture:22}],open:[[52,76]]}, + thread_up:{duration:46,hits:[],air:true}, + thread_hover:{duration:100,hits:[],air:true,kunai:[[22,3],[50,3],[78,3]]}, + thread_dive:{duration:76,hits:[H(26,{reach:2.4,hp:9,posture:12}),H(34,{reach:2.4,hp:9,posture:12}),H(42,{reach:2.4,hp:10,posture:13})],open:[[56,76]]}, + drop_grab:{duration:84,perilous:'grab',hits:[{t:42,type:'grab',noJump:true,reach:2.3,arc:1.5,hp:30,posture:20}],whiff:[[46,84]]}, + counter2:{duration:44,hits:[H(10,{reach:2.5,hp:8,posture:11}),H(22,{reach:2.5,hp:8,posture:11})]}, + deflect_kick:{duration:40,hits:[{t:12,type:'kick',reach:2.2,hp:6,posture:16,push:1.1}]}, + hop_back:{duration:30,hits:[]}, + // Phase 2: illusions of villagers, spirit butterflies and a flurry that ends in a perilous sweep (S17, S19). + illusion:{duration:64,hits:[],summon:[32],open:[[0,16]]}, + dispel:{duration:56,hits:[],dispel:[30],open:[[34,56]],invulnerableUntil:32}, + flurry:{duration:156,perilous:'sweep',perilousFrom:96,hits:[{t:12,type:'kick',reach:2.2,hp:6,posture:14,push:1.3},...[56,66,76,86,96].map(t=>H(t,{reach:2.5,hp:8,posture:10})),{t:122,type:'sweep',reach:3.0,arc:1.6,hp:22,posture:24}],butterflies:[[26,4]],open:[[128,156]]}, + kunai_butterfly:{duration:84,hits:[],butterflies:[[16,4]],kunai:[[32,3],[40,3],[48,3]],open:[[60,84]]}, + waltz:{duration:104,hits:[],air:true,butterflies:[[22,3],[62,3]],kunai:[[42,3],[80,3]]}, + // "Lose yourself in my illusions": she rises from the first deathblow and opens the illusion phase (S17). + rising:{duration:78,hits:[],summon:[60],open:[[62,78]],invulnerableUntil:62} + }; + const BUTTERFLY={moves:BUT_MOVES,radius:.42,height:1.6,kickRange:2.15,names:['Thread Kunoichi','Thread Kunoichi'],forms:['butterfly','illusionist'], + // [easy, normal, hard] pools, calibrated like Genichiro's. BWIKI base (S18): HP 2073, posture 600, 60 per s (10 s), + // recovery cuts 0/40/70/90 %. + anchors:{hp:[340,1201,3593],posture:[380,675,1040],recover:10,spell:[300,540,720],pressure:[.45,1,1],rest:[44,30,18],restStun:[18,11,6],dmg:[.6,.85,1],chase:[.85,1,1.12]}, + tune(d){const a=this.anchors,posture=Math.round(tier(d,a.posture)),bar={hp:Math.round(tier(d,a.hp)),posture,regen:posture/(a.recover*60),table:'std'}; + return {bars:[bar,{...bar}],spell:Math.round(tier(d,a.spell)),pressure:tier(d,a.pressure),rest:Math.round(tier(d,a.rest)),restStun:Math.round(tier(d,a.restStun)),dmg:tier(d,a.dmg),chase:tier(d,a.chase)};}, + extra:()=>({hoverX:0,hoverZ:0,guardAt:-999,counterNext:false,spell:0,dispelDue:false,illusionCooldown:0,spawnTimer:0}), + start(g){const b=g.boss;b.state='idle';b.action='idle';b.cooldown=30;}, + idle(g){const b=g.boss,p=g.player,d=dist(b,p);g.face(b,p);if(b.y>0)b.y=Math.max(0,b.y-.2); + if(d>2.4)g.advance(.07*g.tune.chase,2.3);else if(d<1.6)g.move(b,-Math.sin(b.yaw)*.04,-Math.cos(b.yaw)*.04); + if(b.counterNext){b.counterNext=false;g.startMove('counter2');return;} + if(--b.cooldown<=0)g.startMove(this.choose(g));}, + // An easier tier spends less time on the threads and in the flurry. + choose(g){const b=g.boss,p=g.player,d=dist(b,p),w={thread_up:g.tune.pressure,flurry:g.tune.pressure},pick=a=>pickW(g,a,w); + if(b.form_id==='illusionist'){ + // Kept running, or left alone long enough, she turns the illusions into homing butterflies (S17, S18). + if(b.dispelDue||(b.spell>0&&p.runTicks>=L.runDispel))return 'dispel'; + if(b.spell<=0&&b.illusionCooldown<=0&&!g.minions.some(q=>q.alive))return 'illusion'; + if(d>6)return pick(['kunai_butterfly','thread_up','kunai_dash','leg_drop']); + return pick(['flurry','three_strike','sweep','kunai_butterfly','thread_up','flurry']);} + if(d>6)return pick(['kunai_throw','kunai_dash','thread_up','leg_drop']); + if(d>3)return pick(['kunai_dash','leg_drop','thread_up','sweep','three_strike']); + return pick(['three_strike','sweep','three_strike','kunai_throw','thread_up','leg_drop']);}, + onStart(g,name){const b=g.boss,p=g.player;b.aimX=p.x;b.aimZ=p.z; + if(name==='thread_up'){// a hover point on the threads, away from the pillars, about five units from Sekiro + const a=A(b.x-p.x,b.z-p.z)+(N.rand(g)-.5)*1.2,ar=g.arena;b.hoverX=N.clamp(p.x+Math.sin(a)*5,-ar.halfWidth+2,ar.halfWidth-2);b.hoverZ=N.clamp(p.z+Math.cos(a)*5,-ar.halfDepth+2,ar.halfDepth-2);}}, + followUp(g,move){const b=g.boss; + if(move==='thread_up')return b.form_id==='illusionist'?'waltz':'thread_hover'; + if(move==='thread_hover'||move==='waltz')return N.rand(g)<.6?'thread_dive':'drop_grab'; + return null;}, + step(g,move,m,t){const b=g.boss,p=g.player,ch=g.tune.chase; + const track=until=>{if(t=34&&t<52?Math.sin(Math.PI*(t-34)/18)*1.6:0;} + if(move==='leg_drop'){track(30);b.y=t>=8&&t<50?Math.sin(Math.PI*(t-8)/84)*3.0*(t<29?1:1):0;if(t>=29)b.y=Math.max(0,3.0*(50-t)/21);if(t>=8&&t<50)g.toward(b,b.aimX,b.aimZ,.12,.3);} + if(move==='kunai_dash'){track(40);if((t>=40&&t<52)||(t>=66&&t<78))g.advanceCommitted(.3,1.2);if(t===60){b.aim=A(p.x-b.x,p.z-b.z);b.yaw=b.aim;b.commitDistance=dist(b,p);}} + if(move==='sweep'){track(20);if(t<26)g.advance(.04*ch,1.8);} + if(move==='thread_up'){g.face(b,p);b.y=Math.min(L.hover,L.hover*Math.sin(Math.PI/2*N.clamp((t-6)/30,0,1)));g.toward(b,b.hoverX,b.hoverZ,.16,0);} + if(move==='thread_hover'||move==='waltz'){g.face(b,p);b.y=L.hover;} + if(move==='thread_dive'){track(10);b.y=t<24?L.hover*(1-t/24):0;if(t<26)g.toward(b,b.aimX,b.aimZ,.24,1.2);} + // she tracks Sekiro until she drops (S19: a side step is caught, a retreat straight back as she falls is not) + if(move==='drop_grab'){track(34);b.y=t<26?L.hover:t<40?L.hover*(40-t)/14:0;if(t>=26&&t<42)g.toward(b,b.aimX,b.aimZ,.3,.9);} + if(move==='counter2'){track(16);if(t<20)g.advance(.05,1.6);} + if(move==='deflect_kick'){track(8);} + if(move==='hop_back'){track(4);if(t<20)g.move(b,-Math.sin(b.yaw)*.13,-Math.cos(b.yaw)*.13);b.y=Math.sin(Math.PI*N.clamp(t/20,0,1))*.7;} + if(move==='illusion'||move==='dispel'){g.face(b,p);} + if(move==='rising'){g.face(b,p);b.y=t<52?Math.sin(Math.PI*t/52)*2.4:0;if(t<52)g.toward(b,b.aimX,b.aimZ,.12,0);} + if(move==='flurry'){track(50);if(t>=40&&t<100)g.advance(.06*ch,1.6);} + if(move==='kunai_butterfly'){track(48);} + }, + afterHits(g,move,m,t){const b=g.boss; + for(const [at,n] of m.kunai||[])if(t===at)g.kunai(n); + for(const [at,n] of m.butterflies||[])if(t===at)for(let i=0;i1.2)return; + if(open){if(b.action==='illusion'&&b.state==='attack'){b.illusionCooldown=L.interrupted;g.emit('spell_interrupted');} + g.damageBoss(kind==='thrust'?C.thrustDamage:C.slashDamage,(kind==='thrust'?C.thrustPosture:C.slashPosture)*C.postureUnit);if(!b.deathblowAvailable){g.interruptBoss(L.hitFlinch);b.counterNext=true;}g.fx('cut',b);return;} + if(g.t-b.guardAt>L.guardReset)b.guardCount=0;b.guardAt=g.t;b.guardCount++; + if(b.guardCount>=3){b.guardCount=0;g.stats.bossDeflects++;p.posture=Math.min(p.maxPosture,p.posture+6);p.postureDelay=C.playerPostureDelay;g.fx('boss_deflect',b);g.emit('boss_deflect'); + if(b.state!=='attack'||b.moveTick<8)g.startMove(N.rand(g)<.5?'deflect_kick':'hop_back');} + else{g.stats.bossBlocks++;g.fx('boss_block',b);g.emit('boss_block');g.bossPosture((kind==='thrust'?C.thrustBlockPosture:C.blockPosture)*C.postureUnit);}}, + onDeflect(){}, + special(g){const b=g.boss;if(b.illusionCooldown>0)b.illusionCooldown--; + if(b.spell>0){if(--b.spell===0)b.dispelDue=true;if(g.minions.filter(q=>q.alive).length[1,1] + }; + /* ---------------------------------------------------------------- Isshin, the Sword Saint (silvergrass field) */ + // Way of Tomoe Genichiro (one bar, no Lightning of Tomoe, S29), then Isshin: sword, spear and matchlock, then lightning (S27, S28). + const I={tomoeHP:2556/2240,tomoePosture:750/660,tomoeRecover:25,spearHP:1.27,waveSpeed:.42,bulletSpeed:.6,waveLeak:.35,stompPush:2.2,stompReach:5.5, + mortalChance:.16,passageThrust:.8,lightningChance:.2,lightningDue:420,lightningDueChance:.55,counterThrust:.5,ichimonjiWave:.75,leapThrust:.6,retreatChop:.5,quadThrust:.7}; + const ISSHIN_MOVES={ + // Genichiro's own table (his third phase minus the lightning, S29) plus the black Mortal Blade: run or step through it (S27, S30). + ...Object.fromEntries(['double','passage','swipe5','jump_slam','tomoe_slash','leap_thrust','dive_ready','running_grab','sweep','thrust','kick_arrow','bow_roll','volley','quick_bow','counter','lightning_slash','lightning_sweep'].map(n=>[n,GEN_MOVES[n]])), + mortal_blade:{duration:132,track:50,hits:[{t:62,type:'mortal',reach:7.2,arc:1.5,hp:32,posture:30},{t:96,type:'mortal',reach:7.2,arc:1.5,hp:32,posture:30}],rings:[62,96],open:[[66,90],[108,132]]}, + isshin_emerge:{duration:96,hits:[],invulnerable:true,cinematic:true,next:'cross'}, + // Sword: Ashina Cross, its close-range cancel into a perilous sweep, Ichimonji (a deflect chains the vertical wave), Dragon Flash, the spiral (S27, S28, S30). + cross:{duration:70,hits:[H(36,{reach:3.4,hp:16,posture:18,parry:12}),H(44,{reach:3.4,hp:16,posture:18,parry:12})],adv:[[20,36,.22,1.6]],open:[[56,70]]}, + smack_sweep:{duration:78,perilous:'sweep',perilousFrom:22,hits:[H(14,{reach:2.8,hp:10,posture:14}),{t:46,type:'sweep',reach:4,arc:2,hp:24,posture:26}],open:[[56,78]]}, + ichimonji:{duration:58,hits:[H(26,{type:'slam',reach:3,arc:.9,hp:20,posture:26,parry:15})],open:[[44,58]]}, + dragon_flash:{duration:82,hits:[],waves:[[40,'v'],[54,'v']],open:[[0,24],[64,82]]}, + wind_v:{duration:56,hits:[],waves:[[24,'v']],open:[[34,56]]}, + spiral:{duration:80,hits:[H(40,{ring:true,reach:6.4,arc:3.2,hp:18,posture:22})],rings:[40],open:[[52,80]]}, + combo:{duration:108,hits:[24,42,58,84].map(t=>H(t,{reach:3,hp:12,posture:14,parry:9})),adv:[[0,80,.03,1.7,true]],open:[[96,108]]}, + overhead:{duration:64,hits:[H(30,{type:'slam',reach:3,arc:.9,hp:18,posture:24}),H(46,{reach:2.8})],open:[[54,64]]}, + pose_thrust:{duration:74,perilous:'thrust',track:30,hits:[{t:44,type:'thrust',reach:3.8,hp:26,posture:28}],adv:[[36,44,.2,1.15]],open:[[56,74]]}, + dash_slash:{duration:60,hits:[H(30,{reach:3.2,hp:18,posture:20})],adv:[[10,30,.34,1.6]],open:[[44,60]]}, + // Spear and matchlock: the stomp, Double Projected Force, the leap, the retreating sweep, four shots (the last delayed) into a perilous (S27, S30). + stomp:{duration:82,hits:[H(62,{reach:3.4,arc:3.2,hp:12,posture:14})],stomp:[30],open:[[72,82]]}, + double_disc:{duration:74,hits:[],waves:[[26,'h'],[44,'h']],open:[[54,74]]}, + leap_slam:{duration:66,hits:[H(42,{type:'slam',reach:3.1,hp:22,posture:26})],leap:[14,42,2.4],adv:[[14,42,.2,1.7,true]],whiff:[[46,66]]}, + retreat_sweep:{duration:62,hits:[H(30,{reach:5,arc:1.8,hp:18,posture:20,window:-4})],back:[0,14,.16],open:[[44,62]]}, + quad_shot:{duration:116,track:96,hits:[],gun:[26,40,54,92],back:[0,14,.2],open:[[100,116]]}, + quick_gun:{duration:36,hits:[],gun:[12],open:[[20,36]]}, + spear_thrust:{duration:66,perilous:'thrust',track:24,hits:[{t:36,type:'thrust',reach:4.7,hp:26,posture:28}],adv:[[22,36,.24,1.4]],open:[[48,66]]}, + spear_sweep:{duration:70,perilous:'sweep',hits:[{t:36,type:'sweep',reach:5,arc:2,hp:26,posture:28}],open:[[46,70]]}, + spear_spiral:{duration:90,hits:[H(46,{ring:true,reach:8.5,arc:3.2,hp:20,posture:22})],rings:[46],open:[[58,90]]}, + three_thrust:{duration:92,hits:[22,40,56,74].map(t=>H(t,{reach:3.6,hp:12,posture:14,parry:9})),adv:[[0,70,.03,2,true]],next:'spear_thrust'}, + heavy_chops:{duration:96,hits:[30,60].map(t=>H(t,{type:'slam',reach:3.6,arc:.9,hp:20,posture:30,parry:14})),adv:[[0,40,.03,2,true]],open:[[80,96]]}, + // Lightning: Tomoe's bolt and the double slanted flash join the spear arsenal (S27, S28, S30); the reversal stuns him. + double_flash:{duration:76,hits:[],waves:[[30,'h'],[44,'h']],open:[[54,76]]}, + thunder_chop:{duration:72,hits:[H(42,{type:'slam',reach:3.6,arc:.9,hp:24,posture:30,parry:20,window:-4})],adv:[[0,30,.04,2,true]],open:[[58,72]]} + }; + const ISSHIN={moves:ISSHIN_MOVES,radius:.5,height:1.95,kickRange:2.15,names:['Lightning Swordsman','Old Sword-and-Spear Master','Old Sword-and-Spear Master','Old Sword-and-Spear Master'],forms:['tomoe','isshin_sword','isshin_spear','isshin_lightning'], + // [easy, normal, hard] pools for Isshin's sword bar. BWIKI base (S28, S29): Genichiro 2556 / 750 / 30 per s (25 s), Isshin 2240 / 660 / 60 per s + // (11 s); his spear and lightning bars carry HP x1.27 each. The page leaves stacking open: read as not stacked (engineering choice). + anchors:{hp:[148,700,2500],posture:[330,800,1560],recover:11,rest:[70,32,20],restStun:[18,11,6],dmg:[.6,.85,1],chase:[.85,1,1.15]}, + tune(d){const a=this.anchors,hp=tier(d,a.hp),posture=tier(d,a.posture),bar=(h,x,s,table)=>{const px=Math.round(x);return {hp:Math.round(h),posture:px,regen:px/(s*60),table};}; + return {bars:[bar(hp*I.tomoeHP,posture*I.tomoePosture,I.tomoeRecover,'std'),bar(hp,posture,a.recover,'gen12'),bar(hp*I.spearHP,posture,a.recover,'gen12'),bar(hp*I.spearHP,posture,a.recover,'gen12')], + rest:Math.round(tier(d,a.rest)),restStun:Math.round(tier(d,a.restStun)),dmg:tier(d,a.dmg),chase:tier(d,a.chase)};}, + extra:()=>({lightning:false,lastLightningAt:-999,extraShot:0}), + start(g){g.startMove('mortal_blade');}, + idle(g){const b=g.boss,p=g.player;g.face(b,p);if(dist(b,p)>2.25)g.advance(.058*g.tune.chase,2.2); + if(p.healTick>0||--b.cooldown<=0)g.startMove(this.choose(g));}, + choose(g){const b=g.boss,p=g.player,d=dist(b,p),r=N.rand(g),phase=b.phase,pick=a=>a[Math.floor(N.rand(g)*a.length)]; + // Items and distance both draw the dash or the leap (S27); Genichiro answers healing with his sword dive (S01). + if(p.healTick>0){g.stats.healPunishes++;g.emit('heal_punish');return phase===1?'dive_ready':phase===2?'dash_slash':'leap_slam';} + if(phase===1){if(N.rand(g)5)return r<.6?'leap_thrust':'volley'; + return pick(['double','passage','swipe5','jump_slam','leap_thrust','running_grab','sweep','thrust','kick_arrow','bow_roll']);} + if(phase===4&&N.rand(g)<(g.t-b.lastLightningAt>I.lightningDue?I.lightningDueChance:I.lightningChance))return N.rand(g)<.5?'lightning_slash':'lightning_sweep'; + if(phase===2){if(d>6)return pick(['dash_slash','dragon_flash','wind_v','cross']); + if(d<2.6&&r<.3)return 'smack_sweep'; + return pick(['cross','ichimonji','dragon_flash','spiral','combo','overhead','pose_thrust','smack_sweep','dash_slash']);} + if(d>7)return pick(phase===4?['quad_shot','double_flash','leap_slam','spear_spiral']:['quad_shot','double_disc','leap_slam','spear_spiral']); + const list=['double_disc','leap_slam','quad_shot','spear_thrust','spear_sweep','spear_spiral','three_thrust','heavy_chops','wind_v']; + return pick(phase===4?[...list,'double_flash','thunder_chop']:list);}, + onStart(g,name){GENICHIRO.onStart(g,name);}, + followUp(g,move){const b=g.boss; + if(b.chainNext==='thrust_followup')return dist(b,g.player)>G.thrustFollowRange?'quick_bow':'running_grab'; + if(b.chainNext)return b.chainNext; + const next=ISSHIN_MOVES[move].next;if(next)return next; + if(move==='jump_slam')return 'tomoe_slash'; + if(move==='tomoe_slash')return 'thrust'; + if(move==='passage'&&N.rand(g)=from&&t=m.back[0]&&t=m.leap[0]&&t4.5){g.stats.passageCancels++;g.emit('passage_cancel');g.startMove('quick_bow');} + return;} + for(const [at,kind] of m.waves||[])if(t===at)g.airWave(kind); + for(const at of m.gun||[])if(t===at)g.bullet(); + for(const at of m.rings||[])if(t===at){const reach=m.hits.find(h=>h.t===at)?.reach||6;g.hazards.push({type:move==='mortal_blade'?'mortal_arc':'ring',x:b.x,y:.3,z:b.z,yaw:b.yaw,radius:reach,age:0,life:18});g.emit(move==='mortal_blade'?'mortal_blade':'ring');}}, + // Genichiro: as on the castle top. Isshin's middle stance turns the third cut: two guards, then a plain counter or a pose and a perilous thrust (S28, S30). + playerHit(g,kind,open){const b=g.boss,p=g.player,busy=b.state==='attack'; + if(b.phase===1){GENICHIRO.playerHit(g,kind,open);return;} + // Engineering choice, extrapolated from S28's general note on hyper armor: a cut lands on the gathering bolt but does not stop the leap, so the reversal stays the answer (S27, S30). + if(open){const armored=busy&&b.lightning&&b.moveTick<100;g.damageBoss(kind==='thrust'?C.thrustDamage:C.slashDamage,(kind==='thrust'?C.thrustPosture:C.slashPosture)*C.postureUnit);if(!armored)g.interruptBoss(C.hitStun);g.fx('cut',b);return;} + b.guardCount++; + if(b.guardCount>=3){b.guardCount=0;g.stats.bossDeflects++;p.posture=Math.min(p.maxPosture,p.posture+4);p.postureDelay=C.playerPostureDelay;g.fx('boss_deflect',b);g.emit('boss_deflect'); + // Repeated cuts against the spear draw the retreating sweep (S27). + if(!busy||b.moveTick<9)g.startMove(b.phase>=3?(N.rand(g)b.phase===1?[1,1]:[3,5-b.phase] + }; + /* ---------------------------------------------------------------- Gyoubu Masataka Oniwa (Ashina Castle Gate) */ + // The only mounted boss: no guard, hyper armor until his poise breaks, the horse carries him past and away (S31, S32). There is no + // grappling hook here: after riding off he always wheels and charges back, and his rope spear punishes standing far away. + const O={poiseSlash:50,poiseThrust:75,poiseReset:1500,flinch:44,sharp:.6,upper:3,lower:.7,upperFrom:.6,walk:.09,turn:.05,turnRide:.2,rideOffNext:.6,tripleSweep:.6,flickRide:.7,comboRide:.35,rearAngle:2.4,sideAngle:.6}; + const GYOUBU_MOVES={ + // He talks first and can be cut during it (S31). + intro:{duration:150,hits:[],open:[[0,150]],next:'charge_sweep'}, + // On foot-pace: three cuts, the third staggers him when deflected (S31); the flick from his right flank usually rides off (S31, S32). + combo3:{duration:112,track:20,hits:[H(28,{reach:3.8,arc:1.5,hp:14,posture:16,parry:10}),H(46,{reach:3.8,arc:1.5,hp:12,posture:20}),H(84,{type:'slam',reach:4,arc:1.3,hp:18,posture:22,parry:22,stun:54})],open:[[96,112]]}, + flick:{duration:52,track:10,hits:[H(20,{reach:3.4,arc:1.6,hp:12,posture:16})],open:[[34,52]]}, + thrust_near:{duration:70,perilous:'thrust',track:28,hits:[{t:40,type:'thrust',reach:4.6,hp:24,posture:26}],open:[[52,70]]}, + horse_kick:{duration:54,track:0,hits:[{t:22,type:'kick',rear:true,reach:3.2,arc:1.2,hp:16,posture:18,stagger:20}],open:[[34,54]]}, + // Charges ride through: speed is set when the horse commits so it arrives at the contact tick, then carries on past (S31). + charge_sweep:{duration:96,perilous:'sweep',track:20,ride:[20,76,.3],arrive:52,hits:[{t:52,type:'sweep',reach:4.4,arc:2.2,hp:24,posture:26}],next:'wheel'}, + figure8:{duration:100,track:18,ride:[18,80,.28],arrive:50,hits:[42,50,58].map(t=>H(t,{reach:4,arc:1.8,hp:11,posture:14,parry:8,window:-3})),next:'wheel'}, + triple_charge:{duration:96,track:18,ride:[18,76,.28],arrive:54,hits:[44,54,64].map(t=>H(t,{reach:4,arc:1.8,hp:12,posture:22,parry:9}))}, + late_charge:{duration:92,track:18,ride:[18,72,.28],arrive:46,hits:[H(58,{reach:4.2,arc:3.2,hp:14,posture:18,parry:12})],next:'wheel'}, + // The horse turns round after a pass: this is the opening that closing in with the hook gives in the original. + wheel:{duration:64,track:64,trot:[18,64,.06],hits:[],open:[[0,64]]}, + turn_about:{duration:26,track:26,hits:[]}, + ride_off:{duration:50,track:0,away:[0,44,.3],hits:[]}, + gallop:{duration:40,track:40,chaseAt:.32,chaseTo:9,hits:[]}, + jump_attack:{duration:96,track:12,leap:[12,50,3.2],hits:[H(50,{type:'slam',reach:3.6,arc:1.6,hp:18,posture:22,parry:24}),H(68,{type:'slam',reach:3.6,arc:1.6,hp:18,posture:22,parry:24})],open:[[82,96]]}, + // The spearhead on its rope: three wide circles that can be guarded or deflected, and a line that can only be deflected (S31, S34). + rope_sweep:{duration:122,track:100,hits:[40,68,96].map(t=>H(t,{reach:9.5,arc:3.2,hp:12,posture:16,parry:11})),rings:[40,68,96],open:[[106,122]]}, + rope_thrust:{duration:78,perilous:'thrust',track:36,hits:[{t:44,type:'rope',noBlock:true,reach:12,arc:.3,hp:22,posture:24,parry:18}],line:[44],open:[[56,78]]}, + rising:{duration:1,hits:[]} + }; + const GYOUBU={moves:GYOUBU_MOVES,radius:1,height:2.9,kickRange:2.6,kickAnyHeight:true,names:['Mounted Spear General','Mounted Spear General'],forms:['gyoubu','gyoubu'], + // [easy, normal, hard] pools, calibrated to the windows. BWIKI base (S32): HP 2552, posture 660, 30 per s (22 s), total poise 360, reset 25 s. No source gives a difference between his two bars. + anchors:{hp:[650,1800,6500],posture:[1200,2000,2400],recover:22,poise:[220,300,360],rest:[90,32,20],restStun:[18,11,6],dmg:[.6,.85,1],chase:[.85,1,1.15]}, + tune(d){const a=this.anchors,hp=Math.round(tier(d,a.hp)),posture=Math.round(tier(d,a.posture)),poise=Math.round(tier(d,a.poise)),bar={hp,posture,regen:posture/(a.recover*60),table:'std',poise}; + return {bars:[bar,{...bar}],rest:Math.round(tier(d,a.rest)),restStun:Math.round(tier(d,a.restStun)),dmg:tier(d,a.dmg),chase:tier(d,a.chase)};}, + extra:()=>({poise:0,poiseMax:0,poiseAt:-9999,rideX:0,rideZ:0}), + start(g){const b=g.boss;b.poise=b.poiseMax=g.tune.bars[0].poise;g.startMove('intro');}, + idle(g){const b=g.boss,p=g.player;g.turn(b,A(p.x-b.x,p.z-b.z),O.turn);if(dist(b,p)>3.4)g.advance(O.walk*g.tune.chase,3.2); + if(p.healTick>0||--b.cooldown<=0)g.startMove(this.choose(g));}, + // Right flank: the spear hand; left flank: he prefers to turn; directly behind: the hind legs (S32). + choose(g){const b=g.boss,p=g.player,d=dist(b,p),rel=N.angle(A(p.x-b.x,p.z-b.z)-b.yaw),pick=a=>a[Math.floor(N.rand(g)*a.length)]; + if(p.healTick>0){g.stats.healPunishes++;g.emit('heal_punish');return d>6?'rope_thrust':'triple_charge';} + if(d>9)return pick(['rope_sweep','rope_thrust','gallop']); + if(d>5)return pick(['triple_charge','figure8','late_charge','jump_attack','rope_sweep','rope_thrust','charge_sweep']); + if(Math.abs(rel)>O.rearAngle)return 'horse_kick'; + if(rel>O.sideAngle)return 'turn_about'; + return pick(rel<-O.sideAngle?['combo3','flick','thrust_near','flick','ride_off']:['combo3','thrust_near','jump_attack','ride_off','ride_off']);}, + onStart(g,name){g.boss.lightning=false;}, + followUp(g,move){const b=g.boss;if(b.chainNext)return b.chainNext;const next=GYOUBU_MOVES[move].next;if(next)return next; + if(move==='triple_charge')return N.rand(g){const r=N.rand(g);return r<.4?'charge_sweep':r<.7?'triple_charge':r<.85?'figure8':'late_charge';}; + if(move==='ride_off'){if(N.rand(g)>=O.rideOffNext)return N.rand(g)<.5?'rope_sweep':'rope_thrust';return dist(b,g.player)>12?'gallop':charge();} + if(move==='gallop')return dist(b,g.player)>12?'gallop':charge(); + if(move==='turn_about'){const r=N.rand(g);return r<.4?'combo3':r<.7?'thrust_near':'flick';} + if(move==='combo3'&&N.rand(g)=from&&t=from)g.turn(b,b.aim,O.turnRide);} + if(m.away&&t>=m.away[0]&&t=m.trot[0]&&t=a&&t=a&&t=32&&t<40)g.advanceCommitted(.2,2);}, + afterHits(g,move,m,t){const b=g.boss; + for(const at of m.rings||[])if(t===at){g.hazards.push({type:'ring',x:b.x,y:.3,z:b.z,yaw:b.yaw,radius:9.5,age:0,life:18});g.emit('rope_sweep');} + for(const at of m.line||[])if(t===at){g.hazards.push({type:'rope_line',x:b.x,y:1.9,z:b.z,yaw:b.aim,radius:12,age:0,life:12});g.emit('rope_thrust');}}, + // He cannot guard and hyper armor carries his attacks through; only a broken poise staggers him (S32). Cuts above the waist + // take x3 posture, the horse and his legs x0.7, and the blade takes x0.6 vitality (S32). + playerHit(g,kind){const b=g.boss,p=g.player,part=p.y>O.upperFrom?O.upper:O.lower; + g.damageBoss((kind==='thrust'?C.thrustDamage:C.slashDamage)*O.sharp,(kind==='thrust'?C.thrustPosture:C.slashPosture)*C.postureUnit*part);g.fx('cut',b);if(b.deathblowAvailable||b.hp<=0)return; + if(b.action==='intro'&&b.state==='attack'){g.emit('intro_interrupted');g.startMove('charge_sweep');return;} + b.poise-=kind==='thrust'?O.poiseThrust:O.poiseSlash;b.poiseAt=g.t; + if(b.poise<=0){b.poise=b.poiseMax;g.stats.flinches++;g.stagger('stagger',O.flinch);g.emit('flinch_small');}}, + onDeflect(g,hit){const b=g.boss;if(hit.stun&&b.state==='attack'){g.stagger('stagger',hit.stun);g.emit('combo_staggered');}}, + special(g){const b=g.boss;if(g.t-b.poiseAt>O.poiseReset)b.poise=b.poiseMax;return false;}, + finish(g){const b=g.boss;if(b.phase===2){g.win();return;} + g.nextBar();b.poise=b.poiseMax=g.tune.bars[1].poise;b.source_phase=2;b.state='stunned';b.stun=G.riseOpen;b.action='rising';b.actionTick=0;}, + markers:b=>[2,3-b.phase] + }; + /* ---------------------------------------------------------------- Demon of Hatred (Ashina Castle Gate, in flames) */ + // Three bars, no guard, hyper armor until its poise breaks; most blows miss the space under its belly (S37, S39). Fire arms cannot be + // deflected and guarding them still builds Burn, which drains vitality and stops posture recovery (S38, S39). Timings are calibration values. + const D={poiseSlash:50,poiseThrust:75,poiseReset:1500,flinch:40,turn:.045,walk:.06,belly:2.05,rise3:80, + burnDecay:.15,burnTicks:300,burnDrain:.05,fireLeak:.3,fireRate:1.4,ringRadius:7.5,ringWidth:.55,ringLife:480,ringBurn:30,ringPush:1.4, + lobFlight:52,lobGravity:.012,lobBlast:1.5,homingSpeed:.2,homingTurn:.075,homingClimb:.07,homingFor:66,homingFall:.006,shotSpeed:.34,waveSpeed:.36, + doubleCharge:.75,fireSweep:.5,secondVolley:.35,headbutt2:.3,chargeRanged:.55,burstRadius:5,burstPush:2.5}; + const FIRE=o=>H(o.t,Object.assign({noDeflect:true,burn:24,leak:D.fireLeak,reach:4.3,arc:1.5,inner:D.belly,hp:15,posture:14},o)); + const DEMON_MOVES={ + arm_swing:{duration:72,track:24,hits:[H(32,{reach:4.3,arc:1.5,inner:D.belly,hp:14,posture:16,parry:12})],open:[[52,72]]}, + // Right foot held up about a second (S36); both feet on his left (S36), weaker than the single stomp (S39). + stomp:{duration:84,track:30,hits:[H(50,{type:'slam',reach:3.2,arc:2.2,hp:18,posture:20,parry:16})],open:[[64,84]]}, + double_stomp:{duration:100,track:24,hits:[40,66].map(t=>H(t,{type:'slam',reach:3.2,arc:2.4,hp:13,posture:15,parry:12})),open:[[80,100]]}, + headbutt:{duration:76,track:30,hits:[H(42,{type:'slam',reach:4.6,arc:.75,inner:D.belly,hp:20,posture:22,parry:16})],open:[[56,76]]}, + // Fire arm twice, a stomp, the fire arm again (S39). + fire_combo:{duration:154,track:20,hits:[FIRE({t:30}),FIRE({t:52}),H(90,{type:'slam',reach:3.2,arc:2.2,hp:15,posture:17,parry:13}),FIRE({t:124,hp:17})],open:[[138,154]]}, + fire_throw:{duration:92,track:30,shots:[34,58],hits:[],open:[[70,92]]}, + // Fireballs lobbed with each wave of the hands, the last with the last wave (S36). + fireballs:{duration:124,track:96,lobs:[40,52,64,76,98],hits:[],open:[[0,30],[104,124]]}, + whip_slam:{duration:104,track:40,hits:[FIRE({t:58,type:'slam',reach:12.5,arc:.15,inner:0,hp:18,posture:18,burn:30})],trail:58,open:[[70,104]]}, + // Unblockable: run, or be in the air as it lands; about a second open after landing, in place of the grappling hook (S36, S39). + blast_leap:{duration:154,track:50,leap:[50,82,3.6],hits:[{t:82,type:'blast',reach:6,arc:Math.PI,hp:28,posture:30,burn:45,push:2.4}],open:[[96,154]]}, + charge:{duration:88,perilous:'sweep',track:30,ride:[30,78,.3],arrive:54,hits:[{t:54,type:'sweep',reach:3.6,arc:1.4,hp:24,posture:24}]}, + charge_back:{duration:76,perilous:'sweep',track:18,ride:[18,66,.3],arrive:42,hits:[{t:42,type:'sweep',reach:3.6,arc:1.4,hp:24,posture:24}]}, + fire_sweep:{duration:74,perilous:'sweep',track:26,hits:[{t:38,type:'sweep',reach:4.4,arc:1.7,hp:18,posture:20,burn:30}],open:[[52,74]]}, + kick_wave:{duration:92,track:36,waves:[46],hits:[],open:[[60,92]]}, + // Homing fireballs; the stomp and pose at the end is the opening (S36). + homing:{duration:164,track:90,homing:[34,44,54,64,74,84],hits:[],open:[[124,164]]}, + // Phase 3 opens with the fire ring, then three whip swings: jump the low one, stay down under the high one, get behind the last (S36, S39). + fire_ring:{duration:196,perilous:'sweep',track:150,ringAt:40,hits:[FIRE({t:84,type:'sweep',reach:6,arc:Math.PI,inner:0,burn:26,hp:16,posture:18}),FIRE({t:128,onlyAir:true,reach:6,arc:Math.PI,inner:0,burn:26,hp:16,posture:18}),FIRE({t:166,type:'slam',reach:5.5,arc:1.0,inner:0,burn:26,hp:18,posture:20})],open:[[178,196]]}, + turn_about:{duration:30,track:30,hits:[]}, + // After the first deathblow: crouched and immune, a small blast that pushes without damage, then a leap back (S36). + crouch:{duration:150,invulnerable:true,hits:[],burst:140,next:'leap_back'}, + leap_back:{duration:56,track:0,back:[24,48,.18],hits:[],open:[[0,26]]}, + rising:{duration:1,hits:[]} + }; + const DEMON={moves:DEMON_MOVES,radius:1.1,height:4.4,kickRange:3.0,kickAnyHeight:true,names:['Flame Behemoth','Flame Behemoth','Flame Behemoth'],forms:['demon','demon','demon'], + // [easy, normal, hard] per-bar pools, calibrated to the windows. BWIKI base (S37): HP 3195, posture 1050, 30 per s (35 s), poise 640, reset 25 s. + // No source gives a per-bar difference, so the three bars are equal. + anchors:{hp:[600,1600,4200],posture:[1200,2000,3200],recover:35,poise:[400,520,640],rest:[80,34,20],restStun:[18,11,6],dmg:[.6,.85,1],chase:[.85,1,1.1]}, + tune(d){const a=this.anchors,hp=Math.round(tier(d,a.hp)),posture=Math.round(tier(d,a.posture)),poise=Math.round(tier(d,a.poise)),bar={hp,posture,regen:posture/(a.recover*60),table:'std',poise}; + return {bars:[bar,{...bar},{...bar}],rest:Math.round(tier(d,a.rest)),restStun:Math.round(tier(d,a.restStun)),dmg:tier(d,a.dmg),chase:tier(d,a.chase)};}, + extra:()=>({poise:0,poiseMax:0,poiseAt:-9999,rideX:0,rideZ:0,leapSpeed:0,ringDue:false,waveDue:false,repeat:0,lastMove:''}), + playerExtra:()=>({burn:0,burning:0,burnFed:false}),statsExtra:()=>({burns:0}), + start(g){const b=g.boss;b.poise=b.poiseMax=g.tune.bars[0].poise;b.state='idle';b.action='idle';b.cooldown=40;}, + idle(g){const b=g.boss,p=g.player;g.turn(b,A(p.x-b.x,p.z-b.z),D.turn);if(dist(b,p)>3.6)g.advance(D.walk*g.tune.chase,3.4); + if(p.healTick>0||--b.cooldown<=0)g.startMove(this.choose(g));}, + // Negative relative angle = his right flank (same sign as Gyoubu's). + choose(g){const b=g.boss,p=g.player,d=dist(b,p),rel=N.angle(A(p.x-b.x,p.z-b.z)-b.yaw),ph=b.phase,pick=a=>a[Math.floor(N.rand(g)*a.length)]; + if(b.ringDue)return 'fire_ring'; + if(b.waveDue){b.waveDue=false;if(d>6)return 'kick_wave';} + if(p.healTick>0){g.stats.healPunishes++;g.emit('heal_punish');return d>6?'fireballs':'charge';} + if(d>9)return pick(ph>=2?['fireballs','whip_slam','charge','kick_wave','homing']:['fireballs','whip_slam','charge']); + if(d>5)return pick(ph>=2?['fire_throw','charge','whip_slam','blast_leap','homing','kick_wave']:['fire_throw','charge','whip_slam','blast_leap']); + if(Math.abs(rel)>2.3)return N.rand(g)<.5?'turn_about':'blast_leap'; + if(d.6)return pick(['double_stomp','arm_swing','fire_combo']); + return pick(['headbutt','arm_swing','fire_combo','charge']);}, + onStart(g,name){const b=g.boss;b.lightning=false;b.repeat=name===b.lastMove?b.repeat+1:1;b.lastMove=name;}, + followUp(g,move){const b=g.boss,d=dist(b,g.player),next=DEMON_MOVES[move].next,pick=a=>a[Math.floor(N.rand(g)*a.length)];if(next)return next; + if(move==='charge'&&b.phase===3&&N.rand(g)=2?['fireballs','whip_slam','fire_throw','homing','kick_wave']:['fireballs','whip_slam','fire_throw']);return null;} + if(move==='fireballs'&&b.repeat<2&&d>6&&N.rand(g)=from&&t=a&&t=a&&t=m.back[0]&&t=2; + for(let r=2.5;r<=12.5;r+=2)for(const s of wide?[-1.6,0,1.6]:[0])g.hazards.push({type:'fire',x:b.x+Math.sin(a)*r+Math.cos(a)*s,y:0,z:b.z+Math.cos(a)*r-Math.sin(a)*s,radius:1,age:0,life:150,rate:D.fireRate});g.emit('fire_trail');}, + playerHit(g,kind){const b=g.boss; + g.damageBoss(kind==='thrust'?C.thrustDamage:C.slashDamage,(kind==='thrust'?C.thrustPosture:C.slashPosture)*C.postureUnit);g.fx('cut',b);if(b.deathblowAvailable||b.hp<=0)return; + b.poise-=kind==='thrust'?D.poiseThrust:D.poiseSlash;b.poiseAt=g.t; + if(b.poise<=0){b.poise=b.poiseMax;g.stats.flinches++;g.stagger('stagger',D.flinch);g.emit('flinch_small');}}, + onDeflect(){}, + special(g){const b=g.boss;if(g.t-b.poiseAt>D.poiseReset)b.poise=b.poiseMax;return false;}, + finish(g){const b=g.boss;if(b.phase===3){g.win();return;} + g.nextBar();b.poise=b.poiseMax=g.tune.bars[b.phase-1].poise;b.source_phase=b.phase; + if(b.phase===2){b.waveDue=true;g.startMove('crouch');} + else{b.ringDue=true;b.state='stunned';b.stun=D.rise3;b.action='rising';b.actionTick=0;}}, + markers:b=>[3,4-b.phase] + }; + const KINDS={genichiro:GENICHIRO,ape:APE,butterfly:BUTTERFLY,isshin:ISSHIN,gyoubu:GYOUBU,demon:DEMON}; + const CASES={ + 'sekiro/genichiro':{kind:'genichiro',name:'Bow-and-Blade Swordsman · Castle rooftop (three deathblows)',arena:{shape:'rect',halfWidth:8,halfDepth:6,pillars:[]},player:[0,4.2],boss:[0,-3.6]}, + 'sekiro/guardian_ape':{kind:'ape',name:'Guardian Ape · Valley pool (feigned death and second phase)',arena:{shape:'circle',radius:14.5,pillars:[]},player:[0,6.5],boss:[0,-5]}, + 'sekiro/lady_butterfly':{kind:'butterfly',name:'Thread-Wielding Shinobi · Old estate courtyard (threads and illusions)',arena:{shape:'rect',halfWidth:9.5,halfDepth:7.5,pillars:[-6.6,-2.2,2.2,6.6].flatMap(x=>[{x,z:-4.6,r:.42},{x,z:4.6,r:.42}])},player:[0,3.2],boss:[0,-3.2]}, + 'sekiro/isshin':{kind:'isshin',name:'Old Sword-and-Spear Master · Pampas field (Lightning Swordsman and three master phases)',arena:{shape:'circle',radius:13,pillars:[]},player:[0,4.5],boss:[0,-4.5]}, + 'sekiro/gyoubu':{kind:'gyoubu',name:'Mounted Spear General · Castle gate (charges and rope spear)',arena:{shape:'circle',radius:19,pillars:[]},player:[0,6],boss:[0,-6]}, + 'sekiro/demon':{kind:'demon',name:'Flame Behemoth · Burning castle gate (fire and burn)',arena:{shape:'circle',radius:17,pillars:[]},player:[0,6.5],boss:[0,-6.5]} + }; + + const M=root.SekiroGame={id:'sekiro_remake',version:'sekiro@12',hz:60,maxSeconds:300,dimension:'3d',renderer:'webgl-boss3d', + title:'Sekiro · Shadows Die Twice',tiers:TIERS,cases:Object.entries(CASES).map(([id,c])=>({id,name:c.name})), + tuning:C,genichiro:G,ape:P,butterfly:L,moves:GEN_MOVES,isshin:I,gyoubu:O,demon:D,bosses:{genichiro:GENICHIRO,ape:APE,butterfly:BUTTERFLY,isshin:ISSHIN,gyoubu:GYOUBU,demon:DEMON},caseKinds:Object.fromEntries(Object.entries(CASES).map(([id,c])=>[id,c.kind])), + controls:{'W A S D':'Move relative to the camera; there is no stamina bar. Hold Shift to sprint','mouse dx':'Turn the free camera with horizontal mouse movement. After pressing E to lock on, the camera tracks the boss and horizontal mouse movement no longer turns it', + 'J / LMB':'Tap to slash or hold to charge a thrust. When the red marker appears nearby, press attack again for a deathblow','K / RMB':'Hold to block; press just before impact to deflect. Repeated presses shorten the deflect window', + 'Shift':'Press to dodge. Dodge toward a perilous thrust to counter it; dodge sideways or backward to escape a perilous grab','Space':'Jump over a perilous low sweep, then press jump again near the enemy to kick off them', + 'Q':'Healing gourd (the Bow-and-Blade Swordsman always punishes healing while idle)','E':'Toggle lock-on (off at the start)','R':'Resurrect after death (subject to resurrection nodes and seals; terror deaths cannot be reversed)', + 'Airborne J / LMB':'Lightning reversal: catch lightning in the air, then attack again before landing to send it back','Posture broken':'Press Shift or Space during stagger to recover sooner', + 'Status':'Poison builds from gas and dung, then drains health. Terror builds from the ape’s phase-two scream and kills at full gauge; move away to avoid it','Illusions':'The shinobi’s summoned illusions vanish after one hit. Homing butterflies pursue you; pillars can block them','Mounted Spear General':'The mounted general does not block. Hits land but interrupt him only when his poise breaks. Jumping slashes to his upper body deal more posture damage. He turns and charges back after riding away (there is no grappling rope); standing directly behind the horse risks a kick','Flame Behemoth':'The behemoth does not block and staggers only when its poise breaks. Staying under its belly avoids most moves. Its flaming arm cannot be deflected; blocking reduces damage but builds burn. Full burn drains health and prevents posture recovery. Jump over perilous charges and fire-ring sweeps. Run from the explosive leap or be airborne at impact. The phase-three fire ring knocks you back and burns you','Old Sword-and-Spear Master':'Red-blade ranged slashes cannot be blocked; dodge or run away. Spirit blades chip through blocks, while deflecting avoids posture damage; jumping and sidestepping also work. Blocking bullets from the spear phase costs heavy posture. A four-shot volley is always followed by a perilous attack'}}; + function newBody(x,z,hp,r){return {x,y:0,z,yaw:Math.PI,hp,maxHp:hp,r,posture:0,maxPosture:C.posture,postureDelay:0,action:'idle',actionTick:0,flash:0,hurt:0};} + function openAt(m,tick,connected=true){const inside=w=>tick>=w[0]&&ticks+b.hp,0);this.nextMinion=1; + this.stats={moves:{},deflects:0,blocks:0,guardBreaks:0,safetyRolls:0,mikiri:0,sweepJumps:0,stomps:0,grabEscapes:0, + lightningReversals:0,lightningCatches:0,lightningFailures:0,deathblows:0,resurrections:0,deaths:0,gourdsUsed:0,healsApplied:0, + healPunishes:0,passageOpenings:0,passageCancels:0,healthHits:0,bossDeflects:0,bossBlocks:0,playerAttacks:0,perilousFailures:0,playerHits:0, + postureBreaks:0,vitalityBreaks:0,poisoned:0,terrorDeaths:0,flinches:0,apeRolls:0,neckOpenings:0,falseExecutions:0,illusionsSummoned:0,illusionsKilled:0,butterflies:0,butterflyHits:0,pillarBlocks:0,...K.statsExtra?.()}; + K.start(this); + } + get K(){return KINDS[this.kind];} + get moves(){return KINDS[this.kind].moves;} + state(){return N.copy(this);} + emit(name){this.events.push(name);} + fx(type,at,life=15){this.effects.push({type,x:at.x,y:(at.y||0)+.9,z:at.z,life,maxLife:life});} + face(o,target){o.yaw=A(target.x-o.x,target.z-o.z);} + turn(o,yaw,rate){o.yaw=N.angle(o.yaw+N.clamp(N.angle(yaw-o.yaw),-rate,rate));} + confine(o){const a=this.arena; + if(a.shape==='circle'){const r=Math.hypot(o.x,o.z),lim=a.radius-o.r;if(r>lim){o.x*=lim/r;o.z*=lim/r;}} + else{o.x=N.clamp(o.x,-a.halfWidth+o.r,a.halfWidth-o.r);o.z=N.clamp(o.z,-a.halfDepth+o.r,a.halfDepth-o.r);} + for(const q of a.pillars){const dx=o.x-q.x,dz=o.z-q.z,d=Math.hypot(dx,dz),min=q.r+o.r;if(d1e-9?dx/d:1,nz=d>1e-9?dz/d:0;o.x=q.x+nx*min;o.z=q.z+nz*min;}}} + move(o,dx,dz){o.x+=dx;o.z+=dz;this.confine(o);} + // Steer around a pillar standing in the straight line to the target, so no boss can stall behind one. + heading(o,tx,tz){let a=A(tx-o.x,tz-o.z);const far=Math.hypot(tx-o.x,tz-o.z); + for(const q of this.arena.pillars){const qx=q.x-o.x,qz=q.z-o.z,along=qx*Math.sin(a)+qz*Math.cos(a),side=qx*Math.cos(a)-qz*Math.sin(a); + if(along>0&&along1e-3?-1:1,tx2=-k*vz/len,tz2=k*vx/len;a=A(tx2*.8+Math.sin(a)*.4,tz2*.8+Math.cos(a)*.4);break;}} + return a;} + toward(o,tx,tz,speed,min){const d=Math.hypot(tx-o.x,tz-o.z);if(d<=min)return;const a=this.heading(o,tx,tz),s=Math.min(speed,d-min);this.move(o,Math.sin(a)*s,Math.cos(a)*s);} + advance(speed,min=.9){const b=this.boss,p=this.player;this.toward(b,p.x,p.z,speed,min+(b.r-.5));} + advanceCommitted(speed,min=.9){const b=this.boss,travel=Math.min(speed,Math.max(0,b.commitDistance-min-(b.r-.5))); + this.move(b,Math.sin(b.aim)*travel,Math.cos(b.aim)*travel);b.commitDistance=Math.max(0,b.commitDistance-travel);} + postureFactor(o){const h=o.hp/o.maxHp;return o===this.boss?regenFactor(this.tune.bars[this.boss.phase-1].table,h):regenFactor('player',h);} + recoverPosture(o,boost=1){if(o.postureDelay>0||o.burning>0)return;const rate=o===this.boss?this.tune.bars[this.boss.phase-1].regen:C.postureRate;o.posture=Math.max(0,o.posture-rate*this.postureFactor(o)*boost);} + setPlayerAction(action){const p=this.player;if(p.action!==action){p.action=action;p.actionTick=0;}} + dodgeToward(){const p=this.player,b=this.boss,a=A(b.x-p.x,b.z-p.z);return p.dodgeX*Math.sin(a)+p.dodgeZ*Math.cos(a);} + startMove(name){ + const b=this.boss,m=this.moves[name],p=this.player;if(!m)throw Error('Unknown move '+name); + b.state='attack';b.action=name;b.actionTick=0;b.moveTick=0;b.moveDuration=m.duration;b.perilous=m.perilous||null;b.chainNext=null;b.connected=false; + b.telegraph=m.perilousFrom?null:b.perilous;b.aim=A(p.x-b.x,p.z-b.z);if(this.kind!=='ape'&&this.kind!=='gyoubu'&&this.kind!=='demon')b.yaw=b.aim;b.commitDistance=dist(p,b); + this.K.onStart?.(this,name);this.stats.moves[name]=(this.stats.moves[name]||0)+1;this.emit('move:'+name); + } + stagger(action,ticks){const b=this.boss;b.state='stunned';b.stun=ticks;b.action=action;b.actionTick=0;b.perilous=null;b.telegraph=null;b.lightning=false;b.chainNext=null;b.y=0;} + interruptBoss(ticks){const b=this.boss;if(b.deathblowAvailable||b.executing||b.state==='dead')return;b.state='stunned';b.stun=Math.max(b.stun,ticks);b.action='stagger';b.actionTick=0;b.perilous=null;b.telegraph=null;b.lightning=false;b.chainNext=null;} + // Apparent posture cap: the beast's posture cannot be broken by deflection alone in its first life (S16). + bossPosture(amount,deflect=false){const b=this.boss;if(b.deathblowAvailable||b.executing||b.state==='dead')return; + b.posture=Math.min(b.maxPosture,b.posture+amount);b.postureDelay=0; + if(deflect&&this.kind==='ape'&&b.form_id==='ape'&&b.posture>=b.maxPosture){b.posture=b.maxPosture-1;return;} + if(b.posture>=b.maxPosture)this.breakBoss();} + damageBoss(amount,posture=0){const b=this.boss;if(b.deathblowAvailable||b.executing||b.state==='dead')return;b.hp=Math.max(0,b.hp-amount);b.flash=8;this.stats.healthHits++;this.emit('boss_health_hit'); + if(b.hp<=0)this.breakBoss();else this.bossPosture(posture);} + breakBoss(){const b=this.boss;if(b.executing||b.deathblowAvailable)return;if(b.hp<=0)this.stats.vitalityBreaks++;else this.stats.postureBreaks++;b.deathblowAvailable=true;b.deathblow=b.hp===0?-1:C.deathblowWindow;b.state='deathblow';b.action='posture_break';b.actionTick=0;b.perilous=null;b.telegraph=null;b.lightning=false;b.chainNext=null;b.neckExposed=0;this.emit('deathblow_available');} + execute(){ + const b=this.boss,p=this.player;if(!b.deathblowAvailable||dist(p,b)>C.deathblowReach+b.r||p.y>.2||p.dead)return false; + b.deathblowAvailable=false;b.executing=C.executionFrames;b.state='execution';b.action='deathblow';b.actionTick=0;b.hp=0;b.y=0; + p.inv=C.executionFrames+8;p.stagger=0;p.postureBroken=false;p.lightning=0;p.attackTick=-1;p.charge=0;p.healTick=0;p.dodgeTicks=0;this.setPlayerAction('deathblow'); + this.hazards=[];this.minions=[];this.stats.deathblows++;p.resurrectionLocked=false;this.emit('deathblow');return true; + } + finishExecution(){this.K.finish(this);} + win(){this.outcome='win';this.emit('shinobi_execution');} + nextBar(){const b=this.boss,bar=this.tune.bars[b.phase];b.phase++;b.healthbar_phase=b.phase; + b.hp=b.maxHp=bar.hp;b.maxPosture=bar.posture;b.posture=0;b.postureDelay=0;b.guardCount=0;b.y=0;b.stun=0;b.perilous=null;b.telegraph=null;b.neckExposed=0; + const p=this.player;p.posture=0;p.postureDelay=0;p.inv=25;p.lightning=0;this.setPlayerAction('idle'); + this.hazards=[];this.minions=[];this.emit('phase:'+b.phase);} + breakPlayer(){const p=this.player;p.stagger=C.guardBreakStagger;p.posture=35;p.postureBroken=true;p.attackTick=-1;p.charge=0;p.healTick=0;this.stats.guardBreaks++;this.setPlayerAction('posture_break');this.emit('guard_break');} + die(terror=false){const p=this.player;p.dead=true;p.deathTimer=180;p.vy=0;p.guarding=false;p.lightning=0;p.postureBroken=false;p.terrorDeath=terror;this.stats.deaths++;if(terror)this.stats.terrorDeaths++;this.setPlayerAction('dead');this.emit(terror?'terror_death':'player_dead');} + hurtPlayer(hp,posture=0,stagger=16,bypass=false,scaled=true){ + const p=this.player;if(p.dead||(!bypass&&p.inv>0))return; + p.hp=Math.max(0,p.hp-hp*(scaled?this.tune.dmg:1));p.posture=Math.min(p.maxPosture,p.posture+posture);p.postureDelay=C.playerPostureDelay; + p.hurt=12;p.inv=bypass?0:5;p.stagger=Math.max(p.stagger,stagger);p.attackTick=-1;p.charge=0;p.healTick=0;p.dodgeTicks=0;this.stats.playerHits++; + this.setPlayerAction('hurt');this.emit('player_hit'); + if(p.hp<=0){this.die();return;} + if(p.posture>=p.maxPosture)this.breakPlayer(); + } + revive(){const p=this.player;if(!p.dead||p.nodes<=0||p.resurrectionLocked||p.terrorDeath)return false; + p.nodes--;p.resurrections=p.nodes;p.resurrectionLocked=true;p.dead=false;p.hp=p.maxHp*C.reviveFraction;p.posture=0;p.stagger=0;p.y=0;p.vy=0;p.terror=0; + p.revive=C.reviveFrames;p.inv=C.reviveFrames+10;if(p.burning!==undefined){p.burn=0;p.burning=0;}p.attackTick=-1;p.healTick=0;this.setPlayerAction('revive'); + this.interruptBoss(45);this.hazards=this.hazards.filter(q=>q.type==='gas');this.stats.resurrections++;this.emit('resurrection');return true; + } + guardFacing(source){return Math.abs(N.angle(A(source.x-this.player.x,source.z-this.player.z)-this.player.yaw))<1.55;} + blockOrDeflect(hit,source,kind='melee',move=null){ + const p=this.player,b=this.boss;if(!p.guarding||p.stagger>0||!this.guardFacing(source))return false; + // A fire arm cannot be deflected: a fresh press takes the blow in full (S39). + if(hit.noDeflect&&p.guardAge=p.maxPosture)this.breakPlayer(); + // Guarding fire still builds Burn (S38) and lets some of it through (S36, S39). + if(hit.burn&&!p.dead){this.burnUp(hit.burn);if(hit.leak){p.hp=Math.max(0,p.hp-hit.hp*hit.leak*this.tune.dmg);if(p.hp<=0)this.die();}} + } + p.postureDelay=C.playerPostureDelay;if(hit.push){const a=A(p.x-source.x,p.z-source.z);this.move(p,Math.sin(a)*hit.push,Math.cos(a)*hit.push);}return true; + } + reaches(hit,src){const p=this.player,d=dist(src,p),angle=Math.abs(N.angle(A(p.x-src.x,p.z-src.z)-src.yaw));return d<=hit.reach&&d>=(hit.inner||0)&&(hit.rear?Math.PI-angle:angle)<=(hit.arc||1.13);} + strike(hit,move,src){ + const b=this.boss,p=this.player,fromBoss=src===b;if(p.dead||p.revive||b.executing||(fromBoss&&b.deathblowAvailable))return; + // onlyAir: a high swing that passes over a grounded Sekiro (S36). + const reach=this.reaches(hit,src)&&!(hit.onlyAir&&p.y<=C.sweepHeight); + if(this.probe)this.probe.push({i:this.probeTick,kind:'melee',type:hit.type,move,reach,src:fromBoss?'boss':'minion',noJump:!!hit.noJump,dodge:!!hit.dodge,noDeflect:!!hit.noDeflect,facing:this.guardFacing(src)}); + if(!reach)return; + if(hit.type==='sweep'){ + if(p.y>C.sweepHeight){this.stats.sweepJumps++;this.emit('sweep_avoided');return;} + b.connected=true;this.stats.perilousFailures++;this.hurtPlayer(hit.hp,hit.posture,25,true);if(hit.burn)this.burnUp(hit.burn);return; + } + // The Demon's explosive landing: no guard; be out of reach or in the air (S36, S39). + if(hit.type==='blast'){if(p.y>.9){this.emit('blast_avoided');return;}b.connected=true;this.stats.perilousFailures++;this.hurtPlayer(hit.hp,hit.posture,30,true); + if(!p.dead){const a=A(p.x-src.x,p.z-src.z);this.move(p,Math.sin(a)*hit.push,Math.cos(a)*hit.push);this.burnUp(hit.burn);}return;} + if(hit.type==='grab'){ + // No deflect or guard. Genichiro: jump or step aside; a forward (Mikiri) step is still caught. The ape's floor + // swipe is jumped; its belly flop and Lady Butterfly's aerial grab are escaped only by distance (S05, S14, S19). + if((!hit.noJump&&p.y>C.grabJumpHeight)||(hit.dodge&&p.dodgeTicks>=C.dodgeFrames-C.dodgeInv&&this.dodgeToward()<=.55)){this.stats.grabEscapes++;this.emit('grab_avoided');return;} + b.connected=true;this.stats.perilousFailures++;this.emit('grabbed');this.hurtPlayer(hit.hp,hit.posture,40,true);return; + } + if(hit.type==='lightning'){this.catchLightning();return;} + // Isshin's circular force wave: jump it, deflect it as his arm moves, or be elsewhere (S27). + if(hit.ring&&p.y>C.sweepHeight){this.emit('ring_jumped');return;} + if(hit.type==='mortal'){if(p.dodgeTicks>=C.dodgeFrames-C.dodgeInv){this.emit('mortal_avoided');return;}b.connected=true;this.stats.perilousFailures++;this.hurtPlayer(hit.hp,hit.posture,30,true);return;} + if(p.y>1.9&&hit.type!=='slam')return; + if(hit.type==='thrust'&&p.dodgeTicks>0&&p.y<.3&&this.dodgeToward()>.55){ + this.stats.mikiri++;this.fx('mikiri',b,25);this.emit('mikiri');this.bossPosture(C.mikiriPosture*C.postureUnit);this.interruptBoss(C.mikiriStun);p.dodgeTicks=0;p.inv=12;return; + } + if(this.blockOrDeflect(hit,src,'melee',move)){if(fromBoss)b.connected=true;return;} + if(hit.type!=='thrust'&&p.dodgeTicks>=C.dodgeFrames-C.dodgeInv)return; + if(fromBoss){b.connected=true;if(hit.type==='thrust')this.stats.perilousFailures++;this.K.onLanded?.(this,hit);} + this.hurtPlayer(hit.hp,hit.posture,hit.stagger??(hit.type==='slam'?24:16));if(hit.burn)this.burnUp(hit.burn); + } + // Burn (S38): fire fills the gauge, guarded or not; full, it drains vitality and stops posture recovery for a while. + burnUp(x){const p=this.player;if(p.burn===undefined||p.dead)return;p.burnFed=true;if(p.burning>0)return; + p.burn=Math.min(100,p.burn+x*this.tune.dmg);if(p.burn>=100){p.burn=0;p.burning=D.burnTicks;this.stats.burns++;this.emit('burning');}} + catchLightning(){const p=this.player;if(p.dead)return; + if(p.y>.2){p.hp=Math.max(0,p.hp-G.lightningChip);p.lightning=G.lightningCarry;p.lightningCaughtAt=this.t;this.stats.lightningCatches++;this.fx('lightning_catch',p,20);this.emit('lightning_caught'); + if(p.hp<=0)this.hurtPlayer(1,0,0,true); + }else{this.stats.lightningFailures++;this.fx('shock',p,35);this.emit('grounded_lightning');this.hurtPlayer(G.lightningDamage,G.lightningPosture,G.lightningShock,true);} + } + reverseLightning(){const p=this.player,b=this.boss;if(!p.lightning||p.y<=.1||this.t===p.lightningCaughtAt)return false; + p.lightning=0;this.stats.lightningReversals++;this.emit('lightning_reversal');this.fx('lightning_return',b,30); + if(dist(p,b)<=G.reversalRange&&Math.abs(N.angle(A(b.x-p.x,b.z-p.z)-p.yaw))<1.6){this.damageBoss(Math.round(b.maxHp*G.lightningBossDamage),G.lightningBossPosture*C.postureUnit);this.interruptBoss(G.lightningStun);} + else this.emit('reversal_out_of_range'); + this.hazards=this.hazards.filter(q=>q.type!=='lightning_arrow');return true; + } + // Area terror: the headless ape's blood scream fills the gauge with distance falloff; guarding does not stop it (S20). + terrorWave(s){const p=this.player,b=this.boss;if(p.dead||p.revive||b.executing)return;const d=dist(p,b); + if(this.probe&&d<=s.radius)this.probe.push({i:this.probeTick,kind:'aoe',type:'terror',reach:true}); + if(d>s.radius)return;const fall=Math.sqrt(1-d/s.radius);p.terror=Math.min(100,p.terror+s.rate*fall*this.tune.dmg);p.terrorFed=true; + p.hp=Math.max(0,p.hp-s.drain*fall*this.tune.dmg);if(p.terror>=100){this.emit('terror_full');this.die(true);}else if(p.hp<=0)this.die();} + playerAttack(kind){const p=this.player;if(p.attackTick<0)return; + const wind=kind==='thrust'?C.thrustWind:C.slashWind;if(p.attackTick!==wind||p.attackHit)return;p.attackHit=true; + const b=this.boss,range=kind==='thrust'?3.05:2.55,facing=o=>Math.abs(N.angle(A(o.x-p.x,o.z-p.z)-p.yaw)); + for(const q of this.minions)if(q.alive&&dist(p,q)<=range+q.r-.3&&facing(q)<=1.2){q.alive=false;q.fade=24;this.stats.illusionsKilled++;this.fx('illusion_cut',q);this.emit('illusion_cut');} + if(dist(p,b)>range+b.r-.5||facing(b)>1.2||Math.abs((b.y||0)-(p.y||0))>1.5||b.executing||b.deathblowAvailable||b.state==='dead')return; + const m=this.moves[b.action],busy=b.state==='attack';if(busy&&(m?.invulnerable||b.moveTick<(m?.invulnerableUntil||0)))return; + b.attackedAt=this.t;this.K.playerHit(this,kind,b.state==='stunned'||(busy&&openAt(m,b.moveTick,b.connected)),b.action); + } + arrow(heavy=false,lightning=false){const b=this.boss,p=this.player; + const sy=b.y+1.35,dy=p.y+.9-sy,dx=p.x-b.x,dz=p.z-b.z,len=Math.hypot(dx,dy,dz)||1,speed=lightning?.42:.4; + this.hazards.push({type:lightning?'lightning_arrow':'arrow',x:b.x,y:sy,z:b.z,vx:dx/len*speed,vy:dy/len*speed,vz:dz/len*speed, + sourceX:b.x,sourceZ:b.z,owner:'boss',age:0,life:120,radius:.2,charged:heavy,damage:heavy?24:12,posture:heavy?27:12});this.emit(lightning?'lightning_arrow':'arrow'); + } + // Matchlock shot: fast, and guarding one costs heavy posture, so deflect it (S27). + bullet(){const b=this.boss,p=this.player,sy=b.y+1.3,dy=p.y+.9-sy,dx=p.x-b.x,dz=p.z-b.z,len=Math.hypot(dx,dy,dz)||1,speed=I.bulletSpeed; + this.hazards.push({type:'bullet',x:b.x,y:sy,z:b.z,vx:dx/len*speed,vy:dy/len*speed,vz:dz/len*speed,sourceX:b.x,sourceZ:b.z,age:0,life:60,radius:.14,damage:10,posture:24});this.emit('gunshot');} + // Force waves run along the ground: step aside from a vertical one, jump a flat one; guarding leaks vitality, deflecting does no posture damage (S27). + airWave(kind){const b=this.boss,p=this.player,a=A(p.x-b.x,p.z-b.z),speed=I.waveSpeed; + this.hazards.push({type:'wave',wide:kind==='h',x:b.x,y:.9,z:b.z,yaw:a,vx:Math.sin(a)*speed,vy:0,vz:Math.cos(a)*speed,sourceX:b.x,sourceZ:b.z,age:0,life:60,radius:kind==='h'?.95:.5,damage:kind==='h'?18:16,posture:kind==='h'?22:20});this.emit('force_wave');} + // The poo flies in a straight line at about 60 m/s and lasts three seconds (S16); a hit poisons at once (S14). + throwPoo(){const b=this.boss,p=this.player,sy=b.y+2.2,dx=p.x-b.x,dy=p.y+.9-sy,dz=p.z-b.z,len=Math.hypot(dx,dy,dz)||1,speed=1; + this.hazards.push({type:'poo',x:b.x,y:sy,z:b.z,vx:dx/len*speed,vy:dy/len*speed,vz:dz/len*speed,sourceX:b.x,sourceZ:b.z,age:0,life:180,radius:.42,damage:30,posture:20});this.emit('poo');} + kunai(n){const b=this.boss,p=this.player,sy=b.y+1.25; + for(let i=0;i=4&&a.pillars.every(q=>Math.hypot(x-q.x,z-q.z)>1)){this.minions.push({id:this.nextMinion++,x,y:0,z,yaw:A(p.x-x,p.z-z),r:.36,alive:true,state:'walk',t:0,fade:0,age:0});this.stats.illusionsSummoned++;return;}}} + summonIllusions(){const b=this.boss;b.spell=this.tune.spell||L.spell;b.dispelDue=false;while(this.minions.filter(q=>q.alive).length1.7&&!p.dead)this.toward(q,p.x,p.z,L.illusionSpeed,1.6);else if(!p.dead){q.state='attack';q.t=0;}} + else if(q.state==='attack'){if(++q.t<20)q.yaw=to;if(q.t===34)this.strike({type:'slash',reach:2.1,arc:1.1,hp:7,posture:11,stagger:8},'illusion',q);if(q.t>=40){q.state='recover';q.t=0;}} + else if(++q.t>=50){q.state='walk';q.t=0;}} + this.minions=this.minions.filter(q=>q.alive||q.fade>0);} + projectiles(){const p=this.player,a=this.arena; + for(const q of this.hazards){q.age++;q.life--; + if(q.type==='gas'){if(!p.dead&&p.y<1.6&&dist(q,p)0)q.cool--;const d=dist(q,p); + if(!p.dead&&!p.revive&&p.y<1&&q.cool<=0&&Math.abs(d-q.radius)a.radius+1:Math.abs(q.x)>a.halfWidth+1||Math.abs(q.z)>a.halfDepth+1; + if(out||q.y<-.2){q.life=0;continue;} + if(a.pillars.some(c=>Math.hypot(q.x-c.x,q.z-c.z)2&&!(q.type==='butterfly'&&q.age<(q.swarm?L.butterflyLaunch:L.dartLaunch))&&!p.dead&&!p.revive&&Math.hypot(p.x-old.x-u*dx,q.type==='wave'&&!q.wide?0:p.y+.9-old.y-u*dy,p.z-old.z-u*dz)0||p.dodgeTicks>=C.dodgeFrames-C.dodgeInv)continue; + q.life=0; + const src={x:q.sourceX,z:q.sourceZ};if(q.type==='butterfly'){src.x=old.x;src.z=old.z;this.stats.butterflyHits++;} + const blocks=this.stats.blocks;if(this.blockOrDeflect({type:q.type,hp:q.damage,posture:q.posture,push:q.charged?.55:0,burn:q.burn,leak:q.leak},src,q.swarm?'butterfly':'arrow')){if(q.type==='wave'&&this.stats.blocks>blocks){p.hp=Math.max(0,p.hp-q.damage*I.waveLeak*this.tune.dmg);if(p.hp<=0)this.die();}continue;} + this.hurtPlayer(q.damage,q.posture,18);if(q.burn&&!p.dead)this.burnUp(q.burn); + if(q.type==='poo'&&!p.dead){p.poisoned=C.poisonTicks;p.poison=0;this.stats.poisoned++;this.emit('poisoned');} + } + } + this.hazards=this.hazards.filter(q=>q.life>0); + } + // Lobbed fireballs burst where they land and leave a fire; homing ones steer with a limited turn and sink to the ground (S36, S39). + fireball(q){const p=this.player; + if(q.lob)q.vy-=D.lobGravity;else{if(q.age>12&&q.age<12+D.homingFor){const want=A(p.x-q.x,p.z-q.z),now=A(q.vx,q.vz),yaw=N.angle(now+N.clamp(N.angle(want-now),-D.homingTurn,D.homingTurn));q.vx=Math.sin(yaw)*D.homingSpeed;q.vz=Math.cos(yaw)*D.homingSpeed;q.vy=N.clamp((p.y+.9-q.y)*.08,-D.homingClimb,D.homingClimb);}else if(q.age<=12)q.vy*=.9;else q.vy-=D.homingFall;} + const old={x:q.x,y:q.y,z:q.z};q.x+=q.vx;q.y+=q.vy;q.z+=q.vz; + const hitP=()=>{if(this.probe)this.probe.push({i:this.probeTick,kind:'projectile',type:'fireball',reach:true});if(p.inv>0||p.dodgeTicks>=C.dodgeFrames-C.dodgeInv)return; + if(!this.blockOrDeflect({type:'fireball',hp:q.damage,posture:q.posture,burn:q.burn,leak:D.fireLeak,noDeflect:true},{x:q.sourceX,z:q.sourceZ},'arrow')){this.hurtPlayer(q.damage,q.posture,18);this.burnUp(q.burn);}}; + if(q.y<=0){q.life=0;this.hazards.push({type:'fire',x:q.x,y:0,z:q.z,radius:1.1,age:0,life:q.lob?100:60,rate:D.fireRate});this.emit('fireball_burst'); + if(!p.dead&&!p.revive&&p.y<.8&&Math.hypot(p.x-q.x,p.z-q.z)2&&!p.dead&&!p.revive){const dx=q.x-old.x,dy=q.y-old.y,dz=q.z-old.z,len=dx*dx+dy*dy+dz*dz,u=N.clamp(((p.x-old.x)*dx+(p.y+.9-old.y)*dy+(p.z-old.z)*dz)/(len||1),0,1); + if(Math.hypot(p.x-old.x-u*dx,p.y+.9-old.y-u*dy,p.z-old.z-u*dz)0||p.dodgeTicks>=C.dodgeFrames-C.dodgeInv){if(this.probe)this.probe.push({i:this.probeTick,kind:'projectile',type:'fireball',reach:true});return;}q.life=0;hitP();}}} + statuses(){const p=this.player;if(p.dead){p.poisonFed=p.terrorFed=false;if(p.burnFed!==undefined)p.burnFed=false;return;} + if(p.poison>=100){p.poison=0;p.poisoned=C.poisonTicks;this.stats.poisoned++;this.emit('poisoned');} + if(p.poisoned>0){p.poisoned--;p.hp=Math.max(0,p.hp-C.poisonDrain);if(p.hp<=0)this.die();} + if(!p.poisonFed)p.poison=Math.max(0,p.poison-C.poisonDecay);if(!p.terrorFed)p.terror=Math.max(0,p.terror-C.terrorDecay);p.poisonFed=p.terrorFed=false; + if(p.burning!==undefined){if(p.burning>0&&!p.dead){p.burning--;p.hp=Math.max(0,p.hp-D.burnDrain*this.tune.dmg);if(p.hp<=0)this.die();}if(!p.burnFed)p.burn=Math.max(0,p.burn-D.burnDecay);p.burnFed=false;}} + bossUpdate(){const b=this.boss,p=this.player,K=this.K; + b.actionTick++;if(b.flash>0)b.flash--; + if(b.executing){b.executing--;if(!b.executing)this.finishExecution();return;} + if(b.deathblowAvailable){b.y=Math.max(0,b.y-.15);if(b.deathblow>0&&--b.deathblow===0){b.deathblowAvailable=false;b.posture=b.maxPosture*C.deathblowMissFraction;b.state='idle';b.action='idle';b.cooldown=25;this.emit('deathblow_missed');}return;} + if(K.special&&K.special(this))return; + if(p.dead)return; + if(b.state==='stunned'){if(b.action!=='flinch_big')b.y=Math.max(0,b.y-.15);if(--b.stun<=0){b.state='idle';b.action='idle';b.cooldown=this.tune.restStun;}return;} + // Enemy posture has no recovery delay (S04) and keeps recovering during his own attacks; it pauses while he is + // staggered (returned above, by analogy with the S04 clause for Sekiro) and while a deathblow is open. + this.recoverPosture(b); + if(b.state==='idle'){K.idle(this);return;} + const move=b.action,m=this.moves[move],t=b.moveTick++; + if(m.perilousFrom&&t===m.perilousFrom)b.telegraph=b.perilous; + K.step(this,move,m,t);if(b.state!=='attack'||b.action!==move)return; + for(const hit of m.hits)if(t===hit.t)this.strike(hit,move,b); + if(b.state!=='attack'||b.action!==move)return; + K.afterHits(this,move,m,t);if(b.state!=='attack'||b.action!==move)return; + if(t>=m.duration-1){if(!m.air)b.y=0;const next=K.followUp(this,move); + if(next){this.startMove(next);return;} + b.state='idle';b.action='idle';b.perilous=null;b.telegraph=null;b.lightning=false;b.cooldown=this.tune.rest; + } + } + vertical(){const p=this.player; + if(p.y>0||p.vy>0){p.y+=p.vy;p.vy-=C.gravity;if(p.y<=0){p.y=0;p.vy=0;p.stomped=false;if(p.lightning){p.lightning=0;this.stats.lightningFailures++;this.emit('lightning_grounded');this.hurtPlayer(G.lightningDamage,G.lightningPosture,G.lightningShock,true);}}} + if(p.lightning>0)p.lightning--; + } + kick(){const p=this.player,b=this.boss,K=this.K;if(p.stomped||p.y<=.5||b.executing||b.state==='dead'||b.deathblowAvailable||dist(p,b)>=K.kickRange+b.r-.5)return false; + if(!K.kickAnyHeight&&p.y<=b.y+.5)return false; + p.stomped=true;p.vy=C.jumpSpeed*.8;this.stats.stomps++;const perilousSweep=b.state==='attack'&&b.perilous==='sweep'; + this.bossPosture((this.kind==='butterfly'&&perilousSweep?L.kick:C.stompPosture)*C.postureUnit);this.fx('stomp',b,22);this.emit('head_stomp');K.onKick?.(this);return true;} + playerUpdate(keys,pressed,mouse){const p=this.player,b=this.boss; + if(pressed.has('E'))this.lockOn=!this.lockOn; + if(this.lockOn){this.face(p,b);this.cameraYaw=p.yaw;}else{this.cameraYaw=N.angle(this.cameraYaw-mouse[0]*.003);p.yaw=this.cameraYaw;}p.actionTick++; + // Physical holds continue through death/cinematics; returning to play must + // never synthesize a fresh deflect, charged attack or dodge press. + const guard=keys.has('K')||keys.has('RMB'),attack=keys.has('J')||keys.has('LMB'),dodge=keys.has('Shift'); + const guardPress=guard&&!p.guardHeld,attackPress=attack&&!p.attackHeld,dodgePress=dodge&&!p.dodgeHeld; + p.guardHeld=guard;p.attackHeld=attack;p.dodgeHeld=dodge;p.running=false; + for(const name of ['inv','stagger','hurt','flash','revive'])if(p[name]>0)p[name]--; + if(p.stagger===0)p.postureBroken=false; + if(p.dead){p.guarding=false;p.guardAge=999;p.runTicks=0;if(pressed.has('R'))this.revive();if(p.dead&&--p.deathTimer<=0)this.outcome='loss';return;} + if(b.executing||p.revive||(b.state==='attack'&&(b.action==='tomoe_awaken'||this.moves[b.action]?.cinematic))){p.guarding=false;p.guardAge=999;this.vertical();return;} + if(this.t-p.lastGuardPress>C.spamReset)p.spam=0; + if(guardPress){p.spam=this.t-p.lastGuardPress>p.spam);p.guardAge=0; + }else p.guardAge++; + p.guarding=guard&&p.stagger===0&&p.healTick===0&&(p.attackTick<0||p.attackTick>13); + if(guardPress&&p.charge){p.charge=0;p.attackTick=-1;this.setPlayerAction('guard');} + if(p.lightning&&attackPress&&this.reverseLightning())return; + if(attackPress&&b.deathblowAvailable&&this.execute())return; + if(p.stagger>0){p.guarding=false;p.dodgeTicks=0; + // Safety roll: Step Dodge or Jump makes a posture-break stun much shorter (S04). + if(p.postureBroken&&(dodgePress||pressed.has('Space'))&&C.guardBreakStagger-p.stagger>=C.safetyRollAfter&&p.stagger>C.safetyRollRemain){p.stagger=C.safetyRollRemain;this.stats.safetyRolls++;this.setPlayerAction('safety_roll');this.emit('safety_roll');} + this.vertical();return;} + if(pressed.has('Q')&&p.gourds>0&&p.hpC.gourdFrames){p.healTick=0;this.setPlayerAction('idle');}this.recoverPosture(p);p.runTicks=0;return;} + if(pressed.has('Space')){ + if(p.y===0){p.vy=C.jumpSpeed;p.stomped=false;this.setPlayerAction('jump');this.emit('jump');} + else this.kick(); + } + this.vertical(); + const f=(keys.has('W')?1:0)-(keys.has('S')?1:0),side=(keys.has('D')?1:0)-(keys.has('A')?1:0),a=this.cameraYaw; + let dx=Math.sin(a)*f-Math.cos(a)*side,dz=Math.cos(a)*f+Math.sin(a)*side,len=Math.hypot(dx,dz);if(len){dx/=len;dz/=len;} + if(dodgePress&&p.y===0&&!p.charge&&p.attackTick<0){if(!len){dx=Math.sin(p.yaw);dz=Math.cos(p.yaw);}p.dodgeX=dx;p.dodgeZ=dz;p.dodgeTicks=C.dodgeFrames;this.setPlayerAction('dodge');this.emit('step');} + const stepping=p.dodgeTicks>0; + if(stepping){this.move(p,p.dodgeX*C.dodge,p.dodgeZ*C.dodge);p.dodgeTicks--;} + else if(len){p.running=dodge&&!p.guarding;const speed=p.guarding?C.move*.55:p.running?C.run:C.move;this.move(p,dx*speed,dz*speed);if(p.attackTick<0&&!p.charge&&p.y===0)this.setPlayerAction(p.running?'run':'walk');} + p.runTicks=p.running?p.runTicks+1:0; + if(attackPress&&p.attackTick<0&&!p.guarding&&p.dodgeTicks===0){p.charge=1;this.setPlayerAction('charge');} + if(p.charge){if(!attack||p.charge>=C.thrustCharge){p.attackKind=attack?'thrust':'slash';p.attackTick=0;p.attackHit=false;p.charge=0;this.stats.playerAttacks++;this.setPlayerAction(p.attackKind);}else p.charge++;} + if(p.attackTick>=0){this.playerAttack(p.attackKind);p.attackTick++;if(p.attackTick>(p.attackKind==='thrust'?C.thrustEnd:C.slashEnd)){p.attackTick=-1;this.setPlayerAction('idle');}} + // No posture recovery while attacking, sprinting, dodging, airborne or staggered; guarding speeds it up (S04). + if(p.attackTick<0&&!p.charge&&!stepping&&p.y===0&&!p.running){if(!len)this.setPlayerAction(p.guarding?'guard':'idle');this.recoverPosture(p,p.guarding?C.guardRecovery:1);} + } + separate(o,q,heightO,heightQ){const d=dist(o,q),min=o.r+q.r;if(!(o.y=min)return; + const nx=d>1e-8?(o.x-q.x)/d:Math.sin(o.yaw),nz=d>1e-8?(o.z-q.z)/d:Math.cos(o.yaw),push=(min-d)*.5; + this.move(o,nx*push,nz*push);this.move(q,-nx*push,-nz*push); + const residual=min-dist(o,q);if(residual>1e-6){this.move(o,nx*residual,nz*residual);const remain=min-dist(o,q);if(remain>1e-6)this.move(q,-nx*remain,-nz*remain);}} + update(keys,pressed,mouse){if(this.outcome)return; + for(const body of [this.player,this.boss])if(body.postureDelay>0)body.postureDelay--; + this.playerUpdate(keys,pressed,mouse);if(!this.outcome)this.bossUpdate();if(this.outcome)return; + this.minionUpdate();if(!this.player.dead)this.projectiles();this.statuses(); + const p=this.player,b=this.boss; + // A horse at the gallop rides through: without this it pushes Sekiro along in front of it and can never pass him. + if(!b.executing&&b.state!=='dead'&&!(b.state==='attack'&&this.moves[b.action]?.ride))this.separate(p,b,1.75,b.height); + for(const q of this.minions)if(q.alive)this.separate(p,q,1.75,1.7); + if(this.lockOn){this.face(p,b);this.cameraYaw=p.yaw;} + this.effects=this.effects.filter(fx=>--fx.life>0);this.lastKeys=[...keys].sort(); + } + health(){const b=this.boss,later=this.tune.bars.slice(b.phase).reduce((s,x)=>s+x.hp,0); + return [this.player.hp,C.playerHP,this.outcome==='win'?0:(b.state==='dead'?0:b.hp)+later,this.totalBossHP];} + } + M.Game=Game;M.openAt=openAt;M.regenFactor=regenFactor;M.tier=tier; + + /* Standard scripted reference controller (bossbench scripted hook). Called once per 200 ms packet with the live + * game; it reads privileged state on a deep copy, predicts the next contacts by simulating that copy with no input, + * and returns only legal holds (<= 4 keys each). Deterministic; never touches the live game or its RNG. */ + function cloneGame(g){return Object.assign(Object.create(Game.prototype),N.copy(g));} + function simTick(h,keys,mouse){const prev=new Set(h.lastKeys);h.events=[];h.update(new Set(keys),new Set(keys.filter(k=>!prev.has(k))),mouse);N.quantize(h);h.t++;} + function contacts(h,horizon){const s=cloneGame(h);s.probe=[]; + let first=-1;for(let i=0;ic.reach))first=i;if(first>=0&&i>=first+8)break;} + return s.probe.filter(c=>c.reach); + } + function room(h,x,z){const a=h.arena;/* free distance to the arena edge or a pillar */let r=a.shape==='circle'?a.radius-Math.hypot(x,z):Math.min(a.halfWidth-Math.abs(x),a.halfDepth-Math.abs(z)); + for(const q of a.pillars)r=Math.min(r,Math.hypot(x-q.x,z-q.z)-q.r);return r;} + function sideKey(h,reach=3.2){const p=h.player,a=h.cameraYaw,rx=-Math.cos(a),rz=Math.sin(a); + // Step toward the side with more room. + return room(h,p.x+rx*reach,p.z+rz*reach)>=room(h,p.x-rx*reach,p.z-rz*reach)?'D':'A';} + // Best of eight run directions away from a point, keeping room to keep running (walls, pillars). + function escape(h,x,z){const p=h.player,a=h.cameraYaw,f=[Math.sin(a),Math.cos(a)],r=[-Math.cos(a),Math.sin(a)];let best=null,score=-1e9; + for(const [keys,u,v] of [[['S'],-1,0],[['S','A'],-1,-1],[['S','D'],-1,1],[['A'],0,-1],[['D'],0,1],[['W','A'],1,-1],[['W','D'],1,1],[['W'],1,0]]){ + const len=Math.hypot(u,v),dx=(f[0]*u+r[0]*v)/len,dz=(f[1]*u+r[1]*v)/len;let px=p.x,pz=p.z,stuck=0; + for(let k=1;k<=6;k++){const nx=px+dx*.6,nz=pz+dz*.6;if(room(h,nx,nz)score){score=sc;best=keys;}} + return [...best,'Shift'];} + // Drinking takes 66 ticks: simulate the whole animation on a copy and heal only if nothing lands meanwhile. + function safeHeal(h){const s=cloneGame(h),hits=s.stats.playerHits;simTick(s,['Q'],[0,0,0]); + for(let i=0;ih.stats.healsApplied;} + function swarmCenter(list,p){if(!list.length)return [p.x,p.z];let x=0,z=0;for(const q of list){x+=q.x;z+=q.z;}return [x/list.length,z/list.length];} + function plan(h){ + const p=h.player,b=h.boss,prev=new Set(h.lastKeys),d=dist(p,b),tap=k=>prev.has(k)?[]:[k],kind=h.kind,head=b.form_id==='headless'; + if(h.outcome)return []; + if(p.dead)return p.nodes>0&&!p.resurrectionLocked&&!p.terrorDeath?tap('R'):[]; + if(b.executing||p.revive||(b.state==='attack'&&(b.action==='tomoe_awaken'||h.moves[b.action]?.cinematic)))return []; + if(p.stagger>0)return p.postureBroken&&C.guardBreakStagger-p.stagger>=C.safetyRollAfter?tap('Shift'):[]; + if(p.lightning>0&&p.y>.1)return tap('J'); + if(p.healTick>0)return []; + if(b.deathblowAvailable)return d>C.deathblowReach+b.r-.15?['W']:tap('J'); + const grounded=p.y===0&&p.vy===0,free=grounded&&!p.charge&&p.attackTick<0&&p.dodgeTicks===0; + if(!grounded&&!p.stomped&&p.y>.55&&db.y+.5)&&b.perilous==='sweep'&&b.state==='attack')return tap('Space'); + const swarm=h.hazards.filter(q=>q.type==='butterfly'&&q.swarm&&dist(q,p)<7.5&&q.agec.kind==='melee'&&!['sweep','grab','lightning','mortal'].includes(c.type)); + let threat=all[0]; + // A projectile followed closely by a guardable blow: guard (deflect) the blow instead of stepping into it. + if(threat&&(threat.type==='butterfly'||threat.type==='poo')&&melee&&melee.i<=threat.i+6)threat=melee; + const eta=threat?threat.i:99; + if(threat&&threat.src==='minion'&&!threat.facing){const q=h.minions.filter(m=>m.alive&&m.state==='attack').sort((a,c)=>dist(a,p)-dist(c,p))[0]; + if(free&&eta<=3&&!prev.has('Shift'))return escape(h,q?q.x:p.x,q?q.z:p.z);if(eta<=3)return [];} + if(threat){ + const type=threat.type; + if(type==='terror')return escape(h,b.x,b.z); + if(type==='gas'){const q=h.hazards.find(z=>z.type==='gas');return escape(h,q?q.x:b.x,q?q.z:b.z);} + if(type==='fire'&&!all.some(c=>c.kind!=='aoe'&&c.i<=6))return escape(h,threat.x,threat.z); + if(type==='fire_ring'&&eta<=6)return escape(h,b.x,b.z); + if(type==='blast'){if(grounded&&eta>=4&&eta<=14)return tap('Space');if(eta<=14)return [];} + // Fire arms and fireballs cannot be deflected: be guarding well before they land. + // A fire arm cannot be deflected and guarding it builds Burn: walk in under the belly, where it misses (S36, S37), else hold the guard early. + if(threat.noDeflect&&threat.kind==='melee'&&grounded&&free&&d>D.belly-.1&&(d-D.belly+.1)/C.move=4&&d>D.belly&&p.attackTick<0&&!p.charge)return ['W','Shift']; + if(type==='fireball'&&free&&eta<=2&&!prev.has('Shift'))return [sideKey(h,1.6),'Shift']; + if(type==='fireball'&&eta<=2&&prev.has('Shift'))return []; + if(threat.noDeflect||type==='fireball'){if(eta<=29)return ['RMB'];} + if(type==='lightning'||type==='lightning_arrow'){ + if(grounded&&eta<=1+(type==='lightning'?3:0))return tap('Space'); + if(grounded&&eta>8&&d>7)return ['W']; + if(eta<=8)return []; + }else if(type==='mortal'){ + if(free&&eta<=5&&!prev.has('Shift'))return [sideKey(h),'Shift']; + if(eta<=5)return []; + }else if(type==='sweep'){ + if(grounded&&eta>=3&&eta<=8)return tap('Space'); + if(eta<=8)return []; + }else if(type==='grab'){ + if(threat.noJump){// distance only: retreat straight back as it commits (the aerial grab tracks a side step, S19) + const away=escape(h,b.x,b.z);if(free&&eta<=16&&!prev.has('Shift'))return away; + return eta<=18?(prev.has('Shift')?away.filter(k=>k!=='Shift'):away):[];} + if(threat.dodge&&free&&eta<=3&&!prev.has('Shift'))return [sideKey(h),'Shift']; + if(grounded&&eta>=3&&eta<=8&&!prev.has('Space'))return ['Space']; + if(eta<=8)return prev.has('Shift')||prev.has('Space')?[]:threat.dodge?[sideKey(h)]:[]; + }else if(type==='thrust'){ + if(free&&eta>=1&&eta<=6&&!prev.has('Shift'))return ['W','Shift']; + if(eta<=1)return ['RMB']; + if(eta<=6)return prev.has('Shift')?[]:['W']; + }else if(type==='poo'||type==='butterfly'){ + if(type==='butterfly'&&!swarm.length){if(eta<=1)return ['RMB'];if(eta<=4)return [];} + else{if(free&&eta<=2&&!prev.has('Shift'))return type==='butterfly'?escape(h,...swarmCenter(swarm,p)):[sideKey(h,1.6),'Shift']; + if(eta<=2)return [];} + }else{ + if(eta<=1)return ['RMB']; + if(eta<=4&&!swarm.length)return []; + } + } + // Spirit butterflies outrun a walk but not a sprint: kite them (pillars break them), and back away from the + // flurry instead of guarding it, coming back after its perilous finisher (S17, S19). + if(swarm.length&&grounded)return escape(h,...swarmCenter(swarm,p)); + if(b.state==='attack'&&b.action==='flurry'&&b.moveTick>=6&&b.moveTick<100&&grounded)return d<5.5?escape(h,b.x,b.z):[]; + if(b.state==='attack'&&b.action==='flurry'&&b.moveTick>=100&&b.moveTick<124&&grounded)return d>3.4?['W']:[]; + const ms=b.state==='attack'&&h.moves[b.action]?.scream;if(ms&&b.moveTick['arrow','lightning_arrow','kunai','poo','butterfly','bullet','wave'].includes(q.type)); + const calm=eta>=30&&!arrowsInFlight&&(b.state==='idle'||b.state==='stunned'||b.state==='dead')&&h.minions.every(q=>!q.alive||dist(q,p)>3); + if(p.hp<=50&&p.gourds>0&&free&&!prev.has('Q')&&calm&&(kind!=='genichiro'||b.state!=='idle'||d>=2)&&safeHeal(h))return ['Q']; + if(b.state==='dead'){if(p.hp<=75&&p.gourds>0&&free&&!prev.has('Q')&&safeHeal(h))return ['Q'];return d<6?['S']:[];} + // Lightning: wait for the airborne catch and reversal (heavier payoff) instead of cutting him out of the leap. + const lightningMove=b.state==='attack'&&b.lightning&&b.moveTick<100; + const m=h.moves[b.action],open=!lightningMove&&(b.state==='stunned'||b.state==='idle'||(b.state==='attack'&&openAt(m,b.moveTick+9,b.connected))); + if(lightningMove&&grounded&&d>6.5)return ['W']; + // Illusions: cut one that has closed in when nothing else is coming. + const near=h.minions.find(q=>q.alive&&dist(q,p)<2.3&&Math.abs(N.angle(A(q.x-p.x,q.z-p.z)-p.yaw))<1.1); + if(near&&free&&eta>=14)return tap('J'); + const reach=2.45+b.r-.5,safe=eta>=19&&!(b.state==='attack'&&m?.invulnerable); + if(free&&safe&&open&&d<=reach&&b.y<1.2)return tap('J'); + // The headless ape outranges Sekiro: keep a middle distance unless it is open (S14). + // Its delayed overhead chop is the opening: step in and deflect it to stun it with the neck exposed (S14, S15). + if(head&&b.state==='attack'&&(b.action==='overhead_slam'||b.action==='jump_sweep'&&b.moveTick>40)&&!open){return d>3.5&&b.moveTick<44?['W']:[];} + if(head&&!open&&b.state!=='stunned'){if(b.state==='attack'&&d<4.8)return [];if(d<4.6)return ['S'];if(d>7.5)return ['W'];return [];} + if(kind==='ape'&&b.state==='attack'&&!open&&d<3.6)return []; + if(kind==='gyoubu'&&d>5&&p.attackTick<0&&!p.charge&&grounded)return ['W','Shift']; + if(d>reach-.15&&p.attackTick<0&&!p.charge)return ['W']; + return []; + } + // The fight opens unlocked (free camera, sekiro@11): the script locks on in its first sub-step and never toggles again, + // so from then on it plays exactly as it did when the fight opened locked (camera already faces the boss at tick 0). + M.scripted=function(game){ + const h=cloneGame(game),p=h.player,b=h.boss,holds=[],lock=!h.lockOn; + const mouse=[h.lockOn?0:N.clamp(Math.round(-N.angle(A(b.x-p.x,b.z-p.z)-h.cameraYaw)/.003),-1000,1000),0,0]; + for(let j=0;j<6;j++){ + const keys=j===0&&lock?['E',...plan(h)].slice(0,4):plan(h).slice(0,4);holds.push(keys); + for(let n=0;n<2&&!h.outcome;n++)simTick(h,keys,mouse.map(v=>v/12)); + } + return {holds,mouse}; + }; + M.oracle=M.scripted; // legacy tool name + M.debug={plan:g=>plan(cloneGame(g)),contacts:(g,n=30)=>contacts(cloneGame(g),n)}; +})(typeof window==='undefined'?globalThis:window); diff --git a/environments/games/web/games/sekiro_remake/index.html b/environments/games/web/games/sekiro_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..85ae9c8faee4988b98952044c86279378d3361f5 --- /dev/null +++ b/environments/games/web/games/sekiro_remake/index.html @@ -0,0 +1,7 @@ +Sekiro · Six Bosses
    +
    Sekiro · Shadows Die Twice

    Sekiro · Six Bosses

    Face six foes: a bow-and-blade swordsman, a deceptive guardian ape, an illusion-wielding shinobi, a sword-and-spear master, a mounted general, and a flame behemoth. Read their attacks and break their posture.

    Back to Game Lobby ↗
    +
    Are You Ready?Click Start Challenge
    +

    Verify Script reads game state to check the mechanics. Replays save real inputs and simulate the full battle again.

    +
    +
    + diff --git a/environments/games/web/games/sekiro_remake/manifest.json b/environments/games/web/games/sekiro_remake/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..fda36d3d14ded323b2a3b894f6d719917950a40c --- /dev/null +++ b/environments/games/web/games/sekiro_remake/manifest.json @@ -0,0 +1,33 @@ +{ + "schema": "bossbench/game-manifest@1", + "engine": "independent", + "game": "sekiro_remake", + "module": "SekiroGame", + "title": "Sekiro: Archer Swordsman / Valley Ape / Thread Ninja / Veteran Swordsman / Mounted Spearman / Blazing Beast", + "dimension": "3d", + "native_hz": 60, + "max_seconds": 300, + "renderer": "webgl-boss3d", + "rules": "sekiro@12", + "cases": [ + "sekiro/genichiro", + "sekiro/guardian_ape", + "sekiro/lady_butterfly", + "sekiro/isshin", + "sekiro/gyoubu", + "sekiro/demon" + ], + "scripts": [ + "_native/runtime.js", + "_boss3d/vendor/three.min.js", + "sekiro_remake/renderer3d.js", + "sekiro_remake/game.js", + "sekiro_remake/draw.js" + ], + "sim_scripts": [ + "_native/runtime.js", + "sekiro_remake/game.js" + ], + "play_page": "web/games/sekiro_remake/index.html", + "scripted_controller": "SekiroGame.scripted(game) -> {holds:[6 key arrays], mouse:[dx,dy,dz]} (deep-copy lookahead, deterministic; .oracle is an alias)" +} diff --git a/environments/games/web/games/sekiro_remake/renderer3d.js b/environments/games/web/games/sekiro_remake/renderer3d.js new file mode 100644 index 0000000000000000000000000000000000000000..4bb4b53d6bb531bdb5ac312ebdcd97bc7684005f --- /dev/null +++ b/environments/games/web/games/sekiro_remake/renderer3d.js @@ -0,0 +1,666 @@ +/* Sekiro renderer: original low-poly Three.js art (r160, MIT, vendored under _boss3d/vendor). Characters are rigid + * skinned meshes (one draw call each) posed from the simulation's action clocks; arenas are merged static meshes. + * Rendering is a pure function of the game state: it never writes game state and never draws from the game RNG. */ +(function(root){ + 'use strict'; + const T=root.THREE,B=root.Boss3D={}; + if(!T)throw Error('Offline Three.js renderer library is missing'); + const byCanvas=new WeakMap(),clamp=(x,a,b)=>Math.max(a,Math.min(b,x)),lerp=(a,b,u)=>a+(b-a)*u, + smooth=u=>{u=clamp(u,0,1);return u*u*(3-2*u);},band=(t,a,b)=>smooth((t-a)/(b-a)),v3=(x,y,z)=>new T.Vector3(x,y,z),items=a=>Array.isArray(a)?a:[]; + const M4=(x=0,y=0,z=0,rx=0,ry=0,rz=0,sx=1,sy=sx,sz=sx)=>new T.Matrix4().compose(v3(x,y,z),new T.Quaternion().setFromEuler(new T.Euler(rx,ry,rz)),v3(sx,sy,sz)); + const MY=(x,y,z,yaw,pitch,sx,sy,sz)=>new T.Matrix4().compose(v3(x,y,z),new T.Quaternion().setFromEuler(new T.Euler(pitch,yaw,0,'YXZ')),v3(sx,sy,sz)); + function hash(a,b=0){let n=Math.imul(a|0,374761393)^Math.imul(b|0,668265263);n=Math.imul(n^(n>>>13),1274126177);return ((n^(n>>>16))>>>0)/4294967296;} + // Template primitives, used only on the CPU while merging (never uploaded). + const P={box:new T.BoxGeometry(1,1,1),ball:new T.IcosahedronGeometry(1,1),gem:new T.IcosahedronGeometry(1,0),oct:new T.OctahedronGeometry(1,0), + cyl:(rt,rb,h,s=7)=>new T.CylinderGeometry(rt,rb,h,s,1),cone:(r,h,s=7)=>new T.ConeGeometry(r,h,s,1),disc:new T.CylinderGeometry(1,1,1,12,1)}; + // Mesher: merges primitives with per-face colours (slight jitter gives faceted fabric/fur/stone) and optional bone index. + class Mesher{ + constructor(){this.p=[];this.c=[];this.k=[];} + add(geo,color,m,bone=0,jitter=0){const g=geo.index?geo.toNonIndexed():geo.clone();g.applyMatrix4(m);const a=g.attributes.position.array,base=new T.Color(color),col=new T.Color(); + for(let i=0;i{const g=P.cyl(r0,r1,len,s);g.translate(0,-len/2,0);return g;}; + function canvasTexture(size,paint,repeat=1){const c=document.createElement('canvas');c.width=c.height=size;paint(c.getContext('2d'),size);const t=new T.CanvasTexture(c);t.colorSpace=T.SRGBColorSpace;t.wrapS=t.wrapT=T.RepeatWrapping;t.repeat.set(repeat,repeat);t.anisotropy=4;return t;} + function glowTexture(){return canvasTexture(64,(q,s)=>{const g=q.createRadialGradient(s/2,s/2,0,s/2,s/2,s/2);for(let i=0;i<=16;i++){const r=i/16,v=(r<.25?1-r*1.8:.55*(1-r)/.75)*(1-r*r*r*r);g.addColorStop(r,'rgba(255,255,255,'+v.toFixed(4)+')');}q.fillStyle=g;q.fillRect(0,0,s,s);});} + + /* ------------------------------------------------------------------ humanoid rig */ + const HUMAN=[['root',null,[0,0,0]],['hips','root',[0,.94,0]],['spine','hips',[0,.12,0]],['chest','spine',[0,.22,0]],['neck','chest',[0,.24,0]],['head','neck',[0,.08,0]], + ['lSh','chest',[.2,.17,0]],['lEl','lSh',[0,-.29,0]],['lWr','lEl',[0,-.25,0]],['rSh','chest',[-.2,.17,0]],['rEl','rSh',[0,-.29,0]],['rWr','rEl',[0,-.25,0]], + ['lHip','hips',[.1,-.03,0]],['lKnee','lHip',[0,-.44,0]],['lAnk','lKnee',[0,-.42,0]],['rHip','hips',[-.1,-.03,0]],['rKnee','rHip',[0,-.44,0]],['rAnk','rKnee',[0,-.42,0]], + ['blade','rWr',[0,-.07,.02]],['scab','hips',[.17,.02,-.04]],['tool','lWr',[0,-.06,.03]],['back','chest',[0,.06,-.16]],['tail','head',[0,.1,-.1]],['armor','chest',[0,0,0]],['skirt','hips',[0,0,0]],['sodeL','lSh',[0,0,0]],['sodeR','rSh',[0,0,0]]]; + function rig(bonesSpec){const bones={},list=[];for(const [name,parent,o] of bonesSpec){const b=new T.Bone();b.name=name;b.position.set(...o);if(parent)bones[parent].add(b);bones[name]=b;list.push(b);} + list[0].updateMatrixWorld(true);return {bones,list};} + function skinned(scene,r,build,{scale=1,roughness=.82,metalness=.05,shadow=true}={}){const m=new Mesher(),idx=n=>r.list.indexOf(r.bones[n]); + build((bone,geo,color,mat,jitter=0)=>{const bm=r.bones[bone].matrixWorld;m.add(geo,color,new T.Matrix4().multiplyMatrices(bm,mat),idx(bone),jitter);}); + const geo=scene.keep(m.geometry(true)),mat=scene.keep(new T.MeshStandardMaterial({vertexColors:true,flatShading:true,roughness,metalness})); + const mesh=new T.SkinnedMesh(geo,mat);mesh.add(r.list[0]);mesh.updateMatrixWorld(true);mesh.bind(new T.Skeleton(r.list));mesh.frustumCulled=false;mesh.castShadow=shadow;mesh.receiveShadow=false; + const holder=new T.Group();holder.add(mesh);holder.scale.setScalar(scale);return {holder,mesh,bones:r.bones,mat};} + // Shared limb kit for the three humans. + function limbs(add,c){ + add('lSh',seg(.3,.072,.06),c.sleeveL,M4(),.06);add('rSh',seg(.3,.072,.06),c.sleeveR,M4(),.06); + add('lEl',seg(.26,.058,.046),c.foreL,M4(),.04);add('rEl',seg(.26,.058,.046),c.foreR,M4(),.04); + add('lWr',P.ball,c.handL,M4(0,-.05,0,0,0,0,.05,.065,.045));add('rWr',P.ball,c.handR,M4(0,-.05,0,0,0,0,.05,.065,.045)); + for(const s of ['l','r']){add(s+'Hip',seg(.45,c.thighR||.1,c.thighR2||.085),c.thigh,M4(),.05);add(s+'Knee',seg(.42,.07,.055),c.shin,M4(),.04); + add(s+'Ank',P.box,c.foot,M4(0,-.05,.06,0,0,0,.1,.07,.24),.03);} + } + function katana(add,bone,steel=0xd9dde2){add(bone,P.box,0x17171a,M4(0,.1,0,0,0,0,.032,.24,.032));add(bone,P.disc,0x2a2622,M4(0,-.025,0,0,0,0,.06,.018,.06)); + add(bone,P.box,steel,M4(0,-.5,0,0,0,0,.012,.92,.034));add(bone,P.cone(.018,.07,4),steel,M4(0,-.995,0,Math.PI,0,0,1,1,.5));} + function sekiroModel(scene){const r=rig(HUMAN),c={sleeveL:0x3a3631,sleeveR:0x403b35,foreL:0x6e5b3a,foreR:0x3b3733,handL:0x4a4a4f,handR:0xb89377,thigh:0x3c3833,shin:0x9a9182,foot:0x2a2622,thighR:.12,thighR2:.115}; + return skinned(scene,r,add=>{ + add('hips',P.box,0x37332e,M4(0,-.02,0,0,0,0,.34,.18,.22),.04);add('spine',P.box,0x2f2c29,M4(0,.04,0,0,0,0,.32,.16,.2),.04);add('spine',P.box,0x1e1c1b,M4(0,.0,0,0,0,0,.34,.06,.22)); + add('chest',P.box,0x403a33,M4(0,.1,0,0,0,0,.4,.3,.23),.05);add('chest',P.box,0x8b8476,M4(.05,.16,.112,0,0,.5,.05,.24,.02));add('chest',P.box,0x8b8476,M4(-.05,.16,.112,0,0,-.5,.05,.24,.02)); + // ash scarf wrapped at the neck, its tail streaming behind + add('chest',P.cyl(.14,.17,.13,8),0xa69f92,M4(0,.27,-.01),.08);add('back',P.box,0xa69f92,M4(.06,-.14,0,.25,0,.15,.12,.34,.025),.08);add('back',P.box,0x989183,M4(-.04,-.22,-.02,.35,0,-.1,.09,.38,.02),.08); + add('neck',P.cyl(.05,.055,.1,6),0xb08c70,M4(0,.03,0));add('head',P.ball,0xb89377,M4(0,.1,.01,0,0,0,.1,.12,.105),.03); + add('head',P.ball,0x1c1917,M4(0,.165,-.04,0,0,0,.108,.085,.1),.06);add('head',P.box,0x1c1917,M4(0,.12,-.085,0,0,0,.17,.12,.06),.06);add('head',P.box,0x1c1917,M4(0,.22,-.07,-.5,0,0,.08,.1,.06),.06);add('tail',P.cone(.045,.22,5),0x1c1917,M4(0,.04,-.04,-2.2,0,0),.06); + add('head',P.box,0x241d1a,M4(.035,.115,.105,0,0,0,.028,.012,.01));add('head',P.box,0x241d1a,M4(-.035,.115,.105,0,0,0,.028,.012,.01)); + limbs(add,c); + // Shinobi prosthetic: brass and iron bands over the left forearm + for(let i=0;i<3;i++)add('lEl',P.cyl(.064,.064,.03,8),i%2?0x4b4c52:0x8d7442,M4(0,-.06-i*.07,0)); + katana(add,'blade');add('scab',P.box,0x141416,M4(0,0,0,0,0,0,.035,.9,.045),0);add('tool',P.ball,0x8a5a2b,M4(0,-.04,.02,0,0,0,.06,.08,.06)); + },{roughness:.86});} + function genichiroModel(scene){const r=rig(HUMAN),c={sleeveL:0xd4d0c6,sleeveR:0xd4d0c6,foreL:0x23232a,foreR:0x23232a,handL:0xb68c71,handR:0xb68c71,thigh:0x1b1b20,shin:0x26262c,foot:0x161618,thighR:.115,thighR2:.105}; + return skinned(scene,r,add=>{ + add('hips',P.box,0x1d1d22,M4(0,-.02,0,0,0,0,.35,.18,.23),.03);add('spine',P.box,0xd6d1c4,M4(0,.04,0,0,0,0,.32,.16,.2),.03);add('spine',P.box,0x2a2730,M4(0,0,0,0,0,0,.34,.06,.22)); + add('chest',P.box,0xd6d1c4,M4(0,.1,0,0,0,0,.39,.3,.23),.03);add('chest',P.box,0x1d1d22,M4(0,.13,.115,0,0,0,.08,.22,.01)); + add('neck',P.cyl(.05,.056,.1,6),0xb38a6f,M4(0,.03,0));add('head',P.ball,0xb68c71,M4(0,.1,.01,0,0,0,.1,.125,.105),.03); + add('head',P.ball,0x121214,M4(0,.165,-.045,0,0,0,.11,.085,.1),.05);add('head',P.box,0x121214,M4(0,.11,-.09,0,0,0,.18,.13,.06),.05);add('tail',P.box,0x121214,M4(0,-.1,-.02,.3,0,0,.06,.32,.04),.05); + add('head',P.box,0x2a1d1a,M4(.035,.115,.105,0,0,0,.03,.012,.01));add('head',P.box,0x2a1d1a,M4(-.035,.115,.105,0,0,0,.03,.012,.01)); + limbs(add,c);katana(add,'blade');add('scab',P.box,0x101012,M4(0,0,0,0,0,0,.036,.92,.046)); + // black lacquered armour with crimson lacing (removed for the Way of Tomoe) + add('armor',P.box,0x18181c,M4(0,.1,.005,0,0,0,.43,.31,.26),.04);add('armor',P.box,0x18181c,M4(0,.27,.0,0,0,0,.36,.06,.24),.04); + for(let i=0;i<4;i++)add('armor',P.box,0x8a2424,M4(0,-.01+i*.075,.133,0,0,0,.41,.014,.004)); + for(const [bone,s] of [['sodeL',1],['sodeR',-1]])for(let i=0;i<3;i++)add(bone,P.box,i%2?0x22222a:0x18181c,M4(s*.07,-.04-i*.075,0,0,0,s*.25,.05,.09,.24),.03),add(bone,P.box,0x8a2424,M4(s*.095,-.08-i*.075,0,0,0,s*.25,.004,.012,.24)); + for(const [x,z,ry] of [[0,.12,0],[0,-.12,0],[.15,0,1.57],[-.15,0,1.57]])for(let i=0;i<2;i++)add('skirt',P.box,i?0x7c2222:0x18181c,M4(x,-.14-i*.1,z,ry?0:(z>0?-.12:.12),ry,ry?(x>0?.12:-.12):0,.2,i?.012:.12,.03)); + // the great bow: in the left hand for shots, slung across the back otherwise + for(const bone of ['tool','back'])for(let i=-5;i<=5;i++){const a=i*.19,y=Math.sin(a)*.75,z=(Math.cos(a)-1)*.22;add(bone,P.box,0x221a14,M4(0,y+(bone==='back'?.05:0),z,-a,0,0,.022,.15,.03));} + add('tool',P.box,0xe8e2d4,M4(0,0,-.26,0,0,0,.004,1.45,.004)); + },{roughness:.6,metalness:.15});} + function isshinModel(scene){const r=rig([...HUMAN,['spear','rWr',[0,-.07,.02]],['gun','rWr',[0,-.07,.02]]]),c={sleeveL:0xc9c3b4,sleeveR:0xc9c3b4,foreL:0xa98a6e,foreR:0xa98a6e,handL:0xa98a6e,handR:0xa98a6e,thigh:0x34343c,shin:0x2b2b33,foot:0x1c1c20,thighR:.13,thighR2:.125}; + return skinned(scene,r,add=>{ + add('hips',P.box,0x2d2d35,M4(0,-.02,0,0,0,0,.36,.2,.25),.03);add('spine',P.box,0xa98a6e,M4(0,.04,0,0,0,0,.3,.16,.19),.03);add('spine',P.box,0x7a2a26,M4(0,-.04,0,0,0,0,.33,.07,.22)); + // the robe worn off the left shoulder over a bare, scarred chest + add('chest',P.box,0xa98a6e,M4(0,.1,0,0,0,0,.38,.3,.22),.03);add('chest',P.box,0xc9c3b4,M4(-.09,.1,.005,0,0,0,.22,.31,.235),.04);add('chest',P.box,0x8d6f58,M4(.08,.14,.113,0,0,.7,.012,.2,.004)); + add('neck',P.cyl(.052,.058,.1,6),0xa98a6e,M4(0,.03,0));add('head',P.ball,0xad8e72,M4(0,.1,.01,0,0,0,.1,.125,.105),.03); + // long white hair tied back, heavy brows and beard + add('head',P.ball,0xe6e3da,M4(0,.165,-.04,0,0,0,.115,.09,.105),.05);add('head',P.box,0xe6e3da,M4(0,.11,-.09,0,0,0,.19,.15,.06),.05);add('tail',P.box,0xe6e3da,M4(0,-.2,-.03,.25,0,0,.09,.52,.05),.06); + add('head',P.box,0xe6e3da,M4(0,.035,.09,.25,0,0,.1,.09,.04),.05);add('head',P.box,0xe6e3da,M4(.035,.118,.105,0,0,0,.038,.016,.012));add('head',P.box,0xe6e3da,M4(-.035,.118,.105,0,0,0,.038,.016,.012)); + limbs(add,c);katana(add,'blade');add('scab',P.box,0x1a1416,M4(0,0,0,0,0,0,.036,.92,.046)); + // wide hakama + for(const [x,z,ry] of [[0,.13,0],[0,-.13,0],[.17,0,1.57],[-.17,0,1.57]])for(let i=0;i<2;i++)add('skirt',P.box,i?0x26262d:0x34343c,M4(x,-.16-i*.17,z,ry?0:(z>0?-.1:.1),ry,ry?(x>0?.1:-.1):0,.24,.2,.03),.03); + // the long spear: held in the right hand, slung across the back between its moves + for(const [bone,o] of [['spear',[0,-.65,0]],['back',[0,0,0]]]){const tilt=bone==='back'?.5:0; + add(bone,P.box,0x3a2a1c,M4(o[0],o[1],o[2],0,0,tilt,.024,2.0,.024),.04);add(bone,P.box,0xd9dde2,M4(o[0]+Math.sin(tilt)*1.12,o[1]-Math.cos(tilt)*1.12,o[2],0,0,tilt,.012,.3,.05));add(bone,P.box,0xd9dde2,M4(o[0]+Math.sin(tilt)*1.02,o[1]-Math.cos(tilt)*1.02,o[2],0,0,tilt+1.57,.012,.26,.03));} + // the matchlock pistol + add('gun',P.box,0x2a1e16,M4(0,-.02,.02,0,0,0,.05,.13,.06));add('gun',P.box,0x24242a,M4(0,-.26,.03,0,0,0,.03,.42,.03));add('gun',P.box,0x8d7442,M4(0,-.1,.03,0,0,0,.042,.03,.042)); + },{roughness:.72,metalness:.08});} + function gyoubuModel(scene){const r=rig([...HUMAN,['spear','rWr',[0,-.07,.02]],['hBody','root',[0,1.32,0]],['hNeck','hBody',[0,.12,.72]],['hFL','hBody',[.2,-.1,.62]],['hFR','hBody',[-.2,-.1,.62]],['hBL','hBody',[.2,-.1,-.62]],['hBR','hBody',[-.2,-.1,-.62]]]),c={sleeveL:0x3a1416,sleeveR:0x3a1416,foreL:0x2a2024,foreR:0x2a2024,handL:0x8d6f58,handR:0x8d6f58,thigh:0x2d2226,shin:0x241c20,foot:0x151214,thighR:.12,thighR2:.1}; + return skinned(scene,r,add=>{ + // the rider: lacquered armour over crimson, a horned helm and a heavy beard + add('hips',P.box,0x2d2226,M4(0,-.02,0,0,0,0,.36,.2,.25),.03);add('spine',P.box,0x4a1a1c,M4(0,.04,0,0,0,0,.33,.17,.21),.03);add('chest',P.box,0x1f1c20,M4(0,.1,0,0,0,0,.42,.32,.26),.04); + for(let i=0;i<3;i++)add('chest',P.box,0x8a2424,M4(0,.0+i*.09,.134,0,0,0,.4,.016,.004)); + add('neck',P.cyl(.055,.06,.1,6),0x8d6f58,M4(0,.03,0));add('head',P.ball,0x94745c,M4(0,.1,.01,0,0,0,.11,.13,.11),.03);add('head',P.box,0x141214,M4(0,.03,.08,.2,0,0,.13,.11,.05),.05); + add('head',P.ball,0x1a181c,M4(0,.17,0,0,0,0,.135,.085,.13),.04);add('head',P.box,0x1a181c,M4(0,.13,-.02,0,0,0,.34,.018,.3));for(const s of [1,-1])add('head',P.cone(.03,.26,5),0xb09050,M4(s*.11,.29,.03,0,0,-s*.42)); + limbs(add,c);katana(add,'blade');add('scab',P.box,0x141214,M4(0,0,0,0,0,0,.036,.92,.046)); + // the long spear + add('spear',P.box,0x2c2118,M4(0,-.75,0,0,0,0,.028,2.5,.028),.04);add('spear',P.box,0xd9dde2,M4(0,-2.14,0,0,0,0,.014,.34,.06));add('spear',P.box,0xd9dde2,M4(0,-2.02,0,0,0,1.57,.014,.34,.035)); + // Onikage: a big dark horse with a red harness + add('hBody',P.box,0x201a1a,M4(0,0,0,0,0,0,.46,.5,1.5),.05);add('hBody',P.box,0x2a2120,M4(0,.04,-.62,0,0,0,.48,.52,.42),.05);add('hBody',P.box,0x6e1a1c,M4(0,.27,-.05,0,0,0,.5,.06,.62),.03); + add('hBody',P.box,0x141010,M4(0,.12,-.92,-.5,0,0,.08,.08,.62),.06); + add('hNeck',P.box,0x201a1a,M4(0,.22,.14,-.75,0,0,.2,.34,.7),.05);add('hNeck',P.box,0x141010,M4(0,.36,.02,-.75,0,0,.05,.3,.66),.06);add('hNeck',P.box,0x241d1c,M4(0,.54,.5,.35,0,0,.18,.2,.46),.05);for(const s of [1,-1])add('hNeck',P.cone(.03,.13,4),0x201a1a,M4(s*.06,.7,.36));add('hNeck',P.box,0x6e1a1c,M4(0,.56,.5,.35,0,0,.2,.03,.3)); + for(const [bone,s] of [['hFL',1],['hFR',-1],['hBL',1],['hBR',-1]]){add(bone,seg(.62,.075,.05),0x201a1a,M4(),.05);add(bone,seg(.56,.05,.04),0x1a1515,M4(0,-.58,0),.05);add(bone,P.box,0x0e0c0c,M4(0,-1.14,.02,0,0,0,.09,.07,.13));} + },{roughness:.68,metalness:.1});} + function butterflyModel(scene){const r=rig(HUMAN),c={sleeveL:0x574263,sleeveR:0x574263,foreL:0x574263,foreR:0x574263,handL:0xd8c2ad,handR:0xd8c2ad,thigh:0x382b40,shin:0xe9e3d8,foot:0xe9e3d8,thighR:.1,thighR2:.09}; + return skinned(scene,r,add=>{ + add('hips',P.box,0x4b3956,M4(0,-.02,0,0,0,0,.3,.17,.2),.05);add('spine',P.box,0x8a7d9a,M4(0,.03,0,0,0,0,.31,.14,.2),.04); + add('chest',P.box,0x574263,M4(0,.09,0,0,0,0,.33,.26,.2),.06);add('chest',P.box,0xcfc6d4,M4(.04,.15,.1,0,0,.5,.04,.2,.02));add('chest',P.box,0xcfc6d4,M4(-.04,.15,.1,0,0,-.5,.04,.2,.02)); + // butterfly crests on the sleeves and back + for(const [b,x] of [['lSh',.07],['rSh',-.07]])add(b,P.oct,0xe0ccff,M4(x,-.16,0,0,0,.8,.05,.035,.02));add('back',P.oct,0xe0ccff,M4(0,-.08,-.01,0,0,.8,.1,.06,.02));add('hips',P.oct,0xe0ccff,M4(.12,-.06,.1,0,0,.8,.05,.03,.02)); + add('neck',P.cyl(.045,.05,.09,6),0xd2bba6,M4(0,.03,0));add('head',P.ball,0xd8c2ad,M4(0,.1,.01,0,0,0,.092,.112,.098),.03); + add('head',P.ball,0xe8e6e2,M4(0,.16,-.04,0,0,0,.1,.08,.095),.05);add('head',P.box,0xe8e6e2,M4(0,.11,-.08,0,0,0,.16,.11,.05),.05);add('tail',P.ball,0xe8e6e2,M4(0,.04,-.04,0,0,0,.075,.065,.07),.05);add('tail',P.box,0x8d6a2c,M4(0,.05,-.05,0,0,1.3,.008,.18,.008)); + add('head',P.box,0x5a4038,M4(.03,.11,.095,0,0,0,.024,.01,.01));add('head',P.box,0x5a4038,M4(-.03,.11,.095,0,0,0,.024,.01,.01)); + limbs(add,c); + for(const b of ['blade','tool'])add(b,P.box,0x2c2c32,M4(0,-.14,0,0,0,0,.016,.22,.03)); + },{scale:.93,roughness:.8});} + // Guardian Ape: hunched white beast (S14: white fur, a red scar across the left eye, a nodachi through the neck). + const APE_BONES=[['root',null,[0,0,0]],['hips','root',[0,1.25,0]],['spine','hips',[0,.42,.12]],['chest','spine',[0,.5,.1]],['neck','chest',[0,.46,.42]],['head','neck',[0,.16,.22]], + ['lSh','chest',[.62,.28,.05]],['lEl','lSh',[0,-.78,0]],['lWr','lEl',[0,-.72,0]],['rSh','chest',[-.62,.28,.05]],['rEl','rSh',[0,-.78,0]],['rWr','rEl',[0,-.72,0]], + ['lHip','hips',[.32,-.08,0]],['lKnee','lHip',[0,-.6,0]],['lAnk','lKnee',[0,-.55,0]],['rHip','hips',[-.32,-.08,0]],['rKnee','rHip',[0,-.6,0]],['rAnk','rKnee',[0,-.55,0]], + ['neckBlade','neck',[0,.06,0]],['blade','rWr',[0,-.16,0]],['held','lWr',[0,-.2,.1]],['stump','neck',[0,.04,.04]]]; + function apeModel(scene){const r=rig(APE_BONES),fur=0xdedbd0,furD=0xbdb8ab,skin=0x8f4336; + return skinned(scene,r,add=>{ + add('hips',P.ball,furD,M4(0,.05,0,0,0,0,.52,.42,.46),.12);add('spine',P.ball,fur,M4(0,.12,0,0,0,0,.66,.55,.55),.12);add('chest',P.ball,fur,M4(0,.12,0,0,0,0,.82,.62,.62),.12); + add('chest',P.ball,0xc9a99a,M4(0,.0,.38,0,0,0,.45,.4,.2),.06); + for(let i=0;i<14;i++){const a=i/14*Math.PI*2;add('neck',P.cone(.14,.5,5),i%2?fur:furD,M4(Math.sin(a)*.35,.05,Math.cos(a)*.3-.05,Math.cos(a)*.9,0,-Math.sin(a)*.9),.15);} + add('head',P.ball,fur,M4(0,.12,-.02,0,0,0,.33,.32,.32),.12);add('head',P.ball,skin,M4(0,.08,.2,0,0,0,.22,.2,.16),.05); + add('head',P.box,0x2a1713,M4(.09,.15,.33,0,0,0,.05,.02,.02));add('head',P.box,0x2a1713,M4(-.09,.15,.33,0,0,0,.05,.02,.02));add('head',P.box,0xb3201a,M4(.1,.16,.34,0,0,1.1,.016,.13,.012)); + add('head',P.box,0x3b1b16,M4(0,-.02,.32,0,0,0,.12,.03,.03)); + for(const s of ['l','r']){add(s+'Sh',P.ball,fur,M4(0,-.05,0,0,0,0,.3,.3,.3),.12);add(s+'Sh',seg(.8,.24,.19),fur,M4(),.14);add(s+'El',seg(.72,.18,.15),furD,M4(),.14); + add(s+'Wr',P.ball,0x4a3b35,M4(0,-.1,.02,0,0,0,.17,.14,.2),.06); + add(s+'Hip',seg(.6,.26,.2),fur,M4(),.14);add(s+'Knee',seg(.55,.18,.14),furD,M4(),.14);add(s+'Ank',P.box,0x4a3b35,M4(0,-.06,.12,0,0,0,.22,.12,.4),.05);} + // the nodachi through its neck (phase 1) and the same blade in its right hand (headless phase) + add('neckBlade',P.box,0xcfd3d8,M4(0,0,0,0,0,1.5,.04,2.4,.1));add('neckBlade',P.box,0x2b2018,M4(-1.25,.02,0,0,0,1.5,.06,.4,.06)); + add('blade',P.box,0xcfd3d8,M4(0,-1.3,.0,0,0,0,.05,2.6,.12));add('blade',P.box,0x2b2018,M4(0,.05,0,0,0,0,.07,.42,.07)); + add('held',P.ball,fur,M4(0,0,0,0,0,0,.3,.28,.28),.12);add('held',P.ball,skin,M4(0,-.04,.18,0,0,0,.2,.18,.14),.05);add('held',P.box,0xb3201a,M4(.08,.02,.31,0,0,1.1,.016,.12,.012)); + add('stump',P.cyl(.24,.27,.12,8),0x7d1414,M4(0,0,0),.1);for(let i=0;i<6;i++)add('stump',P.ball,i%2?0x2a1712:0x4d2a1d,M4(Math.sin(i*1.1)*.05,.1+i*.07,Math.cos(i*1.3)*.04,0,0,0,.06,.045,.06)); + },{roughness:.95});} + + // The Demon of Hatred: a hulking burnt-red ogre with a horned head, a fire-wreathed left arm and a ragged cape (original procedural art). + const DEMON_BONES=APE_BONES.filter(([n])=>!['neckBlade','blade','held','stump'].includes(n)).map(([n,p,o])=>[n,p,n==='hips'?[0,1.9,0]:n==='lKnee'||n==='rKnee'?[0,-.9,0]:n==='lAnk'||n==='rAnk'?[0,-.85,0]:n==='lEl'||n==='rEl'?[0,-1.05,0]:n==='lWr'||n==='rWr'?[0,-.95,0]:n==='lSh'?[.85,.4,.05]:n==='rSh'?[-.85,.4,.05]:n==='chest'?[0,.6,.1]:n==='spine'?[0,.5,.1]:o]).concat([['flame','lWr',[0,-.2,0]],['cape','chest',[0,.3,-.4]]]); + function demonModel(scene){const r=rig(DEMON_BONES),skin=0x9a4634,dark=0x5a3026,horn=0xe6d6b0,ash=0x6a5e56; + return skinned(scene,r,add=>{ + add('hips',P.ball,dark,M4(0,.05,0,0,0,0,.7,.5,.58),.1);add('spine',P.ball,skin,M4(0,.12,0,0,0,0,.85,.62,.66),.12);add('chest',P.ball,skin,M4(0,.15,0,0,0,0,1.05,.75,.78),.12); + for(let i=0;i<5;i++)add('chest',P.box,0x1d1210,M4(-.4+i*.2,.1,.68,0,0,(i-2)*.25,.04,.5,.04)); + add('neck',P.ball,skin,M4(0,.1,.1,0,0,0,.42,.38,.42),.1);add('head',P.ball,0x6a3026,M4(0,.15,.1,0,0,0,.4,.36,.4),.1);add('head',P.box,0x1a0d0b,M4(0,.02,.42,0,0,0,.36,.12,.1)); + for(const s of [1,-1]){add('head',P.box,0xffb040,M4(s*.14,.2,.46,0,0,0,.08,.035,.02));add('head',P.cone(.1,.62,5),horn,M4(s*.3,.42,0,-.3,0,-s*.7),.05);add('head',P.cone(.06,.32,5),horn,M4(s*.18,.48,.18,.4,0,-s*.3),.04);} + for(let i=0;i<9;i++){const a=(i/8-.5)*2.2;add('head',P.cone(.1,.5,4),0xd8d0c0,M4(Math.sin(a)*.38,.25-Math.abs(a)*.08,-.22,-.9-Math.abs(a)*.2,0,-a*.6),.12);} + for(const s of ['l','r']){add(s+'Sh',P.ball,skin,M4(0,-.05,0,0,0,0,.42,.42,.42),.1);add(s+'Sh',seg(1.05,.3,.24),s==='l'?0x3a1610:skin,M4(),.12);add(s+'El',seg(.95,.24,.19),s==='l'?0x241008:dark,M4(),.12); + add(s+'Wr',P.ball,0x1d100c,M4(0,-.14,.03,0,0,0,.24,.2,.28),.06);for(let k=0;k<3;k++)add(s+'Wr',P.cone(.04,.22,4),horn,M4((k-1)*.1,-.36,.1,.3,0,0)); + add(s+'Hip',seg(.9,.32,.26),dark,M4(),.12);add(s+'Knee',seg(.85,.24,.2),skin,M4(),.12);add(s+'Ank',P.box,0x1d100c,M4(0,-.08,.16,0,0,0,.34,.16,.56),.05);} + // the burning left arm: glowing cracks and a crown of flame at the fist + for(let i=0;i<6;i++)add('lEl',P.box,0xff7a2a,M4(Math.sin(i*1.7)*.18,-.15-i*.13,.18,0,0,i*.4,.03,.16,.02)); + for(let i=0;i<7;i++){const a=i/7*Math.PI*2;add('flame',P.cone(.12,.55,5),i%2?0xff9a32:0xffd060,M4(Math.sin(a)*.14,.1,Math.cos(a)*.14,Math.cos(a)*.5,0,-Math.sin(a)*.5));} + for(let i=0;i<5;i++)add('cape',P.box,i%2?ash:0x2a2420,M4(-.6+i*.3,-.9,0,.15,0,(i-2)*.08,.32,1.8,.04),.15); + },{roughness:.9});} + /* ------------------------------------------------------------------ poses */ + const J=['hips','spine','chest','neck','head','lSh','lEl','lWr','rSh','rEl','rWr','lHip','lKnee','lAnk','rHip','rKnee','rAnk','blade']; + const pose=o=>{const p={y:0,lean:0};for(const j of J)p[j]=o[j]||[0,0,0];if('y' in o)p.y=o.y;return p;}; + function mixPose(a,b,u){if(u<=0)return a;if(u>=1)return b;const p={y:lerp(a.y,b.y,u)};for(const j of J)p[j]=[lerp(a[j][0],b[j][0],u),lerp(a[j][1],b[j][1],u),lerp(a[j][2],b[j][2],u)];return p;} + const add3=(p,j,v)=>{p[j]=[p[j][0]+v[0],p[j][1]+v[1],p[j][2]+v[2]];}; + // Shared human poses. Arms hang along -Y; negative shoulder X raises an arm forward; the blade runs along the hand. + const H={ + stance:pose({y:-.05,spine:[.1,0,0],chest:[.04,.2,0],head:[-.06,-.15,0],rSh:[-.45,0,-.28],rEl:[-.75,0,0],rWr:[-.85,0,0],lSh:[-.35,0,.2],lEl:[-.9,0,0], + lHip:[-.32,0,.06],lKnee:[.5,0,0],lAnk:[-.18,0,0],rHip:[.15,0,-.08],rKnee:[.4,0,0],rAnk:[-.25,0,0]}), + guard:pose({y:-.08,spine:[.12,0,0],chest:[.05,.35,0],head:[-.05,-.3,0],rSh:[-1.25,0,-.15],rEl:[-1.05,0,0],rWr:[-.25,0,1.35],lSh:[-.9,0,.25],lEl:[-1.3,0,0], + lHip:[-.35,0,.06],lKnee:[.55,0,0],lAnk:[-.2,0,0],rHip:[.2,0,-.08],rKnee:[.45,0,0],rAnk:[-.25,0,0]}), + raise:pose({y:-.04,spine:[-.05,0,0],chest:[-.05,.55,0],head:[0,-.4,0],rSh:[-2.55,0,-.35],rEl:[-.55,0,0],rWr:[-.2,0,0],lSh:[-.6,0,.3],lEl:[-.8,0,0], + lHip:[-.3,0,.06],lKnee:[.4,0,0],lAnk:[-.15,0,0],rHip:[.25,0,-.08],rKnee:[.35,0,0],rAnk:[-.2,0,0]}), + cut:pose({y:-.12,spine:[.3,0,0],chest:[.15,-.65,0],head:[-.1,.45,0],rSh:[-.75,0,.55],rEl:[-.15,0,0],rWr:[-.25,0,0],lSh:[-.2,0,.45],lEl:[-.5,0,0], + lHip:[-.6,0,.06],lKnee:[.7,0,0],lAnk:[-.15,0,0],rHip:[.35,0,-.08],rKnee:[.25,0,0],rAnk:[-.3,0,0]}), + backRaise:pose({y:-.05,chest:[0,-.6,0],head:[0,.45,0],rSh:[-1.6,0,.9],rEl:[-1.2,0,0],rWr:[-.3,0,0],lSh:[-.4,0,.3],lEl:[-.7,0,0],lHip:[-.3,0,.06],lKnee:[.4,0,0],rHip:[.2,0,-.08],rKnee:[.35,0,0]}), + backCut:pose({y:-.1,spine:[.2,0,0],chest:[.1,.7,0],head:[-.05,-.45,0],rSh:[-1.25,0,-1.0],rEl:[-.2,0,0],rWr:[-.3,0,0],lSh:[-.3,0,.3],lEl:[-.6,0,0],lHip:[-.5,0,.06],lKnee:[.6,0,0],rHip:[.3,0,-.08],rKnee:[.3,0,0]}), + pull:pose({y:-.1,spine:[.2,0,0],chest:[.1,.6,0],head:[-.05,-.5,0],rSh:[-.25,0,-.35],rEl:[-1.7,0,0],rWr:[-1.35,0,0],lSh:[-.8,0,.3],lEl:[-.9,0,0],lHip:[-.45,0,.06],lKnee:[.65,0,0],rHip:[.35,0,-.08],rKnee:[.45,0,0],rAnk:[-.3,0,0]}), + lunge:pose({y:-.2,spine:[.35,0,0],chest:[.15,-.25,0],head:[-.2,.2,0],rSh:[-1.55,0,0],rEl:[-.05,0,0],rWr:[-1.55,0,0],lSh:[.3,0,.35],lEl:[-.3,0,0],lHip:[-.95,0,.06],lKnee:[1.0,0,0],lAnk:[-.1,0,0],rHip:[.55,0,-.08],rKnee:[.15,0,0],rAnk:[-.3,0,0]}), + low:pose({y:-.42,spine:[.55,0,0],chest:[.15,.5,0],head:[-.35,-.4,0],rSh:[-.5,0,-.9],rEl:[-.2,0,0],rWr:[-1.4,0,0],lSh:[-.4,0,.4],lEl:[-.6,0,0],lHip:[-1.1,0,.2],lKnee:[1.45,0,0],lAnk:[-.35,0,0],rHip:[.3,0,-.3],rKnee:[1.2,0,0],rAnk:[-.2,0,0]}), + lowCut:pose({y:-.42,spine:[.55,0,0],chest:[.15,-.75,0],head:[-.35,.4,0],rSh:[-.6,0,.95],rEl:[-.1,0,0],rWr:[-1.45,0,0],lSh:[-.2,0,.6],lEl:[-.4,0,0],lHip:[-1.1,0,.2],lKnee:[1.45,0,0],lAnk:[-.35,0,0],rHip:[.3,0,-.3],rKnee:[1.2,0,0],rAnk:[-.2,0,0]}), + overhead:pose({y:0,spine:[-.15,0,0],chest:[-.1,0,0],head:[.1,0,0],rSh:[-2.9,0,-.1],rEl:[-.2,0,0],rWr:[-.3,0,0],lSh:[-2.8,0,.1],lEl:[-.3,0,0],lHip:[-.2,0,.06],lKnee:[.3,0,0],rHip:[.1,0,-.06],rKnee:[.3,0,0]}), + chop:pose({y:-.25,spine:[.6,0,0],chest:[.2,0,0],head:[-.4,0,0],rSh:[-1.1,0,-.05],rEl:[-.1,0,0],rWr:[-.6,0,0],lSh:[-1.1,0,.05],lEl:[-.1,0,0],lHip:[-.8,0,.06],lKnee:[.9,0,0],rHip:[.4,0,-.06],rKnee:[.3,0,0]}), + reach:pose({y:-.15,spine:[.45,0,0],chest:[.1,-.3,0],head:[-.3,.2,0],lSh:[-1.5,0,.1],lEl:[-.1,0,0],rSh:[-.2,0,-.3],rEl:[-.5,0,0],rWr:[-.8,0,0],lHip:[-.9,0,.06],lKnee:[.9,0,0],rHip:[.5,0,-.06],rKnee:[.2,0,0]}), + kick:pose({y:-.02,spine:[-.2,0,0],chest:[-.1,.2,0],rSh:[-.4,0,-.5],rEl:[-.6,0,0],rWr:[-.8,0,0],lSh:[-.4,0,.5],lEl:[-.6,0,0],lHip:[-1.45,0,.05],lKnee:[.1,0,0],lAnk:[.4,0,0],rHip:[.15,0,-.05],rKnee:[.3,0,0]}), + draw:pose({y:-.02,chest:[0,-.95,0],head:[0,.9,0],lSh:[-1.55,0,.1],lEl:[0,0,0],lWr:[0,0,0],rSh:[-1.5,0,-.3],rEl:[-2.3,0,0],lHip:[-.25,0,.15],lKnee:[.25,0,0],rHip:[.2,0,-.15],rKnee:[.25,0,0]}), + release:pose({y:-.02,chest:[0,-.95,0],head:[0,.9,0],lSh:[-1.55,0,.1],lEl:[0,0,0],rSh:[-1.2,0,-1.1],rEl:[-.6,0,0],lHip:[-.25,0,.15],lKnee:[.25,0,0],rHip:[.2,0,-.15],rKnee:[.25,0,0]}), + tuck:pose({y:.1,spine:[.3,0,0],chest:[.1,0,0],rSh:[-1.2,0,-.4],rEl:[-1.0,0,0],rWr:[-.5,0,0],lSh:[-1.0,0,.4],lEl:[-1.1,0,0],lHip:[-1.4,0,.1],lKnee:[1.9,0,0],rHip:[-1.0,0,-.1],rKnee:[1.7,0,0]}), + hurt:pose({y:-.06,spine:[-.25,0,0],chest:[-.2,.2,0],head:[-.35,0,.15],rSh:[-.2,0,-.7],rEl:[-.4,0,0],rWr:[-.5,0,0],lSh:[-.2,0,.7],lEl:[-.4,0,0],lHip:[.1,0,.1],lKnee:[.3,0,0],rHip:[.35,0,-.1],rKnee:[.3,0,0]}), + kneel:pose({y:-.48,spine:[.55,0,0],chest:[.25,.1,0],head:[.45,0,0],rSh:[-.25,0,-.25],rEl:[-.4,0,0],rWr:[-.2,0,0],lSh:[-.1,0,.25],lEl:[-.4,0,0],lHip:[-1.45,0,.1],lKnee:[1.5,0,0],lAnk:[-.1,0,0],rHip:[.25,0,-.1],rKnee:[1.75,0,0],rAnk:[.3,0,0]}), + drink:pose({y:-.03,spine:[-.05,0,0],chest:[-.1,.1,0],head:[-.45,0,0],lSh:[-1.9,0,.5],lEl:[-1.8,0,0],rSh:[-.3,0,-.25],rEl:[-.4,0,0],rWr:[-.6,0,0],lHip:[-.15,0,.06],lKnee:[.2,0,0],rHip:[.1,0,-.06],rKnee:[.2,0,0]}), + cast:pose({y:-.02,chest:[-.1,-.3,0],head:[-.2,.3,0],rSh:[-2.6,0,-.4],rEl:[-.3,0,0],lSh:[-.9,0,.4],lEl:[-.6,0,0],lHip:[-.2,0,.06],lKnee:[.2,0,0],rHip:[.1,0,-.06],rKnee:[.2,0,0]}), + spread:pose({y:-.02,spine:[-.15,0,0],chest:[-.2,0,0],head:[-.4,0,0],rSh:[-.4,0,-1.4],rEl:[-.2,0,0],lSh:[-.4,0,1.4],lEl:[-.2,0,0],lHip:[-.1,0,.1],rHip:[-.1,0,-.1]}), + hover:pose({y:0,spine:[.1,0,0],chest:[0,0,0],head:[.3,0,0],rSh:[-.9,0,-.9],rEl:[-.6,0,0],rWr:[-.5,0,0],lSh:[-.9,0,.9],lEl:[-.6,0,0],lHip:[-1.2,0,.25],lKnee:[1.6,0,0],rHip:[-.2,0,-.2],rKnee:[.6,0,0]}), + aim:pose({y:-.04,chest:[0,-.5,0],head:[0,.45,0],rSh:[-1.55,0,.2],rEl:[0,0,0],rWr:[-1.5,0,0],lSh:[-.35,0,.3],lEl:[-.7,0,0],lHip:[-.3,0,.1],lKnee:[.35,0,0],rHip:[.2,0,-.1],rKnee:[.3,0,0]}), + dead:pose({y:-.9,spine:[-.2,0,0],head:[-.3,.5,0],rSh:[-.1,0,-1.3],lSh:[-.2,0,1.1],lHip:[-.2,0,.2],lKnee:[.3,0,0],rHip:[.1,0,-.2],rKnee:[.5,0,0]}) + }; + const ISSHIN_SPEAR=/^(spear_|lightning_|three_thrust|retreat_sweep|stomp|double_disc|leap_slam)/; + function walkCycle(p,phase,amount,run){if(amount<=0)return p;const s=Math.sin(phase),c=Math.cos(phase),a=amount*(run?1.15:.75);const q={...p}; + add3(q,'lHip',[-s*a,0,0]);add3(q,'rHip',[s*a,0,0]);add3(q,'lKnee',[Math.max(0,c)*a*1.1,0,0]);add3(q,'rKnee',[Math.max(0,-c)*a*1.1,0,0]); + add3(q,'lSh',[s*a*.5,0,0]);add3(q,'chest',[0,s*a*.18,0]);q.y=p.y+Math.abs(c)*.035*amount-(run?.05:0);if(run)add3(q,'spine',[.18,0,0]);return q;} + // Melee timeline for a move: windup -> strike -> follow-through around each contact tick; alternate fore/back hands. + function strikePose(base,hits,t,o={}){let p=base;const W=o.wind||12,F=o.follow||10; + for(let i=0;ik+F+6)continue;const back=(o.alternate!==false)&&i%2===1; + const type=h.type||'slash',raise=type==='thrust'?H.pull:type==='sweep'?H.low:type==='slam'?H.overhead:type==='grab'?H.stance:type==='kick'?H.stance:back?H.backRaise:H.raise; + const hitP=type==='thrust'?H.lunge:type==='sweep'?H.lowCut:type==='slam'?H.chop:type==='grab'?H.reach:type==='kick'?H.kick:back?H.backCut:H.cut; + if(t{e.preventDefault();this.ready=false;this.error='WebGL context lost';}); + this.world=new T.Scene();this.world.fog=new T.Fog(0xb0a9a3,30,90); + this.camera=new T.PerspectiveCamera(50,854/480,.1,260); + this.hemi=new T.HemisphereLight(0xd8e2f0,0x5a4a3c,1.4);this.world.add(this.hemi); + this.sun=new T.DirectionalLight(0xffe2b5,2.6);this.sun.castShadow=true;this.sun.shadow.mapSize.set(1024,1024); + const sc=this.sun.shadow.camera;sc.left=-14;sc.right=14;sc.top=14;sc.bottom=-14;sc.near=1;sc.far=80;this.sun.shadow.bias=-.0006;this.sun.shadow.normalBias=.03; + this.world.add(this.sun);this.world.add(this.sun.target); + this.flashLight=new T.PointLight(0xffe7b0,0,40,1.6);this.world.add(this.flashLight); + this.glowTex=this.keep(glowTexture()); + this.mats={add:this.keep(new T.MeshBasicMaterial({color:0xffffff,transparent:true,opacity:1,blending:T.AdditiveBlending,depthWrite:false,fog:false})), + soft:this.keep(new T.MeshBasicMaterial({color:0xffffff,transparent:true,opacity:.55,depthWrite:false})), + solid:this.keep(new T.MeshStandardMaterial({color:0xffffff,roughness:.6,metalness:.2,flatShading:true})), + glow:this.keep(new T.MeshBasicMaterial({map:this.glowTex,color:0xffffff,transparent:true,blending:T.AdditiveBlending,depthWrite:false,fog:false})), + ghost:this.keep(new T.MeshStandardMaterial({color:0x9fd8ff,emissive:0x4a8cc8,emissiveIntensity:.7,transparent:true,opacity:.42,roughness:.4,flatShading:true,depthWrite:false}))}; + this.geo={box:this.keep(new T.BoxGeometry(1,1,1)),ball:this.keep(new T.IcosahedronGeometry(1,0)),ring:this.keep(new T.TorusGeometry(1,.035,4,40)),quad:this.keep(new T.PlaneGeometry(1,1)), + wing:this.keep((()=>{const g=new T.BufferGeometry();g.setAttribute('position',new T.Float32BufferAttribute([0,0,0,.5,.1,.35,.55,.05,-.15, 0,0,0,-.5,.1,.35,-.55,.05,-.15],3));g.computeVertexNormals();return g;})())}; + this.player=sekiroModel(this);this.world.add(this.player.holder); + this.bosses={genichiro:genichiroModel(this),ape:apeModel(this),butterfly:butterflyModel(this),isshin:isshinModel(this),gyoubu:gyoubuModel(this),demon:demonModel(this)};for(const m of Object.values(this.bosses)){m.holder.visible=false;this.world.add(m.holder);} + const sev=new Mesher();sev.add(P.ball,0xdedbd0,M4(0,0,0,0,0,0,.33,.32,.32),0,.12);sev.add(P.ball,0x8f4336,M4(0,-.04,.2,0,0,0,.22,.2,.16),0,.05);sev.add(P.box,0xb3201a,M4(.1,.04,.34,0,0,1.1,.016,.13,.012));sev.add(P.disc,0x7d1414,M4(0,-.3,0,0,0,0,.22,.04,.22)); + this.severed=new T.Mesh(this.keep(sev.geometry()),this.material(0xffffff,{vertex:true,roughness:.95}));this.severed.castShadow=true;this.severed.visible=false;this.world.add(this.severed); + this.ghosts=[];const ghostGeo=this.keep((()=>{const m=new Mesher();m.add(P.cyl(.16,.26,.95,6),0xffffff,M4(0,.6,0));m.add(P.ball,0xffffff,M4(0,1.22,.05,0,0,0,.13,.15,.13));m.add(P.cone(.36,.16,8),0xffffff,M4(0,1.36,.03)); + m.add(seg(.55,.05,.04),0xffffff,M4(.2,1.0,.08,-1.2,0,.2));m.add(P.box,0xffffff,M4(.22,.85,.6,-.2,0,0,.02,.04,.4));return m.geometry();})()); + for(let i=0;i<6;i++){const g=new T.Mesh(ghostGeo,this.mats.ghost);g.visible=false;this.world.add(g);this.ghosts.push(g);} + this.pool=(geo,mat,n)=>{const m=new T.InstancedMesh(geo,mat,n);m.count=0;m.frustumCulled=false;m.instanceColor=new T.InstancedBufferAttribute(new Float32Array(n*3),3);this.world.add(m);this.keep(m);return m;}; + this.fx={spark:this.pool(this.geo.box,this.mats.add,96),flash:this.pool(this.geo.quad,this.mats.glow,24),blood:this.pool(this.geo.ball,this.keep(new T.MeshBasicMaterial({color:0xffffff})),64), + bolt:this.pool(this.geo.box,this.mats.add,90),proj:this.pool(this.geo.box,this.mats.solid,48),wings:this.pool(this.geo.wing,this.keep(new T.MeshBasicMaterial({color:0xffffff,side:T.DoubleSide,transparent:true,opacity:.9,blending:T.AdditiveBlending,depthWrite:false,fog:false})),64), + puff:this.pool(this.geo.ball,this.keep(new T.MeshBasicMaterial({color:0xffffff,transparent:true,opacity:.28,depthWrite:false})),48),rings:this.pool(this.geo.ring,this.mats.add,10), + mote:this.pool(this.geo.ball,this.mats.add,90),leaf:this.pool(this.geo.quad,this.keep(new T.MeshBasicMaterial({color:0xffffff,side:T.DoubleSide})),40),flame:this.pool(this.keep(new T.ConeGeometry(1,1,6)),this.keep(new T.MeshBasicMaterial({color:0xffffff})),260)}; + this.dummy=new T.Object3D();this.tmp=new T.Color(); + // Sword trails: a ribbon per fighter, rebuilt from the pose clock (past ticks are re-evaluated, no history kept). + this.trails=[0,1].map(()=>{const g=this.keep(new T.BufferGeometry()),n=6;g.setAttribute('position',new T.BufferAttribute(new Float32Array(n*2*3),3).setUsage(T.DynamicDrawUsage)); + g.setAttribute('color',new T.BufferAttribute(new Float32Array(n*2*4),4).setUsage(T.DynamicDrawUsage));const ix=[];for(let i=0;i{const g=q.createLinearGradient(0,0,0,s);g.addColorStop(0,top);g.addColorStop(.55,mid);g.addColorStop(1,low);q.fillStyle=g;q.fillRect(0,0,s,s); + for(let i=0;i<26;i++){const y=s*(.35+hash(i,3)*.4),x=hash(i,5)*s,w=s*(.2+hash(i,9)*.5);q.fillStyle=`rgba(255,240,225,${.05+hash(i,11)*.08})`;q.beginPath();q.ellipse(x,y,w,4+hash(i,13)*9,0,0,Math.PI*2);q.fill();q.beginPath();q.ellipse(x-s,y,w,4+hash(i,13)*9,0,0,Math.PI*2);q.fill();}})); + tex.wrapT=T.ClampToEdgeWrapping;tex.repeat.set(1,1);const dome=new T.Mesh(this.keep(new T.SphereGeometry(200,24,12,0,Math.PI*2,0,Math.PI*.62)),this.keep(new T.MeshBasicMaterial({map:tex,side:T.BackSide,fog:false,depthWrite:false}))); + dome.rotation.x=0;dome.position.y=-30;group.add(dome); + if(sunDir){const sun=new T.Sprite(this.keep(new T.SpriteMaterial({map:this.glowTex,color:sunColor,transparent:true,blending:T.AdditiveBlending,depthWrite:false,fog:false})));sun.position.copy(sunDir.clone().multiplyScalar(170));sun.scale.setScalar(55);group.add(sun);} + return dome;} + + /* ---------------- arenas */ + arena(kind){if(this.arenas[kind])return this.arenas[kind];const group=new T.Group();group.visible=false;this.world.add(group); + const a=kind==='genichiro'?this.castleTop(group):kind==='ape'?this.wateringHole(group):kind==='isshin'?this.silvergrass(group):kind==='gyoubu'?this.castleGate(group):kind==='demon'?this.burningGate(group):this.audienceChamber(group);a.group=group;this.arenas[kind]=a;return a;} + castleTop(group){ + const stone=this.material(0xffffff,{map:canvasTexture(512,(q,s)=>{q.fillStyle='#4a4641';q.fillRect(0,0,s,s);const n=8,w=s/n; + for(let y=0;y{for(let k=0;k<4;k++){const out=.9+k*1.15,y=-.42-k*.5,ox=cx+Math.sin(ry)*out,oz=cz+Math.cos(ry)*out;roof.add(P.box,0x34414c,MY(ox,y,oz,ry,.42,len+k*2.3,.16,1.3),0,.05); + for(let i=-len/2-k;i<=len/2+k;i+=.6)roof.add(P.box,0x27313a,MY(ox+Math.cos(ry)*i,y+.1,oz-Math.sin(ry)*i,ry,.42,.08,.09,1.3),0,.03);}}; + skirt(0,6.6,17,0);skirt(0,-6.6,17,Math.PI);skirt(8.6,0,13,Math.PI/2);skirt(-8.6,0,13,-Math.PI/2); + for(const [x,z] of [[-9.4,-7.2],[9.4,-7.2],[-9.4,7.2],[9.4,7.2]]){const yaw=Math.atan2(x,z);roof.add(P.box,0x34414c,MY(x,-.75,z,yaw,.5,1.6,.2,3.2),0,.04);gold.add(P.cone(.16,.7,5),0xc99a45,MY(x*1.12,-.2,z*1.12,yaw,-.9,1,1,1),0,.08);} + // gold shachihoko on the ridge ends of the keep roof below + for(const s of [-1,1]){gold.add(P.ball,0xd2a24c,M4(s*8.9,-1.2,-8.9,0,0,s*.3,.28,.5,.22),0,.08);gold.add(P.cone(.2,.5,5),0xd2a24c,M4(s*8.9,-.7,-9.05,-.6,0,0),0,.08);} + // lower castle tiers and the town, stepping away below the keep + for(let i=0;i<9;i++){const a=-1.2+i*.3,r=26+(i%3)*6,x=Math.sin(a)*r,z=-Math.cos(a)*r,y=-9-(i%3)*3,w=4+hash(i,1)*3; + wall.add(P.box,0xd7d1c2,M4(x,y,z,0,a,0,w,2.4,w*.7),0,.03);roof.add(P.cone(w*.86,1.7,4),0x2f3b45,M4(x,y+2.0,z,0,a+Math.PI/4,0,1,1,.75),0,.04); + for(let k=-1;k<=1;k++)wall.add(P.box,0x24201c,M4(x+Math.cos(a)*k*w*.3,y+.2,z+Math.sin(a)*k*w*.3,0,a,0,.5,.7,w*.72),0,.02);} + for(let i=0;i<40;i++){const a=hash(i,21)*Math.PI*2,r=48+hash(i,22)*40,y=-22+hash(i,23)*4;far.add(P.box,0x6f6c6a,M4(Math.sin(a)*r,y,Math.cos(a)*r,0,a,0,3+hash(i,24)*4,2.5,3),0,.08);} + const mats={wood:this.material(0xffffff,{vertex:true,roughness:.92}),roof:this.material(0xffffff,{vertex:true,roughness:.7,metalness:.1}),wall:this.material(0xffffff,{vertex:true}),gold:this.material(0xffffff,{vertex:true,roughness:.35,metalness:.75}),far:this.material(0xffffff,{vertex:true,roughness:1})}; + this.static(group,wood,mats.wood);this.static(group,roof,mats.roof);this.static(group,wall,mats.wall,false);this.static(group,gold,mats.gold,false);this.static(group,far,mats.far,false); + this.ridges(group,[0x5b6475,0x75808f,0x98a0ad],[46,70,100],-14,18); + const sunDir=v3(-.82,.3,-.2).normalize();this.sky(group,'#3d5470','#c9a98f','#f2c58f',sunDir,0xffc98a); + return {sun:v3(-.72,.62,.3).normalize(),sunColor:0xffd09a,sunI:2.7,hemiSky:0xc8d4e8,hemiGround:0x6a5444,hemiI:1.45,fog:0xc4a994,fogNear:28,fogFar:120,exposure:1.05,shadowR:11,leaves:true};} + ridges(group,colors,radii,base,height){for(let layer=0;layer{const a=i*Math.PI/32,k=.45+.16*Math.sin(a*3+layer*1.7)+.12*Math.sin(a*7+1)+.08*Math.cos(a*13);return [Math.sin(a)*rad,base+h*k,Math.cos(a)*rad];}; + const geo=new T.BufferGeometry(),pos=[];for(let i=0;i<64;i++){const p=pt(i),q=pt(i+1);pos.push(p[0],base-30,p[2],p[0],p[1],p[2],q[0],q[1],q[2],p[0],base-30,p[2],q[0],q[1],q[2],q[0],base-30,q[2]);} + geo.setAttribute('position',new T.Float32BufferAttribute(pos,3));geo.computeVertexNormals();const mesh=new T.Mesh(this.keep(geo),this.material(colors[layer],{side:T.DoubleSide,roughness:1}));group.add(mesh);}} + wateringHole(group){ + const ground=this.material(0xffffff,{map:canvasTexture(512,(q,s)=>{q.fillStyle='#5e6a45';q.fillRect(0,0,s,s);for(let i=0;i<2600;i++){const v=hash(i,1);q.fillStyle=v<.5?`rgba(90,104,60,${.5})`:`rgba(120,110,80,${.35})`;q.fillRect(hash(i,2)*s,hash(i,3)*s,3+hash(i,4)*6,2+hash(i,5)*4);}},6),roughness:1}); + const floor=new T.Mesh(this.keep(new T.CylinderGeometry(20,20,.4,48)),ground);floor.position.y=-.2;floor.receiveShadow=true;group.add(floor); + const water=new T.Mesh(this.keep(new T.CircleGeometry(9.5,48)),this.material(0x3f7f86,{transparent:true,opacity:.62,roughness:.12,metalness:.3,flat:false}));water.rotation.x=-Math.PI/2;water.position.y=.03;water.receiveShadow=true;group.add(water); + const rock=new Mesher(),grass=new Mesher(),tree=new Mesher(),lotus=new Mesher(); + for(let i=0;i<34;i++){const a=i/34*Math.PI*2+hash(i,1)*.2,r=16.5+hash(i,2)*3,h=7+hash(i,3)*12,w=2.6+hash(i,4)*2.5;rock.add(P.gem,i%3?0x6a665e:0x5d5a52,M4(Math.sin(a)*r,h/2-1,Math.cos(a)*r,hash(i,5),a,hash(i,6)*.3,w,h/2,w*.8),0,.12); + if(i%2)grass.add(P.cone(.9,1.6,5),0x4e6b38,M4(Math.sin(a)*(r-1.2),h*.8,Math.cos(a)*(r-1.2),0,a,.4),0,.12);} + for(let i=0;i<220;i++){const a=hash(i,7)*Math.PI*2,r=9.6+hash(i,8)*5.2;grass.add(P.cone(.07+hash(i,9)*.05,.5+hash(i,10)*.9,3),hash(i,11)<.5?0x7f9a4a:0x99a35a,M4(Math.sin(a)*r,.3,Math.cos(a)*r,(hash(i,12)-.5)*.5,a,(hash(i,13)-.5)*.5),0,.15);} + for(let i=0;i<14;i++){const a=hash(i,14)*Math.PI*2,r=10+hash(i,15)*4;rock.add(P.gem,0x77736a,M4(Math.sin(a)*r,.1,Math.cos(a)*r,hash(i,16),hash(i,17),0,.4+hash(i,18)*.7,.3+hash(i,19)*.4,.5),0,.1);} + for(let i=0;i<16;i++){const a=hash(i,24)*Math.PI*2,r=2+hash(i,25)*6.5;lotus.add(P.disc,0x4f7a3c,M4(Math.sin(a)*r,.05,Math.cos(a)*r,0,0,0,.35,.02,.35));if(i%3===0)lotus.add(P.cone(.12,.18,6),0xe7c6d4,M4(Math.sin(a)*r,.16,Math.cos(a)*r));} + // a great tree leaning over the pool, hung with vines + tree.add(seg(11,.9,1.3,8),0x4c3b2c,M4(-11,11,-9,.12,0,.18),0,.1);for(let i=0;i<9;i++)tree.add(P.gem,0x3d5a31,M4(-9+hash(i,30)*5-2.5,10.5+hash(i,31)*2,-7.5+hash(i,32)*4-2,hash(i,33),hash(i,34),0,2.4,1.6,2.4),0,.12); + for(let i=0;i<7;i++)tree.add(P.box,0x3e5a2e,M4(-8.5+i*.9,7.5,-6.4+i*.3,0,0,0,.05,4+hash(i,35)*2,.05)); + const mats={rock:this.material(0xffffff,{vertex:true}),grass:this.material(0xffffff,{vertex:true,side:T.DoubleSide}),tree:this.material(0xffffff,{vertex:true}),lotus:this.material(0xffffff,{vertex:true})}; + this.static(group,rock,mats.rock);this.static(group,grass,mats.grass,false);this.static(group,tree,mats.tree);this.static(group,lotus,mats.lotus,false); + this.ridges(group,[0x55604f,0x6b7766,0x8a9586],[34,52,80],-4,16); + const sunDir=v3(.35,.85,-.4).normalize();this.sky(group,'#7d98a8','#c5cfc9','#e4e5d6',sunDir,0xfff1d2); + return {sun:sunDir,sunColor:0xfff0d6,sunI:2.4,hemiSky:0xdde8e4,hemiGround:0x4e5a3c,hemiI:1.35,fog:0xb7c2b5,fogNear:24,fogFar:95,exposure:1.0,shadowR:16,water};} + audienceChamber(group){ + const planks=this.material(0xffffff,{map:canvasTexture(512,(q,s)=>{for(let y=0;y<16;y++){const v=58+Math.round(hash(y,1)*22);q.fillStyle=`rgb(${v+16},${v},${v-12})`;q.fillRect(0,y*s/16,s,s/16-2); + for(let i=0;i<30;i++){q.fillStyle=`rgba(20,12,8,${hash(i,y)*.25})`;q.fillRect(hash(i,y+5)*s,y*s/16+hash(i,y+9)*s/16,30+hash(i,y+3)*60,1);}}},3),roughness:.55}); + const floor=new T.Mesh(this.keep(new T.BoxGeometry(19.6,.3,15.6)),planks);floor.position.y=-.15;floor.receiveShadow=true;group.add(floor); + const wood=new Mesher(),paper=new Mesher(),dark=new Mesher(),fire=new Mesher(); + const pillars=[-6.6,-2.2,2.2,6.6].flatMap(x=>[[x,-4.6],[x,4.6]]); + for(const [x,z] of pillars){wood.add(P.cyl(.42,.46,5.6,10),0x6d3d2c,M4(x,2.8,z),0,.05);wood.add(P.cyl(.47,.5,.09,10),0x2a1a12,M4(x,1.0,z));wood.add(P.cyl(.47,.5,.09,10),0x2a1a12,M4(x,3.0,z));wood.add(P.cyl(.47,.5,.09,10),0x2a1a12,M4(x,4.9,z));wood.add(P.box,0x2b1a14,M4(x,.12,z,0,0,0,1.1,.24,1.1));wood.add(P.box,0x3a2219,M4(x,5.45,z,0,0,0,1.0,.3,1.0));} + for(const z of [-4.6,4.6])wood.add(P.box,0x4a281d,M4(0,5.3,z,0,0,0,19.4,.42,.5));for(const x of [-6.6,-2.2,2.2,6.6])wood.add(P.box,0x4a281d,M4(x,5.55,0,0,0,0,.45,.4,15.4)); + dark.add(P.box,0x1b120e,M4(0,5.95,0,0,0,0,19.8,.2,15.8)); + // shoji walls lit from behind by the burning estate; some panels burnt through + for(const z of [-7.75,7.75])for(let x=-9;x<9;x+=1.5){const burnt=hash(Math.round(x*3),z>0?1:2)<.22;(burnt?fire:paper).add(P.box,burnt?0xff7a2a:0xe7b98a,M4(x+.75,2.3,z,0,0,0,1.38,3.8,.04)); + wood.add(P.box,0x2a1a12,M4(x,2.3,z,0,0,0,.08,4.6,.1));for(let y=.5;y<4.3;y+=.6)wood.add(P.box,0x2a1a12,M4(x+.75,y,z,0,0,0,1.5,.04,.06));} + for(const x of [-9.75,9.75])for(let z=-7.5;z<7.5;z+=1.5){paper.add(P.box,0xd9a679,M4(x,2.3,z+.75,0,0,0,.04,3.8,1.38));wood.add(P.box,0x2a1a12,M4(x,2.3,z,0,0,0,.1,4.6,.08));} + for(const s of [-1,1])wood.add(P.box,0x2a1a12,M4(0,4.35,s*7.7,0,0,0,19.6,.25,.2)); + const mats={wood:this.material(0xffffff,{vertex:true,roughness:.7}),paper:this.material(0xffffff,{vertex:true,emissive:0xff9a4a,emissiveIntensity:.42,roughness:1}),dark:this.material(0xffffff,{vertex:true}),fire:this.keep(new T.MeshBasicMaterial({vertexColors:true,fog:false}))}; + this.static(group,wood,mats.wood);this.static(group,paper,mats.paper,false);this.static(group,dark,mats.dark,false);const f=new T.Mesh(this.keep(fire.geometry()),mats.fire);group.add(f); + // illusory strands between the pillar tops (S17: she walks on threads strung around the hall) + const lines=[];const tops=pillars.map(([x,z])=>[x,4.6,z]);for(let i=0;i{const l=new T.PointLight(0xff8a3a,6,14,1.4);l.position.set(...p);group.add(l);return l;}); + return {sun:v3(.3,1,.25).normalize(),sunColor:0xb4c2ee,sunI:2.1,hemiSky:0x7a7fa6,hemiGround:0x4a2e20,hemiI:1.9,fog:0x231915,fogNear:14,fogFar:44,exposure:1.3,shadowR:12,fireLights,embers:true,background:0x140d0b};} + + /* ---------------- per-frame */ + // Original set for the final duel: a wide field of silver grass under a low sun, cliffs and a far castle (S27). + silvergrass(group){ + const ground=this.material(0xffffff,{map:canvasTexture(512,(q,s)=>{q.fillStyle='#8d8a6a';q.fillRect(0,0,s,s);for(let i=0;i<3000;i++){const v=hash(i,1);q.fillStyle=v<.5?'rgba(170,165,125,.45)':'rgba(92,92,66,.4)';q.fillRect(hash(i,2)*s,hash(i,3)*s,2+hash(i,4)*7,1+hash(i,5)*2);}},6),roughness:1}); + const floor=new T.Mesh(this.keep(new T.CylinderGeometry(60,60,.4,48)),ground);floor.position.y=-.2;floor.receiveShadow=true;group.add(floor); + const grass=new Mesher(),rock=new Mesher(),far=new Mesher(); + // low trampled tufts inside the fighting circle, full stems with pale plumes outside it + for(let i=0;i<150;i++){const a=hash(i,6)*Math.PI*2,r=2+hash(i,7)*10.6;grass.add(P.cone(.05+hash(i,8)*.04,.22+hash(i,9)*.2,3),hash(i,10)<.5?0xa8a47c:0x8f9068,M4(Math.sin(a)*r,.13,Math.cos(a)*r,(hash(i,11)-.5)*.5,a,(hash(i,12)-.5)*.5),0,.12);} + for(let i=0;i<620;i++){const a=hash(i,13)*Math.PI*2,r=13.4+hash(i,14)*hash(i,14)*24,h=.9+hash(i,15)*1.1,x=Math.sin(a)*r,z=Math.cos(a)*r,lean=.15+hash(i,16)*.3; + grass.add(P.cone(.028,h,3),hash(i,17)<.5?0xc2bd8c:0xaeb07f,M4(x,h/2,z,0,a,lean),0,.1);grass.add(P.gem,hash(i,18)<.6?0xf6f1e2:0xe8e1c8,M4(x+Math.sin(lean)*h*.5,h+.02,z,lean,a,0,.03,.13,.03),0,.06);} + for(let i=0;i<30;i++){const a=i/30*Math.PI*2+hash(i,19)*.2,r=52+hash(i,20)*10,h=5+hash(i,21)*8,w=4+hash(i,22)*4;rock.add(P.gem,i%3?0x9a9586:0xa8a292,M4(Math.sin(a)*r,h/2-1,Math.cos(a)*r,hash(i,23),a,hash(i,24)*.3,w,h/2,w*.8),0,.12);} + // the far castle keep on its rise, as a silhouette + for(let i=0;i<4;i++){const w=9-i*1.7,y=11+i*2.8;far.add(P.box,0x4a4b52,M4(-40,y,-74,0,0,0,w,2.3,w));far.add(P.box,0x33343a,M4(-40,y+1.35,-74,0,0,0,w*1.3,.45,w*1.3));}far.add(P.box,0x55565a,M4(-40,4,-74,0,0,0,18,10,18),0,.05); + const mats={grass:this.material(0xffffff,{vertex:true,side:T.DoubleSide}),rock:this.material(0xffffff,{vertex:true}),far:this.material(0xffffff,{vertex:true})}; + this.static(group,grass,mats.grass,false);this.static(group,rock,mats.rock);this.static(group,far,mats.far); + this.ridges(group,[0x62687a,0x7b8294,0x9da3b1],[60,84,120],-6,20); + const sunDir=v3(-.55,.6,-.55).normalize();this.sky(group,'#7d8aa3','#d6b89a','#f0d7ae',sunDir,0xffe2b0); + return {sun:sunDir,sunColor:0xffe7c4,sunI:2.3,hemiSky:0xdde0e6,hemiGround:0x6f6c50,hemiI:1.3,fog:0xd8c9ad,fogNear:22,fogFar:92,exposure:1,shadowR:15,plumes:true};} + // Original set: a wide packed-earth yard before a castle gate at dusk, low walls, a burning brazier ring and far ridges (S31 names only "a large arena"). + castleGate(group){ + const ground=this.material(0xffffff,{map:canvasTexture(512,(q,s)=>{q.fillStyle='#6d5f4a';q.fillRect(0,0,s,s);for(let i=0;i<3200;i++){q.fillStyle=hash(i,1)<.5?'rgba(120,104,82,.45)':'rgba(70,60,46,.4)';q.fillRect(hash(i,2)*s,hash(i,3)*s,2+hash(i,4)*6,1+hash(i,5)*3);}},8),roughness:1}); + const floor=new T.Mesh(this.keep(new T.CylinderGeometry(70,70,.4,48)),ground);floor.position.y=-.2;floor.receiveShadow=true;group.add(floor); + const wall=new Mesher(),wood=new Mesher(),roof=new Mesher(),fire=new Mesher(); + for(let i=0;i<40;i++){const a=i/40*Math.PI*2,r=23,x=Math.sin(a)*r,z=Math.cos(a)*r;wall.add(P.box,i%2?0x8a8476:0x7c7668,M4(x,1.1,z,0,a,0,3.9,2.2,.9),0,.08);roof.add(P.box,0x2e2c30,M4(x,2.35,z,0,a,0,4.3,.25,1.5),0,.05);} + // the gate across the far side, in timber with a tiled roof + wood.add(P.box,0x3a2a20,M4(0,3.4,-23.4,0,0,0,9,6.8,1.2),0,.05);wood.add(P.box,0x241a14,M4(0,2.6,-22.7,0,0,0,5,5.2,.3),0,.05);for(const x of [-3.6,3.6])wood.add(P.box,0x2c2018,M4(x,3.4,-22.6,0,0,0,.6,6.8,.6));roof.add(P.box,0x26252a,M4(0,7.2,-23.4,0,0,0,12,.7,3.2));roof.add(P.box,0x1f1e22,M4(0,7.9,-23.4,0,0,0,8,.6,2)); + for(let i=0;i<8;i++){const a=(i+.5)/8*Math.PI*2,x=Math.sin(a)*21,z=Math.cos(a)*21;wood.add(P.cyl(.14,.2,1.5,6),0x2c2420,M4(x,.75,z),0,.05);fire.add(P.cone(.17,.42,6),0xff8a3a,M4(x,1.66,z));} + const mats={wall:this.material(0xffffff,{vertex:true}),wood:this.material(0xffffff,{vertex:true}),roof:this.material(0xffffff,{vertex:true}),fire:this.keep(new T.MeshBasicMaterial({vertexColors:true}))}; + this.static(group,wall,mats.wall);this.static(group,wood,mats.wood);this.static(group,roof,mats.roof);this.static(group,fire,mats.fire,false); + this.ridges(group,[0x4f4a58,0x635c68,0x847a80],[60,84,120],-6,20); + const sunDir=v3(.5,.5,-.7).normalize();this.sky(group,'#58607c','#c79a84','#efc79a',sunDir,0xffd8a8); + return {sun:sunDir,sunColor:0xffdcb8,sunI:2.2,hemiSky:0xd6d6e4,hemiGround:0x5e5240,hemiI:1.25,fog:0xc9b49c,fogNear:30,fogFar:130,exposure:1,shadowR:18};} + // The gate yard again, burning: the same wall ring, charred timber, fires everywhere, a red sky and embers (S36). + burningGate(group){ + const ground=this.material(0xffffff,{map:canvasTexture(512,(q,s)=>{q.fillStyle='#5a4636';q.fillRect(0,0,s,s);for(let i=0;i<3200;i++){q.fillStyle=hash(i,1)<.5?'rgba(96,70,52,.45)':'rgba(28,20,16,.45)';q.fillRect(hash(i,2)*s,hash(i,3)*s,2+hash(i,4)*6,1+hash(i,5)*3);}},8),roughness:1}); + const floor=new T.Mesh(this.keep(new T.CylinderGeometry(70,70,.4,48)),ground);floor.position.y=-.2;floor.receiveShadow=true;group.add(floor); + const wall=new Mesher(),wood=new Mesher(),roof=new Mesher(),fire=new Mesher(); + for(let i=0;i<40;i++){const a=i/40*Math.PI*2,r=21,x=Math.sin(a)*r,z=Math.cos(a)*r;wall.add(P.box,i%2?0x4e4842:0x423c38,M4(x,1.1,z,0,a,0,3.4,2.2,.9),0,.08);if(i%3)roof.add(P.box,0x1c1a1c,M4(x,2.35,z,0,a,.06*(i%4-1.5),3.8,.25,1.5),0,.05); + if(i%4===1)for(let k=0;k<3;k++)fire.add(P.cone(.35-k*.08,1.2+k*.3,6),k%2?0xff7a2a:0xffb84a,M4(x*.98+k*.3-.3,2.9+k*.3,z*.98));} + wood.add(P.box,0x241a14,M4(0,3.4,-21.4,0,0,0,9,6.8,1.2),0,.05);wood.add(P.box,0x140e0a,M4(0,2.6,-20.7,0,0,0,5,5.2,.3),0,.05);for(const x of [-3.6,3.6])wood.add(P.box,0x1c140e,M4(x,3.4,-20.6,0,0,0,.6,6.8,.6));roof.add(P.box,0x1a191c,M4(0,7.2,-21.4,.06,0,.05,12,.7,3.2)); + for(let i=0;i<9;i++){const x=-4+i,h=1+hash(i,7)*1.6;fire.add(P.cone(.5,h+.6,6),i%2?0xff6a20:0xffa840,M4(x,7.6+h*.3,-21.4));} + for(let i=0;i<10;i++){const a=(i+.5)/10*Math.PI*2,x=Math.sin(a)*18.4,z=Math.cos(a)*18.4;wood.add(P.box,0x1a120e,M4(x,.4,z,.2,a,.3,1.6,.3,.3),0,.05);fire.add(P.cone(.3,.9+hash(i,3)*.6,6),0xff8a3a,M4(x,.9,z));} + const mats={wall:this.material(0xffffff,{vertex:true}),wood:this.material(0xffffff,{vertex:true}),roof:this.material(0xffffff,{vertex:true}),fire:this.keep(new T.MeshBasicMaterial({vertexColors:true}))}; + this.static(group,wall,mats.wall);this.static(group,wood,mats.wood);this.static(group,roof,mats.roof);this.static(group,fire,mats.fire,false); + this.ridges(group,[0x2a1c1c,0x3a2424,0x52302a],[60,84,120],-6,20); + const sunDir=v3(-.4,.45,-.8).normalize();this.sky(group,'#1e1014','#7a2a1c','#e0743a',sunDir,0xff9a50); + return {sun:sunDir,sunColor:0xffb27a,sunI:1.8,hemiSky:0xe0a890,hemiGround:0x6a4030,hemiI:1.6,fog:0x5a3428,fogNear:30,fogFar:120,exposure:1.2,shadowR:18,embersWide:true};} + setArena(kind){if(this.kind===kind)return;for(const [k,a] of Object.entries(this.arenas))a.group.visible=false;const a=this.arena(kind);a.group.visible=true;this.kind=kind; + for(const [k,m] of Object.entries(this.bosses))m.holder.visible=k===kind; + this.world.background=a.background!=null?new T.Color(a.background):null;this.world.fog.color.set(a.fog);this.world.fog.near=a.fogNear;this.world.fog.far=a.fogFar; + this.hemi.color.set(a.hemiSky);this.hemi.groundColor.set(a.hemiGround);this.sun.color.set(a.sunColor);this.renderer.toneMappingExposure=a.exposure; + const sc=this.sun.shadow.camera;sc.left=-a.shadowR;sc.right=a.shadowR;sc.top=a.shadowR;sc.bottom=-a.shadowR;sc.updateProjectionMatrix();} + place(pool,i,pos,scale,rot,color){if(i>=pool.instanceMatrix.count)return i;const d=this.dummy;d.position.set(pos[0],pos[1],pos[2]); + if(Array.isArray(scale))d.scale.set(scale[0],scale[1],scale[2]);else d.scale.setScalar(scale);if(rot&&rot.isQuaternion)d.quaternion.copy(rot);else d.rotation.set(...(rot||[0,0,0])); + d.updateMatrix();pool.setMatrixAt(i,d.matrix);pool.setColorAt(i,this.tmp.set(color??0xffffff));return i+1;} + dir(dx,dy,dz){const a=v3(dx,dy,dz);if(a.lengthSq()<1e-12)return new T.Quaternion();return new T.Quaternion().setFromUnitVectors(v3(0,0,1),a.normalize());} + link(pool,i,a,b,w,color){const dx=b[0]-a[0],dy=b[1]-a[1],dz=b[2]-a[2];return this.place(pool,i,[(a[0]+b[0])/2,(a[1]+b[1])/2,(a[2]+b[2])/2],[w,w,Math.hypot(dx,dy,dz)],this.dir(dx,dy,dz),color);} + finish(pool,n){pool.count=n;pool.instanceMatrix.needsUpdate=true;if(pool.instanceColor)pool.instanceColor.needsUpdate=true;} + playerPose(p,tm){const a=String(p.action||''),t=Number(p.actionTick||0);let q=H.stance; + const moving=a==='walk'||a==='run'; + if(p.dead)q=H.dead; + else if(a==='posture_break'||a==='safety_roll')q=mixPose(H.hurt,H.kneel,band(t,0,8)); + else if(a==='hurt')q=mixPose(H.hurt,H.stance,band(t,6,16)); + else if(a==='heal')q=mixPose(H.stance,H.drink,band(t,0,10)*(1-band(t,56,66))); + else if(a==='revive')q=mixPose(H.kneel,H.stance,band(t,10,48)); + else if(a==='deathblow')q=t<26?mixPose(H.pull,H.lunge,band(t,12,20)):mixPose(H.lunge,H.cut,band(t,30,44)); + else if(p.charge>0)q=mixPose(H.stance,H.pull,band(p.charge,0,8)); + else if(p.attackTick>=0)q=p.attackKind==='thrust'?(p.attackTick<10?mixPose(H.pull,H.lunge,band(p.attackTick,6,10)):mixPose(H.lunge,H.stance,band(p.attackTick,18,34))): + (p.attackTick<5?mixPose(H.stance,H.raise,band(p.attackTick,0,4)):p.attackTick<9?mixPose(H.raise,H.cut,band(p.attackTick,5,8)):mixPose(H.cut,H.stance,band(p.attackTick,12,25))); + else if(p.y>0)q=p.stomped&&p.vy>0?H.kick:H.tuck; + else if(p.dodgeTicks>0)q=mixPose(H.stance,H.low,.45); + else if(p.guarding)q=p.guardAge<6?mixPose(H.guard,H.backCut,.35*(1-p.guardAge/6)):H.guard; + if(moving&&!p.guarding)q=walkCycle(q,tm*(a==='run'?13:9),1,a==='run');else if(moving)q=walkCycle(q,tm*7,.5,false); + return q;} + posePlayer(g){const p=g.player,m=this.player,a=String(p.action||''),t=Number(p.actionTick||0),tm=g.t/60; + applyPose(m,this.playerPose(p,tm));const b=m.bones;b.sodeL.scale.setScalar(.001);b.sodeR.scale.setScalar(.001);b.tool.scale.setScalar(a==='heal'?1:.001);b.blade.scale.setScalar(1);b.scab.rotation.set(.5,0,.2);b.back.rotation.set(.3+Math.sin(tm*3)*.08,0,0); + const dead=p.dead?1:0,lie=dead?-1.45*band(t,0,24):0; + m.holder.position.set(p.x||0,(p.y||0)+(dead?.12:0),p.z||0);m.holder.rotation.set(0,p.yaw||0,0);m.mesh.rotation.set(lie,0,0); + return m;} + humanPose(g,b,moves,kind){const a=String(b.action||''),mv=moves?.[a],t=Number(b.state==='attack'?b.moveTick:b.actionTick||0),tm=g.t/60;let q=H.stance,tool=false; + if(b.state==='execution'||b.action==='deathblow')q=mixPose(H.kneel,H.dead,band(t,20,50)); + else if(b.state==='deathblow'||a==='posture_break')q=mixPose(H.hurt,H.kneel,band(t,0,10)); + else if(a==='stagger'||a==='rising')q=a==='rising'&&kind==='genichiro'?mixPose(H.kneel,H.stance,band(t,4,36)):H.hurt; + else if(b.state==='attack'&&mv){ + const bow=/bow|volley|charged|quick_bow|opening/.test(a)&&kind==='genichiro'; + if(bow&&(mv.shots||[]).length&&!(a==='bow_roll'&&t>46)&&!(a==='opening'&&t>30)){tool=true;const shot=(mv.shots||[]).find(s=>t<=s+10)??mv.shots.at(-1);q=tt<=x+7)??mv.gun.at(-1);q=mixPose(H.stance,H.aim,band(t,at-14,at-6)*(1-band(t,at+8,at+16)));} + else if(kind==='isshin'&&(mv.waves||mv.stomp))q=strikePose(H.stance,[...mv.hits,...(mv.waves||[]).map(([at,w])=>({t:at,type:w==='v'?'slam':'sweep'})),...(mv.stomp||[]).map(at=>({t:at,type:'slam'}))].sort((x,y)=>x.t-y.t),t,{wind:12,follow:10}); + else if(kind==='butterfly'&&(a==='thread_up'||a==='thread_hover'||a==='waltz'))q=H.hover; + else if(kind==='butterfly'&&(a==='illusion'||a==='dispel'))q=mixPose(H.stance,H.cast,band(t,8,24)*(1-band(t,40,56))); + else if(kind==='butterfly'&&a==='kunai_throw'||mv.kunai&&!mv.hits.length){const k=(mv.kunai||[]).find(([s])=>t<=s+8);q=k?mixPose(H.backRaise,H.cut,band(t,k[0]-4,k[0])):H.stance;} + else q=strikePose(H.stance,mv.hits,t,{wind:kind==='butterfly'?8:12,follow:kind==='butterfly'?7:10}); + if(kind==='butterfly'&&(a==='leg_drop'||a==='three_strike')&&b.y>.3)q=mixPose(q,H.tuck,.6); + if(kind==='butterfly'&&a==='sweep')q=mixPose(q,H.low,.7); + } + const moving=kind!=='gyoubu'&&b.state==='idle'&&Math.hypot((g.player.x||0)-(b.x||0),(g.player.z||0)-(b.z||0))>2.4;if(moving)q=walkCycle(q,tm*8,.8,false); + if(kind==='gyoubu'){q={...q,y:.72+(q.y||0)*.25,lHip:[-.95,0,.75],rHip:[-.95,0,-.75],lKnee:[1.25,0,0],rKnee:[1.25,0,0],lAnk:[-.3,0,0],rAnk:[-.3,0,0]};} + return {q,tool};} + poseHuman(g,m,b,moves,kind){const a=String(b.action||''),t=Number(b.state==='attack'?b.moveTick:b.actionTick||0),tm=g.t/60,{q,tool}=this.humanPose(g,b,moves,kind); + applyPose(m,q);const bones=m.bones;bones.tool.scale.setScalar(tool?1:.001);if(kind==='genichiro')bones.tool.rotation.set(tool?1.45:0,0,0); + if(kind==='genichiro'){const armored=b.form_id!=='tomoe'||(a==='tomoe_awaken'&&t<40);for(const n of ['armor','skirt','sodeL','sodeR'])bones[n].scale.setScalar(armored?1:.001);bones.back.scale.setScalar(tool?.001:1);} + if(kind!=='genichiro'){bones.tool.scale.setScalar(1);bones.back.scale.setScalar(1);bones.sodeL.scale.setScalar(.001);bones.sodeR.scale.setScalar(.001);} + // Which weapon he holds follows the move: spear, matchlock or katana; the slung spear appears with his second life (S27). + if(kind==='isshin'){const st=b.state==='attack',spear=st&&ISSHIN_SPEAR.test(a),gun=st&&/^(quad_shot|quick_gun)$/.test(a);bones.spear.scale.setScalar(spear?1:.001);bones.gun.scale.setScalar(gun?1:.001);bones.blade.scale.setScalar(spear||gun?.001:1);bones.back.scale.setScalar((b.phase||1)>=3&&!spear?1:.001);bones.active=spear?bones.spear:null;} + if(kind==='gyoubu'){bones.blade.scale.setScalar(.001);bones.back.scale.setScalar(.001);bones.tool.scale.setScalar(.001);bones.active=bones.spear; + const mv=root.SekiroGame?.bosses?.gyoubu?.moves?.[a],run=b.state==='attack'&&(mv?.ride||mv?.away)?1:b.state==='idle'?.35:0,ph=tm*(run>.5?15:7),amp=run>.5?.75:.28*run/.35; + for(const [n,o] of [['hFL',0],['hBR',.4],['hFR',1.6],['hBL',2]])bones[n].rotation.set(Math.sin(ph+o)*amp,0,0);bones.hBody.rotation.set((b.y||0)>.3?-.28:Math.sin(ph*2)*.03*run,0,0);bones.hBody.position.y=1.32+Math.abs(Math.sin(ph))*.07*run;bones.hNeck.rotation.set(Math.sin(ph)*.1*run,0,0);} + bones.scab.rotation.set(.5,0,.2);bones.tail.rotation.set(.2+Math.sin(tm*2.5)*.06,0,0); + const lie=(b.state==='execution'?-1.4*band(t,24,50):0);m.holder.position.set(b.x||0,b.y||0,b.z||0);m.holder.rotation.set(0,b.yaw||0,0);m.mesh.rotation.set(lie,0,0); + const flash=(b.flash||0)/8;m.mat.emissive.setRGB(.3*flash,.25*flash,.25*flash);m.mat.emissiveIntensity=1; + return {};} + poseApe(g,m,b){applyPose(m,this.apePose(g,b),{hipY:1.25});const bn=m.bones,head=b.form_id==='headless'; + const off=head||b.state==='dead';bn.head.scale.setScalar(off?.001:1);bn.neckBlade.scale.setScalar(off?.001:1);bn.blade.scale.setScalar(head?1:.001);bn.held.scale.setScalar(head?1:.001);bn.stump.scale.setScalar(off?1:.001); + m.holder.position.set(b.x||0,b.y||0,b.z||0);m.holder.rotation.set(0,b.yaw||0,0); + // the severed head lies beside the body during the false Shinobi Execution (S14) + this.severed.visible=b.state==='dead';if(this.severed.visible){const s=Math.sin(b.yaw||0),c=Math.cos(b.yaw||0);this.severed.position.set((b.x||0)+s*1.8+c*.8,.28,(b.z||0)+c*1.8-s*.8);this.severed.rotation.set(.4,(b.yaw||0)+2.2,.5);} + const flash=(b.flash||0)/8;m.mat.emissive.setRGB(.3*flash,.25*flash,.25*flash); + return {};} + // The demon stands upright on the ape-style rig; each move gets a readable key pose from its hit times. + poseDemon(g,m,b){const a=String(b.action||''),mv=root.SekiroGame?.bosses?.demon?.moves?.[a],t=Number(b.state==='attack'?b.moveTick:b.actionTick||0),tm=g.t/60; + const q={hips:[.15,0,0],spine:[.12,0,0],chest:[.08,0,0],neck:[-.2,0,0],head:[-.1,0,0],lSh:[-.3,0,.35],lEl:[-.5,0,0],lWr:[0,0,0],rSh:[-.25,0,-.35],rEl:[-.4,0,0],rWr:[0,0,0],lHip:[-.25,0,.12],lKnee:[.4,0,0],lAnk:[-.15,0,0],rHip:[-.25,0,-.12],rKnee:[.4,0,0],rAnk:[-.15,0,0],y:-.1}; + const set=(j,x,y,z)=>{q[j]=[x,y,z];},ad=(j,x,y,z)=>{q[j]=[q[j][0]+x,q[j][1]+y,q[j][2]+z];}; + if(b.state==='idle'){const s=Math.sin(tm*4);ad('lHip',-s*.25,0,0);ad('rHip',s*.25,0,0);ad('chest',Math.abs(s)*.05,0,0);} + if(b.state==='attack'&&mv){const hits=mv.hits||[],near=hits.find(h=>t>=h.t-20&&t<=h.t+12); + const arm=(side,u,v)=>{ad(side+'Sh',-2.6*u+2.4*v,0,0);ad(side+'El',-.4*u,0,0);ad('chest',0,(side==='l'?1:-1)*(.5*u-1.0*v),0);}; + if(near){const u=band(t,near.t-18,near.t-4),v=band(t,near.t-3,near.t+1); + if(near.type==='slam'&&/stomp/.test(a)){const side=a==='double_stomp'&&hits.indexOf(near)===1?'r':a==='double_stomp'?'l':'r';ad(side+'Hip',-1.3*u+1.3*v,0,0);ad(side+'Knee',1.0*u-1.0*v,0,0);} + else if(a==='headbutt'){ad('chest',-.6*u+1.1*v,0,0);ad('neck',-.4*u+.6*v,0,0);} + else if(near.type==='sweep'){set('rSh',-.5,0,-.2);ad('hips',.7*u,0,0);ad('rSh',-.8*u,0,-1.2*u+1.6*v);} + else arm(near.noDeflect||a==='whip_slam'?'l':'r',u,v);} + if(mv.ride&&t>=mv.ride[0]&&t.3;if(air){set('lHip',-1.4,0,.3);set('rHip',-1.4,0,-.3);set('lKnee',1.6,0,0);set('rKnee',1.6,0,0);set('lSh',-2.4,0,.6);set('rSh',-2.4,0,-.6);}else if(tt<=x+8)??0;const u=band(t,at-20,at-4),v=band(t,at-3,at+1);if(mv.waves){ad('rHip',-1.6*u+1.0*v,0,-.8*u);}else arm('l',u,v);} + if(a==='fire_ring'&&t<84){set('lSh',-1.2,0,1.4);set('rSh',-1.2,0,-1.4);ad('chest',0,Math.sin(t*.3)*.4,0);} + if(a==='crouch'){set('hips',.9,0,0);q.y=-.9;set('lSh',-1.6,0,.4);set('rSh',-1.6,0,-.4);ad('lKnee',1.2,0,0);ad('rKnee',1.2,0,0);} + } + if(b.state==='stunned')ad('chest',-.35,0,0); + if(b.state==='deathblow'){ad('chest',.6,0,0);q.y-=.5;ad('lKnee',.8,0,0);ad('rKnee',.8,0,0);} + if(b.state==='dead'||b.state==='execution'){set('hips',1.4,0,0);set('lSh',-2.6,0,.6);set('rSh',-2.6,0,-.6);q.y=-1.5;} + applyPose(m,q,{hipY:1.9});const bn=m.bones;bn.flame.scale.setScalar(1+Math.sin(tm*14)*.12);bn.cape.rotation.set(.2+Math.sin(tm*2)*.06,0,0); + m.holder.position.set(b.x||0,b.y||0,b.z||0);m.holder.rotation.set(0,b.yaw||0,0); + const flash=(b.flash||0)/8;m.mat.emissive.setRGB(.3*flash,.25*flash,.25*flash);return {};} + apePose(g,b){const a=String(b.action||''),mv=root.SekiroGame?.bosses?.ape?.moves?.[a],t=Number(b.state==='attack'?b.moveTick:b.actionTick||0),tm=g.t/60,head=b.form_id==='headless'; + const q={hips:[0,0,0],spine:[0,0,0],chest:[0,0,0],neck:[0,0,0],head:[0,0,0],lSh:[0,0,0],lEl:[0,0,0],lWr:[0,0,0],rSh:[0,0,0],rEl:[0,0,0],rWr:[0,0,0],lHip:[0,0,0],lKnee:[0,0,0],lAnk:[0,0,0],rHip:[0,0,0],rKnee:[0,0,0],rAnk:[0,0,0],y:0}; + const set=(j,x,y,z)=>{q[j]=[x,y,z];},ad=(j,x,y,z)=>{q[j]=[q[j][0]+x,q[j][1]+y,q[j][2]+z];}; + // quadruped base: body pitched forward onto the knuckles; headless form stands hunched upright + if(!head){set('hips',.9,0,0);set('spine',.25,0,0);set('chest',.1,0,0);set('neck',-.85,0,0);set('head',-.25,0,0);set('lSh',-.95,0,.08);set('rSh',-.95,0,-.08);set('lEl',.2,0,0);set('rEl',.2,0,0); + set('lHip',-.95,0,.12);set('rHip',-.95,0,-.12);set('lKnee',1.35,0,0);set('rKnee',1.35,0,0);set('lAnk',-.4,0,0);set('rAnk',-.4,0,0);q.y=-.22;} + else{set('hips',.25,0,0);set('spine',.2,0,0);set('chest',.1,0,0);set('lSh',-.5,0,.25);set('lEl',-.9,0,0);set('rSh',-.6,0,-.25);set('rEl',-.4,0,0);set('rWr',-.6,0,0); + set('lHip',-.45,0,.1);set('rHip',-.25,0,-.1);set('lKnee',.7,0,0);set('rKnee',.6,0,0);set('lAnk',-.25,0,0);q.y=-.15;} + const moving=b.state==='idle'&&!head;if(moving){const s=Math.sin(tm*7),c=Math.cos(tm*7);ad('lSh',s*.45,0,0);ad('rSh',-s*.45,0,0);ad('lHip',-s*.4,0,0);ad('rHip',s*.4,0,0);q.y+=Math.abs(c)*.08;} + if(head&&b.state==='idle'){const s=Math.sin(tm*5);ad('lHip',-s*.25,0,0);ad('rHip',s*.25,0,0);} + if(b.state==='attack'&&mv){ + const hits=mv.hits||[],near=hits.find(h=>t>=h.t-16&&t<=h.t+10); + if(!head&&(a==='slam_combo'||a==='swipe_leap'&&t<50)&&near){const i=hits.indexOf(near),side=i%2?'l':'r',u=band(t,near.t-14,near.t-4),v=band(t,near.t-3,near.t); + ad('hips',-.75*u+.5*v,0,0);ad('chest',-.2*u,0,0);ad(side+'Sh',-2.4*u+2.6*v,0,0);ad(side+'El',-.3*u,0,0);} + if(a==='swipe_leap'&&t>=50){const u=band(t,56,72),v=band(t,80,84);ad('hips',-.6*u+.4*v,0,0);ad('lSh',-2.6*u+2.4*v,0,0);ad('rSh',-2.6*u+2.4*v,0,0);} + if(a==='swipe_grab'){const u=band(t,20,34),v=band(t,36,44);ad('hips',.2*u,0,0);ad('rSh',-.6*u-.6*v,0,0);ad('rSh',0,0,-1.2*u+1.6*v);ad('chest',0,.6*u-1.2*v,0);} + if(a==='belly_flop'){const air=b.y>.4;if(air){set('hips',1.5,0,0);set('lSh',-2.2,0,1.0);set('rSh',-2.2,0,-1.0);set('lHip',-.2,0,.4);set('rHip',-.2,0,-.4);set('lKnee',.4,0,0);set('rKnee',.4,0,0);} + if(t>=58){set('hips',1.55,0,0);set('lSh',-2.9,0,.8);set('rSh',-2.9,0,-.8);q.y=-.55;}} + if(a==='back_thrash'&&t>=10){set('hips',-1.45,0,0);set('spine',-.1,0,0);set('neck',.3,0,0);q.y=-.65;const s=Math.sin(t*.55);set('lSh',-1.5+s*.9,0,.9);set('rSh',-1.5-s*.9,0,-.9);set('lHip',-1.2-s*.5,0,.3);set('rHip',-1.2+s*.5,0,-.3);set('lKnee',.8,0,0);set('rKnee',.8,0,0);} + if(a==='fart'){ad('hips',.3,0,0);ad('lKnee',.4,0,0);ad('rKnee',.4,0,0);q.y-=.15;} + if(a==='flee_poo'&&t>=44){set('hips',.2,0,0);ad('rSh',-2.6*band(t,48,62)+2.2*band(t,64,70),0,0);} + if(a==='roar'&&t>=20){set('hips',.15,0,0);set('chest',-.3,0,0);set('neck',-.2,0,0);set('head',-.5,0,0);set('lSh',-1.2,0,1.1);set('rSh',-1.2,0,-1.1);set('lHip',-.4,0,.1);set('rHip',-.4,0,-.1);set('lKnee',.6,0,0);set('rKnee',.6,0,0);q.y=-.1;} + if((a==='bound'||a==='roll_away')&&b.y>.3){set('lHip',-1.6,0,.2);set('rHip',-1.6,0,-.2);set('lKnee',1.8,0,0);set('rKnee',1.8,0,0);set('lSh',-2.2,0,0);set('rSh',-2.2,0,0);} + if(a==='sword4'&&near){const i=hits.indexOf(near),dir=i%3===0?1:-1,u=band(t,near.t-14,near.t-3),v=band(t,near.t-3,near.t+2);set('rSh',-1.4,0,-.4);set('rEl',-.2,0,0);ad('chest',0,dir*(.9*u-1.8*v),0);ad('spine',0,dir*(.5*u-1.0*v),0);} + if(a==='diving_lunge'){if(t<40){set('rSh',-1.6-.8*band(t,10,24)+1.2*band(t,30,36),0,-.3);ad('hips',.6*band(t,18,36),0,0);}else{set('hips',1.5,0,0);q.y=-.9+.6*band(t,108,124);set('rSh',-2.6,0,-.6);set('lSh',-2.4,0,.6);}} + if(a==='jump_sweep'){set('rSh',-1.0,0,-1.2);if(b.y>.3){set('lHip',-1.2,0,.2);set('rHip',-1.0,0,-.2);set('lKnee',1.4,0,0);set('rKnee',1.4,0,0);}ad('chest',0,-1.4*band(t,48,54),0);} + if(a==='overhead_slam'){const u=band(t,8,40),v=band(t,52,56);set('rSh',-3.0*u+1.7*v,0,-.15);set('rEl',-.3*u,0,0);ad('spine',-.2*u+.8*v,0,0);} + if(mv.scream){const u=band(t,mv.scream.from-40,mv.scream.from-8);set('lSh',-1.6-1.0*u,0,.2);set('lEl',-1.6*u,0,0);if(t>=mv.scream.from&&t=54&&t<100){const tip=this.bladePoints(this.bosses[kind==='isshin'?'isshin':'genichiro'],kind==='isshin'?1.75:1)[1];let last=[tip.x+Math.sin(t)*.4,tip.y+14,tip.z]; + for(let i=1;i<=8;i++){const s=i/8,j=i===8?0:(hash(i,t>>1)-.5)*1.2,next=[tip.x+j*(1-s),tip.y+14*(1-s),tip.z+j*(1-s)*.6];bo=this.link(this.fx.bolt,bo,last,next,.07,0xfff1c2);last=next;} + fl=this.place(this.fx.flash,fl,[tip.x,tip.y,tip.z],1.6+Math.sin(t*.7)*.4,camQ,0xffe9a0);}} + if(p.lightning>0){for(let i=0;i<6;i++){const a=hash(i,g.t>>1)*Math.PI*2;sp=this.link(this.fx.spark,sp,[p.x,(p.y||0)+1,p.z],[p.x+Math.cos(a)*.5,(p.y||0)+1+hash(i,g.t)-.5,p.z+Math.sin(a)*.5],.018,0xffe08a);}} + for(const h of items(g.hazards)){const k=h.type; + if(k==='arrow'||k==='lightning_arrow'||k==='kunai'){const q=this.dir(h.vx,h.vy,h.vz);pr=this.place(this.fx.proj,pr,[h.x,h.y,h.z],k==='kunai'?[.03,.03,.26]:[.025,.025,.75],q,k==='kunai'?0x2b2c33:h.charged?0xb38b52:0x8a6a44); + if(k==='lightning_arrow'){fl=this.place(this.fx.flash,fl,[h.x,h.y,h.z],.9,camQ,0xffe39a);}} + else if(k==='bullet'){const q=this.dir(h.vx,h.vy,h.vz);pr=this.place(this.fx.proj,pr,[h.x,h.y,h.z],[.03,.03,.3],q,0xffd27a);fl=this.place(this.fx.flash,fl,[h.x,h.y,h.z],h.age<4?1.1:.4,camQ,0xffc46a);} + else if(k==='wave'){// a force wave: a standing crescent (vertical) or a wide flat disc (horizontal) + const fx0=Math.cos(h.yaw),fz0=-Math.sin(h.yaw),n=7,w=h.wide?1.5:.55,tall=h.wide?.12:1.15;let last=null; + for(let i=0;i<=n;i++){const v=i/n*2-1,bow=1-v*v,pt=[h.x+fx0*v*w+Math.sin(h.yaw)*bow*.35,h.y+(h.wide?0:v*tall),h.z+fz0*v*w+Math.cos(h.yaw)*bow*.35];if(last)bo=this.link(this.fx.bolt,bo,last,pt,h.wide?.05:.04,h.burn?0xff9a40:0xdff3ff);last=pt;} + fl=this.place(this.fx.flash,fl,[h.x,h.y,h.z],h.wide?1.4:1,camQ,h.burn?0xff8a30:0xbfe6ff);} + else if(k==='ring'){const u=1-h.life/18,r=h.radius*(.25+u*.75);for(let i=0;i<24;i++){const a0=i/24*Math.PI*2,a1=(i+1)/24*Math.PI*2;bo=this.link(this.fx.bolt,bo,[h.x+Math.sin(a0)*r,.7,h.z+Math.cos(a0)*r],[h.x+Math.sin(a1)*r,.7,h.z+Math.cos(a1)*r],.028*(1-u)+.008,0xdff3ff);}} + else if(k==='mortal_arc'){// the black Mortal Blade's reach: a dark crimson sweep along its arc + const u=1-h.life/18;let last=null;for(let i=0;i<=8;i++){const a=(h.yaw||0)+(i/8-.5)*3,r=h.radius*(.45+u*.55),pt=[h.x+Math.sin(a)*r,.9+Math.sin(i/8*Math.PI)*.5,h.z+Math.cos(a)*r];if(last)pr=this.link(this.fx.proj,pr,last,pt,.14*(1-u)+.02,i%2?0x8e1016:0x2a0a10);last=pt;}} + else if(k==='rope_line'){const a=h.yaw||0;pr=this.link(this.fx.proj,pr,[h.x,h.y,h.z],[h.x+Math.sin(a)*h.radius,h.y-.8,h.z+Math.cos(a)*h.radius],.03,0x2c2118);pr=this.place(this.fx.proj,pr,[h.x+Math.sin(a)*h.radius,h.y-.8,h.z+Math.cos(a)*h.radius],[.05,.05,.34],this.dir(Math.sin(a),0,Math.cos(a)),0xd9dde2);} + else if(k==='fire'){const life=Math.min(1,(h.life||0)/30,(h.age||0)/6);for(let i=0;i<4;i++){const a=i*1.6+h.x,r=(h.radius||1)*.45,fy=.25+(.5+.5*Math.sin(g.t*.4+i*2))*.5; + fm=this.place(this.fx.flame,fm,[h.x+Math.cos(a)*r,fy*.5*life,h.z+Math.sin(a)*r],[.26*life,fy*1.3*life,.26*life],[0,a,0],i%2?0xff7a2a:0xffb040);}} + else if(k==='fireball'||k==='fire_shot'){pr=this.place(this.fx.proj,pr,[h.x,h.y,h.z],[(h.radius||.35)*1.3,(h.radius||.35)*1.3,(h.radius||.35)*1.3],[h.age*.3,h.age*.2,0],0xff8a2a); + fl=this.place(this.fx.flash,fl,[h.x,h.y,h.z],(h.radius||.35)*3.2,camQ,0xffa040);} + else if(k==='fire_ring'){const life=Math.min(1,(h.life||0)/40,(h.age||0)/12),n=64;for(let i=0;i=s.from&&t=54&&t<102?(.5+.5*Math.sin(t*.9))*(t>96?2:1):0;} + for(const h of items(g.hazards))if(h.type==='lightning_line'||h.type==='lightning_arc')flash=Math.max(flash,(h.life||0)/14*2.5);} + if(ar.fireLights)ar.fireLights.forEach((l,i)=>{l.intensity=5+Math.sin(tm*7+i*2)*1.2+Math.sin(tm*13+i)*.7;}); + if(ar.water)ar.water.material.color.setHSL(.51,.36,.36+Math.sin(tm*.8)*.02); + this.sun.intensity=sunI;this.hemi.intensity=hemiI;this.flashLight.intensity=flash*9;this.flashLight.position.set(b.x||0,6,b.z||0); + // Lock-on camera: behind and to the right of Sekiro, framing the target; pulled back and up for the ape. + const yaw=g.cameraYaw??Math.atan2((b.x||0)-(p.x||0),(b.z||0)-(p.z||0)),fx=Math.sin(yaw),fz=Math.cos(yaw),rx=-Math.cos(yaw),rz=Math.sin(yaw); + const sep=Math.hypot((b.x||0)-(p.x||0),(b.z||0)-(p.z||0)),big=kind==='ape'||kind==='gyoubu'||kind==='demon',huge=kind==='demon',air=Math.max(0,(b.y||0)-(p.y||0)); + const orbit=clamp(.9-sep*.08,.3,.8)*(big?.75:1),dist=clamp(3.6+sep*.17,3.8,5.5)+(big?2.2:0)+(huge?1.6:0),height=2.1+sep*.05+(big?1.4:0)+(huge?.9:0)+(p.y||0)*.6; + // an airborne target (leaps, threads, lightning) pulls the camera back and up so both stay in frame + const lift=clamp(air-.6,0,3.4),ox=Math.sin(yaw-orbit),oz=Math.cos(yaw-orbit);let pos=v3(p.x-ox*(dist+lift*.55),height+lift*.3,p.z-oz*(dist+lift*.55)); + const bodyH=huge?2.6:big?(b.form_id==='headless'?2.0:1.8):1.15;const wy=air>1?.52:.6;let look=v3(lerp(p.x,b.x,.62),lerp((p.y||0)+1.0,(b.y||0)+bodyH,wy),lerp(p.z,b.z,.62)); + if(kind==='butterfly'){pos.x=clamp(pos.x,-9.3,9.3);pos.z=clamp(pos.z,-7.3,7.3);pos.y=Math.min(pos.y,5.0); + // a pillar in the way: raise the eye and shorten the boom instead of looking through timber + for(const q of g.arena?.pillars||[]){const dx=pos.x-p.x,dz=pos.z-p.z,len=Math.hypot(dx,dz)||1,t=clamp(((q.x-p.x)*dx+(q.z-p.z)*dz)/(len*len),0,1),cx=p.x+dx*t,cz=p.z+dz*t; + // a pillar blocks the line of sight: shorten the boom towards Sekiro, then keep the eye out of any column + if(Math.hypot(cx-q.x,cz-q.z)15){pos.x*=15/r;pos.z*=15/r;}} + // a side angle during a deathblow; a little shake on clashes + if(b.executing>0||(p.action==='deathblow')){const u=band(p.actionTick||0,0,10);pos.lerp(v3(cx+rx*(big?6:3.8)-fx*1.2,big?2.6:1.7,cz+rz*(big?6:3.8)-fz*1.2),u);look.lerp(v3(cx,big?1.6:1.15,cz),u);} + let shake=0;for(const fx2 of items(g.effects))if(/deflect|mikiri|stomp/.test(fx2.type||''))shake=Math.max(shake,(fx2.life||0)/(fx2.maxLife||15)); + if(p.hurt>0)shake=Math.max(shake,p.hurt/12*.7);if(shake){pos.x+=Math.sin(g.t*1.7)*.04*shake;pos.y+=Math.cos(g.t*2.3)*.04*shake;} + if(g.view){pos=v3(...g.view.pos);look=v3(...g.view.look);} + this.camera.position.copy(pos);this.camera.lookAt(look);this.camera.updateMatrixWorld(); + this.effects(g,this.camera); + // sword trails while blades are swinging + const pa=p.attackTick>=(p.attackKind==='thrust'?8:5)&&p.attackTick<=(p.attackKind==='thrust'?12:10)?{alpha:.7,len:1.0}:null; + this.trail(0,this.player,pa,0xdfe9ff,k=>{if(p.attackTick-k<(p.attackKind==='thrust'?7:4))return false;applyPose(this.player,this.playerPose({...p,attackTick:p.attackTick-k,actionTick:(p.actionTick||0)-k},(g.t-k)/60));return true;}); + const mv=root.SekiroGame?.bosses?.[kind]?.moves?.[b.action],swing=b.state==='attack'&&mv&&(mv.hits||[]).some(h=>b.moveTick>=h.t&&b.moveTick<=h.t+4&&h.type!=='grab'&&h.type!=='kick'&&h.type!=='lightning'); + const bossBlade=kind==='ape'?(b.form_id==='headless'?{alpha:.7,len:2.7}:null):kind==='genichiro'?{alpha:.75,len:1}:kind==='isshin'?(model.bones.active?null:{alpha:.75,len:1}):kind==='gyoubu'||kind==='demon'?null:{alpha:.5,len:.3}; + const moves=root.SekiroGame?.bosses?.[kind]?.moves; + const hitT=(mv?.hits||[]).filter(h=>h.t<=b.moveTick).map(h=>h.t).pop()??0; + this.trail(1,model,swing&&bossBlade?bossBlade:null,kind==='genichiro'&&b.form_id==='tomoe'?0xffe7a0:0xffffff,k=>{if(b.moveTick-k120)this.times.shift();this.ready=true;this.error=null; + }catch(e){this.ready=false;this.error=String(e);throw e;} + } + project(x,y,z){const v=v3(x,y,z).project(this.camera);return {x:(v.x+1)*427,y:(1-v.y)*240,visible:v.z<1&&v.z>-1};} + metrics(){ + const info=this.renderer.info,sorted=[...this.times].sort((a,b)=>a-b);let geometryBytes=0,textureBytes=0; + for(const r of this.resources){if(r.isBufferGeometry){for(const a of Object.values(r.attributes))geometryBytes+=a.array.byteLength;if(r.index)geometryBytes+=r.index.array.byteLength;}if(r.isTexture&&r.image)textureBytes+=(r.image.width||0)*(r.image.height||0)*4;if(r.isInstancedMesh)geometryBytes+=r.instanceMatrix.array.byteLength;} + return {renderer:'webgl-boss3d',webglVersion:this.renderer.capabilities.isWebGL2?2:1,drawCalls:info.render.calls,triangles:info.render.triangles,geometries:info.memory.geometries,textures:info.memory.textures,geometryBytes,textureBytes,shadowMapBytes:1024*1024*4,canvasBytes:854*480*4,resourceBytesEstimate:geometryBytes+textureBytes+1024*1024*4+854*480*8,staticAssetBytes:669884,renderSamples:sorted.length,cpuRenderMsP50:sorted.length?sorted[Math.floor((sorted.length-1)*.5)]:null,cpuRenderMsP95:sorted.length?sorted[Math.floor((sorted.length-1)*.95)]:null,shadows:'one 1024x1024 directional map; fighters cast',postprocess:false,arena:this.kind}; + } + close(){if(this.closed)return;this.closed=true;this.ready=false;this.resources.forEach(r=>r.dispose?.());this.renderer.dispose();this.renderer.forceContextLoss();this.resources.clear();} + } + B.render=function(style,g,ctx){let m=byCanvas.get(ctx.canvas);if(!m){m=new Map();byCanvas.set(ctx.canvas,m);}let scene=m.get(style);if(!scene||scene.closed){scene=new Scene(ctx.canvas);m.set(style,scene);}scene.render(g,ctx);return scene;}; + B.scene=function(style,ctx){return ctx&&byCanvas.get(ctx.canvas)?.get(style)||null;}; + B.status=function(style,ctx){const s=ctx&&byCanvas.get(ctx.canvas)?.get(style);if(s&&!s.closed&&s.renderer.getContext().isContextLost()){s.ready=false;s.error='WebGL context lost';}return {renderer:'webgl-boss3d',kind:'perspective',ready:!!s?.ready&&!s.closed,error:s?.error||null};}; + B.metrics=function(style,ctx){const s=ctx&&byCanvas.get(ctx.canvas)?.get(style);return s?s.metrics():null;}; + B.close=function(style,ctx){const m=ctx&&byCanvas.get(ctx.canvas),s=m?.get(style);if(s){s.close();m.delete(style);}}; + B.bar=function(c,x,y,w,h,value,color){c.fillStyle='rgba(12,20,29,.8)';c.fillRect(x,y,w,h);c.fillStyle=color;c.fillRect(x+1,y+1,(w-2)*clamp(value,0,1),h-2);c.strokeStyle='rgba(229,210,169,.6)';c.strokeRect(x+.5,y+.5,w-1,h-1);}; + B.text=function(c,text,x,y,size=16,color='#f3ead9',align='left'){c.font=size+'px "Segoe UI","Microsoft YaHei",sans-serif';c.textAlign=align;c.fillStyle='rgba(8,15,23,.8)';c.fillText(text,x+1,y+1);c.fillStyle=color;c.fillText(text,x,y);}; +})(window); diff --git a/environments/games/web/games/sekiro_remake/style3d.css b/environments/games/web/games/sekiro_remake/style3d.css new file mode 100644 index 0000000000000000000000000000000000000000..df673172470e9188762c19cb2ab95c394082b9f0 --- /dev/null +++ b/environments/games/web/games/sekiro_remake/style3d.css @@ -0,0 +1 @@ +:root{color-scheme:dark;--bg:#14191a;--panel:#1d2425;--edge:#354141;--text:#ebe7dc;--muted:#a5b2ad;--accent:#dfb676}*{box-sizing:border-box}body{margin:0;background:radial-gradient(ellipse at top,#29312b,transparent 60%),var(--bg);color:var(--text);font:14px/1.7 'Segoe UI','Microsoft YaHei',sans-serif}body[data-game=genshin_remake]{--bg:#101822;--panel:#1b2530;--edge:#374754;--accent:#baacff;background:radial-gradient(ellipse at top,#2b2942,transparent 60%),var(--bg)}main{max-width:1220px;margin:auto;padding:28px 24px 40px}header{display:flex;align-items:center;justify-content:space-between;margin-bottom:22px;gap:20px}.eyebrow{color:var(--accent);font-size:11px;letter-spacing:2.5px;text-transform:uppercase}h1{font:500 32px/1.35 Georgia,'Microsoft YaHei',serif;letter-spacing:1px;margin:6px 0}header p{color:var(--muted);margin:0;font-size:13px}a{color:var(--accent);text-decoration:none}a:hover{text-decoration:underline}.layout{display:grid;grid-template-columns:minmax(0,854px) 245px;gap:24px;align-items:start}.stage{position:relative;border:1px solid var(--edge);box-shadow:0 22px 55px #0005;background:#111b1c}canvas{display:block;width:100%;aspect-ratio:854/480;touch-action:none;outline:none}canvas:focus-visible{outline:2px solid var(--accent);outline-offset:3px}#overlay{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:#10171b30;pointer-events:none}#overlay[hidden]{display:none}#overlay div{background:#111b23de;padding:19px 32px;border:1px solid #9ba6a655;max-width:80%;text-align:center}#overlay strong{font:500 24px Georgia,'Microsoft YaHei',serif;display:block}#overlay span{display:block;color:var(--muted);font-size:12px;margin-top:7px}.toolbar{display:flex;gap:8px;flex-wrap:wrap;padding:12px;background:var(--panel);border-top:1px solid var(--edge)}button,select,input{font:inherit;background:var(--panel);color:var(--text);border:1px solid var(--edge);border-radius:4px;padding:7px 11px}button{cursor:pointer}button:hover{border-color:var(--accent);background:#ffffff09}button.primary{background:var(--accent);color:var(--bg);font-weight:600}button:focus-visible,select:focus-visible,input:focus-visible,a:focus-visible{outline:2px solid var(--accent);outline-offset:3px}aside{padding:19px;border:1px solid var(--edge);background:var(--panel)}h2{font-size:16px;margin:0 0 8px}label{display:block;font-size:12px;color:var(--muted);margin:12px 0 5px}select,input{width:100%}dl{border-top:1px solid var(--edge);padding-top:16px;margin:18px 0 0}dt{color:var(--accent);font:12px/1.8 Consolas,monospace}dd{color:var(--muted);font-size:12px;margin:0 0 10px}.note{color:var(--muted);font-size:12px}#status{min-height:25px;margin:10px 0;color:var(--accent);overflow-wrap:anywhere}.record-toolbar{border:1px solid var(--edge);padding:10px;background:transparent}.record-toolbar button{font-size:12px}#file{display:none}.mobile{display:none}footer{display:flex;flex-wrap:wrap;gap:22px;border-top:1px solid var(--edge);margin-top:28px;padding-top:15px;font-size:12px}@media(max-width:950px){main{padding:14px}.layout{grid-template-columns:1fr}aside{display:grid;grid-template-columns:1fr 1fr;gap:0 18px}aside dl,aside .note{grid-column:1/-1}dl{columns:2}.mobile{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}.mobile button{min-width:45px;touch-action:none}header{align-items:start}h1{font-size:26px}}@media(max-width:500px){header{display:block}header a{font-size:12px}aside{padding:14px}#overlay div{padding:14px 20px}#overlay strong{font-size:19px}.toolbar{gap:6px;padding:8px}button{font-size:12px}h1{font-size:25px}} diff --git a/environments/games/web/games/soulknight_remake/compact_actions.json b/environments/games/web/games/soulknight_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..5dd4f8530deb990893e055cc10bc6fc901061e2e --- /dev/null +++ b/environments/games/web/games/soulknight_remake/compact_actions.json @@ -0,0 +1,176 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "soulknight_remake", + "version": "soulknight-compact@1", + "heads": [ + { + "name": "move", + "options": [ + { + "label": "none" + }, + { + "label": "right", + "keys": [ + "D" + ] + }, + { + "label": "down_right", + "keys": [ + "S", + "D" + ] + }, + { + "label": "down", + "keys": [ + "S" + ] + }, + { + "label": "down_left", + "keys": [ + "S", + "A" + ] + }, + { + "label": "left", + "keys": [ + "A" + ] + }, + { + "label": "up_left", + "keys": [ + "W", + "A" + ] + }, + { + "label": "up", + "keys": [ + "W" + ] + }, + { + "label": "up_right", + "keys": [ + "W", + "D" + ] + } + ] + }, + { + "name": "aim", + "options": [ + { + "label": "none" + }, + { + "label": "right_40", + "dx": 40, + "dy": 0 + }, + { + "label": "down_right_40", + "dx": 28, + "dy": 28 + }, + { + "label": "down_40", + "dx": 0, + "dy": 40 + }, + { + "label": "down_left_40", + "dx": -28, + "dy": 28 + }, + { + "label": "left_40", + "dx": -40, + "dy": 0 + }, + { + "label": "up_left_40", + "dx": -28, + "dy": -28 + }, + { + "label": "up_40", + "dx": 0, + "dy": -40 + }, + { + "label": "up_right_40", + "dx": 28, + "dy": -28 + } + ] + }, + { + "name": "act", + "options": [ + { + "label": "none" + }, + { + "label": "fire", + "keys": [ + "J" + ] + }, + { + "label": "fire_skill", + "subs": [ + [ + "J", + "K" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ] + ] + }, + { + "label": "switch", + "subs": [ + [ + "Q" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ] + ] + } + ] + } + ] +} diff --git a/environments/games/web/games/soulknight_remake/draw.js b/environments/games/web/games/soulknight_remake/draw.js new file mode 100644 index 0000000000000000000000000000000000000000..d2bf386f4b0d9893c5bc7dfc66069ac90daff1e9 --- /dev/null +++ b/environments/games/web/games/soulknight_remake/draw.js @@ -0,0 +1,853 @@ +/* Soul Knight arena renderer (read-only). Procedural pixel art: every sprite is painted at + * art resolution, alpha-thresholded, given a 1-art-pixel outline and blitted at 2x without + * smoothing. Never mutates the game object or consumes game RNG; screen shake and decorations + * use hashes of the tick / tile coordinates, so a frame is a pure function of the state. + */ +(function (root) { + 'use strict'; + const M = root.SoulKnightGame, TAU = Math.PI * 2, R = M.room, TILE = M.tile; + const FONT = "'Microsoft YaHei','PingFang SC','Noto Sans CJK SC','Noto Sans SC',sans-serif"; + const cache = new Map(); + const hash = (a, b) => { let h = (Math.imul(a | 0, 73856093) ^ Math.imul(b | 0, 19349663) ^ 0x5bd1e995) >>> 0; h = Math.imul(h ^ (h >>> 15), 2246822519) >>> 0; h = Math.imul(h ^ (h >>> 13), 3266489917) >>> 0; return ((h ^ (h >>> 16)) >>> 0) / 4294967296; }; + const mk = (w, h) => { const c = document.createElement('canvas'); c.width = w; c.height = h; return c; }; + // cached art lives in software-backed canvases: the harness reads every captured frame back (toDataURL), which + // moves the frame canvas to software; GPU-backed sources would then cost a GPU->CPU copy per drawImage + const ctx2d = c => c.getContext('2d', { willReadFrequently: true }); + const poly = (x, pts) => { x.beginPath(); x.moveTo(pts[0][0], pts[0][1]); for (let i = 1; i < pts.length; i++) x.lineTo(pts[i][0], pts[i][1]); x.closePath(); x.fill(); }; + const ell = (x, col, cx, cy, rx, ry, rot) => { x.fillStyle = col; x.beginPath(); x.ellipse(cx, cy, rx, ry, rot || 0, 0, TAU); x.fill(); }; + const starPath = (x, cx, cy, r1, r2, n, rot) => { x.beginPath(); for (let i = 0; i < n * 2; i++) { const a = (rot || -Math.PI / 2) + i * Math.PI / n, r = i % 2 ? r2 : r1; x.lineTo(cx + Math.cos(a) * r, cy + Math.sin(a) * r); } x.closePath(); }; + + // ---------- sprite pipeline ---------- + function sprite(key, w, h, paint, outline) { + let s = cache.get(key); + if (s) return s; + const c = mk(w + 2, h + 2), x = ctx2d(c); + x.translate(1, 1); paint(x); x.setTransform(1, 0, 0, 1, 0, 0); + const img = x.getImageData(0, 0, c.width, c.height), d = img.data, n = c.width * c.height, cw = c.width; + const solid = new Uint8Array(n); + for (let i = 0; i < n; i++) { const on = d[i * 4 + 3] >= 110; d[i * 4 + 3] = on ? 255 : 0; solid[i] = on; } + if (outline !== false) { + const oc = outline || [18, 14, 26]; + for (let y = 0; y < c.height; y++) for (let xx = 0; xx < cw; xx++) { + const i = y * cw + xx; + if (solid[i]) continue; + if ((xx > 0 && solid[i - 1]) || (xx < cw - 1 && solid[i + 1]) || (y > 0 && solid[i - cw]) || (y < c.height - 1 && solid[i + cw])) { + d[i * 4] = oc[0]; d[i * 4 + 1] = oc[1]; d[i * 4 + 2] = oc[2]; d[i * 4 + 3] = 255; + } + } + } + x.putImageData(img, 0, 0); + const f = mk(c.width, c.height), fx = ctx2d(f); + fx.drawImage(c, 0, 0); fx.globalCompositeOperation = 'source-atop'; fx.fillStyle = '#ffffff'; fx.fillRect(0, 0, f.width, f.height); + s = { c, f, w: c.width, h: c.height }; + cache.set(key, s); + return s; + } + function fromMatrix(key, rows, pal) { + const w = Math.max(...rows.map(r => r.length)); + return sprite(key, w, rows.length, x => { rows.forEach((row, y) => { for (let i = 0; i < row.length; i++) { const col = pal[row[i]]; if (col) { x.fillStyle = col; x.fillRect(i, y, 1, 1); } } }); }); + } + // anchor = bottom centre at (x, y) in screen px, k = pixel scale + function blit(c, s, x, y, k, flip, flash, alpha) { + const w = s.w * k, h = s.h * k; + c.save(); c.translate(Math.round(x), Math.round(y)); + if (flip) c.scale(-1, 1); + if (alpha !== undefined) c.globalAlpha = alpha; + c.drawImage(s.c, -Math.round(w / 2), -h, w, h); + if (flash) { c.globalAlpha = (alpha === undefined ? 1 : alpha) * (flash === true ? 0.7 : flash); c.drawImage(s.f, -Math.round(w / 2), -h, w, h); } + c.restore(); + } + + // ---------- characters ---------- + const KPAL = { w: '#f2f6fa', s: '#c4cdd8', g: '#8d98a8', d: '#5d6676', v: '#222a3a', e: '#ffe46b', r: '#e5483f', R: '#a52f2c', b: '#3b4152' }; + const KBODY = ['....wwss....', '...wssssg...', '..wsssssgg..', '..sssvvvvg..', '..ssvvvevg..', '..gssvvvvg..', '..ggsssssg..', + '.rrrrrrrrRR.', '..RRrssgRR..', '.Rsswsssggd.', '..ssssssggd.', '..ssssssgd..', '..gsgggsgd..']; + const KLEGS = [['...gd..gd...', '...bb..bb...', '..bbb..bbb..'], ['..gd....gd..', '..bb....bb..', '.bbb....bbb.']]; + const knight = f => fromMatrix('knight' + f, KBODY.concat(KLEGS[f]), KPAL); + + function paintGP(x, angry) { + const fe = ['#e8833a', '#f6d65a']; + for (let i = 0; i < 5; i++) { x.fillStyle = fe[i % 2]; const bx = 6 + i * 3; poly(x, [[bx, 8], [bx + 1.5, Math.abs(i - 2) * 1.2], [bx + 3, 8]]); } + x.fillStyle = '#4f9a3f'; poly(x, [[8, 9], [0, 5], [8, 14]]); poly(x, [[18, 9], [26, 5], [18, 14]]); + x.fillStyle = '#d98b8b'; poly(x, [[7, 10], [3, 7], [7, 12]]); poly(x, [[19, 10], [23, 7], [19, 12]]); + ell(x, '#5fae4a', 13, 11.5, 6.5, 5.5); ell(x, '#88d06a', 11, 9.5, 3.5, 2.4); + x.fillStyle = '#f2c94c'; x.fillRect(6, 6, 14, 2); x.fillStyle = '#e04a4a'; x.fillRect(12, 6, 2, 2); + x.fillStyle = angry ? '#ff3020' : '#ffd23a'; x.fillRect(9, 10, 3, 2); x.fillRect(15, 10, 3, 2); + x.fillStyle = '#16181c'; x.fillRect(11, 10, 1, 2); x.fillRect(17, 10, 1, 2); + if (angry) { x.fillRect(9, 9, 3, 1); x.fillRect(15, 9, 3, 1); } + x.fillStyle = '#2a1414'; x.fillRect(10, 14, 7, 1); x.fillStyle = '#f4efe6'; x.fillRect(11, 14, 1, 1); x.fillRect(15, 14, 1, 1); + x.fillStyle = '#6c3fa0'; poly(x, [[8, 16], [18, 16], [22, 29], [4, 29]]); + x.fillStyle = '#4a2a73'; poly(x, [[15, 16], [18, 16], [22, 29], [16, 29]]); + x.fillStyle = '#9a6ad0'; poly(x, [[8, 16], [10, 16], [7, 29], [4, 29]]); + x.fillStyle = '#f2c94c'; x.fillRect(4, 27, 18, 2); x.fillRect(12, 17, 2, 10); + x.fillStyle = '#7a4a2a'; x.fillRect(7, 21, 12, 2); + x.fillStyle = '#f4efe6'; x.fillRect(9, 16, 2, 1); x.fillRect(12, 17, 2, 1); x.fillRect(15, 16, 2, 1); + ell(x, '#5fae4a', 5, 21, 2, 2); ell(x, '#5fae4a', 21, 21, 2, 2); + } + function paintCT(x, angry) { + x.fillStyle = '#7a5230'; x.fillRect(11, 37, 6, 8); x.fillRect(21, 37, 6, 8); + x.fillStyle = '#5a3a20'; x.fillRect(15, 37, 2, 8); x.fillRect(25, 37, 2, 8); + x.fillStyle = '#a0703f'; x.fillRect(11, 37, 2, 8); x.fillRect(21, 37, 2, 8); + for (const [top, bot, hw] of [[6, 16, 8], [14, 27, 12], [22, 39, 16]]) { + x.fillStyle = angry ? '#2c5f30' : '#2d6a3a'; poly(x, [[19, top - 5], [19 - hw, bot], [19 + hw, bot]]); + x.fillStyle = angry ? '#3b7c3e' : '#3f8f4c'; poly(x, [[19, top - 5], [19 - hw, bot], [17, bot]]); + x.fillStyle = '#eef6fb'; poly(x, [[19, top - 5], [19 - hw * 0.55, top + 3], [19 - hw * 0.25, top + 1], [19, top + 4], [19 + hw * 0.3, top + 1], [19 + hw * 0.55, top + 3]]); + x.fillStyle = '#d6e8f3'; x.fillRect(19 - hw + 2, bot - 1, hw * 2 - 4, 1); + } + x.fillStyle = '#16181c'; x.fillRect(14, 28, 3, 3); x.fillRect(22, 28, 3, 3); + x.fillStyle = angry ? '#ff3a2a' : '#ffffff'; x.fillRect(15, 28, 1, 1); x.fillRect(23, 28, 1, 1); + if (angry) { x.fillStyle = '#16181c'; x.fillRect(13, 26, 2, 1); x.fillRect(15, 27, 2, 1); x.fillRect(24, 26, 2, 1); x.fillRect(22, 27, 2, 1); } + x.fillStyle = '#5a2a1a'; x.fillRect(17, 32, 5, 2); + x.fillStyle = '#d7303a'; x.fillRect(8, 35, 23, 3); x.fillStyle = '#f4f4f4'; for (let i = 9; i < 31; i += 4) x.fillRect(i, 35, 2, 3); + x.fillStyle = '#d7303a'; x.fillRect(26, 38, 4, 6); x.fillStyle = '#a32028'; x.fillRect(28, 38, 2, 6); + for (const [ox, oy, oc] of [[12, 21, '#ff4a4a'], [26, 19, '#ffd23a'], [16, 12, '#5ac8ff'], [24, 25, '#ff4a4a'], [10, 31, '#ffd23a'], [29, 30, '#5ac8ff'], [20, 8, '#ff4a4a']]) { + x.fillStyle = oc; x.fillRect(ox, oy, 2, 2); x.fillStyle = '#ffffff'; x.fillRect(ox, oy, 1, 1); + } + x.fillStyle = '#ffd23f'; starPath(x, 19, 3, 4, 1.8, 5); x.fill(); + } + function paintDS(x, open) { + const cx = 22, cy = 21; + for (let i = 0; i < 6; i++) { const a = i * TAU / 6 + 0.3; ell(x, i % 2 ? '#2f7a3f' : '#46a052', cx + Math.cos(a) * 13, cy + 7 + Math.sin(a) * 8, 8.5, 4.5, a); } + if (!open) { + ell(x, '#7a2f8f', cx, cy - 2, 12, 14); ell(x, '#a24bb8', cx - 3, cy - 4, 7, 10); ell(x, '#c77ad8', cx - 5, cy - 8, 2.5, 3.5); + x.fillStyle = '#4e1a60'; x.fillRect(cx - 1, cy - 15, 2, 26); x.fillRect(cx - 7, cy - 10, 1, 18); x.fillRect(cx + 6, cy - 10, 1, 18); + x.fillStyle = '#f2d24a'; for (const [sx, sy] of [[cx - 6, cy - 5], [cx + 3, cy - 8], [cx + 7, cy + 2], [cx - 4, cy + 5], [cx + 2, cy]]) x.fillRect(sx, sy, 2, 2); + x.fillStyle = '#c86ad8'; x.fillRect(cx - 4, cy - 20, 1, 5); x.fillRect(cx, cy - 21, 1, 6); x.fillRect(cx + 3, cy - 20, 1, 5); + } else { + for (let i = 0; i < 6; i++) { const a = i * TAU / 6 - Math.PI / 2; ell(x, i % 2 ? '#c2459a' : '#e06ab8', cx + Math.cos(a) * 11, cy + Math.sin(a) * 10, 8.5, 5, a); ell(x, '#f7a0d8', cx + Math.cos(a) * 13, cy + Math.sin(a) * 12, 3, 1.6, a); } + ell(x, '#4e1240', cx, cy, 9, 9); + ell(x, '#8fd65a', cx, cy, 6.5, 6.5); ell(x, '#b8f08a', cx - 2, cy - 2, 3, 2.5); + x.fillStyle = '#ffffff'; x.fillRect(cx - 3, cy - 4, 6, 4); x.fillStyle = '#e02a2a'; x.fillRect(cx - 1, cy - 3, 2, 2); + x.fillStyle = '#16181c'; x.fillRect(cx - 4, cy + 2, 8, 2); x.fillStyle = '#f4efe6'; for (let i = -3; i < 4; i += 2) x.fillRect(cx + i, cy + 2, 1, 1); + } + } + // ---------- 11-02 expansion bosses (original art; half-resolution art blitted at 2x like every other sprite) ---------- + function paintGS(x, angry) { // Grand Slime 36x28: wobbling red-pink jelly with a crown; enraged = darker, angry brows + const body = angry ? '#d8344a' : '#ef5a6a', dark = angry ? '#9a1a30' : '#c23a4c', light = angry ? '#f27a88' : '#ff9aa6'; + ell(x, dark, 18, 17.5, 17, 10.5); + ell(x, body, 18, 17, 16.5, 10); + ell(x, light, 13, 13, 6, 3.5); ell(x, '#ffd8de', 10, 12, 2, 1.2); + x.fillStyle = dark; for (const [dx, h] of [[5, 2], [11, 3], [25, 3], [31, 2]]) x.fillRect(dx, 25, 1.5, h); + x.fillStyle = '#16181c'; x.fillRect(12, 15, 2, 3); x.fillRect(22, 15, 2, 3); + x.fillStyle = '#ffffff'; x.fillRect(12, 15, 1, 1); x.fillRect(22, 15, 1, 1); + if (angry) { x.fillStyle = '#16181c'; x.fillRect(11, 13, 4, 1); x.fillRect(21, 13, 4, 1); } + x.fillStyle = '#4a1018'; x.fillRect(15, 21, 6, 1); x.fillStyle = '#f4efe6'; x.fillRect(16, 21, 1, 1); x.fillRect(19, 21, 1, 1); + x.fillStyle = '#f2c94c'; poly(x, [[12, 7.5], [13, 2], [15, 5], [18, 1], [21, 5], [23, 2], [24, 7.5]]); + x.fillStyle = '#c99a2a'; x.fillRect(12, 6, 12, 1.5); x.fillStyle = '#5ac8ff'; x.fillRect(17, 3.5, 2, 1.5); + } + function paintVL(x, angry) { // Varkolyn Leader 18x32: tall void alien in a hooded cloak, swirl mark on the leg + const cloak = angry ? '#5a2a8a' : '#3e2a6a', trim = angry ? '#c46aff' : '#8a6ad8'; + x.fillStyle = cloak; poly(x, [[6, 10], [12, 10], [16, 31], [2, 31]]); + x.fillStyle = '#2a1a4a'; poly(x, [[9, 10], [12, 10], [16, 31], [10, 31]]); + x.fillStyle = trim; x.fillRect(2, 30, 14, 1); x.fillRect(8.5, 11, 1, 18); + ell(x, '#1a1030', 9, 6, 6, 6); ell(x, '#2a1a4a', 9, 5.5, 5.5, 5.5); + ell(x, '#9ff4c8', 9, 7, 3.5, 2.6); + x.fillStyle = angry ? '#ff3a6a' : '#16181c'; x.fillRect(6.5, 6, 1.5, 1.5); x.fillRect(10, 6, 1.5, 1.5); + x.strokeStyle = angry ? '#ff6af0' : '#6af0ff'; x.lineWidth = 0.8; x.beginPath(); x.arc(5.5, 22, 1.8, 0, 5.2); x.stroke(); + x.fillStyle = '#6ad8b0'; x.fillRect(1, 15, 2, 2); x.fillRect(15, 15, 2, 2); + } + function paintVS(x, angry) { // Volcanic Sandworm 22x40: armoured segmented worm rearing out of the ground + const plate = angry ? '#d0602a' : '#b06a3a', dark = '#5a2a14', glow = angry ? '#ffd04a' : '#ff8a3a'; + for (let i = 0; i < 5; i++) { + const y = 36 - i * 6.5, w = 6.8 - i * 0.3; + ell(x, dark, 11, y + 0.5, w + 0.5, 3); ell(x, plate, 11, y, w, 2.7); + x.fillStyle = glow; x.fillRect(11 - w + 1.5, y - 0.5, 1, 1); x.fillRect(11 + w - 2.5, y - 0.5, 1, 1); + } + ell(x, dark, 11, 6, 8, 5); ell(x, plate, 11, 5.5, 7.5, 4.5); + x.fillStyle = '#2a0e06'; poly(x, [[6, 6], [16, 6], [13, 10], [9, 10]]); + x.fillStyle = '#f4efe6'; for (const dx of [7.5, 10, 12.5, 15]) poly(x, [[dx - 0.6, 6], [dx + 0.6, 6], [dx, 7.8]]); + x.fillStyle = glow; x.fillRect(6, 2, 2, 1); x.fillRect(14, 2, 2, 1); + } + const bossSprite = (kind, alt) => kind === 'goblin_priest' ? sprite('gp' + alt, 26, 30, x => paintGP(x, alt)) + : kind === 'christmas_treant' ? sprite('ct' + alt, 38, 46, x => paintCT(x, alt)) + : kind === 'grand_slime' ? sprite('gs' + alt, 36, 28, x => paintGS(x, alt)) + : kind === 'varkolyn_leader' ? sprite('vl' + alt, 18, 32, x => paintVL(x, alt)) + : kind === 'volcanic_sandworm' ? sprite('vs' + alt, 22, 40, x => paintVS(x, alt)) + : sprite('ds' + alt, 44, 42, x => paintDS(x, alt)); + // minions: slime 10x8 (body = hit circle), tentacle 10x18 (body = hit capsule [-16, 0] r 10) + const minionSprite = (kind, f) => kind === 'slime' ? sprite('slime' + f, 10, 8, x => { + ell(x, '#c23a4c', 5, 4.5, 5, 3.5 - f * 0.4); ell(x, '#ef5a6a', 5, 4, 4.5, 3 - f * 0.4); ell(x, '#ff9aa6', 3.5, 2.8, 1.5, 0.9); + x.fillStyle = '#16181c'; x.fillRect(3, 4, 1, 1.5); x.fillRect(6, 4, 1, 1.5); + }) : sprite('tent' + f, 10, 18, x => { + for (let i = 0; i < 5; i++) { const y = 16 - i * 3, w = 4.5 - i * 0.5, o = Math.sin(i * 0.9 + f * 1.4) * 0.8; ell(x, i % 2 ? '#5a2a8a' : '#7a3aaa', 5 + o, y, w, 2); } + ell(x, '#c46aff', 5, 2.5, 2.2, 2.2); x.fillStyle = '#e8fff4'; x.fillRect(4.5, 1.8, 1, 1); + }); + + // ---------- props ---------- + const PROPS = { + tepee: () => sprite('tepee', 36, 30, x => { + x.fillStyle = '#c9a36a'; poly(x, [[18, 3], [1, 30], [35, 30]]); x.fillStyle = '#a8814a'; poly(x, [[18, 3], [26, 30], [35, 30]]); + x.fillStyle = '#8a3a2a'; for (const y of [12, 18, 24]) { const hw = (y - 3) * 17 / 27; x.fillRect(18 - hw, y, hw * 2, 2); } + x.fillStyle = '#f2c94c'; for (const y of [15, 21]) { const hw = (y - 3) * 17 / 27; for (let i = -hw + 2; i < hw - 1; i += 4) x.fillRect(18 + i, y, 2, 1); } + x.fillStyle = '#2e2014'; poly(x, [[18, 15], [13, 30], [23, 30]]); + x.fillStyle = '#6a4a2a'; x.fillRect(15, 0, 1, 7); x.fillRect(20, 0, 1, 7); x.fillRect(17, 0, 1, 6); + }), + totem: () => sprite('totem', 12, 28, x => { + x.fillStyle = '#8a5a2a'; x.fillRect(3, 2, 6, 26); x.fillStyle = '#6a4220'; x.fillRect(7, 2, 2, 26); + x.fillStyle = '#c84a3a'; x.fillRect(0, 9, 12, 3); x.fillStyle = '#e8833a'; x.fillRect(0, 9, 3, 1); x.fillRect(9, 9, 3, 1); + x.fillStyle = '#f2c94c'; x.fillRect(4, 4, 1, 2); x.fillRect(7, 4, 1, 2); x.fillStyle = '#2a1a10'; x.fillRect(4, 16, 4, 2); x.fillRect(4, 21, 4, 1); + x.fillStyle = '#3a8acf'; x.fillRect(4, 13, 4, 1); x.fillStyle = '#5a3a1a'; x.fillRect(2, 0, 8, 2); + }), + torch: () => sprite('torch', 6, 14, x => { x.fillStyle = '#6a4a2a'; x.fillRect(2, 4, 2, 10); x.fillStyle = '#4a3220'; x.fillRect(1, 3, 4, 2); }), + stone: () => sprite('stone', 24, 30, x => { + x.fillStyle = '#7d8a8f'; x.fillRect(0, 6, 24, 24); x.fillStyle = '#a2afb3'; x.fillRect(0, 0, 24, 8); + x.fillStyle = '#5f6b70'; x.fillRect(0, 26, 24, 4); x.fillRect(20, 7, 4, 23); + x.fillStyle = '#4f8a3f'; x.fillRect(0, 0, 24, 2); x.fillRect(2, 2, 6, 2); x.fillRect(14, 2, 5, 1); x.fillRect(0, 8, 2, 5); + x.fillStyle = '#56626a'; x.fillRect(6, 14, 5, 1); x.fillRect(10, 15, 1, 4); x.fillRect(15, 20, 4, 1); x.fillRect(4, 22, 1, 3); + }), + tree: () => sprite('tree', 24, 38, x => { + x.fillStyle = '#6b4527'; x.fillRect(10, 30, 4, 8); + for (const [top, bot, hw] of [[2, 14, 6], [9, 22, 9], [16, 31, 12]]) { + x.fillStyle = '#2b6236'; poly(x, [[12, top - 2], [12 - hw, bot], [12 + hw, bot]]); x.fillStyle = '#3a8046'; poly(x, [[12, top - 2], [12 - hw, bot], [11, bot]]); + x.fillStyle = '#eef6fb'; poly(x, [[12, top - 2], [12 - hw * 0.5, top + 4], [12, top + 3], [12 + hw * 0.5, top + 4]]); x.fillRect(12 - hw + 1, bot - 1, hw * 2 - 2, 1); + } + }), + crate: d => sprite('crate' + d, 12, 14, x => { + x.fillStyle = '#d29a52'; x.fillRect(0, 0, 12, 4); x.fillStyle = '#aa763c'; x.fillRect(0, 3, 12, 11); + x.fillStyle = '#7a4f24'; x.fillRect(0, 3, 12, 1); x.fillRect(0, 13, 12, 1); x.fillRect(0, 3, 1, 11); x.fillRect(11, 3, 1, 11); + x.fillStyle = '#8a5a2a'; for (let i = 0; i < 9; i++) x.fillRect(1 + i, 4 + i, 2, 1); + if (d) { x.fillStyle = '#3a2410'; x.fillRect(3, 6, 1, 3); x.fillRect(4, 8, 2, 1); x.fillRect(8, 5, 1, 2); x.fillRect(7, 10, 2, 1); } + }), + // Grand Slime room: smiling-face boxes (doc) and weapon crates + smile: d => sprite('smile' + d, 12, 14, x => { + x.fillStyle = '#e8c070'; x.fillRect(0, 0, 12, 4); x.fillStyle = '#c99a4a'; x.fillRect(0, 3, 12, 11); + x.fillStyle = '#8a6224'; x.fillRect(0, 3, 12, 1); x.fillRect(0, 13, 12, 1); x.fillRect(0, 3, 1, 11); x.fillRect(11, 3, 1, 11); + x.fillStyle = '#3a2410'; x.fillRect(3, 6, 2, 2); x.fillRect(7, 6, 2, 2); x.fillRect(3, 10, 6, 1); x.fillRect(2, 9, 1, 1); x.fillRect(9, 9, 1, 1); + if (d) { x.fillRect(5, 4, 1, 2); x.fillRect(9, 11, 2, 1); } + }), + wcrate: d => sprite('wcrate' + d, 14, 14, x => { + x.fillStyle = '#8a94a2'; x.fillRect(0, 0, 14, 4); x.fillStyle = '#5a6270'; x.fillRect(0, 3, 14, 11); + x.fillStyle = '#2f343c'; x.fillRect(0, 3, 14, 1); x.fillRect(0, 13, 14, 1); x.fillStyle = '#f2c94c'; x.fillRect(5, 6, 4, 3); x.fillRect(6, 9, 2, 2); + if (d) { x.fillStyle = '#1a1e24'; x.fillRect(2, 5, 1, 3); x.fillRect(11, 10, 2, 1); } + }), + // Volcanic Sandworm room: one pillar (doc) + pillar: () => sprite('pillar', 24, 34, x => { + x.fillStyle = '#4a3a34'; x.fillRect(1, 6, 22, 28); x.fillStyle = '#6a544a'; x.fillRect(1, 6, 6, 28); + x.fillStyle = '#2a1e1a'; x.fillRect(17, 6, 6, 28); x.fillStyle = '#8a7060'; x.fillRect(0, 0, 24, 7); x.fillStyle = '#a88a74'; x.fillRect(0, 0, 24, 2); + x.fillStyle = '#ff7a2a'; x.fillRect(8, 14, 2, 8); x.fillRect(10, 20, 4, 2); x.fillRect(13, 22, 2, 6); x.fillStyle = '#ffd04a'; x.fillRect(8, 15, 1, 5); + }) + }; + const WEAPON_ART = { + pistol: () => sprite('w-pistol', 9, 6, x => { x.fillStyle = '#9aa3ad'; x.fillRect(0, 0, 9, 3); x.fillStyle = '#d4dbe2'; x.fillRect(1, 0, 7, 1); x.fillStyle = '#4a3a2a'; x.fillRect(1, 3, 3, 3); }), + rifle: () => sprite('w-rifle', 16, 6, x => { x.fillStyle = '#5a6270'; x.fillRect(3, 0, 13, 3); x.fillStyle = '#8a94a2'; x.fillRect(4, 0, 11, 1); x.fillStyle = '#7a5230'; x.fillRect(0, 1, 4, 3); x.fillStyle = '#2f343c'; x.fillRect(7, 3, 3, 3); x.fillRect(4, 3, 2, 2); }), + sword: () => sprite('w-sword', 22, 7, x => { x.fillStyle = '#d8e0e8'; x.fillRect(6, 2, 16, 3); x.fillStyle = '#ffffff'; x.fillRect(7, 2, 14, 1); x.fillStyle = '#9aa6b2'; x.fillRect(6, 4, 15, 1); x.fillStyle = '#c9a227'; x.fillRect(4, 0, 2, 7); x.fillStyle = '#7a4a2a'; x.fillRect(0, 2, 4, 3); }) + }; + const ICONS = { + hp: () => fromMatrix('i-hp', ['.RR.RR.', 'RrrRrrR', 'RrwrrrR', '.RrrrR.', '..RrR..', '...R...'], { R: '#b5282c', r: '#ff5050', w: '#ffc0c0' }), + armor: () => fromMatrix('i-armor', ['SSSSSSS', 'SwsssgS', 'SsssssS', '.SsssS.', '..SsS..', '...S...'], { S: '#6b7686', s: '#c4cdd8', w: '#ffffff', g: '#9aa4b2' }), + energy: () => fromMatrix('i-energy', ['...B...', '..BwB..', '.BbbbB.', 'BbbbbbB', '.BbbbB.', '..BbB..', '...B...'], { B: '#2a6ad0', b: '#5ab4ff', w: '#e0f4ff' }), + angry: () => fromMatrix('i-angry', ['.R...R.', 'RrR.RrR', '.RrrrR.', '..RrR..', '.RrrrR.', 'RrR.RrR', '.R...R.'], { R: '#a01818', r: '#ff3a3a' }), + orb: () => sprite('i-orb', 6, 7, x => { x.fillStyle = '#3a8aff'; poly(x, [[3, 0], [6, 3.5], [3, 7], [0, 3.5]]); x.fillStyle = '#bfe4ff'; x.fillRect(2, 2, 1, 2); }) + }; + + // ---------- bullets (screen resolution, cached) ---------- + function bulletSprite(kind, r) { + const key = 'b' + kind + r; + let s = cache.get(key); + if (s) return s; + const pad = 3, size = Math.ceil(r * 2 + pad * 2 + 6), c = mk(size, size), x = ctx2d(c), m = size / 2; + const disc = (rr, col) => ell(x, col, m, m, rr, rr); + if (kind === 'star') { + x.fillStyle = '#3a2a06'; starPath(x, m, m, r + 3, r * 0.5 + 2, 5); x.fill(); + x.fillStyle = '#ffd43a'; starPath(x, m, m, r + 1, r * 0.5, 5); x.fill(); + x.fillStyle = '#fff4b0'; starPath(x, m - 1, m - 1, r * 0.45, r * 0.2, 5); x.fill(); + } else if (kind === 'cross') { + const arm = (w, h, col) => { x.fillStyle = col; x.fillRect(m - w / 2, m - h / 2, w, h); x.fillRect(m - h / 2, m - w / 2, h, w); }; + arm(r * 2 + 4, r * 0.9 + 4, '#3a1406'); arm(r * 2, r * 0.9, '#ff8a2a'); arm(r * 1.1, r * 0.35, '#ffe0a0'); + } else if (kind === 'bubble') { + disc(r + 2, 'rgba(58,20,70,0.85)'); disc(r, 'rgba(226,128,236,0.75)'); disc(r - 2, 'rgba(250,190,255,0.55)'); ell(x, '#ffffff', m - r * 0.35, m - r * 0.35, 2, 1.6); + } else if (kind === 'homing') { + disc(r + 2, '#1a1640'); disc(r, '#6f74ff'); disc(r * 0.55, '#d4d6ff'); ell(x, '#ffffff', m - 1.5, m - 1.5, 1.4, 1.4); + } else if (kind === 'diamond' || kind === 'slam' || kind === 'petal') { // Grand Slime bullets + const col = kind === 'diamond' ? ['#3a0612', '#ff2a4a', '#ffd0d8'] : kind === 'petal' ? ['#3a1a06', '#ffb03a', '#fff0c0'] : ['#3a0612', '#ff5a6a', '#ffd0d8']; + if (kind === 'diamond') { x.fillStyle = col[0]; poly(x, [[m, m - r - 3], [m + r + 3, m], [m, m + r + 3], [m - r - 3, m]]); x.fillStyle = col[1]; poly(x, [[m, m - r], [m + r, m], [m, m + r], [m - r, m]]); x.fillStyle = col[2]; x.fillRect(m - 1.5, m - r * 0.5, 2, 3); } + else { disc(r + 2, col[0]); disc(r, col[1]); disc(r * 0.5, col[2]); } + } else if (kind === 'vorb') { // Varkolyn spiral emitter + disc(r + 3, '#12061e'); disc(r + 1, '#6a2aaa'); disc(r - 2, '#c46aff'); disc(r * 0.45, '#f6e0ff'); + x.strokeStyle = '#f6e0ff'; x.lineWidth = 2; for (let i = 0; i < 4; i++) { const a = i * Math.PI / 2 + 0.4; x.beginPath(); x.moveTo(m + Math.cos(a) * (r - 4), m + Math.sin(a) * (r - 4)); x.lineTo(m + Math.cos(a) * (r + 1), m + Math.sin(a) * (r + 1)); x.stroke(); } + } else if (kind === 'shell' || kind === 'big') { // Sandworm explosive / big bullet + const col = kind === 'shell' ? ['#2a0e04', '#8a3a14', '#ffb04a'] : ['#2a0606', '#ff4a2a', '#ffd08a']; + disc(r + 2, col[0]); disc(r, col[1]); disc(r * 0.55, col[2]); x.fillStyle = '#fff4d0'; x.fillRect(m - r * 0.45, m - r * 0.45, 2, 2); + } else if (kind === 'bouncy') { + disc(r + 2, '#2a1006'); disc(r, '#ff8a2a'); disc(r * 0.5, '#fff0a0'); + } else { + const col = kind === 'beam' ? ['#0f3a12', '#6dff4a', '#e0ffd0'] : kind === 'rail' ? ['#2a0f3a', '#c86aff', '#f6dcff'] : ['#2a0a10', '#ff5440', '#ffb070']; + disc(r + 2, col[0]); disc(r, col[1]); disc(r * 0.55, col[2]); ell(x, '#ffffff', m - r * 0.35, m - r * 0.35, Math.max(1, r * 0.25), Math.max(1, r * 0.25)); + } + s = { c, m }; + cache.set(key, s); + return s; + } + function capsule(c, x, y, a, len, w, cols) { + c.save(); c.translate(x, y); c.rotate(a); + c.fillStyle = cols[0]; c.beginPath(); c.ellipse(0, 0, len / 2 + 2, w / 2 + 2, 0, 0, TAU); c.fill(); + c.fillStyle = cols[1]; c.beginPath(); c.ellipse(0, 0, len / 2, w / 2, 0, 0, TAU); c.fill(); + c.fillStyle = cols[2]; c.beginPath(); c.ellipse(len * 0.12, -w * 0.12, len * 0.28, w * 0.22, 0, 0, TAU); c.fill(); + c.restore(); + } + + // ---------- room background (cached per case) ---------- + function background(kind) { + const key = 'bg' + kind; + let s = cache.get(key); + if (s) return s; + const c = mk(854, 480), x = ctx2d(c); + x.fillStyle = '#0a110d'; x.fillRect(0, 0, 854, 480); + // per-biome floor: Forest (green), Knight Kingdom (castle flagstone), Spaceship (steel deck), Volcano (basalt) + const theme = kind === 'christmas_treant' ? { a: '#5d8a58', b: '#567f51', lo: '#4a7046', hi: '#76a06e', snow: 0.2 } + : kind === 'devils_snare' ? { a: '#3f6a3d', b: '#3b6439', lo: '#30562f', hi: '#548752', snow: 0 } + : kind === 'grand_slime' ? { a: '#8a8072', b: '#80766a', lo: '#6c6458', hi: '#a09484', snow: 0, stone: 1, wall: ['#5a5048', '#665a50', '#7a6e62'], cap: ['#3a3430', '#4a423a', '#2a2622'] } + : kind === 'varkolyn_leader' ? { a: '#2c3440', b: '#283039', lo: '#1e252e', hi: '#3c4654', snow: 0, deck: 1, wall: ['#1e2a38', '#243244', '#34465c'], cap: ['#121a24', '#1a2430', '#0c1218'] } + : kind === 'volcanic_sandworm' ? { a: '#3a2a26', b: '#352622', lo: '#2a1e1a', hi: '#4a3630', snow: 0, lava: 1, wall: ['#2a1e1a', '#34261f', '#4a3428'], cap: ['#1a1210', '#2a1a14', '#120c0a'] } + : { a: '#4f7d3d', b: '#4a7639', lo: '#3f6630', hi: '#6a9a50', snow: 0 }; + const cols = (R.x1 - R.x0) / TILE, rows = (R.y1 - R.y0) / TILE, forest = !theme.wall; + for (let r = 0; r < rows; r++) for (let q = 0; q < cols; q++) { + const X = R.x0 + q * TILE, Y = R.y0 + r * TILE; + x.fillStyle = (q + r) % 2 ? theme.a : theme.b; x.fillRect(X, Y, TILE, TILE); + for (let i = 0; i < 7; i++) { const u = hash(q * 7 + i, r * 13), v = hash(r * 11 + i, q * 5 + 3); x.fillStyle = u < 0.5 ? theme.lo : theme.hi; x.fillRect(X + Math.floor(u * 11) * 2, Y + Math.floor(v * 11) * 2, 2, 2); } + x.fillStyle = 'rgba(0,0,0,0.10)'; x.fillRect(X, Y + TILE - 2, TILE, 2); x.fillRect(X + TILE - 2, Y, 2, TILE); + const h = hash(q + 101, r + 37); + if (forest) { + if (h < 0.12) { x.fillStyle = theme.hi; const gx = X + 6 + Math.floor(hash(q, r + 5) * 6) * 2, gy = Y + 8 + Math.floor(hash(q + 3, r) * 4) * 2; x.fillRect(gx, gy, 2, 6); x.fillRect(gx - 3, gy + 2, 2, 4); x.fillRect(gx + 3, gy + 2, 2, 4); } + else if (h < 0.16) { const fc = ['#f2d24a', '#e86aa8', '#ffffff', '#7ac8ff'][Math.floor(hash(q, r) * 4)]; const fx = X + 8 + Math.floor(hash(r, q) * 4) * 2, fy = Y + 8; x.fillStyle = fc; x.fillRect(fx - 2, fy, 2, 2); x.fillRect(fx + 2, fy, 2, 2); x.fillRect(fx, fy - 2, 2, 2); x.fillRect(fx, fy + 2, 2, 2); x.fillStyle = '#e0a020'; x.fillRect(fx, fy, 2, 2); } + else if (h < 0.19) { x.fillStyle = '#7d8a7a'; x.fillRect(X + 10, Y + 12, 4, 2); x.fillStyle = '#a2ad9e'; x.fillRect(X + 10, Y + 12, 2, 1); } + } else if (theme.stone && h < 0.1) { x.fillStyle = '#5a5248'; x.fillRect(X + 4, Y + 10, 8, 1); x.fillRect(X + 11, Y + 10, 1, 6); } + else if (theme.deck) { x.fillStyle = '#3c4654'; x.fillRect(X + 2, Y + 2, 2, 2); x.fillRect(X + TILE - 4, Y + 2, 2, 2); x.fillRect(X + 2, Y + TILE - 4, 2, 2); x.fillRect(X + TILE - 4, Y + TILE - 4, 2, 2); if (h < 0.08) { x.fillStyle = '#5ac8ff'; x.fillRect(X + 8, Y + 11, 8, 2); } } + else if (theme.lava && h < 0.09) { x.fillStyle = '#ff6a2a'; x.fillRect(X + 6, Y + 8, 2, 6); x.fillRect(X + 8, Y + 12, 6, 2); x.fillStyle = '#ffc04a'; x.fillRect(X + 6, Y + 9, 1, 3); } + if (theme.snow && hash(q + 9, r + 77) < theme.snow) { x.fillStyle = 'rgba(240,248,255,0.85)'; const sx = X + Math.floor(hash(q, r + 9) * 6) * 2, sy = Y + Math.floor(hash(q + 4, r) * 6) * 2; x.fillRect(sx, sy, 10, 4); x.fillRect(sx + 2, sy - 2, 6, 2); x.fillRect(sx + 2, sy + 4, 8, 2); } + } + if (kind === 'devils_snare') { // moss ring around the stationary boss + for (let i = 0; i < 90; i++) { const a = hash(i, 3) * TAU, d = 50 + hash(i, 4) * 90; x.fillStyle = i % 3 ? '#2e5a2c' : '#5a8a3a'; x.fillRect(Math.round((427 + Math.cos(a) * d) / 2) * 2, Math.round((256 + Math.sin(a) * d) / 2) * 2, 4, 2); } + } + // walls: hedge caps + stone brick face at the top (later biomes: their own masonry colours) + const W = theme.wall || ['#4a584c', '#435046', '#5c6b5e'], C = theme.cap || ['#244d29', '#2f6234', '#1b3d20']; + const hedge = (X, Y, w, h) => { x.fillStyle = C[0]; x.fillRect(X, Y, w, h); for (let i = 0; i < w * h / 18; i++) { const u = hash(X + i, Y), v = hash(Y + i, X + 1); x.fillStyle = u < 0.5 ? C[1] : C[2]; x.fillRect(X + Math.floor(u * w / 2) * 2, Y + Math.floor(v * h / 2) * 2, 2, 2); } }; + x.fillStyle = '#3e4a40'; x.fillRect(R.x0 - 12, 40, R.x1 - R.x0 + 24, 24); + x.save(); x.beginPath(); x.rect(R.x0 - 12, 40, R.x1 - R.x0 + 24, 24); x.clip(); + for (let row = 0; row < 2; row++) for (let i = 0; i < 34; i++) { + const bx = R.x0 - 12 + i * 24 - (row ? 12 : 0), by = 40 + row * 12; + x.fillStyle = (i + row) % 3 ? W[0] : W[1]; x.fillRect(bx + 1, by + 1, 22, 10); x.fillStyle = W[2]; x.fillRect(bx + 1, by + 1, 22, 2); + } + x.restore(); + x.fillStyle = '#2a332c'; x.fillRect(R.x0 - 12, 63, R.x1 - R.x0 + 24, 1); + hedge(R.x0 - 12, 26, R.x1 - R.x0 + 24, 14); hedge(R.x0 - 12, 26, 12, R.y1 - 26 + 10); hedge(R.x1, 26, 12, R.y1 - 26 + 10); hedge(R.x0 - 12, R.y1, R.x1 - R.x0 + 24, 8); + x.fillStyle = '#16301a'; x.fillRect(R.x0 - 12, 38, R.x1 - R.x0 + 24, 2); + const grd = x.createLinearGradient(0, R.y0, 0, R.y0 + 14); grd.addColorStop(0, 'rgba(0,0,0,0.35)'); grd.addColorStop(1, 'rgba(0,0,0,0)'); x.fillStyle = grd; x.fillRect(R.x0, R.y0, R.x1 - R.x0, 14); + x.fillStyle = 'rgba(0,0,0,0.25)'; x.fillRect(R.x0, R.y0, 6, R.y1 - R.y0); x.fillRect(R.x1 - 4, R.y0, 4, R.y1 - R.y0); + s = c; + cache.set(key, s); + return s; + } + + // ---------- helpers ---------- + function txt(c, s, x, y, size, col, align, weight) { + c.font = (weight || 'bold') + ' ' + size + 'px ' + FONT; c.textAlign = align || 'left'; c.textBaseline = 'alphabetic'; + c.lineJoin = 'round'; c.lineWidth = Math.max(2, size / 4); c.strokeStyle = '#0b0a10'; c.strokeText(s, x, y); c.fillStyle = col; c.fillText(s, x, y); + } + function panel(c, x, y, w, h) { + c.fillStyle = 'rgba(16,14,22,0.84)'; c.fillRect(x, y, w, h); + c.strokeStyle = '#06050a'; c.lineWidth = 2; c.strokeRect(x + 1, y + 1, w - 2, h - 2); + c.strokeStyle = 'rgba(150,140,170,0.45)'; c.lineWidth = 1; c.strokeRect(x + 3.5, y + 3.5, w - 7, h - 7); + } + function bar(c, x, y, w, h, v, max, fg, bg, label) { + c.fillStyle = '#06050a'; c.fillRect(x - 1, y - 1, w + 2, h + 2); c.fillStyle = bg; c.fillRect(x, y, w, h); + const f = Math.max(0, Math.min(1, v / max)); + c.fillStyle = fg; c.fillRect(x, y, Math.round(w * f), h); c.fillStyle = 'rgba(255,255,255,0.28)'; c.fillRect(x, y, Math.round(w * f), 2); + if (label) txt(c, label, x + w / 2, y + h - 2, 11, '#ffffff', 'center'); + } + const shadow = (c, x, y, rx, ry) => { c.fillStyle = 'rgba(0,0,0,0.28)'; c.beginPath(); c.ellipse(x, y, rx, ry, 0, 0, TAU); c.fill(); }; + + // ---------- world ---------- + function drawKnight(c, g) { + const p = g.player, t = g.t; + const frame = p.moving && Math.floor(p.step / 8) % 2 ? 1 : 0, bob = p.moving && Math.floor(p.step / 8) % 2 ? -2 : 0; + const flip = p.face < 0, flash = t - p.hurtT < 5, blink = p.inv > 0 && Math.floor(t / 4) % 2 === 1; + shadow(c, p.x, p.y + 11, 10, 4); + if (p.dead > 0 || (p.hp <= 0)) { + c.save(); c.translate(p.x, p.y + 8); c.rotate(-Math.PI / 2); c.globalAlpha = 0.9; c.drawImage(knight(0).c, -14, -16, 28, 34); c.restore(); + return; + } + if (p.dual > 0) { c.strokeStyle = 'rgba(255,210,80,' + (0.35 + 0.2 * Math.sin(t * 0.3)) + ')'; c.lineWidth = 2; c.beginPath(); c.ellipse(p.x, p.y + 11, 15, 6, 0, 0, TAU); c.stroke(); } + const wid = M.slots[p.slot], back = Math.sin(p.aimA) < -0.2; + if (back) drawWeapon(c, g, wid); + blit(c, knight(frame), p.x, p.y + 13 + bob, 2, flip, flash, blink ? 0.35 : undefined); + if (p.poison > 0) { c.fillStyle = 'rgba(90,220,70,0.25)'; c.fillRect(p.x - 12, p.y - 20, 24, 32); } + if (!back) drawWeapon(c, g, wid); + } + function drawWeapon(c, g, wid) { + const p = g.player, t = g.t, s = WEAPON_ART[wid](), a = p.aimA, flipY = Math.cos(a) < 0; + const one = (side, last) => { + c.save(); c.translate(p.x, p.y + 4); c.rotate(a); c.translate(4, side); if (flipY) c.scale(1, -1); + if (wid === 'sword') { + if (p.swing > 0 && p.swingKind !== 'knife') c.rotate(((p.swing / 8) - 0.5) * -2.2); + c.drawImage(s.c, -2, -s.h, s.w * 2, s.h * 2); + } else { + const kick = t - last < 3 ? -2 : 0; + c.drawImage(s.c, kick, -s.h + 1, s.w * 2, s.h * 2); + if (t - last < 3) { const mx = s.w * 2 + kick + 2; c.fillStyle = '#fff6c0'; c.fillRect(mx, -2, 8, 4); c.fillRect(mx + 2, -5, 4, 10); c.fillStyle = '#ffc23a'; c.fillRect(mx + 7, -1, 4, 2); } + } + c.restore(); + }; + one(0, p.lastShot); + if (p.dual > 0) one(7, p.lastCopy); + } + function drawSwing(c, g) { + const p = g.player; + if (p.swing <= 0 || p.dead > 0) return; + const knife = p.swingKind === 'knife', k = p.swing / (knife ? 10 : 8); + const reach = knife ? 24 : M.weapons.sword.reach, arc = knife ? 0.9 : M.weapons.sword.arc * Math.PI / 180; + c.save(); c.globalAlpha = 0.25 + 0.6 * k; + c.strokeStyle = '#ffffff'; c.lineWidth = knife ? 3 : 7; c.beginPath(); c.arc(p.x, p.y, reach - 4, p.swingA - arc, p.swingA + arc); c.stroke(); + c.strokeStyle = knife ? '#ffd0a0' : '#9fd8ff'; c.lineWidth = knife ? 2 : 3; c.beginPath(); c.arc(p.x, p.y, reach - 10, p.swingA - arc * 0.85, p.swingA + arc * 0.85); c.stroke(); + if (!knife) { c.globalAlpha *= 0.18; c.fillStyle = '#cfefff'; c.beginPath(); c.moveTo(p.x, p.y); c.arc(p.x, p.y, reach, p.swingA - arc, p.swingA + arc); c.closePath(); c.fill(); } + c.restore(); + } + function drawBoss(c, g) { + const b = g.boss, t = g.t; + if (b.hp <= 0 && b.state !== 'dying') return; + // hit flash = light 2-tick tint (round 3: a 0.6 white overlay covered the boss in 11-15 % of video frames under sustained fire) + const dying = b.state === 'dying', since = t - b.flash, flash = since < 2 ? 0.32 : (dying && Math.floor(t / 4) % 2 === 0) ? 0.8 : 0; + let alpha = dying ? Math.min(1, b.deadT / 30) : undefined; + if (b.kind === 'goblin_priest') { + const s = bossSprite('goblin_priest', b.enraged), flip = b.face < 0, walk = (b.vx || b.vy) ? Math.floor(t / 10) % 2 * -2 : 0; + shadow(c, b.x, b.y + 18, 20, 6); + blit(c, s, b.x, b.y + 20 + walk, 2, flip, flash, alpha); + drawStaff(c, g); + } else if (b.kind === 'christmas_treant') { + const s = bossSprite('christmas_treant', b.enraged), charging = b.atk === 'charge' && b.vars.ph === 'dash'; + shadow(c, b.x, b.y + 28, 30, 9); + c.save(); + if (charging) { + c.translate(b.x, b.y + 30); c.rotate(Math.cos(b.vars.a) * 0.25); c.translate(-b.x, -(b.y + 30)); + c.strokeStyle = 'rgba(255,255,255,0.55)'; c.lineWidth = 2; + for (let i = 0; i < 5; i++) { const o = (i - 2) * 12, ca = Math.cos(b.vars.a), sa = Math.sin(b.vars.a); c.beginPath(); c.moveTo(b.x - ca * 44 - sa * o, b.y - sa * 44 + ca * o); c.lineTo(b.x - ca * (70 + i * 6) - sa * o, b.y - sa * (70 + i * 6) + ca * o); c.stroke(); } + } + const stomp = (b.atk === 'waves' || b.atk === 'line' || b.atk === 'transform') && b.at % 30 < 8 ? 3 : 0; + blit(c, s, b.x, b.y + 32 + stomp, 2, b.face < 0, flash, alpha); + c.restore(); + if ((b.atk === 'hold' && b.at >= 6 && b.at < 172) || (b.atk === 'throw' && b.at < 30)) drawLaserBall(c, b.x, b.y - 48, 16, t); + if (b.atk === 'homing' && b.at < 22) { c.fillStyle = 'rgba(160,170,255,0.5)'; c.beginPath(); c.arc(b.x, b.y - 58, 10 + b.at * 0.6, 0, TAU); c.fill(); } + } else if (b.kind === 'grand_slime') { + // sprite bottom-centre at y+20: the jelly body (art 1..55 x 7..43) spans the hurt capsule [-16, 2] r 28 + const s = bossSprite('grand_slime', b.enraged), squash = 1 + 0.06 * Math.sin(t * 0.25) + ((b.atk === 'slam' || b.atk === 'goo') && b.at % 30 > 18 ? 0.12 : 0); + const swell = b.boom > 0 ? 1 + 0.18 * (1 - b.boom / M.SLIME_SWELL) : 1; + shadow(c, b.x, b.y + 20, 32, 8); + c.save(); c.translate(b.x, b.y + 17); c.scale(swell * squash, swell / squash); c.translate(-b.x, -(b.y + 17)); + blit(c, s, b.x, b.y + 17, 2, b.face < 0, flash || (b.boom > 0 && Math.floor(t / 4) % 2 ? 0.5 : 0), alpha); + c.restore(); + } else if (b.kind === 'varkolyn_leader') { + const s = bossSprite('varkolyn_leader', b.enraged), walk = (b.vx || b.vy) ? Math.floor(t / 10) % 2 * -2 : 0; + shadow(c, b.x, b.y + 8, 16, 5); + // shield: doc "becomes semi-transparent" while invulnerable in its pool + const a = b.shield > 0 ? 0.45 : alpha; + blit(c, s, b.x, b.y + 8 + walk, 2, b.face < 0, flash, a); + if (b.shield > 0) { c.strokeStyle = 'rgba(200,140,255,' + (0.5 + 0.3 * Math.sin(t * 0.4)) + ')'; c.lineWidth = 2; c.beginPath(); c.ellipse(b.x, b.y - 24, 22, 38, 0, 0, TAU); c.stroke(); } + if (b.atk === 'laser' && !b.vars.on) { // doc: raises its head, swirl mark glows before the chime -> laser + c.fillStyle = 'rgba(255,90,140,' + (0.3 + 0.3 * Math.sin(t * 0.8)) + ')'; c.beginPath(); c.arc(b.x, b.y - M.VARK_EYE, 10, 0, TAU); c.fill(); + } + } else if (b.kind === 'volcanic_sandworm') { + const v = b.vars; + if (b.under) { // doc: "a dirt pile where the boss is burrowed. It will move and can serve as an indicator" + drawMound(c, b.x, b.y, t, v.ph === 'rise' ? 1 - v.c / M.WORM_RISE : 0); + } else { + const sink = v.ph === 'sink' ? 1 - v.c / Math.max(1, Math.round(M.WORM_SINK * (b.enraged ? 0.7 : 1))) : 0; + const tilt = (b.atk === 'explosive' || b.atk === 'spread') && b.at < 24 ? -0.12 * Math.min(1, b.at / 12) : 0; + shadow(c, b.x, b.y + 4, 24, 7); + c.save(); c.beginPath(); c.rect(b.x - 40, b.y - 120, 80, 126); c.clip(); + c.translate(b.x, b.y + 4); c.rotate(tilt); c.translate(-b.x, -(b.y + 4)); + blit(c, bossSprite('volcanic_sandworm', b.enraged), b.x, b.y + 4 + sink * 84, 2, b.face < 0, flash, alpha); + c.restore(); + drawMound(c, b.x, b.y + 6, t, 0, true); + } + } else { + const s = bossSprite('devils_snare', b.enraged), pulse = (b.atk === 'bubbles' && b.at < 20) ? 1 + 0.08 * Math.sin(b.at * 0.8) : 1; + shadow(c, b.x, b.y + 38, 36, 10); + for (const tn of b.tentacles) drawTentacle(c, b, tn, t, b.atk === 'corner' && b.at < 22); + // anchor so the flower centre (art 22,21) sits exactly on the boss / hurt circle centre + c.save(); c.translate(b.x, b.y + 44); c.scale(pulse, pulse); c.translate(-b.x, -(b.y + 44)); + blit(c, s, b.x, b.y + 44, 2, false, flash, alpha); + c.restore(); + if (b.atk === 'beams' && b.at < 22) { c.fillStyle = 'rgba(110,255,80,0.25)'; c.beginPath(); c.arc(b.x, b.y, 36 + b.at, 0, TAU); c.fill(); } + } + const iconUp = ['grand_slime', 'varkolyn_leader', 'volcanic_sandworm'].includes(b.kind) ? -M.bosses[b.kind].hurt[0] + 30 : b.r * 1.7; // above the tall new sprites + if (b.enraged && !dying && !b.under) blit(c, ICONS.angry(), b.x + b.r * 0.8, b.y - iconUp + Math.sin(t * 0.2) * 2, 2); + } + function drawMound(c, x, y, t, rise, rim) { // Sandworm dirt mound (moving indicator) / ring of rubble at the hole + const n = rim ? 7 : 9, w = rim ? 26 : 22 + rise * 8; + for (let i = 0; i < n; i++) { + const a = i * TAU / n + (rim ? 0 : t * 0.05), j = rim ? 0 : Math.sin(t * 0.6 + i) * 1.5 * (1 + rise * 2); + ell(c, i % 2 ? '#5a3a24' : '#7a5232', x + Math.cos(a) * w * 0.6 + j, y + Math.sin(a) * w * 0.25, 7, 4); + } + if (!rim) { ell(c, '#3a2414', x, y, w * 0.5, w * 0.2); if (rise > 0) { c.fillStyle = 'rgba(255,140,60,' + (0.3 + 0.4 * rise) + ')'; c.beginPath(); c.ellipse(x, y, w * 0.4, w * 0.15, 0, 0, TAU); c.fill(); } } + } + function drawMinions(c, g) { + const t = g.t; + for (const m of g.minions) { + const e = m.emerge > 0 ? 1 - m.emerge / (m.kind === 'slime' ? 24 : 40) : 1, f = Math.floor(t / 10) % 2; + if (m.kind === 'slime') { + shadow(c, m.x, m.y + 8, 9, 3); + c.save(); if (e < 1) c.globalAlpha = 0.4 + 0.6 * e; + blit(c, minionSprite('slime', f), m.x, m.y + 9, 2, false, t - m.flash < 3 ? 0.5 : 0); c.restore(); + } else { + // tentacle grows out of the floor (emerging = harmless, not yet firing) + shadow(c, m.x, m.y + 10, 10, 3); + c.save(); c.beginPath(); c.rect(m.x - 20, m.y - 40, 40, 62); c.clip(); + blit(c, minionSprite('tentacle', f), m.x, m.y + 20 + (1 - e) * 40, 2, false, t - m.flash < 3 ? 0.5 : 0); c.restore(); + if (e >= 1 && m.fire < 20) { c.fillStyle = 'rgba(196,106,255,' + (0.6 - m.fire * 0.025) + ')'; c.beginPath(); c.arc(m.x, m.y - 10, 8 + (20 - m.fire) * 0.5, 0, TAU); c.fill(); } + } + } + } + function drawStaff(c, g) { + const b = g.boss, front = b.face > 0 ? 1 : -1; + const hx = b.x + front * 18, top = b.y - 34; + c.fillStyle = '#1a120a'; c.fillRect(hx - 3, top - 2, 6, 58); c.fillStyle = '#8a5a2a'; c.fillRect(hx - 1, top, 3, 54); c.fillStyle = '#b07a40'; c.fillRect(hx - 1, top, 1, 54); + const col = { meteor: '#ff7a2a', orbs: '#6ad8ff', turrets: '#d0d8e0', stars: '#ffd43a' }[b.atk] || '#a8e68e'; + const glow = b.state === 'cast' ? 9 + Math.sin(g.t * 0.5) * 2 : 6; + c.fillStyle = col; c.globalAlpha = 0.35; c.beginPath(); c.arc(hx, top - 4, glow + 5, 0, TAU); c.fill(); c.globalAlpha = 1; + c.fillStyle = '#16120a'; starPath(c, hx, top - 4, 9, 4, 5); c.fill(); c.fillStyle = col; starPath(c, hx, top - 4, 7, 3, 5); c.fill(); + } + function drawTentacle(c, b, tn, t, glow) { + const n = 7; + for (let i = 0; i <= n; i++) { + const k = i / n, w = Math.sin(t * 0.12 + i * 0.9) * 5 * (1 - Math.abs(k - 0.5) * 2); + const dx = tn.x - b.x, dy = tn.y - b.y, L = Math.hypot(dx, dy) || 1; + const x = b.x + dx * k - dy / L * w, y = b.y + dy * k + dx / L * w, r = 9 - k * 2; + ell(c, '#24082c', x, y, r + 2, r + 2); ell(c, i % 2 ? '#7a2f8f' : '#9a45ad', x, y, r, r); + } + ell(c, '#24082c', tn.x, tn.y, tn.r + 2, tn.r + 2); ell(c, glow ? '#e88aff' : '#a24bb8', tn.x, tn.y, tn.r, tn.r); ell(c, '#d47ad8', tn.x - 4, tn.y - 4, 4, 3); + c.fillStyle = '#f4efe6'; for (let i = 0; i < 4; i++) { const a = i * Math.PI / 2 + t * 0.03; c.fillRect(tn.x + Math.cos(a) * (tn.r + 1) - 1, tn.y + Math.sin(a) * (tn.r + 1) - 1, 3, 3); } + } + function drawLaserBall(c, x, y, r, t) { + const gr = c.createRadialGradient(x, y, 2, x, y, r + 10); + gr.addColorStop(0, '#ffffff'); gr.addColorStop(0.45, '#9ff4ff'); gr.addColorStop(0.75, 'rgba(80,190,255,0.6)'); gr.addColorStop(1, 'rgba(80,190,255,0)'); + c.fillStyle = gr; c.beginPath(); c.arc(x, y, r + 10, 0, TAU); c.fill(); + c.strokeStyle = '#ffffff'; c.lineWidth = 2; + for (let i = 0; i < 4; i++) { const a = t * 0.25 + i * Math.PI / 2; c.beginPath(); c.moveTo(x + Math.cos(a) * (r - 4), y + Math.sin(a) * (r - 4)); c.lineTo(x + Math.cos(a) * (r + 6), y + Math.sin(a) * (r + 6)); c.stroke(); } + } + function drawShuriken(c, x, y, r, a) { + c.save(); c.translate(x, y); c.rotate(a); + c.fillStyle = '#14161c'; starPath(c, 0, 0, r + 2, r * 0.35 + 2, 4, 0); c.fill(); + c.fillStyle = '#c0c8d4'; starPath(c, 0, 0, r, r * 0.35, 4, 0); c.fill(); + c.fillStyle = '#5a6270'; c.fillRect(-2, -2, 4, 4); + c.restore(); + } + + function drawGround(c, g) { + const t = g.t, b = g.boss; + for (const tile of g.tiles) { // Grand Slime room: Slow (down arrows) / Boost (up arrows) tiles + const slow = tile.kind === 'slow'; + c.fillStyle = slow ? 'rgba(90,60,140,0.55)' : 'rgba(40,140,200,0.5)'; c.fillRect(tile.x + 2, tile.y + 2, tile.w - 4, tile.h - 4); + c.strokeStyle = slow ? '#b08aff' : '#7ad8ff'; c.lineWidth = 2; c.strokeRect(tile.x + 3, tile.y + 3, tile.w - 6, tile.h - 6); + c.fillStyle = slow ? '#d8c4ff' : '#c8f4ff'; + for (let i = 0; i < 2; i++) for (let j = 0; j < 2; j++) { + const x = tile.x + 12 + i * 24, y = tile.y + 12 + j * 24, s = slow ? 1 : -1, o = ((t * 0.5) % 8) * s; + poly(c, [[x - 6, y - 3 * s + o * 0.3], [x + 6, y - 3 * s + o * 0.3], [x, y + 5 * s + o * 0.3]]); + } + } + for (const pool of g.pools) { + const k = Math.min(1, pool.life / 30), purple = pool.purple; + if (pool.form > 0) { // forming: harmless; the dashed ring is the exact pool radius it will have + c.save(); c.globalAlpha = 0.85; c.strokeStyle = purple ? '#d48aff' : '#a8ff6a'; c.lineWidth = 2; c.setLineDash([5, 4]); + c.beginPath(); c.arc(pool.x, pool.y, pool.r, 0, TAU); c.stroke(); c.restore(); + c.globalAlpha = 0.25 * (1 - pool.form / 24); ell(c, purple ? '#8a3ad0' : '#4ec23a', pool.x, pool.y, pool.r, pool.r); c.globalAlpha = 1; + continue; + } + c.globalAlpha = 0.5 * k; ell(c, purple ? '#7a2ac0' : '#4ec23a', pool.x, pool.y, pool.r, pool.r); + c.globalAlpha = 0.6 * k; c.strokeStyle = purple ? '#d48aff' : '#a8ff6a'; c.lineWidth = 2; c.beginPath(); c.arc(pool.x, pool.y, pool.r - 1, 0, TAU); c.stroke(); + for (let i = 0; i < 6; i++) { const ph = (t * 0.04 + hash(i, pool.x | 0)) % 1, a = hash(i + 4, pool.y | 0) * TAU, d = hash(i, 9) * pool.r * 0.7; ell(c, purple ? '#f0c8ff' : '#c8ff9a', pool.x + Math.cos(a) * d, pool.y + Math.sin(a) * d - ph * 6, 2 + ph * 2, 2 + ph * 2); } + c.globalAlpha = 1; + } + // Grand Slime swell: the growing ring reaches the exact explosion radius when it bursts + if (b.kind === 'grand_slime' && b.boom > 0) { + const k = 1 - b.boom / M.SLIME_SWELL; + c.fillStyle = 'rgba(255,60,80,' + (0.10 + 0.22 * k) + ')'; c.beginPath(); c.arc(b.x, b.y, M.SLIME_BLAST * k, 0, TAU); c.fill(); + c.strokeStyle = 'rgba(255,90,110,0.9)'; c.lineWidth = 2; c.beginPath(); c.arc(b.x, b.y, M.SLIME_BLAST, 0, TAU); c.stroke(); + } + // Sandworm: shockwave rings (expanding, hit band drawn) and the burrow / surface warning radius + for (const q of g.quakes) { + const k = Math.min(1, q.age / q.total); + c.save(); c.globalAlpha = 1 - Math.max(0, (q.age - q.total) / 6); c.fillStyle = 'rgba(255,150,80,0.28)'; c.beginPath(); c.arc(q.x, q.y, q.rc, 0, TAU); c.fill(); + c.strokeStyle = '#ffb06a'; c.lineWidth = 6; c.beginPath(); c.arc(q.x, q.y, q.rc, 0, TAU); c.stroke(); + c.strokeStyle = '#7a3a14'; c.lineWidth = 2; c.beginPath(); c.arc(q.x, q.y, q.rc + 4, 0, TAU); c.stroke(); c.restore(); + void k; + } + if (b.kind === 'volcanic_sandworm' && (b.vars.ph === 'sink' || b.vars.ph === 'rise' || b.vars.ph === 'peek')) { + c.save(); c.strokeStyle = 'rgba(255,150,80,0.85)'; c.lineWidth = 2; c.setLineDash([6, 5]); + c.beginPath(); c.arc(b.x, b.y, M.QUAKE_R, 0, TAU); c.stroke(); c.restore(); + } + // Varkolyn laser: during the charge the whole swept arc is drawn (start edge bright, sweep direction arrow); + // while firing, the beam itself and the part of the arc still to be swept + if (b.atk === 'laser' && b.vars.a0 !== undefined) { + const v = b.vars, oy = b.y - M.VARK_EYE, end = v.a0 + v.dir * M.LASER_ARC, cur = v.on ? v.a : v.a0; + c.save(); c.globalAlpha = v.on ? 0.16 : 0.14 + 0.08 * Math.sin(t * 0.7); c.fillStyle = '#ff3a6a'; + c.beginPath(); c.moveTo(b.x, oy); c.arc(b.x, oy, 1100, Math.min(cur, end), Math.max(cur, end)); c.closePath(); c.fill(); + c.globalAlpha = 0.9; c.strokeStyle = v.on ? '#ffffff' : '#ff8aa8'; c.lineWidth = v.on ? M.LASER_W * 2 : 2; + if (!v.on) c.setLineDash([10, 6]); + c.beginPath(); c.moveTo(b.x, oy); c.lineTo(b.x + Math.cos(cur) * 1100, oy + Math.sin(cur) * 1100); c.stroke(); + if (v.on) { c.strokeStyle = '#ff3a8a'; c.lineWidth = M.LASER_W * 2 + 6; c.globalAlpha = 0.35; c.stroke(); } + c.restore(); + } + for (const m of g.meteors) { + const k = 1 - m.fall / m.total; + c.fillStyle = 'rgba(255,60,30,' + (0.12 + 0.22 * k) + ')'; c.beginPath(); c.arc(m.x, m.y, m.r * k, 0, TAU); c.fill(); + c.strokeStyle = 'rgba(255,90,50,0.9)'; c.lineWidth = 2; c.beginPath(); c.arc(m.x, m.y, m.r, 0, TAU); c.stroke(); + } + for (const L of g.lines) { + // upcoming nodes drawn at their real hit radius (11-02: 4 px dots hid an 18 px hazard), and only up to the + // first wall/obstacle, where game.js stops the line + const ca = Math.cos(L.a), sa = Math.sin(L.a); + c.lineWidth = 1.5; + for (let k = L.k + 1; k <= L.n; k++) { + const d = L.start + k * L.gap, x = L.x + ca * d, y = L.y + sa * d; + if (g.solidAt(x, y, 4, false)) break; + const near = k - L.k <= 2; + c.strokeStyle = near ? 'rgba(220,240,255,0.75)' : 'rgba(220,240,255,0.32)'; + c.beginPath(); c.arc(x, y, M.NODE_R, 0, TAU); c.stroke(); + c.fillStyle = near ? 'rgba(200,235,255,0.18)' : 'rgba(200,235,255,0.07)'; c.fill(); + } + } + for (const n of g.nodes) { + const k = n.life / 14; + c.globalAlpha = Math.min(1, k * 1.6); + ell(c, 'rgba(190,230,255,0.35)', n.x, n.y, n.r, n.r); + for (let i = 0; i < 5; i++) { + const a = i * TAU / 5 + n.x * 0.1, sx = n.x + Math.cos(a) * n.r * 0.55, sy = n.y + Math.sin(a) * n.r * 0.55, hgt = 8 + 6 * k; + c.fillStyle = '#2a4a66'; poly(c, [[sx - 5, sy + 2], [sx, sy - hgt - 2], [sx + 5, sy + 2]]); + c.fillStyle = i % 2 ? '#dff4ff' : '#a8dcf6'; poly(c, [[sx - 3, sy], [sx, sy - hgt], [sx + 3, sy]]); + } + c.globalAlpha = 1; + } + if (b.atk === 'charge' && (b.vars.ph === 'aim' || b.vars.ph === 'dash')) { + // telegraph band = the exact swept ram capsule (game.js M.ramBand), centred on the capsule middle and + // starting behind the boss by the capsule's rear extent, so the drawn band always contains the hit area. + // Tracking: faint + dashed edges; locked (last M.RAM_LOCK ticks): bright solid edges; dash: faint trail. + const a = b.vars.a, ca = Math.cos(a), sa = Math.sin(a), h = M.bosses[b.kind].hurt, half = M.ramBand(b.kind, a), cy = b.y + (h[0] + h[1]) / 2; + const back = h[2] + M.RAM_PAD + (h[1] - h[0]) / 2 * Math.abs(sa), locked = b.vars.ph === 'aim' && b.vars.lock, dash = b.vars.ph === 'dash'; + const L = M.ramReach(g) + back; // the band ends where this dash really ends (wall / dash length) + c.save(); c.translate(b.x, cy); c.rotate(a); c.fillStyle = '#ff3a2a'; + c.globalAlpha = dash ? 0.14 : locked ? 0.30 + 0.10 * Math.sin(t * 1.3) : 0.13 + 0.05 * Math.sin(t * 0.6); + c.fillRect(-back, -half, L + back, half * 2); + if (locked) { c.globalAlpha = 0.95; c.fillStyle = '#ffd0c0'; c.fillRect(-back, -half, L + back, 3); c.fillRect(-back, half - 3, L + back, 3); } + else if (!dash) { c.globalAlpha = 0.7; for (let x = -back; x < L; x += 24) { c.fillRect(x, -half, 12, 2); c.fillRect(x, half - 2, 12, 2); } } + c.restore(); + if (!dash) { + c.fillStyle = locked ? 'rgba(255,220,200,0.95)' : 'rgba(255,90,60,0.7)'; + for (let i = 1; i <= 4; i++) { const d = 40 + i * 34 + (t % 12) * 2; if (d > L) break; const x = b.x + ca * d, y = b.y + sa * d; poly(c, [[x + ca * 10, y + sa * 10], [x - sa * 10, y + ca * 10], [x + sa * 10, y - ca * 10]]); } + } + } + if (b.atk === 'pull' && b.vars.on) { + c.strokeStyle = 'rgba(200,120,255,0.55)'; c.lineWidth = 3; + for (let i = 0; i < 3; i++) { const r = 60 + ((300 - (t * 4 + i * 100) % 300)); c.beginPath(); c.arc(b.x, b.y, r, 0, TAU); c.stroke(); } + } + } + + function drawProjectiles(c, g) { + const t = g.t; + for (const o of g.orbs) { + c.fillStyle = 'rgba(110,220,255,0.35)'; c.beginPath(); c.arc(o.x, o.y, o.r + 6, 0, TAU); c.fill(); + ell(c, '#10203a', o.x, o.y, o.r + 2, o.r + 2); ell(c, '#5ad0ff', o.x, o.y, o.r, o.r); ell(c, '#e0faff', o.x - 2, o.y - 2, o.r * 0.45, o.r * 0.45); + } + for (const q of g.turrets) drawShuriken(c, q.x, q.y, q.r, t * 0.2); + for (const q of g.carriers) drawShuriken(c, q.x, q.y, 11, t * 0.4); + for (const ball of g.balls) { + // blast-radius telegraph (11-02): the burst hurts within M.BLAST_R of the ball (body overlap), wider than its glow + c.save(); c.globalAlpha = 0.45 + 0.15 * Math.sin(t * 0.5); c.strokeStyle = '#9ff4ff'; c.lineWidth = 2; c.setLineDash([6, 5]); + c.beginPath(); c.arc(ball.x, ball.y, M.BLAST_R, 0, TAU); c.stroke(); c.restore(); + drawLaserBall(c, ball.x, ball.y, ball.r, t); + } + for (const st of g.stars) { // Sandworm star turret: spinning cross, its four firing lanes drawn faintly + const lanes = st.shots > 0; + if (lanes) { c.save(); c.globalAlpha = 0.18; c.strokeStyle = '#ffd04a'; c.lineWidth = 6; for (let i = 0; i < 4; i++) { const a = st.a0 + i * Math.PI / 2; c.beginPath(); c.moveTo(st.x, st.y); c.lineTo(st.x + Math.cos(a) * 900, st.y + Math.sin(a) * 900); c.stroke(); } c.restore(); } + c.save(); c.translate(st.x, st.y); c.rotate(t * 0.15); + c.fillStyle = '#2a1406'; starPath(c, 0, 0, st.r + 3, st.r * 0.45 + 2, 4, 0); c.fill(); + c.fillStyle = st.kind === 'long' ? '#ffd04a' : '#ff8a2a'; starPath(c, 0, 0, st.r, st.r * 0.45, 4, 0); c.fill(); + c.restore(); + } + for (const s of g.shots) { + const a = Math.atan2(s.vy, s.vx); + capsule(c, s.x, s.y, a, s.crit ? 14 : 11, s.crit ? 7 : 5, s.crit ? ['#4a1a00', '#ff9a2a', '#fff4c0'] : ['#3a2a00', '#ffd23a', '#fff8d0']); + } + for (const q of g.bullets) { + if (q.kind === 'beam') { capsule(c, q.x, q.y, Math.atan2(q.vy, q.vx), 18, 7, ['#0f3a12', '#6dff4a', '#e0ffd0']); continue; } + if (q.kind === 'rail') { capsule(c, q.x, q.y, Math.atan2(q.vy, q.vx), 22, 9, ['#2a0f3a', '#c86aff', '#f6dcff']); continue; } + if (q.kind === 'long') { capsule(c, q.x, q.y, Math.atan2(q.vy, q.vx), 16, 6, ['#3a1a04', '#ffb03a', '#fff0c0']); continue; } + if (q.blast) { // shells / big bullets: the blast radius rides with the projectile (== the explosion's hit radius) + c.save(); c.globalAlpha = q.kind === 'shell' ? 0.7 : 0.35; c.strokeStyle = q.kind === 'shell' ? '#ff8a3a' : '#ff6a4a'; c.lineWidth = q.kind === 'shell' ? 2 : 1; c.setLineDash([5, 4]); + c.beginPath(); c.arc(q.x, q.y, q.blast, 0, TAU); c.stroke(); c.restore(); + } + if (q.kind === 'homing' && q.hover > 0) { c.globalAlpha = 0.5 + 0.5 * Math.sin(t * 0.5); } + const s = bulletSprite(q.kind, Math.round(q.r)); + c.drawImage(s.c, Math.round(q.x - s.m), Math.round(q.y - s.m)); + c.globalAlpha = 1; + } + for (const m of g.meteors) { + const h = m.fall * 5, x = m.x + m.fall * 1.5, y = m.y - h; + c.fillStyle = 'rgba(255,140,40,0.45)'; c.beginPath(); c.moveTo(x - 7, y); c.lineTo(x + 18, y - 40); c.lineTo(x + 7, y); c.fill(); + ell(c, '#2a1206', x, y, 11, 11); ell(c, '#b4552a', x, y, 9, 9); ell(c, '#ffb04a', x - 2, y - 2, 4, 4); + } + for (const q of g.pickups) { + const s = ICONS.orb(), bob = Math.sin((t + q.x) * 0.15) * 2; + c.fillStyle = 'rgba(80,170,255,0.3)'; c.beginPath(); c.arc(q.x, q.y + bob - 6, 8, 0, TAU); c.fill(); + blit(c, s, q.x, q.y + bob + 2, 2); + } + } + + function drawFx(c, g) { + const t = g.t; + for (const f of g.fx) { + const age = t - f.t; + if (f.k === 'spark' && age < 8) { + c.strokeStyle = f.c ? '#bfe8ff' : '#fff2a0'; c.lineWidth = 2; const r = 3 + age * 1.5; + for (let i = 0; i < 4; i++) { const a = i * Math.PI / 2 + Math.PI / 4; c.beginPath(); c.moveTo(f.x + Math.cos(a) * r * 0.4, f.y + Math.sin(a) * r * 0.4); c.lineTo(f.x + Math.cos(a) * r, f.y + Math.sin(a) * r); c.stroke(); } + } else if (f.k === 'boom' && age < 18) { + const k = age / 18; + c.fillStyle = 'rgba(255,240,200,' + (0.6 * (1 - k)) + ')'; c.beginPath(); c.arc(f.x, f.y, f.r * (0.4 + k * 0.6), 0, TAU); c.fill(); + c.strokeStyle = 'rgba(255,140,60,' + (1 - k) + ')'; c.lineWidth = 3; c.beginPath(); c.arc(f.x, f.y, f.r * (0.6 + k * 0.6), 0, TAU); c.stroke(); + } else if (f.k === 'debris' && age < 22) { + for (let i = 0; i < 7; i++) { const a = hash(i, f.x | 0) * TAU, v = 1.5 + hash(f.y | 0, i) * 2.5; c.fillStyle = i % 2 ? '#aa763c' : '#7a4f24'; c.fillRect(f.x + Math.cos(a) * v * age - 2, f.y + Math.sin(a) * v * age + age * age * 0.05 - 2, 4, 3); } + } else if (f.k === 'num' && age < 40) { + c.globalAlpha = Math.min(1, (40 - age) / 14); + txt(c, String(f.v), f.x, f.y - age * 0.8, f.crit ? 19 : 14, f.crit ? '#ffd23a' : '#ffffff', 'center'); + c.globalAlpha = 1; + } else if (f.k === 'pnum' && age < 36) { + c.globalAlpha = Math.min(1, (36 - age) / 12); + txt(c, '-' + f.v, f.x, f.y - age * 0.7, 14, f.s ? '#8aff6a' : '#ff5a5a', 'center'); + c.globalAlpha = 1; + } else if (f.k === 'txt' && age < 44) { + c.globalAlpha = Math.min(1, (44 - age) / 14); + txt(c, f.s, f.x, f.y - age * 0.5, f.big ? 20 : 13, f.big ? '#ff6a4a' : '#d8dde4', 'center'); + c.globalAlpha = 1; + } + } + const b = g.boss; + if (b.state === 'dying') for (let i = 0; i < 3; i++) { + const h1 = hash(Math.floor(t / 6) * 3 + i, 7), h2 = hash(i, Math.floor(t / 6)), x = b.x + (h1 - 0.5) * b.r * 2.4, y = b.y + (h2 - 0.6) * b.r * 2.4, k = (t % 6) / 6; + c.fillStyle = 'rgba(255,220,140,' + (0.8 - k * 0.6) + ')'; c.beginPath(); c.arc(x, y, 6 + k * 10, 0, TAU); c.fill(); + } + } + + function drawReticle(c, g) { + const p = g.player; + if (p.dead > 0 || g.outcome) return; + const x = Math.round(p.aimX), y = Math.round(p.aimY), manual = p.manual > 0; + c.strokeStyle = '#0b0a10'; c.lineWidth = 4; + const arms = () => { c.beginPath(); c.moveTo(x - 9, y); c.lineTo(x - 3, y); c.moveTo(x + 3, y); c.lineTo(x + 9, y); c.moveTo(x, y - 9); c.lineTo(x, y - 3); c.moveTo(x, y + 3); c.lineTo(x, y + 9); c.stroke(); }; + arms(); c.strokeStyle = manual ? '#ffffff' : '#ffd23a'; c.lineWidth = 2; arms(); + } + + // ---------- HUD ---------- + function drawHud(c, g) { + const p = g.player, b = g.boss, t = g.t, w = M.weapons[M.slots[p.slot]]; + panel(c, 6, 4, 190, 60); + const rows = [['hp', p.hp, p.maxHp, '#e84848', '#4a1c22'], ['armor', p.armor, p.maxArmor, '#aab6c4', '#2c3240'], ['energy', p.energy, p.maxEnergy, '#3f9cff', '#1a2848']]; + rows.forEach(([icon, v, max, fg, bg], i) => { + const y = 10 + i * 17; + blit(c, ICONS[icon](), 20, y + 15, 2); + bar(c, 34, y + 2, 120, 12, v, max, fg, bg, v + '/' + max); + }); + if (p.armor < p.maxArmor && p.sinceHit < 180 && p.dead === 0) { c.fillStyle = 'rgba(170,182,196,0.6)'; c.fillRect(160, 30, Math.round(30 * p.sinceHit / 180), 3); } + if (p.poison > 0) { txt(c, 'Poisoned', 160, 28, 11, '#8aff6a'); } + // boss bar + const name = M.cases.find(q => q.id === g.id), bw = 330, bx = 427 - bw / 2; + panel(c, bx - 12, 4, bw + 24, 38); + txt(c, name.name + ' · ' + name.en, bx, 19, 12, '#f2e6c8'); + txt(c, b.enraged ? 'Phase 2: Enraged' : 'Phase 1', bx + bw, 19, 11, b.enraged ? '#ff7a5a' : '#b8c0cc', 'right'); + const pulse = b.enraged ? (Math.floor(t / 10) % 2 ? '#ff5a3a' : '#e83a2a') : '#d83a3a'; + bar(c, bx, 24, bw, 11, b.hp, b.maxHp, pulse, '#3a1414', Math.ceil(b.hp) + ' / ' + b.maxHp); + c.fillStyle = '#f2e6c8'; c.fillRect(bx + bw / 2 - 1, 23, 2, 13); + const status = b.inv ? 'Invulnerable' : b.under ? 'Burrowed: cannot attack' : b.shield > 0 ? 'Poison-pool shield: immune' : b.boom > 0 ? 'Expanding: about to explode' : ''; + if (status) txt(c, status, bx + bw / 2, 51, 11, b.boom > 0 ? '#ff8a8a' : '#d8dde4', 'center'); + // doc (Grand Slime): enraged charge bar fills after 15 hits + if (b.kind === 'grand_slime' && b.enraged && b.boom === 0) { c.fillStyle = '#06050a'; c.fillRect(bx - 1, 37, bw + 2, 4); c.fillStyle = '#ff7a3a'; c.fillRect(bx, 38, Math.round(bw * b.charge / M.SLIME_HITS), 2); } + // timer + public tier + native clock (2026-11-02: every HUD shows the native Hz) + panel(c, 700, 4, 148, 38); + const sec = t / 60, mm = Math.floor(sec / 60), ss = (sec % 60).toFixed(1).padStart(4, '0'), lim = M.maxSeconds; + txt(c, '⏱ ' + mm + ':' + ss, 712, 23, 14, '#f2f2f2'); + txt(c, '/ ' + Math.floor(lim / 60) + ':' + String(lim % 60).padStart(2, '0'), 840, 23, 10, '#a8b0bc', 'right', 'normal'); + const tier = M.tierOf(g.d), TL = { easy: ['Easy EASY', '#7fe08a'], normal: ['Normal NORMAL', '#ffd23a'], hard: ['Hard HARD', '#ff6a4a'] }[tier] || ['Custom d=' + g.d.toFixed(2), '#c8d0dc']; + txt(c, TL[0], 712, 37, 10, TL[1], 'left'); + txt(c, M.hz + 'Hz', 840, 37, 10, '#9fd8ff', 'right'); + // bottom strip: hints, weapon card, skill + txt(c, 'WASD Move · J Attack · K Duplicate Weapon · Q Switch Weapon · Mouse aim', 12, 472, 11, '#c8d0c0', 'left', 'normal'); + panel(c, 560, 452, 234, 27); + const art = WEAPON_ART[M.slots[p.slot]](); + c.drawImage(art.c, 572, 465 - art.h, art.w * 2, art.h * 2); + txt(c, w.name, 624, 470, 12, '#f2e6c8'); + const lowE = w.cost > p.energy; + txt(c, '⚡' + w.cost, 712, 470, 12, lowE ? (Math.floor(t / 15) % 2 ? '#ff5a5a' : '#ffffff') : '#7ac0ff'); + for (let i = 0; i < M.slots.length; i++) { c.fillStyle = i === p.slot ? '#ffd23a' : '#4a4658'; c.fillRect(746 + i * 13, 461, 9, 9); c.strokeStyle = '#06050a'; c.lineWidth = 1; c.strokeRect(746.5 + i * 13, 461.5, 9, 9); } + // skill button (Dual Wield) + const sx = 822, sy = 452, r = 14; + c.fillStyle = '#06050a'; c.beginPath(); c.arc(sx, sy, r + 3, 0, TAU); c.fill(); + c.fillStyle = p.dual > 0 ? '#5a4410' : '#2a3a5a'; c.beginPath(); c.arc(sx, sy, r, 0, TAU); c.fill(); + const pistol = WEAPON_ART.pistol(); + c.save(); c.translate(sx, sy); c.rotate(-0.5); c.drawImage(pistol.c, -11, -9, pistol.w * 2, pistol.h * 2); c.rotate(1.0); c.drawImage(pistol.c, -11, -2, pistol.w * 2, pistol.h * 2); c.restore(); + if (p.dual > 0) { + c.strokeStyle = '#ffd23a'; c.lineWidth = 3; c.beginPath(); c.arc(sx, sy, r + 1, -Math.PI / 2, -Math.PI / 2 + TAU * p.dual / 300); c.stroke(); + txt(c, (p.dual / 60).toFixed(1), sx, sy + 5, 12, '#ffd23a', 'center'); + } else if (p.skillCd > 0) { + c.fillStyle = 'rgba(0,0,0,0.6)'; c.beginPath(); c.moveTo(sx, sy); c.arc(sx, sy, r, -Math.PI / 2, -Math.PI / 2 + TAU * p.skillCd / 600); c.closePath(); c.fill(); + txt(c, Math.ceil(p.skillCd / 60) + '', sx, sy + 5, 13, '#ffffff', 'center'); + } else { c.strokeStyle = 'rgba(140,200,255,' + (0.5 + 0.4 * Math.sin(t * 0.2)) + ')'; c.lineWidth = 2; c.beginPath(); c.arc(sx, sy, r + 1, 0, TAU); c.stroke(); } + txt(c, 'K', sx + 12, sy + 16, 9, '#c8d0dc', 'center'); + } + function drawResult(c, g) { + if (!g.outcome) return; + const map = { win: ['Victory: Boss Defeated', 'BOSS DEFEATED', '#ffd23a'], loss: ['Defeat: Gunner Down', 'GUNNER DOWN', '#ff5a4a'], timeout: ['Time up', 'TIME UP', '#d8dde4'] }[g.outcome]; + const tier = { easy: 'Easy EASY', normal: 'Normal NORMAL', hard: 'Hard HARD' }[M.tierOf(g.d)] || 'd=' + g.d.toFixed(2); + // upper third (11-02): the shared play-page overlay box (_native/shell.js) sits at the stage centre and hid the + // second line of the old centred banner in the result screenshots + c.fillStyle = 'rgba(8,8,14,0.62)'; c.fillRect(0, 112, 854, 86); + c.fillStyle = map[2]; c.fillRect(0, 112, 854, 2); c.fillRect(0, 196, 854, 2); + txt(c, map[0], 427, 154, 30, map[2], 'center'); + txt(c, map[1] + ' · ' + (g.t / 60).toFixed(2) + ' s · ' + tier + ' · Health ' + g.player.hp + '/' + g.player.maxHp, 427, 182, 13, '#e8e8f0', 'center', 'normal'); + } + + // Build every sprite variant once on the first frame (round 3 found an 81 ms hitch at the + // enrage tick when the enraged boss sprite and new bullet kinds were first painted mid-fight). + let warmed = false; + function warm() { + warmed = true; + for (const kind of ['goblin_priest', 'christmas_treant', 'devils_snare', 'grand_slime', 'varkolyn_leader', 'volcanic_sandworm']) { bossSprite(kind, false); bossSprite(kind, true); } + for (const f of [0, 1]) { minionSprite('slime', f); minionSprite('tentacle', f); } + knight(0); knight(1); + for (const k of Object.keys(PROPS)) { if (k === 'crate' || k === 'smile' || k === 'wcrate') { PROPS[k](0); PROPS[k](1); } else PROPS[k](); } + for (const k of Object.keys(WEAPON_ART)) WEAPON_ART[k](); + for (const k of Object.keys(ICONS)) ICONS[k](); + for (const [kind, r] of [['small', 4], ['small', 5], ['star', 7], ['cross', 9], ['bubble', 7], ['bubble', 8], ['homing', 6], ['beam', 5], ['rail', 6], + ['slam', 5], ['diamond', 6], ['petal', 5], ['vorb', 13], ['shell', 11], ['big', 8], ['bouncy', 5]]) bulletSprite(kind, r); + } + + M.draw = function (g, c) { + if (!warmed) warm(); + c.save(); c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; c.globalCompositeOperation = 'source-over'; c.imageSmoothingEnabled = false; + c.drawImage(background(g.kind), 0, 0); + const age = g.t - g.shake.t, sh = age >= 0 && age < 8 ? g.shake.a * (1 - age / 8) : 0; + const ox = Math.round(Math.sin(g.t * 12.9898) * sh), oy = Math.round(Math.cos(g.t * 78.233) * sh); + c.save(); c.translate(ox, oy); + c.beginPath(); c.rect(R.x0 - 12, 20, R.x1 - R.x0 + 24, R.y1 - 12); c.clip(); + drawGround(c, g); + const items = []; + for (const o of g.obstacles) items.push([o.y + o.h, () => { + const cx = o.x + o.w / 2, by = o.y + o.h; + if (o.kind === 'torch') { blit(c, PROPS.torch(), cx, by + 2, 2); const fl = Math.sin(g.t * 0.6 + o.y) * 1.5; ell(c, 'rgba(255,170,60,0.35)', cx, by - 26, 10, 10); ell(c, '#ff8a2a', cx, by - 25 + fl * 0.3, 4, 6); ell(c, '#ffe08a', cx, by - 24, 2, 3); } + else { shadow(c, cx, by - 2, o.w / 2, 6); blit(c, PROPS[o.kind](), cx, by + 2, 2); } + }]); + // crate art: the Grand Slime room's boxes are smiling-face boxes (doc) and two weapon crates + const crateArt = g.kind === 'grand_slime' ? (cr => cr.kind === 'wcrate' ? PROPS.wcrate : PROPS.smile) : () => PROPS.crate; + for (const cr of g.crates) items.push([cr.y + cr.h, () => blit(c, crateArt(cr)(cr.hp < 6 ? 1 : 0), cr.x + cr.w / 2, cr.y + cr.h + 2, 2)]); + items.push([g.player.y + 10, () => drawKnight(c, g)]); + items.push([g.boss.y + g.boss.r * 0.8, () => drawBoss(c, g)]); + for (const m of g.minions) items.push([m.y + 8, () => drawMinions(c, { t: g.t, minions: [m] })]); + items.sort((a, b) => a[0] - b[0]); + for (const it of items) it[1](); + drawSwing(c, g); + drawProjectiles(c, g); + drawFx(c, g); + drawReticle(c, g); + c.restore(); + drawHud(c, g); + drawResult(c, g); + c.restore(); + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/soulknight_remake/game.js b/environments/games/web/games/soulknight_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..920a66fc0c281e257bc0b0e46489b5dc9510e3c3 --- /dev/null +++ b/environments/games/web/games/soulknight_remake/game.js @@ -0,0 +1,1624 @@ +/* Soul Knight (Soul Knight) boss arena, rules knight-arena@6 (@2-@4 = 2026-11-01 rounds 1-3; @5 = 2026-11-02 three + * public tiers easy/normal/hard; @6 = 2026-11-02 expansion to six bosses: Forest 1-5 + Grand Slime (2-5 Knight + * Kingdom), Varkolyn Leader (3-5 Spaceship), Volcanic Sandworm (3-5 Volcano)). + * Pure simulation (Node + browser). + * 60 Hz ticks; 1 tile = 24 px; whole room visible. Values marked "doc" come from the wiki + * (see SOURCES.md); everything else is a labelled approximation (REPRODUCTION_SPEC.md §10). + */ +(function (root) { + 'use strict'; + // Bind the builtins once: under Node's vm sandbox (tests, harness symbolic path) every lookup of a global goes + // through the context interceptor and is ~30x slower (same functions, identical results in the browser). + const Math = root.Math, JSON = root.JSON, Object = root.Object, Set = root.Set, Map = root.Map, WeakMap = root.WeakMap; + const Int16Array = root.Int16Array, Uint8Array = root.Uint8Array, Error = root.Error, Infinity = root.Infinity; + const N = root.NativeBench, TAU = Math.PI * 2, DEG = Math.PI / 180; + const HZ = 60, TILE = 24; + const ROOM = { x0: 55, y0: 64, x1: 799, y1: 448 }; // 31 x 16 tiles + const clamp = (v, a, b) => (v < a ? a : v > b ? b : v); + const hyp = Math.hypot; + + const M = root.SoulKnightGame = { + // maxSeconds 300: the hard tier's target window is 150-240 s (the old 180 s limit would cut it off) + id: 'soulknight_remake', version: 'knight-arena@6', hz: HZ, maxSeconds: 300, dimension: '2d', + renderer: 'canvas-native', title: 'Soul Knight: Dungeon Bosses', pointerLock: true, + // public difficulty = three tiers (2026-11-02); the continuous d underneath follows LADDER below + tiers: { easy: 0.2, normal: 0.5, hard: 0.8 }, + cases: [ + { id: 'soulknight/goblin_priest', name: 'Meteor Caller', en: 'Meteor Caller' }, + { id: 'soulknight/christmas_treant', name: 'Ram Timber', en: 'Ram Timber' }, + { id: 'soulknight/devils_snare', name: 'Spin Bloom', en: 'Spin Bloom' }, + // 11-02 expansion; Chinese names from the zh wiki Boss page (evidence/wiki-cache/zh_Boss.json) + { id: 'soulknight/grand_slime', name: 'Swell Jelly', en: 'Swell Jelly' }, + { id: 'soulknight/varkolyn_leader', name: 'Violet Sweeper', en: 'Violet Sweeper' }, + { id: 'soulknight/volcanic_sandworm', name: 'Burrow Bomber', en: 'Burrow Bomber' } + ], + controls: { + 'W A S D': 'Move in eight directions (6.5 tiles/s; weapon use slows movement while attacking)', + 'J / LMB': 'Hold to attack: sidearm and burst gun fire repeatedly; the blade swings and clears bullets in its arc. At close range, guns automatically use a knife.', + 'mouse dx dy': 'Move the crosshair by relative displacement; auto-aim engages after 2 seconds without mouse input when a boss is visible', + 'K / RMB': 'Duplicate Weapon skill: copy the current weapon for 5 seconds (each copy consumes energy), followed by a 10-second cooldown. Switching weapons ends it immediately.', + 'Q': 'Switch weapons: Basic Sidearm → Burst Gun → Cutting Blade', + 'Space Shift E L R': 'No dodge roll or jump (these keys do nothing)' + }, + room: ROOM, tile: TILE + }; + + // ---- Knight, level 0 (doc: 6 HP / 5 armor / 180 energy / crit 5 / melee 4; Dual Wield 5 s, CD 10 s) + const K = M.knight = { + hp: 6, armor: 5, energy: 180, crit: 5, melee: 4, r: 9, + speed: 6.5 * TILE / HZ, // doc 6.5 tiles/s + regenDelay: 180, regenEvery: 60, // doc: 3 s without damage, then 1/s + iframes: 36, // approx 0.6 s + dual: 300, skillCd: 600, // doc 5 s / 10 s (starts after the skill ends) + copyDelay: 4, swordCopyDelay: 6, // approx "minor time difference" + knifeReach: 22, knifeCd: 60, // doc: once per second in ranged combat + switchLock: 8, poison: 240, poisonEvery: 120 + }; + // doc: damage / energy / crit / rate; approx: bullet speed, spread angle mapping, swing geometry + const WEAPONS = M.weapons = { + pistol: { name: 'Basic Sidearm', en: 'Basic Sidearm', kind: 'gun', damage: 3, cost: 0, crit: 0, spread: 2.5, interval: 18, speed: 8, move: 0.9 }, + rifle: { name: 'Burst Gun', en: 'Burst Gun', kind: 'gun', damage: 3, cost: 1, crit: 10, spread: 5, interval: 10, speed: 9, move: 6 / 6.5 }, + sword: { name: 'Cutting Blade', en: 'Cutting Blade', kind: 'melee', damage: 12, cost: 0, crit: -5, interval: 40, reach: 58, arc: 75, active: 8, move: 5.5 / 6.5 } + }; + const SLOTS = M.slots = ['pistol', 'rifle', 'sword']; + const BOSS = M.bosses = { + // hurt = vertical capsule [top dy, bottom dy, radius] matching the drawn body (round 3: the + // Treant's upper tree and the Priest's head were outside the old circles); r = movement radius + goblin_priest: { hp: 480, r: 20, gap: 72, first: 70, speed: 0.9, hurt: [-22, 6, 17] }, + christmas_treant: { hp: 510, r: 30, gap: 66, first: 60, speed: 0.9, hurt: [-34, 12, 26] }, + devils_snare: { hp: 600, r: 32, gap: 56, first: 60, speed: 0, hurt: [0, 0, 32] }, + // 11-02 expansion. doc HP: Grand Slime 840; Varkolyn Leader 960 (main page rev 132060; the older Tactics rev + // 128082 says 970); Volcanic Sandworm 950 (Tactics rev 129083; the older main page rev 121244 says 960) + // capsules fitted to the drawn bodies (round 2: jelly dome y -37..+19, cloaked alien -57..+9, rearing worm -78..+6) + grand_slime: { hp: 840, r: 26, gap: 70, first: 60, speed: 0.7, hurt: [-12, -6, 25] }, + varkolyn_leader: { hp: 960, r: 16, gap: 62, first: 60, speed: 0.7, hurt: [-44, -4, 13] }, + volcanic_sandworm: { hp: 950, r: 22, gap: 56, first: 50, speed: 0, hurt: [-64, -8, 14] } + }; + + // ---- difficulty ladder (knight-arena@5). Knots at d = 0, easy, normal, hard, 1; piecewise linear. + // Anchored on the original's own difficulty systems (wiki, SOURCES.md): + // easy = Normal mode boss: original cadence, projectile speed and damage + // normal = Champion boss: "attacks more frequently", same attacks and damage + // hard = Badass Mode: always Champion, "+1 damage from all sources" (status effects included), + // "enemy projectile velocity greatly increased", enemies attack more frequently + // hp multiplies the documented HP per boss (for the Forest bosses d = 0 is exactly the documented value; the + // later-floor bosses' documented 840-960 lies inside their easy..hard range). The + // original's own HP scales (Champion x1.25, co-op +50 % per extra player, at most x3.125 for a 4-player + // Champion) cannot give the meeting's 1-minute / 3-minute fights, so hp is calibrated per boss to the + // seconds windows with the standard scripted controller (the Priest walks in the open and is the + // quickest to shoot down; the Treant hides in two crate rings and is immune while charging). + // gap = attack-interval multiplier, shot = projectile speed, move = boss walk / charge / pull speed, + // dmg = extra damage per hit (rounded), chase = how close the walking bosses come to the Knight. + const H = (gp, ct, ds, gs, vl, vs) => ({ goblin_priest: gp, christmas_treant: ct, devils_snare: ds, grand_slime: gs, varkolyn_leader: vl, volcanic_sandworm: vs }); + const LADDER = [ + { d: 0.0, hp: H(1.0, 1.0, 1.0, 0.6, 0.46, 0.35), gap: 1.15, shot: 0.92, move: 0.95, dmg: 0, chase: 0 }, + { d: 0.2, hp: H(1.35, 1.15, 1.1, 0.75, 0.615, 0.43), gap: 1.0, shot: 1.0, move: 1.0, dmg: 0, chase: 0.1 }, // easy + { d: 0.5, hp: H(2.5, 2.15, 2.05, 1.4, 1.1, 0.9), gap: 0.85, shot: 1.1, move: 1.05, dmg: 0, chase: 0.5 }, // normal + { d: 0.8, hp: H(6.0, 5.1, 5.0, 3.2, 2.5, 1.9), gap: 0.72, shot: 1.3, move: 1.12, dmg: 1, chase: 0.9 }, // hard + { d: 1.0, hp: H(7.2, 6.1, 6.0, 3.8, 2.75, 2.3), gap: 0.65, shot: 1.4, move: 1.18, dmg: 1, chase: 1 } + ]; + M.ladder = function (d, kind) { + let i = 0; + while (i < LADDER.length - 2 && d > LADDER[i + 1].d) i++; + const a = LADDER[i], b = LADDER[i + 1], k = clamp((d - a.d) / (b.d - a.d), 0, 1), mix = (x, y) => x * (1 - k) + y * k; // exact at the knots + const out = { d, hp: mix(a.hp[kind], b.hp[kind]) }; + for (const key of ['gap', 'shot', 'move', 'dmg', 'chase']) out[key] = mix(a[key], b[key]); + out.dmg = Math.round(out.dmg); + return out; + }; + M.tierOf = d => ['easy', 'normal', 'hard'].find(t => Math.abs(M.tiers[t] - d) < 1e-9) || null; + + const tileRect = (c, r, w, h, kind, hp) => { + const o = { x: ROOM.x0 + c * TILE, y: ROOM.y0 + r * TILE, w: (w || 1) * TILE, h: (h || 1) * TILE, kind }; + if (hp) o.hp = hp; + return o; + }; + const crate = (c, r) => tileRect(c, r, 1, 1, 'crate', 6); + const LAYOUTS = { + // doc: little cover; tepee with 2 wooden totems at the top; torches at the edges; six crates on the walls + goblin_priest() { + return { + boss: [427, 232], player: [427, 404], + obstacles: [tileRect(14, 0, 3, 2, 'tepee'), tileRect(12, 1, 1, 1, 'totem'), tileRect(18, 1, 1, 1, 'totem'), + { x: 59, y: 160, w: 12, h: 12, kind: 'torch' }, { x: 59, y: 340, w: 12, h: 12, kind: 'torch' }, + { x: 783, y: 160, w: 12, h: 12, kind: 'torch' }, { x: 783, y: 340, w: 12, h: 12, kind: 'torch' }], + crates: [crate(3, 0), crate(27, 0), crate(0, 8), crate(30, 7), crate(8, 15), crate(22, 15)] + }; + }, + // doc: two layers of wooden crates around the boss; two trees in corners + christmas_treant() { + const crates = []; + for (let r = 7 - 3; r <= 7 + 3; r++) for (let c = 15 - 3; c <= 15 + 3; c++) { + const k = Math.max(Math.abs(c - 15), Math.abs(r - 7)); + if (k === 2 || k === 3) crates.push(crate(c, r)); + } + return { + boss: [427, 244], player: [427, 412], + obstacles: [tileRect(1, 12, 2, 2, 'tree'), tileRect(28, 12, 2, 2, 'tree')], crates + }; + }, + // doc: four stone blocks at equidistant positions on all four sides; boxes stacked in the corners + devils_snare() { + const crates = []; + for (const [c, r] of [[0, 0], [1, 0], [0, 1], [30, 0], [29, 0], [30, 1], [0, 15], [1, 15], [0, 14], [30, 15], [29, 15], [30, 14]]) crates.push(crate(c, r)); + return { + boss: [427, 256], player: [331, 436], // entrance off the stone's shadow so the boss is visible at start + // doc: "four stone blocks at equidistant positions": 140 px from the boss on all four sides + obstacles: [{ x: 403, y: 92, w: 48, h: 48, kind: 'stone' }, { x: 403, y: 372, w: 48, h: 48, kind: 'stone' }, + { x: 263, y: 232, w: 48, h: 48, kind: 'stone' }, { x: 543, y: 232, w: 48, h: 48, kind: 'stone' }], + crates + }; + }, + // doc (Grand Slime, Room Layout): 3 Slow Tiles with 2 Boost Tiles beside them in the centre; smiling-face boxes + // around them, 2 weapon crates among the boxes (approx: 2x2-tile pads, boxes as ordinary 6-HP crates) + grand_slime() { + const tiles = [['boost', 9], ['slow', 11], ['slow', 14], ['slow', 17], ['boost', 20]].map(([kind, c]) => tileRect(c, 7, 2, 2, kind)); + const crates = [[8, 5], [8, 10], [22, 5], [22, 10], [12, 5], [18, 5], [12, 10], [18, 10]].map(([c, r]) => crate(c, r)); + crates.push(Object.assign(crate(15, 5), { kind: 'wcrate' }), Object.assign(crate(15, 10), { kind: 'wcrate' })); + return { boss: [427, 150], player: [427, 412], obstacles: [], crates, tiles }; + }, + // doc (Varkolyn Leader, Room): "The room is clear and has no cover at all." + varkolyn_leader() { + return { boss: [427, 196], player: [427, 412], obstacles: [], crates: [] }; + }, + // doc (Volcanic Sandworm, Room): one pillar and 3 layers of crates in each corner (approx: pillar in the centre, + // each corner a 3-2-1 stack) + volcanic_sandworm() { + const crates = []; + for (const [cx, cy, sx, sy] of [[0, 0, 1, 1], [30, 0, -1, 1], [0, 15, 1, -1], [30, 15, -1, -1]]) + for (let i = 0; i < 3; i++) for (let j = 0; j < 3 - i; j++) crates.push(crate(cx + sx * j, cy + sy * i)); + return { boss: [427, 150], player: [427, 412], obstacles: [tileRect(14, 7, 2, 2, 'pillar')], crates }; + } + }; + M.layouts = LAYOUTS; + + const BAG = { grand_slime: 1, varkolyn_leader: 1, volcanic_sandworm: 1 }; + const POOLS = { + goblin_priest: [['meteor', 'orbs', 'turrets', 'stars'], ['meteor', 'orbs', 'turrets', 'stars']], + christmas_treant: [['hold', 'throw', 'waves'], ['charge', 'homing', 'cross', 'line', 'throw', 'waves', 'hold', 'charge']], + // doc (Devil's Snare/Tactics, Strengths): the boss sits in an almost permanent poison pool -> pool weighted x2, 9 s life + devils_snare: [['bubbles', 'rotate', 'beams', 'bubbles', 'rotate', 'beams', 'pool', 'pool'], + ['bubbles', 'rotate', 'beams', 'pool', 'pool', 'corner', 'corner', 'pull', 'rotate']], + // doc: 4 normal attacks; enraged adds the 15-hit explosion (runs beside the pool, see updateBoss) and 5-damage slams + grand_slime: [['slam', 'rings', 'spawn', 'goo', 'slam', 'rings'], ['slam', 'rings', 'spawn', 'goo', 'slam', 'rings', 'goo']], + // doc: 5 attacks; enraged attacks much more frequently, faster laser (gap x0.6 + laser timing) + varkolyn_leader: [['pools', 'tentacles', 'ring', 'laser', 'orb', 'pools', 'ring'], ['pools', 'tentacles', 'ring', 'laser', 'orb', 'pools', 'ring', 'laser']], + // doc: explosive / big spread / dig (+ resurface); enraged digs and resurfaces much faster, continuous dives + volcanic_sandworm: [['explosive', 'spread', 'dig', 'explosive', 'spread', 'dig'], ['explosive', 'spread', 'dig', 'dive', 'explosive', 'spread', 'dive']] + }; + + function rectHit(x, y, r, o) { + const cx = clamp(x, o.x, o.x + o.w), cy = clamp(y, o.y, o.y + o.h); + const dx = x - cx, dy = y - cy; + return dx * dx + dy * dy < r * r; + } + function segRect(ax, ay, bx, by, o) { // Liang-Barsky: does segment a-b cross rect o? + let t0 = 0, t1 = 1; + const dx = bx - ax, dy = by - ay; + const p = [-dx, dx, -dy, dy], q = [ax - o.x, o.x + o.w - ax, ay - o.y, o.y + o.h - ay]; + for (let i = 0; i < 4; i++) { + if (p[i] === 0) { if (q[i] < 0) return false; continue; } + const t = q[i] / p[i]; + if (p[i] < 0) { if (t > t1) return false; if (t > t0) t0 = t; } + else { if (t < t0) return false; if (t < t1) t1 = t; } + } + return t0 <= t1; + } + const angDiff = (a, b) => Math.abs(Math.atan2(Math.sin(a - b), Math.cos(a - b))); + // N.segmentDistance(p, a, b) < R behind a bounding-box reject (only skips segments more than R + 1 px away, so the + // result is identical); expansion round 3: these two hit tests were ~55 % of the scripted look-ahead time + const segNear = (p, a, b, R) => !(p.x < Math.min(a.x, b.x) - R - 1 || p.x > Math.max(a.x, b.x) + R + 1 || + p.y < Math.min(a.y, b.y) - R - 1 || p.y > Math.max(a.y, b.y) + R + 1) && N.segmentDistance(p, a, b) < R; + + class Game { + constructor(id, seed, d) { + const kind = id.split('/')[1]; + if (!LAYOUTS[kind]) throw Error('Unknown case ' + id); + this.id = id; this.kind = kind; this.rng = Game.mixSeed(seed); this.d = d; this.t = 0; + this.outcome = null; this.events = []; + const T = this.tier = M.ladder(d, kind); // knight-arena@5 difficulty ladder (see LADDER) + this.spd = T.shot; // projectile speed multiplier + this.gapMul = T.gap; // attack interval multiplier + this.moveMul = T.move; // boss walk / charge / pull speed multiplier + this.dmgUp = T.dmg; // extra damage per hit (Badass rule: all sources) + const L = LAYOUTS[kind](); + this.obstacles = L.obstacles; this.crates = L.crates; this.tiles = L.tiles || []; + this.player = { + x: L.player[0], y: L.player[1], r: K.r, hp: K.hp, maxHp: K.hp, armor: K.armor, maxArmor: K.armor, + energy: K.energy, maxEnergy: K.energy, inv: 0, sinceHit: 9999, poison: 0, poisonT: 0, + slot: 0, cd: 0, lock: 0, copy: 0, copyW: '', dual: 0, skillCd: 0, knifeCd: 0, + swing: 0, swingA: 0, swingKind: '', aimX: L.boss[0], aimY: L.boss[1], aimA: -Math.PI / 2, manual: 0, + face: 1, lastShot: -99, lastCopy: -99, hurtT: -99, dead: 0, moving: 0, step: 0, tileT: 0, tileK: '' + }; + this.held = []; + const B = BOSS[kind], hp = Math.round(B.hp * T.hp); + this.boss = { + kind, x: L.boss[0], y: L.boss[1], r: B.r, hp, maxHp: hp, enraged: false, state: 'idle', + timer: Math.round(B.first * T.gap), atk: '', at: 0, last: '', vars: {}, vx: 0, vy: 0, face: 1, flash: -99, inv: false, + tx: L.boss[0], ty: L.boss[1], tentacles: [], deadT: 0, seq: 0, phaseT: -99, + tileT: 0, tileK: '', under: false, shield: 0, vuln: 0, wasInPool: false, charge: 0, boom: 0 + }; + this.shots = []; this.bullets = []; this.meteors = []; this.lines = []; this.nodes = []; this.pools = []; + this.orbs = []; this.turrets = []; this.carriers = []; this.balls = []; this.pickups = []; this.fx = []; + this.minions = []; this.booms = []; this.stars = []; this.quakes = []; + this.shake = { t: -99, a: 0 }; + this.stats = { shots: 0, hits: 0, damageDealt: 0, damageTaken: 0, cuts: 0, crits: 0, knife: 0, swings: 0 }; + } + + ev(name) { this.events.push(name); } + health() { return [this.player.hp, this.player.maxHp, this.boss.hp, this.boss.maxHp]; } + rand() { return N.rand(this); } + shakeIt(a) { if (this.t - this.shake.t > 6 || a > this.shake.a) this.shake = { t: this.t, a }; } + + // ---------------- geometry ---------------- + solidAt(x, y, r, withCrates) { + if (x - r < ROOM.x0 || x + r > ROOM.x1 || y - r < ROOM.y0 || y + r > ROOM.y1) return true; + for (const o of this.obstacles) if (rectHit(x, y, r, o)) return true; + if (withCrates) for (const c of this.crates) if (rectHit(x, y, r, c)) return true; + return false; + } + obstacleAt(x, y, r) { + for (const o of this.obstacles) if (rectHit(x, y, r, o)) return o; + return null; + } + crateAt(x, y, r) { + for (const c of this.crates) if (c.hp > 0 && rectHit(x, y, r, c)) return c; + return null; + } + sight(a, b) { + for (const o of this.obstacles) if (o.kind !== 'torch' && segRect(a.x, a.y, b.x, b.y, o)) return false; + for (const c of this.crates) if (c.hp > 0 && segRect(a.x, a.y, b.x, b.y, c)) return false; + return true; + } + capDist(x, y) { // distance from (x, y) to the boss hurt capsule axis + const b = this.boss, h = BOSS[b.kind].hurt; + return hyp(x - b.x, y - clamp(y, b.y + h[0], b.y + h[1])); + } + bossHurt(x, y, r) { return this.capDist(x, y) < BOSS[this.boss.kind].hurt[2] + r; } + bodyBlock(nx, ny, ox, oy, r) { // the boss body is solid for the Knight; moving out is always allowed + const b = this.boss; + if (b.hp <= 0 || b.state === 'dying' || b.under) return false; + const lim = BOSS[b.kind].hurt[2] + r - 4, dn = this.capDist(nx, ny); + return dn < lim && dn < this.capDist(ox, oy); + } + // doc (Status Effects): Slow tile = -50 % speed for 2 s, Boost tile = +20 % for 2 s; a running effect is neither + // refreshed nor replaced by another tile, and Slow blocks Boost; tiles affect enemies too + tileStatus(o) { + if (o.tileT > 0 && --o.tileT === 0) o.tileK = ''; + if (o.tileT > 0) return; + for (const t of this.tiles) if (o.x >= t.x && o.x < t.x + t.w && o.y >= t.y && o.y < t.y + t.h) { o.tileK = t.kind; o.tileT = M.TILE_FX; this.ev(t.kind); return; } + } + speedMul(o, poisoned) { return poisoned || o.tileK === 'slow' ? 0.5 : o.tileK === 'boost' ? 1.2 : 1; } // slows do not stack + canHit() { const b = this.boss; return b.hp > 0 && b.state !== 'dying' && !b.under; } + moveBody(o, dx, dy, smash) { + const r = o.r, crates = !smash, isP = o === this.player; + if (dx && !this.solidAt(o.x + dx, o.y, r, crates) && !(isP && this.bodyBlock(o.x + dx, o.y, o.x, o.y, r))) o.x += dx; + if (dy && !this.solidAt(o.x, o.y + dy, r, crates) && !(isP && this.bodyBlock(o.x, o.y + dy, o.x, o.y, r))) o.y += dy; + if (smash) for (const c of this.crates) if (c.hp > 0 && rectHit(o.x, o.y, r, c)) this.breakCrate(c); + } + damageCrate(c, dmg) { c.hp -= dmg; if (c.hp <= 0) this.breakCrate(c); } + breakCrate(c) { + if (c.hp === -1) return; + c.hp = -1; + this.fx.push({ k: 'debris', x: c.x + c.w / 2, y: c.y + c.h / 2, t: this.t }); + this.ev('crate_break'); + } + + // ---------------- update ---------------- + update(keys, pressed, mouse) { + this.held = [...keys].sort(); + this.updatePlayer(keys, pressed, mouse); + this.updateBoss(); + this.updateShots(); + this.updateBullets(); + this.updateHazards(); + this.updatePickups(); + if (this.crates.some(c => c.hp <= 0)) this.crates = this.crates.filter(c => c.hp > 0); + const keep = this.t - 48; + if (this.fx.length && this.fx[0].t < keep) this.fx = this.fx.filter(f => f.t >= keep); + if (this.fx.length > 90) this.fx = this.fx.slice(-90); + const b = this.boss, p = this.player; + if (!this.outcome && this.t + 1 >= HZ * M.maxSeconds) { + if (b.state === 'dying') this.outcome = 'win'; + else if (p.dead > 0) this.outcome = 'loss'; + } + } + + updatePlayer(keys, pressed, mouse) { + const p = this.player, b = this.boss; + if (p.inv > 0) p.inv--; + if (p.cd > 0) p.cd--; + if (p.lock > 0) p.lock--; + if (p.knifeCd > 0) p.knifeCd--; + if (p.swing > 0) p.swing--; + if (p.dead > 0) { + p.dead--; + if (p.dead === 0 && !this.outcome) this.outcome = 'loss'; + return; + } + p.sinceHit++; + if (p.armor < p.maxArmor && p.sinceHit >= K.regenDelay && (p.sinceHit - K.regenDelay) % K.regenEvery === 0) { + p.armor++; this.ev('armor_regen'); + } + if (p.poison > 0) { + p.poison--; p.poisonT++; + if (p.poisonT % K.poisonEvery === 0) this.applyDamage(1, 'poison'); + if (p.dead > 0) return; + } + // skill: Dual Wield (press) + if ((pressed.has('K') || pressed.has('RMB')) && p.dual === 0 && p.skillCd === 0) { p.dual = K.dual; this.ev('dual_wield'); } + if (p.dual > 0) { + p.dual--; + if (p.dual === 0) { p.skillCd = K.skillCd; this.ev('dual_end'); } + } else if (p.skillCd > 0) p.skillCd--; + // weapon switch (press); doc: switching ends Dual Wield immediately + if (pressed.has('Q')) { + p.slot = (p.slot + 1) % SLOTS.length; p.lock = K.switchLock; p.copy = 0; p.swing = 0; + if (p.dual > 0) { p.dual = 0; p.skillCd = K.skillCd; this.ev('dual_end'); } + this.ev('switch'); + } + // aim: relative mouse reticle, auto-aim fallback + if (mouse[0] || mouse[1]) { + p.aimX = clamp(p.aimX + mouse[0], ROOM.x0, ROOM.x1); p.aimY = clamp(p.aimY + mouse[1], ROOM.y0, ROOM.y1); p.manual = 120; + } else if (p.manual > 0) p.manual--; + else if (b.hp > 0 && this.sight(p, b)) { p.aimX += (b.x - p.aimX) * 0.3; p.aimY += (b.y - p.aimY) * 0.3; } + const ax = p.aimX - p.x, ay = p.aimY - p.y; + if (ax * ax + ay * ay > 16) p.aimA = Math.atan2(ay, ax); + p.face = Math.cos(p.aimA) >= 0 ? 1 : -1; + // movement + const mx = (keys.has('D') ? 1 : 0) - (keys.has('A') ? 1 : 0), my = (keys.has('S') ? 1 : 0) - (keys.has('W') ? 1 : 0); + const attacking = keys.has('J') || keys.has('LMB'); + const wid = SLOTS[p.slot], w = WEAPONS[wid]; + if (this.tiles.length) this.tileStatus(p); + if (mx || my) { + const n = hyp(mx, my), sp = K.speed * (attacking ? w.move : 1) * this.speedMul(p, p.poison > 0); + this.moveBody(p, mx / n * sp, my / n * sp, false); + p.moving = 1; p.step++; + } else p.moving = 0; + // attack + if (attacking && p.cd <= 0 && p.lock <= 0) this.attack(wid, false); + if (p.copy > 0) { + p.copy--; + if (p.copy === 0 && p.dual > 0 && SLOTS[p.slot] === p.copyW) this.attack(p.copyW, true); + } + if (p.swing > 0 && p.swingKind !== 'knife') this.cut(p.swingA, WEAPONS.sword); + } + + attack(wid, copy) { + const p = this.player, b = this.boss, w = WEAPONS[wid]; + const alive = b.hp > 0 && b.state !== 'dying' && !b.under; + if (w.kind === 'gun' && alive && this.capDist(p.x, p.y) - BOSS[b.kind].hurt[2] - p.r < K.knifeReach && (copy || p.knifeCd <= 0)) { + if (!copy) { p.knifeCd = K.knifeCd; p.cd = Math.max(p.cd, 14); if (p.dual > 0) { p.copy = K.copyDelay; p.copyW = wid; } } + const crit = this.rand() * 100 < K.crit; + p.swing = 10; p.swingKind = 'knife'; p.swingA = Math.atan2(b.y - p.y, b.x - p.x); + this.stats.knife++; + this.hitBoss(K.melee * (crit ? 2 : 1), crit); + this.ev('knife'); + return true; + } + if (w.kind === 'gun') { + if (p.energy < w.cost) { if (!copy) { p.cd = 8; this.ev('no_energy'); } return false; } + p.energy -= w.cost; + const crit = this.rand() * 100 < w.crit + K.crit; + const a = p.aimA + (this.rand() * 2 - 1) * w.spread * DEG; + const side = copy ? 7 : 0, c = Math.cos(a), s = Math.sin(a); + this.shots.push({ x: p.x + c * 15 - s * side, y: p.y + 3 + s * 15 + c * side, vx: c * w.speed, vy: s * w.speed, + r: 3, dmg: w.damage * (crit ? 2 : 1), crit, life: 100, w: wid }); + if (copy) p.lastCopy = this.t; else { + p.lastShot = this.t; p.cd = w.interval; + if (p.dual > 0) { p.copy = K.copyDelay; p.copyW = wid; } + } + this.stats.shots++; + this.ev('fire'); + return true; + } + // melee weapon: wide swing (doc), destroys hostile projectiles (doc), damage once per swing + if (!copy) { p.cd = w.interval; if (p.dual > 0) { p.copy = K.swordCopyDelay; p.copyW = wid; } } + p.swing = w.active; p.swingA = p.aimA; p.swingKind = copy ? 'sword2' : 'sword'; + this.stats.swings++; + const crit = this.rand() * 100 < w.crit + K.crit; + const h = BOSS[b.kind].hurt; + if (alive && this.inArc(b.x, b.y + (h[0] + h[1]) / 2, h[2] + (h[1] - h[0]) / 2, p.aimA, w.reach, w.arc)) this.hitBoss(w.damage * (crit ? 2 : 1), crit); + for (const m of this.minions) if (m.hp > 0 && !m.emerge && this.inArc(m.x, m.y, m.r, p.aimA, w.reach, w.arc)) this.hitMinion(m, w.damage * (crit ? 2 : 1)); + for (const cr of this.crates) if (cr.hp > 0 && this.inArc(cr.x + cr.w / 2, cr.y + cr.h / 2, 12, p.aimA, w.reach, w.arc)) this.damageCrate(cr, w.damage); + this.cut(p.aimA, w); + this.ev('swing'); + return true; + } + inArc(x, y, r, a, reach, arc) { + const p = this.player, dx = x - p.x, dy = y - p.y, dist = hyp(dx, dy); + if (dist > reach + r) return false; + if (dist < r + p.r) return true; + return angDiff(Math.atan2(dy, dx), a) <= arc * DEG + Math.asin(Math.min(1, r / dist)); + } + cut(a, w) { + let n = 0; + for (const q of this.bullets) if (!q.dead && q.cut && this.inArc(q.x, q.y, q.r, a, w.reach, w.arc)) { + q.dead = 1; n++; + if (n <= 6) this.fx.push({ k: 'spark', x: q.x, y: q.y, t: this.t, c: 1 }); + } + for (const q of this.turrets) if (!q.dead && this.inArc(q.x, q.y, q.r, a, w.reach, w.arc)) { q.dead = 1; n++; this.fx.push({ k: 'spark', x: q.x, y: q.y, t: this.t, c: 1 }); } + for (const q of this.carriers) if (!q.dead && this.inArc(q.x, q.y, 8, a, w.reach, w.arc)) { q.dead = 1; n++; } + // doc: the Sandworm's star "can be destroyed if a melee weapon is slashed at it"; the Varkolyn orb is a projectile too + for (const q of this.stars) if (!q.dead && this.inArc(q.x, q.y, q.r, a, w.reach, w.arc)) { q.dead = 1; n++; this.fx.push({ k: 'spark', x: q.x, y: q.y, t: this.t, c: 1 }); } + if (n) { + this.bullets = this.bullets.filter(q => !q.dead); + this.turrets = this.turrets.filter(q => !q.dead); + this.carriers = this.carriers.filter(q => !q.dead); + this.stars = this.stars.filter(q => !q.dead); + this.stats.cuts += n; this.ev('cut'); + } + } + + hitBoss(dmg, crit) { + const b = this.boss; + if (b.hp <= 0 || b.state === 'dying' || b.under) return false; + if (b.inv || b.shield > 0) { + if (!this.fx.some(f => f.k === 'txt' && this.t - f.t < 24)) this.fx.push({ k: 'txt', x: b.x, y: b.y - b.r - 10, s: 'Immune', t: this.t }); + return false; + } + const v = Math.min(dmg, b.hp); + b.hp -= v; b.flash = this.t; + this.stats.damageDealt += v; this.stats.hits++; + if (crit) { this.stats.crits++; this.shakeIt(2); } + const j = (this.stats.hits * 37) % 29 - 14; + this.fx.push({ k: 'num', x: b.x + j, y: b.y - b.r - 4, v: dmg, crit: !!crit, t: this.t }); + this.ev(crit ? 'crit' : 'boss_hit'); + // doc (Grand Slime, enraged): after 15 hits the charge bar fills and it explodes on its position + if (b.kind === 'grand_slime' && b.enraged && b.boom === 0 && b.hp > 0 && ++b.charge >= M.SLIME_HITS) { b.charge = 0; b.boom = M.SLIME_SWELL; this.ev('swell'); } + if (b.hp <= 0) this.bossDeath(); + else if (!b.enraged && b.hp < b.maxHp / 2) this.enrage(); + return true; + } + hitMinion(m, dmg) { + if (m.hp <= 0 || m.emerge > 0) return false; + m.hp -= dmg; m.flash = this.t; + if (m.hp <= 0) { + m.dead = 1; this.ev(m.kind + '_down'); + if (m.kind === 'slime') { // doc: after 1 second, 8 projectiles in all directions (2 dmg); approx: drops 1 energy orb + this.booms.push({ kind: 'burst8', x: m.x, y: m.y, t: 60, total: 60 }); + this.dropOrbs(1, m.x, m.y); + } else if (m.kind === 'tentacle') { // doc: leaves purple poison gas when killed + this.pools.push({ x: m.x, y: m.y, r: 34, life: 360, purple: 1, form: 0 }); + } + } + return true; + } + hurt(dmg, src) { + const p = this.player; + if (p.inv > 0 || p.hp <= 0 || p.dead > 0) return false; + this.applyDamage(dmg, src); + p.inv = K.iframes; + return true; + } + applyDamage(dmg, src) { + const p = this.player; + if (p.hp <= 0 || this.boss.state === 'dying') return; + dmg += this.dmgUp; // hard tier, doc (Badass Mode): 1 extra damage from all sources, status effects included + p.sinceHit = 0; p.hurtT = this.t; this.stats.damageTaken += dmg; + if (p.armor >= dmg) { p.armor -= dmg; this.ev(p.armor ? 'armor_hit' : 'armor_break'); } + else { // doc: excess damage goes to health (no Strong Shield at level 0) + const had = p.armor, over = dmg - p.armor; + p.armor = 0; p.hp = Math.max(0, p.hp - over); this.ev(had ? 'armor_break' : 'hurt'); + } + this.fx.push({ k: 'pnum', x: p.x, y: p.y - 22, v: dmg, t: this.t, s: src === 'poison' ? 1 : 0 }); + this.shakeIt(src === 'poison' ? 1 : 3); + if (p.hp <= 0 && !p.dead) { p.dead = 40; p.poison = 0; this.ev('player_down'); } + } + poisonPlayer() { + const p = this.player; + if (p.hp <= 0) return; + if (p.poison === 0) p.poisonT = 0; + p.poison = K.poison; + } + + // ---------------- boss ---------------- + bspeed(v) { return v * this.spd * (this.boss.enraged ? 1.2 : 1); } + aimAt(x, y) { const p = this.player; return Math.atan2(p.y - y, p.x - x); } + bullet(x, y, a, speed, o) { + let s = this.bspeed(speed); + if (o && o.cap) { s = Math.min(s, o.cap); o = Object.assign({}, o); delete o.cap; } + const q = Object.assign({ x, y, vx: Math.cos(a) * s, vy: Math.sin(a) * s, r: 5, dmg: 2, kind: 'small', cut: true, age: 0, life: 600 }, o || {}); + this.bullets.push(q); + return q; + } + ring(x, y, n, a0, speed, o) { for (let i = 0; i < n; i++) this.bullet(x, y, a0 + i * TAU / n, speed, o); } + // the lane is drawn M.LINE_LEAD ticks before its first node (11-02 audit: node 1 used to spawn - and hurt - in the + // tick the line was cast, before any lane was drawn); c is decremented once in the casting tick, hence + 1 + line(x, y, a, n, every, start) { this.lines.push({ x, y, a, k: 0, n, gap: 30, every, c: M.LINE_LEAD + 1, start, dmg: 3 }); } + dropOrbs(n, x, y) { + for (let i = 0; i < n; i++) { + const a = i * TAU / n + this.rand() * 0.5, s = 1.6 + this.rand() * 1.6; + this.pickups.push({ x, y, vx: Math.cos(a) * s, vy: Math.sin(a) * s, age: 0, v: 4 }); + } + } + enrage() { + const b = this.boss; + b.enraged = true; b.phaseT = this.t; + this.dropOrbs(10, b.x, b.y); // doc: 10 energy orbs at half health + this.ev('enrage'); this.shakeIt(4); + this.fx.push({ k: 'txt', x: b.x, y: b.y - b.r - 18, s: 'Enraged!', t: this.t, big: 1 }); + // transform scripts: Treant 7 shockwave lines, Snare opens with 4 tentacles, Grand Slime explodes once (doc); + // the Varkolyn Leader and the Sandworm have no documented transform and keep their current attack + if (b.kind === 'christmas_treant' || b.kind === 'devils_snare' || b.kind === 'grand_slime') { + b.state = 'transform'; b.atk = 'transform'; b.at = 0; b.vars = {}; b.inv = false; + } + } + bossDeath() { + const b = this.boss; + b.hp = 0; b.state = 'dying'; b.deadT = 60; b.inv = false; b.atk = ''; b.under = false; b.shield = 0; b.boom = 0; + this.bullets = []; this.meteors = []; this.lines = []; this.nodes = []; this.pools = []; + this.orbs = []; this.turrets = []; this.carriers = []; this.balls = []; + this.minions = []; this.booms = []; this.stars = []; this.quakes = []; + this.player.poison = 0; + this.dropOrbs(10, b.x, b.y); + this.ev('boss_defeated'); this.shakeIt(6); + this.fx.push({ k: 'boom', x: b.x, y: b.y, r: b.r * 2, t: this.t }); + } + pickAttack() { + const b = this.boss, pool = POOLS[b.kind][b.enraged ? 1 : 0]; + if (BAG[b.kind]) { + // expansion bosses: a shuffled bag - every pool entry once per cycle, no immediate repeat (expansion round 2: i.i.d. + // picks let one seed draw 5 pool attacks in 30 s and another 1, a 12-15 s spread in the easy fight length) + const key = b.enraged ? 1 : 0; + if (!b.bag || b.bagPhase !== key || !b.bag.length) { b.bag = pool.slice(); b.bagPhase = key; } + let i = Math.floor(this.rand() * b.bag.length); + if (b.bag[i] === b.last && b.bag.length > 1) i = (i + 1) % b.bag.length; + return b.bag.splice(i, 1)[0]; + } + let name = b.last; + for (let i = 0; i < 6 && name === b.last; i++) name = pool[Math.floor(this.rand() * pool.length)]; + return name; + } + updateBoss() { + const b = this.boss, p = this.player; + b.vx = 0; b.vy = 0; + if (b.state === 'dying') { + b.deadT--; + if (b.deadT <= 0 && !this.outcome) this.outcome = 'win'; + return; + } + if (b.hp <= 0) return; + b.face = p.x >= b.x ? 1 : -1; + if (b.state === 'idle') { + this.idleMove(); + if (--b.timer <= 0) { + const name = this.pickAttack(); + b.state = 'cast'; b.atk = name; b.at = 0; b.vars = {}; b.last = name; b.seq++; + this.ev('boss_attack'); + } + } else { + const done = ATTACKS[b.kind][b.atk].call(this, b, b.at, b.vars); + b.at++; + if (done && b.state !== 'dying') { + b.state = 'idle'; b.atk = ''; b.vars = {}; b.inv = false; + b.timer = Math.max(12, Math.round(BOSS[b.kind].gap * this.gapMul * (b.enraged ? 0.6 : 1))); + } + } + if (b.tentacles.length && p.dead === 0) for (const t of b.tentacles) if (hyp(p.x - t.x, p.y - t.y) < p.r + t.r) this.hurt(2, 'tentacle'); + if (b.kind === 'grand_slime') this.slimeTick(b, p); + else if (b.kind === 'varkolyn_leader') this.shieldTick(b); + } + slimeTick(b, p) { + // doc: "can deal damage upon contact, especially when enraged" (approx 2 / 3 damage) + if (p.dead === 0 && this.capDist(p.x, p.y) < BOSS[b.kind].hurt[2] + p.r) this.hurt(b.enraged ? 3 : 2, 'contact'); + // doc: explosion on its current position after 15 hits while enraged, and once right after enraging; the swell + // (M.SLIME_SWELL ticks) is drawn as a growing ring with the exact blast radius + if (b.boom > 0 && --b.boom === 0) { + this.fx.push({ k: 'boom', x: b.x, y: b.y, r: M.SLIME_BLAST, t: this.t }); this.shakeIt(6); this.ev('slime_blast'); + if (p.dead === 0 && hyp(p.x - b.x, p.y - b.y) < M.SLIME_BLAST + p.r) this.hurt(5, 'blast'); + for (const c of this.crates) if (c.hp > 0 && rectHit(b.x, b.y, M.SLIME_BLAST, c)) this.breakCrate(c); + } + } + shieldTick(b) { + // doc: invulnerable for several seconds upon entering a purple poison pool, then a brief enforced vulnerability + // (approx 3 s / 2 s); the shield also ends when it leaves the pool (tactics: "wait for the pools to fade or him + // going out of them") + // triggered on entering a pool (doc wording), not while standing in one: round 1 of the expansion found a boss + // parked in a tentacle's death pool cycling 3 s shield / 2 s vulnerability indefinitely + const inPool = this.pools.some(q => q.purple && !(q.form > 0) && hyp(b.x - q.x, b.y - q.y) < q.r), entered = inPool && !b.wasInPool; + b.wasInPool = inPool; + if (b.shield > 0) { if (--b.shield === 0 || !inPool) { b.shield = 0; b.vuln = M.VARK_VULN; this.ev('shield_end'); } } + else if (b.vuln > 0) b.vuln--; + else if (entered && !b.under) { b.shield = M.VARK_SHIELD; this.ev('shield'); } + } + idleMove() { + const b = this.boss, p = this.player; + const ox = b.x, oy = b.y; + if (b.kind === 'goblin_priest') { + if (hyp(b.tx - b.x, b.ty - b.y) < 6) this.newWalkTarget(); + const a = Math.atan2(b.ty - b.y, b.tx - b.x), s = BOSS[b.kind].speed * this.moveMul; + this.moveBody(b, Math.cos(a) * s, Math.sin(a) * s, true); + if (hyp(b.x - ox, b.y - oy) < 0.2) this.newWalkTarget(); + } else if (b.kind === 'christmas_treant' && b.enraged) { + // doc: moves during the enraged phase; approach distance shrinks with the tier's chase value. Without a padded + // line of fire it keeps pursuing along a path around trees/walls (11-02 round 3/4: it stopped 129 px away while + // the Knight stood in the pocket behind a corner tree; the line only grazed the tree, so shots and charges hit + // the tree and the fight stalled for 10-25 s) + const d = hyp(p.x - b.x, p.y - b.y), stop = 170 - 60 * this.tier.chase, s = BOSS[b.kind].speed * this.moveMul; + if (!this.clearLine(b, p, M.FIRE_PAD)) this.navStep(b, s); + else if (d > stop) { const a = Math.atan2(p.y - b.y, p.x - b.x); this.moveBody(b, Math.cos(a) * s, Math.sin(a) * s, true); } + } else if (b.kind === 'grand_slime' && b.boom === 0) { + // walks toward the Knight (walking animation, contact damage); enraged it presses into contact; tiles affect it + this.tileStatus(b); + const d = hyp(p.x - b.x, p.y - b.y), stop = b.enraged ? 60 - 30 * this.tier.chase : 150 - 60 * this.tier.chase; + const s = BOSS[b.kind].speed * this.moveMul * (b.enraged ? 1.2 : 1) * this.speedMul(b, false); + if (d > stop) { const a = Math.atan2(p.y - b.y, p.x - b.x); this.moveBody(b, Math.cos(a) * s, Math.sin(a) * s, true); } + } else if (b.kind === 'varkolyn_leader') { + if (hyp(b.tx - b.x, b.ty - b.y) < 6) this.newWalkTarget(); + const a = Math.atan2(b.ty - b.y, b.tx - b.x), s = BOSS[b.kind].speed * this.moveMul; + this.moveBody(b, Math.cos(a) * s, Math.sin(a) * s, true); + if (hyp(b.x - ox, b.y - oy) < 0.2) this.newWalkTarget(); + } + b.vx = b.x - ox; b.vy = b.y - oy; + } + clearLine(a, b, pad) { // line of fire ignoring crates (the Treant rams them) and torches; pad widens obstacles + const m = pad || 0; + for (const o of this.obstacles) if (o.kind !== 'torch' && segRect(a.x, a.y, b.x, b.y, m ? { x: o.x - m, y: o.y - m, w: o.w + 2 * m, h: o.h + 2 * m } : o)) return false; + return true; + } + navStep(b, s) { // one step down a BFS field toward the nearest standable tile with a padded line of fire + const p = this.player, F = navGrid(this, b), cols = F.cols; + const tile = (x, y) => clamp(Math.floor((y - ROOM.y0) / TILE), 0, F.rows - 1) * cols + clamp(Math.floor((x - ROOM.x0) / TILE), 0, cols - 1); + const dist = navField(this, F, tile(p.x, p.y)), here = tile(b.x, b.y), hx = here % cols, hy = (here - hx) / cols; + let best = -1; + for (let r = 1; r <= 3 && best < 0; r++) for (let Y = hy - r; Y <= hy + r; Y++) for (let X = hx - r; X <= hx + r; X++) { + if (X < 0 || Y < 0 || X >= cols || Y >= F.rows) continue; + const k = Y * cols + X; + if (dist[k] < 0) continue; + if (best < 0 || dist[k] < dist[best] || (dist[k] === dist[best] && hyp(F.pt[k].x - b.x, F.pt[k].y - b.y) < hyp(F.pt[best].x - b.x, F.pt[best].y - b.y))) best = k; + } + // already on a firing tile (the exact line still grazes): close in on the Knight directly + const t = best < 0 || (dist[here] === 0 && dist[best] === 0) ? p : F.pt[best], a = Math.atan2(t.y - b.y, t.x - b.x); + if (hyp(t.x - b.x, t.y - b.y) > 1) this.moveBody(b, Math.cos(a) * s, Math.sin(a) * s, true); + } + newWalkTarget() { // 3 random points; keep the one closest to the tier's preferred distance from the Knight + const b = this.boss, p = this.player, want = b.kind === 'varkolyn_leader' ? 300 - 140 * this.tier.chase : 360 - 200 * this.tier.chase; + let best = null, bd = Infinity; + for (let i = 0; i < 3; i++) { + const x = ROOM.x0 + 110 + this.rand() * (ROOM.x1 - ROOM.x0 - 220), y = ROOM.y0 + 90 + this.rand() * (ROOM.y1 - ROOM.y0 - 200); + const d = Math.abs(hyp(x - p.x, y - p.y) - want); + if (d < bd) { bd = d; best = [x, y]; } + } + b.tx = best[0]; b.ty = best[1]; + } + + // ---------------- projectiles & hazards ---------------- + updateShots() { + const b = this.boss, live = b.hp > 0 && b.state !== 'dying' && !b.under; + for (const s of this.shots) { + const old = { x: s.x, y: s.y }; + s.x += s.vx; s.y += s.vy; s.life--; + let hitM = null; + for (const m of this.minions) if (m.hp > 0 && !m.emerge && segNear(m, old, s, m.r + s.r)) { hitM = m; break; } + if (hitM) { this.hitMinion(hitM, s.dmg); s.dead = 1; this.fx.push({ k: 'spark', x: s.x, y: s.y, t: this.t, c: 0 }); continue; } + if (live && (this.bossHurt(s.x, s.y, s.r) || this.bossHurt((old.x + s.x) / 2, (old.y + s.y) / 2, s.r))) { + this.hitBoss(s.dmg, s.crit); s.dead = 1; + this.fx.push({ k: 'spark', x: s.x, y: s.y, t: this.t, c: 0 }); + continue; + } + if (s.x < ROOM.x0 || s.x > ROOM.x1 || s.y < ROOM.y0 || s.y > ROOM.y1 || this.obstacleAt(s.x, s.y, 1)) { + s.dead = 1; this.fx.push({ k: 'spark', x: clamp(s.x, ROOM.x0, ROOM.x1), y: clamp(s.y, ROOM.y0, ROOM.y1), t: this.t, c: 0 }); + continue; + } + const c = this.crateAt(s.x, s.y, 1); + if (c) { this.damageCrate(c, s.dmg); s.dead = 1; continue; } + if (s.life <= 0) s.dead = 1; + } + this.shots = this.shots.filter(s => !s.dead); + } + updateBullets() { + const p = this.player; + for (const q of this.bullets) { + if (q.split !== undefined) { + if (--q.split <= 0) { + q.dead = 1; + const a0 = this.rand() * TAU; + for (let i = 0; i < 3; i++) this.bullet(q.x, q.y, a0 + i * TAU / 3, 2.6, { r: 4, dmg: 2 }); + continue; + } + } + if (q.kind === 'homing') { + if (q.hover > 0) { + q.hover--; + if (q.hover === 0) { const a = this.aimAt(q.x, q.y), s = this.bspeed(2.6); q.vx = Math.cos(a) * s; q.vy = Math.sin(a) * s; } + } else { + const a = Math.atan2(q.vy, q.vx), want = this.aimAt(q.x, q.y); + let d = Math.atan2(Math.sin(want - a), Math.cos(want - a)); + d = clamp(d, -0.035, 0.035); + const s = hyp(q.vx, q.vy); + q.vx = Math.cos(a + d) * s; q.vy = Math.sin(a + d) * s; + } + } + if (q.trail !== undefined && --q.trail <= 0) { + q.trail = 5; + const a = Math.atan2(q.vy, q.vx), life = this.boss.enraged ? 360 : 240; + this.bullet(q.x, q.y, a + Math.PI / 2, 0.8, { kind: 'bubble', r: 7, dmg: 3, life }); + this.bullet(q.x, q.y, a - Math.PI / 2, 0.8, { kind: 'bubble', r: 7, dmg: 3, life }); + } + if (q.drag) { // decelerating projectile (Sandworm big bullets) + const s = hyp(q.vx, q.vy), ns = Math.max(q.minSpeed || 0, s * q.drag); + if (s > 0) { q.vx *= ns / s; q.vy *= ns / s; } + } + if (q.kind === 'vorb' && q.age > 0 && q.age % q.emitEvery === 0) { // rotating, 4-way spiral emitter + q.spin += 0.35; + for (let i = 0; i < 4; i++) this.bullet(q.x, q.y, q.spin + i * Math.PI / 2, 1.9, { r: 4, dmg: 3 }); + } + const old = { x: q.x, y: q.y }; + q.x += q.vx; q.y += q.vy; q.age++; + if (q.age >= q.life) { q.dead = 1; continue; } + if (q.hover > 0) continue; // still forming above the Treant's star: not yet a ground projectile + if (q.stop !== undefined) { // travels a set distance, then lingers in place (Grand Slime rings / goo) + q.dist = (q.dist || 0) + hyp(q.x - old.x, q.y - old.y); + if (q.dist >= q.stop) { q.vx = 0; q.vy = 0; q.life = q.age + q.linger; delete q.stop; } + } + if (q.x < ROOM.x0 || q.x > ROOM.x1 || q.y < ROOM.y0 || q.y > ROOM.y1 || this.obstacleAt(q.x, q.y, Math.min(q.r, 3))) { + if (q.bounce > 0) { // bouncy bullets reflect off walls and obstacles + const sx = this.solidAt(q.x, old.y, Math.min(q.r, 3), false), sy = this.solidAt(old.x, q.y, Math.min(q.r, 3), false); + if (sx || !sy) q.vx = -q.vx; + if (sy || !sx) q.vy = -q.vy; + q.x = old.x + q.vx; q.y = old.y + q.vy; q.bounce--; + if (!this.solidAt(q.x, q.y, Math.min(q.r, 3), false)) continue; + } + q.dead = 1; + if (q.blast) this.blastAt(clamp(old.x, ROOM.x0, ROOM.x1), clamp(old.y, ROOM.y0, ROOM.y1), q.blast, q.dmg, 'bigblast'); + continue; + } + const c = this.crateAt(q.x, q.y, Math.min(q.r, 3)); + if (c) { this.damageCrate(c, q.dmg); q.dead = 1; if (q.blast) this.blastAt(q.x, q.y, q.blast, q.dmg, 'bigblast'); continue; } + if (p.dead === 0 && p.hp > 0 && segNear(p, old, q, p.r + q.r * 0.8)) { + if (q.blast) { q.dead = 1; this.blastAt(q.x, q.y, q.blast, q.dmg, 'bigblast'); continue; } // explodes on the Knight + if (this.hurt(q.dmg, 'bullet')) { q.dead = 1; if (q.poison) this.poisonPlayer(); } + } + } + if (this.bullets.length) this.bullets = this.bullets.filter(q => !q.dead); + } + blastAt(x, y, r, dmg, src) { // circular blast: the radius drawn around the projectile in flight is exactly r + const p = this.player; + this.fx.push({ k: 'boom', x, y, r, t: this.t }); this.shakeIt(r > 40 ? 4 : 2); + if (p.dead === 0 && p.hp > 0 && hyp(p.x - x, p.y - y) < r + p.r) this.hurt(dmg, src); + for (const c of this.crates) if (c.hp > 0 && rectHit(x, y, r, c)) this.breakCrate(c); + } + quake(x, y) { this.quakes.push({ x, y, r0: 16, r1: M.QUAKE_R, age: 0, total: 15, rc: 16, dmg: 4, hit: 0 }); this.shakeIt(4); } + updateHazards() { + const p = this.player, b = this.boss, alive = p.dead === 0 && p.hp > 0; + for (const m of this.meteors) { + if (--m.fall <= 0) { + m.dead = 1; + this.fx.push({ k: 'boom', x: m.x, y: m.y, r: m.r, t: this.t }); + this.shakeIt(2); + if (alive && hyp(p.x - m.x, p.y - m.y) < m.r + p.r) this.hurt(m.dmg, 'meteor'); + for (const c of this.crates) if (c.hp > 0 && rectHit(m.x, m.y, m.r, c)) this.breakCrate(c); + } + } + if (this.meteors.length) this.meteors = this.meteors.filter(m => !m.dead); + for (const o of this.orbs) { + o.a += o.w; o.x = b.x + Math.cos(o.a) * o.rad; o.y = b.y + Math.sin(o.a) * o.rad; + if (--o.life <= 0) o.dead = 1; + else if (alive && hyp(p.x - o.x, p.y - o.y) < p.r + o.r) this.hurt(o.dmg, 'orb'); + } + if (this.orbs.length) this.orbs = this.orbs.filter(o => !o.dead); + for (const c of this.carriers) { + c.x += c.vx; c.y += c.vy; + // doc: "fires a projectile which leaves a line of turrets" - the shuriken itself hits like a projectile + // (11-02 audit: it used to pass through the Knight and drop a turret on him, a 1-tick-warning contact hit) + if (alive && hyp(p.x - c.x, p.y - c.y) < p.r + M.CARRIER_R && this.hurt(2, 'carrier')) { c.dead = 1; continue; } + if (--c.drop <= 0 && c.n < 6) { this.turrets.push({ x: c.x, y: c.y, a: c.a, fire: 26, life: 240, r: 8 }); c.n++; c.drop = 14; } + if (c.n >= 6 || this.solidAt(c.x, c.y, 6, false)) c.dead = 1; + } + if (this.carriers.length) this.carriers = this.carriers.filter(c => !c.dead); + for (const t of this.turrets) { + if (--t.life <= 0) { t.dead = 1; continue; } + if (--t.fire <= 0) { + t.fire = 26; + this.bullet(t.x, t.y, t.a + Math.PI / 2, 2.4, { r: 4 }); + this.bullet(t.x, t.y, t.a - Math.PI / 2, 2.4, { r: 4 }); + } + if (alive && hyp(p.x - t.x, p.y - t.y) < p.r + t.r) this.hurt(2, 'turret'); + } + if (this.turrets.length) this.turrets = this.turrets.filter(t => !t.dead); + for (const ball of this.balls) { + ball.x += ball.vx; ball.y += ball.vy; ball.th += 0.4; + if (--ball.emit <= 0) { ball.emit = 10; this.ring(ball.x, ball.y, 6, ball.th, 2.2, { r: 4 }); } + for (const c of this.crates) if (c.hp > 0 && rectHit(ball.x, ball.y, ball.r, c)) this.breakCrate(c); + const hitP = alive && hyp(p.x - ball.x, p.y - ball.y) < p.r + ball.r; + if (hitP || --ball.life <= 0 || this.solidAt(ball.x, ball.y, ball.r * 0.6, false)) { + ball.dead = 1; + this.ring(ball.x, ball.y, 14, ball.th, 2.4, { r: 5 }); + this.fx.push({ k: 'boom', x: ball.x, y: ball.y, r: M.BLAST_R, t: this.t }); + this.shakeIt(3); + if (alive && hyp(p.x - ball.x, p.y - ball.y) < M.BLAST_R + p.r) this.hurt(4, 'laser_ball'); + for (const c of this.crates) if (c.hp > 0 && rectHit(ball.x, ball.y, M.BLAST_R, c)) this.breakCrate(c); + } + } + if (this.balls.length) this.balls = this.balls.filter(x => !x.dead); + for (const L of this.lines) { + if (--L.c > 0) continue; + L.c = L.every; L.k++; + const dist = L.start + L.k * L.gap, x = L.x + Math.cos(L.a) * dist, y = L.y + Math.sin(L.a) * dist; + if (L.k > L.n || this.solidAt(x, y, 4, false)) { L.dead = 1; continue; } + this.nodes.push({ x, y, r: M.NODE_R, life: 14, dmg: L.dmg }); + for (const c of this.crates) if (c.hp > 0 && rectHit(x, y, M.NODE_R, c)) this.breakCrate(c); + } + if (this.lines.length) this.lines = this.lines.filter(L => !L.dead); + for (const n of this.nodes) { + if (--n.life <= 0) { n.dead = 1; continue; } + if (alive && n.life > 2 && hyp(p.x - n.x, p.y - n.y) < p.r + n.r) this.hurt(n.dmg, 'shockwave'); + } + if (this.nodes.length) this.nodes = this.nodes.filter(n => !n.dead); + for (const pool of this.pools) { + if (--pool.life <= 0) { pool.dead = 1; continue; } + if (pool.form > 0) { pool.form--; continue; } // still forming (drawn as a dashed ring): harmless + // green and purple pools both poison (doc: purple pools "slow down the player and deal constant damage"; the + // Poison Buff counters them) + if (alive && hyp(p.x - pool.x, p.y - pool.y) < pool.r) this.poisonPlayer(); + } + if (this.pools.length) this.pools = this.pools.filter(x => !x.dead); + this.updateExpansion(p, b, alive); + } + updateExpansion(p, b, alive) { + // delayed bursts (dead slimes: doc "after 1 second, 8 projectiles in all directions, 2 damage") + for (const e of this.booms) { + if (--e.t > 0) continue; + e.dead = 1; + if (e.kind === 'burst8') this.ring(e.x, e.y, 8, this.rand() * TAU, 2.2, { r: 4, dmg: 2 }); + } + if (this.booms.length) this.booms = this.booms.filter(e => !e.dead); + // Sandworm stars: fire long bullets in a cross (diagonal when enraged), destroyable by melee + for (const st of this.stars) { + if (--st.life <= 0) { st.dead = 1; continue; } + if (--st.fire <= 0 && st.shots > 0) { + st.fire = st.every; st.shots--; st.k = (st.k || 0) + 1; + this.bullet(st.x, st.y, st.a0 + (st.k % 4) * Math.PI / 2, 2.6, { kind: 'long', r: 4, dmg: 3 }); + } + if (st.shots <= 0 && st.fire <= 0) st.dead = 1; + } + if (this.stars.length) this.stars = this.stars.filter(s => !s.dead); + // burrow / surface shockwave rings (doc: 4 damage); the ring grows to M.QUAKE_R and hits once + for (const q of this.quakes) { + q.age++; + q.rc = q.r0 + (q.r1 - q.r0) * Math.min(1, q.age / q.total); + // round 2: hits anywhere inside the growing disc (drawn filled), so the dashed warning ring = the final hit area + if (!q.hit && alive && q.age <= q.total && hyp(p.x - q.x, p.y - q.y) < q.rc + p.r && q.age > 2) { q.hit = 1; this.hurt(q.dmg, 'quake'); } + if (q.age >= q.total + 6) q.dead = 1; + } + if (this.quakes.length) this.quakes = this.quakes.filter(q => !q.dead); + // minions: slimes walk at the Knight and hurt on contact; tentacles stand still and fire rings + for (const m of this.minions) { + if (m.emerge > 0) { m.emerge--; continue; } + if (m.kind === 'slime') { + const a = Math.atan2(p.y - m.y, p.x - m.x), s = M.SLIME_SPEED * this.moveMul; + this.moveBody(m, Math.cos(a) * s, Math.sin(a) * s, false); + if (m.cd > 0) m.cd--; + else if (alive && hyp(p.x - m.x, p.y - m.y) < p.r + m.r) { m.cd = 30; this.hurt(2, 'slime'); } + } else if (--m.fire <= 0) { + m.fire = Math.round(M.TENTACLE_EVERY * this.gapMul); + // doc: round bullets in all directions, 3 dmg; tactics: "their bullets are quite easily avoidable" -> slow + this.ring(m.x, m.y, 8, this.rand() * TAU, 1.5, { r: 4, dmg: 3 }); + } + } + if (this.minions.some(m => m.dead)) this.minions = this.minions.filter(m => !m.dead); + } + updatePickups() { + const p = this.player; + for (const q of this.pickups) { + q.age++; + if (q.age < 24) { q.x += q.vx; q.y += q.vy; q.vx *= 0.9; q.vy *= 0.9; } + else if (p.dead === 0 && (hyp(p.x - q.x, p.y - q.y) < 90 || q.age > 150)) { + const a = Math.atan2(p.y - q.y, p.x - q.x); q.x += Math.cos(a) * 5; q.y += Math.sin(a) * 5; + } + q.x = clamp(q.x, ROOM.x0 + 6, ROOM.x1 - 6); q.y = clamp(q.y, ROOM.y0 + 6, ROOM.y1 - 6); + if (p.dead === 0 && hyp(p.x - q.x, p.y - q.y) < p.r + 7) { + q.dead = 1; p.energy = Math.min(p.maxEnergy, p.energy + q.v); this.ev('energy'); + } + } + if (this.pickups.length) this.pickups = this.pickups.filter(q => !q.dead); + } + } + + // walkable tiles for a boss body (walls/obstacles only: crates are rammed through); static per layout, so cached + const NAV8 = [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [1, -1], [-1, 1], [-1, -1]], NAV = {}; + function navGrid(g, b) { + const key = g.kind + ':' + b.r; + if (NAV[key]) return NAV[key]; + const cols = (ROOM.x1 - ROOM.x0) / TILE, rows = (ROOM.y1 - ROOM.y0) / TILE, open = new Uint8Array(cols * rows), pt = []; + for (let i = 0; i < cols * rows; i++) { + const x = ROOM.x0 + TILE / 2 + (i % cols) * TILE, y = ROOM.y0 + TILE / 2 + Math.floor(i / cols) * TILE; + pt.push({ x, y }); open[i] = g.solidAt(x, y, b.r, false) ? 0 : 1; + } + return (NAV[key] = { cols, rows, open, pt, fields: new Map() }); + } + // BFS distance field to the standable tiles whose padded line (FIRE_PAD + 6, a margin over the movement trigger) reaches + // the centre of the Knight's tile. A pure function of (layout, body radius, Knight tile): the cache can never make a + // replay depend on which states were visited before. + function navField(g, F, goal) { + let dist = F.fields.get(goal); + if (dist) return dist; + const cols = F.cols, n = F.open.length, queue = [], gp = F.pt[goal]; + dist = new Int16Array(n).fill(-1); + for (let k = 0; k < n; k++) if (F.open[k] && g.clearLine(F.pt[k], gp, M.FIRE_PAD + 6)) { dist[k] = 0; queue.push(k); } + for (let q = 0; q < queue.length; q++) { + const k = queue[q], x = k % cols, y = (k - x) / cols; + for (const [dx, dy] of NAV8) { + const X = x + dx, Y = y + dy, m = Y * cols + X; + if (X < 0 || Y < 0 || X >= cols || Y >= F.rows || !F.open[m] || dist[m] >= 0) continue; + if (dx && dy && (!F.open[y * cols + X] || !F.open[Y * cols + x])) continue; + dist[m] = dist[k] + 1; queue.push(m); + } + } + F.fields.set(goal, dist); + return dist; + } + + // ---------------- boss attack scripts: fn(b, t, vars) -> done ---------------- + const ATTACKS = M.attacks = { + goblin_priest: { + meteor(b, t, v) { // doc: 3 meteors around the target, 4 when enraged + const n = b.enraged ? 4 : 3, p = this.player; + if (t >= 10 && (t - 10) % 20 === 0 && (v.n | 0) < n) { + v.n = (v.n | 0) + 1; + const x = clamp(p.x + (this.rand() * 2 - 1) * 32, ROOM.x0 + 20, ROOM.x1 - 20), y = clamp(p.y + (this.rand() * 2 - 1) * 32, ROOM.y0 + 20, ROOM.y1 - 20); + this.meteors.push({ x, y, r: 36, fall: 54, total: 54, dmg: 4 }); + this.ev('meteor'); + } + return t >= 10 + 20 * n + 10; + }, + orbs(b, t) { // doc: 2 orbs circling, 4 damage, stackable + if (t === 20) { const a = this.rand() * TAU; for (let i = 0; i < 2; i++) this.orbs.push({ a: a + i * Math.PI, rad: 54, w: 0.07 * this.spd, life: 300, r: 9, dmg: 4, x: b.x, y: b.y }); } + return t >= 40; + }, + turrets(b, t) { // doc: projectile leaving a line of turrets firing perpendicular + if (t === 24) { const a = this.aimAt(b.x, b.y), s = 3.2 * this.spd; this.carriers.push({ x: b.x, y: b.y, vx: Math.cos(a) * s, vy: Math.sin(a) * s, a, drop: 10, n: 0 }); } + return t >= 40; + }, + stars(b, t) { // doc: one wave of 6 stars, each releasing 3 smaller bullets + if (t === 20) this.ring(b.x, b.y, 6, this.aimAt(b.x, b.y), 2.2, { kind: 'star', r: 7, dmg: 3, split: 40 }); + return t >= 40; + } + }, + christmas_treant: { + hold(b, t, v) { // doc: holds a giant laser ball spewing bullets in all directions + if (t >= 20 && t < 170 && (t - 20) % 8 === 0) { + v.th = (v.th || this.rand() * TAU) + 0.33; + for (let i = 0; i < 3; i++) this.bullet(b.x, b.y - 48, v.th + i * TAU / 3, 2.4, { r: 4 }); + } + return t >= 190; + }, + throw(b, t) { // doc: fires the ball at the player, emitting bullets, explodes on impact + if (t === 30) { + const a = this.aimAt(b.x, b.y - 48), s = 2.0 * this.spd; // leaves from the held position (drawn at y-48) + this.balls.push({ x: b.x, y: b.y - 48, vx: Math.cos(a) * s, vy: Math.sin(a) * s, r: 16, life: 240, emit: 10, th: 0 }); + this.ev('laser_ball'); + } + return t >= 50; + }, + waves(b, t) { // doc: lines of shockwaves in three directions + if (t === 20 || t === 50) { const a = this.aimAt(b.x, b.y); for (const d of [-35, 0, 35]) this.line(b.x, b.y + 10, a + d * DEG, 9, 6, b.r); this.ev('shockwave'); } + return t >= 90; + }, + transform(b, t) { // doc: upon starting the enraged phase, shockwaves in 7 lines + if (t === 10) { const a = this.aimAt(b.x, b.y); for (let i = 0; i < 7; i++) this.line(b.x, b.y + 10, a + i * TAU / 7, 12, 5, b.r); this.ev('shockwave'); } + return t >= 40; + }, + charge(b, t, v) { // doc: charges and rams, through crates, no damage taken while charging + const p = this.player; + // telegraph: the band tracks the Knight, then locks for M.RAM_LOCK ticks before the dash (round 1 of + // 11-02: a 10-tick lock left too little time to leave the band once dashes got faster) + if (t === 0) { v.n = 0; v.ph = 'aim'; v.c = 36; v.a = this.aimAt(b.x, b.y); } + if (v.ph === 'aim') { + v.lock = v.c <= M.RAM_LOCK; + if (!v.lock) v.a = this.aimAt(b.x, b.y); + if (--v.c <= 0) { v.ph = 'dash'; v.c = M.RAM_TICKS; v.lock = false; b.inv = true; this.ev('charge'); } + } else if (v.ph === 'dash') { + // the dash only ever moves along the locked line, so the swept ram area stays inside the drawn band: + // a step that would enter a wall/obstacle ends the dash in place (11-02: the old axis-by-axis move let + // a 45-degree dash slide along the wall, outside the telegraph). Crates are rammed through (doc). + const s = 9 * this.moveMul, nx = b.x + Math.cos(v.a) * s, ny = b.y + Math.sin(v.a) * s; + const crash = this.solidAt(nx, ny, b.r, false); + if (!crash) { + b.vx = nx - b.x; b.vy = ny - b.y; b.x = nx; b.y = ny; + for (const c of this.crates) if (c.hp > 0 && rectHit(b.x, b.y, b.r, c)) this.breakCrate(c); + } + // doc: ram area ~ the (larger) charging sprite -> hurt capsule + RAM_PAD (same band drawn as the telegraph) + if (p.dead === 0 && this.capDist(p.x, p.y) < BOSS[b.kind].hurt[2] + M.RAM_PAD + p.r) this.hurt(4, 'charge'); + if (--v.c <= 0 || crash) { v.ph = 'rest'; v.c = 20; b.inv = false; this.shakeIt(3); } + } else if (--v.c <= 0) { + v.n++; + if (v.n >= 3) return true; + v.ph = 'aim'; v.c = 30; + } + return false; + }, + homing(b, t) { // doc: 5 homing bullets from the star, moving after a short delay + if (t === 20) for (let i = 0; i < 5; i++) this.bullets.push({ x: b.x + (i - 2) * 16, y: b.y - 54 + Math.abs(i - 2) * 6, vx: 0, vy: 0, r: 6, dmg: 3, kind: 'homing', cut: true, age: 0, life: 230, hover: 40 }); + return t >= 40; + }, + cross(b, t, v) { // doc: big cross-shaped bullets in every direction + if (t === 20) { v.a = this.rand() * TAU; this.ring(b.x, b.y, 12, v.a, 2.0, { kind: 'cross', r: 9, dmg: 3 }); } + if (t === 45) this.ring(b.x, b.y, 12, v.a + 15 * DEG, 2.0, { kind: 'cross', r: 9, dmg: 3 }); + return t >= 60; + }, + line(b, t) { // doc: a line of shockwaves (like King Snow Ape) + if (t === 20) { this.line(b.x, b.y + 10, this.aimAt(b.x, b.y), 14, 4, b.r); this.ev('shockwave'); } + return t >= 50; + } + }, + devils_snare: { + bubbles(b, t) { // doc: 18 slow bubbles, vanish after 4 s (travel further when enraged) + if (t === 20) this.ring(b.x, b.y, 18, this.rand() * TAU, 1.0, { kind: 'bubble', r: 8, dmg: 3, life: b.enraged ? 360 : 240 }); + return t >= 40; + }, + rotate(b, t, v) { // doc: bullets from 4 points in 4 directions, rotating, slower than the player + if (t === 0) { v.a0 = this.rand() * TAU; v.dir = this.rand() < 0.5 ? 1 : -1; } + if (t >= 10 && t < 190 && (t - 10) % 6 === 0) { + for (let i = 0; i < 4; i++) { + const a = v.a0 + v.dir * 0.025 * t + i * Math.PI / 2; + // doc: these bullets are slower than the player -> capped at 0.9 x Knight speed at every difficulty + this.bullet(b.x + Math.cos(a) * 26, b.y + Math.sin(a) * 26, a, 2.0, { r: 5, cap: 0.9 * K.speed }); + } + } + if (b.enraged && t >= 10 && t < 190 && (t - 10) % 60 === 30) this.beamVolley(b, this.rand() * TAU); // doc: poison during rotation + return t >= 200; + }, + beams(b, t, v) { // doc: beam-like green bullets all around, cause poison + if (t === 20) { v.a = this.rand() * TAU; this.beamVolley(b, v.a); } + if (t === 40) this.beamVolley(b, v.a + 15 * DEG); + return t >= 55; + }, + pool(b, t) { // doc: poison pool on itself, no self-damage + if (t === 15) { this.pools = this.pools.filter(q => q.x !== b.x || q.y !== b.y); this.pools.push({ x: b.x, y: b.y, r: 64, life: 540 }); } + return t >= 30; + }, + transform(b, t) { // doc: flower unfolds, 4 tentacles spawn + if (t === 20) b.tentacles = [0, 1, 2, 3].map(i => ({ x: b.x + Math.cos(Math.PI / 4 + i * Math.PI / 2) * 52, y: b.y + Math.sin(Math.PI / 4 + i * Math.PI / 2) * 52, r: 14 })); + return t >= 45; + }, + corner(b, t) { // doc: 4 fast bullets toward the corners leaving spreading bubble trails + if (t === 20) { + const corners = [[ROOM.x0, ROOM.y0], [ROOM.x1, ROOM.y0], [ROOM.x0, ROOM.y1], [ROOM.x1, ROOM.y1]]; + for (const [cx, cy] of corners) { + const src = b.tentacles.length ? b.tentacles.reduce((m, q) => (hyp(q.x - cx, q.y - cy) < hyp(m.x - cx, m.y - cy) ? q : m)) : b; + this.bullet(src.x, src.y, Math.atan2(cy - src.y, cx - src.x), 6, { kind: 'rail', r: 6, dmg: 3, trail: 5 }); + } + } + return t >= 40; + }, + pull(b, t, v) { // doc: wave that pulls the player toward itself; walls hamper it; no damage + const p = this.player; + v.on = t >= 10 && t < 100; + if (v.on && p.dead === 0 && this.sight(p, b)) { + const a = Math.atan2(b.y - p.y, b.x - p.x), s = 1.4 * this.moveMul; // < Knight speed at every tier + if (hyp(b.x - p.x, b.y - p.y) > b.r + p.r + 4) this.moveBody(p, Math.cos(a) * s, Math.sin(a) * s, false); + } + return t >= 110; + } + }, + grand_slime: { + // doc: "Slams the ground, releasing clusters of red bullets in random directions, at random speeds; 3 damage" + // (5.5.0+ version; diamond bullets 5 damage when enraged); two slams (pre-5.5.0 text: "slams the ground twice") + slam(b, t, v) { + if (t === 24 || t === 54) { + const n = b.enraged ? 14 : 12; + for (let i = 0; i < n; i++) this.bullet(b.x, b.y + 6, this.rand() * TAU, 1.4 + this.rand() * 1.8, + b.enraged ? { kind: 'diamond', r: 6, dmg: 5 } : { kind: 'slam', r: 5, dmg: 3 }); + this.quakeFx(b.x, b.y + 14); this.ev('slam'); + } + return t >= 74; + }, + // doc: "4 rings of bullets in quick succession; they travel 10 tiles then linger, gradually forming a flower; 2 dmg". + // Approx: each bullet stops at 10 tiles x a 5-petal profile, so the lingering bullets draw a flower whose gaps + // between the petals stay passable (a uniform circle would be a closed cage). + rings(b, t, v) { + if (t === 0) v.a = this.rand() * TAU; + if (t >= 16 && t < 16 + 4 * 10 && (t - 16) % 10 === 0) { + const k = (t - 16) / 10; + for (let i = 0; i < 12; i++) { + const a = v.a + i * TAU / 12 + k * TAU / 48, rel = a - v.a; + const stop = 10 * TILE * (0.45 + 0.55 * Math.abs(Math.cos(2.5 * rel))) - k * 14; + this.bullet(b.x, b.y, a, 2.0, { kind: 'petal', r: 5, dmg: 2, stop, linger: M.PETAL_LINGER, life: 600 }); + } + } + return t >= 70; + }, + // doc: "Spawns a Slime on its position" (Slime: 12 HP, 2 contact damage; endless while the boss lives) + spawn(b, t) { + if (t === 20 && this.minions.filter(m => m.kind === 'slime').length < M.SLIME_MAX) { + this.minions.push({ kind: 'slime', x: b.x, y: b.y + 20, r: 9, hp: 12, cd: 0, emerge: 24, flash: -99 }); + this.ev('summon'); + } + return t >= 40; + }, + // doc: "Slams the ground, leaving a green Poison pool and multiple bullets that linger; 3 damage each" + goo(b, t) { + if (t === 28) { + this.pools.push({ x: b.x, y: b.y + 8, r: 58, life: 420, form: 0 }); + this.ring(b.x, b.y + 8, 10, this.rand() * TAU, 1.6, { kind: 'slam', r: 5, dmg: 3, stop: 60, linger: 200, life: 600 }); + this.quakeFx(b.x, b.y + 14); this.ev('slam'); + } + return t >= 50; + }, + // doc: "The boss will also explode once right after being enraged" (the swell is the telegraph) + transform(b, t) { + if (t === 0) { b.boom = M.SLIME_SWELL; b.charge = 0; this.ev('swell'); } + return t >= M.SLIME_SWELL + 10; + } + }, + varkolyn_leader: { + // doc: "Spawns 4 purple poison circles in a line, aimed in the direction of the target" (pools form first) + pools(b, t, v) { + if (t === 0) v.a = this.aimAt(b.x, b.y); + if (t >= 20 && t < 20 + 4 * 8 && (t - 20) % 8 === 0) { + const k = (t - 20) / 8, d = 44 + k * 52, x = clamp(b.x + Math.cos(v.a) * d, ROOM.x0 + 20, ROOM.x1 - 20), y = clamp(b.y + Math.sin(v.a) * d, ROOM.y0 + 20, ROOM.y1 - 20); + this.pools.push({ x, y, r: 36, life: 480, purple: 1, form: 24 }); + } + return t >= 60; + }, + // doc: "Spawn 4 Tentacles randomly around the room"; cannot spawn more if there is already a good amount + tentacles(b, t) { + if (t === 24) { + const have = this.minions.filter(m => m.kind === 'tentacle').length; + for (let i = 0; i < Math.min(4, M.TENTACLE_MAX - have); i++) { + let x = 0, y = 0; + for (let k = 0; k < 8; k++) { + x = ROOM.x0 + 60 + this.rand() * (ROOM.x1 - ROOM.x0 - 120); y = ROOM.y0 + 60 + this.rand() * (ROOM.y1 - ROOM.y0 - 120); + if (hyp(x - this.player.x, y - this.player.y) > 120 && hyp(x - b.x, y - b.y) > 60) break; + } + this.minions.push({ kind: 'tentacle', x, y, r: 14, hp: 40, fire: 50 + Math.floor(this.rand() * 40), emerge: 40, flash: -99 }); + } + this.ev('summon'); + } + return t >= 50; + }, + // doc: "Fires small bullets in every direction" + ring(b, t, v) { + if (t === 16 || t === 34) { v.a = (v.a === undefined ? this.rand() * TAU : v.a + TAU / 32); this.ring(b.x, b.y - M.VARK_EYE, 16, v.a, 2.3, { r: 4, dmg: 3 }); } + return t >= 50; + }, + // doc: "Emits a sharp chime, then fires a sweeping laser (6 damage)"; enraged: slightly shorter charge, faster + // rotation; the boss does nothing else while firing. Telegraph = the start line of the sweep plus the swept arc. + laser(b, t, v) { + const charge = b.enraged ? M.LASER_CHARGE - 12 : M.LASER_CHARGE, sweep = b.enraged ? M.LASER_SWEEP - 20 : M.LASER_SWEEP; + if (t === 0) { v.dir = this.rand() < 0.5 ? 1 : -1; v.a0 = this.aimAt(b.x, b.y - M.VARK_EYE) - v.dir * M.LASER_ARC / 2; v.a = v.a0; v.on = 0; this.ev('chime'); } + if (t === charge) { v.on = 1; this.ev('laser'); } + if (v.on) { + v.a = v.a0 + v.dir * M.LASER_ARC * Math.min(1, (t - charge) / sweep); + const p = this.player, oy = b.y - M.VARK_EYE, ex = b.x + Math.cos(v.a) * 1000, ey = oy + Math.sin(v.a) * 1000; + if (p.dead === 0 && N.segmentDistance(p, { x: b.x, y: oy }, { x: ex, y: ey }) < M.LASER_W + p.r) this.hurt(6, 'laser'); + } + return t >= charge + sweep; + }, + // doc: "Fires a large bullet that fires spirals of smaller bullets around itself until it is destroyed"; it + // rotates but keeps a 4-way pattern + orb(b, t) { + if (t === 24) { + const a = this.aimAt(b.x, b.y - M.VARK_EYE), s = 1.3 * this.spd; + this.bullets.push({ x: b.x, y: b.y - M.VARK_EYE, vx: Math.cos(a) * s, vy: Math.sin(a) * s, r: 13, dmg: 4, kind: 'vorb', cut: true, age: 0, life: 480, spin: 0, emitEvery: 10 }); + } + return t >= 44; + } + }, + volcanic_sandworm: { + // doc: "Tilts its body backwards, then fires a giant Explosive (5 damage, explodes on impact, massive area of + // effect)"; enraged: 3 in one volley. A straight shell that explodes on the first wall / obstacle / crate / Knight + // it touches; its blast radius M.SHELL_BLAST is drawn around it in flight. + explosive(b, t) { + if (t === 24) { + const n = b.enraged ? 3 : 1, a = this.aimAt(b.x, b.y - M.WORM_MOUTH); + for (let i = 0; i < n; i++) this.bullet(b.x, b.y - M.WORM_MOUTH, a + (n === 1 ? 0 : (i - 1) * 22 * DEG), M.SHELL_SPEED, + { kind: 'shell', r: 11, dmg: 5, blast: M.SHELL_BLAST, life: 400, cut: false }); + this.ev('explosive'); + } + return t >= 44; + }, + // doc: "fires a wide spread of 8 Big bullets that make a small red radial blast upon impact, 4 damage; velocity + // decreases over time"; enraged: 12 + spread(b, t) { + if (t === 24) { + const n = b.enraged ? 12 : 8, a = this.aimAt(b.x, b.y - M.WORM_MOUTH), arc = 100 * DEG; + for (let i = 0; i < n; i++) this.bullet(b.x, b.y - M.WORM_MOUTH, a - arc / 2 + arc * i / (n - 1), 4.2, + { kind: 'big', r: 8, dmg: 4, drag: 0.982, minSpeed: 0.9, blast: 22, life: 260, cut: true }); + this.ev('spread'); + } + return t >= 44; + }, + // doc: digs underground (intangible, cannot be targeted, does not attack), leaves a temporary star that fires 13 + // long bullets in a cross; it may surface at the player and then re-burrow; resurfacing makes a star that fires 12 + // bouncy bullets in all directions; burrowing/surfacing creates a 4-damage shockwave; enraged: diagonal stars, + // faster digs, 12 lingering bubbles on every resurface + dig(b, t, v) { return this.wormDig(b, t, v, false); }, + dive(b, t, v) { return this.wormDig(b, t, v, true); } + } + }; + Game.prototype.quakeFx = function (x, y) { this.fx.push({ k: 'boom', x, y, r: 28, t: this.t }); this.shakeIt(3); }; + // Sandworm dig: sink (wind-up, the burrow shockwave radius is drawn) -> travel underground (moving dirt mound, + // intangible) -> rise (stops, the surface shockwave radius is drawn) -> surface (shockwave, bouncy star) -> rest. + // Enraged "dive": several hops with a short vulnerable peek between them (doc: "momentarily vulnerable during a + // continuous dive. It surfaces but quickly burrows"). + Game.prototype.wormDig = function (b, t, v, dive) { + const fast = b.enraged ? 0.7 : 1; + if (t === 0) { v.ph = 'sink'; v.c = Math.round(M.WORM_SINK * fast); v.hops = dive ? 3 : 1; this.ev('burrow'); } + if (v.ph === 'sink' || v.ph === 'peek') { + if (--v.c <= 0) { + b.under = true; this.quake(b.x, b.y); this.stars.push(this.wormStar(b.x, b.y, 'long')); + v.ph = 'travel'; v.c = Math.round((dive ? 50 : 80) * fast); this.wormTarget(b, v); + } + } else if (v.ph === 'travel') { + const a = Math.atan2(v.ty - b.y, v.tx - b.x), s = M.WORM_SPEED * this.moveMul, d = hyp(v.tx - b.x, v.ty - b.y); + if (d > s) { b.x += Math.cos(a) * s; b.y += Math.sin(a) * s; b.vx = Math.cos(a) * s; b.vy = Math.sin(a) * s; } + else { b.x = v.tx; b.y = v.ty; } + // the travel time ends the dig early, but never under the pillar (expansion round 3: 9 of 196 surfacings were inside + // it - the body stuck in the pillar, out of every line of fire for up to 5 s); the target itself is always clear + if ((--v.c <= 0 && !this.solidAt(b.x, b.y, b.r, false)) || d <= s) { v.ph = 'rise'; v.c = M.WORM_RISE; this.ev('rise'); } + } else if (v.ph === 'rise') { + if (--v.c <= 0) { + b.under = false; this.quake(b.x, b.y); this.ev('surface'); + this.stars.push(this.wormStar(b.x, b.y, 'bouncy')); + if (b.enraged) this.ring(b.x, b.y, 12, this.rand() * TAU, 0.8, { kind: 'bubble', r: 8, dmg: 3, life: 300 }); + v.hops--; v.ph = v.hops > 0 ? 'peek' : 'rest'; v.c = Math.round((v.hops > 0 ? 34 : 30) * fast); + } + } else if (--v.c <= 0) return true; + return false; + }; + // surfacing point: doc "may attempt to surface at players" -> a random point 90-150 px from the Knight that a body can + // occupy and that is a real move (>= 60 px from the burrow hole); up to 6 tries, then the midpoint, else stay + // (expansion round 1: one try behind the pillar fell back to "stay" and the dig became a 1-tick hop) + Game.prototype.wormTarget = function (b, v) { + const p = this.player, ok = (x, y) => !this.solidAt(x, y, b.r, false) && hyp(x - b.x, y - b.y) >= 60; + let x = b.x, y = b.y, found = false; + for (let k = 0; k < 6 && !found; k++) { + const a = this.rand() * TAU, d = 90 + this.rand() * 60; + x = clamp(p.x + Math.cos(a) * d, ROOM.x0 + 40, ROOM.x1 - 40); y = clamp(p.y + Math.sin(a) * d, ROOM.y0 + 50, ROOM.y1 - 30); + found = ok(x, y); + } + if (!found) { x = clamp(b.x + (p.x - b.x) * 0.5, ROOM.x0 + 40, ROOM.x1 - 40); y = clamp(b.y + (p.y - b.y) * 0.5, ROOM.y0 + 50, ROOM.y1 - 30); found = ok(x, y); } + if (!found) { x = b.x; y = b.y; } + v.tx = x; v.ty = y; + }; + Game.prototype.wormStar = function (x, y, kind) { + const b = this.boss; + if (kind === 'long') return { x, y, r: 10, a0: b.enraged ? Math.PI / 4 : 0, every: 6, fire: 14, shots: 13, life: 120, kind, k: 0 }; + // resurface star: 12 bouncy bullets in all directions, once (doc: 4 damage, cannot be reflected) + this.ring(x, y, 12, this.rand() * TAU, 2.4, { kind: 'bouncy', r: 5, dmg: 4, bounce: 2, life: 300, cut: true }); + return { x, y, r: 10, a0: 0, every: 99, fire: 99, shots: 0, life: 24, kind }; + }; + // xorshift32 started from a small seed (1, 2, 3 ...) yields tiny first outputs (every early shot + // would crit, the first attack would always be pool[0]); scramble the seed with a murmur3 finaliser. + Game.mixSeed = function (seed) { + let x = ((seed >>> 0) ^ 0x9e3779b9) >>> 0; + x = Math.imul(x ^ (x >>> 16), 0x85ebca6b) >>> 0; + x = Math.imul(x ^ (x >>> 13), 0xc2b2ae35) >>> 0; + x = (x ^ (x >>> 16)) >>> 0; + return x || 0x6d2b79f5; + }; + Game.prototype.beamVolley = function (b, a0) { this.ring(b.x, b.y, 12, a0, 4.5, { kind: 'beam', r: 5, dmg: 2, poison: true }); }; + + M.Game = Game; + M.RAM_PAD = 8; + // hazard radii shared by the hit test and the drawn telegraph (draw.js reads these, never its own numbers) + M.NODE_R = 18; // shockwave node + M.BLAST_R = 40; // laser-ball burst + M.CARRIER_R = 8; // turret-line shuriken (drawn 11 px star; hit like a bullet at ~0.8 of the drawn size) + M.LINE_LEAD = 12; // ticks a shockwave lane is drawn before its first node + M.FIRE_PAD = 10; // margin a line of fire must keep from trees/walls (shot radius + rifle spread at ~100 px) + M.RAM_LOCK = 20; // ticks the charge direction is fixed (and drawn locked) before the dash + M.RAM_TICKS = 45; // dash length in ticks + // 11-02 expansion (approximations unless marked doc) + M.TILE_FX = 120; // doc: Slow / Boost tile effect lasts 2 s + M.SLIME_HITS = 15; // doc: Grand Slime explodes after 15 hits while enraged + M.SLIME_SWELL = 50; // swell before the explosion (drawn as a growing ring of the blast radius) + M.SLIME_BLAST = 92; // explosion radius + M.SLIME_MAX = 4; // summoned slimes alive at once + M.SLIME_SPEED = 1.1; // slime walk speed (px/tick) + M.PETAL_LINGER = 120; // how long the flower bullets linger + M.VARK_SHIELD = 180; // doc "several seconds" of invulnerability in its own purple pool + M.VARK_VULN = 120; // doc "brief enforced vulnerability period" + M.TENTACLE_EVERY = 180; // doc "every few seconds" (approx 3 s, x tier gap); tactics: "quite easily avoidable" + M.TENTACLE_MAX = 6; // doc: no more tentacles once there is "a good amount" + M.LASER_CHARGE = 60; // doc: the chime is heard "a second before" the laser + M.LASER_SWEEP = 90; // sweep duration (enraged -20: "rotates faster") + M.LASER_ARC = 110 * DEG; + M.LASER_W = 7; // half-width of the beam + M.VARK_EYE = 44; // laser / bullets leave from the Varkolyn's head (drawn at y - 46) + M.WORM_MOUTH = 60; // Sandworm shells / big bullets leave from its mouth (drawn at y - 62) + M.SHELL_BLAST = 46; // doc "massive area of effect" explosive + M.SHELL_SPEED = 2.6; // explosive shell speed (x projectile speed via bullet()) + M.QUAKE_R = 70; // burrow / surface shockwave radius + M.WORM_SPEED = 2.2; // burrowed travel speed (x move) + M.WORM_RISE = 24; // doc: it no longer moves during resurface -> it stops and the mound shakes for this long + M.WORM_SINK = 18; // burrow wind-up at its visible position + // Distance the boss centre will still travel on the current charge line (pure: the same stepping as the + // dash; walls/obstacles stop it, crates do not). The telegraph band and the scripted controller use it, so + // the drawn band ends where the ram really ends instead of running 900 px across the room. + M.ramReach = function (g) { + const b = g.boss, v = b.vars, a = v.a, s = 9 * g.moveMul, n = v.ph === 'dash' ? v.c : M.RAM_TICKS; + let x = b.x, y = b.y, k = 0; + for (; k < n; k++) { const nx = x + Math.cos(a) * s, ny = y + Math.sin(a) * s; if (g.solidAt(nx, ny, b.r, false)) break; x = nx; y = ny; } + return k * s; + }; + // perpendicular half-width of the swept ram capsule for a charge direction a (without the Knight radius) + M.ramBand = function (kind, a) { const h = BOSS[kind].hurt; return h[2] + M.RAM_PAD + (h[1] - h[0]) / 2 * Math.abs(Math.cos(a)); }; + + // ======================= standard scripted controller ======================= + // Reads privileged state, never mutates it: lookahead runs on a JSON deep copy with its own rng copy. + const MOVES = [[0, 0], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]; + const SHORT = 18; // follow-up ticks at which positions are scored (the whole look-ahead for the Forest bosses) + // Varkolyn: doc tactics "stay close to him ... dodging the laser is easier this way"; "far away ... almost certain to be hit" + const RANGE = { goblin_priest: 210, christmas_treant: 240, devils_snare: 190, grand_slime: 210, varkolyn_leader: 115, volcanic_sandworm: 200 }; + // bosses that walk at the Knight / surface beside it: extra keep-away distance and a corner penalty (new bosses only, + // so the Forest fights keep their validated controller behaviour) + const CHASERS = { grand_slime: 120, volcanic_sandworm: 90 }; + const TWO_PLY = { grand_slime: 1, varkolyn_leader: 1, volcanic_sandworm: 1 }; + const memory = new WeakMap(); + const AIM = b => ({ x: b.x, y: b.y + (BOSS[b.kind].hurt[0] + BOSS[b.kind].hurt[1]) / 2 }); // middle of the hurt capsule + // the first of middle / top / bottom of the hurt capsule with a padded line of fire from p, or null + const aimPoint = (g, p, b) => { + const h = BOSS[b.kind].hurt; + for (const dy of [(h[0] + h[1]) / 2, h[0], h[1]]) { const q = { x: b.x, y: b.y + dy }; if (g.sight(p, q) && g.clearLine(p, q, M.FIRE_PAD)) return q; } + return null; + }; + function moveKeys(m) { + const k = []; + if (m[0] > 0) k.push('D'); else if (m[0] < 0) k.push('A'); + if (m[1] > 0) k.push('S'); else if (m[1] < 0) k.push('W'); + return k; + } + M.clone = function (g) { const c = N.copy(g); Object.setPrototypeOf(c, Game.prototype); return c; }; + function simTick(sim, keys, mouse) { + const held = [...keys].sort(), pressed = held.filter(k => !sim.held.includes(k)); + sim.events = []; + sim.update(new Set(held), new Set(pressed), mouse); + sim.t++; + if (!sim.outcome && sim.t >= HZ * M.maxSeconds) sim.outcome = 'timeout'; + } + function holdIndex(n, count) { return Math.ceil(n * 6 / count) - 1; } + function evaluate(g, holds, mouse, follow, horizon, holds2) { + const sim = M.clone(g), p0 = sim.player, hp0 = p0.hp, ar0 = p0.armor, poison0 = p0.poison, dealt0 = sim.stats.damageDealt; + // expansion bosses: the look-ahead must not read random numbers the game has not drawn yet (the copy carried the live + // rng: next attack pick, ring angles, tentacle spots) -> re-seed from the tick, the same for every candidate. Round 5 + // blind-vs-live, seeds 1-8 x 3 tiers: Forest 72/72 wins and in window either way (accepted scenes keep the validated + // controller); expansion bosses within noise + if (TWO_PLY[g.kind]) sim.rng = Game.mixSeed((g.t * 2654435761 + 0x51ed27) >>> 0); + const count = HZ / 5, per = mouse.map(v => v / count); + let lost1 = 0; + for (let n = 1; n <= count && !sim.outcome; n++) simTick(sim, holds[holdIndex(n, count)], per); + // two-ply: a second packet (another move) before the follow-up + if (holds2) for (let n = 1; n <= count && !sim.outcome; n++) simTick(sim, holds2[holdIndex(n, count)], [0, 0, 0]); + const p1 = sim.player; + lost1 = (hp0 - p1.hp) * 1.6 + (ar0 - p1.armor); + for (let n = 0; n < Math.min(horizon, SHORT) && !sim.outcome; n++) simTick(sim, follow, [0, 0, 0]); + const p = sim.player, b = sim.boss; + const lost2 = (hp0 - p.hp) * 1.6 + (ar0 - p.armor) - lost1; + let score = -1000 * lost1 - 650 * Math.max(0, lost2); + if (sim.outcome === 'loss' || p.dead > 0) score -= 1e6; + if (sim.outcome === 'win' || b.state === 'dying') score += 5000; + // expansion bosses: poisoning priced at its real cost - 2 ticks of (1 + tier bonus) damage, armour regeneration + // blocked and 4 s at half speed, which makes the next Varkolyn laser unescapable (round 3 hit logs: the deaths were + // bullet + poison + laser within ~5 s). 1-HP revive fixture, Varkolyn hard seeds 9-32: runs with a death 12/24 -> 2/24 + if (p.poison > poison0 + 2) score -= TWO_PLY[g.kind] ? 4000 : 160; + score += 3 * (sim.stats.damageDealt - dealt0); + if (b.hp > 0 && b.state !== 'dying') { + const d = hyp(p.x - b.x, p.y - b.y), R = RANGE[g.kind]; + score -= 0.7 * Math.abs(d - R); + // doc tactic (Varkolyn): "stay close to him ... dodging the laser is easier this way"; far away the laser is + // "almost certain" to hit. Expansion round 3: 7 of 8 lasers that began with the Knight >= 280 px away ended in a + // hit while it ran (0 of 4 below 120 px); this steep cost beyond 150 px: 1-HP revive fixture, hard seeds 1-8, runs + // with a death 3/8 -> 0/8 (seeds 9-16: 1/8) + if (g.kind === 'varkolyn_leader' && d > 150) score -= 2.5 * (d - 150); + if (d < b.r + 70) score -= (b.r + 70 - d) * 4; + // expansion bosses: a padded line of fire to some part of the hurt capsule (tall bodies), worth more (round 3: 8 % + // of the Sandworm normal-tier shots hit the pillar while the line to its feet was clear, and the Knight sat 4-5 s + // behind the pillar; Sandworm easy seeds 1-24 slowest 33.9 -> 27.9 s at the same HP) + if (TWO_PLY[g.kind] ? aimPoint(sim, p, b) !== null : sim.sight(p, b)) score += TWO_PLY[g.kind] ? 160 : 70; + } + const margin = Math.min(p.x - ROOM.x0, ROOM.x1 - p.x, p.y - ROOM.y0, ROOM.y1 - p.y); + if (margin < 56) score -= (56 - margin) * 1.6; + for (const q of sim.bullets) { const dd = hyp(q.x - p.x, q.y - p.y); if (dd < 64) score -= (64 - dd) * 0.45 * (q.dmg || 2); } + for (const m of sim.meteors) { const dd = hyp(m.x - p.x, m.y - p.y); if (dd < m.r + 18) score -= (m.r + 18 - dd) * 6; } + for (const n of sim.nodes) { const dd = hyp(n.x - p.x, n.y - p.y); if (dd < 40) score -= (40 - dd) * 3; } + for (const pool of sim.pools) { + const dd = hyp(pool.x - p.x, pool.y - p.y); + // purple (Varkolyn) pools, forming ones included: poison halves the Knight's speed, and a slowed Knight cannot + // outrun the sweeping laser (11-02 expansion round 1) -> a much stronger keep-out than the Snare's green pool + if (pool.purple) { if (dd < pool.r + 30) score -= (pool.r + 30 - dd) * 12; } + else if (dd < pool.r + 20) score -= (pool.r + 20 - dd) * 3; + } + for (const L of sim.lines) { // shockwave line still travelling: avoid its ray + const ex = L.x + Math.cos(L.a) * (L.start + L.n * L.gap), ey = L.y + Math.sin(L.a) * (L.start + L.n * L.gap); + const dd = N.segmentDistance(p, { x: L.x, y: L.y }, { x: ex, y: ey }); + if (dd < 34) score -= (34 - dd) * 4; + } + if (b.atk === 'charge' && (b.vars.ph === 'aim' || b.vars.ph === 'dash')) { + const h = BOSS[b.kind].hurt, a = b.vars.a, cy = b.y + (h[0] + h[1]) / 2; + const half = M.ramBand(b.kind, a) + p.r + 16; + const reach = M.ramReach(sim) + h[2] + M.RAM_PAD + (h[1] - h[0]) / 2; + const dd = N.segmentDistance(p, { x: b.x, y: cy }, { x: b.x + Math.cos(a) * reach, y: cy + Math.sin(a) * reach }); + if (dd < half) score -= (half - dd) * 10; + } + // 11-02 expansion hazards (these arrays stay empty in the Forest rooms, so those scores are unchanged) + for (const q of sim.bullets) if (q.blast) { // shells / big bullets: keep out of the blast around the rest of their path + const end = blastEnd(sim, q), dd = N.segmentDistance(p, q, end), de = hyp(p.x - end.x, p.y - end.y), R = q.blast + p.r + 10; + if (dd < R) score -= (R - dd) * (q.kind === 'shell' ? 4 : 1.5); + if (de < R) score -= (R - de) * (q.kind === 'shell' ? 6 : 2); + } + for (const q of sim.quakes) if (!q.hit) { const dd = hyp(q.x - p.x, q.y - p.y); if (dd < q.r1 + 20) score -= (q.r1 + 20 - dd) * 3; } + for (const m of sim.minions) { + const dd = hyp(m.x - p.x, m.y - p.y); + if (dd < m.r + 44) score -= (m.r + 44 - dd) * 3; + // a tentacle about to fire: its 8-bullet ring is dense near it (gap < Knight width inside ~30 px) and only + // outrun radially -> stay well clear while its charge glow is up (expansion round 1: most Varkolyn hard hits) + if (m.kind === 'tentacle' && !m.emerge && m.fire < 40 && dd < 110) score -= (110 - dd) * 4; + } + // expansion bosses: time-to-collision field - penalise final positions that a bullet's straight path crosses within + // ~40 ticks (round 2: a poisoned, half-speed Knight was caught by tentacle rings it could still have stepped out of; + // 1-HP revive fixture, Varkolyn hard: runs with a death 6/8 -> 3/8) + if (TWO_PLY[g.kind]) { + for (const q of sim.bullets) { + const rx = p.x - q.x, ry = p.y - q.y, vv = q.vx * q.vx + q.vy * q.vy; + if (vv < 1e-6 || rx * rx + ry * ry > 160 * 160) continue; + const tc = Math.max(0, Math.min(40, (rx * q.vx + ry * q.vy) / vv)), cx = rx - q.vx * tc, cy = ry - q.vy * tc, miss = hyp(cx, cy), R = p.r + q.r + 6; + if (miss < R) score -= (R - miss) * (q.dmg || 2) * (1 - tc / 50) * 6; + } + } + for (const st of sim.stars) if (st.shots > 0) { // keep off the star's four firing lanes + for (let i = 0; i < 4; i++) { + const a = st.a0 + i * Math.PI / 2, dd = N.segmentDistance(p, st, { x: st.x + Math.cos(a) * 600, y: st.y + Math.sin(a) * 600 }); + if (dd < 22) score -= (22 - dd) * 3; + } + } + if (p.tileK === 'slow') score -= 40; + if (CHASERS[g.kind] && b.hp > 0) { // pursuing bosses: keep escape room - corners and walls near the boss trap the Knight + const mx = Math.min(p.x - ROOM.x0, ROOM.x1 - p.x), my = Math.min(p.y - ROOM.y0, ROOM.y1 - p.y); + score -= Math.max(0, 120 - mx) * Math.max(0, 120 - my) / 30; + // Sandworm: also keep off the walls (round 4: the 5 hard losses in 64 seeds all ended against a wall, boxed in by + // the enraged resurface bubbles and bouncy bullets with the explosive shells' blast reaching the wall; those seeds + // 5/5 -> 0/8 runs with a death, fresh seeds 65-80 1/16 - but over seeds 1-64 hard stays 59/64: the losses moved to + // other seeds, still all escapable 1-HP-revive runs inside the window) + if (g.kind === 'volcanic_sandworm') score -= Math.max(0, 90 - Math.min(mx, my)) * 2; + const d = hyp(p.x - b.x, p.y - b.y); + if (d < CHASERS[g.kind]) score -= (CHASERS[g.kind] - d) * 3; + } + if (b.kind === 'grand_slime' && b.boom > 0) { const dd = hyp(b.x - p.x, b.y - p.y); if (dd < M.SLIME_BLAST + 34) score -= (M.SLIME_BLAST + 34 - dd) * 8; } + if (b.kind === 'volcanic_sandworm' && (b.under || b.vars.ph === 'sink' || b.vars.ph === 'peek')) { + for (const [x, y] of [[b.x, b.y], [b.vars.tx, b.vars.ty]]) { + if (x === undefined) continue; + const dd = hyp(x - p.x, y - p.y); + if (dd < M.QUAKE_R + 34) score -= (M.QUAKE_R + 34 - dd) * 5; + } + } + if (b.atk === 'laser') { + // inside the part of the arc the beam has not swept yet: run for the far end of the arc (the beam sweeps toward + // it and is outrun only close to the boss); the start edge only while the charge still leaves time to clear it + const v = b.vars, cur = v.on ? v.a : v.a0, end = v.a0 + v.dir * M.LASER_ARC, left = Math.abs(end - cur); + const R = Math.max(20, hyp(p.x - b.x, p.y - b.y + M.VARK_EYE)); + const ang = Math.atan2(p.y - (b.y - M.VARK_EYE), p.x - b.x), rel = v.dir * Math.atan2(Math.sin(ang - cur), Math.cos(ang - cur)); + const m = Math.atan2(M.LASER_W + p.r + 6, R); + if (rel > -m && rel < left + m) { + const charge = b.enraged ? M.LASER_CHARGE - 12 : M.LASER_CHARGE, spare = v.on ? 0 : Math.max(0, charge - b.at); + const toEnd = left + m - rel, toStart = rel + m, canStart = toStart * R < spare * K.speed * 0.8; + score -= 300 + 900 * (canStart ? Math.min(toEnd, toStart) : toEnd) / M.LASER_ARC + 0.8 * Math.max(0, R - 110); + } + } + // Long threats (laser sweep, shells, swell, surfacing): positions are scored at the short horizon above; the + // rollout then continues to the threat horizon only to count the damage still coming on this course. Scoring + // bullets 2 s ahead instead would blind the near-term dodge (expansion round 1: most Varkolyn hits were small + // bullets taken while the controller was running from the laser). + let lost3 = 0; + if (horizon > SHORT && !sim.outcome) { + const hpS = p.hp, arS = p.armor; + for (let n = SHORT; n < horizon && !sim.outcome; n++) simTick(sim, follow, [0, 0, 0]); + lost3 = (hpS - sim.player.hp) * 1.6 + (arS - sim.player.armor); + score -= 500 * Math.max(0, lost3); + if (sim.outcome === 'loss' || sim.player.dead > 0) score -= 1e5; + } + return { score, sim, danger: lost1 > 0 || lost2 > 0 || lost3 > 0 }; + } + // where a blast projectile (Sandworm shell / big bullet) will explode: march its own motion until it would hit a + // wall, obstacle or crate (pure; same tests as updateBullets, life-limited) + function blastEnd(g, q) { + let x = q.x, y = q.y, vx = q.vx, vy = q.vy; + const r = Math.min(q.r, 3); + for (let i = 0; i < 160 && q.age + i < q.life; i++) { + if (q.drag) { const s = hyp(vx, vy), ns = Math.max(q.minSpeed || 0, s * q.drag); if (s > 0) { vx *= ns / s; vy *= ns / s; } } + const nx = x + vx, ny = y + vy; + if (nx < ROOM.x0 || nx > ROOM.x1 || ny < ROOM.y0 || ny > ROOM.y1 || g.obstacleAt(nx, ny, r) || g.crateAt(nx, ny, r)) break; + x = nx; y = ny; + } + return { x, y }; + } + // Follow-up horizon (ticks held after the packet) long enough to see the current threat land: 18 normally; the + // Varkolyn laser until its sweep ends, Sandworm shells / big bullets until they explode, the Grand Slime swell + // until it bursts, the burrowed Sandworm until it surfaces (11-02 expansion round 1: a fixed 30-tick look-ahead + // let the Knight run into a sweep or a wall blast it could not see yet). + function threatHorizon(g) { + const b = g.boss, v = b.vars; + let h = 18; + if (b.atk === 'laser') { + const end = (b.enraged ? M.LASER_CHARGE - 12 : M.LASER_CHARGE) + (b.enraged ? M.LASER_SWEEP - 20 : M.LASER_SWEEP); + h = Math.max(h, end - b.at - 12); + } + for (const q of g.bullets) if (q.blast) { + const e = blastEnd(g, q), s = Math.max(0.5, hyp(q.vx, q.vy)); + h = Math.max(h, hyp(e.x - q.x, e.y - q.y) / s - 8); + } + if (b.boom > 0) h = Math.max(h, b.boom - 8); + if (b.kind === 'volcanic_sandworm' && (v.ph === 'travel' || v.ph === 'rise')) h = Math.max(h, (v.ph === 'rise' ? v.c : v.c + M.WORM_RISE) - 8); + return Math.min(140, Math.round(h)); + } + M.scripted = function (g) { + const p = g.player, b = g.boss; + let mem = memory.get(g); + if (!mem || g.t === 0) { mem = { last: 0 }; memory.set(g, mem); } + const count = HZ / 5; + // aim: lead the boss; mouse total moves the reticle onto the target by the end of the packet + // expansion bosses: aim at the middle of the hurt capsule, or its top / bottom when only those are in the line of fire + // (round 4, Sandworm easy seed 25: surfaced beside the pillar with the capsule middle hidden -> 4 s without a hit; seeds + // 25-64 slowest 33.9 -> 30.5 s); the Forest aim stays at the feet as validated + const ap = TWO_PLY[g.kind] ? aimPoint(g, p, b) || AIM(b) : b; + let tx = ap.x, ty = ap.y; + const w = WEAPONS[SLOTS[p.slot]]; + if (b.hp > 0 && w.kind === 'gun') { + const d = hyp(b.x - p.x, b.y - p.y), lead = d / w.speed; + tx += b.vx * lead; ty += b.vy * lead; + } + const mouse = [clamp(Math.round(tx - p.aimX), -1000, 1000), clamp(Math.round(ty - p.aimY), -1000, 1000), 0]; + // weapon choice: rifle while energy lasts, pistol as the free fallback; hysteresis (back to the rifle at + // 12 energy) so single energy orbs do not cause switch thrash (11-02: the old fixed 24-energy reserve was + // never spent - the Knight's skill costs no energy) + const want = p.energy >= (p.slot === 1 ? 1 : 12) ? 1 : 0; + // the burrowed Sandworm and the shielded Varkolyn Leader cannot be damaged: hold fire instead of spending energy + let hold = b.under || b.shield > 0; + if (b.kind === 'volcanic_sandworm' && w.kind === 'gun') { + // fire timing around the burrow (doc tactic: "momentarily vulnerable during a continuous dive ... quick burst damage + // is very effective"): while it rises (the mound has stopped) fire once a shot reaches the body no earlier than it + // surfaces; while it sinks / peeks hold when the shot would arrive after it is gone (round 3: 13 % of the + // normal-tier shots flew through the hole it had just left; normal-tier spread 36.9-73.4 s -> 35.3-51.4 s) + const v = b.vars, tt = Math.max(0, hyp(AIM(b).x - p.x, AIM(b).y - p.y) - BOSS[b.kind].hurt[2]) / w.speed; + if (v.ph === 'rise') hold = tt < v.c - 1; + else if (!hold && (v.ph === 'sink' || v.ph === 'peek')) hold = v.c < tt + 2; + } + let switchPress = 0; + if (p.dead === 0 && b.state !== 'dying' && p.slot !== want && p.lock === 0 && !(p.dual > 0 && p.energy >= 2)) switchPress = (want - p.slot + SLOTS.length) % SLOTS.length; + const skill = p.dead === 0 && b.hp > 0 && b.state !== 'dying' && !b.inv && !hold && p.dual === 0 && p.skillCd === 0 && switchPress === 0 && g.sight(p, b) && (p.slot === 0 || p.energy >= 40); + let best = null; + const cands = [], H = threatHorizon(g); + for (let i = 0; i < MOVES.length; i++) { + const mk = moveKeys(MOVES[i]); + const holds = []; + for (let j = 0; j < 6; j++) { + const k = [...mk]; + const press = (switchPress >= 1 && j === 0) || (switchPress >= 2 && j === 2); + if (press) k.push('Q'); else if (!hold) k.push('J'); + if (skill && j === 0) k.push('K'); + holds.push(k); + } + const follow = hold ? [...mk] : [...mk, 'J']; + const r = evaluate(g, holds, mouse, follow, H); + const c = { s: r.score + (i === mem.last ? 12 : 0), holds, i, danger: r.danger }; + cands.push(c); + if (!best || c.s > best.s) best = c; + } + // Two-ply look-ahead on every packet for the expansion bosses (the Forest fights keep their validated one-ply + // controller): the escape from a tentacle ring or a laser sweep often needs a change of direction one packet + // later. 11-02 expansion round 1: the chosen packet was safe but every straight follow-up was hit (Varkolyn hard + // 1/8 wins). Gating it on "the one-ply plan predicts damage" left 5/8 hard runs with a death (1-HP revive + // fixture); running it always: 1/8. + if (TWO_PLY[g.kind]) { + let best2 = null; + // all nine first moves for the Varkolyn Leader and during its laser, the best four otherwise (round 4: every laser hit + // in the 64-seed hard losses had an escape plan from the chime - 10/10 checked with tools/laser_escape.js - but its + // first move scored below the top four one packet earlier; 64 seeds, hard wins 53/64 -> 56/64 with nine during the + // laser -> 61/64 with nine on every packet) + for (const c of [...cands].sort((a, b) => b.s - a.s).slice(0, b.atk === 'laser' || g.kind === 'varkolyn_leader' ? 9 : 4)) { + for (let j = 0; j < MOVES.length; j++) { + const mk2 = moveKeys(MOVES[j]), f2 = hold ? [...mk2] : [...mk2, 'J'], holds2 = [f2, f2, f2, f2, f2, f2]; + const s2 = evaluate(g, c.holds, mouse, f2, H, holds2).score + (c.i === mem.last ? 12 : 0); + if (!best2 || s2 > best2.s) best2 = { s: s2, c }; + } + } + best = best2.c; + } + mem.last = best.i; + return { holds: best.holds.map(h => h.slice(0, 4)), mouse }; + }; + M.oracle = M.scripted; // web/tools/native_validate.js still calls oracle +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/soulknight_remake/index.html b/environments/games/web/games/soulknight_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..832148807c77131b2f530641e427563ff9575f6b --- /dev/null +++ b/environments/games/web/games/soulknight_remake/index.html @@ -0,0 +1,7 @@ + +Soul Knight: Dungeon Bosses
    +

    Soul Knight: Dungeon Bosses

    Six bosses · Armored Gunner · knight-arena@6 · 60 Hz · Easy/Normal/Hard · Recording and Replay

    Back to Game Lobby
    +
    Select a boss to start

    The gunner has 6 health, 5 armor, and 180 energy. Armor regenerates by 1 per second after 3 seconds without damage. Bosses enrage at half health. The blade can cut ordinary bullets, turrets, star turrets, and vortex shots, but not shockwaves, meteors, laser orbs, explosive shots, or beams. Hold the left mouse button and drag to aim manually, or double-click the screen to lock the pointer for free aim (Esc unlocks it). When the mouse is idle, auto-aim targets a visible boss. Replays save inputs and the seed for deterministic verification. The scripted demo reads internal state and emits only valid keyboard and mouse actions; it does not start RL training.

    +
    +
    + diff --git a/environments/games/web/games/soulknight_remake/manifest.json b/environments/games/web/games/soulknight_remake/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..964f24342d5a48df2b8b698fb09c56cbb6a09e29 --- /dev/null +++ b/environments/games/web/games/soulknight_remake/manifest.json @@ -0,0 +1,31 @@ +{ + "schema": "bossbench/game-manifest@1", + "engine": "independent", + "game": "soulknight_remake", + "module": "SoulKnightGame", + "title": "Soul Knight: Dungeon Bosses", + "dimension": "2d", + "native_hz": 60, + "max_seconds": 300, + "renderer": "canvas-native", + "rules": "knight-arena@6", + "cases": [ + "soulknight/goblin_priest", + "soulknight/christmas_treant", + "soulknight/devils_snare", + "soulknight/grand_slime", + "soulknight/varkolyn_leader", + "soulknight/volcanic_sandworm" + ], + "scripts": [ + "_native/runtime.js", + "soulknight_remake/game.js", + "soulknight_remake/draw.js" + ], + "sim_scripts": [ + "_native/runtime.js", + "soulknight_remake/game.js" + ], + "play_page": "web/games/soulknight_remake/index.html", + "scripted_controller": "SoulKnightGame.scripted(game) -> {holds:[6 key arrays], mouse:[dx,dy,dz]} (falls back to .oracle)" +} diff --git a/environments/games/web/games/terraria_remake/arena.js b/environments/games/web/games/terraria_remake/arena.js new file mode 100644 index 0000000000000000000000000000000000000000..c56f491f5f3d7f75018ed0191004eed57e3607ac --- /dev/null +++ b/environments/games/web/games/terraria_remake/arena.js @@ -0,0 +1,9 @@ +// Arena geometry, in game units (u). Origin = left wall surface / floor surface, y up. +// Scale: 1 u = 2 tiles = 32 px of the source game (a tile is 16 px); its 60 Hz tick is kept, so +// speed px/tick x 1.875 = u/s acceleration px/tick^2 x 112.5 = u/s^2 +// 27 x 15 u = a 54 x 30 tile arena (engine/renderer.js: 30 px per u on screen, keep W <= 28). +// Platforms (one-way, like wooden platforms) are per case: BB.CASES[id].platforms = [[x0, x1, y], ...]. +(function (g) { + var BB = g.BB; + BB.ARENA = { W: 27, H: 15 }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/terraria_remake/art/scenes.js b/environments/games/web/games/terraria_remake/art/scenes.js new file mode 100644 index 0000000000000000000000000000000000000000..6c42e6d8c0fa3dcac326bcb6455d37d074fe3950 --- /dev/null +++ b/environments/games/web/games/terraria_remake/art/scenes.js @@ -0,0 +1,119 @@ +(function(g){ + var BB=g.BB,ART=BB.ART; + // Original procedural backdrops, cached once per case (bg + fg) plus a cached day/night alternate. + // Seeded by a fixed hash (ART.hash), never by the game RNG. + var H=ART.hash; + function sky(x,top,bottom){var gr=x.createLinearGradient(0,0,0,466);gr.addColorStop(0,top);gr.addColorStop(1,bottom);x.fillStyle=gr;x.fillRect(0,0,854,480);} + function hills(x,base,amp,col,seed,step){x.fillStyle=col;x.beginPath();x.moveTo(0,480);for(var px=0;px<=854;px+=step){x.lineTo(px,base-amp*(.5+.5*Math.sin(px*.011+seed))-amp*.35*H(seed+px));}x.lineTo(854,480);x.closePath();x.fill();} + function tree(x,px,base,h,trunk,leaf,leaf2){ + x.fillStyle=trunk;x.fillRect(px-4,base-h,8,h);x.fillRect(px-9,base-6,18,6); + x.fillStyle=leaf;x.beginPath();x.arc(px,base-h,h*.32,0,Math.PI*2);x.arc(px-h*.22,base-h*.82,h*.24,0,Math.PI*2);x.arc(px+h*.22,base-h*.82,h*.24,0,Math.PI*2);x.fill(); + x.fillStyle=leaf2;x.beginPath();x.arc(px-h*.08,base-h*1.06,h*.17,0,Math.PI*2);x.fill(); + } + function stars(x,n,seed){for(var i=0;i.5?'rgba(0,0,0,.12)':'rgba(255,255,255,.05)';x.fillRect(px,y+5,15,10);} + x.fillStyle=top;x.fillRect(0,y-2,854,6); + if(kind!=='dungeon'&&kind!=='hive')for(px=0;px<854;px+=6){var gh=2+Math.floor(H(px*3.1)*5);x.fillRect(px,y-2-gh,2,gh);} + } + // Honeycomb wall for the underground hive (original procedural pattern). + function honeycomb(x,top){ + var r=19,hx=r*1.5,hy=r*Math.sqrt(3); + for(var col=0,cx=-r;cx<880;col++,cx+=hx)for(var cy=top+(col%2)*hy/2;cy<480;cy+=hy){ + var s=H(col*13.7+cy);x.beginPath(); + for(var k=0;k<6;k++){var a=k*Math.PI/3;x.lineTo(cx+Math.cos(a)*(r-1.5),cy+Math.sin(a)*(r-1.5));} + x.closePath();x.fillStyle=s>.86?'#6a4818':s>.5?'#3e2a10':'#35230c';x.fill(); + x.strokeStyle='rgba(18,10,2,.7)';x.lineWidth=2;x.stroke(); + if(s>.86){x.fillStyle='rgba(255,200,90,.12)';x.beginPath();x.arc(cx-4,cy-4,5,0,Math.PI*2);x.fill();} + } + } + ART.scene=function(doc,id){ + var bg=doc.createElement('canvas'),fg=doc.createElement('canvas');bg.width=fg.width=854;bg.height=fg.height=480; + var x=bg.getContext('2d'),V=BB.VIEW,kind=BB.CASES[id].arena; + var night=kind==='night',cave=kind==='dungeon'||kind==='hive',evil=kind==='corruption',crimson=kind==='crimson'; + function paint(x,isNight){ + if(kind==='hive'){ + // underground hive: warm gradient, honeycomb wall, dripping honey and jungle vines (no day/night) + sky(x,'#140c04','#24170a');honeycomb(x,70); + x.fillStyle='rgba(10,6,2,.35)';x.fillRect(0,0,854,480); + for(var d=0;d<14;d++){var hx=30+d*62+H(d)*30,len=30+H(d+3)*90;x.fillStyle='rgba(190,120,30,.6)';x.fillRect(hx-2,60,4,len);x.beginPath();x.arc(hx,60+len,4,0,Math.PI*2);x.fill();} + for(d=0;d<9;d++){var vx=H(d+20)*854;x.strokeStyle='#2c4a1e';x.lineWidth=3;x.beginPath();x.moveTo(vx,40);x.quadraticCurveTo(vx+18,140,vx-6,180+H(d)*120);x.stroke(); + x.fillStyle='#365f24';for(var l=0;l<5;l++){x.beginPath();x.ellipse(vx+6-l*2,70+l*28,6,3,.6,0,Math.PI*2);x.fill();}} + [[150,250],[700,250]].forEach(function(p){ART.glow(x,p[0],p[1],70,'255,170,60',.12);}); + return; + } + if(crimson){ + // crimson: blood-red sky, flesh hills, vertebra spires and veiny ground growths + sky(x,isNight?'#200a10':'#5a1f26',isNight?'#4a1820':'#8a3a3a'); + if(isNight){stars(x,40,5);moon(x,690,84,20);}else sun(x,700,90,20); + hills(x,320,60,isNight?'#3a121a':'#6a2a30',2.7,6); + for(var i=0;i<8;i++){var sx=50+i*110+H(i+11)*40,sh=100+H(i+2)*120; + for(var v=0;v.7?'#33415a':s>.35?'#2d3a50':'#283447';x.fillRect(a,y,50,20); + x.fillStyle='rgba(255,255,255,.04)';x.fillRect(a,y,50,2);} + [110,330,524,744].forEach(function(px){x.fillStyle='#1a2230';x.fillRect(px-20,96,40,370);x.fillStyle='#3d4c63';x.fillRect(px-26,90,52,10);x.fillRect(px-26,450,52,16);}); + [220,634].forEach(function(px){x.fillStyle='#0b0f17';x.beginPath();x.moveTo(px-26,250);x.lineTo(px-26,170);x.arc(px,170,26,Math.PI,0);x.lineTo(px+26,250);x.closePath();x.fill(); + ART.glow(x,px,190,40,'90,140,255',.18);}); + for(var k=0;k<6;k++){var cx=70+k*150+H(k)*30;x.strokeStyle='#4b525c';x.lineWidth=2;x.setLineDash([3,2]);x.beginPath();x.moveTo(cx,96);x.lineTo(cx,96+40+H(k+9)*60);x.stroke();x.setLineDash([]);} + [[180,300],[680,300]].forEach(function(p){ART.glow(x,p[0],p[1],46,'255,170,80',.35);x.fillStyle='#ffcc6a';x.fillRect(p[0]-3,p[1]-6,6,9);x.fillStyle='#5a4632';x.fillRect(p[0]-5,p[1]+3,10,4);}); + return; + } + if(evil){ + sky(x,isNight?'#1d1426':'#4a3a5c',isNight?'#3a2a44':'#7a6585'); + if(isNight){stars(x,50,3);moon(x,120,78,18);}else sun(x,700,90,20); + hills(x,320,60,isNight?'#2c2036':'#4f3f5e',1.3,6); + // ebonstone spires and thorny dead trees + for(var i=0;i<9;i++){var px=40+i*100+H(i)*40,hgt=90+H(i+3)*120;x.fillStyle=isNight?'#231a2c':'#3d2f4a';x.beginPath();x.moveTo(px-26,466);x.lineTo(px-8,466-hgt);x.lineTo(px+4,466-hgt*.82);x.lineTo(px+26,466);x.closePath();x.fill();} + hills(x,380,40,isNight?'#2a1f33':'#46385a',4.1,5); + for(i=0;i<7;i++){var tx=60+i*125+H(i*2)*30,th=60+H(i+8)*40;x.strokeStyle=isNight?'#1a1220':'#2c2235';x.lineWidth=5;x.beginPath();x.moveTo(tx,466);x.lineTo(tx,466-th);x.stroke(); + x.lineWidth=2;x.beginPath();x.moveTo(tx,466-th*.6);x.lineTo(tx-16,466-th*.85);x.moveTo(tx,466-th*.75);x.lineTo(tx+14,466-th);x.stroke();} + for(i=0;i<16;i++){x.fillStyle='rgba(180,140,220,.35)';x.fillRect(H(i+40)*854,140+H(i+60)*300,2,2);} + return; + } + if(isNight){sky(x,'#0e1830','#2c4468');stars(x,90,1);moon(x,700,90,22);} + else{sky(x,'#6fb6e6','#cfe8f2');sun(x,700,92,24); + for(var cl=0;cl<5;cl++){var ccx=60+cl*190+H(cl)*40,ccy=60+H(cl+4)*60;x.fillStyle='rgba(255,255,255,.75)';x.beginPath();x.ellipse(ccx,ccy,46,14,0,0,Math.PI*2);x.ellipse(ccx+24,ccy-8,30,12,0,0,Math.PI*2);x.fill();}} + hills(x,300,70,isNight?'#1d3042':'#8fb9b0',.4,6); + hills(x,350,50,isNight?'#1b3a35':'#5f9670',2.2,5); + for(var j=0;j<12;j++)tree(x,20+j*76+H(j)*30,466,90+H(j+5)*60,isNight?'#2a2620':'#5c3d27',isNight?'#1e4436':'#3f8a4a',isNight?'#2a5a46':'#5aa85c'); + } + paint(x,night); + ground(x,kind,V); + var f=fg.getContext('2d'); + (BB.CASES[id].platforms||[]).forEach(function(p){var x0=Math.round(V.sx(p[0])),w=Math.round((p[1]-p[0])*V.S),y=Math.round(V.sy(p[2])); + f.fillStyle='#4c3423';f.fillRect(x0,y,w,7);f.fillStyle='#c9925a';f.fillRect(x0,y,w,3); + for(var n=0;n0?4:0);return this.status.broken_armor>0?Math.floor(d/2):d;}; + // r7 (2026-11-07): no natural health regeneration. The source regenerates over time (RT/eRT formula), which in a + // single-boss arena let a controller stand and trade hits. Life comes back only from dropped hearts. + // Poisoned: 2 life per second for players (Debuffs Wiki), applied as one point every 30 ticks. + P.updateLifeDrain=function(c){ + if(this.status.poisoned>0&&this.hp>0){this.poisonCounter++;if(this.poisonCounter>=30){this.poisonCounter=0;this.hp=Math.max(0,this.hp-1);c.emit('poison_tick',this.x,this.y+K.H);}} + else this.poisonCounter=0; + }; + P.update=function(c,i){ + var dt=BB.DT,pv=this.prev,oldY=this.y; + function decay(v){return v<=dt+1e-9?0:v-dt;} + this.invul=decay(this.invul);this.atkCd=decay(this.atkCd);this.atkT=decay(this.atkT);this.dropT=decay(this.dropT); + for(var name in this.status)this.status[name]=decay(this.status[name]); + // Confused swaps the movement controls (left with right, jump/up with drop/down); attacks are unchanged. + if(this.status.confused>0)i=Object.assign({},i,{left:i.right,right:i.left,jump:i.drop,drop:i.jump}); + if(this.status.cursed>0)i=Object.assign({},i,{attack:false,bow:false,sword:false}); + if(this.atkT>0){ + this.slashPreviousAngle=this.slashAngle; + var arc=2.2-3.3*(1-this.atkT/K.SWORD_CD);this.slashAngle=this.slashFacing>0?arc:Math.PI-arc; + } + this.knock*=0.89; + var dir=(i.right?1:0)-(i.left?1:0),slow=(this.status.slow>0?0.5:1)*(this.status.weak>0?0.9:1); + // Weak also lowers melee damage and melee speed by 5.1 %; the instance NAIL is what the engine deals per slash. + this.NAIL=this.status.weak>0?K.SWORD*0.949:K.SWORD; + this.vx=TR.playerHorizontal(this.vx,dir,K.BASE_RUN*slow,K.RUN*slow,K.ACC,K.DEC,true); + if(dir&&this.atkT<=0)this.facing=dir; + if(i.switchWeapon&&!pv.switchWeapon)this.weapon=this.weapon==='bow'?'sword':'bow'; + if(i.drop&&this.y>0&&this.grounded){this.dropT=0.18;this.grounded=false;this.y=Math.max(0,this.y-0.06);this.jumpTicks=0;} + if(i.jump&&!pv.jump&&this.grounded&&!i.drop){this.jumpTicks=K.JUMP_TICKS;this.grounded=false;c.emit('jump',this.x,this.y);} + if(!i.jump)this.jumpTicks=0; + this.flying=false;this.gliding=false; + if(this.jumpTicks>0){this.vy=K.JUMP-K.GRAV*dt;this.jumpTicks--;} + else{ + this.vy=Math.max(-K.FALL,this.vy-K.GRAV*dt); + if(i.jump&&!this.grounded&&this.flight>0){ + this.flying=true;this.vy=Math.min(K.FLY,this.vy+60*dt);this.flight=decay(this.flight); + }else if(i.jump&&!this.grounded&&this.vy<0){this.gliding=true;this.vy=Math.max(this.vy,-K.FALL/3);} + } + this.x=BB.clamp(this.x+this.vx*dt,K.W/2,BB.ARENA.W-K.W/2); + this.y=Math.min(BB.ARENA.H-K.H,this.y+this.vy*dt);this.grounded=false; + if(this.y<=0){this.y=0;this.vy=0;this.grounded=true;} + if(this.vy<=0&&this.dropT<=0){ + var landing=-Infinity; + TR.platforms(c).forEach(function(p){ + if(this.x+K.W/2>p[0]&&this.x-K.W/2=p[2]-0.001&&this.y<=p[2])landing=Math.max(landing,p[2]); + },this); + if(landing>-Infinity){this.y=landing;this.vy=0;this.grounded=true;} + } + if(this.grounded){this.flight=K.WINGS;this.jumpTicks=0;this.flying=false;this.gliding=false;} + if(this.y>=BB.ARENA.H-K.H&&this.vy>0){this.vy=0;this.jumpTicks=0;} + if((i.attack||i.bow||i.sword)&&this.atkCd<=0){ + var weapon=i.bow?'bow':i.sword?'sword':this.weapon; + var b=this.centre(),a=Math.atan2(this.aimY-b.y,this.aimX-b.x); + this.facing=Math.cos(a)>=0?1:-1; + if(weapon==='bow'){ + this.atkCd=K.BOW_CD; + this.arrows.push({id:++this.nextId,x:b.x,y:b.y,vx:Math.cos(a)*K.ARROW_SPEED,vy:Math.sin(a)*K.ARROW_SPEED,age:0,life:K.ARROW_LIFE});c.emit('arrow',b.x,b.y); + }else{ + this.atkCd=K.SWORD_CD/(this.status.weak>0?0.949:1);this.atkT=K.SWORD_CD;this.slashFacing=this.facing; + this.slashAngle=this.facing>0?2.2:Math.PI-2.2;this.slashPreviousAngle=this.slashAngle;this.slashHits={};c.emit('slash',b.x,b.y); + } + } + this.arrows=this.arrows.filter(function(p){ + var ox=p.x,oy=p.y; + p.age=(p.age||0)+1;if(p.age>=K.ARROW_GRAV_DELAY)p.vy=Math.max(-K.FALL,p.vy-K.ARROW_GRAV*dt); + p.x+=p.vx*dt;p.y+=p.vy*dt;p.life-=dt; + var shape={x0:ox,y0:oy,x1:p.x,y1:p.y,r:0.08}; + if(TR.resolveArrow(c.boss,c,K.BOW,shape,p.vx>=0?1:-1))return false; + return p.life>0&&p.x>=0&&p.x<=BB.ARENA.W&&p.y>=0&&p.y<=BB.ARENA.H; + },this); + var slash=this.slashBox(); + if(slash)TR.slashExtras(c.boss,c,this.NAIL,slash.pts,this.slashHits); + this.updateLifeDrain(c); + if(typeof TR.updatePickups==='function')TR.updatePickups(c); + this.prev={jump:!!i.jump,switchWeapon:!!i.switchWeapon}; + }; + P.onSlashContact=function () {}; + P.hurt=function(c,base,fromX,hazard){ + if(this.invul>0||this.hp<=0)return false; + var damage=TR.playerDamage(c,base,this.defense(),TR.defFactor(c)); + this.hp=Math.max(0,this.hp-damage);this.invul=damage===1?K.INVUL/2:K.INVUL; + this.knock=this.x>fromX?4.5*TR.PX:-4.5*TR.PX;this.vx=this.knock;this.vy=3.5*TR.PX;this.grounded=false;this.jumpTicks=0; + if(hazard&&hazard.debuff&&c.rng.chance(hazard.debuffChance==null?1:hazard.debuffChance)){ + var duration=hazard.debuffDuration; + if(Array.isArray(duration))duration=c.rng.uniform(duration[0],duration[1]); + this.applyStatus(hazard.debuff,+duration||0); + } + // A weighted debuff pool (Brain of Cthulhu Expert contacts): one roll picks one debuff and its duration range. + if(hazard&&hazard.debuffPool&&c.rng.chance(hazard.debuffChance==null?1:hazard.debuffChance)){ + var pool=hazard.debuffPool,pick=pool[c.rng.pick(pool.map(function(e){return e[1];}))]; + this.applyStatus(pick[0],c.rng.uniform(pick[2][0],pick[2][1])); + } + TR.emitHit(c,'player_hit',this.x,this.y+K.H,damage);return true; + }; + P.state=function(){return TR.snapshot(this,{attacking:this.atkT>0,flight_max:K.WINGS});}; + BB.Adventurer=Adventurer;BB.TR.BODY=K; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/bosses/brain_of_cthulhu.js b/environments/games/web/games/terraria_remake/bosses/brain_of_cthulhu.js new file mode 100644 index 0000000000000000000000000000000000000000..f7af56b828467a4afda75c81bd264c7f460978ec --- /dev/null +++ b/environments/games/web/games/terraria_remake/bosses/brain_of_cthulhu.js @@ -0,0 +1,131 @@ +(function(g){ + var BB=g.BB,TR=BB.TR,S=BB.SPECS.brain_of_cthulhu; + // Desktop 1.4.5.8 ordinary single-player Classic / Expert Brain of Cthulhu (aiStyle 54) and its Creepers. + // Published: brain 1250/2125 life, 30/54 damage, defense 14; 20 Creepers 100/170 life, 20/36 damage, defense 10, + // never respawn; the brain cannot be damaged until every Creeper is dead; a Creeper drops a heart 1/2 when the + // player is hurt; Expert contacts roll one debuff from a nine-entry pool (Creepers always, phase-2 brain 1/3); + // Expert phase 2 adds three mirror illusions around the player whose opacity rises as health drops. + // Unpublished (estimates): teleport and charge timing, speeds, orbit radius, the 1.4.4 + // phase-1 safe radius. + var W=110/32,H=86/32; + // Expert contact debuff pool: [name, weight out of 81, duration range s] (Creeper / Brain of Cthulhu pages). + var POOL=[['poisoned',11,[5.23,10.4]],['darkness',11,[3,5.93]],['cursed',2,[.73,1.47]],['bleeding',11,[15,29.8]], + ['confused',2,[1.5,2.97]],['slow',11,[5.23,10.4]],['weak',11,[11.23,22.33]],['silenced',11,[1.5,2.97]],['broken_armor',11,[9.73,19.37]]]; + function Brain(){} + var P=Brain.prototype;TR.boss(P,S); + P.reset=function(c){ + this.setup(c,20,9,W,H);this.expert=this.k.expert>=.5; + // Boss health is the published combined total (brain + 20 Creepers, 3250 / 5525), like the Eater's segment sum, + // so the HUD, verifier and reward count Creeper kills. The brain's own health is brainHp. + this.brainHp=this.brainMax=TR.paceHp(this,this.expert?2125:1250,10,this.pace.brainHp);this.dmg=TR.paceDmg(this,this.expert?54:30);this.defense=14; + this.creeperHp=TR.paceHp(this,this.expert?170:100);this.creeperDmg=TR.paceDmg(this,this.expert?36:20); + this.sourceProfile=this.expert?'desktop-expert':'desktop-classic';this.phase=1;this.fade=1;this.tpTimer=0;this.chargeTimer=1.2/this.pace.aggr; + this.knockbackResist=this.expert?.6:.55; + this.orbitAngle=0;this.illusions=[];this.illusionAlpha=0; + for(var i=0;i<20;i++){ + // The 20 Creepers spawn on three rings around the brain, evenly spread (no cluster a single sword arc clears). + var a=i/20*Math.PI*2,r=2.2+(i%3)*.55; + this.minions.push({id:++this.nextId,kind:'creeper',x:this.x+TR.cos(a)*r,y:this.y+TR.sin(a)*r,vx:0,vy:0,w:34/32,h:34/32, + hp:this.creeperHp,max_hp:this.creeperHp,dmg:this.creeperDmg,defense:10,knockbackResist:this.expert?.28:.2,floating:true, + drop:'creeper_heart',slot:a,ring:r,st:'orbit',t:0,debuffPool:this.expert?POOL:null,debuffChance:1}); + } + this.max_hp=this.brainMax+20*this.creeperHp;this.sync(); + this.go(c,'idle',0,'creeper_charge'); + }; + P.sync=function(){this.hp=this.brainHp+this.minions.reduce(function(a,m){return a+(m.kind==='creeper'?Math.max(0,m.hp):0);},0);}; + P.alive=function(){return this.minions.filter(function(m){return m.kind==='creeper'&&m.hp>0;});}; + // Phase 1: invulnerable; a teleporting brain is not solid until it has mostly faded in. + P.hitTargets=function(){return this.phase===1||this.fade<.5||this.st==='dead'?[]:[{id:'brain',box:this.bodyBox()}];}; + P.onNailHit=function(c,base,dir,f,id){ + if(this.phase===1||this.fade<.5||this.brainHp<=0)return null; + var hit=TR.rollDetails(c,base,this.defense,.5,.04);this.brainHp=Math.max(0,this.brainHp-hit.damage);this.hitFlash=.12; + TR.emitHit(c,'boss_hit',this.x,this.y,hit.damage,hit.critical);this.sync(); + if(!this.brainHp){this.hp=0;this.st='dead';this.minions=[];this.shots=[];c.emit('boss_dead',this.x,this.y);return 'flesh';} + // "The only boss that is affected by knockback" (Wiki trivia): phase-2 knockback resistance 55 % / 60 % + // (1.4.4). Arrow KB 2, sword KB 5; the push uses the shared NPC knockback rule on the brain's own velocity. + TR.enemyKnockback(c,this,hit.damage,hit.critical,{facing:f<0?-1:1,knockback:dir==='arrow'?TR.BODY.BOW_KB:TR.BODY.SWORD_KB}); + return 'flesh'; + }; + P.teleport=function(c,near){ + // A random spot around the player, away from the player and inside the arena (phase 1 keeps the safe radius). + var b=c.body.centre(),best=null; + for(var k=0;k<12;k++){ + var a=c.rng.uniform(0,Math.PI*2),r=near?c.rng.uniform(5,8):c.rng.uniform(7,11),x=b.x+TR.cos(a)*r,y=b.y+Math.abs(TR.sin(a))*r*.8+1; + if(x>this.w/2&&xthis.h/2+.5&&y.9||m.xBB.ARENA.W-m.w/2||m.yBB.ARENA.H-m.h/2){m.st='return';m.t=0;} + m.x=BB.clamp(m.x,m.w/2,BB.ARENA.W-m.w/2);m.y=BB.clamp(m.y,m.h/2,BB.ARENA.H-m.h/2); + }else{ + // Irregular circles around the brain: each Creeper has its own ring radius and a wobble. + var a=m.slot+self.orbitAngle,r=m.ring+TR.sin(self.orbitAngle*1.7+m.id)*.5; + var tx=self.x+TR.cos(a)*r,ty=self.y+TR.sin(a)*r; + TR.moveToward(m,tx,ty,(m.st==='return'?9:12)*self.pace.speed,m.st==='return'?30:60); + if(m.st==='return'&&Math.hypot(m.x-tx,m.y-ty)<.6)m.st='orbit'; + } + return true; + }); + }; + P.update=function(c){ + if(this.st==='dead')return;this.clock(c);var dt=BB.DT,b=c.body.centre();this.sync(); + this.fade=Math.min(1,this.fade+dt/(this.phase===1?.6:.35)); + if(this.phase===1){ + // Translucent and invulnerable: drift toward the player, then teleport away in a random direction. The drift + // stops short of the player so the orbiting ring cannot simply sit on them: Creepers reach the player by + // charging (the source behaviour), not by the ring overlapping a player the brain is parked next to. + var bx=b.x,by=b.y+1.5,dd=Math.hypot(this.x-bx,this.y-by),keep=4.5; + if(dd>keep)TR.moveToward(this,bx,by,2.4*TR.PX*this.pace.speed,4); + else{this.vx*=.9;this.vy*=.9;this.x=BB.clamp(this.x+this.vx*dt,this.w/2,BB.ARENA.W-this.w/2);this.y=BB.clamp(this.y+this.vy*dt,this.h/2,BB.ARENA.H-this.h/2);} + this.tpTimer+=dt; + if(this.tpTimer>=(this.expert?4:5.5)/this.pace.aggr){this.tpTimer=0;this.teleport(c,false);} + this.updateCreepers(c,b);this.sync(); + if(!this.alive().length){this.phase=2;this.tpTimer=0;this.go(c,'transform',.8,'teleport');c.emit('boss_escalate',this.x,this.y);} + return; + } + if(this.st==='transform'){this.vx=this.vy=0;if(this.timer<=0)this.go(c,'attack',0,'teleport');} + else{ + // Phase 2: visible heart. It closes in "at a steady pace" (Wiki tip) and its illusions "spread away from the + // real Brain if the player is walking away" -- so a walking player outpaces it; its threat is the rapid + // teleports around the player. Chase 3 px/tick (Expert 4) is below the 3 px/tick-plus run speed once tier + // aggression is applied (r6 round 2: at 4.5 px/tick a movement-only beam search died by 33 s on hard). + if(this.fade>=1)TR.moveToward(this,b.x,b.y,(this.expert?4:3)*TR.PX*this.pace.speed,this.expert?12:8); + this.tpTimer+=dt; + if(this.tpTimer>=(this.expert?2.4:3.2)/this.pace.aggr){this.tpTimer=0;this.teleport(c,true);} + } + // Expert illusions mirror the brain through the player; opacity rises as the brain's own health drops. + if(this.expert){var dx=this.x-b.x,dy=this.y-b.y; + this.illusions=[{x:b.x-dx,y:b.y+dy},{x:b.x+dx,y:b.y-dy},{x:b.x-dx,y:b.y-dy}].map(function(p){ + return {x:BB.clamp(p.x,.5,BB.ARENA.W-.5),y:BB.clamp(p.y,.5,BB.ARENA.H-.5)};}); + this.illusionAlpha=.25+.75*(1-this.brainHp/this.brainMax);} + this.minions=this.minions.filter(function(m){return m.hp>0;});this.sync(); + }; + P.hazards=function(){ + if(this.st==='dead')return []; + var out=[]; + // A fading brain cannot touch the player; it becomes solid as it finishes appearing. + if(this.fade>=.5){var h={kind:this.phase===1?'brain':'brain_heart',box:this.bodyBox(),dmg:this.dmg,fromX:this.x}; + if(this.expert&&this.phase===2){h.debuffPool=POOL;h.debuffChance=1/3;}out.push(h);} + return out.concat(TR.extraHazards(this)); + }; + BB.CASES['terraria/brain_of_cthulhu'] = TR.register('brain_of_cthulhu','Teleporting Flesh Brain',Brain,'crimson'); +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/bosses/eater_of_worlds.js b/environments/games/web/games/terraria_remake/bosses/eater_of_worlds.js new file mode 100644 index 0000000000000000000000000000000000000000..af96ae65ebe8fe46fca9d82311d9f21ecbba2a00 --- /dev/null +++ b/environments/games/web/games/terraria_remake/bosses/eater_of_worlds.js @@ -0,0 +1,170 @@ +(function(g){ + var BB=g.BB,TR=BB.TR,S=BB.SPECS.eater_of_worlds; + var EXPLOSIVES={grenade:1,sticky_grenade:1,bouncy_grenade:1,bomb:1,sticky_bomb:1,bouncy_bomb:1, + dynamite:1,sticky_dynamite:1,bouncy_dynamite:1,power_bomb:1,sticky_power_bomb:1,explosives:1, + explosive_bunny:1,confetti_grenade:1,bomb_fish:1,scarab_bomb:1,beenade:1,bee:1,giant_bee:1,tnt_barrel:1}; + var EXPLOSIVE_IDS={30:1,397:1,517:1,28:1,37:1,516:1,29:1,470:1,637:1,1086:1,1087:1, + 108:1,281:1,588:1,519:1,773:1,183:1,181:1,566:1,1002:1}; + function snap(v){return Math.floor(v/TR.TILE)*TR.TILE;} + function Eater(){} + var P=Eater.prototype;TR.boss(P,S); + P.stats=function(type){ + return {hp:TR.paceHp(this,this.expert?210:150,1),dmg:TR.paceDmg(this,this.expert?(type==='head'?48:type==='body'?21:18):(type==='head'?22:type==='body'?13:11)), + defense:(type==='head'?2:type==='body'?4:8)+(this.expert?2:0)}; + }; + P.reset=function(c){ + this.setup(c,20,-1,1.375,1.375);this.expert=this.k.expert>=.5;this.segments=[];this.chains=[]; + this.sourceProfile=this.expert?'desktop-expert':'desktop-classic';this.spacing=46/32; + // Tier aggression (tiers.js) scales top speed by sqrt(aggr) and steering by aggr; 1 at normal. + this.maxSpeed=16*(this.expert?1.2:1)*this.pace.speed;this.acceleration=(this.expert?16.875:7.875)*this.pace.aggr; + // The available reference gives ballistic peak heights (~31/44 tiles), rather than raw AI gravity. + // This approximation is constrained to those peaks; exact continuous steering remains documented. + this.airGravity=16*16/(31*TR.TILE*2);this.max_hp=0; + var n=Math.max(8,Math.round((this.expert?72:67)*this.pace.segments)),size=this.expert?1.2:1; + for(var i=0;i1){ + var first=run[0],prev=old.find(function(ch){return ch.ids[0]===first.id;}),newHead=first.type!=='head'; + run.forEach(function(s,n){self.retype(s,n===0?'head':n===run.length-1?'tail':'body');}); + // A surviving head keeps its momentum. Every new split head must fall and reach material first. + chains.push({ids:run.map(function(s){return s.id;}),st:prev?prev.st:'burrow',timer:0,digTimer:prev?prev.digTimer:0, + target:prev?prev.target:c.body.centre(),vx:prev?prev.vx:0,vy:prev?prev.vy:0, + forceFall:newHead||(!prev&&old.length>0)}); + }run=[]; + } + this.segments.forEach(function(s){if(s.hp>0)run.push(s);else finish();});finish();this.chains=chains; + this.hp=this.segments.reduce(function(a,s){return a+s.hp;},0); + if(!this.hp){this.st='dead';this.shots=[];c.emit('boss_dead',this.x,this.y);} + }; + P.hitTargets=function(){ + // Initial coiled segments are invisible but remain hittable, as in the source game. + return this.segments.filter(function(s){return s.hp>0&&s.y>-s.h/2;}).map(function(s){return {id:s.id,box:TR.box(s)};}); + }; + P.damageMultiplier=function(attack){ + var kind=typeof attack==='string'?attack:attack&&(attack.kind||attack.projectileKind), + id=attack&&typeof attack==='object'?attack.projectileId:null; + if(kind==='molotov_fire'||kind==='obsidian_swordfish_fire')return .65; + return this.expert&&(EXPLOSIVES[kind]||EXPLOSIVE_IDS[id])?.2:1; + }; + P.onNailHit=function(c,base,dir,f,id){ + var s=this.segments.find(function(v){return v.id===id;});if(!s||s.hp<=0)return null; + var hit=TR.rollDetails(c,base*this.damageMultiplier(dir),s.defense,0.5,0.04),damage=hit.damage; + s.hp=Math.max(0,s.hp-damage);this.hitFlash=.12;TR.emitHit(c,'boss_hit',s.x,s.y,damage,hit.critical); + if(!s.hp){if(TR.dropSegment)TR.dropSegment(c,this,s);c.emit('worm_split',s.x,s.y);this.rebuild(c);} + else this.hp=this.segments.reduce(function(a,v){return a+v.hp;},0); + return 'flesh'; + }; + P.inMaterial=function(c,s){ + var solid=function(x,y){return TR.solidAt?TR.solidAt(c,x,y,{platforms:true}):y<=0;}; + return solid(s.x,s.y)||solid(s.x,s.y-s.h/2)||solid(s.x-s.w/2,s.y)||solid(s.x+s.w/2,s.y); + }; + // Source worm steering (vanilla aiStyle 6, as mirrored by tModLoader ExampleMod WormHead): per-axis steps + // of `acceleration` toward the target direction, plus the source's anti-stall terms. When the head moves + // away from a nearly level/vertical target it curves along the other axis (x2 step); when it is slower than + // half its top speed it keeps pushing along its current sign. Without those terms a head below a target + // that is higher than its standing hop hovers at the surface forever (r4 bug). + // y is up here and down in the source, so a zero vertical velocity breaks toward "up" in both. + function toward(v,t,a){return vt?v-a:v;} + P.steerToward=function(ch,dirX,dirY){ + var speed=this.maxSpeed,acc=this.acceleration*BB.DT,len=Math.hypot(dirX,dirY),absX=Math.abs(dirX),absY=Math.abs(dirY),vx=ch.vx,vy=ch.vy; + if(len>0){dirX*=speed/len;dirY*=speed/len;} + if(len>0&&((vx>0&&dirX>0)||(vx<0&&dirX<0)||(vy>0&&dirY>0)||(vy<0&&dirY<0))){ + vx=toward(vx,dirX,acc);vy=toward(vy,dirY,acc); + if(Math.abs(dirY)0&&dirX<0)||(vx<0&&dirX>0)))vy+=vy<0?-acc*2:acc*2; + if(Math.abs(dirX)0&&dirY<0)||(vy<0&&dirY>0)))vx+=vx>0?acc*2:-acc*2; + }else if(absX>absY){ + vx=toward(vx,dirX,acc*1.1); + if(Math.abs(vx)+Math.abs(vy)0)vy=toward(vy,dirY,acc*1.1); + if(Math.abs(vx)+Math.abs(vy)0?acc:-acc; + } + ch.vx=vx;ch.vy=vy; + }; + // Out of material: constant gravity (fitted to the published peaks, EOW-05) and the source's horizontal + // terms: a slow head keeps accelerating along its sign, a head at terminal fall turns toward the target, + // a fast-falling head loses horizontal speed. dirX is the raw tile-snapped distance, compared in source px. + P.fall=function(ch,dirX){ + var speed=this.maxSpeed,acc=this.acceleration*BB.DT; + ch.vy=Math.max(-speed,ch.vy-this.airGravity*BB.DT); + if(Math.abs(ch.vx)+Math.abs(ch.vy)dpx)ch.vx-=acc;} + else if(ch.vy<-4*TR.PX)ch.vx+=ch.vx<0?acc*.9:-acc*.9; + }; + P.spitChance=function(s){return s.type==='head'?1/390+(1-s.hp/s.max_hp)*(1/90-1/390):s.type==='body'?1/900:0;}; + P.spitAllowed=function(c,s){ + if(s.hp<=0||s.type==='tail')return false; + var b=c.body.centre(); + if(TR.lineOfSight&&!TR.lineOfSight(c,s.x,s.y,b.x,b.y))return false; + if(s.type==='body'&&(s.y<=0||(TR.backgroundWallAt&&TR.backgroundWallAt(c,s.x,s.y))))return false; + return true; + }; + P.spit=function(c,s){ + TR.shoot(this,c,s.x,s.y,7*TR.PX,'vile_spit',false); + var shot=this.shots[this.shots.length-1];shot.sourceSegment=s.id;shot.dmg=TR.paceDmg(this,64);shot.destructible=true;shot.solidCollision=true;shot.collidePlatforms=true; + // Eater-specific Vile Spit is an NPC attack and has no Weak debuff since Desktop 1.4.2. + // Its 7 px/tick motion corresponds to the Wiki's rounded 36 mph. + c.emit('vile_spit',s.x,s.y); + }; + P.update=function(c){ + if(this.st==='dead')return;this.clock(c);var dt=BB.DT,b=c.body.centre(),lookup={},self=this; + this.segments.forEach(function(s){lookup[s.id]=s;}); + this.chains.forEach(function(ch){ + var head=lookup[ch.ids[0]],material=self.inMaterial(c,head),distance=Math.hypot(head.x-b.x,head.y-b.y), + far=Math.abs(head.x-b.x)>62.5*TR.TILE||Math.abs(head.y-b.y)>62.5*TR.TILE; + ch.digTimer-=dt; + if(material&&distance<25&&ch.digTimer<=0){ + c.emit('burrow_dig',head.x,head.y);ch.digTimer=BB.clamp(.1+distance*.026,.1,.75); + } + ch.target={x:b.x,y:b.y}; + if(material)ch.forceFall=false; + // The source compares tile-snapped centres (16 px = TR.TILE). + var dirX=snap(b.x)-snap(head.x),dirY=snap(b.y)-snap(head.y); + if((material||far)&&!ch.forceFall){self.steerToward(ch,dirX,dirY);ch.st='burrow';} + // No artificial pause or telegraph: outside tiles a worm follows a ballistic fall. + else{self.fall(ch,dirX);ch.st='lunge';} + head.vx=ch.vx;head.vy=ch.vy;head.x+=ch.vx*dt;head.y+=ch.vy*dt; + // Finite benchmark world margins allow a long chain to turn underground off-screen. + if(head.x< -4){head.x=-4;ch.vx=Math.abs(ch.vx);}if(head.x>BB.ARENA.W+4){head.x=BB.ARENA.W+4;ch.vx=-Math.abs(ch.vx);} + if(head.y< -20){head.y=-20;ch.vy=Math.abs(ch.vy);}if(head.y>BB.ARENA.H+10){head.y=BB.ARENA.H+10;ch.vy=-Math.abs(ch.vy);} + for(var n=1;nself.spacing){ + s.x=prev.x-sx/dist*self.spacing;s.y=prev.y-sy/dist*self.spacing;s.visible=true; + }else if(s.visible&&dist>1e-9){s.x=prev.x-sx/dist*self.spacing;s.y=prev.y-sy/dist*self.spacing;} + s.vx=(s.x-ox)/dt;s.vy=(s.y-oy)/dt; + } + }); + var leader=this.chains[0]; + if(leader){var head=lookup[leader.ids[0]];this.x=head.x;this.y=head.y;this.vx=head.vx;this.vy=head.vy; + this.st=leader.st==='burrow'?'recover':'attack';this.timer=0;this.target=leader.target;} + if(this.expert)this.segments.forEach(function(s){ + if(!self.spitAllowed(c,s))return;s.shotAttempts++; + if(c.rng.chance(self.spitChance(s)))self.spit(c,s); + }); + }; + P.hazards=function(){ + return this.st==='dead'?[]:this.segments.filter(function(s){return s.hp>0&&s.y>-s.h/2;}).map(function(s){ + return {kind:'worm_'+s.type,box:TR.box(s),dmg:s.dmg,fromX:s.x}; + }).concat(TR.extraHazards(this)); + }; + BB.CASES['terraria/eater_of_worlds'] = TR.register('eater_of_worlds','Burrowing Great Worm',Eater,'corruption'); +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/bosses/eye_of_cthulhu.js b/environments/games/web/games/terraria_remake/bosses/eye_of_cthulhu.js new file mode 100644 index 0000000000000000000000000000000000000000..1e5bfa79114c85e7151db706e90a5d2c43f975fb --- /dev/null +++ b/environments/games/web/games/terraria_remake/bosses/eye_of_cthulhu.js @@ -0,0 +1,125 @@ +(function(g){ + var BB=g.BB,TR=BB.TR,S=BB.SPECS.eye_of_cthulhu; + function Eye(){} + var P=Eye.prototype;TR.boss(P,S); + P.reset=function(c){ + this.setup(c,20,10,110/32,110/32); + this.expert=this.k.expert>=0.5;this.easyScale=1; + this.hp=this.max_hp=TR.paceHp(this,this.expert?3640:2800); + this.dmg=TR.paceDmg(this,this.expert?30:15);this.defense=12;this.phaseAt=this.expert?0.65:0.5; + this.k.hp=this.max_hp;this.k.dmg=this.dmg;this.k.phase_at=this.phaseAt; + this.k.def_factor=this.expert?0.75:0.5; + this.cycleIndex=0;this.dashesLeft=0;this.spawnTimer=0;this.servantsThisHover=0; + this.servantsPerHover=this.expert?5:4;this.pendingChain=false; + this.transformFrames=0;this.rotation=0;this.dashAge=0;this.dashFrames=0;this.dashFramesTotal=0;this.chainLevel=0; + this.recoverFrames=0;this.despawned=false;this.dawnDeparting=false; + this.startHover(c); + }; + P.startHover=function(c){ + this.move=null;this.dashesLeft=0;this.pendingChain=false; + this.servantsThisHover=0;this.spawnTimer=1.8/this.pace.aggr;this.hoverFrames=0; + this.go(c,'idle',this.hoverLimit()/60); + }; + // Tier aggression stretches hover and summon cadences and scales dash/hover speeds (tiers.js). + P.hoverLimit=function(){return Math.round((this.phase===1?600:this.expert?120:200)/this.pace.aggr);}; + P.spawnServant=function(c,angle){ + var b=c.body.centre(),dx=b.x-this.x,dy=b.y-this.y,l=Math.hypot(dx,dy)||1; + var vx=dx/l,vy=dy/l; + if(angle){var co=Math.cos(angle),si=Math.sin(angle),ox=vx;vx=ox*co-vy*si;vy=ox*si+vy*co;} + this.minions.push({id:++this.nextId,kind:'servant',x:this.x+vx*this.w/2,y:this.y+vy*this.h/2, + vx:vx*5*TR.PX*this.pace.speed,vy:vy*5*TR.PX*this.pace.speed,w:20/32,h:20/32,hp:this.expert?12:8,max_hp:this.expert?12:8, + dmg:TR.paceDmg(this,this.expert?24:12),defense:0,drop:'heart_star',floating:true,knockbackResist:this.expert?0.1:0}); + c.emit('servant_spawn',this.x,this.y); + }; + P.startDashes=function(c,chain){ + this.move=chain?'chain_dash':'dash';this.dashesLeft=chain?5:3; + this.chainLevel=this.expert&&this.phase===2?(this.hp/this.max_hp<0.04?2:this.hp/this.max_hp<0.12?1:0):0; + this.launch(c); + }; + P.launch=function(c){ + var b=c.body.centre(),chain=this.move==='chain_dash'; + if(chain)this.chainLevel=this.hp/this.max_hp<0.04?2:this.hp/this.max_hp<0.12?1:0; + // A charge commits to one vector. Only rapid charges lead the moving target. + var lead=chain?(this.chainLevel===2?0.25:0.12):0; + this.target={x:b.x+(c.body.vx||0)*lead,y:b.y+(c.body.vy||0)*lead}; + var dx=this.target.x-this.x,dy=this.target.y-this.y,l=Math.hypot(dx,dy)||1; + var speed=(chain?(this.chainLevel===2?20:16):this.phase===2?6.8:6)*TR.PX*this.pace.speed; + if(!chain&&this.expert)speed*=1.15; + this.vx=dx/l*speed;this.vy=dy/l*speed;this.dashAge=0;this.dashFrames=0; + this.dashFramesTotal=chain?(this.chainLevel===2?21:this.chainLevel===1?29:39):150; + this.go(c,'attack',this.dashFramesTotal/60,this.move); + c.emit(chain?'eye_chain_roar':'eye_roar',this.x,this.y); + }; + P.pauseCharges=function(c,frames){frames=Math.round(frames/this.pace.aggr);this.recoverFrames=frames;this.go(c,'recover',frames/60);}; + P.updateServants=function(c,b){ + this.minions=this.minions.filter(function(m){ + if(m.hp<=0){if(TR.dropMinion)TR.dropMinion(c,this,m);return false;} + TR.moveToward(m,b.x,b.y,(this.expert?7:6)*TR.PX*this.pace.speed,12);return true; + },this); + }; + P.updateArmor=function(){ + if(this.phase===1){this.defense=12;this.dmg=TR.paceDmg(this,this.expert?30:15);return;} + var frac=this.hp/this.max_hp; + this.defense=this.expert&&frac<0.04?-30:this.expert&&frac<0.12?-15:0; + this.dmg=TR.paceDmg(this,this.expert?(frac<0.04?40:36):23); + }; + P.onNailHit=function(c,base,dir,f,id){this.updateArmor();return TR.damageBoss(this,c,base,id);}; + P.update=function(c){ + if(this.st==='dead'||this.despawned)return;this.clock(c);var dt=BB.DT,b=c.body.centre(); + if(TR.isDaytime&&TR.isDaytime(c)&&!this.dawnDeparting){ + this.dawnDeparting=true;this.st='despawn';this.timer=1e9;this.stT=0;this.move=null; + this.vy=Math.max(4*TR.PX,this.vy);c.emit('eye_dawn_flee',this.x,this.y); + } + if(this.dawnDeparting){ + // Night-only bosses depart upward rather than vanishing in place when dawn arrives. + this.vx*=0.98;this.vy=Math.min(10*TR.PX,this.vy+0.2*TR.PG*dt); + this.x+=this.vx*dt;this.y+=this.vy*dt;this.updateServants(c,b); + if(this.y-this.h/2>BB.ARENA.H){this.despawned=true;this.minions=[];this.shots=[];c.emit('eye_dawn_despawn',this.x,this.y);} + return; + } + // Mode gates are discrete. At exactly the threshold the original first form remains active. + if(this.phase===1&&this.hp/this.max_hp=this.hoverLimit())this.startDashes(c,this.expert&&this.phase===2&&this.hp/this.max_hp<0.12); + }else if(this.st==='transform'){ + this.vx=this.vy=0;this.transformFrames++;this.rotation+=Math.max(0,100-Math.abs(100-this.transformFrames))*0.005; + // The original Eye remains vulnerable during the transformation. + if(this.transformFrames>=200)this.startDashes(c,false); + }else if(this.st==='attack'){ + this.dashFrames++;this.dashAge=this.dashFrames/60; + if(this.move==='dash'&&this.dashFrames>40){this.vx*=0.98;this.vy*=0.98;} + this.x=BB.clamp(this.x+this.vx*dt,this.w/2,BB.ARENA.W-this.w/2); + this.y=BB.clamp(this.y+this.vy*dt,this.h/2,BB.ARENA.H-this.h/2); + if(this.dashFrames>=this.dashFramesTotal){ + this.dashesLeft--; + if(this.dashesLeft>0)this.pauseCharges(c,this.move==='chain_dash'?(this.chainLevel===2?1:this.chainLevel===1?5:12):1); + else if(this.expert&&this.phase===2){ + if(this.move==='dash'){this.pendingChain=true;this.pauseCharges(c,21);} + else if(this.hp/this.max_hp<0.12){this.pendingChain=true;this.pauseCharges(c,this.hp/this.max_hp<0.04?1:7);} + else this.startHover(c); + }else this.startHover(c); + } + }else if(this.st==='recover'){ + this.vx*=0.98;this.vy*=0.98; + this.recoverFrames--; + if(this.recoverFrames<=0){if(this.pendingChain){this.pendingChain=false;this.startDashes(c,true);}else this.launch(c);} + } + this.updateServants(c,b); + }; + P.hazards=function(){return this.st==='dead'||this.despawned?[]:[{kind:this.phase===2?'maw':'eye',box:this.bodyBox(),dmg:this.dmg,fromX:this.x}].concat(TR.extraHazards(this));}; + BB.CASES['terraria/eye_of_cthulhu'] = TR.register('eye_of_cthulhu','Charging Giant Eye',Eye,'night'); +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/bosses/king_slime.js b/environments/games/web/games/terraria_remake/bosses/king_slime.js new file mode 100644 index 0000000000000000000000000000000000000000..57e6fe6aed13ef4e7d439ec910c783c6269e3b4e --- /dev/null +++ b/environments/games/web/games/terraria_remake/bosses/king_slime.js @@ -0,0 +1,132 @@ +(function(g){ + var BB=g.BB,TR=BB.TR,S=BB.SPECS.king_slime; + // Desktop 1.4.5.8, ordinary single-player Classic / Expert, without secret seeds. + // Units retain the common 32 source pixels per world unit and 60 simulation ticks per second. + var W=122.5/32,H=115/32,GRAVITY=0.3*TR.PG; + function KingSlime(){} + var P=KingSlime.prototype;TR.boss(P,S); + P.reset=function(c){ + this.setup(c,21,H/2,W,H);this.expert=this.k.expert>=0.5; + this.hp=this.max_hp=TR.paceHp(this,this.expert?2800:2000);this.dmg=TR.paceDmg(this,this.expert?64:40);this.defense=10; + this.jumpIndex=0;this.floor=0;this.groundTicks=0;this.teleportWait=0; + this.spawnMark=this.max_hp;this.teleportScale=1;this.hidden=false;this.invulnerable=false; + this.go(c,'idle',1);this.sourceProfile=this.expert?'desktop-expert':'desktop-classic'; + }; + P.jumpCooldown=function(){ + var f=this.hp/this.max_hp,i=f>=.8?0:f>=.6?1:f>=.4?2:f>=.2?3:f>=.1?4:5; + // Tier aggression stretches the source cooldown frames (tiers.js); 1 at normal and above. + return Math.round((this.move==='high_jump'?[100,67,50,34,23,16]:[60,40,30,20,14,10])[i]/this.pace.aggr); + }; + P.resize=function(){ + var bottom=this.y-this.h/2,size=(.6+.4*this.hp/this.max_hp)*this.teleportScale; + this.w=W*size;this.h=H*size;this.y=bottom+this.h/2; + }; + P.slime=function(c,blueOnly){ + var spike=!blueOnly&&this.expert&&c.rng.chance(.25),kind=spike?'spiked_slime':'slime'; + // Sourced ordinary pre-Hardmode NPC statistics; volley timing remains provisional. + var m={id:++this.nextId,kind:kind,x:this.x+c.rng.uniform(-this.w*.35,this.w*.35), + y:Math.max(.3,this.y-this.h*.25),vx:c.rng.uniform(-2,2),vy:c.rng.uniform(3,5), + w:.75,h:.5,hp:spike?100:this.expert?50:25,max_hp:spike?100:this.expert?50:25, + defense:spike?5:2,dmg:TR.paceDmg(this,spike?28:this.expert?14:7),knockbackResist:spike||this.expert?.1:0, + aggressive:spike,face:c.rng.chance(.5)?1:-1,drop:'heart_star',timer:c.rng.uniform(.1,.6),spikeTimer:c.rng.uniform(.8,1.5)}; + this.minions.push(m);c.emit(spike?'spiked_slime_spawn':'slime_spawn',m.x,m.y); + }; + P.onNailHit=function(c,base,dir,f,part){ + if(this.invulnerable||this.hidden||this.st==='dead')return null; + var old=this.hp,result=TR.damageBoss(this,c,base,part); + if(this.hp===old)return result; + if(!this.hp){var deathCount=4+c.rng.int(4);for(var j=0;j125*TR.TILE)return {x:b.x,y:c.body.y}; + var surfaces=[[0,BB.ARENA.W,0]].concat(TR.platforms(c)); + function candidates(lo,hi){ + var result=[];surfaces.forEach(function(p){ + for(var x=Math.max(.5,p[0]);x<=Math.min(BB.ARENA.W-.5,p[1]);x+=TR.TILE){ + var d=Math.max(Math.abs(x-b.x),Math.abs(p[2]-b.y)); + if(d>=lo*TR.TILE&&d<=hi*TR.TILE&&los(x,p[2]+self.h/2)&& + (!TR.solidAt||!TR.solidAt(c,x,p[2]+TR.TILE,{platforms:true})))result.push({x:x,y:p[2]}); + } + });return result; + } + var spots=candidates(7,10);if(!spots.length)spots=candidates(2,6); + return spots.length?spots[c.rng.int(spots.length)]:{x:b.x,y:c.body.y}; + }; + P.startTeleport=function(c){ + this.target=this.teleportSpot(c);this.move='teleport';this.teleportWait=0;this.vx=this.vy=0; + this.go(c,'antic',1,'teleport');c.emit('teleport_disappear',this.x,this.y); + }; + P.jump=function(c){ + this.move=['jump','jump','low_jump','high_jump'][this.jumpIndex++%4]; + this.f=c.body.x>=this.x?1:-1;this.target=c.body.centre(); + this.vx=this.f*(this.move==='low_jump'?4.5:this.move==='high_jump'?3.5:4)*TR.PX; + this.vy=(this.move==='low_jump'?6:this.move==='high_jump'?13:8)*TR.PX; + this.go(c,'attack',0,this.move); + }; + P.updateMinions=function(c){ + var dt=BB.DT,b=c.body.centre(),self=this; + this.minions=this.minions.filter(function(m){ + if(m.hp<=0)return false;var oldFeet=m.y-m.h/2;m.timer-=dt;m.spikeTimer-=dt; + m.vy=Math.max(-10*TR.PX,m.vy-GRAVITY*dt);m.x=BB.clamp(m.x+m.vx*dt,m.w/2,BB.ARENA.W-m.w/2);m.y+=m.vy*dt; + var ground=0;TR.platforms(c).forEach(function(p){if(m.x>=p[0]&&m.x<=p[1]&&oldFeet>=p[2]&&m.y-m.h/2<=p[2]&&m.vy<=0&&c.body.y>=p[2])ground=Math.max(ground,p[2]);}); + if(m.y-m.h/2<=ground){ + m.y=ground+m.h/2;m.vy=0;m.vx*=.8; + if(m.kind==='spiked_slime'&&Math.hypot(b.x-m.x,b.y-m.y)<7&&m.spikeTimer<=0){ + for(var k=-1;k<=1;k++){var dx=b.x-m.x,dy=b.y-m.y,a=Math.atan2(dy,dx)+k*.22; + self.shots.push({id:++self.nextId,kind:'slime_spike',x:m.x,y:m.y,vx:Math.cos(a)*9,vy:Math.sin(a)*9, + r:.12,life:5,dmg:TR.paceDmg(self,36),gravity:9,solidCollision:true,collidePlatforms:false,sourceMinion:m.id});} + m.spikeTimer=1.5;c.emit('slime_spikes',m.x,m.y); + } + if(m.timer<=0){ + if(m.aggressive||m.hp=m.x?1:-1; + m.vy=6*TR.PX;m.vx=m.face*2*TR.PX;m.timer=1; + } + } + return true; + }); + }; + P.update=function(c){ + if(this.st==='dead')return;this.clock(c);var dt=BB.DT; + var obstructed=TR.lineOfSight&&!TR.lineOfSight(c,this.x,this.y,c.body.x,c.body.y+.65); + var teleporting=this.move==='teleport'&&(this.st==='antic'||this.st==='recover'); + if(!teleporting&&(obstructed||Math.abs(c.body.y-(this.y+this.h/2))>10*TR.TILE))this.teleportWait+=dt; + // Timer pauses when reachable and is consumed only once King Slime is grounded. + if(teleporting){ + if(this.st==='antic'){ + this.teleportScale=Math.max(.02,Math.max(0,this.timer));this.resize(); + this.hidden=this.timer<=1e-9;this.invulnerable=this.hidden; + if(this.timer<=1e-9){this.x=this.target.x;this.floor=this.target.y;this.y=this.floor+this.h/2; + this.go(c,'recover',.5,'teleport');c.emit('teleport',this.x,this.floor);} + }else{ + this.hidden=false;this.invulnerable=false;this.teleportScale=BB.clamp(1-this.timer/.5,.02,1);this.resize(); + if(this.timer<=1e-9){this.teleportScale=1;this.resize();this.jumpIndex=0;this.groundTicks=0;this.move=null;this.go(c,'idle',1);} + } + }else if(this.st==='attack'){ + var feet=this.y-this.h/2;this.vy=Math.max(-10*TR.PX,this.vy-GRAVITY*dt); + this.x=BB.clamp(this.x+this.vx*dt,this.w/2,BB.ARENA.W-this.w/2);this.y+=this.vy*dt; + var floor=0;TR.platforms(c).forEach(function(p){ + if(this.vy<=0&&this.x+this.w/2>p[0]&&this.x-this.w/2=p[2]&&this.y-this.h/2<=p[2]&&c.body.y>=p[2]-.1)floor=Math.max(floor,p[2]); + },this); + if(this.y-this.h/2<=floor){this.floor=floor;this.y=floor+this.h/2;this.vx=this.vy=0;this.groundTicks=0; + this.go(c,'recover',this.jumpCooldown()/60);c.emit('boss_land_hard',this.x,this.floor);} + }else{ + this.y=this.floor+this.h/2;this.groundTicks++;this.timer=Math.max(0,(this.jumpCooldown()-this.groundTicks)/60); + if(this.floor>0&&c.body.y=5/this.pace.aggr-1e-9)this.startTeleport(c);else if(!this.timer)this.jump(c); + } + this.updateMinions(c); + }; + P.hazards=function(){ + if(this.st==='dead')return []; + var contact=this.hidden?[]:[{kind:'king_slime',box:this.bodyBox(),dmg:this.dmg,fromX:this.x}]; + return contact.concat(TR.extraHazards(this)); + }; + BB.CASES['terraria/king_slime'] = TR.register('king_slime','Bouncing Gel Giant',KingSlime,'forest'); +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/bosses/kit.js b/environments/games/web/games/terraria_remake/bosses/kit.js new file mode 100644 index 0000000000000000000000000000000000000000..334bee8f1fdce39bada8a2906ddf515749fd6f48 --- /dev/null +++ b/environments/games/web/games/terraria_remake/bosses/kit.js @@ -0,0 +1,24 @@ +(function(g){ + var BB=g.BB,TR=BB.TR;BB.CASES=BB.CASES||{}; + TR.boss=function(P,spec){ + BB.bossKit(P,spec,{idle:'idle',antic:'telegraph',attack:'active',recover:'recovery',transform:'telegraph',dead:'recovery'}); + P.setup=function(c,x,y,w,h){ + this.k=BB.knobs(spec.difficulty,c.d>=.75?1:.5);this.pace=TR.pace(c,spec.id);this.hp=this.max_hp=Math.round(this.k.hp);this.dmg=Math.round(this.k.dmg);this.defense=this.k.defense||0; + this.x=x;this.y=y;this.w=w;this.h=h;this.vx=0;this.vy=0;this.f=-1; + this.st='idle';this.timer=0.8;this.stT=0;this.move=null;this.phase=1;this.hitFlash=0;this.track={};this.cycle={};this.stamp=0;this.lastActive=null; + this.minions=[];this.shots=[];this.pickups=[];this.nextId=0;this.target={x:x,y:y}; + var dawn=c.options&&c.options.dawn_in_seconds; + this.nightTicks=Number.isFinite(dawn)?32400-BB.clamp(dawn,0,540)*60:0; + }; + P.bodyBox=function(){return TR.box(this);}; + P.onNailHit=function(c,base,dir,f,part){return TR.damageBoss(this,c,base,part);}; + P.state=function(){var role=this.role();return TR.snapshot(this,{fsm:this.st,role:role,telegraph_left:role==='telegraph'?BB.r4(Math.max(0,this.timer)):0,hazards:this.hazards()});}; + P.begin=function(c,move,target){this.target=target||c.body.centre();this.move=move;this.go(c,'antic',this.k.telegraph,move);}; + P.recover=function(c,scale){this.vx=this.vy=0;this.go(c,'recover',this.k.recovery*(scale||1));}; + P.clock=function(c){this.flash(BB.DT);this.timer-=BB.DT;this.stT+=BB.DT;this.nightTicks++;TR.updateShots(this,c);}; + }; + TR.register=function(id,title,Boss,arena,platforms){ + BB.CASES=BB.CASES||{}; + return {title:title,Body:BB.Adventurer,Boss:Boss,arena:arena,platforms:platforms||[[2,25,2.4],[4,23,5.3]]}; + }; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/bosses/queen_bee.js b/environments/games/web/games/terraria_remake/bosses/queen_bee.js new file mode 100644 index 0000000000000000000000000000000000000000..5d706368deac2fd99bdd20b23cde8e618c0bbfb7 --- /dev/null +++ b/environments/games/web/games/terraria_remake/bosses/queen_bee.js @@ -0,0 +1,135 @@ +(function(g){ + var BB=g.BB,TR=BB.TR,S=BB.SPECS.queen_bee; + // Desktop 1.4.5.8 ordinary single-player Classic / Expert Queen Bee (aiStyle 43). + // Published: life 3400/4760, contact 30/54, stinger 22/44, defense 8 (Expert 8-28 with lost health), knockback + // immune, 120 % scale, the opening attack is always the triple charge, 6/12/18 bees, Poisoned on stingers 1/3 10 s + // (Expert 100 % 2-20 s, contact 2-8 s). Unpublished (estimates): charge/stinger speeds, + // intervals, stinger count, hover offsets and the Expert speed-up curve. + var W=66/32*1.2,H=66/32*1.2; + function QueenBee(){} + var P=QueenBee.prototype;TR.boss(P,S); + P.reset=function(c){ + this.setup(c,21,10,W,H);this.expert=this.k.expert>=.5; + this.hp=this.max_hp=TR.paceHp(this,this.expert?4760:3400);this.dmg=TR.paceDmg(this,this.expert?54:30); + this.stingerDmg=TR.paceDmg(this,this.expert?44:22);this.defense=8; + this.knockbackResist=1;this.sourceProfile=this.expert?'desktop-expert':'desktop-classic'; + this.chargesLeft=0;this.side=1;this.cycleIndex=0;this.volleyLeft=0;this.volleyTimer=0;this.beeBatch=0;this.beesLeft=0; + this.hoverT=0;this.lockY=null;this.charge=null;this.hold=0;this.align=0;this.spawnTimer=0; + // The source opening attack: always the horizontal charge first. + this.startCharges(c); + }; + // Expert grows faster and more relentless as health drops (published qualitatively; this 0..1 curve is ours). + P.rage=function(){return this.expert?BB.clamp(1-this.hp/this.max_hp,0,1):0;}; + P.updateArmor=function(){this.defense=this.expert?8+Math.round(20*this.rage()):8;}; + P.startCharges=function(c){ + var r=this.rage();this.chargesLeft=this.expert?(r>=.9?6:r>=.75?5:r>=.5?4:3):3; + this.side=c.body.x>=this.x?-1:1;this.move='charge';this.go(c,'antic',0,'charge');this.align=0; + }; + // Charge speed px/tick: 18 Classic (3x the player's 6 px/tick sprint cap), Expert 18 -> 27 as health drops. + // Unlike chase speeds, the committed charge does not scale with tier aggression: a charge is a dodge test + // decided by its height lock, and at 20.5 px/tick (hard x sqrt(1.3)) a movement-only beam search kept only + // 75/200 HP over the opening 20 s versus 164 at normal (r6 round 1, qb_charge_beam.js). Hard raises cadence + // (shorter alignment and recovery), damage and health instead. + P.chargeSpeed=function(){return (18+9*this.rage())*TR.PX;}; + // How long she holds the lined-up pose before a charge (estimate; the source game shows a brief pause while she + // lines up). Expert shortens it as health drops; tier aggression shortens it, never below 0.15 s. + P.windup=function(){return Math.max(.15,(this.expert?.32-.14*this.rage():.32)/this.pace.aggr);}; + P.nextAttack=function(c){ + // After the opening charges the source cycles through its three patterns; ours: summon, stingers, charge. + var order=['summon','stingers','charge'],next=order[this.cycleIndex++%3]; + if(next==='charge')this.startCharges(c); + else if(next==='summon'){ + this.move='summon';this.beeBatch=[6,12,18][c.rng.int(3)];this.beesLeft=this.beeBatch;this.spawnTimer=.35/this.pace.aggr; + this.hoverT=0;this.go(c,'idle',0,'summon');c.emit('queen_bee_buzz',this.x,this.y); + }else{ + this.move='stingers';this.volleyLeft=this.expert?12:8;this.volleyTimer=.7/this.pace.aggr;this.hoverT=0; + this.go(c,'recover',0,'stingers'); + } + }; + P.spawnBee=function(c){ + var big=this.expert&&c.rng.chance(.3),hp=big?24:this.expert?12:10,dmg=TR.paceDmg(this,big?24:this.expert?18:15); + var a=c.rng.uniform(0,Math.PI*2); + this.minions.push({id:++this.nextId,kind:big?'big_bee':'bee',x:this.x,y:this.y-H*.3,vx:TR.cos(a)*3,vy:TR.sin(a)*3, + w:big?.6:.45,h:big?.6:.45,hp:hp,max_hp:hp,dmg:dmg,defense:big?5:2,knockbackResist:.5,floating:true,drop:'heart_star', + debuff:this.expert?'poisoned':null,debuffChance:1,debuffDuration:[2,6],life:12}); + c.emit('bee_spawn',this.x,this.y); + }; + P.fireStinger=function(c){ + var b=c.body.centre(),dx=b.x-this.x,dy=b.y-(this.y-H*.35),u=TR.dir(dx,dy,c.rng.uniform(-.06,.06)),speed=(this.expert?15:12)*TR.PX*this.pace.speed; + this.shots.push({id:++this.nextId,kind:'bee_stinger',x:this.x,y:this.y-H*.35,vx:u.x*speed,vy:u.y*speed,speed:speed, + r:.16,life:4,dmg:this.stingerDmg,solidCollision:true,collidePlatforms:false, + debuff:'poisoned',debuffChance:this.expert?1:1/3,debuffDuration:this.expert?[2,20]:[10,10]}); + c.emit('bee_stinger',this.x,this.y); + }; + P.updateBees=function(c,b){ + var dt=BB.DT,self=this; + this.minions=this.minions.filter(function(m){ + if(m.hp<=0){if(TR.dropMinion)TR.dropMinion(c,self,m);return false;} + m.life-=dt;if(m.life<=0)return false; + // Bees home in with a little wobble; they stay inside the arena. + var wob=TR.sin((c.t+m.id*17)*.15)*.8; + TR.moveToward(m,b.x+wob,b.y+.3,(m.kind==='big_bee'?6:7.5)*self.pace.speed,14);return true; + }); + }; + P.update=function(c){ + if(this.st==='dead')return;this.clock(c);var dt=BB.DT,b=c.body.centre(),self=this; + this.updateArmor(); + if(this.move==='charge'){ + var sp=this.chargeSpeed(),edge=BB.ARENA.W-this.w/2; + if(this.st==='antic'){ + // Line up beside the player at the player's height, then commit to a horizontal dash. Once lined up she + // locks that height and hangs for a beat (the readable windup) before charging along exactly that lane, so + // the pause shows the lane the hitbox will travel (r6 round 3: re-tracking a flying player during the hold + // kept resetting it, the charge came on the 2.56 s timeout instead and easy fights spread over 22-34 s). + var tx=BB.clamp(b.x+this.side*9,this.w/2,edge),ty=BB.clamp(b.y,this.h/2,BB.ARENA.H-this.h/2); + if(this.hold>0){ + this.vx*=.8;this.vy=0;this.x=BB.clamp(this.x+this.vx*dt,this.w/2,edge);this.y=this.lockY;this.hold+=dt; + }else{ + TR.moveToward(this,tx,ty,(16+6*this.rage())*TR.PX*this.pace.speed,60*this.pace.aggr); + this.align+=dt; + if(Math.abs(this.y-ty)<.45&&Math.abs(this.x-tx)<2.2){this.hold=dt;this.lockY=this.y;this.vy=0;} + } + if(this.hold>=this.windup()||this.align>1.6/this.pace.aggr+this.windup()){ + this.hold=0;this.f=b.x>=this.x?1:-1;this.vx=this.f*sp;this.vy=0;this.lockY=this.y;this.go(c,'attack',0,'charge');c.emit('queen_bee_charge',this.x,this.y); + } + }else if(this.st==='attack'){ + this.x+=this.vx*dt;this.y=this.lockY; + // A charge ends past the player (or at the wall); she brakes and turns for the next one. + var past=this.f>0?this.x>b.x+6:this.x=edge){ + this.x=BB.clamp(this.x,this.w/2,edge);this.chargesLeft--;this.vx*=.3; + if(this.chargesLeft>0){this.side=this.f;this.go(c,'recover',(this.expert?.18:.3)/this.pace.aggr,'charge');} + else{this.go(c,'recover',.5/this.pace.aggr,'charge_end');} + } + }else if(this.st==='recover'){ + this.vx*=.85;this.x=BB.clamp(this.x+this.vx*dt,this.w/2,edge); + if(this.timer<=0){if(this.move==='charge'){this.f=b.x>=this.x?1:-1;this.go(c,'antic',0,'charge');this.align=0;}} + } + }else if(this.move==='charge_end'){ + this.vx*=.85;this.x=BB.clamp(this.x+this.vx*dt,this.w/2,BB.ARENA.W-this.w/2); + if(this.timer<=0)this.nextAttack(c); + }else if(this.move==='summon'){ + // Hover above the player and release the batch over time. + TR.moveToward(this,b.x,Math.min(BB.ARENA.H-this.h/2,b.y+6),7*TR.PX*this.pace.speed,8); + this.hoverT+=dt;this.spawnTimer-=dt; + if(this.beesLeft>0&&this.spawnTimer<=0){this.spawnBee(c);this.beesLeft--;this.spawnTimer=(this.expert?.16:.22)/this.pace.aggr;} + if(this.beesLeft<=0&&this.hoverT>.6)this.nextAttack(c); + }else if(this.move==='stingers'){ + // Hornet-like: drift above and to the side of the player and fire stingers down at them. + this.hoverT+=dt;var sway=TR.sin(this.hoverT*1.4)*6; + TR.moveToward(this,BB.clamp(b.x+sway,this.w/2,BB.ARENA.W-this.w/2),Math.min(BB.ARENA.H-this.h/2,b.y+5.5),9*TR.PX*this.pace.speed,10); + this.volleyTimer-=dt; + if(this.volleyTimer<=0&&this.volleyLeft>0){this.fireStinger(c);this.volleyLeft--;this.volleyTimer=(this.expert?.32-.12*this.rage():.45)/this.pace.aggr;} + if(this.volleyLeft<=0&&this.volleyTimer<=-.4)this.nextAttack(c); + } + this.updateBees(c,b); + }; + P.onNailHit=function(c,base,dir,f,id){this.updateArmor();return TR.damageBoss(this,c,base,id);}; + P.hazards=function(){ + if(this.st==='dead')return []; + var body={kind:this.move==='charge'&&this.st==='attack'?'queen_bee_charge':'queen_bee',box:this.bodyBox(),dmg:this.dmg,fromX:this.x}; + if(this.expert){body.debuff='poisoned';body.debuffChance=1;body.debuffDuration=[2,8];} + return [body].concat(TR.extraHazards(this)); + }; + BB.CASES['terraria/queen_bee'] = TR.register('queen_bee','Charging Giant Bee',QueenBee,'hive'); +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/bosses/skeletron.js b/environments/games/web/games/terraria_remake/bosses/skeletron.js new file mode 100644 index 0000000000000000000000000000000000000000..e8724b06a2948ac71a77fd9e9b1e60d3f76d0680 --- /dev/null +++ b/environments/games/web/games/terraria_remake/bosses/skeletron.js @@ -0,0 +1,110 @@ +(function(g){ + var BB=g.BB,TR=BB.TR,S=BB.SPECS.skeletron; + function Skeletron(){} + var P=Skeletron.prototype;TR.boss(P,S); + P.reset=function(c){ + this.setup(c,18,10.5,80/32,102/32);this.expert=this.k.expert>=0.5;this.easyScale=1; + this.hp=this.max_hp=TR.paceHp(this,this.expert?8800:4400);this.dmg=TR.paceDmg(this,this.expert?70:32); + this.k.hp=this.max_hp;this.k.dmg=this.dmg;this.k.def_factor=this.expert?0.75:0.5; + this.k.hand_hp=TR.paceHp(this,this.expert?1560:600);this.skullTimer=80/60;this.skullFrames=0;this.headFrames=0; + this.handIndex=0;this.enraged=false;this.spinSpeed=0; + // Tier aggression stretches the hover / hand cadences and scales chase and hand speeds (tiers.js). + this.hoverFrames=Math.round(800/this.pace.aggr);this.handGap=Math.round((this.expert?200:300)/this.pace.aggr); + var offset=Math.round((this.expert?100:150)/this.pace.aggr); + this.hands=[-1,1].map(function(side,n){return {id:'hand'+n,side:side,x:18+side*3,y:7.8,vx:0,vy:0, + w:52/32,h:52/32,hp:this.k.hand_hp,max_hp:this.k.hand_hp,defense:14,st:'idle',timer:0, + wait:n*offset/60,waitFrames:n*offset,attackIndex:n,target:{x:0,y:0}};},this); + this.go(c,'idle',this.hoverFrames/60);this.defense=this.armor(); + }; + P.hitTargets=function(){return [{id:'head',box:this.bodyBox()}].concat(this.hands.filter(function(h){return h.hp>0;}) + .map(function(h){return {id:h.id,box:TR.box(h)};}));}; + P.armor=function(){return this.enraged?9999:(this.st==='attack'?0:10)+ + (this.expert?this.hands.filter(function(h){return h.hp>0;}).length*25:0);}; + P.onNailHit=function(c,base,dir,f,id){ + if(this.hp<=0)return null;var hand=this.hands.find(function(h){return h.id===id;}); + if(hand){ + if(hand.hp<=0)return null; + var hit=TR.rollDetails(c,base,14,0.5,0.04);hand.hp=Math.max(0,hand.hp-hit.damage);TR.emitHit(c,'boss_hit',hand.x,hand.y,hit.damage,hit.critical); + if(!hand.hp)c.emit('hand_destroyed',hand.x,hand.y);this.defense=this.armor();return 'flesh'; + } + this.defense=this.armor();return TR.damageBoss(this,c,base,id); + }; + P.chaseSpeed=function(b){ + var alive=this.hands.filter(function(h){return h.hp>0;}).length,speed=2*TR.PX*this.pace.speed; + if(this.expert){ + speed*=10/3;speed*=1+(2-alive)*0.05; + var tiles=Math.hypot(this.x-b.x,this.y-b.y)/TR.TILE; + if(tiles>=9.375)speed*=Math.min(2.6,Math.pow(1.1,Math.floor((tiles-9.375)/3.125)+1)); + }return speed; + }; + P.spawnSkull=function(c){ + TR.shoot(this,c,this.x,this.y,3*TR.PX,'homing_skull',true); + var p=this.shots[this.shots.length-1];p.dmg=TR.paceDmg(this,68);p.solidCollision=true;p.collidePlatforms=false;p.life=10; + }; + P.beginHand=function(c,h,b){ + h.attackIndex++;h.attackAxis=h.attackIndex%2?'vertical':'horizontal'; + h.target={x:b.x,y:b.y};h.st='antic';h.timer=0; + c.emit(h.attackAxis==='vertical'?'hand_vertical_antic':'hand_horizontal_antic',h.x,h.y); + }; + P.updateHand=function(c,h,b){ + if(h.hp<=0)return;var dt=BB.DT,speedMul=(this.expert?1.16:1)*this.pace.speed;h.timer-=dt; + if(this.st==='attack'){ + h.st='idle';TR.moveToward(h,this.x+h.side*3.2,this.y-2.8,(this.expert?8:5)*TR.PX*this.pace.speed,35);return; + } + if(h.st==='idle'){ + h.waitFrames++;h.wait=h.waitFrames/60;TR.moveToward(h,this.x+h.side*3.2,this.y-2.8,(this.expert?8:5)*TR.PX*this.pace.speed,25); + if(h.waitFrames>=this.handGap){h.wait=0;h.waitFrames=0;this.beginHand(c,h,b);} + }else if(h.st==='antic'){ + // Preparation is physical alignment, not an added stationary telegraph timer. + var ax=h.attackAxis==='vertical'?b.x:BB.clamp(this.x+h.side*6,h.w/2,BB.ARENA.W-h.w/2); + var ay=h.attackAxis==='vertical'?Math.min(BB.ARENA.H-h.h/2,this.y+2):b.y; + TR.moveToward(h,ax,ay,9*TR.PX*speedMul,40); + if(Math.hypot(ax-h.x,ay-h.y)<0.6){ + h.target={x:b.x,y:b.y};h.st='attack';h.timer=0.7; + if(h.attackAxis==='vertical'){ + h.vx=BB.clamp((b.x-h.x)/Math.max(0.15,Math.abs(b.y-h.y)/(15*TR.PX*speedMul)),-16*TR.PX*speedMul,16*TR.PX*speedMul); + h.vy=-15*TR.PX*speedMul; + }else{h.vx=(b.x=BB.ARENA.W-h.w/2))h.st='return'; + }else if(h.st==='return'){ + var rx=BB.clamp(this.x+h.side*3.2,h.w/2,BB.ARENA.W-h.w/2),ry=BB.clamp(this.y-2.8,h.h/2,BB.ARENA.H-h.h/2); + TR.moveToward(h,rx,ry,(this.expert?12:8)*TR.PX*this.pace.speed,40); + if(Math.hypot(h.x-rx,h.y-ry)<1)h.st='idle'; + } + }; + P.update=function(c){ + if(this.st==='dead')return;this.clock(c);var b=c.body.centre(),alive=this.hands.filter(function(h){return h.hp>0;}); + // Starting at 19:30, dawn is nine real-time minutes later. The finite benchmark may end first. + if((TR.isDaytime?TR.isDaytime(c):c.t>=9*60*60)&&!this.enraged){this.enraged=true;this.go(c,'attack',1e9,'spin');c.emit('skeletron_day_enrage',this.x,this.y);} + if(this.st==='idle'){ + this.headFrames++; + TR.moveToward(this,b.x,Math.min(BB.ARENA.H-this.h/2,b.y+250/32),(this.expert?4:2)*TR.PX*this.pace.speed,this.expert?15:6); + if(this.expert&&(alive.length<2||this.hp/this.max_hp<0.75)){ + this.skullFrames++;this.skullTimer=((alive.length===0?40:80)-this.skullFrames)/60; + if(this.skullFrames>=(alive.length===0?40:80)){this.spawnSkull(c);this.skullFrames=0;this.skullTimer=(alive.length===0?40:80)/60;} + } + if(this.headFrames>=this.hoverFrames){this.headFrames=0;this.go(c,'attack',400/60,'spin');c.emit('skeletron_roar',this.x,this.y);} + }else if(this.st==='attack'){ + this.headFrames++; + this.spinSpeed=this.enraged?20*TR.PX:this.chaseSpeed(b); + TR.moveToward(this,b.x,b.y,this.spinSpeed,this.enraged?100:60); + if(!this.enraged&&this.headFrames>=400){this.headFrames=0;this.go(c,'idle',this.hoverFrames/60);this.move=null;} + } + this.hands.forEach(function(h){this.updateHand(c,h,b);},this);this.defense=this.armor(); + }; + P.hazards=function(){ + if(this.st==='dead')return []; + var head={kind:this.st==='attack'?'skull_spin':'skull',box:this.bodyBox(),fromX:this.x, + dmg:this.enraged?9999:TR.paceDmg(this,this.expert?(this.st==='attack'?91:70):32)}; + if(this.expert){head.debuff='bleeding';head.debuffChance=1;head.debuffDuration=[12,20];} + return [head].concat(this.hands.filter(function(h){return h.hp>0;}).map(function(h){ + var hit={kind:'hand',box:TR.box(h),dmg:TR.paceDmg(this,this.expert?44:20),fromX:h.x}; + if(this.expert){hit.debuff='slow';hit.debuffChance=0.5;hit.debuffDuration=[1,2];}return hit; + },this),TR.extraHazards(this)); + }; + BB.CASES['terraria/skeletron'] = TR.register('skeletron','Twin-Handed Giant Skull',Skeletron,'dungeon'); +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/draw/adventurer.js b/environments/games/web/games/terraria_remake/draw/adventurer.js new file mode 100644 index 0000000000000000000000000000000000000000..c5a70146be97f360b5c53da592cf8229117208ec --- /dev/null +++ b/environments/games/web/games/terraria_remake/draw/adventurer.js @@ -0,0 +1,133 @@ +(function(g){ + var BB=g.BB,D=BB.TR.DRAW,TAU=Math.PI*2; + // Original procedural adventurer: hair, tunic, belt, boots; legs follow the simulated run speed, the cape + // follows velocity, wings appear only while flying/gliding (the simulated state), the sword arc is the hitbox. + function limb(x,ax,ay,bx,by,w,col){x.lineCap='round';x.lineWidth=w;x.strokeStyle=col;x.beginPath();x.moveTo(ax,ay);x.lineTo(bx,by);x.stroke();} + function figure(x,b,V,t){ + var f=b.facing<0?-1:1,s=V.S,run=Math.abs(b.vx)/11.25,air=!b.grounded; + var cx=V.sx(b.x),fy=V.sy(b.y),H=1.3125*s,ph=b.x*2.2; + x.save();x.translate(cx,fy);x.scale(f,1); + var hip=-H*.42,sw=air?.5:Math.sin(ph)*Math.min(1,run*1.4)*.75; + // cape + x.fillStyle='#5a2f63';x.beginPath();x.moveTo(-s*.12,-H*.78);x.quadraticCurveTo(-s*.4-run*s*.2,-H*.5,-s*.32-run*s*.35,-H*.22+(air?-s*.1:0));x.lineTo(-s*.05,-H*.3);x.closePath();x.fill(); + // legs + limb(x,-s*.05,hip,-s*.05+Math.sin(sw)*s*.22,-s*.04,s*.15,'#3a4e66'); + limb(x,s*.06,hip,s*.06-Math.sin(sw)*s*.22,-s*.04,s*.15,'#455d79'); + x.fillStyle='#3a2a20';x.fillRect(-s*.05+Math.sin(sw)*s*.22-s*.08,-s*.08,s*.2,s*.08);x.fillRect(s*.06-Math.sin(sw)*s*.22-s*.08,-s*.08,s*.2,s*.08); + // torso + x.fillStyle='#b5482f';x.beginPath();x.moveTo(-s*.17,-H*.78);x.lineTo(s*.17,-H*.78);x.lineTo(s*.2,hip);x.lineTo(-s*.2,hip);x.closePath();x.fill(); + x.fillStyle='#e8c25e';x.fillRect(-s*.2,hip-s*.06,s*.4,s*.06); + x.strokeStyle='#4a1d12';x.lineWidth=1.2;x.strokeRect(-s*.17,-H*.78,s*.34,H*.36); + // head + x.fillStyle='#efc39b';x.beginPath();x.arc(s*.02,-H*.88,s*.17,0,TAU);x.fill(); + x.fillStyle='#5b3a24';x.beginPath();x.arc(-s*.02,-H*.93,s*.18,Math.PI*.9,Math.PI*2.05);x.fill();x.fillRect(-s*.2,-H*.93,s*.1,s*.16); + x.fillStyle='#1c2430';x.fillRect(s*.09,-H*.9,s*.05,s*.05); + x.restore(); + } + function wings(x,b,V,t){ + var cx=V.sx(b.x),cy=V.sy(b.y+.9),flap=b.flying?Math.sin(t*28)*.5:.25; + [-1,1].forEach(function(k){x.save();x.translate(cx,cy);x.scale(k,1);x.rotate(-.3-flap); + for(var i=0;i<4;i++){x.fillStyle=i%2?'#d9e6ee':'#b9cbd8';x.beginPath();x.ellipse(-12-i*5,-4+i*3,12-i*1.5,4,-.5+i*.18,0,TAU);x.fill();} + x.restore();}); + } + function weapon(x,b,V,center){ + var a=b.atkT>0?b.slashAngle:Math.atan2(b.aimY-center.y,b.aimX-center.x); + x.save();x.translate(V.sx(b.x),V.sy(center.y));x.rotate(-a); + if(b.atkT>0||b.weapon==='sword'){ + x.fillStyle='#8b6a3e';x.fillRect(2,-2,8,4);x.fillStyle='#e9c35a';x.fillRect(9,-7,4,14); + x.fillStyle='#d6ecf0';x.beginPath();x.moveTo(13,-3);x.lineTo(13+V.S*2.0,-2);x.lineTo(16+V.S*2.05,0);x.lineTo(13+V.S*2.0,2);x.lineTo(13,3);x.closePath();x.fill(); + x.strokeStyle='#5d7a86';x.lineWidth=1;x.stroke(); + }else{ + x.strokeStyle='#7b4f2c';x.lineWidth=3;x.beginPath();x.arc(4,0,13,-1.15,1.15);x.stroke(); + x.strokeStyle='#efe6cf';x.lineWidth=1;x.beginPath();x.moveTo(4+13*Math.cos(-1.15),13*Math.sin(-1.15));x.lineTo(4+13*Math.cos(1.15),13*Math.sin(1.15));x.stroke(); + } + x.restore(); + } + function crosshair(x,V,b){ + var ax=V.sx(b.aimX),ay=V.sy(b.aimY);x.save();x.strokeStyle='rgba(20,20,20,.6)';x.lineWidth=3; + x.beginPath();x.arc(ax,ay,6,0,TAU);x.stroke();x.strokeStyle='#fff0b8';x.lineWidth=1.5;x.beginPath();x.arc(ax,ay,6,0,TAU);x.moveTo(ax-11,ay);x.lineTo(ax-7,ay);x.moveTo(ax+7,ay);x.lineTo(ax+11,ay);x.moveTo(ax,ay-11);x.lineTo(ax,ay-7);x.moveTo(ax,ay+7);x.lineTo(ax,ay+11);x.stroke();x.restore(); + } + // Floating combat text from the case's own events (amounts are presentation-only payloads); stateless. + function combatText(x,c,V){ + var ev=c.events;x.save();x.textAlign='center';x.font='bold 13px "Segoe UI",sans-serif'; + for(var i=ev.length-1,n=0;i>=0&&n<24;i--){var e=ev[i];if(e.t=12; + return (h%12||12)+':'+(m<10?'0':'')+m+(pm?' PM':' AM'); + } + BB.BODY_DRAW.terraria_adventurer={ + draw:function(x,c,t,V){ + var b=c.body,center=b.centre(); + D.shadow(x,V,b.x,b.y,.7,c); + if(b.hp<=0){ // Terraria leaves a tombstone where the player died + var gx=V.sx(b.x),gy=V.sy(b.y);x.save();x.fillStyle='#8d949a';x.strokeStyle='#2c3036';x.lineWidth=2; + x.beginPath();x.moveTo(gx-11,gy);x.lineTo(gx-11,gy-22);x.arc(gx,gy-22,11,Math.PI,0);x.lineTo(gx+11,gy);x.closePath();x.fill();x.stroke(); + x.fillStyle='#3b4148';x.fillRect(gx-1.5,gy-26,3,14);x.fillRect(gx-6,gy-22,12,3);x.restore();combatText(x,c,V);return;} + x.save();if(b.invul>0&&Math.floor(t*18)%2)x.globalAlpha=0.45; + if(b.flying||b.gliding)wings(x,b,V,t); + figure(x,b,V,t);weapon(x,b,V,center);x.restore(); + b.arrows.forEach(function(p){ + x.save();x.translate(V.sx(p.x),V.sy(p.y));x.rotate(-Math.atan2(p.vy,p.vx));x.fillStyle='rgba(255,240,200,.25)';x.fillRect(-20,-1,12,2); + x.fillStyle='#d9c08a';x.fillRect(-9,-1,16,2);x.fillStyle='#e9f7ee';x.beginPath();x.moveTo(11,0);x.lineTo(6,-3);x.lineTo(6,3);x.fill();x.fillStyle='#c0644a';x.fillRect(-10,-3,4,2);x.fillRect(-10,1,4,2);x.restore(); + }); + var slash=b.slashBox(); + if(slash){x.save();x.globalCompositeOperation='lighter';x.fillStyle='rgba(255,226,150,.35)';x.beginPath(); + slash.pts.forEach(function(p,n){if(n)x.lineTo(V.sx(p[0]),V.sy(p[1]));else x.moveTo(V.sx(p[0]),V.sy(p[1]));});x.closePath();x.fill();x.restore();} + crosshair(x,V,b); + combatText(x,c,V); + }, + fullHud:function(x,c,V,extra){ + var b=c.body,w=c.boss,dr=BB.BOSS_DRAW[c.id]||{},W=V.W; + x.save();x.textBaseline='alphabetic'; + // player panel (top left) + panel(x,10,8,250,62); + x.font='bold 12px "Segoe UI",sans-serif';x.fillStyle='#ffd7cf';x.fillText('Health '+b.hp+' / '+b.max_hp,18,24); + bar(x,18,29,150,8,b.hp/b.max_hp,b.hp/b.max_hp<.3?'#ff4a4a':'#e2453b','#3b1518'); + x.fillStyle='#bfe6f5';x.font='11px "Segoe UI",sans-serif';x.fillText('Flight',18,52);bar(x,46,45,122,5,b.flight/1.5,'#7fd0ec','#173040'); + x.fillStyle='#c9c4ff';x.fillText('Mana '+b.mana,18,65);bar(x,66,59,102,4,b.mana/b.max_mana,'#6f7cff','#1c1c46'); + x.fillStyle='#f3e2b2';x.font='bold 12px "Segoe UI",sans-serif';x.fillText(b.weapon==='bow'?'Bow':'Sword',180,24); + x.font='10px "Segoe UI",sans-serif';x.fillStyle='#b8c6cc';x.fillText(b.flying?'Flying':b.gliding?'Gliding':b.grounded?'Grounded':'Airborne',180,38); + var st=[],NAMES={slow:'Slow',bleeding:'Bleeding',poisoned:'Poisoned',confused:'Confused',weak:'Weak',broken_armor:'Armor broken',cursed:'Cursed',darkness:'Darkness',silenced:'Silenced'}; + Object.keys(NAMES).forEach(function(k){if(b.status[k]>0)st.push(NAMES[k]+' '+b.status[k].toFixed(1)+'s');}); + if(st.length){x.fillStyle='#ffb36b';x.fillText(st.slice(0,2).join(' '),180,52);if(st.length>2)x.fillText(st.slice(2,4).join(' '),180,64);} + // boss panel (top right) + var bw=330,bx=W-bw-10;panel(x,bx,8,bw,48); + var title=String(c.def&&c.def.title||'Boss'),f=Math.max(0,w.hp/w.max_hp),col=dr.bar?dr.bar(w):'#d8c27a'; + x.font='bold 13px Georgia,"Microsoft YaHei",serif';x.fillStyle='#f6e7c4';x.textAlign='left';x.fillText(title,bx+8,24); + x.textAlign='right';x.font='bold 12px "Segoe UI",sans-serif';x.fillStyle='#fff';x.fillText(w.hp+' / '+w.max_hp,bx+bw-8,24); + bar(x,bx+8,29,bw-16,9,f,col,'#26161a','rgba(240,220,170,.8)'); + if(w.hands){var hx=bx+8;w.hands.forEach(function(h,i){bar(x,hx+i*((bw-16)/2+2),40,(bw-16)/2-2,3,h.hp/h.max_hp,'#cdbf9a','#2a2622');});} + x.textAlign='left';x.font='11px "Segoe UI","Microsoft YaHei",sans-serif';x.fillStyle='#d9e4e8'; + x.fillText(dr.phase?dr.phase(w,!!BB.TR.showCues):'',bx+8,w.hands?54:52); + // centre column, between the two panels: public tier (or the source mode for a custom d) + timer, then the + // rules, native tick rate and in-game clock, then the label + var secs=c.t/BB.FPS,mm=Math.floor(secs/60),ss=Math.floor(secs%60),tier=w.pace&&w.pace.tier,cx=(260+bx)/2, + level=tier?BB.TR.TIER_NAMES[tier]:w.expert?'Expert Expert':'Custom d='+(+c.d).toFixed(2); + x.textAlign='center';x.font='bold 12px "Segoe UI","Microsoft YaHei",sans-serif'; + x.fillStyle=w.expert?'#ff9d6b':tier==='hard'?'#ffc46b':tier==='easy'?'#a8e6b0':'#bfe3c6'; + x.fillText(level+' · '+mm+':'+(ss<10?'0':'')+ss,cx,22); + x.font='11px "Segoe UI","Microsoft YaHei",sans-serif';x.fillStyle=BB.TR.isDaytime(c)?'#ffe48a':'#a9c1e8'; + x.fillText((w.expert?'Expert rules':'Classic rules')+' · '+BB.FPS+' Hz · '+(BB.TR.isDaytime(c)?'Day ':'Night ')+clock(c),cx,37); + if(extra){x.font='bold 12px "Segoe UI","Microsoft YaHei",sans-serif';x.fillStyle='#ffe7a3';x.fillText(extra,cx,54);} + // The play page draws the final live frame once before its HTML result panel opens; that frame skips the + // banner so the two never overlap. Off-page renderers (RGB observations, harness video) keep it. + var onPage=!!(x.canvas&&x.canvas.id==='view'&&g.document&&g.document.getElementById('result')); + if(c.result&&!onPage){x.font='bold 30px Georgia,serif';x.fillStyle=c.result==='win'?'#ffe08a':'#ff8a7a';x.strokeStyle='rgba(0,0,0,.7)';x.lineWidth=4; + var word=c.result==='win'?'VICTORY':c.result==='loss'?'DEFEATED':'TIME UP';x.strokeText(word,W/2,V.H/2-40);x.fillText(word,W/2,V.H/2-40);} + x.restore(); + } + }; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/draw/brain_of_cthulhu.js b/environments/games/web/games/terraria_remake/draw/brain_of_cthulhu.js new file mode 100644 index 0000000000000000000000000000000000000000..b040ade5f283011f5db334f64e7e30d78c20de53 --- /dev/null +++ b/environments/games/web/games/terraria_remake/draw/brain_of_cthulhu.js @@ -0,0 +1,64 @@ +(function(g){ + var BB=g.BB,D=BB.TR.DRAW,TAU=Math.PI*2; + // Original art: a pink, folded brain with a dangling brain stem and a single eye; translucent and invulnerable + // in phase 1, it reveals a beating heart in phase 2. Creepers are veiny eyeballs with flesh tendrils. + // Expert illusions are the same drawing at the illusion opacity; only the real brain flashes when hit. + function brain(x,V,w,cx,cy,t,alpha,flash,phase){ + var s=w.w*V.S,pulse=1+Math.sin(t*(phase===2?9:3))*.03; + x.save();x.globalAlpha=alpha;x.translate(cx,cy);x.scale(pulse,pulse); + // stem + x.strokeStyle='#8a3040';x.lineWidth=s*.08;x.beginPath();x.moveTo(0,s*.25);x.quadraticCurveTo(s*.08+Math.sin(t*2)*s*.05,s*.42,-s*.04,s*.55);x.stroke(); + // lobes + x.fillStyle=D.lit(flash,phase===2?'#e58c98':'#d98a9c');x.beginPath();x.ellipse(0,0,s*.5,s*.36,0,0,TAU);x.fill(); + x.strokeStyle='#6a1f2c';x.lineWidth=2;x.stroke(); + x.strokeStyle='rgba(120,30,50,.7)';x.lineWidth=1.6; + for(var k=0;k<6;k++){var yy=-s*.28+k*s*.11;x.beginPath();x.moveTo(-s*.45,yy); + for(var j=0;j<6;j++)x.quadraticCurveTo(-s*.4+j*s*.16,yy+((j+k)%2?-1:1)*s*.06,-s*.32+j*s*.16,yy);x.stroke();} + x.strokeStyle='#6a1f2c';x.lineWidth=2;x.beginPath();x.moveTo(0,-s*.35);x.quadraticCurveTo(s*.04,0,0,s*.3);x.stroke(); + if(phase===2){ + // the exposed heart + var hb=1+Math.max(0,Math.sin(t*9))*.18;x.save();x.translate(0,s*.12);x.scale(hb,hb); + x.fillStyle='#b8202e';x.beginPath();x.moveTo(0,s*.12);x.bezierCurveTo(-s*.2,-s*.02,-s*.1,-s*.18,0,-s*.07);x.bezierCurveTo(s*.1,-s*.18,s*.2,-s*.02,0,s*.12);x.fill(); + x.strokeStyle='#4a0810';x.lineWidth=1.5;x.stroke();x.restore(); + }else{ + x.fillStyle='#f2e4d6';x.beginPath();x.arc(s*.18,-s*.02,s*.11,0,TAU);x.fill(); + x.fillStyle='#7a1a2a';x.beginPath();x.arc(s*.21,-s*.02,s*.05,0,TAU);x.fill(); + } + x.restore(); + } + function creeper(x,V,m,t){ + var cx=V.sx(m.x),cy=V.sy(m.y),r=m.w*V.S*.5,a=m.st==='charge'?Math.atan2(-m.vy,m.vx):Math.sin(t*2+m.id); + x.save();x.translate(cx,cy);x.rotate(a); + x.strokeStyle='#7a2232';x.lineWidth=2; + for(var k=-1;k<=1;k++){x.beginPath();x.moveTo(-r*.7,k*r*.3);x.quadraticCurveTo(-r*1.5,k*r*.6+Math.sin(t*12+k+m.id)*3,-r*2,k*r*.9);x.stroke();} + x.fillStyle=m.hitT>0?'#fff':'#c9505e';x.beginPath();x.arc(0,0,r,0,TAU);x.fill();x.strokeStyle='#4a1020';x.lineWidth=1.5;x.stroke(); + // health ring: a Creeper the player has hit shows how much is left (the source game draws per-NPC bars) + if(m.hp0)creeper(x,V,m,t);}); + (w.pickups||[]).length&&D.extras(x,{boss:{minions:[],shots:[],pickups:w.pickups}},t,V); + },body:function(x,c,t,V){var w=c.boss;if(w.st==='dead')return; + // Expert illusions first (behind), the real brain on top. A fading (teleporting) brain is drawn at its fade. + if(w.phase===2&&w.illusions&&w.illusions.length){ + w.illusions.forEach(function(p){brain(x,V,w,V.sx(p.x),V.sy(p.y),t,w.illusionAlpha*w.fade,false,2);}); + } + var alpha=(w.phase===1?.55:1)*Math.max(.15,w.fade); + brain(x,V,w,V.sx(w.x),V.sy(w.y),t,alpha,w.hitFlash>0,w.phase); + },bar:function(w){return w.phase===2?'#d0454f':'#d98a9c';}, + phase:function(w){ + var alive=w.minions.filter(function(m){return m.kind==='creeper'&&m.hp>0;}); + if(w.phase===1){ + // The HUD bar is the brain + Creeper total; spell out where the remaining health sits. + var creepers=alive.reduce(function(a,m){return a+m.hp;},0); + return 'Phase 1 · core invulnerable · guard eyes '+alive.length+'/20 ('+creepers+')· core '+w.brainHp; + } + return 'Phase 2 · core '+w.brainHp+'/'+w.brainMax+(w.expert?' · clones':''); + }}; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/draw/eater_of_worlds.js b/environments/games/web/games/terraria_remake/draw/eater_of_worlds.js new file mode 100644 index 0000000000000000000000000000000000000000..1803f53cdcf1b9b0e0a7447e5b30cc582e3bb48d --- /dev/null +++ b/environments/games/web/games/terraria_remake/draw/eater_of_worlds.js @@ -0,0 +1,47 @@ +(function(g){ + var BB=g.BB,D=BB.TR.DRAW; + var TAU=Math.PI*2; + // Original art: armoured corrupt segments, a head with mandibles and a spiked tail. Each segment faces the + // segment in front of it; coiled (not yet visible) and underground segments are not drawn. + function segment(x,s,len,flash,t){ + var r=len*.5; + if(s.type==='tail'){ + x.beginPath();x.moveTo(r*.9,-r*.75);x.quadraticCurveTo(-r*.2,-r*.7,-r*1.3,0);x.quadraticCurveTo(-r*.2,r*.7,r*.9,r*.75);x.closePath(); + x.fillStyle=D.lit(flash,'#6d4f7d');x.fill();x.lineWidth=2;x.strokeStyle='#22162b';x.stroke(); + x.strokeStyle='#a27fb3';x.lineWidth=1.5;x.beginPath();x.moveTo(r*.5,-r*.45);x.quadraticCurveTo(-r*.1,0,r*.5,r*.45);x.stroke();return; + } + x.beginPath();x.ellipse(0,0,r*1.02,r*.92,0,0,TAU);x.fillStyle=D.lit(flash,s.type==='head'?'#7a5a8c':'#6d4f7d');x.fill(); + x.lineWidth=2;x.strokeStyle='#22162b';x.stroke(); + x.fillStyle='rgba(190,160,205,.55)';x.beginPath();x.ellipse(0,-r*.35,r*.75,r*.3,0,0,TAU);x.fill(); + x.strokeStyle='#3a2647';x.lineWidth=1.5;x.beginPath();x.moveTo(-r*.25,-r*.88);x.quadraticCurveTo(-r*.45,0,-r*.25,r*.88);x.stroke(); + x.beginPath();x.moveTo(r*.3,-r*.86);x.quadraticCurveTo(r*.1,0,r*.3,r*.86);x.stroke(); + if(s.type==='head'){ + var bite=Math.sin(t*9)*.18; + [-1,1].forEach(function(k){ + x.save();x.translate(r*.75,k*r*.45);x.rotate(k*(.35+bite)); + x.beginPath();x.moveTo(0,-r*.16*k);x.quadraticCurveTo(r*.75,-r*.1*k,r*.95,r*.25*k);x.quadraticCurveTo(r*.55,r*.08*k,0,r*.18*k);x.closePath(); + x.fillStyle='#d9cc9b';x.fill();x.lineWidth=1.5;x.strokeStyle='#2a1f12';x.stroke();x.restore(); + }); + x.fillStyle='#f2e27a';[-1,1].forEach(function(k){x.beginPath();x.arc(r*.42,k*r*.42,r*.11,0,TAU);x.fill();}); + x.fillStyle='#2a1030';x.beginPath();x.ellipse(r*.86,0,r*.14,r*.22,0,0,TAU);x.fill(); + } + } + BB.BOSS_DRAW['terraria/eater_of_worlds']={hazards:D.extras,body:function(x,c,t,V){var w=c.boss;if(w.st==='dead')return; + var lookup={},fronts={};w.segments.forEach(function(s){lookup[s.id]=s;}); + w.chains.forEach(function(ch){for(var i=1;i0; + w.segments.slice().reverse().forEach(function(s){if(s.hp<=0||s.visible===false||s.y<=-s.h/2)return; + var front=fronts[s.id],dx=front?front.x-s.x:s.vx||0,dy=front?front.y-s.y:s.vy||0; + x.save();x.translate(V.sx(s.x),V.sy(s.y));x.rotate(-Math.atan2(dy,dx||1e-6)); + segment(x,s,s.w*V.S,flash,t);x.restore(); + }); + // dirt bursts where a head is digging just below the surface (presentation only) + w.chains.forEach(function(ch){var h=lookup[ch.ids[0]];if(!h||h.y>.4||h.y<-2.5)return; + x.fillStyle='rgba(98,71,53,.8)';for(var k=0;k<5;k++){var px=V.sx(h.x)+Math.sin(t*13+k*2.3)*14,py=V.sy(0)-Math.abs(Math.sin(t*9+k))*10;x.fillRect(px,py,3,3);}}); + },bar:function(){return '#b07fc4';}, + phase:function(w){ + var alive=w.segments.filter(function(s){return s.hp>0;}).length; + return w.chains.length+' worms · '+alive+' segments alive'; + }}; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/draw/eye_of_cthulhu.js b/environments/games/web/games/terraria_remake/draw/eye_of_cthulhu.js new file mode 100644 index 0000000000000000000000000000000000000000..0b2d27e95aa12615958d93ca305531f61a3dd700 --- /dev/null +++ b/environments/games/web/games/terraria_remake/draw/eye_of_cthulhu.js @@ -0,0 +1,52 @@ +(function(g){ + var BB=g.BB,D=BB.TR.DRAW; + var TAU=Math.PI*2; + // Original art: an eyeball with trailing nerve tendrils; the second form shows a toothed maw. + // Orientation follows the simulated charge velocity, the transform spin, or the player while hovering. + BB.BOSS_DRAW['terraria/eye_of_cthulhu']={hazards:function(x,c,t,V){ + var w=c.boss;if(w.st==='antic')D.cue(x,V,w,w.target,'#f39783');D.extras(x,c,t,V); + },body:function(x,c,t,V){var w=c.boss;if(w.st==='dead'||w.despawned)return; + var b=c.body.centre(),a; + if(w.st==='transform')a=w.rotation; + else if(w.st==='attack'||w.dawnDeparting)a=Math.atan2(-(w.vy||0),w.vx||1e-6); + else a=Math.atan2(-(b.y-w.y),b.x-w.x); + var r=w.w*V.S*.5,flash=w.hitFlash>0,phase2=w.phase===2; + x.save();x.translate(V.sx(w.x),V.sy(w.y));x.rotate(a); + // tendrils trail behind the eye + var wig=w.st==='attack'?2:5; + for(var k=0;k<5;k++){ + var off=(k-2)*r*.22,len=r*(1.25+.18*(k%3)),ph=t*(w.st==='attack'?16:7)+k*1.7; + x.beginPath();x.moveTo(-r*.8,off*.8); + x.bezierCurveTo(-r-len*.35,off+Math.sin(ph)*wig,-r-len*.7,off*1.3-Math.sin(ph+1)*wig*1.5,-r-len,off*1.6+Math.sin(ph+2)*wig*2); + x.lineWidth=Math.max(2,r*.13)*(1-k%2*.3);x.strokeStyle='#7c1f2c';x.stroke(); + x.lineWidth=Math.max(1,r*.05);x.strokeStyle='#c4485a';x.stroke(); + } + // sclera + x.beginPath();x.arc(0,0,r,0,TAU);x.fillStyle=D.lit(flash,phase2?'#e2c3b2':'#efe3d3');x.fill(); + x.lineWidth=2.5;x.strokeStyle='#4a1a22';x.stroke(); + // veins + x.strokeStyle='rgba(184,40,58,.75)';x.lineWidth=1.3; + for(var v=0;v<7;v++){var va=Math.PI*.55+v*.27,vx=Math.cos(va)*r*.95,vy=Math.sin(va)*r*.95; + x.beginPath();x.moveTo(vx,vy);x.quadraticCurveTo(vx*.65+Math.sin(v*3.1)*4,vy*.65,vx*.42,vy*.42+Math.cos(v)*3);x.stroke();} + if(!phase2){ + x.beginPath();x.arc(r*.42,0,r*.46,0,TAU);x.fillStyle='#3b7f8a';x.fill();x.strokeStyle='#18363b';x.lineWidth=2;x.stroke(); + x.beginPath();x.arc(r*.5,0,r*.24,0,TAU);x.fillStyle='#0b0b10';x.fill(); + x.fillStyle='rgba(255,255,255,.75)';x.beginPath();x.arc(r*.36,-r*.16,r*.08,0,TAU);x.fill(); + }else{ + // maw: dark opening with two rows of teeth facing forward + x.beginPath();x.ellipse(r*.38,0,r*.5,r*.62,0,0,TAU);x.fillStyle='#3a0d16';x.fill();x.strokeStyle='#1b0408';x.lineWidth=2;x.stroke(); + x.fillStyle='#f2ead2'; + for(var i=0;i<6;i++){var ty=-r*.5+i*r*.2;x.beginPath();x.moveTo(r*.85,ty);x.lineTo(r*.55,ty+r*.07);x.lineTo(r*.85,ty+r*.14);x.fill(); + x.beginPath();x.moveTo(r*.0,ty+r*.02);x.lineTo(r*.22,ty+r*.09);x.lineTo(r*.0,ty+r*.16);x.fill();} + x.fillStyle='rgba(220,60,70,.6)';x.beginPath();x.ellipse(r*.38,0,r*.18,r*.3,0,0,TAU);x.fill(); + } + x.restore(); + },bar:function(w){return w.phase===2?'#d8545e':'#db927e';}, + phase:function(w,assist){ + if(w.dawnDeparting)return 'Dawn departure · Dawn'; + if(w.st==='transform')return 'Transforming · Transforming'; + var form=w.phase===1?'Phase 1':'Phase 2'; + if(w.st==='attack'||w.st==='recover')return form+' · '+(w.move==='chain_dash'?'Rapid charges':'Dash')+(assist?' remaining '+w.dashesLeft:''); + return form+' · Hovering'; + }}; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/draw/king_slime.js b/environments/games/web/games/terraria_remake/draw/king_slime.js new file mode 100644 index 0000000000000000000000000000000000000000..03e6ce6227bab67726896450888ade9310d22dd8 --- /dev/null +++ b/environments/games/web/games/terraria_remake/draw/king_slime.js @@ -0,0 +1,51 @@ +(function(g){ + var BB=g.BB,D=BB.TR.DRAW,TR=BB.TR; + // Original art: a translucent gel dome with a crown and a dark core. Squash/stretch follows the simulated + // jump velocity and landing recovery; the teleport shrink is the simulated hitbox size itself. + BB.BOSS_DRAW['terraria/king_slime']={ + hazards:function(x,c,t,V){ + var w=c.boss; + if(w.st==='antic'&&w.move==='teleport')D.cue(x,V,{x:w.x,y:w.y},{x:w.target.x,y:w.target.y+0.2},'#88e9d4'); + if(w.st!=='dead'&&!w.hidden)D.shadow(x,V,w.x,w.y-w.h/2,w.w,c); + D.extras(x,c,t,V); + }, + body:function(x,c,t,V){var w=c.boss; + if(w.st==='dead'||w.hidden)return; + var sq=1; + if(w.st==='attack')sq=1+BB.clamp(w.vy/(13*TR.PX),-1,1)*.16; + else if(w.st==='recover'&&w.move!=='teleport')sq=1-.16*Math.max(0,1-w.stT/.22); + else sq=1+Math.sin(t*5)*.025; + var W=w.w*V.S/Math.sqrt(sq),H=w.h*V.S*sq,cx=V.sx(w.x),by=V.sy(w.y-w.h/2),flash=w.hitFlash>0; + var fade=w.move==='teleport'&&(w.st==='antic'||w.st==='recover')?.55:1; + x.save();x.translate(cx,by);x.globalAlpha=fade; + // gel dome + x.beginPath();x.moveTo(-W/2,0);x.bezierCurveTo(-W*.56,-H*.62,-W*.3,-H,0,-H);x.bezierCurveTo(W*.3,-H,W*.56,-H*.62,W/2,0);x.closePath(); + x.globalAlpha=fade*.86;x.fillStyle=D.lit(flash,'#3d86d6');x.fill();x.globalAlpha=fade; + x.lineWidth=2.5;x.strokeStyle='#123563';x.stroke(); + // darker inner core and lower gel + x.fillStyle='rgba(14,40,92,.45)';x.beginPath();x.ellipse(0,-H*.38,W*.2,H*.22,0,0,Math.PI*2);x.fill(); + x.fillStyle='rgba(20,60,120,.35)';x.beginPath();x.ellipse(0,-H*.08,W*.44,H*.1,0,0,Math.PI*2);x.fill(); + // highlights + x.fillStyle='rgba(255,255,255,.55)';x.beginPath();x.ellipse(-W*.25,-H*.72,W*.08,H*.14,-.6,0,Math.PI*2);x.fill(); + x.fillStyle='rgba(255,255,255,.3)';x.beginPath();x.ellipse(-W*.12,-H*.86,W*.05,H*.05,0,0,Math.PI*2);x.fill(); + // crown (dropped visually while vanishing) + if(!(w.move==='teleport'&&w.st==='antic')){ + var cw=W*.36,ch=H*.2,top=-H*1.0; + x.beginPath();x.moveTo(-cw/2,top+ch*.15);x.lineTo(-cw/2,top-ch*.55);x.lineTo(-cw/4,top-ch*.15);x.lineTo(0,top-ch*.75);x.lineTo(cw/4,top-ch*.15);x.lineTo(cw/2,top-ch*.55);x.lineTo(cw/2,top+ch*.15);x.closePath(); + x.fillStyle=D.lit(flash,'#f0c445');x.fill();x.lineWidth=1.5;x.strokeStyle='#6d4b0c';x.stroke(); + x.fillStyle='#d8324a';x.beginPath();x.arc(0,top-ch*.12,ch*.17,0,Math.PI*2);x.fill(); + x.fillStyle='#7fd4f0';x.fillRect(-cw/2+2,top-ch*.2,3,3);x.fillRect(cw/2-5,top-ch*.2,3,3); + } + x.restore(); + if(w.st==='antic'&&w.move!=='teleport')D.cue(x,V,{x:w.x,y:w.y},{x:w.target.x,y:0.2},'#f7d377'); + }, + bar:function(){return '#4f9de0';}, + // Only what the original shows on screen; hidden counters appear only with the explicit assist toggle. + phase:function(w,assist){ + if(w.move==='teleport'&&(w.st==='antic'||w.st==='recover'))return 'Teleport · Teleport'; + var text=w.st==='attack'?'Jump · Jump':'Landed · Landed'; + if(assist)text+=' · next jump '+['normal','normal','low','high'][w.jumpIndex%4]+(w.teleportWait>0?' · TeleportTimer '+(5-w.teleportWait).toFixed(1)+'s':''); + return text; + } + }; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/draw/palette.js b/environments/games/web/games/terraria_remake/draw/palette.js new file mode 100644 index 0000000000000000000000000000000000000000..a5ae00f1467497da6d6db35d268ea2c190d03593 --- /dev/null +++ b/environments/games/web/games/terraria_remake/draw/palette.js @@ -0,0 +1,80 @@ +(function(g){ + var BB=g.BB; + BB.VIEW.PAL={sky:'#83b9c6',forest:'#35694d',earth:'#624735',gold:'#efc96e',ink:'#e8eddd',dark:'#172b32'}; + var D=BB.TR.DRAW={}; + // Hand-authored original procedural art; no downloaded images, fonts or source-game sprites. + // Every function here only reads the case; noise comes from a hash of ids/time, never from the game RNG. + D.sprite=function(ctx,V,e,rows,pal,w,h,flip){ + var sx=V.sx(e.x),sy=V.sy(e.y),cw=w*V.S/rows[0].length,ch=h*V.S/rows.length; + ctx.save();ctx.translate(Math.round(sx),Math.round(sy));if(flip)ctx.scale(-1,1); + for(var y=0;y=p[0]&&ex<=p[1]&&ey>=p[2]-.05&&p[2]>floor)floor=p[2];}); + var gap=Math.max(0,ey-floor),k=Math.max(0,1-gap/8);if(k<=0)return; + BB.ART.shade(x,V.sx(ex),V.sy(floor)+2,width*V.S*.55*(0.6+0.4*k),5,0.35*k); + }; + function slime(x,V,m,t,spiked){ + var cx=V.sx(m.x),by=V.sy(m.y-m.h/2),w=m.w*V.S,h=m.h*V.S*(1+Math.sin(t*7+m.id)*.05),flash=m.hitT>0; + x.save();x.translate(cx,by); + if(spiked){x.fillStyle='#d9d3c4';for(var k=-2;k<=2;k++){x.beginPath();x.moveTo(k*w*.18-3,-h*.55);x.lineTo(k*w*.2,-h*1.15+Math.abs(k)*3);x.lineTo(k*w*.18+3,-h*.55);x.fill();}} + x.beginPath();x.moveTo(-w/2,0);x.quadraticCurveTo(-w/2,-h*1.05,0,-h*1.05);x.quadraticCurveTo(w/2,-h*1.05,w/2,0);x.closePath(); + x.globalAlpha=.88;x.fillStyle=D.lit(flash,spiked?'#4c78c9':'#3f8ee0');x.fill();x.globalAlpha=1; + x.lineWidth=1.5;x.strokeStyle='#14305a';x.stroke(); + x.fillStyle='rgba(255,255,255,.55)';x.beginPath();x.ellipse(-w*.2,-h*.72,w*.11,h*.12,-.5,0,Math.PI*2);x.fill(); + x.fillStyle='#0d1f38';var f=m.face||1;x.fillRect(f*w*.08-3,-h*.55,2,3);x.fillRect(f*w*.08+3,-h*.55,2,3); + x.restore(); + } + function servant(x,V,m,t){ + var cx=V.sx(m.x),cy=V.sy(m.y),r=m.w*V.S*.5,a=Math.atan2(-(m.vy||0),m.vx||1); + x.save();x.translate(cx,cy);x.rotate(a); + x.strokeStyle='#8e2b3a';x.lineWidth=2; + for(var k=-1;k<=1;k++){x.beginPath();x.moveTo(-r*.6,k*r*.3);x.quadraticCurveTo(-r*1.5,k*r*.5+Math.sin(t*14+k+m.id)*3,-r*2.1,k*r*.7);x.stroke();} + x.fillStyle='#ece0d0';x.beginPath();x.arc(0,0,r,0,Math.PI*2);x.fill();x.strokeStyle='#4a1820';x.lineWidth=1.5;x.stroke(); + x.fillStyle='#a8343f';x.beginPath();x.arc(r*.35,0,r*.5,0,Math.PI*2);x.fill(); + x.fillStyle='#120608';x.beginPath();x.arc(r*.45,0,r*.22,0,Math.PI*2);x.fill(); + x.restore(); + } + function shot(x,V,p,t){ + var cx=V.sx(p.x),cy=V.sy(p.y),a=Math.atan2(-p.vy,p.vx),r=Math.max(4,p.r*V.S); + x.save();x.translate(cx,cy); + if(p.kind==='slime_spike'){x.rotate(a);x.fillStyle='#e7e1cf';x.beginPath();x.moveTo(r*1.6,0);x.lineTo(-r*1.2,-2.2);x.lineTo(-r*1.2,2.2);x.closePath();x.fill();x.strokeStyle='#5a5246';x.lineWidth=1;x.stroke();} + else if(p.kind==='vile_spit'){ + x.rotate(a);x.fillStyle='rgba(126,170,52,.45)';x.beginPath();x.ellipse(-r*.9,0,r*1.1,r*.55,0,0,Math.PI*2);x.fill(); + x.fillStyle='#a7c94a';x.beginPath();x.arc(0,0,r,0,Math.PI*2);x.fill();x.strokeStyle='#3d4f17';x.lineWidth=1.5;x.stroke(); + x.fillStyle='#e3f3a0';x.beginPath();x.arc(r*.3,-r*.3,r*.3,0,Math.PI*2);x.fill(); + }else{ // homing skull with a cold flame trail + x.save();x.rotate(a);x.fillStyle='rgba(110,170,255,.35)';x.beginPath();x.moveTo(-r*.4,-r*.7);x.quadraticCurveTo(-r*2.6,Math.sin(t*20+p.id)*3,-r*.4,r*.7);x.fill();x.restore(); + x.fillStyle='#ece3c9';x.beginPath();x.arc(0,-1,r*.85,0,Math.PI*2);x.fill();x.fillRect(-r*.5,r*.3,r,r*.5); + x.strokeStyle='#4d463c';x.lineWidth=1;x.stroke();x.fillStyle='#2a2430';x.fillRect(-r*.45,-r*.35,r*.35,r*.35);x.fillRect(r*.1,-r*.35,r*.35,r*.35); + } + x.restore(); + } + function pickup(x,V,p,t){ + var cx=V.sx(p.x),cy=V.sy(p.y)+Math.sin(t*5+p.x)*1.5;x.save();x.translate(cx,cy); + if(p.kind==='heart'){x.fillStyle='#e9465a';x.beginPath();x.moveTo(0,5);x.bezierCurveTo(-9,-1,-5,-8,0,-3);x.bezierCurveTo(5,-8,9,-1,0,5);x.fill();x.strokeStyle='#5c0f1c';x.lineWidth=1;x.stroke();} + else{BB.ART.glow(x,0,0,12,'150,190,255',.5);x.fillStyle='#ffe78a';x.beginPath();for(var i=0;i<10;i++){var rr=i%2?3:7,a=-Math.PI/2+i*Math.PI/5;x.lineTo(Math.cos(a)*rr,Math.sin(a)*rr);}x.closePath();x.fill();x.strokeStyle='#7a5a12';x.lineWidth=1;x.stroke();} + x.restore(); + } + D.extras=function(x,c,t,V){ + var boss=c.boss; + (boss.minions||[]).forEach(function(m){if(m.hp<=0)return; + if(m.kind==='slime'||m.kind==='spiked_slime'){D.shadow(x,V,m.x,m.y-m.h/2,m.w,c);slime(x,V,m,t,m.kind==='spiked_slime');}else servant(x,V,m,t); + }); + (boss.shots||[]).forEach(function(p){shot(x,V,p,t);}); + (boss.pickups||[]).forEach(function(p){pickup(x,V,p,t);}); + }; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/draw/queen_bee.js b/environments/games/web/games/terraria_remake/draw/queen_bee.js new file mode 100644 index 0000000000000000000000000000000000000000..5cb4b3f0199cf6851f843aa51d35ec3e8ddff032 --- /dev/null +++ b/environments/games/web/games/terraria_remake/draw/queen_bee.js @@ -0,0 +1,71 @@ +(function(g){ + var BB=g.BB,D=BB.TR.DRAW,TAU=Math.PI*2; + // Original art: a crowned queen bee with striped abdomen, stinger, translucent beating wings and a royal ruff. + // She faces her velocity while charging and the player otherwise; bees and stingers are drawn here too. + function bee(x,V,m,t){ + var cx=V.sx(m.x),cy=V.sy(m.y),r=m.w*V.S*.5,f=(m.vx||0)>=0?1:-1,flap=Math.sin(t*60+m.id)*.6; + x.save();x.translate(cx,cy);x.scale(f,1); + x.fillStyle='rgba(230,240,255,.65)';x.beginPath();x.ellipse(-r*.1,-r*.75,r*.55,r*.3*(1+flap*.4),-.5,0,TAU);x.fill(); + x.fillStyle='#f2c23a';x.beginPath();x.ellipse(0,0,r,r*.75,0,0,TAU);x.fill(); + x.fillStyle='#2a1c08';x.fillRect(-r*.35,-r*.72,r*.22,r*1.44);x.fillRect(r*.1,-r*.72,r*.2,r*1.44); + x.beginPath();x.moveTo(-r,0);x.lineTo(-r*1.45,r*.12);x.lineTo(-r,r*.25);x.fill(); + x.fillStyle='#1a1205';x.beginPath();x.arc(r*.72,-r*.15,r*.2,0,TAU);x.fill(); + if(m.kind==='big_bee'){x.strokeStyle='#8a5a12';x.lineWidth=1.5;x.beginPath();x.ellipse(0,0,r,r*.75,0,0,TAU);x.stroke();} + x.restore(); + } + function stinger(x,V,p){ + var a=Math.atan2(-p.vy,p.vx),r=Math.max(5,p.r*V.S*1.4);x.save();x.translate(V.sx(p.x),V.sy(p.y));x.rotate(a); + x.fillStyle='rgba(255,220,90,.35)';x.beginPath();x.ellipse(-r*1.2,0,r*1.3,r*.45,0,0,TAU);x.fill(); + x.fillStyle='#f6d34a';x.beginPath();x.moveTo(r*1.4,0);x.lineTo(-r,-r*.42);x.lineTo(-r*.6,0);x.lineTo(-r,r*.42);x.closePath();x.fill(); + x.strokeStyle='#6a4a08';x.lineWidth=1;x.stroke();x.restore(); + } + BB.BOSS_DRAW['terraria/queen_bee']={hazards:function(x,c,t,V){ + var w=c.boss; + // Readable windup: while she hangs at the charge height a faint (18 %) streak marks that lane. It is drawn only + // during the pause, the period the source shows her holding level with the player; the explicit target box + // stays behind the assist cues switch. + if(w.move==='charge'&&w.st==='antic'&&w.hold>0){ + var y=V.sy(w.y),k=Math.min(1,w.hold/w.windup());x.save();x.globalAlpha=.18*k;x.fillStyle='#ffe28a'; + x.fillRect(Math.min(V.sx(w.x),V.sx(c.body.x))-20,y-3,Math.abs(V.sx(c.body.x)-V.sx(w.x))+40,6);x.restore(); + } + if(w.move==='charge'&&w.st==='antic'&&BB.TR.showCues)D.cue(x,V,w,{x:c.body.centre().x,y:w.y},'#f5d26a'); + w.minions.forEach(function(m){if(m.hp>0)bee(x,V,m,t);}); + w.shots.forEach(function(p){stinger(x,V,p);}); + (w.pickups||[]).length&&D.extras(x,{boss:{minions:[],shots:[],pickups:w.pickups}},t,V); + },body:function(x,c,t,V){var w=c.boss;if(w.st==='dead')return; + var charging=w.move==='charge'&&w.st==='attack',b=c.body.centre(),f=charging?(w.vx>=0?1:-1):(b.x>=w.x?1:-1); + var s=w.w*V.S,flash=w.hitFlash>0,flap=Math.sin(t*(charging?70:48))*.5,tilt=charging?.12:Math.sin(t*3)*.05; + // the windup crouch: she pulls back slightly before the dash + var crouch=w.move==='charge'&&w.st==='antic'&&w.hold>0?Math.min(1,w.hold/w.windup()):0; + x.save();x.translate(V.sx(w.x)-f*crouch*6,V.sy(w.y));x.scale(f,1);x.rotate(-tilt+crouch*.18); + // speed lines while charging + if(charging){x.strokeStyle='rgba(255,240,190,.35)';x.lineWidth=2;for(var k=0;k<4;k++){x.beginPath();x.moveTo(-s*.6,-s*.25+k*s*.16);x.lineTo(-s*(1.1+k%2*.25),-s*.25+k*s*.16);x.stroke();}} + // back wings + x.fillStyle='rgba(210,230,255,.5)';x.beginPath();x.ellipse(-s*.05,-s*.42,s*.42,s*.2*(1+flap*.5),-.6,0,TAU);x.fill(); + // abdomen with stripes and stinger + x.fillStyle=D.lit(flash,'#f0b62e');x.beginPath();x.ellipse(-s*.18,s*.06,s*.36,s*.28,.15,0,TAU);x.fill(); + x.save();x.beginPath();x.ellipse(-s*.18,s*.06,s*.36,s*.28,.15,0,TAU);x.clip();x.fillStyle='#3a2508'; + for(k=0;k<3;k++)x.fillRect(-s*.42+k*s*.17,-s*.3,s*.07,s*.7);x.restore(); + x.strokeStyle='#4a2f08';x.lineWidth=2;x.beginPath();x.ellipse(-s*.18,s*.06,s*.36,s*.28,.15,0,TAU);x.stroke(); + x.fillStyle='#2a1a06';x.beginPath();x.moveTo(-s*.5,s*.1);x.lineTo(-s*.72,s*.2);x.lineTo(-s*.48,s*.22);x.fill(); + // thorax with royal ruff + x.fillStyle=D.lit(flash,'#7a4a12');x.beginPath();x.arc(s*.17,-s*.02,s*.2,0,TAU);x.fill(); + x.fillStyle='#f5e6c2';for(k=0;k<6;k++){var a=-1.2+k*.48;x.beginPath();x.arc(s*.17+Math.cos(a)*s*.2,-s*.02+Math.sin(a)*s*.2,s*.07,0,TAU);x.fill();} + // head, eyes, antennae and crown + x.fillStyle=D.lit(flash,'#e8a82a');x.beginPath();x.arc(s*.38,-s*.13,s*.15,0,TAU);x.fill();x.strokeStyle='#4a2f08';x.lineWidth=1.5;x.stroke(); + x.fillStyle='#2a1408';x.beginPath();x.ellipse(s*.45,-s*.15,s*.05,s*.075,0,0,TAU);x.fill(); + x.strokeStyle='#2a1408';x.lineWidth=1.5;x.beginPath();x.moveTo(s*.4,-s*.27);x.quadraticCurveTo(s*.47,-s*.42,s*.56,-s*.4);x.stroke(); + x.fillStyle='#f6cf46';x.beginPath();x.moveTo(s*.26,-s*.26);for(var p=0;p<5;p++){x.lineTo(s*.28+p*s*.045,-s*(p%2?.32:.4));}x.lineTo(s*.48,-s*.26);x.closePath();x.fill(); + x.fillStyle='#e24a5a';x.beginPath();x.arc(s*.37,-s*.33,s*.022,0,TAU);x.fill(); + // front wings + x.fillStyle='rgba(235,245,255,.6)';x.beginPath();x.ellipse(s*.02,-s*.4,s*.38,s*.17*(1-flap*.5),-.85,0,TAU);x.fill(); + x.strokeStyle='rgba(120,150,190,.6)';x.lineWidth=1;x.stroke(); + x.restore(); + },bar:function(){return '#e6b23a';}, + phase:function(w,assist){ + if(w.move==='charge'||w.move==='charge_end')return 'Lane charge'+(assist?' remaining '+w.chargesLeft:''); + if(w.move==='summon')return 'Summon bees'+(assist?' remaining '+w.beesLeft:''); + if(w.move==='stingers')return 'Stinger volley'+(assist?' remaining '+w.volleyLeft:''); + return ''; + }}; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/draw/skeletron.js b/environments/games/web/games/terraria_remake/draw/skeletron.js new file mode 100644 index 0000000000000000000000000000000000000000..aca054ed323b0506450c8472ede5691f65650427 --- /dev/null +++ b/environments/games/web/games/terraria_remake/draw/skeletron.js @@ -0,0 +1,58 @@ +(function(g){ + var BB=g.BB,D=BB.TR.DRAW; + var TAU=Math.PI*2; + function bone(x,ax,ay,bx,by,wd){ + x.lineCap='round';x.lineWidth=wd+3;x.strokeStyle='#3d362f';x.beginPath();x.moveTo(ax,ay);x.lineTo(bx,by);x.stroke(); + x.lineWidth=wd;x.strokeStyle='#ddd1b3';x.stroke(); + x.fillStyle='#e9dfc4';[[ax,ay],[bx,by]].forEach(function(p){x.beginPath();x.arc(p[0],p[1],wd*.75,0,TAU);x.fill();}); + } + function hand(x,V,h,flash,t){ + var cx=V.sx(h.x),cy=V.sy(h.y),s=h.w*V.S*.5,a=h.st==='attack'?Math.atan2(-h.vy,h.vx):Math.PI/2*(h.side<0?1:1)+.0; + if(h.st!=='attack')a=-Math.PI/2+h.side*.35; + x.save();x.translate(cx,cy);x.rotate(a); + x.fillStyle=D.lit(flash,'#e2d6b8');x.strokeStyle='#3d362f';x.lineWidth=2; + x.beginPath();x.ellipse(0,0,s*.62,s*.55,0,0,TAU);x.fill();x.stroke(); + for(var f=-1.5;f<=1.5;f++){ + var fy=f*s*.28;x.beginPath();x.moveTo(s*.4,fy);x.lineTo(s*1.05,fy*1.15);x.lineWidth=s*.22+2;x.strokeStyle='#3d362f';x.stroke(); + x.lineWidth=s*.22;x.strokeStyle=D.lit(flash,'#e2d6b8');x.stroke(); + x.fillStyle='#3d362f';x.beginPath();x.arc(s*1.08,fy*1.15,s*.1,0,TAU);x.fill(); + } + x.beginPath();x.moveTo(-s*.1,-s*.55);x.lineTo(-s*.55,-s*1.0);x.lineWidth=s*.22+2;x.strokeStyle='#3d362f';x.stroke();x.lineWidth=s*.22;x.strokeStyle=D.lit(flash,'#e2d6b8');x.stroke(); + x.restore(); + } + function skull(x,w,W,H,flash,glow){ + // cranium + cheek + jaw, original silhouette + x.beginPath();x.moveTo(-W*.48,-H*.05);x.bezierCurveTo(-W*.55,-H*.6,-W*.3,-H*.52,0,-H*.52);x.bezierCurveTo(W*.3,-H*.52,W*.55,-H*.6,W*.48,-H*.05); + x.bezierCurveTo(W*.46,H*.16,W*.3,H*.22,W*.26,H*.28);x.lineTo(-W*.26,H*.28);x.bezierCurveTo(-W*.3,H*.22,-W*.46,H*.16,-W*.48,-H*.05);x.closePath(); + x.fillStyle=D.lit(flash,'#e6dbc0');x.fill();x.lineWidth=2.5;x.strokeStyle='#3d362f';x.stroke(); + x.beginPath();x.rect(-W*.22,H*.28,W*.44,H*.17);x.fillStyle=D.lit(flash,'#d8ccae');x.fill();x.stroke(); + x.strokeStyle='#3d362f';x.lineWidth=1.5;for(var i=-2;i<=2;i++){x.beginPath();x.moveTo(i*W*.085,H*.28);x.lineTo(i*W*.085,H*.42);x.stroke();} + [-1,1].forEach(function(s){x.beginPath();x.ellipse(s*W*.2,-H*.04,W*.14,H*.13,s*.2,0,TAU);x.fillStyle='#15121a';x.fill(); + if(glow){BB.ART.glow(x,s*W*.2,-H*.04,W*.2,'255,70,60',.8);x.fillStyle='#ff6a4d';x.beginPath();x.arc(s*W*.2,-H*.04,W*.04,0,TAU);x.fill();}}); + x.beginPath();x.moveTo(0,H*.1);x.lineTo(-W*.06,H*.2);x.lineTo(W*.06,H*.2);x.closePath();x.fillStyle='#15121a';x.fill(); + x.strokeStyle='rgba(61,54,47,.6)';x.lineWidth=1.2;x.beginPath();x.moveTo(W*.1,-H*.5);x.lineTo(W*.16,-H*.36);x.lineTo(W*.1,-H*.28);x.stroke(); + } + BB.BOSS_DRAW['terraria/skeletron']={hazards:D.extras,body:function(x,c,t,V){var w=c.boss;if(w.st==='dead')return; + var flash=w.hitFlash>0,hx=V.sx(w.x),hy=V.sy(w.y); + w.hands.forEach(function(h){if(h.hp<=0)return; + var sx=V.sx(w.x+h.side*.85),sy=V.sy(w.y-.75),ex=V.sx(h.x),ey=V.sy(h.y),mx=(sx+ex)/2,my=(sy+ey)/2,dx=ex-sx,dy=ey-sy,l=Math.hypot(dx,dy)||1; + var bend=Math.max(0,95-l)*.55+12,elx=mx+(-dy/l)*bend*h.side*-1,ely=my+(dx/l)*bend*h.side*-1; + if(ely0;}).length; + if(w.enraged)return 'Daytime enraged · Enraged'; + return (w.st==='attack'?'Spinning pursuit · Spin':'Hovering hand strikes · Hands')+' · hands '+hands+'/2'+(assist?' · Armor '+w.defense:''); + }}; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/game.js b/environments/games/web/games/terraria_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..93b5e9ebb8d3a2335b3f646e8b21f886dfdb22b0 --- /dev/null +++ b/environments/games/web/games/terraria_remake/game.js @@ -0,0 +1,14 @@ +(function(g){ + g.BB.GAME={id:'terraria_remake',title:'Terraria · Arena Trials',rules:'terraria-1458-arena-r7',defaultCase:'terraria/king_slime',roster:[ + {id:'terraria/king_slime',name:'Bouncing Gel Giant',arch:'Jumps, teleports, and slime minions'}, + {id:'terraria/eye_of_cthulhu',name:'Charging Giant Eye',arch:'Read the charge lane and adapt to phase-two rapid charges'}, + {id:'terraria/skeletron',name:'Twin-Handed Giant Skull',arch:'Independent hands, spinning pursuit, and armor windows'}, + {id:'terraria/eater_of_worlds',name:'Burrowing Great Worm',arch:'Burrowing, segmented targets, and real splitting'}, + {id:'terraria/queen_bee',name:'Charging Giant Bee',arch:'Align with lane charges, bee summons, and stinger volleys'}, + {id:'terraria/brain_of_cthulhu',name:'Teleporting Flesh Brain',arch:'Clear the guard eyes, then chase the teleporting core'} + ]}; + // Public three tiers (tiers.js): the shared page builds its difficulty buttons from this declaration. + g.BB.GAME.tiers=g.BB.TR.TIER_D; + g.BB.GAME.resetOptions=function(){var el=g.document&&g.document.getElementById('world-start');return {dawn_in_seconds:el?+el.value:540};}; + if(g.document){var cue=g.document.getElementById('show-cues');if(cue)cue.addEventListener('change',function(){g.BB.TR.showCues=cue.checked;});} +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/index.html b/environments/games/web/games/terraria_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..fcb605800d6475a35669dc1130a034e6b7f01714 --- /dev/null +++ b/environments/games/web/games/terraria_remake/index.html @@ -0,0 +1,68 @@ + + + + +Terraria · Arena Trials | BossBench + + +
    +

    Terraria ARENA TRIALS

    One loadout, six challenges. Read attacks and master your positioning.

    ← BOSSBENCH
    +
    + +

    Choose your challenge

    +
    Difficulty + + +
    +
    + + + +
    + +

    Adventurer: Fixed Equipment

      +
    • A/D Move; hold Space to jump higher and continue flying; S drops through platforms.
    • +
    • Move the mouse to aim; J/left mouse button uses the current weapon; Q switches between sword and bow.
    • +
    • E equips the bow; right mouse button equips the sword. Bow is the default with unlimited standard arrows.
    • +
    • The blue bar shows remaining flight time and refills on landing; hold Space to glide after it runs out. The sword sweeps an arc in the facing direction and can hit several worm segments at once.
    • +
    • The charging giant eye leaves at dawn; the twin-handed skull enrages by day. Target lines are off by default because the original game has none; enable assist cues if needed.
    • +
    • All three difficulty tiers use Classic rules: Easy lasts about 25 seconds, Normal about one minute, and Hard about three minutes. Boss health, attack frequency, and damage increase by tier.
    +

    Move list

      +

      Recording and Replay

      +
      +After a match, save its seed, difficulty, and complete keyboard and mouse input.
      +
      Mechanics reference Terraria; visuals and arena are original adaptations.
      +
      + + + + + + + + + + diff --git a/environments/games/web/games/terraria_remake/presentation.js b/environments/games/web/games/terraria_remake/presentation.js new file mode 100644 index 0000000000000000000000000000000000000000..737e8a33c65a78c7a67227def0de22f664a66dc7 --- /dev/null +++ b/environments/games/web/games/terraria_remake/presentation.js @@ -0,0 +1,32 @@ +// Original synthesized cues; presentation never changes the simulation or its RNG. +(function(g){ + var BB=g.BB,ctx=null; + function unlock(){ + var Audio=g.AudioContext||g.webkitAudioContext;if(!Audio)return; + if(!ctx)ctx=new Audio();if(ctx.state==='suspended')ctx.resume().catch(function(){}); + } + if(g.document){g.document.addEventListener('pointerdown',unlock,{once:true});g.document.addEventListener('keydown',unlock,{once:true});} + function tone(hz,duration,volume,type,end){ + if(!ctx||ctx.state!=='running')return; + var o=ctx.createOscillator(),a=ctx.createGain(),t=ctx.currentTime; + o.type=type||'triangle';o.frequency.setValueAtTime(hz,t);if(end)o.frequency.exponentialRampToValueAtTime(end,t+duration); + a.gain.setValueAtTime(volume,t);a.gain.exponentialRampToValueAtTime(.0001,t+duration); + o.connect(a);a.connect(ctx.destination);o.start(t);o.stop(t+duration); + } + var consume=BB.Juice.prototype.consume; + BB.Juice.prototype.consume=function(c,R){ + var start=this.caseRef===c&&c.events.length>=this.seen?this.seen:c.events.length; + consume.call(this,c,R); + if(!c.id.startsWith('terraria/'))return; + // Terraria has no artificial hit-stop. Keep the shared visual particles. + this.hitstop=0; + if(!R.canvas||R.canvas.id!=='view'||!g.document.getElementById('select').classList.contains('hidden'))return; + var count=0; + for(var i=start;i one legal 200 ms packet. +// It reads the live BB.Case (privileged state) and evaluates candidate key sets on isolated deep copies +// (their own RNG copy, no shared objects except the immutable case definition), so the live simulation and +// its RNG are never touched. Deterministic: no Math.random, no clock, no memory between calls. +// It is a reference/demo controller, never shown to a policy; its wins are not model or human results. +(function (g) { + var BB = g.BB, SC = BB.TR.SCRIPTED = {}; + function copy(v) { + if (!v || typeof v !== 'object') return v; + if (Array.isArray(v)) return v.map(copy); + var o = Object.create(Object.getPrototypeOf(v)); + Object.keys(v).forEach(function (k) { o[k] = k === 'def' ? v[k] : k === 'events' ? [] : copy(v[k]); }); + return o; + } + function dist(a, b) { return Math.hypot(a.x - b.x, a.y - b.y); } + // Aim point: the nearest live target part (Eater segments above ground, Expert Skeletron hands first, + // close minions), led by its velocity over the arrow flight time. + function aimTarget(c) { + var w = c.boss, b = c.body.centre(), parts = []; + if (w.segments) parts = w.segments.filter(function (s) { return s.hp > 0 && s.y > 0.1; }); + else if (w.hands && w.k.expert >= .5) parts = w.hands.filter(function (h) { return h.hp > 0; }); + if (!parts.length) parts = [w]; + parts = parts.concat((w.minions || []).filter(function (m) { return m.hp > 0 && dist(m, b) < 4; })); + parts.sort(function (a, z) { return dist(a, b) - dist(z, b); }); + var p = parts[0], flight = dist(p, b) / 31; + var lead = (w.st === 'antic' || w.st === 'recover') ? 0 : Math.min(.35, flight); + return { x: BB.clamp(p.x + (p.vx || 0) * lead, .1, 26.9), y: BB.clamp(p.y + (p.vy || 0) * lead + 1.5 * flight * flight, .1, 14.9) }; + } + // Same keys held for all six sub-steps; Space is released for one packet when a fresh press is needed. + function packet(c, keys) { + var t = aimTarget(c); keys = Object.assign({}, keys); + if (keys.Space && c.body.grounded && c.body.prev.jump) delete keys.Space; + var held = []; for (var i = 0; i < BB.SUBSTEPS; i++) held.push(keys); + return BB.formatPacket(held, [BB.clamp(Math.round((t.x - c.body.aimX) * 30), -1000, 1000), BB.clamp(Math.round((c.body.aimY - t.y) * 30), -1000, 1000), 0]); + } + function runPacket(s, text) { + var p = BB.parsePacket(text), m = p.mouse.map(function (v) { return v / 12; }); + for (var j = 0; j < 12 && !s.result; j++) s.tick(p.subs[Math.floor(j / 2)], m); + } + function bossHealth(w) { return w.hp + (w.hands ? w.hands.reduce(function (a, h) { return a + h.hp; }, 0) : 0); } + function candidates(c, expertEye) { + var a = [{ E: true }, { E: true, A: true }, { E: true, D: true }, { E: true, Space: true }, { E: true, A: true, Space: true }, + { E: true, D: true, Space: true }, { E: true, S: true }, { E: true, A: true, S: true }, { E: true, D: true, S: true }]; + // The sword is offered where melee arcs pay: Eater segments, Expert Eye, Queen Bee's bee swarms and the Brain's + // Creeper ring (one arc clears several; r6 round 1: hard Queen Bee 6/8 -> 8/8, hard Brain 2/8 -> 8/8 with the + // sword and a 9-packet look-ahead that sees a returning Creeper coming). + if (c.boss.segments || expertEye || c.id === 'terraria/queen_bee' || c.id === 'terraria/brain_of_cthulhu') a = a.concat([{ RMB: true }, { RMB: true, A: true }, { RMB: true, D: true }, { RMB: true, Space: true }, + { RMB: true, A: true, Space: true }, { RMB: true, D: true, Space: true }]); + return a; + } + // Score of holding `keys` for `horizon` packets on a copy: health kept, Boss damage dealt, distance from + // hazards, remaining wing time, and a small penalty for being pinned at a side wall. + // Expert Eye chain dashes change direction every ~0.35-0.65 s, so holding one key set for 10 packets is a poor + // model of the future. There, each candidate first packet is scored by its best follow-up among a few + // continuations (round 3: Expert Eye seeds 1-8 went from 4/8 to 6/8 wins in the Node stress). + var CONTINUATIONS = [null, { E: true }, { E: true, A: true }, { E: true, D: true }]; + function evaluate(c, keys, horizon, expertEye, cont) { + var s = copy(c), initial = s.body.hp, before = bossHealth(s.boss); + for (var n = 0; n < horizon && !s.result; n++) runPacket(s, packet(s, n === 0 || !cont ? keys : cont)); + return score(s, initial, before, expertEye); + } + function score(s, initial, before, expertEye) { + var b = s.body.centre(), near = 0; + s.boss.hazards().forEach(function (h) { + var q = h.box || { x: h.circle[0], y: h.circle[1] }; near += Math.max(0, 3 - Math.hypot(q.x - b.x, q.y - b.y)); + }); + // Eater: health counts 22 per point, not 14. With the r5 worm AI the chain keeps sweeping back through the + // player, so trading sword hits inside it pays over 1.2 s but drains 200 HP over a long fight (r5 round 3: + // hard tier 3/24 losses at 58-81 s with 14; 8/8 with 22, including those three seeds). r7 (no natural regen): + // 26. Over seeds 1-32 hard, 22 lost seed 25 at 88 s; 26, 30 and 34 all win 32/32 (in window 29, 29, 28; normal + // 28, 28, 29). 26 and 30 tie on counts; 26 is used because the recorded seed 1 finishes in the hard window with it + // (204 s vs 142 s). A look-ahead of 9 instead of 6 also saved seed 25 but finished 4 hard seeds under 150 s. + var score = (s.body.hp - initial) * (expertEye ? 16 : s.boss.segments ? 26 : 14) + (before - bossHealth(s.boss)) * (expertEye ? 1.6 : .6) - near * 8 + s.body.flight * 2; + if (s.result === 'loss') score -= 10000; if (s.result === 'win') score += 10000; + return score - Math.max(0, 2 - s.body.x) - Math.max(0, s.body.x - 25); + } + // Classic hard Skeletron: hand swipes come between spins at 1.15x cadence, so a single key set held for the whole + // look-ahead cannot both dodge the swipe and line up the next shot. Two plies: every first packet is scored by its + // best follow-up key set held for the rest of the 1.8 s horizon (r6 round 1: hard 7/16 with one ply, 16/16 on the + // 8 failing seeds with two; ~40 ms per 200 ms packet). + function twoPly(c, horizon) { + var initial = c.body.hp, before = bossHealth(c.boss), list = candidates(c, false), best = null, bestScore = -Infinity; + list.forEach(function (k1) { + var s1 = copy(c); runPacket(s1, packet(s1, k1)); var top = -Infinity; + list.forEach(function (k2) { + var s2 = copy(s1); for (var n = 1; n < horizon && !s2.result; n++) runPacket(s2, packet(s2, k2)); + top = Math.max(top, score(s2, initial, before, false)); + }); + if (top > bestScore) { bestScore = top; best = k1; } + }); + return packet(c, best); + } + function decide(c) { + var expertEye = c.id === 'terraria/eye_of_cthulhu' && !!c.boss.expert; + if (c.boss.hands && !c.boss.expert && c.boss.pace.aggr > 1) return twoPly(c, 9); + // Skeletron's spin chases for 6.7 s: Expert needs a 2.4 s look-ahead to plan the escape past the head. + var horizon = expertEye ? 10 : c.id === 'terraria/brain_of_cthulhu' ? 9 : c.boss.hands && c.boss.expert ? 12 : 6, best = null, bestScore = -Infinity; + candidates(c, expertEye).forEach(function (keys) { + var score = -Infinity; + (expertEye ? CONTINUATIONS : [null]).forEach(function (cont) { score = Math.max(score, evaluate(c, keys, horizon, expertEye, cont)); }); + if (score > bestScore) { bestScore = score; best = keys; } + }); + return packet(c, best); + } + SC.copy = copy; SC.packet = packet; SC.decide = decide; SC.aimTarget = aimTarget; + BB.GAME.scripted = function (c) { return decide(c); }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/terraria_remake/semantic_ppo_v1/__init__.py b/environments/games/web/games/terraria_remake/semantic_ppo_v1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..13ef4b83bfd63fbbe6e09c5b6c36021e8017f4b7 --- /dev/null +++ b/environments/games/web/games/terraria_remake/semantic_ppo_v1/__init__.py @@ -0,0 +1,4 @@ +from .env import SemanticEnv, make_semantic_env +from .actions import to_named, to_indices + +__all__ = ['SemanticEnv', 'make_semantic_env', 'to_named', 'to_indices'] diff --git a/environments/games/web/games/terraria_remake/semantic_ppo_v1/actions.py b/environments/games/web/games/terraria_remake/semantic_ppo_v1/actions.py new file mode 100644 index 0000000000000000000000000000000000000000..1282a25b9ae72f963936af73dfbed579e4897440 --- /dev/null +++ b/environments/games/web/games/terraria_remake/semantic_ppo_v1/actions.py @@ -0,0 +1,42 @@ +"""The named action vocabulary shown to an LLM; integer IDs stay inside PPO.""" +from numbers import Integral +import gymnasium as gym +import numpy as np + +FIELDS = ('move', 'vert', 'attack') +LABELS = (('none', 'left', 'right'), ('none', 'jump', 'drop'), + ('none',) + tuple(f'shoot {i*22.5:g}' for i in range(16)) + ('slash left', 'slash right')) + + +def to_named(indices): + if len(indices) != 3 or any(isinstance(v, (bool, np.bool_)) or not isinstance(v, Integral) + or not 0 <= v < len(labels) for v, labels in zip(indices, LABELS)): + raise ValueError('expected three categorical integer IDs in [3,3,19]') + return {field: labels[int(i)] for field, labels, i in zip(FIELDS, LABELS, indices)} + + +def to_indices(action): + """Decode canonical named fields; the environment additionally accepts text envelopes.""" + if not isinstance(action, dict) or set(action) != set(FIELDS): + raise ValueError('expected move, vert, attack fields') + return tuple(labels.index(action[field]) for field, labels in zip(FIELDS, LABELS)) + + +class NamedActions(gym.Space): + def __init__(self, seed=None): + super().__init__(None, None, seed) + + def sample(self, mask=None, probability=None): + if mask is not None or probability is not None: + raise ValueError('named action masking is not supported') + return to_named([int(self.np_random.integers(len(labels))) for labels in LABELS]) + + def contains(self, action): + try: + to_indices(action) + return True + except (TypeError, ValueError, KeyError): + return False + + def __repr__(self): + return 'NamedActions(move=3, vert=3, attack=19)' diff --git a/environments/games/web/games/terraria_remake/semantic_ppo_v1/env.py b/environments/games/web/games/terraria_remake/semantic_ppo_v1/env.py new file mode 100644 index 0000000000000000000000000000000000000000..76339c0c1d0f2ca030a4da586215284afa05eff4 --- /dev/null +++ b/environments/games/web/games/terraria_remake/semantic_ppo_v1/env.py @@ -0,0 +1,252 @@ +"""Experimental RGB / 100 ms semantic Gym environment, independent of policy-gym@2.""" +from __future__ import annotations + +import base64 +import copy +import hashlib +import json +import math +from numbers import Integral +from pathlib import Path +import re +import shutil +import subprocess + +import gymnasium as gym +import numpy as np + +from bossbench.unified import _finite_number, _plain, _reset_options +from bossbench.tiers import resolve_options +from bossbench.webenv import BrowserTransport +from .actions import NamedActions, FIELDS, LABELS + +HERE = Path(__file__).resolve().parent +GAME = HERE.parent +ROOT = HERE.parents[3] +PROTOCOL = ('Output a JSON object with explicit action meanings, for example ' + '{"move":"left","vert":"jump","attack":"shoot 135"}. ' + 'All three fields execute concurrently in one 100 ms window; use "none" for no action. ' + '0 degrees points right, 90 up. The 16 shoot directions are multiples of 22.5 degrees. ' + 'Text envelopes such as <|semantic_start|> left ; jump ; shoot 135 <|semantic_end|> are also accepted. ' + 'Invalid input executes a no-op; never output categorical integer IDs in the LLM response.') + + +def source_manifest(): + """Fingerprint precisely the frozen page plus the experimental adapter.""" + page = (GAME / 'index.html').read_text(encoding='utf-8') + frozen = hashlib.sha256() + for name in re.findall(r' diff --git a/environments/games/web/games/tombraider_remake/lizard.js b/environments/games/web/games/tombraider_remake/lizard.js new file mode 100644 index 0000000000000000000000000000000000000000..de5c6baa44cea030154282737b5d7f5052c48cfe --- /dev/null +++ b/environments/games/web/games/tombraider_remake/lizard.js @@ -0,0 +1,72 @@ +/* Tomb Raider (1996) boss arenas - the T-Rex of Lost Valley. State logic and thresholds from TRX objects/creatures/trex.c (TR1 branch): + see section A. Approximation: ANIM lengths, speeds, body spheres and the bite's head path (animation/mesh data). */ +(function (root) { + 'use strict'; + const M = root.TombRaiderGame, T = M.T, { deg } = T; + const HP = [120, 280, 700], TOUCH = 1, TRAMPLE = 10, BITE = 10000, PIVOT = 2000, RADIUS = 341; + const RUN_RANGE = Math.pow(5 * T.WALL_L, 2), ATTACK_RANGE = Math.pow(4 * T.WALL_L, 2), BITE_RANGE = 1500 * 1500, ROAR_CHANCE = 512; + const WALK_TURN = T.v(deg(2)), RUN_TURN = T.v(deg(4)); + // Approximation: original ticks per cycle, units per original tick; converted to 60 Hz by T.anim. + const ANIM = T.REX_ANIM = T.anim({ stop: { len: 8, speed: 0 }, walk: { len: 20, speed: 36 }, run: { len: 16, speed: 80 }, bite: { len: 42, speed: 0 }, roar: { len: 48, speed: 0 } }); + const BITE_FROM = T.n(16), BITE_TO = T.n(30); // ticks of the bite where the head sweeps forward: the telegraph is the first 16 + const BODY = [[-2300, 800, 240], [-1500, 1000, 340], [-500, 1200, 620], [400, 1300, 640], [120, 340, 380, 320], [120, 340, 380, -320]]; + const headAt = b => { + if (b.state !== 'bite') return [1800, 1900, 420]; + if (b.stateT < BITE_FROM) return [1800 - 500 * (b.stateT / BITE_FROM), 2050, 420]; + const f = T.clamp((b.stateT - BITE_FROM) / (BITE_TO - BITE_FROM), 0, 1); + return [1300 + 1500 * f, 2050 - 1600 * f, 460]; + }; + T.CREATURES.lizard = { + label: 'Giant-Fanged Lizard Beast', pivot: PIVOT, radius: RADIUS, hpTable: HP, states: { stop: 'Idle', walk: 'Walking slowly', run: 'Charge', bite: 'Gaping bite', roar: 'Roar' }, + spawn(g, x, z, rot) { + const k = g.tierScale, hp = Math.round(T.tierValue(g.d, g.tiers, HP)); + return { kind: 'lizard', x, y: 0, z, rot, hp, maxHp: hp, state: 'stop', goal: 'stop', req: '', stateT: 0, flag: false, turn: 0, bites: 0, roars: 0, attacks: 0, + touchDmg: T.v(TOUCH * k.damage), trampleDmg: T.v(TRAMPLE * k.damage), roarChance: T.chance(ROAR_CHANCE * k.chatter), stopLen: Math.round(ANIM.stop.len * k.pause) }; + }, + aimPoint: b => ({ x: b.x + T.sin(b.rot) * 200, y: b.y + 1250, z: b.z + T.cos(b.rot) * 200 }), + // Telegraphs (tr1-arena@3): which damaging move is winding up or live, for the renderer, the HUD and the measurement scripts. A pure function + // of the boss state; nothing in the simulation reads it. windup = ticks between the move's start and its first damaging tick (the source's). + moves: { bite: { label: 'Gaping bite (instant kill)', windup: BITE_FROM, form: 'Draws head back and opens mouth' }, trample: { label: 'Charging trample', windup: 0, form: 'Charge posture (no original wind-up)' } }, + tele: b => b.state === 'bite' ? (b.stateT < BITE_FROM ? { move: 'bite', phase: 'windup', k: b.stateT / BITE_FROM } : b.stateT <= BITE_TO ? { move: 'bite', phase: 'active', k: 1 } : null) + : b.state === 'run' ? { move: 'trample', phase: 'active', k: 1 } : null, + headLocal: headAt, shadow: 700, + spheres(b) { return T.bodySpheres(b, BODY.concat([headAt(b)])); }, + headSphere(b) { return T.bodySpheres(b, [headAt(b)])[0]; }, + tick(g, b) { + const L = g.lara, i = T.aiInfo(g, b, PIVOT), a = ANIM[b.state]; + b.turn = T.creatureMove(g, b, a.speed, b.state === 'run' ? RUN_TURN : WALK_TURN, RADIUS); + if (T.pushLara(g, this.spheres(b))) T.laraDamage(g, b.state === 'run' ? b.trampleDmg : b.touchDmg, 'lizard_touch'); + b.flag = !i.ahead && i.facing > -T.DEG90 && i.facing < T.DEG90; + if (!b.flag && i.distance > BITE_RANGE && i.distance < ATTACK_RANGE && i.bite) b.flag = true; + switch (b.state) { + case 'stop': + if (b.req) b.goal = b.req; + else if (i.distance < BITE_RANGE && i.bite) b.goal = 'bite'; + else b.goal = b.flag ? 'walk' : 'run'; + break; + case 'walk': // TRX: any mood but BORED leaves the walk at once, so an attacking rex steps and stops + b.goal = 'stop'; + break; + case 'run': + if (i.distance < RUN_RANGE && i.bite) b.goal = 'stop'; + else if (b.flag) b.goal = 'stop'; + else if (i.ahead && T.rand(g) < b.roarChance) { b.req = 'roar'; b.goal = 'stop'; } + break; + case 'bite': { + if (b.stateT === 0) { b.attacks++; T.event(g, 'lizard_bite_start'); } + const h = this.headSphere(b); + if (b.stateT >= BITE_FROM && b.stateT <= BITE_TO && T.touchesLara(L, null, h[0], h[1], h[2], h[3])) { b.bites++; T.laraDamage(g, BITE, 'lizard_bite'); } + b.req = 'walk'; b.goal = 'stop'; + break; + } + case 'roar': + if (b.stateT === 0) { b.roars++; T.event(g, 'lizard_roar'); } + b.goal = 'stop'; + break; + } + const len = b.state === 'stop' ? b.stopLen : a.len; + b.stateT++; + if (b.stateT >= len && b.goal !== b.state) { b.state = b.goal; b.stateT = 0; if (b.state === b.req) b.req = ''; } + }, + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/tombraider_remake/manifest.json b/environments/games/web/games/tombraider_remake/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..c48c7192ad56b159a433be1003ebd1703e651a2b --- /dev/null +++ b/environments/games/web/games/tombraider_remake/manifest.json @@ -0,0 +1,53 @@ +{ + "schema": "bossbench/game-manifest@1", + "engine": "independent", + "game": "tombraider_remake", + "module": "TombRaiderGame", + "title": "Tomb Raider 1: Ruins Bosses", + "dimension": "3d", + "native_hz": 60, + "max_seconds": 300, + "renderer": "webgl-tombraider", + "rules": "tr1-arena@3", + "cases": [ + "tombraider/giant_lizard", + "tombraider/lone_gunman", + "tombraider/cannon_quadruped", + "tombraider/twin_pistols", + "tombraider/legless_giant", + "tombraider/winged_matriarch" + ], + "scripts": [ + "_native/runtime.js", + "_boss3d/vendor/three.min.js", + "tombraider_remake/tr1core.js", + "tombraider_remake/tr1player.js", + "tombraider_remake/tr1camera.js", + "tombraider_remake/tr1creature.js", + "tombraider_remake/lizard.js", + "tombraider_remake/human.js", + "tombraider_remake/fleshkin.js", + "tombraider_remake/game.js", + "tombraider_remake/scripted.js", + "tombraider_remake/renderer3d.js", + "tombraider_remake/draw.js" + ], + "sim_scripts": [ + "_native/runtime.js", + "tombraider_remake/tr1core.js", + "tombraider_remake/tr1player.js", + "tombraider_remake/tr1camera.js", + "tombraider_remake/tr1creature.js", + "tombraider_remake/lizard.js", + "tombraider_remake/human.js", + "tombraider_remake/fleshkin.js", + "tombraider_remake/game.js", + "tombraider_remake/scripted.js" + ], + "play_page": "web/games/tombraider_remake/index.html", + "scripted_controller": "TombRaiderGame.scripted(game) -> {holds:[6 key arrays], mouse:[0,0,0]}; privileged state, look-ahead on copies whose RNG is reseeded per tick by a multiply mix", + "tests": [ + "tombraider_remake/tests/mechanics.js" + ], + "source": "https://github.com/LostArtefacts/TRX/tree/4b9b64f5a717330d148d5d0e0eef220ff389b480 (GPL-3, read only) and https://github.com/XProger/OpenLara/tree/3b268ca4bf986c380f44a26ffd9218bf6d376249 (BSD-2, read only)" +} diff --git a/environments/games/web/games/tombraider_remake/renderer3d.js b/environments/games/web/games/tombraider_remake/renderer3d.js new file mode 100644 index 0000000000000000000000000000000000000000..08ab727542543af90e18c81f7918d919082fcbaa --- /dev/null +++ b/environments/games/web/games/tombraider_remake/renderer3d.js @@ -0,0 +1,454 @@ +/* Tomb Raider (1996) boss arenas - original procedural 3D art on Three.js r160 (MIT, shared read-only vendor copy in web/games/_boss3d/vendor). + Third-person chase camera behind Lara. Low-poly, vertex-shaded and nearest-filtered as a nod to the 1996 look, but every mesh, texture and + colour here is generated by this file; no Tomb Raider model, texture or level geometry is used. Rendering is a pure function of the game + state: it never writes the simulation and never draws gameplay RNG, and animation time comes from the state's tick counter. + Axes: game (x, y up, z) with rot 0 = +z, turning right; three.js (x, y, -z), rotation.y = -rot. */ +(function (root) { + 'use strict'; + const TH = root.THREE, M = root.TombRaiderGame, T = M && M.T; + if (!TH) throw Error('Three.js is missing (web/games/_boss3d/vendor/three.min.js)'); + const R = M.R3 = {}, S = 1 / 256, A2R = Math.PI * 2 / 65536, byCanvas = new WeakMap(); + const vec = (x, y, z, out) => (out || new TH.Vector3()).set(x * S, y * S, -z * S); + function hash(x, y, s) { let n = Math.imul(x + 374761393 * s, 668265263) ^ Math.imul(y + s, 2246822519); n = Math.imul(n ^ (n >>> 13), 1274126177); return ((n ^ (n >>> 16)) >>> 0) / 4294967295; } + + // ---------------- procedural textures ---------------- + function tex(paint, size) { + const c = document.createElement('canvas'); c.width = c.height = size || 128; paint(c.getContext('2d'), c.width); + const t = new TH.CanvasTexture(c); t.colorSpace = TH.SRGBColorSpace; t.wrapS = t.wrapT = TH.RepeatWrapping; t.magFilter = TH.NearestFilter; t.minFilter = TH.NearestMipmapLinearFilter; return t; + } + const speckle = (q, n, base, amp, seed, grain) => { const im = q.createImageData(n, n); for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) { const v = (hash(x >> (grain || 0), y >> (grain || 0), seed) - .5) * amp + (hash(x >> 3, y >> 3, seed + 3) - .5) * amp, i = (y * n + x) * 4; im.data[i] = base[0] + v; im.data[i + 1] = base[1] + v * .95; im.data[i + 2] = base[2] + v * .85; im.data[i + 3] = 255; } q.putImageData(im, 0, 0); }; + const blocks = (q, n, rows, col, seed) => { q.strokeStyle = col; q.lineWidth = 2; const h = n / rows; for (let r = 0; r < rows; r++) { q.beginPath(); q.moveTo(0, r * h); q.lineTo(n, r * h); q.stroke(); const off = r % 2 ? n / 4 : 0; for (let k = 0; k < 2; k++) { const x = off + k * n / 2 + (hash(r, k, seed) - .5) * 8; q.beginPath(); q.moveTo(x, r * h); q.lineTo(x, r * h + h); q.stroke(); } } }; + const PAINT = { + grass(q, n) { speckle(q, n, [78, 98, 46], 44, 5, 1); for (let k = 0; k < 90; k++) { q.fillStyle = k % 3 ? 'rgba(40,62,24,.7)' : 'rgba(136,146,70,.6)'; q.fillRect(hash(k, 1, 7) * n, hash(k, 2, 7) * n, 2, 5); } }, + cliff(q, n) { speckle(q, n, [104, 92, 76], 54, 9); q.strokeStyle = 'rgba(40,32,26,.75)'; q.lineWidth = 3; for (let k = 0; k < 7; k++) { let x = hash(k, 0, 3) * n, y = 0; q.beginPath(); q.moveTo(x, y); while (y < n) { y += 12 + hash(k, y, 4) * 16; x += (hash(k, y, 5) - .5) * 34; q.lineTo(x, y); } q.stroke(); } }, + sand(q, n) { speckle(q, n, [168, 138, 92], 34, 12, 1); blocks(q, n, 2, 'rgba(86,62,34,.8)', 2); }, + sandwall(q, n) { speckle(q, n, [150, 120, 80], 38, 14); blocks(q, n, 4, 'rgba(66,46,26,.85)', 3); q.fillStyle = 'rgba(190,150,70,.35)'; for (let k = 0; k < 6; k++) q.fillRect(14 + k * 19, 34, 9, 9); }, + dark(q, n) { speckle(q, n, [70, 70, 78], 30, 16, 1); blocks(q, n, 2, 'rgba(24,24,30,.9)', 4); }, + darkwall(q, n) { speckle(q, n, [78, 76, 88], 34, 18); blocks(q, n, 3, 'rgba(24,22,30,.85)', 5); q.strokeStyle = 'rgba(96,170,160,.45)'; q.lineWidth = 2; q.strokeRect(n * .3, n * .36, n * .4, n * .26); }, + flesh(q, n) { speckle(q, n, [120, 52, 48], 46, 21); q.strokeStyle = 'rgba(60,14,20,.8)'; q.lineWidth = 3; for (let k = 0; k < 9; k++) { q.beginPath(); q.moveTo(hash(k, 3, 1) * n, 0); q.bezierCurveTo(hash(k, 4, 1) * n, n / 3, hash(k, 5, 1) * n, n * .6, hash(k, 6, 1) * n, n); q.stroke(); } }, + gold(q, n) { speckle(q, n, [150, 114, 46], 40, 25); blocks(q, n, 2, 'rgba(70,46,12,.85)', 6); }, + scale(q, n) { speckle(q, n, [78, 92, 54], 40, 28); q.strokeStyle = 'rgba(30,42,20,.8)'; for (let y = 0; y < n; y += 10) for (let x = (y / 10) % 2 * 6; x < n; x += 12) { q.beginPath(); q.arc(x, y, 6, 0, Math.PI); q.stroke(); } q.fillStyle = 'rgba(160,140,70,.25)'; q.fillRect(0, n * .75, n, n * .25); }, + mutant(q, n) { speckle(q, n, [150, 96, 88], 46, 31); q.fillStyle = 'rgba(90,20,34,.55)'; for (let k = 0; k < 14; k++) { q.beginPath(); q.arc(hash(k, 1, 9) * n, hash(k, 2, 9) * n, 4 + hash(k, 3, 9) * 8, 0, 7); q.fill(); } }, + }; + const THEME = { + valley: { floor: 'grass', wall: 'cliff', wallH: 6, natural: true, fog: [0xa8b8a4, 9000, 30000], sky: ['#5f8fb0', '#b8cdb4', '#d8d2b0'], hemi: [0xe8f0ff, 0x4a5a30, 2.4], sun: [0xfff0d0, 2.2] }, + hall: { floor: 'sand', wall: 'sandwall', wallH: 4, ceil: true, fog: [0x2a1f14, 3000, 13000], hemi: [0xffe0b0, 0x40301c, 2.2], sun: [0xffc080, .9], torch: true }, + crypt: { floor: 'dark', wall: 'darkwall', wallH: 4, ceil: true, fog: [0x151a22, 3000, 14000], hemi: [0xc8d8ff, 0x2a2a38, 2.4], sun: [0xa0c0ff, .9], torch: true }, + pit: { floor: 'flesh', wall: 'flesh', wallH: 5, ceil: true, natural: true, fog: [0x2a0c0e, 2500, 14000], hemi: [0xffc0a8, 0x401018, 2.6], sun: [0xff9060, 1], torch: false }, + gold: { floor: 'gold', wall: 'gold', wallH: 6, ceil: true, fog: [0x241204, 3000, 16000], hemi: [0xffd8a0, 0x402810, 2.4], sun: [0xffa850, 1.2], torch: true }, + }; + const SIDES = [[1, 0, 1, 0, 1, 1], [-1, 0, 0, 1, 0, 0], [0, 1, 1, 1, 0, 1], [0, -1, 0, 0, 1, 0]]; + function arenaGeometry(m, th) { + const fp = [], fu = [], fc = [], fi = [], wp = [], wu = [], wc = [], wi = [], W = T.WALL_L, top = th.wallH * W; + const h = (i, j) => (i < 0 || j < 0 || i >= m.w || j >= m.h ? T.WALL : m.cells[j * m.w + i]); + const jig = () => 0; // a jittered rock face left slivers of sky at the corners; the texture carries the rock look instead + const shade = (i, j) => 1 - .1 * [[0, 0], [-1, 0], [0, -1], [-1, -1]].filter(([a, b]) => h(i + a, j + b) === T.WALL).length; + const quad = (p, u, c, ix, q, uv, cs) => { const n = p.length / 3; for (let k = 0; k < 4; k++) { p.push(q[k][0] * S, q[k][1] * S, -q[k][2] * S); u.push(uv[k][0], uv[k][1]); c.push(cs[k], cs[k], cs[k] * .98); } ix.push(n, n + 1, n + 2, n, n + 2, n + 3); }; + for (let j = 0; j < m.h; j++) for (let i = 0; i < m.w; i++) { + const f = h(i, j); if (f === T.WALL) continue; + const n = hash(i, j, 11) * .1 + .9; + quad(fp, fu, fc, fi, [[i * W, f, j * W], [(i + 1) * W, f, j * W], [(i + 1) * W, f, (j + 1) * W], [i * W, f, (j + 1) * W]], [[0, 0], [1, 0], [1, 1], [0, 1]], + [shade(i, j) * n, shade(i + 1, j) * n, shade(i + 1, j + 1) * n, shade(i, j + 1) * n]); + for (const [di, dj, ax, az, bx, bz] of SIDES) { + const o = h(i + di, j + dj); if (o <= f) continue; + const roof = o === T.WALL ? top : o, tiers = Math.max(1, Math.round((roof - f) / W)); + for (let k = 0; k < tiers; k++) { + const y0 = f + (roof - f) * k / tiers, y1 = f + (roof - f) * (k + 1) / tiers, a = [(i + ax) * W, (j + az) * W], b = [(i + bx) * W, (j + bz) * W]; + const j00 = jig(Math.round(a[0] / W), Math.round(a[1] / W), k, 1), j10 = jig(Math.round(b[0] / W), Math.round(b[1] / W), k, 1), j01 = jig(Math.round(a[0] / W), Math.round(a[1] / W), k + 1, 1), j11 = jig(Math.round(b[0] / W), Math.round(b[1] / W), k + 1, 1); + const light = (dj ? .86 : 1) * (.72 + .28 * (k + .5) / tiers), lo = k === 0 ? light * .72 : light; + quad(wp, wu, wc, wi, [[a[0] + di * j00, y0, a[1] + dj * j00], [b[0] + di * j10, y0, b[1] + dj * j10], [b[0] + di * j11, y1, b[1] + dj * j11], [a[0] + di * j01, y1, a[1] + dj * j01]], [[0, k + 1], [1, k + 1], [1, k], [0, k]], [lo, lo, light, light]); + } + } + if (th.ceil) quad(wp, wu, wc, wi, [[i * W, top, j * W], [i * W, top, (j + 1) * W], [(i + 1) * W, top, (j + 1) * W], [(i + 1) * W, top, j * W]], [[0, 0], [0, 1], [1, 1], [1, 0]], [.34, .34, .34, .34]); + } + const make = (p, u, c, ix) => { const g = new TH.BufferGeometry(); g.setAttribute('position', new TH.Float32BufferAttribute(p, 3)); g.setAttribute('uv', new TH.Float32BufferAttribute(u, 2)); g.setAttribute('color', new TH.Float32BufferAttribute(c, 3)); g.setIndex(ix); return g; }; + return { floor: make(fp, fu, fc, fi), wall: make(wp, wu, wc, wi) }; + } + + // ---------------- model helpers: origin at the feet, forward = -z ---------------- + class Kit { + constructor(scene) { this.mats = new Map(); this.scene = scene; } + mat(color, opts) { const k = color + JSON.stringify(opts ? Object.keys(opts) : 0) + (opts && opts.map ? opts.map.uuid : ''); if (!this.mats.has(k)) { const m = new TH.MeshLambertMaterial(Object.assign({ color, flatShading: true }, opts || {})); this.mats.set(k, m); this.scene.keep(m); } return this.mats.get(k); } + add(parent, geo, mat, x, y, z) { const m = new TH.Mesh(geo, mat); this.scene.keep(geo); m.position.set((x || 0) * S, (y || 0) * S, -(z || 0) * S); parent.add(m); return m; } + box(p, w, h, d, c, x, y, z) { return this.add(p, new TH.BoxGeometry(w * S, h * S, d * S), this.mat(c), x, y, z); } + cyl(p, rt, rb, h, c, x, y, z, seg) { return this.add(p, new TH.CylinderGeometry(rt * S, rb * S, h * S, seg || 7), this.mat(c), x, y, z); } + ball(p, r, c, x, y, z, map) { return this.add(p, new TH.IcosahedronGeometry(r * S, 1), map ? this.mat(0xffffff, { map }) : this.mat(c), x, y, z); } + group(p, x, y, z) { const g = new TH.Group(); g.position.set((x || 0) * S, (y || 0) * S, -(z || 0) * S); p.add(g); return g; } + limb(p, x, y, z, r1, r2, len, c) { const g = this.group(p, x, y, z); this.cyl(g, r1, r2, len, c, 0, -len / 2, 0); return g; } + } + function human(k, o) { // a generic low-poly person: o = { skin, top, legs, boots, hair, scale }; hips at y 400 + const root = new TH.Group(), s = o.scale || 1, hips = k.group(root, 0, 400 * s, 0), L = {}; + root.scale.set(1, 1, 1); + k.cyl(hips, 86 * s, 96 * s, 110 * s, o.legs, 0, 10, 0); + k.cyl(hips, 99 * s, 99 * s, 28 * s, o.belt || 0x3a2a1c, 0, 58 * s, 0, 8); + if (o.coat) k.cyl(hips, 104 * s, 150 * s, 300 * s, o.coat, 0, -130 * s, 0, 8); + const torso = L.torso = k.group(hips, 0, 60 * s, 0); + k.cyl(torso, 96 * s, 74 * s, 220 * s, o.top, 0, 110 * s, 0); + k.ball(torso, 44 * s, o.top, -104 * s, 205 * s, 0); k.ball(torso, 44 * s, o.top, 104 * s, 205 * s, 0); + k.cyl(torso, 32 * s, 36 * s, 50 * s, o.skin, 0, 238 * s, 0, 6); + if (o.pack) k.box(torso, 150 * s, 170 * s, 80 * s, o.pack, 0, 120 * s, -96 * s); + L.head = k.group(torso, 0, 250 * s, 0); k.ball(L.head, 62 * s, o.skin, 0, 40 * s, 0); + k.ball(L.head, 9 * s, 0x141414, -22 * s, 52 * s, 56 * s); k.ball(L.head, 9 * s, 0x141414, 22 * s, 52 * s, 56 * s); + if (o.hair) k.ball(L.head, 64 * s, o.hair, 0, 58 * s, -12 * s); + if (o.cap) { k.cyl(L.head, 64 * s, 66 * s, 44 * s, o.cap, 0, 98 * s, 0, 8); k.box(L.head, 90 * s, 12 * s, 70 * s, o.cap, 0, 80 * s, 66 * s); } + L.armL = k.limb(torso, -118 * s, 205 * s, 0, 34 * s, 26 * s, 250 * s, o.skin); L.armR = k.limb(torso, 118 * s, 205 * s, 0, 34 * s, 26 * s, 250 * s, o.skin); + L.legL = k.limb(hips, -52 * s, -30 * s, 0, 50 * s, 34 * s, 370 * s, o.skinLeg || o.legs); L.legR = k.limb(hips, 52 * s, -30 * s, 0, 50 * s, 34 * s, 370 * s, o.skinLeg || o.legs); + k.box(L.legL, 62 * s, 44 * s, 130 * s, o.boots, 0, -380 * s, 18 * s); k.box(L.legR, 62 * s, 44 * s, 130 * s, o.boots, 0, -380 * s, 18 * s); + if (o.holster) { k.box(L.legL, 44 * s, 110 * s, 64 * s, o.holster, -44 * s, -100 * s, 0); k.box(L.legR, 44 * s, 110 * s, 64 * s, o.holster, 44 * s, -100 * s, 0); } + for (const a of [L.armL, L.armR]) { k.ball(a, 30 * s, o.skin, 0, -238 * s, 0); a.gun = k.box(a, 28 * s, 34 * s, 96 * s, o.gun || 0x24262c, 0, -256 * s, 26 * s); a.flash = k.ball(a, 56 * s, 0xffffff, 0, -280 * s, 90 * s); a.flash.material = k.flashMat; a.flash.visible = false; } + Object.assign(root, { parts: L, hips }); + return root; + } + const pose = (m, st, t) => { + const P = m.parts, w = st.run ? Math.sin(t * .42) * .85 : st.walk ? Math.sin(t * .3) * .45 : 0; + P.legL.rotation.x = w; P.legR.rotation.x = -w; + P.armL.rotation.set(-w * .6, 0, -.12); P.armR.rotation.set(w * .6, 0, .12); + m.hips.position.y = (st.crouch ? 300 : 400) * S + (st.run ? Math.abs(Math.sin(t * .42)) * 16 * S : 0); + P.torso.rotation.set(0, 0, 0); + }; + const aimArm = (a, yaw, pitch) => { a.rotation.order = 'YXZ'; a.rotation.set(Math.PI / 2 + pitch, yaw, 0); }; // the limb hangs along -y: +90 degrees about x swings it to the model's forward (-z) + const flash = (a, f) => { if (a.flash) a.flash.visible = f; }; + + const BUILD = { + lara(k) { + const m = human(k, { skin: 0xd8a080, top: 0x6f6a3c, legs: 0x4c4436, boots: 0x2c2620, hair: 0x2a2a2e, pack: 0x5a4a30, holster: 0x3a2a1c }); + const braid = m.parts.braid = k.group(m.parts.head, 0, 60, -56); k.cyl(braid, 24, 16, 80, 0x2a2a2e, 0, -24, 0, 5); + return m; + }, + lizard(k, s) { + const r = new TH.Group(), skin = k.mat(0xffffff, { map: s.tex.scale }), g = new TH.BoxGeometry(1, 1, 1); + const ell = (p, rx, ry, rz, x, y, z) => { const m = k.ball(p, 1, 0, x, y, z); m.material = skin; m.scale.set(rx, ry, rz); return m; }; + const body = k.group(r, 0, 0, 0); ell(body, 430, 520, 1150, 0, 1230, -300); + const P = r.parts = { tail: [], body }; + let parent = k.group(body, 0, 1160, -1250); for (let i = 0; i < 5; i++) { ell(parent, 280 - i * 50, 280 - i * 50, 360, 0, 0, -300); P.tail.push(parent); parent = k.group(parent, 0, -30, -520); } + P.neck = k.group(body, 0, 1500, 700); ell(P.neck, 300, 320, 520, 0, 150, 260); + P.head = k.group(P.neck, 0, 330, 660); ell(P.head, 310, 240, 460, 0, 40, 260); + P.jaw = k.group(P.head, 0, -80, 60); ell(P.jaw, 250, 90, 400, 0, -40, 240); + for (let i = 0; i < 5; i++) { k.cyl(P.head, 0, 26, 110, 0xe8e0c0, -170 + i * 85, -150, 560, 4); k.cyl(P.jaw, 26, 0, 90, 0xe8e0c0, -130 + i * 65, 50, 440, 4); } + k.ball(P.head, 44, 0xd0a020, -220, 150, 400); k.ball(P.head, 44, 0xd0a020, 220, 150, 400); + P.legL = k.group(body, -340, 900, -100); P.legR = k.group(body, 340, 900, -100); + for (const L of [P.legL, P.legR]) { ell(L, 200, 460, 300, 0, -230, 0); ell(L, 110, 320, 130, 0, -640, -80); const f = k.box(L, 240, 80, 460, 0x3a4228, 0, -860, 110); f.castShadow = false; } + k.limb(P.neck, -230, -120, 300, 44, 30, 240, 0x4a5a36); k.limb(P.neck, 230, -120, 300, 44, 30, 240, 0x4a5a36); + return r; + }, + gunman(k) { return human(k, { skin: 0xd0a080, top: 0x6c5a3c, legs: 0x3e3a34, boots: 0x20201c, hair: 0x6a4a28, scale: 1.1, cap: 0x4a4030, belt: 0x201810 }); }, + duelist(k) { return human(k, { skin: 0xd8a888, top: 0x28303c, legs: 0x20242c, boots: 0x101014, hair: 0x101014, scale: 1.05, coat: 0x1c2230, belt: 0x6a5020 }); }, + quadruped(k, s) { + const r = new TH.Group(), skin = k.mat(0xffffff, { map: s.tex.mutant }), P = r.parts = { legs: [] }; + const ell = (p, rx, ry, rz, x, y, z) => { const m = k.ball(p, 1, 0, x, y, z); m.material = skin; m.scale.set(rx, ry, rz); return m; }; + ell(r, 300, 300, 640, 0, 760, -120); + for (const [x, z] of [[-200, 340], [200, 340], [-200, -520], [200, -520]]) { const L = k.group(r, x, 660, z); ell(L, 90, 340, 110, 0, -320, 0); k.box(L, 120, 60, 170, 0x4a3030, 0, -640, 20); P.legs.push(L); } + P.torso = k.group(r, 0, 930, 380); ell(P.torso, 240, 380, 200, 0, 320, 0); + P.head = k.group(P.torso, 0, 740, 40); ell(P.head, 130, 150, 150, 0, 40, 30); k.cyl(P.head, 0, 42, 240, 0xd8d0b0, -100, 190, 20, 4); k.cyl(P.head, 0, 42, 240, 0xd8d0b0, 100, 190, 20, 4); + P.armL = k.limb(P.torso, -300, 560, 0, 84, 60, 560, 0xa06a60); P.armR = k.limb(P.torso, 300, 560, 0, 84, 60, 560, 0xa06a60); + P.cannon = k.cyl(P.armR, 60, 90, 260, 0x60504a, 0, -640, 0, 6); P.glow = k.ball(P.armR, 86, 0xffffff, 0, -790, 0); P.glow.material = k.flashMat; P.glow.visible = false; + return r; + }, + fleshgiant(k, s) { + const r = new TH.Group(), skin = k.mat(0xffffff, { map: s.tex.flesh }), P = r.parts = {}; + const ell = (p, rx, ry, rz, x, y, z) => { const m = k.ball(p, 1, 0, x, y, z); m.material = skin; m.scale.set(rx, ry, rz); return m; }; + ell(r, 900, 800, 800, 0, 900, 0); ell(r, 560, 420, 520, 0, 1820, 180); + P.head = k.group(r, 0, 2000, 460); ell(P.head, 230, 240, 240, 0, 40, 60); k.ball(P.head, 40, 0xf0e040, -110, 90, 260); k.ball(P.head, 40, 0xf0e040, 110, 90, 260); + P.armL = k.group(r, -980, 1700, 100); P.armR = k.group(r, 980, 1700, 100); + for (const a of [P.armL, P.armR]) { ell(a, 300, 700, 300, 0, -620, 0); const f = k.group(a, 0, -1260, 0); ell(f, 230, 620, 230, 0, -480, 0); for (let i = -1; i <= 1; i++) k.cyl(f, 46, 0, 300, 0xd8c8a0, i * 120, -1120, 0, 4); a.fore = f; } + return r; + }, + winged(k, s) { + const r = human(k, { skin: 0xc8a8a8, top: 0x7a2030, legs: 0x4a1420, boots: 0x20080c, hair: 0x2a1a30, scale: 1.1 }); + const mat = new TH.MeshLambertMaterial({ color: 0x8a2a38, side: TH.DoubleSide, flatShading: true }); s.keep(mat); + const wing = sign => { const pts = new Float32Array([0, 0, 0, sign * 1000, 260, -160, sign * 760, -180, -120, 0, 0, 0, sign * 760, -180, -120, sign * 420, -620, -80]).map(v => v * S), g = new TH.BufferGeometry(); g.setAttribute('position', new TH.BufferAttribute(pts, 3)); g.computeVertexNormals(); s.keep(g); const m = new TH.Mesh(g, mat); m.position.set(0, 180 * S, 80 * S); r.parts.torso.add(m); return m; }; + r.parts.wingL = wing(-1); r.parts.wingR = wing(1); + return r; + }, + }; + const ANIMATE = { + lara(m, L, t, g) { + const st = { run: L.state === 'run' || L.state === 'backHop', walk: ['walk', 'walkBack', 'stepL', 'stepR'].includes(L.state), crouch: L.state === 'compress' || L.state === 'land' }; + pose(m, st, t); + const P = m.parts; + m.rotation.x = L.state === 'roll' ? (L.stateT / T.n(15)) * Math.PI * 2 : 0; + if (L.state === 'jump') { P.legL.rotation.x = -.5; P.legR.rotation.x = .25; } + P.braid.rotation.x = st.run ? .5 + Math.sin(t * .42) * .2 : L.airborne ? -.6 : .1; + if (L.gun === 'ready') { + const rec = a => a.frame >= 24 ? (33 - a.frame) * .02 : 0, yaw = a => -a.ry * A2R, pit = a => a.rx * A2R; + P.torso.rotation.y = -L.torso * A2R; + aimArm(P.armL, yaw(L.armL) + L.torso * A2R, pit(L.armL) + rec(L.armL)); aimArm(P.armR, yaw(L.armR) + L.torso * A2R, pit(L.armR) + rec(L.armR)); + flash(P.armL, L.armL.flash > 0); flash(P.armR, L.armR.flash > 0); + } else { flash(P.armL, false); flash(P.armR, false); } + if (L.hitFlash > 0) { const f = Math.min(1, L.hitFlash / T.n(12)); P.torso.rotation.x -= .32 * f; P.head.rotation.x = -.25 * f; } else P.head.rotation.x = 0; + }, + lizard(m, b, t) { + const P = m.parts, w = b.state === 'run' ? Math.sin(t * .4) * .7 : b.state === 'walk' ? Math.sin(t * .3) * .34 : 0, c = T.CREATURES.lizard, h = c.headLocal(b); + P.legL.rotation.x = w; P.legR.rotation.x = -w; P.body.rotation.z = Math.sin(t * .2) * (b.state === 'run' ? .03 : .01); + P.tail.forEach((s, i) => { s.rotation.y = Math.sin(t * .14 - i * .7) * (.1 + i * .02); s.rotation.x = .04 * i; }); + // The head follows the same path the bite's sphere uses (rex.js headAt), so the lunge on screen is the hit test. + const f = T.clamp((h[0] - 1300) / 1500, -.4, 1), roar = b.state === 'roar' ? Math.min(1, b.stateT / T.n(10)) : 0; + P.neck.rotation.x = b.state === 'bite' ? f * .62 + .0 : -roar * .5 + (b.state === 'bite' ? 0 : 0); + P.neck.position.z = -(700 + Math.max(0, f) * 600) * S; + P.jaw.rotation.x = b.state === 'bite' ? (b.stateT < T.n(26) ? .7 : .1) : roar * .9; + }, + gunman(m, b, t) { const shoot = b.state === 'aim' || b.state === 'shoot'; pose(m, { run: b.state === 'run', walk: b.state === 'walk' }, t); if (shoot) { aimArm(m.parts.armR, 0, 0); if (b.state === 'aim') aimArm(m.parts.armL, 0, -.3); } flash(m.parts.armR, b.flash > 0); flash(m.parts.armL, false); }, + duelist(m, b, t) { const shoot = b.state === 'aim' || b.state === 'shoot'; pose(m, { run: b.state === 'run', walk: b.state === 'walk' }, t); if (shoot) { aimArm(m.parts.armR, 0, 0); aimArm(m.parts.armL, 0, 0); } flash(m.parts.armR, b.flash > 0); flash(m.parts.armL, b.flash > 0); }, + quadruped(m, b, t) { + const P = m.parts, w = b.state === 'run' ? Math.sin(t * .5) * .7 : 0; P.legs.forEach((L, i) => { L.rotation.x = i % 3 ? w : -w; }); + const rear = b.state === 'rear' ? Math.sin(Math.min(1, b.stateT / T.n(30)) * Math.PI) : 0; m.rotation.x = rear * .5; + const aim = b.state === 'aim' || b.state === 'shoot' ? 1 : 0; P.armR.rotation.x = aim * 1.4; P.glow.visible = b.state === 'aim' && (b.stateT >> 1) % 4 < 2; P.armL.rotation.x = Math.sin(t * .2) * .1 + rear; + }, + fleshgiant(m, b, t) { + const P = m.parts, swing = (a, on, f) => { a.rotation.x = on ? -2.2 + f * 2.4 : Math.sin(t * .06) * .1; if (a.fore) a.fore.rotation.x = on ? .9 - f * .8 : -.2; }; + const f = T.clamp(b.stateT / T.n(24), 0, 1); + swing(P.armL, b.state === 'attackL' || b.state === 'attackB', f); swing(P.armR, b.state === 'attackR' || b.state === 'attackB' || b.state === 'grab', f); + m.rotation.z = b.state === 'turnL' ? Math.sin(t * .2) * .05 : b.state === 'turnR' ? -Math.sin(t * .2) * .05 : 0; + m.position.y += b.state === 'forward' ? Math.abs(Math.sin(t * .2)) * 40 * S : 0; + }, + winged(m, b, t) { + const P = m.parts, fly = b.state === 'fly', down = b.state === 'faint'; + pose(m, { run: b.state === 'run', walk: b.state === 'walk' }, t); + const beat = Math.sin(t * .5) * (fly ? .7 : .1); P.wingL.rotation.y = beat; P.wingR.rotation.y = -beat; P.wingL.visible = P.wingR.visible = !down; + m.rotation.x = down ? -Math.PI / 2 * Math.min(1, b.stateT / T.n(15)) : 0; + if (b.state === 'shoot' || b.state === 'aim') { aimArm(P.armR, 0, 0); aimArm(P.armL, 0, 0); } + flash(P.armL, false); flash(P.armR, false); + }, + }; + + // Scenery props, built once per arena from the map: rocks along the walls, plinths and capitals on the pillars. Original procedural shapes. + function decorate(sc, m, th, theme) { + const W = T.WALL_L, k = sc.kit, h = (i, j) => (i < 0 || j < 0 || i >= m.w || j >= m.h ? T.WALL : m.cells[j * m.w + i]); + const rockCol = { valley: 0x7a6e5c, hall: 0x9a8058, crypt: 0x5a5a64, pit: 0x7a302a, gold: 0x8a6a2a }[theme] || 0x777777; + const trim = { hall: 0x8a6a40, crypt: 0x44444e, gold: 0xa07a30, pit: 0x5a1c1c, valley: 0x6a604e }[theme]; + const rock = sc.keep(new TH.IcosahedronGeometry(S, 0)), mat = k.mat(rockCol), group = new TH.Group(); sc.world.add(group); + for (let j = 1; j < m.h - 1; j++) for (let i = 1; i < m.w - 1; i++) { + if (h(i, j) === T.WALL) continue; + for (const [a, c] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) { + if (h(i + a, j + c) !== T.WALL || hash(i * 4 + a + 2, j * 4 + c + 2, 41) > (th.natural ? .5 : .28)) continue; + const cnt = 1 + Math.floor(hash(i, j, 42 + a + 2 * c) * 3); + for (let q = 0; q < cnt; q++) { + const r = 45 + hash(i, j, 43 + q + a) * 90, along = (.15 + .7 * hash(i, j, 50 + q + c)) * W, off = 40 + r * .8; + const x = a ? (i + (a > 0 ? 1 : 0)) * W - a * off : i * W + along, z = c ? (j + (c > 0 ? 1 : 0)) * W - c * off : j * W + along; + const mesh = new TH.Mesh(rock, mat); vec(x, r * .3, z, mesh.position); mesh.scale.set(r, r * .65, r * (.8 + .4 * hash(i, j, 61 + q))); mesh.rotation.set(hash(i, j, 70 + q) * 3, hash(i, j, 80 + q) * 3, 0); group.add(mesh); + } + } + } + if (!th.natural) for (let j = 1; j < m.h - 1; j++) for (let i = 1; i < m.w - 1; i++) { + if (h(i, j) !== T.WALL || ![[1, 0], [-1, 0], [0, 1], [0, -1]].some(([a, c]) => h(i + a, j + c) !== T.WALL)) continue; + k.box(group, W + 90, 150, W + 90, trim, (i + .5) * W, 75, (j + .5) * W); k.box(group, W + 50, 60, W + 50, trim, (i + .5) * W, 180, (j + .5) * W); + k.box(group, W + 70, 110, W + 70, trim, (i + .5) * W, th.wallH * W - 160, (j + .5) * W); + } + } + class Scene { + constructor(key, canvas, boss) { + this.key = key; this.resources = []; this.ready = false; this.error = null; this.closed = false; this.times = []; + const view = this.view = document.createElement('canvas'); view.width = 854; view.height = 480; + const r = this.renderer = new TH.WebGLRenderer({ canvas: view, antialias: true, stencil: true, preserveDrawingBuffer: true, powerPreference: 'low-power' }); + r.setPixelRatio(1); r.setSize(854, 480, false); r.outputColorSpace = TH.SRGBColorSpace; + view.addEventListener('webglcontextlost', e => { e.preventDefault(); this.ready = false; this.error = 'WebGL context lost'; }); + const arena = M.arenas[key], th = THEME[arena.theme]; this.ceilY = th.ceil ? th.wallH * T.WALL_L : 1e9; + this.world = new TH.Scene(); this.world.fog = new TH.Fog(th.fog[0], th.fog[1] * S, th.fog[2] * S); + this.camera = new TH.PerspectiveCamera(58, 854 / 480, 40 * S, 60000 * S); + if (th.sky) { const t = this.keep(tex((q, n) => { const g = q.createLinearGradient(0, 0, 0, n); g.addColorStop(0, th.sky[0]); g.addColorStop(.6, th.sky[1]); g.addColorStop(1, th.sky[2]); q.fillStyle = g; q.fillRect(0, 0, n, n); }, 64)); this.world.background = t; } + else this.world.background = new TH.Color(th.fog[0]); + this.world.add(new TH.HemisphereLight(th.hemi[0], th.hemi[1], th.hemi[2])); + const sun = new TH.DirectionalLight(th.sun[0], th.sun[1]); sun.position.set(4, 8, 3); this.world.add(sun); + this.tex = {}; for (const k of Object.keys(PAINT)) this.tex[k] = this.keep(tex(PAINT[k])); + const geo = arenaGeometry(arena.map, th), base = o => this.keep(new TH.MeshBasicMaterial(Object.assign({ vertexColors: true, side: TH.DoubleSide }, o))); + this.keep(geo.floor); this.keep(geo.wall); + const floorMesh = new TH.Mesh(geo.floor, base({ map: this.tex[th.floor] })), wallMesh = new TH.Mesh(geo.wall, base({ map: this.tex[th.wall] })); + floorMesh.renderOrder = wallMesh.renderOrder = -2; floorMesh.userData.occluder = wallMesh.userData.occluder = true; this.world.add(floorMesh, wallMesh); + this.kit = new Kit(this); this.kit.flashMat = this.keep(new TH.MeshBasicMaterial({ color: 0xffd080, transparent: true, opacity: .9, blending: TH.AdditiveBlending, depthWrite: false })); + this.lara = BUILD.lara(this.kit, this); this.world.add(this.lara); this.lara.traverse(o => { o.renderOrder = -1; }); + // The boss has its own materials: they mark its visible pixels in the stencil buffer, so the x-ray pass draws only the parts a wall (or + // Lara) hides, never its own back behind its front. + this.bkit = new Kit(this); this.bkit.flashMat = this.kit.flashMat; + this.boss = BUILD[boss](this.bkit, this); this.world.add(this.boss); + this.boss.traverse(o => { if (o.isMesh && !o.material.transparent) Object.assign(o.material, { stencilWrite: true, stencilRef: 1, stencilFunc: TH.AlwaysStencilFunc, stencilZPass: TH.ReplaceStencilOp }); }); + this.xray = this.keep(new TH.MeshBasicMaterial({ color: 0xff7a40, transparent: true, opacity: .42, depthWrite: false, depthFunc: TH.GreaterDepth, fog: false, side: TH.DoubleSide, + stencilWrite: true, stencilRef: 0, stencilFunc: TH.EqualStencilFunc, stencilZPass: TH.IncrementStencilOp })); + this.xworld = new TH.Scene(); + this.shadow = this.blob(); this.bshadow = this.blob(); + this.pool = []; this.fxTex = this.keep(tex((q, n) => { const g = q.createRadialGradient(n / 2, n / 2, 0, n / 2, n / 2, n / 2); g.addColorStop(0, '#fff'); g.addColorStop(.5, 'rgba(255,255,255,.5)'); g.addColorStop(1, 'rgba(255,255,255,0)'); q.fillStyle = g; q.fillRect(0, 0, n, n); }, 32)); + for (let i = 0; i < 170; i++) { const sp = new TH.Sprite(this.keep(new TH.SpriteMaterial({ map: this.fxTex, blending: TH.AdditiveBlending, depthWrite: false, transparent: true }))); sp.visible = false; this.world.add(sp); this.pool.push(sp); } + // floor decals (danger zones, impact rings, light pools) and hitscan tracers: pooled, set per frame from the state + this.ringTex = this.keep(tex((q, n) => { const g = q.createRadialGradient(n / 2, n / 2, 0, n / 2, n / 2, n / 2); g.addColorStop(0, 'rgba(255,255,255,.34)'); g.addColorStop(.8, 'rgba(255,255,255,.5)'); g.addColorStop(.88, '#fff'); g.addColorStop(.97, '#fff'); g.addColorStop(1, 'rgba(255,255,255,0)'); q.fillStyle = g; q.fillRect(0, 0, n, n); }, 128)); + this.ringTex.magFilter = TH.LinearFilter; + const D = Math.PI / 180, plane = this.keep(new TH.PlaneGeometry(2, 2)); + this.shapes = { disc: plane, ring: plane, fanR: new TH.CircleGeometry(1, 24, 12 * D, 90 * D), fanL: new TH.CircleGeometry(1, 24, 78 * D, 90 * D), fanB: new TH.CircleGeometry(1, 36, 12 * D, 156 * D), + semi: new TH.CircleGeometry(1, 24, 0, 180 * D), wedge: new TH.RingGeometry(.3, 1, 16, 1, 74 * D, 32 * D), lane: new TH.RingGeometry(.12, 1, 6, 1, 83 * D, 14 * D) }; + for (const k of Object.keys(this.shapes)) this.keep(this.shapes[k]); + this.decals = []; + for (let i = 0; i < 28; i++) { const d = new TH.Mesh(plane, this.keep(new TH.MeshBasicMaterial({ map: this.fxTex, transparent: true, depthWrite: false, side: TH.DoubleSide, fog: false }))); d.visible = false; d.renderOrder = 1; this.world.add(d); this.decals.push(d); } + const tube = this.keep(new TH.CylinderGeometry(1, 1, 1, 6, 1, true)); + this.tracers = []; + for (let i = 0; i < 12; i++) { const m = new TH.Mesh(tube, this.keep(new TH.MeshBasicMaterial({ color: 0xffffff, transparent: true, depthWrite: false, blending: TH.AdditiveBlending, fog: false }))); m.visible = false; this.world.add(m); this.tracers.push(m); } + this.bossMats = []; this.boss.traverse(o => { if (o.isMesh && o.material.emissive && !this.bossMats.includes(o.material)) this.bossMats.push(o.material); }); + const fill = new TH.DirectionalLight(th.hemi[0], .55); fill.position.set(-5, 3, -4); this.world.add(fill); + decorate(this, arena.map, th, arena.theme); + this.torches = []; + if (th.torch) { + const m = arena.map, W = T.WALL_L, spots = []; for (let j = 2; j < m.h - 2; j += 4) for (let i = 2; i < m.w - 2; i += 4) if (m.cells[j * m.w + i] !== T.WALL) for (const [a, b] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) if (m.cells[(j + b) * m.w + i + a] === T.WALL) spots.push([(i + .5 + a * .42) * W, (j + .5 + b * .42) * W]); + for (const [x, z] of spots.slice(0, 14)) { + const sp = new TH.Sprite(this.keep(new TH.SpriteMaterial({ map: this.fxTex, color: 0xff9030, blending: TH.AdditiveBlending, depthWrite: false, transparent: true }))); vec(x, 1100, z, sp.position); sp.scale.set(1.8, 2.6, 1); this.world.add(sp); this.torches.push(sp); + this.kit.box(this.world, 70, 170, 70, 0x2a2420, x, 960, z); this.kit.cyl(this.world, 50, 30, 60, 0x4a3a2a, x, 1060, z, 6); + const pool = new TH.Mesh(plane, this.keep(new TH.MeshBasicMaterial({ map: this.fxTex, color: 0xff9a40, transparent: true, opacity: .22, depthWrite: false, blending: TH.AdditiveBlending, fog: false }))); + pool.rotation.x = -Math.PI / 2; vec(x, 3, z, pool.position); pool.scale.set(700 * S, 700 * S, 1); this.world.add(pool); + } + } + } + keep(x) { this.resources.push(x); return x; } + blob() { const m = new TH.Mesh(this.keep(new TH.CircleGeometry(1, 16)), this.keep(new TH.MeshBasicMaterial({ color: 0, transparent: true, opacity: .34, depthWrite: false }))); m.rotation.x = -Math.PI / 2; this.world.add(m); return m; } + // The view, from the camera rig in the state (tr1camera.js): lens on the boom, then a look direction that starts from the chase view + // (ahead of her) and turns toward her and the boss as the rig's framing weight rises; the boss (while framed) and she are then kept + // inside the frame, the boss first. A pure function of the state. + frame(g) { + const L = g.lara, b = g.boss, c = L.cam, C = T.CAM, cam = this.camera, P = Math.PI, D = P / 180; + const len = C.CHASE + (C.COMBAT - C.CHASE) * c.lock, yaw = T.wrap(L.camYaw + C.SHOULDER * c.lock), up = C.UP + L.lookPitch * 18; + const r = Math.min(c.dist, T.camBoom(g, yaw, len, up)), head = L.y + C.HEAD; + const lift = Math.max(0, Math.min(c.lift, C.ceilOf(g) - 260 - head - up * r / len)); + const ex = L.x - T.sin(yaw) * r, ey = head + up * r / len + lift, ez = L.z - T.cos(yaw) * r; + vec(ex, ey, ez, cam.position); + const fov = 58 + 38 * Math.min(1, lift / 1600); + if (cam.fov !== fov) { cam.fov = fov; cam.updateProjectionMatrix(); } + const halfV = fov / 2 * D, halfH = Math.atan(Math.tan(halfV) * 854 / 480), wr = a => a - 2 * P * Math.round(a / (2 * P)); + const aim = (x, y, z) => { const dx = x - ex, dz = z - ez, h = Math.hypot(dx, dz); return { yaw: Math.atan2(dx, dz), pitch: Math.atan2(y - ey, h), h }; }; + const lk = c.look * A2R, A = aim(L.x + Math.sin(lk) * 1600, head - 60 - L.lookPitch * 14, L.z + Math.cos(lk) * 1600), her = aim(L.x, L.y + 430, L.z); + const shown = b.hp > 0 || b.state === 'faint', ap = T.CREATURES[b.kind].aimPoint(b), B = aim(ap.x, ap.y, ap.z), fr = shown ? c.fr : 0; + if (her.h < 250) her.yaw = shown ? B.yaw : A.yaw; // lens straight above her (corner lift): her bearing means nothing + const wy = A.yaw + wr(wr(her.yaw + wr(B.yaw - her.yaw) * .55) - A.yaw) * fr, wp = A.pitch + ((her.pitch + B.pitch) / 2 - A.pitch) * fr; + // Intervals of allowed offsets from the wanted direction, intersected in priority order; one that would empty the set is skipped. + const fit = (want, cons) => { let lo = -9, hi = 9; for (const [d, m] of cons) { const l = Math.max(lo, d - m), h = Math.min(hi, d + m); if (l <= h) { lo = l; hi = h; } } return want + Math.min(Math.max(0, lo), hi); }; + const boss1 = fr > .5; + const yy = fit(wy, boss1 ? [[wr(B.yaw - wy), halfH - 7 * D], [wr(her.yaw - wy), halfH - 5 * D]] : [[wr(her.yaw - wy), halfH - 5 * D]]); + const pp = T.clamp(fit(wp, boss1 ? [[B.pitch - wp, halfV - 6 * D], [her.pitch - wp, halfV - 8 * D]] : [[her.pitch - wp, halfV - 8 * D]]), -80 * D, 60 * D); + cam.lookAt(vec(ex + Math.sin(yy) * Math.cos(pp) * 1000, ey + Math.sin(pp) * 1000, ez + Math.cos(yy) * Math.cos(pp) * 1000)); + } + // Effects and telegraphs, all pure functions of the state (fx list, missiles, the boss's tele()). Player shots are pale yellow, the boss's red, + // orange or cyan. A telegraph is a floor zone where the move will land and a glow on the boss (or at its gun / hand) that grows over the wind-up. + effects(g, t) { + const L = g.lara, b = g.boss, cre = T.CREATURES[b.kind], sc = this, Wv = new TH.Vector3(), Wv2 = new TH.Vector3(), UP = new TH.Vector3(0, 1, 0); + let n = 0, nd = 0, nt = 0; + const put = (x, y, z, size, color, op) => { if (n >= sc.pool.length || op <= .01) return; const sp = sc.pool[n++]; vec(x, y, z, sp.position); sp.scale.setScalar(size * S); sp.material.color.setHex(color); sp.material.opacity = Math.min(1, op); sp.visible = true; }; + const putW = (w, size, color, op) => { if (n >= sc.pool.length || op <= .01) return; const sp = sc.pool[n++]; sp.position.copy(w); sp.scale.setScalar(size * S); sp.material.color.setHex(color); sp.material.opacity = Math.min(1, op); sp.visible = true; }; + const decal = (shape, x, z, radius, rot, color, op, add) => { + if (nd >= sc.decals.length || op <= .01) return; const d = sc.decals[nd++], f = T.floorAt(g.map, x, z); + // zones (every shape but 'disc') use the ring texture: a faint fill and a bright rim at the reach of the move + d.geometry = sc.shapes[shape]; d.material.map = shape === 'disc' ? sc.fxTex : sc.ringTex; d.material.color.setHex(color); d.material.opacity = Math.min(1, op); + d.material.blending = add ? TH.AdditiveBlending : TH.NormalBlending; vec(x, (f >= T.WALL ? 0 : f) + 8 + nd * .6, z, d.position); d.rotation.set(-Math.PI / 2, 0, -rot * A2R); + const k = shape === 'disc' || shape === 'ring' ? radius / 2 : radius; d.scale.set(k * S, k * S, 1); d.visible = true; + }; + const tracer = (from, x, y, z, color, op, width) => { if (nt >= sc.tracers.length) return; const m = sc.tracers[nt++]; vec(x, y, z, Wv2); const dir = Wv2.clone().sub(from), len = dir.length(); if (len < 1e-3) { m.visible = false; return; } m.position.copy(from).addScaledVector(dir, .5); m.quaternion.setFromUnitVectors(UP, dir.normalize()); m.scale.set(width * S, len, width * S); m.material.color.setHex(color); m.material.opacity = op; m.visible = true; }; + let flinch = 0; + // impacts, sparks, blasts, tracers + for (const f of g.fx) { + const age = g.t - f.t0, k = age / f.life; if (k >= 1) continue; + if (f.kind === 'ricochet') { + for (let i = 0; i < 6; i++) { const a = hash(f.id, i, 3) * 6.283, up = .3 + .7 * hash(f.id, i, 4), r = 40 + 260 * k; put(f.x + Math.cos(a) * r, f.y + up * r - 260 * k * k, f.z + Math.sin(a) * r, 34 * (1 - k) + 8, f.src === 'shard' ? 0x80e8ff : 0xffe080, 1 - k); } + put(f.x, f.y, f.z, 110 * (1 - k), 0xfff4c0, 1 - k); + } else if (f.kind === 'blood') { + for (let i = 0; i < 4; i++) { const a = hash(f.id, i, 5) * 6.283, r = 30 + 180 * k; put(f.x + Math.cos(a) * r, f.y + 60 * hash(f.id, i, 6) - 200 * k * k, f.z + Math.sin(a) * r, 46 * (1 - k) + 10, 0xb01810, 1 - k); } + put(f.x, f.y, f.z, 150 * (1 + k), 0x901410, (1 - k) * .8); + if (f.src === 'lara') flinch = Math.max(flinch, 1 - age / T.n(4)); + } else if (f.kind === 'blast') { + put(f.x, f.y + 200 * k, f.z, 1100 * (.55 + .9 * k), k < .3 ? 0xffe090 : 0xff6a20, (1 - k) * 1.1); + put(f.x, f.y + 120, f.z, 520 * (1 - k * .5), 0xfff6d8, 1 - k * 1.6); + for (let i = 0; i < 5; i++) { const a = hash(f.id, i, 7) * 6.283, r = 300 + 500 * k; put(f.x + Math.cos(a) * r, f.y + 200 + 700 * k * hash(f.id, i, 8), f.z + Math.sin(a) * r, 420 + 600 * k, 0x6a5040, .45 * (1 - k)); } + decal('ring', f.x, f.z, 400 + 1500 * k, 0, 0xff8a30, (1 - k) * .9, true); decal('disc', f.x, f.z, 1700, 0, 0xffa050, (1 - k) * .55, true); + } + if ((f.kind === 'ricochet' || f.kind === 'blood') && age < T.n(2) && (f.src === 'lara' || f.src === 'gunman' || f.src === 'duelist')) { + const own = f.src === 'lara', mdl = own ? sc.lara : sc.boss, arm = own ? (f.side === 'L' ? mdl.parts.armL : mdl.parts.armR) : (f.gun ? mdl.parts.armL : mdl.parts.armR); + if (arm && arm.gun) { arm.gun.getWorldPosition(Wv); tracer(Wv, f.x, f.y, f.z, own ? 0xfff0a0 : 0xff3420, 1 - age / T.n(2), own ? 9 : 12); } + } + } + // muzzle light on the floor + if (L.gun === 'ready' && (L.armL.flash > 0 || L.armR.flash > 0)) decal('disc', L.x, L.z, 900, 0, 0xffd080, .4, true); + if (b.flash > 0) decal('disc', b.x, b.z, 900, 0, 0xff8050, .4, true); + // missiles: hot core, coloured halo, a fading trail, and a ring where the straight flight meets the floor (bombs: the 1024 blast radius) + for (const q of g.missiles) { + const bomb = q.kind === 'bomb', col = bomb ? 0xff5a1e : 0x30d8ff, core = bomb ? 0xfff0c0 : 0xe8ffff, big = bomb ? 190 : 120; + put(q.x, q.y, q.z, big * 2.8, col, .55); put(q.x, q.y, q.z, big, core, 1); + for (let i = 1; i <= 6; i++) put(q.x - q.vx * i * 1.3, q.y - q.vy * i * 1.3, q.z - q.vz * i * 1.3, big * (1.6 - i * .18), col, .55 - i * .075); + let x = q.x, y = q.y, z = q.z, hit = null; + for (let i = 0, lim = Math.max(0, T.n(240) - q.age); i < lim; i++) { x += q.vx; y += q.vy; z += q.vz; const f = T.floorAt(g.map, x, z); if (y <= f || f >= T.WALL || y >= T.CEILING) { hit = [x - q.vx * .5, z - q.vz * .5, i]; break; } } + if (hit) { const soon = 1 - Math.min(1, hit[2] / T.n(30)); decal('ring', hit[0], hit[1], bomb ? 2048 : 420, 0, col, .35 + .5 * soon, true); if (bomb) decal('disc', hit[0], hit[1], 2048, 0, col, .12 + .25 * soon, true); } + } + // telegraph of the current move (cre.tele: windup / active): on the floor, on the boss and at its weapon + const tl = sc.boss.visible && cre.tele ? cre.tele(b) : null, red = 0xff2418; + let glow = 0; + if (tl) { + const w = tl.phase === 'windup' ? .25 + .6 * tl.k : 1, pulse = .78 + .22 * Math.sin(g.t * .8); + const P = sc.boss.parts, at = (part, size, color, op) => { if (part) { part.getWorldPosition(Wv); putW(Wv, size, color, op); } }; + switch (b.kind) { + case 'lizard': if (tl.move === 'bite') decal('wedge', b.x, b.z, 3000, b.rot, red, .75 * w * pulse); else decal('lane', b.x, b.z, 2600, b.rot, 0xff6a20, .35); break; + case 'quadruped': + if (tl.move === 'rear') decal('semi', b.x, b.z, 1150, b.rot, red, .7 * w * pulse); + else { at(P.glow, 160 + 320 * w, 0xff7a30, .9); if (tl.phase !== 'active') decal('ring', L.x, L.z, 2048, 0, red, .7 * w * pulse, true); } + break; + case 'fleshgiant': decal(tl.move === 'attackB' ? 'fanB' : 'fanR', b.x, b.z, 2800, b.rot, tl.move === 'grab' ? 0xc030ff : red, .6 * w * pulse); break; + case 'gunman': case 'duelist': if (tl.phase === 'windup') { at(P.armR.gun, 80 + 170 * w, 0xff4030, w); if (b.kind === 'duelist') at(P.armL.gun, 80 + 170 * w, 0xff4030, w); } break; + case 'winged': { + at(P.armR.gun, 120 + 260 * w, 0xff6a20, w); at(P.armL.gun, 120 + 260 * w, 0xff6a20, w); + if (tl.move === 'volley' && tl.phase === 'windup') decal('ring', L.x, L.z, 2048, 0, red, .6 * w * pulse, true); + break; + } + } + glow = w; + } + // dust under running feet + if (b.state === 'run' && (b.kind === 'lizard' || b.kind === 'quadruped')) for (let i = 0; i < 3; i++) { const ph = ((g.t + i * 7) % 21) / 21, back = -300 - 700 * ph; put(b.x + T.sin(b.rot) * back + (i - 1) * 260, 80 + 200 * ph, b.z + T.cos(b.rot) * back, 300 + 400 * ph, 0x8a7a5a, .35 * (1 - ph)); } + if (L.state === 'run') { const ph = (g.t % 14) / 14; put(L.x - T.sin(L.rot) * (120 + 200 * ph), 40 + 60 * ph, L.z - T.cos(L.rot) * (120 + 200 * ph), 120 + 160 * ph, 0x8a7a5a, .25 * (1 - ph)); } + while (n < sc.pool.length) sc.pool[n++].visible = false; + while (nd < sc.decals.length) sc.decals[nd++].visible = false; + while (nt < sc.tracers.length) sc.tracers[nt++].visible = false; + // the boss glows red over a wind-up and flashes white when a pistol round lands + const fk = sc.boss.visible ? flinch : 0, er = Math.max(glow * .6, fk * .75), eg = fk * .6 + glow * .06, eb = fk * .55; + for (const m of sc.bossMats) m.emissive.setRGB(er, eg, eb); + if (fk > 0) sc.boss.rotation.z += Math.sin(g.t * 1.9) * .05 * fk; + } + // X-ray: the boss's hidden parts (behind a wall, a pillar or Lara) drawn again as a flat translucent silhouette. depthFunc Greater draws only + // where something nearer is in front; the stencil (1 where the boss itself is visible) keeps its own back and front from stacking. + xrayPass() { + const r = this.renderer, ac = r.autoClear; + this.xworld.add(this.boss); this.xworld.overrideMaterial = this.xray; r.autoClear = false; + try { r.render(this.xworld, this.camera); } finally { r.autoClear = ac; this.xworld.overrideMaterial = null; this.world.add(this.boss); } + } + render(g, ctx) { + const t0 = performance.now(); + try { + const L = g.lara, b = g.boss, t = g.t / T.TS; // animation phase in original (30 Hz) ticks, so the look is the same at any clock + vec(L.x, L.y, L.z, this.lara.position); this.lara.rotation.y = -L.rot * A2R; ANIMATE.lara(this.lara, L, t, g); + vec(b.x, b.y || 0, b.z, this.boss.position); this.boss.rotation.set(0, -b.rot * A2R, 0); this.boss.visible = b.hp > 0 || b.state === 'faint'; ANIMATE[b.kind](this.boss, b, t, g); + vec(L.x, T.floorAt(g.map, L.x, L.z) + 4, L.z, this.shadow.position); this.shadow.scale.setScalar(120 * S); + vec(b.x, T.floorAt(g.map, b.x, b.z) + 5, b.z, this.bshadow.position); this.bshadow.scale.setScalar((T.CREATURES[b.kind].shadow || 300) * S); + this.effects(g, t); + for (let i = 0; i < this.torches.length; i++) this.torches[i].material.opacity = .62 + .3 * Math.sin(t * .3 + i * 2); + this.frame(g); + this.renderer.render(this.world, this.camera); + if (this.boss.visible) this.xrayPass(); + ctx.drawImage(this.view, 0, 0, 854, 480); + this.times.push(performance.now() - t0); if (this.times.length > 120) this.times.shift(); + this.ready = true; this.error = null; + } catch (e) { this.ready = false; this.error = String(e && e.stack || e); throw e; } + } + close() { if (this.closed) return; this.closed = true; this.ready = false; for (const r of this.resources) r.dispose && r.dispose(); this.renderer.dispose(); this.renderer.forceContextLoss(); this.resources = []; } + } + R.render = (g, ctx) => { + let m = byCanvas.get(ctx.canvas); if (!m) { m = new Map(); byCanvas.set(ctx.canvas, m); } + let s = m.get(g.key); if (!s || s.closed) { s = new Scene(g.key, ctx.canvas, g.boss.kind); m.set(g.key, s); } + s.render(g, ctx); m.last = s; return s; + }; + const PV = new TH.Vector3(); + // Screen position of a game-space point in the last rendered view (for the HUD's lock reticle and edge arrow). + R.project = (ctx, x, y, z) => { + const m = ctx && byCanvas.get(ctx.canvas), s = m && m.last; if (!s || s.closed) return null; + const cam = s.camera; PV.set(x * S, y * S, -z * S).applyMatrix4(cam.matrixWorldInverse); + const front = PV.z < -cam.near, cx = PV.x, cy = PV.y; PV.set(x * S, y * S, -z * S).project(cam); + return { x: (PV.x + 1) * 427, y: (1 - PV.y) * 240, front, cx, cy }; + }; + // The lens position of the last rendered view, in game units (for the HUD's line-of-sight test). + R.eye = ctx => { const m = ctx && byCanvas.get(ctx.canvas), s = m && m.last; if (!s || s.closed) return null; const p = s.camera.position; return { x: p.x / S, y: p.y / S, z: -p.z / S }; }; + R.status = ctx => { + const m = ctx && byCanvas.get(ctx.canvas); let ready = false, error = null; + if (m) for (const s of m.values()) { if (!s.closed && s.renderer.getContext().isContextLost()) { s.ready = false; s.error = 'WebGL context lost'; } ready = ready || (s.ready && !s.closed); error = error || s.error; } + return { renderer: 'webgl-tombraider', kind: 'perspective', ready, error }; + }; + R.metrics = ctx => { const m = ctx && byCanvas.get(ctx.canvas); if (!m || !m.last || m.last.closed) return null; const a = m.last.times; return { frames: a.length, avg_ms: a.reduce((x, y) => x + y, 0) / (a.length || 1), max_ms: Math.max(0, ...a) }; }; + R.close = ctx => { const m = ctx && byCanvas.get(ctx.canvas); if (!m) return; for (const s of m.values()) s.close(); byCanvas.delete(ctx.canvas); }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/tombraider_remake/scripted.js b/environments/games/web/games/tombraider_remake/scripted.js new file mode 100644 index 0000000000000000000000000000000000000000..3930ca67263b701a4de3b6e68503820f5c29734f --- /dev/null +++ b/environments/games/web/games/tombraider_remake/scripted.js @@ -0,0 +1,134 @@ +/* Tomb Raider (1996) boss arenas - the standard scripted controller. Privileged state, legal keys only, look-ahead on copies of the game. + Blinding: the copies never carry the live RNG. Before every simulated tick the copy is + reseeded from a multiply mix of (tick, sample), so a look-ahead can only learn what is already decided (states, timers, missiles), never a + coin flip that has not happened yet. Each candidate is scored over three sampled futures: half worst case, half mean. + 60 Hz (tr1-arena@2): the horizon is 2 s = 120 ticks; a decision is taken every 2 ticks and held for both, exactly as a packet's six hold + sets are applied by the runtime, so the simulated future is the one the packet will produce. */ +(function (root) { + 'use strict'; + const M = root.TombRaiderGame, T = M.T, { wrap, deg, atan } = T; + const ZERO = [0, 0, 0], HZ = T.HZ, SUB = HZ / 30, HORIZON = 2 * HZ, SAMPLES = 3, LIFE = { winged: 40 }; // per-boss price of one point of the player's health (default 16) + const mix = (t, k) => { let h = Math.imul(t + 40503, 0x85EBCA6B) ^ Math.imul(k + 7919, 0xC2B2AE35); h = Math.imul(h ^ (h >>> 15), 0x2C1B3C6D); h = Math.imul(h ^ (h >>> 13), 0xC2B2AE35); return ((h ^ (h >>> 16)) >>> 0) || 1; }; + M.lookaheadSeed = mix; + const bearing = (L, b) => atan(b.x - L.x, b.z - L.z); + const turnKey = (err, slack) => Math.abs(err) <= slack ? null : err < 0 ? 'A' : 'D'; + // One action = a small closed-loop rule re-evaluated every simulated tick; its first six ticks are the packet. + function keysFor(c, act) { + const L = c.lara, b = c.boss, to = bearing(L, b), keys = ['J']; + if (L.gun !== 'ready') { keys[0] = 'K'; return keys; } + if (act.m === 'stand') { + const k = turnKey(wrap(to - L.rot), deg(10)); if (k && L.state === 'stop') keys.push(k); + } else if (act.m === 'run') { + keys.push('W'); const k = turnKey(wrap(to + act.a - L.rot), deg(4)); if (k) keys.push(k); + } else if (act.m === 'jump') { + // Keep facing the boss between hops: the rex only breaks into its run while Lara has her back to it (flags, enemy_facing). + const k = turnKey(wrap(to - L.rot), deg(14)); + if (L.state === 'stop' && k) keys.push(k); + else if (L.state === 'stop' || L.state === 'compress') keys.push('Space', act.k); + else if (L.state === 'jump' && k) keys.push(k); + } else if (act.m === 'hop') keys.push('S'); + else if (act.m === 'step') keys.push(act.k); + else if (act.m === 'leap') { // a running jump across her line: 2790 per second in the air, twice the run, the fastest way out of a blast + const k = turnKey(wrap(to + act.a - L.rot), deg(8)); + if (L.state === 'run' && !k) keys.push('W', 'Space'); else { keys.push('W'); if (k) keys.push(k); } + } + else if (act.m === 'cover') { // run to the side of a pillar away from the boss, then hold there facing it + const p = coverPoint(c, act.cell), dx = p.x - L.x, dz = p.z - L.z; + if (Math.hypot(dx, dz) > 220) { keys.push('W'); const k = turnKey(wrap(atan(dx, dz) - L.rot), deg(6)); if (k) keys.push(k); } + else { const k = turnKey(wrap(to - L.rot), deg(10)); if (k && L.state === 'stop') keys.push(k); } + } + return keys; + } + // Interior solid cells (pillars) of the arena: a pure function of the map, cached by map identity. + const pillarCache = new WeakMap(); + function pillars(m) { + if (pillarCache.has(m)) return pillarCache.get(m); + const out = []; for (let j = 1; j < m.h - 1; j++) for (let i = 1; i < m.w - 1; i++) if (m.cells[j * m.w + i] === T.WALL && [[1, 0], [-1, 0], [0, 1], [0, -1]].some(([a, b]) => m.cells[(j + b) * m.w + i + a] !== T.WALL)) out.push(j * m.w + i); + pillarCache.set(m, out); return out; + } + function coverPoint(c, cell) { + const m = c.map, i = cell % m.w, j = (cell - i) / m.w, W = T.WALL_L, cx = (i + .5) * W, cz = (j + .5) * W, b = c.boss; + const dx = cx - b.x, dz = cz - b.z, d = Math.hypot(dx, dz) || 1, r = W * 0.5 + T.LARA_RADIUS + 140; + return { x: T.clamp(cx + dx / d * r, W + 120, (m.w - 1) * W - 120), z: T.clamp(cz + dz / d * r, W + 120, (m.h - 1) * W - 120) }; + } + function rollout(g0, act, sample, H, rec) { + const c = M.copyGame(g0); c.noCamera = true; // the camera rig is cosmetic: nothing below reads it + const start = { lara: c.lara.hp, boss: T.CREATURES[c.boss.kind].bossHp ? T.CREATURES[c.boss.kind].bossHp(c.boss) : c.boss.hp }; + let prev = new Set(c.heldKeys || []), died = -1, keys = null; + for (let i = 0; i < H && !c.outcome; i++) { + if (i % SUB === 0) { keys = keysFor(c, act); if (rec) rec.push(keys); } // one decision per hold set (two ticks at 60 Hz) + const set = new Set(keys), pressed = new Set(keys.filter(k => !prev.has(k))); + c.rng = mix(c.t, sample); c.events = []; + c.update(set, pressed, ZERO); c.t++; prev = set; + if (c.lara.hp <= 0 && died < 0) died = Math.floor(i / SUB); + } + return { c, start, died }; + } + const wallCost = (c, reach, k) => { const L = c.lara, e = Math.min(L.x, L.z, c.map.w * T.WALL_L - L.x, c.map.h * T.WALL_L - L.z); return e < reach ? -(reach - e) * k : 0; }; + const SAFETY = { + lizard(c) { + const L = c.lara, b = c.boss, i = T.aiInfo(c, b, T.CREATURES.lizard.pivot); + let s = 0; + if (i.bite && i.distance < Math.pow(2100, 2)) s -= 400; // inside the zone the next stop turns into a bite + if (b.state === 'bite' && i.distance < Math.pow(2400, 2)) s -= 300; + const near = Math.hypot(b.x - L.x, b.z - L.z); // trample: the run state hurts every tick of contact + if (near < 2600) s -= (2600 - near) * (b.state === 'run' ? 0.12 : 0.03); + const edge = Math.min(L.x, L.z, c.map.w * T.WALL_L - L.x, c.map.h * T.WALL_L - L.z); + if (edge < 2200) s -= (2200 - edge) * 0.2; + return s; + }, + gunman: c => SAFETY.human(c), duelist: c => SAFETY.human(c), + // Missiles are dodged by the simulated futures themselves; what the score adds is where to stand. Centaur: outside its kick. Torso: outside its arms, and + // far outside once Lara is low enough to be grabbed. Natla: in the open, off the walls, so a bomb's blast has room to miss. + quadruped(c) { const L = c.lara, b = c.boss, d = Math.hypot(b.x - L.x, b.z - L.z); let s = 0; if (d < 2600) s -= (2600 - d) * 0.12; return s + wallCost(c, 1500, 0.1); }, + fleshgiant(c) { const L = c.lara, b = c.boss, d = Math.hypot(b.x - L.x, b.z - L.z), keep = L.hp > 500 ? 3200 : 3800; let s = 0; if (d < keep) s -= (keep - d) * 0.5; return s + wallCost(c, 1400, 0.1); }, + // A bomb dropped from overhead lands inside its blast whatever she aims at, so keep her at a slant: far enough that the bomb's flight can be stepped out of. + winged(c) { const L = c.lara, b = c.boss, d = Math.hypot(b.x - L.x, b.z - L.z); let s = wallCost(c, 1700, 0.08); if (b.flyMode && d < 4500) s -= (4500 - d) * 0.3; // airborne (or taking off): a bomb from overhead lands inside its own 1024 blast before she can be outrun; distance buys flight time + if (b.stage === 1 && b.y <= 300 && d < 4200) s -= (4200 - d) * 0.06 * (c.tierScale.damage); // on foot her volley of three is aimed at a spot; the farther away, the longer the flight to step out of + // Stage 2: a shard every 20 ticks, aimed where she stands looking. A shard at 250/tick crosses 3 sectors in 12 ticks, so distance buys time to sidestep. + if (b.stage === 2 && d < 5000) s -= (5000 - d) * 0.03 * c.tierScale.damage; + return s; }, + // Gunmen: what matters is his line of fire. Breaking it (a pillar between) or standing beyond the zero-hit distance is safe; + // standing in his open sight close in is what costs. Shown for the score only; the hit roll itself stays in the simulated futures. + human(c) { + const L = c.lara, b = c.boss, d = Math.hypot(b.x - L.x, b.z - L.z), sight = T.los(c.map, b.x, b.y + 768, b.z, L.x, L.y + 768, L.z); + // While he escapes he runs and never stops to aim (his run state ignores targets in that mood), so his sight costs little and closing in + // buys accuracy (the 8 degree spread misses half the shots beyond 4 sectors): chase him then, keep the old caution otherwise. + const esc = b.mood === 'escape'; + let s = 0; if (sight) s -= Math.max(0, 6200 - d) * 0.025 * Math.min(1, b.damage / 75) * (esc ? 0.25 : 1); + if (esc && d > 1600) s -= (d - 1600) * 0.1; + // A fight against a man who hides behind pillars is also lost to time: when he is not escaping and the pillars break every line, the + // look-ahead sees no damage either way and stands still. A small price on a broken line makes it step round to find one. + if (!esc && !sight) s -= 300; + const edge = Math.min(L.x, L.z, c.map.w * T.WALL_L - L.x, c.map.h * T.WALL_L - L.z); if (edge < 1300) s -= (1300 - edge) * 0.1; + return s; + }, + }; + function score(g0, r, kind) { + const c = r.c, cre = T.CREATURES[kind], hp = cre.bossHp ? cre.bossHp(c.boss) : c.boss.hp; + let s = (r.start.boss - hp) * 30 - (r.start.lara - c.lara.hp) * (LIFE[kind] || 16); // 1 boss hp may cost about 2 of the player's (the hard budget); the shard boss gets a dearer price: standing to trade shots loses there + if (r.died >= 0) s -= 200000 - r.died * 1000; // died counts hold sets (1/30 s), as at 30 Hz + if (c.outcome === 'win') s += 5000; + return s + SAFETY[kind](c); + } + const ACTIONS = [{ m: 'stand' }, { m: 'hop' }, { m: 'step', k: 'Q' }, { m: 'step', k: 'E' }, { m: 'jump', k: 'A' }, { m: 'jump', k: 'D' }, { m: 'jump', k: 'S' }]; + for (const a of [0, 45, 90, 135, 180, -45, -90, -135]) ACTIONS.push({ m: 'run', a: deg(a) }); + const LEAPS = [90, -90, 135, -135, 180].map(a => ({ m: 'leap', a: deg(a) })); + M.scripted = function (g) { + const L = g.lara, kind = g.boss.kind; + const acts = T.CREATURES[kind].gunman ? ACTIONS.concat(pillars(g.map).map(cell => ({ m: 'cover', cell }))) : kind === 'winged' ? ACTIONS.concat(LEAPS) : ACTIONS; + // Every action gets one future; only the five best get the other two, so the three-sample rule costs 25 rollouts rather than 45. + const first = acts.map(act => ({ act, s: score(g, rollout(g, act, 0, HORIZON), kind) })).sort((x, y) => y.s - x.s).slice(0, 5); + let best = null, bestS = -Infinity; + for (const f of first) { + let worst = f.s, sum = f.s; + for (let k = 1; k < SAMPLES; k++) { const s = score(g, rollout(g, f.act, k, HORIZON), kind); worst = Math.min(worst, s); sum += s; } + const s = 0.5 * worst + 0.5 * sum / SAMPLES; + if (s > bestS) { bestS = s; best = f.act; } + } + const rec = []; rollout(g, best, 0, 6 * SUB, rec); + while (rec.length < 6) rec.push([]); + if (L.hp <= 500 && L.medi > 0 && !(g.heldKeys || []).includes('R')) { rec[0] = rec[0].slice(0, 3); rec[0].push('R'); } + return { holds: rec, mouse: [0, 0, 0] }; + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/tombraider_remake/tr1camera.js b/environments/games/web/games/tombraider_remake/tr1camera.js new file mode 100644 index 0000000000000000000000000000000000000000..be486a18348caf3bd9558d95c8aa25275f9d75e0 --- /dev/null +++ b/environments/games/web/games/tombraider_remake/tr1camera.js @@ -0,0 +1,69 @@ +/* Tomb Raider (1996) boss arenas - the camera rig, tr1-arena@3 (2026-11-08). + Cosmetic: nothing in the simulation or the scripted controller reads it, it never draws from the RNG, and the controller's look-ahead copies skip + it (g.noCamera). It lives in the state (as camYaw always did) so that a frame stays a pure function of the state while the view moves smoothly. + TRX camera/box_camera.c: the chase camera trails her facing; M_Combat (a target held) swings the boom behind her along the target's bearing + (target_angles[0] + rot.y), 2560 out - here 2200, these rooms are 7 to 18 sectors wide. + BossBench additions, for an agent that sees only the frame ( B): + - with no target held, a boss within 100 degrees of her facing pulls the view up to 35 degrees toward it; + - ten times a second the boom picks, among nine directions within 90 degrees of the wanted one, the one with her and the boss in clear view + (a pillar between the lens and the boss is why the old view so often showed a wall), preferring small swings and the current choice; + - in combat the boom swings 12 degrees off her back (the lens over her right shoulder, she stands left of centre), so a boss straight ahead + is not hidden behind her own body. */ +(function (root) { + 'use strict'; + const M = root.TombRaiderGame, T = M.T, { wrap, sin, cos, atan, deg, clamp } = T; + const C = T.CAM = { HEAD: 620, CHASE: 1700, COMBAT: 2200, UP: 820, PAD: 150, SHOULDER: -deg(12), LIFT_MAX: 2600, + CEIL: { valley: 1e9, hall: 4 * 1024, crypt: 4 * 1024, pit: 5 * 1024, gold: 6 * 1024 } }; // = the renderer's wall heights of the roofed themes + const YAW_BLEND = T.blend(0.12), LOCK_BLEND = T.blend(0.2), DIST_BLEND = T.blend(0.15), LIFT_BLEND = T.blend(0.35); + const OFFS = [0, 1, -1, 2, -2, 3, -3, 4, -4].map(k => k * deg(22.5)); + T.camRig = rot => ({ off: 0, dist: C.CHASE, lift: 0, lock: 0, fr: 0, look: rot || 0 }); + const ceilOf = g => C.CEIL[M.arenas[g.key].theme] || 1e9; + C.ceilOf = ceilOf; + // The boom from her head out along yaw, cut where the lens (with a pad for the near plane that grows with the boom: at her own position she is + // legitimately close to a wall, the lens is not) would enter a wall or come within 200 of the ceiling. + T.camBoom = (g, yaw, len, up) => { + const L = g.lara, m = g.map, head = L.y + C.HEAD, sy = sin(yaw), cy = cos(yaw), top = ceilOf(g) - 200; + for (let d = 64; d <= len; d += 32) { + const x = L.x - sy * d, y = head + up * d / len, z = L.z - cy * d, p = Math.min(C.PAD, d * 0.4); + if (y > top || T.floorAt(m, x, z) >= y - 40 || T.floorAt(m, x + p, z) >= y - 40 || T.floorAt(m, x - p, z) >= y - 40 || T.floorAt(m, x, z + p) >= y - 40 || T.floorAt(m, x, z - p) >= y - 40) return Math.max(0, d - 64); + } + return len; + }; + // In a corner every boom is short: the lens rises above her instead (up to 2600, never into the ceiling); the renderer widens and tilts the view. + T.camLift = (g, r, len) => r < 900 ? Math.max(0, Math.min((900 - r) * 3, C.LIFT_MAX, ceilOf(g) - 260 - (g.lara.y + C.HEAD) - C.UP * r / len)) : 0; + // The boss points the lens should see: its aim point (where the pistols' auto-aim shoots) and its hit-sphere centres. + T.camBossPoints = b => { const c = T.CREATURES[b.kind], a = c.aimPoint(b); return [[a.x, a.y, a.z]].concat(c.spheres(b).map(s => [s[0], s[1], s[2]])); }; + const bossShown = b => b.hp > 0 || b.state === 'faint'; + function lens(g, yaw, len) { + const L = g.lara, up = C.UP + L.lookPitch * 18, r = T.camBoom(g, yaw, len, up); + return { r, x: L.x - sin(yaw) * r, y: L.y + C.HEAD + up * r / len + T.camLift(g, r, len), z: L.z - cos(yaw) * r }; + } + function pickOffset(g, base, len, shoulder) { + const L = g.lara, m = g.map, pts = bossShown(g.boss) ? T.camBossPoints(g.boss) : []; + let best = 0, bestS = -Infinity; + for (const k of OFFS) { + const p = lens(g, wrap(base + k + shoulder), len); + const her = (T.los(m, p.x, p.y, p.z, L.x, L.y + 450, L.z) ? 2 : 0) + (T.los(m, p.x, p.y, p.z, L.x, L.y + 700, L.z) ? 2 : 0); + const seen = pts.length ? pts.filter(q => T.los(m, p.x, p.y, p.z, q[0], q[1], q[2])).length / pts.length : 0; + const s = her + 3 * seen + 1.5 * Math.min(1, p.r / 900) - 1.2 * Math.abs(k) / deg(90) - (k === L.cam.off ? 0 : 0.4); + if (s > bestS) { bestS = s; best = k; } + } + return best; + } + T.camTick = g => { + if (g.noCamera) return; + const L = g.lara, b = g.boss, c = L.cam; + c.lock += ((L.target ? 1 : 0) - c.lock) * LOCK_BLEND; + let base = L.rot, frame = 0; + if (L.target) { base = wrap(L.rot + L.targetYaw); frame = 1; } + else if (bossShown(b)) { const rel = wrap(atan(b.x - L.x, b.z - L.z) - L.rot); if (Math.abs(rel) < deg(100)) { base = wrap(L.rot + clamp(rel, -deg(35), deg(35))); frame = 1; } } + c.fr += (frame - c.fr) * LOCK_BLEND; + c.look = wrap(c.look + wrap(base - c.look) * YAW_BLEND); + const len = C.CHASE + (C.COMBAT - C.CHASE) * c.lock, shoulder = C.SHOULDER * c.lock; + if (g.t % 6 === 0) c.off = pickOffset(g, base, len, shoulder); + L.camYaw = wrap(L.camYaw + wrap(wrap(base + c.off) - L.camYaw) * YAW_BLEND); + const r = T.camBoom(g, wrap(L.camYaw + shoulder), len, C.UP + L.lookPitch * 18); + c.dist = r < c.dist ? r : c.dist + (r - c.dist) * DIST_BLEND; + c.lift += (T.camLift(g, c.dist, len) - c.lift) * LIFT_BLEND; + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/tombraider_remake/tr1core.js b/environments/games/web/games/tombraider_remake/tr1core.js new file mode 100644 index 0000000000000000000000000000000000000000..71adb72e382bafb866b14bcc178e32c5e309f94a --- /dev/null +++ b/environments/games/web/games/tombraider_remake/tr1core.js @@ -0,0 +1,120 @@ +/* Tomb Raider (1996) boss arenas, rules tr1-arena@2 - core: units, RNG, sector map, collision, line of sight, pathing. + Independent reimplementation; constants are read from TRX 4b9b64f and OpenLara 3b268ca (see SOURCES.md), no code is + copied and no original data (levels, animations, models, textures, audio) is used. + Conventions follow the original: world units (1 sector = 1024, 1 click = 256), binary angles (65536 = 360 degrees, + 0 = +z, positive = turn right). One difference: y grows upward here (the original's y grows down). + Clock (tr1-arena@2, 2026-11-06): the original runs 30 ticks per second; this reimplementation runs 60. Every constant below and in the other + files is still written in the original's 30 Hz units and converted where it is defined, with the helpers here: + per-tick velocities T.v, per-tick accelerations T.acc, durations T.n, per-tick chances T.chance, per-tick blend factors T.blend. */ +(function (root) { + 'use strict'; + const N = root.NativeBench, M = root.TombRaiderGame = {}, T = M.T = {}; + T.HZ = 60; const TS = T.TS = T.HZ / 30; // new ticks per original tick + T.v = x => x / TS; // units (or angle) per original tick -> per new tick + T.acc = x => x / (TS * TS); // per original tick, per original tick -> per new tick squared + T.n = x => Math.round(x * TS); // a duration of x original ticks -> new ticks (exact for 30 -> 60) + T.chance = c => 32768 * (1 - Math.pow(1 - c / 32768, 1 / TS)); // a 0..32767 threshold rolled every original tick -> rolled every new tick, same rate per second + T.blend = k => 1 - Math.pow(1 - k, 1 / TS); // x += (target - x) * k every original tick + T.anim = tab => Object.fromEntries(Object.entries(tab).map(([k, a]) => [k, Object.assign({}, a, { len: T.n(a.len), speed: T.v(a.speed) }, a.rot ? { rot: T.v(a.rot) } : {})])); // 30 Hz ANIM table -> 60 Hz + Object.assign(T, { WALL_L: 1024, STEP_L: 256, GRAVITY: T.acc(6), FAST_FALL: T.v(128), FALL_TAIL: T.acc(1), STEPUP: 384 }); + const TAU = Math.PI * 2; + T.deg = d => Math.round(d * 65536 / 360); + T.DEG90 = 16384; T.DEG180 = 32768; + T.wrap = a => ((Math.round(a) + 32768) & 65535) - 32768; // int16 wrap-around, as the original's angle arithmetic + T.sin = a => Math.sin(a * TAU / 65536); + T.cos = a => Math.cos(a * TAU / 65536); + T.atan = (dx, dz) => Math.round(Math.atan2(dx, dz) * 65536 / TAU); // Math_Atan(z, x) + T.rand = g => Math.floor(N.rand(g) * 32768); // Random_GetControl: 0..32767 + T.clamp = N.clamp; + T.event = (g, type, data) => { g.events.push(Object.assign({ type, t: g.t }, data || {})); }; + T.fx = (g, kind, x, y, z, life, extra) => { // cosmetic, read by the renderer only; never touches the RNG. life in original ticks + g.fx.push(Object.assign({ kind, x, y, z, t0: g.t, life: T.n(life), id: g.fxSeq++ }, extra || {})); + if (g.fx.length > 80) g.fx.splice(0, g.fx.length - 80); + }; + + // ---------------- sector map: rows of characters, one per sector. '#' = solid to the ceiling, digits = floor height in clicks ---------------- + const WALL = T.WALL = 1e9; + T.parseMap = rows => { + const h = rows.length, w = rows[0].length, cells = []; + for (const r of rows) { if (r.length !== w) throw Error('uneven map'); for (const c of r) cells.push(c === '#' ? WALL : c === '.' ? 0 : Number(c) * T.STEP_L); } + return { w, h, cells: Object.freeze(cells), rows }; + }; + T.floorAt = (m, x, z) => { + const i = Math.floor(x / T.WALL_L), j = Math.floor(z / T.WALL_L); + if (i < 0 || j < 0 || i >= m.w || j >= m.h) return WALL; + return m.cells[j * m.w + i]; + }; + // Highest floor under a square of half-width r: the footprint test a sector grid allows. + const floorUnder = T.floorUnder = (m, x, z, r) => Math.max(T.floorAt(m, x - r, z - r), T.floorAt(m, x + r, z - r), T.floorAt(m, x - r, z + r), T.floorAt(m, x + r, z + r)); + // Axis-separated slide against sectors a body at height y cannot step onto. Returns what blocked it. + T.slide = (m, e, dx, dz, r, climb) => { + let hitX = false, hitZ = false; + if (dx && floorUnder(m, e.x + dx, e.z, r) - e.y <= climb) e.x += dx; else if (dx) hitX = true; + if (dz && floorUnder(m, e.x, e.z + dz, r) - e.y <= climb) e.z += dz; else if (dz) hitZ = true; + return { hitX, hitZ }; + }; + // LOS_Check on a sector grid: 64-unit march, blocked by any floor rising above the ray. + T.los = (m, ax, ay, az, bx, by, bz) => { + const d = Math.hypot(bx - ax, bz - az), n = Math.max(1, Math.ceil(d / 64)); + for (let i = 1; i < n; i++) { const f = i / n; if (T.floorAt(m, ax + (bx - ax) * f, az + (bz - az) * f) > ay + (by - ay) * f) return false; } + return true; + }; + const corridor = (m, ax, az, bx, bz, r, y) => { // a body of half-width r can walk straight from a to b + const d = Math.hypot(bx - ax, bz - az), n = Math.max(1, Math.ceil(d / 128)); + for (let i = 0; i <= n; i++) { const f = i / n; if (floorUnder(m, ax + (bx - ax) * f, az + (bz - az) * f, r) > y + T.STEPUP) return false; } + return true; + }; + // ---------------- pathing: the original's AI boxes reduced to sectors. A breadth-first flow field from the target's sector; + // the creature aims at the farthest sector centre along it that it can reach in a straight line (Box_CalculateTarget's role). + // The cache is a pure function of (map, sector), so it holds no simulation state. + const flows = new WeakMap(); + function flow(m, ti, tj) { + let byT = flows.get(m); if (!byT) { byT = new Map(); flows.set(m, byT); } + const key = tj * m.w + ti; let dist = byT.get(key); + if (dist) return dist; + dist = new Int16Array(m.w * m.h).fill(-1); + const q = [key]; dist[key] = 0; + for (let k = 0; k < q.length; k++) { + const c = q[k], i = c % m.w, j = (c - i) / m.w; + for (const [a, b] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) { + const u = i + a, v = j + b; if (u < 0 || v < 0 || u >= m.w || v >= m.h) continue; + const n = v * m.w + u; if (dist[n] >= 0 || m.cells[n] === WALL) continue; + dist[n] = dist[c] + 1; q.push(n); + } + } + byT.set(key, dist); + return dist; + } + T.pathTarget = (m, e, r, tx, tz) => { + if (corridor(m, e.x, e.z, tx, tz, r, e.y)) return { x: tx, z: tz }; + const ti = T.clamp(Math.floor(tx / T.WALL_L), 0, m.w - 1), tj = T.clamp(Math.floor(tz / T.WALL_L), 0, m.h - 1), dist = flow(m, ti, tj); + let i = T.clamp(Math.floor(e.x / T.WALL_L), 0, m.w - 1), j = T.clamp(Math.floor(e.z / T.WALL_L), 0, m.h - 1); + let best = { x: tx, z: tz }, found = false; + for (let guard = 0; guard < 64; guard++) { + const here = dist[j * m.w + i]; if (here <= 0) break; + let nx = -1, ny = -1, low = here; + for (const [a, b] of [[0, -1], [1, 0], [0, 1], [-1, 0]]) { + const u = i + a, v = j + b; if (u < 0 || v < 0 || u >= m.w || v >= m.h) continue; + const dn = dist[v * m.w + u]; if (dn >= 0 && dn < low) { low = dn; nx = u; ny = v; } + } + if (nx < 0) break; + i = nx; j = ny; + const cx = (i + 0.5) * T.WALL_L, cz = (j + 0.5) * T.WALL_L; + if (corridor(m, e.x, e.z, cx, cz, r, e.y) || !found) { best = { x: cx, z: cz }; found = true; } else break; + } + return best; + }; + // Lara's body as the vertical segment her spheres cover, against a sphere: Collide_TestCollision reduced to one capsule. + T.touchesLara = (L, s, x, y, z, r) => { + const lo = L.y + T.LARA_RADIUS, hi = L.y + T.LARA_HEIGHT - T.LARA_RADIUS, cy = T.clamp(y, lo, hi), R = r + T.LARA_RADIUS; + const dx = x - L.x, dz = z - L.z, dy = y - cy; + return dx * dx + dy * dy + dz * dz < R * R; + }; + // Ray (unit direction) against a sphere, front side only: the test in Gun_FireWeapon, in world space. + T.rayHitsSphere = (ox, oy, oz, dx, dy, dz, sx, sy, sz, r) => { + const px = sx - ox, py = sy - oy, pz = sz - oz, along = px * dx + py * dy + pz * dz; + if (along <= r) return null; + const qx = px - along * dx, qy = py - along * dy, qz = pz - along * dz; + return qx * qx + qy * qy + qz * qz <= r * r ? along - r : null; + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/tombraider_remake/tr1creature.js b/environments/games/web/games/tombraider_remake/tr1creature.js new file mode 100644 index 0000000000000000000000000000000000000000..7289b773b1894f979a4807a95a1e57fb29dd27a2 --- /dev/null +++ b/environments/games/web/games/tombraider_remake/tr1creature.js @@ -0,0 +1,59 @@ +/* Tomb Raider (1996) boss arenas - the shared creature layer: AI_INFO, turning, moving, contact, generic body tests. + Documented (TRX creature/common.c, creature/shooting.c, creature/const.h): Creature_AIInfo, Creature_Turn, the shot roll. + Approximation: the original changes state only where the animation data allows it; here each state has one tick + length (per boss, in its ANIM table), and a pending goal is taken when that length is up. See */ +(function (root) { + 'use strict'; + const M = root.TombRaiderGame, T = M.T, { wrap, sin, cos, atan, clamp } = T; + T.CREATURES = {}; + const FRONT_ARC = T.DEG90; + Object.assign(T, { BITE_HEIGHT: 256, SHOOT_RANGE: 7 * T.WALL_L, MISS_CHANCE: 0x2000 }); + // Creature_AIInfo. `distance` is squared, as in the original; pivot is the object's pivot_length. + T.aiInfo = (g, b, pivot) => { + const L = g.lara, x = L.x - sin(b.rot) * (pivot || 0) - b.x, z = L.z - cos(b.rot) * (pivot || 0) - b.z; + const angle = atan(x, z), rel = wrap(angle - b.rot), facing = wrap(angle - L.rot + T.DEG180); + const ahead = rel > -FRONT_ARC && rel < FRONT_ARC; + return { distance: x * x + z * z, angle: rel, facing, ahead, bite: ahead && Math.abs(L.y - b.y) <= T.BITE_HEIGHT }; + }; + // Creature_Turn, then the forward move the animation would have made. speed 0 does not turn (TR1 branch). + T.creatureMove = (g, b, speed, maxTurn, radius) => { + let turned = 0; + if (speed > 0 && maxTurn > 0) { + const t = T.pathTarget(g.map, b, radius, g.lara.x, g.lara.z), dx = t.x - b.x, dz = t.z - b.z; + const angle = wrap(atan(dx, dz) - b.rot); + let cap = maxTurn; + if (angle > FRONT_ARC || angle < -FRONT_ARC) { + const range = speed * 16384 / maxTurn; + if (dx * dx + dz * dz < range * range) cap = maxTurn / 2; + } + turned = clamp(angle, -cap, cap); + b.rot = wrap(b.rot + turned); + T.slide(g.map, b, sin(b.rot) * speed, cos(b.rot) * speed, radius, T.STEPUP); + b.y = T.floorUnder(g.map, b.x, b.z, radius); + } + return turned; + }; + T.bodySpheres = (b, list) => { + const s = sin(b.rot), c = cos(b.rot); + return list.map(([f, h, r, side]) => [b.x + s * f + c * (side || 0), b.y + h, b.z + c * f - s * (side || 0), r]); + }; + const PUSH = T.v(40); // push-out per tick, 40 per original tick + // Creature_Collision + Lara_Push reduced to spheres: pushes Lara out sideways and reports touch_bits != 0. + T.pushLara = (g, spheres) => { + const L = g.lara; let touch = false; + for (const [x, y, z, r] of spheres) { + if (!T.touchesLara(L, null, x, y, z, r)) continue; + touch = true; + const dx = L.x - x, dz = L.z - z, d = Math.hypot(dx, dz) || 1, R = r + T.LARA_RADIUS; + if (d < R) T.slide(g.map, L, dx / d * Math.min(R - d, PUSH), dz / d * Math.min(R - d, PUSH), T.LARA_RADIUS, T.STEPUP); + } + return touch; + }; + // Linear between the three tier anchors, held outside them. Purely a function of d. + T.tierValue = (d, tiers, a) => { + if (d <= tiers.easy) return a[0]; + if (d >= tiers.hard) return a[2]; + const lo = d <= tiers.normal, x0 = lo ? tiers.easy : tiers.normal, x1 = lo ? tiers.normal : tiers.hard, y0 = lo ? a[0] : a[1], y1 = lo ? a[1] : a[2]; + return y0 + (y1 - y0) * (d - x0) / (x1 - x0); + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/tombraider_remake/tr1player.js b/environments/games/web/games/tombraider_remake/tr1player.js new file mode 100644 index 0000000000000000000000000000000000000000..5efaecff1be3d87265c4a15e076401978b21a6bf --- /dev/null +++ b/environments/games/web/games/tombraider_remake/tr1player.js @@ -0,0 +1,252 @@ +/* Tomb Raider (1996) boss arenas - Lara: state machine, turning, jumps, pistols. See sections B-D. + Documented (TRX gun/pistols.c, gun/misc.c, gun/control.c, lara/const.h, lara/state/*.c, lara/control.c): the turn rates and their order + of application, gravity, the pistol arm-frame counter (10 ticks per shot, both hands), spread, lock cone, arm arcs, aim speed. + Approximation (the original keeps these in its animation data, which is copyrighted and not used): every speed and duration in APPROX. */ +(function (root) { + 'use strict'; + const M = root.TombRaiderGame, T = M.T, { wrap, sin, cos, atan, deg, clamp } = T; + Object.assign(T, { LARA_MAX_HP: 1000, LARA_RADIUS: 100, LARA_HEIGHT: 762, GUN_HEIGHT: 650 }); + // lara/const.h at 30 Hz: +409 per tick while a turn key is held, then -364 undo every tick, caps 728 / 1092 / 1456 / 546. The 30 Hz net + // behaviour is a ramp of 45 per tick per tick up to (cap - 364) per tick, and a 364 per tick per tick decay on release. At 60 Hz the undo is + // an acceleration (/4), the ramp too, and each cap is chosen so cap - undo is the original top rate per second (/2). + const TURN_UNDO = T.acc(364), TURN_RATE = T.acc(409 - 364) + TURN_UNDO, capOf = x => T.v(x - 364) + TURN_UNDO; + const SLOW = capOf(728), MED = capOf(1092), FAST = capOf(1456), JUMP_TURN = capOf(546); + // Approximations, written in 30 Hz units (units per original tick, original ticks) and converted; jump numbers give the usual 1 sector standing, + // 2 sectors running over 0.7 s in the air. + const A30 = T.LARA_APPROX30 = { run: 44, walk: 20, back: 30, walkBack: 16, step: 20, accel: 8, compress: 3, jumpUp: 66, jumpStand: 46.5, jumpRun: 93, land: 3, roll: 15, rollSpeed: 16, backHop: 14 }; + const APPROX = T.LARA_APPROX = { run: T.v(A30.run), walk: T.v(A30.walk), back: T.v(A30.back), walkBack: T.v(A30.walkBack), step: T.v(A30.step), accel: T.acc(A30.accel), + compress: T.n(A30.compress), jumpUp: T.v(A30.jumpUp), jumpStand: T.v(A30.jumpStand), jumpRun: T.v(A30.jumpRun), land: T.n(A30.land), roll: T.n(A30.roll), rollSpeed: T.v(A30.rollSpeed), backHop: T.n(A30.backHop) }; + // Arm frames, gun/pistols.c with lara/enum.h. The arm animation advances one frame per original (30 Hz) tick: armTick steps it every TS ticks. + const AIM_START = 0, AIM_BEND = 1, AIM_EXTEND = 3, AIM_END = 4, RECOIL_START = 24, RECOIL_END = 32, RECOIL_FRAME = 9; + // weapons.json5, pistols + const PISTOL = T.PISTOL = { damage: 1, range: 8 * T.WALL_L, aimSpeed: T.v(deg(10)), spread: deg(8), lock: deg(60), armOut: deg(170), armIn: deg(60), drawTicks: T.n(19) }; + const MEDI_SMALL = 500, HOP_MOVE = T.n(A30.backHop - 1), HOP_END = T.n(A30.backHop) + T.TS - 1; + const arm = () => ({ frame: AIM_START, lock: false, ry: 0, rx: 0, flash: 0, sub: 0 }); + + T.spawnLara = (x, z, rot, y) => ({ + x, y: y || 0, z, rot, turnRate: 0, state: 'stop', stateT: 0, speed: 0, moveAngle: rot, fall: 0, airborne: false, hp: T.LARA_MAX_HP, + medi: 2, gun: 'ready', gunT: 0, target: false, targetYaw: 0, targetPitch: 0, armL: arm(), armR: arm(), torso: 0, + mouseFrac: 0, lookPitch: 0, camYaw: rot, cam: T.camRig(rot), hitFlash: 0, shots: 0, hits: 0, damageTaken: 0, bitten: false, + }); + T.laraDamage = (g, n, kind) => { + const L = g.lara; if (L.hp <= 0) return; + L.hp -= n; L.damageTaken += n; + if (L.hp <= 0 && g.oneHpFixture) { g.fixtureSaves = (g.fixtureSaves || 0) + 1; L.hp = 1; L.bitten = false; } + L.hp = Math.max(0, L.hp); L.hitFlash = Math.max(L.hitFlash, T.n(Math.min(12, 3 + n))); + if (n >= 10) T.event(g, 'player_hit', { damage: n, kind }); + }; + const setState = (L, s) => { if (L.state !== s) { L.state = s; L.stateT = 0; } }; + const turnBy = (L, sign, cap) => { L.turnRate = clamp(L.turnRate + sign * TURN_RATE, -cap, cap); }; + function approach(L, to) { L.speed = L.speed < to ? Math.min(to, L.speed + APPROX.accel) : Math.max(to, L.speed - APPROX.accel); } + // Gravity at 60 Hz: the 30 Hz rule is v += 6 then y -= v once per original tick. With a = 6/4 per new tick and a start offset of a(TS-1)/2 the + // new-tick sum over each original tick equals the original step exactly, so heights and air time match the original at every 1/30 s. + const FALL0 = T.GRAVITY * (T.TS - 1) / 2; + function startJump(L, angle, h) { setState(L, 'jump'); L.airborne = true; L.fall = -APPROX.jumpUp + FALL0; L.moveAngle = angle; L.speed = h; } + + function stateTick(g, L, keys, pressed) { + const W = keys.has('W'), S = keys.has('S'), A = keys.has('A'), D = keys.has('D'), slow = keys.has('Shift'), jump = keys.has('Space'); + const Q = keys.has('Q'), E = keys.has('E'), roll = pressed.has('L'), side = A ? -1 : D ? 1 : 0; + L.stateT++; + switch (L.state) { + case 'stop': { + approach(L, 0); L.moveAngle = L.rot; + if (roll) { setState(L, 'roll'); L.moveAngle = L.rot; L.speed = APPROX.rollSpeed; break; } + if (jump) { setState(L, 'compress'); break; } + if (W) { setState(L, slow ? 'walk' : 'run'); break; } + if (S) { setState(L, slow ? 'walkBack' : 'backHop'); break; } + if (Q || E) { setState(L, Q ? 'stepL' : 'stepR'); break; } + if (side) { + // M_TurnLeft/Right + M_FastTurn: with the guns ready Lara goes straight to the fast turn; otherwise once past the slow rate. + if (L.gun === 'ready' || Math.abs(L.turnRate) > SLOW) L.turnRate = side * FAST; + else turnBy(L, side, FAST); + } + break; + } + case 'run': + if (roll) { setState(L, 'roll'); L.moveAngle = L.rot; L.speed = APPROX.rollSpeed; break; } + if (side) turnBy(L, side, FAST); + L.moveAngle = L.rot; + if (jump) { startJump(L, L.rot, APPROX.jumpRun); break; } + if (!W) { setState(L, 'stop'); break; } + if (slow) { setState(L, 'walk'); break; } + approach(L, APPROX.run); + break; + case 'walk': + if (side) turnBy(L, side, SLOW); + L.moveAngle = L.rot; + if (!W) { setState(L, 'stop'); break; } + if (!slow) { setState(L, 'run'); break; } + approach(L, APPROX.walk); + break; + case 'backHop': // LS_FAST_BACK: one committed hop, repeated while S is held + // At 30 Hz a hop cycle is 15 ticks: 1 in stop, 13 moving, 1 ending. The new clock keeps that per second: the hop runs TS - 1 ticks longer + // (the stop tick between hops is one new tick, not one original tick) and moves only over the original's 13 moving ticks. + if (side) turnBy(L, side, MED); + L.moveAngle = wrap(L.rot + T.DEG180); L.speed = L.stateT <= HOP_MOVE ? APPROX.back : 0; + if (L.stateT >= HOP_END) { L.speed = 0; setState(L, 'stop'); } + break; + case 'walkBack': + if (side) turnBy(L, side, SLOW); + L.moveAngle = wrap(L.rot + T.DEG180); L.speed = APPROX.walkBack; + if (!S || !slow) { L.speed = 0; setState(L, 'stop'); } + break; + case 'stepL': case 'stepR': { + const held = L.state === 'stepL' ? Q : E; + L.moveAngle = wrap(L.rot + (L.state === 'stepL' ? -T.DEG90 : T.DEG90)); L.speed = APPROX.step; + if (!held) { L.speed = 0; setState(L, 'stop'); } + break; + } + case 'compress': // M_Compress: the direction read at the end of the crouch picks the jump + approach(L, 0); + if (L.stateT >= APPROX.compress) { + if (W) startJump(L, L.rot, APPROX.jumpStand); + else if (A) startJump(L, wrap(L.rot - T.DEG90), APPROX.jumpStand); + else if (D) startJump(L, wrap(L.rot + T.DEG90), APPROX.jumpStand); + else if (S) startJump(L, wrap(L.rot + T.DEG180), APPROX.jumpStand); + else startJump(L, L.rot, 0); + } + break; + case 'jump': + if (side) turnBy(L, side, JUMP_TURN); + break; + case 'land': // at 30 Hz the last tick of a committed state stands still: here its whole last original tick (TS new ticks) does + approach(L, 0); if (L.stateT > T.n(A30.land - 1)) L.speed = 0; + if (L.stateT >= APPROX.land) { L.speed = 0; setState(L, 'stop'); } + break; + case 'roll': + if (L.stateT >= APPROX.roll) { L.rot = wrap(L.rot + T.DEG180); L.camYaw = wrap(L.camYaw + T.DEG180); L.speed = 0; setState(L, 'stop'); } + break; + } + } + // The turn cap of the current state; the mouse may never turn Lara faster than the keys do. + function turnCap(L) { + switch (L.state) { + case 'stop': case 'run': return FAST - TURN_UNDO; + case 'backHop': return MED - TURN_UNDO; + case 'jump': return JUMP_TURN - TURN_UNDO; + case 'walk': case 'walkBack': return SLOW - TURN_UNDO; + default: return 0; + } + } + T.laraTick = function (g, keys, pressed, mouse) { + const L = g.lara, m = g.map; + if (L.hp <= 0) return; + if (L.hitFlash > 0) L.hitFlash--; + if (pressed.has('R') && L.medi > 0 && L.hp < T.LARA_MAX_HP) { L.medi--; L.hp = Math.min(T.LARA_MAX_HP, L.hp + MEDI_SMALL); T.event(g, 'medipack', { hp: L.hp }); } + stateTick(g, L, keys, pressed); + // lara/control.c: undo first, then apply. Keyboard turning alone never exceeds the cap; the mouse fills up to it, one count = 0.1 degrees. + L.turnRate = L.turnRate > 0 ? Math.max(0, L.turnRate - TURN_UNDO) : Math.min(0, L.turnRate + TURN_UNDO); + const cap = turnCap(L), wanted = mouse[0] * 18.2 + L.mouseFrac; + const total = clamp(L.turnRate + wanted, -Math.max(cap, Math.abs(L.turnRate)), Math.max(cap, Math.abs(L.turnRate))); + const whole = Math.round(total); + L.mouseFrac = cap ? clamp(total - whole, -1, 1) : 0; + L.rot = wrap(L.rot + whole); + L.lookPitch = clamp(L.lookPitch - mouse[1] * 0.1, -60, 60); + // movement + const dx = sin(L.moveAngle) * L.speed, dz = cos(L.moveAngle) * L.speed; + const hit = T.slide(m, L, dx, dz, T.LARA_RADIUS, L.airborne ? 0 : T.STEPUP); + if (L.airborne && (hit.hitX || hit.hitZ)) L.speed = 0; // Lara_Col_Jumper: a wall kills the horizontal speed + const floor = T.floorUnder(m, L.x, L.z, T.LARA_RADIUS); + if (L.airborne) { + L.fall += L.fall < T.FAST_FALL ? T.GRAVITY : T.FALL_TAIL; // lara/common.c + L.y -= L.fall; + if (L.y <= floor && L.fall >= 0) { L.y = floor; L.airborne = false; L.fall = 0; setState(L, 'land'); } + } else if (floor < L.y) { + L.airborne = true; L.fall = FALL0; setState(L, 'jump'); // walked off an edge + } else L.y = floor; + // The camera (camYaw, cam) is updated after the guns by T.camTick (tr1camera.js), from Game.update. + }; + + // ---------------- pistols ---------------- + function targetFrom(g) { + const L = g.lara, b = g.boss, c = T.CREATURES[b.kind], p = c.aimPoint(b); + const gx = L.x, gy = L.y + T.GUN_HEIGHT, gz = L.z; + const dx = p.x - gx, dy = p.y - gy, dz = p.z - gz; + return { p, gx, gy, gz, yaw: atan(dx, dz), pitch: Math.round(Math.atan2(dy, Math.hypot(dx, dz)) * 65536 / (Math.PI * 2)), los: T.los(g.map, gx, gy, gz, p.x, p.y, p.z) }; + } + function considerTarget(g, t) { // M_ConsiderTarget + const L = g.lara, b = g.boss; + if (b.hp <= 0 || (T.CREATURES[b.kind].untargetable && T.CREATURES[b.kind].untargetable(b))) return false; + if (Math.hypot(b.x - L.x, b.y - (L.y + T.GUN_HEIGHT), b.z - L.z) >= PISTOL.range || !t.los) return false; + const ay = wrap(t.yaw - (L.torso + L.rot)), ax = t.pitch; + return Math.abs(ay) <= PISTOL.lock && Math.abs(ax) <= PISTOL.lock; + } + function targetInfo(g, t) { // Gun_TargetInfo + const L = g.lara; + if (!L.target) { L.armL.lock = false; L.armR.lock = false; L.targetYaw = 0; L.targetPitch = 0; return; } + const ay = wrap(t.yaw - L.rot), ax = t.pitch; + if (!t.los) { L.armL.lock = false; L.armR.lock = false; } + else if (Math.abs(ay) <= PISTOL.lock && Math.abs(ax) <= PISTOL.lock) { L.armL.lock = true; L.armR.lock = true; } + else { + if (L.armL.lock && (ay < -PISTOL.armOut || ay > PISTOL.armIn || Math.abs(ax) > deg(80))) L.armL.lock = false; + if (L.armR.lock && (ay < -PISTOL.armIn || ay > PISTOL.armOut || Math.abs(ax) > deg(80))) L.armR.lock = false; + } + L.targetYaw = ay; L.targetPitch = ax; + } + function aimArm(L, a) { // Gun_AimWeapon + const s = PISTOL.aimSpeed, dy = a.lock ? L.targetYaw : 0, dx = a.lock ? L.targetPitch : 0; + a.ry = a.ry >= dy - s && a.ry <= dy + s ? dy : a.ry < dy ? a.ry + s : a.ry - s; + a.rx = a.rx >= dx - s && a.rx <= dx + s ? dx : a.rx < dx ? a.rx + s : a.rx - s; + } + function fire(g, a, side) { // Gun_FireWeapon + const L = g.lara, b = g.boss, c = T.CREATURES[b.kind]; + const yaw = wrap(a.ry + L.rot + PISTOL.spread * (T.rand(g) - T.DEG90) / 65536), pitch = a.rx + PISTOL.spread * (T.rand(g) - T.DEG90) / 65536; + const cp = cos(pitch), dx = sin(yaw) * cp, dy = sin(pitch), dz = cos(yaw) * cp; + const ox = L.x, oy = L.y + T.GUN_HEIGHT, oz = L.z; + L.shots++; a.flash = T.n(3); + let best = null; + if (L.target && b.hp > 0) for (const s of c.spheres(b)) { + const hit = T.rayHitsSphere(ox, oy, oz, dx, dy, dz, s[0], s[1], s[2], s[3]); + if (hit !== null && (best === null || hit < best)) best = hit; + } + if (best === null) { + let d = 64, reach = PISTOL.range; + while (d < reach && T.floorAt(g.map, ox + dx * d, oz + dz * d) <= oy + dy * d) d += 64; + T.fx(g, 'ricochet', ox + dx * d, oy + dy * d, oz + dz * d, 6, { side, src: 'lara' }); + return; + } + L.hits++; + const was = b.hp; b.hp = Math.max(c.hpFloor ? c.hpFloor(b) : 0, b.hp - PISTOL.damage); + T.fx(g, 'blood', ox + dx * best, oy + dy * best, oz + dz * best, 10, { side, src: 'lara' }); + c.onHit && c.onHit(g, b, PISTOL.damage); + if (was > 0 && b.hp <= 0) T.event(g, 'boss_dead', { kind: b.kind }); + } + function armTick(g, L, a, action, side) { // M_Animate, one hand: one frame per original tick + if (a.flash > 0) a.flash--; + if (++a.sub < T.TS) return; + a.sub = 0; + let f = a.frame; + if (!a.lock && (!action || L.target)) { + if (f >= RECOIL_START && f <= RECOIL_END) f = AIM_END; + else if (f >= AIM_BEND && f <= AIM_END) f--; + } else if (f >= AIM_START && f <= AIM_EXTEND) f++; + else if (f === AIM_END) { if (action) { fire(g, a, side); f = RECOIL_START; } } + else if (f >= RECOIL_START && f <= RECOIL_END) { f++; if (f === RECOIL_START + RECOIL_FRAME) f = AIM_END; } + a.frame = f; + } + T.gunTick = function (g, keys, pressed) { + const L = g.lara; + if (L.hp <= 0) return; + const action = keys.has('J') || keys.has('LMB'); + if (pressed.has('K') || pressed.has('RMB')) { // Gun_Control: the draw key flips between drawn and holstered + if (L.gun === 'ready') { L.gun = 'undraw'; L.gunT = PISTOL.drawTicks; L.target = false; L.armL.lock = L.armR.lock = false; } + else if (L.gun === 'armless') { L.gun = 'draw'; L.gunT = PISTOL.drawTicks; } + } + if (L.gun === 'draw' || L.gun === 'undraw') { + L.armL.ry = L.armR.ry = L.armL.rx = L.armR.rx = 0; + if (--L.gunT <= 0) { L.gun = L.gun === 'draw' ? 'ready' : 'armless'; L.armL.frame = L.armR.frame = AIM_START; } + return; + } + if (L.gun !== 'ready') { L.torso = 0; return; } + const cre = T.CREATURES[g.boss.kind]; + if (cre.untargetable && cre.untargetable(g.boss)) { L.target = false; L.armL.lock = L.armR.lock = false; } // M_IsTargetable: the lock drops at once + const t = targetFrom(g), held = L.target && action; // Gun_GetNewTarget: a target is kept while the trigger stays down + if (!held) L.target = considerTarget(g, t); + targetInfo(g, t); + aimArm(L, L.armL); aimArm(L, L.armR); + // Gun_Pistols_Control: the torso follows the locked arms + L.torso = L.armL.lock && L.armR.lock ? (L.armL.ry + L.armR.ry) / 4 : L.armL.lock ? L.armL.ry / 2 : L.armR.lock ? L.armR.ry / 2 : 0; + armTick(g, L, L.armR, action, 'R'); + armTick(g, L, L.armL, action, 'L'); + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/touhou_remake/compact_actions.json b/environments/games/web/games/touhou_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..ef6ea8595c7b183194227d13362c4d92ed68bd83 --- /dev/null +++ b/environments/games/web/games/touhou_remake/compact_actions.json @@ -0,0 +1,148 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "touhou_remake", + "version": "touhou-compact@1", + "heads": [ + { + "name": "move", + "options": [ + { + "label": "none" + }, + { + "label": "up", + "keys": [ + "W" + ] + }, + { + "label": "down", + "keys": [ + "S" + ] + }, + { + "label": "left", + "keys": [ + "A" + ] + }, + { + "label": "right", + "keys": [ + "D" + ] + }, + { + "label": "up_left", + "keys": [ + "W", + "A" + ] + }, + { + "label": "up_right", + "keys": [ + "W", + "D" + ] + }, + { + "label": "down_left", + "keys": [ + "S", + "A" + ] + }, + { + "label": "down_right", + "keys": [ + "S", + "D" + ] + } + ] + }, + { + "name": "action", + "options": [ + { + "label": "none" + }, + { + "label": "bomb_focus", + "subs": [ + [ + "K", + "J" + ], + [ + "J", + "Shift" + ], + [ + "J", + "Shift" + ], + [ + "J", + "Shift" + ], + [ + "J", + "Shift" + ], + [ + "J", + "Shift" + ] + ] + }, + { + "label": "bomb_fast", + "subs": [ + [ + "K", + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ] + ] + }, + { + "label": "bomb_hold", + "keys": [ + "K", + "J" + ] + }, + { + "label": "fire_fast", + "keys": [ + "J" + ] + }, + { + "label": "fire_focus", + "keys": [ + "J", + "Shift" + ] + } + ] + } + ] +} diff --git a/environments/games/web/games/touhou_remake/draw.js b/environments/games/web/games/touhou_remake/draw.js new file mode 100644 index 0000000000000000000000000000000000000000..8a49bab5efd243522f346ab8bd7ae487249ccff7 --- /dev/null +++ b/environments/games/web/games/touhou_remake/draw.js @@ -0,0 +1,671 @@ +/* Read-only renderer for touhou_remake (scarlet-practice@8). The whole 854x480 frame is the playfield: no side panel and no + * frame; the HUD is drawn over the field in the corners. Never writes game state and never touches the game RNG. + * All art is original procedural Canvas drawing; sprites and tiles are cached in module-level canvases. */ +(function (root) { + 'use strict'; + const M = root.TouhouGame, TAU = Math.PI * 2, PI = Math.PI, W = M.W, H = M.H, CX = M.CX; + const SANS = '"Yu Gothic UI","Yu Gothic","Microsoft YaHei","Meiryo",sans-serif', SERIF = 'Georgia,"Yu Mincho","SimSun",serif'; + const COL = ['#ff3048', '#ff5ec8', '#3a6bff', '#3fd2ff', '#45e06a', '#ffe14a', '#ff9a2a', '#eef2ff', '#a85cff']; + const DIFF_COL = ['#7fe08a', '#7fb4ff', '#ffb35c', '#d78cff']; + const THEME = {rumia: {acc: '255,70,90', bar: ['#ff9ec0', '#ff4f86']}, cirno: {acc: '150,220,255', bar: ['#bff0ff', '#58b8ff']}, sakuya: {acc: '190,200,255', bar: ['#e6e9ff', '#8f9cff']}, meiling: {acc: '120,230,150', bar: ['#c8ffd4', '#3fc06a']}, patchouli: {acc: '200,150,255', bar: ['#ecd8ff', '#9a5cff']}, remilia: {acc: '255,60,80', bar: ['#ffc2c8', '#e0203a']}}; + const TILE_H = 960, cache = {}; + const hash = n => { n = (n ^ 61) ^ (n >>> 16); n = n + (n << 3); n ^= n >>> 4; n = Math.imul(n, 0x27d4eb2d); n ^= n >>> 15; return (n >>> 0) / 4294967296; }; + function canvas(w, h) { const c = document.createElement('canvas'); c.width = w; c.height = h; return c; } + function rgba(hex, a) { const n = parseInt(hex.slice(1), 16); return `rgba(${n >> 16},${(n >> 8) & 255},${n & 255},${a})`; } + function text(c, s, x, y, size, color, font, align) { c.font = size + 'px ' + (font || SANS); c.textAlign = align || 'left'; c.fillStyle = color; c.fillText(s, x, y); } + function outlined(c, s, x, y, size, color, font, align, edge) { c.font = size + 'px ' + (font || SANS); c.textAlign = align || 'left'; c.lineJoin = 'round'; c.lineWidth = 3; c.strokeStyle = edge || 'rgba(10,6,20,.85)'; c.strokeText(s, x, y); c.fillStyle = color; c.fillText(s, x, y); } + function star(c, cx, cy, r1, r2, fill) { c.fillStyle = fill; c.beginPath(); for (let k = 0; k < 10; k++) { const r = k % 2 ? r2 : r1, a = -PI / 2 + k * PI / 5; c.lineTo(cx + Math.cos(a) * r, cy + Math.sin(a) * r); } c.fill(); } + + // ---------- sprites ---------- + function bulletSprite(k, ci) { + const key = 'b' + k + '_' + ci; if (cache[key]) return cache[key]; + const col = COL[ci] || COL[7], size = [14, 18, 18, 18, 18, 18, 34, 28, 28, 52][k], cv = canvas(size, size), c = cv.getContext('2d'), m = size / 2; + const glow = c.createRadialGradient(m, m, 0, m, m, m); + glow.addColorStop(0, rgba(col, 0.55)); glow.addColorStop(1, rgba(col, 0)); c.fillStyle = glow; c.fillRect(0, 0, size, size); + c.translate(m, m); + const disc = (r, fill) => { c.fillStyle = fill; c.beginPath(); c.arc(0, 0, r, 0, TAU); c.fill(); }; + if (k === 0) { disc(3.2, col); disc(1.6, '#fff'); } + else if (k === 1) { disc(5.2, col); disc(3.4, '#fff'); c.strokeStyle = rgba(col, 0.9); c.lineWidth = 1; c.beginPath(); c.arc(0, 0, 2.2, 0, TAU); c.stroke(); } + else if (k === 3) { disc(5.4, col); disc(3.6, rgba('#ffffff', 0.95)); } + else if (k === 6) { disc(11, col); disc(8, '#fff'); } + else if (k === 7) { disc(9, col); disc(5, '#fff6d8'); } + else if (k === 9) { c.strokeStyle = rgba(col, 0.9); c.lineWidth = 3; c.beginPath(); c.arc(0, 0, 18, 0, TAU); c.stroke(); disc(14, rgba(col, 0.25)); disc(6, rgba('#ffffff', 0.5)); } + else if (k === 8) { // knife: steel blade pointing to +x, coloured guard and glow (blue / red / green read at a glance) + c.fillStyle = rgba(col, 0.9); c.beginPath(); c.moveTo(-6, -4.2); c.lineTo(-4, -4.2); c.lineTo(-4, 4.2); c.lineTo(-6, 4.2); c.closePath(); c.fill(); + c.fillStyle = col; c.fillRect(-11, -1.6, 6, 3.2); + c.fillStyle = '#f4f7ff'; c.beginPath(); c.moveTo(12, 0); c.lineTo(-3, -3); c.lineTo(-4, 0); c.lineTo(-3, 3); c.closePath(); c.fill(); + c.strokeStyle = rgba(col, 0.95); c.lineWidth = 1; c.beginPath(); c.moveTo(11, 0); c.lineTo(-3, 0); c.stroke(); + } else { // oriented shapes pointing to +x + c.fillStyle = col; c.beginPath(); + if (k === 2) c.ellipse(0, 0, 7, 3.4, 0, 0, TAU); + else if (k === 4) { c.moveTo(8, 0); c.lineTo(-2, -4); c.lineTo(-7, -1.5); c.lineTo(-7, 1.5); c.lineTo(-2, 4); } + else { c.moveTo(8.5, 0); c.lineTo(0, -3.2); c.lineTo(-8, 0); c.lineTo(0, 3.2); } + c.closePath(); c.fill(); + c.fillStyle = 'rgba(255,255,255,.92)'; c.beginPath(); + if (k === 2) c.ellipse(0.5, 0, 4, 1.6, 0, 0, TAU); else { c.moveTo(5, 0); c.lineTo(-1, -1.4); c.lineTo(-4, 0); c.lineTo(-1, 1.4); c.closePath(); } + c.fill(); + } + return (cache[key] = cv); + } + function itemSprite(k) { + const key = 'i' + k; if (cache[key]) return cache[key]; + const cv = canvas(22, 22), c = cv.getContext('2d'); + if (k === 6) { + c.translate(11, 11); c.fillStyle = 'rgba(255,240,140,.35)'; c.beginPath(); c.arc(0, 0, 9, 0, TAU); c.fill(); + star(c, 0, 0, 6, 2.4, '#ffe860'); return (cache[key] = cv); + } + const big = k === 2 || k === 4, s = big ? 16 : 12, o = (22 - s) / 2; + const fill = ['#e8333f', '#3a6cf0', '#e8333f', '#3cb84a', '#f0c030', '#ff6fb0'][k], label = ['P', 'Point', 'P', 'B', 'F', '1UP'][k]; + c.fillStyle = 'rgba(0,0,0,.35)'; c.fillRect(o + 1, o + 1, s, s); c.fillStyle = fill; c.fillRect(o, o, s, s); + c.strokeStyle = 'rgba(255,255,255,.85)'; c.lineWidth = 1; c.strokeRect(o + 0.5, o + 0.5, s - 1, s - 1); + c.fillStyle = '#fff'; c.font = 'bold ' + (big ? 12 : 9) + 'px ' + SANS; c.textAlign = 'center'; c.textBaseline = 'middle'; c.fillText(label, 11, 11.5); + return (cache[key] = cv); + } + function shotSprite(k) { + const key = 's' + k; if (cache[key]) return cache[key]; + const cv = canvas(16, 44), c = cv.getContext('2d'); + if (k === 2) { const g = c.createLinearGradient(0, 0, 0, 44); g.addColorStop(0, 'rgba(255,255,255,.95)'); g.addColorStop(1, 'rgba(255,200,120,.1)'); c.fillStyle = g; c.fillRect(6, 2, 4, 40); } + else { + const red = k === 0; c.globalAlpha = 0.5; c.fillStyle = red ? '#ffffff' : '#c9b7ff'; c.fillRect(4, 16, 8, 13); + c.fillStyle = red ? '#ff5470' : '#8a62ff'; c.fillRect(5, 18, 6, 2); c.fillRect(5, 25, 6, 2); + c.globalAlpha = 0.14; c.fillStyle = red ? '#ff8aa0' : '#a080ff'; c.fillRect(2, 14, 12, 17); + } + return (cache[key] = cv); + } + // ---------- stage and spell backgrounds (cached, full width) ---------- + function stageTile(kind) { + const key = 'st' + kind; if (cache[key]) return cache[key]; + const cv = canvas(W, TILE_H), c = cv.getContext('2d'), T = TILE_H; + if (kind === 'rumia') { // dusk forest seen from above, a pale path winding down the middle + const g = c.createLinearGradient(0, 0, W, 0); g.addColorStop(0, '#0f1428'); g.addColorStop(0.5, '#1c2343'); g.addColorStop(1, '#0f1428'); c.fillStyle = g; c.fillRect(0, 0, W, T); + c.strokeStyle = 'rgba(130,108,150,.17)'; c.lineWidth = 140; c.lineCap = 'round'; c.beginPath(); + for (let y = -40; y <= T + 40; y += 6) { const x = CX + Math.sin(y / T * TAU * 2) * 70; if (y === -40) c.moveTo(x, y); else c.lineTo(x, y); } + c.stroke(); + for (let i = 0; i < 330; i++) { + const y = hash(i * 31 + 7) * T, side = i % 2 ? 1 : -1, x = CX + side * (110 + hash(i * 17 + 3) * 330), r = 20 + hash(i * 11) * 30; + for (const yy of [y, y - T, y + T]) { + const gr = c.createRadialGradient(x - r * 0.3, yy - r * 0.3, r * 0.1, x, yy, r); + gr.addColorStop(0, i % 3 ? '#2b3f4a' : '#36405c'); gr.addColorStop(1, 'rgba(10,14,28,0.0)'); c.fillStyle = gr; c.beginPath(); c.arc(x, yy, r, 0, TAU); c.fill(); + } + } + } else if (kind === 'cirno') { // misty lake: deep water with ripple bands + const g = c.createLinearGradient(0, 0, W, 0); g.addColorStop(0, '#0d3247'); g.addColorStop(0.5, '#17546e'); g.addColorStop(1, '#0d3247'); c.fillStyle = g; c.fillRect(0, 0, W, T); + for (let i = 0; i < 260; i++) { + const y = hash(i * 19 + 2) * T, x = hash(i * 23 + 9) * W, rw = 20 + hash(i * 5) * 70; + for (const yy of [y, y - T, y + T]) { c.strokeStyle = 'rgba(190,235,255,' + (0.07 + hash(i) * 0.12).toFixed(3) + ')'; c.lineWidth = 1.2; c.beginPath(); c.ellipse(x, yy, rw, rw * 0.18, 0, 0, TAU); c.stroke(); } + } + } else if (kind === 'meiling') { // the mansion gate: a stone path through the front garden, flower beds and hedges either side + const g = c.createLinearGradient(0, 0, W, 0); g.addColorStop(0, '#13291b'); g.addColorStop(0.5, '#1d3d27'); g.addColorStop(1, '#13291b'); c.fillStyle = g; c.fillRect(0, 0, W, T); + const pw = 210; c.fillStyle = '#3a3533'; c.fillRect(CX - pw / 2, 0, pw, T); + for (let y = 0; y < T; y += 30) for (let x = CX - pw / 2; x < CX + pw / 2; x += 42) { // flagstones + const ox = (y / 30) % 2 ? 21 : 0; c.fillStyle = (((x + ox) / 42 + y / 30) % 3) ? '#4a4440' : '#555049'; c.fillRect(x + ox - 20 + 2, y + 2, 38, 26); + } + c.fillStyle = '#9a2a2a'; c.fillRect(CX - pw / 2 - 6, 0, 6, T); c.fillRect(CX + pw / 2, 0, 6, T); // red brick kerbs + for (let i = 0; i < 300; i++) { // flowers in the beds + const y = hash(i * 29 + 5) * T, side = i % 2 ? 1 : -1, x = CX + side * (pw / 2 + 24 + hash(i * 13 + 1) * 280), col = ['#ff8fb8', '#ffe066', '#ff6a5c', '#ffffff', '#c38bff'][i % 5]; + for (const yy of [y, y - T, y + T]) { c.fillStyle = col; c.globalAlpha = 0.55; c.beginPath(); c.arc(x, yy, 2.5 + hash(i) * 2, 0, TAU); c.fill(); c.globalAlpha = 1; } + } + for (let y = 0; y < T; y += 120) for (const s of [-1, 1]) { // trimmed hedges + const x = CX + s * 380, gr = c.createRadialGradient(x - 8, y - 8, 4, x, y, 34); gr.addColorStop(0, '#3f7a3c'); gr.addColorStop(1, '#173018'); + c.fillStyle = gr; c.beginPath(); c.arc(x, y, 32, 0, TAU); c.fill(); + } + } else if (kind === 'remilia') { // the clock-tower terrace at night: dark slates, a red runner, stone balustrades either side + c.fillStyle = '#100a14'; c.fillRect(0, 0, W, T); + for (let y = 0; y < T; y += 40) for (let x = (y / 40) % 2 ? -30 : 0; x < W; x += 60) { c.fillStyle = hash(x * 11 + y * 3) < 0.5 ? '#1a1220' : '#201626'; c.fillRect(x, y, 58, 38); } + c.fillStyle = '#4a0c18'; c.fillRect(CX - 70, 0, 140, T); c.fillStyle = '#7a1626'; c.fillRect(CX - 70, 0, 6, T); c.fillRect(CX + 64, 0, 6, T); + for (let y = 0; y < T; y += 80) for (const sd of [-1, 1]) { const x = sd < 0 ? 26 : W - 26; c.fillStyle = '#2c2430'; c.fillRect(x - 14, y, 28, 66); c.fillStyle = '#3c3240'; c.fillRect(x - 18, y, 36, 8); c.fillRect(x - 18, y + 58, 36, 8); } + c.fillStyle = 'rgba(255,60,70,.05)'; c.fillRect(0, 0, W, T); + } else if (kind === 'patchouli') { // the Voile library: tall bookshelves either side of a dim aisle, reading desks under lamps + c.fillStyle = '#120c1c'; c.fillRect(0, 0, W, T); + const aisle = 260; c.fillStyle = '#1d1430'; c.fillRect(CX - aisle / 2, 0, aisle, T); + for (let y = 0; y < T; y += 48) for (const sd of [-1, 1]) { + const x0 = sd < 0 ? 0 : CX + aisle / 2, x1 = sd < 0 ? CX - aisle / 2 : W; + c.fillStyle = '#2b1a14'; c.fillRect(x0, y, x1 - x0, 48); c.fillStyle = '#3d2618'; c.fillRect(x0, y + 42, x1 - x0, 6); // shelf board + for (let x = x0 + 4; x < x1 - 6;) { // book spines + const bw = 6 + Math.floor(hash(x * 7 + y * 13) * 9), bh = 26 + Math.floor(hash(x * 3 + y) * 14); + c.fillStyle = ['#5a2a3a', '#2f3f6a', '#3a5a3a', '#6a5a2a', '#4a2f6a', '#6a3a2a'][Math.floor(hash(x + y * 5) * 6)]; c.fillRect(x, y + 42 - bh, bw, bh); + c.fillStyle = 'rgba(230,200,120,.35)'; c.fillRect(x, y + 42 - bh + 4, bw, 1.5); x += bw + 1; + } + } + c.fillStyle = 'rgba(0,0,0,.35)'; c.fillRect(CX - aisle / 2 - 10, 0, 10, T); c.fillRect(CX + aisle / 2, 0, 10, T); + for (let y = 60; y < T; y += 240) { c.fillStyle = '#3b2a1c'; c.fillRect(CX - 60, y, 120, 50); c.fillStyle = 'rgba(255,220,140,.25)'; c.beginPath(); c.arc(CX, y + 25, 46, 0, TAU); c.fill(); } + } else { // Scarlet Devil Mansion corridor: red carpet, checker floor, pillars and moonlit windows + c.fillStyle = '#170b10'; c.fillRect(0, 0, W, T); + for (let y = 0; y < T; y += 40) for (let x = 0; x < W; x += 40) { c.fillStyle = ((x + y) / 40) % 2 ? '#24121a' : '#1b0d13'; c.fillRect(x, y, 40, 40); } + for (let y = 0; y < T; y += 240) for (const s of [-1, 1]) { // moonlight falling through the windows + const x = CX + s * 330, gr = c.createLinearGradient(x, y, x + s * 60, y + 120); gr.addColorStop(0, 'rgba(170,190,255,.16)'); gr.addColorStop(1, 'rgba(170,190,255,0)'); + c.fillStyle = gr; c.beginPath(); c.moveTo(x - 40, y); c.lineTo(x + 40, y); c.lineTo(x + 40 + s * 80, y + 160); c.lineTo(x - 40 + s * 80, y + 160); c.closePath(); c.fill(); + } + const cw = 230; c.fillStyle = '#5c0f1c'; c.fillRect(CX - cw / 2, 0, cw, T); + c.fillStyle = '#7a1626'; c.fillRect(CX - cw / 2 + 14, 0, cw - 28, T); + c.fillStyle = '#c9a24a'; c.fillRect(CX - cw / 2 + 6, 0, 3, T); c.fillRect(CX + cw / 2 - 9, 0, 3, T); + c.strokeStyle = 'rgba(230,190,110,.35)'; c.lineWidth = 1.5; + for (let y = 0; y < T; y += 60) { c.beginPath(); c.moveTo(CX, y + 8); c.lineTo(CX + 26, y + 30); c.lineTo(CX, y + 52); c.lineTo(CX - 26, y + 30); c.closePath(); c.stroke(); } + for (let y = 40; y < T; y += 160) for (const s of [-1, 1]) { + const x = CX + s * 190, gr = c.createRadialGradient(x - 6, y - 6, 2, x, y, 26); gr.addColorStop(0, '#7b5a52'); gr.addColorStop(1, '#2a1517'); + c.fillStyle = 'rgba(0,0,0,.35)'; c.beginPath(); c.arc(x + 5, y + 6, 27, 0, TAU); c.fill(); + c.fillStyle = gr; c.beginPath(); c.arc(x, y, 24, 0, TAU); c.fill(); c.strokeStyle = 'rgba(220,180,120,.5)'; c.lineWidth = 2; c.beginPath(); c.arc(x, y, 24, 0, TAU); c.stroke(); + } + } + return (cache[key] = cv); + } + function spellTile(kind) { + const key = 'sp' + kind; if (cache[key]) return cache[key]; + const cv = canvas(W, H), c = cv.getContext('2d'), R = Math.hypot(CX, H / 2); + if (kind === 'rumia') { + const g = c.createRadialGradient(CX, H / 2, 10, CX, H / 2, R); g.addColorStop(0, '#3a0710'); g.addColorStop(0.55, '#12030a'); g.addColorStop(1, '#050106'); c.fillStyle = g; c.fillRect(0, 0, W, H); + c.translate(CX, H / 2); + for (let r = 40; r < R; r += 34) { c.strokeStyle = 'rgba(255,60,80,' + (0.22 - r / R * 0.16).toFixed(3) + ')'; c.lineWidth = 2; c.beginPath(); c.arc(0, 0, r, 0, TAU); c.stroke(); } + c.strokeStyle = 'rgba(255,90,110,.14)'; c.lineWidth = 1.5; + for (let i = 0; i < 32; i++) { const a = i * TAU / 32; c.beginPath(); c.moveTo(Math.cos(a) * 30, Math.sin(a) * 30); c.lineTo(Math.cos(a + 0.6) * R, Math.sin(a + 0.6) * R); c.stroke(); } + } else if (kind === 'cirno') { + const g = c.createRadialGradient(CX, H / 2, 10, CX, H / 2, R); g.addColorStop(0, '#24607f'); g.addColorStop(0.4, '#143958'); g.addColorStop(1, '#06162a'); c.fillStyle = g; c.fillRect(0, 0, W, H); + c.strokeStyle = 'rgba(170,225,255,.10)'; c.lineWidth = 1.5; + for (let y = -40; y < H + 40; y += 70) for (let x = -40; x < W + 40; x += 80) { + const ox = x + ((y / 70) % 2 ? 40 : 0); c.beginPath(); for (let i = 0; i <= 6; i++) { const a = i * TAU / 6; c.lineTo(ox + Math.cos(a) * 30, y + Math.sin(a) * 30); } c.stroke(); + } + } else if (kind === 'meiling') { // rainbow rays fanning from the centre over deep green, a taiji ring + const g = c.createRadialGradient(CX, H / 2, 10, CX, H / 2, R); g.addColorStop(0, '#1e5a35'); g.addColorStop(0.5, '#0f2e1d'); g.addColorStop(1, '#06140c'); c.fillStyle = g; c.fillRect(0, 0, W, H); + c.translate(CX, H / 2); + const RB = ['255,70,70', '255,160,60', '255,230,80', '90,220,110', '80,200,255', '90,110,255', '190,110,255']; + for (let i = 0; i < 28; i++) { const a = i * TAU / 28; c.fillStyle = `rgba(${RB[i % 7]},.07)`; c.beginPath(); c.moveTo(0, 0); c.lineTo(Math.cos(a - 0.07) * R, Math.sin(a - 0.07) * R); c.lineTo(Math.cos(a + 0.07) * R, Math.sin(a + 0.07) * R); c.closePath(); c.fill(); } + c.strokeStyle = 'rgba(170,255,190,.20)'; c.lineWidth = 2; c.beginPath(); c.arc(0, 0, 150, 0, TAU); c.stroke(); + c.fillStyle = 'rgba(170,255,190,.08)'; c.beginPath(); c.arc(0, 0, 150, -PI / 2, PI / 2); c.arc(0, 75, 75, PI / 2, -PI / 2, true); c.arc(0, -75, 75, PI / 2, -PI / 2); c.fill(); + } else if (kind === 'remilia') { // a blood-red full moon, thin clouds and a ring of bats' wings + const g = c.createRadialGradient(CX, H / 2, 10, CX, H / 2, R); g.addColorStop(0, '#5a0a1c'); g.addColorStop(0.55, '#230512'); g.addColorStop(1, '#090208'); c.fillStyle = g; c.fillRect(0, 0, W, H); + const m = c.createRadialGradient(CX, H / 2, 40, CX, H / 2, 170); m.addColorStop(0, 'rgba(255,70,80,.55)'); m.addColorStop(0.75, 'rgba(210,20,50,.35)'); m.addColorStop(1, 'rgba(210,20,50,0)'); c.fillStyle = m; c.beginPath(); c.arc(CX, H / 2, 170, 0, TAU); c.fill(); + c.translate(CX, H / 2); c.fillStyle = 'rgba(0,0,0,.34)'; + for (let i = 0; i < 12; i++) { const a = i * TAU / 12; c.save(); c.rotate(a); c.translate(205, 0); c.beginPath(); c.moveTo(-24, 0); c.quadraticCurveTo(-12, -14, 0, -3); c.quadraticCurveTo(12, -14, 24, 0); c.quadraticCurveTo(10, -2, 0, 7); c.quadraticCurveTo(-10, -2, -24, 0); c.fill(); c.restore(); } + } else if (kind === 'patchouli') { // seven-element magic circle (fire, water, wood, metal, earth, sun, moon) on violet + const g = c.createRadialGradient(CX, H / 2, 10, CX, H / 2, R); g.addColorStop(0, '#3a2160'); g.addColorStop(0.5, '#1a0f33'); g.addColorStop(1, '#08051a'); c.fillStyle = g; c.fillRect(0, 0, W, H); + c.translate(CX, H / 2); c.strokeStyle = 'rgba(220,190,255,.22)'; c.lineWidth = 2; + for (const r of [200, 186, 120]) { c.beginPath(); c.arc(0, 0, r, 0, TAU); c.stroke(); } + c.beginPath(); for (let i = 0; i <= 7; i++) { const a = -PI / 2 + i * TAU * 3 / 7; c.lineTo(Math.cos(a) * 186, Math.sin(a) * 186); } c.stroke(); // heptagram + const EL = ['Fire', 'Water', 'Wood', 'Metal', 'Earth', 'Sun', 'Moon'], ECOL = ['255,110,90', '110,170,255', '110,220,120', '230,230,240', '220,180,90', '255,220,90', '200,200,255']; + c.font = '22px ' + SERIF; c.textAlign = 'center'; c.textBaseline = 'middle'; + for (let i = 0; i < 7; i++) { const a = -PI / 2 + i * TAU / 7; c.fillStyle = 'rgba(' + ECOL[i] + ',.40)'; c.beginPath(); c.arc(Math.cos(a) * 186, Math.sin(a) * 186, 18, 0, TAU); c.fill(); c.fillStyle = 'rgba(255,255,255,.55)'; c.fillText(EL[i], Math.cos(a) * 186, Math.sin(a) * 186); } + } else { // Sakuya: indigo night and a great clock face with gears + const g = c.createRadialGradient(CX, H / 2, 10, CX, H / 2, R); g.addColorStop(0, '#2b2a6a'); g.addColorStop(0.5, '#141537'); g.addColorStop(1, '#07061a'); c.fillStyle = g; c.fillRect(0, 0, W, H); + const gear = (x, y, r, n) => { + c.save(); c.translate(x, y); c.strokeStyle = 'rgba(200,190,255,.14)'; c.lineWidth = 3; c.beginPath(); + for (let i = 0; i < n * 2; i++) { const a = i * PI / n, rr = i % 2 ? r : r + 9; c.lineTo(Math.cos(a) * rr, Math.sin(a) * rr); } c.closePath(); c.stroke(); + c.beginPath(); c.arc(0, 0, r * 0.45, 0, TAU); c.stroke(); c.restore(); + }; + gear(90, 70, 60, 14); gear(W - 110, 400, 80, 18); gear(W - 70, 60, 36, 10); gear(120, 420, 44, 12); + c.translate(CX, H / 2); + c.strokeStyle = 'rgba(210,205,255,.28)'; c.lineWidth = 3; c.beginPath(); c.arc(0, 0, 214, 0, TAU); c.stroke(); + c.lineWidth = 1; c.beginPath(); c.arc(0, 0, 200, 0, TAU); c.stroke(); c.beginPath(); c.arc(0, 0, 150, 0, TAU); c.stroke(); + for (let i = 0; i < 60; i++) { const a = i * TAU / 60, r0 = i % 5 ? 192 : 182; c.lineWidth = i % 5 ? 1 : 3; c.beginPath(); c.moveTo(Math.cos(a) * r0, Math.sin(a) * r0); c.lineTo(Math.cos(a) * 200, Math.sin(a) * 200); c.stroke(); } + const NUM = ['XII', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X', 'XI']; + c.fillStyle = 'rgba(220,214,255,.30)'; c.font = '22px ' + SERIF; c.textAlign = 'center'; c.textBaseline = 'middle'; + for (let i = 0; i < 12; i++) { const a = -PI / 2 + i * TAU / 12; c.fillText(NUM[i], Math.cos(a) * 166, Math.sin(a) * 166); } + } + return (cache[key] = cv); + } + + // ---------- characters ---------- + function reimu(c, x, y, lean, t) { + c.save(); c.translate(x, y); c.rotate(lean * 0.12); + c.fillStyle = 'rgba(0,0,0,.25)'; c.beginPath(); c.ellipse(0, 18, 11, 3, 0, 0, TAU); c.fill(); + c.fillStyle = '#c81f35'; c.beginPath(); c.moveTo(-7, 2); c.lineTo(-11, 17); c.lineTo(11, 17); c.lineTo(7, 2); c.closePath(); c.fill(); // skirt + c.fillStyle = '#e8e2e6'; c.fillRect(-3, 12, 6, 5); + c.fillStyle = '#d7263d'; c.fillRect(-6, -4, 12, 8); // vest + c.fillStyle = '#ffd34a'; c.fillRect(-2, -3, 4, 3); // ascot + const sw = Math.sin(t * 0.2) * 1.2; + c.fillStyle = '#f4f2f6'; c.beginPath(); c.moveTo(-6, -3); c.lineTo(-15, 6 + sw); c.lineTo(-10, 10 + sw); c.lineTo(-5, 3); c.fill(); + c.beginPath(); c.moveTo(6, -3); c.lineTo(15, 6 - sw); c.lineTo(10, 10 - sw); c.lineTo(5, 3); c.fill(); // detached sleeves + c.fillStyle = '#2a1b1f'; c.beginPath(); c.arc(0, -10, 7, 0, TAU); c.fill(); c.fillRect(-7, -10, 3, 10); c.fillRect(4, -10, 3, 10); // hair + c.fillStyle = '#f6d9c8'; c.beginPath(); c.arc(0, -9, 4.6, 0, PI); c.fill(); + c.fillStyle = '#e0283f'; c.beginPath(); c.moveTo(0, -17); c.lineTo(-11, -23); c.lineTo(-9, -13); c.closePath(); c.fill(); c.beginPath(); c.moveTo(0, -17); c.lineTo(11, -23); c.lineTo(9, -13); c.closePath(); c.fill(); // bow + c.fillStyle = '#fff'; c.fillRect(-8, -21, 2, 5); c.fillRect(6, -21, 2, 5); + c.restore(); + } + function yinyang(c, x, y, a, blue) { + c.save(); c.translate(x, y); c.rotate(a); + c.fillStyle = blue ? 'rgba(150,140,255,.28)' : 'rgba(255,120,150,.25)'; c.beginPath(); c.arc(0, 0, 8.5, 0, TAU); c.fill(); + c.fillStyle = '#f8f4f4'; c.beginPath(); c.arc(0, 0, 6, 0, TAU); c.fill(); + c.fillStyle = blue ? '#5a4fd0' : '#c81f35'; c.beginPath(); c.arc(0, 0, 6, -PI / 2, PI / 2); c.arc(0, 3, 3, PI / 2, -PI / 2, true); c.arc(0, -3, 3, PI / 2, -PI / 2); c.fill(); + c.fillStyle = '#f8f4f4'; c.beginPath(); c.arc(0, 3, 1.2, 0, TAU); c.fill(); c.fillStyle = blue ? '#5a4fd0' : '#c81f35'; c.beginPath(); c.arc(0, -3, 1.2, 0, TAU); c.fill(); + c.restore(); + } + function rumia(c, x, y, t) { + c.save(); c.translate(x, y + Math.sin(t * 0.05) * 2); + c.fillStyle = '#16131c'; c.beginPath(); c.moveTo(-8, 0); c.lineTo(-13, 22); c.lineTo(13, 22); c.lineTo(8, 0); c.closePath(); c.fill(); // black skirt + c.fillStyle = '#f0ece6'; c.fillRect(-6, -6, 12, 9); + c.fillStyle = '#1b1820'; c.beginPath(); c.moveTo(-7, -6); c.lineTo(-3, 4); c.lineTo(-7, 4); c.closePath(); c.fill(); c.beginPath(); c.moveTo(7, -6); c.lineTo(3, 4); c.lineTo(7, 4); c.closePath(); c.fill(); + c.fillStyle = '#c4253a'; c.beginPath(); c.moveTo(0, -5); c.lineTo(-3, 1); c.lineTo(3, 1); c.closePath(); c.fill(); // necktie + c.strokeStyle = '#f0ece6'; c.lineWidth = 4; c.lineCap = 'round'; c.beginPath(); c.moveTo(-6, -4); c.lineTo(-22, -7); c.moveTo(6, -4); c.lineTo(22, -7); c.stroke(); // outstretched arms + c.fillStyle = '#f6d9c8'; c.beginPath(); c.arc(-23, -7, 2.2, 0, TAU); c.arc(23, -7, 2.2, 0, TAU); c.fill(); + c.fillStyle = '#f2d15a'; c.beginPath(); c.arc(0, -15, 8.5, 0, TAU); c.fill(); c.fillRect(-9, -15, 18, 7); // blonde bob + c.fillStyle = '#f6d9c8'; c.beginPath(); c.arc(0, -13, 5.2, 0, PI); c.fill(); + c.fillStyle = '#c0182c'; c.fillRect(-11, -22, 6, 5); // red hair ribbon (ofuda) + c.fillStyle = '#d42a3c'; c.fillRect(-3, -12, 2, 2); c.fillRect(1, -12, 2, 2); + c.restore(); + } + function cirno(c, x, y, t) { + c.save(); c.translate(x, y + Math.sin(t * 0.06) * 2); + for (const s of [-1, 1]) for (let j = 0; j < 3; j++) { // six ice wings + c.save(); c.translate(s * 7, -4 + j * 7); c.rotate(s * (-0.6 + j * 0.5)); const g = c.createLinearGradient(0, 0, s * 18, 0); + g.addColorStop(0, 'rgba(210,245,255,.95)'); g.addColorStop(1, 'rgba(120,200,255,.55)'); c.fillStyle = g; + c.beginPath(); c.moveTo(0, 0); c.lineTo(s * 9, -4); c.lineTo(s * 19, 0); c.lineTo(s * 9, 4); c.closePath(); c.fill(); c.restore(); + } + c.fillStyle = '#2f6fd8'; c.beginPath(); c.moveTo(-8, -1); c.lineTo(-13, 21); c.lineTo(13, 21); c.lineTo(8, -1); c.closePath(); c.fill(); // blue dress + c.fillStyle = '#f2f6ff'; c.fillRect(-6, -7, 12, 7); + c.fillStyle = '#e0283f'; c.fillRect(-3, -6, 6, 3); + c.fillStyle = '#7cc6ff'; c.beginPath(); c.arc(0, -15, 8.5, 0, TAU); c.fill(); c.fillRect(-9, -15, 18, 8); // blue hair + c.fillStyle = '#f6d9c8'; c.beginPath(); c.arc(0, -13, 5.2, 0, PI); c.fill(); + c.fillStyle = '#3a7fe8'; c.beginPath(); c.moveTo(0, -23); c.lineTo(-10, -30); c.lineTo(-9, -20); c.closePath(); c.fill(); c.beginPath(); c.moveTo(0, -23); c.lineTo(10, -30); c.lineTo(9, -20); c.closePath(); c.fill(); // big bow + c.fillStyle = '#244a9a'; c.fillRect(-3, -12, 2, 2); c.fillRect(1, -12, 2, 2); + c.restore(); + } + function sakuya(c, x, y, t) { + c.save(); c.translate(x, y + Math.sin(t * 0.05) * 1.6); + c.fillStyle = '#25317f'; c.beginPath(); c.moveTo(-8, 0); c.lineTo(-14, 22); c.lineTo(14, 22); c.lineTo(8, 0); c.closePath(); c.fill(); // navy dress + c.fillStyle = '#f2f3fb'; c.beginPath(); c.moveTo(-5, 1); c.lineTo(-8, 20); c.lineTo(8, 20); c.lineTo(5, 1); c.closePath(); c.fill(); // apron + c.fillStyle = '#2d3a96'; c.fillRect(-6, -7, 12, 9); + c.fillStyle = '#f2f3fb'; c.beginPath(); c.moveTo(-6, -7); c.lineTo(0, -2); c.lineTo(6, -7); c.closePath(); c.fill(); + c.fillStyle = '#3fb06a'; c.fillRect(-2, -5, 4, 3); // green bow + c.strokeStyle = '#2d3a96'; c.lineWidth = 3.5; c.lineCap = 'round'; c.beginPath(); c.moveTo(-6, -4); c.lineTo(-16, 3); c.moveTo(6, -4); c.lineTo(16, 3); c.stroke(); + for (const s of [-1, 1]) { // a knife fanned in each hand + c.save(); c.translate(s * 17, 4); c.rotate(s * 0.9 - PI / 2 * s); + for (let i = -1; i <= 1; i++) { c.save(); c.rotate(i * 0.25); c.fillStyle = '#e8ecff'; c.beginPath(); c.moveTo(0, -12); c.lineTo(-1.6, 0); c.lineTo(1.6, 0); c.closePath(); c.fill(); c.restore(); } + c.restore(); + } + const hg = c.createLinearGradient(0, -26, 0, -6); hg.addColorStop(0, '#ffffff'); hg.addColorStop(1, '#a9b2cc'); c.fillStyle = hg; + c.beginPath(); c.arc(0, -15, 8.6, 0, TAU); c.fill(); c.fillRect(-9, -15, 18, 7); // silver hair + c.fillRect(-10, -12, 3, 11); c.fillRect(7, -12, 3, 11); // braids + c.fillStyle = '#3fb06a'; c.fillRect(-10, -2, 3, 3); c.fillRect(7, -2, 3, 3); + c.fillStyle = '#f6d9c8'; c.beginPath(); c.arc(0, -13, 5.2, 0, PI); c.fill(); + c.fillStyle = '#ffffff'; c.beginPath(); c.moveTo(-8, -21); c.quadraticCurveTo(0, -27, 8, -21); c.lineTo(7, -19); c.quadraticCurveTo(0, -24, -7, -19); c.closePath(); c.fill(); // maid headdress + c.fillStyle = '#2f55c8'; c.fillRect(-3, -12, 2, 2); c.fillRect(1, -12, 2, 2); + c.restore(); + } + function meiling(c, x, y, t) { + c.save(); c.translate(x, y + Math.sin(t * 0.05) * 1.8); + c.fillStyle = '#2f9a52'; c.beginPath(); c.moveTo(-8, -1); c.lineTo(-13, 22); c.lineTo(-2, 22); c.lineTo(0, 8); c.lineTo(2, 22); c.lineTo(13, 22); c.lineTo(8, -1); c.closePath(); c.fill(); // green dress with side slits + c.fillStyle = '#f4f2ea'; c.fillRect(-3, 8, 6, 14); // white trousers in the slit + c.fillStyle = '#38ad5e'; c.fillRect(-7, -7, 14, 9); + c.fillStyle = '#f0d36a'; c.fillRect(-1, -7, 2, 9); // frog buttons + c.strokeStyle = '#38ad5e'; c.lineWidth = 3.5; c.lineCap = 'round'; c.beginPath(); c.moveTo(-6, -4); c.lineTo(-15, -12); c.moveTo(6, -4); c.lineTo(16, 2); c.stroke(); // martial-arts stance + c.fillStyle = '#f6d9c8'; c.beginPath(); c.arc(-16, -13, 2.4, 0, TAU); c.arc(17, 3, 2.4, 0, TAU); c.fill(); + const hg = c.createLinearGradient(0, -26, 0, 8); hg.addColorStop(0, '#ff5a4a'); hg.addColorStop(1, '#c22a2a'); c.fillStyle = hg; + c.beginPath(); c.arc(0, -15, 8.6, 0, TAU); c.fill(); c.fillRect(-9, -15, 18, 8); c.fillRect(-10, -12, 4, 20); c.fillRect(6, -12, 4, 20); // long red hair + c.fillStyle = '#2a7a45'; c.beginPath(); c.moveTo(-9, -20); c.lineTo(9, -20); c.lineTo(6, -27); c.lineTo(-6, -27); c.closePath(); c.fill(); // beret + c.fillStyle = '#f0d36a'; c.beginPath(); c.arc(0, -25, 2.2, 0, TAU); c.fill(); // star badge + c.fillStyle = '#f6d9c8'; c.beginPath(); c.arc(0, -13, 5.2, 0, PI); c.fill(); + c.fillStyle = '#2f7a4a'; c.fillRect(-3, -12, 2, 2); c.fillRect(1, -12, 2, 2); + c.restore(); + } + function patchouli(c, x, y, t) { + c.save(); c.translate(x, y + Math.sin(t * 0.04) * 1.5); + c.fillStyle = '#c9a4e0'; c.beginPath(); c.moveTo(-9, -2); c.lineTo(-14, 22); c.lineTo(14, 22); c.lineTo(9, -2); c.closePath(); c.fill(); // striped pale-purple gown + c.strokeStyle = 'rgba(120,80,160,.6)'; c.lineWidth = 1; for (let i = -2; i <= 2; i++) { c.beginPath(); c.moveTo(i * 3, 0); c.lineTo(i * 5, 22); c.stroke(); } + c.fillStyle = '#d9bdf0'; c.fillRect(-7, -7, 14, 8); + c.fillStyle = '#7a4a2a'; c.fillRect(6, -2, 10, 12); c.fillStyle = '#e8d6a0'; c.fillRect(7, -1, 8, 10); // the book she holds + c.fillStyle = '#f6d9c8'; c.beginPath(); c.arc(-8, 2, 2.2, 0, TAU); c.fill(); + const hg = c.createLinearGradient(0, -26, 0, 12); hg.addColorStop(0, '#b07ad8'); hg.addColorStop(1, '#6e3ea0'); c.fillStyle = hg; + c.beginPath(); c.arc(0, -15, 8.8, 0, TAU); c.fill(); c.fillRect(-10, -15, 20, 8); c.fillRect(-11, -12, 4, 22); c.fillRect(7, -12, 4, 22); // long purple hair + c.fillStyle = '#f2e6f6'; c.beginPath(); c.moveTo(-11, -19); c.quadraticCurveTo(0, -34, 11, -19); c.quadraticCurveTo(0, -23, -11, -19); c.fill(); // mob cap + c.fillStyle = '#f0d36a'; c.beginPath(); c.moveTo(4, -27); c.lineTo(8, -23); c.lineTo(4, -21); c.lineTo(0, -23); c.closePath(); c.fill(); // crescent pin + c.fillStyle = '#f6d9c8'; c.beginPath(); c.arc(0, -13, 5.2, 0, PI); c.fill(); + c.fillStyle = '#7a3ea8'; c.fillRect(-3, -12, 2, 2); c.fillRect(1, -12, 2, 2); + c.restore(); + } + function remilia(c, x, y, t) { + c.save(); c.translate(x, y + Math.sin(t * 0.05) * 1.5); + const fl = Math.sin(t * 0.2) * 0.12; + c.fillStyle = '#2a1830'; for (const sd of [-1, 1]) { c.save(); c.scale(sd, 1); c.rotate(fl); c.beginPath(); c.moveTo(4, -6); c.quadraticCurveTo(16, -22, 32, -14); c.quadraticCurveTo(26, -8, 27, -1); c.quadraticCurveTo(20, -5, 18, 2); c.quadraticCurveTo(12, -3, 5, 3); c.closePath(); c.fill(); c.restore(); } // bat wings + c.fillStyle = '#f4e6f0'; c.beginPath(); c.moveTo(-7, -2); c.lineTo(-13, 20); c.lineTo(13, 20); c.lineTo(7, -2); c.closePath(); c.fill(); // pale pink dress + c.fillStyle = '#d0304a'; c.fillRect(-13, 16, 26, 3); c.fillRect(-2, -3, 4, 6); + c.fillStyle = '#f4e6f0'; c.fillRect(-7, -7, 14, 8); + const hg = c.createLinearGradient(0, -24, 0, -6); hg.addColorStop(0, '#a8b4e8'); hg.addColorStop(1, '#6c78c0'); c.fillStyle = hg; + c.beginPath(); c.arc(0, -15, 8.2, 0, TAU); c.fill(); c.fillRect(-9, -15, 18, 7); // short lavender hair + c.fillStyle = '#f7ecf2'; c.beginPath(); c.ellipse(0, -22, 11, 6.5, 0, 0, TAU); c.fill(); c.fillStyle = '#d0304a'; c.fillRect(-10, -20, 20, 2); // mob cap with a red band + c.fillStyle = '#f6d9c8'; c.beginPath(); c.arc(0, -13, 5.2, 0, PI); c.fill(); + c.fillStyle = '#c8102e'; c.fillRect(-3, -12, 2, 2); c.fillRect(1, -12, 2, 2); + c.restore(); + } + // Ordinary enemy (fairy): small body with translucent wings; fades in, flickers when hit. + function fairy(c, f, t) { + const col = f.c === M.C.CYAN ? '120,230,255' : '110,140,255'; + c.save(); c.translate(f.x, f.y); + const fl = Math.sin(t * 0.5 + f.fire) * 0.3; + c.fillStyle = `rgba(${col},.45)`; for (const s of [-1, 1]) { c.beginPath(); c.ellipse(s * 7, -3, 7, 4 + fl * 4, s * 0.5, 0, TAU); c.fill(); } + c.fillStyle = '#2f5fc8'; c.beginPath(); c.moveTo(-4, -1); c.lineTo(-6, 9); c.lineTo(6, 9); c.lineTo(4, -1); c.closePath(); c.fill(); + c.fillStyle = '#f6e7a0'; c.beginPath(); c.arc(0, -5, 4.2, 0, TAU); c.fill(); + c.fillStyle = '#f6d9c8'; c.beginPath(); c.arc(0, -4, 2.6, 0, PI); c.fill(); + c.restore(); + } + // Spell cut-in bust: drawn once per boss into a cached 220x260 canvas. + function bustTile(kind) { + const key = 'bust' + kind; if (cache[key]) return cache[key]; + const cv = canvas(220, 260), c = cv.getContext('2d'), R = kind === 'rumia', S = kind === 'sakuya', Mei = kind === 'meiling', Pa = kind === 'patchouli', Re = kind === 'remilia'; + const hair = R ? ['#fff3b0', '#f2cf55', '#c99a2a'] : S ? ['#ffffff', '#d5dbea', '#8f99b8'] : Mei ? ['#ff8a70', '#e23a32', '#9a1c22'] : Pa ? ['#d6b0f0', '#9a62c8', '#5e2e8a'] : Re ? ['#c4ccf2', '#8a96d8', '#525ea8'] : ['#d6f0ff', '#7cc6ff', '#3d82d6'], eye = R ? '#c8102e' : S ? '#3352c8' : Mei ? '#2f8a50' : Pa ? '#8a3ac8' : '#2d6fe0'; + c.translate(110, 0); + if (R) { const a = c.createRadialGradient(0, 120, 20, 0, 120, 130); a.addColorStop(0, 'rgba(20,0,20,.75)'); a.addColorStop(1, 'rgba(20,0,20,0)'); c.fillStyle = a; c.fillRect(-110, 0, 220, 260); } + else if (Re) { // a blood moon and spread bat wings behind her + const gl = c.createRadialGradient(0, 110, 30, 0, 110, 120); gl.addColorStop(0, 'rgba(255,60,70,.75)'); gl.addColorStop(1, 'rgba(255,60,70,0)'); c.fillStyle = gl; c.fillRect(-110, 0, 220, 240); + c.fillStyle = '#231228'; for (const sd of [-1, 1]) { c.save(); c.scale(sd, 1); c.beginPath(); c.moveTo(26, 170); c.quadraticCurveTo(60, 70, 108, 96); c.quadraticCurveTo(94, 116, 98, 142); c.quadraticCurveTo(80, 128, 72, 156); c.quadraticCurveTo(58, 142, 46, 186); c.closePath(); c.fill(); c.restore(); } + } else if (Pa) { // an open grimoire glowing behind her + const gl = c.createRadialGradient(0, 200, 10, 0, 200, 120); gl.addColorStop(0, 'rgba(220,180,255,.7)'); gl.addColorStop(1, 'rgba(220,180,255,0)'); c.fillStyle = gl; c.fillRect(-110, 80, 220, 180); + c.fillStyle = 'rgba(240,225,190,.9)'; c.beginPath(); c.moveTo(-90, 230); c.lineTo(0, 210); c.lineTo(90, 230); c.lineTo(90, 250); c.lineTo(0, 232); c.lineTo(-90, 250); c.closePath(); c.fill(); + } else if (Mei) { // rainbow rays behind her + const RB = ['255,70,70', '255,160,60', '255,230,80', '90,220,110', '80,200,255', '90,110,255', '190,110,255']; + for (let i = 0; i < 7; i++) { c.save(); c.translate(0, 200); c.rotate(-1.05 + i * 0.35); c.fillStyle = `rgba(${RB[i]},.55)`; c.beginPath(); c.moveTo(-5, 0); c.lineTo(-16, -190); c.lineTo(16, -190); c.lineTo(5, 0); c.closePath(); c.fill(); c.restore(); } + } else if (S) { // knives fanned behind her + for (let i = 0; i < 9; i++) { + c.save(); c.translate(0, 190); c.rotate(-1.2 + i * 0.3); c.fillStyle = 'rgba(225,232,255,.85)'; + c.beginPath(); c.moveTo(0, -150); c.lineTo(-6, -96); c.lineTo(6, -96); c.closePath(); c.fill(); c.fillStyle = 'rgba(80,110,220,.8)'; c.fillRect(-7, -96, 14, 5); c.restore(); + } + } else for (const s of [-1, 1]) for (let j = 0; j < 3; j++) { // ice wings behind + c.save(); c.translate(s * 34, 130 + j * 26); c.rotate(s * (-0.5 + j * 0.42)); const g = c.createLinearGradient(0, 0, s * 70, 0); + g.addColorStop(0, 'rgba(225,248,255,.95)'); g.addColorStop(1, 'rgba(120,200,255,.35)'); c.fillStyle = g; + c.beginPath(); c.moveTo(0, 0); c.lineTo(s * 34, -13); c.lineTo(s * 74, 0); c.lineTo(s * 34, 13); c.closePath(); c.fill(); c.restore(); + } + // shoulders and clothes + c.fillStyle = R ? '#16131c' : S ? '#26338a' : Mei ? '#2f9a52' : Pa ? '#c9a4e0' : Re ? '#f2e2ec' : '#2f6fd8'; c.beginPath(); c.moveTo(-78, 260); c.bezierCurveTo(-74, 196, -46, 172, 0, 170); c.bezierCurveTo(46, 172, 74, 196, 78, 260); c.closePath(); c.fill(); + c.fillStyle = '#f4f2f6'; c.beginPath(); c.moveTo(-30, 176); c.lineTo(0, 236); c.lineTo(30, 176); c.closePath(); c.fill(); + c.fillStyle = R ? '#c4253a' : S ? '#3fb06a' : Mei ? '#f0d36a' : Pa ? '#e0507a' : Re ? '#c8102e' : '#e0283f'; c.beginPath(); c.moveTo(-10, 182); c.lineTo(0, 214); c.lineTo(10, 182); c.closePath(); c.fill(); + // neck and face + c.fillStyle = '#f2d0bd'; c.fillRect(-11, 146, 22, 30); + const fg = c.createRadialGradient(-10, 104, 8, 0, 112, 52); fg.addColorStop(0, '#fff1e6'); fg.addColorStop(1, '#f0c9b2'); c.fillStyle = fg; + c.beginPath(); c.ellipse(0, 112, 40, 46, 0, 0, TAU); c.fill(); + // hair: back volume, bangs, side locks + const hg = c.createLinearGradient(0, 40, 0, 170); hg.addColorStop(0, hair[0]); hg.addColorStop(0.45, hair[1]); hg.addColorStop(1, hair[2]); c.fillStyle = hg; + c.beginPath(); c.moveTo(-52, 150); c.bezierCurveTo(-64, 80, -40, 44, 0, 42); c.bezierCurveTo(40, 44, 64, 80, 52, 150); c.bezierCurveTo(44, 120, 40, 100, 34, 92); + c.lineTo(22, 104); c.lineTo(14, 88); c.lineTo(2, 104); c.lineTo(-8, 88); c.lineTo(-20, 104); c.lineTo(-30, 90); c.bezierCurveTo(-40, 104, -44, 124, -52, 150); c.closePath(); c.fill(); + if (S) { // braids with green ribbons, maid headdress + for (const s of [-1, 1]) { + c.fillStyle = hg; c.beginPath(); c.ellipse(s * 46, 160, 9, 34, s * 0.12, 0, TAU); c.fill(); + c.strokeStyle = 'rgba(120,130,170,.6)'; c.lineWidth = 1.2; for (let k = 0; k < 4; k++) { c.beginPath(); c.arc(s * 46, 136 + k * 14, 8, 0.2 * PI, 0.8 * PI); c.stroke(); } + c.fillStyle = '#3fb06a'; c.beginPath(); c.moveTo(s * 46, 190); c.lineTo(s * 34, 200); c.lineTo(s * 36, 186); c.closePath(); c.fill(); c.beginPath(); c.moveTo(s * 46, 190); c.lineTo(s * 58, 200); c.lineTo(s * 56, 186); c.closePath(); c.fill(); + } + c.fillStyle = '#ffffff'; c.beginPath(); c.moveTo(-46, 58); c.quadraticCurveTo(0, 22, 46, 58); c.lineTo(40, 66); c.quadraticCurveTo(0, 36, -40, 66); c.closePath(); c.fill(); + c.strokeStyle = 'rgba(160,170,210,.7)'; c.lineWidth = 1; for (let k = -4; k <= 4; k++) { c.beginPath(); c.arc(k * 10, 44 + Math.abs(k) * 2.4, 4, PI, TAU); c.stroke(); } + } + // eyes + for (const s of [-1, 1]) { + c.fillStyle = '#ffffff'; c.beginPath(); c.ellipse(s * 16, 120, 9, 11, 0, 0, TAU); c.fill(); + const eg = c.createLinearGradient(0, 110, 0, 132); eg.addColorStop(0, '#1a0f14'); eg.addColorStop(0.35, eye); eg.addColorStop(1, '#ffd8e0'); c.fillStyle = eg; + c.beginPath(); c.ellipse(s * 16, 121, 6.5, 9, 0, 0, TAU); c.fill(); + c.fillStyle = '#fff'; c.beginPath(); c.arc(s * 16 - 2, 116, 2.4, 0, TAU); c.fill(); + c.strokeStyle = '#3a2228'; c.lineWidth = 2.2; c.beginPath(); c.arc(s * 16, 120, 10, PI * 1.15, PI * 1.85); c.stroke(); + } + c.strokeStyle = '#b06a6a'; c.lineWidth = 1.6; c.beginPath(); c.arc(0, 140, 6, 0.2 * PI, 0.8 * PI); c.stroke(); + c.fillStyle = 'rgba(255,120,140,.25)'; c.beginPath(); c.ellipse(-24, 136, 7, 4, 0, 0, TAU); c.ellipse(24, 136, 7, 4, 0, 0, TAU); c.fill(); + if (R) { c.fillStyle = '#c0182c'; c.beginPath(); c.moveTo(34, 64); c.lineTo(56, 52); c.lineTo(58, 78); c.closePath(); c.fill(); c.fillStyle = '#fff'; c.fillRect(44, 60, 3, 10); } + else if (Mei) { // long side locks with braids, green beret with a gold star + for (const s2 of [-1, 1]) { c.fillStyle = hg; c.beginPath(); c.ellipse(s2 * 50, 180, 10, 56, s2 * 0.08, 0, TAU); c.fill(); c.fillStyle = '#2f9a52'; c.fillRect(s2 * 50 - 6, 222, 12, 6); } + c.fillStyle = '#2a7a45'; c.beginPath(); c.moveTo(-50, 62); c.quadraticCurveTo(0, 6, 50, 62); c.quadraticCurveTo(0, 46, -50, 62); c.fill(); + star(c, 0, 40, 11, 4.6, '#f0d36a'); + } else if (Re) { // mob cap with a red band, two small fangs + c.fillStyle = '#f7ecf2'; c.beginPath(); c.moveTo(-58, 64); c.quadraticCurveTo(0, -6, 58, 64); c.quadraticCurveTo(0, 42, -58, 64); c.fill(); + c.strokeStyle = '#c8102e'; c.lineWidth = 5; c.beginPath(); c.moveTo(-50, 58); c.quadraticCurveTo(0, 32, 50, 58); c.stroke(); + c.fillStyle = '#ffffff'; for (const s2 of [-4, 4]) { c.beginPath(); c.moveTo(s2 - 2, 142); c.lineTo(s2, 149); c.lineTo(s2 + 2, 142); c.closePath(); c.fill(); } + } else if (Pa) { // long locks with red / blue ribbons, mob cap with a crescent + for (const s2 of [-1, 1]) { c.fillStyle = hg; c.beginPath(); c.ellipse(s2 * 50, 184, 10, 60, s2 * 0.06, 0, TAU); c.fill(); c.fillStyle = s2 < 0 ? '#e0507a' : '#5a7ae0'; c.fillRect(s2 * 50 - 6, 224, 12, 6); } + c.fillStyle = '#f2e6f6'; c.beginPath(); c.moveTo(-58, 66); c.quadraticCurveTo(0, -4, 58, 66); c.quadraticCurveTo(0, 44, -58, 66); c.fill(); + c.fillStyle = '#f0d36a'; c.beginPath(); c.arc(22, 30, 9, 0.4 * PI, 1.6 * PI); c.arc(26, 30, 7, 1.6 * PI, 0.4 * PI, true); c.fill(); + } else if (!S) { // big ribbon + c.fillStyle = '#3a7fe8'; for (const s of [-1, 1]) { c.beginPath(); c.moveTo(0, 46); c.bezierCurveTo(s * 20, 20, s * 54, 18, s * 50, 46); c.bezierCurveTo(s * 46, 60, s * 18, 58, 0, 46); c.fill(); } + c.fillStyle = '#2a5fc0'; c.beginPath(); c.arc(0, 46, 7, 0, TAU); c.fill(); + } + return (cache[key] = cv); + } + function portrait(c, kind, x, y, alpha) { c.save(); c.globalAlpha = alpha; c.drawImage(bustTile(kind), x - 110, y - 150); c.restore(); } + + // ---------- scene ---------- + function drawBackground(c, g) { + const tile = stageTile(g.kind), off = (g.t * (g.kind === 'rumia' ? 0.7 : g.kind === 'cirno' || g.kind === 'meiling' ? 0.9 : g.kind === 'patchouli' ? 0.5 : g.kind === 'remilia' ? 0.4 : 0.6)) % TILE_H; + c.drawImage(tile, 0, off - TILE_H); c.drawImage(tile, 0, off); + if (g.kind === 'cirno') { // drifting fog + for (let i = 0; i < 7; i++) { + const x = ((hash(i * 9) * W + g.t * (0.25 + i * 0.07)) % (W + 260)) - 130, y = 50 + i * 64 + Math.sin(g.t * 0.01 + i) * 20; + const fg = c.createRadialGradient(x, y, 10, x, y, 140); fg.addColorStop(0, 'rgba(225,245,255,.18)'); fg.addColorStop(1, 'rgba(225,245,255,0)'); c.fillStyle = fg; c.fillRect(x - 140, y - 140, 280, 280); + } + } else if (g.kind === 'rumia') { + const v = c.createRadialGradient(CX, H / 2, 160, CX, H / 2, 520); v.addColorStop(0, 'rgba(0,0,0,0)'); v.addColorStop(1, 'rgba(4,2,12,.6)'); c.fillStyle = v; c.fillRect(0, 0, W, H); + for (let i = 0; i < 22; i++) { const x = hash(i * 41) * W, y = (hash(i * 43) * H + g.t * 0.4 * (1 + i % 3)) % H, a = 0.3 + 0.3 * Math.sin(g.t * 0.07 + i); c.fillStyle = 'rgba(200,255,170,' + a.toFixed(2) + ')'; c.fillRect(x, y, 2, 2); } + } else { + const v = c.createRadialGradient(CX, H / 2, 180, CX, H / 2, 560); v.addColorStop(0, 'rgba(0,0,0,0)'); v.addColorStop(1, 'rgba(8,0,6,.55)'); c.fillStyle = v; c.fillRect(0, 0, W, H); + } + if (g.spell && g.phaseId) { + const a = Math.min(1, g.phaseT / 50), th = THEME[g.kind].acc; + c.save(); c.globalAlpha = a * 0.9; c.drawImage(spellTile(g.kind), 0, 0); c.restore(); + c.save(); c.globalAlpha = a; c.translate(CX, H / 2); + if (g.kind === 'sakuya') { // clock hands follow the spell clock, which stands still while time is stopped + const sec = g.clock / 60; + c.strokeStyle = `rgba(${th},.55)`; c.lineCap = 'round'; + c.lineWidth = 6; c.beginPath(); c.moveTo(0, 0); const ah = -PI / 2 + sec * TAU / 120; c.lineTo(Math.cos(ah) * 110, Math.sin(ah) * 110); c.stroke(); + c.lineWidth = 3; c.beginPath(); c.moveTo(0, 0); const am = -PI / 2 + sec * TAU / 10; c.lineTo(Math.cos(am) * 170, Math.sin(am) * 170); c.stroke(); + c.fillStyle = `rgba(${th},.7)`; c.beginPath(); c.arc(0, 0, 8, 0, TAU); c.fill(); + } else { + c.rotate(g.phaseT * (g.kind === 'rumia' ? 0.004 : -0.003)); c.strokeStyle = `rgba(${th},.16)`; c.lineWidth = 2; + const n = g.kind === 'rumia' ? 8 : 6; + for (let i = 0; i < n; i++) { const a = i * TAU / n, b = a + TAU * (n === 8 ? 3 : 2) / n; c.beginPath(); c.moveTo(Math.cos(a) * 200, Math.sin(a) * 200); c.lineTo(Math.cos(b) * 200, Math.sin(b) * 200); c.stroke(); } + c.beginPath(); c.arc(0, 0, 200, 0, TAU); c.stroke(); c.beginPath(); c.arc(0, 0, 224, 0, TAU); c.stroke(); + } + c.restore(); + } + if (g.stop > 0) { // time stop: the world loses its colour; bullets and characters are drawn after this, still in colour + const el = (g.stopLen || g.stop) - g.stop, a = Math.min(1, el / 6, g.stop / 8); + c.save(); c.globalAlpha = 0.85 * a; c.globalCompositeOperation = 'saturation'; c.fillStyle = '#808080'; c.fillRect(0, 0, W, H); + c.globalCompositeOperation = 'source-over'; c.globalAlpha = 0.22 * a; c.fillStyle = '#1b1640'; c.fillRect(0, 0, W, H); c.restore(); + } + } + function drawFamiliars(c, g) { + for (const f of g.fams) { + if (f.hp !== undefined) { if (f.t >= 0) fairy(c, f, g.t); continue; } + const col = f.c === M.C.RED ? '255,90,110' : '120,150,255', u = Math.min(1, f.t / 40); + c.save(); c.translate(f.x, f.y); c.globalAlpha = u; + const gr = c.createRadialGradient(0, 0, 2, 0, 0, 22); gr.addColorStop(0, `rgba(${col},.55)`); gr.addColorStop(1, `rgba(${col},0)`); c.fillStyle = gr; c.beginPath(); c.arc(0, 0, 22, 0, TAU); c.fill(); + c.rotate(f.t * (f.c === M.C.RED ? 0.05 : -0.05)); c.strokeStyle = `rgba(${col},.9)`; c.lineWidth = 1.5; + c.beginPath(); c.arc(0, 0, 14, 0, TAU); c.stroke(); + for (let k = 0; k < 2; k++) { c.beginPath(); for (let i = 0; i <= 3; i++) { const a = k * PI / 3 + i * TAU / 3; c.lineTo(Math.cos(a) * 13, Math.sin(a) * 13); } c.stroke(); } + c.restore(); + } + } + function drawBoss(c, g) { + const b = g.boss; if (b.y < -60) return; + const spellOn = g.spell && g.phaseId, th = THEME[g.kind].acc; + if (g.kind === 'rumia') { // darkness aura + const r = 46 + Math.sin(g.t * 0.05) * 4, a = c.createRadialGradient(b.x, b.y, 4, b.x, b.y, r); a.addColorStop(0, 'rgba(10,0,10,.55)'); a.addColorStop(1, 'rgba(10,0,10,0)'); c.fillStyle = a; c.beginPath(); c.arc(b.x, b.y, r, 0, TAU); c.fill(); + } else { const a = c.createRadialGradient(b.x, b.y, 4, b.x, b.y, 44); a.addColorStop(0, `rgba(${th},.35)`); a.addColorStop(1, `rgba(${th},0)`); c.fillStyle = a; c.beginPath(); c.arc(b.x, b.y, 44, 0, TAU); c.fill(); } + if (spellOn) { // spell circle shrinking with the remaining time + const left = Math.max(0, 1 - g.clock / g.timer), r = 28 + 52 * left; + c.save(); c.translate(b.x, b.y); c.rotate(g.t * 0.03); c.strokeStyle = `rgba(${th},.75)`; c.lineWidth = 2; c.beginPath(); c.arc(0, 0, r, 0, TAU); c.stroke(); + c.lineWidth = 1; c.beginPath(); c.arc(0, 0, r - 6, 0, TAU); c.stroke(); + for (let i = 0; i < 16; i++) { c.rotate(TAU / 16); c.fillStyle = `rgba(${th},.85)`; c.fillRect(r - 4.5, -1.5, 3, 3); } + c.restore(); + } + if (g.trans > 0 || (g.phaseId && g.phaseT < 40 && g.spell)) { // charge particles converging on the boss + for (let i = 0; i < 12; i++) { const a = i * TAU / 12 + g.t * 0.05, d = 70 - ((g.t * 2 + i * 9) % 70); c.fillStyle = `rgba(${th},.85)`; c.fillRect(b.x + Math.cos(a) * d - 1.5, b.y + Math.sin(a) * d - 1.5, 3, 3); } + } + if (g.defeat > 0) { + const u = 1 - g.defeat / 100; + for (let i = 0; i < 3; i++) { c.strokeStyle = `rgba(255,255,255,${(0.8 - u * 0.7).toFixed(2)})`; c.lineWidth = 3; c.beginPath(); c.arc(b.x, b.y, 10 + u * (220 + i * 80), 0, TAU); c.stroke(); } + if (u > 0.35) return; + } + if (g.kind === 'rumia') rumia(c, b.x, b.y, g.t); else if (g.kind === 'cirno') cirno(c, b.x, b.y, g.t); else if (g.kind === 'meiling') meiling(c, b.x, b.y, g.t); else if (g.kind === 'patchouli') patchouli(c, b.x, b.y, g.t); else if (g.kind === 'remilia') { + const iv = g.sub.inv || g.sub.bat > 0; // untouchable (C47): faded, inside a dark ring + if (iv) { c.strokeStyle = 'rgba(40,10,50,.85)'; c.lineWidth = 3; c.beginPath(); c.arc(b.x, b.y, 26, 0, TAU); c.stroke(); c.globalAlpha = 0.45; } + remilia(c, b.x, b.y, g.t); c.globalAlpha = 1; + } else sakuya(c, b.x, b.y, g.t); + } + function drawBullets(c, g, ox, oy) { + for (const q of g.bullets) { + const img = bulletSprite(q.k, q.c), oriented = q.k === 2 || q.k === 4 || q.k === 5 || q.k === 8, hw = img.width / 2; + if (oriented) { + const a = (q.vx * q.vx + q.vy * q.vy) > 1e-6 ? Math.atan2(q.vy, q.vx) : (q.a !== undefined ? q.a : PI / 2); + const cs = Math.cos(a), sn = Math.sin(a); c.setTransform(cs, sn, -sn, cs, q.x + ox, q.y + oy); c.drawImage(img, -hw, -hw); + } else { c.setTransform(1, 0, 0, 1, q.x + ox, q.y + oy); c.drawImage(img, -hw, -hw); } + } + c.setTransform(1, 0, 0, 1, ox, oy); + } + function drawLasers(c, g) { + for (const l of g.lasers) { + const warn = l.t <= l.wn, fade = l.t > l.wn + l.on, w = warn ? 1.5 : fade ? l.w * Math.max(0, 1 - (l.t - l.wn - l.on) / 16) : l.w * Math.min(1, (l.t - l.wn) / 6); + c.save(); c.translate(l.x, l.y); c.rotate(l.a); + const lc = l.col === undefined ? null : rgba(COL[l.col], 0.55), le = l.col === undefined ? 'rgba(60,220,110,0)' : rgba(COL[l.col], 0); + if (warn) { c.fillStyle = lc || 'rgba(160,255,190,.55)'; c.fillRect(0, -0.75, l.l, 1.5); } + else { const gr = c.createLinearGradient(0, -w, 0, w); gr.addColorStop(0, le); gr.addColorStop(0.5, 'rgba(220,255,230,.95)'); gr.addColorStop(1, le); c.fillStyle = gr; c.fillRect(0, -w, l.l, w * 2); } + c.restore(); + } + } + function drawPlayer(c, g) { + const p = g.player, B = g.bomb; + if (B && B.k === 'A') for (const o of B.orbs) { + const col = COL[[0, 5, 4, 3, 2, 8, 1][o.c % 7]]; + if (o.st === 0) { const gr = c.createRadialGradient(o.x, o.y, 2, o.x, o.y, 26); gr.addColorStop(0, '#ffffff'); gr.addColorStop(0.35, rgba(col, 0.9)); gr.addColorStop(1, rgba(col, 0)); c.fillStyle = gr; c.beginPath(); c.arc(o.x, o.y, 26, 0, TAU); c.fill(); } + else { const u = o.st / 30, gr = c.createRadialGradient(o.x, o.y, 4, o.x, o.y, 40 + u * 110); gr.addColorStop(0, rgba('#ffffff', 0.8 * (1 - u))); gr.addColorStop(1, rgba(col, 0)); c.fillStyle = gr; c.beginPath(); c.arc(o.x, o.y, 40 + u * 110, 0, TAU); c.fill(); } + } + if (B && B.k === 'B') { + const a = Math.min(1, B.t / 10) * Math.min(1, (B.dur - B.t) / 20); + c.fillStyle = `rgba(255,90,120,${(0.35 * a).toFixed(3)})`; c.fillRect(B.x - 31, 0, 62, H); c.fillRect(0, B.y - 31, W, 62); + c.strokeStyle = `rgba(255,230,240,${(0.8 * a).toFixed(3)})`; c.lineWidth = 2; c.strokeRect(B.x - 31, -2, 62, H + 4); c.strokeRect(-2, B.y - 31, W + 4, 62); + } + if (p.state === 'dead') { + const u = Math.min(1, p.deadT / 30); + for (let i = 0; i < 2; i++) { c.strokeStyle = `rgba(255,${i ? 120 : 255},${i ? 160 : 255},${(1 - u).toFixed(2)})`; c.lineWidth = 3 - i; c.beginPath(); c.arc(p.x, p.y, 6 + u * (60 + i * 40), 0, TAU); c.stroke(); } + return; + } + let alpha = 1; + if (p.state === 'spawning') alpha = 1 - p.spawnT / 30; else if (p.inv > 0 && p.inv % 8 < 2) alpha = 0.45; + c.save(); c.globalAlpha = alpha; + if (p.power >= 8) for (const o of g.orbs()) yinyang(c, o.x, o.y, g.t * 0.12, g.shotType === 'B'); + reimu(c, p.x, p.y, p.mx, g.t); c.restore(); + } + function drawHitbox(c, g) { + const p = g.player; if (p.state === 'dead' || !p.foc) return; + c.save(); c.translate(p.x, p.y); c.rotate(g.t * 0.04); c.strokeStyle = 'rgba(255,255,255,.55)'; c.lineWidth = 1; c.beginPath(); c.arc(0, 0, 14, 0, TAU * 0.8); c.stroke(); c.restore(); + c.fillStyle = '#ff2a4a'; c.beginPath(); c.arc(p.x, p.y, 3.4, 0, TAU); c.fill(); c.fillStyle = '#fff'; c.beginPath(); c.arc(p.x, p.y, 2, 0, TAU); c.fill(); + } + function fmt(n) { return String(Math.floor(n)).padStart(9, '0').replace(/(\d)(?=(\d{3})+$)/g, '$1,'); } + function drawOverlays(c, g) { + const p = g.player; + for (const q of g.pops) outlined(c, String(q.v), q.x, q.y - q.t * 0.4, 9, q.g ? '#ffe35c' : '#f2f2ff', SANS, 'center'); + if (g.cutin > 0) { + const u = g.cutin / 110, x = W - 150 + Math.max(0, u - 0.75) * 4 * 300, a = Math.min(1, u * 3) * 0.85; + c.fillStyle = `rgba(0,0,0,${(0.22 * a).toFixed(3)})`; c.fillRect(0, 130, W, 230); + portrait(c, g.kind, x, 260, a); + } + if (g.msg) { + const m = g.msg, a = Math.min(1, m.t / 20); + c.save(); c.globalAlpha = a; + if (m.k === 'capture') { outlined(c, 'Get Spell Card Bonus!!', CX, 150, 22, '#ffe066', SERIF, 'center'); outlined(c, m.v.toLocaleString('en-US'), CX, 178, 19, '#ffffff', SERIF, 'center'); } + else if (m.k === 'failed') outlined(c, 'Bonus Failed...', CX, 150, 19, '#b8c0d8', SERIF, 'center'); + else if (m.k === 'fullpower') outlined(c, 'Full Power Mode!!', CX, 230, 18, '#ff9ab6', SERIF, 'center'); + else if (m.k === 'extend') outlined(c, 'Extend!!', CX, 262, 20, '#9affc0', SERIF, 'center'); + c.restore(); + } + if (g.intro > 0) { + const boss = M.BOSS[g.kind], a = Math.min(1, g.intro / 20); + c.save(); c.globalAlpha = a; + outlined(c, boss.title, CX, 186, 15, '#e8d8ff', SERIF, 'center'); outlined(c, boss.name + ' ' + boss.en, CX, 218, 27, '#ffffff', SERIF, 'center'); + outlined(c, M.DIFFS[g.D] + ' · ' + M.hz + 'Hz', CX, 246, 15, DIFF_COL[g.D], SERIF, 'center'); + const sel = g.shotType; + outlined(c, (sel === 'A' ? '▶ ' : ' ') + 'Type A: Homing shots · Homing orbs', CX, 298, 13, sel === 'A' ? '#ffd7e0' : '#8a8fa8', SANS, 'center'); + outlined(c, (sel === 'B' ? '▶ ' : ' ') + 'Type B: Straight needles · Cross beam', CX, 318, 13, sel === 'B' ? '#ffd7e0' : '#8a8fa8', SANS, 'center'); + outlined(c, 'Q / E: Switch type at any time', CX, 340, 11, '#c6c8d8', SANS, 'center'); + c.restore(); + } + if (g.swapT > 0 && g.intro === 0) { c.save(); c.globalAlpha = Math.min(1, g.swapT / 15); outlined(c, g.shotType === 'A' ? 'Type A: Homing shots' : 'Type B: Straight needles', p.x, p.y - 34, 12, '#ffe2ea', SANS, 'center'); c.restore(); } + if (g.defeat > 0 || g.outcome === 'win') { outlined(c, 'Defeated!', CX, 232, 28, '#fff2a8', SERIF, 'center'); outlined(c, M.BOSS[g.kind].name + ' · ' + g.captures + ' / ' + g.declared + ' Spell Card · ' + (g.t / 60).toFixed(1) + ' s', CX, 260, 14, '#ffe9f0', SANS, 'center'); } + if (g.outcome === 'loss') { c.fillStyle = 'rgba(10,0,10,.5)'; c.fillRect(0, 0, W, H); outlined(c, 'GAME OVER', CX, 220, 32, '#ff8a9a', SERIF, 'center'); } + if (g.outcome === 'timeout') outlined(c, 'TIME UP', CX, 220, 30, '#ffd08a', SERIF, 'center'); + if (g.phaseId === 'c_freeze' && g.phaseT >= 40) { const lt = (g.phaseT - 40) % 330; if (lt >= 130 && lt < 146) { c.fillStyle = 'rgba(210,240,255,' + ((146 - lt) / 40).toFixed(3) + ')'; c.fillRect(0, 0, W, H); } } + if (g.stop > 0 && g.stopLen) { // time stop: a ripple from Sakuya when it starts, a cold vignette while it lasts + const el = g.stopLen - g.stop, a = Math.min(1, el / 8, g.stop / 10); + if (el < 28) { c.strokeStyle = `rgba(230,225,255,${(0.8 * (1 - el / 28)).toFixed(3)})`; c.lineWidth = 3; c.beginPath(); c.arc(g.boss.x, g.boss.y, 20 + el * 34, 0, TAU); c.stroke(); } + const v = c.createRadialGradient(CX, H / 2, 200, CX, H / 2, 520); v.addColorStop(0, 'rgba(150,140,255,0)'); v.addColorStop(1, `rgba(150,140,255,${(0.32 * a).toFixed(3)})`); + c.fillStyle = v; c.fillRect(0, 0, W, H); + } + if (g.bomb) { const B = g.bomb, a = Math.min(1, B.t / 12, (B.dur - B.t) / 30); c.save(); c.globalAlpha = Math.max(0, a); c.fillStyle = 'rgba(60,0,20,.5)'; c.fillRect(0, H - 70, 260, 22); outlined(c, B.k === 'A' ? 'Homing orbs' : 'Cross beam', 10, H - 54, 14, '#ffd6e2', SANS); c.restore(); } + if (g.flash > 0) { c.fillStyle = `rgba(255,255,255,${(g.flash / 40).toFixed(3)})`; c.fillRect(0, 0, W, H); } + if (g.hitFx > 0) { c.fillStyle = `rgba(255,40,70,${(g.hitFx / 110).toFixed(3)})`; c.fillRect(0, 0, W, H); } + if (p.state === 'alive' && p.power >= 128 && p.y < 128 && g.t % 40 < 30) outlined(c, '— Point of Collection —', p.x, 126, 9, 'rgba(255,240,200,.8)', SANS, 'center'); + } + // HUD over the field: boss line on top, player resources bottom-left, score / difficulty / native Hz bottom-right. + function drawHud(c, g) { + const ph = g.phaseId ? M.PHASES[g.phaseId] : null, boss = M.BOSS[g.kind], p = g.player, theme = THEME[g.kind]; + const top = c.createLinearGradient(0, 0, 0, 40); top.addColorStop(0, 'rgba(6,4,14,.55)'); top.addColorStop(1, 'rgba(6,4,14,0)'); c.fillStyle = top; c.fillRect(0, 0, W, 40); + const bot = c.createLinearGradient(0, H - 34, 0, H); bot.addColorStop(0, 'rgba(6,4,14,0)'); bot.addColorStop(1, 'rgba(6,4,14,.55)'); c.fillStyle = bot; c.fillRect(0, H - 34, W, 34); + if (g.intro === 0 && !g.defeat && !g.outcome) { + outlined(c, 'Enemy', 10, 14, 11, '#ffd0d8'); outlined(c, boss.name, 52, 14, 12, '#ffffff', SANS); + const left = g.remainingAttacks(), sx = 60 + c.measureText(boss.name).width; + for (let i = 0; i < Math.min(9, left); i++) star(c, sx + 6 + i * 11, 10, 4.6, 2, '#ffd56a'); + const pi = Math.min(g.phase + 1, g.phases.length) + ' / ' + g.phases.length; + outlined(c, pi, W - 52, 14, 11, '#e6dcf2', SANS, 'right'); + if (ph) { + const frac = Math.max(0, g.phaseHp / g.phaseMax), bx = 10, bw = W - 64; + c.fillStyle = 'rgba(0,0,0,.45)'; c.fillRect(bx, 19, bw, 5); + const gr = c.createLinearGradient(bx, 0, bx + bw, 0); gr.addColorStop(0, ph.spell ? theme.bar[0] : '#fff2f5'); gr.addColorStop(1, ph.spell ? theme.bar[1] : '#ffd0dc'); c.fillStyle = gr; c.fillRect(bx, 19, bw * frac, 5); + const secs = Math.max(0, Math.ceil((g.timer - g.clock) / 60)); + outlined(c, String(Math.min(99, secs)).padStart(2, '0'), W - 8, 30, 24, g.stop > 0 ? '#b8b0ff' : secs <= 10 ? '#ff6a6a' : '#ffffff', SERIF, 'right'); + if (ph.spell && !g.trans) { + const decl = Math.max(0, g.cutin) / 110, y = 50 + decl * decl * 360; + c.fillStyle = 'rgba(20,6,18,.5)'; c.fillRect(W - 330, y - 13, 322, 30); + outlined(c, ph.name, W - 12, y + 1, 14, '#ffffff', SANS, 'right'); + const base = boss.base, bonus = g.capture ? base + Math.floor(base * Math.floor((g.timer - g.clock) / 60) / 10) : 0; + outlined(c, g.capture ? 'Bonus ' + bonus.toLocaleString('en-US') : 'Bonus Failed', W - 12, y + 14, 10, g.capture ? '#ffe58a' : '#9aa3b8', SANS, 'right'); + } else outlined(c, ph.name + ' · ' + ph.en, 10, 40, 11, '#e9e2f2'); + } + const b = g.boss; // boss x indicator on the bottom edge + c.fillStyle = 'rgba(255,80,110,.8)'; c.fillRect(b.x - 16, H - 9, 32, 9); text(c, 'ENEMY', b.x, H - 1.5, 8, '#fff', SANS, 'center'); + } + // bottom-left: spare lives, bombs, power, shot type + const y0 = H - 12; + outlined(c, 'Player', 10, y0, 12, '#f2c4d0', SERIF); + for (let i = 0; i < Math.max(0, Math.min(8, p.lives - 1)); i++) star(c, 58 + i * 14, y0 - 4, 5.6, 2.4, '#ff7aa0'); + const bx = 58 + Math.max(1, Math.min(8, p.lives - 1)) * 14 + 8; + outlined(c, 'Bomb', bx, y0, 12, '#f2c4d0', SERIF); + for (let i = 0; i < Math.min(8, p.bombs); i++) star(c, bx + 42 + i * 14, y0 - 4, 5.6, 2.4, '#9be37a'); + const px = bx + 42 + Math.max(1, Math.min(8, p.bombs)) * 14 + 8, pw = Math.min(128, p.power); + outlined(c, 'Power', px, y0, 12, '#f2c4d0', SERIF); + c.fillStyle = 'rgba(0,0,0,.45)'; c.fillRect(px + 44, y0 - 9, 60, 8); c.fillStyle = pw >= 128 ? '#ffd35a' : '#ff5a72'; c.fillRect(px + 44, y0 - 9, 60 * pw / 128, 8); + outlined(c, pw >= 128 ? 'MAX' : String(pw), px + 110, y0, 12, pw >= 128 ? '#ffd35a' : '#ffffff', SERIF); + outlined(c, g.shotType === 'A' ? 'Type A' : 'Type B', px + 146, y0, 11, '#f0dce2', SANS); + // bottom-right: score, graze, spell count, difficulty, native Hz + const right = W - 8; + outlined(c, M.hz + 'Hz', right, y0, 12, '#9fe0ff', SERIF, 'right'); + outlined(c, M.DIFFS[g.D], right - 46, y0, 13, DIFF_COL[g.D], SERIF, 'right'); + outlined(c, 'Spell ' + g.captures + '/' + g.declared, right - 116, y0, 11, '#e2cfd8', SANS, 'right'); + outlined(c, 'Graze ' + p.graze, right - 186, y0, 11, '#e2cfd8', SANS, 'right'); + outlined(c, fmt(p.score), right - 262, y0, 13, '#ffffff', SERIF, 'right'); + outlined(c, 'Score', right - 352, y0, 11, '#f2c4d0', SERIF, 'right'); + } + // Build every cached sprite/tile once, before the first frame, so no gameplay frame pays for canvas creation. + function warm() { + if (cache.warm) return; + for (let k = 0; k < 10; k++) for (let ci = 0; ci < COL.length; ci++) bulletSprite(k, ci); + for (let k = 0; k < 7; k++) itemSprite(k); + for (let k = 0; k < 3; k++) shotSprite(k); + for (const kind of ['rumia', 'cirno', 'sakuya', 'meiling', 'patchouli', 'remilia']) { stageTile(kind); spellTile(kind); bustTile(kind); } + // first use of a CJK string triggers font fallback and glyph rasterisation; do it once here instead of at a spell declaration + const sc = canvas(64, 32).getContext('2d'), strings = ['Defeated! Get Spell Card Bonus!! Bonus Failed... Full Power Mode!! Extend!! GAME OVER TIME UP ENEMY Enemy Point of Collection 60Hz', + 'Homing orbs Cross beam A Type B Homing shots Straight needles Q / E: Switch type at any time ▶ Player Bomb Power MAX Score Graze Spell 0123456789,/ ·']; + for (const id in M.PHASES) strings.push(M.PHASES[id].name + ' · ' + M.PHASES[id].en); + for (const k in M.BOSS) strings.push(M.BOSS[k].name + M.BOSS[k].en + M.BOSS[k].title); + for (const str of strings) for (const size of [8, 9, 10, 11, 12, 13, 14, 15, 18, 19, 20, 22, 24, 27, 28, 30, 32]) for (const font of [SANS, SERIF]) { sc.font = size + 'px ' + font; sc.fillText(str, 0, 20); sc.strokeText(str, 0, 20); } + // draw every cached canvas once so its pixels are uploaded before the first gameplay frame that needs it + const up = canvas(16, 16).getContext('2d'); for (const k in cache) if (cache[k] && cache[k].width) up.drawImage(cache[k], 0, 0, 16, 16); + up.getImageData(0, 0, 1, 1); + cache.warm = true; + } + M.warmRenderer = warm; + M.draw = function (g, c) { + warm(); + c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; c.globalCompositeOperation = 'source-over'; c.textBaseline = 'alphabetic'; + const sh = g.shake > 0 ? Math.min(4, g.shake / 4) : 0, ox = sh ? Math.sin(g.t * 1.7) * sh : 0, oy = sh ? Math.cos(g.t * 2.3) * sh : 0; + if (sh) { c.fillStyle = '#05030a'; c.fillRect(0, 0, W, H); } + c.setTransform(1, 0, 0, 1, ox, oy); + drawBackground(c, g); + for (const it of g.items) c.drawImage(itemSprite(it.k), it.x - 11, it.y - 11); + for (const s of g.shots) { const img = shotSprite(s.k); if (s.k === 1) { c.save(); c.translate(s.x, s.y); c.rotate(Math.atan2(s.vy, s.vx) + PI / 2); c.drawImage(img, -8, -22); c.restore(); } else c.drawImage(img, s.x - 8, s.y - 22); } + drawFamiliars(c, g); drawBoss(c, g); drawLasers(c, g); drawPlayer(c, g); + drawBullets(c, g, ox, oy); + drawHitbox(c, g); drawOverlays(c, g); + c.setTransform(1, 0, 0, 1, 0, 0); + drawHud(c, g); + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/touhou_remake/game.js b/environments/games/web/games/touhou_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..7516b6f4b85e03c3f3e5f034f9c14e7f165a6bb1 --- /dev/null +++ b/environments/games/web/games/touhou_remake/game.js @@ -0,0 +1,1517 @@ +/* Touhou 6 (EoSD) boss practice: Rumia (stage 1), Cirno (stage 2), Hong Meiling (stage 3), Patchouli Knowledge (stage 4), Sakuya + * (stage 5) and Remilia Scarlet (stage 6), rules scarlet-practice@8. + * Player/bomb/item/rank/spell-card/time-stop rules follow the CC0 GensokyoClub/th06 decompilation (v1.02h); spell geometry is + * authored from community descriptions. + * @4 (2026-11-02): the arena is the whole 854x480 frame (16:9) instead of the original 384x448 lane, three public tiers, + * Sakuya Izayoi, Q/E shot-type switching at any time. Object rules (speeds, hitboxes, damage, bombs) keep original pixel units. + * @5 (2026-11-03): touching the boss's body kills the player (C17; @1-@4 had read the decompilation the wrong way round). + * @6 (2026-11-05): Hong Meiling with ordinary enemies (fairies, C33); homing amulets and Fantasy Seal orbs steer to the lowest + * interactable enemy (C34) - with no fairy that is the boss, so the three earlier cases replay bit-identically. + * @7 (2026-11-05): Patchouli Knowledge (Reimu A card list fixed at reset, C40; bullets from the lasers, C42; optional laser sweep `va`); + * health() no longer counts a finished attack twice during the transition (C44, reporting only). + * @8 (2026-11-05): Remilia Scarlet (C45-C48): per-card score base, untouchable rules read through `sub`, the Func7 laser web, optional laser + * colour `col`; attacks without those fields behave as before. */ +(function (root) { + 'use strict'; + // Local bindings of the builtins: under Node's vm loader every global lookup goes through the sandbox interceptor (30x slower + // in the hot loops); in a browser this changes nothing. Same functions, same results. + const Math = root.Math, Number = root.Number, Object = root.Object, Array = root.Array, Set = root.Set, Error = root.Error; + const N = root.NativeBench, TAU = Math.PI * 2, PI = Math.PI; + const W = 854, H = 480, CX = W / 2; // full-frame arena (C18B; original lane 384x448, C18) + const AREA = {x0: 8, y0: 16, x1: W - 8, y1: H - 16}; // movement-area insets 8/16 (S11) + const SPAWN = {x: CX, y: H - 64}; // 64 px above the bottom edge, as (192, 384) in 448 (S08) + const DIFFS = ['Easy', 'Normal', 'Hard', 'Lunatic']; + const diffIndex = d => d < 0.3 ? 0 : d < 0.6 ? 1 : d < 0.85 ? 2 : 3; // C15 (engineering mapping) + const TIERS = {easy: 0.2, normal: 0.5, hard: 0.8}; // public tiers = original Easy / Normal / Hard (C24) + // Tier calibration (C24, approximation): one life multiplier per boss and tier on the C16 per-attack life, non-decreasing from + // easy to hard, and one attack-timer multiplier per tier; linear in d between the tier anchors, flat outside them (Lunatic uses + // the hard values). Calibrated with the reference controller against the meeting windows (easy 20-30 s, normal 45-90 s, + // hard 150-240 s); a boss with more attacks gets a smaller multiplier for the same window. + const LIFE_CAL = {rumia: [0.40, 0.52, 1.6], cirno: [0.40, 0.415, 1.0], sakuya: [0.45, 0.45, 0.9], meiling: [0.40, 0.45, 0.9], patchouli: [0.40, 0.42, 0.8], remilia: [0.45, 0.45, 0.74]}; + const TIME_CAL = [1, 1, 2]; + const calAt = (v, d) => { + const a = [TIERS.easy, TIERS.normal, TIERS.hard]; + if (d <= a[0]) return v[0]; + if (d >= a[2]) return v[2]; + const i = d <= a[1] ? 0 : 1; + return v[i] + (v[i + 1] - v[i]) * (d - a[i]) / (a[i + 1] - a[i]); + }; + // Enemy bullet sprite boxes (edge length, px), BulletManager templates (S15). + const K = {PELLET: 0, RING: 1, RICE: 2, BALL: 3, KUNAI: 4, SHARD: 5, BIG: 6, FIRE: 7, KNIFE: 8, BUBBLE: 9}; + const BSIZE = [4, 6, 4, 6, 5, 4, 16, 11, 9, 32]; + const C = {RED: 0, PINK: 1, BLUE: 2, CYAN: 3, GREEN: 4, YELLOW: 5, ORANGE: 6, WHITE: 7, PURPLE: 8}; + const RAINBOW = [0, 6, 5, 4, 3, 2, 8]; + const PLAYER_HALF = 1.25, GRAZE_PAD = 20, BOSS_HALF = 16; // C02, C04; boss box is an approximation (C23) + // Shot rows: [wait, start, dx, dy, w, h, angleDeg, speed, damage, spawn(0 body,1 left orb,2 right orb), kind(0 main,1 homing,2 needle)] + const MAIN = (dx, a, d) => [5, 0, dx, 0, 12, 12, a, 12, d, 0, 0]; + const AM = (w, s, a1, a2, d) => [[w, s, 0, 0, 12, 12, a1, 10, d, 1, 1], [w, s, 0, 0, 12, 12, a2, 10, d, 2, 1]]; + const ND = (w, dx, d) => [[w, 0, dx, -16, 12, 40, -90, 22, d, 1, 2], [w, 0, dx, -16, 12, 40, -90, 22, d, 2, 2]]; + const A7 = [MAIN(0, -97, 24), MAIN(0, -90, 28), MAIN(0, -83, 24)], B8 = [MAIN(0, -106, 9), MAIN(0, -98, 17), MAIN(0, -90, 20), MAIN(0, -82, 17), MAIN(0, -74, 9)]; + const SHOT = { // g_CharacterPowerDataReimuA / ReimuB (S09); the first tier whose cut-off exceeds power is used + A: [[8, [MAIN(0, -90, 48)]], [16, [MAIN(0, -90, 48), ...AM(30, 0, -120, -60, 14)]], + [32, [MAIN(-4, -91, 30), MAIN(4, -89, 30), ...AM(30, 0, -120, -60, 14)]], + [48, [MAIN(0, -96, 24), MAIN(0, -90, 30), MAIN(0, -84, 24), ...AM(30, 0, -120, -60, 14)]], + [64, [MAIN(0, -97, 24), MAIN(0, -90, 30), MAIN(0, -83, 24), ...AM(15, 0, -120, -60, 12)]], + [80, [MAIN(0, -97, 24), MAIN(0, -90, 29), MAIN(0, -83, 24), ...AM(15, 0, -120, -60, 9), ...AM(30, 0, -150, -30, 12)]], + [96, [...A7, ...AM(30, 0, -110, -70, 10), ...AM(30, 10, -130, -50, 9), ...AM(30, 20, -150, -30, 11)]], + [127, [...A7, ...AM(15, 0, -110, -70, 8), ...AM(15, 5, -130, -50, 8), ...AM(15, 10, -150, -30, 8)]], + [999, [MAIN(-8, -97, 23), MAIN(-8, -90, 24), MAIN(8, -90, 24), MAIN(8, -83, 23), ...AM(16, 0, -110, -70, 10), ...AM(16, 4, -130, -50, 8), ...AM(16, 8, -150, -30, 7), ...AM(16, 12, -170, -10, 10)]]], + B: [[8, [MAIN(0, -90, 48)]], [16, [MAIN(0, -90, 48), ...ND(15, 0, 12)]], + [32, [MAIN(-4, -91, 32), MAIN(4, -89, 32), ...ND(10, 0, 12)]], + [48, [MAIN(-4, -91, 30), MAIN(4, -89, 30), ...ND(8, 0, 12)]], + [64, [MAIN(0, -97, 20), MAIN(0, -90, 28), MAIN(0, -83, 20), ...ND(8, 0, 12)]], + [80, [MAIN(0, -97, 16), MAIN(0, -90, 27), MAIN(0, -83, 16), ...ND(5, 8, 12), ...ND(8, -8, 10)]], + [96, [MAIN(0, -98, 16), MAIN(0, -90, 22), MAIN(0, -82, 16), ...ND(3, 8, 10), ...ND(5, -8, 10)]], + [127, [...B8, ...ND(3, 12, 10), ...ND(5, -12, 10), ...ND(10, 0, 10)]], + [999, [...B8, ...ND(3, 12, 10), ...ND(3, -12, 10), ...ND(5, 0, 10)]]] + }; + const POWER_SCORE = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 11000, 12000, 51200]; + const POINT_VALUE = [[100000, 60000, 100], [100000, 60000, 100], [150000, 100000, 180], [200000, 150000, 270]]; // (S10) + const RANK = [[16, 12, 20], [16, 10, 32], [16, 10, 32], [16, 10, 32]]; // rank, min, max (S11) + const EXTENDS = [10000000, 20000000, 40000000, 60000000]; + const ITEM = {POWER: 0, POINT: 1, BIG: 2, BOMB: 3, FULL: 4, LIFE: 5, STAR: 6}; + // Attack tables. hp/time are the C16 calibration (approximation) before the tier multipliers; names are neutral display names (the originals are in + const PHASES = { + r_non1: {spell: false, hp: 9000, time: 30, name: 'Non-spell pattern 1', en: 'Non-spell 1'}, + r_bird: {spell: true, hp: 2600, time: 40, name: 'Alternating Sweep', en: 'Alternating Sweep', easyTimeoutOnly: true}, + r_non2: {spell: false, hp: 10000, time: 30, name: 'Non-spell pattern 2', en: 'Non-spell 2'}, + r_demarc: {spell: true, hp: 3200, time: 45, name: 'Counter Rings', en: 'Counter Rings'}, + c_non1: {spell: false, hp: 10000, time: 30, name: 'Non-spell pattern 1', en: 'Non-spell 1'}, + c_icicle: {spell: true, hp: 2800, time: 40, name: 'Side Arcs', en: 'Side Arcs', diffs: [0, 1]}, + c_hail: {spell: true, hp: 3000, time: 40, name: 'Hanging Shard Rings', en: 'Hanging Shard Rings', diffs: [2, 3]}, + c_non2: {spell: false, hp: 11000, time: 30, name: 'Non-spell pattern 2', en: 'Non-spell 2'}, + c_freeze: {spell: true, hp: 3600, time: 50, name: 'Stall and Scatter', en: 'Stall and Scatter'}, + c_blizzard: {spell: true, hp: 2600, time: 45, name: 'Drifting Shard Bursts', en: 'Drifting Shard Bursts', diffs: [1, 2, 3]}, + // Sakuya: the time stops freeze the player's shots, so for the same C16 capture time her cards carry less life (C16B) + s_non1: {spell: false, hp: 7000, time: 30, name: 'Non-spell pattern 1', en: 'Non-spell 1'}, + s_corpse: {spell: true, hp: 2200, time: 40, name: 'Stop and Lay Knives', en: 'Stop and Lay Knives', diffs: [0, 1]}, + s_jack: {spell: true, hp: 2300, time: 40, name: 'Trail Knives', en: 'Trail Knives', diffs: [2, 3]}, + s_non2: {spell: false, hp: 11000, time: 35, name: 'Non-spell pattern 2', en: 'Non-spell 2'}, + s_luna: {spell: true, hp: 2300, time: 45, name: 'Knife Lanes', en: 'Knife Lanes', diffs: [0, 1]}, + s_world: {spell: true, hp: 2400, time: 45, name: 'Surround Knives', en: 'Surround Knives', diffs: [2, 3]}, + s_non3: {spell: false, hp: 11000, time: 30, name: 'Non-spell pattern 3', en: 'Non-spell 3'}, + s_doll: {spell: true, hp: 2300, time: 50, name: 'Turning Ricochet Knives', en: 'Turning Ricochet Knives', diffs: [0, 1]}, + s_killing: {spell: true, hp: 2400, time: 50, name: 'Rest and Aim Rings', en: 'Rest and Aim Rings', diffs: [2, 3]}, + // Hong Meiling (stage 3, C35): Easy 5 / Normal 6 / Hard+ 7 attacks; hp/time are C16-style starting values, calibrated per tier + m_non1: {spell: false, hp: 10000, time: 30, name: 'Non-spell pattern 1', en: 'Non-spell 1'}, + m_chime: {spell: true, hp: 2800, time: 40, name: 'Fixed Angle Streams', en: 'Fixed Angle Streams'}, + m_non2: {spell: false, hp: 11000, time: 35, name: 'Non-spell pattern 2', en: 'Non-spell 2'}, + m_vine: {spell: true, hp: 2800, time: 40, name: 'Drifting Scatter', en: 'Drifting Scatter', diffs: [2, 3]}, + m_non3: {spell: false, hp: 11000, time: 30, name: 'Non-spell pattern 3', en: 'Non-spell 3'}, + m_rain: {spell: true, hp: 3000, time: 45, name: 'Side Accel Shards', en: 'Side Accel Shards', diffs: [0, 1]}, + m_dance: {spell: true, hp: 3000, time: 45, name: 'Burst and Curve', en: 'Burst and Curve', diffs: [2, 3]}, + m_typhoon: {spell: true, hp: 3200, time: 50, name: 'Crossing Spirals', en: 'Crossing Spirals', diffs: [1, 2, 3]}, + // Patchouli Knowledge (stage 4, C40), Reimu A list: Easy 4 / Normal 6 / Hard+ 7 attacks + p_non1: {spell: false, hp: 10000, time: 30, name: 'Non-spell pattern 1', en: 'Non-spell 1'}, + p_agni: {spell: true, hp: 2800, time: 40, name: 'Wavering Fall', en: 'Wavering Fall', diffs: [0, 1]}, + p_agni_hl: {spell: true, hp: 3000, time: 40, name: 'Wavering Fall Dense', en: 'Wavering Fall Dense', diffs: [2, 3]}, + p_non2: {spell: false, hp: 11000, time: 30, name: 'Non-spell pattern 2', en: 'Non-spell 2'}, + p_trilithon_hl: {spell: true, hp: 2800, time: 40, name: 'Stall and Turn', en: 'Stall and Turn', diffs: [1]}, + p_shake: {spell: true, hp: 3000, time: 40, name: 'Stall Turn and Heavy Shots', en: 'Stall Turn and Heavy Shots', diffs: [2, 3]}, + p_lava: {spell: true, hp: 3000, time: 45, name: 'Rings and Stalls', en: 'Rings and Stalls'}, + p_mercury: {spell: true, hp: 3000, time: 45, name: 'Twin Curving Streams', en: 'Twin Curving Streams', diffs: [1, 2, 3]}, + p_forest: {spell: true, hp: 3200, time: 50, name: 'Corner Stream and Sparks', en: 'Corner Stream and Sparks', diffs: [2, 3]}, + // Remilia Scarlet (stage 6, C45): Normal and Hard+ each 4 non-spells + 5 cards; the original Easy has no stage 6. `base` = the + // card's own g_SpellcardScore where it differs from BOSS.base (C46); `bat` = the bomb rule of the final card (C47). + r6_non1: {spell: false, hp: 10000, time: 30, name: 'Non-spell pattern 1', en: 'Non-spell 1'}, + r6_david: {spell: true, hp: 1100, time: 40, name: 'Beam Web', en: 'Beam Web', diffs: [0, 1]}, + r6_demon: {spell: true, hp: 2600, time: 40, name: 'Static Web Shells', en: 'Static Web Shells', diffs: [2, 3], base: 600000}, + r6_non2: {spell: false, hp: 8000, time: 30, name: 'Non-spell pattern 2', en: 'Non-spell 2'}, + r6_nether: {spell: true, hp: 1100, time: 40, name: 'Falling Slivers', en: 'Falling Slivers', diffs: [0, 1]}, + r6_needles: {spell: true, hp: 2600, time: 40, name: 'Bouncing Slivers', en: 'Bouncing Slivers', diffs: [2, 3], base: 600000}, + r6_non3: {spell: false, hp: 7000, time: 30, name: 'Non-spell pattern 3', en: 'Non-spell 3'}, + r6_tepes: {spell: true, hp: 1200, time: 45, name: 'Spiral Blades', en: 'Spiral Blades', diffs: [0, 1]}, + r6_fantasy: {spell: true, hp: 2800, time: 45, name: 'Even Way Shells', en: 'Even Way Shells', diffs: [2, 3], base: 600000}, + r6_non4: {spell: false, hp: 6000, time: 35, name: 'Non-spell pattern 4', en: 'Non-spell 4'}, + r6_shoot: {spell: true, hp: 1000, time: 40, name: 'Fast Aimed Shells', en: 'Fast Aimed Shells', diffs: [0, 1]}, + r6_meister: {spell: true, hp: 1900, time: 40, name: 'Led Volleys', en: 'Led Volleys', diffs: [2, 3], base: 600000}, + r6_magic: {spell: true, hp: 2800, time: 50, name: 'Bouncing Trail Shells', en: 'Bouncing Trail Shells', diffs: [0, 1], bat: true}, + r6_gensokyo: {spell: true, hp: 2600, time: 50, name: 'Trail Shells and Ring', en: 'Trail Shells and Ring', diffs: [2, 3], base: 600000, bat: true} + }; + const ORDER = { + rumia: ['r_non1', 'r_bird', 'r_non2', 'r_demarc'], + cirno: ['c_non1', 'c_icicle', 'c_hail', 'c_non2', 'c_freeze', 'c_blizzard'], + sakuya: ['s_non1', 's_corpse', 's_jack', 's_non2', 's_luna', 's_world', 's_non3', 's_doll', 's_killing'], + meiling: ['m_non1', 'm_chime', 'm_non2', 'm_vine', 'm_non3', 'm_rain', 'm_dance', 'm_typhoon'], + // the Reimu A card list (C40): the shot type at reset fixes it; only Reimu A is implemented + patchouli: ['p_non1', 'p_agni', 'p_agni_hl', 'p_non2', 'p_trilithon_hl', 'p_shake', 'p_lava', 'p_mercury', 'p_forest'], + remilia: ['r6_non1', 'r6_david', 'r6_demon', 'r6_non2', 'r6_nether', 'r6_needles', 'r6_non3', 'r6_tepes', 'r6_fantasy', 'r6_non4', 'r6_shoot', 'r6_meister', 'r6_magic', 'r6_gensokyo'] + }; + // BossBench easy (d < 0.30) keeps the opening non-spell and the boss's final Easy card (C24, deviation from the original Easy). + const EASY_ORDER = {rumia: ['r_non1', 'r_bird', 'r_demarc'], cirno: ['c_non1', 'c_freeze'], sakuya: ['s_non1', 's_doll'], meiling: ['m_non1', 'm_rain'], patchouli: ['p_non1', 'p_lava'], remilia: ['r6_non1', 'r6_magic']}; + const BOSS = { + rumia: {name: 'Fan Caster', en: 'FAN CASTER', title: 'Spread arms and fire sweeping loops', stage: 'Stage 1', base: 200000}, + cirno: {name: 'Shard Sprayer', en: 'SHARD SPRAYER', title: 'Crystal shards fill the sky, then suddenly freeze', stage: 'Stage 2', base: 200000}, + meiling: {name: 'Spiral Weaver', en: 'SPIRAL WEAVER', title: 'Stationary crossed streams', stage: 'Stage 3', base: 250000}, // g_SpellcardScore stage 3 (C36) + patchouli: {name: 'Beam Elementalist', en: 'BEAM ELEMENTALIST', title: 'Rotating beams and rapid elemental shots', stage: 'Stage 4', base: 300000}, // g_SpellcardScore stage 4 (C41) + sakuya: {name: 'Stoptime Knifer', en: 'STOPTIME KNIFER', title: 'Time stops and knives are already in place', stage: 'Stage 5', base: 400000}, // g_SpellcardScore (S13) + remilia: {name: 'Web Bombardier', en: 'WEB BOMBARDIER', title: 'Beam webs and trailing giant bullets', stage: 'Stage 6', base: 500000} // Normal cards; Hard+ cards carry their own 600,000 (S13) + }; + const INTRO = 120, TRANSITION = 80, DEFEAT = 100, START_POWER = 128; + + const M = root.TouhouGame = { + id: 'touhou_remake', version: 'scarlet-practice@8', hz: 60, maxSeconds: 600, dimension: '2d', renderer: 'canvas-native', + title: 'Touhou Koumakyou: Boss Practice', tiers: TIERS, + cases: [{id: 'touhou/rumia', name: 'Fan Caster · Stage 1 Boss'}, {id: 'touhou/cirno', name: 'Shard Sprayer · Stage 2 Boss'}, {id: 'touhou/sakuya', name: 'Stoptime Knifer · Stage 5 Boss'}, {id: 'touhou/meiling', name: 'Spiral Weaver · Stage 3 Boss'}, {id: 'touhou/patchouli', name: 'Beam Elementalist · Stage 4 Boss'}, {id: 'touhou/remilia', name: 'Web Bombardier · Stage 6 Boss'}], + controls: { + 'W A S D / arrow keys': 'Move in eight directions at 4.0 px/frame; diagonal movement is normalized by √2', + 'Shift': 'Slow movement at 2.0 px/frame, showing the 2.5×2.5 px hitbox; options cluster inward', + 'J / LMB': 'Hold to shoot: Type A homing shots / Type B straight needles (one cycle per 30 frames)', + 'K / RMB': 'Spell card: Type A homing orbs / Type B cross beam; deathbomb within 6 frames after being hit', + 'Q / E': 'Switch between Type A and Type B at any time except during a spell card or time stop', + 'Esc': 'Pause (automatic on focus loss)' + }, + W, H, CX, AREA, SPAWN, K, C, BSIZE, PHASES, ORDER, EASY_ORDER, BOSS, DIFFS, diffIndex, LIFE_CAL, TIME_CAL, calAt, ITEM, SHOT + }; + + // Fairies (C33): ordinary enemies with a 12x12 hitbox (contact box 8x8); only in-bounds fairies interact. + const FAIRY_HALF = 6, EMPTY_A = []; + const fairyIn = f => f.x >= 0 && f.x <= W && f.y >= 0 && f.y <= H; + const clone = v => { + if (v === null || typeof v !== 'object') return v; + if (Array.isArray(v)) { const a = new Array(v.length); for (let i = 0; i < v.length; i++) a[i] = clone(v[i]); return a; } + const o = {}; for (const k in v) o[k] = clone(v[k]); return o; + }; + const angDiff = (a, b) => Math.atan2(Math.sin(a - b), Math.cos(a - b)); + + class Game { + constructor(id, seed, d) { + this.id = id; this.kind = id.split('/')[1]; this.d = d; this.D = diffIndex(d); + if (!ORDER[this.kind]) throw Error('Unknown touhou case ' + id); + this.rng = (seed >>> 0) || 0x9e3779b9; this.t = 0; this.outcome = null; this.events = []; + this.shotType = 'A'; + const r = RANK[this.D]; this.rank = r[0]; this.rankMin = r[1]; this.rankMax = r[2]; this.subrank = 0; + // lifeCount 4 on easy, the default 2 otherwise: both inside the original option range 0..4 (S22), the tier's "damage" axis (C24) + const lives = this.D === 0 ? 5 : 3; this.lifeMax = lives; + this.player = {x: SPAWN.x, y: SPAWN.y, state: 'alive', inv: 120, deadT: 0, window: 0, spawnT: 0, focus: 0, foc: 0, mx: 0, + fireT: -1, lives, bombs: 3, power: START_POWER, graze: 0, grazeStage: 0, score: 0, points: 0, pc: 0, grace: 0, + misses: 0, bombsUsed: 0, extendsEarned: 0, hits: 0}; + const lm = calAt(LIFE_CAL[this.kind], d), tm = calAt(TIME_CAL, d); + this.phases = (this.D === 0 ? EASY_ORDER : ORDER)[this.kind].filter(id => !PHASES[id].diffs || PHASES[id].diffs.includes(this.D)); + this.lifeOf = this.phases.map(id => Math.max(100, Math.round(PHASES[id].hp * lm / 10) * 10)); + this.timeOf = this.phases.map(id => Math.round(PHASES[id].time * tm) * 60); + this.bossMax = this.lifeOf.reduce((v, x) => v + x, 0); this.cleared = 0; + this.boss = {x: CX, y: -40, fx: CX, fy: -40, tx: CX, ty: 112, mt: 0, md: 90, lin: 0}; + this.phase = -1; this.phaseId = null; this.phaseT = 0; this.clock = 0; this.timer = 0; this.phaseHp = 0; this.phaseMax = 1; + this.spell = false; this.capture = false; this.usedBomb = false; this.timedOut = []; this.sub = {}; + this.intro = INTRO; this.trans = 0; this.defeat = 0; this.captures = 0; this.declared = 0; this.stop = 0; this.stopLen = 0; + this.bullets = []; this.lasers = []; this.shots = []; this.items = []; this.fams = []; this.bomb = null; + this.pops = []; this.msg = null; this.cutin = 0; this.shake = 0; this.flash = 0; this.hitFx = 0; this.swapT = 0; + } + // ---------- helpers ---------- + ev(name) { this.events.push(name); } + rnd() { return N.rand(this); } + rankLerp(lo, hi) { return this.rank * (hi - lo) / 32 + lo; } + sp(s) { return s * (1 + this.rankLerp(-0.08, 0.08)); } // approximated rank speed range + cnt(n) { return Math.max(1, n + Math.trunc(this.rankLerp(1, -1))); } // low rank denser, high rank sparser (S19) + iv(n) { return Math.max(1, n + Math.trunc(this.rankLerp(n / 5, -n / 5))); } // +-20 % interval (S13) + addSubrank(n) { this.subrank += n; while (this.subrank >= 100) { this.rank++; this.subrank -= 100; } if (this.rank > this.rankMax) this.rank = this.rankMax; } + subSubrank(n) { this.subrank -= n; while (this.subrank < 0) { this.rank--; this.subrank += 100; } if (this.rank < this.rankMin) this.rank = this.rankMin; } + aim(x, y) { const p = this.player; return Math.atan2(p.y - y, p.x - x); } + // Every enemy bullet is created with the same fields in the same order (unused ones undefined, which JSON and the state hash + // omit), so the per-tick loops stay monomorphic. + shoot(x, y, a, s, k, c, ex) { + const q = {x, y, vx: Math.cos(a) * s, vy: Math.sin(a) * s, k, c, t: 0, g: 0, a: undefined, s: undefined, st: undefined, gt: undefined, gm: undefined, + ga: undefined, gs: undefined, w: undefined, wt: undefined, ta: undefined, tw: undefined, ax: undefined, ay: undefined, am: undefined, bn: undefined, bm: undefined}; + if (ex) { for (const key in ex) { if (!(key in q)) throw Error('unknown bullet field ' + key); q[key] = ex[key]; } if (q.st) q.a = a; } + this.bullets.push(q); return q; + } + knife(x, y, a, s, c, ex) { return this.shoot(x, y, a, s, K.KNIFE, c, ex ? Object.assign({s, a}, ex) : {s, a}); } + ring(x, y, n, a0, s, k, c, ex) { for (let i = 0; i < n; i++) this.shoot(x, y, a0 + TAU * i / n, s, k, c, ex); } + fan(x, y, n, a, gap, s, k, c, ex) { for (let i = 0; i < n; i++) this.shoot(x, y, a + (i - (n - 1) / 2) * gap, s, k, c, ex); } + laser(x, y, a, l, w, warn, on) { this.lasers.push({x, y, a, l, w, t: 0, wn: warn, on, gz: 0}); } + // ExInsStage4Func12 (C42): for every live laser (at most 8), fire(x, y, angle) at 64 px from the boss along the laser. + fromLasers(b, fire) { + let n = 0; + for (const l of this.lasers) { + if (n >= 8) break; + if (l.t > l.wn + l.on) continue; + n++; fire(b.x + Math.cos(l.a) * 64, b.y + Math.sin(l.a) * 64, l.a); + } + return n; + } + moveBoss(x, y, frames, linear) { const b = this.boss; b.fx = b.x; b.fy = b.y; b.tx = N.clamp(x, 40, W - 40); b.ty = N.clamp(y, 48, 200); b.mt = 0; b.md = frames; b.lin = linear ? 1 : 0; } + timeStop(frames) { this.stop = this.stopLen = frames; this.ev('time_stop'); } // ExInsStage56Func4 arg 1 / 0 (S14) + addScore(v) { + const p = this.player; p.score += v; + if (p.extendsEarned < EXTENDS.length && p.score >= EXTENDS[p.extendsEarned]) { + p.extendsEarned++; if (p.lives < 9) p.lives++; this.addSubrank(200); this.ev('extend'); this.msg = {k: 'extend', t: 120, v: 0}; + } + } + pop(x, y, v, gold) { this.pops.push({x, y, v, t: 0, g: gold ? 1 : 0}); if (this.pops.length > 24) this.pops.shift(); } + spawnItem(type, x, y, magnet) { this.items.push({x, y, vy: -2.2, k: type, m: magnet ? 1 : 0}); } + starItems(awardScore) { // TurnAllBulletsIntoPoints / DespawnBullets (S15) + let s = 2000, total = 0; + for (const q of this.bullets) { this.spawnItem(ITEM.STAR, q.x, q.y, true); if (awardScore) { total += s; s = Math.min(12800, s + 10); } } + this.bullets = []; this.lasers = []; + if (total) this.addScore(total); + return total; + } + // ExInsStage56Func4 with arg >= 2 (S14): medium-or-larger bullets that are not green yet turn green with probability 1/4 and take + // a new heading at their own speed, oldest first, at most 14 (Easy/Normal) or 52 (Hard/Lunatic). Further than 128 px from the + // player the heading is random in [pi/4, pi] on Easy/Normal and anywhere on Hard/Lunatic; closer, effectively random. + redirect(extra) { + let left = this.D <= 1 ? 14 : 52, n = 0; + const p = this.player; + for (const q of this.bullets) { + if (left <= 0) break; + if (BSIZE[q.k] < 5 || q.c === C.GREEN) continue; + if (Math.floor(this.rnd() * 4) !== 0) continue; + const far = Math.hypot(q.x - p.x, q.y - p.y) > 128; + const a = far ? (this.D <= 1 ? this.rnd() * (3 * PI / 4) + PI / 4 : this.rnd() * TAU) : Math.atan2(q.y - p.y, q.x - p.x) + PI / 2 + this.rnd() * TAU; + const s = q.s || Math.hypot(q.vx, q.vy) || 2; + q.c = C.GREEN; q.vx = Math.cos(a) * s; q.vy = Math.sin(a) * s; q.a = a; + q.st = undefined; q.gt = undefined; q.gm = undefined; q.ga = undefined; q.gs = undefined; q.ta = undefined; q.tw = undefined; q.am = undefined; q.ax = undefined; q.ay = undefined; + if (extra) Object.assign(q, extra); + left--; n++; + } + this.ev('redirect'); + return n; + } + // ---------- player ---------- + hitPlayer() { // Player::Die + const p = this.player; + p.state = 'dead'; p.deadT = 0; p.window = 6; p.fireT = -1; p.hits++; + this.capture = false; this.hitFx = 32; this.ev('hit'); + for (const l of this.lasers) if (l.t < l.wn + l.on) l.t = l.wn + l.on; + } + finalizeMiss() { + const p = this.player; p.misses++; p.pc = 0; this.subSubrank(1600); this.ev('miss'); + const drops = p.lives > 1 ? [ITEM.BIG, ITEM.POWER, ITEM.POWER, ITEM.POWER, ITEM.POWER, ITEM.POWER] : [ITEM.FULL, ITEM.FULL, ITEM.FULL, ITEM.FULL, ITEM.FULL]; + // items glide to random points of the upper field; within +-144 px of the player in the wide arena (C18B) + for (const k of drops) this.items.push({x: p.x, y: p.y, vy: 0, k, m: 0, np: 1, gx: p.x, gy: p.y, tx: N.clamp(p.x + (this.rnd() - 0.5) * 288, 48, W - 48), ty: this.rnd() * 192 - 64, gt: 0}); + p.power = p.lives > 1 ? Math.max(0, p.power - 16) : 0; + } + startBomb() { + const p = this.player, type = this.shotType; + p.bombs--; p.bombsUsed++; this.subSubrank(200); this.capture = false; + if (this.spell) this.usedBomb = true; + p.inv = type === 'A' ? 360 : 200; + this.bomb = {k: type, t: 0, dur: type === 'A' ? 300 : 140, x: p.x, y: p.y, orbs: []}; + for (const it of this.items) it.m = 1; // MagnetAllItems + this.shake = type === 'B' ? 60 : 0; this.flash = 12; this.ev('bomb'); + } + updatePlayer(keys, pressed) { + const p = this.player, bombKey = pressed.has('K') || pressed.has('RMB'); + if (p.state === 'dead') { + if (bombKey && p.window > 0 && p.bombs > 0 && !this.bomb) { p.state = 'alive'; p.window = 0; this.startBomb(); this.ev('deathbomb'); } + else { + p.deadT++; + if (p.window > 0 && --p.window === 0) this.finalizeMiss(); + if (p.deadT >= 30) { + p.lives--; + if (p.lives <= 0) { p.lives = 0; this.outcome = 'loss'; this.ev('game_over'); return; } + p.state = 'spawning'; p.spawnT = 30; p.x = SPAWN.x; p.y = SPAWN.y; p.bombs = 3; p.grace = 90; p.fireT = -1; + } + return; + } + } else if (bombKey && p.state === 'alive' && p.bombs > 0 && !this.bomb) this.startBomb(); + if (p.state === 'spawning' && --p.spawnT <= 0) { p.state = 'alive'; p.inv = 240; } + else if (p.state === 'alive' && p.inv > 0) p.inv--; + // movement (Player.cpp: up before down, right overrides left, diagonal speed/sqrt2 per axis) + const focus = keys.has('Shift'); + let dx = 0, dy = 0; + if (keys.has('W')) dy = -1; else if (keys.has('S')) dy = 1; + if (keys.has('A')) dx = -1; + if (keys.has('D')) dx = 1; + const speed = focus ? 2 : 4, s = dx && dy ? speed / Math.SQRT2 : speed; + p.x = N.clamp(p.x + dx * s, AREA.x0, AREA.x1); p.y = N.clamp(p.y + dy * s, AREA.y0, AREA.y1); + p.mx = dx; p.foc = focus ? 1 : 0; p.focus = focus ? Math.min(8, p.focus + 1) : Math.max(0, p.focus - 1); + // shot volley timer (30-frame cycle that finishes after release) + const shooting = keys.has('J') || keys.has('LMB'); + if (p.fireT < 0 && shooting) p.fireT = 0; + if (p.fireT >= 0) { this.fire(p.fireT); if (++p.fireT >= 30) p.fireT = -1; } + } + orbs() { + const p = this.player, f = p.focus / 8, ox = 24 - 16 * f, oy = -32 * f; + return [{x: p.x - ox, y: p.y + oy}, {x: p.x + ox, y: p.y + oy}]; + } + fire(timer) { + const p = this.player, table = SHOT[this.shotType]; + let tier = 0; while (tier < table.length - 1 && p.power >= table[tier][0]) tier++; + const rows = table[tier][1], orbs = this.orbs(); + for (const r of rows) { + if (timer % r[0] !== r[1]) continue; + const o = r[9] === 0 ? p : orbs[r[9] - 1], a = r[6] * PI / 180; + this.shots.push({x: o.x + r[2], y: o.y + r[3], vx: Math.cos(a) * r[7], vy: Math.sin(a) * r[7], s: r[7], k: r[10], w: r[4], h: r[5], d: r[8], t: 0}); + } + } + graze(x, y) { // CheckGraze (S08): score always, counters skipped during bombs + const p = this.player; this.addScore(500); this.addSubrank(6); this.ev('graze'); + if (!this.bomb) { if (p.graze < 999999) p.graze++; if (p.grazeStage < 9999) p.grazeStage++; } + } + // ---------- boss ---------- + // sub.bat (C47): not interactable at all; sub.inv (C47): the attack segments of Remilia's non-spell 4 take no damage. Both stay undefined outside those attacks. + targetable() { return this.intro === 0 && !this.defeat && this.boss.y > -16 && !(this.sub.bat > 0); } + damageable() { return this.phase >= 0 && !this.trans && !this.intro && !this.defeat && !this.sub.inv && !(this.sub.bat > 0); } + // positionOfLastEnemyHit (C34): starting from "no target", the boss (when targetable) and then every interactable fairy in spawn + // order replace the target if it is strictly higher on screen, so the lowest enemy wins. Returns the enemy object itself (or null): + // with no fairy on the field this is this.boss, exactly the @5 target. + homingTarget() { + let t = this.targetable() ? this.boss : null; + for (const f of this.fams) if (f.hp !== undefined && fairyIn(f) && (!t || t.y < f.y)) t = f; + return t; + } + startPhase(i) { + while (i < this.phases.length) { + const id = this.phases[i]; + if (PHASES[id].easyTimeoutOnly && this.D === 0 && !this.timedOut.includes(this.phases[i - 1])) { this.cleared += this.lifeOf[i]; i++; continue; } + break; + } + if (i >= this.phases.length) return this.bossDefeated(); + const id = this.phases[i], ph = PHASES[id]; + this.phase = i; this.phaseId = id; this.phaseT = 0; this.clock = 0; this.timer = this.timeOf[i]; this.phaseHp = this.phaseMax = this.lifeOf[i]; + this.spell = ph.spell; this.capture = ph.spell; this.usedBomb = false; this.sub = {}; this.fams = []; this.stop = 0; + if (ph.spell) { this.starItems(false); this.declared++; this.cutin = 110; this.ev('spell_start'); } + else this.ev('phase_start'); + } + endPhase(timeout) { + const ph = PHASES[this.phaseId], b = this.boss; + this.stop = 0; this.fams = []; + if (timeout) this.timedOut.push(this.phaseId); + if (timeout) { this.capture = false; this.bullets = []; this.lasers = []; } // RemoveAllBullets(0): no items, no score (S16) + if (ph.spell) { + this.starItems(true); + if (this.capture && !timeout) { + const base = ph.base || BOSS[this.kind].base, secs = Math.floor((this.timer - this.clock) / 60), bonus = base + Math.floor(base * secs / 10); + this.addScore(bonus); this.captures++; this.msg = {k: 'capture', t: 150, v: bonus}; this.ev('spell_capture'); + } else { this.msg = {k: 'failed', t: 110, v: 0}; this.ev(timeout ? 'spell_timeout' : 'spell_failed'); } + } else { if (!timeout) this.starItems(false); else this.ev('phase_timeout'); } + this.cleared += this.phaseMax; this.spell = false; this.capture = false; this.ev('phase_end'); + const drops = ph.spell ? [1, 1, 1, 1, 1, 1, 0, 0, 0, 0] : [0, 0, 0, 0, 0, 0, 1, 1, 1, 1]; // approximated drop table + for (const k of drops) this.spawnItem(k, b.x + (this.rnd() - 0.5) * 96, b.y + (this.rnd() - 0.6) * 48, false); + if (this.phase + 1 >= this.phases.length) return this.bossDefeated(); + this.trans = TRANSITION; this.moveBoss(CX, 112, 60); + } + bossDefeated() { + this.phase = this.phases.length; this.phaseId = null; this.defeat = DEFEAT; this.bullets = []; this.lasers = []; this.fams = []; this.stop = 0; + this.cleared = this.bossMax; this.flash = 30; this.shake = 30; + for (const it of this.items) it.m = 1; + this.ev('boss_defeated'); + } + damageBoss(raw, byBomb) { // EnemyManager damage block (S16) + if (!raw || !this.damageable()) return; + let d = Math.min(70, raw); + this.addScore(Math.floor(d / 5) * 10); + if (this.spell) { + if (!byBomb) d = d > 7 ? Math.floor(d / 7) : 1; + else if (this.usedBomb) d = d > 3 ? Math.floor(d / 3) : 1; + else d = 0; + } + this.phaseHp = Math.max(0, this.phaseHp - d); + } + updateBoss(frozen) { + const b = this.boss; + if (b.mt < b.md) { b.mt++; const u = b.mt / b.md, e = b.lin ? u : u * u * (3 - 2 * u); b.x = b.fx + (b.tx - b.fx) * e; b.y = b.fy + (b.ty - b.fy) * e; } + if (this.intro > 0) { if (--this.intro === 0) this.startPhase(0); return; } + if (this.defeat > 0) { if (--this.defeat === 0) { this.outcome = 'win'; this.ev('win'); } return; } + if (this.trans > 0) { if (--this.trans === 0) this.startPhase(this.phase + 1); return; } + if (this.phaseId) { + // ExInsHandleBatTransformation's shape (C47): uninteractable with a bomb on the field and for 60 frames after it + if (PHASES[this.phaseId].bat) { if (this.bomb) this.sub.bat = 60; else if (this.sub.bat > 0) this.sub.bat--; } + const start = this.spell ? 40 : 16, lt = this.phaseT - start; + if (lt >= 0) PATTERN[this.phaseId].call(this, lt, this.sub, b, this.D); + this.phaseT++; + if (!frozen) this.clock++; // the spell clock (phaseTimer) stands still while time is stopped (S16) + } + } + // ---------- bomb ---------- + updateBomb() { + const B = this.bomb, p = this.player; if (!B) return 0; + const boxes = []; + let dmg = 0; + const tgt = this.homingTarget() || p, fairies = this.fams.length ? this.fams.filter(f => f.hp > 0 && fairyIn(f)) : EMPTY_A; + // bomb regions damage every fairy they overlap too (C33); the damage is applied with the fairy's shot damage in updateFairies + const hitF = (x, y, hw, hh, v) => { let n = 0; for (const f of fairies) if (Math.abs(f.x - x) < hw + FAIRY_HALF && Math.abs(f.y - y) < hh + FAIRY_HALF) { f.bd += v; n += v; } return n; }; + if (B.k === 'A') { // BombReimuACalc (S12) + if (B.t === 0) boxes.push([p.x, p.y, 128]); + if (B.t >= 60 && B.t < 180 && B.t % 16 === 0) { + const i = Math.floor((B.t - 60) / 16); + if (i !== 0) { const a = this.rnd() * TAU - PI; B.orbs.push({x: p.x, y: p.y, vx: Math.cos(a) * 4, vy: Math.sin(a) * 4, s: 4, st: 0, tot: 0, c: i - 1}); } + } + for (const o of B.orbs) { + if (o.st === 0) { + let vx = tgt.x - o.x, vy = tgt.y - o.y, len = Math.hypot(vx, vy) / (o.s / 8); + if (len < 1) len = 1; + vx = vx / len + o.vx; vy = vy / len + o.vy; + const l = Math.hypot(vx, vy) || 1; o.s = N.clamp(l, 1, 10); o.vx = vx / l * o.s; o.vy = vy / l * o.s; + o.x += o.vx; o.y += o.vy; + boxes.push([o.x, o.y, 24]); + if (this.damageable() && Math.abs(o.x - this.boss.x) < 24 + BOSS_HALF && Math.abs(o.y - this.boss.y) < 24 + BOSS_HALF) { dmg += 8; o.tot += 8; } + if (fairies.length) o.tot += hitF(o.x, o.y, 24, 24, 8); + if (o.tot >= 100 || B.t >= B.dur - 30) { + o.st = 1; boxes.push([o.x, o.y, 128]); this.shake = Math.max(this.shake, 16); this.ev('bomb_burst'); + if (this.damageable() && Math.abs(o.x - this.boss.x) < 128 + BOSS_HALF && Math.abs(o.y - this.boss.y) < 128 + BOSS_HALF) dmg += 200; + if (fairies.length) hitF(o.x, o.y, 128, 128, 200); + } + } else { o.st++; o.x += o.vx; o.y += o.vy; if (o.st < 30) boxes.push([o.x, o.y, 64]); } + } + B.orbs = B.orbs.filter(o => o.st < 30); + } else { // BombReimuBCalc: two vertical and two horizontal 62 px bars through the bombing point + boxes.push([B.x, H / 2, 31, H / 2], [W / 2, B.y, W / 2, 31]); + if (B.t % 2 === 1 && this.damageable()) { + const b = this.boss; + if (Math.abs(b.x - B.x) < 31 + BOSS_HALF) dmg += 16; // two stacked vertical bars x 8 + if (Math.abs(b.y - B.y) < 31 + BOSS_HALF) dmg += 16; + } + if (B.t % 2 === 1 && fairies.length) { hitF(B.x, H / 2, 31, H / 2, 16); hitF(W / 2, B.y, W / 2, 31, 16); } + if (B.t === 60) this.shake = 80; + } + // a fairy whose contact box overlaps a bomb region this frame grazes instead of colliding (CheckCollision GRAZE, C33) + for (const f of fairies) for (const bx of boxes) { const hh = bx.length > 3 ? bx[3] : bx[2]; if (Math.abs(f.x - bx[0]) < bx[2] + FAIRY_HALF / 1.5 && Math.abs(f.y - bx[1]) < hh + FAIRY_HALF / 1.5) { f.gz = 1; break; } } + if (boxes.length && this.bullets.length) { + const keep = []; + for (const q of this.bullets) { + let hit = false; + for (const bx of boxes) { const hw = bx[2], hh = bx.length > 3 ? bx[3] : bx[2]; if (Math.abs(q.x - bx[0]) < hw && Math.abs(q.y - bx[1]) < hh) { hit = true; break; } } + if (hit) this.spawnItem(ITEM.STAR, q.x, q.y, true); else keep.push(q); + } + this.bullets = keep; + if (this.lasers.length) this.lasers = this.lasers.filter(l => !boxes.some(bx => Math.hypot(l.x - bx[0], l.y - bx[1]) < bx[2])); + } + if (++B.t >= B.dur) { this.bomb = null; this.ev('bomb_end'); } + return dmg; + } + // ---------- per-tick ---------- + // Time stop (S08 S15 S16): while stopped the player, its shots and bomb, enemy bullets, lasers, items and the spell clock do + // not update; the boss, its script and familiars keep running, and frozen shots that touch the boss still damage it. + update(keys, pressed) { + if (this.outcome) return; + const frozen = this.stop > 0; + if (frozen) this.stop--; + const p = this.player; + if (!frozen) { + // Q/E: shot type at any time except during a bomb (@4 deviation from the character select, meeting request C25) + if ((pressed.has('Q') || pressed.has('E')) && !this.bomb && p.state !== 'dead') { this.shotType = this.shotType === 'A' ? 'B' : 'A'; this.swapT = 70; this.ev('shot_type'); } + this.updatePlayer(keys, pressed); + if (this.outcome) return; + } + this.updateBoss(frozen); + // player shots vs boss (box overlap, one hit per shot, damage /3 during a bomb) + let shotDmg = 0; + const b = this.boss, tgt = this.targetable(), live = [], ht = this.homingTarget(), fams = this.fams; + for (const s of this.shots) { + if (!frozen) { + if (s.k === 1) { // homing amulet (Player.cpp), toward positionOfLastEnemyHit (C34) + if (ht && s.t < 40) { + let vx = ht.x - s.x, vy = ht.y - s.y, len = Math.hypot(vx, vy) / (s.s / 4); + if (len < 1) len = 1; + vx = vx / len + s.vx; vy = vy / len + s.vy; + const l = Math.hypot(vx, vy) || 1; s.s = N.clamp(l, 1, 10); s.vx = vx / l * s.s; s.vy = vy / l * s.s; + } else if (s.s < 10) { const l = s.s || 1; s.s = Math.min(10, s.s + 1 / 3); s.vx = s.vx / l * s.s; s.vy = s.vy / l * s.s; } + } + s.x += s.vx; s.y += s.vy; s.t++; + } + if (tgt && Math.abs(s.x - b.x) < s.w / 2 + BOSS_HALF && Math.abs(s.y - b.y) < s.h / 2 + BOSS_HALF) { + if (this.damageable()) { const dd = this.bomb ? Math.max(1, Math.floor(s.d / 3)) : s.d; shotDmg += dd; } + continue; + } + // a shot that hits is consumed by the first enemy processed: the boss, then the fairies in spawn order (C33) + let used = false; + for (const f of fams) { + if (f.hp === undefined || f.hp <= 0 || !fairyIn(f) || Math.abs(s.x - f.x) >= s.w / 2 + FAIRY_HALF || Math.abs(s.y - f.y) >= s.h / 2 + FAIRY_HALF) continue; + f.sd += this.bomb ? Math.max(1, Math.floor(s.d / 3)) : s.d; used = true; break; + } + if (used) continue; + if (s.y > -24 && s.y < H + 24 && s.x > -24 && s.x < W + 24) live.push(s); + } + this.shots = live; + const bombDmg = frozen ? 0 : this.updateBomb(); + this.damageBoss(shotDmg + bombDmg, bombDmg > 0); + this.bodyContact(); + if (fams.length) this.updateFairies(); + if (!frozen) { this.updateBullets(); this.updateLasers(); this.updateItems(); } + // phase end: life depleted or timer expired + if (this.phaseId && !this.trans && !this.defeat) { + if (this.phaseHp <= 0) this.endPhase(false); + else if (this.clock >= this.timer) this.endPhase(true); + } + if (this.cutin > 0) this.cutin--; if (this.shake > 0) this.shake--; if (this.flash > 0) this.flash--; if (this.hitFx > 0) this.hitFx--; if (this.swapT > 0) this.swapT--; + if (this.msg && --this.msg.t <= 0) this.msg = null; + for (const q of this.pops) q.t++; + if (this.pops.length && this.pops[0].t > 50) this.pops = this.pops.filter(q => q.t <= 50); + } + // Body contact (C17, S16 EnemyManager_OnUpdate + S08 Player::CheckCollision): every collidable, interactable enemy tests the + // player against its hitbox / 1.5. CheckCollision kills only a player in the ALIVE state (invulnerability after a respawn or + // during a bomb is its own state there, so it is spared), and the `!isBoss` term only exempts a boss from the enemy's own + // -10 life, so a boss kills on contact too. Checked after the damage step, as there, and also during a time stop (the enemy + // update is not frozen). Boss box 32x32 (C23 approximation) -> contact half-size 10.67 px; no graze for bodies. + bodyContact() { + const p = this.player, b = this.boss; + if (p.state !== 'alive' || p.inv > 0 || !this.targetable()) return; + const r = BOSS_HALF / 1.5 + PLAYER_HALF; + if (Math.abs(p.x - b.x) < r && Math.abs(p.y - b.y) < r) { this.hitPlayer(); this.ev('contact'); } + } + // Fairies after the boss (C33, EnemyManager_OnUpdate block order): body contact, then this frame's shot and bomb damage, then + // death. Contact box = hitbox / 1.5; an overlap costs the fairy 10 life whatever the player's state (it only kills an ALIVE, + // non-invulnerable player) unless the fairy touches a bomb region this frame (GRAZE). Damage: cap 70, score (d/5)*10, the + // spell-card divisors as for the boss. Death: 100 points and one point item (itemDrop unread, engineering choice). + updateFairies() { + const p = this.player, r = FAIRY_HALF / 1.5 + PLAYER_HALF, keep = []; + for (const f of this.fams) { + if (f.hp === undefined) { keep.push(f); continue; } + if (fairyIn(f)) { + if (!f.gz && Math.abs(p.x - f.x) < r && Math.abs(p.y - f.y) < r) { + if (p.state === 'alive' && p.inv === 0) { this.hitPlayer(); this.ev('contact'); } + f.hp -= 10; + } + const raw = f.sd + f.bd; + if (raw) { + let d = Math.min(70, raw); + this.addScore(Math.floor(d / 5) * 10); + if (this.spell) { + if (!f.bd) d = d > 7 ? Math.floor(d / 7) : 1; + else if (this.usedBomb) d = d > 3 ? Math.floor(d / 3) : 1; + else d = 0; + } + f.hp -= d; + } + } + f.sd = 0; f.bd = 0; f.gz = 0; + if (f.hp <= 0) { this.addScore(100); this.spawnItem(ITEM.POINT, f.x, f.y, false); this.ev('fairy_down'); continue; } + if (f.t > 60 && (f.x < -32 || f.x > W + 32 || f.y < -48 || f.y > H + 32)) continue; // flew off the field + keep.push(f); + } + this.fams = keep; + } + // EX_BOUNCE_TLR (bm 1) / TBLR (bm 2) (S15): checked before the move; side walls reflect the angle (-a - pi), the top (and for + // TBLR the floor) negate it; the speed is kept, every bounce counts down and the flag clears at the limit. + bounce(q) { + const ox = (q.x < 0 && q.vx < 0) || (q.x > W && q.vx > 0), ot = q.y < 0 && q.vy < 0, ob = q.bm === 2 && q.y > H && q.vy > 0; + if (!ox && !ot && !ob) return; + let a = Math.atan2(q.vy, q.vx); + if (ox) a = -a - PI; + if (ot || ob) a = -a; + const s = Math.hypot(q.vx, q.vy); + q.vx = Math.cos(a) * s; q.vy = Math.sin(a) * s; q.a = a; + if (--q.bn <= 0) { q.bn = undefined; q.bm = undefined; } + } + updateBullets() { + const p = this.player; + if (p.grace > 0) { p.grace--; this.bullets = []; this.lasers = []; return; } + const canGraze = p.state === 'alive', hitOk = canGraze && p.inv === 0, keep = []; + for (const q of this.bullets) { + if (q.ta !== undefined) { // turn toward a target heading + const a = Math.atan2(q.vy, q.vx), d = angDiff(q.ta, a), s = Math.hypot(q.vx, q.vy); + const na = Math.abs(d) <= q.tw ? q.ta : a + Math.sign(d) * q.tw; + q.vx = Math.cos(na) * s; q.vy = Math.sin(na) * s; + if (na === q.ta) { q.ta = undefined; q.tw = undefined; } + } + if (q.w) { + if (q.wt > 0) { const c = Math.cos(q.w), s = Math.sin(q.w), vx = q.vx * c - q.vy * s; q.vy = q.vx * s + q.vy * c; q.vx = vx; q.wt--; } + else { q.w = undefined; q.wt = undefined; } + } + if (q.st) { // decelerate linearly to rest at st, relaunch at gt + if (q.t < q.st) { const f = (q.st - q.t - 1) / (q.st - q.t); q.vx *= f; q.vy *= f; } + else if (q.t >= q.gt) { + const a = q.gm === 1 ? this.aim(q.x, q.y) + (q.ga || 0) : q.gm === 2 ? q.a + (q.ga || 0) : q.ga; + q.vx = Math.cos(a) * q.gs; q.vy = Math.sin(a) * q.gs; q.a = a; + q.st = undefined; q.gt = undefined; q.gm = undefined; q.ga = undefined; q.gs = undefined; + } + } + if (q.am) { q.vx += q.ax; q.vy += q.ay; if (--q.am <= 0) { q.ax = undefined; q.ay = undefined; q.am = undefined; } } + if (q.bn) this.bounce(q); + q.x += q.vx; q.y += q.vy; q.t++; + const hs = BSIZE[q.k] / 2; + if (q.x < -hs - 8 || q.x > W + hs + 8 || q.y < -hs - 8 || q.y > H + hs + 8) continue; + if (canGraze) { + const dx = Math.abs(q.x - p.x), dy = Math.abs(q.y - p.y), hb = hs + PLAYER_HALF; + if (!q.g && dx < hb + GRAZE_PAD && dy < hb + GRAZE_PAD) { q.g = 1; this.graze(q.x, q.y); } + if (hitOk && p.state === 'alive' && dx < hb && dy < hb) { this.hitPlayer(); continue; } + } + keep.push(q); + } + this.bullets = keep; + } + updateLasers() { + if (!this.lasers.length) return; + const p = this.player, keep = []; + for (const l of this.lasers) { + l.t++; + if (l.t >= l.wn + l.on + 16) continue; + if (l.va !== undefined && l.t > l.wn && l.t <= l.wn + l.on) l.a += l.va; // optional sweep (@7, Patchouli); lasers without va never turn + if (l.t > l.wn && l.t <= l.wn + l.on && p.state === 'alive') { + const c = Math.cos(l.a), s = Math.sin(l.a), rx = p.x - l.x, ry = p.y - l.y, along = rx * c + ry * s, perp = Math.abs(-rx * s + ry * c); + if (along > -PLAYER_HALF && along < l.l + PLAYER_HALF) { + if (perp < l.w / 2 + 48 + PLAYER_HALF && l.t % 12 === 0) this.graze(p.x, p.y); + if (p.inv === 0 && perp < l.w / 2 + PLAYER_HALF) this.hitPlayer(); + } + } + keep.push(l); + } + this.lasers = keep; + } + collect(it) { + const p = this.player; + switch (it.k) { + case ITEM.POWER: case ITEM.BIG: { + const add = it.k === ITEM.BIG ? 8 : 1; + if (p.power < 128) { + const before = p.power; p.power = Math.min(128, p.power + add); this.addScore(10); + if (it.k === ITEM.POWER) p.pc = 0; + if (p.power >= 128) { this.starItems(false); this.msg = {k: 'fullpower', t: 120, v: 0}; this.ev('full_power'); } + else if ([8, 16, 32, 48, 64, 80, 96].some(v => before < v && p.power >= v)) this.ev('power_up'); + } else { p.pc = Math.min(POWER_SCORE.length - 1, p.pc + add); const v = POWER_SCORE[p.pc]; this.addScore(v); this.pop(it.x, it.y, v, v >= 12800); } + if (it.k === ITEM.POWER) this.addSubrank(1); + break; + } + case ITEM.FULL: this.addScore(1000); if (p.power < 128) { p.power = 128; this.starItems(false); this.msg = {k: 'fullpower', t: 120, v: 0}; this.ev('full_power'); } break; + case ITEM.POINT: { + const pv = POINT_VALUE[this.D], v = it.y < 128 ? pv[0] : Math.max(0, Math.floor(pv[1] - (Math.floor(it.y) - 128) * pv[2])); + this.addScore(v); p.points++; this.addSubrank(it.y < 128 ? 30 : 3); this.pop(it.x, it.y, v, it.y < 128); break; + } + case ITEM.BOMB: if (p.bombs < 8) p.bombs++; this.addSubrank(5); break; + case ITEM.LIFE: if (p.lives < 9) p.lives++; this.addSubrank(200); break; + case ITEM.STAR: this.addScore(this.bomb ? 100 : 500 + 10 * Math.floor(p.grazeStage / 3)); break; + } + this.ev('item'); + } + updateItems() { + if (!this.items.length) return; + const p = this.player, poc = p.power >= 128 && p.y < 128 && p.state === 'alive', canGet = p.state !== 'dead', keep = []; + for (const it of this.items) { + if (it.gt !== undefined) { // death drop glides to its target over 60 frames + it.gt++; const u = it.gt / 60; it.x = it.gx + (it.tx - it.gx) * u; it.y = it.gy + (it.ty - it.gy) * u; + if (it.gt >= 60) { it.gt = undefined; it.gx = undefined; it.gy = undefined; it.tx = undefined; it.ty = undefined; it.vy = 0; } + } else if (it.m || (poc && !it.np)) { + it.m = 1; const a = Math.atan2(p.y - it.y, p.x - it.x); it.x += Math.cos(a) * 8; it.y += Math.sin(a) * 8; + } else { it.vy = Math.min(3, it.vy + 0.03); it.y += it.vy; } + if (canGet && Math.abs(it.x - p.x) < 20 && Math.abs(it.y - p.y) < 20) { this.collect(it); continue; } + if (it.y >= H + 16) { this.subSubrank(3); continue; } + keep.push(it); + } + this.items = keep; + } + // Reported boss life (C44, @7): endPhase has already added the finished attack to `cleared`, and during the following + // transition (trans > 0) phaseId still names that attack, so its progress must not be counted a second time (@1-@6 did, + // which dipped boss_hp by one attack for 80 frames). Reporting only; the simulation never reads this. + health() { + const done = this.cleared + (this.phaseId && !this.trans ? this.phaseMax - this.phaseHp : 0); + return [this.player.lives, Math.max(this.lifeMax, this.player.lives), Math.max(0, this.bossMax - done), this.bossMax]; + } + remainingAttacks() { return this.phaseId ? this.phases.length - this.phase - 1 : Math.max(0, this.phases.length - this.phase - 1); } + // ExInsStage6Func7 geometry (C48): two webs of 8 arms 45 deg apart (the second 22.5 deg on and turning the other way), starting 32 px + // out; 3 segments each, every segment starting 112 / 112 / 480 px on from the last and turning 45 deg. + webEach(b, r, fn) { + for (let net = 0; net < 2; net++) for (let arm = 0; arm < 8; arm++) { + let a = (net ? -7 * PI / 8 : -PI) + r + arm * PI / 4, x = b.x + Math.cos(a) * 32, y = b.y + Math.sin(a) * 32; + for (let n = 0; n < 3; n++) { + const len = n < 2 ? 112 : 480; + fn(x, y, a, n, len, net); + x += Math.cos(a) * len; y += Math.sin(a) * len; a += net ? -PI / 4 : PI / 4; + } + } + } + // Func7's beams on the shared laser model (C48): warning 60+16n, then 90-16n on, 16 fading, so all three segments end together; red, width 28, as long as the step up to Normal; cyan, width 20, 440 long above. + webLasers(b, r) { + const w = this.D >= 2 ? 20 : 28, col = this.D >= 2 ? C.CYAN : C.RED; + this.webEach(b, r, (x, y, a, n, len) => { this.laser(x, y, a, this.D >= 2 ? 440 : len, w, 60 + 16 * n, 90 - 16 * n); this.lasers[this.lasers.length - 1].col = col; }); + } + // ExInsStage6Func8 (C48): a still dark-red ball at every live bullet of kind k and colour c. The original's 640-bullet ceiling applies (S44). + dropStill(k, c) { + const n = this.bullets.length; + for (let i = 0; i < n && this.bullets.length < 640; i++) { const q = this.bullets[i]; if (q.k === k && q.c === c && q.x >= 0 && q.x <= W && q.y >= 0 && q.y <= H) this.shoot(q.x, q.y, 0, 0, K.BALL, C.RED); } + } + // ExInsStage6Func9 / Func11 (C48): every still bullet below the large size accelerates at 0.01 for 120 frames, in a swirl (distance to her x pi/256 + one shared angle) or each its own random way. + releaseStill(b, swirl) { + const r = this.rnd() * TAU; + for (const q of this.bullets) { + if (BSIZE[q.k] >= 16 || q.vx !== 0 || q.vy !== 0 || q.am) continue; + const a = swirl ? Math.hypot(q.x - b.x, q.y - b.y) * PI / 256 + r : this.rnd() * TAU; + q.ax = Math.cos(a) * 0.01; q.ay = Math.sin(a) * 0.01; q.am = 120; + } + this.ev('still_release'); + } + hasBullet(k, c) { for (const q of this.bullets) if (q.k === k && q.c === c) return true; return false; } + // ExInsStage5Func5 (S14): one wave of nine daggers 10 deg apart on a 256 px arc laid across the boss->player line; the reference + // point starts halfway to the player and slides back 1/18 per wave, the arc bows to alternate sides; each dagger is an aimed fan + // (1 on Easy/Normal, 3 at pi/6 above) at speed 2, odd waves on Easy/Normal spread -45..+35 deg instead of aiming. + daggerArc(wave, b) { + const p = this.player, dx = p.x - b.x, dy = p.y - b.y, len = Math.hypot(dx, dy) || 1, ux = dx / len, uy = dy / len; + const f = 0.5 - wave * 0.5 / 9, rx = b.x + dx * f, ry = b.y + dy * f, side = wave % 2 ? -1 : 1; + const cx = rx + side * 256 * ux, cy = ry + side * 256 * uy; + let ang = Math.atan2(ry - cy, rx - cx) + PI / 4; + const per = this.D <= 1 ? 1 : 3, spread = wave % 2 === 1 && this.D <= 1; + for (let i = 0; i < 9; i++) { + ang -= PI / 18; + const x = cx + Math.cos(ang) * 256, y = cy + Math.sin(ang) * 256; + if (x < -8 || x > W + 8 || y < -8 || y > H + 8) continue; + const a = this.aim(x, y) + (spread ? (-45 + 10 * i) * PI / 180 : 0); + for (let j = 0; j < per; j++) this.knife(x, y, a + (j - (per - 1) / 2) * PI / 6, 2, C.BLUE); + } + } + } + + // ---------- attack patterns: (t from attack start, sub-state, boss, difficulty 0..3) ---------- + // Geometry is reconstructed (C14/C26). In the 854 px arena, boss relocation spans are 1.75x the 384 px originals (C18B). + const PATTERN = { + r_non1(t, s, b, D) { // aimed sub-patterns, always red first, never repeated back-to-back (S17) + if (s.k === undefined) { s.k = 0; s.t0 = 0; } + const lt = t - s.t0, dur = [96, 72, 112, 84][s.k]; + if (lt < dur) { + if (s.k === 0 && lt % 32 === 0) { + const a = this.aim(b.x, b.y), n = 3 + 2 * D; + for (let i = 0; i < n; i++) for (let j = 0; j < 4 + D; j++) this.shoot(b.x, b.y, a + (i - (n - 1) / 2) * 0.3, this.sp(1.7 + 0.45 * j), K.RICE, C.RED); + } else if (s.k === 1 && lt % 18 === 0) { + const n = 7 + 2 * D, gap = 1.25 / (n - 1), w = lt / 18; + this.fan(b.x, b.y, n, this.aim(b.x, b.y) + (w % 2 ? gap / 2 : -gap / 2), gap, this.sp(2.3 + 0.15 * D), K.BALL, C.GREEN); + } else if (s.k === 2 && lt % 38 === 0) { + const a = this.aim(b.x, b.y); + this.fan(b.x, b.y, 5, a, 0.17, this.sp(3.0), K.BALL, C.RED); + this.ring(b.x, b.y, this.cnt(12 + 6 * D), a, this.sp(1.7), K.RING, C.BLUE); + } else if (s.k === 3 && lt % 21 === 0) { + const n = this.cnt(14 + 6 * D), w = lt / 21; + this.ring(b.x, b.y, n, this.aim(b.x, b.y) + (w % 2 ? PI / n : 0), this.sp(2.0 + 0.15 * D), K.BALL, C.BLUE); + } + } else if (lt === dur) this.moveBoss(CX + (this.rnd() - 0.5) * 280, 88 + this.rnd() * 40, 50); + else if (lt >= dur + 50) { s.k = (s.k + 1 + Math.floor(this.rnd() * 3)) % 4; s.t0 = t; } + }, + r_bird(t, s, b, D) { // alternating aimed wing sweeps of light-blue/blue bullets; relocate between volleys + if (s.t0 === undefined) { s.t0 = 0; s.side = 1; } + const lt = t - s.t0, flaps = 3 + D, fl = 20, n = D ? 14 : 11; + if (lt < flaps * fl) { + const f = Math.floor(lt / fl), ft = lt % fl, side = (f % 2 ? -1 : 1) * s.side; + if (ft === 0) s.a = this.aim(b.x, b.y); + if (ft < n) { + const u = ft / (n - 1), ang = s.a + side * (1.3 - 2.6 * u), v = this.sp(1.8 + 1.5 * Math.sin(PI * u)), col = f % 2 ? C.BLUE : C.CYAN; + this.shoot(b.x, b.y, ang, v, K.RING, col); + if (D >= 2) this.shoot(b.x, b.y, ang, v * 0.72, K.RING, col); + } + } else if (lt === flaps * fl) this.moveBoss(CX + (this.rnd() - 0.5) * 390, 80 + this.rnd() * 60, 56); + else if (lt >= flaps * fl + 60) { s.t0 = t; s.side = -s.side; } + }, + r_non2(t, s, b, D) { // laser+fan first, then yellow two-way rings, green aimed rings, anti-aimed layered fan (S17) + if (s.k === undefined) { s.k = 0; s.t0 = 0; } + const lt = t - s.t0, dur = [112, 84, 72, 80][s.k]; + if (lt < dur) { + if (s.k === 0) { + if (lt === 0) { const a = this.aim(b.x, b.y), n = 2 + D; for (let i = 0; i < n; i++) this.laser(b.x, b.y, a + (i - (n - 1) / 2) * 0.42, 600, 12, 48, 36); } + if (lt === 16 || lt === 40 || lt === 64) this.fan(b.x, b.y, 5 + 2 * D, this.aim(b.x, b.y), 0.15, this.sp(2.6), K.BALL, C.GREEN); + } else if (s.k === 1 && lt % 28 === 0) { + const n = this.cnt(16 + 4 * D), a = this.aim(b.x, b.y); + this.ring(b.x, b.y, n, a, this.sp(2.2), K.RICE, C.YELLOW, {w: 0.004, wt: 120}); + this.ring(b.x, b.y, n, a + PI / n, this.sp(1.6), K.RICE, C.YELLOW, {w: -0.004, wt: 120}); + } else if (s.k === 2 && lt % 16 === 0) { + this.ring(b.x, b.y, this.cnt(18 + 6 * D), this.aim(b.x, b.y), this.sp(2.5), K.BALL, C.GREEN); + } else if (s.k === 3 && lt % 26 === 0) { + const m = 6 + 2 * D, a = this.aim(b.x, b.y), layers = D ? [1.7, 2.3, 2.9] : [1.8, 2.5]; + for (const v of layers) this.fan(b.x, b.y, m, a, 0.2, this.sp(v), K.RICE, C.GREEN); + } + } else if (lt === dur) this.moveBoss(CX + (this.rnd() - 0.5) * 280, 88 + this.rnd() * 40, 50); + else if (lt >= dur + 46) { s.k = (s.k + 1 + Math.floor(this.rnd() * 3)) % 4; s.t0 = t; } + }, + r_demarc(t, s, b, D) { // 3 waves of counter-rotating rings, pause, 3 aimed volleys growing with time + const cyc = D ? 260 : 290, lt = t % cyc; + if (lt === 0 || lt === 30 || lt === 60) { + const n = this.cnt(16 + 8 * D), a0 = this.rnd() * TAU, v = this.sp(1.2 + 0.1 * D); + for (let i = 0; i < n; i++) { + this.shoot(b.x, b.y, a0 + TAU * i / n, v, K.BALL, C.BLUE, {w: 0.0065, wt: 170}); + this.shoot(b.x, b.y, a0 + TAU * (i + 0.5) / n, v, K.BALL, C.RED, {w: -0.0065, wt: 170}); + } + } + if (lt === 130 || lt === 148 || lt === 166) { + const m = (D >= 2 ? 5 : 3) + 2 * Math.min(4, Math.floor(t / 540)); + this.fan(b.x, b.y, m, this.aim(b.x, b.y), 0.14, this.sp(3.2), K.RICE, C.PURPLE); + } + if (lt === 200) this.moveBoss(N.clamp(b.x + (this.rnd() - 0.5) * 160, CX - 126, CX + 126), 96 + this.rnd() * 24, 40); + }, + c_non1(t, s, b, D) { // A: three aimed icicle triangles + aimed rings; B: moving icicle rings redirected at the player (S18) + if (s.k === undefined) { s.k = 0; s.t0 = 0; s.dir = 1; } + const lt = t - s.t0; + if (s.k === 0) { + if (lt === 0 || lt === 28 || lt === 56) { + const w = lt / 28, a = this.aim(b.x, b.y), rows = 5 + D - w, gap = [0.06, 0.1, 0.15][w]; + for (let r = 0; r < rows; r++) for (let i = 0; i <= r; i++) this.shoot(b.x, b.y, a + (i - r / 2) * gap, this.sp(4.0 - r * 0.32), K.KUNAI, C.CYAN); + this.ring(b.x, b.y, this.cnt(10 + 4 * D), a, this.sp(1.6), K.PELLET, C.BLUE); + } + if (lt >= 110) { s.k = 1; s.t0 = t; s.dir = -s.dir; this.moveBoss(CX + s.dir * 168, 104, 90); } + } else { + if (lt < 90 && lt % 18 === 0) { + const n = this.cnt(12 + 4 * D), a0 = this.rnd() * TAU; + for (let i = 0; i < n; i++) this.shoot(b.x, b.y, a0 + TAU * i / n, 2.2, K.SHARD, C.CYAN, {st: 28, gt: 44, gm: 1, gs: this.sp(2.4 + 0.25 * D)}); + if (lt % 36 === 0) this.ring(b.x, b.y, this.cnt(10 + 4 * D), this.aim(b.x, b.y), this.sp(1.8), K.PELLET, C.BLUE); + } + if (lt === 120) this.moveBoss(CX, 104, 60); + if (lt >= 190) { s.k = 0; s.t0 = t; } + } + }, + c_icicle(t, s, b, D) { // side lines of shards that curve down into falling arcs; Normal adds aimed yellow 5-way + if (s.iv === undefined || t % 120 === 0) s.iv = this.iv(D ? 7 : 10); + if (t % s.iv === 0) { + const kn = D ? 4 : 3; + for (const side of [-1, 1]) for (let k = 0; k < kn; k++) { + const th = 0.12 + 0.2 * k, a = side > 0 ? -th : PI + th; + // turn rate 0.010 rad/frame (0.022 in the 384 px lane) so the arcs still reach ~0.7 of the half-width (C18B) + this.shoot(b.x + side * 8, b.y, a, this.sp(1.6 + 0.4 * k), K.SHARD, C.CYAN, {ta: PI / 2, tw: 0.010}); + } + } + if (D >= 1 && t % 56 === 20) this.fan(b.x, b.y, 5, this.aim(b.x, b.y), 0.22, this.sp(2.8), K.BALL, C.YELLOW); + if (t % 180 === 90) this.moveBoss(CX + (this.rnd() - 0.5) * 105, 100 + this.rnd() * 16, 90); + }, + c_hail(t, s, b, D) { // circles of shards stop around Cirno, then each circle leaves along an ordered arc below her + const per = s.per || (s.per = this.iv(D === 3 ? 56 : 70)); + if (t % per === 0) { + s.per = this.iv(D === 3 ? 56 : 70); + const G = D === 3 ? 8 : 6, r0 = this.rnd() * TAU, m = 6; + for (let g = 0; g < G; g++) { + const th = r0 + TAU * g / G, cx = 50 * Math.cos(th), cy = 50 * Math.sin(th), dir = PI / 2 + (g / (G - 1) - 0.5) * 1.7; + for (let j = 0; j < m; j++) { + const ph = TAU * j / m, tx = cx + 14 * Math.cos(ph), ty = cy + 14 * Math.sin(ph), dist = Math.hypot(tx, ty); + this.shoot(b.x, b.y, Math.atan2(ty, tx), 2 * dist / 24, K.SHARD, C.CYAN, {st: 24, gt: 40, gm: 0, ga: dir, gs: this.sp(2.0 + 0.3 * (D - 2))}); + } + } + } + if (t % 240 === 120) this.moveBoss(CX + (this.rnd() - 0.5) * 210, 96 + this.rnd() * 30, 60); + }, + c_non2(t, s, b, D) { // authored (no readable description): rotating kunai arms, then aimed shard bursts + if (s.k === undefined) { s.k = 0; s.t0 = 0; s.rot = this.rnd() * TAU; s.dir = 1; s.iv = this.iv(5); } + const lt = t - s.t0; + if (s.k === 0) { + if (lt < 120 && lt % s.iv === 0) { const A = 3 + D; for (let i = 0; i < A; i++) this.shoot(b.x, b.y, s.rot + TAU * i / A, this.sp(2.1), K.KUNAI, C.CYAN); s.rot += 0.21 * s.dir; } + if (lt === 120) this.moveBoss(CX + (this.rnd() - 0.5) * 280, 92 + this.rnd() * 30, 44); + if (lt >= 160) { s.k = 1; s.t0 = t; } + } else { + if (lt < 80 && lt % 20 === 0) { const a = this.aim(b.x, b.y), n = 8 + 3 * D; for (let i = 0; i < n; i++) this.shoot(b.x, b.y, a + (this.rnd() - 0.5) * 0.9, this.sp(2.0 + this.rnd() * 1.6), K.SHARD, C.BLUE); } + if (lt === 90) this.moveBoss(CX + (this.rnd() - 0.5) * 280, 92 + this.rnd() * 30, 44); + if (lt >= 130) { s.k = 0; s.t0 = t; s.dir = -s.dir; s.iv = this.iv(5); } + } + }, + c_freeze(t, s, b, D) { // random rainbow spray -> freeze white -> aimed blue -> random release (S14) + const cyc = 330, lt = t % cyc; + if (lt === 0) s.iv = this.iv([4, 3, 2, 2][D]); + if (lt < 120 && lt % s.iv === 0) { + const m = D >= 2 ? 3 : 2; + for (let i = 0; i < m; i++) this.shoot(b.x, b.y, this.rnd() * TAU, this.sp(1.2 + this.rnd() * 2.4), K.BALL, RAINBOW[Math.floor(this.rnd() * 7)]); + } + if (lt === 130) { // ExInsCirnoRainbowBallJank mode 0 + for (const q of this.bullets) { q.vx = 0; q.vy = 0; q.c = C.WHITE; q.w = undefined; q.ta = undefined; q.am = undefined; q.st = undefined; } + this.ev('freeze'); + } + if (lt === 150 || lt === 194 || (D >= 1 && lt === 172)) this.fan(b.x, b.y, this.rank >= 20 ? 6 : 5, this.aim(b.x, b.y), 0.2, this.sp(3.0), K.RICE, C.BLUE); + if (lt === 236) { // mode 1: every bullet white, random direction, acceleration 0.01 for 220 frames + for (const q of this.bullets) { const a = this.rnd() * TAU - PI; q.c = C.WHITE; q.ax = Math.cos(a) * 0.01; q.ay = Math.sin(a) * 0.01; q.am = 220; } + this.ev('thaw'); + } + if (lt === 262) this.moveBoss(CX + (this.rnd() - 0.5) * 252, 90 + this.rnd() * 30, 50); + }, + c_blizzard(t, s, b, D) { // shard explosions around an erratically moving Cirno + if (t % 40 === 0) this.moveBoss(CX + (this.rnd() - 0.5) * 448, 64 + this.rnd() * 96, 40); + if (s.iv === undefined || t % 120 === 0) s.iv = this.iv([5, 4, 3, 2][D]); + if (t >= 20 && t % s.iv === 0) { + const r = this.rnd() * 64, th = this.rnd() * TAU, x = b.x + Math.cos(th) * r, y = b.y + Math.sin(th) * r * 0.8, k = 4 + D; + for (let i = 0; i < k; i++) this.shoot(x, y, this.rnd() * TAU, this.sp(1.0 + this.rnd() * 2.0), K.SHARD, [C.CYAN, C.WHITE, C.BLUE][Math.floor(this.rnd() * 3)]); + } + }, + // ---------- Sakuya Izayoi (stage 5) ---------- + s_non1(t, s, b, D) { // wild spray of small bullets + knives, alternating with dagger arcs (S24 NC; arcs = ExInsStage5Func5, S14) + const cyc = 236, lt = t % cyc; + if (lt < 84 && lt % 4 === 0) { + for (let i = 0; i < (D >= 2 ? 3 : 2); i++) this.shoot(b.x, b.y, PI / 2 + (this.rnd() - 0.5) * 2.6, this.sp(1.5 + this.rnd() * 1.8), K.PELLET, i % 2 ? C.RED : C.BLUE); + if (lt % 8 === 0) this.knife(b.x, b.y, PI / 2 + (this.rnd() - 0.5) * 2.2, this.sp(2.1 + this.rnd()), C.BLUE); + } + if (lt === 92) this.moveBoss(CX + (this.rnd() - 0.5) * 300, 92 + this.rnd() * 30, 40); + if (lt >= 140 && lt < 194 && (lt - 140) % 9 === 0) this.daggerArc((lt - 140) / 9, b); + }, + s_corpse(t, s, b, D) { // rice scatter -> time stop: Sakuya moves and lays aimed + parabolic blue knives -> time resumes (S25 S27) + const cyc = 300, lt = t % cyc; + if (lt < 40 && lt % 5 === 0) this.ring(b.x, b.y, this.cnt(D ? 14 : 10), this.rnd() * TAU, this.sp(1.5 + this.rnd() * 0.8), K.RICE, C.RED); + if (lt === 60) { this.timeStop(72); const s2 = b.x < CX ? 1 : -1; this.moveBoss(b.x + s2 * (200 + this.rnd() * 160), 80 + this.rnd() * 70, 68, true); } // she crosses the field at an even pace, laying the curtain + if (lt > 60 && lt <= 128 && lt % (D ? 6 : 8) === 0) { + const a = this.aim(b.x, b.y); + this.knife(b.x, b.y, a, this.sp(2.6), C.BLUE); + for (const side of [-1, 1]) this.knife(b.x, b.y, a + side * 0.55, this.sp(2.1), C.BLUE, {ax: 0, ay: 0.022, am: 150}); + } + }, + s_jack(t, s, b, D) { // downward bubble burst -> time stop: Sakuya travels leaving knives aimed at and around the player (S23) + const cyc = 270, lt = t % cyc, p = this.player; + if (lt === 0) for (let i = 0; i < (D === 3 ? 12 : 9); i++) this.shoot(b.x, b.y, PI / 2 + (this.rnd() - 0.5) * 2.0, this.sp(1.1 + this.rnd() * 1.4), K.BUBBLE, [C.BLUE, C.PURPLE, C.CYAN][i % 3]); + if (lt === 40) { this.timeStop(82); const s2 = b.x < CX ? 1 : -1; this.moveBoss(b.x + s2 * (240 + this.rnd() * 200), 70 + this.rnd() * 90, 78, true); } + if (lt > 40 && lt <= 118 && lt % 4 === 0) { + const k = (lt / 4) % 3, off = [0, -40, 40][k]; + this.knife(b.x, b.y, Math.atan2(p.y - b.y, p.x + off - b.x), this.sp(3.0), k ? C.RED : C.BLUE); + } + }, + s_non2(t, s, b, D) { // four moving magic circles: the blue pair sweeps CCW, the red pair CW; their kunai ricochet twice off + // the top/side walls before leaving through the floor (EX_BOUNCE_TLR, S15); Sakuya adds aimed knife rings (S23 S24) + if (!this.fams.length) for (let i = 0; i < 4; i++) { + const blue = i < 2, side = i % 2 ? 1 : -1, a0 = -PI / 2 + side * (blue ? 0.35 : 0.85); + this.fams.push({x: b.x, y: b.y, ox: side * (blue ? 290 : 140), oy: blue ? 96 : 30, t: 0, c: blue ? C.BLUE : C.RED, a0, a: a0, w: blue ? -0.045 : 0.045}); + } + const pair = Math.floor(t / 96) % 2, lt = t % 96; // blue pair, then red pair, 96 frames each + for (let i = 0; i < 4; i++) { + const f = this.fams[i], u = Math.min(1, f.t / 50), e = u * u * (3 - 2 * u), k = f.t + i * 40; + f.x = b.x + (f.ox + Math.sin(k * 0.02) * 26) * e; f.y = b.y + (f.oy + Math.cos(k * 0.025) * 16) * e; f.t++; + if ((i < 2 ? 0 : 1) !== pair || f.t <= 40) continue; + if (lt === 0) f.a = f.a0; + // a circle that has drifted off the playfield cannot fire (S23) + if (lt < 72 && lt % (D >= 2 ? 4 : 6) === 0 && f.x > 0 && f.x < W && f.y > 0 && f.y < H) { + this.shoot(f.x, f.y, f.a, this.sp(2.3 + 0.2 * D), K.KUNAI, f.c, {bn: 2, bm: 1}); f.a += f.w; + } + } + if (t % 70 === 50) this.ring(b.x, b.y, this.cnt(12 + 4 * D), this.aim(b.x, b.y), this.sp(2.2), K.KNIFE, C.BLUE, {s: 2.2}); + if (t % 300 === 280) this.moveBoss(CX + (this.rnd() - 0.5) * 200, 96 + this.rnd() * 24, 50); + }, + s_luna(t, s, b, D) { // fixed rice ripples -> time stop: lanes of blue knives toward the player, some turn green (ExInsStage56Func4) -> resume (S25 S26) + const cyc = 320, lt = t % cyc, p = this.player; + if (lt === 0 || lt === 12 || (D && lt === 24)) { const n = D ? 20 : 16; this.ring(b.x, b.y, n, PI / 2 + (lt / 12) * PI / n, this.sp(1.3 + lt / 40), K.RICE, C.YELLOW); } + if (lt === 50) { this.timeStop(96); s.a = this.aim(b.x, b.y); s.dist = Math.hypot(p.x - b.x, p.y - b.y); } + if (lt > 50 && lt <= 100 && lt % 5 === 0) { + const k = (lt - 55) / 5, lanes = D ? [-0.5, -0.25, 0, 0.25, 0.5] : [-0.34, 0, 0.34], r = 50 + k * Math.max(10, s.dist - 120) / 9; + for (const o of lanes) { const x = b.x + Math.cos(s.a + o) * r, y = b.y + Math.sin(s.a + o) * r; this.knife(x, y, this.aim(x, y), this.sp(2.2), C.BLUE); } + } + if (lt === 112) this.redirect(); + if (lt === 118) this.moveBoss(CX + (this.rnd() - 0.5) * 360, 80 + this.rnd() * 60, 40); + }, + s_world(t, s, b, D) { // rice rings -> time stop: daggers appear around the player (further away the closer she is to Sakuya), many turn green -> resume (S25 S26) + const cyc = 300, lt = t % cyc, p = this.player; + if (lt === 0 || lt === 10 || lt === 20) this.ring(b.x, b.y, this.cnt(24), this.rnd() * TAU, this.sp(1.6 + lt / 20), K.RICE, C.YELLOW); + if (lt === 40) this.timeStop(96); + if (lt > 40 && lt <= 110 && lt % 2 === 0) { + const dist = Math.hypot(p.x - b.x, p.y - b.y), r = 64 + Math.max(0, 300 - dist) * 0.4 + this.rnd() * 40, a = this.rnd() * TAU; + const x = p.x + Math.cos(a) * r, y = p.y + Math.sin(a) * r; + if (x > 0 && x < W && y > 0 && y < H) this.knife(x, y, this.aim(x, y), this.sp(2.3), C.BLUE); + } + if (lt === 120) this.redirect(); + if (lt === 124) this.moveBoss(CX + (this.rnd() - 0.5) * 420, 80 + this.rnd() * 60, 40); + }, + s_non3(t, s, b, D) { // blue knives from above alternate with red knives from the diagonals; nothing is aimed (S24 NC) + const cyc = 120, lt = t % cyc, wave = Math.floor(t / cyc); + if (lt < 36 && lt % 6 === 0) { + if (wave % 2 === 0) { + const n = this.cnt(D >= 2 ? 11 : D ? 9 : 7); + for (let i = 0; i < n; i++) { const x = (i + 0.5 + (this.rnd() - 0.5) * 0.6) * W / n; this.knife(x, -6, PI / 2 + (this.rnd() - 0.5) * 0.3, this.sp(2.0 + this.rnd() * 0.8), C.BLUE); } + } else { + for (const side of [-1, 1]) for (let i = 0; i < (D >= 2 ? 5 : D ? 4 : 3); i++) { + const x = side < 0 ? -6 : W + 6, y = 20 + this.rnd() * 140, a = side < 0 ? 0.45 + this.rnd() * 0.5 : PI - 0.45 - this.rnd() * 0.5; + this.knife(x, y, a, this.sp(2.4 + this.rnd() * 0.6), C.RED); + } + } + } + if (lt === 80) this.moveBoss(CX + (this.rnd() - 0.5) * 300, 90 + this.rnd() * 30, 40); + }, + s_doll(t, s, b, D) { // slow aimed 4-way blue then red knives -> time stop -> some turn into scattered green knives that ricochet once (S24 S26) + const cyc = 240, lt = t % cyc, vol = D ? 3 : 2; + if (lt < vol * 10 && lt % 10 === 0) this.fan(b.x, b.y, 4, this.aim(b.x, b.y), D ? 0.22 : 0.3, this.sp(1.6 + lt / 60), K.KNIFE, C.BLUE, {s: 2}); + if (lt >= 30 && lt < 30 + vol * 10 && lt % 10 === 0) this.fan(b.x, b.y, 4, this.aim(b.x, b.y) + 0.11, D ? 0.22 : 0.3, this.sp(1.8 + (lt - 30) / 60), K.KNIFE, C.RED, {s: 2.2}); + if (lt === 76) this.timeStop(60); + if (lt === 100) this.redirect({bn: 1, bm: 1}); + if (lt === 108) this.moveBoss(CX + (this.rnd() - 0.5) * 360, 84 + this.rnd() * 50, 36); + }, + s_killing(t, s, b, D) { // knife rings around Sakuya: blue come to rest, red stop and re-aim; in the stop she moves and some turn green (S23) + const cyc = 260, lt = t % cyc; + if (lt < 40 && lt % 8 === 0) { + const n = this.cnt(D === 3 ? 24 : 18), red = lt >= 24, a0 = this.rnd() * TAU, v = this.sp(red ? 3.0 : 2.4); + for (let i = 0; i < n; i++) this.knife(b.x, b.y, a0 + TAU * i / n, v, red ? C.RED : C.BLUE, red ? {st: 30, gt: 44, gm: 1, gs: v} : {st: 34, gt: 214, gm: 2, ga: 0, gs: 1.6}); + } + if (lt === 56) { this.timeStop(70); this.moveBoss(CX + (this.rnd() - 0.5) * 460, 80 + this.rnd() * 80, 60); } + if (lt === 100) this.redirect({bn: 1, bm: 2}); + }, + // ---------- Hong Meiling (stage 3) ---------- + // Geometry from community text only (C37, approximation); the only source numbers are the starting ways of non-spell 1 + // (4/5/7/10) and the ways of non-spell 3 (16/24/35/42). Fairies are ordinary enemies (C33/C38). + m_non1(t, s, b, D) { // red player-dependent rotating rings: every shot re-aims at the player, the ring turns, ways grow per wave + const cyc = 96, lt = t % cyc, wave = Math.floor(t / cyc); + if (lt === 0) s.dir = wave % 2 ? -1 : 1; + if (lt < 30 && lt % 3 === 0) { + const n = [4, 5, 7, 10][D] + Math.min(6, wave), rot = s.dir * (lt / 3) * 0.11; + this.ring(b.x, b.y, n, this.aim(b.x, b.y) + rot, this.sp(2.0 + 0.1 * D), K.RICE, C.RED); + } + if (lt === 40 && D >= 1) this.fan(b.x, b.y, 3 + D, this.aim(b.x, b.y), 0.16, this.sp(2.8), K.BALL, C.PINK); + if (lt === 60 && wave % 2 === 1) this.moveBoss(CX + (this.rnd() - 0.5) * 280, 96 + this.rnd() * 30, 36); + }, + m_chime(t, s, b, D) { // fixed-angle rainbow bullets, nothing aimed or random; she sinks slowly, the gap right below her is the safe spot + const cyc = 540, lt = t % cyc; + if (lt === 0) this.moveBoss(CX, 70, 50); + if (lt === 60) this.moveBoss(CX, 196, 440, true); + const iv = [9, 7, 6, 5][D], sh = (this.rank - 16) * 0.004; // rank shifts the angles slightly (C37) + if (lt >= 40 && lt % iv === 0) { + const k = Math.floor(lt / iv) % 7, v = this.sp(1.5 + 0.12 * k); + for (const side of [-1, 1]) { + // purple/blue rows lean to one side, orange/red to the other, so the colours ask for a nudge (C37) + const a = PI / 2 + side * (0.30 + 0.16 * k + 0.10 * Math.sin(lt * 0.035 + k)) + (k - 3) * 0.02 + sh; + this.shoot(b.x, b.y, a, v, K.BALL, RAINBOW[k]); + if (D >= 2) this.shoot(b.x, b.y, a + side * 0.07, v * 0.85, K.BALL, RAINBOW[k]); + } + } + }, + m_non2(t, s, b, D) { // three random blue sub-patterns (around her / above her / a line) + fairy squads with aimed kunai lines (C37 C38) + if (s.k === undefined) { s.k = Math.floor(this.rnd() * 3); s.t0 = 0; s.sq = 0; } + const lt = t - s.t0; + if (lt < 90) { + if (s.k === 0 && lt % 18 === 0) { + const n = this.cnt(14 + 4 * D), a0 = this.rnd() * TAU; + for (let i = 0; i < n; i++) { const a = a0 + TAU * i / n; this.shoot(b.x + Math.cos(a) * 36, b.y + Math.sin(a) * 36, a, this.sp(1.7), K.BALL, C.BLUE); } + } else if (s.k === 1 && lt % 5 === 0) { + for (let i = 0; i < 1 + (D >= 2 ? 1 : 0); i++) this.shoot(b.x + (this.rnd() - 0.5) * 320, b.y - 40 - this.rnd() * 30, PI / 2 + (this.rnd() - 0.5) * 0.7, this.sp(1.4 + this.rnd() * 1.2), K.RICE, C.BLUE); + } else if (s.k === 2 && lt % 30 === 0) { + const m = 5 + D; + for (let i = -m; i <= m; i++) { const x = b.x + i * 34; if (x > 8 && x < W - 8) this.shoot(x, b.y, this.aim(x, b.y), this.sp(1.9), K.PELLET, C.CYAN); } + } + } else if (lt === 90) this.moveBoss(CX + (this.rnd() - 0.5) * 240, 92 + this.rnd() * 30, 40); + else if (lt >= 130) { s.k = (s.k + 1 + Math.floor(this.rnd() * 2)) % 3; s.t0 = t; } + // fairy squad every 260 frames from alternating sides: they cross the field sinking slowly (so they pass below her) and each + // fires a line of kunai aimed at the player (several kunai on one line with rising speeds = the laser-like kunai) + if (t % 260 === 20) { + const side = s.sq % 2 ? 1 : -1, n = 3 + Math.min(D, 2); + s.sq++; + for (let i = 0; i < n; i++) this.fams.push({x: side < 0 ? -12 : W + 12, y: 56 + i * 22, vx: -side * 2.2, vy: 0.28, t: -i * 24, c: i % 2 ? C.CYAN : C.BLUE, hp: 120, sd: 0, bd: 0, gz: 0, fire: 50 + i * 10}); + } + for (const f of this.fams) { + if (f.hp === undefined) continue; + if (f.t++ < 0) continue; + f.x += f.vx; f.y += f.vy; + if (f.t === f.fire || (f.t > f.fire && (f.t - f.fire) % 110 === 0)) { + if (fairyIn(f)) { const a = this.aim(f.x, f.y); for (let j = 0; j < 4 + D; j++) this.shoot(f.x, f.y, a, this.sp(1.8 + 0.45 * j), K.KUNAI, C.CYAN); } + } + } + }, + m_vine(t, s, b, D) { // Hard/Lunatic: scatter whose density drifts in patches (Hard slower and denser, Lunatic faster and sparser) + if (t % 3 === 0) { + const tries = D === 3 ? 3 : 4, ph = t * 0.013; + for (let i = 0; i < tries; i++) { + const a = PI / 2 + (this.rnd() - 0.5) * 3.0, keep = this.rnd(); + if (keep > 0.25 + 0.75 * (0.5 + 0.5 * Math.sin(5 * a + ph * 4))) continue; + const v = D === 3 ? this.sp(2.0 + this.rnd()) : this.sp(1.3 + this.rnd() * 0.9); + this.shoot(b.x, b.y, a, v, K.RICE, [C.PINK, C.PURPLE, C.GREEN][i % 3]); + } + } + if (t % 200 === 150) this.moveBoss(CX + (this.rnd() - 0.5) * 260, 90 + this.rnd() * 30, 50); + }, + m_non3(t, s, b, D) { // all-round kunai rows: blue (slow) then red (fast) circle her before flying out with a gap to her + // left (blue) / right (red), then a short random scatter (C37) + const cyc = 250, lt = t % cyc, n = [16, 24, 35, 42][D]; + for (const [at, red] of [[0, false], [70, true]]) { + if (lt !== at && lt !== at + 8) continue; + const gap = PI / 2 + (red ? -0.5 : 0.5), w = red ? -0.035 : 0.035, wt = 40, a0 = this.rnd() * TAU; + for (let i = 0; i < n; i++) { + const a = a0 + TAU * i / n, fin = a + w * wt; + if (Math.abs(angDiff(fin, gap)) < 0.33) continue; // the lane stays open after the turn + this.shoot(b.x, b.y, a, this.sp(red ? 2.4 : 1.5), K.KUNAI, red ? C.RED : C.BLUE, {w, wt}); + } + } + if (lt >= 140 && lt < 180 && lt % 5 === 0) for (let i = 0; i < 2 + (D >> 1); i++) this.shoot(b.x, b.y, PI / 2 + (this.rnd() - 0.5) * 2.4, this.sp(1.6 + this.rnd() * 1.4), K.PELLET, C.YELLOW); + if (lt === 200) this.moveBoss(CX + (this.rnd() - 0.5) * 260, 96 + this.rnd() * 26, 40); + }, + m_rain(t, s, b, D) { // Easy/Normal: colourful shards cross from both sides of her, accelerating; then curves in from both sides + const cyc = 260, lt = t % cyc; + if (lt < 110 && lt % (D ? 4 : 5) === 0) { + for (const side of [-1, 1]) { + const x = b.x + side * 130, a = PI / 2 - side * (0.55 + this.rnd() * 0.45), v = this.sp(0.6), acc = 0.018 + 0.004 * D; + this.shoot(x, b.y - 10, a, v, K.SHARD, RAINBOW[Math.floor(this.rnd() * 7)], {ax: Math.cos(a) * acc, ay: Math.sin(a) * acc, am: 90}); + } + } + if (lt >= 130 && lt < 200 && lt % 10 === 0) { + for (const side of [-1, 1]) for (let j = 0; j < 2 + D; j++) { + const a = side > 0 ? -0.25 - j * 0.12 : PI + 0.25 + j * 0.12; + this.shoot(b.x, b.y, a, this.sp(1.4 + 0.2 * j), K.BALL, side > 0 ? C.ORANGE : C.GREEN, {ta: PI / 2, tw: 0.016}); + } + } + if (lt === 110 || lt === 235) this.moveBoss(CX + (this.rnd() - 0.5) * 300, 88 + this.rnd() * 36, 40); + }, + m_dance(t, s, b, D) { // Hard/Lunatic: accelerating radial bursts alternate with curves (red inner, yellow outer) mostly from the upper right + const cyc = 220, lt = t % cyc; + if (lt === 0 || lt === 12 || lt === 24) { + const n = this.cnt(18 + 4 * D), a0 = this.rnd() * TAU, acc = 0.012; + for (let i = 0; i < n; i++) { const a = a0 + TAU * i / n; this.shoot(b.x, b.y, a, this.sp(0.8), K.SHARD, RAINBOW[i % 7], {ax: Math.cos(a) * acc, ay: Math.sin(a) * acc, am: 100}); } + } + if (lt >= 80 && lt < 160 && lt % 6 === 0) { + const ox = this.rnd() < 0.75 ? 1 : -1, x = b.x + ox * 160, y = b.y - 40; + for (const [r, col] of [[0, C.RED], [1, C.YELLOW]]) { + const a = PI / 2 + ox * (0.35 + 0.35 * r); + this.shoot(x, y, a, this.sp(1.2 + 0.5 * r), K.BALL, col, {w: -ox * 0.008 * (r ? 0.6 : 1), wt: 90, ax: Math.cos(a) * 0.01, ay: Math.sin(a) * 0.01, am: 80}); + } + } + if (lt === 180) this.moveBoss(CX + (this.rnd() - 0.5) * 260, 92 + this.rnd() * 30, 36); + }, + m_typhoon(t, s, b, D) { // Meiling stays put and fires nonstop: two counter-turning spiral streams cross, colours random + if (t === 0) { this.moveBoss(CX, 120, 40); s.a = 0; } + const iv = [5, 4, 3, 3][D]; + if (t >= 40 && t % iv === 0) { + s.a += 0.21; + for (const side of [-1, 1]) { + const a = PI / 2 + side * s.a; + this.shoot(b.x, b.y, a, this.sp(1.7 + 0.2 * D), K.SHARD, RAINBOW[Math.floor(this.rnd() * 7)], {w: -side * 0.006, wt: 120}); + } + if (D >= 3 && t % 6 === 0) this.shoot(b.x, b.y, this.rnd() * TAU, this.sp(1.4), K.BALL, C.RED); + } + }, + // ---------- Patchouli Knowledge (stage 4), Reimu A card list ---------- + // Geometry from guide text (C42, C43, approximation); documented: lasers fire from 64 px along each laser (C42), the + // Lava Cromlech ways 8/12/16/20 and the Mercury Poison ways 15/20/28 with +1 way per set. + p_non1(t, s, b, D) { PATTERN.p_nonspell.call(this, t, s, b, D, false); }, + p_non2(t, s, b, D) { PATTERN.p_nonspell.call(this, t, s, b, D, true); }, + // Rotating lasers from one side sweep down toward her (Easy stops short of straight down, Normal reaches it, Hard+ goes a + // little past), alternating left / right; from the 2nd wave (non-spell 2: every wave) aimed bullets come from the lasers; + // then she moves and fires aimed all-round rings (non-spell 2: faster, turning like a winder). + p_nonspell(t, s, b, D, two) { + const cyc = 300, lt = t % cyc, wave = Math.floor(t / cyc), side = wave % 2 ? 1 : -1; + if (lt === 0) { + const n = [3, 4, 5, 5][D], sweep = PI / 2 + [-0.25, 0, 0.2, 0.2][D], frames = 100, gap = 0.22; + for (let i = 0; i < n; i++) { + const a0 = side < 0 ? PI + i * gap : -i * gap; // fanned away from straight down, the lead laser first + this.laser(b.x, b.y, a0, 600, 14, 40, frames); + this.lasers[this.lasers.length - 1].va = side * sweep / frames; // canvas y is down: left lasers turn from pi toward pi/2 + } + } + if (lt > 40 && lt <= 140 && lt % 20 === 0 && (two || wave >= 1)) { + const v = this.sp(2.0 + 0.15 * D); + this.fromLasers(b, (x, y) => this.fan(x, y, 3, this.aim(x, y), 0.18, v, K.PELLET, C.PURPLE)); + } + if (lt === 160) this.moveBoss(CX + (this.rnd() - 0.5) * 260, 92 + this.rnd() * 30, 40); + const shots = two ? 6 : 3, step = two ? 7 : 14; + if (lt >= 210 && lt < 210 + shots * step && (lt - 210) % step === 0) { + const k = (lt - 210) / step, n = this.cnt([12, 16, 20, 24][D]); + this.ring(b.x, b.y, n, this.aim(b.x, b.y) + (two ? side * 0.06 * k : 0), this.sp(two ? 2.4 : 2.0), K.BALL, C.BLUE); + } + }, + p_agni(t, s, b, D) { PATTERN.p_fire.call(this, t, s, b, D, false); }, + p_agni_hl(t, s, b, D) { PATTERN.p_fire.call(this, t, s, b, D, true); }, + // Agni Shine: waves of wavering fire bullets falling from above her and from her body; the outer ones leave the + // screen before the bottom, thinning the lower right (High Level: both lower corners, denser waves) + p_fire(t, s, b, D, hl) { + const per = hl ? 56 : 72, lt = t % per; + if (lt === 0) s.k = (s.k || 0) + 1; + if (lt < 24 && lt % 4 === 0) { + const lanes = hl ? [-1, 0, 1] : [-1, 0]; + for (const o of lanes) { + const x = o ? b.x + o * 210 : b.x, y = o ? 24 : b.y, base = PI / 2 + (o ? -o * 0.35 : 0); + for (let j = 0; j < 2 + (D >> 1); j++) { + const a = base + (this.rnd() - 0.5) * 1.2; + this.shoot(x, y, a, this.sp(1.5 + this.rnd()), K.FIRE, j % 2 ? C.ORANGE : C.RED, {w: (j % 2 ? 1 : -1) * 0.006, wt: 160}); + } + } + } + if (t % 300 === 260) this.moveBoss(CX + (this.rnd() - 0.5) * 200, 96 + this.rnd() * 26, 40); + }, + p_trilithon_hl(t, s, b, D) { PATTERN.p_earth.call(this, t, s, b, D, false); }, + p_shake(t, s, b, D) { PATTERN.p_earth.call(this, t, s, b, D, true); }, + // Earth: yellow bullets stop near her, turn to a random heading and go again (High Level: a short stop close to her); + // being above her draws aimed penalty shots; Trilithon Shake adds periodic aimed large bullets. She does not move. + p_earth(t, s, b, D, shake) { + if (t % 24 === 0) { + const n = this.cnt(8 + 2 * D), a0 = this.rnd() * TAU; + for (let i = 0; i < n; i++) this.shoot(b.x, b.y, a0 + TAU * i / n, 2.2, K.BALL, C.YELLOW, {st: 18, gt: 30, gm: 0, ga: PI / 2 + (this.rnd() - 0.5) * 2.6, gs: this.sp(1.5 + this.rnd() * 0.8)}); + } + if (this.player.y < b.y && t % 10 === 0) this.fan(b.x, b.y, 3, this.aim(b.x, b.y), 0.12, this.sp(3.4), K.RICE, C.YELLOW); + if (shake && t % 90 === 45) this.shoot(b.x, b.y, this.aim(b.x, b.y), this.sp(2.4), K.BIG, C.ORANGE); + }, + // Lava Cromlech: 16 sets alternating straight all-round fire (8/12/16/20-way, two speeds) and Earth-type yellow bullets + p_lava(t, s, b, D) { + const set = Math.floor(t / 40) % 16, lt = t % 40; + if (lt === 0) { + if (set % 2 === 0) { + const n = [8, 12, 16, 20][D], a0 = this.rnd() * TAU; + this.ring(b.x, b.y, n, a0, this.sp(1.8), K.FIRE, C.RED); + this.ring(b.x, b.y, n, a0 + PI / n, this.sp(2.6), K.FIRE, C.ORANGE); + } else { + const n = this.cnt(10 + 2 * D), a0 = this.rnd() * TAU; + for (let i = 0; i < n; i++) this.shoot(b.x, b.y, a0 + TAU * i / n, 2.0, K.BALL, C.YELLOW, {st: 22, gt: 34, gm: 0, ga: PI / 2 + (this.rnd() - 0.5) * 2.4, gs: this.sp(1.3 + this.rnd() * 0.7)}); + } + } + if (t % 640 === 600) this.moveBoss(CX + (this.rnd() - 0.5) * 180, 100 + this.rnd() * 20, 40); + }, + // Mercury Poison: from two points beside her, yellow streams curving clockwise and light-blue counter-clockwise, 8 + 8 + // alternate shots a set, 15/20/28 ways (Normal/Hard/Lunatic; not on Easy) and one more way every set + p_mercury(t, s, b, D) { + const step = 20, k = Math.floor(t / step), set = Math.floor(k / 16), n = [15, 15, 20, 28][D] + set; + if (t % step === 0) { + const yellow = k % 2 === 0, x = b.x + (yellow ? -60 : 60), a0 = PI / 2 + (k % 16) * 0.04 * (yellow ? 1 : -1); + this.ring(x, b.y, n, a0, this.sp(2.1), K.BALL, yellow ? C.YELLOW : C.CYAN, {w: yellow ? 0.004 : -0.004, wt: 200}); + } + }, + // Forest Blaze: green bullets stream in from off-screen top right toward the lower left, her body scatters fire bullets + p_forest(t, s, b, D) { + if (t % 6 === 0) for (let i = 0; i < 1 + (D >> 1); i++) { + const x = W * 0.45 + this.rnd() * (W * 0.6), a = PI / 2 + 0.2 + this.rnd() * 0.5; + this.shoot(x, -8, a, this.sp(1.8 + this.rnd() * 0.9), K.RICE, C.GREEN); + } + if (t % 40 === 20) for (let i = 0; i < 6; i++) this.shoot(b.x, b.y, PI / 2 + (this.rnd() - 0.5) * 2.4, this.sp(1.6 + this.rnd()), K.FIRE, C.RED); + if (t % 240 === 200) this.moveBoss(CX + (this.rnd() - 0.5) * 220, 90 + this.rnd() * 30, 50); + }, + // ---------- Remilia (stage 6, C45-C48). Order and rules are documented; counts and speeds are approximations unless a comment says otherwise ---------- + // Non-spell 1: "enemy-dependent all-round": one emission point; red large, blue medium at random angles and aimed blue pellets, then a move + r6_non1(t, s, b, D) { + const cyc = 170, lt = t % cyc; + if (lt === 0) this.ring(b.x, b.y, [6, 10, 14, 18][D], this.aim(b.x, b.y), this.sp(1.7), K.BIG, C.RED); + if (lt < 48 && lt % 12 === 0) { + this.ring(b.x, b.y, this.cnt([10, 14, 18, 24][D]), this.rnd() * TAU, this.sp(2.2), K.BALL, C.BLUE); + this.ring(b.x, b.y, this.cnt([12, 20, 26, 32][D]), this.aim(b.x, b.y), this.sp(2.9), K.PELLET, C.BLUE); + } + if (lt === 90) this.moveBoss(CX + (this.rnd() - 0.5) * 300, 88 + this.rnd() * 56, 50); + }, + // Non-spell 2: fixed order "aimed, move, right to left, move, left to right, aimed, move"; large with scattered medium and small; 8 shots a sweep (S45), the top row is out of reach + r6_non2(t, s, b, D) { + const lt = t % 500, volley = a => { + this.shoot(b.x, b.y, a, this.sp(2.6), K.BIG, C.RED); + for (let i = 0; i < 3 + D; i++) this.shoot(b.x, b.y, a + (this.rnd() - 0.5) * 0.5, this.sp(1.9 + this.rnd() * 1.1), i % 2 ? K.BALL : K.PELLET, C.BLUE); + }; + if (lt < 70 && lt % 14 === 0) { const a = this.aim(b.x, b.y); for (const o of [-0.3, 0, 0.3]) volley(a + o); } + if (lt === 80) this.moveBoss(CX + 200, 110, 40); + if (lt >= 130 && lt < 130 + 8 * 13 && (lt - 130) % 13 === 0) { const a = (lt - 130) / 13 * PI / 7; for (let i = 0; i < 2 + (D >> 1); i++) volley(a + i * 0.16); } + if (lt === 240) this.moveBoss(CX - 200, 110, 40); + if (lt >= 290 && lt < 290 + 8 * 13 && (lt - 290) % 13 === 0) { const a = PI - (lt - 290) / 13 * PI / 7; for (let i = 0; i < 2 + (D >> 1); i++) volley(a - i * 0.16); } + if (lt === 400) this.moveBoss(CX, 100, 40); + }, + // Non-spell 3: fixed all-round knives; each set's rounds share one angle, so they fly the same paths and the gap in the first row + // stays safe; clockwise first, then the same counter-clockwise, random starting point (S46) + r6_non3(t, s, b, D) { + const lt = t % 170; + if (lt === 0) { s.k = (s.k || 0) + 1; if (s.k % 2) s.a0 = this.aim(b.x, b.y) + (this.rnd() - 0.5) * 0.5; } + if (lt < 66 && lt % 11 === 0) { + const n = [14, 18, 22, 26][D], dir = s.k % 2 ? 1 : -1, v = 2.2 + 0.2 * D; + for (let i = 0; i < n; i++) this.knife(b.x, b.y, s.a0 + TAU * i / n, v, C.BLUE, {w: dir * 0.0065, wt: 150}); + } + }, + // Non-spell 4: fixed three segments, invulnerable while attacking (documented, hit her between them): 1 scattered accelerating falling + // rice, 2 aimed odd-way large, 3 aimed odd-way fire much slower than 2; she moves at random between them. Segment lengths are approximations. + r6_non4(t, s, b, D) { + const lt = t % 600, seg = lt < 120 ? 1 : lt < 200 ? 0 : lt < 280 ? 2 : lt < 360 ? 0 : lt < 480 ? 3 : 0; + s.inv = seg > 0 ? 1 : 0; + if (seg === 1 && lt % 5 === 0) for (let i = 0; i < 2 + D; i++) { + const a = PI / 2 + (this.rnd() - 0.5) * 2.8; + this.shoot(b.x, b.y, a, this.sp(0.5), K.RICE, this.rnd() < 0.5 ? C.RED : C.PINK, {ax: Math.cos(a) * 0.012, ay: 0.02 + Math.sin(a) * 0.012, am: 110}); + } + if (seg === 2 && (lt - 200) % 16 === 0) this.fan(b.x, b.y, 3 + 2 * (D >> 1), this.aim(b.x, b.y), 0.22, this.sp(2.4 + 0.4 * D), K.BIG, C.RED); + if (seg === 3 && (lt - 360) % 14 === 0) this.fan(b.x, b.y, 5 + 2 * (D >> 1), this.aim(b.x, b.y), 0.2, this.sp(1.4 + 0.2 * D), K.FIRE, C.ORANGE); + if (lt === 120 || lt === 280 || lt === 480) this.moveBoss(CX + (this.rnd() - 0.5) * 340, 88 + this.rnd() * 52, 50); + }, + // Star of David: the web, and from the 16x3 points of a second Func7 call with its own rotation (S45 S47) blue medium bullets: the first web's points all-round 5-way at one common angle + // (reads as rings from her), the second's 3 shots in one common direction, slightly random, mostly right or down (lower left is often safe). + r6_david(t, s, b, D) { + const lt = t % 240; + if (lt === 0) { s.a0 = this.rnd() * TAU; s.a1 = (this.rnd() < 0.5 ? 0 : PI / 2) + (this.rnd() - 0.5) * 0.5; this.webLasers(b, this.rnd() * TAU); } + if (lt === 20) this.webEach(b, this.rnd() * TAU, (x, y, a, n, len, net) => { + if (x < 0 || x > W || y < 0 || y > H) return; + if (net === 0) this.ring(x, y, 5, s.a0, this.sp(1.5), K.BALL, C.BLUE); + else for (let i = 0; i < 3; i++) this.shoot(x, y, s.a1 + (this.rnd() - 0.5) * 0.4, this.sp(1.5 + this.rnd() * 0.6), K.BALL, C.BLUE); + }); + }, + // Young Demon Lord: the same web (inferred, C48), a static random rotation each wave, large and medium bullets from the points + r6_demon(t, s, b, D) { + const lt = t % 240; + if (lt === 0) { s.a0 = this.rnd() * TAU; this.webLasers(b, this.rnd() * TAU); } + if (lt === 20) this.webEach(b, this.rnd() * TAU, (x, y, a, n, len, net) => { + if (x < 0 || x > W || y < 0 || y > H) return; + if (net === 0) this.shoot(x, y, a, this.sp(1.8), K.BIG, C.CYAN); + else this.ring(x, y, 4 + D, s.a0, this.sp(1.7), K.BALL, C.BLUE); + }); + }, + // From the second card on rank no longer changes her cards (S44), so these take plain speeds, not sp(). + // Scarlet Netherworld: 16-way falling needles (gravity on Normal, S45) + 24-way crossing bullets; the first wave's angle is random and + // every later wave repeats it, so the rows are orderly and a spot that survives one wave survives the next. + r6_nether(t, s, b, D) { + if (t === 0) s.a0 = this.rnd() * TAU; + if (t % 90 !== 0) return; + this.ring(b.x, b.y, 16, s.a0, 1.8, K.RICE, C.RED, {ax: 0, ay: 0.012, am: 200}); + for (let i = 0; i < 24; i++) { const a = s.a0 + TAU * i / 24; this.shoot(b.x, b.y, a, 2.0, K.BALL, C.PINK, {w: (i % 2 ? 1 : -1) * 0.006, wt: 160}); } + }, + // Thousand Needles: the crossing bullets become 16-way knives; needles without gravity reflect off the top and side walls, 12-way on Hard, 32-way on Lunatic (S44) + r6_needles(t, s, b, D) { + if (t === 0) s.a0 = this.rnd() * TAU; + if (t % 80 !== 0) return; + this.ring(b.x, b.y, D >= 3 ? 32 : 12, s.a0, 2.2, K.RICE, C.RED, {bn: 2, bm: 1}); + for (let i = 0; i < 16; i++) this.knife(b.x, b.y, s.a0 + TAU * i / 16, 2.3, C.BLUE, {w: (i % 2 ? 1 : -1) * 0.006, wt: 160}); + }, + // Curse of Vlad Tepes: spiral all-round blue knives, 13 growing to 18 ways, strongly curving; red bullets spread along their tracks; a new + // round only when no blue knife is on screen (documented, S44 S45) + r6_tepes(t, s, b, D) { + if (s.next === undefined) { s.next = 0; s.k = 0; } + if (t >= s.next && !this.hasBullet(K.KNIFE, C.BLUE)) { + const n = Math.min(18, 13 + s.k), a0 = this.rnd() * TAU, dir = s.k % 2 ? 1 : -1; + for (let i = 0; i < n; i++) this.knife(b.x, b.y, a0 + TAU * i / n, 2.6, C.BLUE, {w: dir * 0.011, wt: 130}); + s.k++; s.next = t + 40; + } + if (t % 16 === 8 && this.bullets.length < 640) { + const m = this.bullets.length; + for (let i = 0; i < m; i++) { + const q = this.bullets[i]; + if (q.k === K.KNIFE && q.c === C.BLUE && q.x >= 0 && q.x <= W && q.y >= 0 && q.y <= H) this.shoot(q.x, q.y, this.rnd() * TAU, 0.5 + this.rnd() * 0.5, K.PELLET, C.RED); + } + } + }, + // Vampire Illusion: aimed even-way large bullets (only a big move runs into them) leave still bullets on their tracks that slowly spread; a + // new round only when no blue large bullet is on screen (S44) + r6_fantasy(t, s, b, D) { + if (s.next === undefined) s.next = 0; + if (t >= s.next && !this.hasBullet(K.BIG, C.BLUE)) { + this.fan(b.x, b.y, D >= 3 ? 8 : 6, this.aim(b.x, b.y), 0.3, 2.4, K.BIG, C.BLUE); + s.next = t + 30; + } + if (t % 12 === 6) this.dropStill(K.BIG, C.BLUE); + if (t % 60 === 30) this.releaseStill(b, false); + }, + // Scarlet Shoot: aimed large bullets with scattered medium and small from one point: 5-way x 2 (180 deg across), a narrow 3-way, a pause, + // 5-way x 2, a gap (S44 S45); fast + r6_shoot(t, s, b, D) { + const lt = t % 320, volley = (n, gap) => { + const a0 = this.aim(b.x, b.y); + for (let i = 0; i < n; i++) { + const a = a0 + (i - (n - 1) / 2) * gap; + this.shoot(b.x, b.y, a, 3.4, K.BIG, C.RED); + for (let j = 0; j < 4; j++) this.shoot(b.x, b.y, a + (this.rnd() - 0.5) * 0.3, 2.2 + this.rnd() * 1.2, j % 2 ? K.BALL : K.PELLET, C.RED); + } + }; + if (lt === 0 || lt === 26 || lt === 160 || lt === 186) volley(5, PI / 4); + else if (lt === 70) volley(3, 0.2); + if (lt === 250) this.moveBoss(CX + (this.rnd() - 0.5) * 240, 92 + this.rnd() * 40, 40); + }, + // Scarlet Meister: circular volleys led by large bullets; each wave a long aimed row of 5 turning clockwise, she moves a fixed distance, a + // short row of 3 turning counter-clockwise, a long pause (S44 S46) + r6_meister(t, s, b, D) { + const lt = t % 340, n = D >= 3 ? 26 : 20, row = (k, dir) => { + const a = (k === 0 ? (s.a0 = this.aim(b.x, b.y)) : s.a0) + dir * k * 0.09, v = 2.7; + this.ring(b.x, b.y, n, a, v, K.BIG, C.RED); this.ring(b.x, b.y, n, a, v * 0.82, K.BALL, C.RED); this.ring(b.x, b.y, n, a, v * 0.66, K.PELLET, C.RED); + }; + if (lt < 50 && lt % 10 === 0) row(lt / 10, 1); + if (lt === 70) { const sd = this.rnd() < 0.5 ? -1 : 1, x = b.x + sd * 180; this.moveBoss(x < 60 || x > W - 60 ? b.x - sd * 180 : x, 92 + this.rnd() * 40, 40); } + if (lt >= 120 && lt < 150 && (lt - 120) % 10 === 0) row((lt - 120) / 10, -1); + }, + // Red Magic (C47 C48): all-round large bullets leaving still bullets on their tracks, 10-way x 5 at one random angle (S45; Easy's sparser + // 6-way x 3 with still bullets every 30 frames is our own, the original has no Easy stage 6), reflecting off the top and sides but not the floor; on her signal the pellets + // scatter (Func11 random / Func9 swirl in turn); the next round only when no large bullet is left. + r6_magic(t, s, b, D) { PATTERN.r6_final.call(this, t, s, b, D, D === 0 ? 6 : 10, D === 0 ? 3 : 5, true, 0); }, + // Scarlet Gensokyo: the same without the reflection, with the 56-way ring (S44) + r6_gensokyo(t, s, b, D) { PATTERN.r6_final.call(this, t, s, b, D, 12, 5, false, 56); }, + r6_final(t, s, b, D, ways, sets, reflect, ring) { + if (s.left === undefined) { s.left = 0; s.k = 0; } + if (s.left > 0 && t >= s.fire) { + this.ring(b.x, b.y, ways, s.a0, 2.1, K.BIG, C.RED, reflect ? {bn: 1, bm: 1} : undefined); + s.left--; s.fire = t + 14; + if (ring && s.left === sets - 1) this.ring(b.x, b.y, ring, s.a0, 1.5, K.BALL, C.PINK); + } else if (s.left === 0 && !this.hasBullet(K.BIG, C.RED)) { s.a0 = this.rnd() * TAU; s.left = sets; s.fire = t; s.k++; } + if (t % (D === 0 ? 30 : 20) === 10) this.dropStill(K.BIG, C.RED); + if (t % 100 === 60) this.releaseStill(b, s.k % 2 === 0); + } + }; + M.Game = Game; M.PATTERN = PATTERN; + + // ---------- standard scripted controller (trusted reference; reads privileged state, never mutates it) ---------- + const DIRS = [[0, 0], [-1, 0], [1, 0], [0, -1], [0, 1], [-1, -1], [1, -1], [-1, 1], [1, 1]]; + const keysFor = (dx, dy, focus, extra) => { + const k = ['J']; if (focus) k.push('Shift'); + if (dx < 0) k.push('A'); else if (dx > 0) k.push('D'); + if (dy < 0) k.push('W'); else if (dy > 0) k.push('S'); + if (extra && k.length < 4) k.push(extra); + return k; + }; + // Private copy for lookahead. Spread copies keep the source objects' fast shapes; copying key by key (o[k] = v) would turn the + // ~60-field game and the 26-field bullets into slow dictionary-mode objects. Arrays fixed at construction are shared. + const SHARED = new Set(['phases', 'lifeOf', 'timeOf']), OWN = new Set(['player', 'boss', 'sub', 'bullets', 'shots', 'items', 'lasers', 'fams', 'bomb', 'events', 'pops', 'msg']); + const spreadAll = a => { const out = new Array(a.length); for (let i = 0; i < a.length; i++) out[i] = {...a[i]}; return out; }; + function cloneGame(g) { + const c = Object.setPrototypeOf({...g}, Game.prototype); + for (const k in c) { const v = c[k]; if (v !== null && typeof v === 'object' && !SHARED.has(k) && !OWN.has(k)) c[k] = clone(v); } + c.player = {...g.player}; c.boss = {...g.boss}; c.sub = {...g.sub}; + c.bullets = spreadAll(g.bullets); c.shots = spreadAll(g.shots); c.items = spreadAll(g.items); c.lasers = spreadAll(g.lasers); c.fams = spreadAll(g.fams); + if (g.bomb) { c.bomb = {...g.bomb}; c.bomb.orbs = spreadAll(g.bomb.orbs); } + c.events = []; c.pops = []; c.msg = null; + return c; + } + // Same rounding as NativeBench.quantize, restricted to the containers that can hold fractional numbers. + function qo(o) { for (const k in o) { const v = o[k]; if (typeof v === 'number') { if (!Number.isInteger(v)) o[k] = Math.round(v * 1e6) / 1e6; } else if (v !== null && typeof v === 'object') qo(v); } } + function qa(a) { for (let i = 0; i < a.length; i++) qo(a[i]); } + const r6 = v => Number.isInteger(v) ? v : Math.round(v * 1e6) / 1e6; + function qb(a) { + for (let i = 0; i < a.length; i++) { + const q = a[i]; q.x = r6(q.x); q.y = r6(q.y); q.vx = r6(q.vx); q.vy = r6(q.vy); + if (q.a !== undefined) q.a = r6(q.a); if (q.ax !== undefined) { q.ax = r6(q.ax); q.ay = r6(q.ay); } + if (q.w !== undefined) q.w = r6(q.w); if (q.ta !== undefined) q.ta = r6(q.ta); if (q.ga !== undefined) q.ga = r6(q.ga); if (q.gs !== undefined) q.gs = r6(q.gs); + if (q.s !== undefined) q.s = r6(q.s); if (q.tw !== undefined) q.tw = r6(q.tw); + } + } + function quantizeGame(g) { qo(g.player); qo(g.boss); qb(g.bullets); qa(g.shots); qa(g.items); qa(g.lasers); qa(g.fams); if (g.bomb) qo(g.bomb); qo(g.sub); if (g.msg) qo(g.msg); } + M.quantizeGame = quantizeGame; + const EMPTY = new Set(); + // Advance a private copy n ticks with constant held keys (candidates never press K/Q/E, so pressed is empty), + // quantized exactly like NativeBench.Session so the prediction matches the live packet. + function advance(g, keys, n, acc) { + const p = g.player, hits0 = p.hits; + for (let i = 0; i < n; i++) { + g.events = []; g.update(keys, EMPTY, null); quantizeGame(g); g.t++; + if (g.outcome === 'win') { acc.win = 1; return true; } + if (p.hits !== hits0 || g.outcome === 'loss') { acc.dead = acc.tick + i; return false; } + if (p.state === 'alive' && p.inv === 0 && !g.stop) { + const w = 1 / (1 + (acc.tick + i) * 0.12); + for (const q of g.bullets) { + const dx = Math.abs(q.x - p.x), dy = Math.abs(q.y - p.y); + if (dx > 40 || dy > 40) continue; + const d = Math.max(dx, dy) - BSIZE[q.k] / 2 - PLAYER_HALF; + if (d < acc.margin) acc.margin = d; + if (d < 24) acc.danger += (24 - d) * (24 - d) * w; + } + for (const l of g.lasers) { + if (l.t > l.wn + l.on) continue; + const c = Math.cos(l.a), s = Math.sin(l.a), rx = p.x - l.x, ry = p.y - l.y, along = rx * c + ry * s; + if (along < 0 || along > l.l) continue; + const d = Math.abs(-rx * s + ry * c) - l.w / 2 - PLAYER_HALF; + if (d < acc.margin) acc.margin = d; + if (d < 30) acc.danger += (30 - d) * (30 - d) * 2 * w; + } + } + } + acc.tick += n; return true; + } + const T = M.tune = {danger: 0.6, margin: 4, ax: 1.6, ay: 0.35, wantY: 400}; // controller weights (fixed constants of the reference controller) + M.scripted = function (game) { + const p = game.player, holds = k => ({holds: Array.from({length: 6}, () => k), mouse: [0, 0, 0]}); + if (game.outcome) return holds([]); + // Hit inside the previous packet: deathbomb while the 6-frame window is still open. The window (like everything of the + // player's) stands still in a time stop, so the press goes into the first hold set whose first tick is not frozen. + if (p.state === 'dead') { + const j0 = Math.ceil(Math.min(12, game.stop) / 2); + if (p.window > 0 && p.bombs > 0 && !game.bomb && j0 <= 5) return {holds: Array.from({length: 6}, (_, j) => j >= j0 ? ['K', 'J'] : ['J']), mouse: [0, 0, 0]}; + return holds(['J']); + } + // The whole packet is inside a time stop: input is ignored, nothing to decide. + if (game.stop > 12) return holds(keysFor(0, 0, true)); + // Line up under where the boss will be when the 12 px/frame amulets arrive (~20 frames), not where it is now. + const b = game.boss, lead = Math.min(1, (b.mt + 20) / (b.md || 1)), ease = lead * lead * (3 - 2 * lead); + const wantX = b.mt < b.md ? b.fx + (b.tx - b.fx) * ease : b.x, wantY = T.wantY, stay = new Set(keysFor(0, 0, true)); + const stage1 = []; + for (const [dx, dy] of DIRS) for (const focus of [true, false]) { + if (!focus && dx === 0 && dy === 0) continue; + const k = keysFor(dx, dy, focus), ks = new Set(k), g1 = cloneGame(game), acc = {tick: 0, dead: -1, danger: 0, margin: 99, win: 0}; + const ok = advance(g1, ks, 12, acc), gp = g1.player; + // cheap first-stage estimate, used only to choose which candidates get the expensive second stage + const pre = !ok ? -1e7 + acc.dead * 1e4 : acc.win ? 1e6 : -acc.danger * T.danger + Math.min(acc.margin, 30) * T.margin - Math.abs(gp.x - wantX) * T.ax - Math.abs(gp.y - wantY) * T.ay; + stage1.push({k, ks, g1, acc, ok, pre}); + } + stage1.sort((a, b2) => b2.pre - a.pre); + let best = null; + for (let i = 0; i < stage1.length; i++) { + const c = stage1[i], {k, ks, g1, acc} = c; + let score; + if (!c.ok) score = -1e7 + acc.dead * 1e4; + else if (acc.win) score = 1e6; + else if (i >= 7) score = c.pre - 1e5; // not expanded: ranked below every expanded survivor + else { + let cont = null; + for (const k2 of [ks, stay]) { + const g2 = cloneGame(g1), a2 = {tick: acc.tick, dead: -1, danger: acc.danger, margin: acc.margin, win: 0}; + const ok = advance(g2, k2, 12, a2), gp = g2.player; + let v; + if (!ok) v = -1e6 + a2.dead * 1e4; + else { + v = -a2.danger * T.danger + Math.min(a2.margin, 30) * T.margin - Math.abs(gp.x - wantX) * T.ax - Math.abs(gp.y - wantY) * T.ay; + if (gp.x < 28 || gp.x > W - 28) v -= 60; + if (gp.y > H - 24) v -= 40; + } + if (cont === null || v > cont) cont = v; + } + score = cont; + } + if (!best || score > best.score) best = {k, score, dead: acc.dead}; + } + // Every candidate is hit inside this packet: bomb (any bomb voids the capture anyway). The press must land on a tick + // outside a time stop, so it goes into the first hold set whose first tick is no longer frozen. + if (best.dead >= 0 && p.bombs > 0 && !game.bomb && p.state === 'alive') { + const j0 = Math.ceil(Math.min(12, game.stop) / 2); + if (j0 <= 5) { + const k = best.k.slice(0, 3); k.push('K'); + return {holds: Array.from({length: 6}, (_, j) => j === j0 ? k : best.k), mouse: [0, 0, 0]}; + } + } + return holds(best.k); + }; + M.oracle = M.scripted; // legacy name used by web/tools/native_validate.js +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/touhou_remake/index.html b/environments/games/web/games/touhou_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..2b77f06faaa1efb86cfa4a0e012786d6f9e30ece --- /dev/null +++ b/environments/games/web/games/touhou_remake/index.html @@ -0,0 +1,31 @@ + +Touhou Koumakyou: Boss Practice + +
      +
      + +
      Select a boss to start
      + +

      + +
      +
      + +
      + diff --git a/environments/games/web/games/touhou_remake/manifest.json b/environments/games/web/games/touhou_remake/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..8691e96a8ca74438478af0fb0c1ea73e64e449ae --- /dev/null +++ b/environments/games/web/games/touhou_remake/manifest.json @@ -0,0 +1,31 @@ +{ + "schema": "bossbench/game-manifest@1", + "engine": "independent", + "game": "touhou_remake", + "module": "TouhouGame", + "title": "Touhou Koumakyou: Boss Practice", + "dimension": "2d", + "native_hz": 60, + "max_seconds": 600, + "renderer": "canvas-native", + "rules": "scarlet-practice@8", + "cases": [ + "touhou/rumia", + "touhou/cirno", + "touhou/sakuya", + "touhou/meiling", + "touhou/patchouli", + "touhou/remilia" + ], + "scripts": [ + "_native/runtime.js", + "touhou_remake/game.js", + "touhou_remake/draw.js" + ], + "sim_scripts": [ + "_native/runtime.js", + "touhou_remake/game.js" + ], + "play_page": "web/games/touhou_remake/index.html", + "scripted_controller": "TouhouGame.scripted(game) -> {holds:[6 key arrays], mouse:[0,0,0]}: exact 24-tick lookahead on a private copy, deathbomb/bomb on unavoidable hits (bomb press placed outside time stops)" +} diff --git a/environments/games/web/games/touhou_remake/page.css b/environments/games/web/games/touhou_remake/page.css new file mode 100644 index 0000000000000000000000000000000000000000..76cccd740aedafe77d6224f787dabc111ae4acec --- /dev/null +++ b/environments/games/web/games/touhou_remake/page.css @@ -0,0 +1,49 @@ +/* touhou_remake play page (scarlet-practice@4): the window is the game. No page chrome, no borders. */ +:root{color-scheme:dark;--ink:#f3eaf0;--muted:#b9a9b6;--accent:#f0b6d0;--glass:rgba(14,8,22,.72);--edge:rgba(255,200,225,.22)} +*{box-sizing:border-box} +html,body{margin:0;height:100%;background:#05030a;color:var(--ink);font:14px/1.5 "Yu Gothic UI","Microsoft YaHei","Segoe UI",sans-serif;overflow:hidden} +a{color:var(--accent)} +.stage{position:fixed;inset:0;display:flex;align-items:center;justify-content:center;overflow:hidden} +#ambient{position:fixed;inset:-6%;z-index:-1;background:#05030a center/cover no-repeat;filter:blur(26px) brightness(.5) saturate(1.25);pointer-events:none} +.frame{position:relative;width:min(100vw,calc(100vh * 854 / 480));aspect-ratio:854/480;box-shadow:0 0 60px rgba(0,0,0,.6)} +.frame>canvas{display:block;width:100%;height:100%;touch-action:none;outline:none} +.frame>canvas:focus-visible{box-shadow:inset 0 0 0 2px var(--accent)} +#overlay{pointer-events:none;position:absolute;inset:0;background:radial-gradient(ellipse at center,rgba(8,4,16,.12),rgba(8,4,16,.45))} +#overlay[hidden]{display:none} +#overlay div{position:absolute;top:11.5%;left:1.2%;white-space:nowrap;padding:4px 16px;background:var(--glass);border:1px solid var(--edge);border-radius:4px;font:16px/1.4 Georgia,"Yu Mincho","SimSun",serif;letter-spacing:.06em;text-align:left} +.bar{position:absolute;left:0;right:0;top:0;display:flex;flex-wrap:wrap;align-items:center;gap:6px 10px;padding:6px 10px;background:linear-gradient(rgba(10,6,18,.88),rgba(10,6,18,.62));border-bottom:1px solid var(--edge);transition:opacity .35s ease;z-index:2} +.bar.idle{opacity:0} +.bar.idle.locked{pointer-events:none} +.bar h1{margin:0 6px 0 0;font:600 15px/1.2 Georgia,"Yu Mincho","Microsoft YaHei",serif;letter-spacing:.04em;white-space:nowrap} +.bar label{display:flex;align-items:center;gap:5px;color:var(--muted);font-size:12px;white-space:nowrap} +.bar .group{display:flex;gap:5px} +.bar .lobby{font-size:12px;align-self:center;margin-left:2px} +button,select,input{font:inherit;font-size:12.5px;color:var(--ink);background:rgba(40,24,52,.85);border:1px solid var(--edge);border-radius:3px;padding:4px 9px} +button{cursor:pointer}button:hover{border-color:var(--accent)} +button.primary{background:#e9a6c4;color:#1c0d18;font-weight:600;border-color:#f7c9dc} +input[type=number]{width:96px} +select{max-width:190px} +#file{display:none} +:focus-visible{outline:2px solid var(--accent);outline-offset:1px} +#status{position:absolute;left:50%;bottom:44px;transform:translateX(-50%);margin:0;max-width:80%;padding:4px 14px;background:var(--glass);border:1px solid var(--edge);border-radius:3px;font-size:12.5px;color:var(--accent);text-align:center;pointer-events:none;transition:opacity .6s ease;overflow-wrap:anywhere} +#status:empty,#status.faded{opacity:0} +.help{position:absolute;right:10px;top:52px;width:min(360px,46%);max-height:calc(100% - 64px);overflow:auto;padding:12px 16px;background:var(--glass);border:1px solid var(--edge);border-radius:4px;z-index:3} +.help[hidden]{display:none} +.help h2{margin:0 0 8px;font:600 15px Georgia,"Microsoft YaHei",serif} +.help dl{margin:0}.help dt{color:var(--accent);font:12px Consolas,monospace}.help dd{margin:0 0 7px;font-size:12.5px;color:var(--muted)} +.help .note{font-size:12px;color:var(--muted);margin:8px 0}.help .links{display:flex;gap:14px;font-size:12px;margin:6px 0 0} +.mobile{display:none} +@media (max-width:900px),(orientation:portrait){ + html,body{overflow:auto} + .stage{position:static;display:block;min-height:100%} + .frame{width:100vw;box-shadow:none} + .bar{position:static;background:rgba(10,6,18,.9)} + .bar.idle,.bar.idle.locked{opacity:1;pointer-events:auto} + #overlay div{font-size:14px;padding:3px 14px} + #status{position:static;transform:none;max-width:none;margin:6px 10px} + .help{position:static;width:auto;max-height:none;margin:8px 10px} + .mobile{display:flex;flex-wrap:wrap;gap:8px;padding:10px} + .mobile button{min-width:52px;min-height:44px;font-size:15px;touch-action:none} + #ambient{display:none} +} +@media (prefers-reduced-motion:reduce){.bar,#status{transition:none}} diff --git a/environments/games/web/games/touhou_remake/page.js b/environments/games/web/games/touhou_remake/page.js new file mode 100644 index 0000000000000000000000000000000000000000..acbbeb0a1ab7f244e60c06a4f27df2ee88582272 --- /dev/null +++ b/environments/games/web/games/touhou_remake/page.js @@ -0,0 +1,56 @@ +/* touhou_remake play page helpers (scarlet-practice@8). Runs after the shared _native/shell.js and only uses its public + * surface (window.nativeAPI and the page's controls); it never touches the simulation. */ +(function () { + 'use strict'; + const $ = s => document.querySelector(s), game = $('canvas'), bar = $('#bar'), overlay = $('#overlay'), frame = $('#frame'); + const ambient = $('#ambient'), status = $('#status'), help = $('#help'); + const mini = document.createElement('canvas'); mini.width = 96; mini.height = 54; const mctx = mini.getContext('2d'); // off-DOM: the page keeps one canvas + const playing = () => overlay.hidden; // shell.js hides the overlay exactly while a fight is running + const formField = () => ['INPUT', 'SELECT', 'TEXTAREA'].includes(document.activeElement && document.activeElement.tagName); + // ---- menu strip: always shown outside a fight; during a fight it fades 2 s after the pointer last moved over the top edge. + // While the player is steering with the keyboard the faded strip also stops taking clicks (no accidental restart); a scripted + // demo or replay keeps it clickable. ---- + const GAME_KEYS = new Set(['KeyW', 'KeyA', 'KeyS', 'KeyD', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'KeyJ', 'KeyK', 'KeyQ', 'KeyE', 'ShiftLeft', 'ShiftRight']); + let shownAt = performance.now(), keyPlay = false; + const show = () => { shownAt = performance.now(); keyPlay = false; bar.classList.remove('idle', 'locked'); }; + function updateBar() { + if (!playing()) keyPlay = false; + const idle = playing() && performance.now() - shownAt > 2000 && !bar.contains(document.activeElement) && help.hidden; + bar.classList.toggle('idle', idle); bar.classList.toggle('locked', idle && keyPlay); + } + window.addEventListener('keydown', e => { if (GAME_KEYS.has(e.code) && playing() && !formField()) keyPlay = true; }, true); + frame.addEventListener('pointermove', e => { const r = frame.getBoundingClientRect(); if (e.clientY - r.top < Math.max(48, r.height * 0.12)) show(); }); + bar.addEventListener('focusin', show); + // ---- Up / Down choose the boss before a fight (meeting 2026-11-02: boss switching on up/down). Only on a fresh or finished + // session, so a paused fight is never thrown away by a movement key. ---- + window.addEventListener('keydown', e => { + if ((e.code !== 'ArrowUp' && e.code !== 'ArrowDown') || playing() || formField() || !window.nativeAPI) return; + const st = nativeAPI.state(); if (st.ticks > 0 && !st.outcome) return; + const sel = $('#case'), n = sel.options.length; sel.selectedIndex = (sel.selectedIndex + (e.code === 'ArrowDown' ? 1 : n - 1)) % n; preview(); + }, true); + // ---- keep keyboard focus on the game after a menu button (the shell ignores keys while a button has focus) ---- + bar.addEventListener('click', e => { const b = e.target.closest('button'); if (b && !['import', 'help-toggle', 'fullscreen'].includes(b.id)) setTimeout(() => { game.focus({preventScroll: true}); shownAt = performance.now(); }, 0); }); + // ---- choosing a boss or a tier before a fight shows that fight's opening frame ---- + function preview() { + if (playing() || !window.nativeAPI) return; + const seed = Number($('#seed').value), d = Number($('#difficulty').value); + if (!Number.isInteger(seed) || seed < 0) return; + try { nativeAPI.reset($('#case').value, seed, d); status.textContent = $('#case').selectedOptions[0].textContent + ' · ' + $('#difficulty').selectedOptions[0].textContent + ' (↑ / ↓ switch bosses)'; } catch (err) { status.textContent = err.message; } + } + $('#case').addEventListener('change', preview); $('#difficulty').addEventListener('change', preview); + // ---- help panel and full screen ---- + $('#help-toggle').addEventListener('click', () => { help.hidden = !help.hidden; $('#help-toggle').setAttribute('aria-expanded', String(!help.hidden)); }); + $('#fullscreen').addEventListener('click', () => { if (document.fullscreenElement) document.exitFullscreen(); else if (document.documentElement.requestFullscreen) document.documentElement.requestFullscreen(); }); + document.addEventListener('fullscreenchange', () => { $('#fullscreen').textContent = document.fullscreenElement ? 'Exit Fullscreen' : 'Fullscreen'; }); + game.addEventListener('dblclick', () => { if (!document.fullscreenElement && document.documentElement.requestFullscreen) document.documentElement.requestFullscreen(); }); + // ---- status line fades a few seconds after each message ---- + let fadeTimer = 0; + new MutationObserver(() => { status.classList.remove('faded'); clearTimeout(fadeTimer); fadeTimer = setTimeout(() => status.classList.add('faded'), 5000); }).observe(status, {childList: true, characterData: true, subtree: true}); + // ---- letterbox fill (window not 16:9): a tiny, blurred live copy of the frame instead of bars ---- + let n = 0; + (function loop() { + if ((n & 3) === 0) updateBar(); + if (n % 12 === 0 && ambient.offsetParent !== null) { mctx.drawImage(game, 0, 0, 96, 54); ambient.style.backgroundImage = 'url(' + mini.toDataURL('image/jpeg', 0.7) + ')'; } + n++; requestAnimationFrame(loop); + })(); +})(); diff --git a/environments/games/web/games/zelda_oot_remake/app3d.js b/environments/games/web/games/zelda_oot_remake/app3d.js new file mode 100644 index 0000000000000000000000000000000000000000..ca91759825ce20aab747a86418691d390a45df53 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/app3d.js @@ -0,0 +1,68 @@ +/* Human play and exact native-input recording. Game state is owned by each module. */ +(function () { + 'use strict'; + const N=NativeBench, M=window.GAME_MODULE, $=s=>document.querySelector(s), canvas=$('canvas'), context=canvas.getContext('2d'); + let session=new N.Session(M,M.cases[0].id,1,.5),running=false,last=0,accumulator=0; + // A key pressed and released between two ticks stays held until one tick has sampled it (same latch as _native/shell.js), + // so fast taps (jump, ground pound, camera steps) are never lost. + const held=new Set(),pending=new Set(),releaseAfter=new Set(),pointerHeld=new Map(),touchHeld=new Map(); let mouse=[0,0,0],replay=null,replayIndex=0,automatic=false,script=null,scriptTick=0; + const keys={KeyW:'W',KeyA:'A',KeyS:'S',KeyD:'D',Space:'Space',ShiftLeft:'Shift',ShiftRight:'Shift',KeyJ:'J',KeyK:'K',KeyL:'L',KeyQ:'Q',KeyE:'E',KeyR:'R',ArrowUp:'W',ArrowDown:'S',ArrowLeft:'A',ArrowRight:'D'}; + document.body.dataset.game=M.id; + // Public difficulty = three tiers (2026-11-02): rebuilt from Module.tiers when the game declares it. + if(M.tiers&&$('#difficulty')){const sel=$('#difficulty'),names={easy:'Easy',normal:'Normal',hard:'Hard'};sel.textContent=''; + for(const t of ['easy','normal','hard']){const op=document.createElement('option');op.value=String(M.tiers[t]);op.textContent=names[t]+' (d='+M.tiers[t]+')';if(t==='normal')op.selected=true;sel.append(op);}} + for(const def of M.cases){const option=document.createElement('option');option.value=def.id;option.textContent=def.name;$('#case').append(option);} + const controls=Array.isArray(M.controls)?M.controls.map(value=>['',value]):Object.entries(M.controls); + for(const [key,value]of controls){const dt=document.createElement('dt'),dd=document.createElement('dd');dt.textContent=key;dd.textContent=value;$('dl').append(dt,dd);} + function status(value){$('#status').textContent=value;} + function clear(){held.clear();pending.clear();releaseAfter.clear();pointerHeld.clear();touchHeld.clear();mouse=[0,0,0];accumulator=0;} + function inputKeys(){return [...new Set([...held,...[...pointerHeld.values()].flatMap(keys=>[...keys]),...touchHeld.values()])].filter(key=>N.keys.includes(key)).slice(0,4);} + function draw(){ + M.draw(session.game,context); + $('#pause').textContent=running?'Pause':'Resume'; + $('#overlay').hidden=running&&!session.game.outcome; + $('#overlay strong').textContent=session.game.outcome?{win:'Challenge Complete',loss:'Challenge Failed',timeout:'Time up'}[session.game.outcome]:replay?'ReplayReplay · Paused':session.game.t?'Paused':'Are You Ready?'; + $('#overlay span').textContent=session.game.outcome?'Restart the challenge or export this replay':session.game.t?'Click Resume to return to battle':'Click Start Challenge, then click the screen to use keyboard and mouse controls.'; + } + function reset(id,seed,difficulty){running=false;automatic=false;replay=null;script=null;scriptTick=0;clear();session=new N.Session(M,id,seed,difficulty);draw();return session.snapshot();} + window.nativeAPI={reset,packet(packet){if(running)throw Error('Pause before a scripted packet');const value=session.packet(packet);draw();return value;}, + state(){return session.snapshot();},recording(){return session.export();}, + render(){draw();return canvas.toDataURL('image/png');}, + renderMetrics(){return M.renderMetrics?M.renderMetrics(context):{};}, + module(){return {id:M.id,hz:M.hz,version:M.version,cases:M.cases};}}; + function start(useScript){try{reset($('#case').value,Number($('#seed').value),Number($('#difficulty').value));automatic=useScript;running=true;status(useScript?'Script verification running':'Battle started; recording this match.');canvas.focus();draw();}catch(error){status(error.message);}} + $('#start').onclick=()=>start(false);$('#demo').onclick=()=>start(true); + $('#pause').onclick=()=>{if(session.game.outcome)return;running=!running;clear();if(running)canvas.focus();draw();}; + $('#step').onclick=()=>{running=false;if(replay)replayTick();else session.tick();draw();}; + function openReplay(data){N.Session.import(M,data);reset(data.case,data.seed,data.difficulty);replay=data;replayIndex=0;running=true;$('#case').value=data.case;status('Replay verified; starting playback.');draw();} + $('#sample').onclick=()=>{try{const data=M.example?.[$('#case').value];if(!data)throw Error('No built-in replay for this scene; run script verification first.');openReplay(data);}catch(error){status(error.message);}}; + function replayTick(){if(replayIndex{const data=session.export(),url=URL.createObjectURL(new Blob([JSON.stringify(data)],{type:'application/json'}));const link=document.createElement('a');link.href=url;link.download=M.id+'-'+session.seed+'.json';link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);status('Current replay exported');}; + $('#import').onclick=()=>$('#file').click();$('#file').onchange=async event=>{const file=event.target.files[0];if(!file)return;try{if(file.size>12e6)throw Error('Replay file is too large');openReplay(JSON.parse(await file.text()));}catch(error){status('Import failed: '+error.message);}event.target.value='';}; + function release(){clear();if(running){running=false;status('Window lost focus; battle paused.');}draw();} + window.addEventListener('blur',release);document.addEventListener('visibilitychange',()=>{if(document.hidden)release();}); + window.addEventListener('keydown',event=>{if(['INPUT','SELECT','BUTTON'].includes(document.activeElement.tagName))return;if(keys[event.code]){event.preventDefault();held.add(keys[event.code]);pending.add(keys[event.code]);releaseAfter.delete(keys[event.code]);}if(event.code==='Escape'){running=false;clear();draw();}}); + window.addEventListener('keyup',event=>{const key=keys[event.code];if(key){event.preventDefault();if(pending.has(key))releaseAfter.add(key);else held.delete(key);}}); + canvas.oncontextmenu=event=>event.preventDefault();canvas.onpointerdown=event=>{if(event.button!==0&&event.button!==2)return;canvas.focus();const keys=pointerHeld.get(event.pointerId)||new Set();keys.add(event.button===2?'RMB':'LMB');pointerHeld.set(event.pointerId,keys);}; + // Pointer Events emits pointerup only after the final mouse button is released. + // pointermove carries changes to the button mask for chorded mouse presses. + function syncMouse(event){if(event.pointerType==='mouse'&&pointerHeld.has(event.pointerId)){const keys=new Set();if(event.buttons&1)keys.add('LMB');if(event.buttons&2)keys.add('RMB');if(keys.size)pointerHeld.set(event.pointerId,keys);else pointerHeld.delete(event.pointerId);}} + window.addEventListener('pointermove',syncMouse); + window.addEventListener('pointerup',event=>{if(event.pointerType==='mouse')syncMouse(event);else pointerHeld.delete(event.pointerId);touchHeld.delete(event.pointerId);}); + window.addEventListener('pointercancel',event=>{pointerHeld.delete(event.pointerId);touchHeld.delete(event.pointerId);}); + canvas.onpointermove=event=>{if(event.buttons||document.pointerLockElement===canvas){mouse[0]+=event.movementX;mouse[1]+=event.movementY;}}; + canvas.onwheel=event=>{event.preventDefault();mouse[2]+=Math.sign(event.deltaY);}; + canvas.ondblclick=()=>canvas.requestPointerLock?.(); + document.querySelectorAll('[data-key]').forEach(button=>{button.onpointerdown=event=>{event.preventDefault();button.setPointerCapture(event.pointerId);touchHeld.set(event.pointerId,button.dataset.key);};button.onpointerup=button.onpointercancel=event=>touchHeld.delete(event.pointerId);}); + function frame(now){const delta=Math.min(.1,(now-last)/1000||0);last=now;const beforeTick=session.game.t,wasRunning=running;try{ + if(running&&!session.game.outcome){accumulator+=delta;while(accumulator>=1/M.hz&&running&&!session.game.outcome){accumulator-=1/M.hz; + if(replay)replayTick();else if(automatic){const count=M.hz/5;if(scriptTick===0)script=(M.scripted||M.oracle).call(M,session.game);const sub=Math.ceil((scriptTick+1)*6/count)-1;session.tick(script.holds[sub],script.mouse.map(value=>value/count));scriptTick=(scriptTick+1)%count;} + else{session.tick(inputKeys(),mouse.map((value,index)=>N.clamp(value,index===2?-5:-1000,index===2?5:1000)));mouse=[0,0,0];pending.clear();for(const key of releaseAfter)held.delete(key);releaseAfter.clear();}} + if(session.game.outcome){running=false;status({win:'Challenge Complete',loss:'Challenge Failed',timeout:'Challenge Timed Out'}[session.game.outcome]+' · you can export or replay this match');}} + if(session.game.t!==beforeTick||running!==wasRunning)draw(); + }catch(error){running=false;clear();status('Runtime error: '+error.message);$('#overlay').hidden=false;$('#overlay strong').textContent='Unable to continue right now';$('#overlay span').textContent=error.message;} + requestAnimationFrame(frame); + } + window.addEventListener('pagehide',()=>M.closeRenderer?.(context)); + draw();requestAnimationFrame(frame); +})(); diff --git a/environments/games/web/games/zelda_oot_remake/art/dodongo.js b/environments/games/web/games/zelda_oot_remake/art/dodongo.js new file mode 100644 index 0000000000000000000000000000000000000000..d7f92b53fa8fa8e23d03c5361b61d41ebdf16943 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/art/dodongo.js @@ -0,0 +1,79 @@ +/* Original procedural look for the fire-breathing cave lizard king: a squat armoured lizard with a ridge of horn plates, curling into a rolling ball. Lava cavern. No original model or texture is traced. + * Telegraphs (read from the state): inhaling, the mouth glows brighter and a fire lane lights up on the floor ahead (inhale 100 + 18 frames before the first flame); + * winding up a roll (27 frames) he curls and the lane to the corner he will roll to lights up; a bomb about to go off shows its blast radius. */ +(function(root){ + 'use strict'; + const R=root.ZeldaOot3D,PI=Math.PI,{canvasTex,noise}=R.tex; + const CORNERS=[[-500,-500],[-500,500],[500,500],[500,-500]],FIRE_LEN=585,FIRE_W=84,BLAST=110; + R.art.dodongo={camY:150,lookBias:.3,focusUp:40,focusR:110,lockR:70, + hits(g){const b=g.boss;if(b.act!=='damaged')return [];const y=['lay','vuln'].includes(b.act)?30:60;return [{x:b.x+Math.sin(b.yaw)*96,y:y+30,z:b.z+Math.cos(b.yaw)*96,k:b.timer/12}];}, + marker(g){const b=g.boss;return {x:b.x,y:60,z:b.z};}, + dangers(g){const b=g.boss,out=[];if(b.act==='inhale'||(b.act==='fire'&&b.af<34))out.push({x:b.x+Math.sin(b.yaw)*112,y:60,z:b.z+Math.cos(b.yaw)*112,label:'Fire breath'}); + if(b.act==='roll')out.push({x:b.x,y:60,z:b.z,label:'Roll'});return out;}, + room(S,group){const T=root.THREE; + const floorTex=canvasTex(512,512,(q,w,h)=>{q.fillStyle='#4a3a30';q.fillRect(0,0,w,h);noise(q,w,h,6000,31,'rgba(20,12,8,.4)','rgba(150,110,80,.14)',6); + q.strokeStyle='rgba(30,18,10,.6)';q.lineWidth=3;for(let i=0;i<=8;i++){q.beginPath();q.moveTo(i*64,0);q.lineTo(i*64,h);q.stroke();q.beginPath();q.moveTo(0,i*64);q.lineTo(w,i*64);q.stroke();} + q.strokeStyle='rgba(255,110,40,.16)';q.lineWidth=1.5;for(let i=0;i<24;i++){let x=(i*131)%w,y=(i*71)%h;q.beginPath();q.moveTo(x,y);for(let k=0;k<4;k++){x+=((i*k*29)%40)-20;y+=((i*k*43)%40)-20;q.lineTo(x,y);}q.stroke();}},6,6); + const wallTex=canvasTex(512,256,(q,w,h)=>{q.fillStyle='#3b2a22';q.fillRect(0,0,w,h);noise(q,w,h,4000,41,'rgba(10,6,4,.45)','rgba(160,90,60,.12)',8); + for(let i=0;i<9;i++){const x=i*58+10,G=q.createLinearGradient(0,h,0,h*.4);G.addColorStop(0,'rgba(255,120,40,.5)');G.addColorStop(1,'rgba(255,120,40,0)');q.fillStyle=G;q.fillRect(x,h*.4,6+i%3*4,h*.6);}},4,1); + const lavaTex=canvasTex(256,256,(q,w,h)=>{const g=q.createRadialGradient(128,128,10,128,128,128);g.addColorStop(0,'#ffe08a');g.addColorStop(.5,'#ff7a1a');g.addColorStop(1,'#a8240c');q.fillStyle=g;q.fillRect(0,0,w,h);noise(q,w,h,900,7,'rgba(140,20,0,.35)','rgba(255,240,160,.35)',6);}); + const m=new T.MeshLambertMaterial({map:floorTex}),floor=new T.Mesh(new T.PlaneGeometry(1200,1200),m);floor.rotation.x=-PI/2;group.add(floor); + const wm=new T.MeshLambertMaterial({map:wallTex});for(let i=0;i<4;i++){const wall=new T.Mesh(new T.PlaneGeometry(1200,520),wm);const a=i*PI/2;wall.position.set(Math.sin(a)*600,260,Math.cos(a)*600);wall.rotation.y=a+PI;group.add(wall);} + const lava=new T.Mesh(new T.CircleGeometry(210,40),new T.MeshBasicMaterial({map:lavaTex}));lava.rotation.x=-PI/2;lava.position.y=1.2;group.add(lava); + const rim=new T.Mesh(new T.RingGeometry(206,232,40),new T.MeshLambertMaterial({color:0x2a1a12}));rim.rotation.x=-PI/2;rim.position.y=1.5;group.add(rim); + const rock=new T.MeshLambertMaterial({color:0x3a2a20,flatShading:true});for(let i=0;i<16;i++){const a=i*PI/8+.1,r=219,s=new T.Mesh(new T.DodecahedronGeometry(12+i%4*4,0),rock);s.position.set(Math.sin(a)*r,4,Math.cos(a)*r);s.rotation.set(i,i*2,0);group.add(s);} + // Corner pillars (outside his lap) and a dark ceiling. + for(const [x,z] of CORNERS){const p=new T.Mesh(new T.CylinderGeometry(26,34,520,8),rock);p.position.set(x*1.12,260,z*1.12);group.add(p);} + const ceil=new T.Mesh(new T.PlaneGeometry(1200,1200),new T.MeshLambertMaterial({color:0x22160f}));ceil.rotation.x=PI/2;ceil.position.y=520;group.add(ceil); + S.hemi.color.set(0xffd2b0);S.hemi.groundColor.set(0x40261a);S.hemi.intensity=2.2;S.sun.intensity=1.8;S.sun.color.set(0xffe2c0);S.glow.color.set(0xff7a2a);S.glow.intensity=2.4;S.glow.position.set(0,80,0);S.world.background=new T.Color(0x140c08);S.world.fog=new T.Fog(0x140c08,900,1900);}, + focus(g){return g.lockTarget()||g.boss;}, + draw(S,g,f){const b=g.boss,x=b.ox+(b.x-b.ox)*f,y=b.oy+(b.y-b.oy)*f,z=b.oz+(b.z-b.oz)*f,t=g.t/60,h=g.hero; + const flash=b.inv>0&&(g.t>>1)%2===0,skin=S.mat(flash?0xffffff:0x5d6b3a),skin2=S.mat(flash?0xffffff:0x46522c),belly=S.mat(flash?0xffffff:0xb8a070),horn=S.mat(0xe8dcc0),dark=S.mat(0x2a2a1a),claw=S.mat(0xf0e6cc); + // Lava pit: heat shimmer and embers rising. + for(let i=0;i<6;i++){const u=(t*.4+i/6)%1,a=i*1.7+Math.floor(t*.4+i/6)*2.3;S.flare(Math.sin(a)*150*(.3+.7*((i*37)%10)/10),10+u*160,Math.cos(a)*150*(.3+.7*((i*53)%10)/10),14*(1-u)+4,0xff8a2a,.7*(1-u));} + S.flare(0,30,0,380,0xff6a1a,.18); + S.shadow(x,0,z,b.act==='roll'?90:110); + const down=b.act==='lay'||b.act==='vuln',inh=b.act==='inhale',blow=b.act==='fire',open=inh?.3+.25*Math.sin(t*14)+.3*Math.min(1,b.af/100):blow?.8:down?.5:.1,heat=inh?Math.min(1,b.af/100):blow?1:0; + // Fire lane: faint through the inhale, bright in its last second and while the flames run. + if(inh||blow&&b.af<=34){const k=blow?1:Math.min(1,b.af/100),late=blow||b.af>80,mx=x+Math.sin(b.yaw)*112,mz=z+Math.cos(b.yaw)*112; + S.decal('strip',mx,mz,FIRE_LEN,FIRE_W,0xff3a1a,late?.42:.1+.15*k,b.yaw);S.decal('strip',mx,mz,FIRE_LEN*k,FIRE_W*.35,0xff8a3a,late?.5:.2,b.yaw);} + // Roll lane: from his position to the corner he heads for, lit while he winds up and rolls. + if(b.act==='roll'){const c=CORNERS[b.corner],dx=c[0]-x,dz=c[1]-z,L=Math.hypot(dx,dz),wind=b.timer>0,yw=Math.atan2(dx,dz); + if(L>1)S.decal('strip',x,z,L,192,0xff3a1a,wind?.18+.25*(1-b.timer/27):.3,yw);S.decal('thin',x,z,100+(wind?Math.sin(t*30)*6:0),0,0xff3a1a,.8);} + if(b.act==='roll'){const sp=b.spin,wind=b.timer>0?1-b.timer/27:1;S.push(x,y+82,z,b.yaw,sp,0);S.part('ball',skin,0,0,0,82); + for(let i=0;i<10;i++){const a=i*PI/5;S.part('cone',horn,0,Math.cos(a)*80,Math.sin(a)*80,12,30,12,0,a);} + for(const sd of [-1,1])S.part('ball',belly,sd*44,0,0,40,70,70);S.pop();if(b.timer>0)S.flare(x,y+82,z,200*wind,0xff6a2a,.35*wind); + if(b.timer===0)for(let i=0;i<3;i++)S.flare(x-Math.sin(b.yaw)*(60+i*40),20,z-Math.cos(b.yaw)*(60+i*40),60-i*14,0xb08a6a,.35-i*.1);} + else{const dead=b.act==='dead',sink=down?-30:0,tilt=down?.25:0,breathe=inh?Math.sin(t*16)*3:Math.sin(t*2)*1.5; + S.push(x,y,z,b.yaw,0,tilt); + // Body: armoured back plates over a pale belly, a heavy tail and four clawed legs. + S.part('ball',skin,0,70+sink+breathe,-10,78,62+breathe,96);S.part('ball',belly,0,48+sink,6,60,36,80); + for(let i=0;i<5;i++)S.part('ball',skin2,0,118+sink-i*3+breathe,-56+i*26,40-i*2,10,20); + for(let i=0;i<6;i++){const zz=-70+i*26;S.part('cone',horn,0,128+sink-i*2,zz,10,34-i*2,14,0,-.25);} + const sw=Math.sin(t*2.4)*.25;S.push(0,48+sink,-100,sw,0,0);S.part('ball',skin,0,0,-12,34,26,50);S.part('ball',skin2,0,-8,-56,22,16,30);S.part('cone',skin2,0,-12,-92,12,40,12,0,-PI/2-.1); + for(let i=0;i<3;i++)S.part('cone',horn,0,22-i*5,-10-i*26,6,16,8,0,-.3);S.pop(); + const gait=b.act==='walk'?Math.sin(t*5):0;for(const sd of [-1,1])for(const fz of [-1,1]){const ph=gait*sd*fz;S.part('cyl',skin,sd*62,26+sink,fz*44+ph*8,16,52,18,0,ph*.3,0);S.part('box',dark,sd*62,4,fz*44+ph*10+8,22,8,30); + for(let c=-1;c<2;c++)S.part('cone',claw,sd*62+c*7,4,fz*44+ph*10+26,3,10,3,0,PI/2);} + // Head with the mouth that eats bombs: the inside glows hotter through the inhale. + S.push(0,92+sink,90,0,down?.35:-.1,0);S.part('ball',skin,0,0,8,44,36,50);S.part('box',belly,0,-18-open*14,30,40,10,46,0,open*.6); + S.part('box',skin,0,6+open*8,38,46,12,46,0,-open*.4);for(const c of [-1,1])for(let i=0;i<4;i++)S.part('cone',claw,c*(6+i*9),-4-open*6,52,2.4,7,2.4,0,PI); + const eyeCol=inh||blow?0xff5a2a:0xffe08a;for(const sd of [-1,1]){S.part('ball',S.mat(eyeCol,{em:0xaa4400}),sd*24,22,22,9);S.part('cone',horn,sd*28,30,-4,8,36,8,0,-.8,-sd*.5);} + if(heat>0)S.part('ball',S.mat(0xffb040,{basic:true,op:.5+.5*heat,add:true}),0,-6,40,16*heat+6,10*heat+4,10); + S.pop(); + if(down&&!dead)for(let i=0;i<3;i++){const a=t*4+i*2.1;S.flare(x+Math.sin(a+b.yaw)*30+Math.sin(b.yaw)*90,150+sink,z+Math.cos(a+b.yaw)*30+Math.cos(b.yaw)*90,16,0xfff0a0,.9);} + S.pop(); + const hx=x+Math.sin(b.yaw)*112,hz=z+Math.cos(b.yaw)*112; + if(heat>0)S.flare(hx,66+sink,hz,60+80*heat,0xff7a2a,.25+.45*heat); + if(inh)for(let i=0;i<6;i++){const k=((t*2+i/6)%1),r=60+(1-k)*200,a=b.yaw+(i-2.5)*.18;S.flare(hx+Math.sin(a)*r,60+Math.sin(i*2.3)*20,hz+Math.cos(a)*r,10+(1-k)*8,0xfff2d0,.5*k);}} + // Flames: hot core, orange halo, smoke tail, scorch under each. + for(const q of b.flames){const k=q.life/26,fx=q.ox+(q.x-q.ox)*f,fz=q.oz+(q.z-q.oz)*f,fy=24+Math.sin(q.idx+t*20)*6,r=18+(1-k)*20; + S.flare(fx,fy,fz,r*3.2,k>.5?0xff9a2a:0xff4a1a,.75*k+.2);S.flare(fx,fy,fz,r*1.4,0xffe8a0,.9*k);S.flare(fx-q.vx*.5,fy+10,fz-q.vz*.5,r*2,0x6a4030,.3*(1-k));S.decal('disc',fx,fz,r*1.2,0,0xff5a1a,.25*k);} + // Bombs: dark shell, sparking fuse, and the blast radius once the fuse is short. + for(const q of b.bombs){const bx=q.ox+(q.x-q.ox)*f,by=q.oy+(q.y-q.oy)*f,bz=q.oz+(q.z-q.oz)*f,blink=q.fuse<20&&(g.t>>2)%2===0;S.shadow(bx,0,bz,12); + S.part('ball',S.mat(blink?0xff4030:0x22263a),bx,by+12,bz,12);S.part('cyl',S.mat(0x8a7a5a),bx,by+26,bz,2,6,2);S.flare(bx,by+30,bz,14+Math.sin(t*40)*4,0xffd060,1); + if(q.fuse<24)S.decal('thin',bx,bz,BLAST,0,0xff4a2a,blink?.8:.45);} + if(h.holding){const hx=h.ox+(h.x-h.ox)*f,hz=h.oz+(h.z-h.oz)*f,blink=h.bombT<20&&(g.t>>2)%2===0;S.part('ball',S.mat(blink?0xff4030:0x22263a),hx,h.y+66,hz,11);S.flare(hx,h.y+80,hz,14+Math.sin(t*40)*4,0xffd060,1); + if(h.bombT<24)S.decal('thin',hx,hz,BLAST,0,0xff4a2a,blink?.8:.45);} + } + }; +})(window); diff --git a/environments/games/web/games/zelda_oot_remake/art/ganondrof.js b/environments/games/web/games/zelda_oot_remake/art/ganondrof.js new file mode 100644 index 0000000000000000000000000000000000000000..78c4f16874a022aefd9b809a4553138241f6d3aa --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/art/ganondrof.js @@ -0,0 +1,63 @@ +/* Original procedural look for the phantom sorcerer: a floating cloaked rider-less spectre with a crescent-bladed trident, in a round gallery of blank picture frames. No original model or texture is traced. + * Telegraphs (read from the state): before a throw the trident is raised and an energy orb grows on its tip for 25 frames (21 for the slow ball), with a green flare; + * before a charge (20 frames) he rears back, his eyes and cloak flare red and a red lane points at the hero. The ball is green while it flies at the hero + * and turns pale blue once the hero sends it back, so it is always clear whose turn it is. */ +(function(root){ + 'use strict'; + const R=root.ZeldaOot3D,PI=Math.PI,{canvasTex,noise}=R.tex; + R.art.ganondrof={camY:120,lookBias:.45,focusUp:0,focusR:70,lockR:(g,L)=>g.boss.act==='throw'?100:60, + hits(g){const b=g.boss;return b.inv>0&&b.act==='stunned'&&b.ground?[{x:b.x,y:b.y+50,z:b.z,k:b.inv/10,c:0xd8ffd8}]:[];}, + marker(g){const b=g.boss;return {x:b.x,y:b.y+50,z:b.z};}, + dangers(g){const b=g.boss,out=[];if(b.ball&&b.ball.mode==='green')out.push({x:b.ball.x,y:b.ball.y,z:b.ball.z,label:'Light orbs'});if(b.act==='charge')out.push({x:b.x,y:b.y+40,z:b.z,label:'Charge'});return out;}, + room(S,group){const T=root.THREE; + const floorTex=canvasTex(512,512,(q,w,h)=>{q.fillStyle='#2c3330';q.fillRect(0,0,w,h);noise(q,w,h,5000,51,'rgba(0,0,0,.35)','rgba(140,170,150,.1)',4); + q.strokeStyle='rgba(150,190,170,.25)';q.lineWidth=3;for(let r=40;r<256;r+=48){q.beginPath();q.arc(256,256,r,0,PI*2);q.stroke();} + for(let i=0;i<12;i++){q.beginPath();q.moveTo(256,256);q.lineTo(256+Math.cos(i*PI/6)*256,256+Math.sin(i*PI/6)*256);q.stroke();} + q.strokeStyle='rgba(160,255,190,.18)';q.lineWidth=6;q.beginPath();q.arc(256,256,232,0,PI*2);q.stroke();}); + const wallTex=canvasTex(512,256,(q,w,h)=>{q.fillStyle='#232a2a';q.fillRect(0,0,w,h);noise(q,w,h,2500,61,'rgba(0,0,0,.35)','rgba(120,150,140,.1)',5); + for(let i=0;i<4;i++){const x=24+i*128;q.fillStyle='#5a4426';q.fillRect(x,46,80,128);q.fillStyle='#8a6a32';q.fillRect(x+4,50,72,120);q.fillStyle='#10161a';q.fillRect(x+10,56,60,108); + const G=q.createLinearGradient(0,56,0,164);G.addColorStop(0,'rgba(80,140,110,.25)');G.addColorStop(1,'rgba(10,20,20,0)');q.fillStyle=G;q.fillRect(x+10,56,60,108);}},4,1); + S.addChamber(group,{r:330,h:520,floorTex,wallTex}); + // Columns between the frames and green torches above them (scenery, outside the floor radius). + const stone=new T.MeshLambertMaterial({color:0x3a4440,flatShading:true}),fire=new T.MeshBasicMaterial({color:0x9fff9f}); + for(let i=0;i<8;i++){const a=i*PI/4+PI/8,c=new T.Mesh(new T.CylinderGeometry(14,18,520,8),stone);c.position.set(Math.sin(a)*322,260,Math.cos(a)*322);group.add(c); + const fl=new T.Mesh(new T.SphereGeometry(7,8,6),fire);fl.position.set(Math.sin(a)*312,230,Math.cos(a)*312);group.add(fl);} + S.hemi.color.set(0xc8e8d8);S.hemi.groundColor.set(0x202826);S.hemi.intensity=2.0;S.sun.intensity=1.4;S.sun.color.set(0xd8f0e0);S.glow.color.set(0x9cff9c);S.glow.intensity=0;S.world.background=new T.Color(0x0b0f0e);S.world.fog=new T.Fog(0x0b0f0e,500,1200);}, + focus(g){const b=g.boss;return b.ball?{x:(b.x+b.ball.x)/2,y:(b.y+b.ball.y)/2,z:(b.z+b.ball.z)/2}:b;}, + draw(S,g,f){const b=g.boss,x=b.ox+(b.x-b.ox)*f,y=b.oy+(b.y-b.oy)*f,z=b.oz+(b.z-b.oz)*f,t=g.t/60; + for(let i=0;i<8;i++){const a=i*PI/4+PI/8;S.flare(Math.sin(a)*312,232+Math.sin(t*9+i)*3,Math.cos(a)*312,34,0x7aff8a,.6);} + const flash=b.inv>0&&(g.t>>1)%2===0,shock=b.act==='stunned'&&!b.ground,charging=b.act==='charge',wind=charging&&b.sub==='wind'; + const cloak=S.mat(flash||shock&&(g.t>>2)%2?0xffffff:charging?0x40243a:0x2a2440,{em:charging?0x300810:0x0a0618}),trim=S.mat(0xb08a3a,{em:0x201400}),mask=S.mat(0xd8d0c0),eyeCol=charging?0xff2a1a:0xff7a3a; + S.shadow(x,0,z,40); + // Charge lane: from him toward the hero through the wind-up. + if(wind){const h=g.hero,dx=h.x-x,dz=h.z-z,L=Math.hypot(dx,dz);S.decal('strip',x,z,Math.min(L+60,560),70,0xff3a2a,.18+.3*(1-b.t0/20),Math.atan2(dx,dz));} + const down=b.act==='stunned'&&b.ground,lean=charging?(wind?-.35:.7):down?1.1:0,throwArm=b.act==='throw'?Math.min(1,b.af/b.throwFrame):b.act==='return'?1:0,bob=Math.sin(t*3)*3; + S.push(x,y+bob,z,b.yaw,lean,0); + // Robe: layered tattered skirt, cape, shoulder plates; the hem streams in tatters that sway. + S.part('cone',cloak,0,30,0,34,80,30,0,PI);S.part('cone',cloak,0,40,-10,38,70,26,0,PI+.12);S.part('ball',cloak,0,70,0,24,26,22);S.part('cyl',trim,0,52,0,26,6,24); + for(const sd of [-1,1]){S.part('ball',trim,sd*24,82,0,12,8,12);S.part('cone',trim,sd*30,88,0,4,14,4,0,0,-sd*.8);} + for(let i=0;i<7;i++){const a=t*3+i;S.part('cone',cloak,Math.sin(i*.9)*22,-14-Math.sin(a)*6,Math.cos(i*.9)*16,7,32,7,0,PI+Math.sin(a)*.15);} + // Masked head with horns, eyes that burn hotter before a charge. + S.push(0,96,6,0,0,0);S.part('ball',mask,0,0,4,15,17,13);S.part('box',S.mat(0x1a1420),0,-4,14,10,3,2);S.part('ball',S.mat(eyeCol,{em:0xaa2010}),-5,3,14,3);S.part('ball',S.mat(eyeCol,{em:0xaa2010}),5,3,14,3); + for(const sd of [-1,1])S.part('cone',trim,sd*12,14,-2,4,24,4,0,-.3,-sd*.6);S.part('cone',cloak,0,10,-8,18,28,18,0,-.4);S.pop(); + // Trident arm: raised to throw, swung to return the ball; the orb grows on its tip until the throw frame. + S.push(-26,66,4,0,-.6-throwArm*1.4,0);S.part('cyl',cloak,0,10,0,6,26,6);S.part('cyl',trim,0,30,0,2.2,70,2.2);S.part('cone',S.mat(0xd8e0e8,{em:0x203040}),0,70,0,7,16,2); + for(const sd of [-1,1])S.part('cone',S.mat(0xd8e0e8,{em:0x203040}),sd*8,64,0,3,12,2,0,0,-sd*.5); + S.pop(); + S.pop(); + // World-space glows (outside push/pop so sprites sit in the room's frame). + const eyeY=y+bob+99,fx=Math.sin(b.yaw),fz=Math.cos(b.yaw);for(const sd of [-1,1])S.flare(x+fx*20+fz*sd*5,eyeY,z+fz*20-fx*sd*5,charging?26:14,eyeCol,charging?.9:.6); + if(b.act==='throw'&&b.afo===undefined?a:o+(a-o)*f,x=ip(b.x,b.ox),y=ip(b.y,b.oy),z=ip(b.z,b.oz),fw=b.y>100?0:34; + return {x:x+Math.sin(b.yaw)*fw,y:y>100?y-28:y+50,z:z+Math.cos(b.yaw)*fw};}, + focusR:62,lockR:(g,L)=>L.id==='eye'?(g.boss.y>100?70:56):26, + threat(g){const b=g.boss,L=g.lockTarget();if(b.y>100&&L&&L.id!=='eye')return {x:b.x,y:b.y-20,z:b.z,r:70};return null;}, + hits(g){const b=g.boss,out=[],e={x:b.x+Math.sin(b.yaw)*(b.y>100?0:34),y:b.y>100?b.y-50:b.y+(b.act==='stunned'||b.act==='damaged'?34:62),z:b.z+Math.cos(b.yaw)*(b.y>100?0:34)}; + if(b.act==='damaged')out.push({...e,k:1-b.af/16});else if(b.inv>0)out.push({...e,k:b.inv/10,c:0xd8ff8a}); + for(const k of b.kids)if(k.inv>0&&k.act==='hurt')out.push({x:k.x,y:k.y+14,z:k.z,k:k.inv/10*.6});return out;}, + marker(g){const b=g.boss;return {x:b.x,y:b.y>100?b.y-20:b.y+40,z:b.z};}, + dangers(g){const b=g.boss,out=[];if(b.act==='posture'||(b.act==='attack'&&b.sub===0))out.push({x:b.x,y:40,z:b.z,label:'Leg strike'}); + for(const k of b.kids){if(k.act==='prep'||k.act==='jump')out.push({x:k.x,y:k.y+12,z:k.z,label:'Pounce'});} + if(b.act==='fallJump'||b.act==='fallStruck')out.push({x:b.x,y:0,z:b.z,label:'Landing'});return out;}, + room(S,group){const T=root.THREE; + const floorTex=canvasTex(512,512,(q,w,h)=>{q.fillStyle='#3a3a2a';q.fillRect(0,0,w,h);noise(q,w,h,5000,11,'rgba(20,24,12,.34)','rgba(120,120,80,.13)',5); + q.strokeStyle='rgba(16,20,10,.55)';for(let i=0;i<46;i++){q.lineWidth=2+i%3;q.beginPath();let x=(i*97)%w,y=(i*211)%h;q.moveTo(x,y);for(let k=0;k<5;k++){x+=((i*k*37)%90)-45;y+=((i*k*53)%90)-45;q.lineTo(x,y);}q.stroke();} + for(let i=0;i<30;i++){const x=(i*173)%w,y=(i*89)%h,G=q.createRadialGradient(x,y,1,x,y,10+i%7*3);G.addColorStop(0,'rgba(140,200,120,.22)');G.addColorStop(1,'rgba(140,200,120,0)');q.fillStyle=G;q.fillRect(x-30,y-30,60,60);}},4,4); + const wallTex=canvasTex(512,256,(q,w,h)=>{q.fillStyle='#2e2c22';q.fillRect(0,0,w,h);noise(q,w,h,3000,23,'rgba(10,12,8,.4)','rgba(110,110,70,.12)',6); + q.strokeStyle='rgba(70,84,40,.75)';q.lineCap='round';for(let i=0;i<26;i++){q.lineWidth=3+i%6;q.beginPath();let x=(i*71)%w,y=0;q.moveTo(x,y);while(y{q.fillStyle='#22221a';q.fillRect(0,0,w,h);noise(q,w,h,1600,5,'rgba(0,0,0,.3)','rgba(90,90,60,.13)',7); + q.strokeStyle='rgba(60,70,36,.6)';q.lineWidth=5;for(let i=0;i<12;i++){q.beginPath();q.moveTo(128,128);q.quadraticCurveTo(128+Math.cos(i)*90,128+Math.sin(i*1.3)*90,128+Math.cos(i*.52)*128,128+Math.sin(i*.52)*128);q.stroke();}},3,3); + S.addChamber(group,{r:430,h:360,floorTex,wallTex,ceilTex}); + // Hanging roots and glowing fungus clumps round the wall (scenery only, outside the play radius). + const root_=new T.MeshLambertMaterial({color:0x3e4a26,flatShading:true}),fungus=new T.MeshLambertMaterial({color:0x3a5a3a,emissive:0x1a3a24}); + for(let i=0;i<18;i++){const a=i*PI/9+.2,r=418,len=80+(i*37)%120,m=new T.Mesh(new T.ConeGeometry(4+i%3*2,len,5),root_);m.position.set(Math.sin(a)*r,360-len/2,Math.cos(a)*r);m.rotation.z=PI;group.add(m); + if(i%2===0){const c=new T.Mesh(new T.SphereGeometry(5+i%4,8,6),fungus);c.position.set(Math.sin(a+.1)*(r-4),20+(i*13)%60,Math.cos(a+.1)*(r-4));group.add(c);}} + S.hemi.color.set(0xb7d6a8);S.hemi.groundColor.set(0x3b3424);S.hemi.intensity=2.6;S.sun.intensity=2.2;S.sun.color.set(0xe8f2c8);S.glow.intensity=0;S.world.background=new T.Color(0x0d0f09);S.world.fog=new T.Fog(0x0d0f09,700,1500);}, + draw(S,g,f){const b=g.boss,x=b.ox+(b.x-b.ox)*f,y=b.oy+(b.y-b.oy)*f,z=b.oz+(b.z-b.oz)*f,t=g.t/60,dead=b.act==='dead',red=['posture','attack','prepEggs'].includes(b.act),stun=b.act==='stunned'||b.act==='damaged'; + const hitFlash=b.inv>0&&(g.t>>1)%2===0; + const shell=S.mat(hitFlash?0xffffff:0x4a5e46,{em:red?0x3a1008:0x0a1208}),plate=S.mat(hitFlash?0xffffff:0xa8a47e),plate2=S.mat(hitFlash?0xffffff:0xd0c89e),limb=S.mat(0x2a3324),joint=S.mat(0x6d6a50),claw=S.mat(0xd8d0b0); + const eyeCol=red?0xff3a1a:stun?0xfff2a0:0x66ffcc,glow=S.mat(eyeCol,{em:red?0xaa2200:stun?0x887a22:0x118866}); + S.shadow(x,0,z,70); + const onCeil=y>100,flip=onCeil?PI:0,climb=b.act==='climb'?-PI/2:0,base=onCeil?y-32:y+44,legK=onCeil?1.75:1.2; + // Leg-strike telegraph: a red sector of the strike's reach in front of her, filling as the rear-up runs (posture 33 frames), solid on the hit frames. + if(b.act==='posture'||(b.act==='attack'&&b.sub===0&&b.af<=13)){const k=b.act==='posture'?Math.min(1,b.af/33):1,hot=b.act==='attack'&&b.af>=7; + S.decal('sector',x,z,LEG_REACH,.8,0xff3a1a,hot?.55:.18+.22*k,b.yaw);S.decal('sector',x,z,LEG_REACH*k,.8,0xff6a3a,hot?.4:.3,b.yaw);S.decal('thin',x,z,LEG_REACH,0,0xff5a3a,.6);} + S.push(x,base,z,b.yaw,climb,flip); + const attack=b.act==='attack'&&b.sub===0?Math.sin(Math.min(1,b.af/12)*PI):0,rear=b.act==='posture'?Math.min(1,b.af/20):0,breathe=Math.sin(t*3)*1.5; + if(dead){const k=Math.max(0,b.timer/30);S.push(0,-10*(1-k),0,0,(1-k)*.4,0,.6+.4*k);} + // Abdomen: banded shell plates over a soft underbelly; the egg sac swells and glows red before eggs. + const sac=b.act==='prepEggs'?.5+.5*Math.sin(t*14):b.act==='spawnEggs'?1:0; + S.part('ball',shell,0,4+rear*5+breathe,-20,38,28,48);for(let i=0;i<3;i++)S.part('ball',plate,0,18+rear*7-i*2+breathe,-6-i*16,30-i*3,8,14); + for(let i=0;i<4;i++){const swell=b.act==='spawnEggs'&&((b.spawnT-24)>>3)===i?1.5:1,r=(22-i*4)*swell;S.part('ball',shell,0,6-i*3,-62-i*20,r,r*.86,r);S.part('ball',plate2,0,12-i*3,-62-i*20,r*.7,r*.3,r*.76);} + if(sac>0)S.flare(0,4,-90,90*sac,0xff4a2a,.5*sac); + // Head: crest horns, mandibles that open on the strike, and the single eye under a lid. + S.push(0,18+rear*18,26,0,-rear*.5-attack*.1); + S.part('ball',shell,0,0,4,28,24,26);S.part('cone',plate2,0,22,-2,7,18,7,0,-.3);S.part('cone',plate,-14,16,4,5,14,5,0,0,.5);S.part('cone',plate,14,16,4,5,14,5,0,0,-.5); + const jaw=.2+rear*.5+attack*.4;for(const sd of [-1,1])S.part('cone',claw,sd*10,-14,26,3.5,20,3.5,sd*jaw,PI/2-.4,0); + const lid=b.eyeLid||0,ey=stun?-28:0;S.part('ball',glow,0,ey,24,16);S.part('ball',S.mat(0x0a0a0a),0,ey,36,6,9,4); + S.part('hemi',S.mat(0x4a5a42),0,ey,24,17.5,17.5*Math.max(.05,lid),17.5,0,0,0);S.part('hemi',S.mat(0x4a5a42),0,ey,24,17.5,17.5*Math.max(.05,lid),17.5,0,PI,0); + if(lid<.6)S.flare(0,ey,32,(red?70:stun?54:40)*(1-lid),eyeCol,red?.8:.5); + S.pop(); + // Six jointed legs; the front pair rise and slam. + const walk=b.act==='main'||b.act==='ceilMove'?t*7:0; + for(let i=0;i<3;i++)for(const sd of [-1,1]){const ph=walk+i*2.1+(sd>0?PI:0),lift=Math.max(0,Math.sin(ph))*12; + const front=i===2,up=front?(rear*40-attack*48):0; + S.push(sd*18,6,(i-1)*18-4,PI/2*sd-(i-1)*.6*sd,0,0); + S.part('box',limb,0,8+lift*.5+up*.4,20,7,7,44,0,-.5-up*.012);S.part('ball',joint,0,22+lift+up*.8,40,6.5);const L=62*legK,ca=PI-.5+up*.012,dy=Math.cos(ca),dz=Math.sin(ca);S.part('cone',limb,0,21+lift+up*.9+dy*L/2,43+dz*L/2,5.5,L,5.5,0,ca); + S.part('cone',claw,0,21+lift+up*.9+dy*(L+5),43+dz*(L+5),3,12,3,0,ca);S.pop();} + if(dead)S.pop(); + S.pop(); + if(stun){for(let i=0;i<3;i++){const a=t*4+i*2.1;S.flare(x+Math.sin(a)*30,y+92,z+Math.cos(a)*30,16,0xfff0a0,.9);}} + // Eggs: the landing spot is marked while one falls; an egg about to hatch throbs. Larvae crouch and flash red before a pounce. + for(const k of b.kids){const kx=k.ox+(k.x-k.ox)*f,ky=k.oy+(k.y-k.oy)*f,kz=k.oz+(k.z-k.oz)*f;S.shadow(kx,0,kz,20); + if(k.act==='fall'){S.decal('thin',kx,kz,22+Math.min(30,ky*.1),0,0xffd04a,.7);S.decal('disc',kx,kz,16,0,0xffd04a,.25);} + if(k.act==='fall'||k.act==='egg'){const late=k.act==='egg'?(80-k.timer)/80:0,pulse=1+Math.sin(g.t*(.25+late*.5))*.05*(1+late*3); + S.part('ball',S.mat(0xbcc48a,{em:late>.7?0x332200:0x223300}),kx,ky+15,kz,14*pulse,18*pulse,14*pulse);S.part('ball',S.mat(0x7c8a50),kx,ky+24,kz,6,6,6);if(late>.6)S.flare(kx,ky+16,kz,36*late,0xd8ff6a,.4);} + else{const prep=k.act==='prep',jump=k.act==='jump',sq=prep?.7:1,warn=prep&&(g.t>>2)%2===0; + S.push(kx,ky+12*sq,kz,k.yaw);S.part('ball',S.mat(k.inv>0?0xffffff:warn?0xc8402a:0x46563a),0,0,0,15,12*sq,15);S.part('ball',S.mat(prep||jump?0xff5a3a:0x88ffcc,{em:prep||jump?0x882010:0x116644}),0,4,12,6); + for(let i=0;i<3;i++)for(const sd of [-1,1]){const w=Math.sin(g.t*.5+i)*.3;S.part('box',S.mat(0x2a3324),sd*14,-4+w*3,-7+i*7,16,3,3,sd*(i-1)*.4);}S.pop(); + if(prep||jump){S.flare(kx,ky+18,kz+0,30,0xff5a3a,.6);S.decal('strip',kx,kz,150,26,0xff4a2a,.28,k.yaw);}}} + } + }; +})(window); diff --git a/environments/games/web/games/zelda_oot_remake/art/morpha.js b/environments/games/web/games/zelda_oot_remake/art/morpha.js new file mode 100644 index 0000000000000000000000000000000000000000..7c6e1a7c368e867e8dfdc6669016515e29bf9485 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/art/morpha.js @@ -0,0 +1,58 @@ +/* Original procedural look for the water nucleus: a glassy red nucleus in a square pool, raising a translucent column of water that lashes out. No original model or texture is traced. + * Telegraphs (read from the state): a tentacle about to rise shows a rippling ring at its root (70-frame rise); while it sways (40-62 frames) a lane on the floor shows where the lash + * will land, filling as the sway runs out; once it curls a ring marks the grab. The nucleus glows through the water so it can be followed while it hides. */ +(function(root){ + 'use strict'; + const R=root.ZeldaOot3D,PI=Math.PI,{canvasTex,noise}=R.tex,POOL=380,A=520,REACH=360; + R.art.morpha={camY:160,lookBias:.4,focusUp:0,focusR:70,lockR:40, + hits(g){const c=g.boss.core;return c.flash>0&&c.y>-10?[{x:c.x,y:c.y+12,z:c.z,k:c.flash/15,c:0xc8f0ff}]:[];}, + marker(g){const c=g.boss.core;return c.y>-10?{x:c.x,y:c.y+12,z:c.z}:null;}, + dangers(g){const out=[];for(const t of g.boss.tents){if(t.st==='spawn'||t.st==='swing'||t.st==='attack'||t.st==='curl')out.push({x:t.x,y:20,z:t.z,label:t.st==='spawn'?'Tentacles':t.st==='curl'?'Grab':'Whip'});}return out;}, + room(S,group){const T=root.THREE; + const floorTex=canvasTex(1024,1024,(q,w,h)=>{q.fillStyle='#3b4a52';q.fillRect(0,0,w,h);noise(q,w,h,9000,91,'rgba(0,0,0,.3)','rgba(160,200,220,.1)',5); + q.strokeStyle='rgba(20,30,36,.5)';q.lineWidth=3;for(let i=0;i<=16;i++){const p=i*w/16;q.beginPath();q.moveTo(p,0);q.lineTo(p,h);q.stroke();q.beginPath();q.moveTo(0,p);q.lineTo(w,p);q.stroke();} + const m=(A-POOL)/(2*A)*w,G=q.createLinearGradient(0,m,0,h-m);G.addColorStop(0,'#1f5e78');G.addColorStop(.5,'#2a7896');G.addColorStop(1,'#1f5e78');q.fillStyle=G;q.fillRect(m,m,w-2*m,h-2*m); + q.strokeStyle='rgba(200,240,255,.35)';q.lineWidth=2;let s=5;const r=()=>(s=(s*16807)%2147483647)/2147483647;for(let i=0;i<70;i++){const x=m+r()*(w-2*m),y=m+r()*(h-2*m),l=20+r()*50;q.beginPath();q.moveTo(x,y);q.quadraticCurveTo(x+l/2,y-6,x+l,y);q.stroke();} + q.strokeStyle='#8fa6ae';q.lineWidth=8;q.strokeRect(m,m,w-2*m,h-2*m);}); + const wallTex=canvasTex(1024,512,(q,w,h)=>{q.fillStyle='#2a383f';q.fillRect(0,0,w,h);noise(q,w,h,6000,93,'rgba(0,0,0,.3)','rgba(140,190,210,.1)',6); + q.strokeStyle='rgba(140,190,210,.25)';q.lineWidth=3;for(let i=0;i<8;i++){q.strokeRect(20+i*126,60,96,h-120);}},4,1); + const fl=new T.Mesh(new T.PlaneGeometry(2*A,2*A),new T.MeshLambertMaterial({map:floorTex}));fl.rotation.x=-PI/2;group.add(fl); + for(let i=0;i<4;i++){const wl=new T.Mesh(new T.PlaneGeometry(2*A,600),new T.MeshLambertMaterial({map:wallTex}));const a=i*PI/2;wl.position.set(Math.sin(a)*A,300,Math.cos(a)*A);wl.rotation.y=a+PI;group.add(wl);} + // A raised kerb round the pool and blue lamps in the corners (scenery only). + const kerb=new T.MeshLambertMaterial({color:0x6a828a,flatShading:true});for(let i=0;i<4;i++){const a=i*PI/2,k=new T.Mesh(new T.BoxGeometry(2*POOL+16,6,8),kerb);k.position.set(Math.sin(a)*(POOL+4),3,Math.cos(a)*(POOL+4));k.rotation.y=a;group.add(k);} + const lamp=new T.MeshBasicMaterial({color:0x9fe8ff});for(let i=0;i<8;i++){const a=i*PI/4,l=new T.Mesh(new T.SphereGeometry(10,10,8),lamp),r=i%2?A*1.38:A-2;l.position.set(Math.sin(a)*r,230,Math.cos(a)*r);if(i%2===0)group.add(l);} + S.hemi.color.set(0xd0f0ff);S.hemi.groundColor.set(0x203038);S.hemi.intensity=2.1;S.sun.intensity=1.5;S.sun.color.set(0xe8f6ff);S.glow.color.set(0xff6a5a);S.glow.intensity=0;S.world.background=new T.Color(0x0c1418);S.world.fog=new T.Fog(0x0c1418,900,2000);}, + threat(g){const b=g.boss,c=b.core;let best=null,bd=1e9;for(const t of b.tents){if(!['spawn','swing','attack','curl'].includes(t.st))continue;if((c.act==='ride'||c.act==='back')&&t.i===0)continue; + const d=Math.hypot(t.x-g.hero.x,t.z-g.hero.z);if(d-10?{x:c.x,y:c.y+12,z:c.z}:{x:t.x,y:Math.max(40,140*t.grow),z:t.z};}, + draw(S,g,f){const b=g.boss,c=b.core,t0=g.t/60,h=g.hero; + for(let i=0;i<4;i++){const a=i*PI/2;S.flare(Math.sin(a)*(A-8),230,Math.cos(a)*(A-8),90,0x9fe8ff,.5);} + // Surface shimmer over the pool. + for(let i=0;i<10;i++){const u=(t0*.3+i*.1)%1,x=Math.sin(i*2.7)*POOL*.85,z=Math.cos(i*1.9)*POOL*.85;S.decal('thin',x,z,10+u*50,0,0xd8f6ff,.35*(1-u));} + for(const t of b.tents){ + const swing=t.st==='swing',lash=t.st==='attack',curl=t.st==='curl'||t.st==='grab'||t.st==='shake'; + if(t.st==='wait'&&t.i===1&&t.t0<20||t.st==='spawn'){const k=.7+Math.sin(t0*12)*.3;S.decal('ring',t.x,t.z,50*k+20,0,0xd8f6ff,.5);S.decal('thin',t.x,t.z,90,0,0xff7a5a,.6);} + if(t.grow<=0.02&&t.st!=='spawn')continue; + // Lash lane: from the root toward where it will strike, filling as the sway runs down; bright while it lashes. + if(swing||lash&&t.ext<.6){const k=swing?Math.max(0,1-t.t0/50):1;S.decal('strip',t.x,t.z,REACH+40,84,0xff3a2a,swing?.12+.3*k:.45,t.yaw);S.decal('strip',t.x,t.z,(REACH+40)*k,30,0xff8a6a,.35,t.yaw);} + if(t.st==='curl')S.decal('thin',t.x+Math.sin(t.yaw)*REACH*.55,t.z+Math.cos(t.yaw)*REACH*.55,90,0,0xff3a2a,.8); + const water=S.mat(swing?0xc8f0ff:0x9fe2ff,{em:swing||lash?0x3a2a40:0x1a4a60,op:.62}); + const pt=fr=>{const s=Math.sin(t.sway+fr*2.2)*fr*fr*36*(1-t.ext),H=280*t.grow,dx=Math.sin(t.yaw),dz=Math.cos(t.yaw),ux=t.x+Math.cos(t.yaw)*s,uz=t.z-Math.sin(t.yaw)*s,uy=fr*H,sx=t.x+dx*fr*360,sz=t.z+dz*fr*360,sy=24+(1-fr)*(1-fr)*H*.55; + return {x:ux+(sx-ux)*t.ext,y:uy+(sy-uy)*t.ext,z:uz+(sz-uz)*t.ext};}; + const n=18;for(let i=0;i<=n;i++){const fr=i/n,p=pt(fr),r=(30-fr*16)*(.4+.6*t.grow)*(t.st==='cut'?Math.max(.2,1-fr):1);S.part('ball',water,p.x,p.y,p.z,r,r*1.15,r);if(i%3===0)S.flare(p.x,p.y,p.z,r*2.2,swing?0xffb0a0:0x9fe8ff,.22);} + const tip=pt(1);S.part('ico',S.mat(0xe8fbff,{basic:true,op:.5}),tip.x,tip.y,tip.z,14,14,14,t0*4,t0*3);S.flare(tip.x,tip.y,tip.z,swing?60:40,swing?0xff8a6a:0xc8f4ff,.6); + if(lash)for(let i=0;i<5;i++){const u=(t0*3+i/5)%1,p=pt(.4+u*.6);S.flare(p.x,p.y+10,p.z,20,0xffffff,.4*(1-u));} + S.decal('ring',t.x,t.z,46,0,0xd8f6ff,.45);for(let i=0;i<3;i++){const u=(t0*1.2+i/3)%1;S.decal('thin',t.x,t.z,46+u*60,0,0xd8f6ff,.4*(1-u));}} + // The nucleus: a red core with a glassy shell, a glow that shows through the water, and a trail while it rides the tentacle. + if(c.y>-60){const x=c.ox+(c.x-c.ox)*f,y=c.oy+(c.y-c.oy)*f,z=c.oz+(c.z-c.oz)*f,hit=c.flash>0&&(g.t>>1)%2===0,under=y<-10,stunned=c.act==='stunned'; + S.part('ball',S.mat(hit?0xffffff:0xd8323a,{em:0x6a0a10}),x,y+12,z,18,18,18);S.part('ball',S.mat(0xffffff,{basic:true,op:.35}),x,y+12,z,26,24,26); + S.part('ball',S.mat(0xffd0c8,{basic:true}),x+5,y+18,z+6,4);S.flare(x,y+12,z,under?70:90,0xff4a3a,under?.35:.55); + if(!under)S.shadow(x,0,z,20);else S.decal('disc',x,z,30,0,0xff4a3a,.3); + if(stunned&&!under)for(let i=0;i<3;i++){const a=t0*4+i*2.1;S.flare(x+Math.sin(a)*24,y+44,z+Math.cos(a)*24,14,0xfff0a0,.9);} + S.glow.position.set(x,y+20,z);S.glow.intensity=y>-10?2:.8;} + // Held by a tentacle: the squeeze shows as rings closing round the hero. + if(h.grabbed)for(let i=0;i<3;i++){const u=(t0*2+i/3)%1;S.part('ring',S.mat(0xc8f0ff,{basic:true,op:.6*(1-u),add:true}),h.x,h.y+30,h.z,40-u*20,40-u*20,40-u*20,0,-PI/2);} + } + }; +})(window); diff --git a/environments/games/web/games/zelda_oot_remake/art/twinrova.js b/environments/games/web/games/zelda_oot_remake/art/twinrova.js new file mode 100644 index 0000000000000000000000000000000000000000..de62b5d442e8ed131c5e675362e465f436903eb1 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/art/twinrova.js @@ -0,0 +1,57 @@ +/* Original procedural look for the twin-element witch: a hovering sorceress in split red-and-pale-blue robes over a sandstone disc. No original model or texture is traced. + * Her four perches are floating rune circles, not towers, so she can be followed all the way down when knocked out of the air (the rules have no tower bodies). + * Telegraphs (read from the state): arriving at a perch (25 frames) and winding up (30 frames) the sceptre of the coming element glows and a coloured line runs to the hero; + * the blast leaves on frame 12 of the throw. Blasts are fire-orange or ice-blue with trails; the hero's reflected charge is a white-gold beam, so who fired what is always clear. */ +(function(root){ + 'use strict'; + const R=root.ZeldaOot3D,PI=Math.PI,{canvasTex,noise}=R.tex,A=640,PERCH=[[580,0],[0,580],[-580,0],[0,-580]],FIRE=0xff6a1a,ICE=0x7ad8ff; + R.art.twinrova={camY:170,lookBias:.45,focusUp:0,focusR:70,lockR:70, + hits(g){const b=g.boss;return b.inv>0?[{x:b.x,y:b.y+40,z:b.z,k:b.inv/20}]:[];}, + marker(g){const b=g.boss;return {x:b.x,y:b.y+40,z:b.z};}, + dangers(g){const out=[];for(const q of g.boss.blasts)out.push({x:q.x,y:q.y,z:q.z,label:q.el?'fire':'ice'});return out;}, + room(S,group){const T=root.THREE; + const floorTex=canvasTex(1024,1024,(q,w,h)=>{q.fillStyle='#6b5038';q.fillRect(0,0,w,h);noise(q,w,h,12000,101,'rgba(0,0,0,.3)','rgba(230,190,140,.12)',5); + q.strokeStyle='rgba(40,24,14,.45)';q.lineWidth=3;for(let r=60;r<512;r+=70){q.beginPath();q.arc(512,512,r,0,PI*2);q.stroke();} + const G=q.createLinearGradient(0,0,w,0);G.addColorStop(0,'rgba(255,90,40,.28)');G.addColorStop(.5,'rgba(0,0,0,0)');G.addColorStop(1,'rgba(120,200,255,.28)');q.fillStyle=G;q.fillRect(0,0,w,h); + q.strokeStyle='rgba(255,220,160,.25)';q.lineWidth=4;for(let i=0;i<8;i++){q.beginPath();q.moveTo(512,512);q.lineTo(512+Math.cos(i*PI/4)*500,512+Math.sin(i*PI/4)*500);q.stroke();}}); + const wallTex=canvasTex(1024,512,(q,w,h)=>{q.fillStyle='#2b1d18';q.fillRect(0,0,w,h);noise(q,w,h,6000,103,'rgba(0,0,0,.35)','rgba(200,150,110,.1)',6); + for(let i=0;i<12;i++){const x=i*86+20,G=q.createLinearGradient(0,h,0,0);G.addColorStop(0,i%2?'rgba(255,110,50,.35)':'rgba(110,200,255,.35)');G.addColorStop(1,'rgba(0,0,0,0)');q.fillStyle=G;q.fillRect(x,0,8,h);}},4,1); + S.addChamber(group,{r:A,h:900,floorTex,wallTex}); + S.hemi.color.set(0xffe2c8);S.hemi.groundColor.set(0x3a2418);S.hemi.intensity=2.2;S.sun.intensity=1.6;S.sun.color.set(0xfff0e0);S.glow.intensity=0;S.world.background=new T.Color(0x140c0a);S.world.fog=new T.Fog(0x140c0a,1100,2400);}, + focus(g){return g.boss;}, + draw(S,g,f){const b=g.boss,x=b.ox+(b.x-b.ox)*f,y=b.oy+(b.y-b.oy)*f,z=b.oz+(b.z-b.oz)*f,t=g.t/60,flash=b.inv>0&&(g.t>>1)%2===0,down=b.act==='stun'||b.act==='dead',h=g.hero; + // Perches: floating rune circles at her landing height, the one she is heading for lit. + PERCH.forEach(([px,pz],i)=>{const on=b.perch===i&&b.act!=='stun'&&b.act!=='dead',col=i%2?ICE:FIRE; + S.part('ring',S.mat(col,{basic:true,op:on?.85:.4,add:true}),px,372,pz,70,70,70,t*(i%2?-.6:.6),-PI/2);S.part('ring',S.mat(0xfff0d0,{basic:true,op:on?.6:.25,add:true}),px,372,pz,46,46,46,-t*.9,-PI/2); + S.flare(px,372,pz,on?160:90,col,on?.45:.2);}); + const fire=S.mat(flash?0xffffff:0xc8402a),ice=S.mat(flash?0xffffff:0x9fd6ff),skin=S.mat(0xd8c8b0),hair=S.mat(0xf2f0ea),gold=S.mat(0xe0b040,{em:0x402a00}); + S.shadow(x,0,z,50*(1+Math.max(0,400-y)/400)); + // Wind-up: the coming element is decided only at the end of the wind-up (W4), so the wind-up shows both sceptres; the throw shows the chosen one. + const arrive=b.act==='arrive',wind=b.act==='windup',thr=b.act==='throw'&&b.af<12,el=b.act==='throw'?b.element:-1,ch=arrive?1-b.t0/25:wind?1:thr?1:0; + if(ch>0){const dx=h.x-x,dz=h.z-z,L=Math.hypot(dx,dz),col=el===1?FIRE:el===0?ICE:0xffe0a0;S.decal('strip',x,z,L,40,col,(wind||thr)?.3:.12,Math.atan2(dx,dz));S.decal('thin',h.x,h.z,40,0,col,(wind||thr)?.8:.4);} + S.push(x,y,z,b.yaw,down?1.2:0,0); + S.part('cone',fire,-12,10,0,26,70,30,0,PI,.15);S.part('cone',ice,12,10,0,26,70,30,0,PI,-.15); + for(let i=0;i<5;i++){const a=t*3+i;S.part('cone',i%2?ice:fire,-16+i*8,-24-Math.sin(a)*5,Math.cos(i)*8,6,26,6,0,PI+Math.sin(a)*.2);} + S.part('ball',fire,-9,48,0,15,20,15);S.part('ball',ice,9,48,0,15,20,15);S.part('ball',skin,0,74,4,13); + for(const sd of [-1,1]){S.part('cone',hair,sd*10,88,-4,8,30,8,0,-.2,sd*.6);S.part('ball',S.mat(sd<0?0xff5a2a:0x6ac8ff,{basic:true}),sd*5,78,15,2.5);} + S.part('torus',gold,0,96,0,10,10,10,0,PI/2);S.part('cone',gold,0,104,0,6,14,6); + for(const sd of [-1,1]){S.push(sd*34,50,6,0,-.3-(ch>0?.6:0),sd*.4);S.part('cyl',gold,0,0,0,2.4,70,2.4);S.part('ico',S.mat(sd<0?0xff7a2a:0x9fe2ff,{basic:true,op:.9}),0,40,0,7+(ch>0&&(el<0||(el===1)===(sd<0))?6*ch:0));S.pop();} + S.pop(); + // World-space glows at the two sceptre heads. + const c=Math.cos(b.yaw),s=Math.sin(b.yaw);for(const sd of [-1,1]){const lit=ch>0&&(el<0||(el===1)===(sd<0)),px=x+c*sd*34+s*20,pz=z-s*sd*34+c*20,py=y+(down?30:92); + S.flare(px,py,pz,lit?40+80*ch:26,sd<0?FIRE:ICE,lit?.9:.45);} + if(ch>0){S.glow.position.set(x,y+40,z);S.glow.color.set(el===1?FIRE:el===0?ICE:0xffd0a0);S.glow.intensity=1+2*ch;}else S.glow.intensity=0; + if(down)for(let i=0;i<3;i++){const a=t*4+i*2.1;S.flare(x+Math.sin(a)*30,y+70,z+Math.cos(a)*30,16,0xfff0a0,.9);} + // Blasts: element-coloured cores with a long trail and a marker under them. + for(const q of b.blasts){const bx=q.ox+(q.x-q.ox)*f,by=q.oy+(q.y-q.oy)*f,bz=q.oz+(q.z-q.oz)*f,col=q.el?FIRE:ICE; + S.part('ico',S.mat(q.el?0xffd0a0:0xe8faff,{basic:true}),bx,by,bz,12,12,12,t*6,t*5);S.bolt(bx,by,bz,q.ox,q.oy,q.oz,14,q.el?0xffe0b0:0xf0fcff,col,6); + for(let k=0;k<3;k++){const a=t*20+k*2.1;S.flare(bx+Math.sin(a)*16,by+Math.cos(a)*16,bz+Math.cos(a*1.3)*16,10,col,.6);}S.shadow(bx,0,bz,14);S.decal('thin',bx,bz,22,0,col,.6);} + // The hero's reflected charge: a white-gold beam with the soaked element's rim. + for(const sh of b.shots){const sx=sh.ox+(sh.x-sh.ox)*f,sy=sh.oy+(sh.y-sh.oy)*f,sz=sh.oz+(sh.z-sh.oz)*f;S.beam(sh.ox,sh.oy,sh.oz,sx,sy,sz,14,0xfff0b0,.9,4);S.bolt(sx,sy,sz,sh.ox,sh.oy,sh.oz,16,0xffffff,sh.el?FIRE:ICE,4);} + // Charge stored on the mirror shield: stacked rings round the hero in the soaked element. + if(b.charge>0){for(let k=0;k.2)S.part('ball',S.mat(0xffc15a,{basic:true,op:.85,add:true}),0,-7,36,8+Math.sin(t*40)*1.5);} + // Breath: a cone of fire from the jaws, hot core and orange halo glows along it. + function flame(S,x,y,z,a,pitch,len,t){const dx=Math.sin(a)*Math.cos(pitch),dy=-Math.sin(pitch),dz=Math.cos(a)*Math.cos(pitch); + for(let i=0;i<10;i++){const k=(i+((t*12)%1))/10,w=18+k*90,j=Math.sin(t*40+i*1.7)*6;S.flare(x+dx*len*k+j,y+dy*len*k,z+dz*len*k-j,w*1.4,i<3?0xffe08a:0xff6a1a,.85-k*.4);S.flare(x+dx*len*k,y+dy*len*k,z+dz*len*k,w*.6,0xfff4c0,.8-k*.6);}} + R.art.volvagia={camY:150,lookBias:.42,focusUp:0,focusR:70,lockR:60, + focus(g,f){const b=g.boss;if(b.act==='under'||b.act==='burrow'||b.act==='peek')return {x:b.x,y:30,z:b.z};if(b.act==='fly'){const h=g.hero;return {x:b.mode==='rocks'?b.x:h.x,y:0,z:b.mode==='rocks'?b.z:h.z};} + const down=b.act==='vuln'||b.act==='dead';return {x:b.x+Math.sin(b.yaw)*46,y:118*(down?.35:1),z:b.z+Math.cos(b.yaw)*46};}, + threat(g){const b=g.boss;if(b.act!=='fly')return null;return {x:b.x,y:Math.min(b.y,b.mode==='rocks'?600:420),z:b.z,r:70};}, + hits(g){const b=g.boss;if(!(b.inv>0)||b.act==='fly'||b.act==='under')return [];const down=b.act==='vuln'||b.act==='dead'; + return [{x:b.x+Math.sin(b.yaw)*46,y:b.y+118*(down?.35:1),z:b.z+Math.cos(b.yaw)*46,k:Math.min(1,b.inv/(b.exposed&&b.inv<=6?6:30)),c:0xffd8a0}];}, + marker(g){const b=g.boss;return b.act==='under'||b.act==='burrow'?null:{x:b.x,y:b.act==='fly'?b.y:90,z:b.z};}, + dangers(g){const b=g.boss,out=[];if(b.act==='under'||b.act==='peek')out.push({x:b.x,y:10,z:b.z,label:'Hole'});if(b.act==='fly')out.push({x:b.x,y:b.y,z:b.z,label:'Flying'}); + for(const q of b.rocks)out.push({x:q.x,y:2,z:q.z,label:'Rockfall'});return out;}, + room(S,group){const T=root.THREE; + const floorTex=canvasTex(1024,1024,(q,w,h)=>{q.fillStyle='#3a2a24';q.fillRect(0,0,w,h);noise(q,w,h,14000,71,'rgba(0,0,0,.35)','rgba(190,120,80,.1)',6); + q.strokeStyle='rgba(255,120,40,.3)';q.lineWidth=2;let s=9;const r=()=>(s=(s*16807)%2147483647)/2147483647;for(let i=0;i<46;i++){let x=r()*w,y=r()*h;q.beginPath();q.moveTo(x,y);for(let j=0;j<6;j++){x+=(r()-.5)*70;y+=(r()-.5)*70;q.lineTo(x,y);}q.stroke();} + for(const a of [-H,0,H])for(const c of [-H,0,H]){const x=512+a/526*512,y=512+c/526*512,G=q.createRadialGradient(x,y,6,x,y,74);G.addColorStop(0,'#ff9a3a');G.addColorStop(.3,'#a8381a');G.addColorStop(.52,'#160c0a');G.addColorStop(.78,'#2a1a14');G.addColorStop(1,'rgba(42,26,20,0)');q.fillStyle=G;q.beginPath();q.arc(x,y,74,0,PI*2);q.fill();}}); + const wallTex=canvasTex(1024,512,(q,w,h)=>{q.fillStyle='#21140f';q.fillRect(0,0,w,h);noise(q,w,h,9000,73,'rgba(0,0,0,.4)','rgba(150,90,60,.1)',7); + for(let i=0;i<9;i++){const x=40+i*114,G=q.createLinearGradient(0,h,0,h*.3);G.addColorStop(0,'rgba(255,120,40,.65)');G.addColorStop(1,'rgba(255,90,20,0)');q.fillStyle=G;q.fillRect(x,h*.3,10+i%3*7,h*.7);}},3,1); + const ceilTex=canvasTex(256,256,(q,w,h)=>{q.fillStyle='#1a100c';q.fillRect(0,0,w,h);noise(q,w,h,3000,79,'rgba(0,0,0,.4)','rgba(150,90,60,.14)',6);}); + S.addChamber(group,{r:520,h:820,floorTex,wallTex,ceilTex}); + // Rim rocks round each vent and stalactites over the room (scenery; the vents stay flat, as the rules have no lip). + const rock=new T.MeshLambertMaterial({color:0x2e201a,flatShading:true}); + for(const a of [-H,0,H])for(const c of [-H,0,H])for(let i=0;i<6;i++){const u=i*PI/3+a*.01,m=new T.Mesh(new T.DodecahedronGeometry(7+i%3*3,0),rock);m.position.set(a+Math.sin(u)*64,3,c+Math.cos(u)*64);m.rotation.set(i,i*2,0);group.add(m);} + for(let i=0;i<14;i++){const a=i*PI/7,r=200+(i*67)%280,len=60+(i*41)%110,m=new T.Mesh(new T.ConeGeometry(10+i%4*4,len,6),rock);m.position.set(Math.sin(a)*r,820-len/2,Math.cos(a)*r);m.rotation.z=PI;group.add(m);} + S.hemi.color.set(0xffd8b8);S.hemi.groundColor.set(0x6a2a14);S.hemi.intensity=2.2;S.sun.intensity=1.5;S.sun.color.set(0xffe0c0);S.glow.color.set(0xff7a2a);S.glow.intensity=0;S.world.background=new T.Color(0x120806);S.world.fog=new T.Fog(0x120806,900,2000);}, + draw(S,g,f){const b=g.boss,x=b.ox+(b.x-b.ox)*f,y=b.oy+(b.y-b.oy)*f,z=b.oz+(b.z-b.oz)*f,t=g.t/60,flash=b.inv>0&&(g.t>>1)%2===0,h=g.hero; + // Vent embers everywhere; the vent he is under glows, smokes and rings, brighter on the true emergence. + for(const a of [-H,0,H])for(const c of [-H,0,H]){const u=(t*.6+(a+c)*.001)%1;S.flare(a,8+u*60,c,18*(1-u)+6,0xff7a2a,.35*(1-u));} + if(b.act==='under'||b.act==='peek'){const k=.7+Math.sin(t*14)*.3,real=b.act==='peek'&&b.fakes===0;S.decal('ring',b.x,b.z,70*k,0,0xffa040,.6);S.decal('thin',b.x,b.z,real?120:80,0,real?0xff3a1a:0xffa040,real?.8:.5); + S.flare(b.x,30,b.z,140,0xff7a2a,.5);for(let i=0;i<4;i++){const u=(t*.8+i/4)%1;S.flare(b.x+Math.sin(i*2.1)*12,10+u*130,b.z+Math.cos(i*2.1)*12,30+u*50,0x6a5a50,.35*(1-u));}} + if(b.act==='burrow'&&y<-40)S.flare(b.x,20,b.z,120,0xff7a2a,.4); + S.glow.intensity=0; + if(b.act==='fly'){const body=[{x,y,z},...b.trail]; + for(let i=1;i3)for(const sd of [-1,1]){const s=body[3];S.part('cone',S.mat(0x3a2a24),s.x+Math.cos(b.yaw)*sd*40,s.y+10+Math.sin(t*8)*10,s.z-Math.sin(b.yaw)*sd*40,8,70,30,b.yaw,0,sd*(1.2+Math.sin(t*8)*.3));} + S.push(x,y,z,b.yaw,.2,0);head(S,g,b,{flash,exposed:false,open:b.breathT>0?1:.15});S.pop();S.flare(x,y,z,150,0xff7a2a,.4);S.glow.position.set(x,y,z);S.glow.color.set(0xff7a2a);S.glow.intensity=2; + if(b.breathT>0){const off=Math.atan2(y-h.y,Math.max(40,Math.hypot(h.x-x,h.z-z)));flame(S,x+Math.sin(b.yaw)*50,y-8,z+Math.cos(b.yaw)*50,b.yaw,off,FIRE,t);S.glow.position.set(x,y,z);S.glow.intensity=3; + S.decal('sector',x,z,FIRE,.35,0xff3a1a,.35,b.yaw);} + S.shadow(x,0,z,50);} + else if(b.act!=='under'){const down=b.act==='vuln'||b.act==='dead',hy=118*(down?.35:1),n=7,fwd=46; + for(let i=0;i0)S.flare(sx,sy,sz,r*2.2,0xff5a1a,.3);} + const fireAnim=b.act==='fire',pre=fireAnim&&b.af<25,open=fireAnim?Math.min(1,b.af/20):b.act==='swipe'?.5:b.act==='dead'?.8:.1,hx=x+Math.sin(b.yaw)*fwd,hz=z+Math.cos(b.yaw)*fwd,hh=y+hy; + S.push(hx,hh,hz,b.yaw,down?.5:0,down?.3:0);head(S,g,b,{flash,exposed:b.exposed,open});S.pop(); + if(b.exposed)S.flare(hx,hh+10,hz,60,0xff6a3a,.4+.2*Math.sin(t*10)); + if(down)for(let i=0;i<3;i++){const a=t*4+i*2.1;S.flare(hx+Math.sin(a)*30,hh+38,hz+Math.cos(a)*30,16,0xfff0a0,.9);} + // Breath wind-up: the jaws fill with fire and the cone it will sweep (head turn up to 0x1F40 either way) shows on the floor. + if(pre){const k=b.af/25;S.flare(hx+Math.sin(b.yaw)*34,hh-6,hz+Math.cos(b.yaw)*34,30+70*k,0xff8a2a,.5+.4*k);S.decal('sector',x,z,FIRE+fwd,ARC+.24,0xff3a1a,.12+.25*k,b.yaw);} + // Claws on the rim; within reach they rise and the swipe arc shows. + const near=b.act==='idle'&&Math.hypot(h.x-b.x,h.z-b.z)=8?.5:.22,b.yaw); + for(const sd of [-1,1]){S.push(x,y,z,b.yaw,0,0);S.part('box',S.mat(0x6a4a3a,{em:0x2a0a00}),sd*(44+sw*30),22+sw*30,16+sw*70,16,14,46,sd*sw*.5,-sw*.5);for(let i=-1;i<2;i++)S.part('cone',S.mat(0xe0d4b8),sd*(44+sw*30)+i*7,16+sw*30,42+sw*90,3,16,3,0,PI/2);S.pop();} + S.shadow(x,0,z,64); + if(fireAnim&&b.af>=25&&b.af<70){const a=b.yaw+(b.breath||0);flame(S,hx+Math.sin(a)*34,hh-6,hz+Math.cos(a)*34,a,Math.atan2(hh,FIRE),FIRE,t);S.glow.position.set(hx,hh,hz);S.glow.intensity=4;S.decal('sector',x,z,FIRE+fwd,.24,0xff4a1a,.4,a);}} + // Rocks: a molten core, a smoke tail, and the landing circle sized to the hit radius. + for(const q of b.rocks){const ry=q.oy+(q.y-q.oy)*f,k=Math.max(0,Math.min(1,1-ry/600));S.part('ico',S.mat(0x5a4438,{em:0x601a08}),q.x,ry,q.z,q.r,q.r*.8,q.r,t*3,t*2);S.flare(q.x,ry,q.z,q.r*3,0xff6a1a,.5);S.flare(q.x,ry+40,q.z,q.r*2.4,0x5a4a40,.35); + S.decal('ring',q.x,q.z,q.r+14,0,0xff3a1a,.25+.45*k);S.decal('thin',q.x,q.z,(q.r+14)*(2-k),0,0xff7a2a,.7*k);S.shadow(q.x,0,q.z,q.r+6);} + } + }; +})(window); diff --git a/environments/games/web/games/zelda_oot_remake/bosses/dodongo.js b/environments/games/web/games/zelda_oot_remake/bosses/dodongo.js new file mode 100644 index 0000000000000000000000000000000000000000..bade785170aea64664c7c7ebd8d7a2ce5f3429e5 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/bosses/dodongo.js @@ -0,0 +1,130 @@ +/* King Dodongo (z_boss_dodongo.c, z_en_bom.c; SOURCES.md D1-D14). Original mechanics, own code. Frame counts are 20 Hz logic frames. + * The room is a square lap: he walks and rolls along the four corners of a 1000-unit square around a central lava pit, as in the source. Coordinates are centred on that square. */ +(function(root){ + 'use strict'; + const M=root.ZeldaOotGame,N=root.NativeBench,{wrap,hd,yawTo,MOVE}=M.helpers,PI=Math.PI; + const HALF=500,CORNERS=[{x:-HALF,z:-HALF},{x:-HALF,z:HALF},{x:HALF,z:HALF},{x:HALF,z:-HALF}]; // source order (D2), recentred + // A*: approximations for data found only in the assets. Everything else is a source value. + const D={inhaleFrames:100,eatFrom:21,eatTo:81,mouthBox:40,explode:35,vulnerable:100,rollWind:27,rollJump:15,rollEndJump:20,fire:50,fireFrom:18,fireTo:34,breakWalk:50,invHit:5,inhaleRange:500,cornerNear:200,yawRange:0x38e3, + walkScale:.7,rollScale:3,bombFuse:70,bombGravity:4,bombHold:44, + layFrames:12,getUpFrames:18,damagedFrames:12,bodyR:88,rollR:96,mouthFwd:112,mouthY:64,headFwd:96,headR:44,standOff:70,fireStep:15,fireLife:26,fireR:30,blastR:110,throwSpeed:9,throwVy:7,pickupCd:18,pitR:210,roomHalf:600}; // A: his body (88) covers the strip between his lap (500) and the wall, so the only lane he cannot reach is the inner one by the pit + const TUNE={ + hp:[8,8,20,48], // BossBench: scaled to the tier windows (T1). Source 12; the d = 0 anchor is easy's 8 so health never falls as d rises (dsweep found 12 > 10 > 8 below easy) + bombDmg:[2,2,2,2], // source (D1), kept in every tier: only his vulnerable window grows the fight + touch:[8,8,12,16], // contact and rolling + fireDmg:[8,8,12,16], + rollCap:[1,1,1.08,1.16], // speed factor on the source roll + vuln:[100,100,90,80] // frames down after a bomb + }; + const setAct=(b,a,t)=>{b.act=a;b.timer=t===undefined?0:t;b.af=0;}; + function setupWalk(b){setAct(b,'walk',0);b.walkAnim=0;} + function setupRoll(b){setAct(b,'roll',D.rollWind);b.walls=0;} + const mouth=b=>({x:b.x+Math.sin(b.yaw)*D.mouthFwd,y:b.y+D.mouthY,z:b.z+Math.cos(b.yaw)*D.mouthFwd}); + const head=b=>({x:b.x+Math.sin(b.yaw)*D.headFwd,y:b.y+(['lay','vuln'].includes(b.act)?30:60),z:b.z+Math.cos(b.yaw)*D.headFwd}); + // Source: smooth step with a capped increment (scale s on the remaining distance, then at most `step`), written directly to the coordinate, so no x 1.5 here. + const smooth=(v,t,s,step)=>{const d=(t-v)*s;return v+N.clamp(d,-step,step);}; + function lane(b,h,turn){const a=b.yaw+turn,dx=h.x-b.x,dz=h.z-b.z,side=Math.cos(a)*dx-Math.sin(a)*dz,ahead=Math.sin(a)*dx+Math.cos(a)*dz;return Math.abs(side)<150&&ahead>=100&&ahead<=2000?1:0;} + function arriveNext(b){b.corner=(b.corner+(b.dir?3:1))%4;} + function move(g,b,scale,cap,accel,near,fine){const c=CORNERS[b.corner];b.spd=Math.min(cap,b.spd+accel);b.x=smooth(b.x,c.x,fine,b.spd);b.z=smooth(b.z,c.z,fine,b.spd); + const dx=c.x-b.x,dz=c.z-b.z;if(Math.abs(dx)>1e-3||Math.abs(dz)>1e-3)b.yaw=wrap(b.yaw+N.clamp(wrap(Math.atan2(dx,dz)-b.yaw)/5,-(scale*b.turn)*M.helpers.BIN,(scale*b.turn)*M.helpers.BIN)); + return Math.abs(dx)<=near&&Math.abs(dz)<=near;} + function hitBoss(g,b,dmg){b.hp-=dmg;b.inv=D.invHit;g.ev('dodongo_hit');if(b.hp>0)setAct(b,'damaged',D.damagedFrames);else killCheck(g,b);} + function killCheck(g,b){if(b.hp<=0&&b.act!=='dead'){b.hp=0;setAct(b,'dead',45);g.ev('boss_dead');g.fxAdd('burst',b.x,70,b.z,16,{r:90,color:0xff8a3a});}} + function explodeBomb(g,q){g.ev('bomb_blast');g.fxAdd('burst',q.x,q.y+10,q.z,12,{r:D.blastR*.8,color:0xffb04a});g.fxAdd('ring',q.x,3,q.z,10,{r:D.blastR}); + const h=g.hero;if(Math.hypot(q.x-h.x,q.z-h.z){q.ox=q.x;q.oy=q.y;q.oz=q.z;q.fuse--; + if(q.state==='air'){q.vy-=D.bombGravity*.25;q.x+=q.vx*MOVE;q.z+=q.vz*MOVE;q.y+=q.vy*MOVE; + if(q.y<=0){q.y=0;q.state='ground';q.vx=q.vz=q.vy=0;g.ev('bomb_land');}} + if(b.act==='inhale'&&b.af>D.eatFrom&&b.af0)b.next--;b.turn=2000;if(move(g,b,D.walkScale,D.walkScale*4,D.walkScale*.25,5,.3)){b.spd=0;arriveNext(b);} + if(b.next===0){const near=hd(b,h)Math.abs(b.x-p.x)=D.fireFrom&&b.af<=D.fireTo){const m=mouth(b),idx=b.af-D.fireFrom;b.flames.push({x:m.x,y:m.y-12,z:m.z,ox:m.x,oy:m.y-12,oz:m.z,vx:Math.sin(b.yaw)*D.fireStep,vz:Math.cos(b.yaw)*D.fireStep,life:D.fireLife,idx});} + if(b.timer===0){setupRoll(b);g.ev('dodongo_roll');}}, + roll(g,b,h){b.turn=2000;const t=b.timer;if(t===10)b.vy=D.rollJump; + if(t===0){b.turn=3000;if(move(g,b,D.rollScale,D.rollScale*5*g.T.rollCap,D.rollScale*.25,15,1)){b.walls++; + if(b.walls>=2){if(b.switchDir)b.dir=b.dir?0:1;b.spd=0;setupWalk(b);b.next=0;b.vy=D.rollEndJump;g.ev('dodongo_roll_end');g.fxAdd('ring',b.x,3,b.z,12,{r:140});}else b.vy=D.rollJump; + arriveNext(b);}}}, + explode(g,b){b.af++;if(b.timer===0){setAct(b,'lay',0);g.ev('dodongo_blast');g.fxAdd('burst',b.x,80,b.z,12,{r:66,color:0xffb04a});b.hp-=D.bomb||g.T.bombDmg;if(b.hp<=0)b.hp=1;}}, // the source's bomb can never kill: it leaves 1 (D1) + lay(g,b){b.af++;if(b.af>=D.layFrames)setAct(b,'vuln',Math.round(g.T.vuln));}, + vuln(g,b){if(b.timer===0)setAct(b,'getup',D.getUpFrames);}, + getup(g,b){if(b.timer===0){setupRoll(b);g.ev('dodongo_roll');}}, + damaged(g,b){if(b.timer===0){setupRoll(b);g.ev('dodongo_roll');}}, + dead(g,b){if(b.timer===0)g.outcome='win';} + }; + M.register('dodongo',{ + cases:[{id:'zelda/lava_lizard_king',name:'Lava-Cave Fire Lizard King (Young Swordsman · Bomb Fruit)'}], + arena:{r:900,square:600,ceil:520,start:[0,-300]},hearts:6,age:'child',camDist:330,tune:TUNE,art:'dodongo', + item:{kind:'bomb',name:'Bomb Fruit: pick up / throw'},threats:{dodongo_inhale:1,dodongo_roll:1,dodongo_fire:1,hero_hurt:1}, + init(g){const b=g.boss,k=Math.floor(g.rand()*4),dir=g.rand()<.5?0:1,p=CORNERS[k],nx=(k+(dir?3:1))%4;Object.assign(b,{x:p.x,y:0,z:p.z,ox:p.x,oy:0,oz:p.z,vy:0,yaw:Math.atan2(CORNERS[nx].x-p.x,CORNERS[nx].z-p.z),spd:0,turn:2000,corner:nx,dir,walls:0,next:0,timer:0,af:0,walkAnim:0,inv:0,hp:Math.round(g.T.hp),maxHp:Math.round(g.T.hp), + playerNear:0,switchDir:0,bombs:[],flames:[],lastSlash:-1,stock:0,fired:0,spin:0});setupWalk(b); + const h=g.hero;h.holding=false;h.bombT=0;h.x=-p.x*.55;h.z=-p.z*.55;h.ox=h.x;h.oz=h.z;h.yaw=h.face=Math.atan2(-h.x,-h.z);}, + // The item key takes a fresh bomb flower and, while one is held, throws it forward. Held too long it goes off in hand (fuse 70). + useItem(g){const h=g.hero,b=g.boss; + if(!h.holding){h.holding=true;h.bombT=D.bombFuse;h.itemCd=D.pickupCd;g.ev('bomb_pick');return;} + const y0=h.y+34;b.bombs.push({state:'air',x:h.x+Math.sin(h.face)*16,y:y0,z:h.z+Math.cos(h.face)*16,ox:h.x,oy:y0,oz:h.z,vx:Math.sin(h.face)*D.throwSpeed,vy:D.throwVy,vz:Math.cos(h.face)*D.throwSpeed,fuse:h.bombT}); + h.holding=false;h.bombT=0;h.itemCd=D.pickupCd;g.ev('bomb_throw');}, + update(g){const b=g.boss,h=g.hero;if(b.inv>0)b.inv--;if(b.timer>0)b.timer--; + if(h.holding&&!g.events.includes('bomb_pick')&&--h.bombT<=0){h.holding=false;explodeBomb(g,{x:h.x,y:h.y,z:h.z});} + // The walk's two sensors (D5): the player straight ahead (within 150 to the side, 100-2000 in front) lets him inhale; straight behind makes the next roll turn back. + b.playerNear=lane(b,h,0);b.switchDir=lane(b,h,PI); + ACT[b.act](g,b,h);if(g.outcome)return; + b.vy-=2;b.y=Math.max(0,b.y+b.vy*MOVE);if(b.y===0&&b.vy<0)b.vy=0; + if(Math.hypot(h.x,h.z){q.ox=q.x;q.oy=q.y;q.oz=q.z;q.x+=q.vx*MOVE;q.z+=q.vz*MOVE;q.life--;if(Math.hypot(q.x-h.x,q.z-h.z)0;}); + if(b.act==='roll'&&b.timer===0)b.spin+=2000*M.helpers.BIN; + const s=g.strike(); + if(s&&s.id!==b.lastSlash&&(b.act==='vuln'||b.act==='lay')&&b.inv===0){const q=head(b);if(g.swordReach(q.x,q.y,q.z,D.headR)){b.lastSlash=s.id;hitBoss(g,b,s.dmg);}} + const R=b.act==='roll'?D.rollR:D.bodyR; + if(!['lay','vuln','dead','explode'].includes(b.act)&&Math.hypot(b.x-h.x,b.z-h.z)h.lastKeys.includes(k)?[]:[k],free=H.act==='idle'; + if(b.act==='dead'||H.act==='dead'||H.act==='kb')return []; + // A trial for the next half second: is this stick direction hit, and how close does it pass? + const trial=(keys,n=30)=>{const s=cloneGame(h);let hurt=0;for(let i=0;i{let best=[],bs=-1e9;for(const o of [0,.5,-.5,1,-1,1.6,-1.6,2.4,-2.4,PI]){const a=wrap(yaw+o),k=stickTo(h,a),r=trial([...base,...k]),sc=(r.hurt?-1e4:0)-Math.abs(o)*10+Math.min(hd(r.s.hero,r.s.boss),220)*.3;if(sc>bs){bs=sc;best=k;}}return best;}; + // Stay on the inside of his lap, where the roll cannot reach: the pit edge between centre and the side he is on is the safe track (D3). + const dangerous=b.act==='roll'||b.act==='getup'||b.act==='damaged'; + if(b.act==='vuln'||b.act==='lay'){const q=head(b),d=Math.hypot(q.x-H.x,q.z-H.z),reach=M.constants.reach[H.age]+D.headR-8,keys=['Shift']; + const jump=reach+70,lock=H.lock==='head'; + if(lock&&free&&b.inv===0&&d>reach-25&&d12))return ['Shift',...tap('Space')]; + if(d>reach&&free)keys.push(...stickTo(h,yawTo(H,q)));else if(b.inv===0)keys.push(...tap('J'));return keys;} + if(dangerous&&b.timer>0&&b.act!=='roll'){const c={x:0,z:0},back=hd(H,b);if(back<300&&free)return steer(yawTo(b,H),[]);return [];} + if(b.act==='roll'||(b.act==='walk'&&b.timer===0&&hd(H,b)<260)){if(!free)return [];let best=[],bs=-1e9; + for(const o of [0,.6,-.6,1.2,-1.2,1.9,-1.9,2.6,-2.6,PI]){const a=wrap(Math.atan2(-H.x,-H.z)+o),k=stickTo(h,a);for(const roll of [false,true]){const s=cloneGame(h);let hurt=0,minD=1e9; + for(let i=0;i<48&&!s.outcome;i++){simTick(s,roll&&i<3?[...k,'Space']:k);minD=Math.min(minD,hd(s.hero,s.boss));if(s.events.includes('hero_hurt')){hurt=1;break;}} + const r=Math.hypot(s.hero.x,s.hero.z),sc=(hurt?-1e4:0)+Math.min(minD,260)-Math.abs(r-(D.pitR+70))*.4-(roll?25:0)-Math.abs(o)*3;if(sc>bs){bs=sc;best=roll?[...k,'Space']:k;}}} + return best.includes('Space')&&h.lastKeys.includes('Space')?best.filter(x=>x!=='Space'):best;} + if(b.act==='explode'){const q=head(b),spot={x:q.x+Math.sin(b.yaw)*95,z:q.z+Math.cos(b.yaw)*95};if(hd(H,spot)>12&&free)return ['Shift',...stickTo(h,yawTo(H,spot))];return ['Shift'];} + if(b.act==='fire'){const fwd=Math.abs(wrap(yawTo(b,H)-b.yaw));if(fwd<.9&&hd(H,b)<520&&free)return steer(wrap(yawTo(b,H)+(wrap(yawTo(b,H)-b.yaw)>=0?1.3:-1.3)),[]);return [];} + // Inhale: he stands still, so walk to a point in line with the mouth and let a copy say when a throw now lands in the mouth inside the eating frames. + const m=mouth(b),want={x:m.x+Math.sin(b.yaw)*170,z:m.z+Math.cos(b.yaw)*170}; + if(b.act==='inhale'){if(H.holding){const try1=cloneGame(h);let ate=false;for(let i=0;i<70&&!try1.outcome;i++){simTick(try1,i===0?['Shift','L']:['Shift']);if(try1.events.includes('dodongo_ate_bomb')){ate=true;break;}if(try1.boss.act!=='inhale')break;} + if(ate&&free&&H.itemCd===0)return ['Shift',...tap('L')];} + else if(free&&H.itemCd===0&&b.timer>18)return ['Shift',...tap('L')]; + if(hd(H,want)>10&&free)return ['Shift',...stickTo(h,yawTo(H,want))];return ['Shift'];} + // Walking: keep a bomb out of the fuse's way and stand ahead of him, within the range that triggers his inhale, away from the corners. + // His inhale needs the hero on his walking line (D5): wait on that line between him and the next corner, at least 200 short of the corner (no inhale near one). + const c=CORNERS[b.corner],len=hd(b,c),ux=(c.x-b.x)/(len||1),uz=(c.z-b.z)/(len||1),ahead=Math.min(len-220,Math.max(260,len*.5)),spot={x:b.x+ux*ahead,z:b.z+uz*ahead}; + if(b.act==='walk'&&len>480&&hd(spot,{x:0,z:0})>D.pitR+20){if(hd(H,spot)>16&&free)return steer(yawTo(H,spot),[]);return ['Shift'];} + // Otherwise wait by the pit on the side he is heading for, clear of his body. + const nxt=CORNERS[(b.corner+(b.dir?3:1))%4],mid={x:(c.x+nxt.x)/2*.5,z:(c.z+nxt.z)/2*.5}; + if(hd(H,b)<170&&free)return steer(yawTo(b,H),[]); + if(hd(H,mid)>30&&free)return steer(yawTo(H,mid),[]); + return [];} + }); +})(typeof window==='undefined'?globalThis:window); diff --git a/environments/games/web/games/zelda_oot_remake/bosses/ganondrof.js b/environments/games/web/games/zelda_oot_remake/bosses/ganondrof.js new file mode 100644 index 0000000000000000000000000000000000000000..879337010d0df0faf4e9189c12439e7e3d71db70 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/bosses/ganondrof.js @@ -0,0 +1,113 @@ +/* Phantom Ganon, second phase (z_boss_ganondrof.c, z_en_fhg_fire.c; SOURCES.md F1-F14). Original mechanics, own code. The painting phase on horseback is not built: + * the fight starts as he leaves the paintings and floats free. Frame counts are 20 Hz logic frames. */ +(function(root){ + 'use strict'; + const M=root.ZeldaOotGame,N=root.NativeBench,{wrap,hd,yawTo,approachF,approachS,MOVE}=M.helpers,PI=Math.PI; + const F={roomR:280,lead:180,var:100,heightN:100,heightV:200,heightC:150,volleyZ:265,chargeZ:215,throwFrame:25,throwEnd:34, + ballSpeed:8,ballSlow:3,ballR:25,reflectNeutral:15,reflectSpin:20,returnNear:150,returnPer:8,reflectFrames:8,bossBox:[30,45], + stunAir:50,stunLong:120,invHit:10,chargeWind:20,chargeStart:10,chargeCap:10,chargeAccel:.5,chargeEnd:20,chargeNear:100, + blockFrames:10,bodyR:36,floorY:5,ballLife:200}; + const TUNE={ + hp:[18,18,50,170], // BossBench: tier windows (T1). Source 30; the d = 0 anchor is easy's 18 so health never falls as d rises (dsweep found 30 > 24 > 18 below easy) + dmg:[16,16,20,24], // energy ball (source 0x10 = one heart) + charge:[16,16,20,24], + pick:[64,64,52,40], // random part of his neutral wait (source 30 + 0..63) + speedUp:[1,1,1.5,2], // ball speed added per return + stun:[50,50,50,50] // frames he stays down after his own ball hits him (source 50); longer on the easier tiers, T3 + }; + const setAct=(b,a)=>{b.act=a;b.af=0;}; + function setupNeutral(g,b){setAct(b,'neutral');b.floatSpeed=0;b.t0=30+Math.floor(g.rand()*g.T.pick);} + function setupThrow(g,b){setAct(b,'throw');b.slow=g.rand()<=.1&&b.throws>=10&&b.fly==='neutral';b.throwFrame=b.slow?21:F.throwFrame;b.throws++;g.ev('ganon_windup');} + function newBall(g,b){const s=spearTip(b),h=g.hero,dx=h.x-s.x,dy=h.y+30-s.y,dz=h.z-s.z,dxz=Math.hypot(dx,dz)||1,sp=b.slow?F.ballSlow:F.ballSpeed; + b.ball={mode:'green',x:s.x,y:s.y,z:s.z,ox:s.x,oy:s.y,oz:s.z,yaw:Math.atan2(dx,dz),pitch:Math.atan2(dy,dxz),speed:sp,returns:0,timer:0,life:F.ballLife};g.ev('ganon_ball');} + const spearTip=b=>({x:b.x+Math.sin(b.yaw)*40,y:b.y+70,z:b.z+Math.cos(b.yaw)*40}); + function stun(g,b,returns){if(b.act==='stunned'){setAct(b,'stunned');return;}setAct(b,'stunned');b.t0=returns>=2?F.stunLong:Math.round(g.T.stun);b.ground=false;b.vy=0;b.inv=F.invHit;g.ev('ganon_stunned');} + function ballUpdate(g,b){const q=b.ball;if(!q)return;const h=g.hero;q.ox=q.x;q.oy=q.y;q.oz=q.z;q.life--;if(q.timer>0)q.timer--; + const c=Math.cos(q.pitch);q.x+=Math.sin(q.yaw)*c*q.speed*MOVE;q.y+=Math.sin(q.pitch)*q.speed*MOVE;q.z+=Math.cos(q.yaw)*c*q.speed*MOVE; + const toL={x:h.x-q.x,y:h.y+40-q.y,z:h.z-q.z},dL=Math.hypot(toL.x,toL.y,toL.z),T=b.target,toB={x:T.x-q.x,y:T.y-q.y,z:T.z-q.z}; + if(q.mode==='green'){ + const s=g.strike(); + if(s&&s.id!==q.lastSlash&&g.swordReach(q.x,q.y,q.z,F.ballR)){q.lastSlash=s.id; + // The sword sends it back at him: aimed exactly in a rally (F7), with some scatter while he floats freely; the spin attack sends it fast. + if(b.fly==='neutral'){q.yaw=Math.atan2(toB.x,toB.z)+(g.rand()-.5)*.39;q.pitch=Math.atan2(toB.y,Math.hypot(toB.x,toB.z))+(g.rand()-.5)*.39;q.speed=F.reflectNeutral;} + else{q.returns++;if(q.returns>3&&g.rand()<.5)q.returns=100; + if(s.kind==='spin'){q.speed=F.reflectSpin;q.returns=4;}else q.speed+=g.T.speedUp; + q.yaw=Math.atan2(toB.x,toB.z);q.pitch=Math.atan2(toB.y,Math.hypot(toB.x,toB.z));} + q.mode='blue';g.ev('ball_reflect');g.fxAdd('spark',q.x,q.y,q.z,8,{r:20,color:0xbfe9ff});return;} + if(dL<=F.ballR){const r=g.hurt(g.T.dmg,q.yaw,{kb:6,vy:6});if(r==='block'){q.mode='dead';}else{g.fxAdd('burst',q.x,q.y,q.z,10,{r:30,color:0xb8ff7a});q.mode='dead';} + b.fly='neutral';return;}} + else if(q.mode==='blue'){ + if(b.fly==='return'&&q.returns<100){q.yaw=Math.atan2(toB.x,toB.z);if(Math.hypot(toB.x,toB.z)=100){if(Math.hypot(toB.x,toB.y,toB.z)<100)b.returnSuccess=true;q.yaw=Math.atan2(toB.x,toB.z);q.pitch=Math.atan2(toB.y,Math.hypot(toB.x,toB.z));} + if(Math.abs(toB.x)g.arena.ceil||Math.hypot(q.x,q.z)>g.arena.r+30||q.life<=0)){q.mode='dead';b.fly='neutral';g.fxAdd('burst',q.x,Math.max(4,q.y),q.z,10,{r:26,color:0xb8ff7a});} + if(q.mode==='dead')b.ball=null;} + function hitCheck(g,b){const h=g.hero;if(b.inv>0){b.inv--;b.returnCount=0;return;} + if(b.returnCount){const n=b.returnCount;b.returnCount=0;if(b.act==='charge')return;stun(g,b,n);if(n>=2)b.t0=F.stunLong;return;} + const s=g.strike();if(!s||s.id===b.lastSlash)return; + if(b.act==='stunned'&&b.ground&&g.swordReach(b.x,b.y+50,b.z,F.bodyR)){b.lastSlash=s.id;b.hp-=s.dmg;b.inv=F.invHit;g.ev('ganon_hit'); + if(b.hp<=0){b.hp=0;setAct(b,'dead');b.t0=40;g.ev('boss_dead');}else setAct(b,'stunned');}} + const ACT={ + neutral(g,b,h){if(b.t0>0)b.t0--;let tx,ty,tz;const v=b.vt; + if(b.fly==='neutral'){if(b.t0===0){b.t0=30+Math.floor(g.rand()*g.T.pick);const r=g.rand(); + if(b.hp=.8){b.fly='charge';b.t0=60;b.floatSpeed=0;}else{b.fly='volley';b.t0=60;b.floatSpeed=0;}} + else if(r<.5||b.throws<5)return setupThrow(g,b);else{b.fly='volley';b.t0=60;b.floatSpeed=0;}} + if(b.t1>0){tx=0;tz=0;}else{tx=h.x+F.lead*Math.sin(h.face);tz=h.z+F.lead*Math.cos(h.face);if(Math.hypot(tx,tz)>F.roomR){b.t1=50;b.floatSpeed=0;}} + ty=h.y+F.heightN;tx+=Math.sin(v*0x500*M.helpers.BIN)*F.var;tz+=Math.cos(v*0x700*M.helpers.BIN)*F.var;} + else if(b.fly==='volley'){tx=-14;tz=F.volleyZ;ty=h.y+F.heightV;tx+=Math.sin(v*0x500*M.helpers.BIN)*F.var;tz+=Math.cos(v*0x700*M.helpers.BIN)*F.var; + if(b.t0===0){b.fly='return';b.returnSuccess=false;setupThrow(g,b);b.t0=80;return;}} + else if(b.fly==='return'){tx=-14;tz=F.volleyZ;ty=h.y+F.heightV;tx+=Math.sin(v*0x500*M.helpers.BIN)*50;tz+=Math.cos(v*0x700*M.helpers.BIN)*50; + if(b.returnSuccess){b.returnSuccess=false;setAct(b,'return');b.t0=80;return;}if(b.t0===0)b.fly='neutral';} + else{tx=-14;tz=F.chargeZ;ty=h.y+F.heightC;tx+=Math.sin(v*0x500*M.helpers.BIN)*F.var;tz+=Math.cos(v*0x700*M.helpers.BIN)*F.var;if(b.t0===0){setAct(b,'charge');b.sub='wind';b.t0=F.chargeWind;g.ev('ganon_charge');return;}} + b.x=approachF(b.x,tx,.05,b.floatSpeed);b.y=approachF(b.y,ty,.05,10);b.z=approachF(b.z,tz,.05,b.floatSpeed);b.floatSpeed=approachF(b.floatSpeed,50,1,.5); + b.y+=2*Math.sin(v*1500*M.helpers.BIN);b.yaw=approachS(b.yaw,yawTo(b,h),5,0xbb8);}, + throw(g,b,h){b.af++;if(b.af===b.throwFrame)newBall(g,b);if(b.af>=F.throwEnd)setupNeutral(g,b);b.yaw=approachS(b.yaw,yawTo(b,h),5,0x7d0);b.y+=2*Math.sin(b.vt*1500*M.helpers.BIN);}, + return(g,b){b.af++;if(b.returnSuccess){b.returnSuccess=false;setAct(b,'return');b.t0=80;}if(b.af>=14&&!b.returnSuccess){setupNeutral(g,b);b.fly='return';b.t0=Math.max(1,b.t0);}b.y+=2*Math.sin(b.vt*1500*M.helpers.BIN);}, + stunned(g,b){if(b.t0>0)b.t0--;if(!b.ground){b.vy-=.2;b.y+=b.vy*MOVE;if(b.y<=F.floorY){b.y=F.floorY;b.vy=0;b.ground=true;g.ev('ganon_fall');}} + if(b.t0===0){setupNeutral(g,b);b.t0=30;b.t2=30;b.fly='neutral';b.ground=false;}}, + charge(g,b,h){if(b.t0>0)b.t0--; + if(b.sub==='wind'){b.yaw=approachS(b.yaw,yawTo(b,h),5,0x7d0);if(b.t0===0){b.sub='attack';b.t0=F.chargeStart;b.cspeed=0;}} + else if(b.sub==='attack'){if(b.t0>0){b.yaw=approachS(b.yaw,yawTo(b,h),5,0x7d0);b.pitch=Math.atan2(h.y+40-b.y,Math.hypot(h.x-b.x,h.z-b.z));} + b.cspeed=approachF(b.cspeed,F.chargeCap,1,F.chargeAccel);const c=Math.cos(b.pitch);b.x+=Math.sin(b.yaw)*c*b.cspeed*MOVE;b.y+=Math.sin(b.pitch)*b.cspeed*MOVE;b.z+=Math.cos(b.yaw)*c*b.cspeed*MOVE; + if(Math.hypot(b.x,b.z)>F.roomR||Math.hypot(b.x-h.x,b.y-h.y-40,b.z-h.z)F.roomR)b.t0=0; + if(b.t0===0&&b.cspeed<=.5){setupNeutral(g,b);b.t0=30;b.fly='neutral';}}}, + dead(g,b){if(--b.t0<=0)g.outcome='win';} + }; + M.register('ganondrof',{ + cases:[{id:'zelda/specter_rider',name:'Gallery Specter Rider (Young Swordsman · Longsword)'}], + arena:{r:330,ceil:520,start:[0,-220]},hearts:8,age:'adult',camDist:300,tune:TUNE,art:'ganondrof', + threats:{ganon_ball:1,ganon_return:1,hero_hurt:1,ganon_charge:1}, + init(g){const b=g.boss;Object.assign(b,{x:0,y:F.heightN,z:120,ox:0,oy:F.heightN,oz:120,vy:0,yaw:PI,pitch:0,hp:Math.round(g.T.hp),maxHp:Math.round(g.T.hp),fly:'neutral', + t0:0,t1:0,t2:0,af:0,throws:0,slow:false,throwFrame:F.throwFrame,floatSpeed:0,vt:0,ball:null,returnSuccess:false,returnCount:0,inv:0,ground:false,lastSlash:-1,sub:'',cspeed:0,target:{x:0,y:0,z:0}}); + setupNeutral(g,b);b.t0=90;g.hero.face=g.hero.yaw=0;}, // A: he hovers 90 frames before the first throw (the cutscene before it is not built) + update(g){const b=g.boss,h=g.hero;b.vt++;if(b.t1>0)b.t1--;if(b.t2>0)b.t2--;b.target={x:b.x,y:b.y+50,z:b.z}; + if(b.act==='dead'){ACT.dead(g,b);return;} + ACT[b.act](g,b,h);if(g.outcome||b.act==='dead')return;g.confine(b,10); + ballUpdate(g,b);hitCheck(g,b);}, + targets(g){const b=g.boss;if(b.act==='dead')return [];const out=[{id:'ganon',x:b.x,y:b.y+50,z:b.z,range:900}];return out;}, + focus(g){return g.boss.ball&&g.boss.ball.mode!=='dead'?{x:(g.boss.x+g.boss.ball.x)/2,y:g.boss.y,z:(g.boss.z+g.boss.ball.z)/2}:g.boss;}, + hud(g){const b=g.boss,q=b.ball;if(b.act==='stunned')return b.ground?'He is down! Approach and strike with J.':'He was shocked and is falling.'; + if(q&&q.mode==='green')return 'An orb is incoming: swing your sword with J to return it.';if(q&&q.mode!=='green')return 'During the exchange, wait for him to return it before swinging again.'; + if(b.act==='charge')return 'He is charging! Roll aside.';return '';}, + plan(h){const {stickTo,cloneGame,simTick}=M.ctl,H=h.hero,b=h.boss,q=b.ball,tap=k=>h.lastKeys.includes(k)?[]:[k],free=H.act==='idle'; + if(b.act==='dead'||H.act==='dead'||H.act==='kb')return []; + // A grounded, stunned Ganon: walk in and cut; a jump slash from just outside reach. + if(b.act==='stunned'&&b.ground){const d=Math.hypot(b.x-H.x,b.z-H.z),reach=M.constants.reach.adult+F.bodyR-8; + if(H.lock==='ganon'&&free&&d>reach-20&&d14)return ['Shift',...tap('Space')]; + if(d>reach&&free)return ['Shift',...stickTo(h,yawTo(H,b))];return b.inv===0?['Shift',...tap('J')]:['Shift'];} + if(b.act==='stunned'){const d=Math.hypot(b.x-H.x,b.z-H.z);return d>70&&free?['Shift',...stickTo(h,yawTo(H,b))]:['Shift'];} + // An incoming green ball: let a copy find the slash timing that sends it back; never turn the back on it. + if(q&&q.mode==='green'){const keysFor=k=>['Shift',...k]; + if(free){for(const k of [['J']]){const s=cloneGame(h);let ok=false;for(let i=0;i<9&&!s.outcome;i++){simTick(s,i<2?keysFor(k):['Shift']);if(s.events.includes('ball_reflect')){ok=true;break;}if(s.events.includes('hero_hurt'))break;}if(ok)return keysFor(tap('J'));}} + return ['Shift'];} + if(b.act==='charge'){if(!free)return [];const s0=cloneGame(h);let hit=false;for(let i=0;i<24&&!s0.outcome;i++){simTick(s0,['Shift']);if(s0.events.includes('hero_hurt')){hit=true;break;}} + if(hit){for(const o of [PI/2,-PI/2,PI]){const k=stickTo(h,wrap(yawTo(H,b)+o)),s=cloneGame(h);let hurt=false;for(let i=0;i<24&&!s.outcome;i++){simTick(s,i<2?[...k,'Space']:k);if(s.events.includes('hero_hurt')){hurt=true;break;}}if(!hurt)return [...k,'Space'];}} + return ['Shift'];} + // Otherwise keep the middle of the room and face him. + if(Math.hypot(H.x,H.z)>120&&free)return ['Shift',...stickTo(h,yawTo(H,{x:0,z:0}))]; + return ['Shift'];} + }); +})(typeof window==='undefined'?globalThis:window); diff --git a/environments/games/web/games/zelda_oot_remake/bosses/goma.js b/environments/games/web/games/zelda_oot_remake/bosses/goma.js new file mode 100644 index 0000000000000000000000000000000000000000..8f7cd1b74be904018192477c3b82bfd87825242d --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/bosses/goma.js @@ -0,0 +1,161 @@ +/* Queen Gohma (z_boss_goma.c, z_en_goma.c; SOURCES.md G1-G14). Original mechanics, own code. Frame counts are 20 Hz logic frames. */ +(function(root){ + 'use strict'; + const M=root.ZeldaOotGame,N=root.NativeBench,{wrap,hd,yawTo,approachF,approachS,MOVE}=M.helpers,PI=Math.PI; + // Source values, except A* (approximations for data only found in the assets: room size, animation lengths, limb positions). + const G={roof:320,wallMargin:62,eyeFwd:34,eyeY:{floor:62,stunned:34,ceil:-50},eyeR:26,bodyR:62,legReach:178, + stunSeed:90,stunFall:150,inv:10,idleBase:20,idleRange:30,mainBase:70,mainRange:40,ceilBase:30,ceilRange:60,walk:10/3,walkAway:20/3,walkBack:-10,prep:70, + postureFrames:33,postureTurnFrom:19,postureTurnTo:30,attackRange:150,attackConfirm:250,attackFrames:20,attackHit:[7,13],restBase:30,restRange:30,recover:15,damagedFrames:16,landFrames:25,crashFrames:20, + eggGravity:1.3,eggSpeed:1.5,hatch:80,kidHp:2,kidStandBase:10,kidStandRange:30,kidChaseBase:70,kidChaseRange:40,kidWalk:10/3,kidJumpRange:150,kidPrep:30,kidJumpVy:8,kidJumpSpeed:10,kidLand:10,kidR:20,kidDmg:8,kidInv:10,kidDead:5}; + const TUNE={ + hp:[10,10,15,42], // BossBench: scaled to the tier windows (T1) + dmg:[8,8,12,16], // contact and leg strike + patience:[200,200,240,280], + walk:[1,1,1.12,1.25], + stunSeed:[90,90,84,78], + // BossBench (T2): frames the eye stays shut after she reaches the ceiling / lands, so that a player who always hits still meets the eggs and the leg strike. 0 at d = 0 (source). + ceilGuard:[0,40,240,280], + floorGuard:[0,105,130,170] + }; + const ceilingActs=new Set(['ceilMove','ceilIdle','prepEggs']); + const eyeOf=b=>{const c=b.y>100,fy=c?G.eyeY.ceil:(b.act==='stunned'||b.act==='damaged'?G.eyeY.stunned:G.eyeY.floor);return {x:b.x+Math.sin(b.yaw)*G.eyeFwd,y:b.y+fy,z:b.z+Math.cos(b.yaw)*G.eyeFwd};}; + function setAct(b,a){b.act=a;b.af=0;} + function setupMain(g,b){setAct(b,'main');b.next=g.randS(G.mainBase,G.mainRange);b.walkAnim=0;} + function setupIdle(g,b){setAct(b,'idle');b.next=g.randS(G.idleBase,G.idleRange);} + function setupStunned(b){setAct(b,'stunned');} + function kidAlive(b){return b.kids.some(k=>k.state>0);} + function spawnEgg(g,b,i){const tail={x:b.x-Math.sin(b.yaw)*60,y:b.y-60,z:b.z-Math.cos(b.yaw)*60}; + b.kids.push({i,state:1,act:'fall',x:tail.x,y:tail.y,z:tail.z,ox:tail.x,oy:tail.y,oz:tail.z,vy:0,speed:G.eggSpeed,yaw:b.yaw,hp:G.kidHp,timer:0,inv:10});b.kidState[i]=1;g.ev('egg_spawn');} + function updateKids(g,b){const h=g.hero; + for(const k of b.kids){if(k.state<=0)continue;k.ox=k.x;k.oy=k.y;k.oz=k.z;if(k.inv>0)k.inv--;if(k.timer>0)k.timer--; + const d=hd(k,h),aim=yawTo(k,h); + if(k.act==='fall'){k.vy=Math.max(-20,k.vy-G.eggGravity);if(k.y<=0&&k.vy<0){k.y=0;k.vy=0;k.speed=0;k.act='egg';k.timer=G.hatch;}} + else if(k.act==='egg'){if(k.timer===0){k.act='stand';k.timer=g.randS(G.kidStandBase,G.kidStandRange);g.ev('egg_hatch');}} + else if(k.act==='stand'){k.speed=approachF(k.speed,0,.5,2);k.yaw=approachS(k.yaw,aim,3,2000);if(k.timer===0){k.act='chase';k.timer=g.randS(G.kidChaseBase,G.kidChaseRange);}} + else if(k.act==='chase'){k.speed=approachF(k.speed,G.kidWalk,.5,2);k.yaw=approachS(k.yaw,aim,3,2000); + if(d<=G.kidJumpRange){k.act='prep';k.timer=G.kidPrep;}else if(k.timer===0){k.act='stand';k.timer=g.randS(G.kidStandBase,G.kidStandRange);}} + else if(k.act==='prep'){k.speed=approachF(k.speed,0,.5,2);k.yaw=approachS(k.yaw,aim,3,2000);if(k.timer===0){k.act='jump';k.vy=G.kidJumpVy;g.ev('kid_jump');}} + else if(k.act==='jump'){k.vy-=G.eggGravity;k.speed=approachF(k.speed,G.kidJumpSpeed,.5,5);if(k.y<=0&&k.vy<0){k.y=0;k.vy=0;k.act='land';k.timer=G.kidLand;}} + else if(k.act==='land'){k.speed=approachF(k.speed,0,1,2);if(k.timer===0){k.act='stand';k.timer=g.randS(G.kidStandBase,G.kidStandRange);}} + else if(k.act==='hurt'){k.speed=approachF(k.speed,0,1,2);if(k.timer===0){if(k.hp<=0)killKid(g,b,k);else{k.act='stand';k.timer=g.randS(G.kidStandBase,G.kidStandRange);}}} + if(k.state<=0)continue; + k.x+=Math.sin(k.yaw)*k.speed*MOVE;k.z+=Math.cos(k.yaw)*k.speed*MOVE;k.y=Math.max(0,k.y+k.vy*MOVE);g.confine(k,G.kidR); + if(k.act!=='fall'&&k.act!=='egg'&&k.act!=='hurt'&&Math.hypot(k.x-h.x,k.z-h.z)k.state>0);} + function killKid(g,b,k){k.state=-1;b.kidState[k.i]=-1;g.ev('kid_dead');g.fxAdd('burst',k.x,k.y+14,k.z,10);} + function hitKid(g,b,k,dmg){if(k.inv>0)return; + if(k.act==='fall'||k.act==='egg'){killKid(g,b,k);return;} + k.hp-=dmg;k.inv=G.kidInv;k.act='hurt';k.timer=k.hp<=0?G.kidDead:10;k.speed=20;k.yaw=yawTo(g.hero,k);k.vy=0;g.ev('kid_hurt');} + function struckEye(g,b,kind,dmg){ // kind 'seed' or 'sword' + if(b.inv>0||b.eyeClosed>0||b.act==='spawnEggs'||b.act==='dead')return false; + if(ceilingActs.has(b.act)){setAct(b,'fallStruck');b.speed=0;b.vy=0;b.grav=-2;g.ev('gohma_struck_down');return true;} + if(b.act==='stunned'&&kind==='sword'){b.hp-=dmg;b.inv=G.inv;g.ev('gohma_hit'); + if(b.hp>0){setAct(b,'damaged');}else{b.hp=0;setAct(b,'dead');b.timer=30;g.ev('boss_dead');}return true;} + if(b.act!=='stunned'&&b.patience>0&&kind==='seed'&&b.y<5&&b.act!=='climb'){b.inv=G.inv;setupStunned(b);b.next=Math.round(g.T.stunSeed);b.timer=4;g.ev('gohma_stunned');return true;} + return false;} + const ACT={ + main(g,b,h){b.walkAnim=(b.walkAnim+(b.playSpeed||1))%31;const f=Math.floor(b.walkAnim);if(f===1||f===15||f===16||f===30)b.noMove=true;b.playSpeed=1; + if(!b.noMove){const rot=yawTo(b,h),d=hd(b,h); + if(b.patience>0){b.patience--;if(d0){b.speed=approachF(b.speed,G.walkBack,.5,2);b.playSpeed=3;if(b.timer===1)b.speed=0;b.yaw=approachS(b.yaw,rot,3,0x9c4);} + else{b.speed=approachF(b.speed,G.walkAway*g.T.walk,.5,2);b.playSpeed=2;b.yaw=approachS(b.yaw,wrap(rot+PI),3,0x9c4);}} + if(hd(b,{x:0,z:0})>=g.arena.r-G.wallMargin&&b.y<=0){setAct(b,'climb');b.speed=0;b.vy=0;b.grav=0;b.wallYaw=yawTo({x:0,z:0},b);g.ev('gohma_climb');return;} + if(b.next===0&&b.patience>0)setupIdle(g,b);}, + idle(g,b){b.speed=approachF(b.speed,0,.5,2);if(b.next===0)setupMain(g,b);}, + posture(g,b,h){b.af++;b.speed=approachF(b.speed,0,.5,2);if(b.af>=G.postureTurnFrom&&b.af<=G.postureTurnTo)b.yaw=approachS(b.yaw,yawTo(b,h),3,0xbb8); + if(b.af>=G.postureFrames){if(hd(b,h)=G.attackHit[0]&&b.af<=G.attackHit[1]&&!b.struck){const d=hd(b,h),off=Math.abs(wrap(yawTo(b,h)-b.yaw));if(d=G.attackFrames){b.sub=1;if(!b.struck)b.timer=g.randS(G.restBase,G.restRange);}} + else if(b.sub===1){if(b.timer===0){b.sub=2;b.af=0;}} + else if(b.af>=G.recover)setupIdle(g,b);}, + stunned(g,b,h){b.speed=approachF(b.speed,0,.5,1);if(b.next===0){setupMain(g,b);if(b.patience===0&&hd(b,h)<130)b.timer=20;}}, + damaged(g,b){b.af++;if(b.af>=G.damagedFrames){setupStunned(b);b.patience=0;}}, + climb(g,b){b.vy=approachF(b.vy,5,.5,2);b.yaw=approachS(b.yaw,wrap(b.wallYaw+PI),2,0x5dc); + if(b.y>G.roof){setAct(b,'ceilMove');b.guard=Math.round(g.T.ceilGuard);b.speed=0;b.vy=0;b.grav=0;b.y=G.roof;b.next=g.randS(G.ceilBase,G.ceilRange);b.kidState=[0,0,0];b.kids=[];}}, + ceilMove(g,b){b.yaw=approachS(b.yaw,wrap(yawTo(b,{x:0,z:0})+PI),2,0x3e8);b.speed=approachF(b.speed,-5,.5,2);b.y=G.roof; + if(b.next===0&&Math.abs(b.x)<100&&Math.abs(b.z)<100){setAct(b,'ceilIdle');b.next=g.randS(G.idleBase,G.idleRange);}}, + ceilIdle(g,b){b.speed=approachF(b.speed,0,.5,2); + if(b.next===0){const s=b.kidState; + if(s[0]===0&&s[1]===0&&s[2]===0){setAct(b,'prepEggs');b.next=G.prep;g.ev('gohma_prep_eggs');} + else if(s[0]<0&&s[1]<0&&s[2]<0){setAct(b,'fallJump');b.speed=0;b.vy=0;b.grav=-2;g.ev('gohma_jump_down');} + else{setAct(b,'ceilMove');b.next=g.randS(G.ceilBase,G.ceilRange);}}}, + prepEggs(g,b){if(b.next===0){setAct(b,'spawnEggs');b.spawnT=0;}}, + spawnEggs(g,b){b.speed=approachF(b.speed,0,.5,2);b.spawnT++; + // The tail swells limb by limb from frame 24 of each cycle and the egg leaves on frame 56 (limb timer 10 reaching 2, source sequence). + if(b.spawnT===56){const i=b.kidState.indexOf(0);if(i>=0)spawnEgg(g,b,i);if(b.kidState.includes(0))b.spawnT=23;} + if(b.spawnT>=64){setAct(b,'ceilIdle');b.next=g.randS(G.idleBase,G.idleRange);}}, + fallJump(g,b,h){b.yaw=approachS(b.yaw,yawTo(b,h),2,0x7d0);if(b.y<=0){setAct(b,'land');b.vy=0;b.y=0;g.ev('gohma_land');g.fxAdd('ring',b.x,2,b.z,12);}}, + fallStruck(g,b,h){b.yaw=approachS(b.yaw,yawTo(b,h),3,0x7d0);if(b.y<=0){setAct(b,'landStruck');b.vy=0;b.y=0;g.ev('gohma_land');g.fxAdd('ring',b.x,2,b.z,12);}}, + land(g,b){b.af++;if(b.af>=G.landFrames){setupIdle(g,b);b.patience=Math.round(g.T.patience);b.guard=Math.round(g.T.floorGuard);}}, + landStruck(g,b){b.af++;if(b.af>=G.crashFrames){setupStunned(b);b.patience=0;b.next=G.stunFall;}}, + dead(g,b){if(b.timer===0)g.outcome='win';} + }; + M.register('goma',{ + cases:[{id:'zelda/armored_spider_queen',name:'One-Eyed Armored Spider Queen (Young Swordsman · Slingshot)'}], + arena:{r:430,ceil:360,start:[0,300]},hearts:5,age:'child',camDist:300,tune:TUNE,item:{kind:'seed',cd:14,name:'Slingshot'},art:'goma',threats:{gohma_attack:1,egg_spawn:1,kid_jump:1}, + init(g){const b=g.boss;Object.assign(b,{x:0,y:0,z:-130,ox:0,oy:0,oz:-130,vy:0,speed:0,yaw:0,grav:-2,next:0,timer:0,af:0,sub:0,hp:Math.round(g.T.hp),maxHp:Math.round(g.T.hp), + inv:0,patience:Math.round(g.T.patience),eyeClosed:0,eyeLid:0,guard:Math.round(g.T.floorGuard),noMove:false,playSpeed:1,walkAnim:0,struck:false,spawnT:0,wallYaw:0,kidState:[0,0,0],kids:[],frameCount:0}); + setupMain(g,b);g.hero.face=g.hero.yaw=PI;}, + update(g){const b=g.boss,h=g.hero;b.frameCount++;if(b.next>0)b.next--;if(b.timer>0)b.timer--; + if(b.act==='dead'){ACT.dead(g,b);return;} + const eyeDefault=!['posture','attack','stunned','damaged','prepEggs','spawnEggs'].includes(b.act); + ACT[b.act](g,b,h);if(g.outcome)return; + if(!b.noMove){b.x+=Math.sin(b.yaw)*b.speed*MOVE;b.z+=Math.cos(b.yaw)*b.speed*MOVE;b.vy=Math.max(-20,b.vy+b.grav);b.y+=b.vy*MOVE;if(b.y<=0){b.y=0;if(b.vy<0)b.vy=0;}}else b.noMove=false; + g.confine(b,G.wallMargin-2); + // Eye: a quiet boss may blink (30% every 16 frames, shut for 7); while a child lives it stays shut. Lids take a few frames to move. + if(eyeDefault&&b.frameCount%16===0&&g.rand()<.3)b.eyeClosed=7; + if(kidAlive(b))b.eyeClosed=7; + if(b.guard>0){b.guard--;b.eyeClosed=Math.max(b.eyeClosed,2);} + if(b.eyeClosed>0){b.eyeClosed--;b.eyeLid=Math.min(1,b.eyeLid+.34);}else b.eyeLid=Math.max(0,b.eyeLid-.34); + if(b.inv>0)b.inv--; + updateKids(g,b); + const s=g.strike(); + if(s){if(s.id!==b.lastSlash){const e=eyeOf(b);if(b.act!=='spawnEggs'&&g.swordReach(e.x,e.y,e.z,G.eyeR)){if(struckEye(g,b,'sword',s.dmg))b.lastSlash=s.id;}} + for(const k of b.kids)if(k.state>0&&k.lastSlash!==s.id&&g.swordReach(k.x,k.y+12,k.z,G.kidR)){k.lastSlash=s.id;hitKid(g,b,k,s.dmg);} + b.kids=b.kids.filter(k=>k.state>0);if(b.act==='dead')return;} + // Body contact: on except while stunned or hurt and while backing away (source condition). + if(b.act!=='stunned'&&b.act!=='damaged'&&(b.act!=='main'||b.timer===0)&&b.y<70&&hd(b,h)0&&Math.hypot(s.x-k.x,s.y-k.y-12,s.z-k.z)q.state>0);return true;} + const e=eyeOf(b);if(Math.hypot(s.x-e.x,s.y-e.y,s.z-e.z)100||Math.abs(wrap(Math.atan2(-s.vx,-s.vz)-b.yaw))<1.9){struckEye(g,b,'seed',0);return true;}}return false;}, + targets(g){const b=g.boss,e=eyeOf(b),out=[];for(const k of b.kids)if(k.state>0)out.push({id:'kid'+k.i,x:k.x,y:k.y+12,z:k.z,range:520});if(b.act!=='dead'&&!b.kids.length)out.push({id:'eye',x:e.x,y:e.y,z:e.z,range:900});return out;}, + focus(g){return g.lockTarget()||g.boss;}, + hud(g){const b=g.boss,e=b.eyeClosed>0||b.eyeLid>.5; + if(b.act==='stunned'||b.act==='damaged')return 'She is stunned! Approach and strike the eye with J.'; + if(b.kids.length)return `Defeat the hatchlings first (slingshot or sword); ${b.kids.length} remain`; + if(ceilingActs.has(b.act))return e?'Her eye is closed':'Shoot her eye with the slingshot to knock her from the ceiling (Shift lock, L shoot).'; + if(b.patience>0&&!e&&b.act!=='climb')return 'Shoot her open eye with the slingshot (Shift lock, L shoot).';return '';}, + plan(h){const {stickTo}=M.ctl,H=h.hero,b=h.boss; + if(b.act==='dead'||H.act==='dead'||H.act==='kb')return []; + const tap=k=>h.lastKeys.includes(k)?[]:[k],d=hd(H,b),free=H.act==='idle'; + // Larvae first: a seed bursts an egg and hurts a larva. Keep moving away from a larva that is about to pounce. + if(b.kids.length){const k=[...b.kids].sort((p,q)=>hd(H,p)-hd(H,q))[0],dk=hd(H,k),keys=['Shift']; + const up=['prep','jump'].includes(k.act); + if(dk<(up?170:90)&&k.act!=='egg'&&k.act!=='fall'&&k.act!=='hurt'){keys.push(...safeStep(h,wrap(yawTo(k,H)),['Shift']));if(free&&H.itemCd===0)keys.push(...tap('L'));return keys;} + if(free&&H.itemCd===0&&H.lock!==null)keys.push(...tap('L'));return keys;} + // Stunned: run to the eye and cut. Stay on the near side; the third combo cut lands harder only in reach, so tap steadily. + if(b.act==='stunned'||b.act==='damaged'){const e=eyeOf(b),de=Math.hypot(e.x-H.x,e.z-H.z),keys=['Shift']; + if(de>M.constants.reach[H.age]+G.eyeR-6&&free)keys.push(...stickTo(h,yawTo(H,e))); + else if(b.act==='stunned'&&!(b.inv>4))keys.push(...tap('J')); + return keys;} + if(ceilingActs.has(b.act)){const keys=['Shift'];if(b.eyeLid<.2&&free&&H.itemCd===0&&H.lock==='eye')keys.push(...tap('L'));else if(hd(H,{x:0,z:0})>170&&free)keys.push(...stickTo(h,yawTo(H,{x:0,z:0})));return keys;} + if(b.act==='climb'||b.act==='spawnEggs'||b.act==='fallJump'||b.act==='fallStruck'||b.act==='land'||b.act==='landStruck'){const keys=[];if(hd(H,{x:0,z:0})>170&&free)keys.push(...stickTo(h,yawTo(H,{x:0,z:0})));return keys;} + // Floor: stay out of leg reach and shoot the open eye from the front while she still has patience; once it has run out, seeds do nothing, so only keep clear. + const keys=['Shift'],close=b.act==='posture'||b.act==='attack'?205:105; + if(d0&&b.eyeLid<.2&&free&&H.itemCd===0&&H.lock==='eye'&&Math.abs(wrap(yawTo(b,H)-b.yaw))<1.6)keys.push(...tap('L'));return keys;} + if(b.patience>0&&b.eyeLid<.2&&free&&H.itemCd===0&&H.lock==='eye'&&Math.abs(wrap(yawTo(b,H)-b.yaw))<1.6)keys.push(...tap('L')); + return keys;} + }); + // Run in the given direction, turning along the wall or toward the centre when a copy says that step is hit or walled in. + function safeStep(h,yaw,base){const {cloneGame,simTick,stickTo}=M.ctl;let best=[],bestS=-1e9; + for(const o of [0,.6,-.6,1.2,-1.2,1.9,-1.9]){const a=wrap(yaw+o),keys=stickTo(h,a),s=cloneGame(h);let hit=0; + for(let i=0;i<30&&!s.outcome;i++){simTick(s,[...base,...keys]);if(s.events.includes('hero_hurt')){hit=1;break;}} + const R=hd(s.hero,{x:0,z:0}),score=(hit?-1000:0)-Math.max(0,R-(h.arena.r-70))*4-Math.abs(o)*2+hd(s.hero,s.boss)*.05; + if(score>bestS){bestS=score;best=keys;}} + return best;} +})(typeof window==='undefined'?globalThis:window); diff --git a/environments/games/web/games/zelda_oot_remake/bosses/morpha.js b/environments/games/web/games/zelda_oot_remake/bosses/morpha.js new file mode 100644 index 0000000000000000000000000000000000000000..5feee14188691deb624b9db5f41e276e8c0ff4e9 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/bosses/morpha.js @@ -0,0 +1,146 @@ +/* Morpha (z_boss_mo.c; SOURCES.md M1-M12). Original mechanics, own code. Frame counts are 20 Hz logic frames. + * A water nucleus hides in a square pool and grows a water tentacle near the hero. The tentacle sways, then lashes out and the nucleus rides up inside it; + * a tentacle that reaches the hero curls round, lifts and squeezes him. The hookshot tears the nucleus out of the tentacle and drags it ashore, where the sword hurts it. + * After three sword hits a second tentacle joins. */ +(function(root){ + 'use strict'; + const M=root.ZeldaOotGame,N=root.NativeBench,{wrap,hd,yawTo,approachF,MOVE}=M.helpers,PI=Math.PI; + const SPAWNS=[[-360,-360],[-180,-360],[0,-360],[180,-360],[360,-360],[-360,-180],[0,-180],[360,-180],[-360,0],[-180,0],[0,0],[180,0],[360,0],[-360,180],[0,180],[360,180],[-360,360],[-180,360],[0,360],[180,360],[360,360]]; // M3, source order + const ORDER=[0,1,2,3,4,15,19,5,14,16,17,18,6,13,20,7,12,11,10,9,8]; + const V={pool:380,spawn:70,ready:60,attack1:175,attack2:55,curl:40,shake:150,retreat:75,shakeEvery:8,mash:40,releaseInv:50,near:320,far:300, + hookStun:30,swordStun:25,coreInv:10,knock:15,knockDecay:0,coreR:24,height:280,reach:360,tentR:40,grabR:120,curlGrab:90,hookRange:520,hookR:34,landY:10,poolY:-60, + climb:[15,10],segs:40,swingJitter:12,arena:520}; + const TUNE={ + hp:[20,26,120,400], // BossBench: tier windows (T17); source 20 (M1). Seeds 1-16: easy 22 -> 19-20 s, 26 -> 21-24 s; normal 110 -> 44-76 s, 120 -> 46-81 s; hard 320 -> 125-209 s, 400 -> 158-254 s + dmg:[16,16,16,16], // tentacle and nucleus contact, source 0x10 = one heart in every tier: hard 400 with 20 lost 3 of 16 to the second tentacle's lashes + squeeze:[1,1,1,2], // per 8 frames while held (source 1) + swing:[50,50,45,40] // sway before the lash (source 50) + }; + const inPool=(x,z)=>Math.abs(x)h.y-30)return true;}return false;} + function tentReset(t,st,t0){t.st=st;t.t0=t0;} + function holding(b,t){return b.tents.some(o=>o!==t&&o.held);} + function relocate(g,b,t){const h=g.hero;for(let n=0;n<40;n++){const k=ORDER[Math.floor(g.rand()*20.9)],[x,z]=SPAWNS[k]; + if(Math.abs(h.x-x)>V.near||Math.abs(h.z-z)>V.near||b.tents.some(o=>o!==t&&o.spawn===k))continue;t.spawn=k;t.x=x;t.z=z;break;} + if(t.spawn<0){t.spawn=10;t.x=0;t.z=0;}} + function release(g,b,t,shaken){const h=g.hero;if(!t.held)return;t.held=false;h.grabbed=false;h.y=0; + if(shaken){h.act='kb';h.timer=18;h.yaw=wrap(t.yaw);h.speed=8;h.vy=6;h.face=wrap(t.yaw+PI);}else{h.act='idle';h.timer=0;h.speed=0;} + g.ev('tentacle_release');} + const TENT={ + wait(g,b,t){if(t.i===1&&t.t0===0){tentReset(t,'spawn',V.spawn);t.yaw=yawTo(t,g.hero);g.ev('tentacle_rise');}}, + spawn(g,b,t){t.grow=Math.min(1,t.grow+1/50);if(t.t0<20&&t.grow>=1){tentReset(t,'ready',60);}}, + ready(g,b,t){if(t.t0===0&&!holding(b,t)){tentReset(t,'swing',Math.round(g.T.swing)+Math.floor(g.rand()*V.swingJitter));t.mod=(g.rand()-.5)*0x1000*M.helpers.BIN;}}, + swing(g,b,t,h){t.yaw=M.helpers.approachS(t.yaw,wrap(yawTo(t,h)+t.mod),3,0x1f4);if(t.t0===0){tentReset(t,'attack',t.i===0?V.attack1:V.attack2);t.lash=0;g.ev('tentacle_lash');}}, + attack(g,b,t,h){t.ext=Math.min(1,t.ext+.15);if(t.ext>.5&&!h.grabbed&&touching(t,h,V.tentR)){const r=g.hurt(g.T.dmg,t.yaw,{kb:6});if(r)t.lash=5;} + if(t.lash>0)t.lash--; + if(t.t0===0||t.lash===4){const p=tentPoint(t,.55); + if(Math.hypot(p.x-h.x,p.z-h.z)V.far||Math.abs(h.z-t.z)>V.far||holding(b,t))tentReset(t,'retreat',V.retreat);}}}, + curl(g,b,t,h){t.ext=Math.max(.5,t.ext-.04);if(t.t0>=30)t.yaw=M.helpers.approachS(t.yaw,yawTo(t,h),5,0xc8); + const p=tentPoint(t,.55);if(t.t0>=5&&!h.grabbed&&h.act!=='dead'&&Math.hypot(p.x-h.x,p.z-h.z)=V.mash||t.t0===0){release(g,b,t,t.t0===0);t.inv=V.releaseInv;tentReset(t,'retreat',V.retreat);}}, + cut(g,b,t){release(g,b,t,false);t.grow=Math.max(0,t.grow-.06);t.ext=Math.max(0,t.ext-.06);if(t.t0===0||t.grow<=0)tentReset(t,'retreat',V.retreat);}, + retreat(g,b,t){t.ext=Math.max(0,t.ext-.05);if(t.t0===0){t.grow=Math.max(0,t.grow-.05);if(t.grow<=0){relocate(g,b,t);tentReset(t,'despawn',30+Math.floor(g.rand()*20)); + if(t.i===0&&b.hitCount>=3&&b.tents.length<2){const u=newTent(1);u.spawn=t.spawn>10?t.spawn-1:t.spawn+1;[u.x,u.z]=SPAWNS[u.spawn];b.tents.push(u);g.ev('second_tentacle');}}}}, + despawn(g,b,t){if(t.t0===0){tentReset(t,'wait',10+Math.floor(g.rand()*20));}} + }; + function tentUpdate(g,b,t){const h=g.hero;if(t.inv>0)t.inv--;t.sway+=.3;if(t.st!=='attack'&&t.st!=='curl'&&t.st!=='cut')t.ext=Math.max(0,t.ext-.1);TENT[t.st](g,b,t,h); + // Swaying column: the base of the tentacle hurts on contact. + if((t.st==='ready'||t.st==='swing')&&t.grow>.5&&!h.grabbed&&t.inv===0&&Math.hypot(h.x-t.x,h.z-t.z)0)c.inv--;if(c.flash>0)c.flash--;c.vt++; + if(c.act==='move'){if(c.t0===0&&(t.st==='wait'||t.st==='ready')&&c.y<0&&inPool(c.x,c.z)){c.act='make';c.speed=0;if(t.st==='wait'){tentReset(t,'spawn',V.spawn);t.yaw=yawTo(t,h);g.ev('tentacle_rise');}}} + else if(c.act==='make'){if(t.st==='despawn'||t.st==='wait'){c.act='move';c.t0=70;}if(t.st==='attack'||t.st==='cut'){c.act='ride';c.pos=0;c.speed=0;}} + else if(c.act==='stunned'){if(c.t0===0){c.act='move';c.t0=30;}if(c.y<0&&inPool(c.x,c.z)){c.act='make';c.t0=50;c.speed=0;}} + if(c.act==='ride'){c.pos++;const cap=Math.round(Math.sin(c.vt*0x300*M.helpers.BIN)*V.climb[1])+V.climb[0];if(t.st==='attack'&&c.pos>cap)c.pos=cap;if(t.st!=='attack'&&t.st!=='cut')c.act='back';} + else if(c.act==='back'){c.pos--;if(c.pos<=0){c.pos=0;c.act='make';c.t0=100;}} + if(c.act==='ride'||c.act==='back'){const p=tentPoint(t,Math.min(V.segs,c.pos)/V.segs);c.x=approachF(c.x,p.x,.5,30);c.y=approachF(c.y,p.y-(c.pos<=1?20:0),.5,30);c.z=approachF(c.z,p.z,.5,30);c.vy=0;} + else{const floor=inPool(c.x,c.z)?V.poolY:V.landY; + if(c.act==='move'){const a=c.vt*0x800*M.helpers.BIN;c.speed=Math.min(10,c.speed+.5);c.x=approachF(c.x,t.x+Math.sin(a)*100,.05,c.speed);c.z=approachF(c.z,t.z+Math.cos(a)*100,.05,c.speed);} + else if(c.act==='make'){c.speed=Math.min(10,c.speed+.5);c.x=approachF(c.x,t.x,.1,c.speed);c.z=approachF(c.z,t.z,.1,c.speed);c.y=approachF(c.y,-40,.1,c.speed);} + else if(c.act==='stunned'){c.x+=Math.sin(c.yaw)*c.speed;c.z+=Math.cos(c.yaw)*c.speed;c.speed=Math.max(0,c.speed-V.knockDecay);} + if(c.act==='move'||c.act==='stunned'){c.y+=c.vy*MOVE;c.vy-=1; + if(!inPool(c.x,c.z)){if(c.y<=V.landY){c.y=V.landY;c.vy=c.act==='move'&&c.vt%3===0?6:0;}} + // In the pool it stays under (A: the source's 18-unit hop above the surface is left out, so the hookshot waits for the tentacle). + else if(c.act==='move'&&c.y<-30){c.y=-30;c.vy=0;} + if(c.y-10&&!h.grabbed&&Math.hypot(c.x-h.x,c.z-h.z)0||c.y<0||!['move','make','stunned'].includes(c.act))return;const s=g.strike();if(!s||s.id===b.lastSlash)return; + if(!g.swordReach(c.x,c.y+12,c.z,V.coreR))return;b.lastSlash=s.id; + c.act='stunned';c.t0=V.swordStun;c.speed=V.knock;c.yaw=yawTo(h,c);c.vy=3;c.flash=15;c.inv=V.coreInv;b.hp-=s.dmg;b.hitCount++;g.ev('core_hit');g.fxAdd('burst',c.x,c.y+12,c.z,10,{r:26,color:0xc8f0ff}); + if(b.hp<=0){if(b.tents.some(t=>t.held))b.hp=1;else{b.hp=0;b.act='dead';b.t0=50;g.ev('boss_dead');}}} + M.register('morpha',{ + cases:[{id:'zelda/water_core_amoeba',name:'Water-Core Amoeba (Young Swordsman · Hookshot)'}], + arena:{r:V.arena,square:V.arena,ceil:600,start:[0,-460]},hearts:10,age:'adult',camDist:340,tune:TUNE,art:'morpha', + item:{kind:'hook',name:'Hookshot: fire with L (auto-aim at the core while locked)'},threats:{tentacle_lash:1,tentacle_grab:1,second_tentacle:1,core_hit:1,hero_hurt:1}, + // The hookshot: a straight reach of 520; a nucleus above the water is torn out of its tentacle and dragged to the hero (M8). + useItem(g){const h=g.hero,b=g.boss,c=b.core,T=g.lockTarget();if(h.itemCd>0)return;h.itemCd=16;const yaw=T?Math.atan2(T.x-h.x,T.z-h.z):h.face;h.face=yaw;g.ev('hook_fire'); + const dx=c.x-h.x,dz=c.z-h.z,along=dx*Math.sin(yaw)+dz*Math.cos(yaw),side=Math.abs(dx*Math.cos(yaw)-dz*Math.sin(yaw)); + for(let k=1;k<=6;k++){const f=Math.min(along>0?along:V.hookRange,V.hookRange)*k/6;g.fxAdd('spark',h.x+Math.sin(yaw)*f,h.y+44,h.z+Math.cos(yaw)*f,6,{r:5,color:0xd0d8e0});} + if(b.act==='dead'||c.y<-10||along<0||along>V.hookRange||side>V.hookR||c.inv>0)return; + if(c.act==='ride'||c.act==='back'){const t=b.tents[0];release(g,b,t,false);tentReset(t,'cut',40);g.ev('tentacle_cut');} + c.act='stunned';c.t0=V.hookStun;c.speed=0;c.inv=V.coreInv;c.x=h.x+Math.sin(yaw)*50;c.z=h.z+Math.cos(yaw)*50; + // Dragged all the way to the hero (source pulls the actor to the hookshot). Where it lands beside him is not in the code we can read (T19): here, on his wall side, so it never lands back in the pool. + const ox=Math.abs(h.x)>=Math.abs(h.z)?Math.sign(h.x||1):0,oz=ox?0:Math.sign(h.z||1),m=V.arena-30;c.x=N.clamp(h.x+ox*45,-m,m);c.z=N.clamp(h.z+oz*45,-m,m); + if(Math.hypot(c.x-h.x,c.z-h.z)<30){c.x=N.clamp(h.x+oz*45,-m,m);c.z=N.clamp(h.z+ox*45,-m,m);} + c.y=Math.max(c.y,30);c.vy=2;g.ev('core_hooked');}, + init(g){const b=g.boss;Object.assign(b,{hp:Math.round(g.T.hp),maxHp:Math.round(g.T.hp),act:'fight',t0:0,hitCount:0,lastSlash:-1,tents:[newTent(0)], + core:{x:200,y:-40,z:0,ox:200,oy:-40,oz:0,vy:0,speed:0,yaw:0,act:'move',t0:50,pos:0,inv:0,flash:0,vt:0}}); + const t=b.tents[0];relocate(g,b,t);}, + update(g){const b=g.boss,h=g.hero,c=b.core;c.ox=c.x;c.oy=c.y;c.oz=c.z;if(b.t0>0)b.t0--; + if(b.act==='dead'){if(b.t0===0)g.outcome='win';return;} + for(const t of b.tents){if(t.t0>0)t.t0--;}if(c.t0>0)c.t0--; + for(const t of b.tents)tentUpdate(g,b,t);if(g.outcome)return;coreUpdate(g,b);swordCheck(g,b); + // Deep water: the hero keeps to the walkway round the pool (T18). + if(!h.grabbed&&inPool(h.x,h.z)){const ex=V.pool+12-Math.abs(h.x),ez=V.pool+12-Math.abs(h.z);if(ex-10?{x:c.x,y:c.y,z:c.z}:{x:t.x,y:60,z:t.z};}, + hud(g){const b=g.boss,c=b.core,h=g.hero;if(h.grabbed)return 'Grabbed! Press J repeatedly to break free.'; + if(c.act==='stunned'||(c.act==='move'&&c.y>-10&&!inPool(c.x,c.z)))return 'Core on shore! Strike it with J.'; + if(c.act==='ride')return 'Core in a tentacle: lock with Shift, then pull it out with the hookshot (L).'; + return 'The core is hiding in water; wait for a tentacle to emerge.';}, + plan(h){return M.plans.__morpha(h);} + }); + M.plans.__morpha=function(h){const {stickTo,cloneGame,simTick}=M.ctl,H=h.hero,b=h.boss,c=b.core,t=b.tents[0],tap=k=>h.lastKeys.includes(k)?[]:[k],free=H.act==='idle'; + if(b.act==='dead'||H.act==='dead')return []; + if(H.grabbed){const k=Math.floor(h.t/2)%3;return k===0?['J']:k===1?['Space']:[];} + if(H.act==='kb')return []; + const safe=(keys,n)=>{const s=cloneGame(h);for(let i=0;i{for(const o of [0,.7,-.7,1.4,-1.4,2.2,-2.2,PI]){const k=stickTo(h,wrap(yaw+o));if(safe(k,16))return k;}for(const o of [0,PI/2,-PI/2,PI]){const k=[...stickTo(h,wrap(yaw+o)),'Space'];if(safe(k,14))return k;}return stickTo(h,yaw);}; + // The tentacle to keep away from: the nearest one that is up (a second one joins after three cuts, M10). + const live=b.tents.filter(q=>q.grow>.3||q.st==='spawn'),near=(live.length?live:b.tents).reduce((p,q)=>Math.hypot(q.x-H.x,q.z-H.z)-10&&!inPool(c.x,c.z)&&['move','stunned'].includes(c.act); + // Ashore: come at it from the pool side so each cut knocks it outwards against the wall (its knock-back is 15 a frame for 25 frames, M7), not back into the water. + if(ashore){const keys=['Shift'];if(!free)return keys;const ox=Math.abs(c.x)>=Math.abs(c.z)?Math.sign(c.x||1):0,oz=ox?0:Math.sign(c.z||1),side=(H.x-c.x)*ox+(H.z-c.z)*oz; + const spot={x:c.x-ox*40,z:c.z-oz*40},ds=Math.hypot(spot.x-H.x,spot.z-H.z); + // A cut roots the hero for its swing (10 frames): only start one the other tentacle cannot reach before it ends. + const lashing=b.tents.some(q=>q!==t&&(q.st==='swing'&&q.t0<12||q.st==='attack')&&Math.hypot(q.x-H.x,q.z-H.z)16){const k=stickTo(h,yawTo(H,side>10&&d<70?{x:c.x-ox*80+(H.x-c.x)*.3,z:c.z-oz*80+(H.z-c.z)*.3}:spot));keys.push(...(safe([...keys,...k],8)?k:dodge(yawTo(near,H))));} + return keys;} + // Above the water and within the hookshot's reach: pull it out. + if(c.y>-10&&dq.st==='swing'||q.st==='attack'||q.st==='curl'); + if(!safe([],busy?24:12))return dodge(yawTo(near,H)); + if(dw>30){const k=stickTo(h,yawTo(H,want));return safe(k,busy?24:12)?k:dodge(yawTo(near,H));}return [];}; + // The walkway point nearest the hero on a ring of radius 420 round the first root (past the lash, 360 + 40, and inside the hookshot reach of the riding nucleus), also 420 from any other root. + function standOff(ts,H){const t=ts[0];let best=null,bd=1e9;for(let i=0;i<32;i++){const a=i*PI/16,x=t.x+Math.sin(a)*420,z=t.z+Math.cos(a)*420; + if(inPool(x,z)&&Math.max(Math.abs(x),Math.abs(z))V.arena-24||Math.abs(z)>V.arena-24||ts.some(q=>q!==t&&Math.hypot(q.x-x,q.z-z)<400))continue;const d=Math.hypot(x-H.x,z-H.z);if(d 61-143 s (a run of fire blasts below 10/24 stalls the charge), 18 -> 63-67 s: two knock-downs finish her before the random phase. Source 24 (W1) is above normal; the d = 0 anchor is easy's 6 so health never falls as d rises + blast:[48,48,48,48], // blast damage, source 0x30 = three hearts (W5) + speed:[1,1,1.1,1.2], // blast speed factor (source 20) + rest:[60,30,50,45] // frames after a throw (source 60); easy 30: three soaked blasts are the shortest fight, and with 60 they alone take 31 s (T23) + }; + const setAct=(b,a,t)=>{b.act=a;b.t0=t===undefined?0:t;b.af=0;}; + function pickPerch(g,b){const h=g.hero;for(let n=0;n<20;n++){b.perch=(b.perch+1+Math.floor(g.rand()*2.99))%4;const [x,z]=PERCH[b.perch];if(Math.hypot(x-h.x,z-h.z)>W.away)break;} + const [x,z]=PERCH[b.perch];b.tx=x;b.tz=z;b.ty=W.flyY;} + function nextElement(g,b){if(b.hp=W.seqLen+1){b.seq=1;b.fixed=1-b.fixed;}return b.fixed;} // W4, threshold read at source health 10 of 24 + const ACT={ + fly(g,b){const sp=W.flySpeed*MOVE*.5;b.speed=Math.min(sp,b.speed+2);const dx=b.tx-b.x,dz=b.tz-b.z,d=Math.hypot(dx,dz)||1;b.x+=dx/d*Math.min(b.speed,d);b.z+=dz/d*Math.min(b.speed,d); + b.ty=Math.max(W.perchY,b.ty-2);b.y=approachF(b.y,b.ty,.1,6);b.yaw=Math.atan2(dx,dz);if(d{q.ox=q.x;q.oy=q.y;q.oz=q.z;q.life--; + const steps=3;for(let i=0;ih.y-10){ + if(shieldFaces(h,q)){absorb(g,b,q);return false;}g.hurt(g.T.blast,Math.atan2(q.vx,q.vz),{unblockable:true,kb:6});g.ev(q.el?'burned':'frozen');return false;} + if(q.y<=0||Math.hypot(q.x,q.z)>W.arena){g.fxAdd('burst',q.x,Math.max(4,q.y),q.z,12,{r:40,color:q.el?0xff7a2a:0x9fe2ff});return false;}} + return q.life>0;});} + // Soak: the same element adds a charge, the other element cancels the charge; three charges fire back along the shield (W7). + function absorb(g,b,q){const h=g.hero;g.ev('shield_absorb');if(b.charge>0&&b.chargeEl!==q.el){b.charge=0;g.ev('charge_cancel');return;} + b.chargeEl=q.el;b.charge++;if(b.charge>=3){b.charge=0;const T=g.lockTarget(),yaw=T?Math.atan2(T.x-h.x,T.z-h.z):h.face,pitch=T?Math.atan2(T.y-(h.y+40),Math.hypot(T.x-h.x,T.z-h.z)):.6; + b.shots.push({el:q.el,x:h.x,y:h.y+40,z:h.z,ox:h.x,oy:h.y+40,oz:h.z,vx:Math.sin(yaw)*Math.cos(pitch)*W.chargeSpeed,vy:Math.sin(pitch)*W.chargeSpeed,vz:Math.cos(yaw)*Math.cos(pitch)*W.chargeSpeed,life:W.chargeLife});g.ev('charge_release');}} + function chargeShots(g,b){b.shots=b.shots.filter(s=>{s.ox=s.x;s.oy=s.y;s.oz=s.z;s.life--;for(let i=0;i<4;i++){s.x+=s.vx*MOVE/4;s.y+=s.vy*MOVE/4;s.z+=s.vz*MOVE/4; + if(b.act!=='stun'&&b.act!=='dead'&&b.act!=='getup'&&Math.hypot(s.x-b.x,s.y-b.y,s.z-b.z)0&&Math.hypot(s.x,s.z)0||b.y>60)return;const s=g.strike();if(!s||s.id===b.lastSlash)return;if(!g.swordReach(b.x,b.y+30,b.z,W.bodyR))return;b.lastSlash=s.id; + b.hp-=s.dmg;b.inv=W.swordInv;g.ev('witch_hit');g.fxAdd('burst',b.x,b.y+40,b.z,8,{r:24,color:0xffffff});if(b.hp<=0){b.hp=0;setAct(b,'dead',50);g.ev('boss_dead');}} + M.register('twinrova',{ + cases:[{id:'zelda/twin_flame_frost_witches',name:'Twin Flame and Frost Witches (Young Swordsman · Mirror Shield)'}], + arena:{r:W.arena,ceil:900,start:[0,0]},hearts:12,age:'adult',camDist:360,tune:TUNE,art:'twinrova', + // No C item: the mirror shield (K) is the tool here (W6, W7), so L does nothing.threats:{fire_blast:1,ice_blast:1,charge_release:1,witch_stunned:1,hero_hurt:1}, + init(g){const b=g.boss;Object.assign(b,{x:PERCH[0][0],y:W.flyY,z:PERCH[0][1],ox:PERCH[0][0],oy:W.flyY,oz:PERCH[0][1],yaw:0,hp:Math.round(g.T.hp),maxHp:Math.round(g.T.hp),t0:0,af:0, + perch:0,tx:PERCH[0][0],ty:W.flyY,tz:PERCH[0][1],speed:0,vy:0,inv:0,lastSlash:-1,seq:0,fixed:0,element:0,blasts:[],shots:[],charge:0,chargeEl:0}); + pickPerch(g,b);setAct(b,'fly');}, + update(g){const b=g.boss,h=g.hero;if(b.t0>0)b.t0--;if(b.inv>0)b.inv--; + ACT[b.act](g,b,h);if(g.outcome)return;blasts(g,b);chargeShots(g,b);swordCheck(g,b); + if(b.act!=='stun'&&b.act!=='dead'&&b.y0)return `Shield holds ${c} charges of ${el}: absorb another of the same element (hold K to raise the shield); opposite elements cancel.`; + return 'Lock onto her with Shift and raise the shield with K to absorb shockwaves. Three of the same element reflect automatically.';}, + plan(h){return M.plans.__twinrova(h);} + }); + M.plans.__twinrova=function(h){const {stickTo,cloneGame,simTick}=M.ctl,H=h.hero,b=h.boss,tap=k=>h.lastKeys.includes(k)?[]:[k],free=H.act==='idle'; + if(b.act==='dead'||H.act==='dead'||H.act==='kb')return []; + // Knocked down: run to where she falls (straight down) and cut once she is low enough. + if(b.act==='stun'){const keys=['Shift'],d=hd(b,H),reach=M.constants.reach.adult+W.bodyR-6;if(!free)return keys;if(d>reach)keys.push(...stickTo(h,yawTo(H,b)));else if(b.inv===0&&b.y<60)keys.push(...tap('J'));return keys;} + // A blast on the way: face it with the shield if it is the element we are charging (or the shield is empty); otherwise roll out of its line. + const incoming=b.blasts.filter(q=>{const t=((H.x-q.x)*q.vx+(H.z-q.z)*q.vz)/(q.vx*q.vx+q.vz*q.vz||1);return t>0&&t<40;}); + if(incoming.length){const q=incoming[0],want=b.charge===0||q.el===b.chargeEl; + if(want){const keys=['Shift','K'];return keys;} + if(!free)return [];const side=wrap(Math.atan2(q.vx,q.vz)+PI/2);for(const o of [0,PI]){const k=[...stickTo(h,wrap(side+o)),'Space'];const s=cloneGame(h);let ok=true;for(let i=0;i<12&&!s.outcome;i++){simTick(s,k);if(s.events.includes('hero_hurt')){ok=false;break;}}if(ok)return k;} + return ['Shift','K'];} + // Otherwise stay near the middle, locked on, shield down. + const keys=['Shift'];if(free&&Math.hypot(H.x,H.z)>120)keys.push(...stickTo(h,yawTo(H,{x:0,z:0})));return keys;}; +})(typeof window==='undefined'?globalThis:window); diff --git a/environments/games/web/games/zelda_oot_remake/bosses/volvagia.js b/environments/games/web/games/zelda_oot_remake/bosses/volvagia.js new file mode 100644 index 0000000000000000000000000000000000000000..8bc82509127cc3232644cf4c4fafe0a985ecc7fa --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/bosses/volvagia.js @@ -0,0 +1,102 @@ +/* Volvagia (z_boss_fd2.c hole phase, z_boss_fd.c flying phase; SOURCES.md V1-V12). Original mechanics, own code. Frame counts are 20 Hz logic frames. + * Hole phase: he rises from one of nine holes, faking out more often as he weakens; a hammer blow on the head knocks him flat and exposes the face to the sword. + * Flying phase after three holes: alternately chases the hero breathing fire, or rams the ceiling to rain rocks, then dives into a new hole. */ +(function(root){ + 'use strict'; + const M=root.ZeldaOotGame,N=root.NativeBench,{wrap,hd,yawTo,approachS,MOVE}=M.helpers,PI=Math.PI; + const HOLES=[];for(const x of [-243,0,243])for(const z of [-243,0,243])HOLES.push({x,z}); // V2, source order + const V={wait:10,rise:15,sink:25,invHammer:30,vulnAnim:22,vuln:60,swipeR:200,swipe:24,swipeHit:[8,14],fireAnim:76,fireFrom:25,fireTo:70,fireLen:300,fireArc:0x1f40,headR:42,headY:118,headFwd:46,bodyR:58, + emergeKnock:120,flyChase:300,flyCeil:150,ceilY:700,rockEvery:16,rockFor:300,rockR:[130,50],rockFall:16,flySpeed:5,chaseFloor:50,chaseHigh:300,breathEvery:64,breathFor:20,bodySeg:16,roomR:520}; + const holeTime=(hp,mx)=>{const k=hp/mx*24;return k>=24?30:k>=18?25:k>=12?20:k>=6?10:5;}; // V3, read at the source's health thresholds of 24 + const idleTime=(hp,mx)=>{const k=hp/mx*24;return k>=24?50:k>=18?40:k>=12?40:k>=6?30:20;}; + const fakes=(hp,mx)=>{const k=hp/mx*24;return k>=18?0:k>=12?1:k>=6?2:3;}; + const TUNE={ + hp:[24,32,64,190], // BossBench: tier windows, source 24 at d = 0 (T13); easy 20 ended in 15-16 s, 28 in 17-19 s, 32 in 23-26 s (seeds 1-16) + hammer:[2,2,2,2], // source (V4) + touch:[32,32,36,40], // hole-phase body and claw (source 0x20) + fly:[16,16,20,24], // flying body and breath (source 0x10) + rock:[16,16,20,24], + chase:[1,1,1.12,1.25] // flying speed factor + }; + const setAct=(b,a,t)=>{b.act=a;b.t0=t===undefined?0:t;b.af=0;}; + const headOf=b=>({x:b.x+Math.sin(b.yaw)*V.headFwd,y:b.y+V.headY*(b.act==='vuln'?.35:1),z:b.z+Math.cos(b.yaw)*V.headFwd}); + function pickHole(g,b){let i;do{i=Math.floor(g.rand()*8.9);}while(i===b.hole&&b.holesTried++<6);b.hole=i;const H=HOLES[i];b.x=H.x;b.z=H.z;} + function setupEmerge(g,b){setAct(b,'under',V.wait);pickHole(g,b);b.y=-200;b.fakes=fakes(b.hp,b.maxHp);b.exposed=false;g.ev('volvagia_rumble');} + function hurtHero(g,b,dmg,from,opt){return g.hurt(dmg,from,opt);} + const ACT={ + under(g,b){if(b.t0===0){setAct(b,'peek',holeTime(b.hp,b.maxHp));b.y=-60;g.ev('volvagia_peek');}}, + peek(g,b,h){if(b.t0===0){if(b.fakes>0){b.fakes--;setAct(b,'under',V.wait);pickHole(g,b);b.y=-200;return;} // a fake-out moves to another hole without resetting the count (V3) + setAct(b,'rise',V.rise);b.y=0;b.yaw=yawTo(b,h);b.holeCount++;g.ev('volvagia_emerge');g.fxAdd('ring',b.x,3,b.z,12,{r:150,color:0xff8a3a});}}, + rise(g,b,h){b.yaw=approachS(b.yaw,yawTo(b,h),3,0x7d0);if(b.t0===1&&hd(b,h)=V.swipeHit[0]&&b.af<=V.swipeHit[1]&&hd(b,h)=V.fireFrom&&b.af=3&&b.hpV.vulnAnim&&b.t0===0){b.exposed=false;setAct(b,'burrow',V.sink);}}, + damaged(g,b){if(b.t0===0){b.exposed=false;setAct(b,'burrow',V.sink);}}, + fly(g,b,h){b.af++;const T=b.flyTarget,dx=T.x-b.x,dy=T.y-b.y,dz=T.z-b.z,dist=Math.hypot(dx,dy,dz); + b.yaw=wrap(b.yaw+N.clamp(wrap(Math.atan2(dx,dz)-b.yaw),-b.turn*M.helpers.BIN,b.turn*M.helpers.BIN));const sp=V.flySpeed*b.speedK*MOVE; + const c=Math.min(1,dist/Math.max(1,sp));b.x+=Math.sin(b.yaw)*Math.min(sp,Math.hypot(dx,dz));b.z+=Math.cos(b.yaw)*Math.min(sp,Math.hypot(dx,dz));b.y+=N.clamp(dy,-sp,sp); + b.trail.unshift({x:b.x,y:b.y,z:b.z});if(b.trail.length>V.bodySeg)b.trail.pop(); + if(b.mode==='chase'){b.chaseY=Math.max(V.chaseFloor,b.chaseY-1);b.flyTarget={x:h.x,y:h.y+30+b.chaseY+Math.sin(b.af*2396*M.helpers.BIN)*30,z:h.z}; + if(b.t0%V.breathEvery===0&&b.t0<450&&Math.abs(wrap(yawTo(b,h)-b.yaw))<.6){b.breathT=V.breathFor;g.ev('volvagia_breath');} + if(b.t0===0||b.hitFly){b.hitFly=false;toHole(g,b);}} + else if(b.mode==='ceiling'){b.flyTarget={x:0,y:V.ceilY+60,z:-300};if(b.y>V.ceilY){b.mode='rocks';b.t0=V.flyCeil;b.rocksT=V.rockFor;g.ev('volvagia_ceiling');}} + else if(b.mode==='rocks'){b.flyTarget={x:b.ceilTargets[Math.floor(b.af/25)%6].x,y:V.ceilY+60,z:b.ceilTargets[Math.floor(b.af/25)%6].z};if(b.t0===0)toHole(g,b);} + else if(b.mode==='toHole'){if(dist<100){setAct(b,'burrow',V.sink*2);b.y=0;b.trail=[];g.ev('volvagia_dive');}} + if(b.breathT>0){b.breathT--;const d=hd(b,h),off=Math.abs(wrap(yawTo(b,h)-b.yaw));if(di%3===0))if(Math.hypot(s.x-h.x,s.z-h.z)0){b.rocksT--;if(b.rocksT%V.rockEvery===0){const r=V.rockR[0]+Math.floor(g.rand()*V.rockR[1]);b.rocks.push({x:b.x+(g.rand()-.5)*80,y:600,z:b.z+(g.rand()-.5)*80,oy:600,r:r*.3,vy:0});g.ev('rock_fall');}} + const h=g.hero;b.rocks=b.rocks.filter(q=>{q.oy=q.y;q.vy-=1.6;q.y+=q.vy*MOVE;if(q.y<=q.r){g.fxAdd('burst',q.x,8,q.z,10,{r:q.r*1.4,color:0xb06a3a});if(Math.hypot(q.x-h.x,q.z-h.z)0){b.inv--;return;}const s=g.strike();if(!s||s.id===b.lastSlash)return; + const q=headOf(b);if(!['peek','rise','idle','swipe','fire','vuln'].includes(b.act)||b.y<-10&&b.act!=='vuln')return; + if(!g.swordReach(q.x,q.y-(h.weapon==='hammer'?40:0),q.z,V.headR+(h.weapon==='hammer'?20:0)))return;b.lastSlash=s.id; + if(!b.exposed){if(h.weapon!=='hammer')return;b.hp-=g.T.hammer;if(b.hp<=2)b.hp=1;b.exposed=true;setAct(b,'vuln',0);b.inv=V.invHammer;g.ev('volvagia_hammered');g.fxAdd('burst',q.x,q.y,q.z,10,{r:30,color:0xffe0a0});return;} + if(h.weapon==='hammer'){if(b.hp>2){b.hp-=2;}}else b.hp-=s.dmg;g.ev('volvagia_hit');b.inv=6; + if(b.hp<=0){b.hp=0;setAct(b,'dead',50);g.ev('boss_dead');}} + M.register('volvagia',{ + cases:[{id:'zelda/burrowing_fire_dragon',name:'Burrowing Fire Dragon (Young Swordsman · Heavy Hammer)'}], + arena:{r:V.roomR,ceil:820,start:[0,-380]},hearts:10,age:'adult',camDist:340,tune:TUNE,art:'volvagia', + item:{kind:'hammer',name:'Heavy Hammer: L switches hammer / sword'},threats:{volvagia_emerge:1,volvagia_fire:1,volvagia_swipe:1,volvagia_fly:1,rock_fall:1,hero_hurt:1}, + // The C item swaps the hammer in for the sword: J then swings the hammer (slower, the only thing that dents his skull plate, V4). + useItem(g){const h=g.hero;h.weapon=h.weapon==='hammer'?'sword':'hammer';h.itemCd=8;g.ev('weapon_swap');}, + init(g){const b=g.boss;Object.assign(b,{x:0,y:-200,z:0,ox:0,oy:-200,oz:0,yaw:0,hp:Math.round(g.T.hp),maxHp:Math.round(g.T.hp),t0:0,af:0,hole:-1,holesTried:0,holeCount:0,fakes:0,exposed:false,inv:0,lastSlash:-1, + breath:0,flyCount:0,mode:'',trail:[],chaseY:0,turn:1000,speedK:1,flyTarget:{x:0,y:0,z:0},ceilTargets:[],breathT:0,rocksT:0,rocks:[],hitFly:false});setupEmerge(g,b);g.hero.weapon='sword';}, + update(g){const b=g.boss,h=g.hero;if(b.t0>0)b.t0--; + if(b.act==='dead'){if(b.t0===0)g.outcome='win';return;} + ACT[b.act](g,b,h);if(g.outcome)return;rocks(g,b);hitCheck(g,b); + if(['rise','idle','swipe','fire'].includes(b.act)&&hd(b,h)h.lastKeys.includes(k)?[]:[k],free=H.act==='idle'; + if(b.act==='dead'||H.act==='dead'||H.act==='kb')return []; + const want=b.exposed?'sword':'hammer';if(free&&H.weapon!==want&&H.itemCd===0&&['peek','rise','idle','swipe','fire','vuln','under'].includes(b.act))return tap('L'); + const safe=(keys,n)=>{const s=cloneGame(h);for(let i=0;i{for(const o of [0,.7,-.7,1.4,-1.4,2.2,-2.2,PI]){const k=stickTo(h,wrap(yaw+o));if(safe(k,24))return k;}for(const o of [0,PI/2,-PI/2,PI]){const k=[...stickTo(h,wrap(yaw+o)),'Space'];if(safe(k,18))return k;}return stickTo(h,yaw);}; + // Flying: keep moving away from him and from falling rocks; nothing to hit. + if(b.act==='fly'){if(!free)return [];if(safe([],24))return [];return dodge(yawTo(b,H));} + // Up out of a hole: walk to the head and strike while he is idle; leave his breath cone and claw. + if(['rise','idle','swipe','fire','vuln','peek'].includes(b.act)){const q=headOf(b),d=Math.hypot(q.x-H.x,q.z-H.z),reach=M.constants.reach.adult+V.headR-6; + if(!free)return ['Shift']; + const keys=['Shift'];if(b.act==='peek'){if(d>140)keys.push(...stickTo(h,yawTo(H,q)));return keys;} + if(d>reach){const k=stickTo(h,yawTo(H,q));if(safe([...keys,...k],12))keys.push(...k);else keys.push(...dodge(yawTo(b,H)));return keys;} + if(b.inv===0&&safe([...keys,'J'],6)||b.act==='vuln')keys.push(...tap('J'));else keys.push(...dodge(yawTo(b,H)));return keys;} + // Underground: wait near the middle. + if(Math.hypot(H.x,H.z)>140&&free)return stickTo(h,yawTo(H,{x:0,z:0}));return [];}; +})(typeof window==='undefined'?globalThis:window); diff --git a/environments/games/web/games/zelda_oot_remake/compact_actions.json b/environments/games/web/games/zelda_oot_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..b6eebd9487aecb38c70f82951228cb8269dc2ae0 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/compact_actions.json @@ -0,0 +1,582 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "zelda_oot_remake", + "version": "zelda_oot_remake-compact@3", + "note": "Third-person lock-on swordplay in the ViZDoom manner: lock (held) x 8-way movement x one action at a time. One action = one 200 ms packet = 12 ticks = 4 logic frames (20 Hz rules on the 60 Hz shell; logic runs on ticks 2, 5, 8, 11). Slash, item and roll/jump are press-triggered and timed to the logic frame, so each has four options, one per logic frame of the packet (a press in sub-step 0 or 1 lands on frame 1, 2 on frame 2, 3 or 4 on frame 3, 5 on frame 4; the sub-steps chosen are the ones the reference controller uses). With a single packet-start option the nearest-option snap drops 3 of 4 presses: a single-sub-step press at another phase is as far from it as from the no-op, and ties go to the no-op. Shield can also be raised for the second half or the first half of the packet (the mirror shield has to be up on the exact logic frame a blast arrives). Each movement direction also has a short form held for the first half of the packet only (logic frames 1-2): the reference controller sets a roll's direction with the stick for one or two sub-steps and steps short distances to line up (bomb into the mouth, standing in the lash's reach), and a whole-packet hold overshoots. Movement is camera-relative. The simulation's camera follows the lock target (else the boss) by itself, up to 0.14 rad per logic frame, and while locked the hero always faces the target and the item auto-aims at it, so no aiming head is needed. Camera steps (user 2026-11-10: every 3D compact set must be able to turn the camera): Q / E turn the camera offset 45 degrees left / right and R resets it to 0, pressed once per packet (tap, read on logic frame 1). The offset is added on top of the automatic follow, so the view orbits the hero and the stick directions turn with it. They share the action head because a camera step and a sword / shield / roll / item action are never needed in the same 200 ms; merging adds 3 actions where a separate head would multiply the count by 4, and every combination stays within 4 keys per sub-step (Shift + two direction keys + one action key). The same offset by mouse is 0.0035 rad per count (dx 224 = 45 degrees), so mouse dx adds nothing and is left out. The reference controller never turns the camera, so snapping its packets never picks a camera step. Left out because no scene needs them: the held-J charge for the spin attack (the reference controller never spins), mouse dy (slingshot pitch only while not locked; lock-on aim covers every scene) and the wheel. One-frame forward steps (version @3, 2026-11-10, after the amoeba hard cell snapped to 0 wins on seeds 1-4): forward / forward-left / forward-right held on logic frame 1 only or on logic frame 3 only, and forward on logic frame 4 only. Held keys are read only on the logic ticks (sub-steps 1, 2, 4, 5), and the reference controller lines up on the nucleus one logic frame at a time (a frame moves the hero at most 9 units; the sword reaches 62), mostly forward or diagonally forward. Snapped to the nearest whole-packet or half-packet option these steps were dropped or doubled. They are appended after the older options, so every packet the older options matched still snaps to them. With them the amoeba hard cell wins 1 of 4 on seeds 1-4 and 12 of 32 on seeds 1-32 (6 of 32 without); the rest of the loss is the packet-level grain itself: per-half-packet directions (9 x 9 = 81 move options) win about half, and do not fit under 1000 actions.", + "heads": [ + { + "name": "lock", + "options": [ + { + "label": "none" + }, + { + "label": "hold", + "keys": [ + "Shift" + ] + } + ] + }, + { + "name": "move", + "options": [ + { + "label": "none" + }, + { + "label": "forward", + "keys": [ + "W" + ] + }, + { + "label": "back", + "keys": [ + "S" + ] + }, + { + "label": "left", + "keys": [ + "A" + ] + }, + { + "label": "right", + "keys": [ + "D" + ] + }, + { + "label": "forward_left", + "keys": [ + "W", + "A" + ] + }, + { + "label": "forward_right", + "keys": [ + "W", + "D" + ] + }, + { + "label": "back_left", + "keys": [ + "S", + "A" + ] + }, + { + "label": "back_right", + "keys": [ + "S", + "D" + ] + }, + { + "label": "forward_step", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [], + [], + [] + ] + }, + { + "label": "back_step", + "subs": [ + [ + "S" + ], + [ + "S" + ], + [ + "S" + ], + [], + [], + [] + ] + }, + { + "label": "left_step", + "subs": [ + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [], + [], + [] + ] + }, + { + "label": "right_step", + "subs": [ + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [], + [], + [] + ] + }, + { + "label": "forward_left_step", + "subs": [ + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [], + [], + [] + ] + }, + { + "label": "forward_right_step", + "subs": [ + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [], + [], + [] + ] + }, + { + "label": "back_left_step", + "subs": [ + [ + "S", + "A" + ], + [ + "S", + "A" + ], + [ + "S", + "A" + ], + [], + [], + [] + ] + }, + { + "label": "back_right_step", + "subs": [ + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [], + [], + [] + ] + }, + { + "label": "forward_f1", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [], + [], + [], + [] + ] + }, + { + "label": "forward_left_f1", + "subs": [ + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [], + [], + [], + [] + ] + }, + { + "label": "forward_right_f1", + "subs": [ + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [], + [], + [], + [] + ] + }, + { + "label": "forward_f3", + "subs": [ + [], + [], + [], + [ + "W" + ], + [ + "W" + ], + [] + ] + }, + { + "label": "forward_left_f3", + "subs": [ + [], + [], + [], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [] + ] + }, + { + "label": "forward_right_f3", + "subs": [ + [], + [], + [], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [] + ] + }, + { + "label": "forward_f4", + "subs": [ + [], + [], + [], + [], + [], + [ + "W" + ] + ] + } + ] + }, + { + "name": "act", + "options": [ + { + "label": "none" + }, + { + "label": "slash_f1", + "subs": [ + [ + "J" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "slash_f2", + "subs": [ + [], + [], + [ + "J" + ], + [], + [], + [] + ] + }, + { + "label": "slash_f3", + "subs": [ + [], + [], + [], + [ + "J" + ], + [], + [] + ] + }, + { + "label": "slash_f4", + "subs": [ + [], + [], + [], + [], + [], + [ + "J" + ] + ] + }, + { + "label": "shield", + "keys": [ + "K" + ] + }, + { + "label": "shield_late", + "subs": [ + [], + [], + [], + [ + "K" + ], + [ + "K" + ], + [ + "K" + ] + ] + }, + { + "label": "shield_early", + "subs": [ + [ + "K" + ], + [ + "K" + ], + [ + "K" + ], + [], + [], + [] + ] + }, + { + "label": "jump_f1", + "subs": [ + [], + [ + "Space" + ], + [], + [], + [], + [] + ] + }, + { + "label": "jump_f2", + "subs": [ + [], + [], + [ + "Space" + ], + [], + [], + [] + ] + }, + { + "label": "jump_f3", + "subs": [ + [], + [], + [], + [ + "Space" + ], + [], + [] + ] + }, + { + "label": "jump_f4", + "subs": [ + [], + [], + [], + [], + [], + [ + "Space" + ] + ] + }, + { + "label": "item_f1", + "subs": [ + [ + "L" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "item_f2", + "subs": [ + [], + [], + [ + "L" + ], + [], + [], + [] + ] + }, + { + "label": "item_f3", + "subs": [ + [], + [], + [], + [ + "L" + ], + [], + [] + ] + }, + { + "label": "item_f4", + "subs": [ + [], + [], + [], + [], + [], + [ + "L" + ] + ] + }, + { + "label": "struggle", + "subs": [ + [ + "J" + ], + [ + "Space" + ], + [], + [ + "J" + ], + [ + "Space" + ], + [] + ] + }, + { + "label": "cam_left", + "tap": [ + "Q" + ] + }, + { + "label": "cam_right", + "tap": [ + "E" + ] + }, + { + "label": "cam_reset", + "tap": [ + "R" + ] + } + ] + } + ] +} diff --git a/environments/games/web/games/zelda_oot_remake/draw.js b/environments/games/web/games/zelda_oot_remake/draw.js new file mode 100644 index 0000000000000000000000000000000000000000..51851dffd4a9519aec927a1ab4242801f408c4fb --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/draw.js @@ -0,0 +1,39 @@ +/* HUD drawn over the WebGL frame: hearts, boss bar, timer, native Hz, tier, item, per-boss hint. Reads state only. */ +(function(root){ + 'use strict';const M=root.ZeldaOotGame,R=root.ZeldaOot3D; + const NAMES={goma:['One-Eyed Carapace Queen','ONE-EYED CARAPACE QUEEN'],dodongo:['Magma Cave Lizard King','MAGMA CAVE LIZARD KING'],ganondrof:['Gallery Specter','GALLERY SPECTER'],volvagia:['Burrowing Fire Dragon','BURROWING FIRE DRAGON'],morpha:['Water-Core Amoeba','WATER CORE AMOEBA'],twinrova:['Twin Flame-Frost Witches','TWIN FLAME FROST WITCHES']}; + const ACT={idle:'',slash:'Sword slash',spin:'Spin attack',jumpslash:'Jump slash',roll:'Roll',hop:'Side hop',land:'Landing',kb:'Knocked back',dead:'Down'}; + function text(c,s,x,y,size,color,align='left',weight='bold'){c.font=`${weight} ${size}px "Segoe UI","Microsoft YaHei",sans-serif`;c.textAlign=align;c.lineJoin='round';c.lineWidth=Math.max(3,size/4.5);c.strokeStyle='rgba(10,12,24,.88)';c.strokeText(s,x,y);c.fillStyle=color;c.fillText(s,x,y);} + function heart(c,x,y,r,k){c.save();c.translate(x,y);const path=()=>{c.beginPath();c.moveTo(0,r*.9);c.bezierCurveTo(-r*1.3,-r*.1,-r*.7,-r,0,-r*.35);c.bezierCurveTo(r*.7,-r,r*1.3,-r*.1,0,r*.9);c.closePath();}; + path();c.fillStyle='rgba(30,16,22,.82)';c.fill();if(k>0){c.save();path();c.clip();c.fillStyle='#ef4a56';c.fillRect(-r*1.4,-r*1.2,r*2.8*k,r*2.4);c.restore();}path();c.lineWidth=1.6;c.strokeStyle='#f8eede';c.stroke();c.restore();} + function tierName(d){for(const [k,v] of Object.entries(M.tiers))if(Math.abs(v-d)<1e-9)return k;return 'd='+(+d).toFixed(2);} + // Aim aids drawn in 2D over the frame, so walls never hide them: a lock reticle on the locked target, a small marker on lockable targets, + // and at the frame edge an arrow toward the boss or an active threat that is out of view. Everything comes from the state through the view's own camera. + function reticle(c,x,y,r,a,col,ring){c.save();c.translate(x,y);c.lineWidth=4;c.strokeStyle='rgba(10,12,24,.9)';c.beginPath();c.arc(0,0,r,0,PI2);c.stroke();c.lineWidth=2.5;c.strokeStyle=ring||col;c.beginPath();c.arc(0,0,r,0,PI2);c.stroke(); + for(let i=0;i<4;i++){const o=a+i*PI2/4;c.save();c.rotate(o);c.beginPath();c.moveTo(0,-r-3);c.lineTo(-7,-r-15);c.lineTo(7,-r-15);c.closePath();c.fillStyle=col;c.fill();c.lineWidth=1.5;c.strokeStyle='rgba(10,12,24,.9)';c.stroke();c.restore();} + c.fillStyle=col;c.beginPath();c.arc(0,0,2.5,0,PI2);c.fill();c.restore();} + function edgeArrow(c,p,col,label){const m=34,ax=p.dx,ay=p.dy,k=Math.min((427-m)/Math.max(1e-6,Math.abs(ax)),(240-m)/Math.max(1e-6,Math.abs(ay))),x=427+ax*k,y=240+ay*k,a=Math.atan2(ay,ax); + c.save();c.translate(x,y);c.rotate(a);c.beginPath();c.moveTo(18,0);c.lineTo(-10,-13);c.lineTo(-4,0);c.lineTo(-10,13);c.closePath();c.fillStyle=col;c.fill();c.lineWidth=2.5;c.strokeStyle='rgba(10,12,24,.92)';c.stroke();c.restore(); + if(label)text(c,label,x-Math.cos(a)*30,y-Math.sin(a)*30+5,12,col,'center');} + const PI2=Math.PI*2; + function aimAids(g,c,def){const P=(x,y,z)=>R.project(c,x,y,z);if(!R.project)return;const lock=g.lockTarget(),ts=g.targets(); + for(const q of ts){if(lock&&q.id===lock.id)continue;const p=P(q.x,q.y,q.z);if(p&&p.on){c.beginPath();c.moveTo(p.x,p.y-26);c.lineTo(p.x-7,p.y-38);c.lineTo(p.x+7,p.y-38);c.closePath();c.fillStyle='rgba(255,236,160,.9)';c.fill();c.lineWidth=1.5;c.strokeStyle='rgba(10,12,24,.9)';c.stroke();}} + if(lock){const p=P(lock.x,lock.y,lock.z),h=g.hero,d=Math.hypot(lock.x-h.x,lock.z-h.z),reach=M.constants.reach[h.age]+24,inReach=d<=reach&&lock.y-24<=h.y+96; + // The reticle closes in as the hero does (ring radius from the hero-target distance: a range finder in the picture) and its ring turns orange once the target is within a sword's reach. + if(p&&p.on)reticle(c,p.x,p.y,14+18*Math.max(0,Math.min(1,(d-reach)/360)),g.t*(inReach?.2:.09),'#ffd34a',inReach?'#ff7a2a':null);else if(p)edgeArrow(c,p,'#ffd34a','Lock');} + // The boss gets its own arrow whenever it is off screen and the lock is on something else (a larva, an egg) or on nothing. + const b=def.marker?def.marker(g):null;if(b&&(!lock||Math.hypot(lock.x-b.x,lock.y-b.y,lock.z-b.z)>90)){const p=P(b.x,b.y,b.z);if(p&&!p.on)edgeArrow(c,p,'#ffb07a','Boss');} + for(const w of def.dangers?def.dangers(g):[]){const p=P(w.x,w.y,w.z);if(p&&!p.on)edgeArrow(c,p,'#ff4a3a',w.label||'Danger');}} + M.draw=function(g,c){R.render(g,c);const h=g.hero,def=g.def(),[hp,maxHp,bh,bm]=g.health(),n=Math.ceil(maxHp/16);aimAids(g,c,R.art[g.kind]||{}); + for(let i=0;iq.id===g.id)||{}).name||'').split(' (')[0],''];text(c,`${cn} ${en}`,427,28,18,'#fff4d6','center'); + const w=300;c.fillStyle='rgba(16,16,34,.82)';c.fillRect(427-w/2,36,w,12);c.fillStyle='#ffbf4a';c.fillRect(427-w/2+2,38,(w-4)*(bm?bh/bm:0),8);c.strokeStyle='#f6f2e6';c.lineWidth=1.4;c.strokeRect(427-w/2,36,w,12);text(c,`${bh} / ${bm}`,427,64,12,'#fff','center'); + const s=g.t/M.hz,mm=Math.floor(s/60),ss=(s%60).toFixed(1).padStart(4,'0');text(c,`${mm}:${ss}`,830,30,20,'#fff','right');text(c,`${M.hz}Hz`,830,52,14,'#9fe7ff','right');text(c,tierName(g.d).toUpperCase(),830,72,13,'#ffd23a','right'); + if(def.item)text(c,`C Item: ${def.item.name} (L)`,22,78,13,'#ffe9a8');if(ACT[h.act])text(c,ACT[h.act],22,98,14,'#fff'); + if(h.charge>0){c.fillStyle='rgba(16,16,34,.82)';c.fillRect(22,108,110,8);c.fillStyle=h.charge>=.85?'#9fe7ff':'#6a7fb0';c.fillRect(23,109,108*h.charge,6);} + if(h.lock!==null)text(c,'Lockin',22,130,13,'#ffd34a'); + const tip=def.hud?def.hud(g):'';if(tip)text(c,tip,427,430,16,'#fff3c4','center','600'); + if(g.outcome==='win')text(c,'★ Boss defeated',427,226,40,'#ffe24a','center');if(g.outcome==='loss')text(c,'You fell',427,226,40,'#ff6b5b','center');if(g.outcome==='timeout')text(c,'Time up',427,226,40,'#ffd0c0','center'); + text(c,'WASD run · Space roll/dodge · Shift lock · J sword · K shield · L item · Q/E camera',832,466,12,'#d8e8ff','right','600');}; + M.renderStatus=ctx=>R.status(ctx);M.renderMetrics=ctx=>R.metrics(ctx);M.closeRenderer=ctx=>R.close(ctx); +})(window); diff --git a/environments/games/web/games/zelda_oot_remake/game.js b/environments/games/web/games/zelda_oot_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..9b08c21646d3c9ba784504cbc5831fd3993a97b4 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/game.js @@ -0,0 +1,154 @@ +/* The Legend of Zelda: Ocarina of Time (N64, 1998): boss trials as an independent deterministic simulation (rules: M.version). + * Rules and numbers are facts read from the zeldaret/oot decompilation at commit 14759abf (no code, comments or assets + * copied; see SOURCES.md and ASSET_RIGHTS.md). The original's game logic runs at 20 Hz (R_UPDATE_RATE = 3 on a 60 Hz VI); + * the shell runs 60 Hz and every third tick runs one logic frame, so constants keep their per-frame source values. + * Positions move by velocity x 1.5 per logic frame, as the original's position update does at that rate. */ +(function(root){ + 'use strict'; + const N=root.NativeBench,PI=Math.PI,BIN=PI*2/65536,MOVE=1.5,K=3; + const wrap=a=>N.angle(a),hd=(a,b)=>Math.hypot(a.x-b.x,a.z-b.z),yawTo=(a,b)=>Math.atan2(b.x-a.x,b.z-a.z); + // Same behaviour as the source's approach helpers, in radians where the original uses binary angles. + const approachF=(v,t,scale,step)=>v+N.clamp((t-v)*scale,-step,step); + const approachS=(c,t,scale,step)=>wrap(c+N.clamp(wrap(t-c)/scale,-step*BIN,step*BIN)); + const stepF=(v,t,s)=>vvwrap(c+N.clamp(wrap(t-c),-s*BIN*MOVE,s*BIN*MOVE)); + // Player constants: SOURCES.md P1-P9. Animation data is not in the repository, so action lengths are marked A1 there. + const P={heart:16,runCap:6,accel:2,decel:1.5,stop:8,turn:2000,gravity:1,rollFrames:16,rollInvFrom:6,rollInv:10,rollMin:3,rollMul:1.5, + hopBackVy:5.8,hopSideVy:3.5,hopBack:6,hopSide:8.5,jumpVy:5,jumpFwd:5,hurtInv:20,kbSpeed:4,kbVy:5,kbRecover:18,chargeStep:.02,chargeNeed:.85, + radius:12,height:60,seedSpeed:80,arrowSpeed:150, + slashFrames:[10,10,14],slashActive:[[1,4],[1,4],[0,5]],comboFrom:5,reach:{child:48,adult:62},itemCd:12,spinFrames:14,spinReach:1.3,shieldArc:1.2,deadFrames:30}; + const SWORD={child:{slash:1,jump:2,spin:1},adult:{slash:2,jump:4,spin:2}}; + const TIERS={easy:.2,normal:.5,hard:.8}; + // Each tuning row is [source value, easy, normal, hard] at d = 0 / .2 / .5 / .8, piecewise linear; past hard the last slope continues. + const lerpTune=(r,d)=>{const X=[0,.2,.5,.8];let i=0;while(i<2&&d>X[i+1])i++;return r[i]+(r[i+1]-r[i])*(d-X[i])/(X[i+1]-X[i]);}; + const M=root.ZeldaOotGame={id:'zelda_oot_remake',version:'oot-arena@5',hz:60,maxSeconds:300,dimension:'3d',renderer:'webgl-zelda-oot', + title:'Ancient Sword Legend: Boss Trials',tiers:TIERS,cases:[],bosses:{},plans:{},constants:P, + controls:{'W A S D':'Run relative to camera direction (full analog-stick deflection)','Space':'A: roll while unlocked (invulnerable frames); while locked, forward = jump slash, back = back hop, left/right = side hop.', + 'Shift':'Z: hold to lock onto the nearest target; press again to switch. Face the target while locked.','J / LMB':'B: swing sword; press repeatedly for a three-hit combo. Hold to charge, release for a spin attack.','K / RMB':'R: hold shield to block attacks from the front.', + 'L':'C: use the item for this fight (auto-aim while locked; otherwise aim forward).','Q / E':'Turn camera left/right by 45°','R':'reset the camera','MouseMove':'Rotate camera; vertical movement changes unlocked aim pitch.'}, + helpers:{wrap,hd,yawTo,approachF,approachS,stepF,stepAsym,stepYaw,BIN,MOVE,lerpTune}}; + M.register=(key,def)=>{M.bosses[key]=def;M.plans[key]=def.plan;for(const c of def.cases)M.cases.push({id:c.id,name:c.name,boss:key});}; + M.difficultyBand=d=>d===0?'source':d<=.2?'source-easy':d<=.5?'easy-normal':d<=.8?'normal-hard':'beyond-hard'; + // Planning copies draw from this instead of the live generator: a multiplicative mix of tick, draw count and salt, so nothing not yet drawn can reach a plan. + const planMix=(t,n,s)=>{let x=Math.imul(t+1,0x9e3779b1)^Math.imul(n+1,0x85ebca6b)^Math.imul(s+1,0xc2b2ae35);x=Math.imul(x^(x>>>15),0x2c1b3c6d);x=Math.imul(x^(x>>>12),0x297a2d39);return ((x^(x>>>15))>>>0)/4294967296;}; + class Game{ + constructor(id,seed,d){ + const c=M.cases.find(q=>q.id===id);if(!c)throw Error('Unknown case '+id); + this.id=id;this.seed=seed;this.d=d;this.t=0;this.outcome=null;this.events=[];this.sub=0;this.frame=0;this.draws=0; + this.rng=(Math.imul((seed^0x6f6f7421)>>>0,0x9e3779b1)>>>0)||1; + this.inp={press:[],mouse:[0,0]};this.shots=[];this.fx=[];this.lastKeys=[]; + const def=M.bosses[c.boss];this.kind=c.boss;this.T={};for(const k of Object.keys(def.tune))this.T[k]=lerpTune(def.tune[k],d); + const a=def.arena;this.arena={r:a.r,ceil:a.ceil,square:a.square||0}; + this.hero={x:a.start[0],y:0,z:a.start[1],ox:a.start[0],oy:0,oz:a.start[1],vy:0,speed:0,yaw:PI,face:PI,act:'idle',timer:0, + hp:def.hearts*P.heart,maxHp:def.hearts*P.heart,inv:0,lock:null,combo:0,slashId:0,charge:0,itemCd:0,shield:false,age:def.age,airSlash:false,flash:0,grabbed:false,mode:0}; + this.cam={yaw:PI,offset:0,dist:def.camDist||360,oyaw:PI,pitchAim:0}; + this.boss={kind:c.boss,hp:1,maxHp:1,act:'init',timer:0};def.init(this); + this.cam.yaw=this.cam.oyaw=this.hero.face; + } + rand(){if(this.blind!==undefined)return planMix(this.t,this.draws++,this.blind);this.draws++;return N.rand(this);} + randS(base,range){return base+Math.floor(this.rand()*range);} + ev(name){this.events.push(name);} + fxAdd(kind,x,y,z,life,extra){if(this.fx.length<48)this.fx.push(Object.assign({kind,x,y,z,life,max:life},extra||{}));} + def(){return M.bosses[this.kind];} + // fromYaw is the direction of the push, so the attacker stands at fromYaw + PI from the hero. Returns true (hurt), 'block', or false (no effect). + hurt(dmg,fromYaw,opt){const h=this.hero,o=opt||{};if(this.outcome||h.act==='dead'||h.inv!==0||(h.grabbed&&!o.grab))return false; + if(!o.unblockable&&h.shield&&Math.abs(wrap(fromYaw+PI-h.face))reach)return false; + if(!spin&&d>r&&Math.abs(wrap(Math.atan2(tx-h.x,tz-h.z)-h.face))>1.1)return false; + return ty+r>=h.y-10&&ty-r<=h.y+P.height+36;} + strike(){const h=this.hero; + if(h.act==='slash'){const [a,b]=P.slashActive[h.combo];return h.timer>=a&&h.timer<=b?{id:h.slashId,dmg:SWORD[h.age][h.airSlash?'jump':'slash'],kind:h.airSlash?'jump':'slash'}:null;} + if(h.act==='jumpslash')return h.vy<0?{id:h.slashId,dmg:SWORD[h.age].jump,kind:'jump'}:null; + if(h.act==='spin')return h.timer<=P.spinFrames-2?{id:h.slashId,dmg:SWORD[h.age].spin,kind:'spin'}:null; + return null;} + targets(){return this.def().targets(this);} + lockTarget(){const h=this.hero;return h.lock===null?null:this.targets().find(q=>q.id===h.lock)||null;} + confine(e,rad){const A=this.arena;if(A.square){const m=A.square-rad;e.x=N.clamp(e.x,-m,m);e.z=N.clamp(e.z,-m,m);return;} + const d=Math.hypot(e.x,e.z),m=A.r-rad;if(d>m){e.x*=m/d;e.z*=m/d;}} + stickFrom(held){const f=(held.has('W')?1:0)-(held.has('S')?1:0),s=(held.has('A')?1:0)-(held.has('D')?1:0);return !f&&!s?null:wrap(this.cam.yaw+this.cam.offset+Math.atan2(s,f));} + updateLock(held,press){const h=this.hero;if(!held.has('Shift')){h.lock=null;return;} + const ts=this.targets(),here=ts.some(q=>q.id===h.lock);if(!press.has('Shift')&&here)return; + let best=null,bd=1e9;for(const q of ts){const d=Math.hypot(q.x-h.x,q.z-h.z);if(d0)return; + if(it.kind==='seed'||it.kind==='arrow'){const t=this.lockTarget(),sp=it.kind==='seed'?P.seedSpeed:P.arrowSpeed,y0=h.y+(h.age==='child'?30:44);let yaw=h.face,pitch=this.cam.pitchAim; + if(t){yaw=Math.atan2(t.x-h.x,t.z-h.z);pitch=Math.atan2(t.y-y0,Math.hypot(t.x-h.x,t.z-h.z));h.face=yaw;} + const x=h.x+Math.sin(yaw)*14,z=h.z+Math.cos(yaw)*14; + this.shots.push({kind:it.kind,x,y:y0,z,ox:x,oy:y0,oz:z,vx:Math.sin(yaw)*Math.cos(pitch)*sp,vy:Math.sin(pitch)*sp,vz:Math.cos(yaw)*Math.cos(pitch)*sp,life:18}); + h.itemCd=it.cd||P.itemCd;this.ev('item_fire');} + else if(def.useItem)def.useItem(this);} + updateHero(held,press){const h=this.hero,def=this.def(); + if(h.inv>0)h.inv--;else if(h.inv<0)h.inv++;if(h.itemCd>0)h.itemCd--;if(h.flash>0)h.flash--; + if(h.grabbed){h.lock=null;return;} + const yawS=this.stickFrom(held);this.updateLock(held,press);const T=this.lockTarget(),J=held.has('J')||held.has('LMB'),jp=press.has('J')||press.has('LMB'); + h.mode=T?1:0;h.shield=false; + if(h.act==='idle'){ + if(held.has('K')||held.has('RMB'))h.shield=true; + if(press.has('Space')){ + if(T){const dir=yawS===null?0:wrap(yawS-h.face),ab=Math.abs(dir); + if(ab>2.36){h.act='hop';h.timer=0;h.yaw=wrap(h.face+PI);h.speed=P.hopBack;h.vy=P.hopBackVy;this.ev('backhop');} + else if(ab>.79){h.act='hop';h.timer=0;h.yaw=wrap(h.face+(dir>0?PI/2:-PI/2));h.speed=P.hopSide;h.vy=P.hopSideVy;this.ev('sidehop');} + else{h.act='jumpslash';h.timer=0;h.yaw=h.face;h.speed=P.jumpFwd;h.vy=P.jumpVy;h.airSlash=true;h.slashId++;h.shield=false;this.ev('jumpslash');}} + else if(yawS!==null){h.act='roll';h.timer=0;h.face=yawS;h.yaw=yawS;h.shield=false;this.ev('roll');}} + if(h.act==='idle'&&jp&&!h.shield){h.act='slash';h.timer=0;h.combo=0;h.airSlash=false;h.slashId++;h.charge=0;this.ev('slash');} + if(h.act==='idle'&&press.has('L')&&!h.shield)this.fireItem(); + if(h.act==='idle'&&J&&!h.shield&&!jp)h.charge=Math.min(1,h.charge+P.chargeStep); + if(h.act==='idle'&&!J){if(h.charge>=P.chargeNeed){h.act='spin';h.timer=0;h.slashId++;h.speed=0;this.ev('spin');}h.charge=0;} + } + if(h.act==='idle'){ + if(h.shield){h.speed=stepF(h.speed,0,P.stop);if(T)h.face=stepYaw(h.face,Math.atan2(T.x-h.x,T.z-h.z),P.turn*2);} + else{const target=yawS===null?0:P.runCap*(h.charge>0?.5:1); + if(yawS!==null){if(T)h.yaw=yawS;else if(Math.abs(wrap(yawS-h.yaw))>2.6&&h.speed>2)h.speed=stepF(h.speed,0,P.stop);else h.yaw=stepYaw(h.yaw,yawS,P.turn*2);} + h.speed=stepAsym(h.speed,target,P.accel,P.decel); + if(T)h.face=stepYaw(h.face,Math.atan2(T.x-h.x,T.z-h.z),P.turn*2);else if(yawS!==null)h.face=h.yaw;} + }else if(h.act==='slash'){h.timer++;h.speed=stepF(h.speed,0,P.decel);if(T)h.face=stepYaw(h.face,Math.atan2(T.x-h.x,T.z-h.z),P.turn);h.yaw=h.face; + if(jp&&h.timer>=P.comboFrom&&h.combo<2){h.combo++;h.timer=0;h.airSlash=false;h.slashId++;this.ev('slash');} + else if(h.timer>=P.slashFrames[h.combo]){h.act='idle';h.combo=0;h.timer=0;h.airSlash=false;} + }else if(h.act==='spin'){h.timer++;h.face=wrap(h.face+PI*2/P.spinFrames);if(h.timer>=P.spinFrames){h.act='idle';h.timer=0;} + }else if(h.act==='roll'){h.timer++;if(h.timer===P.rollInvFrom&&h.inv>=0)h.inv=-P.rollInv; + h.speed=stepAsym(h.speed,yawS!==null?Math.max(P.rollMin,P.runCap*P.rollMul):P.rollMin,P.accel,P.decel); + if(h.timer>=P.rollFrames){h.act='idle';h.timer=0;} + }else if(h.act==='hop'||h.act==='jumpslash'){h.vy-=P.gravity;h.y+=h.vy*MOVE;h.timer++; + if(h.y<=0&&h.vy<0){h.y=0;h.vy=0; + if(h.act==='jumpslash'){h.act='slash';h.combo=0;h.timer=1;h.speed=0;}else{h.act='land';h.timer=3;h.speed=0;}} + }else if(h.act==='land'){if(--h.timer<=0){h.act='idle';h.timer=0;} + }else if(h.act==='kb'){h.vy-=P.gravity;h.y+=h.vy*MOVE;if(h.y<=0){h.y=0;h.vy=0;h.speed=stepF(h.speed,0,1);if(--h.timer<=0){h.act='idle';h.timer=0;h.speed=0;}} + }else if(h.act==='dead'){if(--h.timer<=0)this.outcome='loss';return; + }else if(def.heroAct)def.heroAct(this,held,press,yawS); + h.x+=Math.sin(h.yaw)*h.speed*MOVE;h.z+=Math.cos(h.yaw)*h.speed*MOVE;this.confine(h,P.radius); + } + updateShots(){const def=this.def();this.shots=this.shots.filter(s=>{s.ox=s.x;s.oy=s.y;s.oz=s.z;s.life--; + const steps=Math.ceil(Math.hypot(s.vx,s.vy,s.vz)*MOVE/15)||1; + for(let i=0;ithis.arena.ceil||Math.hypot(s.x,s.z)>this.arena.r+40)return false;} + return s.life>0;});} + updateCam(mouse,press){const c=this.cam,h=this.hero,f=this.def().focus(this);c.oyaw=c.yaw; + if(press.has('Q'))c.offset=wrap(c.offset+PI/4);if(press.has('E'))c.offset=wrap(c.offset-PI/4);if(press.has('R'))c.offset=0; + c.offset=wrap(c.offset-mouse[0]*.0035);c.pitchAim=N.clamp(c.pitchAim-mouse[1]*.003,-.4,1.2); + if(Math.hypot(f.x-h.x,f.z-h.z)>40)c.yaw=wrap(c.yaw+N.clamp(wrap(Math.atan2(f.x-h.x,f.z-h.z)-c.yaw),-.14,.14));} + logic(held,press,mouse){this.frame++;const h=this.hero,b=this.boss;h.ox=h.x;h.oy=h.y;h.oz=h.z;if(b.x!==undefined){b.ox=b.x;b.oy=b.y;b.oz=b.z;} + this.updateCam(mouse,press);this.updateHero(held,press);if(this.outcome)return; + this.updateShots();this.def().update(this); + this.fx=this.fx.filter(q=>{q.life--;q.x+=q.vx||0;q.y+=q.vy||0;q.z+=q.vz||0;return q.life>0;});} + update(held,pressed,mouse){const I=this.inp;for(const k of pressed)if(!I.press.includes(k))I.press.push(k);I.mouse[0]+=mouse[0];I.mouse[1]+=mouse[1]; + this.lastKeys=[...held].sort();this.sub=(this.sub+1)%K;if(this.sub!==0)return; + const press=new Set(I.press),ms=I.mouse;this.inp={press:[],mouse:[0,0]};this.logic(held,press,ms);} + health(){const h=this.hero,b=this.boss;return [Math.max(0,h.hp),h.maxHp,this.outcome==='win'?0:Math.max(0,Math.min(b.hp,b.maxHp)),b.maxHp];} + } + M.Game=Game; + /* Scripted reference controller: plans on deep copies with blinded futures (planMix above, measured by tests/leak_probe.js) and returns legal holds only. */ + function cloneGame(g,salt){const c=Object.assign(Object.create(Game.prototype),N.copy(g));c.events=[];c.blind=salt===undefined?(g.blind===undefined?0:g.blind):salt;return c;} + function simTick(h,keys){const prev=new Set(h.lastKeys);h.events=[];h.update(new Set(keys),new Set(keys.filter(k=>!prev.has(k))),[0,0,0]);N.quantize(h);h.t++;if(h.t>=M.hz*M.maxSeconds&&!h.outcome)h.outcome='timeout';} + const STICK=[['W'],['W','A'],['A'],['S','A'],['S'],['S','D'],['D'],['W','D']]; + function stickTo(h,yaw){const r=wrap(yaw-h.cam.yaw-h.cam.offset),i=((Math.round(r/(PI/4))%8)+8)%8;return STICK[i];} + M.ctl={cloneGame,simTick,stickTo,STICK}; + M.scripted=function(game){const h=cloneGame(game,0),holds=[]; + for(let j=0;j<6;j++){const keys=h.outcome?[]:M.plans[h.kind](h).slice(0,4);holds.push(keys);for(let n=0;n<2&&!h.outcome;n++)simTick(h,keys);} + return {holds,mouse:[0,0,0]};}; + M.oracle=M.scripted; +})(typeof window==='undefined'?globalThis:window); diff --git a/environments/games/web/games/zelda_oot_remake/index.html b/environments/games/web/games/zelda_oot_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..9c2180fdaed1b4fdc45c7e23303a546284549176 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/index.html @@ -0,0 +1,7 @@ +Ancient Sword Legend: Boss Trials
      +
      N64 · 1998 · Boss Trials

      Ancient Sword Legend: Boss Trials

      Third-person view, Z targeting, shield, and sword: each fight starts with one item. Mechanics were inferred from a public decompilation as read-only facts; characters, bosses, and arenas use original procedural art.

      Back to Game Lobby ↗
      +
      Are You Ready?ClickStart Challenge
      +

      The scripted demo reads internal state only to verify that each fight can be completed. Replays save actual inputs for deterministic full-battle and final-state verification.

      +
      +
      + diff --git a/environments/games/web/games/zelda_oot_remake/manifest.json b/environments/games/web/games/zelda_oot_remake/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..5d300aba3d321a4d4f57f2482cd0bd6fec866ea4 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/manifest.json @@ -0,0 +1,52 @@ +{ + "schema": "bossbench/game-manifest@1", + "engine": "independent", + "game": "zelda_oot_remake", + "module": "ZeldaOotGame", + "title": "Ancient Sword Legend: Boss Trials", + "dimension": "3d", + "native_hz": 60, + "max_seconds": 300, + "renderer": "webgl-zelda-oot", + "rules": "oot-arena@5", + "cases": [ + "zelda/armored_spider_queen", + "zelda/lava_lizard_king", + "zelda/specter_rider", + "zelda/burrowing_fire_dragon", + "zelda/water_core_amoeba", + "zelda/twin_flame_frost_witches" + ], + "scripts": [ + "_native/runtime.js", + "_boss3d/vendor/three.min.js", + "zelda_oot_remake/renderer3d.js", + "zelda_oot_remake/art/goma.js", + "zelda_oot_remake/art/dodongo.js", + "zelda_oot_remake/art/ganondrof.js", + "zelda_oot_remake/art/volvagia.js", + "zelda_oot_remake/art/morpha.js", + "zelda_oot_remake/art/twinrova.js", + "zelda_oot_remake/game.js", + "zelda_oot_remake/bosses/goma.js", + "zelda_oot_remake/bosses/dodongo.js", + "zelda_oot_remake/bosses/ganondrof.js", + "zelda_oot_remake/bosses/volvagia.js", + "zelda_oot_remake/bosses/morpha.js", + "zelda_oot_remake/bosses/twinrova.js", + "zelda_oot_remake/draw.js" + ], + "sim_scripts": [ + "_native/runtime.js", + "zelda_oot_remake/game.js", + "zelda_oot_remake/bosses/goma.js", + "zelda_oot_remake/bosses/dodongo.js", + "zelda_oot_remake/bosses/ganondrof.js", + "zelda_oot_remake/bosses/volvagia.js", + "zelda_oot_remake/bosses/morpha.js", + "zelda_oot_remake/bosses/twinrova.js" + ], + "play_page": "web/games/zelda_oot_remake/index.html", + "original_clock": "Original game logic runs at 20 Hz (decompilation src/code/game.c R_UPDATE_RATE = 3 on a 60 Hz VI); this port runs 60 Hz, three ticks per original frame, logic on every third tick", + "scripted_controller": "ZeldaOotGame.scripted(game) -> {holds:[6 key arrays], mouse:[0,0,0]} (plans on deep copies with blinded futures)" +} diff --git a/environments/games/web/games/zelda_oot_remake/renderer3d.js b/environments/games/web/games/zelda_oot_remake/renderer3d.js new file mode 100644 index 0000000000000000000000000000000000000000..90ae606bd9f24b3103bdb16c5e0343b075c0d5b4 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/renderer3d.js @@ -0,0 +1,169 @@ +/* WebGL view for the Ocarina of Time boss trials. Reads the simulation only and never writes to it. All geometry and textures are made here in code (ASSET_RIGHTS.md): + * an immediate-mode pool of primitives, so each boss's art file is a short list of parts per frame. */ +(function(root){ + 'use strict'; + const T=root.THREE,PI=Math.PI,byCanvas=new WeakMap(),R=root.ZeldaOot3D={art:{}}; + const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)); + function canvasTex(w,h,paint,rx=1,ry=1){const c=document.createElement('canvas');c.width=w;c.height=h;paint(c.getContext('2d'),w,h);const t=new T.CanvasTexture(c);t.colorSpace=T.SRGBColorSpace;t.wrapS=t.wrapT=T.RepeatWrapping;t.repeat.set(rx,ry);return t;} + function noise(q,w,h,n,seed,dark,light,size=3){let s=seed>>>0||1;const r=()=>{s=Math.imul(s^(s>>>15),0x2c1b3c6d)+0x9e37|0;return (s>>>0)/4294967296;};for(let i=0;i{e.preventDefault();this.ready=false;this.error='WebGL context lost';}); + this.world=new T.Scene();this.camera=new T.PerspectiveCamera(54,854/480,4,4200); + this.hemi=new T.HemisphereLight(0xcfe4ff,0x4a4034,1.7);this.world.add(this.hemi);this.sun=new T.DirectionalLight(0xfff0d8,2.2);this.sun.position.set(-300,700,260);this.world.add(this.sun); + this.glow=new T.PointLight(0xffffff,0,1200,1.6);this.world.add(this.glow); + this.geo={box:this.keep(new T.BoxGeometry(1,1,1)),ball:this.keep(new T.SphereGeometry(1,14,10)),hemi:this.keep(new T.SphereGeometry(1,14,6,0,PI*2,0,PI/2)),cyl:this.keep(new T.CylinderGeometry(1,1,1,12)),cone:this.keep(new T.ConeGeometry(1,1,10)), + disc:this.keep(new T.CircleGeometry(1,28)),ring:this.keep(new T.RingGeometry(.8,1,32)),ico:this.keep(new T.IcosahedronGeometry(1,0)),oct:this.keep(new T.OctahedronGeometry(1,0)),torus:this.keep(new T.TorusGeometry(1,.16,6,18)),blade:this.keep(new T.ConeGeometry(.5,1,4))}; + this.mats=new Map();this.pool=new Map();this.stack=[new T.Matrix4()];this.tmp=new T.Matrix4();this.e=new T.Euler(0,0,0,'YXZ');this.v=new T.Vector3();this.s=new T.Vector3();this.q=new T.Quaternion(); + this.blob=this.keep(new T.MeshBasicMaterial({map:this.keep(canvasTex(64,64,(q,w,h)=>{const g=q.createRadialGradient(32,32,2,32,32,31);g.addColorStop(0,'rgba(0,0,0,.6)');g.addColorStop(.7,'rgba(0,0,0,.36)');g.addColorStop(1,'rgba(0,0,0,0)');q.fillStyle=g;q.fillRect(0,0,w,h);})),transparent:true,depthWrite:false})); + // Soft additive glow for projectiles, flames, sparks and charge-ups: camera-facing sprites from one radial texture. + this.glowTex=this.keep(canvasTex(64,64,(q,w,h)=>{const g=q.createRadialGradient(32,32,0,32,32,32);g.addColorStop(0,'rgba(255,255,255,1)');g.addColorStop(.22,'rgba(255,255,255,.8)');g.addColorStop(.55,'rgba(255,255,255,.22)');g.addColorStop(1,'rgba(255,255,255,0)');q.fillStyle=g;q.fillRect(0,0,w,h);})); + this.glowTex.wrapS=this.glowTex.wrapT=T.ClampToEdgeWrapping;this.glowTex.repeat.set(1,1); + this.sprites={items:[],n:0};this.smats=new Map();this.sectors=new Map(); + this.geo.plane=this.keep(new T.PlaneGeometry(1,1));this.geo.thin=this.keep(new T.RingGeometry(.9,1,48));this.geo.capsule=this.keep(new T.CapsuleGeometry(.5,1,4,10)); + } + keep(r){this.resources.add(r);return r;} + // Lambert by colour; `emissive` for things that must read in a dark room; `flat` faceted by default; `add` = additive glow. Opacity is quantised so the cache stays small. + mat(color,o={}){const op=o.op===undefined?undefined:Math.round(clamp(o.op,0,1)*32)/32,key=color+'|'+(o.em||0)+'|'+op+'|'+(o.basic?1:0)+'|'+(o.smooth?1:0)+'|'+(o.ei||0)+'|'+(o.add?1:0);let m=this.mats.get(key);if(m)return m; + if(o.basic)m=new T.MeshBasicMaterial({color,transparent:op!==undefined||!!o.add,opacity:op??1,depthWrite:op===undefined&&!o.add,side:T.DoubleSide,blending:o.add?T.AdditiveBlending:T.NormalBlending,toneMapped:!o.add,fog:!o.add}); + else m=new T.MeshLambertMaterial({color,flatShading:!o.smooth,emissive:o.em||0,emissiveIntensity:o.ei??1,transparent:op!==undefined,opacity:op??1}); + this.keep(m);this.mats.set(key,m);return m;} + // A camera-facing glow in world coordinates (not under push/pop). + flare(x,y,z,s,color,op=1){const q=Math.round(clamp(op,0,1)*32)/32;if(q<=0||s<=0)return null;const key=color+'|'+q;let m=this.smats.get(key); + if(!m){m=this.keep(new T.SpriteMaterial({map:this.glowTex,color,transparent:true,opacity:q,blending:T.AdditiveBlending,depthWrite:false,toneMapped:false,fog:false}));this.smats.set(key,m);} + const P=this.sprites;let sp=P.items[P.n];if(!sp){sp=new T.Sprite(m);sp.frustumCulled=false;sp.renderOrder=6;P.items.push(sp);this.world.add(sp);}P.n++; + sp.material=m;sp.visible=true;sp.position.set(x,y,z);sp.scale.set(s,s,1);return sp;} + // A projectile: bright core, coloured halo, and a tail of fading glows back along its last move. + bolt(x,y,z,px,py,pz,r,core,halo,tail=4){this.flare(x,y,z,r*4.2,halo,.55);this.flare(x,y,z,r*2,core,.95); + for(let i=1;i<=tail;i++){const k=i/(tail+1),u=1-k;this.flare(x+(px-x)*k*1.6,y+(py-y)*k*1.6,z+(pz-z)*k*1.6,r*2.6*u,halo,.5*u);}} + // Hit feedback: a white-hot flash with short rays, strength k (1 on the hit frame, fading with the target's invulnerability counter). + hitBurst(x,y,z,k,col=0xfff0c0){if(k<=0)return;this.flare(x,y,z,90*k+20,col,.8*k);this.flare(x,y,z,40*k+10,0xffffff,k); + for(let i=0;i<6;i++){const a=i*PI/3+.3,e=i%2?.6:1,L=(30+50*(1-k))*e;this.beam(x+Math.sin(a)*10,y+Math.cos(a)*10,z,x+Math.sin(a)*L,y+Math.cos(a)*L*.8,z+Math.cos(a+1)*L*.4,3*k+1,col,.8*k,1);}} + // A segment of glow (beams, sword arcs): a thin additive cylinder plus glows along it. + beam(x0,y0,z0,x1,y1,z1,w,color,op=.8,n=4){const dx=x1-x0,dy=y1-y0,dz=z1-z0,L=Math.hypot(dx,dy,dz);if(L<1e-3)return; + this.part('cyl',this.mat(color,{basic:true,op,add:true}),(x0+x1)/2,(y0+y1)/2,(z0+z1)/2,w*.35,L,w*.35,Math.atan2(dx,dz),Math.atan2(Math.hypot(dx,dz),dy)); + for(let i=0;i<=n;i++){const k=i/n;this.flare(x0+dx*k,y0+dy*k,z0+dz*k,w*2.2,color,op*.5);}} + // Flat marks on the floor, over it (no depth write): ring / thin ring / disc / sector (half-angle b round yaw) / strip (from x,z along yaw, length a, width b). + decal(kind,x,z,a,b,color,op,yaw=0,y=1.4){const m=this.mat(color,{basic:true,op,add:true});let mesh; + if(kind==='ring'||kind==='thin'||kind==='disc')mesh=this.part(kind,m,x,y,z,a,a,a,0,-PI/2); + else if(kind==='sector'){const k=Math.max(1,Math.min(62,Math.round(b*20))),name='sec'+k;if(!this.geo[name])this.geo[name]=this.keep(new T.CircleGeometry(1,Math.max(6,k),-PI/2-k/20,k/10));mesh=this.part(name,m,x,y,z,a,a,a,yaw,-PI/2);} + else mesh=this.part('plane',m,x+Math.sin(yaw)*a/2,y,z+Math.cos(yaw)*a/2,b,a,1,yaw,-PI/2); + mesh.renderOrder=3;return mesh;} + push(x,y,z,yaw=0,pitch=0,roll=0,s=1){this.e.set(pitch,yaw,roll);this.q.setFromEuler(this.e);this.v.set(x,y,z);this.s.set(s,s,s);this.stack.push(new T.Matrix4().multiplyMatrices(this.stack[this.stack.length-1],this.tmp.compose(this.v,this.q,this.s)));} + pop(){this.stack.pop();} + // One part: geometry name, material, position, scale, rotation. + part(g,m,x,y,z,sx,sy=sx,sz=sx,yaw=0,pitch=0,roll=0){let list=this.pool.get(g);if(!list){list={items:[],n:0};this.pool.set(g,list);} + let mesh=list.items[list.n];if(!mesh){mesh=new T.Mesh(this.geo[g],m);mesh.matrixAutoUpdate=false;mesh.frustumCulled=false;list.items.push(mesh);this.world.add(mesh);} + list.n++;mesh.material=m;mesh.visible=true;this.e.set(pitch,yaw,roll);this.q.setFromEuler(this.e);this.v.set(x,y,z);this.s.set(sx,sy,sz);mesh.matrix.multiplyMatrices(this.stack[this.stack.length-1],this.tmp.compose(this.v,this.q,this.s));return mesh;} + shadow(x,y,z,r){const m=this.part('disc',this.blob,x,y+.6,z,r,r,r,0,-PI/2);m.renderOrder=2;} + buildRoom(kind,art){if(this.room){this.world.remove(this.room);this.room.traverse(o=>{if(o.geometry)o.geometry.dispose();if(o.material){if(o.material.map)o.material.map.dispose();o.material.dispose();}});this.room=null;} + this.room=new T.Group();this.world.add(this.room);this.kind=kind;art.room(this,this.room);} + // A round chamber (or square hall) with procedural floor and wall textures. + addChamber(group,o){const r=o.r,h=o.h,floor=new T.CircleGeometry(r+6,64),fm=new T.MeshLambertMaterial({map:o.floorTex}),fl=new T.Mesh(floor,fm);fl.rotation.x=-PI/2;group.add(fl); + const wall=new T.CylinderGeometry(r+6,r+6,h,64,1,true),wm=new T.MeshLambertMaterial({map:o.wallTex,side:T.BackSide}),wl=new T.Mesh(wall,wm);wl.position.y=h/2;group.add(wl); + if(o.ceilTex){const cm=new T.MeshLambertMaterial({map:o.ceilTex}),c=new T.Mesh(new T.CircleGeometry(r+6,64),cm);c.rotation.x=PI/2;c.position.y=h;group.add(c);}} + drawHero(g,f){const h=g.hero,x=h.ox+(h.x-h.ox)*f,y=h.oy+(h.y-h.oy)*f,z=h.oz+(h.z-h.oz)*f,child=h.age==='child',s=child?.72:1,t=g.t/60,act=h.act; + // Hurt feedback: a red-white flash for the source's 10 flash frames, then a soft blink through the rest of the invulnerability. + const white=h.flash>0&&(g.t>>1)%2===0,blink=!white&&h.inv>0&&h.flash===0&&(g.t>>2)%2===0,cl=c=>white?0xffd8d0:c; + const tunic=this.mat(cl(0xc48a3a)),tunic2=this.mat(cl(0xa8702c)),belt=this.mat(cl(0x5a3a1e)),gold=this.mat(cl(0xd8b048),{em:0x302000}),skin=this.mat(cl(0xf0c7a0)),hood=this.mat(cl(0x5e3f28)),scarf=this.mat(cl(0x2f6fb0)),boot=this.mat(cl(0x4a2e1a)); + const steel=this.mat(0xe6edf6,{em:0x405468}),hilt=this.mat(0x2a4a8a),shf=this.mat(cl(0x8a96a6)),shRim=this.mat(cl(0xc8ccd4)),shEm=this.mat(cl(0x2f6fb0)); + this.shadow(x,0,z,18*(1+y/200));if(blink)return; + const roll=act==='roll'?h.timer/16*PI*2:0,run=act==='idle'&&Math.abs(h.speed)>.5?Math.sin(t*16):0,bob=Math.abs(run)*2,lean=act==='idle'?Math.min(.25,Math.abs(h.speed)*.04):0,kb=act==='kb'?.5:0,dead=act==='dead'?Math.min(1,1-h.timer/30):0; + this.push(x,y,z,h.face,0,0,s);this.push(0,dead?6:30,0,0,roll+lean-kb,dead*1.4); + // Body (original design: ochre coat, blue scarf, brown hood): coat skirt, torso, belt with buckle, scarf tail flying with the run. + this.part('cone',tunic,0,-8+bob,0,12,22,10,0,0);this.part('cyl',tunic2,0,4+bob,0,9.5,16,7.5);this.part('box',belt,0,-2+bob,0,11,3,8.4);this.part('box',gold,0,-2+bob,4.4,3,2.6,.8); + this.part('ball',skin,0,20+bob,0,8.4,9,8.2);this.part('hemi',hood,0,21+bob,-.5,10.2,10,10.2);this.part('box',hood,0,17+bob,-7,12,9,4); + this.part('box',this.mat(0x1c1410),-3,20+bob,7.6,1.6,2.4,.8);this.part('box',this.mat(0x1c1410),3,20+bob,7.6,1.6,2.4,.8); + this.part('torus',scarf,0,12+bob,0,8.5,8.5,14,0,PI/2);this.part('box',scarf,0,8+bob,-9,5,14,1.6,0,.35+Math.abs(run)*.5+Math.abs(h.speed)*.05);this.part('box',scarf,3,4+bob,-12-Math.abs(run)*3,4,10,1.4,.3,.6+Math.abs(run)*.6); + // Legs stride with the run; a roll tucks them. + const st=act==='roll'?0:run*5;for(const sd of [-1,1]){this.part('box',this.mat(cl(0xe8e0c8)),sd*4,-21,sd*st,3.6,14,4);this.part('box',boot,sd*4,-29,sd*st+1,4.6,5,7);} + // Sword arm: windup and follow-through by combo stage, a raised blade while charging, overhead on a jump slash. + const sl=act==='slash'?Math.min(1,h.timer/([10,10,14][h.combo]||10)):0,dir=h.combo===1?-1:1; + let arm=act==='slash'?(sl<.25?-1.6*dir:-1.6*dir+(sl-.25)/.75*3.4*dir):act==='spin'?0:act==='jumpslash'?(h.vy>0?-1.5:1.2):h.charge>0?-1.2:-.3,pitch=act==='jumpslash'?(h.vy>0?-1.2:.3):act==='slash'&&h.combo===2?-.2-sl*.8:-.6; + this.push(-11,7+bob,1,arm,pitch,0);this.part('box',skin,0,-3,3,3.4,3.4,9);this.part('box',hilt,0,-3,9,7,2.2,2.4);this.part('ball',gold,0,-3,7,1.8); + if(h.weapon==='hammer'){this.part('cyl',belt,0,-3,26,2.4,36,2.4,0,PI/2);this.part('cyl',this.mat(0x6a6f78,{em:0x202428}),0,-3,46,11,24,11,0,0,PI/2);this.part('cyl',gold,0,-3,46,11.5,3,11.5,0,0,PI/2);} + else{const L=(child?48:62)*.82;this.part('blade',steel,0,-3,10+L/2,3.2,L,1.4,0,PI/2);} + this.pop(); + // Shield arm: held across the body, raised to the front while blocking. + const up=h.shield;this.push(up?1:12,up?6+bob:4+bob,up?12:1,up?0:.5,0,0);this.part('cyl',shf,0,0,0,up?13:10,2.2,up?15:12,0,PI/2);this.part('torus',shRim,0,0,1.2,up?13:10,up?13:10,6,0,0); + this.part('oct',shEm,0,1,1.8,3.4,5,1.2);this.pop(); + this.pop();this.pop(); + // Sword trail: an additive arc swept across the slash's active frames; the spin draws a full ring. + if(act==='slash'||act==='jumpslash'||act==='spin'){const reach=(child?48:62)*s,hy=y+26*s,col=0xcfeaff; + if(act==='spin')for(let i=0;i<14;i++){const a=h.face+i/14*PI*2,k=i/14;this.flare(x+Math.sin(a)*reach,hy,z+Math.cos(a)*reach,26*s*(.4+.6*k),col,.55*k);} + else{const n=7,from=act==='jumpslash'?-1.1:-1.1*dir,to=act==='jumpslash'?1.1:1.1*dir,k0=act==='slash'?Math.max(0,(sl-.15)/.85):1; + for(let i=0;ik0)break;const a=h.face+from+(to-from)*u,yy=act==='jumpslash'?hy+30-u*40:hy+(h.combo===2?20-u*20:0);this.flare(x+Math.sin(a)*reach*.85,yy,z+Math.cos(a)*reach*.85,24*s,col,.55*(.4+.6*u));}}} + // Charge glow at the blade and a ring on the floor once a spin is ready. + if(h.charge>0){const k=Math.min(1,h.charge/.85),hx2=x+Math.sin(h.face-.6)*30*s,hz2=z+Math.cos(h.face-.6)*30*s;this.flare(hx2,y+48*s,hz2,(10+18*k)*s,h.charge>=.85?0xbfe9ff:0x6a8fd0,.5+.4*k); + if(h.charge>=.85){const a=t*12;this.decal('thin',x,z,46+Math.sin(t*20)*3,0,0x9fe2ff,.75);this.part('ring',this.mat(0xbfe9ff,{basic:true,op:.5,add:true}),x,4,z,40,40,40,a,-PI/2);}} + if(white)this.flare(x,y+34*s,z,70*s,0xff6a5a,.45); + } + render(g,ctx){const start=performance.now(); + try{const kind=g.kind,art=R.art[kind];if(!art)throw Error('no art for '+kind);if(this.kind!==kind)this.buildRoom(kind,art); + for(const l of this.pool.values()){for(let i=0;i120)this.times.shift();this.ready=true;this.error=null; + }catch(e){this.ready=false;this.error=String(e);throw e;} + } + metrics(){const info=this.renderer.info,sorted=[...this.times].sort((a,b)=>a-b); + return {renderer:'webgl-zelda-oot',webglVersion:this.renderer.capabilities.isWebGL2?2:1,drawCalls:info.render.calls,triangles:info.render.triangles,geometries:info.memory.geometries,textures:info.memory.textures,canvasBytes:854*480*4, + renderSamples:sorted.length,cpuRenderMsP50:sorted.length?sorted[Math.floor((sorted.length-1)*.5)]:null,cpuRenderMsP95:sorted.length?sorted[Math.floor((sorted.length-1)*.95)]:null,shadows:'blob shadows, no shadow maps',postprocess:false};} + close(){if(this.closed)return;this.closed=true;this.ready=false;if(this.room)this.room.traverse(o=>{if(o.geometry)o.geometry.dispose();if(o.material){if(o.material.map)o.material.map.dispose();o.material.dispose();}});this.resources.forEach(r=>{if(r.map)r.map.dispose?.();r.dispose?.();});this.renderer.dispose();this.renderer.forceContextLoss();this.resources.clear();} + } + const P={reach:62}; + const wrapDiff=a=>Math.atan2(Math.sin(a),Math.cos(a)); + // Usable half-angles of the 54-degree 854 x 480 view, with a margin so a framed point stays clear of the edge. + // Vertical fit keeps clear of the HUD: the title and boss bar take the top ~72 px, the hint and key line the bottom ~45 px. + const HALF_V=27*PI/180,HALF_H=Math.atan(Math.tan(HALF_V)*854/480),FIT_TOP=Math.atan(Math.tan(HALF_V)*162/240),FIT_BOT=Math.atan(Math.tan(HALF_V)*190/240),FIT_H=HALF_H*.84; + // Composed third-person camera. The simulation owns the camera yaw (it maps the stick, game.js updateCam); the view stands behind the hero along it, + // a little over the right shoulder so the hero does not hide the boss, and solves pitch and distance so hero and focus (lock target, else boss) both fit. + // A pure function of the state: the same tick always gives the same view, whoever renders it. + Scene.prototype.focusOf=function(g,f,art){const F=this.focusOf0(g,f,art),w=art.threat?art.threat(g,f):null;if(!w)return F; + const mx=(F.x+w.x)/2,my=(F.y+w.y)/2,mz=(F.z+w.z)/2,dy=Math.abs(F.y-w.y)/2;return {x:mx,y:my,z:mz,r:Math.max(F.r,w.r||40)+dy,pts:[F,w]};}; + Scene.prototype.focusOf0=function(g,f,art){const L=g.lockTarget();if(L)return {x:L.x,y:L.y,z:L.z,r:typeof art.lockR==='function'?art.lockR(g,L):art.lockR||28}; + const p=art.focus?art.focus(g,f):g.def().focus(g),ip=(a,o)=>o===undefined?a:o+(a-o)*f; + return {x:ip(p.x,p.ox),y:ip(p.y||0,p.oy)+(art.focusUp??40),z:ip(p.z,p.oz),r:art.focusR||50};}; + Scene.prototype.frame=function(g,f,art,hx,hy,hz){const c=g.cam,A=g.arena,yaw=c.oyaw+wrapDiff(c.yaw-c.oyaw)*f+c.offset,fo=this.focusOf(g,f,art),base=c.dist*(art.distK||1),camY=art.camY||118,lb=art.lookBias||.38; + const sx=Math.sin(yaw),sz=Math.cos(yaw);let dist=base,px=0,py=0,pz=0,vx=sx,vz=sz,lo=0,hi=0,pref=0; + for(let it=0;it<4;it++){const sh=dist*(art.shoulder??.13);px=hx-sx*dist-sz*sh;pz=hz-sz*dist+sx*sh;py=hy+camY; + if(A.square){const m=A.square-14;px=clamp(px,-m,m);pz=clamp(pz,-m,m);}else{const d=Math.hypot(px,pz),m=A.r-16;if(d>m){px*=m/d;pz*=m/d;}} + py=clamp(py,12,A.ceil-14); + const lb2=fo.pts?Math.max(lb,.5):lb,lx=hx+(fo.x-hx)*lb2,lz=hz+(fo.z-hz)*lb2,dl=Math.hypot(lx-px,lz-pz)||1;vx=(lx-px)/dl;vz=(lz-pz)/dl; + const va=Math.atan2(vx,vz),angs=(fo.pts||[fo]).map(p=>wrapDiff(Math.atan2(p.x-px,p.z-pz)-va)),amin=Math.min(...angs),amax=Math.max(...angs); + let shift=0;if(amax-amin<=2*FIT_H){if(amax>FIT_H)shift=amax-FIT_H;else if(amin<-FIT_H)shift=amin+FIT_H;}else{const fa=angs[0];if(Math.abs(fa)>FIT_H)shift=fa-Math.sign(fa)*FIT_H;} + if(shift){const t=va+clamp(shift,-.6,.6);vx=Math.sin(t);vz=Math.cos(t);} + const el=(x,y,z)=>Math.atan2(y-py,Math.max(30,(x-px)*vx+(z-pz)*vz)); + const P2=fo.pts||[fo],ft=Math.max(...P2.map(p=>el(p.x,p.y+(p.r||fo.r),p.z))),fb=Math.min(...P2.map(p=>el(p.x,p.y-(p.r||fo.r)*.6,p.z))),ht=el(hx,hy+70,hz),hb=el(hx,hy-4,hz),top=Math.max(ht,ft),bot=Math.min(hb,fb); + // Pitch window that keeps the focus in view; the hero is fitted inside it when both fit, else the focus wins and the hero is kept as close as it allows. + lo=ft-FIT_TOP;hi=fb+FIT_BOT;pref=el(lx,hy+34+(fo.y-hy-34)*lb*.9,lz);const both=top-bot<=FIT_TOP+FIT_BOT;if(both){lo=top-FIT_TOP;hi=bot+FIT_BOT;}else pref=(ht+hb)/2; + if(both||dist>=base*1.6)break;dist=Math.min(base*1.6,dist*(top-bot)/(FIT_TOP+FIT_BOT));} + const th=clamp(pref,Math.min(lo,hi),Math.max(lo,hi));this.camera.position.set(px,py,pz);this.camera.lookAt(px+vx*Math.cos(th)*100,py+Math.sin(th)*100,pz+vz*Math.cos(th)*100);this.camera.updateMatrixWorld();}; + // Screen position of a world point for the HUD: on-screen flag, pixel position, depth, and a screen direction that stays meaningful behind the camera. + Scene.prototype.project=function(x,y,z){const v=new T.Vector3(x,y,z).applyMatrix4(this.camera.matrixWorldInverse),depth=-v.z,cx=v.x,cy=v.y; + if(depth>1){v.applyMatrix4(this.camera.projectionMatrix);const sx=(v.x+1)*427,sy=(1-v.y)*240;return {front:true,on:sx>=0&&sx<=854&&sy>=0&&sy<=480,x:sx,y:sy,depth,dx:sx-427,dy:sy-240};} + return {front:false,on:false,x:NaN,y:NaN,depth,dx:cx,dy:-cy+Math.abs(depth)*.5+1};}; + R.render=function(g,ctx){let s=byCanvas.get(ctx.canvas);if(!s||s.closed){s=new Scene(ctx.canvas);byCanvas.set(ctx.canvas,s);}s.render(g,ctx);return s;}; + R.status=function(ctx){const s=ctx&&byCanvas.get(ctx.canvas);if(s&&!s.closed&&s.renderer.getContext().isContextLost()){s.ready=false;s.error='WebGL context lost';} + return {renderer:'webgl-zelda-oot',kind:'perspective',ready:!!s?.ready&&!s.closed,error:s?.error||null};}; + R.metrics=function(ctx){const s=ctx&&byCanvas.get(ctx.canvas);return s?s.metrics():null;}; + R.project=function(ctx,x,y,z){const s=ctx&&byCanvas.get(ctx.canvas);return s&&!s.closed?s.project(x,y,z):null;}; + R.close=function(ctx){const s=ctx&&byCanvas.get(ctx.canvas);if(s){s.close();byCanvas.delete(ctx.canvas);}}; +})(window); diff --git a/environments/games/web/games/zelda_oot_remake/style3d.css b/environments/games/web/games/zelda_oot_remake/style3d.css new file mode 100644 index 0000000000000000000000000000000000000000..ec39215c7a394dd8d0d0758490acf67ca7ec50f9 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/style3d.css @@ -0,0 +1 @@ +:root{color-scheme:dark;--bg:#14191a;--panel:#1d2425;--edge:#354141;--text:#ebe7dc;--muted:#a5b2ad;--accent:#dfb676}*{box-sizing:border-box}body{margin:0;background:radial-gradient(ellipse at top,#29312b,transparent 60%),var(--bg);color:var(--text);font:14px/1.7 'Segoe UI','Microsoft YaHei',sans-serif}body[data-game=genshin_remake]{--bg:#101822;--panel:#1b2530;--edge:#374754;--accent:#baacff;background:radial-gradient(ellipse at top,#2b2942,transparent 60%),var(--bg)}body[data-game=mario64_remake]{--bg:#0f1530;--panel:#18214a;--edge:#34407a;--text:#f3f1ea;--muted:#aeb7dd;--accent:#ffd23a;background:radial-gradient(ellipse at top,#2b3a8a,transparent 62%),radial-gradient(ellipse at bottom right,#5a1616,transparent 55%),var(--bg)}body[data-game=mario64_remake] h1{font-family:"Segoe UI","Microsoft YaHei",sans-serif;font-weight:800;letter-spacing:.5px;text-shadow:0 3px 0 #b81d22,0 6px 14px #0008}body[data-game=mario64_remake] button.primary{background:#e52521;color:#fff}body[data-game=mario64_remake] .stage{border-color:#ffd23a55}main{max-width:1220px;margin:auto;padding:28px 24px 40px}header{display:flex;align-items:center;justify-content:space-between;margin-bottom:22px;gap:20px}.eyebrow{color:var(--accent);font-size:11px;letter-spacing:2.5px;text-transform:uppercase}h1{font:500 32px/1.35 Georgia,'Microsoft YaHei',serif;letter-spacing:1px;margin:6px 0}header p{color:var(--muted);margin:0;font-size:13px}a{color:var(--accent);text-decoration:none}a:hover{text-decoration:underline}.layout{display:grid;grid-template-columns:minmax(0,854px) 245px;gap:24px;align-items:start}.stage{position:relative;border:1px solid var(--edge);box-shadow:0 22px 55px #0005;background:#111b1c}canvas{display:block;width:100%;aspect-ratio:854/480;touch-action:none;outline:none}canvas:focus-visible{outline:2px solid var(--accent);outline-offset:3px}#overlay{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:#10171b30;pointer-events:none}#overlay[hidden]{display:none}#overlay div{background:#111b23de;padding:19px 32px;border:1px solid #9ba6a655;max-width:80%;text-align:center}#overlay strong{font:500 24px Georgia,'Microsoft YaHei',serif;display:block}#overlay span{display:block;color:var(--muted);font-size:12px;margin-top:7px}.toolbar{display:flex;gap:8px;flex-wrap:wrap;padding:12px;background:var(--panel);border-top:1px solid var(--edge)}button,select,input{font:inherit;background:var(--panel);color:var(--text);border:1px solid var(--edge);border-radius:4px;padding:7px 11px}button{cursor:pointer}button:hover{border-color:var(--accent);background:#ffffff09}button.primary{background:var(--accent);color:var(--bg);font-weight:600}button:focus-visible,select:focus-visible,input:focus-visible,a:focus-visible{outline:2px solid var(--accent);outline-offset:3px}aside{padding:19px;border:1px solid var(--edge);background:var(--panel)}h2{font-size:16px;margin:0 0 8px}label{display:block;font-size:12px;color:var(--muted);margin:12px 0 5px}select,input{width:100%}dl{border-top:1px solid var(--edge);padding-top:16px;margin:18px 0 0}dt{color:var(--accent);font:12px/1.8 Consolas,monospace}dd{color:var(--muted);font-size:12px;margin:0 0 10px}.note{color:var(--muted);font-size:12px}#status{min-height:25px;margin:10px 0;color:var(--accent);overflow-wrap:anywhere}.record-toolbar{border:1px solid var(--edge);padding:10px;background:transparent}.record-toolbar button{font-size:12px}#file{display:none}.mobile{display:none}footer{display:flex;flex-wrap:wrap;gap:22px;border-top:1px solid var(--edge);margin-top:28px;padding-top:15px;font-size:12px}@media(max-width:950px){main{padding:14px}.layout{grid-template-columns:1fr}aside{display:grid;grid-template-columns:1fr 1fr;gap:0 18px}aside dl,aside .note{grid-column:1/-1}dl{columns:2}.mobile{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}.mobile button{min-width:45px;touch-action:none}header{align-items:start}h1{font-size:26px}}@media(max-width:500px){header{display:block}header a{font-size:12px}aside{padding:14px}#overlay div{padding:14px 20px}#overlay strong{font-size:19px}.toolbar{gap:6px;padding:8px}button{font-size:12px}h1{font-size:25px}} diff --git a/environments/games/web/index.html b/environments/games/web/index.html new file mode 100644 index 0000000000000000000000000000000000000000..43c1a9cb7e99e813acaabde0820c346c9fffafbe --- /dev/null +++ b/environments/games/web/index.html @@ -0,0 +1 @@ +GameDojo Games

      GameDojo: 20 games / 120 scenes

      Serve this directory with python -m http.server 8765. Minecraft requires the Python play server; see README.

      \ No newline at end of file diff --git a/environments/games/web/tools/gym_server.js b/environments/games/web/tools/gym_server.js new file mode 100644 index 0000000000000000000000000000000000000000..3b46f4e8ed7a374fad6e5aca05d3dad246d0e4f2 --- /dev/null +++ b/environments/games/web/tools/gym_server.js @@ -0,0 +1,14 @@ +// Node transport for the Python gymnasium binding: one env per process, one JSON command per stdin line, +// one JSON reply per stdout line ({error} on failure). Symbolic only; pixels go through the browser transport. +// usage: node tools/gym_server.js [game = hollowknight_remake] (a name under web/games/ or a path to a game folder) +// One game per process (games share the BB global); prototype/bossbench/webenv.py starts one per game. +var path = require('path'), fs = require('fs'); +var arg = process.argv[2] || 'hollowknight_remake', dir = fs.existsSync(path.join(__dirname, '..', 'games', arg)) ? path.join(__dirname, '..', 'games', arg) : path.resolve(arg); +var BB = require('../engine/load.js')(dir); +require('../engine/bridge.js'); +var rl = require('readline').createInterface({ input: process.stdin, terminal: false }); +rl.on('line', function (line) { + var res; + try { res = BB.bridge(JSON.parse(line)); } catch (e) { res = { error: String(e && e.stack || e) }; } + process.stdout.write(JSON.stringify(res) + '\n'); +}); diff --git a/environments/requirements-games.txt b/environments/requirements-games.txt new file mode 100644 index 0000000000000000000000000000000000000000..4a257ce8773f18b1cf54034fc74d27cbbd494011 --- /dev/null +++ b/environments/requirements-games.txt @@ -0,0 +1,6 @@ +gymnasium==1.4.0 +numpy==2.5.4 +pillow==13.0.0 +playwright==1.65.0 +moderngl==5.13.0 +glcontext==3.1.0 diff --git a/environments/run_model.py b/environments/run_model.py new file mode 100644 index 0000000000000000000000000000000000000000..a2a93b607acab041f5ce816a54d2f4475c09ad45 --- /dev/null +++ b/environments/run_model.py @@ -0,0 +1,6 @@ +import json, sys +from pathlib import Path +sys.path.insert(0,str(Path(__file__).resolve().parent/'games/prototype')) +from bossbench_llm.run import main +defaults=['--policy','chat','--format','lumine','--lang','en','--base-url','http://127.0.0.1:8000/v1','--model','gamedojo-4b','--history','2','--image-size','854x480','--seeds','1','--policy-seed','1','--temperature','1','--top-p','1','--max-tokens','256','--extra-body',json.dumps({'skip_special_tokens':False,'chat_template_kwargs':{'enable_thinking':False}})] +sys.exit(main(defaults+sys.argv[1:]))