From 304c312caa0d23be968d5a508654db11aedbd615 Mon Sep 17 00:00:00 2001 From: user1303836 Date: Tue, 17 Nov 2026 01:08:30 -0500 Subject: [PATCH 1/2] fix(hands): keep the picture when the resolution scaler reaches its bottom tier - At the low tier the key light's shadow map was disposed and left null. three then binds a stand-in depth texture with no comparison function to the shadow sampler, which ANGLE refuses, so every lit mesh (ring, crowd, fighters) stopped drawing on a slow or busy client. - The shadow map is now swapped for a 16 pixel one drawn once, never left null; castShadow is still untouched, so no program is recompiled. --- src/intelstream/hands/static/assets/hands.js | 10 +++++----- web/hands/src/render/renderer-gpu.test.ts | 19 +++++++++++++++++-- web/hands/src/render/renderer.ts | 13 ++++++++++--- 3 files changed, 32 insertions(+), 10 deletions(-) diff --git a/src/intelstream/hands/static/assets/hands.js b/src/intelstream/hands/static/assets/hands.js index a373642a..561f0ba3 100644 --- a/src/intelstream/hands/static/assets/hands.js +++ b/src/intelstream/hands/static/assets/hands.js @@ -5355,7 +5355,7 @@ transformed += ropeOut * ropeFlex; transformed += inverse( mat3( modelMatrix ) ) * vec3( 0.0, ${0 .toFixed(4)} - pressedOntoCanvas.y, 0.0 ); } }`;function bF(e){let t=e.onBeforeCompile,n=Object.hasOwn(e,`customProgramCacheKey`)?e.customProgramCacheKey():`plain`;e.onBeforeCompile=(n,r)=>{t.call(e,n,r),n.vertexShader=n.vertexShader.replace(`#include `,`${yF}\n#include `)},e.customProgramCacheKey=()=>`${n}-on-canvas`,e.needsUpdate=!0}function xF(e,t){let n=t.outfit!==void 0,r=!n||t.wounds===!0,i=[],a=[],o=new Map,s=null,c={value:0},l=null,u=null;if(e.traverse(e=>{if(!(e instanceof Hv)||Array.isArray(e.material))return;let d=e.material.name,f=aF[d];if(f===void 0)throw Error(`fighter GLB has unsupported material ${d}`);let p=o.get(d);if(p===void 0){let e=d===`MHeadMat0`||d===`MBodyMat0`,m=t.outfit,h=d===`GlovesMat0`?t.gear:d===`PantsMat0`?m?.trousers??t.gear:d===`ShoesMat0`&&m!==void 0?m.shoes:16777215,g=vF(f);p=e&&!n?new jb({map:g,color:h,roughness:.58,metalness:.02,clearcoat:.25,clearcoatRoughness:.6}):new Ab({map:g,color:h,roughness:e?.58:.4,metalness:e?.02:.03}),p.name=d,o.set(d,p),a.push(p),e&&i.push(p),d===`MHeadMat0`&&(l=new nj(r?p:null,iA,{core:zA,lids:VA})),d===`MBodyMat0`&&(u=new nj(r?p:null,aA,{core:BA,wash:!0}));let _=SF[d];m!==void 0&&_!==void 0?Zj(p,_,m):d===`PantsMat0`?c=rA(p,!1,`trunks`):d===`GlovesMat0`&&(s=rA(p)),bF(p)}e.material=p,e.castShadow=!n,e.receiveShadow=!0,e.frustumCulled=!1}),i.length!==2||s===null||a.length!==5||l===null||u===null)throw Error(`fighter GLB material contract failed: ${i.length} skin, ${a.length} total`);return{skin:i,gloveBlood:s,trunksBlood:c,owned:a,headInjury:l,bodyInjury:u}}var SF={MHeadMat0:`head`,MBodyMat0:`body`,ShoesMat0:`shoes`,PantsMat0:`pants`},CF=new J().setRGB(.6,.32,.19,dh),wF=(e,t,n,r)=>e+(t-e)*(1-Math.exp(-n*r)),TF=(e,t,n,r)=>e+(((t-e+Math.PI)%(Math.PI*2)+Math.PI*2)%(Math.PI*2)-Math.PI)*(1-Math.exp(-n*r)),EF=G.clamp,DF=class{root=new t_;bones=new Map;rig;metrics;skinMaterials;ownedMaterials;gloveBlood;trunksBlood;headMeshes=[];handMeshes={left:[],right:[]};decapitated=!1;burst=!1;dismemberedHands={left:!1,right:!1};dressed;ownedGeometries=[];gearBaseColor;skinBaseColor;headInjury;bodyInjury;headLook;bareHand;constructor(e,t){let n=YO(e.scene);n.scale.setScalar(1),this.root.add(n);let r=xF(n,t);this.skinMaterials=r.skin,this.ownedMaterials=[...r.owned],this.gloveBlood=r.gloveBlood,this.trunksBlood=r.trunksBlood,this.headInjury=r.headInjury,this.bodyInjury=r.bodyInjury,this.gearBaseColor=new J(t.gear),this.skinBaseColor=new J(t.skin),this.dressed=t.outfit!==void 0,n.traverse(e=>{e instanceof Hv&&e.name===`BoxerHead`&&this.headMeshes.push(e),e instanceof Hv&&e.name===`BoxerGloveLeft`&&this.handMeshes.left.push(e),e instanceof Hv&&e.name===`BoxerGloveRight`&&this.handMeshes.right.push(e),e instanceof Uv&&this.bones.set(e.name,e)});let i=Object.values(Qk).filter(e=>!this.bones.has(e));if(i.length>0)throw Error(`fighter GLB missing required bones: ${i.join(`, `)}`);if(this.headMeshes.length!==1)throw Error(`fighter GLB requires one BoxerHead mesh, found ${this.headMeshes.length}`);let a=this.headInjury.shadowMaterial();this.headMeshes[0].customDepthMaterial=a;let o=this.headMeshes[0].material;o.side=0,o.shadowSide=1,this.ownedMaterials.push(a);for(let e of[`left`,`right`])if(this.handMeshes[e].length!==1)throw Error(`fighter GLB requires one ${e} glove mesh, found ${this.handMeshes[e].length}`);this.root.updateMatrixWorld(!0),this.rig=new SM(this.root),this.headLook=new Aj(this.headMeshes[0].material),this.bareHand=t.outfit===void 0?null:this.addHands(t.outfit),this.setLook(t.look??mj);let s=this.rig.metrics;this.metrics={armUpper:s.armL.upper,armFore:s.armL.lower,legThigh:s.legL.upper,legShin:s.legL.lower,headRestY:s.headHeight,chestRestY:s.chestHeight,ankleRestY:s.ankleHeight}}bone(e){return this.bones.get(Qk[e]??e)??null}setGloveBlood(e){this.gloveBlood.value=EF(e,0,1)}get gloveBloodLevel(){return this.gloveBlood.value}setTrunksBlood(e){this.trunksBlood.value=EF(e,0,1)}get trunksBloodLevel(){return this.trunksBlood.value}get headMesh(){return this.headMeshes[0]}gloveMesh(e){return this.handMeshes[e][0]}get skin(){return this.skinMaterials[0]}get isDecapitated(){return this.decapitated}setDecapitated(e){this.decapitated=e,this.burst=!1,this.headInjury.setSevered(e),this.bone(`head`).visible=!e}get isHeadBurst(){return this.burst}setHeadBurst(e){this.burst=e,this.decapitated=!1,this.headInjury.setBurst(e),this.bone(`head`).visible=!e}isHandDismembered(e){return this.dismemberedHands[e]}setHandDismembered(e,t){this.dismemberedHands[e]=t;for(let n of this.handMeshes[e])n.visible=!t&&!this.dressed}setLook(e){this.headLook.set(e);for(let t of this.skinMaterials)t.color.setHex(e.tint);this.bareHand?.color.copy(CF).multiply(this.skinMaterials[0].color)}get look(){return this.headLook.look}addHands(e){let t=e.gloves!==null,n=new Ab({color:t?e.gloves:CF,roughness:t?.38:.6,metalness:.02}),r=t?n:new Ab({color:new J(e.shirt).multiplyScalar(.9),roughness:.88,metalness:0});this.ownedMaterials.push(n),r!==n&&this.ownedMaterials.push(r);let i=tM();this.ownedGeometries.push(i);for(let e of[`left`,`right`]){for(let t of this.handMeshes[e])t.visible=!1;let t=eM(e);this.ownedGeometries.push(t);let a=e===`left`?`L`:`R`;for(let[o,s,c,l]of[[this.rig.bones[`glove${a}`],t,n,`hand-${e}`],[this.rig.bones[`elbow${a}`],i,r,`cuff-${e}`]]){let e=new Y(s,c);e.name=l,e.castShadow=!1,e.receiveShadow=!0,o.add(e)}}return t?null:n}setSkinClearcoat(e){for(let t of this.skinMaterials)t instanceof jb&&(t.clearcoat=e)}dispose(){for(let e of this.ownedMaterials)e.dispose();for(let e of this.ownedGeometries)e.dispose();_F(this.root)}},OF=(e,t,n,r,i)=>{let a=e.value,o=e.velocity;o.addScaledVector(a,-n*t).multiplyScalar(Math.exp(-r*t)),a.addScaledVector(o,t),a.length()>i&&a.setLength(i)},kF=.06,AF=150,jF=.58,MF=.25,NF=.32,PF=9,FF=1,IF=.08,LF=.3,RF=1,zF=1.6,BF=.25,VF=.12,HF=.3,UF=.3,WF=8;function GF(e,t,n,r){QP(e,t,n);let i=Math.hypot(n.x,n.z);if(i<=0)return r.x=0,r.z=0,0;let a=EM(0,BF,i),o=1+VF*a/i;return r.x=n.x*o,r.z=n.z*o,a}var KF=(e,t)=>e===0||Math.sign(t)===Math.sign(e)&&Math.abs(t)>Math.abs(e)?t:e,qF=.75,JF=.38,YF=.72,XF=.5,ZF=.2,QF=.55,$F=.7,eI=6,tI=.4,nI=.2,rI=.3,iI=.5,aI=class{mapping;boxer;solver;yaw=0;yawInitialized=!1;rootX=null;rootZ=0;punchActive=!1;punchAgeTicks=0;punchTotalTicks=1;punchClass=`jab`;punchHand=`left`;punchTarget=`head`;punchPower=`normal`;punchTiming=oe(`jab`,`head`,`normal`);actionId=null;completedActionId=null;ownActionId=null;ownPress=!1;ownLeadTicks=0;ownAuthoritativeAge=null;ownWaitedTicks=0;ownExpectedTicks=0;ownPulled=!1;ownSequence=null;ownStarted=!1;ownPressedAt=0;ownRefused=!1;ownCut=!1;recoveryCut=!1;ownQueued=null;contactId=null;contactParried=!1;shownFighter=null;shownOpponent=null;retiredOwnIds=[];pressesLanded=[];anticipatedId=null;hitstop=0;hitstopScale=1;hitstopLag=0;downState=`up`;fallAge=0;riseProgress=0;riseFrom=0;fallSide=0;fallProne=!1;fallKneel=!1;windedSide=-1;windedTime=0;winded=0;landProne=!1;landSide=0;landShift=new q;landSettled=!1;fallen=SL();fallenFromPhysics=!1;riseRoot=new q;riseRootFrom=new q;downPoles=[new q,new q,new q,new q];downPolesSet=!1;poleSettle=0;characterInverse=new Dg;place=new q;riseRootVelocity=new q;liveOpponentHead=new q;hasLiveHead=!1;guardOpponentHead=new q;opponentHeadOffset=new q;opponentSteadySeconds=0;followHead=0;aimActionId=null;refereeContactId=null;refereeHead=new q;hasRefereeHead=!1;followReferee=0;headKick={value:new q,velocity:new q};torsoKick={value:new q,velocity:new q};rootKick={value:new q,velocity:new q};coverKick={value:new q,velocity:new q};foldDelay=0;pendingFold=0;guardKick=0;guardHigh=0;guardLow=0;guardSpent=0;slip=0;weave=0;weaveTime=0;pull=0;crouchExtra=0;bouncePhase=0;weightPhase=0;stunPhase=0;feintTimer=2;feint=0;stunAmount=0;tired=0;clinchWeight=0;foulWeight=0;tauntWeight=0;crowding=0;punchCommit=0;headSpace=new K;ownHead=new q;ropeHold=new q;ropeExcess={x:0,z:0};ropeOwn={x:0,z:0};ropeTheirs={x:0,z:0};ropeLeanTarget=0;ropeLean=0;ropeOutward=new q(1,0,0);ropeLocal=new q;tauntEnd=null;lastSpeed=0;stool;stoolRoot=new q;stoolYaw=0;enswell;bottle;treatProp=`enswell`;treatTarget=new q;treatScratch=new q;treatFacing=new q(0,0,-1);treatFacingLocal=new q;treatSide=1;treating=!1;treatWeight=0;resting=!1;seated=0;stillTime=0;celebrateTime=0;celebration=0;waveTime=0;wave=0;breakTime=0;breakWeight=0;breakFighters=[new q,new q];breakAimed=!1;attending=!1;verdictSide=0;verdict=null;squareWeight=0;raisedWeight=0;bowedWeight=0;wrists=[null,null];wristTargets=[new q,new q];wristWeights=[0,0];attendWeight=0;countdownTicks=null;countdownEnd=null;touchWeight=0;touchOffset=new q;touchVelocity=new q;debugHoldImpact=!1;feet=[{planted:new q,from:new q,to:new q,progress:1,stepping:!1,duration:.2},{planted:new q,from:new q,to:new q,progress:1,stepping:!1,duration:.2}];feetInitialized=!1;dislocation=null;scratch=new q;scratchB=new q;scratchC=new q;scratchD=new q;scratchE=new q;clinchCentre=new q;clinchForward=new q;clinchTemp=new q;scratchQ=new rg;headWorld=new q;hand={L:this.makeHand(),R:this.makeHand()};punchGuard=this.makeHand();punchDir=new q;punchContact=new q;punchStart=new q;punchSweepFrom=new q;punchSweepTo=new q;punchMid=new q;foot={L:this.makeFoot(),R:this.makeFoot()};torso={hips:new q,hipsYaw:0,hipsPitch:0,hipsRoll:0,shouldersYaw:0,spinePitch:0,spineRoll:0,headYaw:0,headPitch:0,headRoll:0,headOffset:new q};pose;downStanding=SL();downFrom=SL();downTo=SL();downResult=SL();downStand=1;fallStart=SL();fallStartStand=1;fallFromGetUp=!1;referee;refereeCount=0;refereeCounting=!1;countChangedTick=null;ragdoll;forcedDown=!1;heldDown=!1;authoredNextFall=!1;obstacle=null;blows=0;riseBlendAge=0;posedInjuries=0;armCarry=[`whole`,`whole`];armLimp=[0,0];armSnap=[0,0];armDangle=[wI(),wI()];forearmDangle=[wI(),wI()];trunkLow=new q;trunkHigh=new q;lostLean=0;cover=0;kneeBlown=[!1,!1];kneeGive=[0,0];gutted=!1;hunch=0;liver=!1;curl=0;faintTarget=0;faint=0;retchTime=0;retching=0;dazed=!1;daze=0;dazeTime=0;stepPace=[1,1];stepLift=[1,1];stepSlack=1;hurt=!1;punchReach=0;dead=!1;deathFall=!1;deathStyle=`crumple`;deathAge=0;throe=DI.length;throeSide=0;laidOut=!1;constructor(e,t,n={}){this.mapping=t,this.boxer=e,this.referee=n.referee===!0,this.solver=new BM(e.rig),this.pose={torso:this.torso,handL:this.hand.L,handR:this.hand.R,footL:this.foot.L,footR:this.foot.R,shrugL:0,shrugR:0},this.stool=YL(),this.stool.group.position.set(0,0,.02),e.root.add(this.stool.group),this.enswell=qL(),e.rig.bones.gloveL.add(this.enswell.group),this.bottle=JL(),e.rig.bones.gloveL.add(this.bottle.group),this.ragdoll=this.referee&&n.knockout!==!0?null:new IP(e.rig,e.root)}primeReplayFall(){this.ragdoll?.prime()}useAuthoredFall(){this.authoredNextFall=!0}knockOut(){this.forcedDown=!0}stayDown(e){this.heldDown=e}setObstacle(e,t){this.obstacle??={x:e,z:t},this.obstacle.x=e,this.obstacle.z=t}get fallBody(){return this.ragdoll?.active===!0?this.ragdoll:null}setResting(e){this.resting=e}get stoolVisible(){return this.stool.group.visible}celebrate(e=4.4){this.celebrateTime=e}resetTransient(e=!1){this.forcedDown=!1;let t=this.ragdoll;t!==null&&(e?t.active?t.settle():t.restoreSettled():(t.stop(),t.clearRise())),this.downState=e?`down`:`up`,this.landSettled=!1,this.fallenFromPhysics=!1,this.riseRoot.set(0,0,0),this.riseRootFrom.set(0,0,0),this.riseRootVelocity.set(0,0,0),this.fallAge=e?qF:0,this.riseProgress=0,this.hitstop=0,this.hitstopScale=1,this.hitstopLag=0;for(let e of[this.headKick,this.torsoKick,this.rootKick,this.coverKick])e.value.set(0,0,0),e.velocity.set(0,0,0);this.foldDelay=0,this.pendingFold=0,this.guardKick=0,this.stunAmount=0,this.windedTime=0,this.winded=0,this.celebrateTime=0,this.celebration=0,this.waveTime=0,this.wave=0,this.verdictSide=0,this.verdict=null,this.squareWeight=0,this.raisedWeight=0,this.bowedWeight=0,this.wrists.fill(null),this.wristWeights.fill(0),this.seated=0,this.stillTime=0,this.rootX=null,this.yawInitialized=!1,this.feetInitialized=!1,this.retirePunch(),this.ownQueued=null,this.completedActionId=null,this.retiredOwnIds.length=0,this.anticipatedId=null,this.retchTime=0,this.retching=0,this.dazed=!1,this.daze=0,this.dazeTime=0;for(let e=0;e<2;e+=1)EI(this.armDangle[e]),EI(this.forearmDangle[e]);this.dead=!1,this.deathFall=!1,this.throe=DI.length,this.laidOut=e}waveOff(e=2.6){this.waveTime=e}setCountdown(e){this.countdownTicks=e}attend(e){this.attending=e}treat(e,t,n=1,r=`enswell`){this.treating=e!==null,e!==null&&(this.treatTarget.copy(e),t!==void 0&&this.treatFacing.copy(t),this.treatSide=n,this.treatProp=r)}awaitVerdict(e){this.verdictSide=e??0,e===null&&(this.verdict=null)}announce(e){this.verdict=e}raise(e,t){this.wrists[0]=e===null?null:this.wristTargets[0].copy(e),this.wrists[1]=t===null?null:this.wristTargets[1].copy(t)}breakClinch(e=1.3){this.breakTime=e}get breaking(){return this.breakTime>0}aimBreak(e,t){this.breakFighters[0].copy(e),this.breakFighters[1].copy(t),this.breakAimed=!0}makeHand(){return{position:new q,knuckles:new q(0,1,0),palm:new q(0,0,1),pole:new q(0,-1,0)}}makeFoot(){return{position:new q,toe:new q(0,0,1),heel:0,pole:new q(0,0,1)}}get currentRoot(){return{x:this.rootX??0,z:this.rootZ}}get isDown(){return this.downState!==`up`||this.dead}setRefereeCount(e,t){(e!==this.refereeCounting||t!==this.refereeCount)&&(this.countChangedTick=null),this.refereeCounting=e,this.refereeCount=t}predict(e,t,n,r=0,i,a=r){if(e.kind!==`punch`||e.id===void 0)return;let o={action:{...e,id:e.id},timing:i??oe(e.class,e.target,e.power),leadTicks:r,answerTicks:a,pressedAt:t,sequence:null,started:!1,waited:0};if(this.punchActive&&this.ownActionId!==null&&this.ownAuthoritativeAge===null&&!this.ownPulled&&!this.ownStarted&&(t-this.ownPressedAt)*n0||e.clinch_ticks>0||e.clinch_startup_ticks>0,a=this.ownQueued;if(a!==null&&(a.sequence??=r?.(a.action.id)??null,e.action_id===a.action.id?a.started=!0:!a.started&&(i||a.sequence!==null&&e.last_input_sequence>=a.sequence&&e.queued_actions===0)&&(this.ownQueued=null)),!this.punchActive||this.ownActionId===null||this.ownPulled||this.ownRefused)return;this.ownStarted||(this.ownSequence??=r?.(this.ownActionId)??null);let o=e.action_id===this.ownActionId;o&&(this.ownStarted=!0);let s=this.ownQueued;s!==null&&s.sequence!==null&&r!==null&&!this.ownStarted&&this.ownSequence===null&&this.ownAuthoritativeAge===null?(this.ownActionId=null,this.ownQueued=null,this.retirePunch(),this.startOwnPunch(s)):(o?i&&e.action_contact_tick===null:!this.ownStarted&&this.ownAuthoritativeAge===null&&(i||this.ownSequence!==null&&e.last_input_sequence>=this.ownSequence&&e.queued_actions===0))&&(this.ownRefused=!0,this.takeBack())}takeBack(){this.punchAgeTickse.action_startup_ticks*(1/sR-1)||this.punchActive&&this.punchAgeTicks/this.punchTotalTicks<=.55)return;this.anticipatedId=n;let r=e.action_target??`head`,i=e.action_power??`normal`,a={...oe(e.action,r,i),startup:e.action_startup_ticks,active:e.action_active_ticks,recovery:e.action_recovery_ticks},o=e.action_hand??(e.stance===`orthodox`?`left`:`right`);this.startEarly(n,e.action,o,r,i,a,t,t)}startOwnPunch(e){let{action:t,timing:n}=e;this.startEarly(t.id,t.class,t.hand,t.target,t.power,n,0,Math.max(0,e.answerTicks)),this.ownPress=!0,this.ownSequence=e.sequence,this.ownStarted=e.started,this.ownPressedAt=e.pressedAt}startEarly(e,t,n,r,i,a,o,s){this.retirePunch(),this.punchClass=t,this.punchHand=n,this.punchTarget=r,this.punchPower=i,this.punchTiming=a,this.punchTotalTicks=Math.max(1,de(a)),this.punchAgeTicks=0,this.punchActive=!0,this.ownActionId=e,this.ownLeadTicks=EF(o,0,ZL),this.ownExpectedTicks=s}followUpStartAge(e){let t=this.shownFighter,n=this.shownOpponent,r=this.actionId??this.ownActionId,i=r!==null&&r===this.contactId&&!this.contactParried;return t!==null&&n!==null&&D(this.punchClass,i,e.action,t.stamina,n.stunned_ticks>0,t.style)?E(this.punchTiming):this.punchTotalTicks}releaseQueuedPress(e){let t=this.ownQueued;t!==null&&(t.waited+=e*30,this.punchActive&&!this.ownPulled&&this.punchAgeTicks+this.serverLag(t.leadTicks)6&&this.retiredOwnIds.shift()),this.actionId=null,this.punchActive=!1,this.ownActionId=null,this.ownPress=!1,this.ownLeadTicks=0,this.ownAuthoritativeAge=null,this.ownWaitedTicks=0,this.ownExpectedTicks=0,this.ownPulled=!1,this.ownSequence=null,this.ownStarted=!1,this.ownRefused=!1,this.ownCut=!1,this.recoveryCut=!1,this.hitstopLag=0}setRefereeHead(e){this.hasRefereeHead=e!==null,e!==null&&this.refereeHead.copy(e)}landedHit(e,t,n=!1){this.punchActive&&e!==null&&e===(this.actionId??this.ownActionId)&&(this.punchAgeTicks>=this.punchTiming.startup+this.punchTiming.active+1||(this.hitstop=Math.max(this.hitstop,(t?o.block:n?o.power:o.hit)/1e3)))}powerHeat(e){if(!this.punchActive||this.punchPower!==`power`||this.punchHand!==e||this.ownPulled)return 0;let{startup:t,active:n,recovery:r}=this.punchTiming,i=this.punchAgeTicks;return i=0?-1:1;if(t===`body`){switch(r){case`hook`:this.torsoKick.velocity.x+=3*s,this.torsoKick.velocity.z+=4.6*s*c,this.rootKick.velocity.x+=.5*s*c,this.coverKick.velocity.x+=2.2*s*c;break;case`uppercut`:this.rootKick.velocity.y+=.9*s,this.torsoKick.velocity.x-=1.6*s,this.foldDelay=.1,this.pendingFold=5.2*s;break;default:this.torsoKick.velocity.x+=4.6*s}this.rootKick.velocity.z-=.45*s,this.headKick.velocity.z-=.6*s,this.headKick.velocity.y-=.7*s,this.guardKick=Math.max(this.guardKick,.6*s)}else{switch(e===`hit`&&(this.guardKick=Math.max(this.guardKick,.4*s)),r){case`hook`:this.headKick.velocity.x+=2.6*s*c,this.headKick.velocity.z-=.7*s,this.torsoKick.velocity.z+=.9*s*c;break;case`uppercut`:this.headKick.velocity.y+=2.2*s,this.headKick.velocity.z-=1.2*s,this.torsoKick.velocity.x-=1.2*s;break;case`straight`:this.headKick.velocity.z-=2.4*s,this.torsoKick.velocity.x-=.6*s;break;default:this.headKick.velocity.z-=1.5*s,this.torsoKick.velocity.x-=.35*s}this.rootKick.velocity.z-=.45*s,e===`block`&&(this.guardKick=Math.max(this.guardKick,.9*s))}if(e===`hit`&&(this.dentSurface(t,c,r,o),this.fallSide=r===`hook`?c:c*.5,this.fallProne=r===`hook`||t===`body`),e===`hit`&&a>=10&&this.ragdoll!==null){let e=FP({target:t,punchClass:r,hand:i,lateral:c,amount:a}),n=this.scratchE.set(e.x,e.y,e.z).applyAxisAngle(XL,this.yaw),o=this.scratchD.set(e.driveX,e.driveY,e.driveZ).applyAxisAngle(XL,this.yaw);this.blows+=1,this.ragdoll.takeBlow(n,o,t,e.twist,gP(r,t,a,this.blows+Math.round(a)))}}stagger(){this.torsoKick.velocity.x-=2.6,this.headKick.velocity.z-=1.4,this.headKick.velocity.y+=.5,this.rootKick.velocity.z-=1.1,this.guardKick=Math.max(this.guardKick,1.1)}windedFor(e,t){this.windedTime=Math.max(this.windedTime,e),this.windedSide=t>=0?1:-1}fallToKnee(e){this.dead||(this.fallKneel=e,e&&(this.authoredNextFall=!0))}dentSurface(e,t,n,r){let i=1.1+r*2.1;if(e===`body`){let e=n===`hook`?t>0?`rightRibs`:`leftRibs`:`solarPlexus`;this.boxer.bodyInjury.impact(e,[n===`hook`?t*i*.8:0,0,-i],9)}else n===`hook`?this.boxer.headInjury.impact(t>0?`rightCheek`:`leftCheek`,[t*i,0,-i*.35],5.5):n===`uppercut`?this.boxer.headInjury.impact(`chin`,[0,i*.7,-i*.6],5):this.boxer.headInjury.impact(n===`jab`?`nose`:`mouth`,[0,0,-i],4.5)}stepFeet(e,t,n,r,i,a){let o=this.scratch,s=this.scratchQ.setFromAxisAngle(XL,a);for(let c=0;c<2;c+=1){let l=this.feet[c],u=c===0==t>0?VM.leadFoot:VM.rearFoot;if(this.referee||this.squareWeight>.5?o.set(c===0?.16:-.16,0,c===0?.02:-.02).applyQuaternion(s).add(i):o.set(u.x*t,0,u.z).applyQuaternion(s).add(i),o.y=0,this.daze>.001&&this.stumble(c,o,a),!this.feetInitialized){l.planted.copy(o),l.progress=1,l.stepping=!1;continue}if(l.stepping){l.progress=Math.min(1,l.progress+e/l.duration),l.progress>=1&&(l.stepping=!1,l.planted.copy(l.to));continue}let d=this.feet[1-c];l.planted.distanceTo(o)>(n>.05?.09:.14)*this.stepSlack&&!d.stepping&&(l.stepping=!0,l.progress=0,l.duration=EF(.24-n*.07,.15,.24)*this.stepPace[c],l.from.copy(l.planted),l.to.copy(o).addScaledVector(r,l.duration*.6),l.to.y=0)}this.feetInitialized=!0}footWorld(e,t){let n=this.feet[e];if(!n.stepping)return t.copy(n.planted),0;let r=OM(n.progress,1.6);return t.copy(n.from).lerp(n.to,r),Math.sin(n.progress*Math.PI)*.055*this.stepLift[e]}update(e,t,n,r,i,a,o,s){let c=this.boxer,l=e.stance===`orthodox`?1:-1,u=i?.35:1,d=this.touchWalk(e,t,n,o);this.walkBackFromTheFall(n);let f=this.holdOnTheRopes(t,this.mapping.x(e.x)+d.x+this.riseRoot.x,this.mapping.z(e.y)+d.z+this.riseRoot.z),p=this.mapping.x(e.x)+d.x+this.riseRoot.x-f.x,h=this.mapping.z(e.y)+d.z+this.riseRoot.z-f.z;this.place.set(p,0,h),this.rootX===null&&(this.rootX=p,this.rootZ=h);let g=_R*Math.max(n,1/60);this.rootX+=EF(p-this.rootX,-g,g),this.rootZ+=EF(h-this.rootZ,-g,g);let _=Math.atan2(e.facing_x,-e.facing_y);this.yawInitialized||=(this.yaw=_,!0);let v=this.punchActive&&this.punchAgeTicks0?.12:1;let y=n*this.hitstopScale;this.punchActive&&this.hitstop>0&&(this.hitstopLag+=(n-y)*30),this.syncAction(e,t,o,y),this.debugHoldImpact||(this.boxer.headInjury.update(y),this.boxer.bodyInjury.update(y)),s!==void 0&&this.trackOpponentHead(t,s,n);let b=this.scratchB.set(this.mapping.x(e.velocity_x)*30,0,this.mapping.z(e.velocity_y)*30).add(this.touchVelocity).add(this.riseRootVelocity),x=b.length(),S=Math.hypot(b.x-this.riseRootVelocity.x,b.z-this.riseRootVelocity.z);this.lastSpeed=x,this.stillTime=x<.03?this.stillTime+n:0;let C=this.resting&&this.stillTime>.2&&this.downState===`up`;this.seated=wF(this.seated,+!!C,C?2.2:4,n);let w=this.resting&&this.stillTime>.05&&this.downState===`up`;w&&(this.stoolRoot.set(this.rootX,0,this.rootZ),this.stoolYaw=this.yaw),this.stool.group.visible=w||this.seated>sI&&this.downState===`up`,this.stool.group.position.set(this.stoolRoot.x-this.rootX,0,this.stoolRoot.z-this.rootZ).add(this.scratch.set(0,0,.02).applyAxisAngle(XL,this.stoolYaw)).applyAxisAngle(XL,-this.yaw),this.stool.group.rotation.y=this.stoolYaw-this.yaw,this.celebrateTime=Math.max(0,this.celebrateTime-n),this.celebration=wF(this.celebration,+(this.celebrateTime>0&&this.downState===`up`),3.5,n),this.waveTime=Math.max(0,this.waveTime-n),this.wave=wF(this.wave,+(this.waveTime>0&&this.downState===`up`),4,n),this.breakTime=Math.max(0,this.breakTime-n),this.breakWeight=wF(this.breakWeight,+(this.breakTime>0&&this.downState===`up`),6,n),this.attendWeight=wF(this.attendWeight,+!!this.attending,2.5,n),this.squareWeight=wF(this.squareWeight,this.verdictSide===0?0:1,3,n),this.raisedWeight=wF(this.raisedWeight,+(this.verdictSide!==0&&(this.verdict===`winner`||this.verdict===`level`)),3.2,n),this.bowedWeight=wF(this.bowedWeight,+(this.verdictSide!==0&&this.verdict===`loser`),2.2,n);for(let e of[0,1])this.wristWeights[e]=wF(this.wristWeights[e],this.wrists[e]===null?0:1,3.2,n);this.treatWeight=wF(this.treatWeight,+!!this.treating,3,n),this.windedTime=Math.max(0,this.windedTime-n);let T=this.fallKneel&&this.downState===`falling`;this.winded=wF(this.winded,this.windedTime>0&&this.downState===`up`||T?1:0,this.windedTime>0||T?12:4,n),this.enswell.group.visible=this.treatWeight>.4&&this.treatProp===`enswell`,this.bottle.group.visible=this.treatWeight>.4&&this.treatProp===`bottle`;let E=this.countdownTicks!==null&&this.countdownTicks<=dI&&this.countdownTicks>=fI;this.touchWeight=wF(this.touchWeight,+!!E,6,n);let D=e.stamina/Math.max(1,e.maximum_stamina);this.tired=wF(this.tired,EF((.55-D)/.5,0,1),2,n),this.stunAmount=wF(this.stunAmount,Math.min(1,e.stunned_ticks/24),8,n);let O=e.defense;this.guardHigh=wF(this.guardHigh,+(O===`guard_high`),dR,n),this.guardLow=wF(this.guardLow,+(O===`guard_low`),dR,n),this.guardSpent=wF(this.guardSpent,+(e.guard0||e.clinch_startup_ticks>0),10,n),this.foulWeight=wF(this.foulWeight,+!!e.is_foul_recovery_target,8,n),this.tauntWeight=wF(this.tauntWeight,+(e.taunt_ticks>0),10,n);let j=Math.hypot(this.mapping.x(t.x)-this.mapping.x(e.x),this.mapping.z(t.y)-this.mapping.z(e.y)),ee=this.referee||e.is_downed||t.is_downed?0:1-EM(jF,FF,j);this.crowding=wF(this.crowding,ee,9,n);let M=1/0;if(this.hasLiveHead&&!this.referee&&this.downState===`up`){let e=this.boxer.rig.bones.head.getWorldPosition(this.ownHead),t=e.x-this.liveOpponentHead.x,r=e.z-this.liveOpponentHead.z,i=Math.hypot(t,r);if(M=Math.hypot(t,e.y-this.liveOpponentHead.y,r),M1e-4){let e=(MF-M)/MF*PF*n,a=Math.cos(-this.yaw),o=Math.sin(-this.yaw);this.headSpace.x+=(t*a+r*o)/i*e,this.headSpace.y+=(-t*o+r*a)/i*e,this.headSpace.lengthSq()>1&&this.headSpace.normalize()}}M>NF&&this.headSpace.multiplyScalar(Math.exp(-3*n)),this.tauntEnd=GL(this.tauntEnd,o,e.taunt_ticks>0?e.taunt_ticks:null),OF(this.headKick,n,190,7.5,.24),OF(this.torsoKick,n,150,7,.7),OF(this.rootKick,n,120,8,.12),OF(this.coverKick,n,110,15,.3),this.foldDelay>0&&(this.foldDelay-=n,this.foldDelay<=0&&(this.torsoKick.velocity.x+=this.pendingFold,this.pendingFold=0)),this.guardKick=Math.max(0,this.guardKick-n*2.4),this.ragdoll?.tick(n),this.updateDownState(e,n,i,S),this.stepDeath(n),this.stepInjuries(n);let te=(1.9-this.tired*.7)*(1-this.stunAmount*.6);this.bouncePhase+=n*te*Math.PI*2*u,this.weightPhase+=n*.55*Math.PI*2*u,this.stunPhase+=n*5.5,this.feintTimer-=n,this.feintTimer<=0&&!this.punchActive&&x<.05&&this.downState===`up`&&(this.feintTimer=2.5+this.bouncePhase%1.7,this.feint=1),this.feint=Math.max(0,this.feint-n*3.5);let ne=this.scratchC.set(this.rootX,0,this.rootZ);(this.downState===`up`||this.downState===`rising`)&&this.stepFeet(n,l,x,b,ne,this.yaw);let re=this.scratchQ.setFromAxisAngle(XL,-this.yaw),ie=l>0?this.foot.L:this.foot.R,N=l>0?this.foot.R:this.foot.L,ae=l>0?0:1,oe=+(l>0),se=this.footWorld(ae,ie.position),ce=this.footWorld(oe,N.position);ie.position.sub(ne).applyQuaternion(re),N.position.sub(ne).applyQuaternion(re);let le=this.boxer.rig.metrics.ankleHeight;ie.position.y=le+se,N.position.y=le+ce,HM(VM.leadToe,l,ie.toe),HM(VM.rearToe,l,N.toe),ie.heel=0,N.heel=0,ie.pole.copy(ie.toe).setY(.35).normalize(),N.pole.copy(N.toe).setY(.35).normalize();let P=this.torso,ue=VM.bladeYaw*l,de=Math.sin(this.bouncePhase)*.012*(1-this.stunAmount)*(x>.6?.6:1),fe=Math.sin(this.weightPhase)*.02,pe=.012+this.tired*.03+this.stunAmount*.05;P.hips.set(fe*l+Math.sin(this.stunPhase*.9)*.05*this.stunAmount,VM.hipsHeight-pe+de,0),P.hipsYaw=ue,P.hipsPitch=.02+this.tired*.08,P.hipsRoll=Math.sin(this.stunPhase)*.09*this.stunAmount,P.shouldersYaw=ue*.88,P.spinePitch=.16+this.tired*.16+Math.sin(r*(2.1+this.tired*1.8))*.012,P.spineRoll=Math.sin(this.stunPhase*1.3)*.06*this.stunAmount,P.headYaw=-.12*l+Math.sin(r*.9)*.05+Math.sin(this.stunPhase*.7)*.25*this.stunAmount,P.headPitch=.12+Math.sin(r*1.7)*.02+this.stunAmount*.18,P.headRoll=Math.sin(this.stunPhase*1.1)*.14*this.stunAmount,P.headOffset.set(0,0,0);let me=l>0?this.hand.L:this.hand.R,he=l>0?this.hand.R:this.hand.L,ge=this.headRestChar(l),_e=EF(this.guardHigh+this.guardLow,0,1),ve=this.scratch.copy(VM.relaxedLead).lerp(VM.guardHighLead,this.guardHigh).lerp(VM.guardLowLead,this.guardLow),ye=this.scratchB.copy(VM.relaxedRear).lerp(VM.guardHighRear,this.guardHigh).lerp(VM.guardLowRear,this.guardLow);ve.y-=this.tired*.12+this.stunAmount*.22,ye.y-=this.tired*.1+this.stunAmount*.2,ve.y-=this.guardSpent*xI,ye.y-=this.guardSpent*xI,ve.z-=this.guardSpent*.04,ye.z-=this.guardSpent*.03,ve.z+=this.feint*.1+Math.sin(r*2.3)*.012*u,ve.x+=Math.sin(r*1.9)*.01*u,ye.y+=Math.cos(r*2.7)*.01*u,ve.z-=this.guardKick*.07,ye.z-=this.guardKick*.05,ve.y-=this.guardKick*.02,ve.add(ge),ye.add(ge),me.position.set(ve.x*l,ve.y,ve.z),he.position.set(ye.x*l,ye.y,ye.z),HM(VM.leadKnuckles,l,me.knuckles),HM(VM.leadPalm,l,me.palm),HM(VM.rearKnuckles,l,he.knuckles),HM(VM.rearPalm,l,he.palm),HM(VM.leadPole,l,me.pole),HM(VM.rearPole,l,he.pole);let be=.15*_e,xe=.25*_e;if(this.hurt&&this.applyHurtStance(r,l,me,he,ge),Math.abs(this.slip)>.001){let e=this.slip;P.headOffset.x+=e*.13,P.spineRoll+=-e*.28,P.hips.x+=e*.03,P.hips.y-=Math.abs(e)*.05,P.spinePitch+=Math.abs(e)*.12,P.headRoll+=-e*.2}if(this.weave>.001){let e=this.weave,t=EF(this.weaveTime/fR,0,1),n=Math.sin(t*Math.PI);P.hips.y-=e*.2,P.spinePitch+=e*.42,P.headOffset.x+=e*(1-2*t)*.16*l,P.headOffset.y-=e*n*.08,P.spineRoll+=e*(1-2*t)*.18*l,me.position.y-=e*.1,he.position.y-=e*.1}if(this.pull>.001){let e=this.pull;P.spinePitch-=e*.34,P.hips.z-=e*.11,P.hips.x-=e*.05*l,P.headOffset.z-=e*.06,P.headPitch-=e*.1}this.punchCommit=wF(this.punchCommit,+!!this.punchActive,10,n);let Se=this.crowding*(1-this.clinchWeight)*(1-this.punchCommit);if(Se>.001&&(P.headOffset.x-=Se*.075,P.headOffset.z-=Se*.05,P.headYaw-=Se*.2,P.spinePitch-=Se*.07,P.hips.z-=Se*.05,me.position.z-=Se*.14,me.position.x-=Se*.035*l,he.position.z-=Se*.07),Math.abs(this.headSpace.x)+Math.abs(this.headSpace.y)>.001){let e=this.headSpace.x,t=this.headSpace.y,n=1-this.clinchWeight;P.spinePitch+=t*.7*n,P.spineRoll-=e*.7*n,P.hips.z+=t*.1*n,P.hips.x+=e*.05*n,P.headOffset.x+=e*.05,P.headOffset.z+=t*.05,P.headPitch+=t*.2,P.headRoll-=e*.3}if(this.ropeLean=wF(this.ropeLean,this.referee||this.downState!==`up`?0:this.ropeLeanTarget,WF,n),this.ropeLean>.001){let e=this.ropeLocal.copy(this.ropeOutward).applyAxisAngle(XL,-this.yaw);P.hipsPitch+=e.z*HF*this.ropeLean,P.hipsRoll-=e.x*UF*this.ropeLean}if(this.referee||this.applyReactions(me,he,ie,N),this.punchActive){be=0,xe=0;let e=this.applyPunch(l,me,he,ie,N,ge);this.punchReach=e,this.punchHand===`left`==l>0?be=e:xe=e}if(this.referee&&(this.applyRefereePose(l,me,he,ie,N,ge,r,o,e.stunned_ticks),this.applyReactions(me,he,ie,N)),this.clinchWeight>.001&&this.applyClinchPose(this.clinchWeight,r,l,e,t,me,he,ge),this.foulWeight>.001){let e=this.foulWeight;P.hips.y-=e*.16,P.spinePitch+=e*.55,P.headPitch+=e*.2,me.position.lerp(this.scratch.set(.06*l,.72,.16),e),he.position.lerp(this.scratch.set(-.05*l,.7,.14),e),me.pole.set(.6*l,-.6,.5),he.pole.set(-.6*l,-.6,.5)}if(this.tauntWeight>.001){let e=this.tauntEnd===null?0:EF(this.tauntEnd-o,0,yI);this.applyTauntPose(this.tauntWeight,(yI-e)/yI*bI,l,me,he,ge)}if(this.dislocation===`shoulder_left`||this.dislocation===`shoulder_right`){let e=this.dislocation===`shoulder_left`?this.hand.L:this.hand.R,t=this.dislocation===`shoulder_left`?1:-1;e.position.set(.24*t,.55,.05),e.pole.set(.9*t,-.3,.2),e.knuckles.set(0,-1,.1),e.palm.set(-t,0,.2)}this.winded>.001&&(this.downState===`up`||T)&&this.applyWindedPose(this.winded,r,l,me,he),this.hurt&&this.downState===`up`&&this.applyHurtActs(r,l,ie,N),this.touchWeight>.001&&this.downState===`up`&&this.applyTouchGlovesPose(this.touchWeight,l,me,he),this.celebration>.001&&this.downState===`up`&&this.applyCelebratePose(this.celebration,r,l,me,he,ie,N),this.wave>.001&&this.downState===`up`&&this.applyWaveOffPose(this.wave,r,l,me,he),this.squareWeight>.001&&this.downState===`up`&&this.applyVerdictPose(this.squareWeight,r,l,me,he,ie,N,ge),(this.wristWeights[0]>.001||this.wristWeights[1]>.001)&&this.downState===`up`&&this.applyRaisePose(l,me,he),this.breakWeight>.001&&this.downState===`up`&&this.applyBreakPose(this.breakWeight,l,me,he),this.attendWeight>.001&&this.downState===`up`&&this.applyAttendPose(this.attendWeight,r,l,me,he),this.treatWeight>.001&&this.downState===`up`&&this.applyTreatPose(this.treatWeight,r,l,me,he,ie,N),this.seated>.001&&this.downState===`up`&&this.applySeatedPose(this.seated,r,l,me,he,ie,N),this.downState!==`up`&&this.applyDownPose(l,me,he,ie,N),this.steadyJointPoles(l,me,he,ie,N,n),pe=0;let F=this.pose;F.shrugL=l>0?be:xe,F.shrugR=l>0?xe:be;let Ce=this.ragdoll;if(Ce?.active===!0&&i&&(Ce.stop(),Ce.clearRise()),Ce?.active===!0&&!Ce.handingOver)Ce.setLost(c.isDecapitated,c.isHandDismembered(`left`),c.isHandDismembered(`right`)),Ce.update(n,this.obstacle),this.hurt&&this.dropDangles();else{if(this.solver.apply(c.root,this.pose),Ce?.handingOver===!0)Ce.followPose(n,this.obstacle),this.riseProgress>=JF&&Ce.handOverSeconds>=rI&&(Ce.letGo(),this.riseBlendAge=0);else if(Ce!==null&&Ce.hasRisePose){let e=EM(0,nI,this.riseBlendAge);e<1&&this.downState!==`up`?Ce.blendRise(e):Ce.clearRise()}this.hurt&&this.dangleArms(n),Ce?.sample(n)}this.applyDislocation();let we=Math.min(1,(t.trauma.bleeding+t.trauma.left_cut+t.trauma.right_cut+t.trauma.head/4)/300*(a===`off`?0:a===`reduced`?.15:1.5));c.setGloveBlood(we),c.setTrunksBlood(fj(e.trauma,a)),dj(c.headInjury,e.trauma,a),pj(c.bodyInjury,e.trauma,a),c.setSkinClearcoat(.25+(1-D)*.4),this.laidOut=!1}applyTauntPose(e,t,n,r,i,a){let o=this.torso,s=.5-.5*Math.cos(t*Math.PI*2);i.position.lerp(this.scratch.set(-.3*n,a.y-.62,.02),e),i.pole.lerp(this.scratch.set(-.5*n,-.4,-.75),e).normalize(),i.knuckles.lerp(this.scratch.set(-.1*n,-.95,.3),e).normalize(),i.palm.lerp(this.scratch.set(0,.3,.95),e).normalize(),r.position.lerp(this.scratch.set(.26*n,a.y-.36+s*.1,.52-s*.24),e),r.pole.lerp(this.scratch.set(.7*n,-.7,.1),e).normalize(),r.knuckles.lerp(this.scratch.set(.1*n,.25+s*.6,.95-s*.7),e).normalize(),r.palm.lerp(this.scratch.set(-.2*n,.95,-.2-s*.5),e).normalize(),o.spinePitch-=e*.12,o.headPitch-=e*.22,o.headYaw+=Math.sin(t*Math.PI)*.15*e,o.shouldersYaw+=Math.sin(t*Math.PI*3)*.1*e,o.hips.x+=Math.sin(t*Math.PI)*.03*e*n,o.headOffset.z+=e*.03}applyClinchPose(e,t,n,r,i,a,o,s){let c=this.torso,l=r.player_idy&&(h.x*=y/v,h.z*=y/v),h.x+=o,h.z+=u,t.position.lerp(h,e),t.pole.lerp(this.clinchTemp.set(r*.85,l?.35:-.6,.25),e).normalize(),t.knuckles.lerp(this.clinchTemp.set(-p*r*.9+f.x*.3,l?-.25:.1,-m*r*.9+f.z*.3),e).normalize(),t.palm.lerp(this.clinchTemp.set(-f.x,l?.1:.35,-f.z),e).normalize()}}holdOnTheRopes(e,t,n){if(this.referee)return this.ropeLeanTarget=0,this.ropeHold.set(0,0,0);this.ropeLeanTarget=GF(t,n,this.ropeExcess,this.ropeOwn);let r=Math.hypot(this.ropeExcess.x,this.ropeExcess.z);r>0&&this.ropeOutward.set(this.ropeExcess.x/r,0,this.ropeExcess.z/r);let i=this.mapping.x(e.x),a=this.mapping.z(e.y);GF(i,a,this.ropeTheirs,this.ropeTheirs);let o=1-EM(RF,zF,Math.hypot(i-t,a-n));return this.ropeHold.set(KF(this.ropeOwn.x,this.ropeTheirs.x*o),0,KF(this.ropeOwn.z,this.ropeTheirs.z*o))}headRestChar(e){let t=this.boxer.rig.metrics;return this.headWorld.set(-.08,t.headHeight-t.hipsHeight+this.torso.hips.y,.02)}syncAction(e,t,n,r){this.shownFighter=e,this.shownOpponent=t;let i=this.ownQueued;if(i!==null&&e.action_id===i.action.id&&(this.ownQueued=null,this.retirePunch(),this.startOwnPunch(i),this.ownPress=!1),e.action_id!==null&&e.action_id!==this.actionId&&e.action_id!==this.completedActionId&&!this.retiredOwnIds.includes(e.action_id)){let t=e.action;if(t!==null){let r=e.action_hand??(e.stance===`orthodox`?`left`:`right`),i=this.ownActionId===e.action_id&&this.punchActive,a=this.punchTiming;this.actionId=e.action_id,this.punchClass=t,this.punchHand=r,this.punchTarget=e.action_target??`head`,this.punchPower=e.action_power??`normal`,this.punchTiming={...oe(this.punchClass,this.punchTarget,this.punchPower),startup:e.action_startup_ticks,active:e.action_active_ticks,recovery:e.action_recovery_ticks},this.punchTotalTicks=Math.max(1,e.action_startup_ticks+e.action_active_ticks+e.action_recovery_ticks);let o=Math.max(0,n-e.action_start_tick);i?(this.punchAgeTicks=gR(this.punchAgeTicks,a,this.punchTiming),this.ownAuthoritativeAge=o,this.ownRefused||(this.ownPulled=!1,this.ownCut=!1,o-this.punchAgeTicks>1&&(this.punchAgeTicks=o))):(this.punchAgeTicks=o,this.ownActionId=null,this.ownPress=!1,this.ownLeadTicks=0,this.ownAuthoritativeAge=null),this.ownWaitedTicks=0,this.punchActive=!0}}if(e.action_id===null)this.actionId=null,this.completedActionId=null;else if(e.action_id===this.actionId&&this.punchActive){let t=Math.max(0,n-e.action_start_tick);this.ownActionId===this.actionId?(this.ownAuthoritativeAge=t,!this.ownPulled&&t-this.punchAgeTicks-this.hitstopLag>1.5&&(this.punchAgeTicks=t)):Math.abs(this.punchAgeTicks+this.hitstopLag-t)>1.5&&(this.punchAgeTicks=t,this.hitstopLag=0)}if(this.punchActive&&this.ownActionId!==null&&this.ownAuthoritativeAge===null&&!this.ownPulled&&!this.ownCut&&(this.ownWaitedTicks+=r*30,this.ownWaitedTicks>this.ownExpectedTicks*1.5+QL&&(this.ownPress?!this.ownStarted:this.punchAgeTicks=e,n=this.hitstop>0?0:Math.min(this.hitstopLag,r*30*tR);this.hitstopLag-=n,this.punchAgeTicks+=r*30*(t?eR:this.ownPunchRate())+n,this.ownPress&&this.ownActionId!==null&&!this.ownCut&&this.punchAgeTicks>=this.punchTiming.startup&&this.pressesLanded.at(-1)!==this.ownActionId&&(this.pressesLanded.push(this.ownActionId),this.pressesLanded.length>6&&this.pressesLanded.shift()),this.punchAgeTicks>=this.punchTotalTicks&&this.retirePunch()}e.is_downed&&(this.punchActive&&this.retirePunch(),this.ownQueued=null),this.releaseQueuedPress(r);let a=this.actionId??this.ownActionId;a!==this.aimActionId&&(this.aimActionId=a,this.followHead=0),this.followHead=wF(this.followHead,+(a!==null&&a===this.contactId),mR,r),this.followReferee=wF(this.followReferee,+(a!==null&&a===this.refereeContactId),mR,r)}trackOpponentHead(e,t,n){let r=this.guardOpponentHead.set(this.mapping.x(e.x),0,this.mapping.z(e.y));this.opponentSteadySeconds=uR.has(e.defense)?0:this.opponentSteadySeconds+n,(!this.hasLiveHead||this.opponentSteadySeconds>=pR)&&this.opponentHeadOffset.copy(t).sub(r),r.add(this.opponentHeadOffset),this.liveOpponentHead.copy(t),this.hasLiveHead=!0}ownPunchRate(){if(this.ownActionId===null||this.ownPress)return 1;let e=this.punchTiming.startup,t=this.ownAuthoritativeAge;return t===null?this.punchAgeTicks0,h=m?t:n,g=m?n:t,_=m?1:-1,v=+(this.punchPower===`power`),y=+(this.punchTarget===`body`),b,x,S,C=1,w=1,T=0;if(u0){let t=this.scratchQ.setFromAxisAngle(XL,-ae*e*E);r.toe.applyQuaternion(t),r.pole.applyQuaternion(t)}if(ie>.3){let t=this.scratchQ.setFromAxisAngle(XL,.45*e*E);i.toe.applyQuaternion(t),i.pole.applyQuaternion(t)}let _e=this.scratchE;switch(this.punchClass){case`hook`:_e.set(.22*_*e,-.06,-.12);break;case`uppercut`:_e.set(.05*_*e,-.42,-.02);break;case`straight`:_e.set(.02*_*e,-.03,-.09-.05*v);break;default:_e.set(0,-.01,-.05-.04*v)}_e.x+=(this.punchClass===`hook`?.08:0)*_*e*v,_e.y-=.05*v,_e.z-=.12*v;let ve=this.punchStart.copy(k).addScaledVector(_e,Math.max(x,this.punchClass===`hook`||this.punchClass===`uppercut`?(1-D)*.6*C:0));if(this.punchClass===`hook`){let t=Math.hypot(ve.x-de.x,ve.z-de.z),n=Math.hypot(ge.x-de.x,ge.z-de.z),r=this.punchSweepFrom.copy(ve).sub(de).setY(0).normalize(),i=this.punchSweepTo.copy(ge).sub(de).setY(0).normalize(),a=Math.acos(EF(r.dot(i),-1,1)),o=r.z*i.x-r.x*i.z>=0?1:-1,s=EM(0,1,D),c=r.applyAxisAngle(XL,a*s*o).normalize();h.position.copy(de).addScaledVector(c,G.lerp(t,n,s)),h.position.y=G.lerp(ve.y,ge.y,s),h.pole.set(.95*_*e,.08,.3).normalize(),h.knuckles.copy(c).applyAxisAngle(XL,o*Math.PI/2).setY(.05).normalize(),h.palm.set(0,-1,0)}else if(this.punchClass===`uppercut`){let t=EM(0,1,D),n=ve,r=this.punchMid.copy(ge).lerp(n,.5);r.y=Math.min(n.y,ge.y)-.04,r.z+=.08,h.position.copy(n).lerp(r,t*2>1?1:t*2),t>.5&&h.position.copy(r).lerp(ge,(t-.5)*2),h.pole.set(.3*_*e,-.2,1),h.knuckles.set(.05*_*e,.9,.35).normalize(),h.palm.set(-.2*_*e,.3,-.95).normalize()}else{h.position.copy(ve).lerp(ge,Math.min(1,D)),h.position.y+=Math.sin(EF(D,0,1)*Math.PI)*.025,h.pole.set(.55*_*e,-.9,.35);let t=EM(.55,1,D);h.knuckles.copy(fe).lerp(this.scratchC.set(.1*_*e,.55,.8),1-t).normalize(),h.palm.set(-.9*_*e,.2,-.3).lerp(this.scratchC.set(0,-1,.1),t).normalize()}if(O>0&&(h.position.lerp(k,O),h.knuckles.lerp(A,O).normalize(),h.palm.lerp(j,O).normalize(),h.pole.lerp(ee,O).normalize()),w<1){let t=(1-h.pole.dot(ee)/Math.max(1e-6,h.pole.length()*ee.length()))/2;h.knuckles.lerp(A,1-w).normalize(),h.palm.lerp(j,1-w).normalize(),h.pole.lerp(ee,1-w).addScaledVector(this.scratchC.set(_*e,0,0),hR*t*Math.sin(Math.PI*w)).normalize()}let ye=this.scratchE.set(-.1*_*e,a.y-.04,.12+a.z);return g.position.lerp(ye,E*.7),E}applyReactions(e,t,n,r){let i=this.torso;i.headOffset.add(this.headKick.value),i.headPitch+=-this.headKick.value.z*2.4+this.headKick.value.y*1.6,i.headYaw+=this.headKick.value.x*2.2,i.headRoll+=-this.headKick.value.x*.9,i.spinePitch+=this.torsoKick.value.x,i.spineRoll+=this.torsoKick.value.z*.5,i.hips.x+=this.rootKick.value.x,i.hips.z+=this.rootKick.value.z,i.hips.y-=Math.max(0,this.torsoKick.value.x)*.08,this.torsoKick.value.x>.05&&(e.position.y-=this.torsoKick.value.x*.25,t.position.y-=this.torsoKick.value.x*.2,e.position.z-=this.torsoKick.value.x*.1);let a=Math.max(0,this.rootKick.value.y);i.hips.y+=a,n.heel+=a*6,r.heel+=a*6;let o=this.coverKick.value.x;if(Math.abs(o)>.002){let e=o>0?this.hand.R:this.hand.L;e.position.y-=Math.abs(o)*.9,e.position.x+=o*.2,e.position.z-=Math.abs(o)*.25,e.pole.y-=Math.abs(o)*3}}applyRefereePose(e,t,n,r,i,a,o,s,c=0){let l=this.torso;l.hipsYaw=0,l.shouldersYaw=0,l.hipsPitch=0,l.spinePitch=.06,l.headYaw=Math.sin(o*.7)*.08,l.headPitch=.08,l.hips.y=VM.hipsHeight+.03,l.hips.x=0,l.hips.z=0,r.toe.set(.12*e,0,1).normalize(),i.toe.set(-.12*e,0,1).normalize(),r.pole.copy(r.toe).setY(.3).normalize(),i.pole.copy(i.toe).setY(.3).normalize();let u=Math.sin(o*1.3)*.01;if(t.position.set(.27*e,.86+u,.12),n.position.set(-.27*e,.86-u,.12),t.pole.set(.5*e,-.4,-.8).normalize(),n.pole.set(-.5*e,-.4,-.8).normalize(),t.knuckles.set(.15*e,-.9,.35).normalize(),n.knuckles.set(-.15*e,-.9,.35).normalize(),t.palm.set(-.9*e,.1,.35).normalize(),n.palm.set(.9*e,.1,.35).normalize(),this.refereeCounting){this.countChangedTick??=s;let r=EF((s-this.countChangedTick)/ee,0,1),i=r0){let r=Math.min(1,c/12),i=Math.sin(o*9.5);l.hips.y-=.09*r,l.hips.x+=i*.05*r,l.spineRoll+=i*.18*r,l.headRoll-=i*.35*r,l.headPitch+=.25*r,t.position.x+=.18*e*r,n.position.x-=.18*e*r,t.position.y-=.1*r,n.position.y-=.1*r}}updateDownState(e,t,n,r){if(this.riseBlendAge+=t,e.is_downed||this.forcedDown||this.dead){if(this.downState===`up`||this.downState===`rising`||this.deathFall)this.deathFall=!1,this.fallFromGetUp=this.downState!==`up`,this.fallFromGetUp&&(HL(this.fallStart,this.downResult),this.fallStartStand=this.downStand),this.downState=`falling`,this.fallAge=0,this.riseProgress=0,this.riseRootFrom.copy(this.riseRoot),this.landSettled=!1,this.fallenFromPhysics=!1,this.downPolesSet=!1,this.ragdoll?.clearRise(),this.authoredNextFall?this.ragdoll?.forget():n||this.startFall(e),this.authoredNextFall=!1;else if(this.downState===`falling`)this.fallAge+=t,this.fallAge>=qF&&(this.downState=`down`);else if(this.fallKneel)this.riseProgress=YF;else{let n=(!this.forcedDown&&!this.heldDown&&!this.dead&&e.get_up_required>0?EF(e.get_up_meter/e.get_up_required,0,1):0)*YF;if(this.ragdoll?.active===!0&&!this.ragdoll.handingOver){if(n<=0)return;this.handOverFall(e)}this.riseProgress+=EF(n-this.riseProgress,-.4*t,QF*t)}return}if((this.downState===`down`||this.downState===`falling`)&&(this.downState=`rising`,this.ragdoll?.active===!0&&!this.ragdoll.handingOver&&this.handOverFall(e),this.fallKneel&&(this.riseProgress=Math.max(this.riseProgress,YF)),this.riseFrom=this.riseProgress,this.feetInitialized=!1),this.downState!==`rising`)return;let i=r>.3||this.punchActive,a=(1-this.riseFrom)/(i?ZF:XF);this.riseProgress=Math.min(1,this.riseProgress+(this.riseProgress=1&&(this.downState=`up`,this.fallKneel=!1)}startFall(e){let t=this.ragdoll;t!==null&&(this.rootX!==null&&Math.hypot(this.place.x-this.rootX,this.place.z-this.rootZ)>iI&&(this.rootX=this.place.x,this.rootZ=this.place.z,this.boxer.root.position.set(this.rootX,0,this.rootZ)),t.start(this.dead?this.deathStyle:`crumple`),e.get_up_count>0&&!this.dead&&(t.settle(),this.fallAge=qF))}handOverFall(e){let t=this.ragdoll;if(t===null||!t.active||t.handingOver)return;let n=e.stance===`orthodox`?1:-1,r=this.boxer.rig.bones;this.boxer.root.updateMatrixWorld(!0);let i=this.scratchC.set(this.rootX??0,0,this.rootZ),a=this.scratchQ.setFromAxisAngle(XL,-this.yaw),o=this.fallen,s=(e,t)=>t.setFromMatrixPosition(e.matrixWorld).sub(i).applyQuaternion(a),c=(e,t,n,r)=>NL(vL.setFromQuaternion(e.getWorldQuaternion(_L).premultiply(a),`YXZ`),t,n,r);s(r.hips,o.hips),this.landProne=t.faceDown();let l=Math.abs(o.hips.x)>.12?Math.sign(o.hips.x):0,u=this.landProne?kL(this.downTo,TL,EL,n,l,this.boxer.rig.metrics.ankleHeight):kL(this.downTo,CL,wL,n,l,this.boxer.rig.metrics.ankleHeight);this.landSide=l,this.landShift.set(o.hips.x-u.hips.x,0,o.hips.z-u.hips.z);let d=c(r.hips,u.hipsPitch,u.hipsYaw,u.hipsRoll);o.hipsPitch=d.x,o.hipsYaw=d.y,o.hipsRoll=d.z;let f=c(r.upperChest,o.hipsPitch,o.hipsYaw,o.hipsRoll);o.shouldersYaw=f.y,o.spinePitch=f.x-o.hipsPitch,o.spineRoll=f.z-o.hipsRoll;let p=c(r.head,f.x,f.y,f.z);o.headPitch=p.x,o.turn=p.y,o.headRoll=p.z,s(n>0?r.gloveL:r.gloveR,o.leadHand),s(n>0?r.gloveR:r.gloveL,o.rearHand),s(n>0?r.ankleL:r.ankleR,o.leadFoot),s(n>0?r.ankleR:r.ankleL,o.rearFoot);let m=this.boxer.rig.metrics.ankleHeight;o.leadFoot.y=Math.max(o.leadFoot.y,m),o.rearFoot.y=Math.max(o.rearFoot.y,m);let h=(e,t,n,r,i)=>{let o=s(e,this.scratchB),c=s(n,this.scratchD).sub(o).normalize();s(t,r).sub(o),r.addScaledVector(uL.copy(i).applyQuaternion(e.getWorldQuaternion(_L)).applyQuaternion(a),gL),r.addScaledVector(c,-r.dot(c)),r.lengthSq()>1e-6?r.normalize():r.copy(i===pL?dL:fL)},g=n>0;h(g?r.hipL:r.hipR,g?r.kneeL:r.kneeR,g?r.ankleL:r.ankleR,o.leadKnee,pL),h(g?r.hipR:r.hipL,g?r.kneeR:r.kneeL,g?r.ankleR:r.ankleL,o.rearKnee,pL),h(g?r.shoulderL:r.shoulderR,g?r.elbowL:r.elbowR,g?r.gloveL:r.gloveR,o.leadElbow,g?mL:hL),h(g?r.shoulderR:r.shoulderL,g?r.elbowR:r.elbowL,g?r.gloveR:r.gloveL,o.rearElbow,g?hL:mL);let _=(e,t,n)=>{let r=e.getWorldQuaternion(_L).premultiply(a);t.set(0,1,0).applyQuaternion(r),n.set(0,0,1).applyQuaternion(r)};_(g?r.gloveL:r.gloveR,o.leadKnuckles,o.leadPalm),_(g?r.gloveR:r.gloveL,o.rearKnuckles,o.rearPalm),o.ownJoints=1,o.leadHeel=0,o.rearHeel=0,o.palmsDown=+!!this.landProne,this.fallenFromPhysics=!0,this.landSettled=!0,this.downPolesSet=!1,t.handOver(),this.riseBlendAge=0;let v=this.scratchE.set(t.pelvis(this.scratchD).x-(this.rootX??0),0,this.scratchD.z-this.rootZ),y=this.scratchB.copy(v).applyQuaternion(a);for(let e of[o.hips,o.leadHand,o.rearHand,o.leadFoot,o.rearFoot])e.x-=y.x,e.z-=y.z;t.shiftRise(this.scratchC.copy(v).negate()),this.rootX=(this.rootX??0)+v.x,this.rootZ+=v.z,this.boxer.root.position.set(this.rootX,0,this.rootZ),this.riseRoot.set(this.rootX-this.mapping.x(e.x)-this.touchOffset.x,0,this.rootZ-this.mapping.z(e.y)-this.touchOffset.z),this.riseRootFrom.copy(this.riseRoot)}walkBackFromTheFall(e){let t=this.downState===`rising`?1-EM(YF,1,this.riseProgress):this.downState===`up`?0:1,n=this.riseRootFrom.x*t,r=this.riseRootFrom.z*t;e>0?this.riseRootVelocity.set((n-this.riseRoot.x)/e,0,(r-this.riseRoot.z)/e):this.riseRootVelocity.set(0,0,0),this.riseRoot.set(n,0,r),t===0&&this.riseRootFrom.set(0,0,0)}steadyJointPoles(e,t,n,r,i,a){if(this.poleSettle=this.downState===`up`?Math.max(0,this.poleSettle-a):tI,this.poleSettle<=0||this.ragdoll?.active===!0&&!this.ragdoll.handingOver){this.downPolesSet=!1;return}let o=this.boxer.rig.bones,s=e>0;this.characterInverse.copy(this.boxer.root.matrixWorld).invert();for(let e=0;e<4;e+=1){let c=e<2,l=e%2==0,u=l===s,d=c?u?o.hipL:o.hipR:u?o.shoulderL:o.shoulderR,f=c?l?r:i:l?t:n,p=f.position,m=f.pole,h=this.downPoles[e];if(!this.downPolesSet){h.copy(m);continue}let g=this.scratchB.setFromMatrixPosition(d.matrixWorld).applyMatrix4(this.characterInverse).sub(p).negate();if(g.lengthSq()<1e-6){h.copy(m);continue}g.normalize();let _=this.scratchD.copy(h).addScaledVector(g,-h.dot(g)),v=this.scratchE.copy(m).addScaledVector(g,-m.dot(g));if(_.lengthSq()<1e-4||v.lengthSq()<1e-4){h.copy(m);continue}let y=Math.atan2(this.scratch.crossVectors(_,v).dot(g),_.dot(v)),b=eI*Math.max(a,1/120);Math.abs(y)<=b||m.copy(_.normalize().applyAxisAngle(g,Math.sign(y)*b)),h.copy(m)}this.downPolesSet=!0}applyWindedPose(e,t,n,r,i){let a=this.torso,o=G.lerp,s=this.windedSide,c=Math.sin(t*23)*.006;a.hips.y=o(a.hips.y,VM.hipsHeight-.1,e),a.hips.z=o(a.hips.z,-.04,e),a.hipsPitch=o(a.hipsPitch,.2,e),a.spinePitch=o(a.spinePitch,.62+c,e),a.spineRoll=o(a.spineRoll,s*.16,e),a.headPitch=o(a.headPitch,.38,e);let l=s>0?this.hand.L:this.hand.R,u=l===r?i:r;l.position.lerp(Q.set(s*.13,.98,.17),e),l.palm.lerp(Q.set(-s*.6,0,-.8),e).normalize(),l.knuckles.lerp(Q.set(-s*.5,.5,.2),e).normalize(),l.pole.lerp(Q.set(s*.9,-.3,-.3),e).normalize(),u.position.lerp(Q.set(-s*.2,.86,.3),e),u.pole.lerp(Q.set(-s*.8,-.6,0),e).normalize()}applyTouchGlovesPose(e,t,n,r){let i=this.torso,a=G.lerp;i.hips.z=a(i.hips.z,.06,e),i.hipsYaw=a(i.hipsYaw,i.hipsYaw*.4,e),i.shouldersYaw=a(i.shouldersYaw,0,e),i.spinePitch=a(i.spinePitch,.12,e),i.headPitch=a(i.headPitch,.1,e),n.position.lerp(Q.set(.11*t,1.24,.5),e),r.position.lerp(Q.set(-.11*t,1.22,.47),e),n.palm.lerp(Q.set(-t,0,0),e).normalize(),r.palm.lerp(Q.set(t,0,0),e).normalize(),n.knuckles.lerp(Q.set(0,.15,1),e).normalize(),r.knuckles.lerp(Q.set(0,.15,1),e).normalize(),n.pole.lerp(Q.set(.7*t,-.7,0),e).normalize(),r.pole.lerp(Q.set(-.7*t,-.7,0),e).normalize()}touchWalk(e,t,n,r){this.countdownEnd=GL(this.countdownEnd,r,this.countdownTicks);let i=this.countdownEnd===null?0:KL(this.countdownEnd-r),a=this.mapping.x(t.x)-this.mapping.x(e.x),o=this.mapping.z(t.y)-this.mapping.z(e.y),s=Math.hypot(a,o),c=s>pI?(s-pI)/2/s*i:0;return this.touchVelocity.set(a*c-this.touchOffset.x,0,o*c-this.touchOffset.z).divideScalar(Math.max(n,.001)).clampLength(0,vI),this.touchOffset.set(a*c,0,o*c)}applyCelebratePose(e,t,n,r,i,a,o){let s=this.torso,c=G.lerp,l=Math.sin(t*6)*.04;s.hips.y=c(s.hips.y,VM.hipsHeight+.035+l*.5,e),s.hipsYaw=c(s.hipsYaw,0,e),s.hipsPitch=c(s.hipsPitch,-.12,e),s.hipsRoll=c(s.hipsRoll,0,e),s.shouldersYaw=c(s.shouldersYaw,0,e),s.spinePitch=c(s.spinePitch,-.1,e),s.headPitch=c(s.headPitch,-.25,e),r.position.lerp(Q.set(.3*n,1.86+l,.08),e),i.position.lerp(Q.set(-.3*n,1.84+l,.06),e),r.palm.lerp(Q.set(0,0,1),e).normalize(),i.palm.lerp(Q.set(0,0,1),e).normalize(),r.knuckles.lerp(Q.set(.15*n,1,0),e).normalize(),i.knuckles.lerp(Q.set(-.15*n,1,0),e).normalize(),r.pole.lerp(Q.set(n,.1,-.3),e).normalize(),i.pole.lerp(Q.set(-n,.1,-.3),e).normalize(),a.heel=c(a.heel,.45,e),o.heel=c(o.heel,.45,e)}applyAttendPose(e,t,n,r,i){let a=this.torso,o=G.lerp,s=Math.sin(t*3.1)*.03;a.hips.z=o(a.hips.z,.12,e),a.hips.y=o(a.hips.y,VM.hipsHeight-.04,e),a.hipsPitch=o(a.hipsPitch,.3,e),a.spinePitch=o(a.spinePitch,.42,e),a.headPitch=o(a.headPitch,.4,e),r.position.lerp(Q.set(.2*n,1.3+s,.62),e),i.position.lerp(Q.set(-.18*n,1.24-s,.58),e),r.palm.lerp(Q.set(0,-.6,.8),e).normalize(),i.palm.lerp(Q.set(0,-.6,.8),e).normalize(),r.knuckles.lerp(Q.set(.1*n,.5,1),e).normalize(),i.knuckles.lerp(Q.set(-.1*n,.5,1),e).normalize(),r.pole.lerp(Q.set(.8*n,-.5,-.1),e).normalize(),i.pole.lerp(Q.set(-.8*n,-.5,-.1),e).normalize()}applyTreatPose(e,t,n,r,i,a,o){let s=this.torso,c=G.lerp,l=this.treatScratch.set(this.rootX??0,0,this.rootZ),u=this.scratchQ.setFromAxisAngle(XL,-this.yaw),d=Q.copy(this.treatTarget).sub(l).applyQuaternion(u),f=this.treatFacingLocal.copy(this.treatFacing).applyQuaternion(u),p=f.z,m=-f.x,h=Math.sin(t*2.6)*.006;s.hips.lerp(this.treatScratch.set(0,.62,.04),e),s.hipsYaw=c(s.hipsYaw,0,e),s.hipsPitch=c(s.hipsPitch,.22,e),s.hipsRoll=c(s.hipsRoll,0,e),s.shouldersYaw=c(s.shouldersYaw,0,e),s.spinePitch=c(s.spinePitch,.3,e),s.headPitch=c(s.headPitch,.2,e),a.position.x=c(a.position.x,.24*n,e),a.position.z=c(a.position.z,.14,e),o.position.x=c(o.position.x,-.2*n,e),o.position.z=c(o.position.z,-.2,e),o.heel=c(o.heel,.55,e),a.toe.lerp(this.treatScratch.set(.2*n,0,1),e).normalize(),o.toe.lerp(this.treatScratch.set(-.1*n,0,1),e).normalize(),a.pole.lerp(this.treatScratch.set(.25*n,.4,1),e).normalize(),o.pole.lerp(this.treatScratch.set(-.2*n,.4,1),e).normalize();let g=this.treatProp===`bottle`,_=g?.3:.08-h;r.position.lerp(this.treatScratch.set(d.x+f.x*_,d.y+(g?.02:-.07),d.z+f.z*_),e),g?r.knuckles.lerp(this.treatScratch.set(-f.x,-.25,-f.z),e).normalize():r.knuckles.lerp(this.treatScratch.set(0,1,.05),e).normalize(),r.palm.lerp(g?this.treatScratch.set(0,-1,0):this.treatScratch.set(-f.x,0,-f.z),e).normalize(),r.pole.lerp(this.treatScratch.set(.85*n,-.35,.1),e).normalize();let v=this.treatSide*.135;i.position.lerp(this.treatScratch.set(d.x-p*v+f.x*.05,d.y-.2,d.z-m*v+f.z*.05),e),i.knuckles.lerp(this.treatScratch.set(0,.9,.4),e).normalize(),i.palm.lerp(this.treatScratch.set(p*this.treatSide*.8-f.x*.6,.1,m*this.treatSide*.8-f.z*.6),e).normalize(),i.pole.lerp(this.treatScratch.set(-.85*n,-.4,.1),e).normalize()}applyBreakPose(e,t,n,r){let i=this.torso,a=G.lerp;i.hipsPitch=a(i.hipsPitch,.14,e),i.spinePitch=a(i.spinePitch,.08,e);let o=this.scratchC.set(.48*t,1.22,.52),s=this.scratchD.set(-.48*t,1.22,.52);if(this.breakAimed){let[e,n]=this.breakFighters,r=this.scratch.subVectors(n,e).setY(0).normalize(),i=this.scratchQ.setFromAxisAngle(XL,-this.yaw),a=this.scratchB.set(this.rootX??0,0,this.rootZ);o.copy(e).addScaledVector(r,lI).sub(a).applyQuaternion(i),s.copy(n).addScaledVector(r,-lI).sub(a).applyQuaternion(i),o.x*tqF*.15;let s=this.downResult;if(this.downState!==`falling`){let a=this.riseProgress,c=0;if(this.fallKneel)c=EM(YF,1,a),UL(s,this.placeKneel(this.downFrom,e),o,c);else if(a0==t>0;return e.hips.set(.02*t,.53,-.06),e.hipsYaw=VM.bladeYaw*t*.3,e.hipsPitch=.24,e.hipsRoll=0,e.shouldersYaw=VM.bladeYaw*t*.2,e.spinePitch=.62,e.headPitch=.48,(r?e.leadHand:e.rearHand).set(n*.13,.66,.2),(r?e.rearHand:e.leadHand).set(.13*t,.66,.37),e.leadFoot.set(.16*t,.125,.32),e.rearFoot.set(-.12*t,.12,-.5),e.leadHeel=0,e.rearHeel=0,e.palmsDown=1,e}placeLying(e){let t=this.boxer.rig.metrics.ankleHeight;return PL(this.landProne?kL(this.downFrom,TL,EL,e,this.landSide,t):kL(this.downFrom,CL,wL,e,this.landSide,t),this.landShift)}placeDown(e,t,n){return kL(e,t,null,n,0,this.boxer.rig.metrics.ankleHeight)}chooseLanding(e){let t=this.boxer.rig.metrics.ankleHeight,n=1/0;for(let r=0;r=n||(n=u.length()+o,this.landProne=s,this.landSide=c,this.landShift.copy(u))}}ropeShift(e,t){let n=this.scratchQ.setFromAxisAngle(XL,this.yaw);vL.set(e.hipsPitch+e.spinePitch*.7,e.hipsYaw,e.hipsRoll,`YXZ`),RL[0].set(0,IL,0).applyEuler(vL).add(e.hips),RL[1].set(.2,LL,0).applyEuler(vL).add(e.hips),RL[2].set(-.2,LL,0).applyEuler(vL).add(e.hips),RL[3].copy(e.leadHand),RL[4].copy(e.rearHand),RL[5].copy(e.leadFoot).z+=e.leadHeel>0?.25:.19,RL[6].copy(e.rearFoot).z+=e.rearHeel>0?.25:.19,RL[7].copy(e.hips);let r=1/0,i=-1/0,a=1/0,o=-1/0;for(let e=0;e0==t>0,c=s?n:r,l=s?r:n;i.pole.lerp(Q.set(.15*t,.35,1),e).normalize(),a.pole.lerp(Q.set(-.1*t,-1,.3),e).normalize(),i.toe.lerp(Q.set(.15*t,0,1),e).normalize(),a.toe.lerp(Q.set(0,-.35,-1),e).normalize(),c.palm.lerp(Q.set(-o*.75,0,-.65),e).normalize(),c.knuckles.lerp(Q.set(-o*.35,.25,.9),e).normalize(),c.pole.lerp(Q.set(o*.9,-.35,-.25),e).normalize(),l.palm.lerp(Q.set(0,-1,.1),e).normalize(),l.knuckles.lerp(Q.set(.2*t,-.2,1),e).normalize(),l.pole.lerp(Q.set(t*.7,.1,-.7),e).normalize()}writeDown(e,t,n,r,i,a,o,s){let c=this.torso,l=1-s;this.downStand=s,c.hips.copy(e.hips),c.hipsYaw=e.hipsYaw,c.hipsPitch=e.hipsPitch,c.hipsRoll=e.hipsRoll,c.shouldersYaw=e.shouldersYaw,c.spinePitch=e.spinePitch,c.spineRoll=c.spineRoll*s+e.spineRoll,c.headPitch=e.headPitch,c.headYaw=c.headYaw*s+e.turn,c.headRoll=c.headRoll*s+e.headRoll,c.headOffset.multiplyScalar(s),c.headOffset.z-=o,n.position.copy(e.leadHand),r.position.copy(e.rearHand),xL(n,t,e.palmsDown,l),xL(r,-t,e.palmsDown,l),i.position.copy(e.leadFoot),a.position.copy(e.rearFoot),i.toe.lerp(uL.set(.2*t,0,1).normalize(),l).normalize(),a.toe.lerp(uL.set(-.2*t,0,1).normalize(),l).normalize(),i.heel=e.leadHeel,a.heel=e.rearHeel;let u=uL.set(0,0,1).applyEuler(vL.set(e.hipsPitch,e.hipsYaw,e.hipsRoll,`YXZ`));if(i.pole.lerp(u,l),a.pole.lerp(u,l),e.ownJoints>0){let t=e.ownJoints*l;ML(i.pole,e.leadKnee,t),ML(a.pole,e.rearKnee,t),ML(n.pole,e.leadElbow,t),ML(r.pole,e.rearElbow,t),ML(n.knuckles,e.leadKnuckles,t),ML(n.palm,e.leadPalm,t),ML(r.knuckles,e.rearKnuckles,t),ML(r.palm,e.rearPalm,t)}}calmInjuries(){this.armLimp.fill(0),this.armSnap.fill(0),this.kneeGive.fill(0),this.lostLean=0,this.cover=0,this.hunch=0,this.curl=0,this.faint=0,this.retching=0,this.daze=0,this.stepPace.fill(1),this.stepLift.fill(1),this.stepSlack=1,this.hurt=!1,this.dropDangles()}dropDangles(){for(let e=0;e<2;e+=1)this.armDangle[e].live=!1,this.forearmDangle[e].live=!1}stepInjuries(e){this.retchTime=Math.max(0,this.retchTime-e);let t=this.posedInjuries>1||this.faintTarget>0||this.retchTime>0||this.dazed;if(!t&&!this.hurt)return;let n=this.downState===`up`,r=0;for(let t=0;t<2;t+=1){let n=this.armCarry[t];this.armLimp[t]=wF(this.armLimp[t],+(n===`dead`||n===`gone`),OI,e),this.armSnap[t]=wF(this.armSnap[t],+(n===`snapped`),OI,e),this.kneeGive[t]=wF(this.kneeGive[t],+!!this.kneeBlown[t],8,e),r=Math.max(r,this.armLimp[t],this.armSnap[t],this.kneeGive[t])}let i=this.armCarry[0],a=this.armCarry[1],o=i===`whole`||i===`stump`,s=a===`whole`||a===`stump`;this.cover=wF(this.cover,o===s?0:o?1:-1,6,e),this.lostLean=wF(this.lostLean,(i===`gone`)-+(a===`gone`),4,e),this.hunch=wF(this.hunch,+!!this.gutted,5,e),this.curl=wF(this.curl,+!!this.liver,4,e),this.faint=wF(this.faint,this.faintTarget,2.5,e);let c=this.retchTime>0&&n;this.retching=wF(this.retching,+!!c,c?12:5,e);let l=this.dazed&&n;if(this.daze=wF(this.daze,+!!l,l?8:5,e),this.dazeTime=this.daze>.001?this.dazeTime+e:0,r=Math.max(r,Math.abs(this.cover),Math.abs(this.lostLean),this.hunch,this.curl,this.faint,this.retching,this.daze),!t&&r<.001){this.calmInjuries();return}this.hurt=!0;let u=this.hunch,d=this.faint,f=this.daze;this.stepSlack=(1-.3*u)*(1-.55*f);for(let e=0;e<2;e+=1){let t=this.kneeGive[e],n=this.kneeGive[1-e];this.stepPace[e]=(1-.4*n)*(1+.25*t)*(1-.25*u)*(1+.15*d)*(1+.2*f),this.stepLift[e]=(1-.5*t)*(1-.6*u)*(1-.75*d)*(1-.4*f)}}stepDeath(e){if(!(!this.dead||this.throe>=DI.length))for(this.deathAge+=e;this.throe=DI[this.throe].at;){let e=DI[this.throe];this.ragdoll?.twitch(e.part,(this.throe+this.throeSide)%2,e.speed),this.throe+=1}}stumble(e,t,n){let r=this.dazeTime;t.add(this.scratchD.set(Math.sin(r*1.7+e*2.1)*.07,0,Math.sin(r*1.25+e*1.3)*.06).multiplyScalar(this.daze).applyAxisAngle(XL,n))}applyHurtStance(e,t,n,r,i){let a=this.torso,o=0,s=0,c=0,l=this.hunch;l>.001&&(s+=.3*l,o+=.045*l,a.hipsPitch+=.06*l,a.headPitch+=.12*l);let u=this.curl;u>.001&&(s+=.1*u,a.spineRoll+=.21*u,a.headRoll+=.08*u,c+=.02*u,this.hand.R.position.y-=.08*u);let d=this.lostLean;Math.abs(d)>.001&&(a.spineRoll+=.15*d,c+=.025*d,a.headRoll-=.05*d);let f=this.faint;if(f>.001){let t=Math.sin(e*1.15),i=Math.sin(e*.83+1.3);a.hips.x+=t*.09*f,a.hips.z+=i*.06*f,a.hipsRoll+=t*.05*f,a.spineRoll+=Math.sin(e*1.15-.7)*.2*f,s+=(.17+i*.06)*f,o+=.03*f+(.06+.04*(.5+.5*Math.sin(e*2.6)))*f*f,a.headPitch+=(.4+Math.sin(e*.9+.4)*.14)*f,a.headRoll+=Math.sin(e*.7)*.36*f,a.headYaw+=Math.sin(e*.53+2)*.18*f,n.position.y-=.32*f,r.position.y-=.27*f,n.position.z-=.07*f}for(let e=0;e<2;e+=1){let t=this.kneeGive[e];if(t<=.001)continue;let n=e===0?1:-1,r=e===0?this.foot.L:this.foot.R,i=e===0?this.foot.R:this.foot.L,s=this.feet[1-e],c=s.stepping?Math.sin(s.progress*Math.PI)*t:0,l=t-c;a.hips.x+=(i.position.x-a.hips.x)*.25*l,a.hips.z+=(i.position.z-a.hips.z)*.18*l,o+=.085*c+.01*l,a.hipsRoll-=n*.16*c,a.spineRoll+=n*.13*c,r.heel+=.3*l,r.pole.x-=n*(.35*t+.9*c),r.pole.normalize()}if(a.hips.x+=Math.cos(a.hipsYaw)*c,a.hips.z-=Math.sin(a.hipsYaw)*c,o!==0||s!==0){a.hips.y-=o,a.spinePitch+=s;let e=o+s*XI,t=s*YI;i.y-=e,i.z+=t,n.position.y-=e,n.position.z+=t,r.position.y-=e,r.position.z+=t}let p=this.cover;if(Math.abs(p)>.001){let e=p>0?this.hand.L:this.hand.R,n=Math.abs(p);e.position.x+=(ZI*t-e.position.x)*.7*n,e.position.y+=.03*n,e.position.z+=.03*n}}applyHurtActs(e,t,n,r){let i=this.torso,a=G.lerp,o=+(t>0),s=this.armCarry[o]===`whole`?o:this.armCarry[1-o]===`whole`?1-o:-1,c=this.retching*(1-.7*this.punchCommit);if(c>.001){let t=Math.max(0,Math.sin(e*10.5))**2;i.hips.y=a(i.hips.y,VM.hipsHeight-.13-t*.02,c),i.hips.z=a(i.hips.z,-.08,c),i.hipsPitch=a(i.hipsPitch,.36,c),i.spinePitch=a(i.spinePitch,.78+t*.12,c),i.spineRoll=a(i.spineRoll,0,c),i.headPitch=a(i.headPitch,1.3+t*.15,c),i.headYaw=a(i.headYaw,0,c),i.headRoll=a(i.headRoll,0,c),i.headOffset.multiplyScalar(1-c);let n=s<0?o:1-s;if(this.armCarry[n]===`whole`){let e=n===0?1:-1,t=n===0?this.hand.L:this.hand.R;t.position.lerp(Q.set(e*.19,.62,n===o?-.02:.15),c),t.pole.lerp(Q.set(e*.9,.1,-.4),c).normalize(),t.knuckles.lerp(Q.set(-e*.2,-.7,.6),c).normalize(),t.palm.lerp(Q.set(0,-.6,-.8),c).normalize()}}let l=Math.max(Math.abs(this.slip),this.weave,this.pull),u=EF(1-this.guardHigh-this.guardLow,0,1)*(1-this.punchCommit)*(1-l)*(1-this.clinchWeight),d=this.punchActive&&s===(this.punchHand===`left`?0:1)?EF(this.punchReach*4,0,1):0,f=Math.max(c,this.hunch*u)*(1-d);f>.001&&s>=0&&this.clutchBelly(s,f);let p=this.daze;if(p>.001){let e=this.dazeTime,o=EM(.7,1.6,e),s=Math.sin(e*2.2),c=Math.sin(e*1.45+.9),l=VM.bladeYaw*t;i.hips.x=a(i.hips.x,s*.06,p),i.hips.z=a(i.hips.z,c*.045,p),i.hips.y=a(i.hips.y,VM.hipsHeight-.08-Math.sin(e*4.4+1)*.02,p),i.hipsYaw=a(i.hipsYaw,l*.8,p),i.hipsPitch=a(i.hipsPitch,.04,p),i.hipsRoll=a(i.hipsRoll,s*.05,p),i.shouldersYaw=a(i.shouldersYaw,l*.65,p),i.spinePitch=a(i.spinePitch,.24+c*.07,p),i.spineRoll=a(i.spineRoll,Math.sin(e*2.2-.9)*.13,p),i.headYaw=a(i.headYaw,o*Math.sin(e*1.1+2)*.3,p),i.headPitch=a(i.headPitch,.95-o*(.28+Math.sin(e*1.3)*.25),p),i.headRoll=a(i.headRoll,o*Math.sin(e*1.9)*.42,p),i.headOffset.multiplyScalar(1-p),n.heel=a(n.heel,0,p),r.heel=a(r.heel,0,p)}}clutchBelly(e,t){let n=this.torso,r=e===0?this.hand.L:this.hand.R,i=e===0?1:-1,a=n.hipsYaw+(n.shouldersYaw-n.hipsYaw)*.25,o=n.hipsPitch+n.spinePitch*.2;r.position.lerp(Q.set(i*.05,.17,.19+o*.08).applyAxisAngle(XL,a).add(n.hips),t),r.knuckles.lerp(Q.set(-i*.9,-.3,.2).applyAxisAngle(XL,a),t).normalize(),r.palm.lerp(Q.set(-i*.1,.15,-1).applyAxisAngle(XL,a),t).normalize(),r.pole.lerp(Q.set(i*.85,-.35,-.4).applyAxisAngle(XL,a),t).normalize()}dangleArms(e){let t=this.daze,n=this.boxer.rig,r=n.bones;yM(r.hips,this.trunkLow),yM(r.upperChest,this.trunkHigh),this.trunkLow.addScaledVector(QI.subVectors(this.trunkLow,this.trunkHigh).normalize(),KI);let i=this.ragdoll?.handingOver===!0;for(let a=0;a<2;a+=1){let o=Math.max(this.armLimp[a],t),s=this.armSnap[a],c=this.armDangle[a],l=this.forearmDangle[a];if(o<=.001&&(c.live=!1),s<=.001&&(l.live=!1),o<=.001&&s<=.001)continue;let u=a===0,d=u?1:-1,f=u?r.shoulderL:r.shoulderR,p=u?r.elbowL:r.elbowR,m=u?r.gloveL:r.gloveR,h=u?n.metrics.armL:n.metrics.armR;if(o>.001){let t=yM(m,$I);if(bM(m,cL),this.armCarry[a]===`dead`){let e=yM(f,eL);e.y-=kI*this.armLimp[a],n.aimAt(u?r.clavicleL:r.clavicleR,e,`z`),f.updateWorldMatrix(!1,!1)}let s=yM(f,eL),l=(h.upper+h.lower)*AI;if(!c.live){let e=o>WI&&!i;TI(c,e?QI.set(s.x,s.y-l,s.z):t,s),e&&this.holdDangle(c.at,s,l,!1,null)}let g=this.punchActive&&this.punchHand===`left`===u?this.punchReach:0;this.swing(c,s,l,!1,e,jI,MI,t,g*PI);let _=tL.set(d*.3,.15+3*EF(1-s.y/JI,0,1),-1).lerp(u?this.hand.L.pole:this.hand.R.pole,1-o).applyAxisAngle(XL,this.yaw);n.solveLimb(f,p,h,t.lerp(c.at,o),_,`z`,u?1:-1,.012),m.updateWorldMatrix(!1,!1),xM(nL.subVectors(yM(m,$I),yM(p,QI)).normalize(),tL.set(-d,0,.2).applyAxisAngle(XL,this.yaw),`z`,lL),n.setWorldRotation(m,cL.slerp(lL,o))}if(s>.001){let t=yM(p,eL),r=yM(m,$I);bM(m,cL);let a=Math.max(0,-(t.y-yM(f,QI).y)/h.upper),o=sL.set(d*(FI+II*a*a),-1,0).applyAxisAngle(XL,this.yaw).normalize();l.live||(TI(l,s>WI&&!i?QI.set(t.x,t.y-h.lower,t.z):r,t),this.holdDangle(l.at,t,h.lower,!0,o)),this.swing(l,t,h.lower,!0,e,jI,NI,null,0,o);let c=nL.subVectors(r,t).lerp(QI.subVectors(l.at,t),s).normalize(),u=tL.setFromMatrixColumn(p.matrixWorld,2).lerp(QI.setFromMatrixColumn(p.matrixWorld,0).multiplyScalar(d),s);n.setWorldFrame(p,c,u,`z`),m.updateWorldMatrix(!1,!1),xM(QI.copy(c).addScaledVector(fL,.9).normalize(),tL.set(-d,.2,-.4).applyAxisAngle(XL,this.yaw),`z`,lL),n.setWorldRotation(m,cL.slerp(lL,s))}}}swing(e,t,n,r,i,a,o,s,c,l=null){let u=e.at,d=e.velocity;(e.carried||t.distanceToSquared(e.pivot)>UI*UI)&&(u.add(t).sub(e.pivot),d.set(0,0,0),e.pivot.copy(t),e.carried=!1);let f=i>0?Math.min(VI,Math.ceil(i/BI)):0,p=f>0?i/f:0;for(let i=1;i<=f;i+=1)rL.copy(u),d.addScaledVector(a,p),s!==null&&c>0&&d.addScaledVector(iL.subVectors(s,u),c*p),d.multiplyScalar(Math.exp(-o*p)),u.addScaledVector(d,p),this.holdDangle(u,iL.lerpVectors(e.pivot,t,i/f),n,r,l),d.subVectors(u,rL).divideScalar(p).clampLength(0,HI);f===0&&this.holdDangle(u,t,n,r,l),e.pivot.copy(t)}holdDangle(e,t,n,r,i){let a=this.trunkLow,o=aL.subVectors(this.trunkHigh,a);for(let s=0;s<2;s+=1){let s=EF(oL.subVectors(e,a).dot(o)/Math.max(1e-6,o.lengthSq()),0,1),c=oL.addScaledVector(o,-s).length();c1e-4&&e.addScaledVector(oL,(GI-c)/c),e.y=Math.max(e.y,qI);let l=oL.subVectors(e,t),u=l.length();if(u<1e-6?e.set(t.x,t.y-n,t.z):(r||u>n)&&e.copy(t).addScaledVector(l,n/u),i===null)continue;l.subVectors(e,t);let d=l.dot(i);if(d>=n*RI)continue;let f=l.addScaledVector(i,-d).length();e.copy(t).addScaledVector(i,n*(f>1e-6?RI:1)),f>1e-6&&e.addScaledVector(l,n*zI/f)}}applyDislocation(){if(this.dislocation!==`jaw`)return;let e=this.boxer.bone(`head`);e!==null&&(e.quaternion.multiply(SI),e.updateWorldMatrix(!1,!0))}dispose(){this.stool.dispose(),this.enswell.dispose(),this.bottle.dispose(),this.boxer.dispose()}},oI=.44,sI=.2,cI=.75,lI=.26,uI=1.2,dI=48,fI=14,pI=1.34,mI=80,hI=56,gI=24,_I=4,vI=1.5,yI=60,bI=4,xI=.15,Q=new q,SI=new rg().setFromEuler(new Lg(.08,.2,-.22)),CI=[`shoulder_left_dislocated`,`shoulder_right_dislocated`,`arm_left_broken`,`arm_right_broken`,`forearm_left_severed`,`forearm_right_severed`,`arm_left_torn`,`arm_right_torn`,`knee_left_blown`,`knee_right_blown`,`disemboweled`,`liver_ruptured`];function wI(){return{at:new q,velocity:new q,pivot:new q,live:!1,carried:!1}}function TI(e,t,n){e.at.copy(t),e.velocity.set(0,0,0),e.pivot.copy(n),e.live=!0,e.carried=!1}function EI(e){e.velocity.set(0,0,0),e.carried=!0}var DI=[{at:1.5,part:`leg`,speed:2.8},{at:2.1,part:`back`,speed:2.4},{at:2.6,part:`arm`,speed:2.6},{at:3.3,part:`leg`,speed:1.9},{at:4,part:`back`,speed:1.4},{at:4.7,part:`arm`,speed:1.2}],OI=12,kI=.05,AI=.985,jI=new q(0,-9.81,0),MI=2.4,NI=3,PI=22,FI=.7,II=1.8,LI=.4,RI=Math.cos(LI),zI=Math.sin(LI),BI=1/90,VI=4,HI=8,UI=.35,WI=.5,GI=.25,KI=.3,qI=.07,JI=.6,YI=.36,XI=.05,ZI=-.06,QI=new q,$I=new q,eL=new q,tL=new q,nL=new q,rL=new q,iL=new q,aL=new q,oL=new q,sL=new q,cL=new rg,lL=new rg,uL=new q,dL=new q(0,0,1),fL=new q(0,-1,0),pL=new q(0,0,1),mL=new q(1,0,0),hL=new q(-1,0,0),gL=.04,_L=new rg,vL=new Lg,yL={pole:TM(.4,.9,.2),knuckles:TM(.6,.2,-.75).normalize(),palm:TM(0,1,.2).normalize()},bL={pole:TM(.6,.2,-.7),knuckles:TM(.25,-.1,1).normalize(),palm:TM(0,-1,.1).normalize()};function xL(e,t,n,r){uL.lerpVectors(yL.pole,bL.pole,n),uL.x*=t,e.pole.lerp(uL,r),uL.lerpVectors(yL.knuckles,bL.knuckles,n),uL.x*=t,e.knuckles.lerp(uL.normalize(),r).normalize(),uL.lerpVectors(yL.palm,bL.palm,n),uL.x*=t,e.palm.lerp(uL.normalize(),r).normalize()}function SL(e={}){return{hips:new q,hipsYaw:0,hipsPitch:0,hipsRoll:0,shouldersYaw:0,spinePitch:0,spineRoll:0,headPitch:0,headRoll:0,leadHand:new q,rearHand:new q,leadFoot:new q,rearFoot:new q,leadHeel:0,rearHeel:0,palmsDown:0,turn:0,leadKnee:new q(0,0,1),rearKnee:new q(0,0,1),leadElbow:new q(0,-1,0),rearElbow:new q(0,-1,0),leadKnuckles:new q(0,0,1),leadPalm:new q(0,-1,0),rearKnuckles:new q(0,0,1),rearPalm:new q(0,-1,0),ownJoints:0,...e}}var CL=SL({hips:TM(0,.14,-.4),hipsPitch:-1.42,spinePitch:.1,headPitch:-.5,leadHand:TM(.52,.1,-.62),rearHand:TM(-.5,.1,-.7),leadFoot:TM(.17,0,.16),rearFoot:TM(-.16,0,-.02)}),wL=SL({hips:TM(.22,0,0),hipsYaw:-.35,hipsRoll:-.25,shouldersYaw:-.2,leadFoot:TM(.05,0,0),rearFoot:TM(.05,0,0)}),TL=SL({hips:TM(0,.25,.32),hipsPitch:1.5,spinePitch:.05,headPitch:.2,palmsDown:1,leadHand:TM(.34,.12,.78),rearHand:TM(-.3,.12,.62),leadFoot:TM(.16,0,-.82),rearFoot:TM(-.15,0,-.86),leadHeel:1.3,rearHeel:1.3}),EL=SL({hips:TM(.12,0,0),hipsYaw:.3,hipsRoll:.15,shouldersYaw:.15,leadFoot:TM(.04,0,0),rearFoot:TM(.04,0,0)}),DL=SL({hips:TM(.05,.52,-.2),hipsYaw:VM.bladeYaw*.15,hipsPitch:1.38,shouldersYaw:VM.bladeYaw*.15,spinePitch:.35,headPitch:1,palmsDown:1,leadHand:TM(.2,.115,.36),rearHand:TM(-.2,.115,.32),leadFoot:TM(.15,0,-.74),rearFoot:TM(-.14,0,-.78),leadHeel:1.25,rearHeel:1.25}),OL=SL({hips:TM(0,.47,-.05),hipsYaw:VM.bladeYaw*.12,hipsPitch:.2,shouldersYaw:VM.bladeYaw*.4,spinePitch:.3,headPitch:.2,palmsDown:1,leadHand:TM(.15,.68,.32),rearHand:TM(-.26,.42,.02),leadFoot:TM(.15,0,.36),rearFoot:TM(-.13,0,-.7),rearHeel:1.2});function kL(e,t,n,r,i,a){return e.hips.set(t.hips.x*r,t.hips.y,t.hips.z),e.hipsYaw=t.hipsYaw*r,e.hipsPitch=t.hipsPitch,e.hipsRoll=t.hipsRoll*r,e.shouldersYaw=t.shouldersYaw*r,e.spinePitch=t.spinePitch,e.spineRoll=0,e.headPitch=t.headPitch,e.headRoll=0,HM(t.leadHand,r,e.leadHand),HM(t.rearHand,r,e.rearHand),HM(t.leadFoot,r,e.leadFoot).y+=a,HM(t.rearFoot,r,e.rearFoot).y+=a,e.leadHeel=t.leadHeel,e.rearHeel=t.rearHeel,e.palmsDown=t.palmsDown,e.turn=0,e.ownJoints=0,n===null||i===0||(e.hips.addScaledVector(n.hips,i),e.hipsYaw+=n.hipsYaw*i,e.hipsPitch+=n.hipsPitch*i,e.hipsRoll+=n.hipsRoll*i,e.shouldersYaw+=n.shouldersYaw*i,e.spinePitch+=n.spinePitch*i,e.headPitch+=n.headPitch*i,e.leadHand.addScaledVector(n.leadHand,i),e.rearHand.addScaledVector(n.rearHand,i),e.leadFoot.addScaledVector(n.leadFoot,i),e.rearFoot.addScaledVector(n.rearFoot,i)),e}var AL=e=>Math.atan2(Math.sin(e),Math.cos(e)),jL=new q;function ML(e,t,n){if(n<=0)return e;e.normalize();let r=e.angleTo(t);return r<1e-4?e:(jL.crossVectors(e,t),jL.lengthSq()<1e-8&&jL.crossVectors(e,Math.abs(e.y)<.9?XL:dL),e.applyAxisAngle(jL.normalize(),r*Math.min(1,n)))}function NL(e,t,n,r){let i=t+AL(e.x-t),a=n+AL(e.y-n),o=r+AL(e.z-r),s=t+AL(Math.PI-e.x-t),c=n+AL(e.y+Math.PI-n),l=r+AL(e.z+Math.PI-r);return Math.abs(i-t)+Math.abs(a-n)+Math.abs(o-r)<=Math.abs(s-t)+Math.abs(c-n)+Math.abs(l-r)?e.set(i,a,o,`YXZ`):e.set(s,c,l,`YXZ`)}function PL(e,t){return e.hips.add(t),e.leadHand.add(t),e.rearHand.add(t),e.leadFoot.add(t),e.rearFoot.add(t),e}var FL=wE*.72-.05,IL=.78,LL=.5,RL=Array.from({length:8},()=>new q),zL=[.17,.22,.22,.13,.13,.12,.12,.2],BL=[[!1,1,0],[!1,0,.15],[!1,-1,.3],[!0,1,.4],[!0,0,.5],[!0,-1,.6]];function VL(e,t){return e<-FL&&t>FL?-(e+t)/2:e<-FL?-FL-e:t>FL?FL-t:0}function HL(e,t){return UL(e,t,t,0)}function UL(e,t,n,r){let i=G.lerp;return e.hips.copy(t.hips).lerp(n.hips,r),e.hipsYaw=i(t.hipsYaw,n.hipsYaw,r),e.hipsPitch=i(t.hipsPitch,n.hipsPitch,r),e.hipsRoll=i(t.hipsRoll,n.hipsRoll,r),e.shouldersYaw=i(t.shouldersYaw,n.shouldersYaw,r),e.spinePitch=i(t.spinePitch,n.spinePitch,r),e.spineRoll=i(t.spineRoll,n.spineRoll,r),e.headPitch=i(t.headPitch,n.headPitch,r),e.headRoll=i(t.headRoll,n.headRoll,r),e.leadHand.copy(t.leadHand).lerp(n.leadHand,r),e.rearHand.copy(t.rearHand).lerp(n.rearHand,r),e.leadFoot.copy(t.leadFoot).lerp(n.leadFoot,r),e.rearFoot.copy(t.rearFoot).lerp(n.rearFoot,r),e.leadHeel=i(t.leadHeel,n.leadHeel,r),e.rearHeel=i(t.rearHeel,n.rearHeel,r),e.palmsDown=i(t.palmsDown,n.palmsDown,r),e.turn=i(t.turn,n.turn,r),ML(e.leadKnee.copy(t.leadKnee),n.leadKnee,r),ML(e.rearKnee.copy(t.rearKnee),n.rearKnee,r),ML(e.leadElbow.copy(t.leadElbow),n.leadElbow,r),ML(e.rearElbow.copy(t.rearElbow),n.rearElbow,r),ML(e.leadKnuckles.copy(t.leadKnuckles),n.leadKnuckles,r),ML(e.leadPalm.copy(t.leadPalm),n.leadPalm,r),ML(e.rearKnuckles.copy(t.rearKnuckles),n.rearKnuckles,r),ML(e.rearPalm.copy(t.rearPalm),n.rearPalm,r),e.ownJoints=i(t.ownJoints,n.ownJoints,r),e}var WL=3;function GL(e,t,n){if(n===null)return null;let r=t+n;return e===null||Math.abs(r-e)>WL?r:e}function KL(e){return(1-EM(hI,mI,e))*EM(_I,gI,e)}function qL(){let e=new t_;e.name=`enswell`,e.visible=!1;let t=new Iy(3.2,3.2,.9,20),n=new Iy(.8,.8,6,10),r=new Ab({color:13159634,roughness:.3,metalness:.9}),i=new Y(t,r);i.rotation.x=Math.PI/2,i.position.set(0,9.5,3.4),e.add(i);let a=new Y(n,r);return a.position.set(0,5.5,2.4),e.add(a),{group:e,dispose:()=>{t.dispose(),n.dispose(),r.dispose()}}}function JL(){let e=new t_;e.name=`bottle`,e.visible=!1;let t=new Iy(3.3,3.3,15,18),n=new Iy(1.3,3.3,3,18),r=new Iy(.7,1.1,3.2,10),i=new Ab({color:14280430,roughness:.32,metalness:0}),a=new Ab({color:1920728,roughness:.5,metalness:0}),o=new Y(t,i);o.position.set(0,9,2.6);let s=new Y(n,i);s.position.set(0,18,2.6);let c=new Y(r,a);return c.position.set(0,21,2.6),e.add(o,s,c),{group:e,dispose:()=>{t.dispose(),n.dispose(),r.dispose(),i.dispose(),a.dispose()}}}function YL(){let e=new t_;e.name=`stool`,e.visible=!1;let t=new Iy(.17,.17,.035,18),n=new Iy(.012,.014,.42,8),r=new Ab({color:13222581,roughness:.85}),i=new Ab({color:2764083,roughness:.45,metalness:.6}),a=new Y(t,r);a.position.y=.4225,a.castShadow=!0,e.add(a);for(let t=0;t<4;t+=1){let r=Math.PI/4+t*Math.PI/2,a=new Y(n,i);a.position.set(Math.cos(r)*.13,.42/2,Math.sin(r)*.13),a.rotation.set(-Math.sin(r)*.12,0,Math.cos(r)*.12),a.castShadow=!0,e.add(a)}return{group:e,dispose:()=>{t.dispose(),n.dispose(),r.dispose(),i.dispose()}}}var XL=new q(0,1,0),ZL=6,QL=3,$L=1.5,eR=2.5,tR=1.5,nR=.55,rR=2.1,iR=.42,aR=.22,oR=.08,sR=.5,cR=.5,lR=new Set([`hit`,`counter_hit`,`block`,`perfect_block`,`referee_hit`]),uR=new Set([`slip_left`,`slip_right`,`weave`,`pull`]),dR=40,fR=y/a,pR=.12,mR=30,hR=2;function gR(e,t,n){if(e0;case`forearm_left`:return t===`glove_left`||o&&yA(r,i,a,1)>0;case`forearm_right`:return t===`glove_right`||o&&yA(r,i,a,-1)>0;case`arm_left`:return t===`glove_left`||o&&bA(r,i,a,1)>0;case`arm_right`:return t===`glove_right`||o&&bA(r,i,a,-1)>0;case`leg_left`:return r>=0&&(t===`shoes`||o&&i<60);case`leg_right`:return r<0&&(t===`shoes`||o&&i<60);case`upper_body`:return t===`head`||t===`glove_left`||t===`glove_right`||o&&xA(r,i,a)>0;case`torso`:return t===`pants`||o&&i>=60&&bA(r,i,a,1)<=0&&bA(r,i,a,-1)<=0}}var yR={head:`BoxerHead`,body:`BoxerBody`,glove_left:`BoxerGloveLeft`,glove_right:`BoxerGloveRight`,pants:`BoxerPants`,shoes:`BoxerShoes`},bR=new WeakMap;function xR(e,t){let n=bR.get(e);if(n===void 0){n={};let t=new Map(Object.entries(yR).map(([e,t])=>[t,e]));e.root.traverse(e=>{let r=e instanceof Hv?t.get(e.name):void 0;r!==void 0&&(n[r]=e)}),bR.set(e,n)}return n[t]??null}var SR=[`left`,`right`],CR=new q(0,1,0),wR=new q(0,-1,0),TR=15129792,ER=6032400,DR=9313310,OR=4982537,kR=14200392,AR=2228997,jR=14263970,MR=8270912,NR=11618383,PR=15524550,FR=12866653,IR=13602176,LR=9384504,RR=new J,zR=new J,BR=new q,VR=G.smoothstep;function HR(e,t){e.deleteAttribute(`uv`);let n=e.getAttribute(`position`),r=new Float32Array(n.count*3);for(let e=0;eo/2-.001){let t=Math.atan2(BR.z,BR.x);BR.y+=i<1e-4?-n*.8:n*(.5*Math.sin(t*3+e[1])+.35*Math.sin(t*5+e[2]))}c.setXYZ(t,BR.x,BR.y+o/2,BR.z*r)}return s.computeVertexNormals(),HR(s,(t,r)=>{let i=1-VR(t.y/o,.15,.42)*(.85+.15*Math.sin(Math.atan2(t.z,t.x)*4+e[0]));r.setHex(TR).lerp(zR.setHex(OR),i),Math.hypot(t.x,t.z)o*.5&&r.setHex(ER)}),s.applyQuaternion(new rg().setFromUnitVectors(CR,a.normalize())),s.translate(i.x,i.y,i.z),s}function GR(e,t,n,r=!1){return HR(new yb(new Jy(e.map(e=>new q(...e)),r),e.length*5,t,7,r),n)}var KR=[0,123.6,-3.2],qR=[4.5,4,5];function JR(){let e=new _b(1,40,24,0,Math.PI*2,0,Math.PI*.6),t=e.getAttribute(`position`),n=new Float32Array(t.count);for(let e=0;e{let i=n[r];r+=1,t.setHex(MR).lerp(zR.setHex(jR),VR(i,-.5,.45)),(i<-1||Math.sin(e.x*.9+e.z*1.3)>.72)&&t.lerp(zR.setHex(DR),.7)})}function YR(){let e=[[1,.2,TR],[.9,0,TR],[.82,0,ER],[.74,0,TR],[.66,-.9,OR]],t=[],n=[],r=[];for(let[i,[a,o,s]]of e.entries())for(let e=0;e<32;e+=1){let c=e/32*Math.PI*2;if(t.push(Math.cos(c)*5.6*a,124+o,-3.3+Math.sin(c)*6.4*a),RR.setHex(s).multiplyScalar(.85+.15*Math.sin(c*11+i)),n.push(RR.r,RR.g,RR.b),i===0)continue;let l=(e+1)%32;r.push((i-1)*32+e,i*32+e,(i-1)*32+l,(i-1)*32+l,i*32+e,i*32+l)}let i=new iv;return i.setAttribute(`position`,new K_(t,3)),i.setAttribute(`color`,new K_(n,3)),i.setIndex(r),i.computeVertexNormals(),i}var XR=[0,112.9,-.4],ZR=9,QR=new q(0,-.93,.37).normalize(),$R=.95;function ez(){let e=new Py(1.5,6,6,16,8),t=e.getAttribute(`position`);for(let e=0;e0?.5*(1-VR(r,0,.45)):0,a=.5*Math.sin(n*5)*(1-n);t.setXYZ(e,BR.x*G.lerp(.9,1.1,Math.sin(n*Math.PI))+a*.4,BR.y-ZR/2,(BR.z-i)*.3+.35*r*r+1.3*n*n)}return e.computeVertexNormals(),HR(e,(e,t)=>{let n=-e.y/ZR,r=Math.sin(e.y*2.6+e.x*2.1)*Math.sin(e.x*3.3-e.y*1.2);t.setHex(FR).multiplyScalar(.8+.2*r).lerp(zR.setHex(OR),.8*(1-VR(n,0,.35))),(r>.45||n>.88)&&t.lerp(zR.setHex(DR),.65)})}function tz(){let e=[],t=new _b(1,18,12,Math.PI,Math.PI);t.scale(3.3,2.5,3.2),t.translate(0,113.3,-.5),e.push(HR(t,(e,t)=>{t.setHex(AR).lerp(zR.setHex(DR),VR(Math.hypot(e.x,e.y-112.6,(e.z+3)*.7),.7,2.6))}));let n=new Fy(1,20);n.rotateX(Math.PI/2),n.scale(3.3,1,3.9),n.translate(0,115.25,.5),e.push(HR(n,(e,t)=>{t.setHex(LR).multiplyScalar(.75+.25*Math.sin(e.z*5)).lerp(zR.setHex(AR),1-VR(e.z,-3,.5))}));let r=[];for(let t=0;t<14;t+=1){let n=-1.75+t/13*3.5,i=1-Math.abs(n)/1.75,a=t===4||t===9?1.35:G.lerp(.85,1.2,i),o=new Iy(.3,t===4||t===9?.16:.37,a,6);o.scale(1,1,G.lerp(1.15,.55,i)),o.rotateY(n);let s=Math.sin(n)*2.75,c=.9+Math.cos(n)*3.1;o.translate(s,114.9-a/2,c),e.push(HR(o,(e,t)=>{t.setHex(PR).lerp(zR.setHex(DR),.8*VR(e.y,114.3,114.9))})),r.push([s,114.95,c])}return e.push(GR(r,.45,NR)),UR(e)}function nz(e){return UR([WR([e*29.4,103.8,-4.2],[e*32.9,104.1,-4],.85),WR([e*29.4,102,-6.2],[e*32.3,101.8,-6.5],.7)])}function rz(e){let t=new _b(1,12,9);return t.scale(.9,1.7,1.5),t.translate(e*13.3,103.4,-5.5),HR(t,(e,t)=>{t.setHex(15327954).lerp(zR.setHex(DR),Math.sin(e.y*3.1+e.z*2.3)>.4?.75:.1)})}function iz(){return UR([HR(new Iy(2,2.1,1.8,10).translate(0,80.4,-5.4),TR),HR(new Iy(1.8,1.8,.6,10).translate(0,81.6,-5.4),12563866),WR([0,81.9,-5.4],[.4,85.4,-5.8],1.9),GR([[.2,84.6,-5.6],[.3,86.6,-5.8],[.9,87.8,-5.2]],.55,15255984),GR([[-6.5,81.6,.5],[-3,82.6,3.6],[1.5,81.8,4.4],[6,82.8,2],[7,81.6,-2],[3.5,82.9,-1],[-1,81.7,.6],[-5,82.9,-2.6],[-7.2,81.5,-4]],1.25,IR,!0),GR([[4.5,83.6,1.6],[1,84.4,2.4],[-3,83.5,.6],[-2,84.2,-2.6],[2.5,83.6,-2.2]],1.05,12548720,!0),HR(new _b(1,10,7).scale(3.2,1.6,2.6).translate(-6,82.2,1.5),4854808)])}function az(e){return UR(NA.map((t,n)=>{let r=new q(-t[0],0,-2-t[2]).normalize();return WR([e*(t[0]+r.x*3),t[1]-.3,t[2]+r.z*3],[e*(t[0]-r.x*1.3),t[1]+.7-.3*n,t[2]-r.z*1.3+.7],.75,.5)}))}function oz(){let e=[];for(let t=0;t<5;t+=1){let n=.5+t*1.26,r=Math.cos(n),i=Math.sin(n);e.push(WR([r*5.8,99.5+i*5.8,3.9],[r*2.9,99.5+i*2.9,2.4],.7,.5)),e.push(WR([i*5.6,99.5-r*5.6,-9.6],[i*4.3,99.5-r*4.3,-12.8],.7,.5))}return UR(e)}var sz=new q,cz=new q,lz=new q,uz=new q,dz=new WeakMap;function fz(e,t,n){let r=e.getAttribute(`position`),i=e.getAttribute(`skinIndex`),a=e.getAttribute(`skinWeight`),o=new Map,s=new q;for(let e of t)o.has(e)||(o.set(e,o.size),s.add(BR.fromBufferAttribute(r,e)));s.multiplyScalar(1/o.size);let c=n.layers.length,l=[],u=[],d=[],f=[],p=new Map;for(let e of o.keys()){for(let[t,[o,c]]of n.layers.entries()){n.place(BR.fromBufferAttribute(r,e),s,o,sz),l.push(sz.x,sz.y,sz.z),RR.setHex(c).multiplyScalar(.8+.4*Math.abs(Math.sin(e*12.9898+t*4.1))),u.push(RR.r,RR.g,RR.b);for(let t=0;t<4;t+=1)d.push(i.getComponent(e,t)),f.push(a.getComponent(e,t))}for(let t=0;t<4;t+=1)p.set(i.getComponent(e,t),(p.get(i.getComponent(e,t))??0)+a.getComponent(e,t))}let m=o.size*c;if(n.middle!==null){n.place(s,s,1,sz),l.push(sz.x,sz.y,sz.z),RR.setHex(n.middle),u.push(RR.r,RR.g,RR.b);let e=[...p].sort((e,t)=>t[1]-e[1]).slice(0,4),t=e.reduce((e,[,t])=>e+t,0);for(let n=0;n<4;n+=1)d.push(e[n]?.[0]??0),f.push((e[n]?.[1]??0)/t)}let h=[],g=(e,t,r)=>{sz.fromArray(l,e*3),cz.fromArray(l,t*3),lz.fromArray(l,r*3),n.facing(BR.copy(sz).add(cz).add(lz).multiplyScalar(1/3),s,uz);let i=cz.sub(sz).cross(lz.sub(sz)).dot(uz)>=0;h.push(e,i?t:r,i?r:t)};for(let e=0;evoid a.copy(n).lerp(r,i).addScaledVector(e,-t*i),facing:(t,n,r)=>void r.copy(e),middle:AR}}var mz={layers:[[0,OR],[.4,OR],[1,AR]],place:(e,t,n,r)=>void r.set(G.lerp(e.x,t.x,.22*n),G.lerp(e.y,t.y,.22*n),G.lerp(e.z,t.z-Math.sign(e.z-t.z)*.6,n)),facing:(e,t,n)=>void n.set(t.x-e.x,t.y-e.y,0),middle:null},hz={nose:{bone:`head`,mesh:`head`,at:[0,117,5.3],axis:[0,-.3,1]},mouth:{bone:`head`,mesh:`head`,at:[0,114.3,4.6],axis:[0,-.35,1]},eye_left:{bone:`head`,mesh:`head`,at:VA[0],axis:[.2,0,1]},eye_right:{bone:`head`,mesh:`head`,at:VA[1],axis:[-.2,0,1]},ear_left:{bone:`head`,mesh:`head`,at:MA,axis:[1,-.2,0]},ear_right:{bone:`head`,mesh:`head`,at:[-MA[0],MA[1],MA[2]],axis:[-1,-.2,0]},skull:{bone:`head`,mesh:`head`,at:[0,127.5,-3],axis:[0,1,0]},neck:{bone:`neck`,mesh:`body`,at:[0,109,-2],axis:[0,1,0]},shoulder_left:{bone:`clavicleL`,mesh:`body`,at:[15,103.5,-5.5],axis:[1,0,0]},shoulder_right:{bone:`clavicleR`,mesh:`body`,at:[-15,103.5,-5.5],axis:[-1,0,0]},elbow_left:{bone:`shoulderL`,mesh:`body`,at:[31,102.8,-5.2],axis:[1,0,0]},elbow_right:{bone:`shoulderR`,mesh:`body`,at:[-31,102.8,-5.2],axis:[-1,0,0]},chest:{bone:`chest`,mesh:`body`,at:[0,99.5,5.6],axis:[0,0,1]},ribs_left:{bone:`chest`,mesh:`body`,at:NA[1],axis:[1,0,.3]},ribs_right:{bone:`chest`,mesh:`body`,at:[-NA[1][0],NA[1][1],NA[1][2]],axis:[-1,0,.3]},liver:{bone:`chest`,mesh:`body`,at:[-8.5,89.5,4.4],axis:[-.5,0,1]},belly:{bone:`spine`,mesh:`body`,at:IA,axis:[0,-.2,1]},waist:{bone:`spine`,mesh:`body`,at:[0,81.5,-1],axis:[0,1,0]},crotch:{bone:`hips`,mesh:`body`,at:[0,72,2],axis:[0,-1,.15]},knee_left:{bone:`kneeL`,mesh:`body`,at:FA,axis:[1,0,.2]},knee_right:{bone:`kneeR`,mesh:`body`,at:[-FA[0],FA[1],FA[2]],axis:[-1,0,.2]}},gz=[`skull`,`maw`,`chest`,`waist`,...SR.flatMap(e=>[`fracture`,`ribs`,`knee`,`elbow`,`shoulder`].map(t=>`${t}_${e}`))],_z={left:{sign:1,bone:`L`,ear:`leftEar`,face:`leftFace`,cheek:`leftCheek`,eye:`leftEye`,arm:`leftArm`,shoulder:`leftShoulder`,elbow:`leftElbow`,ribs:`leftRibs`,knee:`leftKnee`,smear:`leftShoulderSmear`},right:{sign:-1,bone:`R`,ear:`rightEar`,face:`rightFace`,cheek:`rightCheek`,eye:`rightEye`,arm:`rightArm`,shoulder:`rightShoulder`,elbow:`rightElbow`,ribs:`rightRibs`,knee:`rightKnee`,smear:`rightShoulderSmear`}},vz=class{boxer;headRaises=[];bodyRaises=[];gloveGone={left:!1,right:!1};eyeOut={left:!1,right:!1};eyeShut={left:!1,right:!1};gloved;flesh;owned=[];tongueTip=new q;tongueVelocity=new q;root=new q;rest=new q;reach=new q;matrix=new Dg;fit=new Dg;upperGone=!1;headHidden=!1;injuries=0;blood=`full`;hole=!1;jawHung=!1;pieces=new Map;geometries=[];skull=null;skullMount=new Dg;brain=null;tongue=null;bodyShadow=null;standIns=null;tongueHung=!1;constructor(e){this.boxer=e,this.gloved={left:e.gloveMesh(`left`).visible,right:e.gloveMesh(`right`).visible},this.flesh=new Ab({vertexColors:!0,roughness:.3,metalness:0,side:2}),bF(this.flesh)}apply(e,t){let n=0;for(let t=0;tc*3)&&(this.tongueHung=!0,l.copy(o).addScaledVector(s,c),u.set(0,0,0));let d=this.reach.copy(l);e>1e-4&&(u.y-=9.8*e,u.addScaledVector(BR.copy(o).addScaledVector(s,c).sub(l),60*e).multiplyScalar(Math.exp(-5*e)),d.addScaledVector(u,e)),d.sub(o).setLength(c),d.angleTo(s)>$R&&(BR.copy(d).addScaledVector(s,-d.dot(s)).setLength(Math.sin($R)*c),d.copy(s).multiplyScalar(Math.cos($R)*c).add(BR)),d.add(o),e>1e-4&&u.copy(d).sub(l).multiplyScalar(1/e),l.copy(d),r.quaternion.setFromUnitVectors(wR,BR.copy(l).sub(o).transformDirection(a.invert()))}compileStandIns(){if(this.standIns!==null)return this.standIns;let e=this.boxer;for(let e of gz)this.built(e);let t=[],n=[[e.headMesh,e.headInjury],[xR(e,`body`),e.bodyInjury]];for(let[e,r]of n)for(let n of[!1,!0]){let i=e===null?null:r.variant(n);if(e===null||i===null)continue;this.owned.push(i);let a=new Hv(e.geometry,i);if(a.bind(e.skeleton,e.bindMatrix),a.frustumCulled=!1,a.castShadow=e.castShadow,n){let e=r.shadowVariant();this.owned.push(e),a.customDepthMaterial=e}t.push(a)}this.brain!==null&&t.push(new Y(this.brain.geometry,this.flesh));let r=this.built(`waist`).find(e=>e instanceof Hv);if(r!==void 0){let e=new Hv(r.geometry,this.flesh);e.bind(r.skeleton,r.bindMatrix),e.frustumCulled=!1,t.push(e)}return this.standIns=t,t}clear(){this.upperGone=!1,this.hole=!1,this.injuries=0,this.show(),this.setPallor(0)}dispose(){this.clear();for(let e of this.standIns??[])e.removeFromParent();this.standIns=null;for(let e of this.pieces.values())for(let t of e)t.removeFromParent();for(let e of this.geometries)e.dispose();this.pieces.clear(),this.geometries.length=0,this.skull=this.brain=this.tongue=null,this.bodyShadow?.dispose(),this.bodyShadow=null;for(let e of this.owned)e.dispose();this.owned.length=0,this.flesh.dispose()}has(e){return!!(this.injuries&1<this.blood!==`off`&&this.has(e),o=r&&this.upperGone,s=this.isPartGone(`jaw`),c=r&&this.has(`skull_fractured`);t.setExplicit(r),n.setExplicit(r);let l=this.headRaises,u=this.bodyRaises;l.length=0,u.length=0;let d=(e,t,n,r=0,a=0)=>void e.push({site:t,bruise:n,blood:r*i,cut:a});if(t.setWound(`nose`,+!!a(`broken_nose`)),a(`broken_nose`)&&d(l,`nose`,1.1,1.4),a(`broken_jaw`)||a(`jaw_torn`)){let e=a(`jaw_torn`);d(l,`chin`,1.2),d(l,`leftJaw`,e?1.2:1),d(l,`rightJaw`,e?1.2:1),d(l,`mouth`,.7,e?1.4:.9,.7),d(u,`neckSmear`,0,e?1.4:.6)}a(`skull_fractured`)&&(d(l,`forehead`,1.1,1.4,+!r),d(u,`neckSmear`,0,1.1)),t.setGone(`jaw`,+!!s),t.setGone(`skull`,+!!c);let f=!1;for(let i of SR){let s=_z[i];t.setWound(s.ear,+!!a(`ear_${i}_torn`));let c=a(`face_${i}_flayed`);t.setWound(s.face,+!!c),c&&(d(l,s.cheek,.8,1.2),d(u,`neckSmear`,0,.9));let p=a(`eye_${i}_out`);p&&d(l,s.eye,1.1,+!r),this.eyeOut[i]&&!(p&&r)&&(f=!0),this.eyeOut[i]=p&&r,this.eyeShut[i]=p&&!r;let m=o?0:this.isPartGone(`arm_${i}`)?2:+!!this.isPartGone(`forearm_${i}`),h=!r&&a(`arm_${i}_torn`),g=!r&&a(`forearm_${i}_severed`);n.setGone(s.arm,m),n.setWound(s.shoulder,a(`shoulder_${i}_dislocated`)||h?1:0),n.setWound(s.elbow,a(`arm_${i}_broken`)||g?1:0),n.setWound(s.ribs,+!!a(`ribs_${i}_broken`)),n.setWound(s.knee,+!!a(`knee_${i}_blown`)),(m===2||h)&&d(u,s.smear,0,1.2),a(`ribs_${i}_broken`)&&d(u,s.ribs,1.2);let _=m>0||o;_?e.gloveMesh(i).visible=!1:this.gloveGone[i]&&(e.gloveMesh(i).visible=this.gloved[i]&&!e.isHandDismembered(i)),this.gloveGone[i]=_,this.piece(`fracture_${i}`,r&&!o&&m===0&&this.has(`arm_${i}_broken`)),this.piece(`ribs_${i}`,r&&!o&&this.has(`ribs_${i}_broken`)),this.piece(`knee_${i}`,r&&this.has(`knee_${i}_blown`)),this.piece(`elbow_${i}`,m===1),this.piece(`shoulder_${i}`,m===2)}f&&t.setEyeOut(this.eyeOut.left&&this.eyeOut.right?`both`:this.eyeOut.left?`left`:this.eyeOut.right?`right`:null),n.setWound(`liver`,+!!a(`liver_ruptured`)),n.setWound(`belly`,+!!a(`disemboweled`)),n.setGone(`waist`,+!!o),n.setGone(`chestHole`,r&&this.hole&&!o?1:0);let p=r&&this.has(`broken_jaw`)&&!s;this.jawHung&&!p&&t.setJaw(0),this.jawHung=p,o?e.headMesh.visible=!1:this.headHidden&&(e.headMesh.visible=!0),this.headHidden=o,this.piece(`skull`,c&&!o),this.piece(`maw`,s&&!o),this.piece(`chest`,r&&this.hole&&!o),this.piece(`waist`,o),c&&!o&&this.fitSkull();let m=xR(e,`body`);m!==null&&n.material!==null&&(n.open?m.customDepthMaterial=this.bodyShadow??=n.shadowMaterial():m.customDepthMaterial===this.bodyShadow&&(m.customDepthMaterial=void 0))}assert(){let e=this.boxer,t=e.headInjury,n=this.headRaises,r=this.bodyRaises;for(let e=0;e0,o=this.eyeOut.right||i.y>0;(this.eyeOut.left&&i.x===0||this.eyeOut.right&&i.y===0)&&t.setEyeOut(a&&o?`both`:a?`left`:`right`);let s=t.uniforms.uInjuryLid.value;(this.eyeShut.left||this.eyeShut.right)&&t.setEyesShut(this.eyeShut.left?1:s[0].w,this.eyeShut.right?1:s[1].w),this.gloveGone.left&&(e.gloveMesh(`left`).visible=!1),this.gloveGone.right&&(e.gloveMesh(`right`).visible=!1)}piece(e,t){if(t||this.pieces.has(e))for(let n of this.built(e))n.visible=t}built(e){let t=this.pieces.get(e);return t===void 0&&(t=this.make(e),this.pieces.set(e,t)),t}bindToWorld(e,t,n){let r=this.boxer.rig.bones[t],i=e.skeleton.bones.indexOf(r);return i<0?!1:(n.multiplyMatrices(r.matrixWorld,e.skeleton.boneInverses[i]).multiply(e.bindMatrix),!0)}fitSkull(){let e=this.skull;if(e===null)return;let t=this.boxer.look,n=Dj(BR.set(5.9,124.6,-3.3),t,this.root).x,r=Dj(BR.set(-5.9,124.6,-3.3),t,this.root).x,i=Dj(BR.set(0,124.6,3.3),t,this.root).z,a=Dj(BR.set(0,124.6,-9.9),t,this.root).z,o=(i-a)/13.2;this.fit.makeScale((n-r)/11.8,1,o).setPosition((n+r)/2,0,(i+a)/2+3.3*o),e.matrix.multiplyMatrices(this.skullMount,this.fit)}solid(e){this.geometries.push(e);let t=new Y(e,this.flesh);return t.receiveShadow=!0,t}mount(e,t,n=xR(this.boxer,`body`)){let r=this.boxer.rig.bones[e],i=n===null?-1:n.skeleton.bones.indexOf(r);return n!==null&&i>=0&&t.matrix.multiplyMatrices(n.skeleton.boneInverses[i],n.bindMatrix),t.matrixAutoUpdate=!1,t.visible=!1,r.add(t),t}closing(e,t,n){let r=xR(this.boxer,`body`);if(r===null)return[];let i=dz.get(r.geometry);i===void 0&&dz.set(r.geometry,i=new Map);let a=i.get(e);if(a===void 0&&i.set(e,a=AO(r.geometry,t)),a.length===0)return[];let o=new Hv(fz(r.geometry,a,n),this.flesh);return this.geometries.push(o.geometry),o.bind(r.skeleton,r.bindMatrix),o.frustumCulled=!1,o.receiveShadow=!0,o.visible=!1,(r.parent??this.boxer.root).add(o),[o]}make(e){let t=this.boxer.headMesh;if(e===`skull`){let e=new t_,n=this.solid(JR());return n.position.set(...KR),e.add(n,this.solid(YR())),this.mount(`head`,e,t),this.skullMount.copy(e.matrix),this.skull=e,this.brain=n,[e]}if(e===`maw`){let e=new t_,n=this.solid(ez());return n.position.set(...XR),e.add(this.solid(tz()),n),this.tongue=n,[this.mount(`head`,e,t)]}if(e===`chest`)return[...this.closing(e,e=>SA(e.x,e.y,e.z)<=0,mz),this.mount(`chest`,this.solid(oz()))];if(e===`waist`)return[...this.closing(e,e=>!vR(`upper_body`,`body`,e),pz(CR,.8)),this.mount(`spine`,this.solid(iz()))];let n=e.endsWith(`_left`)?`left`:`right`,{sign:r,bone:i}=_z[n];switch(e.slice(0,e.indexOf(`_`))){case`fracture`:return[this.mount(`shoulder${i}`,this.solid(WR([r*27.6,103.3,-5],[r*(PA[0]+2.4),PA[1]+2.6,PA[2]+1.4],1.05))),this.mount(`elbow${i}`,this.solid(UR([WR([r*34.6,102.3,-4.8],[r*30,98.6,-.8],.8),WR([r*34,103.2,-5.6],[r*30.6,100.6,-9.8],.6)])))];case`ribs`:return[this.mount(`chest`,this.solid(az(r)))];case`knee`:return[this.mount(`knee${i}`,this.solid(WR([r*8.8,37.8,-4.6],[r*(FA[0]+3.8),FA[1]-1.2,FA[2]-.2],1.2)))];case`elbow`:return[...this.closing(e,e=>!vR(`forearm_${n}`,`body`,e),pz(new q(r,0,0),0)),this.mount(`shoulder${i}`,this.solid(nz(r)))];case`shoulder`:return[...this.closing(e,e=>!vR(`arm_${n}`,`body`,e),pz(new q(r,0,0),1.6)),this.mount(`clavicle${i}`,this.solid(rz(r)))]}}},yz={broken_nose:[`nose`,.3],broken_jaw:[`mouth`,.25],jaw_torn:[`mouth`,.75],eye_left_out:[`eye_left`,.3],eye_right_out:[`eye_right`,.3],ear_left_torn:[`ear_left`,.3],ear_right_torn:[`ear_right`,.3],skull_fractured:[`skull`,.4],arm_left_broken:[`elbow_left`,.3],arm_right_broken:[`elbow_right`,.3],forearm_left_severed:[`elbow_left`,1],forearm_right_severed:[`elbow_right`,1],arm_left_torn:[`shoulder_left`,1],arm_right_torn:[`shoulder_right`,1],ribs_left_broken:[`ribs_left`,.15],ribs_right_broken:[`ribs_right`,.15],disemboweled:[`belly`,.6],knee_left_blown:[`knee_left`,.2],knee_right_blown:[`knee_right`,.2]},bz=new Map(he.map(e=>[e,[]]));for(let[e,[t,n]]of Object.entries(yz))bz.get(t).push([e,n]);var xz=new Set([`nose`,`mouth`,`eye_left`,`eye_right`,`ear_left`,`ear_right`,`skull`]),Sz=new Set([`waist`,`crotch`,`knee_left`,`knee_right`]),Cz=1.5,wz=8,Tz=.9,Ez=18,Dz=36,Oz=.45,kz=.25,Az=.3,jz=.08,Mz=.012,Nz=[`ankleL`,`ankleR`],Pz=.35,Fz=.05,Iz=.5,Lz=.3,Rz=.4,zz=[`left`,`right`],Bz={left:`eye_left_out`,right:`eye_right_out`},Vz={left:`eye_left`,right:`eye_right`},Hz={left:[`forearm_left_severed`,`arm_left_torn`],right:[`forearm_right_severed`,`arm_right_torn`]},Uz=[`head`,`arm_left`,`arm_right`,`leg_left`,`leg_right`,`torso`],Wz={head:[`neck`,`neck`],jaw:[`mouth`,`head`],forearm_left:[`elbow_left`,`elbowL`],forearm_right:[`elbow_right`,`elbowR`],arm_left:[`shoulder_left`,`shoulderL`],arm_right:[`shoulder_right`,`shoulderR`],leg_left:[`knee_left`,`kneeL`],leg_right:[`knee_right`,`kneeR`],upper_body:[`waist`,`hips`],torso:[`chest`,`upperChest`]},Gz=Object.keys(Wz),Kz={head:[`head`],jaw:[`head`],forearm_left:[`body`,`glove_left`],forearm_right:[`body`,`glove_right`],arm_left:[`body`,`glove_left`],arm_right:[`body`,`glove_right`],leg_left:[`body`,`shoes`],leg_right:[`body`,`shoes`],upper_body:[`head`,`body`,`glove_left`,`glove_right`],torso:[`body`,`pants`]},qz=new q(0,1,0),Jz=new q(0,.12,.02),Yz=class{effects;bake;bodies=[null,null];position=new q;axis=new q;scratch=new q;turn=new rg;skullOffset=new q;injuries=new Set;time=0;settings={blood:`full`,reducedMotion:!1};constructor(e,t){this.effects=e,this.bake=t}attach(e,t){this.bodies[e]?.mutilation.dispose();let n={graph:t,mutilation:new vz(t.boxer),shown:new Set,early:new Map,awaited:new Map,inflicted:new Set,fatalWounds:new Map,forced:new Set,fatalParts:[],burst:new Set,fatality:null,dead:null,gutsDropAt:null,gibbed:!1,vomitUntil:0,printed:[new q,new q],dragged:new q,sliding:!1};return this.bodies[e]=n,n.mutilation}get graphic(){return this.settings.blood===`full`&&!this.settings.reducedMotion}expect(e,t){let n=this.bodies[e];n!=null&&!n.inflicted.has(t)&&n.awaited.set(t,this.time+wz)}sync(e,t,n,r,i,a=!1){this.time=i,this.settings=n;let o=this.bodies[e];if(o==null)return;let s=this.graphic;!s&&(o.gibbed||o.fatalParts.length>0||o.fatalWounds.size>0||o.forced.size>0)&&this.unmaim(o,e);let c=this.injuries;c.clear();let l=!1;for(let e of t.injuries){let t=o.awaited.get(e);if(t!==void 0){if(i<=t){l=!0;continue}o.awaited.delete(e)}c.add(e),o.early.delete(e),o.inflicted.add(e)}for(let[e,t]of o.early)i>t?o.early.delete(e):c.add(e);for(let e of o.forced)c.add(e);if(l)for(let e of o.shown)c.add(e);o.shown.clear();for(let e of c)o.shown.add(e);for(let e of o.inflicted)o.shown.has(e)||o.inflicted.delete(e);let u=o.graph.boxer,d=G.clamp(1-t.blood_volume/ve,0,1);if(o.mutilation.apply(o.shown,s?`full`:n.blood===`off`?`off`:`reduced`),o.mutilation.setPallor(n.blood===`off`?0:d),o.graph.setInjuries(o.shown,s),o.graph.setFaint(o.dead===null?G.clamp((.6-t.blood_volume/ve)/.6,0,1):0),o.dead!==null&&!o.graph.isDead&&o.graph.die(o.dead),o.mutilation.update(r,i),u.root.visible=!o.gibbed,o.gibbed)return;let f=o.mutilation.isPartGone(`upper_body`),p=f||u.isDecapitated,m=p||u.isHeadBurst,h=1-.65*d,g=0;for(let t of he){let n=o.fatalWounds.get(t)??0,r=`blood`,i=bz.get(t);for(let e=0;e0&&o.mutilation.anchor(t,this.position,this.axis)&&this.effects.anchorWound(e,t,this.position,this.axis)}for(let t=0;t=o.gutsDropAt&&(o.gutsDropAt=null,this.effects.dropGuts(e)),this.effects.anchorGuts(e,this.position,this.axis)):this.effects.gutsOut(e)&&this.effects.clearGuts(e),i=kz&&this.track(o,Math.min(1,g)),o.dead===null||!o.mutilation.anchor(`waist`,this.position,this.axis))return;this.effects.setCorpse(e,s?this.position:null);let v=s&&this.position.yIz?o.dragged.copy(this.position):y>Fz&&(this.effects.smear(o.dragged.x,o.dragged.z,this.position.x,this.position.z,Lz),o.dragged.copy(this.position)),o.sliding=v}gibbed(e){return this.bodies[e]?.gibbed===!0}hasGlove(e,t){let n=this.bodies[e]?.shown;return n===void 0||!this.graphic||!(n.has(Hz[t][0])||n.has(Hz[t][1]))}vomiting(e){return this.time<(this.bodies[e]?.vomitUntil??0)}punched(e,t,n){let r=this.bodies[e];r!=null&&this.graphic&&r.shown.has(Bz[t])&&this.effects.burstEye(e,t,n)&&r.burst.add(t)}eyeBurst(e,t){return this.bodies[e]?.burst.has(t)===!0}inflict(e,t,n,r){let i=this.bodies[e];if(i==null||(i.awaited.delete(t),i.inflicted.has(t)||i.gibbed))return!1;if(i.inflicted.add(t),i.early.set(t,this.time+Cz),i.shown.add(t),!this.graphic)return!0;let a=this.effects,o=this.position,s=this.axis,c=t.includes(`_right_`)?`right`:`left`,l=e=>i.mutilation.anchor(e,o,s);switch(t){case`broken_nose`:l(`nose`)&&a.sprayFluid(`blood`,o,r,140,n,1.1);break;case`broken_jaw`:l(`mouth`)&&(a.spawnTeeth(o,r,5,n),a.sprayFluid(`blood`,o,r,180,n));break;case`jaw_torn`:l(`mouth`)&&(this.fling(i,e,`jaw`,n,r,{radius:.05,speed:1.2,lift:.8}),a.spawnDebris(`jawbone`,o,r,1,n,1.2),a.spawnTeeth(o,r,9,n),a.sprayFluid(`blood`,o,r,420,n,1.2));break;case`eye_left_out`:case`eye_right_out`:l(`eye_${c}`)&&(a.gougeEye(e,o,s,r,n,c),a.sprayFluid(`blood`,o,r,120,n));break;case`ear_left_torn`:case`ear_right_torn`:l(`ear_${c}`)&&(a.spawnDebris(`ear`,o,r,1,n),a.sprayFluid(`blood`,o,r,130,n));break;case`face_left_flayed`:case`face_right_flayed`:l(`eye_${c}`)&&(a.spawnDebris(`skin`,o,r,3,n),a.sprayFluid(`blood`,o,r,260,n));break;case`skull_fractured`:l(`skull`)&&(a.spawnDebris(`shard`,o,r,7,n,1.2),a.spawnDebris(`brain`,o,r,8,n),a.sprayFluid(`blood`,o,r,300,n,1.3),a.sprayFluid(`brain`,o,r,90,n));break;case`shoulder_left_dislocated`:case`shoulder_right_dislocated`:break;case`arm_left_broken`:case`arm_right_broken`:l(`elbow_${c}`)&&(a.spawnDebris(`bone`,o,r,3,n),a.sprayFluid(`blood`,o,r,200,n));break;case`forearm_left_severed`:case`forearm_right_severed`:this.fling(i,e,`forearm_${c}`,n,r,{radius:.07,speed:1.1}),l(`elbow_${c}`)&&(a.spawnDebris(`bone`,o,r,2,n),a.spawnDebris(`flesh`,o,r,8,n),a.sprayFluid(`blood`,o,r,600,n,1.3));break;case`arm_left_torn`:case`arm_right_torn`:this.fling(i,e,`arm_${c}`,n,r,{radius:.08,speed:1,spin:.7}),l(`shoulder_${c}`)&&(a.spawnDebris(`flesh`,o,r,14,n),a.spawnDebris(`bone`,o,r,2,n),a.sprayFluid(`blood`,o,r,800,n,1.4));break;case`ribs_left_broken`:case`ribs_right_broken`:l(`ribs_${c}`)&&(a.spawnDebris(`bone`,o,r,2,n,.8),a.sprayFluid(`blood`,o,r,140,n));break;case`liver_ruptured`:this.vomit(e,n,1.6);break;case`disemboweled`:l(`belly`)&&(a.spillGuts(e,o,n,Ez),a.spawnDebris(`organ`,o,r,3,n),a.spawnDebris(`gut`,o,r,4,n),a.spawnDebris(`fat`,o,r,4,n),a.sprayFluid(`blood`,o,r,650,n,1.2),a.sprayFluid(`bile`,o,r,110,n));break;case`knee_left_blown`:case`knee_right_blown`:l(`knee_${c}`)&&(a.spawnDebris(`bone`,o,r,2,n,.7),a.sprayFluid(`blood`,o,r,110,n))}return!0}vomit(e,t,n=1.3){let r=this.bodies[e];r==null||r.gibbed||this.settings.reducedMotion||(r.graph.retch(n),this.settings.blood===`full`&&r.mutilation.anchor(`mouth`,this.position,this.axis)&&(r.vomitUntil=this.time+n,this.effects.gush(e,this.position,this.axis.addScaledVector(qz,-.4).normalize(),n,520,t,`bile`),this.effects.sprayFluid(`blood`,this.position,0,90,t,.6),this.effects.puddle(this.position.x+this.axis.x*Rz,this.position.z+this.axis.z*Rz,.22,`bile`,t)))}fatality(e,t,n,r){let i=this.bodies[e];if(i==null||i.fatality!==null||!this.graphic)return!1;i.fatality=t;let a=this.effects,o=this.position,s=this.axis,c=(t,i,s=1)=>a.spawnDebris(t,o,r,i,n,s,e),l=(e,t,i=1)=>a.sprayFluid(e,o,r,t,n,i);if(t===`eyes_out`){for(let t=0;tr||Math.hypot(this.position.x-o.x,this.position.z-o.z)t!==n&&e.mutilation.isPartGone(t)),d=[],f=new q;for(let e of Kz[n]){let t=xR(c,e);if(t===null||!t.visible)continue;let r=t=>vR(n,e,t)&&!u.some(n=>vR(n,e,t)),i=t.geometry.getAttribute(`position`),a=t.geometry.getIndex(),o=0,s=0,p=new Uint8Array(i.count);if(a===null)p.fill(1);else for(let e=0;e0&&d.push(this.bake(c,e,t,l,this.turn,o===s?void 0:r))}return d.length>0&&this.effects.flingPart(Xz(t,n),d,l,this.turn,i,r,{...a,part:n})}};function Xz(e,t){return`${e}:${t}`}var Zz=96,Qz=4,$z=2.5,eB=.45,tB=.032,nB=e=>()=>(e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296);function rB(e){let t=document.createElement(`canvas`);t.width=Zz,t.height=Zz;let n=t.getContext(`2d`);if(n===null)return t;let r=nB(e),i=Zz/2,a=4+Math.floor(r()*3);for(let e=0;e.05)||!Number.isFinite(e)||!Number.isFinite(t))return;let i=nB((Number.isSafeInteger(r)?r:0)*40503+11),a=Math.min(24,Math.max(1,Math.round(n*12))),o=.7+.3*Math.min(3,n);for(let r=0;r=1.5?1.8:1),l=$z+i()*2.5;this.drops.push({x:Math.min(1,Math.max(0,a?i():e+(i()+i()-1)*s*1.6)),y:Math.min(1,Math.max(0,a?i():t+(i()+i()-1)*s)),radius:c,alpha:.6+i()*.35,life:l,maxLife:l,run:c>=tB?.02+i()*.04:0,ran:0,sprite:Math.floor(i()*Qz),turn:i()*Math.PI*2})}this.drops.length>96&&this.drops.splice(0,this.drops.length-96)}update(e){let t=Number.isFinite(e)?Math.max(0,e):0;for(let e=this.drops.length-1;e>=0;--e){let n=this.drops[e];n.life-=t,n.life<=0?this.drops.splice(e,1):n.ran+=n.run*t*(n.life/n.maxLife)}}draw(e,t,n){if(this.drops.length!==0){this.sprites??=Array.from({length:Qz},(e,t)=>rB(1374496523+t*7919)),e.save();for(let r of this.drops){let i=Math.min(1,r.life/(r.maxLife*eB)),a=r.radius*n,o=r.x*t,s=(r.y+r.ran)*n;if(e.globalAlpha=r.alpha*i,r.ran>0){let t=r.y*n,i=e.createLinearGradient(0,t,0,s);i.addColorStop(0,`rgba(88,0,6,0)`),i.addColorStop(1,`rgba(88,0,6,0.6)`),e.fillStyle=i,e.beginPath(),e.moveTo(o-a*.06,t),e.lineTo(o+a*.06,t),e.lineTo(o+a*.28,s),e.lineTo(o-a*.28,s),e.closePath(),e.fill()}e.save(),e.translate(o,s),e.rotate(r.turn),e.drawImage(this.sprites[r.sprite],-a,-a,a*2,a*2),e.restore()}e.restore()}}clear(){this.drops.length=0}},aB=.026,oB=.038,sB=22,cB=[[.55,.85],[.55,.1],[.4,-.12],[-.4,-.12],[-.55,.05],[-.55,.6],[-.32,.62],[-.3,.16],[.3,.16],[.32,.85]],lB=.03;function uB(){let e=[],t=[],n=cB.length,r=new q,i=new q,a=new q;for(let t=0;t<=sB;t+=1){let n=t/sB*2-1;r.set(n*aB,0,oB*(1-n*n)-oB*.5),i.set(aB,0,-2*oB*n).normalize(),a.set(i.z,0,-i.x),a.dot(r.clone().setY(0).add(new q(0,0,oB*.5)))<0&&a.negate();for(let[t,n]of cB)e.push(r.x+a.x*t*.01,n*.01,r.z+a.z*t*.01)}for(let e=0;e=50:e===`hit`&&t>=65:!1}var fB=9.81,pB=.32,mB=4.5,hB=.04,gB=3;function _B(){return{out:!1,moving:!1,sliding:!1,x:0,y:-50,z:0,vx:0,vy:0,vz:0,wx:0,wy:0,wz:0,bounces:0,age:0,restYaw:0}}function vB(e,t,n,r){if(!e.out||!e.moving)return!1;e.age+=n;let i=r+.006;if(!e.sliding)e.vy-=fB*n,e.x+=e.vx*n,e.y+=e.vy*n,e.z+=e.vz*n,CB(t,e.wx*n,e.wy*n,e.wz*n),e.y<=i&&(e.y=i,e.bounces.6?(e.bounces+=1,e.vy=-e.vy*pB,e.vx*=.72,e.vz*=.72,e.wx*=.55,e.wy*=.7,e.wz*=.55):(e.vy=0,e.sliding=!0));else{let r=Math.hypot(e.vx,e.vz),a=Math.max(0,r-mB*n);a<=hB?(e.vx=0,e.vz=0):(e.vx*=a/r,e.vz*=a/r),e.x+=e.vx*n,e.z+=e.vz*n,e.y=i,e.wy*=Math.exp(-4*n),e.restYaw+=e.wy*n,bB.setFromAxisAngle(yB,e.restYaw),t.slerp(bB,1-Math.exp(-12*n)),e.vx===0&&e.vz===0&&t.angleTo(bB)<.02&&(t.copy(bB),e.moving=!1)}return e.moving}var yB=new q(0,1,0),bB=new rg,xB=new rg,SB=new Lg;function CB(e,t,n,r){xB.setFromEuler(SB.set(t,n,r)),e.multiply(xB).normalize()}var wB=[.84,.78,.62],TB=[.4,.04,.04],EB=[.3,.012,.018],DB=[.5,.045,.05],OB=[.86,.64,.16],kB=[.42,.19,.09],AB=[.92,.88,.74],jB=[.72,.36,.34],MB=[.82,.52,.46],NB=(e,t,n)=>{let r=Math.min(1,Math.max(0,n));return[e[0]+(t[0]-e[0])*r,e[1]+(t[1]-e[1])*r,e[2]+(t[2]-e[2])*r]},PB=e=>{let t=Math.min(1,Math.max(0,e));return t*t*(3-2*t)},FB=(e,t,n=0)=>.5+.25*Math.sin(e.x*t*1.31+n)*Math.sin(e.y*t*1.93+n*1.7)+.25*Math.sin(e.z*t*1.57+n*.6)*Math.sin(e.x*t*.83-n),IB=e=>()=>(e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296),LB=new q;function RB(e,t){e.deleteAttribute(`normal`),e.deleteAttribute(`uv`);let n=yE(e,1e-5);e.dispose();let r=n.getAttribute(`position`);for(let e=0;enew Dg().compose(new q(e,t,n),new rg().setFromEuler(new Lg(r,i,a)),new q(o,s,c));function HB(e,t,n){return zB(new yb(new Jy(e.map(e=>new q(...e))),Math.max(4,e.length*3),t,7,!1),n)}var UB=new Map;function WB(e){let t=UB.get(e);return t===void 0&&(t=e(),UB.set(e,t)),t.clone()}function GB(){return BB([zB(RB(new fb(1,3),e=>{e.normalize();let t=.45+.55*PB((e.x+1)/2),n=1-.34*Math.exp(-(((e.x+.2)/.14)**2))*PB(e.z+.6),r=1+.07*Math.sin(e.x*5.1+.7)*Math.sin(e.z*4.3+1.9);e.set(e.x*.1*r,(e.y>0?e.y:e.y*.4)*.04*t*r,e.z*.062*n*(.7+.3*t))}),e=>NB(NB([.2,.035,.022],[.34,.07,.04],FB(e,70)),EB,e.y<-.006?.5:0)),zB(RB(new fb(1,2),e=>e.set(e.x*.03,e.y*.012,e.z*.014)),[.16,.24,.04],VB(.03,-.012,.03,0,.5,0)),HB([[.01,.004,-.03],[0,.012,-.055],[-.012,.014,-.075]],.007,e=>NB([.16,.05,.2],EB,PB((-e.z-.06)*60)))])}function KB(){return BB([zB(RB(new fb(1,3),e=>{e.normalize();let t=1-.42*Math.exp(-((e.x/.4)**2))*PB(e.z);e.set(e.x*.058,e.y*.024,e.z*.033*t-e.x*e.x*.012)}),e=>NB([.3,.05,.075],[.19,.025,.05],FB(e,120,1.3))),HB([[0,0,.014],[.004,.002,.034],[.018,0,.058],[.02,-.002,.082]],.0048,e=>NB([.86,.72,.56],EB,PB((e.z-.066)*70))),HB([[-.006,.002,.014],[-.012,.004,.034],[-.03,.002,.046]],.0042,EB),zB(RB(new fb(1,1),e=>e.set(e.x*.014,e.y*.009,e.z*.01)),OB,VB(0,.002,.02))])}function qB(){return BB([zB(RB(new fb(1,3),e=>{e.normalize();let t=.55+.45*PB((1-e.z)/2+.1),n=1-.3*Math.exp(-(((e.z-.1-e.x*.3)/.1)**2)),r=1+.035*Math.sin(e.x*23)*Math.sin(e.y*19)*Math.sin(e.z*21);e.set(e.x*.062*t*n*r,(e.y>0?e.y:e.y*.55)*.036*t*n*r,e.z*.09*r)}),e=>NB(NB([.66,.34,.34],[.34,.16,.2],PB(FB(e,160,.4)*1.7-.5)),EB,PB((e.z-.05)*22)*.7)),zB(new Iy(.011,.012,.045,9,5,!0),e=>Math.abs((e.y+.5)*110%2)<1?[.84,.74,.62]:[.6,.26,.24],VB(0,.006,.105,Math.PI/2-.2,0,0))])}function JB(){let e=new Jy([[-.085,0,.012],[-.045,.004,-.02],[0,0,.018],[.04,.003,-.016],[.082,0,.014]].map(e=>new q(...e))),t=[],n=[],r=[],i=e.computeFrenetFrames(30,!1);for(let r=0;r<=30;r+=1){let a=r/30,o=e.getPointAt(a),s=Math.min(1,Math.sin(a*Math.PI)*5),c=.0175*(.82+.18*Math.abs(Math.sin(a*Math.PI*5.5)))*(.25+.75*s);for(let e=0;e<9;e+=1){let l=e/9*Math.PI*2,u=LB.copy(i.normals[r]).multiplyScalar(Math.cos(l)).addScaledVector(i.binormals[r],Math.sin(l));t.push(o.x+u.x*c,o.y+u.y*c,o.z+u.z*c);let d=1-.3*(1-Math.abs(Math.sin(a*Math.PI*5.5))),f=e===0?EB:NB(NB(jB,MB,.5+.5*Math.sin(a*23+e)),EB,s<1?.8:0);n.push(f[0]*d,f[1]*d,f[2]*d)}}for(let e=0;e<30;e+=1)for(let t=0;t<9;t+=1){let n=e*9+t,i=e*9+(t+1)%9;r.push(n,i,n+9,i,i+9,n+9)}let a=new iv;a.setAttribute(`position`,new K_(t,3)),a.setAttribute(`color`,new K_(n,3)),a.setIndex(r),a.computeVertexNormals();let o=a.toNonIndexed();return a.dispose(),BB([o,...[[-.03,-.004,-.03],[.012,-.004,.03],[.05,-.004,-.028]].map(([e,t,n])=>zB(RB(new fb(1,1),e=>e.set(e.x*.016,e.y*.007,e.z*.011)),OB,VB(e,t,n,0,e*20,0)))])}function YB(){let e=[[.012,.008],[.004,.0105],[-.01,.0075],[-.013,-.004],[-.002,-.0095],[.01,-.0065]],t=[-1,-.72,-.3,.2,.62,1],n=[.02,.62,1,.9,.5,.02],r=[.004,-.002,0,.001,-.003,.005],i=[],a=[],o=(i,a)=>{let[o,s]=e[a%e.length];return[t[i]*.062,s*n[i],o*n[i]+r[i]]},s=(n,r)=>{let i=Math.abs(t[n]);return NB(r%e.length===3||r%e.length===4?NB(wB,TB,.75):wB,EB,PB((i-.6)*3.2))};for(let n=0;nNB(kB,DB,PB((-e.x-.006)*90));return BB([zB(RB(new fb(1,3),e=>{e.normalize();let t=e.y>0?1-.75*Math.exp(-(((e.x-.1)/.5)**2+((e.z+.1)/.55)**2)):1;e.set(e.x*.019,e.y*.0055*t,e.z*.031*(1-.18*e.x))}),t=>NB(e(t),[.24,.08,.05],t.y<.003&&t.y>-.001?.5:0)),zB(new vb(.024,.0048,7,18,Math.PI*1.25),kB,VB(-.001,.004,.004,-Math.PI/2,0,-Math.PI*.72,.78,1.18,1)),zB(RB(new fb(1,2),e=>e.set(e.x*.0095,e.y*.0055,e.z*.0105)),e,VB(.002,.002,.031)),zB(RB(new fb(1,1),e=>e.set(e.x*.005,e.y*.005,e.z*.007)),e,VB(-.011,.004,.006)),zB(RB(new fb(1,1),e=>e.set(e.x*.006,e.y*.005,e.z*.022)),DB,VB(-.017,0,.002))])}var ZB=12;function QB(){let e=e=>[Math.sin(e)*.046,Math.cos(e)*.056-.02],t=[],n=e=>NB(NB(wB,[.7,.6,.44],FB(e,200)),EB,PB((e.y-.003)*220)*.75),r=Math.PI*.62,i=[];for(let t=0;t<=22;t+=1){let[n,a]=e(-r+t/22*r*2);i.push(new q(n,0,a))}let a=new yb(new Jy(i),44,.0085,8,!1);t.push(zB(RB(a,e=>e.setY(e.y*1.35)),n)),t.push(zB(RB(new fb(1,2),e=>e.set(e.x*.016,e.y*.013,e.z*.011)),n,VB(0,-.003,.038)));for(let n=0;nNB(AB,[.7,.2,.14],PB((-e.y-5e-4)*400)),VB(a,.0125+(s?.0045:.003),o,0,-i,0))),t.push(zB(RB(new fb(1,1),e=>e.set(e.x*.0058,e.y*.0045,e.z*.0058)),c?[.05,.004,.006]:[.5,.07,.08],VB(a,.0105,o)))}for(let n of[-1,1]){let[i,a]=e(n*r),o=RB(new Ny(.008,.05,.026,1,4,2),e=>{let t=e.y/.05+.5;e.z+=-.012*t+(t>.9?Math.sign(e.z)*.004:0),e.x*=1-.3*t});t.push(zB(o,e=>NB(wB,EB,PB((e.y-.012)*60)),VB(i,.02,a-.006,0,n*.25,n*-.12))),t.push(zB(RB(new fb(1,1),e=>e.set(e.x*.009,e.y*.006,e.z*.014)),DB,VB(i,.047,a-.016)))}let o=BB(t);return o.translate(0,-.016,0),o.computeBoundingBox(),o.computeBoundingSphere(),o}function $B(){let e=(e,t,n)=>{let r=t/13*Math.PI*2,i=.55+.45*Math.abs(Math.sin(t*2.7+.9))+.12*Math.sin(t*5.3),a=e/3*i,o=Math.cos(r)*a*.062,s=Math.sin(r)*a*.044;return[o,.009*Math.sin(o*60+.4)*Math.cos(s*48)+.3*(o*o+s*s)/.062+n*.0028*(1-e/3*.7),s]},t=[],n=[],r=(e,r,i,a)=>{for(let o of[e,r,i])t.push(...o),n.push(...a(o))},i=()=>kB,a=e=>Math.sin(e[0]*310+1)*Math.sin(e[2]*270)>.45?OB:NB(DB,EB,.5+.5*Math.sin(e[0]*140+e[2]*90));for(let t=0;t<3;t+=1)for(let n=0;n<13;n+=1){let o=(n+1)%13;r(e(t,n,1),e(t+1,o,1),e(t+1,n,1),i),r(e(t,n,0),e(t+1,n,0),e(t+1,o,0),a),t>0&&(r(e(t,n,1),e(t,o,1),e(t+1,o,1),i),r(e(t,n,0),e(t+1,o,0),e(t,o,0),a))}for(let t=0;t<13;t+=1){let n=(t+1)%13;r(e(3,t,1),e(3,n,1),e(3,t,0),()=>DB),r(e(3,n,1),e(3,n,0),e(3,t,0),()=>DB)}let o=new iv;return o.setAttribute(`position`,new K_(t,3)),o.setAttribute(`color`,new K_(n,3)),o.computeVertexNormals(),BB([o])}function eV(){let e=IB(795558343),t=[];for(let n=0;n<9;n+=1){let r=e()*Math.PI*2,i=n===0?0:.012+e()*.02,a=n===0?.021:.009+e()*.009,o=e();t.push(zB(RB(new fb(1,2),e=>e.set(e.x*a,e.y*a*.7,e.z*a)),NB(OB,[.92,.8,.36],o),VB(Math.cos(r)*i,(e()-.3)*.008,Math.sin(r)*i*.8)))}return t.push(zB(RB(new fb(1,1),e=>e.set(e.x*.02,e.y*.005,e.z*.009)),DB,VB(.018,-.006,.01,0,.6,0))),BB(t)}function tV(){let e=e=>NB(NB(wB,[.68,.58,.42],FB(e,260)),EB,PB(FB(e,90,2.2)*2.4-1.3)),t=zB(RB(new Iy(.02,.02,.022,14,2),e=>{let t=1-.14*(1-(e.y/.011)**2);e.x*=t,e.z*=t*(e.z<0?.8:1)}),e,VB(0,0,.008)),n=zB(new Iy(.0175,.0175,.005,12),e=>NB([.78,.5,.46],DB,FB(e,400)),VB(0,.0125,.008)),r=zB(new vb(.0115,.0042,6,12),e,VB(0,0,-.016,Math.PI/2,0,0)),i=zB(RB(new Ny(.007,.011,.03,1,1,3),e=>{let t=.5-e.z/.03;e.x*=1-.55*t,e.y=e.y*(1-.4*t)-.008*t}),e,VB(0,0,-.04)),a=[-1,1].map(t=>zB(RB(new Ny(.024,.008,.008,3,1,1),e=>{let n=.5+t*e.x/.024;e.y*=1-.5*n,e.z=e.z*(1-.4*n)-.006*n}),e,VB(t*.027,0,-.012))),o=zB(new Iy(.0048,.0048,.03,7),e=>NB([.88,.8,.6],EB,PB((Math.abs(e.y)-.009)*200)),VB(0,0,-.016));return BB([t,n,r,i,...a,o])}function nV(){return BB([zB(RB(new Ny(.075,.004,.022,9,1,3),e=>{let t=e.x/.075+.5;e.x+=.0375,e.z=e.z*(1-.75*t)*(1+.5*Math.sin(t*17))+.006*Math.sin(t*9),e.y+=.004*Math.sin(t*13)}),e=>NB(NB(DB,EB,FB(e,240)),OB,Math.sin(e.x*260)>.93?.8:0))])}var rV={position:new q(.012,.089,.004),direction:new q(.47,.88,-.12).normalize()};function iV(){let e=zB(RB(new fb(1,4),e=>{e.normalize();let t=PB((1-e.y)/2),n=1-.62*t**2.4,r=1-.1*Math.exp(-(((e.x+.12)/.14)**2))*(e.z>-.2?1:.4);e.set(e.x*.05*n*r+.012*t,e.y>0?e.y*.038:e.y*.07,e.z*.04*n*r)}),e=>{let t=Math.exp(-(((e.x+.008+e.y*.3)/.006)**2)),n=Math.exp(-(((e.y-.032)/.006)**2));return NB(NB(NB([.42,.03,.035],[.26,.015,.025],FB(e,130)),OB,Math.max(t*.85,n*.7)*PB(FB(e,420,.7)*2)),[.12,.02,.1],t>.6&&Math.sin(e.y*300)>.2?.7:0)}),t=(e,t,n)=>zB(RB(new fb(1,2),e=>{let t=1+.12*Math.sin(e.x*9)*Math.sin(e.z*8);e.set(e.x*n*t,e.y*n*.72,e.z*n*.9*t)}),e=>NB([.3,.02,.05],[.18,.012,.045],FB(e,200)),VB(e,.04,t)),n=(e,t)=>n=>NB(e,EB,PB((n.y-t)*120)),r=HB([[-.006,.03,.006],[-.004,.058,.008],[.004,.08,.006],[.012,.095,.004]],.0125,n([.82,.56,.44],.082)),i=[-1,0,1].map(e=>HB([[-.003+e*.004,.066,.008],[-.012+e*.012,.086,.012-e*.004],[-.016+e*.018,.1,.014-e*.006]],.0048,n([.78,.5,.4],.09))),a=HB([[.016,.03,.022],[.012,.052,.026],[-.006,.066,.03],[-.026,.07,.03]],.0105,e=>NB([.3,.3,.52],EB,PB((-e.x-.014)*110))),o=HB([[.03,.036,-.016],[.034,.058,-.018],[.036,.08,-.02]],.0095,n([.16,.14,.34],.068)),s=BB([e,t(.027,-.006,.024),t(-.024,-.004,.022),r,...i,a,o]);return s.translate(0,-.006,0),s.computeBoundingBox(),s.computeBoundingSphere(),s}var aV=2;function oV(e){let t=Math.min(14,Math.max(0,e));return aV*t-1.55*t*t/28}function sV(e){return Math.max(0,1-Math.max(0,e)/14)**.8}function cV(e){let t=e-Math.floor(e);return t<.16?PB(t/.16):1-PB((t-.16)/.3)}var lV=9.81,uV=.97,dV=.6,fV=10,pV=1.02,mV=.5,hV=.5,gV=2e-4,_V=.45,vV=.03,yV=.15,bV=class{capacity;radius;selfAvoiding;positions;previous;nodes=0;segment=0;pinned=!1;resting=!0;paidOut=0;payRate=0;still=0;constructor(e,t,n){this.capacity=e,this.radius=t,this.selfAvoiding=n,this.positions=new Float32Array(e*3),this.previous=new Float32Array(e*3)}get held(){return this.pinned?Math.max(0,this.nodes-1-Math.floor(this.paidOut)):-1}spill(e,t,n,r,i){this.nodes=Math.min(this.capacity,Math.max(2,Math.round(e)+1)),this.segment=t,this.pinned=!0,this.resting=!1,this.paidOut=1,this.payRate=r,this.still=0;for(let e=0;e.4)for(let e=0;ethis.segment?this.segment:s=a-1?this.still+e:0,this.still>=hV&&(this.resting=!0,s.set(o)),!0}drape(e,t,n,r=!1){let i=Math.hypot(n.x,n.z);if(i<.3)return;let a=this.positions;for(let o=e;o_V||s<-.05)continue;let c=vV+yV*Math.min(1,Math.max(0,s)/.25),l=((a[e]-t.x)*n.x+(a[e+2]-t.z)*n.z)/i;if(l>=c+(r?1e-4:0))continue;let u=Math.max(0,c-l);if(a[e]=a[e]+n.x/i*u,a[e+2]=a[e+2]+n.z/i*u,!r)continue;let d=((a[e]-this.previous[e])*n.x+(a[e+2]-this.previous[e+2])*n.z)/i;this.previous[e]=this.previous[e]+n.x/i*d,this.previous[e+2]=this.previous[e+2]+n.z/i*d}}keepApart(e){let t=this.positions,n=this.radius*1.7;for(let r=e;r=n*n)continue;let c=Math.sqrt(s),l=Math.hypot(i,o)1e-10&&TV.copy(OV).normalize(),EV.addScaledVector(TV,-EV.dot(TV)),EV.lengthSq()<1e-8&&(EV.set(+(Math.abs(TV.x)<.9),0,Math.abs(TV.x)<.9?0:1),EV.addScaledVector(TV,-EV.dot(TV))),EV.normalize(),DV.crossVectors(TV,EV);let a=Math.min(e,n-1-e),c=this.radii[e]*(a===0?.08:a===1?.62:a===2?.9:1);for(let t=0;t0?t.fromBufferAttribute(n,0):t.set(0,1,0).applyQuaternion(e.mesh.quaternion),t.lengthSq()>1e-8?t.normalize():t.set(0,1,0)}var WH=e=>()=>(e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296),$=(e,t=0)=>Number.isFinite(e)?e:t,GH=()=>({alive:!1,x:0,y:-50,z:0,vx:0,vy:0,vz:0,rx:0,ry:0,rz:0,vrx:0,vry:0,vrz:0,scale:0,stretch:1,bounces:0,stained:!1,kind:`flesh`,resting:!1,born:0,owner:-1,fading:-1}),KH=e=>{for(let t of e)if(!t.alive)return!0;return!1},qH=new J(16054267),JH=.012,YH=.055,XH=90,ZH=10,QH=.985,$H=new K(.097,.132),eU=.012,tU={r:.82,g:.86,b:.9},nU=4,rU=(e,t)=>Math.trunc(e)*2+(t===`left`?0:1),iU=new q(1,0,0),aU=[`blood`,`bile`,`brain`,`urine`],oU=2400,sU={liver:{build:GB,share:.06,size:[.8,.5],stretch:[.9,.3],stain:.5},kidney:{build:KB,share:.06,size:[.9,.5],stretch:[.9,.25],stain:.3},lung:{build:qB,share:.06,size:[.75,.45],stretch:[.9,.3],stain:.45},gut:{build:JB,share:.18,size:[.8,.5],stretch:[.8,.5],stain:.4},bone:{build:YB,share:.24,size:[.7,.8],stretch:[.8,.6],stain:.14},vertebra:{build:tV,share:.1,size:[.9,.3],stretch:[1,0],stain:.2},skin:{build:$B,share:.1,size:[.8,.8],stretch:[.7,.7],stain:.3},fat:{build:eV,share:.12,size:[.6,.7],stretch:[.8,.5],stain:.2},ear:{build:XB,share:.03,size:[1.3,.3],stretch:[1,0],stain:.14},jawbone:{build:QB,share:.016,size:[1.1,.15],stretch:[1,0],stain:.34}},cU=Object.keys(sU),lU=[`liver`,`kidney`,`lung`],uU=Object.fromEntries(he.map((e,t)=>[e,t])),dU=14,fU=3.5,pU=1100,mU=.12,hU=.45,gU=TH*Math.sqrt(Math.PI),_U=e=>G.clamp((e-.3)/.6,0,1),vU=e=>dU+326*e**2.2,yU=e=>vU(e)*(1-_U(e)*.88*(1-gU)),bU=16,xU=8,SU=.4,CU=24,wU=11,TU=.046,EU=[0,0,1,3,6],DU=50,OU=48,kU=.6,AU=1,jU=.06,MU=.075,NU=4,PU=24,FU=1.3,IU=new rg().setFromEuler(new Lg(.95,0,0)),LU=60,RU=4,zU=5,BU=1.2,VU=1.5,HU=.5;function UU(e){if(typeof e==`number`)return{x:e<0?-1:1,z:0};let t=Math.hypot(e.x,e.z);return Number.isFinite(t)&&t>1e-6?{x:e.x/t,z:e.z/t}:{x:1,z:0}}var WU=new q(0,1,0),GU=new q(0,0,1),KU=e=>Number.isFinite(e)?G.clamp(e,0,hH):0,qU=new Set([`hit`,`counter_hit`,`block`,`perfect_block`,`guard_break`,`knockdown`,`bleed`]);function JU(e,t,n,r){let i=Math.abs(e)-r;if(i<=0)return{position:e,velocity:t};let a=Math.sign(e);return Math.abs(n)<=r?{position:a*r,velocity:t*-.42}:{position:e,velocity:-a*Math.max(-a*t,i*ZV)}}function YU(e){if(e.kind===`bleed`)return`ooze`;if(e.kind===`knockdown`)return`impact`;let t=e.detail.split(`:`);if(t.at(-1)===`body`)return`body_burst`;let n=t.find(e=>[`jab`,`straight`,`hook`,`uppercut`].includes(e));return n===`hook`?`fan`:n===`uppercut`?`plume`:`jet`}function XU(e,t){e.set($(t.x),$(t.y),$(t.z),$(t.w,1)),e.lengthSq()<1e-6?e.identity():e.normalize()}function ZU(){return new jb({color:9063730,roughness:.58,metalness:.02,clearcoat:.25,clearcoatRoughness:.6})}function QU(e,t){let n=ZU();n.map=t;let r=e?new nj(n,aA,{core:BA,wash:!0,baked:!0}):new nj(n,iA,{core:zA,lids:VA,baked:!0});if(!e)return{material:n,injury:r,look:new Aj(n,!0)};let i=n.onBeforeCompile;return n.onBeforeCompile=(e,t)=>{i.call(n,e,t),e.vertexShader=e.vertexShader.replace(`#include `,`#include -attribute vec3 bindPosition;`)},{material:n,injury:r,look:null}}var $U=0,eW=1,tW=2,nW=3;function rW(e,t,n){return e===void 0||e===`forearm_left`||e===`forearm_right`?$U:e===`head`?tW:e===`upper_body`?t?nW:eW:e===`torso`&&n?tW:eW}function iW(e,t,n,r=0){let i=new Ab({map:e,color:t,roughness:n===void 0?.6:.38,metalness:.02,side:2});return n!==void 0&&(rA(i,!0,n).value=r),i}function aW(e,t,n){n.identity();let r=e.getAttribute(`position`),i=e.getAttribute(`bindPosition`),a=e.getIndex();if(i===void 0||i.count!==r.count)return n;let o=new Uint8Array(r.count);if(a===null)o.fill(1);else for(let e=0;e({active:!1,eventId:null,fluid:`blood`,life:0,seconds:1,rate:0,accumulator:0,position:new q,axis:new q(0,1,0)}));simulationRemainder=0;ambientSeed=1597463007;shake=0;lowTier=!1;bloodLevel=`full`;lens=new iB;camera=null;lensPoint=new q;debrisCursor=new Map;visceraMaterial;viscera=[];visceraByShape={};wounds=[];woundsOpen=0;woundShare=1;woundClock=0;parts=[];partsThrown=0;partBox=new T_;partMiddle=new q;partVertex=new q;limbMap;limbMaterial;trunkMap;trunkMaterial;fleshSections;spines=[];spineMesh;spineStretch;shredGeometry;shredMesh;spineNeck=new q;guts=[];heartGeometry;heartMesh;heartRest;heartRadius;heart={active:!1,moving:!1,owner:-1,age:0,beats:0,vx:0,vy:0,vz:0,vrx:0,vry:0,vrz:0,bounces:0,settle:-1,settleFrom:new rg,settleTo:new rg,settleFromY:0,pool:0,trail:0};corpses=[];flyGeometry;flyMaterial;flyMesh;flies;constructor(e,t=1024,n=NV){this.scene=e,this.budget=n,this.dropletPositions=new Float32Array(n.droplets*3),this.dropletColors=new Float32Array(n.droplets*3),this.dropletBuffers={position:new U_(this.dropletPositions,3),color:new U_(this.dropletColors,3)},this.dropletGeometry=CO(),this.dropletMaterial=new Ab({color:16777215,roughness:.3,metalness:.02}),this.dropletMesh=new ny(this.dropletGeometry,this.dropletMaterial,n.droplets),this.dropletMesh.instanceMatrix.setUsage(gh),this.dropletMesh.frustumCulled=!1,this.dropletMesh.castShadow=!1,e.add(this.dropletMesh);for(let e=0;eObject.assign(new Y(e.geometry,e.material),{castShadow:e.castShadow}));if(e.push(Object.assign(new Y(this.stumpGeometry,this.jawMaterial),{castShadow:this.stumps[0].mesh.castShadow})),this.bakedStandIns===null){let e=new xg,t=[QU(!1,e),QU(!0,e)].flatMap(e=>[e.material,e.injury.variant(!1),e.injury.variant(!0)]),n=new Ab({color:1920728,roughness:.38,metalness:.03,map:e});rA(n,!0);let r=[iW(e,16777215),iW(null,16777215),iW(e,1920728,`gloves`),iW(e,1920728,`trunks`)],i=new ny(this.heartGeometry,this.visceraMaterial,1);i.setColorAt(0,this.gibColor.setHex(16777215)),i.castShadow=!0,this.bakedStandIns={map:e,materials:[...t,n,...r],instanced:[i,new ny(this.flyGeometry,this.flyMaterial,1)]}}for(let t of this.bakedStandIns.materials)e.push(Object.assign(new Y(this.headGeometry,t),{castShadow:!0}));return e.push(Object.assign(new Y(this.heartGeometry,this.visceraMaterial),{castShadow:!0}),...this.bakedStandIns.instanced),e}setCamera(e){this.camera=e}drawLens(e,t,n){this.lens.draw(e,t,n)}get lensDrops(){return this.lens.count}setBloodLevel(e){if(e===this.bloodLevel)return;let t=this.bloodLevel;this.bloodLevel=e,(e===`off`||t===`full`&&e===`reduced`)&&this.clearArcadeGore()}get shakeAmount(){return this.shake}get liveParticles(){return this.droplets.filter(e=>e.alive).length}get liveBloodParticles(){return this.droplets.filter(e=>e.alive&&e.blood).length}get liveMist(){return this.mists.filter(e=>e.alive).length}get canvasStains(){return this.canvasBlood.stains}useUploader(e){this.canvasBlood.useUploader(e)}setLowTier(e){this.canvasBlood.setLowTier(e),this.lowTier=e}get liveGibs(){return this.gibs.filter(e=>e.alive).length}get liveShards(){return this.shards.filter(e=>e.alive).length}debrisCount(e){let t=0;for(let n of this.gibs)n.alive&&n.kind===e&&(t+=1);for(let n of this.shards)n.alive&&n.kind===e&&(t+=1);for(let n of this.eyeballs)n.alive&&n.kind===e&&(t+=1);for(let n of this.viscera)for(let r of n.pieces)r.alive&&r.kind===e&&(t+=1);return t}get activeHeads(){return this.heads.filter(e=>e.active).length}headBurst(e){let t=this.stumps[Math.trunc(e)];return t!==void 0&&t.active&&t.mesh.material===this.jawMaterial}severedHeadPosition(e,t){let n=this.heads[Math.trunc(e)];return n===void 0||!n.active?!1:(t.copy(n.mesh.position),!0)}severedHeadFacing(e,t){let n=this.heads[Math.trunc(e)];return n===void 0||!n.active?!1:(t.set(0,0,1).applyQuaternion(n.mesh.quaternion),!0)}mouthpieceOut(e){return this.shields[Math.trunc(e)]?.out===!0}mouthpiecePosition(e,t){let n=this.shields[Math.trunc(e)];return n===void 0||!n.out?!1:(t.set(n.x,n.y,n.z),!0)}ejectMouthpiece(e,t,n,r,i,a,o=!1){if(e<0||e>=BV)return!1;let s=Math.trunc(e),c=this.shields[s],l=Number.isSafeInteger(i)?i:0;if(c.out&&!o||this.lastShieldEvent[s]===l)return!1;this.lastShieldEvent[s]=l;let u=WH(l*48271+s*7907+5),d=UU(r),f=.9+u()*.9,p=.9+u()*.9,m=(u()-.5)*1.1;Object.assign(c,_B(),{out:!0,moving:!0,x:$(t.x),y:$(t.y,1.45),z:$(t.z),vx:f*d.x-m*d.z,vy:p,vz:f*d.z+m*d.x,wx:(u()-.5)*26,wy:(u()-.5)*18,wz:(u()-.5)*26,restYaw:u()*Math.PI*2});let h=this.shieldMeshes[s];h.position.set(c.x,c.y,c.z),XU(h.quaternion,n),h.visible=!0,this.shieldMaterials[s].color.setHex(a).lerp(qH,.55);let g=this.bloodLevel===`full`;for(let e=0;e<(g?22:12);e+=1){let t=u()*Math.PI*2,n=g?e%3!=0:this.bloodLevel===`reduced`&&e%3==0;this.spawnDroplet(c.x+(u()-.5)*.03,c.y+(u()-.5)*.03,c.z+(u()-.5)*.03,c.vx*(.5+u()*.6)+Math.sin(t)*.4,c.vy*(.4+u()*.6),c.vz*.5+Math.cos(t)*.4,n?EO(u()):tU,.5+u()*.5,n)}return!0}gougeEye(e,t,n,r,i,a,o=!1){if(this.bloodLevel!==`full`||e<0||e>=BV)return;let s=Math.trunc(e),c=rU(s,a),l=this.eyes[c],u=Number.isSafeInteger(i)?i:0;if(l.active&&(o||l.eventId===u))return;l.active&&this.burstEye(s,a,u),l.active=!0,l.eventId=u,l.socket.set($(t.x),$(t.y,1.6),$(t.z)),l.facing.copy(n),l.hasSkull=!1,l.position.copy(l.socket).addScaledVector(n,JH*1.5),this.eyeDirection.copy(n).multiplyScalar(1.3);let d=UU(r);if(this.eyeDirection.x+=d.x*.5,this.eyeDirection.z+=d.z*.5,l.previous.copy(l.position),o||l.previous.addScaledVector(this.eyeDirection,-.016666666666666666),l.bleeding=o?0:ZH,l.accumulator=0,this.eyeMeshes[c].visible=!0,this.nerveMeshes[c].visible=!0,this.writeEye(c),o)return;let f=WH(u*52711+s*3571+(a===`right`?977:0)+13);for(let e=0;e1e-8&&o.facing.copy(n).normalize(),r!==void 0&&i!==void 0&&(o.skull.set($(r.x),$(r.y,1.6),$(r.z)),XU(o.skullTurn,i),o.hasSkull=!0))}eyeOut(e,t){return t===void 0?this.eyes[rU(e,`left`)]?.active===!0||this.eyes[rU(e,`right`)]?.active===!0:this.eyes[rU(e,t)]?.active===!0}eyePosition(e,t,n){let r=this.eyes[rU(e,`left`)],i=this.eyes[rU(e,`right`)],a=n===`left`||n===void 0&&r?.active===!0?r:i;return a===void 0||!a.active?!1:(t.copy(a.position),!0)}updateEyes(e){for(let[t,n]of this.eyes.entries()){if(!n.active)continue;this.eyeDirection.copy(n.position).sub(n.previous).multiplyScalar(QH),n.previous.copy(n.position),n.position.add(this.eyeDirection),n.position.y-=QV*e*e,this.eyeDirection.copy(n.position).sub(n.socket);let r=this.eyeDirection.length();if(r>.055&&n.position.copy(n.socket).addScaledVector(this.eyeDirection,YH/r),n.hasSkull&&this.restOnFace(n)){n.previous.lerp(n.position,.6),this.eyeDirection.copy(n.position).sub(n.socket);let e=this.eyeDirection.length();e>.055&&n.position.copy(n.socket).addScaledVector(this.eyeDirection,YH/e)}if(n.position.y<0+JH&&(n.position.y=0+JH),this.bloodLevel===`full`&&n.bleeding>0)for(n.bleeding=Math.max(0,n.bleeding-e),n.accumulator+=e*this.forDevice(XH);n.accumulator>=1;){--n.accumulator;let e=.15+this.ambientRandom()*.5;this.spawnDroplet(n.socket.x,n.socket.y-.005,n.socket.z,n.facing.x*e+(this.ambientRandom()-.5)*.2,-.15-this.ambientRandom()*.4,n.facing.z*e+(this.ambientRandom()-.5)*.2,EO(this.ambientRandom()),.9,!0)}this.writeEye(t)}}restOnFace(e){this.eyeTurn.copy(e.skullTurn).invert();let t=this.eyeDirection.copy(e.position).sub(e.skull).applyQuaternion(this.eyeTurn),n=this.eyeSocketLocal.copy(e.socket).sub(e.skull).applyQuaternion(this.eyeTurn).z+JH+eU;if(t.z>=n)return!1;let r=Math.hypot(t.x/$H.x,t.y/$H.y);return r>=1?!1:(n-t.z<=(1-r)*Math.min($H.x,$H.y)||r<1e-6?t.z=n:(t.x/=r,t.y/=r),e.position.copy(e.skull).add(t.applyQuaternion(e.skullTurn)),!0)}writeEye(e){let t=this.eyes[e],n=this.eyeMeshes[e],r=this.nerveMeshes[e];n.position.copy(t.position),this.eyeDirection.copy(t.position).sub(t.socket);let i=this.eyeDirection.length();i>1e-5&&(this.eyeDirection.multiplyScalar(1/i),r.quaternion.setFromUnitVectors(WU,this.eyeDirection),this.eyeDirection.addScaledVector(t.facing,.9).normalize(),n.quaternion.setFromUnitVectors(GU,this.eyeDirection)),r.position.copy(t.socket),r.scale.set(1,Math.max(.001,i-JH*.8),1)}returnMouthpiece(e){let t=Math.trunc(e),n=this.shields[t];n!==void 0&&(Object.assign(n,_B()),this.shieldMeshes[t].visible=!1,this.lastShieldEvent[t]=null)}clearMouthpieces(){for(let[e,t]of this.shields.entries())Object.assign(t,_B()),this.shieldMeshes[e].visible=!1,this.lastShieldEvent[e]=null}updateShields(e){for(let[t,n]of this.shields.entries()){if(!n.out||!n.moving)continue;let r=this.shieldMeshes[t],i=n.age<.3&&!n.sliding,a=n.x,o=n.z;vB(n,r.quaternion,e,0);let s=TE-lB-XV,c=JU(n.x,n.vx,a,s),l=JU(n.z,n.vz,o,s);if(n.x=c.position,n.vx=c.velocity,n.z=l.position,n.vz=l.velocity,r.position.set(n.x,n.y,n.z),i&&this.ambientRandom()e.active).length}get activeStumps(){return[...this.stumps,...this.handStumps].filter(e=>e.active).length}spawnDroplet(e,t,n,r,i,a,o,s,c,l=c?.0035+this.ambientRandom()**3*.0125:.0025+this.ambientRandom()**2*.004,u=`blood`){let d=this.liveDropletsthis.droplets[e].maxLife-this.droplets[e].life;for(let n=0;n0&&t(e[i-1])_H&&e.pop()}}forDevice(e){return Math.round(e*this.budget.droplets*(this.lowTier?.5:1)/NV.droplets)}uploadDroplets(e,t,n){if(this.dropletMesh.count=this.liveDroplets,t<=e)return;this.dropletMesh.instanceMatrix.addUpdateRange(e*16,(t-e)*16),this.dropletMesh.instanceMatrix.needsUpdate=!0;let r=this.dropletMesh.instanceColor;n&&r!==null&&(r.addUpdateRange(e*3,(t-e)*3),r.needsUpdate=!0)}retireDroplet(e){this.oldest.length=0;let t=this.liveDroplets-1,n=this.droplets[e];if(n.alive=!1,this.liveDroplets=t,e!==t){let r=this.droplets[t];this.droplets[e]=r,this.droplets[t]=n,this.dropletPositions.copyWithin(e*3,t*3,t*3+3),this.dropletColors.copyWithin(e*3,t*3,t*3+3),this.dropletMesh.setColorAt(e,this.dropletColor.setRGB(r.r,r.g,r.b)),this.writeDropletMatrix(e,r)}this.dropletPositions[t*3+1]=-50,this.writeDropletMatrix(t,n)}sprayDroplet(e,t,n,r,i,a,o,s,c,l,u,d){this.spawnDroplet(t,n,r,i*e.x-o*e.z,a,i*e.z+o*e.x,s,c,l,u,d)}writeDropletMatrix(e,t){if(!t.alive){this.dropletScale.setScalar(0),this.dropletQuaternion.identity(),this.dropletMatrix.compose(this.dropletVelocity.set(0,-50,0),this.dropletQuaternion,this.dropletScale),this.dropletMesh.setMatrixAt(e,this.dropletMatrix);return}let n=Math.hypot(t.vx,t.vy,t.vz);n>1e-4?(this.dropletVelocity.set(t.vx/n,t.vy/n,t.vz/n),this.dropletQuaternion.setFromUnitVectors(WU,this.dropletVelocity)):this.dropletQuaternion.identity();let r=Math.min(1,t.life/(t.maxLife*.3))*this.dropletCloseness*(t.blood&&this.bloodLevel===`full`?dH:1),i=wO(t.radius*r,n,this.dropletShape);this.dropletScale.set(i.width,i.length,i.width),this.dropletMatrix.compose(this.dropletVelocity.set(t.x,t.y,t.z),this.dropletQuaternion,this.dropletScale),this.dropletMesh.setMatrixAt(e,this.dropletMatrix)}spawnMist(e,t,n,r,i){let a=this.mistIndex%this.budget.mist;this.mistIndex+=1;let o=this.mists[a];o.alive=!0,o.x=$(e),o.y=$(t,1),o.z=$(n),o.maxLife=Math.max(.05,$(i,.5)),o.life=o.maxLife,o.scale=Math.max(.1,$(r,1)),this.mistPositions[a*3]=o.x,this.mistPositions[a*3+1]=o.y,this.mistPositions[a*3+2]=o.z,this.mistColors[a*4+3]=Math.min(1,o.scale),this.mistGeometry.attributes.position.needsUpdate=!0,this.mistGeometry.attributes.color.needsUpdate=!0}placeDecal(e,t,n,r,i,a,o){this.canvasBlood.stain($(e),$(t),Math.max(.01,$(n,.2))*.28,Math.max(.01,$(r,.15))*.28,$(i),G.clamp($(a,.4),0,.95),o)}splashLens(e,t,n,r,i){let a=this.camera;if(a===null||this.bloodLevel===`off`||!(r>0))return;let o=this.lensPoint.set($(e),$(t,1.5),$(n)),s=o.distanceTo(a.position);if(o.project(a),!(o.z<1)||Math.abs(o.x)>1.15||Math.abs(o.y)>1.15)return;let c=G.clamp((vH-s)/8.5,0,1);this.lens.splash((o.x+1)/2,(1-o.y)/2,c*r*(this.bloodLevel===`reduced`?.25:1),i)}ambientRandom(){return this.ambientSeed=Math.imul(this.ambientSeed^this.ambientSeed>>>15,1|this.ambientSeed),this.ambientSeed^=this.ambientSeed+Math.imul(this.ambientSeed^this.ambientSeed>>>7,61|this.ambientSeed),((this.ambientSeed^this.ambientSeed>>>14)>>>0)/4294967296}splatter(e,t,n,r=()=>this.ambientRandom(),i=12,a=oH){if(this.bloodLevel===`off`)return;let o=this.bloodLevel===`reduced`,s=o?Math.ceil(i/4):i,c=o?.35:sH;for(let i=0;i0?$(t.y):e.detail.endsWith(`:body`)?1.05:1.58,z:$(t.z)},f=e.kind===`bleed`,p=n||f?0:Math.round(s?(a?4:6)+Math.min(6,Math.max(0,e.amount)/40):(a?6:16)+Math.min(20,Math.max(0,e.amount)/20)),m={x:0,y:0,z:0,vx:0,vy:0,vz:0,life:0,radius:0,color:EO(0)},h=e.kind===`hit`||e.kind===`counter_hit`,g=h?Math.max(0,e.blood-Math.floor(Math.max(0,e.amount)/3)):0,_=n||e.blood<=0||this.bloodLevel===`off`?0:f?this.bloodLevel===`reduced`?1:Math.min(12,3+Math.floor(Math.max(0,e.amount)/8)):this.bloodLevel===`reduced`?Math.min(24,Math.round(e.blood*(a?.12:.24))):this.forDevice(a?Math.round(vO(e.blood,0)/2):o?vO(e.blood,0)+fH:vO(e.blood,h?e.amount:0));f||(this.shake=Math.min(.14,this.shake+(a?.008:Math.max(.012,e.amount/1500)))),o&&(this.shake=Math.min(.2,this.shake+.09));let v=o?1.2:h?G.clamp((e.amount-40)/60,0,1)*(.6+Math.min(100,e.blood)/150):0;!n&&!f&&e.blood>0&&this.splashLens(d.x,d.y,d.z,v,e.event_id);for(let e=0;e0&&t<=eH){let e=1-tH*t;this.spawnDroplet(m.x,m.y,m.z,m.vx*e,m.vy*e,m.vz*e,m.color,m.life,!0,m.radius*(1-nH*t));continue}let n=t===0,r=(i()-.5)*Math.PI,a=n?2.2+i()*1.8:.9+i()*1.5,o=a,s=.5+i()*1.25,u=(i()-.5)*.5;if(c===`fan`)o=a*(.45+Math.cos(r)*.35),s=.55+i()*1.15,u=Math.sin(r)*a*.9;else if(c===`plume`)o=a*(.25+i()*.25),s=1.8+i()*2.2,u=(i()-.5)*a*.65;else if(c===`body_burst`)o=a*(.55+i()*.45),s=-.15+i()*1.05,u=Math.sin(r)*a*.75;else if(c===`ooze`)o=.08+i()*.22,s=-.3-i()*.55,u=(i()-.5)*.22;else if(c===`impact`)o=a*(.45+i()*.65),s=.9+i()*2.1,u=Math.sin(r)*a;else{let e=n?.12:.34;o=a*(.8+i()*.35),s=n?1.3+i()*1.6:.5+i()*1.25,u=(i()-.5)*a*e}let f=o*l.x-u*l.z,p=o*l.z+u*l.x,h=EO(i()),g=d.x+(i()-.5)*.12,_=d.y+(i()-.5)*.14,v=d.z+(i()-.5)*.12,y=.65+i()*.85;n?(m.x=g,m.y=_,m.z=v,m.vx=f,m.vy=s,m.vz=p,m.color=h,m.life=y,m.radius=.008+i()*.008,this.spawnDroplet(g,_,v,f,s,p,h,y,!0,m.radius)):this.spawnDroplet(g,_,v,f,s,p,h,y,!0)}let y=s?o||e.kind===`counter_hit`||h&&(e.amount>=35||g>=cH):e.kind===`hit`&&e.amount>=70||o||e.kind===`counter_hit`||g>=16;if(!n&&e.blood>0&&this.bloodLevel!==`off`&&y){let t=s?this.forDevice(o?36:12+Math.min(24,Math.floor(g/2)+Math.floor(Math.max(0,e.amount-35)/6))):o?3:2,n=s?1:.35;for(let e=0;e0&&this.bloodLevel!==`off`){let t=o?1+Math.min(2,e.blood/55):.8+Math.min(1.2,g/30);this.splatter(d.x+(i()-.5)*.6,d.z+(i()-.5)*.6,s?t*1.3:t,i,x,o?aH:iH)}let S=e.amount>=70||e.kind===`counter_hit`&&e.amount>=gO,C=h&&(e.amount>=60||S&&g>=cH/4);if(s&&!n&&C&&!e.detail.endsWith(`:body`)){let t=Math.min(20,Math.max(3,Math.round((e.amount-10)/6)));for(let e=0;e0){e.sideLow=1/0,e.sideHigh=-1/0;for(let t=0;t=BV)return;let s=Math.trunc(e),c=Number.isSafeInteger(i)?i:0,l=this.heads[s];if(l.active||this.lastDecapitationEvent[s]===c)return;this.stopGush(s),this.applyBakedPart(l,o,a);let u=WH(c*104729+s*8191+23),d=UU(r);this.lastDecapitationEvent[s]=c,l.active=!0,l.moving=!0,l.eventId=c;let f=1.8+u()*1.1;l.vy=2.3+u()*1.1;let p=(u()-.5)*2.2;l.vx=f*d.x-p*d.z,l.vz=f*d.z+p*d.x,l.vrx=(u()-.5)*12,l.vry=(u()-.5)*12,l.vrz=(u()-.5)*12,l.bounces=0,l.trail=0,l.stained=!1,l.settle=-1,l.mesh.position.set($(t.x),$(t.y,1.55),$(t.z)),XU(l.mesh.quaternion,n),l.mesh.visible=!0;let m=this.stumps[s];m.mesh.material=this.stumpMaterial,m.active=!0,m.fountainLife=14,m.accumulator=0,m.seed=c|1,m.direction=d,m.mesh.position.copy(l.mesh.position),m.mesh.quaternion.copy(l.mesh.quaternion),m.mesh.visible=!0;for(let e=0;e=BV)return;let i=Math.trunc(e),a=Number.isSafeInteger(r)?r:0,o=this.stumps[i];if(o.active||this.lastBurstEvent[i]===a)return;this.lastBurstEvent[i]=a,this.stopGush(i);let s=WH(a*91813+i*6151+41),c=UU(n),l=$(t.x),u=$(t.y,1.6),d=$(t.z),f=(e,t,n,r,a)=>{for(let o=0;o=BV)return;let c=Math.trunc(e)*2+(t===`left`?0:1),l=Number.isSafeInteger(a)?a:0,u=this.hands[c];if(u.active||this.lastDismembermentEvent[c]===l)return;this.applyBakedPart(u,s,o);let d=WH(l*130363+c*12289+37),f=UU(i);this.lastDismembermentEvent[c]=l,u.active=!0,u.moving=!0,u.eventId=l;let p=1.3+d()*1.1;u.vy=1.5+d()*1.2;let m=(d()-.5)*1.8;u.vx=p*f.x-m*f.z,u.vz=p*f.z+m*f.x,u.vrx=(d()-.5)*16,u.vry=(d()-.5)*16,u.vrz=(d()-.5)*16,u.bounces=0,u.trail=0,u.stained=!1,u.mesh.position.set($(n.x),$(n.y,1.25),$(n.z)),XU(u.mesh.quaternion,r),u.mesh.visible=!0;let h=this.handStumps[c];h.active=!0,h.fountainLife=SH,h.accumulator=0,h.seed=l|1,h.direction=f,h.mesh.position.copy(u.mesh.position),h.mesh.quaternion.copy(u.mesh.quaternion),h.mesh.visible=!0;for(let t=0;t=BV)return;let o=Math.trunc(e),s=Number.isSafeInteger(i)?i:0,c=WH(s*69061+o*2741+29),l=UU(r),u=this.tornAxis.copy(n);u.lengthSq()>1e-8&&Number.isFinite(u.lengthSq())||u.set(0,1,0),u.normalize();let d=$(t.x),f=$(t.y,1.2),p=$(t.z);for(let e=0;e{for(let n=0;n=BV)return;let i=Math.trunc(e)*2+(t===`left`?0:1),a=this.handStumps[i];a.active&&(a.mesh.position.set($(n.x),$(n.y,1.2),$(n.z)),XU(a.mesh.quaternion,r))}anchorStump(e,t,n,r,i){if(this.bloodLevel!==`full`||e<0||e>=BV)return;let a=this.stumps[Math.trunc(e)];a.active&&(a.mesh.position.set($(t.x),$(t.y,1.5),$(t.z)),r===void 0||r.length<18?(a.mesh.geometry=this.stumpGeometry,XU(a.mesh.quaternion,n)):(RO(a.flesh,r,a.mesh.position,this.stumpOutward.set(0,1,0).applyQuaternion(n),.01,i),a.mesh.geometry=a.flesh,a.mesh.quaternion.identity()))}restoreFighter(e){if(e<0||e>=BV)return;let t=Math.trunc(e),n=this.heads[t];n.active=!1,n.moving=!1,n.mesh.visible=!1,n.mesh.position.y=-50,this.applyBakedPart(n,void 0,9063730);let r=this.stumps[t];r.active=!1,r.fountainLife=0,r.accumulator=0,r.mesh.visible=!1,r.mesh.position.y=-50,r.mesh.material=this.stumpMaterial,this.clearGibs(t),this.stopGush(t);for(let e of[t*2,t*2+1]){let t=this.eyes[e];t.active=!1,t.bleeding=0,this.eyeMeshes[e].visible=!1,this.nerveMeshes[e].visible=!1}this.clearWounds(t),this.clearGuts(t),this.clearSpine(t),this.clearCorpse(t),this.heart.owner===t&&(this.heart.active=!1,this.heartMesh.visible=!1);for(let e of[t*2,t*2+1]){let t=this.hands[e];t.active=!1,t.moving=!1,t.mesh.visible=!1,t.mesh.position.y=-50,this.applyBakedPart(t,void 0,1920728);let n=this.handStumps[e];n.active=!1,n.fountainLife=0,n.accumulator=0,n.mesh.visible=!1,n.mesh.position.y=-50}}drip(e,t,n,r=0){let i=+(r===1);if(this.bloodLevel===`off`||n||t<=.05){this.stopDrip(i);return}let a=this.dripEmitters[i];a.position.set($(e.x),$(e.y,1.5),$(e.z)),a.rate=this.bloodLevel===`reduced`?Math.min(3,t*3):Math.min(60,t*40),a.active=!0}stopDrip(e){let t=this.dripEmitters[+(e===1)];t.active=!1,t.rate=0,t.accumulator=0}gush(e,t,n,r,i,a,o=`blood`){if(this.bloodLevel!==`full`||e<0||e>=this.gushes.length)return;let s=this.gushes[Math.trunc(e)],c=Number.isSafeInteger(a)?a:0;s.active&&s.eventId===c||(s.active=!0,s.eventId=c,s.fluid=o,s.seconds=Math.max(.1,$(r,1)),s.life=s.seconds,s.rate=Math.max(0,$(i)),s.accumulator=0,this.anchorGush(e,t,n))}anchorGush(e,t,n){let r=this.gushes[Math.trunc(e)];r!==void 0&&r.active&&(r.position.set($(t.x),$(t.y,1.4),$(t.z)),n.lengthSq()>1e-8&&Number.isFinite(n.lengthSq())&&r.axis.copy(n).normalize())}gushing(e){return this.gushes[Math.trunc(e)]?.active===!0}stopGush(e){let t=this.gushes[e];t!==void 0&&(t.active=!1,t.eventId=null)}updateGushes(e){for(let t of this.gushes){if(!t.active)continue;if(t.life-=e,t.life<=0||this.bloodLevel!==`full`){t.active=!1;continue}let n=t.life/t.seconds,r=(t.seconds-t.life)*wH%1,i=Math.exp(-(((r-.5)/FH)**2));if(t.accumulator+=e*this.forDevice(t.rate)*n*(IH+.7*i),!(t.accumulator<1))for(BH.set(Math.abs(t.axis.y)<.9?0:1,+(Math.abs(t.axis.y)<.9),0).cross(t.axis).normalize(),VH.crossVectors(t.axis,BH);t.accumulator>=1;){--t.accumulator;let e=Math.sqrt(this.ambientRandom())*RH,r=this.ambientRandom()*Math.PI*2,a=(LH+this.ambientRandom()*2)*(.5+.5*n)*(.7+.3*i);HH.copy(t.axis).multiplyScalar(Math.cos(e)).addScaledVector(BH,Math.sin(e)*Math.cos(r)).addScaledVector(VH,Math.sin(e)*Math.sin(r)).multiplyScalar(a),this.spawnDroplet(t.position.x+(this.ambientRandom()-.5)*.03,t.position.y+(this.ambientRandom()-.5)*.02,t.position.z+(this.ambientRandom()-.5)*.03,HH.x,HH.y,HH.z,OO(t.fluid,this.ambientRandom()),1.2,!0,(.004+this.ambientRandom()**2*.01)*DO[t.fluid].drop,t.fluid)}}}updateDripEmitters(e){for(let t of this.dripEmitters)if(t.active)for(t.accumulator+=e*t.rate;t.accumulator>=1;)--t.accumulator,this.spawnDroplet(t.position.x+(this.ambientRandom()-.5)*.14,t.position.y-.04,t.position.z+(this.ambientRandom()-.5)*.1,(this.ambientRandom()-.5)*.08,-.25-this.ambientRandom()*.4,(this.ambientRandom()-.5)*.08,EO(this.ambientRandom()),1.1,!0)}spawnTeeth(e,t,n,r){if(this.bloodLevel===`off`)return;let i=this.bloodLevel===`reduced`?+(n>=3):Math.min(12,Math.max(1,Math.round(n)));if(i<=0)return;let a=WH((Number.isSafeInteger(r)?r:0)*7331+91),o=UU(t);for(let t=0;t>3):f.length>>2)}debrisSlot(e){let t=this.debrisCursor.get(e)??0,n=t%e.length;for(let r=0;r=0?n.scale*Math.max(0,n.fading)/bH:n.scale;this.gibScale.set(e*n.stretch,e,e/Math.sqrt(n.stretch))}this.gibMatrix.compose(this.gibPosition,this.gibQuaternion,this.gibScale),e.setMatrixAt(t,this.gibMatrix)}updateDebris(e,t,n,r){let i=!1;for(let[a,o]of e.entries()){if(!o.alive||o.resting&&o.fading<0)continue;if(i=!0,o.fading>=0){o.fading-=n,o.fading<=0&&(o.alive=!1),this.writeDebrisMatrix(t,a,o);continue}o.vy-=6.4*n,o.x+=o.vx*n,o.y+=o.vy*n,o.z+=o.vz*n,o.rx+=o.vrx*n,o.ry+=o.vry*n,o.rz+=o.vrz*n,this.confineGib(o);let e=0+(r===void 0?o.kind===`eye`?JH*RV:.015:r.low*o.scale);if(o.y<=e){if(o.y=e,!o.stained&&this.bloodLevel===`full`&&o.kind!==`tooth`&&o.kind!==`eye`&&(o.stained=!0,r===void 0?this.placeDecal(o.x,o.z,.24+o.scale*.16,.14+o.scale*.1,o.rz,.55,6425104):this.canvasBlood.stain(o.x,o.z,sU[r.shape].stain*o.scale,sU[r.shape].stain*o.scale*.7,o.ry,.6,6425104)),o.bounces.35)o.bounces+=1,o.vy=Math.abs(o.vy)*.3,o.vx*=.68,o.vz*=.68,o.vrx*=.7,o.vry*=.7,o.vrz*=.7;else{if(o.vx=0,o.vy=0,o.vz=0,o.vrx=o.vry=o.vrz=0,o.kind===`shard`&&(o.rx=Math.round(o.rx/Math.PI)*Math.PI),r!==void 0){let e=Math.round(o.rx/Math.PI),t=Math.round(o.rz/Math.PI);o.rx=e*Math.PI,o.rz=t*Math.PI,o.y=0+((e+t)%2==0?r.low:r.high)*o.scale}o.resting=!0}}this.writeDebrisMatrix(t,a,o)}i?t.instanceMatrix.needsUpdate=!0:r!==void 0&&(r.moving=!1)}confineGib(e){Math.abs(e.x)>3.05&&(e.x=Math.sign(e.x)*xE,e.vx*=-.45),Math.abs(e.z)>3.05&&(e.z=Math.sign(e.z)*xE,e.vz*=-.45)}updateDetachedParts(e,t){for(let n of e){if(n.active&&n.settle>=0&&n.settle<1){n.settle=Math.min(1,n.settle+t/YV);let e=n.settle*n.settle*(3-2*n.settle);n.mesh.quaternion.slerpQuaternions(n.settleFrom,n.settleTo,e),n.mesh.position.y=n.settleFromY+(n.settleToY-n.settleFromY)*e}if(!n.active||!n.moving)continue;let e=n.mesh.position.x,r=n.mesh.position.z;if(n.vy-=5.8*t,n.mesh.position.x+=n.vx*t,n.mesh.position.y+=n.vy*t,n.mesh.position.z+=n.vz*t,n.mesh.rotation.x+=n.vrx*t,n.mesh.rotation.y+=n.vry*t,n.mesh.rotation.z+=n.vrz*t,this.bloodLevel===`full`)for(n.trail+=t*this.forDevice(zV),n.trail>=1&&this.trailPoint.copy(n.cap.position).multiply(n.mesh.scale).applyQuaternion(n.mesh.quaternion).add(n.mesh.position);n.trail>=1;)--n.trail,this.spawnDroplet(this.trailPoint.x+(this.ambientRandom()-.5)*.03,this.trailPoint.y+(this.ambientRandom()-.5)*.03,this.trailPoint.z+(this.ambientRandom()-.5)*.03,n.vx*.35+(this.ambientRandom()-.5)*.9,n.vy*.35+(this.ambientRandom()-.5)*.9,n.vz*.35+(this.ambientRandom()-.5)*.9,EO(this.ambientRandom()),.9,!0);let i=TE-n.radius-XV,a=JU(n.mesh.position.x,n.vx,e,i),o=JU(n.mesh.position.z,n.vz,r,i);if(n.mesh.position.x=a.position,n.mesh.position.z=o.position,n.vx=a.velocity,n.vz=o.velocity,n.mesh.position.y<=0+n.radius){if(n.mesh.position.y=0+n.radius,!n.stained&&this.bloodLevel===`full`){n.stained=!0;let e=n.radius===JV?1:.55;this.placeDecal(n.mesh.position.x,n.mesh.position.z,1.3*e,.9*e,n.mesh.rotation.z,.85,4392199)}n.bounces<2&&Math.abs(n.vy)>.42?(n.bounces+=1,n.vy=Math.abs(n.vy)*.32,n.vx*=.62,n.vz*=.62,n.vrx*=.65,n.vry*=.65,n.vrz*=.65):(n.moving=!1,n.vx=0,n.vy=0,n.vz=0,n.vrx=0,n.vry=0,n.vrz=0,n.look!==null&&this.rollOntoEar(n))}Number.isFinite(n.mesh.position.x)&&Number.isFinite(n.mesh.position.y)&&Number.isFinite(n.mesh.position.z)&&Number.isFinite(n.mesh.quaternion.x)&&Number.isFinite(n.mesh.quaternion.y)&&Number.isFinite(n.mesh.quaternion.z)&&Number.isFinite(n.mesh.quaternion.w)||(n.mesh.position.set(0,0+n.radius,0),n.mesh.quaternion.identity(),n.moving=!1,n.vx=0,n.vy=0,n.vz=0)}}rollOntoEar(e){let t=this.settleAxis.set(1,0,0).applyQuaternion(e.mesh.quaternion),n=t.y>=0?1:-1;e.settleFrom.copy(e.mesh.quaternion),e.settleTo.setFromUnitVectors(t,this.settleUp.set(0,n,0)).multiply(e.mesh.quaternion),e.settleFromY=e.mesh.position.y,e.settleToY=0+(n>0?-e.sideLow:e.sideHigh),e.settle=0}stumpRandom(e){let t=e.seed|0;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),e.seed=t|0,((t^t>>>14)>>>0)/4294967296}updateStumpFountains(e){if(this.bloodLevel===`full`)for(let t of[...this.stumps,...this.handStumps]){if(!t.active||t.fountainLife<=0)continue;t.fountainLife=Math.max(0,t.fountainLife-e);let n=Math.min(1,t.fountainLife/CH),r=t.fountainLife*wH%1,i=Math.exp(-(((r-.5)/TH)**2));if(t.accumulator+=e*this.forDevice(EH)*n*(DH+.88*i),t.accumulator<1)continue;let a=UH(t,zH);for(BH.set(Math.abs(a.y)<.9?0:1,+(Math.abs(a.y)<.9),0).cross(a).normalize(),VH.crossVectors(a,BH);t.accumulator>=1;){--t.accumulator;let e=this.stumpRandom(t),r=this.stumpRandom(t),o=this.stumpRandom(t),s=Math.sqrt(e)*AH,c=r*Math.PI*2;HH.copy(a).multiplyScalar(Math.cos(s)).addScaledVector(BH,Math.sin(s)*Math.cos(c)).addScaledVector(VH,Math.sin(s)*Math.sin(c)).multiplyScalar(G.lerp(OH,kH,o)*(.7+.3*i)*(.55+.45*n)),this.spawnDroplet(t.mesh.position.x+a.x*.015+(e-.5)*.03,t.mesh.position.y+a.y*.015,t.mesh.position.z+a.z*.015+(r-.5)*.03,HH.x,HH.y,HH.z,EO(e),1.2+o*.6,!0,.004+o*o*.01)}}}update(e){for(this.canvasBlood.update(KU(e)),this.lens.update(KU(e)),this.simulationRemainder+=KU(e);this.simulationRemainder+1e-9>=gH;)this.simulationRemainder=Math.max(0,this.simulationRemainder-gH),this.simulate(gH);for(let e of this.guts)e.active&&e.sinceDrop<0&&e.rope.hold(e.anchor)&&(e.moved=!0),e.moved&&=(e.tube.write(e.rope),!1)}simulate(e){this.shake*=.02**e,this.updateDripEmitters(e),this.updateGushes(e),this.updateStumpFountains(e),this.updateDetachedParts(this.heads,e),this.updateDetachedParts(this.hands,e),this.updateShields(e),this.updateEyes(e),this.updateDebris(this.gibs,this.gibMesh,e),this.updateDebris(this.shards,this.shardMesh,e),this.updateDebris(this.eyeballs,this.eyeballMesh,e);for(let t of this.viscera)t.moving&&this.updateDebris(t.pieces,t.mesh,e,t);this.updateWounds(e),this.updateParts(e),this.updateSpines(e),this.updateGuts(e),this.updateHeart(e),this.updateCorpses(e);let t=this.liveDroplets,n=!1;for(let t=0;t0&&(this.dropletBuffers.position.needsUpdate=!0,this.dropletBuffers.color.needsUpdate=!0,this.uploadDroplets(0,this.liveDroplets,n));let r=!1;for(let[t,n]of this.mists.entries()){if(!n.alive)continue;if(r=!0,n.life-=e,n.life<=0){n.alive=!1,this.mistPositions[t*3+1]=-50;continue}let i=1-n.life/n.maxLife;this.mistPositions[t*3]=n.x,this.mistPositions[t*3+1]=n.y+i*.14,this.mistPositions[t*3+2]=n.z,this.mistColors[t*4+3]=Math.max(0,1-i)*Math.min(1,n.scale)}r&&(this.mistGeometry.attributes.position.needsUpdate=!0,this.mistGeometry.attributes.color.needsUpdate=!0)}clearDroplets(e){let t=this.liveDroplets;for(let t=0;t0))return;let s=WH((Number.isSafeInteger(i)?i:0)*15485863+e.charCodeAt(0)*131+e.length*977+7),c=UU(n),l=Math.max(.2,$(a,1)),u=$(t.x),d=$(t.y,1.2),f=$(t.z),p=Math.min(Math.round(r),this.debrisPlaces(e));for(let t=0;t0))return;let o=Number.isSafeInteger(i)?i:0,s=WH(o*86243+aU.indexOf(e)*3331+59),c=UU(n),l=DO[e],u=Math.max(.2,$(a,1)),d=$(t.x),f=$(t.y,1.2),p=$(t.z),m=Math.min(oU,r);for(let t=this.forDevice(m);t>0;--t){let t=s()*Math.PI*2,n=(.5+s()*1.9)*u;this.sprayDroplet(c,d+(s()-.5)*.08,f+(s()-.5)*.08,p+(s()-.5)*.08,(.4+s()*1.9)*u+Math.sin(t)*n*.35,(.3+s()*2.3)*Math.sqrt(u),Math.cos(t)*n*.8,OO(e,s()),.7+s(),!0,(.004+s()**2*.013)*l.drop,e)}if(e===`blood`){for(let e=Math.min(48,Math.round(m/25));e>0;--e)this.spawnMist(d+(s()-.5)*.4,f+(s()-.5)*.3,p+(s()-.5)*.4,.9+s()*1.5,.6+s()*.7);this.splatter(d+c.x*.3,p+c.z*.3,1+Math.min(2.4,m/500),s,Math.min(50,Math.round(m/20))),this.splashLens(d,f,p,Math.min(3,m/350),o)}else for(let e=Math.min(10,Math.round(m/30));e>0;--e){let t=.2+s()*.9*u;this.placeDecal(d+c.x*t+(s()-.5)*.5,p+c.z*t+(s()-.5)*.5,.5+s()*.9,.3+s()*.7,s()*Math.PI,.7*l.soak,e%2==0?l.splash:l.stain)}this.shake=Math.min(.22,this.shake+Math.min(.06,m/2e4))}puddle(e,t,n,r,i){if(this.bloodLevel!==`full`)return;let a=DO[r];this.canvasBlood.pool($(e),$(t),Math.max(.02,$(n,.1)),.95*a.soak,i,a.pool)}smear(e,t,n,r,i){this.bloodLevel===`full`&&this.canvasBlood.smear(e,t,n,r,Math.max(.005,$(i,.05)),.75,DO.blood.splash)}footprint(e,t,n,r,i){this.bloodLevel===`full`&&i>0&&this.canvasBlood.print(e,t,n,r,Math.min(1,i)*.85,DO.blood.splash)}setWound(e,t,n,r=`blood`){let i=this.woundAt(e,t);if(i===null)return;let a=this.bloodLevel===`full`?G.clamp($(n),0,1):0;a>0&&i.strength<=0&&(i.anchored=!1,i.accumulator=0,i.run=0,i.pool=0),i.strength=a,i.fluid=r,this.shareWounds()}anchorWound(e,t,n,r){let i=this.woundAt(e,t);i===null||i.strength<=0||(i.position.set($(n.x),$(n.y,1.2),$(n.z)),r.lengthSq()>1e-8&&Number.isFinite(r.lengthSq())&&i.axis.copy(r).normalize(),i.anchored=!0)}woundStrength(e,t){return this.woundAt(e,t)?.strength??0}clearWounds(e){for(let[t,n]of this.wounds.entries())(e===void 0||Math.floor(t/he.length)===Math.trunc(e))&&(n.strength=0);this.shareWounds()}get openWounds(){return this.woundsOpen}woundAt(e,t){let n=Math.trunc(e);return n>=0&&npU?pU/e:1}updateWounds(e){if(this.woundsOpen!==0&&this.bloodLevel===`full`){this.woundClock+=e;for(let t=0;t=mU){n.run-=mU;let e=.12+fU*r*r,i=l.y*e,a=(i+Math.sqrt(i*i+2*QV*Math.max(0,u.y-0)))/QV,o=u.x+l.x*e*a,s=u.z+l.z*e*a;n.pool<=0||Math.hypot(o-n.poolX,s-n.poolZ)>Math.max(.12,n.pool*1.2)?(n.poolX=o,n.poolZ=s,n.pool=.03):n.pool=Math.min(hU*(.25+.75*r),n.pool+.012);let c=DO[n.fluid];this.canvasBlood.pool(n.poolX,n.poolZ,n.pool,.95*c.soak,t*7+Math.round(n.pool*80),c.pool)}if(n.accumulator<1)continue;BH.set(Math.abs(l.y)<.9?0:1,+(Math.abs(l.y)<.9),0).cross(l).normalize(),VH.crossVectors(l,BH);let d=G.lerp(.8,AH*.8,r),f=DO[n.fluid].drop;for(;n.accumulator>=1;){--n.accumulator;let e=Math.sqrt(this.ambientRandom())*d,t=this.ambientRandom()*Math.PI*2;HH.copy(l).multiplyScalar(Math.cos(e)).addScaledVector(BH,Math.sin(e)*Math.cos(t)).addScaledVector(VH,Math.sin(e)*Math.sin(t)).multiplyScalar(c*(.75+this.ambientRandom()*.4)),this.spawnDroplet(u.x+l.x*.012+(this.ambientRandom()-.5)*.02,u.y+l.y*.012,u.z+l.z*.012+(this.ambientRandom()-.5)*.02,HH.x,HH.y,HH.z,OO(n.fluid,this.ambientRandom()),1.3+r*.5,!0,(.004+this.ambientRandom()**2*.01)*f,n.fluid)}}}}burstEye(e,t,n){let r=Math.trunc(e),i=rU(r,t),a=this.eyes[i];if(r<0||r>=BV||a===void 0||!a.active)return!1;if(a.active=!1,a.bleeding=0,this.eyeMeshes[i].visible=!1,this.nerveMeshes[i].visible=!1,this.bloodLevel!==`full`)return!0;let o=Number.isSafeInteger(n)?n:0,s=WH(o*39916801+i*211+3),{x:c,y:l,z:u}=a.position;for(let e=this.forDevice(160);e>0;--e){let t=s()*Math.PI*2,n=s()*1.6-.6,r=Math.sqrt(Math.max(0,1-Math.min(1,n*n))),i=.6+s()*2.2,a=e%3!=0;this.spawnDroplet(c,l,u,Math.cos(t)*r*i,n*i+.5,Math.sin(t)*r*i,a?EO(s()):tU,.5+s()*.7,a,.003+s()**2*.008)}for(let e=0;e<4;e+=1)this.spawnGib(c,l,u,(s()-.5)*1.6,.4+s()*1.2,(s()-.5)*1.6,s,`flesh`,r);for(let e=0;e<8;e+=1)this.spawnMist(c+(s()-.5)*.12,l+(s()-.5)*.1,u+(s()-.5)*.12,.5+s()*.6,.4+s()*.4);return this.splashLens(c,l,u,.8,o),!0}skinOf(e,t){let n=QU(t.sites===aA,e.map),r=e.look??mj;return n.look?.set(r),n.material.color.setHex(e.color),n.injury.copyFrom(t),n.injury.setBindToPart(aW(e.geometry,r,this.bindToPartMatrix)),t.material instanceof jb&&(n.material.clearcoat=t.material.clearcoat),n.material}flingPart(e,t,n,r,i,a,o={}){this.removePart(e);let s=this.partBox.makeEmpty();for(let e of t){let t=e.geometry.getAttribute(`position`),n=e.geometry.getIndex(),r=n===null?t.count:n.count;for(let e=0;ep.reach)&&(p=e),(m===null||e.height>m.height)&&(m=e);for(let{fan:e,opening:t}of f)e.materialIndex=rW(o.part,t===p,t===m);c.cut.set(0,0,0),p!==null&&c.cut.copy(p.centre).sub(l),XU(c.group.quaternion,r),c.group.position.copy(l).applyQuaternion(c.group.quaternion),c.group.position.set(c.group.position.x+$(n.x),c.group.position.y+$(n.y,1.2),c.group.position.z+$(n.z)),c.group.visible=!0,c.key=e,c.born=this.partsThrown++;let h=0;for(let t=0;tt.key===e)}partPosition(e,t){let n=this.parts.find(t=>t.key===e);return n!==void 0&&(t.copy(n.group.position),!0)}removePart(e){for(let t of this.parts)if(t.key===e){t.key=null,t.moving=!1,t.settle=-1,t.group.visible=!1,t.group.clear();for(let e of t.geometries)e.dispose();for(let e of t.materials)e.dispose();t.geometries.length=0,t.materials.length=0}}get activeParts(){let e=0;for(let t of this.parts)t.key!==null&&(e+=1);return e}partResting(e){return this.parts.some(t=>t.key===e&&!t.moving&&(t.settle<0||t.settle>=1))}updateParts(e){let t=this.bloodLevel===`full`;for(let n=0;n=0&&r.settle<1){r.settle=Math.min(1,r.settle+e/YV);let t=r.settle*r.settle*(3-2*r.settle);i.quaternion.slerpQuaternions(r.settleFrom,r.settleTo,t),i.position.y=r.settleFromY+(r.settleToY-r.settleFromY)*t}if(!r.moving){if(!t||r.lain>=xU)continue;let a=Math.floor(r.lain/SU);for(r.lain+=e,this.trailPoint.copy(r.cut).applyQuaternion(i.quaternion).add(i.position),r.trail+=e*this.forDevice(CU);r.trail>=1;)--r.trail,this.spawnDroplet(this.trailPoint.x,Math.max(.02,this.trailPoint.y),this.trailPoint.z,(this.ambientRandom()-.5)*.5,.2+this.ambientRandom()*.5,(this.ambientRandom()-.5)*.5,EO(this.ambientRandom()),.6,!0);if(Math.floor(r.lain/SU)===a)continue;let o=.1+r.radius*1.8;r.pool=Math.min(o,r.pool+o*SU*1.5/xU),this.canvasBlood.pool(this.trailPoint.x,this.trailPoint.z,r.pool,.95,n*13+a);continue}let a=i.position.x,o=i.position.z;if(r.vy-=5.8*e,i.position.x+=r.vx*e,i.position.y+=r.vy*e,i.position.z+=r.vz*e,i.rotation.x+=r.vrx*e,i.rotation.y+=r.vry*e,i.rotation.z+=r.vrz*e,t)for(r.trail+=e*this.forDevice(zV),r.trail>=1&&this.trailPoint.copy(r.cut).applyQuaternion(i.quaternion).add(i.position);r.trail>=1;)--r.trail,this.spawnDroplet(this.trailPoint.x+(this.ambientRandom()-.5)*.03,this.trailPoint.y+(this.ambientRandom()-.5)*.03,this.trailPoint.z+(this.ambientRandom()-.5)*.03,r.vx*.35+(this.ambientRandom()-.5)*.9,r.vy*.35+(this.ambientRandom()-.5)*.9,r.vz*.35+(this.ambientRandom()-.5)*.9,EO(this.ambientRandom()),.9,!0);let s=Math.max(.5,TE-r.reach-XV),c=JU(i.position.x,r.vx,a,s),l=JU(i.position.z,r.vz,o,s);if(i.position.x=c.position,i.position.z=l.position,r.vx=c.velocity,r.vz=l.velocity,i.position.y<=0+r.radius){if(i.position.y=0+r.radius,!r.stained&&t){r.stained=!0;let e=Math.min(2.4,r.radius/JV+.3);this.placeDecal(i.position.x,i.position.z,1.3*e,.9*e,i.rotation.z,.85,4392199)}if(r.bounces<2&&Math.abs(r.vy)>.42)r.bounces+=1,r.vy=Math.abs(r.vy)*.32,r.vx*=.62,r.vz*=.62,r.vrx*=.65,r.vry*=.65,r.vrz*=.65;else{r.moving=!1,r.trail=0;let e=this.settleAxis.copy(r.thin).applyQuaternion(i.quaternion);r.settleFrom.copy(i.quaternion),r.settleTo.setFromUnitVectors(e,this.settleUp.set(0,e.y>=0?1:-1,0)).multiply(i.quaternion),r.settleFromY=i.position.y,r.settleToY=0+r.thickness,r.settle=0}}Number.isFinite(i.position.x+i.position.y+i.position.z+i.quaternion.x+i.quaternion.y+i.quaternion.z+i.quaternion.w)||(i.position.set(0,0+r.thickness,0),i.quaternion.identity(),r.moving=!1,r.settle=-1)}}attachSpine(e){let t=this.spines[Math.trunc(e)];t!==void 0&&this.bloodLevel===`full`&&(t.wanted=!0)}spineOut(e){return this.spines[Math.trunc(e)]?.out===!0}spineTail(e,t){let n=this.spines[Math.trunc(e)];return n===void 0||!n.out?!1:(n.rope.node(wU,t),!0)}updateSpines(e){for(let t=0;t=1;){--n.trail;let e=a.node(Math.floor(this.ambientRandom()*12),this.gibPosition);this.spawnDroplet(e.x,e.y,e.z,(this.ambientRandom()-.5)*.8,(this.ambientRandom()-.5)*.8,(this.ambientRandom()-.5)*.8,EO(this.ambientRandom()),.8,!0)}}}}writeSpine(e){let t=this.spines[e].rope;for(let n=0;n1e-6?i.multiplyScalar(1/a):i.set(0,1,0)),r.add(this.partVertex).multiplyScalar(.5);let o=(.9+.5*Math.min(1,n/6))*(n>=9?.55+.25*(10-n):1);this.gibMatrix.compose(r,this.gibQuaternion,this.gibScale.set(o,this.spineStretch,o)),this.spineMesh.setMatrixAt(e*wU+n,this.gibMatrix)}this.spineMesh.instanceMatrix.needsUpdate=!0;for(let n=0;ne.out);this.spineMesh.visible=n,this.shredMesh.visible=n}spillGuts(e,t,n,r=18){let i=this.guts[Math.trunc(e)];if(i===void 0||e<0||this.bloodLevel!==`full`)return;let a=Number.isSafeInteger(n)?n:0;if(i.active&&i.eventId===a)return;let o=G.clamp(Math.round($(r,18)),2,OU),s=Math.max(2,Math.min(o,this.lowTier?Math.ceil(this.budget.gutLinks/2):this.budget.gutLinks));i.active=!0,i.eventId=a,i.sinceDrop=-1,i.drip=0,i.smeared.fill(NaN),i.anchor.set($(t.x),$(t.y,.9),$(t.z)),i.rope.spill(s,o*SV/s,i.anchor,s/kU,WH(a*28657+Math.trunc(e)*5+1)),i.tube.write(i.rope),i.mesh.visible=!0,i.moved=!1}anchorGuts(e,t,n){let r=this.guts[Math.trunc(e)];r===void 0||!r.active||r.sinceDrop>=0||(r.anchor.set($(t.x),$(t.y,.9),$(t.z)),n.lengthSq()>1e-8&&Number.isFinite(n.lengthSq())&&r.away.copy(n).normalize())}gutsOut(e){return this.guts[Math.trunc(e)]?.active===!0}dropGuts(e){let t=this.guts[Math.trunc(e)];t===void 0||!t.active||t.sinceDrop>=0||(t.sinceDrop=0,t.rope.release())}clearGuts(e){for(let[t,n]of this.guts.entries())(e===void 0||t===Math.trunc(e))&&(n.active=!1,n.eventId=null,n.moved=!1,n.rope.clear(),n.mesh.visible=!1)}gutsLength(e){let t=this.guts[Math.trunc(e)];return t===void 0||!t.active?0:t.rope.length}gutsPoint(e,t,n){let r=this.guts[Math.trunc(e)];return r===void 0||!r.active?!1:(r.rope.node(Math.round(G.clamp(t,0,1)*(r.rope.nodes-1)),n),!0)}updateGuts(e){for(let t=0;t=0&&n.sinceDrop=AU&&i)){let e=r.node(r.nodes>>1,this.gibPosition);this.canvasBlood.pool(e.x,e.z,.26,.95,t+3),this.puddle(e.x+.12,e.z+.05,.11,`bile`,t+5)}if(r.step(e,n.anchor,0,Math.max(2.4383999999999997,Math.abs(n.anchor.x),Math.abs(n.anchor.z)),n.away)&&(n.moved=!0,i)){for(let e=0;e0+.024*1.5){n.smeared[e*2]=NaN;continue}let i=n.smeared[e*2],a=n.smeared[e*2+1],o=Math.hypot(t.x-i,t.z-a);o=0))for(n.drip+=e*this.forDevice(PU);n.drip>=1;){--n.drip;let e=r.node(Math.floor(this.ambientRandom()*r.nodes),this.gibPosition),t=this.ambientRandom()<.8?`blood`:`bile`;this.spawnDroplet(e.x,e.y-xV,e.z,(this.ambientRandom()-.5)*.3,-.1,(this.ambientRandom()-.5)*.3,OO(t,this.ambientRandom()),.9,!0,.004+this.ambientRandom()*.005,t)}}}}ejectHeart(e,t,n,r=-1){if(this.bloodLevel!==`full`)return;let i=this.heart,a=WH((Number.isSafeInteger(n)?n:0)*611953+19),o=UU(t),s=2+a()*1.2,c=(a()-.5)*1.2;i.active=!0,i.moving=!0,i.owner=Math.trunc(r),i.age=0,i.beats=0,i.bounces=0,i.settle=-1,i.pool=0,i.trail=0,i.vx=s*o.x-c*o.z,i.vy=1.8+a()*1.2,i.vz=s*o.z+c*o.x,i.vrx=(a()-.5)*14,i.vry=(a()-.5)*14,i.vrz=(a()-.5)*14,i.settleTo.setFromAxisAngle(WU,a()*Math.PI*2).multiply(IU),this.heartMesh.position.set($(e.x),$(e.y,1.2),$(e.z)),this.heartMesh.quaternion.identity(),this.heartMesh.scale.setScalar(FU),this.heartMesh.visible=!0}get heartOut(){return this.heart.active}get heartBeating(){return this.heart.active&&this.heart.age<14}heartPosition(e){return this.heart.active?(e.copy(this.heartMesh.position),!0):!1}updateHeart(e){let t=this.heart;if(!t.active)return;let n=this.heartMesh,r=this.bloodLevel===`full`;if(t.moving){let i=n.position.x,a=n.position.z;t.vy-=6.4*e,n.position.x+=t.vx*e,n.position.y+=t.vy*e,n.position.z+=t.vz*e,n.rotation.x+=t.vrx*e,n.rotation.y+=t.vry*e,n.rotation.z+=t.vrz*e;let o=TE-this.heartRadius-XV,s=JU(n.position.x,t.vx,i,o),c=JU(n.position.z,t.vz,a,o);if(n.position.x=s.position,n.position.z=c.position,t.vx=s.velocity,t.vz=c.velocity,r)for(t.trail+=e*this.forDevice(zV/2);t.trail>=1;)--t.trail,this.spawnDroplet(n.position.x,n.position.y,n.position.z,t.vx*.3+(this.ambientRandom()-.5)*.8,t.vy*.3+(this.ambientRandom()-.5)*.8,t.vz*.3+(this.ambientRandom()-.5)*.8,EO(this.ambientRandom()),.8,!0);n.position.y<=0+this.heartRadius&&(n.position.y=0+this.heartRadius,t.bounces===0&&r&&this.placeDecal(n.position.x,n.position.z,.9,.7,n.rotation.z,.8,4392199),t.bounces<2&&Math.abs(t.vy)>.4?(t.bounces+=1,t.vy=Math.abs(t.vy)*.3,t.vx*=.6,t.vz*=.6,t.vrx*=.6,t.vry*=.6,t.vrz*=.6):(t.moving=!1,t.settle=0,t.settleFrom.copy(n.quaternion),t.settleFromY=n.position.y)),Number.isFinite(n.position.x+n.position.y+n.position.z)||(n.position.set(0,0+this.heartRest,0),n.quaternion.copy(t.settleTo),t.moving=!1,t.settle=1)}else if(t.settle<1){t.settle=Math.min(1,t.settle+e/YV);let r=t.settle*t.settle*(3-2*t.settle);n.quaternion.slerpQuaternions(t.settleFrom,t.settleTo,r),n.position.y=t.settleFromY+(0+this.heartRest-t.settleFromY)*r}if(t.age>=14)return;t.age+=e;let i=sV(t.age),a=oV(t.age),o=cV(a)*(.35+.65*i);if(n.scale.set(FU*(1-.17*o),FU*(1+.08*o),FU*(1-.17*o)),Math.floor(a)<=t.beats||(t.beats=Math.floor(a),!r))return;let s=this.trailPoint.copy(rV.position).multiply(n.scale).applyQuaternion(n.quaternion).add(n.position),c=zH.copy(rV.direction).applyQuaternion(n.quaternion);BH.set(Math.abs(c.y)<.9?0:1,+(Math.abs(c.y)<.9),0).cross(c).normalize(),VH.crossVectors(c,BH);for(let e=this.forDevice(Math.round(8+LU*i));e>0;--e){let e=Math.sqrt(this.ambientRandom())*.2,t=this.ambientRandom()*Math.PI*2;HH.copy(c).multiplyScalar(Math.cos(e)).addScaledVector(BH,Math.sin(e)*Math.cos(t)).addScaledVector(VH,Math.sin(e)*Math.sin(t)).multiplyScalar((.7+2.9*i)*(.5+.55*this.ambientRandom())),this.spawnDroplet(s.x,s.y,s.z,HH.x,HH.y,HH.z,EO(this.ambientRandom()),1.1,!0,.004+this.ambientRandom()**2*.011)}t.moving||(t.pool=Math.min(.3,t.pool+.022),this.canvasBlood.pool(n.position.x,n.position.z,t.pool,.95,t.beats))}setCorpse(e,t){let n=Math.trunc(e),r=this.corpses[n];r!==void 0&&(t===null||this.bloodLevel!==`full`?this.clearCorpse(n):(r.active||(r.active=!0,r.age=0,r.puddle=0),r.position.set($(t.x),Math.max(0,$(t.y,0)),$(t.z))))}fliesOver(e){let t=this.corpses[Math.trunc(e)];return t===void 0||!t.active?0:this.fliesArrived(t.age)}fliesArrived(e){let t=this.lowTier?this.budget.flies>>1:this.budget.flies;return Math.floor(G.clamp((e-RU)/zU,0,1)*t)}updateCorpses(e){for(let t=0;t=n.puddle+.04&&(n.puddle=r,this.puddle(n.position.x,n.position.z,r,`urine`,t*11+Math.round(r*25)));let i=this.fliesArrived(n.age);if(i===0)continue;let a=this.budget.flies,o=zU/(this.lowTier?a>>1:a);for(let e=0;e=i)this.gibMatrix.makeScale(0,0,0).setPosition(0,-50,0);else{let t=Math.min(1,(n.age-RU-e*o)/BU),i=MV(this.flies,r,n.age,this.gibPosition),a=1+(1-t)*2.5;this.gibMatrix.makeTranslation(n.position.x+i.x*a,Math.max(.03,n.position.y+i.y+(1-t)*(1-t)*1.6),n.position.z+i.z*a)}this.flyMesh.setMatrixAt(r,this.gibMatrix)}this.flyMesh.visible=!0,this.flyMesh.instanceMatrix.needsUpdate=!0}}clearCorpse(e){let t=this.corpses[e];if(t.active){t.active=!1,this.gibMatrix.makeScale(0,0,0).setPosition(0,-50,0);for(let t=0;te.active)}}dispose(){this.scene.remove(this.dropletMesh),this.scene.remove(this.mistPoints),this.scene.remove(this.gibMesh),this.scene.remove(this.shardMesh),this.scene.remove(this.eyeballMesh);for(let e of this.viscera)this.scene.remove(e.mesh),e.mesh.dispose(),e.geometry.dispose();this.visceraMaterial.dispose();for(let e of this.parts)e.key!==null&&this.removePart(e.key),this.scene.remove(e.group);this.limbMaterial.dispose(),this.limbMap.dispose(),this.trunkMaterial.dispose(),this.trunkMap.dispose(),this.scene.remove(this.spineMesh,this.shredMesh,this.heartMesh,this.flyMesh),this.spineMesh.dispose(),this.shredMesh.dispose(),this.shredGeometry.dispose();for(let e of this.guts)this.scene.remove(e.mesh),e.tube.dispose();this.heartGeometry.dispose(),this.flyMesh.dispose(),this.flyGeometry.dispose(),this.flyMaterial.dispose(),this.dropletMesh.dispose(),this.dropletGeometry.dispose(),this.dropletMaterial.dispose(),this.canvasBlood.dispose();for(let e of[...this.heads,...this.hands])e.baked?.dispose(),e.bakedFlesh?.dispose();for(let e of[...this.stumps,...this.handStumps])e.flesh.dispose();this.mistGeometry.dispose(),this.mistMaterial.dispose(),this.mistMap.dispose(),this.gibMesh.dispose(),this.gibGeometry.dispose(),this.gibMaterial.dispose(),this.shardMesh.dispose(),this.eyeballMesh.dispose(),this.shardGeometry.dispose(),this.shardMaterial.dispose(),this.jawMaterial.dispose(),this.jawMap.dispose(),this.headGeometry.dispose();for(let e of this.headMaterials)e.dispose();this.handGeometry.dispose();for(let e of this.handMaterials)e.dispose();this.stumpGeometry.dispose(),this.wristStumpGeometry.dispose(),this.shieldGeometry.dispose();for(let e of this.shieldMaterials)e.dispose();for(let e of this.shieldMeshes)this.scene.remove(e);this.eyeGeometry.dispose(),this.eyeMap.dispose(),this.eyeMaterial.dispose(),this.nerveGeometry.dispose(),this.nerveMaterial.dispose();for(let e of[...this.eyeMeshes,...this.nerveMeshes])this.scene.remove(e);if(this.stumpMaterial.dispose(),this.stumpMap.dispose(),this.wristMaterial.dispose(),this.wristMap.dispose(),this.bakedStandIns!==null){this.bakedStandIns.map.dispose();for(let e of this.bakedStandIns.materials)e.dispose();for(let e of this.bakedStandIns.instanced)e.dispose();this.bakedStandIns=null}for(let e of this.heads)this.scene.remove(e.mesh);for(let e of this.hands)this.scene.remove(e.mesh);for(let e of[...this.stumps,...this.handStumps])this.scene.remove(e.mesh)}},cW={maximum:1,minimum:.55,slowMs:24,fastMs:17.5,windowMs:1e3,step:.15},lW=10,uW=10,dW=160,fW=3,pW=3,mW=class{options;scale;elapsed=0;frames=0;fastWindows=0;holdWindows=0;fruitlessAttempts=0;pending=null;raised=null;raiseHoldWindows=0;failedRaises=0;constructor(e=cW){this.options=e,this.scale=e.maximum}record(e){if(!(e>0)||e>1e3||(this.elapsed+=e,this.frames+=1,this.elapsede.before*.9)return this.scale=e.previous,this.holdWindows=Math.min(dW,lW*2**this.fruitlessAttempts),this.fruitlessAttempts+=1,!0;this.fruitlessAttempts=0}if(this.raised!==null){let e=this.raised;if(t>this.options.slowMs)return this.raised=null,this.scale=e.previous,this.fastWindows=0,this.raiseHoldWindows=Math.min(dW,uW*2**this.failedRaises),this.failedRaises+=1,!0;e.windows+=1,e.windows>=pW&&(this.raised=null,this.failedRaises=0)}if(t>this.options.slowMs){if(this.fastWindows=0,this.holdWindows>0)return--this.holdWindows,!1;if(this.scale<=this.options.minimum)return!1;let e=this.scale;return this.scale=Math.max(this.options.minimum,this.scale-this.options.step),this.pending={before:t,previous:e},!0}return t0?(--this.raiseHoldWindows,!1):this.fastWindows>=fW&&this.scale0&&e.poise===0)return 1;if(e.is_downed)return gW;let n=e.stunned_ticksthis.value?7:.9;return this.value+=(e-this.value)*(1-Math.exp(-n*Math.max(0,t))),e===0&&this.value<.003&&(this.value=0),this.value}},yW=.4,bW=.5,xW={before:24,after:24,speed:.5};function SW(e,t,n=30,r=yW,i=42,a=33){let o=t.tick-i,s=t.tick+a,c=e.filter(e=>e.tick>=o-1&&e.tick<=s+1),l=c.at(-1),u=l!==void 0&&l.result!==null&&l.tick({...l,tick:l.tick+t+1,events:[]}))]:c,d=u[0],f=u.at(-1);if(d===void 0||f===void 0||u.length<8||d.tick>t.tick-12||f.tick=1&&this.lastHeat<1&&!r&&(this.flare=1),this.lastHeat=t,this.flare=Math.max(0,this.flare-n/DW);let a=this.mesh.material;if(a.opacity=Math.min(1,t*.8+this.flare*.6),this.mesh.visible=a.opacity>.01,!this.mesh.visible)return;this.mesh.position.copy(e),this.mesh.quaternion.copy(i.quaternion);let o=TW*(.55+.45*t)*(1+this.flare*EW);this.mesh.scale.set(o,o,1)}get active(){return this.mesh.visible}standIn(){return new Y(this.mesh.geometry,this.mesh.material)}reset(){this.flare=0,this.lastHeat=0,this.mesh.material.opacity=0,this.mesh.visible=!1}dispose(){this.mesh.geometry.dispose(),this.mesh.material.dispose()}},FW=class{group=new t_;flash;ring;age=1/0;constructor(e){this.flash=NW(e,new J(1,.86,.62)),this.flash.material.depthTest=!1,this.ring=new Y(new gb(.42,.5,40),new yv({color:wW,blending:2,depthWrite:!1,transparent:!0,side:2})),this.flash.renderOrder=6,this.ring.renderOrder=6,this.group.add(this.flash,this.ring),this.group.visible=!1}fire(e){this.age=0,this.group.position.copy(e)}update(e,t){this.age+=e;let n=this.age/OW,r=this.age/AW;if(this.group.visible=r<1,!this.group.visible)return;this.group.quaternion.copy(t.quaternion),this.flash.visible=n<1;let i=kW*(.35+.65*Math.sqrt(Math.min(1,n)));this.flash.scale.set(i,i,1),this.flash.material.opacity=(1-Math.min(1,n))**2;let a=jW*(.15+.85*(1-(1-r)**3));this.ring.scale.set(a,a,a),this.ring.material.opacity=.9*(1-r)}get active(){return this.group.visible}standIns(){return[new Y(this.flash.geometry,this.flash.material),new Y(this.ring.geometry,this.ring.material)]}reset(){this.age=1/0,this.group.visible=!1}dispose(){this.flash.geometry.dispose(),this.flash.material.dispose(),this.ring.geometry.dispose(),this.ring.material.dispose()}},IW=10,LW=.055,RW=3.2,zW=1.4,BW=class{color;mesh;geometry;positions=new Float32Array(60);colors=new Float32Array(80);history=[];last=new q;hasLast=!1;tangent=new q;side=new q;toCamera=new q;shade=new J;strength=0;heat=0;constructor(e){this.color=e,this.geometry=new iv,this.geometry.setAttribute(`position`,new U_(this.positions,3).setUsage(gh)),this.geometry.setAttribute(`color`,new U_(this.colors,4).setUsage(gh));let t=[];for(let e=0;e<9;e+=1){let n=e*2;t.push(n,n+1,n+2,n+1,n+3,n+2)}this.geometry.setIndex(t);let n=new yv({vertexColors:!0,transparent:!0,blending:2,depthWrite:!1,side:2});this.mesh=new Y(this.geometry,n),this.mesh.frustumCulled=!1,this.mesh.visible=!1,this.mesh.renderOrder=4}update(e,t,n,r,i=0){if(t<=0)return;let a=this.hasLast?e.distanceTo(this.last)/t:0;this.last.copy(e),this.hasLast=!0,this.heat=i>this.heat?i:this.heat+(i-this.heat)*Math.min(1,t*6);let o=RW*(1-.55*this.heat),s=r&&a>o?Math.min(1,(a-o)/4+this.heat*.4):0;this.strength+=(s-this.strength)*Math.min(1,t*18);let c=this.history.length>=IW?this.history.shift():new q;if(c.copy(e),this.history.push(c),this.strength<.02||this.history.length<3){this.mesh.visible=!1;return}let l=this.history.length,u=this.shade.copy(this.color).lerp(wW,this.heat),d=LW*(1+zW*this.heat);for(let e=0;e3*t}function WW(e,t,n){let r=e.detail.endsWith(`:head`)||e.detail.endsWith(`:body`);return t===void 0||![`hit`,`counter_hit`].includes(e.kind)||!r||n===null||n.winner_id===null||n.winner_id!==e.actor_id?!1:n.finish_method===`flash_ko`||(n.finish_method===`ko`||n.finish_method===`tko`)&&t.is_downed}function GW(e){for(let t of e.passes)t.dispose?.();e.dispose()}function KW(e,t,n,r,i){e.setRenderTarget(t.readBuffer);let a=e.compileAsync(n,r,i);return e.setRenderTarget(null),a}var qW=-4e-4,JW=10;function YW(e,t,n){e.autoUpdate=!t,e.intensity=+!t,e.bias=t?JW:qW,(t&&e.map!==null||e.mapSize.x!==n)&&(e.mapSize.set(n,n),e.map?.dispose(),e.map=null)}function XW(e,t){let n=t.fighters.findIndex(t=>t.player_id===e.target_id),r=t.fighters.findIndex(t=>t.player_id===e.actor_id),i=e.kind===`block`||e.kind===`perfect_block`;return{recipientIndex:i?r:n,puncherIndex:i?n:r}}function ZW(e,t,n){if(e===void 0||t===void 0)return;let r=n.x(t.x)-n.x(e.x),i=n.z(t.y)-n.z(e.y),a=Math.hypot(r,i);return Number.isFinite(a)&&a>.001?{x:r/a,z:i/a}:void 0}var QW=e=>e.kind===`hit`||e.kind===`counter_hit`,$W=e=>e.kind===`block`||e.kind===`perfect_block`,eG=480,tG=.56,nG=1.8,rG=1.7,iG=1.2,aG=1.6,oG=30,sG=6.5,cG=.4,lG=600,uG=2.8,dG=.6,fG=[[1,0],[-1,0],[.75,-.66],[-.75,-.66],[.75,.66],[-.75,.66]],pG=.15,mG=.6,hG=2.3,gG=.5,_G=3.42,vG=2.2,yG=.9,bG=`body`,xG=`collapse`,SG=.55,CG=.5,wG=.5,TG=.28,EG=104,DG=260,OG=.05,kG=2.95,AG=2.4,jG=1.6,MG=.98,NG={uniforms:{tDiffuse:{value:null},uTime:{value:0},uVignette:{value:.32},uGrain:{value:.035},uRocked:{value:0}},vertexShader:` +attribute vec3 bindPosition;`)},{material:n,injury:r,look:null}}var $U=0,eW=1,tW=2,nW=3;function rW(e,t,n){return e===void 0||e===`forearm_left`||e===`forearm_right`?$U:e===`head`?tW:e===`upper_body`?t?nW:eW:e===`torso`&&n?tW:eW}function iW(e,t,n,r=0){let i=new Ab({map:e,color:t,roughness:n===void 0?.6:.38,metalness:.02,side:2});return n!==void 0&&(rA(i,!0,n).value=r),i}function aW(e,t,n){n.identity();let r=e.getAttribute(`position`),i=e.getAttribute(`bindPosition`),a=e.getIndex();if(i===void 0||i.count!==r.count)return n;let o=new Uint8Array(r.count);if(a===null)o.fill(1);else for(let e=0;e({active:!1,eventId:null,fluid:`blood`,life:0,seconds:1,rate:0,accumulator:0,position:new q,axis:new q(0,1,0)}));simulationRemainder=0;ambientSeed=1597463007;shake=0;lowTier=!1;bloodLevel=`full`;lens=new iB;camera=null;lensPoint=new q;debrisCursor=new Map;visceraMaterial;viscera=[];visceraByShape={};wounds=[];woundsOpen=0;woundShare=1;woundClock=0;parts=[];partsThrown=0;partBox=new T_;partMiddle=new q;partVertex=new q;limbMap;limbMaterial;trunkMap;trunkMaterial;fleshSections;spines=[];spineMesh;spineStretch;shredGeometry;shredMesh;spineNeck=new q;guts=[];heartGeometry;heartMesh;heartRest;heartRadius;heart={active:!1,moving:!1,owner:-1,age:0,beats:0,vx:0,vy:0,vz:0,vrx:0,vry:0,vrz:0,bounces:0,settle:-1,settleFrom:new rg,settleTo:new rg,settleFromY:0,pool:0,trail:0};corpses=[];flyGeometry;flyMaterial;flyMesh;flies;constructor(e,t=1024,n=NV){this.scene=e,this.budget=n,this.dropletPositions=new Float32Array(n.droplets*3),this.dropletColors=new Float32Array(n.droplets*3),this.dropletBuffers={position:new U_(this.dropletPositions,3),color:new U_(this.dropletColors,3)},this.dropletGeometry=CO(),this.dropletMaterial=new Ab({color:16777215,roughness:.3,metalness:.02}),this.dropletMesh=new ny(this.dropletGeometry,this.dropletMaterial,n.droplets),this.dropletMesh.instanceMatrix.setUsage(gh),this.dropletMesh.frustumCulled=!1,this.dropletMesh.castShadow=!1,e.add(this.dropletMesh);for(let e=0;eObject.assign(new Y(e.geometry,e.material),{castShadow:e.castShadow}));if(e.push(Object.assign(new Y(this.stumpGeometry,this.jawMaterial),{castShadow:this.stumps[0].mesh.castShadow})),this.bakedStandIns===null){let e=new xg,t=[QU(!1,e),QU(!0,e)].flatMap(e=>[e.material,e.injury.variant(!1),e.injury.variant(!0)]),n=new Ab({color:1920728,roughness:.38,metalness:.03,map:e});rA(n,!0);let r=[iW(e,16777215),iW(null,16777215),iW(e,1920728,`gloves`),iW(e,1920728,`trunks`)],i=new ny(this.heartGeometry,this.visceraMaterial,1);i.setColorAt(0,this.gibColor.setHex(16777215)),i.castShadow=!0,this.bakedStandIns={map:e,materials:[...t,n,...r],instanced:[i,new ny(this.flyGeometry,this.flyMaterial,1)]}}for(let t of this.bakedStandIns.materials)e.push(Object.assign(new Y(this.headGeometry,t),{castShadow:!0}));return e.push(Object.assign(new Y(this.heartGeometry,this.visceraMaterial),{castShadow:!0}),...this.bakedStandIns.instanced),e}setCamera(e){this.camera=e}drawLens(e,t,n){this.lens.draw(e,t,n)}get lensDrops(){return this.lens.count}setBloodLevel(e){if(e===this.bloodLevel)return;let t=this.bloodLevel;this.bloodLevel=e,(e===`off`||t===`full`&&e===`reduced`)&&this.clearArcadeGore()}get shakeAmount(){return this.shake}get liveParticles(){return this.droplets.filter(e=>e.alive).length}get liveBloodParticles(){return this.droplets.filter(e=>e.alive&&e.blood).length}get liveMist(){return this.mists.filter(e=>e.alive).length}get canvasStains(){return this.canvasBlood.stains}useUploader(e){this.canvasBlood.useUploader(e)}setLowTier(e){this.canvasBlood.setLowTier(e),this.lowTier=e}get liveGibs(){return this.gibs.filter(e=>e.alive).length}get liveShards(){return this.shards.filter(e=>e.alive).length}debrisCount(e){let t=0;for(let n of this.gibs)n.alive&&n.kind===e&&(t+=1);for(let n of this.shards)n.alive&&n.kind===e&&(t+=1);for(let n of this.eyeballs)n.alive&&n.kind===e&&(t+=1);for(let n of this.viscera)for(let r of n.pieces)r.alive&&r.kind===e&&(t+=1);return t}get activeHeads(){return this.heads.filter(e=>e.active).length}headBurst(e){let t=this.stumps[Math.trunc(e)];return t!==void 0&&t.active&&t.mesh.material===this.jawMaterial}severedHeadPosition(e,t){let n=this.heads[Math.trunc(e)];return n===void 0||!n.active?!1:(t.copy(n.mesh.position),!0)}severedHeadFacing(e,t){let n=this.heads[Math.trunc(e)];return n===void 0||!n.active?!1:(t.set(0,0,1).applyQuaternion(n.mesh.quaternion),!0)}mouthpieceOut(e){return this.shields[Math.trunc(e)]?.out===!0}mouthpiecePosition(e,t){let n=this.shields[Math.trunc(e)];return n===void 0||!n.out?!1:(t.set(n.x,n.y,n.z),!0)}ejectMouthpiece(e,t,n,r,i,a,o=!1){if(e<0||e>=BV)return!1;let s=Math.trunc(e),c=this.shields[s],l=Number.isSafeInteger(i)?i:0;if(c.out&&!o||this.lastShieldEvent[s]===l)return!1;this.lastShieldEvent[s]=l;let u=WH(l*48271+s*7907+5),d=UU(r),f=.9+u()*.9,p=.9+u()*.9,m=(u()-.5)*1.1;Object.assign(c,_B(),{out:!0,moving:!0,x:$(t.x),y:$(t.y,1.45),z:$(t.z),vx:f*d.x-m*d.z,vy:p,vz:f*d.z+m*d.x,wx:(u()-.5)*26,wy:(u()-.5)*18,wz:(u()-.5)*26,restYaw:u()*Math.PI*2});let h=this.shieldMeshes[s];h.position.set(c.x,c.y,c.z),XU(h.quaternion,n),h.visible=!0,this.shieldMaterials[s].color.setHex(a).lerp(qH,.55);let g=this.bloodLevel===`full`;for(let e=0;e<(g?22:12);e+=1){let t=u()*Math.PI*2,n=g?e%3!=0:this.bloodLevel===`reduced`&&e%3==0;this.spawnDroplet(c.x+(u()-.5)*.03,c.y+(u()-.5)*.03,c.z+(u()-.5)*.03,c.vx*(.5+u()*.6)+Math.sin(t)*.4,c.vy*(.4+u()*.6),c.vz*.5+Math.cos(t)*.4,n?EO(u()):tU,.5+u()*.5,n)}return!0}gougeEye(e,t,n,r,i,a,o=!1){if(this.bloodLevel!==`full`||e<0||e>=BV)return;let s=Math.trunc(e),c=rU(s,a),l=this.eyes[c],u=Number.isSafeInteger(i)?i:0;if(l.active&&(o||l.eventId===u))return;l.active&&this.burstEye(s,a,u),l.active=!0,l.eventId=u,l.socket.set($(t.x),$(t.y,1.6),$(t.z)),l.facing.copy(n),l.hasSkull=!1,l.position.copy(l.socket).addScaledVector(n,JH*1.5),this.eyeDirection.copy(n).multiplyScalar(1.3);let d=UU(r);if(this.eyeDirection.x+=d.x*.5,this.eyeDirection.z+=d.z*.5,l.previous.copy(l.position),o||l.previous.addScaledVector(this.eyeDirection,-.016666666666666666),l.bleeding=o?0:ZH,l.accumulator=0,this.eyeMeshes[c].visible=!0,this.nerveMeshes[c].visible=!0,this.writeEye(c),o)return;let f=WH(u*52711+s*3571+(a===`right`?977:0)+13);for(let e=0;e1e-8&&o.facing.copy(n).normalize(),r!==void 0&&i!==void 0&&(o.skull.set($(r.x),$(r.y,1.6),$(r.z)),XU(o.skullTurn,i),o.hasSkull=!0))}eyeOut(e,t){return t===void 0?this.eyes[rU(e,`left`)]?.active===!0||this.eyes[rU(e,`right`)]?.active===!0:this.eyes[rU(e,t)]?.active===!0}eyePosition(e,t,n){let r=this.eyes[rU(e,`left`)],i=this.eyes[rU(e,`right`)],a=n===`left`||n===void 0&&r?.active===!0?r:i;return a===void 0||!a.active?!1:(t.copy(a.position),!0)}updateEyes(e){for(let[t,n]of this.eyes.entries()){if(!n.active)continue;this.eyeDirection.copy(n.position).sub(n.previous).multiplyScalar(QH),n.previous.copy(n.position),n.position.add(this.eyeDirection),n.position.y-=QV*e*e,this.eyeDirection.copy(n.position).sub(n.socket);let r=this.eyeDirection.length();if(r>.055&&n.position.copy(n.socket).addScaledVector(this.eyeDirection,YH/r),n.hasSkull&&this.restOnFace(n)){n.previous.lerp(n.position,.6),this.eyeDirection.copy(n.position).sub(n.socket);let e=this.eyeDirection.length();e>.055&&n.position.copy(n.socket).addScaledVector(this.eyeDirection,YH/e)}if(n.position.y<0+JH&&(n.position.y=0+JH),this.bloodLevel===`full`&&n.bleeding>0)for(n.bleeding=Math.max(0,n.bleeding-e),n.accumulator+=e*this.forDevice(XH);n.accumulator>=1;){--n.accumulator;let e=.15+this.ambientRandom()*.5;this.spawnDroplet(n.socket.x,n.socket.y-.005,n.socket.z,n.facing.x*e+(this.ambientRandom()-.5)*.2,-.15-this.ambientRandom()*.4,n.facing.z*e+(this.ambientRandom()-.5)*.2,EO(this.ambientRandom()),.9,!0)}this.writeEye(t)}}restOnFace(e){this.eyeTurn.copy(e.skullTurn).invert();let t=this.eyeDirection.copy(e.position).sub(e.skull).applyQuaternion(this.eyeTurn),n=this.eyeSocketLocal.copy(e.socket).sub(e.skull).applyQuaternion(this.eyeTurn).z+JH+eU;if(t.z>=n)return!1;let r=Math.hypot(t.x/$H.x,t.y/$H.y);return r>=1?!1:(n-t.z<=(1-r)*Math.min($H.x,$H.y)||r<1e-6?t.z=n:(t.x/=r,t.y/=r),e.position.copy(e.skull).add(t.applyQuaternion(e.skullTurn)),!0)}writeEye(e){let t=this.eyes[e],n=this.eyeMeshes[e],r=this.nerveMeshes[e];n.position.copy(t.position),this.eyeDirection.copy(t.position).sub(t.socket);let i=this.eyeDirection.length();i>1e-5&&(this.eyeDirection.multiplyScalar(1/i),r.quaternion.setFromUnitVectors(WU,this.eyeDirection),this.eyeDirection.addScaledVector(t.facing,.9).normalize(),n.quaternion.setFromUnitVectors(GU,this.eyeDirection)),r.position.copy(t.socket),r.scale.set(1,Math.max(.001,i-JH*.8),1)}returnMouthpiece(e){let t=Math.trunc(e),n=this.shields[t];n!==void 0&&(Object.assign(n,_B()),this.shieldMeshes[t].visible=!1,this.lastShieldEvent[t]=null)}clearMouthpieces(){for(let[e,t]of this.shields.entries())Object.assign(t,_B()),this.shieldMeshes[e].visible=!1,this.lastShieldEvent[e]=null}updateShields(e){for(let[t,n]of this.shields.entries()){if(!n.out||!n.moving)continue;let r=this.shieldMeshes[t],i=n.age<.3&&!n.sliding,a=n.x,o=n.z;vB(n,r.quaternion,e,0);let s=TE-lB-XV,c=JU(n.x,n.vx,a,s),l=JU(n.z,n.vz,o,s);if(n.x=c.position,n.vx=c.velocity,n.z=l.position,n.vz=l.velocity,r.position.set(n.x,n.y,n.z),i&&this.ambientRandom()e.active).length}get activeStumps(){return[...this.stumps,...this.handStumps].filter(e=>e.active).length}spawnDroplet(e,t,n,r,i,a,o,s,c,l=c?.0035+this.ambientRandom()**3*.0125:.0025+this.ambientRandom()**2*.004,u=`blood`){let d=this.liveDropletsthis.droplets[e].maxLife-this.droplets[e].life;for(let n=0;n0&&t(e[i-1])_H&&e.pop()}}forDevice(e){return Math.round(e*this.budget.droplets*(this.lowTier?.5:1)/NV.droplets)}uploadDroplets(e,t,n){if(this.dropletMesh.count=this.liveDroplets,t<=e)return;this.dropletMesh.instanceMatrix.addUpdateRange(e*16,(t-e)*16),this.dropletMesh.instanceMatrix.needsUpdate=!0;let r=this.dropletMesh.instanceColor;n&&r!==null&&(r.addUpdateRange(e*3,(t-e)*3),r.needsUpdate=!0)}retireDroplet(e){this.oldest.length=0;let t=this.liveDroplets-1,n=this.droplets[e];if(n.alive=!1,this.liveDroplets=t,e!==t){let r=this.droplets[t];this.droplets[e]=r,this.droplets[t]=n,this.dropletPositions.copyWithin(e*3,t*3,t*3+3),this.dropletColors.copyWithin(e*3,t*3,t*3+3),this.dropletMesh.setColorAt(e,this.dropletColor.setRGB(r.r,r.g,r.b)),this.writeDropletMatrix(e,r)}this.dropletPositions[t*3+1]=-50,this.writeDropletMatrix(t,n)}sprayDroplet(e,t,n,r,i,a,o,s,c,l,u,d){this.spawnDroplet(t,n,r,i*e.x-o*e.z,a,i*e.z+o*e.x,s,c,l,u,d)}writeDropletMatrix(e,t){if(!t.alive){this.dropletScale.setScalar(0),this.dropletQuaternion.identity(),this.dropletMatrix.compose(this.dropletVelocity.set(0,-50,0),this.dropletQuaternion,this.dropletScale),this.dropletMesh.setMatrixAt(e,this.dropletMatrix);return}let n=Math.hypot(t.vx,t.vy,t.vz);n>1e-4?(this.dropletVelocity.set(t.vx/n,t.vy/n,t.vz/n),this.dropletQuaternion.setFromUnitVectors(WU,this.dropletVelocity)):this.dropletQuaternion.identity();let r=Math.min(1,t.life/(t.maxLife*.3))*this.dropletCloseness*(t.blood&&this.bloodLevel===`full`?dH:1),i=wO(t.radius*r,n,this.dropletShape);this.dropletScale.set(i.width,i.length,i.width),this.dropletMatrix.compose(this.dropletVelocity.set(t.x,t.y,t.z),this.dropletQuaternion,this.dropletScale),this.dropletMesh.setMatrixAt(e,this.dropletMatrix)}spawnMist(e,t,n,r,i){let a=this.mistIndex%this.budget.mist;this.mistIndex+=1;let o=this.mists[a];o.alive=!0,o.x=$(e),o.y=$(t,1),o.z=$(n),o.maxLife=Math.max(.05,$(i,.5)),o.life=o.maxLife,o.scale=Math.max(.1,$(r,1)),this.mistPositions[a*3]=o.x,this.mistPositions[a*3+1]=o.y,this.mistPositions[a*3+2]=o.z,this.mistColors[a*4+3]=Math.min(1,o.scale),this.mistGeometry.attributes.position.needsUpdate=!0,this.mistGeometry.attributes.color.needsUpdate=!0}placeDecal(e,t,n,r,i,a,o){this.canvasBlood.stain($(e),$(t),Math.max(.01,$(n,.2))*.28,Math.max(.01,$(r,.15))*.28,$(i),G.clamp($(a,.4),0,.95),o)}splashLens(e,t,n,r,i){let a=this.camera;if(a===null||this.bloodLevel===`off`||!(r>0))return;let o=this.lensPoint.set($(e),$(t,1.5),$(n)),s=o.distanceTo(a.position);if(o.project(a),!(o.z<1)||Math.abs(o.x)>1.15||Math.abs(o.y)>1.15)return;let c=G.clamp((vH-s)/8.5,0,1);this.lens.splash((o.x+1)/2,(1-o.y)/2,c*r*(this.bloodLevel===`reduced`?.25:1),i)}ambientRandom(){return this.ambientSeed=Math.imul(this.ambientSeed^this.ambientSeed>>>15,1|this.ambientSeed),this.ambientSeed^=this.ambientSeed+Math.imul(this.ambientSeed^this.ambientSeed>>>7,61|this.ambientSeed),((this.ambientSeed^this.ambientSeed>>>14)>>>0)/4294967296}splatter(e,t,n,r=()=>this.ambientRandom(),i=12,a=oH){if(this.bloodLevel===`off`)return;let o=this.bloodLevel===`reduced`,s=o?Math.ceil(i/4):i,c=o?.35:sH;for(let i=0;i0?$(t.y):e.detail.endsWith(`:body`)?1.05:1.58,z:$(t.z)},f=e.kind===`bleed`,p=n||f?0:Math.round(s?(a?4:6)+Math.min(6,Math.max(0,e.amount)/40):(a?6:16)+Math.min(20,Math.max(0,e.amount)/20)),m={x:0,y:0,z:0,vx:0,vy:0,vz:0,life:0,radius:0,color:EO(0)},h=e.kind===`hit`||e.kind===`counter_hit`,g=h?Math.max(0,e.blood-Math.floor(Math.max(0,e.amount)/3)):0,_=n||e.blood<=0||this.bloodLevel===`off`?0:f?this.bloodLevel===`reduced`?1:Math.min(12,3+Math.floor(Math.max(0,e.amount)/8)):this.bloodLevel===`reduced`?Math.min(24,Math.round(e.blood*(a?.12:.24))):this.forDevice(a?Math.round(vO(e.blood,0)/2):o?vO(e.blood,0)+fH:vO(e.blood,h?e.amount:0));f||(this.shake=Math.min(.14,this.shake+(a?.008:Math.max(.012,e.amount/1500)))),o&&(this.shake=Math.min(.2,this.shake+.09));let v=o?1.2:h?G.clamp((e.amount-40)/60,0,1)*(.6+Math.min(100,e.blood)/150):0;!n&&!f&&e.blood>0&&this.splashLens(d.x,d.y,d.z,v,e.event_id);for(let e=0;e0&&t<=eH){let e=1-tH*t;this.spawnDroplet(m.x,m.y,m.z,m.vx*e,m.vy*e,m.vz*e,m.color,m.life,!0,m.radius*(1-nH*t));continue}let n=t===0,r=(i()-.5)*Math.PI,a=n?2.2+i()*1.8:.9+i()*1.5,o=a,s=.5+i()*1.25,u=(i()-.5)*.5;if(c===`fan`)o=a*(.45+Math.cos(r)*.35),s=.55+i()*1.15,u=Math.sin(r)*a*.9;else if(c===`plume`)o=a*(.25+i()*.25),s=1.8+i()*2.2,u=(i()-.5)*a*.65;else if(c===`body_burst`)o=a*(.55+i()*.45),s=-.15+i()*1.05,u=Math.sin(r)*a*.75;else if(c===`ooze`)o=.08+i()*.22,s=-.3-i()*.55,u=(i()-.5)*.22;else if(c===`impact`)o=a*(.45+i()*.65),s=.9+i()*2.1,u=Math.sin(r)*a;else{let e=n?.12:.34;o=a*(.8+i()*.35),s=n?1.3+i()*1.6:.5+i()*1.25,u=(i()-.5)*a*e}let f=o*l.x-u*l.z,p=o*l.z+u*l.x,h=EO(i()),g=d.x+(i()-.5)*.12,_=d.y+(i()-.5)*.14,v=d.z+(i()-.5)*.12,y=.65+i()*.85;n?(m.x=g,m.y=_,m.z=v,m.vx=f,m.vy=s,m.vz=p,m.color=h,m.life=y,m.radius=.008+i()*.008,this.spawnDroplet(g,_,v,f,s,p,h,y,!0,m.radius)):this.spawnDroplet(g,_,v,f,s,p,h,y,!0)}let y=s?o||e.kind===`counter_hit`||h&&(e.amount>=35||g>=cH):e.kind===`hit`&&e.amount>=70||o||e.kind===`counter_hit`||g>=16;if(!n&&e.blood>0&&this.bloodLevel!==`off`&&y){let t=s?this.forDevice(o?36:12+Math.min(24,Math.floor(g/2)+Math.floor(Math.max(0,e.amount-35)/6))):o?3:2,n=s?1:.35;for(let e=0;e0&&this.bloodLevel!==`off`){let t=o?1+Math.min(2,e.blood/55):.8+Math.min(1.2,g/30);this.splatter(d.x+(i()-.5)*.6,d.z+(i()-.5)*.6,s?t*1.3:t,i,x,o?aH:iH)}let S=e.amount>=70||e.kind===`counter_hit`&&e.amount>=gO,C=h&&(e.amount>=60||S&&g>=cH/4);if(s&&!n&&C&&!e.detail.endsWith(`:body`)){let t=Math.min(20,Math.max(3,Math.round((e.amount-10)/6)));for(let e=0;e0){e.sideLow=1/0,e.sideHigh=-1/0;for(let t=0;t=BV)return;let s=Math.trunc(e),c=Number.isSafeInteger(i)?i:0,l=this.heads[s];if(l.active||this.lastDecapitationEvent[s]===c)return;this.stopGush(s),this.applyBakedPart(l,o,a);let u=WH(c*104729+s*8191+23),d=UU(r);this.lastDecapitationEvent[s]=c,l.active=!0,l.moving=!0,l.eventId=c;let f=1.8+u()*1.1;l.vy=2.3+u()*1.1;let p=(u()-.5)*2.2;l.vx=f*d.x-p*d.z,l.vz=f*d.z+p*d.x,l.vrx=(u()-.5)*12,l.vry=(u()-.5)*12,l.vrz=(u()-.5)*12,l.bounces=0,l.trail=0,l.stained=!1,l.settle=-1,l.mesh.position.set($(t.x),$(t.y,1.55),$(t.z)),XU(l.mesh.quaternion,n),l.mesh.visible=!0;let m=this.stumps[s];m.mesh.material=this.stumpMaterial,m.active=!0,m.fountainLife=14,m.accumulator=0,m.seed=c|1,m.direction=d,m.mesh.position.copy(l.mesh.position),m.mesh.quaternion.copy(l.mesh.quaternion),m.mesh.visible=!0;for(let e=0;e=BV)return;let i=Math.trunc(e),a=Number.isSafeInteger(r)?r:0,o=this.stumps[i];if(o.active||this.lastBurstEvent[i]===a)return;this.lastBurstEvent[i]=a,this.stopGush(i);let s=WH(a*91813+i*6151+41),c=UU(n),l=$(t.x),u=$(t.y,1.6),d=$(t.z),f=(e,t,n,r,a)=>{for(let o=0;o=BV)return;let c=Math.trunc(e)*2+(t===`left`?0:1),l=Number.isSafeInteger(a)?a:0,u=this.hands[c];if(u.active||this.lastDismembermentEvent[c]===l)return;this.applyBakedPart(u,s,o);let d=WH(l*130363+c*12289+37),f=UU(i);this.lastDismembermentEvent[c]=l,u.active=!0,u.moving=!0,u.eventId=l;let p=1.3+d()*1.1;u.vy=1.5+d()*1.2;let m=(d()-.5)*1.8;u.vx=p*f.x-m*f.z,u.vz=p*f.z+m*f.x,u.vrx=(d()-.5)*16,u.vry=(d()-.5)*16,u.vrz=(d()-.5)*16,u.bounces=0,u.trail=0,u.stained=!1,u.mesh.position.set($(n.x),$(n.y,1.25),$(n.z)),XU(u.mesh.quaternion,r),u.mesh.visible=!0;let h=this.handStumps[c];h.active=!0,h.fountainLife=SH,h.accumulator=0,h.seed=l|1,h.direction=f,h.mesh.position.copy(u.mesh.position),h.mesh.quaternion.copy(u.mesh.quaternion),h.mesh.visible=!0;for(let t=0;t=BV)return;let o=Math.trunc(e),s=Number.isSafeInteger(i)?i:0,c=WH(s*69061+o*2741+29),l=UU(r),u=this.tornAxis.copy(n);u.lengthSq()>1e-8&&Number.isFinite(u.lengthSq())||u.set(0,1,0),u.normalize();let d=$(t.x),f=$(t.y,1.2),p=$(t.z);for(let e=0;e{for(let n=0;n=BV)return;let i=Math.trunc(e)*2+(t===`left`?0:1),a=this.handStumps[i];a.active&&(a.mesh.position.set($(n.x),$(n.y,1.2),$(n.z)),XU(a.mesh.quaternion,r))}anchorStump(e,t,n,r,i){if(this.bloodLevel!==`full`||e<0||e>=BV)return;let a=this.stumps[Math.trunc(e)];a.active&&(a.mesh.position.set($(t.x),$(t.y,1.5),$(t.z)),r===void 0||r.length<18?(a.mesh.geometry=this.stumpGeometry,XU(a.mesh.quaternion,n)):(RO(a.flesh,r,a.mesh.position,this.stumpOutward.set(0,1,0).applyQuaternion(n),.01,i),a.mesh.geometry=a.flesh,a.mesh.quaternion.identity()))}restoreFighter(e){if(e<0||e>=BV)return;let t=Math.trunc(e),n=this.heads[t];n.active=!1,n.moving=!1,n.mesh.visible=!1,n.mesh.position.y=-50,this.applyBakedPart(n,void 0,9063730);let r=this.stumps[t];r.active=!1,r.fountainLife=0,r.accumulator=0,r.mesh.visible=!1,r.mesh.position.y=-50,r.mesh.material=this.stumpMaterial,this.clearGibs(t),this.stopGush(t);for(let e of[t*2,t*2+1]){let t=this.eyes[e];t.active=!1,t.bleeding=0,this.eyeMeshes[e].visible=!1,this.nerveMeshes[e].visible=!1}this.clearWounds(t),this.clearGuts(t),this.clearSpine(t),this.clearCorpse(t),this.heart.owner===t&&(this.heart.active=!1,this.heartMesh.visible=!1);for(let e of[t*2,t*2+1]){let t=this.hands[e];t.active=!1,t.moving=!1,t.mesh.visible=!1,t.mesh.position.y=-50,this.applyBakedPart(t,void 0,1920728);let n=this.handStumps[e];n.active=!1,n.fountainLife=0,n.accumulator=0,n.mesh.visible=!1,n.mesh.position.y=-50}}drip(e,t,n,r=0){let i=+(r===1);if(this.bloodLevel===`off`||n||t<=.05){this.stopDrip(i);return}let a=this.dripEmitters[i];a.position.set($(e.x),$(e.y,1.5),$(e.z)),a.rate=this.bloodLevel===`reduced`?Math.min(3,t*3):Math.min(60,t*40),a.active=!0}stopDrip(e){let t=this.dripEmitters[+(e===1)];t.active=!1,t.rate=0,t.accumulator=0}gush(e,t,n,r,i,a,o=`blood`){if(this.bloodLevel!==`full`||e<0||e>=this.gushes.length)return;let s=this.gushes[Math.trunc(e)],c=Number.isSafeInteger(a)?a:0;s.active&&s.eventId===c||(s.active=!0,s.eventId=c,s.fluid=o,s.seconds=Math.max(.1,$(r,1)),s.life=s.seconds,s.rate=Math.max(0,$(i)),s.accumulator=0,this.anchorGush(e,t,n))}anchorGush(e,t,n){let r=this.gushes[Math.trunc(e)];r!==void 0&&r.active&&(r.position.set($(t.x),$(t.y,1.4),$(t.z)),n.lengthSq()>1e-8&&Number.isFinite(n.lengthSq())&&r.axis.copy(n).normalize())}gushing(e){return this.gushes[Math.trunc(e)]?.active===!0}stopGush(e){let t=this.gushes[e];t!==void 0&&(t.active=!1,t.eventId=null)}updateGushes(e){for(let t of this.gushes){if(!t.active)continue;if(t.life-=e,t.life<=0||this.bloodLevel!==`full`){t.active=!1;continue}let n=t.life/t.seconds,r=(t.seconds-t.life)*wH%1,i=Math.exp(-(((r-.5)/FH)**2));if(t.accumulator+=e*this.forDevice(t.rate)*n*(IH+.7*i),!(t.accumulator<1))for(BH.set(Math.abs(t.axis.y)<.9?0:1,+(Math.abs(t.axis.y)<.9),0).cross(t.axis).normalize(),VH.crossVectors(t.axis,BH);t.accumulator>=1;){--t.accumulator;let e=Math.sqrt(this.ambientRandom())*RH,r=this.ambientRandom()*Math.PI*2,a=(LH+this.ambientRandom()*2)*(.5+.5*n)*(.7+.3*i);HH.copy(t.axis).multiplyScalar(Math.cos(e)).addScaledVector(BH,Math.sin(e)*Math.cos(r)).addScaledVector(VH,Math.sin(e)*Math.sin(r)).multiplyScalar(a),this.spawnDroplet(t.position.x+(this.ambientRandom()-.5)*.03,t.position.y+(this.ambientRandom()-.5)*.02,t.position.z+(this.ambientRandom()-.5)*.03,HH.x,HH.y,HH.z,OO(t.fluid,this.ambientRandom()),1.2,!0,(.004+this.ambientRandom()**2*.01)*DO[t.fluid].drop,t.fluid)}}}updateDripEmitters(e){for(let t of this.dripEmitters)if(t.active)for(t.accumulator+=e*t.rate;t.accumulator>=1;)--t.accumulator,this.spawnDroplet(t.position.x+(this.ambientRandom()-.5)*.14,t.position.y-.04,t.position.z+(this.ambientRandom()-.5)*.1,(this.ambientRandom()-.5)*.08,-.25-this.ambientRandom()*.4,(this.ambientRandom()-.5)*.08,EO(this.ambientRandom()),1.1,!0)}spawnTeeth(e,t,n,r){if(this.bloodLevel===`off`)return;let i=this.bloodLevel===`reduced`?+(n>=3):Math.min(12,Math.max(1,Math.round(n)));if(i<=0)return;let a=WH((Number.isSafeInteger(r)?r:0)*7331+91),o=UU(t);for(let t=0;t>3):f.length>>2)}debrisSlot(e){let t=this.debrisCursor.get(e)??0,n=t%e.length;for(let r=0;r=0?n.scale*Math.max(0,n.fading)/bH:n.scale;this.gibScale.set(e*n.stretch,e,e/Math.sqrt(n.stretch))}this.gibMatrix.compose(this.gibPosition,this.gibQuaternion,this.gibScale),e.setMatrixAt(t,this.gibMatrix)}updateDebris(e,t,n,r){let i=!1;for(let[a,o]of e.entries()){if(!o.alive||o.resting&&o.fading<0)continue;if(i=!0,o.fading>=0){o.fading-=n,o.fading<=0&&(o.alive=!1),this.writeDebrisMatrix(t,a,o);continue}o.vy-=6.4*n,o.x+=o.vx*n,o.y+=o.vy*n,o.z+=o.vz*n,o.rx+=o.vrx*n,o.ry+=o.vry*n,o.rz+=o.vrz*n,this.confineGib(o);let e=0+(r===void 0?o.kind===`eye`?JH*RV:.015:r.low*o.scale);if(o.y<=e){if(o.y=e,!o.stained&&this.bloodLevel===`full`&&o.kind!==`tooth`&&o.kind!==`eye`&&(o.stained=!0,r===void 0?this.placeDecal(o.x,o.z,.24+o.scale*.16,.14+o.scale*.1,o.rz,.55,6425104):this.canvasBlood.stain(o.x,o.z,sU[r.shape].stain*o.scale,sU[r.shape].stain*o.scale*.7,o.ry,.6,6425104)),o.bounces.35)o.bounces+=1,o.vy=Math.abs(o.vy)*.3,o.vx*=.68,o.vz*=.68,o.vrx*=.7,o.vry*=.7,o.vrz*=.7;else{if(o.vx=0,o.vy=0,o.vz=0,o.vrx=o.vry=o.vrz=0,o.kind===`shard`&&(o.rx=Math.round(o.rx/Math.PI)*Math.PI),r!==void 0){let e=Math.round(o.rx/Math.PI),t=Math.round(o.rz/Math.PI);o.rx=e*Math.PI,o.rz=t*Math.PI,o.y=0+((e+t)%2==0?r.low:r.high)*o.scale}o.resting=!0}}this.writeDebrisMatrix(t,a,o)}i?t.instanceMatrix.needsUpdate=!0:r!==void 0&&(r.moving=!1)}confineGib(e){Math.abs(e.x)>3.05&&(e.x=Math.sign(e.x)*xE,e.vx*=-.45),Math.abs(e.z)>3.05&&(e.z=Math.sign(e.z)*xE,e.vz*=-.45)}updateDetachedParts(e,t){for(let n of e){if(n.active&&n.settle>=0&&n.settle<1){n.settle=Math.min(1,n.settle+t/YV);let e=n.settle*n.settle*(3-2*n.settle);n.mesh.quaternion.slerpQuaternions(n.settleFrom,n.settleTo,e),n.mesh.position.y=n.settleFromY+(n.settleToY-n.settleFromY)*e}if(!n.active||!n.moving)continue;let e=n.mesh.position.x,r=n.mesh.position.z;if(n.vy-=5.8*t,n.mesh.position.x+=n.vx*t,n.mesh.position.y+=n.vy*t,n.mesh.position.z+=n.vz*t,n.mesh.rotation.x+=n.vrx*t,n.mesh.rotation.y+=n.vry*t,n.mesh.rotation.z+=n.vrz*t,this.bloodLevel===`full`)for(n.trail+=t*this.forDevice(zV),n.trail>=1&&this.trailPoint.copy(n.cap.position).multiply(n.mesh.scale).applyQuaternion(n.mesh.quaternion).add(n.mesh.position);n.trail>=1;)--n.trail,this.spawnDroplet(this.trailPoint.x+(this.ambientRandom()-.5)*.03,this.trailPoint.y+(this.ambientRandom()-.5)*.03,this.trailPoint.z+(this.ambientRandom()-.5)*.03,n.vx*.35+(this.ambientRandom()-.5)*.9,n.vy*.35+(this.ambientRandom()-.5)*.9,n.vz*.35+(this.ambientRandom()-.5)*.9,EO(this.ambientRandom()),.9,!0);let i=TE-n.radius-XV,a=JU(n.mesh.position.x,n.vx,e,i),o=JU(n.mesh.position.z,n.vz,r,i);if(n.mesh.position.x=a.position,n.mesh.position.z=o.position,n.vx=a.velocity,n.vz=o.velocity,n.mesh.position.y<=0+n.radius){if(n.mesh.position.y=0+n.radius,!n.stained&&this.bloodLevel===`full`){n.stained=!0;let e=n.radius===JV?1:.55;this.placeDecal(n.mesh.position.x,n.mesh.position.z,1.3*e,.9*e,n.mesh.rotation.z,.85,4392199)}n.bounces<2&&Math.abs(n.vy)>.42?(n.bounces+=1,n.vy=Math.abs(n.vy)*.32,n.vx*=.62,n.vz*=.62,n.vrx*=.65,n.vry*=.65,n.vrz*=.65):(n.moving=!1,n.vx=0,n.vy=0,n.vz=0,n.vrx=0,n.vry=0,n.vrz=0,n.look!==null&&this.rollOntoEar(n))}Number.isFinite(n.mesh.position.x)&&Number.isFinite(n.mesh.position.y)&&Number.isFinite(n.mesh.position.z)&&Number.isFinite(n.mesh.quaternion.x)&&Number.isFinite(n.mesh.quaternion.y)&&Number.isFinite(n.mesh.quaternion.z)&&Number.isFinite(n.mesh.quaternion.w)||(n.mesh.position.set(0,0+n.radius,0),n.mesh.quaternion.identity(),n.moving=!1,n.vx=0,n.vy=0,n.vz=0)}}rollOntoEar(e){let t=this.settleAxis.set(1,0,0).applyQuaternion(e.mesh.quaternion),n=t.y>=0?1:-1;e.settleFrom.copy(e.mesh.quaternion),e.settleTo.setFromUnitVectors(t,this.settleUp.set(0,n,0)).multiply(e.mesh.quaternion),e.settleFromY=e.mesh.position.y,e.settleToY=0+(n>0?-e.sideLow:e.sideHigh),e.settle=0}stumpRandom(e){let t=e.seed|0;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),e.seed=t|0,((t^t>>>14)>>>0)/4294967296}updateStumpFountains(e){if(this.bloodLevel===`full`)for(let t of[...this.stumps,...this.handStumps]){if(!t.active||t.fountainLife<=0)continue;t.fountainLife=Math.max(0,t.fountainLife-e);let n=Math.min(1,t.fountainLife/CH),r=t.fountainLife*wH%1,i=Math.exp(-(((r-.5)/TH)**2));if(t.accumulator+=e*this.forDevice(EH)*n*(DH+.88*i),t.accumulator<1)continue;let a=UH(t,zH);for(BH.set(Math.abs(a.y)<.9?0:1,+(Math.abs(a.y)<.9),0).cross(a).normalize(),VH.crossVectors(a,BH);t.accumulator>=1;){--t.accumulator;let e=this.stumpRandom(t),r=this.stumpRandom(t),o=this.stumpRandom(t),s=Math.sqrt(e)*AH,c=r*Math.PI*2;HH.copy(a).multiplyScalar(Math.cos(s)).addScaledVector(BH,Math.sin(s)*Math.cos(c)).addScaledVector(VH,Math.sin(s)*Math.sin(c)).multiplyScalar(G.lerp(OH,kH,o)*(.7+.3*i)*(.55+.45*n)),this.spawnDroplet(t.mesh.position.x+a.x*.015+(e-.5)*.03,t.mesh.position.y+a.y*.015,t.mesh.position.z+a.z*.015+(r-.5)*.03,HH.x,HH.y,HH.z,EO(e),1.2+o*.6,!0,.004+o*o*.01)}}}update(e){for(this.canvasBlood.update(KU(e)),this.lens.update(KU(e)),this.simulationRemainder+=KU(e);this.simulationRemainder+1e-9>=gH;)this.simulationRemainder=Math.max(0,this.simulationRemainder-gH),this.simulate(gH);for(let e of this.guts)e.active&&e.sinceDrop<0&&e.rope.hold(e.anchor)&&(e.moved=!0),e.moved&&=(e.tube.write(e.rope),!1)}simulate(e){this.shake*=.02**e,this.updateDripEmitters(e),this.updateGushes(e),this.updateStumpFountains(e),this.updateDetachedParts(this.heads,e),this.updateDetachedParts(this.hands,e),this.updateShields(e),this.updateEyes(e),this.updateDebris(this.gibs,this.gibMesh,e),this.updateDebris(this.shards,this.shardMesh,e),this.updateDebris(this.eyeballs,this.eyeballMesh,e);for(let t of this.viscera)t.moving&&this.updateDebris(t.pieces,t.mesh,e,t);this.updateWounds(e),this.updateParts(e),this.updateSpines(e),this.updateGuts(e),this.updateHeart(e),this.updateCorpses(e);let t=this.liveDroplets,n=!1;for(let t=0;t0&&(this.dropletBuffers.position.needsUpdate=!0,this.dropletBuffers.color.needsUpdate=!0,this.uploadDroplets(0,this.liveDroplets,n));let r=!1;for(let[t,n]of this.mists.entries()){if(!n.alive)continue;if(r=!0,n.life-=e,n.life<=0){n.alive=!1,this.mistPositions[t*3+1]=-50;continue}let i=1-n.life/n.maxLife;this.mistPositions[t*3]=n.x,this.mistPositions[t*3+1]=n.y+i*.14,this.mistPositions[t*3+2]=n.z,this.mistColors[t*4+3]=Math.max(0,1-i)*Math.min(1,n.scale)}r&&(this.mistGeometry.attributes.position.needsUpdate=!0,this.mistGeometry.attributes.color.needsUpdate=!0)}clearDroplets(e){let t=this.liveDroplets;for(let t=0;t0))return;let s=WH((Number.isSafeInteger(i)?i:0)*15485863+e.charCodeAt(0)*131+e.length*977+7),c=UU(n),l=Math.max(.2,$(a,1)),u=$(t.x),d=$(t.y,1.2),f=$(t.z),p=Math.min(Math.round(r),this.debrisPlaces(e));for(let t=0;t0))return;let o=Number.isSafeInteger(i)?i:0,s=WH(o*86243+aU.indexOf(e)*3331+59),c=UU(n),l=DO[e],u=Math.max(.2,$(a,1)),d=$(t.x),f=$(t.y,1.2),p=$(t.z),m=Math.min(oU,r);for(let t=this.forDevice(m);t>0;--t){let t=s()*Math.PI*2,n=(.5+s()*1.9)*u;this.sprayDroplet(c,d+(s()-.5)*.08,f+(s()-.5)*.08,p+(s()-.5)*.08,(.4+s()*1.9)*u+Math.sin(t)*n*.35,(.3+s()*2.3)*Math.sqrt(u),Math.cos(t)*n*.8,OO(e,s()),.7+s(),!0,(.004+s()**2*.013)*l.drop,e)}if(e===`blood`){for(let e=Math.min(48,Math.round(m/25));e>0;--e)this.spawnMist(d+(s()-.5)*.4,f+(s()-.5)*.3,p+(s()-.5)*.4,.9+s()*1.5,.6+s()*.7);this.splatter(d+c.x*.3,p+c.z*.3,1+Math.min(2.4,m/500),s,Math.min(50,Math.round(m/20))),this.splashLens(d,f,p,Math.min(3,m/350),o)}else for(let e=Math.min(10,Math.round(m/30));e>0;--e){let t=.2+s()*.9*u;this.placeDecal(d+c.x*t+(s()-.5)*.5,p+c.z*t+(s()-.5)*.5,.5+s()*.9,.3+s()*.7,s()*Math.PI,.7*l.soak,e%2==0?l.splash:l.stain)}this.shake=Math.min(.22,this.shake+Math.min(.06,m/2e4))}puddle(e,t,n,r,i){if(this.bloodLevel!==`full`)return;let a=DO[r];this.canvasBlood.pool($(e),$(t),Math.max(.02,$(n,.1)),.95*a.soak,i,a.pool)}smear(e,t,n,r,i){this.bloodLevel===`full`&&this.canvasBlood.smear(e,t,n,r,Math.max(.005,$(i,.05)),.75,DO.blood.splash)}footprint(e,t,n,r,i){this.bloodLevel===`full`&&i>0&&this.canvasBlood.print(e,t,n,r,Math.min(1,i)*.85,DO.blood.splash)}setWound(e,t,n,r=`blood`){let i=this.woundAt(e,t);if(i===null)return;let a=this.bloodLevel===`full`?G.clamp($(n),0,1):0;a>0&&i.strength<=0&&(i.anchored=!1,i.accumulator=0,i.run=0,i.pool=0),i.strength=a,i.fluid=r,this.shareWounds()}anchorWound(e,t,n,r){let i=this.woundAt(e,t);i===null||i.strength<=0||(i.position.set($(n.x),$(n.y,1.2),$(n.z)),r.lengthSq()>1e-8&&Number.isFinite(r.lengthSq())&&i.axis.copy(r).normalize(),i.anchored=!0)}woundStrength(e,t){return this.woundAt(e,t)?.strength??0}clearWounds(e){for(let[t,n]of this.wounds.entries())(e===void 0||Math.floor(t/he.length)===Math.trunc(e))&&(n.strength=0);this.shareWounds()}get openWounds(){return this.woundsOpen}woundAt(e,t){let n=Math.trunc(e);return n>=0&&npU?pU/e:1}updateWounds(e){if(this.woundsOpen!==0&&this.bloodLevel===`full`){this.woundClock+=e;for(let t=0;t=mU){n.run-=mU;let e=.12+fU*r*r,i=l.y*e,a=(i+Math.sqrt(i*i+2*QV*Math.max(0,u.y-0)))/QV,o=u.x+l.x*e*a,s=u.z+l.z*e*a;n.pool<=0||Math.hypot(o-n.poolX,s-n.poolZ)>Math.max(.12,n.pool*1.2)?(n.poolX=o,n.poolZ=s,n.pool=.03):n.pool=Math.min(hU*(.25+.75*r),n.pool+.012);let c=DO[n.fluid];this.canvasBlood.pool(n.poolX,n.poolZ,n.pool,.95*c.soak,t*7+Math.round(n.pool*80),c.pool)}if(n.accumulator<1)continue;BH.set(Math.abs(l.y)<.9?0:1,+(Math.abs(l.y)<.9),0).cross(l).normalize(),VH.crossVectors(l,BH);let d=G.lerp(.8,AH*.8,r),f=DO[n.fluid].drop;for(;n.accumulator>=1;){--n.accumulator;let e=Math.sqrt(this.ambientRandom())*d,t=this.ambientRandom()*Math.PI*2;HH.copy(l).multiplyScalar(Math.cos(e)).addScaledVector(BH,Math.sin(e)*Math.cos(t)).addScaledVector(VH,Math.sin(e)*Math.sin(t)).multiplyScalar(c*(.75+this.ambientRandom()*.4)),this.spawnDroplet(u.x+l.x*.012+(this.ambientRandom()-.5)*.02,u.y+l.y*.012,u.z+l.z*.012+(this.ambientRandom()-.5)*.02,HH.x,HH.y,HH.z,OO(n.fluid,this.ambientRandom()),1.3+r*.5,!0,(.004+this.ambientRandom()**2*.01)*f,n.fluid)}}}}burstEye(e,t,n){let r=Math.trunc(e),i=rU(r,t),a=this.eyes[i];if(r<0||r>=BV||a===void 0||!a.active)return!1;if(a.active=!1,a.bleeding=0,this.eyeMeshes[i].visible=!1,this.nerveMeshes[i].visible=!1,this.bloodLevel!==`full`)return!0;let o=Number.isSafeInteger(n)?n:0,s=WH(o*39916801+i*211+3),{x:c,y:l,z:u}=a.position;for(let e=this.forDevice(160);e>0;--e){let t=s()*Math.PI*2,n=s()*1.6-.6,r=Math.sqrt(Math.max(0,1-Math.min(1,n*n))),i=.6+s()*2.2,a=e%3!=0;this.spawnDroplet(c,l,u,Math.cos(t)*r*i,n*i+.5,Math.sin(t)*r*i,a?EO(s()):tU,.5+s()*.7,a,.003+s()**2*.008)}for(let e=0;e<4;e+=1)this.spawnGib(c,l,u,(s()-.5)*1.6,.4+s()*1.2,(s()-.5)*1.6,s,`flesh`,r);for(let e=0;e<8;e+=1)this.spawnMist(c+(s()-.5)*.12,l+(s()-.5)*.1,u+(s()-.5)*.12,.5+s()*.6,.4+s()*.4);return this.splashLens(c,l,u,.8,o),!0}skinOf(e,t){let n=QU(t.sites===aA,e.map),r=e.look??mj;return n.look?.set(r),n.material.color.setHex(e.color),n.injury.copyFrom(t),n.injury.setBindToPart(aW(e.geometry,r,this.bindToPartMatrix)),t.material instanceof jb&&(n.material.clearcoat=t.material.clearcoat),n.material}flingPart(e,t,n,r,i,a,o={}){this.removePart(e);let s=this.partBox.makeEmpty();for(let e of t){let t=e.geometry.getAttribute(`position`),n=e.geometry.getIndex(),r=n===null?t.count:n.count;for(let e=0;ep.reach)&&(p=e),(m===null||e.height>m.height)&&(m=e);for(let{fan:e,opening:t}of f)e.materialIndex=rW(o.part,t===p,t===m);c.cut.set(0,0,0),p!==null&&c.cut.copy(p.centre).sub(l),XU(c.group.quaternion,r),c.group.position.copy(l).applyQuaternion(c.group.quaternion),c.group.position.set(c.group.position.x+$(n.x),c.group.position.y+$(n.y,1.2),c.group.position.z+$(n.z)),c.group.visible=!0,c.key=e,c.born=this.partsThrown++;let h=0;for(let t=0;tt.key===e)}partPosition(e,t){let n=this.parts.find(t=>t.key===e);return n!==void 0&&(t.copy(n.group.position),!0)}removePart(e){for(let t of this.parts)if(t.key===e){t.key=null,t.moving=!1,t.settle=-1,t.group.visible=!1,t.group.clear();for(let e of t.geometries)e.dispose();for(let e of t.materials)e.dispose();t.geometries.length=0,t.materials.length=0}}get activeParts(){let e=0;for(let t of this.parts)t.key!==null&&(e+=1);return e}partResting(e){return this.parts.some(t=>t.key===e&&!t.moving&&(t.settle<0||t.settle>=1))}updateParts(e){let t=this.bloodLevel===`full`;for(let n=0;n=0&&r.settle<1){r.settle=Math.min(1,r.settle+e/YV);let t=r.settle*r.settle*(3-2*r.settle);i.quaternion.slerpQuaternions(r.settleFrom,r.settleTo,t),i.position.y=r.settleFromY+(r.settleToY-r.settleFromY)*t}if(!r.moving){if(!t||r.lain>=xU)continue;let a=Math.floor(r.lain/SU);for(r.lain+=e,this.trailPoint.copy(r.cut).applyQuaternion(i.quaternion).add(i.position),r.trail+=e*this.forDevice(CU);r.trail>=1;)--r.trail,this.spawnDroplet(this.trailPoint.x,Math.max(.02,this.trailPoint.y),this.trailPoint.z,(this.ambientRandom()-.5)*.5,.2+this.ambientRandom()*.5,(this.ambientRandom()-.5)*.5,EO(this.ambientRandom()),.6,!0);if(Math.floor(r.lain/SU)===a)continue;let o=.1+r.radius*1.8;r.pool=Math.min(o,r.pool+o*SU*1.5/xU),this.canvasBlood.pool(this.trailPoint.x,this.trailPoint.z,r.pool,.95,n*13+a);continue}let a=i.position.x,o=i.position.z;if(r.vy-=5.8*e,i.position.x+=r.vx*e,i.position.y+=r.vy*e,i.position.z+=r.vz*e,i.rotation.x+=r.vrx*e,i.rotation.y+=r.vry*e,i.rotation.z+=r.vrz*e,t)for(r.trail+=e*this.forDevice(zV),r.trail>=1&&this.trailPoint.copy(r.cut).applyQuaternion(i.quaternion).add(i.position);r.trail>=1;)--r.trail,this.spawnDroplet(this.trailPoint.x+(this.ambientRandom()-.5)*.03,this.trailPoint.y+(this.ambientRandom()-.5)*.03,this.trailPoint.z+(this.ambientRandom()-.5)*.03,r.vx*.35+(this.ambientRandom()-.5)*.9,r.vy*.35+(this.ambientRandom()-.5)*.9,r.vz*.35+(this.ambientRandom()-.5)*.9,EO(this.ambientRandom()),.9,!0);let s=Math.max(.5,TE-r.reach-XV),c=JU(i.position.x,r.vx,a,s),l=JU(i.position.z,r.vz,o,s);if(i.position.x=c.position,i.position.z=l.position,r.vx=c.velocity,r.vz=l.velocity,i.position.y<=0+r.radius){if(i.position.y=0+r.radius,!r.stained&&t){r.stained=!0;let e=Math.min(2.4,r.radius/JV+.3);this.placeDecal(i.position.x,i.position.z,1.3*e,.9*e,i.rotation.z,.85,4392199)}if(r.bounces<2&&Math.abs(r.vy)>.42)r.bounces+=1,r.vy=Math.abs(r.vy)*.32,r.vx*=.62,r.vz*=.62,r.vrx*=.65,r.vry*=.65,r.vrz*=.65;else{r.moving=!1,r.trail=0;let e=this.settleAxis.copy(r.thin).applyQuaternion(i.quaternion);r.settleFrom.copy(i.quaternion),r.settleTo.setFromUnitVectors(e,this.settleUp.set(0,e.y>=0?1:-1,0)).multiply(i.quaternion),r.settleFromY=i.position.y,r.settleToY=0+r.thickness,r.settle=0}}Number.isFinite(i.position.x+i.position.y+i.position.z+i.quaternion.x+i.quaternion.y+i.quaternion.z+i.quaternion.w)||(i.position.set(0,0+r.thickness,0),i.quaternion.identity(),r.moving=!1,r.settle=-1)}}attachSpine(e){let t=this.spines[Math.trunc(e)];t!==void 0&&this.bloodLevel===`full`&&(t.wanted=!0)}spineOut(e){return this.spines[Math.trunc(e)]?.out===!0}spineTail(e,t){let n=this.spines[Math.trunc(e)];return n===void 0||!n.out?!1:(n.rope.node(wU,t),!0)}updateSpines(e){for(let t=0;t=1;){--n.trail;let e=a.node(Math.floor(this.ambientRandom()*12),this.gibPosition);this.spawnDroplet(e.x,e.y,e.z,(this.ambientRandom()-.5)*.8,(this.ambientRandom()-.5)*.8,(this.ambientRandom()-.5)*.8,EO(this.ambientRandom()),.8,!0)}}}}writeSpine(e){let t=this.spines[e].rope;for(let n=0;n1e-6?i.multiplyScalar(1/a):i.set(0,1,0)),r.add(this.partVertex).multiplyScalar(.5);let o=(.9+.5*Math.min(1,n/6))*(n>=9?.55+.25*(10-n):1);this.gibMatrix.compose(r,this.gibQuaternion,this.gibScale.set(o,this.spineStretch,o)),this.spineMesh.setMatrixAt(e*wU+n,this.gibMatrix)}this.spineMesh.instanceMatrix.needsUpdate=!0;for(let n=0;ne.out);this.spineMesh.visible=n,this.shredMesh.visible=n}spillGuts(e,t,n,r=18){let i=this.guts[Math.trunc(e)];if(i===void 0||e<0||this.bloodLevel!==`full`)return;let a=Number.isSafeInteger(n)?n:0;if(i.active&&i.eventId===a)return;let o=G.clamp(Math.round($(r,18)),2,OU),s=Math.max(2,Math.min(o,this.lowTier?Math.ceil(this.budget.gutLinks/2):this.budget.gutLinks));i.active=!0,i.eventId=a,i.sinceDrop=-1,i.drip=0,i.smeared.fill(NaN),i.anchor.set($(t.x),$(t.y,.9),$(t.z)),i.rope.spill(s,o*SV/s,i.anchor,s/kU,WH(a*28657+Math.trunc(e)*5+1)),i.tube.write(i.rope),i.mesh.visible=!0,i.moved=!1}anchorGuts(e,t,n){let r=this.guts[Math.trunc(e)];r===void 0||!r.active||r.sinceDrop>=0||(r.anchor.set($(t.x),$(t.y,.9),$(t.z)),n.lengthSq()>1e-8&&Number.isFinite(n.lengthSq())&&r.away.copy(n).normalize())}gutsOut(e){return this.guts[Math.trunc(e)]?.active===!0}dropGuts(e){let t=this.guts[Math.trunc(e)];t===void 0||!t.active||t.sinceDrop>=0||(t.sinceDrop=0,t.rope.release())}clearGuts(e){for(let[t,n]of this.guts.entries())(e===void 0||t===Math.trunc(e))&&(n.active=!1,n.eventId=null,n.moved=!1,n.rope.clear(),n.mesh.visible=!1)}gutsLength(e){let t=this.guts[Math.trunc(e)];return t===void 0||!t.active?0:t.rope.length}gutsPoint(e,t,n){let r=this.guts[Math.trunc(e)];return r===void 0||!r.active?!1:(r.rope.node(Math.round(G.clamp(t,0,1)*(r.rope.nodes-1)),n),!0)}updateGuts(e){for(let t=0;t=0&&n.sinceDrop=AU&&i)){let e=r.node(r.nodes>>1,this.gibPosition);this.canvasBlood.pool(e.x,e.z,.26,.95,t+3),this.puddle(e.x+.12,e.z+.05,.11,`bile`,t+5)}if(r.step(e,n.anchor,0,Math.max(2.4383999999999997,Math.abs(n.anchor.x),Math.abs(n.anchor.z)),n.away)&&(n.moved=!0,i)){for(let e=0;e0+.024*1.5){n.smeared[e*2]=NaN;continue}let i=n.smeared[e*2],a=n.smeared[e*2+1],o=Math.hypot(t.x-i,t.z-a);o=0))for(n.drip+=e*this.forDevice(PU);n.drip>=1;){--n.drip;let e=r.node(Math.floor(this.ambientRandom()*r.nodes),this.gibPosition),t=this.ambientRandom()<.8?`blood`:`bile`;this.spawnDroplet(e.x,e.y-xV,e.z,(this.ambientRandom()-.5)*.3,-.1,(this.ambientRandom()-.5)*.3,OO(t,this.ambientRandom()),.9,!0,.004+this.ambientRandom()*.005,t)}}}}ejectHeart(e,t,n,r=-1){if(this.bloodLevel!==`full`)return;let i=this.heart,a=WH((Number.isSafeInteger(n)?n:0)*611953+19),o=UU(t),s=2+a()*1.2,c=(a()-.5)*1.2;i.active=!0,i.moving=!0,i.owner=Math.trunc(r),i.age=0,i.beats=0,i.bounces=0,i.settle=-1,i.pool=0,i.trail=0,i.vx=s*o.x-c*o.z,i.vy=1.8+a()*1.2,i.vz=s*o.z+c*o.x,i.vrx=(a()-.5)*14,i.vry=(a()-.5)*14,i.vrz=(a()-.5)*14,i.settleTo.setFromAxisAngle(WU,a()*Math.PI*2).multiply(IU),this.heartMesh.position.set($(e.x),$(e.y,1.2),$(e.z)),this.heartMesh.quaternion.identity(),this.heartMesh.scale.setScalar(FU),this.heartMesh.visible=!0}get heartOut(){return this.heart.active}get heartBeating(){return this.heart.active&&this.heart.age<14}heartPosition(e){return this.heart.active?(e.copy(this.heartMesh.position),!0):!1}updateHeart(e){let t=this.heart;if(!t.active)return;let n=this.heartMesh,r=this.bloodLevel===`full`;if(t.moving){let i=n.position.x,a=n.position.z;t.vy-=6.4*e,n.position.x+=t.vx*e,n.position.y+=t.vy*e,n.position.z+=t.vz*e,n.rotation.x+=t.vrx*e,n.rotation.y+=t.vry*e,n.rotation.z+=t.vrz*e;let o=TE-this.heartRadius-XV,s=JU(n.position.x,t.vx,i,o),c=JU(n.position.z,t.vz,a,o);if(n.position.x=s.position,n.position.z=c.position,t.vx=s.velocity,t.vz=c.velocity,r)for(t.trail+=e*this.forDevice(zV/2);t.trail>=1;)--t.trail,this.spawnDroplet(n.position.x,n.position.y,n.position.z,t.vx*.3+(this.ambientRandom()-.5)*.8,t.vy*.3+(this.ambientRandom()-.5)*.8,t.vz*.3+(this.ambientRandom()-.5)*.8,EO(this.ambientRandom()),.8,!0);n.position.y<=0+this.heartRadius&&(n.position.y=0+this.heartRadius,t.bounces===0&&r&&this.placeDecal(n.position.x,n.position.z,.9,.7,n.rotation.z,.8,4392199),t.bounces<2&&Math.abs(t.vy)>.4?(t.bounces+=1,t.vy=Math.abs(t.vy)*.3,t.vx*=.6,t.vz*=.6,t.vrx*=.6,t.vry*=.6,t.vrz*=.6):(t.moving=!1,t.settle=0,t.settleFrom.copy(n.quaternion),t.settleFromY=n.position.y)),Number.isFinite(n.position.x+n.position.y+n.position.z)||(n.position.set(0,0+this.heartRest,0),n.quaternion.copy(t.settleTo),t.moving=!1,t.settle=1)}else if(t.settle<1){t.settle=Math.min(1,t.settle+e/YV);let r=t.settle*t.settle*(3-2*t.settle);n.quaternion.slerpQuaternions(t.settleFrom,t.settleTo,r),n.position.y=t.settleFromY+(0+this.heartRest-t.settleFromY)*r}if(t.age>=14)return;t.age+=e;let i=sV(t.age),a=oV(t.age),o=cV(a)*(.35+.65*i);if(n.scale.set(FU*(1-.17*o),FU*(1+.08*o),FU*(1-.17*o)),Math.floor(a)<=t.beats||(t.beats=Math.floor(a),!r))return;let s=this.trailPoint.copy(rV.position).multiply(n.scale).applyQuaternion(n.quaternion).add(n.position),c=zH.copy(rV.direction).applyQuaternion(n.quaternion);BH.set(Math.abs(c.y)<.9?0:1,+(Math.abs(c.y)<.9),0).cross(c).normalize(),VH.crossVectors(c,BH);for(let e=this.forDevice(Math.round(8+LU*i));e>0;--e){let e=Math.sqrt(this.ambientRandom())*.2,t=this.ambientRandom()*Math.PI*2;HH.copy(c).multiplyScalar(Math.cos(e)).addScaledVector(BH,Math.sin(e)*Math.cos(t)).addScaledVector(VH,Math.sin(e)*Math.sin(t)).multiplyScalar((.7+2.9*i)*(.5+.55*this.ambientRandom())),this.spawnDroplet(s.x,s.y,s.z,HH.x,HH.y,HH.z,EO(this.ambientRandom()),1.1,!0,.004+this.ambientRandom()**2*.011)}t.moving||(t.pool=Math.min(.3,t.pool+.022),this.canvasBlood.pool(n.position.x,n.position.z,t.pool,.95,t.beats))}setCorpse(e,t){let n=Math.trunc(e),r=this.corpses[n];r!==void 0&&(t===null||this.bloodLevel!==`full`?this.clearCorpse(n):(r.active||(r.active=!0,r.age=0,r.puddle=0),r.position.set($(t.x),Math.max(0,$(t.y,0)),$(t.z))))}fliesOver(e){let t=this.corpses[Math.trunc(e)];return t===void 0||!t.active?0:this.fliesArrived(t.age)}fliesArrived(e){let t=this.lowTier?this.budget.flies>>1:this.budget.flies;return Math.floor(G.clamp((e-RU)/zU,0,1)*t)}updateCorpses(e){for(let t=0;t=n.puddle+.04&&(n.puddle=r,this.puddle(n.position.x,n.position.z,r,`urine`,t*11+Math.round(r*25)));let i=this.fliesArrived(n.age);if(i===0)continue;let a=this.budget.flies,o=zU/(this.lowTier?a>>1:a);for(let e=0;e=i)this.gibMatrix.makeScale(0,0,0).setPosition(0,-50,0);else{let t=Math.min(1,(n.age-RU-e*o)/BU),i=MV(this.flies,r,n.age,this.gibPosition),a=1+(1-t)*2.5;this.gibMatrix.makeTranslation(n.position.x+i.x*a,Math.max(.03,n.position.y+i.y+(1-t)*(1-t)*1.6),n.position.z+i.z*a)}this.flyMesh.setMatrixAt(r,this.gibMatrix)}this.flyMesh.visible=!0,this.flyMesh.instanceMatrix.needsUpdate=!0}}clearCorpse(e){let t=this.corpses[e];if(t.active){t.active=!1,this.gibMatrix.makeScale(0,0,0).setPosition(0,-50,0);for(let t=0;te.active)}}dispose(){this.scene.remove(this.dropletMesh),this.scene.remove(this.mistPoints),this.scene.remove(this.gibMesh),this.scene.remove(this.shardMesh),this.scene.remove(this.eyeballMesh);for(let e of this.viscera)this.scene.remove(e.mesh),e.mesh.dispose(),e.geometry.dispose();this.visceraMaterial.dispose();for(let e of this.parts)e.key!==null&&this.removePart(e.key),this.scene.remove(e.group);this.limbMaterial.dispose(),this.limbMap.dispose(),this.trunkMaterial.dispose(),this.trunkMap.dispose(),this.scene.remove(this.spineMesh,this.shredMesh,this.heartMesh,this.flyMesh),this.spineMesh.dispose(),this.shredMesh.dispose(),this.shredGeometry.dispose();for(let e of this.guts)this.scene.remove(e.mesh),e.tube.dispose();this.heartGeometry.dispose(),this.flyMesh.dispose(),this.flyGeometry.dispose(),this.flyMaterial.dispose(),this.dropletMesh.dispose(),this.dropletGeometry.dispose(),this.dropletMaterial.dispose(),this.canvasBlood.dispose();for(let e of[...this.heads,...this.hands])e.baked?.dispose(),e.bakedFlesh?.dispose();for(let e of[...this.stumps,...this.handStumps])e.flesh.dispose();this.mistGeometry.dispose(),this.mistMaterial.dispose(),this.mistMap.dispose(),this.gibMesh.dispose(),this.gibGeometry.dispose(),this.gibMaterial.dispose(),this.shardMesh.dispose(),this.eyeballMesh.dispose(),this.shardGeometry.dispose(),this.shardMaterial.dispose(),this.jawMaterial.dispose(),this.jawMap.dispose(),this.headGeometry.dispose();for(let e of this.headMaterials)e.dispose();this.handGeometry.dispose();for(let e of this.handMaterials)e.dispose();this.stumpGeometry.dispose(),this.wristStumpGeometry.dispose(),this.shieldGeometry.dispose();for(let e of this.shieldMaterials)e.dispose();for(let e of this.shieldMeshes)this.scene.remove(e);this.eyeGeometry.dispose(),this.eyeMap.dispose(),this.eyeMaterial.dispose(),this.nerveGeometry.dispose(),this.nerveMaterial.dispose();for(let e of[...this.eyeMeshes,...this.nerveMeshes])this.scene.remove(e);if(this.stumpMaterial.dispose(),this.stumpMap.dispose(),this.wristMaterial.dispose(),this.wristMap.dispose(),this.bakedStandIns!==null){this.bakedStandIns.map.dispose();for(let e of this.bakedStandIns.materials)e.dispose();for(let e of this.bakedStandIns.instanced)e.dispose();this.bakedStandIns=null}for(let e of this.heads)this.scene.remove(e.mesh);for(let e of this.hands)this.scene.remove(e.mesh);for(let e of[...this.stumps,...this.handStumps])this.scene.remove(e.mesh)}},cW={maximum:1,minimum:.55,slowMs:24,fastMs:17.5,windowMs:1e3,step:.15},lW=10,uW=10,dW=160,fW=3,pW=3,mW=class{options;scale;elapsed=0;frames=0;fastWindows=0;holdWindows=0;fruitlessAttempts=0;pending=null;raised=null;raiseHoldWindows=0;failedRaises=0;constructor(e=cW){this.options=e,this.scale=e.maximum}record(e){if(!(e>0)||e>1e3||(this.elapsed+=e,this.frames+=1,this.elapsede.before*.9)return this.scale=e.previous,this.holdWindows=Math.min(dW,lW*2**this.fruitlessAttempts),this.fruitlessAttempts+=1,!0;this.fruitlessAttempts=0}if(this.raised!==null){let e=this.raised;if(t>this.options.slowMs)return this.raised=null,this.scale=e.previous,this.fastWindows=0,this.raiseHoldWindows=Math.min(dW,uW*2**this.failedRaises),this.failedRaises+=1,!0;e.windows+=1,e.windows>=pW&&(this.raised=null,this.failedRaises=0)}if(t>this.options.slowMs){if(this.fastWindows=0,this.holdWindows>0)return--this.holdWindows,!1;if(this.scale<=this.options.minimum)return!1;let e=this.scale;return this.scale=Math.max(this.options.minimum,this.scale-this.options.step),this.pending={before:t,previous:e},!0}return t0?(--this.raiseHoldWindows,!1):this.fastWindows>=fW&&this.scale0&&e.poise===0)return 1;if(e.is_downed)return gW;let n=e.stunned_ticksthis.value?7:.9;return this.value+=(e-this.value)*(1-Math.exp(-n*Math.max(0,t))),e===0&&this.value<.003&&(this.value=0),this.value}},yW=.4,bW=.5,xW={before:24,after:24,speed:.5};function SW(e,t,n=30,r=yW,i=42,a=33){let o=t.tick-i,s=t.tick+a,c=e.filter(e=>e.tick>=o-1&&e.tick<=s+1),l=c.at(-1),u=l!==void 0&&l.result!==null&&l.tick({...l,tick:l.tick+t+1,events:[]}))]:c,d=u[0],f=u.at(-1);if(d===void 0||f===void 0||u.length<8||d.tick>t.tick-12||f.tick=1&&this.lastHeat<1&&!r&&(this.flare=1),this.lastHeat=t,this.flare=Math.max(0,this.flare-n/DW);let a=this.mesh.material;if(a.opacity=Math.min(1,t*.8+this.flare*.6),this.mesh.visible=a.opacity>.01,!this.mesh.visible)return;this.mesh.position.copy(e),this.mesh.quaternion.copy(i.quaternion);let o=TW*(.55+.45*t)*(1+this.flare*EW);this.mesh.scale.set(o,o,1)}get active(){return this.mesh.visible}standIn(){return new Y(this.mesh.geometry,this.mesh.material)}reset(){this.flare=0,this.lastHeat=0,this.mesh.material.opacity=0,this.mesh.visible=!1}dispose(){this.mesh.geometry.dispose(),this.mesh.material.dispose()}},FW=class{group=new t_;flash;ring;age=1/0;constructor(e){this.flash=NW(e,new J(1,.86,.62)),this.flash.material.depthTest=!1,this.ring=new Y(new gb(.42,.5,40),new yv({color:wW,blending:2,depthWrite:!1,transparent:!0,side:2})),this.flash.renderOrder=6,this.ring.renderOrder=6,this.group.add(this.flash,this.ring),this.group.visible=!1}fire(e){this.age=0,this.group.position.copy(e)}update(e,t){this.age+=e;let n=this.age/OW,r=this.age/AW;if(this.group.visible=r<1,!this.group.visible)return;this.group.quaternion.copy(t.quaternion),this.flash.visible=n<1;let i=kW*(.35+.65*Math.sqrt(Math.min(1,n)));this.flash.scale.set(i,i,1),this.flash.material.opacity=(1-Math.min(1,n))**2;let a=jW*(.15+.85*(1-(1-r)**3));this.ring.scale.set(a,a,a),this.ring.material.opacity=.9*(1-r)}get active(){return this.group.visible}standIns(){return[new Y(this.flash.geometry,this.flash.material),new Y(this.ring.geometry,this.ring.material)]}reset(){this.age=1/0,this.group.visible=!1}dispose(){this.flash.geometry.dispose(),this.flash.material.dispose(),this.ring.geometry.dispose(),this.ring.material.dispose()}},IW=10,LW=.055,RW=3.2,zW=1.4,BW=class{color;mesh;geometry;positions=new Float32Array(60);colors=new Float32Array(80);history=[];last=new q;hasLast=!1;tangent=new q;side=new q;toCamera=new q;shade=new J;strength=0;heat=0;constructor(e){this.color=e,this.geometry=new iv,this.geometry.setAttribute(`position`,new U_(this.positions,3).setUsage(gh)),this.geometry.setAttribute(`color`,new U_(this.colors,4).setUsage(gh));let t=[];for(let e=0;e<9;e+=1){let n=e*2;t.push(n,n+1,n+2,n+1,n+3,n+2)}this.geometry.setIndex(t);let n=new yv({vertexColors:!0,transparent:!0,blending:2,depthWrite:!1,side:2});this.mesh=new Y(this.geometry,n),this.mesh.frustumCulled=!1,this.mesh.visible=!1,this.mesh.renderOrder=4}update(e,t,n,r,i=0){if(t<=0)return;let a=this.hasLast?e.distanceTo(this.last)/t:0;this.last.copy(e),this.hasLast=!0,this.heat=i>this.heat?i:this.heat+(i-this.heat)*Math.min(1,t*6);let o=RW*(1-.55*this.heat),s=r&&a>o?Math.min(1,(a-o)/4+this.heat*.4):0;this.strength+=(s-this.strength)*Math.min(1,t*18);let c=this.history.length>=IW?this.history.shift():new q;if(c.copy(e),this.history.push(c),this.strength<.02||this.history.length<3){this.mesh.visible=!1;return}let l=this.history.length,u=this.shade.copy(this.color).lerp(wW,this.heat),d=LW*(1+zW*this.heat);for(let e=0;e3*t}function WW(e,t,n){let r=e.detail.endsWith(`:head`)||e.detail.endsWith(`:body`);return t===void 0||![`hit`,`counter_hit`].includes(e.kind)||!r||n===null||n.winner_id===null||n.winner_id!==e.actor_id?!1:n.finish_method===`flash_ko`||(n.finish_method===`ko`||n.finish_method===`tko`)&&t.is_downed}function GW(e){for(let t of e.passes)t.dispose?.();e.dispose()}function KW(e,t,n,r,i){e.setRenderTarget(t.readBuffer);let a=e.compileAsync(n,r,i);return e.setRenderTarget(null),a}var qW=-4e-4,JW=10,YW=16;function XW(e,t,n){let r=t?YW:n;e.autoUpdate=!t,e.intensity=+!t,e.bias=t?JW:qW,e.mapSize.x!==r&&(e.mapSize.set(r,r),e.map?.dispose(),e.map=null,e.needsUpdate=!0)}function ZW(e,t){let n=t.fighters.findIndex(t=>t.player_id===e.target_id),r=t.fighters.findIndex(t=>t.player_id===e.actor_id),i=e.kind===`block`||e.kind===`perfect_block`;return{recipientIndex:i?r:n,puncherIndex:i?n:r}}function QW(e,t,n){if(e===void 0||t===void 0)return;let r=n.x(t.x)-n.x(e.x),i=n.z(t.y)-n.z(e.y),a=Math.hypot(r,i);return Number.isFinite(a)&&a>.001?{x:r/a,z:i/a}:void 0}var $W=e=>e.kind===`hit`||e.kind===`counter_hit`,eG=e=>e.kind===`block`||e.kind===`perfect_block`,tG=480,nG=.56,rG=1.8,iG=1.7,aG=1.2,oG=1.6,sG=30,cG=6.5,lG=.4,uG=600,dG=2.8,fG=.6,pG=[[1,0],[-1,0],[.75,-.66],[-.75,-.66],[.75,.66],[-.75,.66]],mG=.15,hG=.6,gG=2.3,_G=.5,vG=3.42,yG=2.2,bG=.9,xG=`body`,SG=`collapse`,CG=.55,wG=.5,TG=.5,EG=.28,DG=104,OG=260,kG=.05,AG=2.95,jG=2.4,MG=1.6,NG=.98,PG={uniforms:{tDiffuse:{value:null},uTime:{value:0},uVignette:{value:.32},uGrain:{value:.035},uRocked:{value:0}},vertexShader:` varying vec2 vUv; void main() { vUv = uv; @@ -5387,8 +5387,8 @@ void main() { float grain = (hash(floor(vUv * vec2(960.0, 540.0))) - 0.5) * uGrain; color.rgb += grain * (0.15 + color.rgb); gl_FragColor = color; -}`},PG=[{x:-102,y:-16},{x:102,y:-16}],FG=[0,1],IG=.5,LG={x:0,z:-.2},RG=0,zG=200,BG=1.3,VG=.7,HG=4.5;function UG(e,t,n,r){let i=n.x-e,a=n.y-t,o=Math.hypot(i,a);return o<=Math.max(r,1e-6)?{x:n.x,y:n.y,arrived:!0}:{x:e+i/o*r,y:t+a/o*r,arrived:!1}}var WG=16,GG=.6,KG={hit:.18,counter_hit:.3,guard_break:.25,knockdown:1,block:.04,perfect_block:.1,parry:.22,body_collapse:.45},qG=new Set([`hit`,`counter_hit`,`block`,`perfect_block`,`guard_break`,`knockdown`,`parry`,`body_collapse`,`eye_shut`]),JG=new Set([`parry`,`body_collapse`,`eye_shut`]),YG=new Set([`hit`,`counter_hit`,`block`,`perfect_block`]),XG=1.2,ZG=.8,QG=2.4,$G=2.5,eK=new Set([`referee_hit`,`referee_down`]),tK=.05,nK=.08,rK={parry:{text:`PARRIED`,seconds:1},eye_shut:{text:`EYE SWOLLEN SHUT`,seconds:1.6}},iK=new Set([`injury`,`vomit`,`finish_him`,`fatality`,`death`]),aK=1.8,oK=3,sK=.6;function cK(e,t){let n=Ae(e,t);return n!==`severed`&&n!==`torn`}function lK(e){return e.kind===`death`?e.detail===`brain`?`head_burst`:null:e.kind===`fatality`?e.detail===`head_burst`?`head_burst`:e.detail===`decapitation`||e.detail===`spine_rip`?`decapitation`:null:null}var uK=e=>e.kind===`knockdown`&&e.detail===`body`;function dK(e,t){if(QW(e)&&e.action_id!==null)return t.find(t=>$W(t)&&t.action_id===e.action_id&&t.actor_id===e.target_id&&t.target_id===e.actor_id)}function fK(e,t){if($W(e)&&e.action_id!==null)return t.find(t=>QW(t)&&t.action_id===e.action_id&&t.actor_id===e.target_id&&t.target_id===e.actor_id)}function pK(e,t){return e.map((n,r)=>{if(JG.has(n.kind)||n.kind===`knockdown`&&n.detail===xG)return{event:n,presentationEvent:n,presentImpact:!1,reactAmount:null};let{puncherIndex:i}=XW(n,t),a=t.fighters[i],o=a?.action_key?.split(`:`)??[],s=o.length>=3?`${o[0]}:${o[2]}`:n.detail,c=fK(n,e);if($W(n))return{event:n,presentationEvent:{...n,detail:c?.detail||s,direction:c?.direction??a?.facing??n.direction,blood:c?.blood??n.blood},presentImpact:!0,reactAmount:n.amount};if(dK(n,e)!==void 0)return{event:n,presentationEvent:n,presentImpact:!1,reactAmount:n.amount};if(n.kind===`knockdown`){let t=e.slice(0,r).reverse().find(e=>QW(e)&&e.tick===n.tick&&e.actor_id===n.actor_id&&e.target_id===n.target_id);if(t!==void 0)return{event:n,presentationEvent:{...n,detail:t.detail,direction:t.direction,blood:t.blood,action_id:t.action_id},presentImpact:!0,reactAmount:dK(t,e)===void 0?null:t.amount}}return{event:n,presentationEvent:n,presentImpact:!0,reactAmount:n.amount}})}function mK(e){let t=e?.trauma;if(t===void 0)return{side:1,lift:.08,lateral:.035,prop:`enswell`};switch(e?.corner_choice){case`cut`:return{side:t.right_cut>t.left_cut?-1:1,lift:.11,lateral:.04,prop:`enswell`};case`swelling`:return{side:t.right_eye>t.left_eye?-1:1,lift:.08,lateral:.035,prop:`enswell`};case`breath`:return{side:1,lift:-.015,lateral:0,prop:`bottle`};default:return{side:t.right_eye+t.right_cut>t.left_eye+t.left_cut?-1:1,lift:.08,lateral:.035,prop:`enswell`}}}function hK(e){return e?.split(`:`)[1]===`right`?1:-1}function gK(e){return e.result===null?e.tick-1:e.tick}var _K=50,vK=40,yK=40,bK=50,xK=[`jab`,`straight`,`hook`,`uppercut`];function SK(e,t,n,r){if(!WW(e,t,n))return null;let i=r?.action_key?.split(`:`),a=e.detail.split(`:`).find(e=>xK.includes(e))??i?.[0],o=i?.[1]===`right`?`left`:`right`,s=e.amount;return e.detail.endsWith(`:head`)?n?.finish_method===`flash_ko`||e.kind===`counter_hit`&&s>=70?`head_burst`:a===`uppercut`&&s>=vK||a===`straight`&&s>=_K?`decapitation`:(a===`hook`||a===`jab`)&&s>=yK?`eye_${o}`:`jaw_dislocation`:a===`hook`?s>=bK?`dismember_${o}`:`shoulder_${o}`:`ribs_${o}`}function CK(){let e=document.createElement(`canvas`);e.width=128,e.height=128;let t=e.getContext(`2d`);if(t!==null){let e=t.createRadialGradient(64,64,8,64,64,62);e.addColorStop(0,`rgba(0,0,0,0.68)`),e.addColorStop(.6,`rgba(0,0,0,0.34)`),e.addColorStop(1,`rgba(0,0,0,0)`),t.fillStyle=e,t.fillRect(0,0,128,128)}return new ky(e)}var wK=new q(0,.12,.02),TK=new q(0,1,0),EK=new WeakMap;function DK(e){let t=EK.get(e);return t===void 0&&(t=AO(e,KK),EK.set(e,t)),t}function OK(e){return e.y>cA-1.4}var kK=new WeakMap;function AK(e){let t=kK.get(e);return t===void 0&&(t=AO(e,OK),kK.set(e,t)),t}function jK(e,t,n){let r=e.bone(`head`);if(r===null)return null;e.root.updateMatrixWorld(!0);let i=e.headMesh,a=AK(i.geometry);if(a.length===0)return null;let o=t.length===a.length*3?t:new Float32Array(a.length*3);n.position.set(0,0,0);for(let[t,r]of a.entries())BK(e,r,n.scratch),n.scratch.toArray(o,t*3),n.position.add(n.scratch);return n.position.multiplyScalar(1/a.length),r.getWorldQuaternion(n.quaternion),n.across.set(1,0,0).applyQuaternion(n.quaternion),n.scratch.set(0,1,0).applyQuaternion(n.quaternion),n.quaternion.setFromUnitVectors(TK,n.scratch),o}function MK(e,t,n,r){let i=e?.currentRoot;return r.set(i?.x??n.x(t.x),0,i?.z??n.z(t.y))}function NK(e,t,n,r,i){let a=Math.hypot(e-n,t-r);return a>=i?{x:e,z:t}:a<1e-6?{x:n,z:r-i}:{x:n+(e-n)/a*i,z:r+(t-r)/a*i}}var PK=[0,1.05,-1.05,2.1,-2.1,Math.PI];function FK(e,t,n,r,i,a,o=[]){let s=n===null?0:Math.hypot(n.x,n.z),c=n!==null&&s>=.35?[Math.atan2(n.x,n.z)]:[];for(let e of PK)c.push(a+e);for(let n of c){let a=G.clamp(e+Math.sin(n)*r,-i,i),s=G.clamp(t+Math.cos(n)*r,-i,i),c=Math.hypot(a-e,s-t);if(!(c{let r=G.clamp(((n.x-e)*(a-e)+(n.z-t)*(s-t))/(c*c),.25,1);return Math.hypot(e+(a-e)*r-n.x,t+(s-t)*r-n.z)1e-9&&(s=Math.min(s,(Math.sign(n)*i-e)/n)),Math.abs(r)>1e-9&&(s=Math.min(s,(Math.sign(r)*a-t)/r));for(let i of[-1,1])for(let a of[-1,1]){let c=i*n+a*r;c>1e-9&&(s=Math.min(s,(o-i*e-a*t)/c))}return Math.max(0,s)}function LK(e,t,n,r,i,a,o,s=1/0){let c=Math.hypot(n-e,r-t);if(c>=i)return null;let l=c<1e-6?1:(n-e)/c,u=c<1e-6?0:(r-t)/c,d=i-c,f=IK(e,t,-l,-u,a,o,s),p=IK(n,r,l,u,a,o,s),m=Math.min(d/2,f),h=Math.min(d-m,p);m=Math.min(d-h,f);let g=G.clamp;return{ax:g(e-l*m,-a,a),ay:g(t-u*m,-o,o),bx:g(n+l*h,-a,a),by:g(r+u*h,-o,o)}}var RK=new WeakMap;function zK(e,t,n,r,i,a,o,s=null){let c=RK.get(e);if(c!==void 0&&c.width===t&&c.height===n)return c.top;let l=Hr(t,n,zr(e,r,i,r.map(e=>a.total(e.player_id)),s),!0).y;return RK.set(e,{width:t,height:n,top:l}),l}function BK(e,t,n){let r=e.headMesh;return Dj(n.fromBufferAttribute(r.geometry.getAttribute(`position`),t),e.look,n),r.applyBoneTransform(t,n).applyMatrix4(r.matrixWorld)}var VK=new Sg,HK=new Sg,UK=new Dg;function WK(e,t,n){let r=e.geometry;VK.fromBufferAttribute(r.getAttribute(`skinIndex`),t),HK.fromBufferAttribute(r.getAttribute(`skinWeight`),t),n.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);for(let t=0;t<4;t+=1){let r=HK.getComponent(t);if(r===0)continue;let i=VK.getComponent(t);UK.multiplyMatrices(e.skeleton.bones[i].matrixWorld,e.skeleton.boneInverses[i]);for(let e=0;e<16;e+=1)n.elements[e]+=UK.elements[e]*r}return n.premultiply(e.bindMatrixInverse).multiply(e.bindMatrix)}var GK=new q(-1,0,0);function KK(e){return e.y>oA-sA*(e.z- -4)-.3}var qK={tick_rate:30,ring_half_width:500,ring_half_height:500};function JK(e,t,n,r,i,a,o=!0){let s=e.geometry,c=s.getAttribute(`position`),l=s.getIndex(),u=[],d=l!==null&&r===void 0?[]:null;if(l===null||d===null)for(let e=0;e=i.start+o))return{action:i.punchClass,action_hand:i.hand,action_target:`head`,action_power:`normal`,action_id:`idle-${n}-${r}`,action_key:`${i.punchClass}:${i.hand}:head:normal`,action_start_tick:e-(t-i.start),action_startup_ticks:a.startup,action_active_ticks:a.active,action_recovery_ticks:a.recovery,action_contact_tick:e-(t-i.start)+a.startup}}return{}}var tq=1000003,nq=1.6;function rq(e,t,n,r,i,a){let o=r<0?-1:1,s=o=>Math.hypot(G.clamp(e+n*o*i,-a,a)-e,G.clamp(t+r*o*i,-a,a)-t);return s(o)>=i*.8||s(o)>=s(-o)?o:-o}function iq(e,t,n){return t?e.kind===`knockdown`?1:Math.min(1,.35+e.amount/400):(n===`full`?1:n===`reduced`?.4:0)*(e.kind===`knockdown`?.85:e.amount>=50?Math.min(.75,(e.amount-30)/140):0)}function aq(e){if(e.kind!==`hit`&&e.kind!==`counter_hit`||e.amount<(e.detail.endsWith(`:body`)?70:50))return null;let t=Math.min(100,Math.max(0,e.blood));return{seconds:.6+t/50,rate:150+e.amount*1.5+t*2}}function oq(e,t){return t===`full`?e>100?Math.min(.65,e/1800):0:e>350?Math.min(.3,e/4600):0}function sq(e){return!e.is_downed&&e.stunned_ticks===0&&e.clinch_ticks===0&&e.clinch_startup_ticks===0&&e.taunt_ticks===0&&!e.is_foul_recovery_target}function cq(e,t){if(e===null)return null;let n=t.fighters.find(t=>t.player_id===e.target_id),r=t.fighters.find(t=>t.player_id===e.actor_id);return SK(e,n===void 0?void 0:{...n,is_downed:!0},{finish_method:`ko`,winner_id:e.actor_id},r)}var lq=.2,uq=1.1,dq=1.6,fq=2.4,pq=2,mq=new q(0,-.1,.08),hq=new q(0,-.07,.1),gq=new q(0,-.35,1),_q=3,vq=320,yq=8,bq=1.6,xq=.08,Sq=.12,Cq=e=>e===`shoulder_left`||e===`shoulder_right`||e===`ribs_left`||e===`ribs_right`?e:`mouth`;function wq(e,t,n=uq){return Math.min(n,.06+.08*Math.sqrt(Math.max(0,e))*Math.min(1.6,Math.max(0,t)))}function Tq(e,t,n){return e.is_downed||t?.isDown===!0||n!==void 0&&e.player_id===n}var Eq=6,Dq=11,Oq=.13;function kq(e,t){let n=t===`left`?`leftRibs`:`rightRibs`;e.impact(n,[t===`left`?-6:Eq,-6*.15,-1.5],Dq),e.set(n,{bruise:1.2,swell:0,blood:1.4})}function Aq(e,t){e.set(`mouth`,{cut:1,blood:1.4}),e.set(`chin`,{bruise:1.2}),t.set(`neckSmear`,{blood:1.4})}function jq(e,t){e.set(t===`left`?`leftShoulderSmear`:`rightShoulderSmear`,{blood:1.4}),e.set(t===`left`?`leftPec`:`rightPec`,{bruise:1.1})}var Mq=new WeakMap;function Nq(e,t){let n=Mq.get(e);if(n===void 0){let t=e.getAttribute(`position`),r=new q,i=new q,a=VA.map(e=>{let n=0,a=1/0;i.set(e[0],e[1],e[2]);for(let e=0;ethis.onAnnouncement?.(e),cue:e=>this.onCrowdCue?.(e)});touchControls=Md();resultAnnounced=!1;captionText=``;rocked=new vW;tmpA=new q;tmpB=new q;contactPoint=new q;cornerPanelTop=null;mouthPoint=new q;tmpHead=new q;tmpHeadQuaternion=new rg;tmpStump=new q;tmpStumpOffset=new q;tmpStumpQuaternion=new rg;tmpStumpAcross=new q;tmpPart=new q;tmpPartQuaternion=new rg;woundPoint=new q;woundAxis=new q;constructor(e,t=qK,n,r={}){this.canvas=e,this.simulation=t,this.settings=n,this.manualClock=r.manualClock===!0,this.localInput=r.localInput??null,this.powerHeld=r.powerHeld??null,this.inputSequenceOf=r.inputSequenceOf??null,this.buffer=new Ef(8,t.tick_rate),this.mapping=DE(t),this.renderer=new AT({canvas:e,antialias:!0,powerPreference:`high-performance`,preserveDrawingBuffer:r.manualClock===!0}),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=1,this.renderer.toneMapping=4,this.renderer.toneMappingExposure=1,this.renderer.setPixelRatio(this.basePixelRatio),this.scene.background=new J(`#04060b`),this.scene.fog=new l_(`#04060b`,.042),this.camera=new Ox(36,1,.1,80),this.camera.position.set(0,2.05,5.9),this.camera.lookAt(0,1.05,0),this.setupLights(),this.ring=rF(),this.scene.add(this.ring.group),this.arena=iD(),this.scene.add(this.arena.group),this.effects=new sW(this.scene,Md()?1024:2048,Md()?PV:NV),this.effects.useUploader(this.renderer),this.effects.setCamera(this.camera),this.carnage=new Yz(this.effects,XK),this.blobTexture=CK();let i=new hb(1,1);for(let e=0;e<3;e+=1){let t=new Y(i,new yv({map:this.blobTexture,transparent:!0,depthWrite:!1}));t.rotation.x=-Math.PI/2,t.position.y=.006+e*4e-4,t.renderOrder=1,this.blobShadows.push(t),this.scene.add(t)}this.composer=new zT(this.renderer),this.composer.addPass(new BT(this.scene,this.camera));let a=new HT(new K(1280,720),.2,.45,1.08);this.bloomPass=a,this.composer.addPass(a),this.finishPass=new IT(NG),this.composer.addPass(this.finishPass),this.composer.addPass(new WT),this.hudCanvas=document.createElement(`canvas`),this.hudCanvas.className=`fight-hud`,this.hudCanvas.style.cssText=`position:absolute;inset:0;width:100%;height:100%;pointer-events:none`,e.insertAdjacentElement(`afterend`,this.hudCanvas),this.bloodLevel=n().blood,this.effects.setBloodLevel(this.bloodLevel),this.ensureGraphs(),this.manualClock||(this.raf=requestAnimationFrame(e=>this.draw(e)))}ensureGraphs(){this.glbLoading||this.graphs!==null||(this.glbLoading=!0,this.graphsReady=mF().then(async e=>{if(this.destroyed)return;let t=new DF(e,{skin:11563071,gear:1920728}),n=new DF(e,{skin:7225640,gear:12131356});this.graphs=[new aI(t,this.mapping),new aI(n,this.mapping)];let r=[this.carnage.attach(0,this.graphs[0]),this.carnage.attach(1,this.graphs[1])];this.lookIds.fill(null),this.syncInjuryPresentation(0),this.syncInjuryPresentation(1);let i=new DF(e,{skin:13081462,gear:3889080,look:hj.referee,outfit:Pj,wounds:!0});this.referee=new aI(i,this.mapping,{referee:!0,knockout:!0});let a=new DF(e,{skin:9067067,gear:1778224,look:hj.blueCorner,outfit:Fj}),o=new DF(e,{skin:14264188,gear:1778224,look:hj.redCorner,outfit:Ij});this.cornermen=[new aI(a,this.mapping,{referee:!0}),new aI(o,this.mapping,{referee:!0})];let s=new DF(e,{skin:12160102,gear:1778224,look:hj.blueCutman,outfit:Lj}),c=new DF(e,{skin:5913126,gear:1778224,look:hj.redCutman,outfit:Lj});this.cutmen=[new aI(s,this.mapping,{referee:!0}),new aI(c,this.mapping,{referee:!0})],s.root.visible=!1,c.root.visible=!1,this.trails=[1920728,12131356].flatMap(e=>[0,1].map(()=>new BW(new J(e).lerp(new J(16777215),.55))));let l=MW();this.glowMap=l,this.glows=[0,1,2,3].map(()=>new PW(l)),this.impactFlashes=[0,1].map(()=>new FW(l));let u=new t_;u.add(t.root,n.root,i.root,a.root,o.root,s.root,c.root,...this.trails.map(e=>e.mesh),...this.effects.compileStandIns(),...r.flatMap(e=>e.compileStandIns()),this.glows[0].standIn(),...this.impactFlashes[0].standIns());let d=t.headInjury.open;t.headInjury.setOpen(!0);try{await KW(this.renderer,this.composer,u,this.camera,this.scene)}catch{}if(!this.destroyed){this.scene.add(t.root,n.root,i.root,a.root,o.root,s.root,c.root);for(let e of this.trails)this.scene.add(e.mesh);for(let e of this.glows)this.scene.add(e.mesh);for(let e of this.impactFlashes)this.scene.add(e.group);this.compileShadowsOf(u),t.headInjury.setOpen(d)}}).catch(e=>{this.glbLoading=!1,console.error(`boxer_glb_load_failed`,e)}))}compileShadowsOf(e){let t=this.keyLight;if(t!==null&&e.children.length!==0){for(let t of e.children)t.frustumCulled=!1,t.onBeforeShadow=(e,t,n,r,i,a)=>{a.needsUpdate=!0};this.scene.add(e),t.shadow.needsUpdate=!0,this.renderer.setRenderTarget(this.composer.readBuffer);try{this.renderer.render(this.scene,this.camera)}catch{}finally{this.renderer.setRenderTarget(null),this.scene.remove(e)}}}get ready(){return this.graphsReady}get labRigs(){let e=this.graphs;return e===null?[]:[e[0].boxer.root,e[1].boxer.root]}get labScene(){return this.scene}get labEffects(){return this.effects}labSetCameraOverride(e,t){this.cameraOverride={position:new q(...e),lookAt:new q(...t)}}labFrame(e,t=!0){this.draw(e*1e3,!0,t)}setCornerPanelTop(e){this.cornerPanelTop=e}viewForward(){return this.ownViewActive?(this.ownForward.x=this.fighterCam.forwardX,this.ownForward.z=this.fighterCam.forwardZ,this.ownForward):null}setPlayers(e,t,n=Object.keys(e)){this.players=e,this.viewerId=t,this.playerOrder=n}updateIdleFighters(e,t,n){let r=this.graphs;if(r===null)return;let i=this.playerOrder.filter(e=>this.players[e]!==void 0).length<2;for(let[a,o]of r.entries()){let r=this.playerOrder[a]??`seat-${a}`,s=!i||r===this.viewerId||this.viewerId===null&&a===0;if(o.boxer.root.visible=s,!s)continue;this.wearLook(a===0?0:1,r);let c=a===0?-1:1,l=Math.floor(t*this.simulation.tick_rate),u={...ZK(r),x:i?0:c*180,y:i?-70:0,facing:i?1:-c,facing_x:i?0:-c*1e3,facing_y:i?-1e3:0,...i?eq(l):{}},d={...ZK(this.playerOrder[1-a]??`opponent`),x:i?0:-c*180,y:i?-150:0};o.setResting(!1),o.update(u,d,e,t,this.settings().reducedMotion,this.bloodLevel,i?l:n)}}setFinal(e){if(e!==null&&e.match_id===this.final?.match_id)return;this.final=e,this.stoppageWinner=-1,this.stoppageRaiseAt=1/0,this.stoppageSpot=null,this.raiseFramed=!1,this.ceremony=this.ceremonyFor(e);let t=e?.method===`draw`&&this.deaths.every(e=>e!==null);if(this.finalRevealAt=this.frameSeconds+(this.ceremony===null?t?fr:mr(e):HG),this.ovationUntil=e===null?0:this.frameSeconds+WG,e!==null&&this.commentary.finish(e,this.players,this.ceremony!==null,this.frameSeconds),this.ceremony===null&&this.endCeremony(),this.pendingFinish=null,e===null||!dr.has(e.method))return;let n=this.lastKnockdown===null?null:SW(this.history,this.lastKnockdown.hit??this.lastKnockdown.knockdown,this.simulation.tick_rate),r=this.finishingInjury(e);if(n!==null&&this.graphs!==null&&!this.settings().reducedMotion){r!==null&&(this.replayInjuries[r.index]={injury:r.injury,event:r.event}),this.startReplay(n);return}if(r!==null){let e=this.pendingContacts.find(e=>e.event.event_id===r.event.event_id);e===void 0?this.applyArcadeInjury(r.index,r.injury,r.event):e.injury??=r.injury}let i=this.buffer.latest()?.result?.tick;i===void 0?this.presentFinish(e):this.pendingFinish={final:e,tick:i,latestAt:this.frameSeconds+gG}}presentFinishWhenShown(e){let t=this.pendingFinish;t===null||ee.player_id===t.hit.target_id)??-1;return r<0||this.arcadeInjuries[r]!==null?null:{index:r,injury:t.finisher,event:t.hit}}ceremonyFor(e){let t=this.buffer.latest()?.fighters;if(e===null||t===void 0||e.method!==`decision`&&e.method!==`draw`||t.some(e=>e.is_downed)||this.deaths.some(e=>e!==null))return null;let n=t.findIndex(t=>t.player_id===e.winner_id);return{winnerSeat:n===0||n===1?n:null,positions:null,refereeArrived:!1,arrivedAt:null,announced:!1}}endCeremony(){for(let e of this.graphs??[])e.awaitVerdict(null);this.referee?.raise(null,null)}ceremonyFighters(e,t,n,r,i=null){e.positions===null&&(e.positions=[{x:t[0].x+(i?.[0].x??0),y:t[0].y+(i?.[0].y??0)},{x:t[1].x+(i?.[1].x??0),y:t[1].y+(i?.[1].y??0)}],e.marks=e.positions[0].x<=e.positions[1].x?[0,1]:[1,0]);let a=e.marks??FG,o=e.refereeArrived;for(let r of[0,1]){let i=e.positions[r],s=a[r],c=UG(i.x,i.y,PG[s],zG*n),l=Math.hypot(c.x-i.x,c.y-i.y),u=n>0?1/(n*this.simulation.tick_rate):0,d=!c.arrived&&l>1e-6;Object.assign(this.drawnFighters[r],t[r],{x:c.x,y:c.y,velocity_x:(c.x-i.x)*u,velocity_y:(c.y-i.y)*u,facing_x:d?Math.round((c.x-i.x)/l*1e3):0,facing_y:d?Math.round((c.y-i.y)/l*1e3):-1e3,facing:d&&c.x=VG){e.announced=!0,this.commentary.verdict(this.frameSeconds);for(let t of[0,1])this.graphs?.[t]?.announce(e.winnerSeat===null?`level`:e.winnerSeat===t?`winner`:`loser`);this.finalRevealAt=Math.min(this.finalRevealAt,this.frameSeconds+.35),this.arena.excite(1)}if(e.announced){let n=n=>{let r=a[0]===n?0:1,i=e.winnerSeat===null||e.winnerSeat===r,o=Ae(t[r].injuries,n===0?`left`:`right`)===`whole`,s=this.graphs?.[r]?.boxer.rig.bones[n===0?`gloveL`:`gloveR`];return i&&o&&s!==void 0?s.getWorldPosition(this.ceremonyWrists[n]):null};this.referee?.isDown!==!0&&this.referee?.raise(n(1),n(0))}return this.drawnFighters}ceremonyFrame(e){let t=this.ceremony,n=this.buffer.latest();if(t===null||t.arrivedAt===null||this.replay!==null||this.final===null||n===null)return null;let{width:r,height:i}=this.hudViewport,a=zK(this.final,r,i,n.fighters,this.players,this.roundStats,this.viewerId),o=CD(this.camera.aspect,this.camera.fov,(i-a)/Math.max(1,i)),s=this.settings().reducedMotion?0:Math.sin((e-t.arrivedAt)*.35)*.06*o.distance;return this.cornerPosition.set(s,o.height+.05*o.distance,o.distance),this.cornerLookAt.set(0,o.height,0),{position:this.cornerPosition,lookAt:this.cornerLookAt,framed:!0}}raiseFrame(e,t,n){let r=this.buffer.latest();if(this.stoppageWinner<0||this.final===null||this.replay!==null||this.ceremony!==null||r===null||e0?-1:1)*dG,o=this.stoppageSpot?.z??0;this.raiseFramed||this.raiseCentre.set(i.x+a/2,0,i.z+o/2),this.raiseCentre.lerp(this.tmpCamera.set(i.x+a/2,0,i.z+o/2),1-Math.exp(-3*t)),this.raiseFramed=!0;let{width:s,height:c}=this.hudViewport,l=zK(this.final,s,c,r.fighters,this.players,this.roundStats,this.viewerId,this.deaths[0]??this.deaths[1]),u=CD(this.camera.aspect,this.baseFov,(c-l)/Math.max(1,c)),d=e-(this.stoppageRaiseAt-uG),f=n?0:Math.sin(d*.35)*.06*u.distance;return this.cornerPosition.set(G.clamp(this.raiseCentre.x,-1.4,1.4)+f,u.height+.05*u.distance,this.raiseCentre.z+u.distance),this.cornerLookAt.set(this.raiseCentre.x,u.height,this.raiseCentre.z),{position:this.cornerPosition,lookAt:this.cornerLookAt,framed:!0}}presentFinish(e){let t=this.buffer.latest()?.referee.alive===!1;t||this.referee?.waveOff();let n=this.buffer.latest()?.fighters,r=n?.findIndex(t=>t.player_id!==e.winner_id&&t.player_id!==null)??-1;if(r>=0&&this.headCacheValid[r]&&!this.settings().reducedMotion&&!this.carnage.gibbed(r)&&(this.finishCloseUpIndex=r,this.finishCloseUpUntil=this.frameSeconds+rG,this.finishCloseUpBearing=null,this.finishCloseUpAt=this.frameSeconds),e.winner_id===null)return;let i=n?.findIndex(t=>t.player_id===e.winner_id)??-1;if(i<0)return;this.graphs?.[i]?.celebrate(lG);let a=n?.[i]?.injuries??[];!t&&(cK(a,`left`)||cK(a,`right`))&&(this.stoppageWinner=i,this.stoppageRaiseAt=this.frameSeconds+uG)}cornerShotFrame(e,t,n){if(t===null||t.phase!==`rest`||n||this.graphs===null)return null;let r=t.fighters.findIndex(e=>e.player_id===this.viewerId),i=e-this.restStartedAt,a=hD(i,t.phase_ticks_remaining/this.simulation.tick_rate,+(r===1));return a===null||!this.graphs[a].stoolVisible||this.cutmen!==null&&this.cutmanProgress[a]e.player_id===this.viewerId)===1),n=this.mapping.x(l);return bD(t,n,-3.5,oG,this.cornerPosition).setY(sG),bD(t,n,0,0,this.cornerLookAt),this.cornerLookAt.lerp(bD(+(t===0),n,0,0,this.tmpCamera),cG).setY(.9),{position:this.cornerPosition,lookAt:this.cornerLookAt,framed:!0}}closeUpFrame(e){if(e>=this.finishCloseUpUntil||this.finishCloseUpIndex<0||!this.headCacheValid[this.finishCloseUpIndex])return null;let t=this.arcadeInjuries[this.finishCloseUpIndex],n=t===`decapitation`&&this.effects.severedHeadPosition(this.finishCloseUpIndex,this.closeUpTarget),r=!n&&this.effects.partPosition(Xz(this.finishCloseUpIndex,`upper_body`),this.closeUpTarget),i=n||r?null:this.graphs?.[this.finishCloseUpIndex]?.fallBody??null;if(this.finishCloseUpBearing===null&&i!==null&&!i.body.asleep&&e-this.finishCloseUpAt.4?u:.9,a)}let d=this.finishCloseUpBearing+l;return this.closeUpPosition.set(G.clamp(s.x+Math.sin(d)*c,-2.2,vG),s.y+(n?.42:o?.5:.75),G.clamp(s.z+Math.cos(d)*c,-2.2,vG)),this.replayLookAt.copy(s),{position:this.closeUpPosition,lookAt:this.replayLookAt,tight:!0}}raiseSpot(e,t){let n=e.x>0?-1:1,r={x:n*dG,z:0},i=-1/0;for(let[a,o]of fG){let s=e.x+n*a*dG,c=e.z+o*dG,l=Math.min(hG-Math.abs(s),hG-Math.abs(c),Math.hypot(s-t.x,c-t.z)-mG);for(let e of this.graphs??[]){let t=e.fallBody;if(t!==null)for(let e of[0,1,2,3,4])t.bodyPoint(e,this.bodyPoint),l=Math.min(l,Math.hypot(s-this.bodyPoint.x,c-this.bodyPoint.z)-SG-.05)}for(let e of[0,1])this.effects.severedHeadPosition(e,this.closeUpTarget)&&(l=Math.min(l,Math.hypot(s-this.closeUpTarget.x,c-this.closeUpTarget.z)-yG-.05));if(l>=0)return{x:s-e.x,z:c-e.z};l>i&&(i=l,r={x:s-e.x,z:c-e.z})}return r}nearerGlove(e,t){e.getWorldPosition(this.stoppageWrist),t.getWorldPosition(this.stoppageOtherWrist);let n=e=>Math.hypot(e.x-this.refereePosition.x,e.z-this.refereePosition.z);return n(this.stoppageOtherWrist)-.5*n.length()}startReplay(e){let t=new Ef(e.snapshots.length+2,this.simulation.tick_rate);for(let n of e.snapshots)t.push(n);if(this.replay={plan:e,buffer:t,startedAt:this.frameSeconds,impactFired:!1,side:null},this.drawnOffsetsLive=!1,this.commentary.replay(this.frameSeconds,e.impact),this.replayFollow=0,this.replayFollowAt=0,e.impact.kind===`referee_down`){this.referee?.resetTransient(!1),this.referee?.primeReplayFall(),this.effects.stopGush(2);return}for(let e=this.pendingGore.length-1;e>=0;--e)this.pendingGore[e].event.kind!==`injury`&&this.pendingGore.splice(e,1);for(let e of[0,1]){this.effects.stopGush(e),this.deaths[e]!==null&&this.carnage.undoDeath(e);let t=this.arcadeInjuries[e],n=this.arcadeInjuryEvents[e];t!==null&&n!==null&&(this.replayInjuries[e]={injury:t,event:n},this.restoreInjury(e))}for(let t of this.pendingContacts.splice(0)){let n=t.recipientIndex;t.injury!==null&&(n===0||n===1)&&this.replayInjuries[n]===null&&this.arcadeInjuries[n]===null&&(this.replayInjuries[n]={injury:t.injury,event:t.event}),t.event.event_id!==e.impact.event_id&&(t.injury=null,t.contactTick=1/0,this.pendingContacts.push(t))}let n=e.snapshots[0]?.fighters.findIndex(t=>t.player_id===e.impact.target_id)??-1;n>=0&&e.impact.detail.endsWith(`:head`)&&this.effects.returnMouthpiece(n);let r=this.lastKnockdown?.knockdown.detail===bG;for(let[t,i]of(this.graphs??[]).entries()){let a=this.liveFallTicks[t]??null;i.resetTransient(!1),a!==null&&a>=e.impact.tick-1&&i.primeReplayFall(),t===n&&r&&i.fallToKnee(!0)}this.finalRevealAt=this.frameSeconds+e.durationSeconds+mr(this.final)}endReplay(){let e=this.replay?.plan.impact.kind===`referee_down`;if(this.replay=null,e){this.drawnOffsetsLive=!1;let e=this.buffer.latest();for(let[t,n]of(this.graphs??[]).entries())n.resetTransient(e?.fighters[t]?.is_downed===!0);return}this.drawnOffsetsLive=!1,this.reapplyReplayInjuries();let t=this.buffer.latest();for(let[e,n]of(this.graphs??[]).entries()){let r=t?.fighters[e],i=r!==void 0&&r.player_id===this.flashKnockout?.loserId;n.resetTransient(r?.is_downed===!0||i),i&&n.knockOut()}for(let e of[0,1])this.showDeath(e,0,!0);this.final!==null&&this.presentFinish(this.final)}fireRefereeEvents(e){for(let t=0;te){t+=1;continue}this.pendingRefereeEvents.splice(t,1);let r=this.buffer.latest();n.kind===`referee_down`?(r!==null&&this.fireRefereeFall(n,r),this.eventCallout={text:`THE REFEREE IS DEAD!`,until:this.frameSeconds+QG},this.refereeReplayAt={at:this.frameSeconds+ZG,impact:n}):n.kind===`referee_hit`?r!==null&&this.punchReferee(n,r,!1):this.referee!==null&&(this.referee.boxer.rig.bones.head.getWorldPosition(this.refereeHead),this.effects.addEvent(n,this.refereeHead,this.settings().reducedMotion))}}punchReferee(e,t,n){let r=this.referee;if(r===null)return;let[i,a]=e.detail.split(`:`),o=t.fighters.findIndex(t=>t.player_id===e.actor_id),s=t.fighters[o],c=s?.action_key?.split(`:`)[1]??null;r.react(`hit`,a===`body`?`body`:`head`,e.direction,i,c,n?Math.max(e.amount,140):e.amount),r.boxer.rig.bones.head.getWorldPosition(this.refereeHead);let l=s===void 0?void 0:ZW(s,{...s,x:t.referee.x,y:t.referee.y},this.mapping),u=this.settings().reducedMotion;this.effects.addEvent({...e,kind:n?`knockdown`:`hit`},this.refereeHead,u,l);let d=n||u?null:aq({...e,kind:`hit`}),f=d===null?null:this.refereeMouth();d!==null&&f!==null&&this.effects.gush(2,f.position,f.axis,d.seconds,d.rate,e.event_id);let p=this.refereePunchPower(e);o>=0&&this.graphs?.[o]?.landedHit(e.action_id,!1,p),this.onContact?.(e,p)}fireRefereeFall(e,t,n=!1){let r=this.referee;if(r===null)return;let i=n?this.refereeBlow(e):null;i===null?(r.boxer.rig.bones.head.getWorldPosition(this.refereeHead),this.effects.addEvent({...e,kind:`knockdown`,amount:160,blood:80},this.refereeHead,this.settings().reducedMotion)):this.punchReferee(i,t,!0);let a=this.settings().reducedMotion?null:this.refereeMouth();a!==null&&this.effects.gush(2,a.position,a.axis,_q,vq,e.event_id),r.knockOut(),this.onContact?.(e,!1)}refereePunchPower(e){for(let t=this.history.length-1;t>=0;--t){let n=this.history[t];if(n.tickt.player_id===e.actor_id);return r!==void 0&&r.action_id===e.action_id&&r.action_power===`power`}return!1}refereeBlow(e){if(e.action_id===null)return null;for(let t=this.history.length-1;t>=0;--t){let n=this.history[t],r=n.events.find(t=>t.kind===`referee_hit`&&t.action_id===e.action_id&&t.tick===e.tick);if(r!==void 0)return r;if(n.tick=0?e.fighters[a]:void 0,l=c?.action_key?.split(`:`)??[],u=l[0]??null,d=l[1]??null,f=l[3]===`power`;this.graphs?.[i]?.react(`hit`,r.detail.endsWith(`:body`)?`body`:`head`,r.direction,u,d,r.amount),n.knockdown.detail===`body`&&n.knockdown.tick>r.tick&&this.graphs?.[i]?.windedFor((n.knockdown.tick-r.tick)/this.simulation.tick_rate+.15,hK(c?.action_key??null)),o.player_id===this.flashKnockout?.loserId&&this.graphs?.[i]?.knockOut(),a>=0&&this.graphs?.[a]?.landedHit(r.action_id,n.blocked,f),r.detail.endsWith(`:head`)&&!this.settings().reducedMotion&&this.knockOutMouthpiece(i,s??r.direction,r.event_id+tq,!0),f&&!n.blocked&&!this.settings().reducedMotion&&this.presentPowerHit(i,r),this.onContact?.(r,f),this.reapplyReplayInjuries(s),this.deaths[i]!=null&&(this.showDeath(i,s??r.direction,!0),this.announceDeath(i));for(let e of this.pendingGore.splice(0))this.presentGore(e.event);for(let t of this.pendingContacts)t.contactTick===1/0&&(t.contactTick=this.replay?.plan.impact.tick??e.tick)}replayFrame(e,t){let[n,r]=e.fighters,i=this.mapping.x(n.x),a=this.mapping.z(n.y),o=this.mapping.x(r.x),s=this.mapping.z(r.y),c=this.replay?.plan.impact.kind===`referee_down`,l=e.fighters.findIndex(e=>e.player_id===this.replay?.plan.impact.target_id),u=this.replay?.impactFired===!0&&l>=0&&this.headCacheValid[l]===!0;if(c&&this.referee!==null)return this.refereeReplayFrame(e,t);let d=1-Math.exp(-3*Math.max(0,t-this.replayFollowAt));this.replayFollowAt=t,this.replayFollow+=(+!!u-this.replayFollow)*d;let f=l<0?0:Math.max(this.portraitPull>1.3?.7:0,this.replayFollow*.8),p=u?this.headCache[l].x:l===1?o:i,m=u?this.headCache[l].z:l===1?s:a,h=(i+o)/2+(p-(i+o)/2)*f,g=(a+s)/2+(m-(a+s)/2)*f,_=-(s-a),v=o-i,y=Math.hypot(_,v)||1;_/=y,v/=y;let b=2.5,x=this.replay;x!==null&&x.side===null&&(x.side=rq(h,g,_,v,b,vG));let S=x?.side??(v<0?-1:1);_*=S,v*=S;let C=.35*Math.sin(t*.7),w=_*Math.cos(C)-v*Math.sin(C),T=_*Math.sin(C)+v*Math.cos(C);this.replayCameraPosition.set(G.clamp(h+w*b,-2.2,vG),1.38-Math.min(.25,t*.05),G.clamp(g+T*b,-2.2,vG));let E=Math.hypot(this.replayCameraPosition.x-h,this.replayCameraPosition.z-g),D=Math.hypot(h,g);if(E.01){let e=nq-E;this.replayCameraPosition.x=G.clamp(this.replayCameraPosition.x-h/D*e,-2.2,vG),this.replayCameraPosition.z=G.clamp(this.replayCameraPosition.z-g/D*e,-2.2,vG)}let O=u?G.clamp(this.headCache[l].y,.45,1.28):1.28;this.replayLookAt.set(h,1.28+(O-1.28)*this.replayFollow,g);let k=this.settings().reducedMotion?0:this.powerShake;if(k>5e-4){let e=t*61;this.replayCameraPosition.x=G.clamp(this.replayCameraPosition.x+Math.sin(e*1.31)*k,-2.2,vG),this.replayCameraPosition.y+=Math.cos(e*1.97)*k*.6,this.replayLookAt.x+=Math.sin(e*1.53)*k*.5,this.replayLookAt.y+=Math.cos(e*2.11)*k*.35}return{position:this.replayCameraPosition,lookAt:this.replayLookAt,tight:!0}}setInputLatency(e){this.inputLatencyMs=e,this.lagWarned=gr(e,this.lagWarned)}resyncClock(){this.buffer.resync()}setReconnect(e){this.reconnectMs=e}setBloodLevel(e){e!==`full`&&this.bloodLevel===`full`&&this.restoreAllInjuries(),this.bloodLevel=e,e===`off`&&this.downedPoolAccumulators.fill(0),this.effects.setBloodLevel(e)}setReducedMotion(e){e&&(this.restoreAllInjuries(),this.effects.clearDynamic())}syncInjuryPresentation(e){let t=this.arcadeInjuries[e],n=this.graphs;if(n!==null){let r=n[e];t===`head_burst`?r.boxer.setHeadBurst(!0):r.boxer.setDecapitated(t===`decapitation`),r.boxer.headInjury.setEyeOut(t===`eye_left`||t===`eye_right`?`both`:null),r.boxer.setHandDismembered(`left`,t===`dismember_left`),r.boxer.setHandDismembered(`right`,t===`dismember_right`);let i=t===`jaw_dislocation`?`jaw`:t===`shoulder_left`||t===`shoulder_right`?t:null;r.setArcadeDislocation(i)}}applyArcadeInjury(e,t,n,r){t===`dismember_left`&&!this.carnage.hasGlove(e,`left`)?t=`ribs_left`:t===`dismember_right`&&!this.carnage.hasGlove(e,`right`)?t=`ribs_right`:(t===`eye_left`&&this.carnage.eyeBurst(e,`left`)||t===`eye_right`&&this.carnage.eyeBurst(e,`right`))&&(t=`jaw_dislocation`);let i=!1;if(t===`decapitation`){let t=this.headWorldPose(e);if(t!==null){let a=this.graphs?.[e],o=a===void 0?void 0:YK(a.boxer,t.position,t.quaternion);this.effects.decapitate(e,t.position,t.quaternion,r??n.direction,n.event_id,this.skinColor(e),o);let s=this.stumpWorldPose(e);s!==null&&this.effects.anchorStump(e,s.position,s.quaternion,s.rim,s.across),i=!0}}else if(t===`head_burst`){let t=this.headWorldPose(e);if(t!==null){this.effects.burstHead(e,t.position,r??n.direction,n.event_id);let a=this.burstStumpPose(e);a!==null&&this.effects.anchorStump(e,a.position,a.quaternion,a.rim,a.across),i=!0}}else if(t===`eye_left`||t===`eye_right`){let a=this.graphs?.[e]?.boxer,o=t===`eye_left`?`left`:`right`;if(a!==void 0&&Pq(a,o,this.tmpPart,this.tmpStumpOffset,this.tmpPartQuaternion)){let t=r??n.direction;this.effects.gougeEye(e,this.tmpPart,this.tmpStumpOffset,t,n.event_id,o);let s=o===`left`?`right`:`left`;!this.effects.eyeOut(e,s)&&!this.carnage.eyeBurst(e,s)&&Pq(a,s,this.tmpPart,this.tmpStumpOffset,this.tmpPartQuaternion)&&this.effects.spawnDebris(`eye`,this.tmpPart,t,1,n.event_id,bq,e),i=!0}}else if(t===`dismember_left`||t===`dismember_right`){let a=t===`dismember_left`?`left`:`right`,o=this.handWorldPose(e,a);if(o!==null){let t=this.graphs?.[e],s=t===void 0?void 0:{...JK(t.boxer.gloveMesh(a),o.position,o.quaternion),gloveBlood:t.boxer.gloveBloodLevel};this.effects.dismemberHand(e,a,o.position,o.quaternion,r??n.direction,n.event_id,this.gearColor(e),s),this.effects.anchorHandStump(e,a,o.position,o.quaternion),i=!0}}else if(t===`jaw_dislocation`||t===`shoulder_left`||t===`shoulder_right`||t===`ribs_left`||t===`ribs_right`){let a=this.tornWound(e,Cq(t));a!==null&&(this.effects.tearOpen(e,a.position,a.axis,r??n.direction,n.event_id,t===`jaw_dislocation`?yq:0),i=!0)}return i?(this.arcadeInjuries[e]=t,this.arcadeInjuryEvents[e]=n,this.observedInjuryDown[e]=!1,this.syncInjuryPresentation(e),this.onArcadeInjury?.(t,n),!0):!1}reapplyReplayInjuries(e){for(let t of[0,1]){let n=this.replayInjuries[t];if(n===null)continue;this.replayInjuries[t]=null;let r=this.settings();r.blood!==`full`||r.reducedMotion||this.applyArcadeInjury(t,n.injury,{...n.event,event_id:n.event.event_id+tq},e)}}restoreInjury(e){this.arcadeInjuries[e]!==null&&(this.arcadeInjuries[e]=null,this.arcadeInjuryEvents[e]=null,this.observedInjuryDown[e]=!1,this.syncInjuryPresentation(e),this.effects.restoreFighter(e))}restoreAllInjuries(){this.restoreInjury(0),this.restoreInjury(1),this.effects.clearArcadeGore()}headWorldPose(e){let t=this.graphs,n=t===null?null:t[e].boxer.bone(`head`);return n===null||t===null?null:(t[e].boxer.root.updateMatrixWorld(!0),n.getWorldPosition(this.tmpHead),n.getWorldQuaternion(this.tmpHeadQuaternion),this.tmpStumpOffset.copy(wK).applyQuaternion(this.tmpHeadQuaternion),this.tmpHead.add(this.tmpStumpOffset),{position:this.tmpHead,quaternion:this.tmpHeadQuaternion})}handWorldPose(e,t){let n=this.graphs,r=n===null?null:n[e].boxer.bone(t===`left`?`gloveL`:`gloveR`);return r===null||n===null?null:(n[e].boxer.root.updateMatrixWorld(!0),r.getWorldPosition(this.tmpPart),r.getWorldQuaternion(this.tmpPartQuaternion),{position:this.tmpPart,quaternion:this.tmpPartQuaternion})}gearColor(e){return this.graphs?.[e]?.boxer.gearBaseColor.getHex()??1920728}skinColor(e){return this.graphs?.[e]?.boxer.skinBaseColor.getHex()??11563071}stumpWorldPose(e){let t=this.graphs?.[e]?.boxer,n=t?.bone(`head`);if(t===void 0||n==null)return null;t.root.updateMatrixWorld(!0);let r=t.headMesh,i=DK(r.geometry);if(i.length===0)return null;this.stumpRim.length!==i.length*3&&(this.stumpRim=new Float32Array(i.length*3)),this.tmpStump.set(0,0,0);for(let[e,n]of i.entries())BK(t,n,this.tmpStumpOffset),this.tmpStumpOffset.toArray(this.stumpRim,e*3),this.tmpStump.add(this.tmpStumpOffset);return this.tmpStump.multiplyScalar(1/i.length),n.getWorldPosition(this.tmpStumpOffset).sub(this.tmpStump).normalize(),this.tmpStumpAcross.set(1,0,0).applyQuaternion(n.getWorldQuaternion(this.tmpStumpQuaternion)),this.tmpStumpQuaternion.setFromUnitVectors(TK,this.tmpStumpOffset),{position:this.tmpStump,quaternion:this.tmpStumpQuaternion,rim:this.stumpRim,across:this.tmpStumpAcross}}burstStumpPose(e){let t=this.graphs?.[e]?.boxer;if(t===void 0)return null;let n=jK(t,this.stumpRim,this.burstStump);return n===null?null:(this.stumpRim=n,{position:this.burstStump.position,quaternion:this.burstStump.quaternion,rim:n,across:this.burstStump.across})}predictAction(e){let t=this.buffer.latest();if(t===null||this.viewerId===null||this.replay!==null)return;let n=t.fighters.findIndex(e=>e.player_id===this.viewerId);if(n<0)return;let r=t.fighters[n];if(t.phase!==`fight`&&t.phase!==`finish`||!sq(r))return;let i=(this.inputLatencyMs??60)/1e3*this.simulation.tick_rate,a=i+this.buffer.interpolationDelayTicks,o=this.manualClock?this.lastManualTime:performance.now(),s=this.graphs?.[n];if(mE(e.kind)){let n=s?.ownPunchActive===!0;if(e.id===void 0||r.stamina0||!n&&ZT(r,t.tick)>0)return;let i=n?s.ownTicksToRecovery:0;n&&s.cutOwnRecovery(),this.evasion.press(e.kind,e.id,o,a,this.simulation.tick_rate,y+P(r.style).evasionTicks,o+i*1e3/this.simulation.tick_rate);return}if(e.kind!==`punch`)return;this.evasion.drop(o)&&s?.keepOwnRecovery();let c=Me(r.injuries,e.hand);c!==null&&s?.predict(c===e.hand?e:{...e,hand:c},performance.now()/1e3,this.simulation.tick_rate,a,XT(r,e,t.tick+1),i)}acknowledgeActions(e,t){for(let[n,r]of e.fighters.entries()){let i=r.player_id===this.viewerId,a=e.phase===`fight`||e.phase===`finish`;i&&this.evasion.acknowledge(r,a,this.inputSequenceOf)&&this.graphs?.[n]?.keepOwnRecovery();let o=t.filter(t=>XW(t,e).puncherIndex===n);this.graphs?.[n]?.acknowledge(r,a,o,i?this.inputSequenceOf:null)}}push(e){if(!this.buffer.push(e,this.manualClock?this.lastManualTime:performance.now()))return;let t=this.dedupe.accept(e.events);this.acknowledgeActions(e,t),this.history.push(e),this.history.length>eG&&this.history.shift();for(let n of t){if(this.roundStats.record(n,t),n.kind===`knockdown`){let r=t.find(e=>QW(e)&&e.target_id===n.target_id&&e.tick===n.tick)??(n.detail===`body`?this.recordedHit(n):null),i=r!==null&&cr(r,e.events);this.lastKnockdown={knockdown:n,hit:r,blocked:i,finisher:i?null:cq(r,e)};let a=e.fighters.findIndex(e=>e.player_id===n.target_id);this.graphs?.[a]?.fallToKnee(n.detail===bG),n.detail===xG&&(this.lastKnockdown=null)}if(n.kind===`result`&&n.detail===`flash_ko`){let e=t.findLast(e=>(e.kind===`hit`||e.kind===`counter_hit`)&&e.actor_id===n.actor_id)??null;e!==null&&e.target_id!==null&&(this.flashKnockout={hitEventId:e.event_id,loserId:e.target_id},this.lastKnockdown={knockdown:{...e,kind:`knockdown`},hit:e,blocked:!1,finisher:null})}n.kind===`referee_break`&&this.referee?.breakClinch(),(eK.has(n.kind)||n.kind===`bleed`&&n.actor_id===`referee`)&&this.pendingRefereeEvents.push(n),n.kind===`box`&&(this.eventCallout={text:`BOX!`,until:this.frameSeconds+XG}),n.kind===`body_collapse`&&n.target_id===this.viewerId&&(this.ownCollapseUntil=n.tick+n.amount),n.kind===`finish_him`&&(this.finishTargetId=n.target_id),(n.kind===`fatality`||n.kind===`death`)&&this.noteDeath(n,t,e),this.movement.observe(n,this.viewerId)}this.commentary.observe(e,t,this.players,this.simulation.tick_rate,this.frameSeconds);let n=e.fighters.findIndex(e=>e.player_id===this.viewerId),r=e.result===null&&!t.some(e=>e.kind===`knockdown`);for(let{event:i,presentationEvent:a,presentImpact:o,reactAmount:s}of pK(t,e)){let t=e.fighters.findIndex(e=>e.player_id===i.target_id),c=e.fighters.findIndex(e=>e.player_id===i.actor_id),{recipientIndex:l,puncherIndex:u}=XW(i,e),d=e.fighters[l]??e.fighters[t]??e.fighters[c]??e.fighters[0];if(MK(this.graphs?.[e.fighters.indexOf(d)],d,this.mapping,this.contactPoint),qG.has(i.kind)){let t=u>=0?e.fighters[u]:null;this.pendingContacts.push({event:i,presentationEvent:a,presentImpact:o,reactAmount:s,contactTick:r&&u===n&&YG.has(i.kind)&&this.graphs?.[u]?.pressLanded(i.action_id)===!0?-1/0:t?.action_contact_tick??i.tick,recipientIndex:l,puncherIndex:u,injury:SK(i,e.fighters[l],e.result,t??void 0),power:t!==null&&t.action_id===i.action_id&&t.action_power===`power`})}else i.kind===`bleed`&&i.actor_id!==`referee`&&this.effects.addEvent(i,this.contactPoint,this.settings().reducedMotion)}for(let n of t){if(!iK.has(n.kind))continue;let t=n.action_id===null?void 0:this.pendingContacts.find(e=>e.event.tick===n.tick&&e.event.action_id===n.action_id&&(QW(e.event)||$W(e.event)));t!==void 0&&(t.injury??=lK(n)),n.kind!==`fatality`&&(this.pendingGore.push({event:n,at:t?.contactTick??n.tick}),n.kind===`injury`&&pe(n.detail)&&this.carnage.expect(e.fighters.findIndex(e=>e.player_id===n.target_id),n.detail))}}fireContacts(e){for(let t=0;te){t+=1;continue}this.pendingContacts.splice(t,1);let{event:r,presentationEvent:i,reactAmount:a,recipientIndex:o,puncherIndex:s,injury:c}=n,l=n.presentImpact&&!uK(i),u=this.buffer.latest()?.fighters[o],d=ZW(this.buffer.latest()?.fighters[s],u,this.mapping);this.presentFightEvent(r,o,s),l&&u!==void 0&&(this.contactOn(o,u,i.detail.endsWith(`:body`),d,i.direction),this.effects.addEvent(i,this.contactPoint,this.settings().reducedMotion,d));let f=this.settings();if(n.power&&l&&QW(r)&&u!==void 0&&!f.reducedMotion&&this.presentPowerHit(o,i),(n.presentImpact||JG.has(r.kind))&&this.arena.excite(KG[r.kind]??0),l&&o>=0&&[`hit`,`counter_hit`,`knockdown`].includes(r.kind)){let e=this.viewerId!==null&&this.buffer.latest()?.fighters[o]?.player_id===this.viewerId;this.viewerHitFlash=Math.max(this.viewerHitFlash,iq(r,e,f.blood))}c!==null&&o>=0&&this.arcadeInjuries[o]===null&&f.blood===`full`&&!f.reducedMotion&&this.applyArcadeInjury(o,c,r,d);let p=this.graphs;l&&o>=0&&!f.reducedMotion&&dB(r.kind,r.amount,i.detail.endsWith(`:head`))&&this.knockOutMouthpiece(o,d??i.direction,r.event_id,!1);let m=l&&!f.reducedMotion?aq(r):null;m!==null&&o>=0&&this.gushFromMouth(o,r.event_id,m.seconds,m.rate),n.presentImpact&&o>=0&&r.kind===`knockdown`&&!f.reducedMotion&&this.gushFromMouth(o,r.event_id,_q,vq);let h=l&&o>=0?_O(r.kind,r.amount,i.detail.endsWith(`:head`)):0;if(h>0&&!f.reducedMotion&&f.blood!==`off`){let e=this.headWorldPose(o);e!==null&&(this.mouthPoint.set(0,-.07,.1).applyQuaternion(e.quaternion).add(e.position),this.effects.spawnTeeth(this.mouthPoint,d??i.direction,h,r.event_id))}if(l&&o>=0&&a!==null&&[`hit`,`counter_hit`,`block`,`perfect_block`,`knockdown`].includes(r.kind)){let e=r.kind===`block`||r.kind===`perfect_block`,t=i.detail.endsWith(`:body`)?`body`:`head`;if(p!==null){let n=(s>=0?this.buffer.latest()?.fighters[s]:void 0)?.action_key?.split(`:`)??[],c=n[0]??i.detail.split(`:`)[0]??null,l=n[1]??null;p[o].react(e?`block`:`hit`,t,i.direction,c,l,a),QW(r)&&t===`head`&&l!==null&&this.carnage.punched(o,l===`left`?`right`:`left`,r.event_id),this.flashKnockout?.hitEventId===r.event_id&&p[o].knockOut()}}l&&s>=0&&[`hit`,`counter_hit`,`block`,`perfect_block`,`guard_break`].includes(r.kind)&&p?.[s]?.landedHit(r.action_id,r.kind===`block`||r.kind===`perfect_block`,n.power),(n.presentImpact||!QW(r))&&this.onContact?.(r,n.power===!0)}this.replay===null&&this.fireRefereeEvents(e);let t=this.refereeReplayAt;if(t!==null&&this.replay===null&&this.frameSeconds>=t.at){this.refereeReplayAt=null;let e=SW(this.history,t.impact,this.simulation.tick_rate,xW.speed,xW.before,xW.after),n=this.buffer.latest(),r=e!==null&&n!==null&&n.phase===`referee_down`&&n.phase_ticks_remaining/this.simulation.tick_rate>=e.durationSeconds-.5;e!==null&&r&&!this.settings().reducedMotion&&this.startReplay(e)}}fireGore(e){for(let t=0;te?t+=1:(this.pendingGore.splice(t,1),this.presentGore(n.event))}}presentGore(e){let t=this.buffer.latest()?.fighters,n=t?.findIndex(t=>t.player_id===(e.kind===`vomit`?e.actor_id:e.target_id))??-1;if(t===void 0||n<0)return;let r=ZW(e.actor_id===e.target_id?void 0:t.find(t=>t.player_id===e.actor_id),t[n],this.mapping)??e.direction;if(e.kind===`vomit`)this.carnage.vomit(n,e.event_id),this.onGore?.({kind:`vomit`});else if(e.kind===`finish_him`)this.arena.excite(1),this.onGore?.({kind:`finish_him`});else if(e.kind===`death`)this.showDeath(n,r,!1),this.announceDeath(n);else if(e.kind===`injury`&&pe(e.detail)){let i=e.detail;if(!this.carnage.inflict(n,i,e.event_id,r))return;this.eventCallout={text:`${we(i)}!`,until:this.frameSeconds+aK},this.arena.excite(sK);let a=this.viewerId!==null&&t[n].player_id===this.viewerId;this.settings().blood!==`off`&&(this.viewerHitFlash=Math.max(this.viewerHitFlash,a?1:.5)),this.settings().reducedMotion||(this.powerShake=Math.min(nK,this.powerShake+tK)),this.onGore?.({kind:`injury`,injury:i})}}showDeath(e,t,n){let r=this.deaths[e]??null;if(r===null)return;let i=this.fatal?.index===e?this.fatal:null,a=(i?.hit.event_id??e)+(n?tq:0);i===null?r===`gutted`&&this.carnage.fatality(e,`gutting`,a,t):this.carnage.fatality(e,i.fatality,a,t),this.carnage.die(e,r)}announceDeath(e){let t=this.deaths[e]??null;if(t===null)return;let n=Oe(t);this.eventCallout={text:`${ke(t)}!`,until:this.frameSeconds+oK},this.arena.excite(1),this.settings().reducedMotion||(this.powerShake=nK),n!==null&&this.onGore?.({kind:`fatality`,fatality:n}),this.onGore?.({kind:`death`,cause:t})}noteDeath(e,t,n){let r=n.fighters.findIndex(t=>t.player_id===e.target_id);if(r!==0&&r!==1)return;let i=e.action_id===null?null:t.find(t=>QW(t)&&t.tick===e.tick&&t.action_id===e.action_id&&t.target_id===e.target_id)??null;if(e.kind===`fatality`){i!==null&&me.includes(e.detail)&&(this.fatal={index:r,fatality:e.detail,hit:i});return}let a=De(e.detail);a!==null&&(this.deaths[r]=a,i===null?this.lastKnockdown=null:(this.flashKnockout={hitEventId:i.event_id,loserId:n.fighters[r].player_id},this.lastKnockdown={knockdown:{...i,kind:`knockdown`},hit:i,blocked:!1,finisher:null}))}presentFightEvent(e,t,n){let r=rK[e.kind];r!==void 0&&(this.eventCallout={text:r.text,until:this.frameSeconds+r.seconds});let i=this.graphs;if(!(i===null||t<0)&&(e.kind===`parry`&&i[t]?.stagger(),e.kind===`body_collapse`)){let r=n>=0?this.buffer.latest()?.fighters[n]:void 0;i[t]?.windedFor(e.amount/this.simulation.tick_rate+.15,hK(r?.action_key??null))}}recordedHit(e){if(e.action_id===null)return null;for(let t=this.history.length-1;t>=0;--t){let n=this.history[t].events.find(t=>(t.kind===`hit`||t.kind===`counter_hit`)&&t.action_id===e.action_id&&t.target_id===e.target_id);if(n!==void 0)return n}return null}enterRest(e){this.restStartedAt=e,this.effects.clearMouthpieces()}contactOn(e,t,n,r,i){let a=n?null:this.headWorldPose(e),o=n?this.graphs?.[e]?.boxer.rig.bones.upperChest:void 0,s=a?.position??o?.getWorldPosition(this.contactPoint)??null;if(s===null)return MK(this.graphs?.[e],t,this.mapping,this.contactPoint);let c=r??{x:i<0?-1:1,z:0},l=n?Sq:xq;return this.contactPoint.set(s.x-c.x*l,s.y,s.z-c.z*l)}gushFromMouth(e,t,n,r){let i=this.tornWound(e,`mouth`);i!==null&&this.effects.gush(e,i.position,i.axis,n,r,t)}anchorGush(e){if(!this.effects.gushing(e)||this.carnage.vomiting(e))return;let t=this.tornWound(e,Cq(this.arcadeInjuries[e]??null));t!==null&&this.effects.anchorGush(e,t.position,t.axis)}tornWound(e,t){if(t===`mouth`){let t=this.headWorldPose(e);return t===null?null:{position:this.woundPoint.copy(hq).applyQuaternion(t.quaternion).add(t.position),axis:this.woundAxis.copy(gq).applyQuaternion(t.quaternion)}}let n=this.graphs?.[e]?.boxer;if(n===void 0)return null;n.root.updateMatrixWorld(!0);let r=n.rig.bones,i=t===`shoulder_left`||t===`ribs_left`,a=r.shoulderL.getWorldPosition(this.woundAxis).sub(r.shoulderR.getWorldPosition(this.tmpStumpOffset)).normalize().multiplyScalar(i?1:-1),o=r.upperChest.getWorldPosition(this.tmpStump),s=this.tmpStumpOffset.copy(o).sub(r.hips.getWorldPosition(this.tmpStumpAcross)).normalize();return t===`ribs_left`||t===`ribs_right`?{position:this.woundPoint.copy(o).addScaledVector(a,Oq).addScaledVector(s,-.06),axis:a}:((i?r.shoulderL:r.shoulderR).getWorldPosition(this.woundPoint),{position:this.woundPoint,axis:a.addScaledVector(s,.5).normalize()})}refereeMouth(){let e=this.referee?.boxer.rig.bones.head;return e===void 0?null:(e.getWorldPosition(this.tmpHead),e.getWorldQuaternion(this.tmpHeadQuaternion),this.tmpHead.add(this.tmpStumpOffset.copy(wK).applyQuaternion(this.tmpHeadQuaternion)),{position:this.woundPoint.copy(hq).applyQuaternion(this.tmpHeadQuaternion).add(this.tmpHead),axis:this.woundAxis.copy(gq).applyQuaternion(this.tmpHeadQuaternion)})}knockOutMouthpiece(e,t,n,r){let i=this.headWorldPose(e);i!==null&&(this.mouthPoint.set(0,-.075,.1).applyQuaternion(i.quaternion).add(i.position),this.effects.ejectMouthpiece(e,this.mouthPoint,i.quaternion,t,n,this.gearColor(e),r))}get resultVisible(){return this.final!==null&&this.frameSeconds>=this.finalRevealAt}get resolutionScale(){return this.scaler.scale}get diagnostics(){let e=this.renderer.getContext(),t=e.getExtension(`WEBGL_debug_renderer_info`),n=t===null?e.getParameter(e.RENDERER):e.getParameter(t.UNMASKED_RENDERER_WEBGL);return{frameMs:this.frameMsAverage,resolutionScale:this.scaler.scale,gpu:this.memoryInfo,graphics:String(n)}}get memoryInfo(){return{geometries:this.renderer.info.memory.geometries,textures:this.renderer.info.memory.textures,programs:this.renderer.info.programs?.length??0}}applyResolutionScale(){let e=this.basePixelRatio*this.scaler.scale;this.renderer.setPixelRatio(e),this.composer.setPixelRatio(e);let t=this.scaler.scale<=tG;this.bloomPass.enabled=!t,this.keyLight!==null&&YW(this.keyLight.shadow,t,this.scaler.scale<.8?1024:2048),this.arena.setLowTier(t),this.effects.setLowTier(t)}setupLights(){let e=new gx(`#3c4a72`,`#07080c`,.55);this.scene.add(e),this.lights.push(e);let t=new Ax(`#fff1dc`,150,24,.56,.55,1.7);t.position.set(.6,7.4,1.2),t.target.position.set(0,.6,0),t.castShadow=!0,t.shadow.mapSize.set(2048,2048),t.shadow.bias=qW,t.shadow.camera.near=3,t.shadow.camera.far=14,this.keyLight=t,this.scene.add(t,t.target),this.lights.push(t);let n=new Ax(`#ffe6c8`,95,24,.6,.6,1.7);n.position.set(-2.6,7,-2.2),n.target.position.set(0,.8,0),this.scene.add(n,n.target),this.lights.push(n);for(let[e,t,n,r]of[[`#8fa8ff`,-5.5,3.8,-5.4],[`#7f95e8`,5.6,3.6,-5.6]]){let i=new Ax(e,34,30,.72,.9,1.8);i.position.set(t,n,r),i.target.position.set(0,1.2,0),this.scene.add(i,i.target),this.lights.push(i)}let r=new Ax(`#ffe8d0`,48,22,.32,.8,1.5);r.position.set(0,5.8,5.4),r.target.position.set(0,1,0),this.scene.add(r,r.target),this.lights.push(r),this.followSpot=r}draw(e,t=!1,n=!0){if(this.destroyed)return;let r=e-this.previous,i=t?1/60:Math.min(.05,Math.max(.001,r/1e3));this.previous=e,!t&&this.scaler.record(r)&&this.applyResolutionScale(),!t&&r>0&&r<1e3&&(this.frameMsAverage+=(r-this.frameMsAverage)*.05);let a=Math.min(this.pixelRatioCap,window.devicePixelRatio||1);a!==this.basePixelRatio&&(this.basePixelRatio=a,this.applyResolutionScale());let o=this.canvas.clientWidth,s=this.canvas.clientHeight;o>0&&s>0&&(this.renderer.getSize(this.sizeCheck),(this.sizeCheck.x!==o||this.sizeCheck.y!==s)&&(this.renderer.setSize(o,s,!1),this.composer.setSize(o,s),this.camera.aspect=o/s,this.portraitPull=G.clamp(1.2/this.camera.aspect,1,2.2),this.baseFov=36*Math.min(1.3,Math.sqrt(this.portraitPull)),this.camera.fov=this.baseFov,this.camera.updateProjectionMatrix()));let c=e/1e3;this.frameSeconds=c,this.finishPass.uniforms.uTime.value=c%1e3,t&&(this.lastManualTime=e);let l=this.settings();this.setBloodLevel(l.blood);let u=this.buffer.latest(),d=i,f=u?.result!==null&&u?.result!==void 0&&dr.has(u.result.finish_method);if(this.cheer(c,i),f&&!this.finishSeen&&(this.finishSeen=!0,this.finishSlowMotion=2.2,this.arena.excite(1)),this.finishSlowMotion>0&&!l.reducedMotion){this.finishSlowMotion=Math.max(0,this.finishSlowMotion-i);let e=Math.min(1,this.finishSlowMotion/.5);i*=.3+.7*(1-e)}this.viewerHitFlash=Math.max(0,this.viewerHitFlash-i*3.2);let p=u===null?0:t?gK(u):this.buffer.renderTick(e),m=this.updateRocked(u===null?null:this.shownAt(p),d,l.reducedMotion);m!==null&&u!==null&&this.onRocked?.(m,u.tick);let h=u===null?null:this.applyLocalPrediction(this.buffer.sample(p),i,e),g=this.replay;if(g!==null){let e=c-g.startedAt;e>=g.plan.durationSeconds||g.plan.impact.kind===`referee_down`&&u?.phase!==`referee_down`?this.endReplay():(p=CW(g.plan,e,this.simulation.tick_rate),h=g.buffer.sample(p)??h,!g.impactFired&&p>=g.plan.impact.tick&&h!==null&&(g.impactFired=!0,this.fireReplayImpact(h)))}let _=this.replay===null?i:i*this.replay.plan.speed,v=1.8,y=!1,b=null;if(h!==null){let e=this.replay===null?this.ceremony:null,[t,n]=e===null?this.standApart(h.fighters,_):this.ceremonyFighters(e,h.fighters,_,c,this.drawnOffsets);for(let[e,t]of h.fighters.entries())this.arcadeInjuries[e]!==null&&this.replay===null&&(t.is_downed?this.observedInjuryDown[e]=!0:this.observedInjuryDown[e]&&h.result===null&&this.restoreInjury(e));let r=this.graphs;if(r!==null){this.wearLook(0,t.player_id),this.wearLook(1,n.player_id);let e=this.headCacheValid[0]?this.headCache[0]:void 0,i=this.headCacheValid[1]?this.headCache[1]:void 0;r[0].boxer.root.visible=!0,r[1].boxer.root.visible=!0;let a=UW(h,this.simulation.tick_rate);r[0].setResting(a),r[1].setResting(a);let o=h.phase===`countdown`?h.phase_ticks_remaining:null;r[0].setCountdown(o),r[1].setCountdown(o);let s=this.replay!==null||h.phase===`complete`;r[0].stayDown(s),r[1].stayDown(s),h.phase===`fight`&&this.lastPhase===`rest`&&this.replay===null&&(this.roundCalloutUntil=c+nG,this.roundCalloutRound=h.round_number),h.phase===`rest`&&this.lastPhase!==`rest`&&this.enterRest(c),this.lastPhase=h.phase,this.anticipatePunches(u,p),r[0].setObstacle(r[1].boxer.root.position.x,r[1].boxer.root.position.z),r[1].setObstacle(r[0].boxer.root.position.x,r[0].boxer.root.position.z);let d=this.referee?.boxer.rig.bones.head.getWorldPosition(this.refereeHead)??null;r[0].setRefereeHead(d),r[1].setRefereeHead(d),r[0].update(t,n,_,c,l.reducedMotion,l.blood,p,i),r[1].update(n,t,_,c,l.reducedMotion,l.blood,p,e);let f=h.phase===`finish`?Er(h.fighters,this.finishTargetId):null;for(let[e,t]of h.fighters.entries()){let n=f!==null&&t.player_id===f.player_id;r[e].setDazed(n),this.carnage.sync(e,(this.replay===null?void 0:u?.fighters[e])??t,l,_,c,n)}let m=r[h.fighters.findIndex(e=>e.player_id===this.viewerId)],g=m?.ownPressId??null;if(m!==void 0&&g!==null&&g!==this.soundedPress){this.soundedPress=g;let{punchClass:e,power:t}=m.punchKind;this.onOwnPunch?.(e,t,g)}for(let[e,t]of r.entries()){let n=t.boxer.bone(`head`);n!==null&&(t.boxer.root.updateMatrixWorld(!0),n.getWorldPosition(this.headCache[e]),this.headCacheValid[e]=!0);let r=t.fallBody!==null;r&&!this.fallingLive[e]&&this.replay===null&&(this.liveFallTicks[e]=p),this.fallingLive[e]=r}}for(let e=0;ee.player_id===this.viewerId),C=l.camera===`fighter`&&S>=0&&HW(h)?this.fighterCam.update(i,c,S===0?this.tmpA:this.tmpB,S===0?this.tmpB:this.tmpA,this.effects.shakeAmount+this.powerShake,l.reducedMotion,this.camera.aspect):null;C===null&&this.fighterCam.reset();let w=this.replay,T=this.cameraOverride??(w!==null&&h!==null?this.replayFrame(h,c-w.startedAt):this.closeUpFrame(c)??this.raiseFrame(c,i,l.reducedMotion)??this.cornerShotFrame(c,h,l.reducedMotion)??this.restWideFrame(h)??this.ceremonyFrame(c)??C??x);this.ownViewActive=C!==null&&T===C;let E=this.ownViewActive?this.baseFov*kD:this.baseFov;if(this.camera.fov!==E&&(this.camera.fov=E,this.camera.updateProjectionMatrix()),this.cameraOverride===null&&this.portraitPull>1&&T.framed!==!0&&!this.ownViewActive){let e=T.tight===!0,t=this.portraitPull/Math.min(1.3,Math.sqrt(this.portraitPull)),n=e?Math.min(t,1.25):t;this.tmpCamera.subVectors(T.position,T.lookAt).multiplyScalar(n),this.camera.position.copy(T.lookAt).add(this.tmpCamera),e&&(this.camera.position.x=G.clamp(this.camera.position.x,-2.2,vG),this.camera.position.z=G.clamp(this.camera.position.z,-2.2,vG)),this.camera.lookAt(T.lookAt.x,T.lookAt.y-(this.portraitPull-1)*(e?.08:.45),T.lookAt.z)}else this.camera.position.copy(T.position),this.camera.lookAt(T.lookAt);this.effects.setViewDistance(this.camera.position.distanceTo(T.lookAt)),this.arena.makeRoomForCamera(this.camera.position);let D=T===x?BP(Math.max(this.tmpA.z,this.tmpB.z)):T.framed===!0?RG:1;this.ring.setNearRopeOpacity(this.ring.nearRopeOpacity()+(D-this.ring.nearRopeOpacity())*(1-Math.exp(-6*i))),n&&(this.composer.render(),this.drawHudOverlay(h)),!this.destroyed&&!this.manualClock&&(this.raf=requestAnimationFrame(e=>this.draw(e)))}applyLocalPrediction(e,t,n){if(e===null||this.localInput===null||this.viewerId===null)return e;let r=e.fighters.findIndex(e=>e.player_id===this.viewerId),i=this.localInput()??{moveX:0,moveY:0,defense:`none`},a=(this.inputLatencyMs??60)/1e3*this.simulation.tick_rate+this.buffer.interpolationDelayTicks,o=this.ownCollapseUntil>e.tick,s=e.phase===`fight`||e.phase===`finish`&&r>=0&&Er(e.fighters,this.finishTargetId)!==e.fighters[r],c=r>=0&&s&&!o?e.fighters[r]:null,l=this.evasion.holdsFeet(n)?0:this.graphs?.[r]?.ownFootwork??1,u=this.movement.update(c,i,l,n,a,e.tick,t,this.simulation.tick_rate),d=this.evasion.pose(n);if(r<0)return e;let f=e.fighters[r],p=c===null?f.defense:hE(c,i,d,this.evasion.hidesServerEvasion(n));if(Math.abs(u.dx)<.01&&Math.abs(u.dy)<.01&&p===f.defense)return e;let m=pE(f,u,e.fighters[+(r===0)]??null),h={...f,x:f.x+m.dx,y:f.y+m.dy,defense:p},g=r===0?[h,e.fighters[1]]:[e.fighters[0],h];return{...e,fighters:g}}anticipatePunches(e,t){if(!(this.replay!==null||e===null||e.phase!==`fight`&&e.phase!==`finish`))for(let[n,r]of(this.graphs??[]).entries()){let i=e.fighters[n];i!==void 0&&!i.is_downed&&r.anticipate(i,i.action_start_tick-t)}}cheer(e,t){ee.clinch_ticks>0||e.clinch_startup_ticks>0||e.is_downed)?null:LK(n.x,n.y,r.x,r.y,EG,u-f,d-f,S),[a,o]=this.drawnTargets;a.x=i===null?0:i.ax-n.x,a.y=i===null?0:i.ay-n.y,o.x=i===null?0:i.bx-r.x,o.y=i===null?0:i.by-r.y,this.clearOfTheFallen(e);let s=1-Math.exp(-14*t);for(let e of[0,1]){let n=this.drawnOffsets[e],r=this.drawnTargets[e],i=r.x-n.x,a=r.y-n.y;if(this.drawnOffsetsLive){i*=s,a*=s;let e=Math.hypot(i,a);e>DG*t&&(i*=DG*t/e,a*=DG*t/e)}n.x+=i,n.y+=a}return this.drawnOffsetsLive=!0,[this.drawnAt(0,n),this.drawnAt(1,r)]}drawnAt(e,t){let n=this.drawnOffsets[e];if(Math.abs(n.x)<.01&&Math.abs(n.y)<.01)return t;let r=fE(t.x+n.x,t.y+n.y);return Object.assign(this.drawnFighters[e],t,{x:r.x,y:r.y})}clearOfTheFallen(e){for(let t of[0,1]){let n=this.graphs?.[t]?.fallBody??null,r=+(t===0),i=e[r];if(n===null||i.is_downed||(this.graphs?.[r]?.fallBody??null)!==null)continue;let a=this.drawnTargets[r],o=this.mapping.x(i.x+a.x),s=this.mapping.z(i.y+a.y),c=this.clearOf(n,o,s);a.x+=(c.x-o)/this.mapping.x(1),a.y+=(c.z-s)/this.mapping.z(1);return}}clearOf(e,t,n){let r={x:t,z:n};for(let t of[0,1,2,3,4])e.bodyPoint(t,this.bodyPoint),r=NK(r.x,r.z,this.bodyPoint.x,this.bodyPoint.z,CG);let i=this.insideRopes(r.x,r.z);if(Math.hypot(i.x-r.x,i.z-r.z)<1e-6)return r;let a=t=>[0,1,2,3,4].every(n=>(e.bodyPoint(n,this.bodyPoint),Math.hypot(t.x-this.bodyPoint.x,t.z-this.bodyPoint.z)>=.499999));for(let e=OG;e<=2.000000001;e+=OG)for(let[t,n]of[[1,0],[-1,0],[0,1],[0,-1]]){let r=this.insideRopes(i.x+t*e,i.z+n*e);if(a(r))return r}return i}insideRopes(e,t){let n=fE(e/this.mapping.x(1),t/this.mapping.z(1));return{x:this.mapping.x(n.x),z:this.mapping.z(n.y)}}headHeightOf(e){return(this.graphs?.[e]?.boxer.metrics.headRestY??1.52)+.04}bleed(e,t,n){for(let[r,i]of e.entries()){let e=Tq(i,this.graphs?.[r],this.flashKnockout?.loserId),a=this.arcadeInjuries[r]??null,o=a!==null,s=(i.trauma.bleeding+i.trauma.left_cut+i.trauma.right_cut)/380,c=o?Math.max(s,dq):s;if(c>.05&&!e)this.downedPoolAccumulators[r]=0,this.downedPoolCounts[r]=0,this.effects.drip(this.dripPoint(r),c,n.reducedMotion,r);else if(c>lq&&e&&n.blood!==`off`){this.effects.stopDrip(r),this.downedPoolAccumulators[r]+=t*5*(o?fq:1);let e=this.poolSource(r,a);for(;this.downedPoolAccumulators[r]>=1;){--this.downedPoolAccumulators[r];let t=this.downedPoolCounts[r];this.downedPoolCounts[r]=t+1;let n=wq(t,c,o?pq:uq),i=t*2.399963+r*Math.PI;this.effects.pool(e.x+Math.sin(i)*n*.25,e.z+Math.cos(i)*n*.25,n,t+r*7)}}else this.effects.stopDrip(r),this.downedPoolAccumulators[r]=0,e||(this.downedPoolCounts[r]=0)}}dripPoint(e){let t=this.headWorldPose(e);if(t!==null)return t.position.add(this.tmpStumpOffset.copy(mq).applyQuaternion(t.quaternion));if(this.headCacheValid[e])return this.tmpHead.copy(this.headCache[e]);let n=e===0?this.tmpA:this.tmpB;return this.tmpHead.set(n.x,this.headHeightOf(e),n.z)}poolSource(e,t){if(t===`dismember_left`||t===`dismember_right`){let n=this.handWorldPose(e,t===`dismember_left`?`left`:`right`);if(n!==null)return n.position}let n=Cq(t);if(n!==`mouth`){let t=this.tornWound(e,n);if(t!==null)return t.position}return this.headCacheValid[e]?this.headCache[e]:e===0?this.tmpA:this.tmpB}updateBlobShadows(){let e=[this.tmpA,this.tmpB,this.refereePosition];for(let[t,n]of this.blobShadows.entries()){n.visible=t>=2||!this.carnage.gibbed(t);let r=t<2?this.graphs?.[t]:this.referee??void 0,i=r?.fallBody?.centre(this.bodyPoint)??null??(r?.boxer.root.visible===!0?r.currentRoot:e[t]);n.position.x=i.x,n.position.z=i.z;let a=t<2?this.buffer.latest()?.fighters[t]:void 0,o=t<2?a!==void 0&&Tq(a,r,this.flashKnockout?.loserId):r?.isDown===!0;n.scale.set(o?2.1:1.25,o?.9:.85,1)}}updateReferee(e,t,n,r){let i=this.referee;if(i===null)return;let a=this.replay===null||this.replay.plan.impact.kind===`referee_down`;i.boxer.root.visible=a;let o=this.blobShadows[2];o!==void 0&&(o.visible=a);let s=n?.referee??null,c=this.replay!==null&&this.replay.plan.impact.kind===`referee_down`?this.replay:null;!this.refereePlaced&&s!==null&&(this.refereePlaced=!0,this.refereePosition.set(this.mapping.x(s.x),0,this.mapping.z(s.y)));let l=this.refereeReplayAt!==null||this.pendingRefereeEvents.some(e=>e.kind===`referee_down`);s?.alive===!0&&i.isDown&&this.replay===null&&n?.phase!==`referee_down`&&!l&&i.resetTransient(!1),s===null||s.alive||i.isDown||this.replay!==null||l||(this.refereePosition.set(this.mapping.x(s.x),0,this.mapping.z(s.y)),i.knockOut(),this.refereeFallUnseen=!0);let u=s!==null&&(n?.phase===`fight`&&s.alive||c!==null&&!c.impactFired)?s:null,d=s?.alive===!1&&(c===null||c.impactFired),f=n?.fighters.find(e=>e.is_downed)??(n?.phase===`knockdown`?n.fighters.find(e=>e.player_id===this.lastKnockdown?.knockdown.target_id):void 0)??null,p=n?.fighters.some(e=>e.clinch_ticks>0||e.clinch_startup_ticks>0)??!1,m=f===null&&i.breaking,h=f===null?void 0:this.graphs?.[n?.fighters.indexOf(f)??-1],g=h?.fallBody?.centre(this.bodyPoint)??null,_=f!==null&&!f.is_downed?h?.currentRoot??null:null,v=f===null?(this.tmpA.x+this.tmpB.x)/2:g?.x??_?.x??this.mapping.x(f.x),y=f===null?(this.tmpA.z+this.tmpB.z)/2:g?.z??_?.z??this.mapping.z(f.y),b=this.refereeAway.set(this.refereePosition.x-v,0,this.refereePosition.z-y);if(b.lengthSq()<.01&&b.set(0,0,-1),b.normalize(),m){let e=this.tmpB.z-this.tmpA.z,t=this.tmpA.x-this.tmpB.x,n=Math.hypot(e,t),r=e*b.x+t*b.z>=0?1:-1;n>.01&&b.set(e/n*r,0,t/n*r)}let{standoff:x,clearance:S}=Fq(f!==null,p,m),C=G.clamp(v+b.x*x,-2.4,2.4),w=G.clamp(y+b.z*x,-2.4,2.4),T=this.refereePosition.x,E=this.refereePosition.z,D=this.replay===null&&this.ceremony?.positions!==null?this.ceremony:null,O=!d&&D===null&&this.replay===null&&this.stoppageWinner>=0&&this.frameSeconds>=this.stoppageRaiseAt?this.stoppageWinner===0?this.tmpA:this.tmpB:null,k=O===null?null:this.stoppageSpot??=this.raiseSpot(O,this.stoppageWinner===0?this.tmpB:this.tmpA),A=k!==null&&k.x<0?-1:1;if(d)D!==null&&(D.refereeArrived=!0);else if(O!==null&&k!==null){let t=UG(this.refereePosition.x,this.refereePosition.z,{x:O.x+k.x,y:O.z+k.z},BG*e);this.refereePosition.x=t.x,this.refereePosition.z=t.y}else if(D!==null){let t=UG(this.refereePosition.x,this.refereePosition.z,{x:LG.x,y:LG.z},BG*e);this.refereePosition.x=t.x,this.refereePosition.z=t.y,D.refereeArrived=t.arrived}else if(u!==null){let t=c===null?1-Math.exp(-20*e):1;this.refereePosition.x+=(this.mapping.x(u.x)-this.refereePosition.x)*t,this.refereePosition.z+=(this.mapping.z(u.y)-this.refereePosition.z)*t}else{let t=1-Math.exp(-(m?8:1.6)*e),n=m?Math.min(1,AG*e/Math.max(1e-6,Math.hypot(C-this.refereePosition.x,w-this.refereePosition.z)*t)):1;this.refereePosition.x+=(C-this.refereePosition.x)*t*n,this.refereePosition.z+=(w-this.refereePosition.z)*t*n}let j=O===null?D===null?u!==null||d?0:S:D.refereeArrived?0:IG:dG*.85;for(let e of j>0?[this.tmpA,this.tmpB]:[]){let t=this.refereePosition.x-e.x,n=this.refereePosition.z-e.z,r=Math.hypot(t,n);r.001&&(this.refereePosition.x=e.x+t/r*j,this.refereePosition.z=e.z+n/r*j)}for(let e of D!==null||d?[]:this.graphs??[]){let t=e.fallBody;if(t!==null)for(let e of[0,1,2,3,4]){t.bodyPoint(e,this.bodyPoint);let n=NK(this.refereePosition.x,this.refereePosition.z,this.bodyPoint.x,this.bodyPoint.z,SG);this.refereePosition.x=n.x,this.refereePosition.z=n.z}}for(let e of d?[]:[0,1]){if(!this.effects.severedHeadPosition(e,this.closeUpTarget))continue;let t=NK(this.refereePosition.x,this.refereePosition.z,this.closeUpTarget.x,this.closeUpTarget.z,yG);this.refereePosition.x=t.x,this.refereePosition.z=t.z}if(c===null&&!d){let t=this.refereePosition.x-T,n=this.refereePosition.z-E,r=Math.hypot(t,n),i=$G*e;r>i&&(this.refereePosition.x=T+t/r*i,this.refereePosition.z=E+n/r*i)}e>0&&this.refereeVelocity.set((this.refereePosition.x-T)/e,0,(this.refereePosition.z-E)/e);let ee=O!==null&&k!==null&&Math.hypot(this.refereePosition.x-O.x-k.x,this.refereePosition.z-O.z-k.z)<=pG,M=D!==null&&!D.refereeArrived,te=O===null?D===null?u===null?Math.atan2(v-this.refereePosition.x,y-this.refereePosition.z):Math.atan2(u.facing_x,-u.facing_y):M?Math.atan2(LG.x-this.refereePosition.x,LG.z-this.refereePosition.z):0:ee?0:Math.atan2(O.x-this.refereePosition.x,O.z-this.refereePosition.z);if(O!==null){let e=this.graphs?.[this.stoppageWinner]?.boxer.rig.bones,t=n?.fighters[this.stoppageWinner]?.injuries??[],r=cK(t,`left`),a=!ee||e===void 0?null:r&&cK(t,`right`)?this.nearerGlove(e.gloveL,e.gloveR):(r?e.gloveL:e.gloveR).getWorldPosition(this.stoppageWrist);i.raise(A<0?a:null,A>0?a:null)}let ne=((te-this.refereeYaw+Math.PI)%(Math.PI*2)+Math.PI*2)%(Math.PI*2)-Math.PI;this.refereeYaw+=ne*(1-Math.exp(-(m?8:3)*e));let re=Iq(this.refereePosition,this.refereeYaw,this.refereeVelocity,this.mapping,s);i.setRefereeCount(f!==null,f?.get_up_count??0),i.aimBreak(this.tmpA,this.tmpB);let ie=this.settings();if(i.update(re.self,re.focus,e,t,ie.reducedMotion,ie.blood,r),this.refereeFallUnseen&&(this.refereeFallUnseen=!1,i.fallBody?.settle()),this.effects.gushing(2)){let e=this.refereeMouth();e!==null&&this.effects.anchorGush(2,e.position,e.axis)}this.poolUnderReferee(s?.alive===!1,d,e,ie.blood)}poolUnderReferee(e,t,n,r){if(!e&&this.replay===null&&(this.refereePoolAccumulator=0,this.refereePoolCount=0),!t||r===`off`||this.referee===null)return;this.refereePoolAccumulator+=n*5*fq;let i=this.referee.boxer.rig.bones.head.getWorldPosition(this.refereeHead);for(;this.refereePoolAccumulator>=1;){--this.refereePoolAccumulator;let e=this.refereePoolCount,t=wq(e,dq,pq);if(t>=pq)return;this.refereePoolCount=e+1;let n=e*2.399963;this.effects.pool(i.x+Math.sin(n)*t*.25,i.z+Math.cos(n)*t*.25,t,e+14)}}updateTrails(e,t){let n=this.graphs;if(!(n===null||this.trails.length<4)){for(let[r,i]of n.entries())for(let[n,a]of[`gloveL`,`gloveR`].entries()){let o=this.trails[r*2+n],s=this.glows[r*2+n];if(!i.boxer.root.visible||!this.carnage.hasGlove(r,n===0?`left`:`right`)){o.reset(),s?.reset();continue}i.boxer.rig.bones[a].getWorldPosition(this.trailGlove);let c=i.powerHeat(n===0?`left`:`right`);o.update(this.trailGlove,e,this.camera.position,!t&&this.replay===null&&!i.isDown,c),s?.update(this.trailGlove,c,e,t,this.camera)}for(let t of this.impactFlashes)t.update(e,this.camera);this.powerShake*=.02**e}}presentPowerHit(e,t){let n=!t.detail.endsWith(`:body`)&&this.headCacheValid[e]===!0?this.headCache[e]:void 0;n===void 0?this.powerHitPoint.set(this.contactPoint.x,t.detail.endsWith(`:body`)?1.05:1.55,this.contactPoint.z):this.powerHitPoint.copy(n),this.impactFlashes[e]?.fire(this.powerHitPoint),this.powerShake=Math.min(nK,this.powerShake+tK)}updateCornermen(e,t,n,r){let i=this.cornermen;if(i===null)return;let a=UW(n,this.simulation.tick_rate);for(let[n,o]of i.entries()){let i=n===0?-1:1,s=a?kG:_G;this.cornermanPosition.set(i*s,0,-i*s);let c=n===0?3*Math.PI/4:-Math.PI/4;o.attend(a);let l=Iq(this.cornermanPosition,c,this.cornermanVelocity,this.mapping);o.update(l.self,l.focus,e,t,!1,`off`,r)}}updateCutmen(e,t,n,r){let i=this.cutmen,a=this.graphs;if(i===null||a===null)return;let o=n?.phase===`rest`,s=this.mapping.x(l);for(let[c,l]of i.entries()){let i=c===0?-1:1,u=o&&a[c].stoolVisible?1:0,d=this.cutmanProgress[c],f=d+Math.sign(u-d)*Math.min(Math.abs(u-d),e/jG);this.cutmanProgress[c]=f;let p=l.boxer.root.visible;if(l.boxer.root.visible=f>.005,!l.boxer.root.visible)continue;this.cutmanFrom.set(i*_G,0,-i*2.42),bD(c===0?0:1,s,_D,32,this.cutmanTo);let m=f*f*(3-2*f);this.cornermanPosition.copy(this.cutmanFrom).lerp(this.cutmanTo,m);let h=this.cutmanLast[c];p||h.copy(this.cornermanPosition),this.cornermanVelocity.copy(this.cornermanPosition).sub(h).divideScalar(Math.max(e,.001)),h.copy(this.cornermanPosition);let g=f>.02&&f=MG?_===null?Math.atan2(i,-i):Math.atan2(_.x-this.cutmanTo.x,_.z-this.cutmanTo.z):Math.atan2(-this.cutmanFrom.x,-this.cutmanFrom.z),y=mK(n?.fighters[c]);if(f>=MG&&_!==null){let e=a[c].boxer.root.rotation.y;this.cutmanFacing.set(Math.sin(e),0,Math.cos(e)),this.cutmanEye.copy(_).addScaledVector(this.cutmanFacing,.09),this.cutmanEye.x+=Math.cos(e)*y.side*y.lateral,this.cutmanEye.z-=Math.sin(e)*y.side*y.lateral,this.cutmanEye.y+=y.lift,l.treat(this.cutmanEye,this.cutmanFacing,y.side,y.prop)}else l.treat(null);let b=Iq(this.cornermanPosition,v,this.cornermanVelocity,this.mapping);l.update(b.self,b.focus,e,t,!1,`off`,r)}}drawHudOverlay(e){let t=VW(this.hudCanvas);if(t===null)return;let{context:n,viewport:r}=t;if(this.hudViewport.width=r.width,this.hudViewport.height=r.height,n.clearRect(0,0,r.width,r.height),e===null)return;let i=this.settings();if(this.viewerHitFlash>.01&&!i.reducedMotion){let e=n.createRadialGradient(r.width/2,r.height/2,r.width*.12,r.width/2,r.height/2,r.width*.7);e.addColorStop(0,`rgba(255,235,225,${(this.viewerHitFlash*.18).toFixed(3)})`),e.addColorStop(1,`rgba(140,0,10,${(this.viewerHitFlash*.55).toFixed(3)})`),n.fillStyle=e,n.fillRect(0,0,r.width,r.height)}let a=oq(Math.max(...e.fighters.map(e=>e.trauma.head+e.trauma.body)),i.blood);if(a>0){let e=n.createRadialGradient(r.width/2,r.height/2,r.width*.2,r.width/2,r.height/2,r.width*.72);e.addColorStop(0,`rgba(90,0,8,0)`),e.addColorStop(1,`rgba(75,0,8,${a.toFixed(3)})`),n.fillStyle=e,n.fillRect(0,0,r.width,r.height)}i.reducedMotion||this.effects.drawLens(n,r.width,r.height);let o=this.deaths[0]??this.deaths[1],s=this.replay===null?null:this.replay.plan.impact.kind===`referee_down`?`REFEREE DOWN`:o===null?`KNOCKOUT REPLAY`:Oe(o)===null?`DEATH REPLAY`:`FATALITY REPLAY`;Fr(n,r.width,r.height,e,this.players,this.viewerId,this.frameSeconds>=this.finalRevealAt?this.final:null,this.reconnectMs,this.simulation.tick_rate,this.roundStats,s,this.lagWarned?this.inputLatencyMs:null,this.frameSecondsthis.avatars.get(e),this.lastKnockdown?.knockdown.target_id??null,this.touchControls&&e.fighters.some(e=>e.player_id===this.viewerId),this.powerHeld?.()===!0,o,this.finishTargetId,!i.reducedMotion),this.drawCaption(n,r.width,r.height,e)}updateRocked(e,t,n){let r=e?.fighters.find(e=>e.player_id===this.viewerId),i=e===null||this.replay!==null||this.final!==null?0:_W(r,e.phase),a=this.rocked.update(n?0:i,t);return this.finishPass.uniforms.uRocked.value=n?0:a,r===void 0?null:i}shownAt(e){for(let t=this.history.length-1;t>=0;--t)if(this.history[t].tick<=e)return this.history[t];return null}drawCaption(e,t,n,r){let i=this.final!==null&&this.frameSeconds>=this.finalRevealAt?this.final:null;i!==null&&!this.resultAnnounced&&(this.resultAnnounced=!0,this.commentary.resultShown(this.frameSeconds));let a=this.commentary.current(this.frameSeconds),o=this.settings(),s=a===null||!o.commentary?``:a.line.text;if(s!==this.captionText&&(this.captionText=s,this.hudCanvas.dataset.caption=s),a===null||!o.commentary)return;let c=r.fighters.find(e=>e.player_id===this.viewerId),l=Vn(t,n),u=i===null?null:zK(i,t,n,r.fighters,this.players,this.roundStats,this.viewerId,this.deaths[0]??this.deaths[1])/l,d=this.frameSeconds0});p!==null&&(e.save(),e.scale(l,l),XD(e,a,p,o.reducedMotion),e.restore())}destroy(){if(!this.destroyed){if(this.destroyed=!0,cancelAnimationFrame(this.raf),this.raf=0,this.buffer.clear(),this.dedupe.reset(),this.pendingContacts.length=0,this.pendingGore.length=0,this.carnage.dispose(),this.effects.dispose(),this.avatars.dispose(),this.arena.dispose(),iF(this.ring),this.graphs!==null){for(let e of this.graphs)this.scene.remove(e.boxer.root),e.dispose();this.graphs=null}this.referee!==null&&(this.scene.remove(this.referee.boxer.root),this.referee.dispose(),this.referee=null);for(let e of this.trails)this.scene.remove(e.mesh),e.dispose();this.trails=[];for(let e of this.glows)this.scene.remove(e.mesh),e.dispose();this.glows=[];for(let e of this.impactFlashes)this.scene.remove(e.group),e.dispose();if(this.impactFlashes=[],this.glowMap?.dispose(),this.glowMap=null,this.cornermen!==null){for(let e of this.cornermen)this.scene.remove(e.boxer.root),e.dispose();this.cornermen=null}if(this.cutmen!==null){for(let e of this.cutmen)this.scene.remove(e.boxer.root),e.dispose();this.cutmen=null}for(let e of this.lights)this.scene.remove(e);this.keyLight?.shadow.map?.dispose(),this.keyLight?.shadow.dispose(),this.blobTexture.dispose();for(let e of this.blobShadows)this.scene.remove(e),e.geometry.dispose(),e.material.dispose();this.renderer.renderLists.dispose(),GW(this.composer),this.bloomPass.materialHighPassFilter.dispose(),hF(),this.renderer.dispose(),this.hudCanvas.remove()}}},Rq=[`broadcast`,`close`,`fighter`],zq=`hands.preferences.v1`,Bq={length:0,clear:()=>void 0,getItem:()=>null,key:()=>null,removeItem:()=>void 0,setItem:()=>void 0},Vq=()=>{try{return window.localStorage}catch{return Bq}},Hq=()=>({volume:.7,haptics:!0,reducedMotion:window.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches??!1,blood:`full`,commentary:!0,announcer:!0,camera:`broadcast`});function Uq(e=Vq()){let t=Hq();try{let n=JSON.parse(e.getItem(zq)??`null`);if(typeof n!=`object`||!n||Array.isArray(n))return t;let r=n;return{volume:typeof r.volume==`number`&&Number.isFinite(r.volume)?Math.max(0,Math.min(1,r.volume)):t.volume,haptics:typeof r.haptics==`boolean`?r.haptics:t.haptics,reducedMotion:typeof r.reducedMotion==`boolean`?r.reducedMotion:t.reducedMotion,blood:r.blood===`reduced`||r.blood===`off`||r.blood===`full`?r.blood:t.blood,commentary:typeof r.commentary==`boolean`?r.commentary:t.commentary,announcer:typeof r.announcer==`boolean`?r.announcer:t.announcer,camera:Rq.includes(r.camera)?r.camera:t.camera}}catch{return t}}function Wq(e,t=Vq()){try{t.setItem(zq,JSON.stringify({volume:Math.max(0,Math.min(1,e.volume)),haptics:e.haptics,reducedMotion:e.reducedMotion,blood:e.blood,commentary:e.commentary,announcer:e.announcer,camera:e.camera}))}catch{}}var Gq=class{value;listeners=new Set;constructor(e=Vq()){this.storage=e,this.value=Uq(e)}storage;get current(){return this.value}update(e){this.value={...this.value,...e},Wq(this.value,this.storage);for(let e of this.listeners)e(this.value)}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}destroy(){this.listeners.clear()}},Kq={stage:`bootstrapping`,player:null,playerId:null,role:null,players:{},playerOrder:[],simulation:null,snapshot:null,final:null,select:null,serverTick:0,nextSequence:0,reconnectMs:0,safeError:null},qq=e=>Object.fromEntries(e.map(e=>[e.id,e]));function Jq(e,t){if(t.type===`bootstrap`)return{...e,stage:`authorizing`,simulation:t.simulation,safeError:null};if(t.type===`authorized`)return{...e,stage:`connecting`,player:t.player,safeError:null};if(t.type===`connecting`)return{...e,stage:`connecting`};if(t.type===`reconnect-tick`)return{...e,stage:`paused`,reconnectMs:Math.max(0,t.remainingMs)};if(t.type===`fatal`)return{...e,stage:`fatal`,safeError:t.code,reconnectMs:0};let n=t.message;switch(n.type){case`welcome`:return{...e,playerId:n.role===`fighter`?n.player_id:null,role:n.role,players:qq(n.players),playerOrder:n.players.map(e=>e.id),serverTick:n.server_tick,nextSequence:n.role===`fighter`?n.next_sequence:0,safeError:null};case`ticket`:return e;case`waiting`:return{...e,stage:`waiting`,select:null};case`select`:return{...e,stage:`select`,select:n,players:qq(n.players),playerOrder:n.players.map(e=>e.id)};case`ready`:return{...e,stage:e.snapshot?.phase??`countdown`,select:null,players:qq(n.players),playerOrder:n.players.map(e=>e.id)};case`paused`:return{...e,stage:`paused`,reconnectMs:n.grace_ms};case`resumed`:return{...e,stage:e.snapshot?.phase??`countdown`,reconnectMs:0};case`snapshot`:return{...e,stage:n.payload.phase,snapshot:n.payload,serverTick:Math.max(e.serverTick,n.payload.tick)};case`final`:return{...e,stage:`complete`,final:n,reconnectMs:0};case`error`:return{...e,stage:`fatal`,safeError:n.code,reconnectMs:0}}}var Yq=new Set([`hit`,`counter_hit`,`block`,`perfect_block`,`guard_break`,`knockdown`,`parry`,`body_collapse`,`eye_shut`,`referee_hit`,`referee_down`]),Xq=11e3,Zq=1500,Qq=4e3,$q=3e3,eJ=6,tJ=5e3,nJ=[{level:`rookie`,label:`Rookie`,detail:`Slow hands, leaves openings`},{level:`contender`,label:`Contender`,detail:`Works the body, punishes mistakes`},{level:`champion`,label:`Champion`,detail:`Slips, counters, finishes`}],rJ=e=>Mt.includes(e),iJ=class{root;reloadPage;authorizer;state=Kq;settings=new Gq;input=new pf;audio=new _i(()=>this.settings.current);haptics=new Rd(()=>this.settings.current);voice=new Zr(()=>this.settings.current);feedbackEvents=new Df;soundedPunches=[];renderer=null;network=null;session=null;abort=new AbortController;destroyed=!1;generation=0;reloadOnRetry=!1;reloading=!1;canvas;status;overlay;roleIndicator;controlsButton;controlsPanel;retry;rematchButton;hint;cpuPicker;cpuPrompt;cpuLevel=null;rematchOpponent=null;lastPhase=null;cpuRematchLevel=null;cpuRematch=null;cpuRematchTimer=null;diagnosticsTimer=null;finalReceivedAt=0;lastFinalMatchId=null;rematchAttempts=0;rematchTimer=null;rematchCountdownTimer=null;resultRevealTimer=null;resultWaitTimer=null;completeSince=null;summaryClock=new or;fightSummary;liveFightStatus;finalSummary;corner;stylePicker;constructor(e,t=()=>window.location.reload(),n=new _d){this.root=e,this.reloadPage=t,this.authorizer=n,e.innerHTML=`
HANDStwo-player boxing

`,this.canvas=e.querySelector(`canvas`),this.status=e.querySelector(`[data-status]`),this.overlay=e.querySelector(`[data-overlay]`),this.roleIndicator=e.querySelector(`[data-role]`),this.controlsButton=e.querySelector(`[data-controls]`),this.controlsPanel=e.querySelector(`[data-controls-panel]`),this.retry=e.querySelector(`[data-retry]`),this.rematchButton=e.querySelector(`[data-rematch]`),this.hint=e.querySelector(`[data-hint]`),this.cpuPicker=e.querySelector(`[data-cpu]`),this.cpuPrompt=e.querySelector(`[data-cpu-prompt]`),this.cpuPicker.addEventListener(`click`,this.onCpuPick),this.rematchButton.addEventListener(`click`,this.onRematch),this.fightSummary=e.querySelector(`[data-fight-summary]`),this.liveFightStatus=e.querySelector(`[data-fight-status]`),this.finalSummary=e.querySelector(`[data-final]`),this.retry.addEventListener(`click`,this.onRetry),this.bindPanels(),this.syncSettings(),this.input.attachTouch(e.querySelector(`.activity`)),this.corner=new kd(e.querySelector(`.activity`),e=>this.network?.sendCornerChoice(e)??!1),this.stylePicker=new Xt(e.querySelector(`.activity`),(e,t)=>this.network?.chooseStyle(e,t)??!1),this.input.setViewForward(()=>this.renderer?.viewForward()??null),window.addEventListener(`keydown`,this.onCameraKey)}onCameraKey=e=>{if(e.code!==`KeyK`||e.repeat||e.ctrlKey||e.metaKey||e.altKey)return;let t=e.target;if(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement)return;e.preventDefault();let n=Rq[(Rq.indexOf(this.settings.current.camera)+1)%Rq.length];this.settings.update({camera:n}),this.root.querySelector(`[data-camera]`).value=n};start(){this.authorize()}resetForAuthorization(){this.reloadOnRetry=!1,this.network?.dispose(),this.network=null,this.session?.destroy(),this.session=null,this.renderer?.destroy(),this.renderer=null,this.voice.cancel(),this.audio.reset(),this.abort.abort(),this.abort=new AbortController,this.state=Kq,this.feedbackEvents.reset(),this.input.setActive(!1),this.input.reset(),this.finalSummary.textContent=``,this.fightSummary.textContent=``,this.liveFightStatus.textContent=``,this.clearRematchTimers(),this.rematchButton.hidden=!0,this.cpuLevel=null,this.lastPhase=null}onCpuPick=e=>{let t=e.target?.closest(`[data-cpu-level]`)?.dataset.cpuLevel;rJ(t)&&this.state.stage===`waiting`&&this.state.role===`fighter`&&this.cpuLevel===null&&this.callCpu(t)};callCpu(e){this.network?.requestCpu(e)===!0&&(this.cpuLevel=e,this.renderState())}get cpuBout(){return Object.values(this.state.players).some(e=>e.cpu===!0)}onRematch=()=>{this.rematchButton.disabled||this.state.stage!==`complete`||(this.rematchAttempts=1,this.rematchOpponent=this.cpuBout||this.state.role!==`fighter`?null:Object.values(this.state.players).find(e=>e.id!==this.state.playerId)?.name??null,this.authorize())};clearRematchTimers(){this.rematchTimer!==null&&window.clearTimeout(this.rematchTimer),this.rematchCountdownTimer!==null&&window.clearInterval(this.rematchCountdownTimer),this.rematchTimer=null,this.rematchCountdownTimer=null,this.clearCpuRematch()}scheduleCpuRematch(e){this.clearCpuRematch(),this.cpuRematch={level:e,at:Date.now()+tJ},this.cpuRematchTimer=window.setInterval(()=>{let e=this.cpuRematch;e===null||this.state.stage!==`waiting`||this.state.role!==`fighter`||this.cpuLevel!==null?this.clearCpuRematch():Date.now()>=e.at&&(this.clearCpuRematch(),this.callCpu(e.level)),this.renderState()},250)}clearCpuRematch(){this.cpuRematchTimer!==null&&window.clearInterval(this.cpuRematchTimer),this.cpuRematchTimer=null,this.cpuRematch=null}awaitResultReveal(){this.resultRevealTimer!==null&&window.clearInterval(this.resultRevealTimer);let e=()=>{let e=this.renderer?.resultVisible??!0;this.overlay.hidden=this.state.stage===`complete`&&!e,(e||this.state.stage!==`complete`)&&this.resultRevealTimer!==null&&(window.clearInterval(this.resultRevealTimer),this.resultRevealTimer=null)};this.resultRevealTimer=window.setInterval(e,200),e()}startRematchCountdown(){this.clearRematchTimers();let e=this.state.role===`fighter`?`Rematch`:`Next bout`,t=()=>{let t=Math.ceil((this.finalReceivedAt+Xq-Date.now())/1e3);this.rematchButton.hidden=this.state.stage!==`complete`,this.rematchButton.disabled=t>0,this.setText(this.rematchButton,t>0?`${e} in ${t}s`:e),t<=0&&this.rematchCountdownTimer!==null&&(window.clearInterval(this.rematchCountdownTimer),this.rematchCountdownTimer=null)};t(),this.rematchCountdownTimer=window.setInterval(t,1e3)}scheduleRematchRetry(){this.rematchTimer===null&&(this.rematchAttempts>=eJ?this.fail(`rematch_unavailable`):(this.rematchAttempts+=1,this.setText(this.status,`The ring is still being cleared… trying again.`),this.rematchTimer=window.setTimeout(()=>{this.rematchTimer=null,this.authorize()},$q)))}async authorize(){let e=++this.generation;this.resetForAuthorization(),this.dispatch({type:`connecting`}),this.setText(this.status,`Securing Discord Activity session…`),this.retry.hidden=!0;try{let t=await this.authorizer.authorize(this.abort.signal);if(this.destroyed||e!==this.generation){t.destroy();return}this.session=t,this.dispatch({type:`bootstrap`,simulation:t.bootstrap.simulation}),this.dispatch({type:`authorized`,player:t.player}),this.input.onAction(e=>{this.renderer?.predictAction?.(e),this.network?.notifyAction()}),this.input.onHeldChange(()=>this.network?.notifyHeld());let n=t.takeTicket();if(n===null)throw Error(`ticket_unavailable`);let r=new Rf(n,()=>this.input.frame(),{onMessage:e=>this.receive(e),onReconnect:e=>{this.dispatch({type:`reconnect-tick`,remainingMs:e}),this.renderer?.setReconnect(e),this.renderState()},onFatal:e=>this.fail(e),onFreshAuth:()=>{e===this.generation&&this.authorize()}});this.network=r,r.start(),this.setText(this.status,`Connecting to the ring…`)}catch(t){!this.abort.signal.aborted&&e===this.generation&&(this.reloadOnRetry=t instanceof vi&&t.reloadRequired,this.fail(wi(t)))}}ensureRenderer(){if(this.renderer!==null||this.session===null||this.destroyed)return;let e=new Lq(this.canvas,this.session.bootstrap.simulation,()=>this.settings.current,{localInput:()=>this.input.held(),inputSequenceOf:e=>this.network?.sequenceOf(e)??null,powerHeld:()=>this.input.powerHeld});e.onContact=(e,t)=>{this.audio.event(e,t),this.haptics.event(e,t)},e.onOwnPunch=(e,t,n)=>{this.audio.whoosh(e,t),this.soundedPunches.push(n),this.soundedPunches.length>8&&this.soundedPunches.shift()},e.onArcadeInjury=e=>this.audio.injury(e),e.onGore=e=>{this.audio.gore(e),this.haptics.gore(e),e.kind===`finish_him`?this.voice.shout(`Finish him!`):e.kind===`fatality`&&this.voice.shout(`Fatality.`)},e.onAnnouncement=e=>this.voice.speak(e),e.onCrowdCue=()=>this.audio.chant(),e.onRocked=(e,t)=>this.audio.rocked(e,t),this.renderer=e}receive(e){if(e.type===`error`){this.fail(e.code);return}e.type===`welcome`&&this.ensureRenderer(),(e.type===`welcome`||e.type===`resumed`)&&this.renderer?.resyncClock();let t=this.rematchAttempts>0;(e.type===`waiting`||e.type===`ready`)&&(this.rematchAttempts=0),e.type===`ready`&&(this.rematchOpponent=null),e.type===`ready`&&this.rememberStyle(e.players),e.type===`final`&&this.rematchAttempts>0&&e.match_id===this.lastFinalMatchId?this.scheduleRematchRetry():(this.dispatch({type:`message`,message:e}),e.type===`snapshot`&&this.receiveSnapshot(e.payload),e.type!==`select`&&e.type!==`ready`||e.players.some(e=>e.cpu===!0)||(this.cpuLevel=null),e.type===`waiting`&&(this.cpuLevel===null?t&&this.cpuRematchLevel!==null&&this.scheduleCpuRematch(this.cpuRematchLevel):this.callCpu(this.cpuLevel)),e.type===`final`&&(this.cpuRematchLevel=this.cpuBout?this.cpuLevel:null,this.rematchAttempts=0,this.lastFinalMatchId=e.match_id,this.finalReceivedAt=Date.now(),this.renderer?.setFinal(e),this.audio.result(e),this.startRematchCountdown(),this.awaitResultReveal()),this.renderer?.setPlayers(this.state.players,this.state.playerId,this.state.playerOrder),this.renderer?.setReconnect(this.state.reconnectMs),this.renderState())}get networkStats(){return{inputLatencyMs:this.network?.inputLatencyMs??null,resolutionScale:this.renderer?.resolutionScale??null,gpu:this.renderer?.memoryInfo??null}}receiveSnapshot(e){this.lastPhase===`countdown`&&e.phase!==`countdown`&&this.voice.finishLine(Zq),this.lastPhase=e.phase,this.renderer?.setInputLatency(this.network?.inputLatencyMs??null),this.renderer?.push(e);let t=e.fighters.find(e=>e.player_id===this.state.playerId);this.input.setKnockdown(t?.is_downed===!0),t!==void 0&&this.audio.snapshot(e.tick,t.stamina,t.maximum_stamina,t.trauma.head+t.trauma.body),this.audio.roundClock(e.phase,e.round_number,e.phase_ticks_remaining,this.state.simulation?.tick_rate??30),this.audio.tension(Fp(e));for(let t of this.feedbackEvents.accept(e.events)){if(Yq.has(t.kind)||t.kind===`punch_start`&&t.action_id!==null&&this.soundedPunches.includes(t.action_id))continue;let n=t.kind===`punch_start`?e.fighters.find(e=>e.player_id===t.actor_id&&e.action_id===t.action_id):void 0;this.audio.event(t,n?.action_power===`power`),this.haptics.event(t)}}rememberStyle(e){let t=e.find(e=>e.id===this.state.playerId)?.style;this.state.role===`fighter`&&t!==void 0&&Ut(t)}dispatch(e){this.state=Jq(this.state,e)}setText(e,t){e.textContent!==t&&(e.textContent=t)}renderState(){let e={bootstrapping:`Loading…`,authorizing:`Authorizing with Discord…`,connecting:`Connecting securely…`,waiting:this.state.role===`spectator`?`Waiting for the fighters…`:this.cpuLevel===null?this.cpuRematch===null?this.rematchOpponent===null?`Waiting for an opponent. Anyone in this channel can join with Play now.`:`Waiting for ${this.rematchOpponent} to take the rematch…`:`Rematch with the ${nJ.find(e=>e.level===this.cpuRematch?.level)?.label??`computer`} in ${Math.max(1,Math.ceil((this.cpuRematch.at-Date.now())/1e3))}s, unless someone joins first.`:`Calling in the computer…`,select:`Pick how your fighter boxes.`,countdown:`Bout countdown.`,fight:`Round ${this.state.snapshot?.round_number??1} in progress.`,knockdown:`Knockdown count ${this.state.snapshot?.fighters.find(e=>e.player_id===this.state.playerId)?.get_up_count??0}.`,foul_recovery:`Foul recovery in progress.`,referee_down:`The referee is down. The bout goes on without him.`,finish:this.state.snapshot!==null&&Er(this.state.snapshot.fighters)?.player_id===this.state.playerId?`You are out on your feet: one more punch kills you.`:`Finish him: one more punch kills.`,rest:`Between-round rest.`,paused:`Connection paused. ${Math.ceil(this.state.reconnectMs/1e3)} seconds remain.`,complete:this.cpuBout?`Bout complete. Scorecards are displayed. Bouts against the computer are unrated.`:`Bout complete. Scorecards and rating changes are displayed.`,fatal:jd(this.state.safeError??`safe_error`)},t=this.state.role===`spectator`;this.setText(this.status,t?`Spectating — ${e[this.state.stage]}`:e[this.state.stage]);let n=this.state.stage===`complete`&&this.state.final!==null;if(this.status.hidden=n||[`select`,`countdown`,`fight`,`knockdown`,`foul_recovery`,`referee_down`,`finish`,`rest`].includes(this.state.stage),this.overlay.toggleAttribute(`data-raised`,this.state.snapshot!==null),this.overlay.toggleAttribute(`data-result`,n),this.state.stage!==`complete`)this.overlay.hidden=!1,this.completeSince=null;else if(this.state.final===null){this.completeSince??=Date.now();let e=Date.now()-this.completeSince;this.overlay.hidden=e{this.resultWaitTimer=null,this.renderState()},Qq-e+50))}this.roleIndicator.hidden=!t,this.controlsButton.hidden=t,t&&(this.controlsPanel.hidden=!0,this.controlsButton.setAttribute(`aria-expanded`,`false`));let r=this.state.snapshot?.fighters.find(e=>e.player_id===this.state.playerId),i=t?`Spectating. ${e[this.state.stage]}`:this.state.stage===`knockdown`&&r?.is_downed===!0?`Knockdown. Count ${r.get_up_count}. ${r.get_up_prompt===null?`Wait for your private rhythm instruction.`:`Press ${r.get_up_prompt===`get_up_left`?`left`:`right`} now.`}`:this.state.stage===`paused`?`Connection paused.`:e[this.state.stage];this.setText(this.liveFightStatus,i),this.corner.update(this.state.snapshot,this.state.playerId,this.state.role===`fighter`&&this.state.stage===`rest`),this.renderer?.setCornerPanelTop(this.corner.top()),this.stylePicker.update(this.state.stage===`select`?this.state.select:null,this.state.playerId,this.state.role),this.retry.hidden=this.state.stage!==`fatal`,this.setText(this.retry,this.reloadOnRetry?`Reload`:`Retry securely`),this.state.stage!==`complete`&&(this.rematchButton.hidden=!0),this.cpuPicker.hidden=t||this.state.stage!==`waiting`||this.cpuLevel!==null,this.setText(this.cpuPrompt,this.cpuRematch===null?this.rematchOpponent===null?`No one here yet? Fight the computer.`:`Or fight the computer instead:`:`Or start now:`);let a=!t&&(this.state.stage===`waiting`||this.state.stage===`countdown`);this.hint.hidden=!a,a&&this.setText(this.hint,Kd(Md(),window.innerWidth)),this.overlay.toggleAttribute(`data-touch-hint`,a&&this.state.stage===`countdown`&&Md());let o=!t&&[`countdown`,`fight`,`knockdown`,`foul_recovery`,`referee_down`,`finish`].includes(this.state.stage),s=!t&&this.state.snapshot!==null&&(this.state.stage===`rest`||this.state.stage===`paused`);if(this.input.setActive(o,o||s),this.network?.setActive(o),this.renderFightSummary(),this.state.final!==null){let e=this.state.final;this.setText(this.finalSummary,`${e.method.replaceAll(`_`,` `)}. ${e.winner_id===null?`Draw`:`${this.state.players[e.winner_id]?.name??`Winner`} wins`}. Scorecards: ${e.scorecards.map(e=>`${e.judge}: ${e.player_one.reduce((e,t)=>e+t,0)} to ${e.player_two.reduce((e,t)=>e+t,0)}`).join(`; `)}. ${this.cpuBout?`Unrated bout against the computer.`:`Ratings: ${Object.entries(e.ratings).map(([e,t])=>`${this.state.players[e]?.name??`fighter`} ${t.before} to ${t.after}`).join(`; `)}.`}`)}}renderFightSummary(){let e=this.state.snapshot;if(e===null)return;let t=this.state.simulation?.tick_rate??30,n=Math.floor(this.summaryClock.ticks(e)/t),r=`${Math.floor(n/60)}:${String(n%60).padStart(2,`0`)}`,i=e.fighters.map(e=>{let t=this.state.players[e.player_id],n=e.injuries.length===0?`no injuries`:`injuries: ${e.injuries.map(e=>we(e).toLowerCase()).join(`, `)}`;return`${t?.name??`Fighter`}, ${t?.cpu===!0?`computer opponent`:`ELO ${t?.rating??`unknown`}`}, stamina ${Math.round(e.stamina)} of ${Math.round(e.maximum_stamina)}, guard ${Math.round(e.guard)}, poise ${Math.round(e.poise)}, conditioning ${Math.round(e.conditioning)}, blood ${Math.round(e.blood_volume/ve*100)} percent, ${n}, ${e.warnings} warnings, ${e.knockdowns} knockdowns`}),a=e.fighters.find(e=>e.player_id===this.state.playerId),o=a?.is_downed===!0?a.get_up_prompt===null?`You are down. Count ${a.get_up_count}. Wait for your private rhythm instruction.`:`You are down. Count ${a.get_up_count}. Press ${a.get_up_prompt===`get_up_left`?`left`:`right`} now. Get-up progress ${a.get_up_meter} of ${a.get_up_required}.`:``;this.setText(this.fightSummary,`Round ${e.round_number}. ${e.phase.replace(`_`,` `)}. Clock ${r}. ${i.join(`. `)}. ${o}`.trim())}onRetry=()=>{this.reloadOnRetry?(this.reloading=!0,this.reloadPage()):this.authorize()};bindPanels(){let e=(e,t)=>{let n=this.root.querySelector(e),r=this.root.querySelector(t);n.addEventListener(`click`,()=>{r.hidden=!r.hidden,n.setAttribute(`aria-expanded`,String(!r.hidden))})};e(`[data-controls]`,`[data-controls-panel]`),e(`[data-settings]`,`[data-settings-panel]`);let t=this.root.querySelector(`[data-settings-panel]`);this.root.querySelector(`[data-settings]`).addEventListener(`click`,()=>{this.diagnosticsTimer!==null&&window.clearInterval(this.diagnosticsTimer),this.diagnosticsTimer=null,t.hidden||(this.refreshDiagnostics(),this.diagnosticsTimer=window.setInterval(()=>this.refreshDiagnostics(),1e3))});let n=this.root.querySelector(`[data-copy-diagnostics]`);n.addEventListener(`click`,()=>{let e=this.diagnosticsText(),t=()=>{this.setText(n,`Copied`),window.setTimeout(()=>this.setText(n,`Copy diagnostics`),1500)},r=()=>{let e=this.root.querySelector(`[data-diagnostics]`),t=window.getSelection();if(t===null)return;let r=document.createRange();r.selectNodeContents(e),t.removeAllRanges(),t.addRange(r),this.setText(n,`Selected. Copy manually`),window.setTimeout(()=>this.setText(n,`Copy diagnostics`),2500)},i=navigator.clipboard;i===void 0||typeof i.writeText!=`function`?r():i.writeText(e).then(t).catch(r)}),this.root.querySelector(`[data-volume]`).addEventListener(`input`,e=>{this.settings.update({volume:Number(e.target.value)}),this.audio.setVolume(),this.voice.settingsChanged()}),this.root.querySelector(`[data-haptics]`).addEventListener(`change`,e=>{this.settings.update({haptics:e.target.checked})}),this.root.querySelector(`[data-motion]`).addEventListener(`change`,e=>{let t=e.target.checked;this.settings.update({reducedMotion:t}),this.renderer?.setReducedMotion(t)}),this.root.querySelector(`[data-commentary]`).addEventListener(`change`,e=>{this.settings.update({commentary:e.target.checked})}),this.root.querySelector(`[data-announcer]`).addEventListener(`change`,e=>{let t=e.target.checked;this.settings.update({announcer:t}),t||this.voice.cancel()}),this.root.querySelector(`[data-blood]`).addEventListener(`change`,e=>{let t=e.target.value;this.settings.update({blood:t}),this.renderer?.setBloodLevel(t)}),this.root.querySelector(`[data-camera]`).addEventListener(`change`,e=>{let t=Rq.find(t=>t===e.target.value);t!==void 0&&this.settings.update({camera:t})})}diagnosticsText(){let e=this.networkStats,t=this.renderer?.diagnostics,n=t===void 0||t.frameMs<=0?`-`:(1e3/t.frameMs).toFixed(0);return[`stage: ${this.state.stage} · role: ${this.state.role??`-`}`,`input latency: ${e.inputLatencyMs===null?`-`:`${Math.round(e.inputLatencyMs)} ms`}`,`frame: ${t===void 0?`-`:`${t.frameMs.toFixed(1)} ms (${n} fps)`} · render scale: ${t?.resolutionScale??`-`}`,`gpu objects: ${t===void 0?`-`:`${t.gpu.geometries} geometries, ${t.gpu.textures} textures, ${t.gpu.programs} programs`}`,`graphics: ${t?.graphics??`-`}`,`browser: ${navigator.userAgent}`,`pointer: ${Md()?`coarse`:`fine`} · viewport: ${window.innerWidth}x${window.innerHeight} @${window.devicePixelRatio}`,`last error: ${this.state.safeError??`none`}`,`match: ${this.state.final?.match_id??`-`}`].join(` -`)}refreshDiagnostics(){this.setText(this.root.querySelector(`[data-diagnostics]`),this.diagnosticsText())}syncSettings(){let e=this.settings.current;this.root.querySelector(`[data-volume]`).value=String(e.volume),this.root.querySelector(`[data-haptics]`).checked=e.haptics,this.root.querySelector(`[data-motion]`).checked=e.reducedMotion,this.root.querySelector(`[data-blood]`).value=e.blood,this.root.querySelector(`[data-commentary]`).checked=e.commentary,this.syncAnnouncerSetting(),this.voice.onVoicesChanged=()=>this.syncAnnouncerSetting(),this.root.querySelector(`[data-camera]`).value=e.camera}syncAnnouncerSetting(){let e=this.root.querySelector(`[data-announcer]`),t=this.voice.hasVoice;e.checked=this.settings.current.announcer&&t,e.disabled=!t;let n=this.voice.supported?t?null:`This device has no English voice of its own`:`This browser cannot speak`;n===null?e.parentElement.removeAttribute(`title`):e.parentElement.title=n}fail(e){e===`room_closed`&&this.rematchAttempts>0?this.scheduleRematchRetry():(e===`client_outdated`&&(this.reloadOnRetry=!0),this.dispatch({type:`fatal`,code:e}),this.rematchOpponent=null,this.voice.cancel(),this.network?.dispose(),this.network=null,this.session?.destroy(),this.session=null,this.renderer?.destroy(),this.renderer=null,this.input.setActive(!1),this.input.reset(),this.renderState())}destroy(){this.destroyed||(this.destroyed=!0,this.generation+=1,this.abort.abort(),this.network?.dispose(),this.session?.destroy(),this.reloading||this.authorizer.close(),this.renderer?.destroy(),window.removeEventListener(`keydown`,this.onCameraKey),this.input.destroy(),this.corner.destroy(),this.stylePicker.destroy(),this.audio.destroy(),this.voice.destroy(),this.settings.destroy(),this.retry.removeEventListener(`click`,this.onRetry),this.rematchButton.removeEventListener(`click`,this.onRematch),this.cpuPicker.removeEventListener(`click`,this.onCpuPick),this.clearRematchTimers(),this.diagnosticsTimer!==null&&window.clearInterval(this.diagnosticsTimer),this.resultRevealTimer!==null&&window.clearInterval(this.resultRevealTimer),this.resultWaitTimer!==null&&window.clearTimeout(this.resultWaitTimer),this.diagnosticsTimer=null,this.root.replaceChildren())}};(new URLSearchParams(window.location.search).get(`styles`)??``).split(`,`);var aJ={broadcast:{position:[0,1.88,7.15],lookAt:[0,1.12,0]},side:{position:[7.4,1.6,0],lookAt:[0,1.1,0]},top:{position:[.01,8.5,.01],lookAt:[0,0,0]},ringside:{position:[1.6,1.5,4.1],lookAt:[.2,1.25,0]}},oJ=[[`hips`,`spine`],[`spine`,`head`],[`chest`,`shoulderL`],[`shoulderL`,`elbowL`],[`elbowL`,`gloveL`],[`chest`,`shoulderR`],[`shoulderR`,`elbowR`],[`elbowR`,`gloveR`],[`hips`,`hipL`],[`hipL`,`kneeL`],[`kneeL`,`ankleL`],[`hips`,`hipR`],[`hipR`,`kneeR`],[`kneeR`,`ankleR`]],sJ=class{root;renderer=null;replay=null;raf=0;playing=!1;speed=1;virtualTick=0;carry=0;latencyMs=0;pendingQueue=[];destroyed=!1;overlays={skeleton:!1,hurtbox:!1,hitbox:!1};skeletonLines=[];hurtboxMeshes=[];hitboxMeshes=[];statusEl;metricsEl;canvas;constructor(e){this.root=e,e.innerHTML=`
+}`},FG=[{x:-102,y:-16},{x:102,y:-16}],IG=[0,1],LG=.5,RG={x:0,z:-.2},zG=0,BG=200,VG=1.3,HG=.7,UG=4.5;function WG(e,t,n,r){let i=n.x-e,a=n.y-t,o=Math.hypot(i,a);return o<=Math.max(r,1e-6)?{x:n.x,y:n.y,arrived:!0}:{x:e+i/o*r,y:t+a/o*r,arrived:!1}}var GG=16,KG=.6,qG={hit:.18,counter_hit:.3,guard_break:.25,knockdown:1,block:.04,perfect_block:.1,parry:.22,body_collapse:.45},JG=new Set([`hit`,`counter_hit`,`block`,`perfect_block`,`guard_break`,`knockdown`,`parry`,`body_collapse`,`eye_shut`]),YG=new Set([`parry`,`body_collapse`,`eye_shut`]),XG=new Set([`hit`,`counter_hit`,`block`,`perfect_block`]),ZG=1.2,QG=.8,$G=2.4,eK=2.5,tK=new Set([`referee_hit`,`referee_down`]),nK=.05,rK=.08,iK={parry:{text:`PARRIED`,seconds:1},eye_shut:{text:`EYE SWOLLEN SHUT`,seconds:1.6}},aK=new Set([`injury`,`vomit`,`finish_him`,`fatality`,`death`]),oK=1.8,sK=3,cK=.6;function lK(e,t){let n=Ae(e,t);return n!==`severed`&&n!==`torn`}function uK(e){return e.kind===`death`?e.detail===`brain`?`head_burst`:null:e.kind===`fatality`?e.detail===`head_burst`?`head_burst`:e.detail===`decapitation`||e.detail===`spine_rip`?`decapitation`:null:null}var dK=e=>e.kind===`knockdown`&&e.detail===`body`;function fK(e,t){if($W(e)&&e.action_id!==null)return t.find(t=>eG(t)&&t.action_id===e.action_id&&t.actor_id===e.target_id&&t.target_id===e.actor_id)}function pK(e,t){if(eG(e)&&e.action_id!==null)return t.find(t=>$W(t)&&t.action_id===e.action_id&&t.actor_id===e.target_id&&t.target_id===e.actor_id)}function mK(e,t){return e.map((n,r)=>{if(YG.has(n.kind)||n.kind===`knockdown`&&n.detail===SG)return{event:n,presentationEvent:n,presentImpact:!1,reactAmount:null};let{puncherIndex:i}=ZW(n,t),a=t.fighters[i],o=a?.action_key?.split(`:`)??[],s=o.length>=3?`${o[0]}:${o[2]}`:n.detail,c=pK(n,e);if(eG(n))return{event:n,presentationEvent:{...n,detail:c?.detail||s,direction:c?.direction??a?.facing??n.direction,blood:c?.blood??n.blood},presentImpact:!0,reactAmount:n.amount};if(fK(n,e)!==void 0)return{event:n,presentationEvent:n,presentImpact:!1,reactAmount:n.amount};if(n.kind===`knockdown`){let t=e.slice(0,r).reverse().find(e=>$W(e)&&e.tick===n.tick&&e.actor_id===n.actor_id&&e.target_id===n.target_id);if(t!==void 0)return{event:n,presentationEvent:{...n,detail:t.detail,direction:t.direction,blood:t.blood,action_id:t.action_id},presentImpact:!0,reactAmount:fK(t,e)===void 0?null:t.amount}}return{event:n,presentationEvent:n,presentImpact:!0,reactAmount:n.amount}})}function hK(e){let t=e?.trauma;if(t===void 0)return{side:1,lift:.08,lateral:.035,prop:`enswell`};switch(e?.corner_choice){case`cut`:return{side:t.right_cut>t.left_cut?-1:1,lift:.11,lateral:.04,prop:`enswell`};case`swelling`:return{side:t.right_eye>t.left_eye?-1:1,lift:.08,lateral:.035,prop:`enswell`};case`breath`:return{side:1,lift:-.015,lateral:0,prop:`bottle`};default:return{side:t.right_eye+t.right_cut>t.left_eye+t.left_cut?-1:1,lift:.08,lateral:.035,prop:`enswell`}}}function gK(e){return e?.split(`:`)[1]===`right`?1:-1}function _K(e){return e.result===null?e.tick-1:e.tick}var vK=50,yK=40,bK=40,xK=50,SK=[`jab`,`straight`,`hook`,`uppercut`];function CK(e,t,n,r){if(!WW(e,t,n))return null;let i=r?.action_key?.split(`:`),a=e.detail.split(`:`).find(e=>SK.includes(e))??i?.[0],o=i?.[1]===`right`?`left`:`right`,s=e.amount;return e.detail.endsWith(`:head`)?n?.finish_method===`flash_ko`||e.kind===`counter_hit`&&s>=70?`head_burst`:a===`uppercut`&&s>=yK||a===`straight`&&s>=vK?`decapitation`:(a===`hook`||a===`jab`)&&s>=bK?`eye_${o}`:`jaw_dislocation`:a===`hook`?s>=xK?`dismember_${o}`:`shoulder_${o}`:`ribs_${o}`}function wK(){let e=document.createElement(`canvas`);e.width=128,e.height=128;let t=e.getContext(`2d`);if(t!==null){let e=t.createRadialGradient(64,64,8,64,64,62);e.addColorStop(0,`rgba(0,0,0,0.68)`),e.addColorStop(.6,`rgba(0,0,0,0.34)`),e.addColorStop(1,`rgba(0,0,0,0)`),t.fillStyle=e,t.fillRect(0,0,128,128)}return new ky(e)}var TK=new q(0,.12,.02),EK=new q(0,1,0),DK=new WeakMap;function OK(e){let t=DK.get(e);return t===void 0&&(t=AO(e,qK),DK.set(e,t)),t}function kK(e){return e.y>cA-1.4}var AK=new WeakMap;function jK(e){let t=AK.get(e);return t===void 0&&(t=AO(e,kK),AK.set(e,t)),t}function MK(e,t,n){let r=e.bone(`head`);if(r===null)return null;e.root.updateMatrixWorld(!0);let i=e.headMesh,a=jK(i.geometry);if(a.length===0)return null;let o=t.length===a.length*3?t:new Float32Array(a.length*3);n.position.set(0,0,0);for(let[t,r]of a.entries())VK(e,r,n.scratch),n.scratch.toArray(o,t*3),n.position.add(n.scratch);return n.position.multiplyScalar(1/a.length),r.getWorldQuaternion(n.quaternion),n.across.set(1,0,0).applyQuaternion(n.quaternion),n.scratch.set(0,1,0).applyQuaternion(n.quaternion),n.quaternion.setFromUnitVectors(EK,n.scratch),o}function NK(e,t,n,r){let i=e?.currentRoot;return r.set(i?.x??n.x(t.x),0,i?.z??n.z(t.y))}function PK(e,t,n,r,i){let a=Math.hypot(e-n,t-r);return a>=i?{x:e,z:t}:a<1e-6?{x:n,z:r-i}:{x:n+(e-n)/a*i,z:r+(t-r)/a*i}}var FK=[0,1.05,-1.05,2.1,-2.1,Math.PI];function IK(e,t,n,r,i,a,o=[]){let s=n===null?0:Math.hypot(n.x,n.z),c=n!==null&&s>=.35?[Math.atan2(n.x,n.z)]:[];for(let e of FK)c.push(a+e);for(let n of c){let a=G.clamp(e+Math.sin(n)*r,-i,i),s=G.clamp(t+Math.cos(n)*r,-i,i),c=Math.hypot(a-e,s-t);if(!(c{let r=G.clamp(((n.x-e)*(a-e)+(n.z-t)*(s-t))/(c*c),.25,1);return Math.hypot(e+(a-e)*r-n.x,t+(s-t)*r-n.z)1e-9&&(s=Math.min(s,(Math.sign(n)*i-e)/n)),Math.abs(r)>1e-9&&(s=Math.min(s,(Math.sign(r)*a-t)/r));for(let i of[-1,1])for(let a of[-1,1]){let c=i*n+a*r;c>1e-9&&(s=Math.min(s,(o-i*e-a*t)/c))}return Math.max(0,s)}function RK(e,t,n,r,i,a,o,s=1/0){let c=Math.hypot(n-e,r-t);if(c>=i)return null;let l=c<1e-6?1:(n-e)/c,u=c<1e-6?0:(r-t)/c,d=i-c,f=LK(e,t,-l,-u,a,o,s),p=LK(n,r,l,u,a,o,s),m=Math.min(d/2,f),h=Math.min(d-m,p);m=Math.min(d-h,f);let g=G.clamp;return{ax:g(e-l*m,-a,a),ay:g(t-u*m,-o,o),bx:g(n+l*h,-a,a),by:g(r+u*h,-o,o)}}var zK=new WeakMap;function BK(e,t,n,r,i,a,o,s=null){let c=zK.get(e);if(c!==void 0&&c.width===t&&c.height===n)return c.top;let l=Hr(t,n,zr(e,r,i,r.map(e=>a.total(e.player_id)),s),!0).y;return zK.set(e,{width:t,height:n,top:l}),l}function VK(e,t,n){let r=e.headMesh;return Dj(n.fromBufferAttribute(r.geometry.getAttribute(`position`),t),e.look,n),r.applyBoneTransform(t,n).applyMatrix4(r.matrixWorld)}var HK=new Sg,UK=new Sg,WK=new Dg;function GK(e,t,n){let r=e.geometry;HK.fromBufferAttribute(r.getAttribute(`skinIndex`),t),UK.fromBufferAttribute(r.getAttribute(`skinWeight`),t),n.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);for(let t=0;t<4;t+=1){let r=UK.getComponent(t);if(r===0)continue;let i=HK.getComponent(t);WK.multiplyMatrices(e.skeleton.bones[i].matrixWorld,e.skeleton.boneInverses[i]);for(let e=0;e<16;e+=1)n.elements[e]+=WK.elements[e]*r}return n.premultiply(e.bindMatrixInverse).multiply(e.bindMatrix)}var KK=new q(-1,0,0);function qK(e){return e.y>oA-sA*(e.z- -4)-.3}var JK={tick_rate:30,ring_half_width:500,ring_half_height:500};function YK(e,t,n,r,i,a,o=!0){let s=e.geometry,c=s.getAttribute(`position`),l=s.getIndex(),u=[],d=l!==null&&r===void 0?[]:null;if(l===null||d===null)for(let e=0;e=i.start+o))return{action:i.punchClass,action_hand:i.hand,action_target:`head`,action_power:`normal`,action_id:`idle-${n}-${r}`,action_key:`${i.punchClass}:${i.hand}:head:normal`,action_start_tick:e-(t-i.start),action_startup_ticks:a.startup,action_active_ticks:a.active,action_recovery_ticks:a.recovery,action_contact_tick:e-(t-i.start)+a.startup}}return{}}var nq=1000003,rq=1.6;function iq(e,t,n,r,i,a){let o=r<0?-1:1,s=o=>Math.hypot(G.clamp(e+n*o*i,-a,a)-e,G.clamp(t+r*o*i,-a,a)-t);return s(o)>=i*.8||s(o)>=s(-o)?o:-o}function aq(e,t,n){return t?e.kind===`knockdown`?1:Math.min(1,.35+e.amount/400):(n===`full`?1:n===`reduced`?.4:0)*(e.kind===`knockdown`?.85:e.amount>=50?Math.min(.75,(e.amount-30)/140):0)}function oq(e){if(e.kind!==`hit`&&e.kind!==`counter_hit`||e.amount<(e.detail.endsWith(`:body`)?70:50))return null;let t=Math.min(100,Math.max(0,e.blood));return{seconds:.6+t/50,rate:150+e.amount*1.5+t*2}}function sq(e,t){return t===`full`?e>100?Math.min(.65,e/1800):0:e>350?Math.min(.3,e/4600):0}function cq(e){return!e.is_downed&&e.stunned_ticks===0&&e.clinch_ticks===0&&e.clinch_startup_ticks===0&&e.taunt_ticks===0&&!e.is_foul_recovery_target}function lq(e,t){if(e===null)return null;let n=t.fighters.find(t=>t.player_id===e.target_id),r=t.fighters.find(t=>t.player_id===e.actor_id);return CK(e,n===void 0?void 0:{...n,is_downed:!0},{finish_method:`ko`,winner_id:e.actor_id},r)}var uq=.2,dq=1.1,fq=1.6,pq=2.4,mq=2,hq=new q(0,-.1,.08),gq=new q(0,-.07,.1),_q=new q(0,-.35,1),vq=3,yq=320,bq=8,xq=1.6,Sq=.08,Cq=.12,wq=e=>e===`shoulder_left`||e===`shoulder_right`||e===`ribs_left`||e===`ribs_right`?e:`mouth`;function Tq(e,t,n=dq){return Math.min(n,.06+.08*Math.sqrt(Math.max(0,e))*Math.min(1.6,Math.max(0,t)))}function Eq(e,t,n){return e.is_downed||t?.isDown===!0||n!==void 0&&e.player_id===n}var Dq=6,Oq=11,kq=.13;function Aq(e,t){let n=t===`left`?`leftRibs`:`rightRibs`;e.impact(n,[t===`left`?-6:Dq,-6*.15,-1.5],Oq),e.set(n,{bruise:1.2,swell:0,blood:1.4})}function jq(e,t){e.set(`mouth`,{cut:1,blood:1.4}),e.set(`chin`,{bruise:1.2}),t.set(`neckSmear`,{blood:1.4})}function Mq(e,t){e.set(t===`left`?`leftShoulderSmear`:`rightShoulderSmear`,{blood:1.4}),e.set(t===`left`?`leftPec`:`rightPec`,{bruise:1.1})}var Nq=new WeakMap;function Pq(e,t){let n=Nq.get(e);if(n===void 0){let t=e.getAttribute(`position`),r=new q,i=new q,a=VA.map(e=>{let n=0,a=1/0;i.set(e[0],e[1],e[2]);for(let e=0;ethis.onAnnouncement?.(e),cue:e=>this.onCrowdCue?.(e)});touchControls=Md();resultAnnounced=!1;captionText=``;rocked=new vW;tmpA=new q;tmpB=new q;contactPoint=new q;cornerPanelTop=null;mouthPoint=new q;tmpHead=new q;tmpHeadQuaternion=new rg;tmpStump=new q;tmpStumpOffset=new q;tmpStumpQuaternion=new rg;tmpStumpAcross=new q;tmpPart=new q;tmpPartQuaternion=new rg;woundPoint=new q;woundAxis=new q;constructor(e,t=JK,n,r={}){this.canvas=e,this.simulation=t,this.settings=n,this.manualClock=r.manualClock===!0,this.localInput=r.localInput??null,this.powerHeld=r.powerHeld??null,this.inputSequenceOf=r.inputSequenceOf??null,this.buffer=new Ef(8,t.tick_rate),this.mapping=DE(t),this.renderer=new AT({canvas:e,antialias:!0,powerPreference:`high-performance`,preserveDrawingBuffer:r.manualClock===!0}),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=1,this.renderer.toneMapping=4,this.renderer.toneMappingExposure=1,this.renderer.setPixelRatio(this.basePixelRatio),this.scene.background=new J(`#04060b`),this.scene.fog=new l_(`#04060b`,.042),this.camera=new Ox(36,1,.1,80),this.camera.position.set(0,2.05,5.9),this.camera.lookAt(0,1.05,0),this.setupLights(),this.ring=rF(),this.scene.add(this.ring.group),this.arena=iD(),this.scene.add(this.arena.group),this.effects=new sW(this.scene,Md()?1024:2048,Md()?PV:NV),this.effects.useUploader(this.renderer),this.effects.setCamera(this.camera),this.carnage=new Yz(this.effects,ZK),this.blobTexture=wK();let i=new hb(1,1);for(let e=0;e<3;e+=1){let t=new Y(i,new yv({map:this.blobTexture,transparent:!0,depthWrite:!1}));t.rotation.x=-Math.PI/2,t.position.y=.006+e*4e-4,t.renderOrder=1,this.blobShadows.push(t),this.scene.add(t)}this.composer=new zT(this.renderer),this.composer.addPass(new BT(this.scene,this.camera));let a=new HT(new K(1280,720),.2,.45,1.08);this.bloomPass=a,this.composer.addPass(a),this.finishPass=new IT(PG),this.composer.addPass(this.finishPass),this.composer.addPass(new WT),this.hudCanvas=document.createElement(`canvas`),this.hudCanvas.className=`fight-hud`,this.hudCanvas.style.cssText=`position:absolute;inset:0;width:100%;height:100%;pointer-events:none`,e.insertAdjacentElement(`afterend`,this.hudCanvas),this.bloodLevel=n().blood,this.effects.setBloodLevel(this.bloodLevel),this.ensureGraphs(),this.manualClock||(this.raf=requestAnimationFrame(e=>this.draw(e)))}ensureGraphs(){this.glbLoading||this.graphs!==null||(this.glbLoading=!0,this.graphsReady=mF().then(async e=>{if(this.destroyed)return;let t=new DF(e,{skin:11563071,gear:1920728}),n=new DF(e,{skin:7225640,gear:12131356});this.graphs=[new aI(t,this.mapping),new aI(n,this.mapping)];let r=[this.carnage.attach(0,this.graphs[0]),this.carnage.attach(1,this.graphs[1])];this.lookIds.fill(null),this.syncInjuryPresentation(0),this.syncInjuryPresentation(1);let i=new DF(e,{skin:13081462,gear:3889080,look:hj.referee,outfit:Pj,wounds:!0});this.referee=new aI(i,this.mapping,{referee:!0,knockout:!0});let a=new DF(e,{skin:9067067,gear:1778224,look:hj.blueCorner,outfit:Fj}),o=new DF(e,{skin:14264188,gear:1778224,look:hj.redCorner,outfit:Ij});this.cornermen=[new aI(a,this.mapping,{referee:!0}),new aI(o,this.mapping,{referee:!0})];let s=new DF(e,{skin:12160102,gear:1778224,look:hj.blueCutman,outfit:Lj}),c=new DF(e,{skin:5913126,gear:1778224,look:hj.redCutman,outfit:Lj});this.cutmen=[new aI(s,this.mapping,{referee:!0}),new aI(c,this.mapping,{referee:!0})],s.root.visible=!1,c.root.visible=!1,this.trails=[1920728,12131356].flatMap(e=>[0,1].map(()=>new BW(new J(e).lerp(new J(16777215),.55))));let l=MW();this.glowMap=l,this.glows=[0,1,2,3].map(()=>new PW(l)),this.impactFlashes=[0,1].map(()=>new FW(l));let u=new t_;u.add(t.root,n.root,i.root,a.root,o.root,s.root,c.root,...this.trails.map(e=>e.mesh),...this.effects.compileStandIns(),...r.flatMap(e=>e.compileStandIns()),this.glows[0].standIn(),...this.impactFlashes[0].standIns());let d=t.headInjury.open;t.headInjury.setOpen(!0);try{await KW(this.renderer,this.composer,u,this.camera,this.scene)}catch{}if(!this.destroyed){this.scene.add(t.root,n.root,i.root,a.root,o.root,s.root,c.root);for(let e of this.trails)this.scene.add(e.mesh);for(let e of this.glows)this.scene.add(e.mesh);for(let e of this.impactFlashes)this.scene.add(e.group);this.compileShadowsOf(u),t.headInjury.setOpen(d)}}).catch(e=>{this.glbLoading=!1,console.error(`boxer_glb_load_failed`,e)}))}compileShadowsOf(e){let t=this.keyLight;if(t!==null&&e.children.length!==0){for(let t of e.children)t.frustumCulled=!1,t.onBeforeShadow=(e,t,n,r,i,a)=>{a.needsUpdate=!0};this.scene.add(e),t.shadow.needsUpdate=!0,this.renderer.setRenderTarget(this.composer.readBuffer);try{this.renderer.render(this.scene,this.camera)}catch{}finally{this.renderer.setRenderTarget(null),this.scene.remove(e)}}}get ready(){return this.graphsReady}get labRigs(){let e=this.graphs;return e===null?[]:[e[0].boxer.root,e[1].boxer.root]}get labScene(){return this.scene}get labEffects(){return this.effects}labSetCameraOverride(e,t){this.cameraOverride={position:new q(...e),lookAt:new q(...t)}}labFrame(e,t=!0){this.draw(e*1e3,!0,t)}setCornerPanelTop(e){this.cornerPanelTop=e}viewForward(){return this.ownViewActive?(this.ownForward.x=this.fighterCam.forwardX,this.ownForward.z=this.fighterCam.forwardZ,this.ownForward):null}setPlayers(e,t,n=Object.keys(e)){this.players=e,this.viewerId=t,this.playerOrder=n}updateIdleFighters(e,t,n){let r=this.graphs;if(r===null)return;let i=this.playerOrder.filter(e=>this.players[e]!==void 0).length<2;for(let[a,o]of r.entries()){let r=this.playerOrder[a]??`seat-${a}`,s=!i||r===this.viewerId||this.viewerId===null&&a===0;if(o.boxer.root.visible=s,!s)continue;this.wearLook(a===0?0:1,r);let c=a===0?-1:1,l=Math.floor(t*this.simulation.tick_rate),u={...QK(r),x:i?0:c*180,y:i?-70:0,facing:i?1:-c,facing_x:i?0:-c*1e3,facing_y:i?-1e3:0,...i?tq(l):{}},d={...QK(this.playerOrder[1-a]??`opponent`),x:i?0:-c*180,y:i?-150:0};o.setResting(!1),o.update(u,d,e,t,this.settings().reducedMotion,this.bloodLevel,i?l:n)}}setFinal(e){if(e!==null&&e.match_id===this.final?.match_id)return;this.final=e,this.stoppageWinner=-1,this.stoppageRaiseAt=1/0,this.stoppageSpot=null,this.raiseFramed=!1,this.ceremony=this.ceremonyFor(e);let t=e?.method===`draw`&&this.deaths.every(e=>e!==null);if(this.finalRevealAt=this.frameSeconds+(this.ceremony===null?t?fr:mr(e):UG),this.ovationUntil=e===null?0:this.frameSeconds+GG,e!==null&&this.commentary.finish(e,this.players,this.ceremony!==null,this.frameSeconds),this.ceremony===null&&this.endCeremony(),this.pendingFinish=null,e===null||!dr.has(e.method))return;let n=this.lastKnockdown===null?null:SW(this.history,this.lastKnockdown.hit??this.lastKnockdown.knockdown,this.simulation.tick_rate),r=this.finishingInjury(e);if(n!==null&&this.graphs!==null&&!this.settings().reducedMotion){r!==null&&(this.replayInjuries[r.index]={injury:r.injury,event:r.event}),this.startReplay(n);return}if(r!==null){let e=this.pendingContacts.find(e=>e.event.event_id===r.event.event_id);e===void 0?this.applyArcadeInjury(r.index,r.injury,r.event):e.injury??=r.injury}let i=this.buffer.latest()?.result?.tick;i===void 0?this.presentFinish(e):this.pendingFinish={final:e,tick:i,latestAt:this.frameSeconds+_G}}presentFinishWhenShown(e){let t=this.pendingFinish;t===null||ee.player_id===t.hit.target_id)??-1;return r<0||this.arcadeInjuries[r]!==null?null:{index:r,injury:t.finisher,event:t.hit}}ceremonyFor(e){let t=this.buffer.latest()?.fighters;if(e===null||t===void 0||e.method!==`decision`&&e.method!==`draw`||t.some(e=>e.is_downed)||this.deaths.some(e=>e!==null))return null;let n=t.findIndex(t=>t.player_id===e.winner_id);return{winnerSeat:n===0||n===1?n:null,positions:null,refereeArrived:!1,arrivedAt:null,announced:!1}}endCeremony(){for(let e of this.graphs??[])e.awaitVerdict(null);this.referee?.raise(null,null)}ceremonyFighters(e,t,n,r,i=null){e.positions===null&&(e.positions=[{x:t[0].x+(i?.[0].x??0),y:t[0].y+(i?.[0].y??0)},{x:t[1].x+(i?.[1].x??0),y:t[1].y+(i?.[1].y??0)}],e.marks=e.positions[0].x<=e.positions[1].x?[0,1]:[1,0]);let a=e.marks??IG,o=e.refereeArrived;for(let r of[0,1]){let i=e.positions[r],s=a[r],c=WG(i.x,i.y,FG[s],BG*n),l=Math.hypot(c.x-i.x,c.y-i.y),u=n>0?1/(n*this.simulation.tick_rate):0,d=!c.arrived&&l>1e-6;Object.assign(this.drawnFighters[r],t[r],{x:c.x,y:c.y,velocity_x:(c.x-i.x)*u,velocity_y:(c.y-i.y)*u,facing_x:d?Math.round((c.x-i.x)/l*1e3):0,facing_y:d?Math.round((c.y-i.y)/l*1e3):-1e3,facing:d&&c.x=HG){e.announced=!0,this.commentary.verdict(this.frameSeconds);for(let t of[0,1])this.graphs?.[t]?.announce(e.winnerSeat===null?`level`:e.winnerSeat===t?`winner`:`loser`);this.finalRevealAt=Math.min(this.finalRevealAt,this.frameSeconds+.35),this.arena.excite(1)}if(e.announced){let n=n=>{let r=a[0]===n?0:1,i=e.winnerSeat===null||e.winnerSeat===r,o=Ae(t[r].injuries,n===0?`left`:`right`)===`whole`,s=this.graphs?.[r]?.boxer.rig.bones[n===0?`gloveL`:`gloveR`];return i&&o&&s!==void 0?s.getWorldPosition(this.ceremonyWrists[n]):null};this.referee?.isDown!==!0&&this.referee?.raise(n(1),n(0))}return this.drawnFighters}ceremonyFrame(e){let t=this.ceremony,n=this.buffer.latest();if(t===null||t.arrivedAt===null||this.replay!==null||this.final===null||n===null)return null;let{width:r,height:i}=this.hudViewport,a=BK(this.final,r,i,n.fighters,this.players,this.roundStats,this.viewerId),o=CD(this.camera.aspect,this.camera.fov,(i-a)/Math.max(1,i)),s=this.settings().reducedMotion?0:Math.sin((e-t.arrivedAt)*.35)*.06*o.distance;return this.cornerPosition.set(s,o.height+.05*o.distance,o.distance),this.cornerLookAt.set(0,o.height,0),{position:this.cornerPosition,lookAt:this.cornerLookAt,framed:!0}}raiseFrame(e,t,n){let r=this.buffer.latest();if(this.stoppageWinner<0||this.final===null||this.replay!==null||this.ceremony!==null||r===null||e0?-1:1)*fG,o=this.stoppageSpot?.z??0;this.raiseFramed||this.raiseCentre.set(i.x+a/2,0,i.z+o/2),this.raiseCentre.lerp(this.tmpCamera.set(i.x+a/2,0,i.z+o/2),1-Math.exp(-3*t)),this.raiseFramed=!0;let{width:s,height:c}=this.hudViewport,l=BK(this.final,s,c,r.fighters,this.players,this.roundStats,this.viewerId,this.deaths[0]??this.deaths[1]),u=CD(this.camera.aspect,this.baseFov,(c-l)/Math.max(1,c)),d=e-(this.stoppageRaiseAt-dG),f=n?0:Math.sin(d*.35)*.06*u.distance;return this.cornerPosition.set(G.clamp(this.raiseCentre.x,-1.4,1.4)+f,u.height+.05*u.distance,this.raiseCentre.z+u.distance),this.cornerLookAt.set(this.raiseCentre.x,u.height,this.raiseCentre.z),{position:this.cornerPosition,lookAt:this.cornerLookAt,framed:!0}}presentFinish(e){let t=this.buffer.latest()?.referee.alive===!1;t||this.referee?.waveOff();let n=this.buffer.latest()?.fighters,r=n?.findIndex(t=>t.player_id!==e.winner_id&&t.player_id!==null)??-1;if(r>=0&&this.headCacheValid[r]&&!this.settings().reducedMotion&&!this.carnage.gibbed(r)&&(this.finishCloseUpIndex=r,this.finishCloseUpUntil=this.frameSeconds+iG,this.finishCloseUpBearing=null,this.finishCloseUpAt=this.frameSeconds),e.winner_id===null)return;let i=n?.findIndex(t=>t.player_id===e.winner_id)??-1;if(i<0)return;this.graphs?.[i]?.celebrate(uG);let a=n?.[i]?.injuries??[];!t&&(lK(a,`left`)||lK(a,`right`))&&(this.stoppageWinner=i,this.stoppageRaiseAt=this.frameSeconds+dG)}cornerShotFrame(e,t,n){if(t===null||t.phase!==`rest`||n||this.graphs===null)return null;let r=t.fighters.findIndex(e=>e.player_id===this.viewerId),i=e-this.restStartedAt,a=hD(i,t.phase_ticks_remaining/this.simulation.tick_rate,+(r===1));return a===null||!this.graphs[a].stoolVisible||this.cutmen!==null&&this.cutmanProgress[a]e.player_id===this.viewerId)===1),n=this.mapping.x(l);return bD(t,n,-3.5,sG,this.cornerPosition).setY(cG),bD(t,n,0,0,this.cornerLookAt),this.cornerLookAt.lerp(bD(+(t===0),n,0,0,this.tmpCamera),lG).setY(.9),{position:this.cornerPosition,lookAt:this.cornerLookAt,framed:!0}}closeUpFrame(e){if(e>=this.finishCloseUpUntil||this.finishCloseUpIndex<0||!this.headCacheValid[this.finishCloseUpIndex])return null;let t=this.arcadeInjuries[this.finishCloseUpIndex],n=t===`decapitation`&&this.effects.severedHeadPosition(this.finishCloseUpIndex,this.closeUpTarget),r=!n&&this.effects.partPosition(Xz(this.finishCloseUpIndex,`upper_body`),this.closeUpTarget),i=n||r?null:this.graphs?.[this.finishCloseUpIndex]?.fallBody??null;if(this.finishCloseUpBearing===null&&i!==null&&!i.body.asleep&&e-this.finishCloseUpAt.4?u:.9,a)}let d=this.finishCloseUpBearing+l;return this.closeUpPosition.set(G.clamp(s.x+Math.sin(d)*c,-2.2,yG),s.y+(n?.42:o?.5:.75),G.clamp(s.z+Math.cos(d)*c,-2.2,yG)),this.replayLookAt.copy(s),{position:this.closeUpPosition,lookAt:this.replayLookAt,tight:!0}}raiseSpot(e,t){let n=e.x>0?-1:1,r={x:n*fG,z:0},i=-1/0;for(let[a,o]of pG){let s=e.x+n*a*fG,c=e.z+o*fG,l=Math.min(gG-Math.abs(s),gG-Math.abs(c),Math.hypot(s-t.x,c-t.z)-hG);for(let e of this.graphs??[]){let t=e.fallBody;if(t!==null)for(let e of[0,1,2,3,4])t.bodyPoint(e,this.bodyPoint),l=Math.min(l,Math.hypot(s-this.bodyPoint.x,c-this.bodyPoint.z)-CG-.05)}for(let e of[0,1])this.effects.severedHeadPosition(e,this.closeUpTarget)&&(l=Math.min(l,Math.hypot(s-this.closeUpTarget.x,c-this.closeUpTarget.z)-bG-.05));if(l>=0)return{x:s-e.x,z:c-e.z};l>i&&(i=l,r={x:s-e.x,z:c-e.z})}return r}nearerGlove(e,t){e.getWorldPosition(this.stoppageWrist),t.getWorldPosition(this.stoppageOtherWrist);let n=e=>Math.hypot(e.x-this.refereePosition.x,e.z-this.refereePosition.z);return n(this.stoppageOtherWrist)-.5*n.length()}startReplay(e){let t=new Ef(e.snapshots.length+2,this.simulation.tick_rate);for(let n of e.snapshots)t.push(n);if(this.replay={plan:e,buffer:t,startedAt:this.frameSeconds,impactFired:!1,side:null},this.drawnOffsetsLive=!1,this.commentary.replay(this.frameSeconds,e.impact),this.replayFollow=0,this.replayFollowAt=0,e.impact.kind===`referee_down`){this.referee?.resetTransient(!1),this.referee?.primeReplayFall(),this.effects.stopGush(2);return}for(let e=this.pendingGore.length-1;e>=0;--e)this.pendingGore[e].event.kind!==`injury`&&this.pendingGore.splice(e,1);for(let e of[0,1]){this.effects.stopGush(e),this.deaths[e]!==null&&this.carnage.undoDeath(e);let t=this.arcadeInjuries[e],n=this.arcadeInjuryEvents[e];t!==null&&n!==null&&(this.replayInjuries[e]={injury:t,event:n},this.restoreInjury(e))}for(let t of this.pendingContacts.splice(0)){let n=t.recipientIndex;t.injury!==null&&(n===0||n===1)&&this.replayInjuries[n]===null&&this.arcadeInjuries[n]===null&&(this.replayInjuries[n]={injury:t.injury,event:t.event}),t.event.event_id!==e.impact.event_id&&(t.injury=null,t.contactTick=1/0,this.pendingContacts.push(t))}let n=e.snapshots[0]?.fighters.findIndex(t=>t.player_id===e.impact.target_id)??-1;n>=0&&e.impact.detail.endsWith(`:head`)&&this.effects.returnMouthpiece(n);let r=this.lastKnockdown?.knockdown.detail===xG;for(let[t,i]of(this.graphs??[]).entries()){let a=this.liveFallTicks[t]??null;i.resetTransient(!1),a!==null&&a>=e.impact.tick-1&&i.primeReplayFall(),t===n&&r&&i.fallToKnee(!0)}this.finalRevealAt=this.frameSeconds+e.durationSeconds+mr(this.final)}endReplay(){let e=this.replay?.plan.impact.kind===`referee_down`;if(this.replay=null,e){this.drawnOffsetsLive=!1;let e=this.buffer.latest();for(let[t,n]of(this.graphs??[]).entries())n.resetTransient(e?.fighters[t]?.is_downed===!0);return}this.drawnOffsetsLive=!1,this.reapplyReplayInjuries();let t=this.buffer.latest();for(let[e,n]of(this.graphs??[]).entries()){let r=t?.fighters[e],i=r!==void 0&&r.player_id===this.flashKnockout?.loserId;n.resetTransient(r?.is_downed===!0||i),i&&n.knockOut()}for(let e of[0,1])this.showDeath(e,0,!0);this.final!==null&&this.presentFinish(this.final)}fireRefereeEvents(e){for(let t=0;te){t+=1;continue}this.pendingRefereeEvents.splice(t,1);let r=this.buffer.latest();n.kind===`referee_down`?(r!==null&&this.fireRefereeFall(n,r),this.eventCallout={text:`THE REFEREE IS DEAD!`,until:this.frameSeconds+$G},this.refereeReplayAt={at:this.frameSeconds+QG,impact:n}):n.kind===`referee_hit`?r!==null&&this.punchReferee(n,r,!1):this.referee!==null&&(this.referee.boxer.rig.bones.head.getWorldPosition(this.refereeHead),this.effects.addEvent(n,this.refereeHead,this.settings().reducedMotion))}}punchReferee(e,t,n){let r=this.referee;if(r===null)return;let[i,a]=e.detail.split(`:`),o=t.fighters.findIndex(t=>t.player_id===e.actor_id),s=t.fighters[o],c=s?.action_key?.split(`:`)[1]??null;r.react(`hit`,a===`body`?`body`:`head`,e.direction,i,c,n?Math.max(e.amount,140):e.amount),r.boxer.rig.bones.head.getWorldPosition(this.refereeHead);let l=s===void 0?void 0:QW(s,{...s,x:t.referee.x,y:t.referee.y},this.mapping),u=this.settings().reducedMotion;this.effects.addEvent({...e,kind:n?`knockdown`:`hit`},this.refereeHead,u,l);let d=n||u?null:oq({...e,kind:`hit`}),f=d===null?null:this.refereeMouth();d!==null&&f!==null&&this.effects.gush(2,f.position,f.axis,d.seconds,d.rate,e.event_id);let p=this.refereePunchPower(e);o>=0&&this.graphs?.[o]?.landedHit(e.action_id,!1,p),this.onContact?.(e,p)}fireRefereeFall(e,t,n=!1){let r=this.referee;if(r===null)return;let i=n?this.refereeBlow(e):null;i===null?(r.boxer.rig.bones.head.getWorldPosition(this.refereeHead),this.effects.addEvent({...e,kind:`knockdown`,amount:160,blood:80},this.refereeHead,this.settings().reducedMotion)):this.punchReferee(i,t,!0);let a=this.settings().reducedMotion?null:this.refereeMouth();a!==null&&this.effects.gush(2,a.position,a.axis,vq,yq,e.event_id),r.knockOut(),this.onContact?.(e,!1)}refereePunchPower(e){for(let t=this.history.length-1;t>=0;--t){let n=this.history[t];if(n.tickt.player_id===e.actor_id);return r!==void 0&&r.action_id===e.action_id&&r.action_power===`power`}return!1}refereeBlow(e){if(e.action_id===null)return null;for(let t=this.history.length-1;t>=0;--t){let n=this.history[t],r=n.events.find(t=>t.kind===`referee_hit`&&t.action_id===e.action_id&&t.tick===e.tick);if(r!==void 0)return r;if(n.tick=0?e.fighters[a]:void 0,l=c?.action_key?.split(`:`)??[],u=l[0]??null,d=l[1]??null,f=l[3]===`power`;this.graphs?.[i]?.react(`hit`,r.detail.endsWith(`:body`)?`body`:`head`,r.direction,u,d,r.amount),n.knockdown.detail===`body`&&n.knockdown.tick>r.tick&&this.graphs?.[i]?.windedFor((n.knockdown.tick-r.tick)/this.simulation.tick_rate+.15,gK(c?.action_key??null)),o.player_id===this.flashKnockout?.loserId&&this.graphs?.[i]?.knockOut(),a>=0&&this.graphs?.[a]?.landedHit(r.action_id,n.blocked,f),r.detail.endsWith(`:head`)&&!this.settings().reducedMotion&&this.knockOutMouthpiece(i,s??r.direction,r.event_id+nq,!0),f&&!n.blocked&&!this.settings().reducedMotion&&this.presentPowerHit(i,r),this.onContact?.(r,f),this.reapplyReplayInjuries(s),this.deaths[i]!=null&&(this.showDeath(i,s??r.direction,!0),this.announceDeath(i));for(let e of this.pendingGore.splice(0))this.presentGore(e.event);for(let t of this.pendingContacts)t.contactTick===1/0&&(t.contactTick=this.replay?.plan.impact.tick??e.tick)}replayFrame(e,t){let[n,r]=e.fighters,i=this.mapping.x(n.x),a=this.mapping.z(n.y),o=this.mapping.x(r.x),s=this.mapping.z(r.y),c=this.replay?.plan.impact.kind===`referee_down`,l=e.fighters.findIndex(e=>e.player_id===this.replay?.plan.impact.target_id),u=this.replay?.impactFired===!0&&l>=0&&this.headCacheValid[l]===!0;if(c&&this.referee!==null)return this.refereeReplayFrame(e,t);let d=1-Math.exp(-3*Math.max(0,t-this.replayFollowAt));this.replayFollowAt=t,this.replayFollow+=(+!!u-this.replayFollow)*d;let f=l<0?0:Math.max(this.portraitPull>1.3?.7:0,this.replayFollow*.8),p=u?this.headCache[l].x:l===1?o:i,m=u?this.headCache[l].z:l===1?s:a,h=(i+o)/2+(p-(i+o)/2)*f,g=(a+s)/2+(m-(a+s)/2)*f,_=-(s-a),v=o-i,y=Math.hypot(_,v)||1;_/=y,v/=y;let b=2.5,x=this.replay;x!==null&&x.side===null&&(x.side=iq(h,g,_,v,b,yG));let S=x?.side??(v<0?-1:1);_*=S,v*=S;let C=.35*Math.sin(t*.7),w=_*Math.cos(C)-v*Math.sin(C),T=_*Math.sin(C)+v*Math.cos(C);this.replayCameraPosition.set(G.clamp(h+w*b,-2.2,yG),1.38-Math.min(.25,t*.05),G.clamp(g+T*b,-2.2,yG));let E=Math.hypot(this.replayCameraPosition.x-h,this.replayCameraPosition.z-g),D=Math.hypot(h,g);if(E.01){let e=rq-E;this.replayCameraPosition.x=G.clamp(this.replayCameraPosition.x-h/D*e,-2.2,yG),this.replayCameraPosition.z=G.clamp(this.replayCameraPosition.z-g/D*e,-2.2,yG)}let O=u?G.clamp(this.headCache[l].y,.45,1.28):1.28;this.replayLookAt.set(h,1.28+(O-1.28)*this.replayFollow,g);let k=this.settings().reducedMotion?0:this.powerShake;if(k>5e-4){let e=t*61;this.replayCameraPosition.x=G.clamp(this.replayCameraPosition.x+Math.sin(e*1.31)*k,-2.2,yG),this.replayCameraPosition.y+=Math.cos(e*1.97)*k*.6,this.replayLookAt.x+=Math.sin(e*1.53)*k*.5,this.replayLookAt.y+=Math.cos(e*2.11)*k*.35}return{position:this.replayCameraPosition,lookAt:this.replayLookAt,tight:!0}}setInputLatency(e){this.inputLatencyMs=e,this.lagWarned=gr(e,this.lagWarned)}resyncClock(){this.buffer.resync()}setReconnect(e){this.reconnectMs=e}setBloodLevel(e){e!==`full`&&this.bloodLevel===`full`&&this.restoreAllInjuries(),this.bloodLevel=e,e===`off`&&this.downedPoolAccumulators.fill(0),this.effects.setBloodLevel(e)}setReducedMotion(e){e&&(this.restoreAllInjuries(),this.effects.clearDynamic())}syncInjuryPresentation(e){let t=this.arcadeInjuries[e],n=this.graphs;if(n!==null){let r=n[e];t===`head_burst`?r.boxer.setHeadBurst(!0):r.boxer.setDecapitated(t===`decapitation`),r.boxer.headInjury.setEyeOut(t===`eye_left`||t===`eye_right`?`both`:null),r.boxer.setHandDismembered(`left`,t===`dismember_left`),r.boxer.setHandDismembered(`right`,t===`dismember_right`);let i=t===`jaw_dislocation`?`jaw`:t===`shoulder_left`||t===`shoulder_right`?t:null;r.setArcadeDislocation(i)}}applyArcadeInjury(e,t,n,r){t===`dismember_left`&&!this.carnage.hasGlove(e,`left`)?t=`ribs_left`:t===`dismember_right`&&!this.carnage.hasGlove(e,`right`)?t=`ribs_right`:(t===`eye_left`&&this.carnage.eyeBurst(e,`left`)||t===`eye_right`&&this.carnage.eyeBurst(e,`right`))&&(t=`jaw_dislocation`);let i=!1;if(t===`decapitation`){let t=this.headWorldPose(e);if(t!==null){let a=this.graphs?.[e],o=a===void 0?void 0:XK(a.boxer,t.position,t.quaternion);this.effects.decapitate(e,t.position,t.quaternion,r??n.direction,n.event_id,this.skinColor(e),o);let s=this.stumpWorldPose(e);s!==null&&this.effects.anchorStump(e,s.position,s.quaternion,s.rim,s.across),i=!0}}else if(t===`head_burst`){let t=this.headWorldPose(e);if(t!==null){this.effects.burstHead(e,t.position,r??n.direction,n.event_id);let a=this.burstStumpPose(e);a!==null&&this.effects.anchorStump(e,a.position,a.quaternion,a.rim,a.across),i=!0}}else if(t===`eye_left`||t===`eye_right`){let a=this.graphs?.[e]?.boxer,o=t===`eye_left`?`left`:`right`;if(a!==void 0&&Fq(a,o,this.tmpPart,this.tmpStumpOffset,this.tmpPartQuaternion)){let t=r??n.direction;this.effects.gougeEye(e,this.tmpPart,this.tmpStumpOffset,t,n.event_id,o);let s=o===`left`?`right`:`left`;!this.effects.eyeOut(e,s)&&!this.carnage.eyeBurst(e,s)&&Fq(a,s,this.tmpPart,this.tmpStumpOffset,this.tmpPartQuaternion)&&this.effects.spawnDebris(`eye`,this.tmpPart,t,1,n.event_id,xq,e),i=!0}}else if(t===`dismember_left`||t===`dismember_right`){let a=t===`dismember_left`?`left`:`right`,o=this.handWorldPose(e,a);if(o!==null){let t=this.graphs?.[e],s=t===void 0?void 0:{...YK(t.boxer.gloveMesh(a),o.position,o.quaternion),gloveBlood:t.boxer.gloveBloodLevel};this.effects.dismemberHand(e,a,o.position,o.quaternion,r??n.direction,n.event_id,this.gearColor(e),s),this.effects.anchorHandStump(e,a,o.position,o.quaternion),i=!0}}else if(t===`jaw_dislocation`||t===`shoulder_left`||t===`shoulder_right`||t===`ribs_left`||t===`ribs_right`){let a=this.tornWound(e,wq(t));a!==null&&(this.effects.tearOpen(e,a.position,a.axis,r??n.direction,n.event_id,t===`jaw_dislocation`?bq:0),i=!0)}return i?(this.arcadeInjuries[e]=t,this.arcadeInjuryEvents[e]=n,this.observedInjuryDown[e]=!1,this.syncInjuryPresentation(e),this.onArcadeInjury?.(t,n),!0):!1}reapplyReplayInjuries(e){for(let t of[0,1]){let n=this.replayInjuries[t];if(n===null)continue;this.replayInjuries[t]=null;let r=this.settings();r.blood!==`full`||r.reducedMotion||this.applyArcadeInjury(t,n.injury,{...n.event,event_id:n.event.event_id+nq},e)}}restoreInjury(e){this.arcadeInjuries[e]!==null&&(this.arcadeInjuries[e]=null,this.arcadeInjuryEvents[e]=null,this.observedInjuryDown[e]=!1,this.syncInjuryPresentation(e),this.effects.restoreFighter(e))}restoreAllInjuries(){this.restoreInjury(0),this.restoreInjury(1),this.effects.clearArcadeGore()}headWorldPose(e){let t=this.graphs,n=t===null?null:t[e].boxer.bone(`head`);return n===null||t===null?null:(t[e].boxer.root.updateMatrixWorld(!0),n.getWorldPosition(this.tmpHead),n.getWorldQuaternion(this.tmpHeadQuaternion),this.tmpStumpOffset.copy(TK).applyQuaternion(this.tmpHeadQuaternion),this.tmpHead.add(this.tmpStumpOffset),{position:this.tmpHead,quaternion:this.tmpHeadQuaternion})}handWorldPose(e,t){let n=this.graphs,r=n===null?null:n[e].boxer.bone(t===`left`?`gloveL`:`gloveR`);return r===null||n===null?null:(n[e].boxer.root.updateMatrixWorld(!0),r.getWorldPosition(this.tmpPart),r.getWorldQuaternion(this.tmpPartQuaternion),{position:this.tmpPart,quaternion:this.tmpPartQuaternion})}gearColor(e){return this.graphs?.[e]?.boxer.gearBaseColor.getHex()??1920728}skinColor(e){return this.graphs?.[e]?.boxer.skinBaseColor.getHex()??11563071}stumpWorldPose(e){let t=this.graphs?.[e]?.boxer,n=t?.bone(`head`);if(t===void 0||n==null)return null;t.root.updateMatrixWorld(!0);let r=t.headMesh,i=OK(r.geometry);if(i.length===0)return null;this.stumpRim.length!==i.length*3&&(this.stumpRim=new Float32Array(i.length*3)),this.tmpStump.set(0,0,0);for(let[e,n]of i.entries())VK(t,n,this.tmpStumpOffset),this.tmpStumpOffset.toArray(this.stumpRim,e*3),this.tmpStump.add(this.tmpStumpOffset);return this.tmpStump.multiplyScalar(1/i.length),n.getWorldPosition(this.tmpStumpOffset).sub(this.tmpStump).normalize(),this.tmpStumpAcross.set(1,0,0).applyQuaternion(n.getWorldQuaternion(this.tmpStumpQuaternion)),this.tmpStumpQuaternion.setFromUnitVectors(EK,this.tmpStumpOffset),{position:this.tmpStump,quaternion:this.tmpStumpQuaternion,rim:this.stumpRim,across:this.tmpStumpAcross}}burstStumpPose(e){let t=this.graphs?.[e]?.boxer;if(t===void 0)return null;let n=MK(t,this.stumpRim,this.burstStump);return n===null?null:(this.stumpRim=n,{position:this.burstStump.position,quaternion:this.burstStump.quaternion,rim:n,across:this.burstStump.across})}predictAction(e){let t=this.buffer.latest();if(t===null||this.viewerId===null||this.replay!==null)return;let n=t.fighters.findIndex(e=>e.player_id===this.viewerId);if(n<0)return;let r=t.fighters[n];if(t.phase!==`fight`&&t.phase!==`finish`||!cq(r))return;let i=(this.inputLatencyMs??60)/1e3*this.simulation.tick_rate,a=i+this.buffer.interpolationDelayTicks,o=this.manualClock?this.lastManualTime:performance.now(),s=this.graphs?.[n];if(mE(e.kind)){let n=s?.ownPunchActive===!0;if(e.id===void 0||r.stamina0||!n&&ZT(r,t.tick)>0)return;let i=n?s.ownTicksToRecovery:0;n&&s.cutOwnRecovery(),this.evasion.press(e.kind,e.id,o,a,this.simulation.tick_rate,y+P(r.style).evasionTicks,o+i*1e3/this.simulation.tick_rate);return}if(e.kind!==`punch`)return;this.evasion.drop(o)&&s?.keepOwnRecovery();let c=Me(r.injuries,e.hand);c!==null&&s?.predict(c===e.hand?e:{...e,hand:c},performance.now()/1e3,this.simulation.tick_rate,a,XT(r,e,t.tick+1),i)}acknowledgeActions(e,t){for(let[n,r]of e.fighters.entries()){let i=r.player_id===this.viewerId,a=e.phase===`fight`||e.phase===`finish`;i&&this.evasion.acknowledge(r,a,this.inputSequenceOf)&&this.graphs?.[n]?.keepOwnRecovery();let o=t.filter(t=>ZW(t,e).puncherIndex===n);this.graphs?.[n]?.acknowledge(r,a,o,i?this.inputSequenceOf:null)}}push(e){if(!this.buffer.push(e,this.manualClock?this.lastManualTime:performance.now()))return;let t=this.dedupe.accept(e.events);this.acknowledgeActions(e,t),this.history.push(e),this.history.length>tG&&this.history.shift();for(let n of t){if(this.roundStats.record(n,t),n.kind===`knockdown`){let r=t.find(e=>$W(e)&&e.target_id===n.target_id&&e.tick===n.tick)??(n.detail===`body`?this.recordedHit(n):null),i=r!==null&&cr(r,e.events);this.lastKnockdown={knockdown:n,hit:r,blocked:i,finisher:i?null:lq(r,e)};let a=e.fighters.findIndex(e=>e.player_id===n.target_id);this.graphs?.[a]?.fallToKnee(n.detail===xG),n.detail===SG&&(this.lastKnockdown=null)}if(n.kind===`result`&&n.detail===`flash_ko`){let e=t.findLast(e=>(e.kind===`hit`||e.kind===`counter_hit`)&&e.actor_id===n.actor_id)??null;e!==null&&e.target_id!==null&&(this.flashKnockout={hitEventId:e.event_id,loserId:e.target_id},this.lastKnockdown={knockdown:{...e,kind:`knockdown`},hit:e,blocked:!1,finisher:null})}n.kind===`referee_break`&&this.referee?.breakClinch(),(tK.has(n.kind)||n.kind===`bleed`&&n.actor_id===`referee`)&&this.pendingRefereeEvents.push(n),n.kind===`box`&&(this.eventCallout={text:`BOX!`,until:this.frameSeconds+ZG}),n.kind===`body_collapse`&&n.target_id===this.viewerId&&(this.ownCollapseUntil=n.tick+n.amount),n.kind===`finish_him`&&(this.finishTargetId=n.target_id),(n.kind===`fatality`||n.kind===`death`)&&this.noteDeath(n,t,e),this.movement.observe(n,this.viewerId)}this.commentary.observe(e,t,this.players,this.simulation.tick_rate,this.frameSeconds);let n=e.fighters.findIndex(e=>e.player_id===this.viewerId),r=e.result===null&&!t.some(e=>e.kind===`knockdown`);for(let{event:i,presentationEvent:a,presentImpact:o,reactAmount:s}of mK(t,e)){let t=e.fighters.findIndex(e=>e.player_id===i.target_id),c=e.fighters.findIndex(e=>e.player_id===i.actor_id),{recipientIndex:l,puncherIndex:u}=ZW(i,e),d=e.fighters[l]??e.fighters[t]??e.fighters[c]??e.fighters[0];if(NK(this.graphs?.[e.fighters.indexOf(d)],d,this.mapping,this.contactPoint),JG.has(i.kind)){let t=u>=0?e.fighters[u]:null;this.pendingContacts.push({event:i,presentationEvent:a,presentImpact:o,reactAmount:s,contactTick:r&&u===n&&XG.has(i.kind)&&this.graphs?.[u]?.pressLanded(i.action_id)===!0?-1/0:t?.action_contact_tick??i.tick,recipientIndex:l,puncherIndex:u,injury:CK(i,e.fighters[l],e.result,t??void 0),power:t!==null&&t.action_id===i.action_id&&t.action_power===`power`})}else i.kind===`bleed`&&i.actor_id!==`referee`&&this.effects.addEvent(i,this.contactPoint,this.settings().reducedMotion)}for(let n of t){if(!aK.has(n.kind))continue;let t=n.action_id===null?void 0:this.pendingContacts.find(e=>e.event.tick===n.tick&&e.event.action_id===n.action_id&&($W(e.event)||eG(e.event)));t!==void 0&&(t.injury??=uK(n)),n.kind!==`fatality`&&(this.pendingGore.push({event:n,at:t?.contactTick??n.tick}),n.kind===`injury`&&pe(n.detail)&&this.carnage.expect(e.fighters.findIndex(e=>e.player_id===n.target_id),n.detail))}}fireContacts(e){for(let t=0;te){t+=1;continue}this.pendingContacts.splice(t,1);let{event:r,presentationEvent:i,reactAmount:a,recipientIndex:o,puncherIndex:s,injury:c}=n,l=n.presentImpact&&!dK(i),u=this.buffer.latest()?.fighters[o],d=QW(this.buffer.latest()?.fighters[s],u,this.mapping);this.presentFightEvent(r,o,s),l&&u!==void 0&&(this.contactOn(o,u,i.detail.endsWith(`:body`),d,i.direction),this.effects.addEvent(i,this.contactPoint,this.settings().reducedMotion,d));let f=this.settings();if(n.power&&l&&$W(r)&&u!==void 0&&!f.reducedMotion&&this.presentPowerHit(o,i),(n.presentImpact||YG.has(r.kind))&&this.arena.excite(qG[r.kind]??0),l&&o>=0&&[`hit`,`counter_hit`,`knockdown`].includes(r.kind)){let e=this.viewerId!==null&&this.buffer.latest()?.fighters[o]?.player_id===this.viewerId;this.viewerHitFlash=Math.max(this.viewerHitFlash,aq(r,e,f.blood))}c!==null&&o>=0&&this.arcadeInjuries[o]===null&&f.blood===`full`&&!f.reducedMotion&&this.applyArcadeInjury(o,c,r,d);let p=this.graphs;l&&o>=0&&!f.reducedMotion&&dB(r.kind,r.amount,i.detail.endsWith(`:head`))&&this.knockOutMouthpiece(o,d??i.direction,r.event_id,!1);let m=l&&!f.reducedMotion?oq(r):null;m!==null&&o>=0&&this.gushFromMouth(o,r.event_id,m.seconds,m.rate),n.presentImpact&&o>=0&&r.kind===`knockdown`&&!f.reducedMotion&&this.gushFromMouth(o,r.event_id,vq,yq);let h=l&&o>=0?_O(r.kind,r.amount,i.detail.endsWith(`:head`)):0;if(h>0&&!f.reducedMotion&&f.blood!==`off`){let e=this.headWorldPose(o);e!==null&&(this.mouthPoint.set(0,-.07,.1).applyQuaternion(e.quaternion).add(e.position),this.effects.spawnTeeth(this.mouthPoint,d??i.direction,h,r.event_id))}if(l&&o>=0&&a!==null&&[`hit`,`counter_hit`,`block`,`perfect_block`,`knockdown`].includes(r.kind)){let e=r.kind===`block`||r.kind===`perfect_block`,t=i.detail.endsWith(`:body`)?`body`:`head`;if(p!==null){let n=(s>=0?this.buffer.latest()?.fighters[s]:void 0)?.action_key?.split(`:`)??[],c=n[0]??i.detail.split(`:`)[0]??null,l=n[1]??null;p[o].react(e?`block`:`hit`,t,i.direction,c,l,a),$W(r)&&t===`head`&&l!==null&&this.carnage.punched(o,l===`left`?`right`:`left`,r.event_id),this.flashKnockout?.hitEventId===r.event_id&&p[o].knockOut()}}l&&s>=0&&[`hit`,`counter_hit`,`block`,`perfect_block`,`guard_break`].includes(r.kind)&&p?.[s]?.landedHit(r.action_id,r.kind===`block`||r.kind===`perfect_block`,n.power),(n.presentImpact||!$W(r))&&this.onContact?.(r,n.power===!0)}this.replay===null&&this.fireRefereeEvents(e);let t=this.refereeReplayAt;if(t!==null&&this.replay===null&&this.frameSeconds>=t.at){this.refereeReplayAt=null;let e=SW(this.history,t.impact,this.simulation.tick_rate,xW.speed,xW.before,xW.after),n=this.buffer.latest(),r=e!==null&&n!==null&&n.phase===`referee_down`&&n.phase_ticks_remaining/this.simulation.tick_rate>=e.durationSeconds-.5;e!==null&&r&&!this.settings().reducedMotion&&this.startReplay(e)}}fireGore(e){for(let t=0;te?t+=1:(this.pendingGore.splice(t,1),this.presentGore(n.event))}}presentGore(e){let t=this.buffer.latest()?.fighters,n=t?.findIndex(t=>t.player_id===(e.kind===`vomit`?e.actor_id:e.target_id))??-1;if(t===void 0||n<0)return;let r=QW(e.actor_id===e.target_id?void 0:t.find(t=>t.player_id===e.actor_id),t[n],this.mapping)??e.direction;if(e.kind===`vomit`)this.carnage.vomit(n,e.event_id),this.onGore?.({kind:`vomit`});else if(e.kind===`finish_him`)this.arena.excite(1),this.onGore?.({kind:`finish_him`});else if(e.kind===`death`)this.showDeath(n,r,!1),this.announceDeath(n);else if(e.kind===`injury`&&pe(e.detail)){let i=e.detail;if(!this.carnage.inflict(n,i,e.event_id,r))return;this.eventCallout={text:`${we(i)}!`,until:this.frameSeconds+oK},this.arena.excite(cK);let a=this.viewerId!==null&&t[n].player_id===this.viewerId;this.settings().blood!==`off`&&(this.viewerHitFlash=Math.max(this.viewerHitFlash,a?1:.5)),this.settings().reducedMotion||(this.powerShake=Math.min(rK,this.powerShake+nK)),this.onGore?.({kind:`injury`,injury:i})}}showDeath(e,t,n){let r=this.deaths[e]??null;if(r===null)return;let i=this.fatal?.index===e?this.fatal:null,a=(i?.hit.event_id??e)+(n?nq:0);i===null?r===`gutted`&&this.carnage.fatality(e,`gutting`,a,t):this.carnage.fatality(e,i.fatality,a,t),this.carnage.die(e,r)}announceDeath(e){let t=this.deaths[e]??null;if(t===null)return;let n=Oe(t);this.eventCallout={text:`${ke(t)}!`,until:this.frameSeconds+sK},this.arena.excite(1),this.settings().reducedMotion||(this.powerShake=rK),n!==null&&this.onGore?.({kind:`fatality`,fatality:n}),this.onGore?.({kind:`death`,cause:t})}noteDeath(e,t,n){let r=n.fighters.findIndex(t=>t.player_id===e.target_id);if(r!==0&&r!==1)return;let i=e.action_id===null?null:t.find(t=>$W(t)&&t.tick===e.tick&&t.action_id===e.action_id&&t.target_id===e.target_id)??null;if(e.kind===`fatality`){i!==null&&me.includes(e.detail)&&(this.fatal={index:r,fatality:e.detail,hit:i});return}let a=De(e.detail);a!==null&&(this.deaths[r]=a,i===null?this.lastKnockdown=null:(this.flashKnockout={hitEventId:i.event_id,loserId:n.fighters[r].player_id},this.lastKnockdown={knockdown:{...i,kind:`knockdown`},hit:i,blocked:!1,finisher:null}))}presentFightEvent(e,t,n){let r=iK[e.kind];r!==void 0&&(this.eventCallout={text:r.text,until:this.frameSeconds+r.seconds});let i=this.graphs;if(!(i===null||t<0)&&(e.kind===`parry`&&i[t]?.stagger(),e.kind===`body_collapse`)){let r=n>=0?this.buffer.latest()?.fighters[n]:void 0;i[t]?.windedFor(e.amount/this.simulation.tick_rate+.15,gK(r?.action_key??null))}}recordedHit(e){if(e.action_id===null)return null;for(let t=this.history.length-1;t>=0;--t){let n=this.history[t].events.find(t=>(t.kind===`hit`||t.kind===`counter_hit`)&&t.action_id===e.action_id&&t.target_id===e.target_id);if(n!==void 0)return n}return null}enterRest(e){this.restStartedAt=e,this.effects.clearMouthpieces()}contactOn(e,t,n,r,i){let a=n?null:this.headWorldPose(e),o=n?this.graphs?.[e]?.boxer.rig.bones.upperChest:void 0,s=a?.position??o?.getWorldPosition(this.contactPoint)??null;if(s===null)return NK(this.graphs?.[e],t,this.mapping,this.contactPoint);let c=r??{x:i<0?-1:1,z:0},l=n?Cq:Sq;return this.contactPoint.set(s.x-c.x*l,s.y,s.z-c.z*l)}gushFromMouth(e,t,n,r){let i=this.tornWound(e,`mouth`);i!==null&&this.effects.gush(e,i.position,i.axis,n,r,t)}anchorGush(e){if(!this.effects.gushing(e)||this.carnage.vomiting(e))return;let t=this.tornWound(e,wq(this.arcadeInjuries[e]??null));t!==null&&this.effects.anchorGush(e,t.position,t.axis)}tornWound(e,t){if(t===`mouth`){let t=this.headWorldPose(e);return t===null?null:{position:this.woundPoint.copy(gq).applyQuaternion(t.quaternion).add(t.position),axis:this.woundAxis.copy(_q).applyQuaternion(t.quaternion)}}let n=this.graphs?.[e]?.boxer;if(n===void 0)return null;n.root.updateMatrixWorld(!0);let r=n.rig.bones,i=t===`shoulder_left`||t===`ribs_left`,a=r.shoulderL.getWorldPosition(this.woundAxis).sub(r.shoulderR.getWorldPosition(this.tmpStumpOffset)).normalize().multiplyScalar(i?1:-1),o=r.upperChest.getWorldPosition(this.tmpStump),s=this.tmpStumpOffset.copy(o).sub(r.hips.getWorldPosition(this.tmpStumpAcross)).normalize();return t===`ribs_left`||t===`ribs_right`?{position:this.woundPoint.copy(o).addScaledVector(a,kq).addScaledVector(s,-.06),axis:a}:((i?r.shoulderL:r.shoulderR).getWorldPosition(this.woundPoint),{position:this.woundPoint,axis:a.addScaledVector(s,.5).normalize()})}refereeMouth(){let e=this.referee?.boxer.rig.bones.head;return e===void 0?null:(e.getWorldPosition(this.tmpHead),e.getWorldQuaternion(this.tmpHeadQuaternion),this.tmpHead.add(this.tmpStumpOffset.copy(TK).applyQuaternion(this.tmpHeadQuaternion)),{position:this.woundPoint.copy(gq).applyQuaternion(this.tmpHeadQuaternion).add(this.tmpHead),axis:this.woundAxis.copy(_q).applyQuaternion(this.tmpHeadQuaternion)})}knockOutMouthpiece(e,t,n,r){let i=this.headWorldPose(e);i!==null&&(this.mouthPoint.set(0,-.075,.1).applyQuaternion(i.quaternion).add(i.position),this.effects.ejectMouthpiece(e,this.mouthPoint,i.quaternion,t,n,this.gearColor(e),r))}get resultVisible(){return this.final!==null&&this.frameSeconds>=this.finalRevealAt}get resolutionScale(){return this.scaler.scale}get diagnostics(){let e=this.renderer.getContext(),t=e.getExtension(`WEBGL_debug_renderer_info`),n=t===null?e.getParameter(e.RENDERER):e.getParameter(t.UNMASKED_RENDERER_WEBGL);return{frameMs:this.frameMsAverage,resolutionScale:this.scaler.scale,gpu:this.memoryInfo,graphics:String(n)}}get memoryInfo(){return{geometries:this.renderer.info.memory.geometries,textures:this.renderer.info.memory.textures,programs:this.renderer.info.programs?.length??0}}applyResolutionScale(){let e=this.basePixelRatio*this.scaler.scale;this.renderer.setPixelRatio(e),this.composer.setPixelRatio(e);let t=this.scaler.scale<=nG;this.bloomPass.enabled=!t,this.keyLight!==null&&XW(this.keyLight.shadow,t,this.scaler.scale<.8?1024:2048),this.arena.setLowTier(t),this.effects.setLowTier(t)}setupLights(){let e=new gx(`#3c4a72`,`#07080c`,.55);this.scene.add(e),this.lights.push(e);let t=new Ax(`#fff1dc`,150,24,.56,.55,1.7);t.position.set(.6,7.4,1.2),t.target.position.set(0,.6,0),t.castShadow=!0,t.shadow.mapSize.set(2048,2048),t.shadow.bias=qW,t.shadow.camera.near=3,t.shadow.camera.far=14,this.keyLight=t,this.scene.add(t,t.target),this.lights.push(t);let n=new Ax(`#ffe6c8`,95,24,.6,.6,1.7);n.position.set(-2.6,7,-2.2),n.target.position.set(0,.8,0),this.scene.add(n,n.target),this.lights.push(n);for(let[e,t,n,r]of[[`#8fa8ff`,-5.5,3.8,-5.4],[`#7f95e8`,5.6,3.6,-5.6]]){let i=new Ax(e,34,30,.72,.9,1.8);i.position.set(t,n,r),i.target.position.set(0,1.2,0),this.scene.add(i,i.target),this.lights.push(i)}let r=new Ax(`#ffe8d0`,48,22,.32,.8,1.5);r.position.set(0,5.8,5.4),r.target.position.set(0,1,0),this.scene.add(r,r.target),this.lights.push(r),this.followSpot=r}draw(e,t=!1,n=!0){if(this.destroyed)return;let r=e-this.previous,i=t?1/60:Math.min(.05,Math.max(.001,r/1e3));this.previous=e,!t&&this.scaler.record(r)&&this.applyResolutionScale(),!t&&r>0&&r<1e3&&(this.frameMsAverage+=(r-this.frameMsAverage)*.05);let a=Math.min(this.pixelRatioCap,window.devicePixelRatio||1);a!==this.basePixelRatio&&(this.basePixelRatio=a,this.applyResolutionScale());let o=this.canvas.clientWidth,s=this.canvas.clientHeight;o>0&&s>0&&(this.renderer.getSize(this.sizeCheck),(this.sizeCheck.x!==o||this.sizeCheck.y!==s)&&(this.renderer.setSize(o,s,!1),this.composer.setSize(o,s),this.camera.aspect=o/s,this.portraitPull=G.clamp(1.2/this.camera.aspect,1,2.2),this.baseFov=36*Math.min(1.3,Math.sqrt(this.portraitPull)),this.camera.fov=this.baseFov,this.camera.updateProjectionMatrix()));let c=e/1e3;this.frameSeconds=c,this.finishPass.uniforms.uTime.value=c%1e3,t&&(this.lastManualTime=e);let l=this.settings();this.setBloodLevel(l.blood);let u=this.buffer.latest(),d=i,f=u?.result!==null&&u?.result!==void 0&&dr.has(u.result.finish_method);if(this.cheer(c,i),f&&!this.finishSeen&&(this.finishSeen=!0,this.finishSlowMotion=2.2,this.arena.excite(1)),this.finishSlowMotion>0&&!l.reducedMotion){this.finishSlowMotion=Math.max(0,this.finishSlowMotion-i);let e=Math.min(1,this.finishSlowMotion/.5);i*=.3+.7*(1-e)}this.viewerHitFlash=Math.max(0,this.viewerHitFlash-i*3.2);let p=u===null?0:t?_K(u):this.buffer.renderTick(e),m=this.updateRocked(u===null?null:this.shownAt(p),d,l.reducedMotion);m!==null&&u!==null&&this.onRocked?.(m,u.tick);let h=u===null?null:this.applyLocalPrediction(this.buffer.sample(p),i,e),g=this.replay;if(g!==null){let e=c-g.startedAt;e>=g.plan.durationSeconds||g.plan.impact.kind===`referee_down`&&u?.phase!==`referee_down`?this.endReplay():(p=CW(g.plan,e,this.simulation.tick_rate),h=g.buffer.sample(p)??h,!g.impactFired&&p>=g.plan.impact.tick&&h!==null&&(g.impactFired=!0,this.fireReplayImpact(h)))}let _=this.replay===null?i:i*this.replay.plan.speed,v=1.8,y=!1,b=null;if(h!==null){let e=this.replay===null?this.ceremony:null,[t,n]=e===null?this.standApart(h.fighters,_):this.ceremonyFighters(e,h.fighters,_,c,this.drawnOffsets);for(let[e,t]of h.fighters.entries())this.arcadeInjuries[e]!==null&&this.replay===null&&(t.is_downed?this.observedInjuryDown[e]=!0:this.observedInjuryDown[e]&&h.result===null&&this.restoreInjury(e));let r=this.graphs;if(r!==null){this.wearLook(0,t.player_id),this.wearLook(1,n.player_id);let e=this.headCacheValid[0]?this.headCache[0]:void 0,i=this.headCacheValid[1]?this.headCache[1]:void 0;r[0].boxer.root.visible=!0,r[1].boxer.root.visible=!0;let a=UW(h,this.simulation.tick_rate);r[0].setResting(a),r[1].setResting(a);let o=h.phase===`countdown`?h.phase_ticks_remaining:null;r[0].setCountdown(o),r[1].setCountdown(o);let s=this.replay!==null||h.phase===`complete`;r[0].stayDown(s),r[1].stayDown(s),h.phase===`fight`&&this.lastPhase===`rest`&&this.replay===null&&(this.roundCalloutUntil=c+rG,this.roundCalloutRound=h.round_number),h.phase===`rest`&&this.lastPhase!==`rest`&&this.enterRest(c),this.lastPhase=h.phase,this.anticipatePunches(u,p),r[0].setObstacle(r[1].boxer.root.position.x,r[1].boxer.root.position.z),r[1].setObstacle(r[0].boxer.root.position.x,r[0].boxer.root.position.z);let d=this.referee?.boxer.rig.bones.head.getWorldPosition(this.refereeHead)??null;r[0].setRefereeHead(d),r[1].setRefereeHead(d),r[0].update(t,n,_,c,l.reducedMotion,l.blood,p,i),r[1].update(n,t,_,c,l.reducedMotion,l.blood,p,e);let f=h.phase===`finish`?Er(h.fighters,this.finishTargetId):null;for(let[e,t]of h.fighters.entries()){let n=f!==null&&t.player_id===f.player_id;r[e].setDazed(n),this.carnage.sync(e,(this.replay===null?void 0:u?.fighters[e])??t,l,_,c,n)}let m=r[h.fighters.findIndex(e=>e.player_id===this.viewerId)],g=m?.ownPressId??null;if(m!==void 0&&g!==null&&g!==this.soundedPress){this.soundedPress=g;let{punchClass:e,power:t}=m.punchKind;this.onOwnPunch?.(e,t,g)}for(let[e,t]of r.entries()){let n=t.boxer.bone(`head`);n!==null&&(t.boxer.root.updateMatrixWorld(!0),n.getWorldPosition(this.headCache[e]),this.headCacheValid[e]=!0);let r=t.fallBody!==null;r&&!this.fallingLive[e]&&this.replay===null&&(this.liveFallTicks[e]=p),this.fallingLive[e]=r}}for(let e=0;ee.player_id===this.viewerId),C=l.camera===`fighter`&&S>=0&&HW(h)?this.fighterCam.update(i,c,S===0?this.tmpA:this.tmpB,S===0?this.tmpB:this.tmpA,this.effects.shakeAmount+this.powerShake,l.reducedMotion,this.camera.aspect):null;C===null&&this.fighterCam.reset();let w=this.replay,T=this.cameraOverride??(w!==null&&h!==null?this.replayFrame(h,c-w.startedAt):this.closeUpFrame(c)??this.raiseFrame(c,i,l.reducedMotion)??this.cornerShotFrame(c,h,l.reducedMotion)??this.restWideFrame(h)??this.ceremonyFrame(c)??C??x);this.ownViewActive=C!==null&&T===C;let E=this.ownViewActive?this.baseFov*kD:this.baseFov;if(this.camera.fov!==E&&(this.camera.fov=E,this.camera.updateProjectionMatrix()),this.cameraOverride===null&&this.portraitPull>1&&T.framed!==!0&&!this.ownViewActive){let e=T.tight===!0,t=this.portraitPull/Math.min(1.3,Math.sqrt(this.portraitPull)),n=e?Math.min(t,1.25):t;this.tmpCamera.subVectors(T.position,T.lookAt).multiplyScalar(n),this.camera.position.copy(T.lookAt).add(this.tmpCamera),e&&(this.camera.position.x=G.clamp(this.camera.position.x,-2.2,yG),this.camera.position.z=G.clamp(this.camera.position.z,-2.2,yG)),this.camera.lookAt(T.lookAt.x,T.lookAt.y-(this.portraitPull-1)*(e?.08:.45),T.lookAt.z)}else this.camera.position.copy(T.position),this.camera.lookAt(T.lookAt);this.effects.setViewDistance(this.camera.position.distanceTo(T.lookAt)),this.arena.makeRoomForCamera(this.camera.position);let D=T===x?BP(Math.max(this.tmpA.z,this.tmpB.z)):T.framed===!0?zG:1;this.ring.setNearRopeOpacity(this.ring.nearRopeOpacity()+(D-this.ring.nearRopeOpacity())*(1-Math.exp(-6*i))),n&&(this.composer.render(),this.drawHudOverlay(h)),!this.destroyed&&!this.manualClock&&(this.raf=requestAnimationFrame(e=>this.draw(e)))}applyLocalPrediction(e,t,n){if(e===null||this.localInput===null||this.viewerId===null)return e;let r=e.fighters.findIndex(e=>e.player_id===this.viewerId),i=this.localInput()??{moveX:0,moveY:0,defense:`none`},a=(this.inputLatencyMs??60)/1e3*this.simulation.tick_rate+this.buffer.interpolationDelayTicks,o=this.ownCollapseUntil>e.tick,s=e.phase===`fight`||e.phase===`finish`&&r>=0&&Er(e.fighters,this.finishTargetId)!==e.fighters[r],c=r>=0&&s&&!o?e.fighters[r]:null,l=this.evasion.holdsFeet(n)?0:this.graphs?.[r]?.ownFootwork??1,u=this.movement.update(c,i,l,n,a,e.tick,t,this.simulation.tick_rate),d=this.evasion.pose(n);if(r<0)return e;let f=e.fighters[r],p=c===null?f.defense:hE(c,i,d,this.evasion.hidesServerEvasion(n));if(Math.abs(u.dx)<.01&&Math.abs(u.dy)<.01&&p===f.defense)return e;let m=pE(f,u,e.fighters[+(r===0)]??null),h={...f,x:f.x+m.dx,y:f.y+m.dy,defense:p},g=r===0?[h,e.fighters[1]]:[e.fighters[0],h];return{...e,fighters:g}}anticipatePunches(e,t){if(!(this.replay!==null||e===null||e.phase!==`fight`&&e.phase!==`finish`))for(let[n,r]of(this.graphs??[]).entries()){let i=e.fighters[n];i!==void 0&&!i.is_downed&&r.anticipate(i,i.action_start_tick-t)}}cheer(e,t){ee.clinch_ticks>0||e.clinch_startup_ticks>0||e.is_downed)?null:RK(n.x,n.y,r.x,r.y,DG,u-f,d-f,S),[a,o]=this.drawnTargets;a.x=i===null?0:i.ax-n.x,a.y=i===null?0:i.ay-n.y,o.x=i===null?0:i.bx-r.x,o.y=i===null?0:i.by-r.y,this.clearOfTheFallen(e);let s=1-Math.exp(-14*t);for(let e of[0,1]){let n=this.drawnOffsets[e],r=this.drawnTargets[e],i=r.x-n.x,a=r.y-n.y;if(this.drawnOffsetsLive){i*=s,a*=s;let e=Math.hypot(i,a);e>OG*t&&(i*=OG*t/e,a*=OG*t/e)}n.x+=i,n.y+=a}return this.drawnOffsetsLive=!0,[this.drawnAt(0,n),this.drawnAt(1,r)]}drawnAt(e,t){let n=this.drawnOffsets[e];if(Math.abs(n.x)<.01&&Math.abs(n.y)<.01)return t;let r=fE(t.x+n.x,t.y+n.y);return Object.assign(this.drawnFighters[e],t,{x:r.x,y:r.y})}clearOfTheFallen(e){for(let t of[0,1]){let n=this.graphs?.[t]?.fallBody??null,r=+(t===0),i=e[r];if(n===null||i.is_downed||(this.graphs?.[r]?.fallBody??null)!==null)continue;let a=this.drawnTargets[r],o=this.mapping.x(i.x+a.x),s=this.mapping.z(i.y+a.y),c=this.clearOf(n,o,s);a.x+=(c.x-o)/this.mapping.x(1),a.y+=(c.z-s)/this.mapping.z(1);return}}clearOf(e,t,n){let r={x:t,z:n};for(let t of[0,1,2,3,4])e.bodyPoint(t,this.bodyPoint),r=PK(r.x,r.z,this.bodyPoint.x,this.bodyPoint.z,wG);let i=this.insideRopes(r.x,r.z);if(Math.hypot(i.x-r.x,i.z-r.z)<1e-6)return r;let a=t=>[0,1,2,3,4].every(n=>(e.bodyPoint(n,this.bodyPoint),Math.hypot(t.x-this.bodyPoint.x,t.z-this.bodyPoint.z)>=.499999));for(let e=kG;e<=2.000000001;e+=kG)for(let[t,n]of[[1,0],[-1,0],[0,1],[0,-1]]){let r=this.insideRopes(i.x+t*e,i.z+n*e);if(a(r))return r}return i}insideRopes(e,t){let n=fE(e/this.mapping.x(1),t/this.mapping.z(1));return{x:this.mapping.x(n.x),z:this.mapping.z(n.y)}}headHeightOf(e){return(this.graphs?.[e]?.boxer.metrics.headRestY??1.52)+.04}bleed(e,t,n){for(let[r,i]of e.entries()){let e=Eq(i,this.graphs?.[r],this.flashKnockout?.loserId),a=this.arcadeInjuries[r]??null,o=a!==null,s=(i.trauma.bleeding+i.trauma.left_cut+i.trauma.right_cut)/380,c=o?Math.max(s,fq):s;if(c>.05&&!e)this.downedPoolAccumulators[r]=0,this.downedPoolCounts[r]=0,this.effects.drip(this.dripPoint(r),c,n.reducedMotion,r);else if(c>uq&&e&&n.blood!==`off`){this.effects.stopDrip(r),this.downedPoolAccumulators[r]+=t*5*(o?pq:1);let e=this.poolSource(r,a);for(;this.downedPoolAccumulators[r]>=1;){--this.downedPoolAccumulators[r];let t=this.downedPoolCounts[r];this.downedPoolCounts[r]=t+1;let n=Tq(t,c,o?mq:dq),i=t*2.399963+r*Math.PI;this.effects.pool(e.x+Math.sin(i)*n*.25,e.z+Math.cos(i)*n*.25,n,t+r*7)}}else this.effects.stopDrip(r),this.downedPoolAccumulators[r]=0,e||(this.downedPoolCounts[r]=0)}}dripPoint(e){let t=this.headWorldPose(e);if(t!==null)return t.position.add(this.tmpStumpOffset.copy(hq).applyQuaternion(t.quaternion));if(this.headCacheValid[e])return this.tmpHead.copy(this.headCache[e]);let n=e===0?this.tmpA:this.tmpB;return this.tmpHead.set(n.x,this.headHeightOf(e),n.z)}poolSource(e,t){if(t===`dismember_left`||t===`dismember_right`){let n=this.handWorldPose(e,t===`dismember_left`?`left`:`right`);if(n!==null)return n.position}let n=wq(t);if(n!==`mouth`){let t=this.tornWound(e,n);if(t!==null)return t.position}return this.headCacheValid[e]?this.headCache[e]:e===0?this.tmpA:this.tmpB}updateBlobShadows(){let e=[this.tmpA,this.tmpB,this.refereePosition];for(let[t,n]of this.blobShadows.entries()){n.visible=t>=2||!this.carnage.gibbed(t);let r=t<2?this.graphs?.[t]:this.referee??void 0,i=r?.fallBody?.centre(this.bodyPoint)??null??(r?.boxer.root.visible===!0?r.currentRoot:e[t]);n.position.x=i.x,n.position.z=i.z;let a=t<2?this.buffer.latest()?.fighters[t]:void 0,o=t<2?a!==void 0&&Eq(a,r,this.flashKnockout?.loserId):r?.isDown===!0;n.scale.set(o?2.1:1.25,o?.9:.85,1)}}updateReferee(e,t,n,r){let i=this.referee;if(i===null)return;let a=this.replay===null||this.replay.plan.impact.kind===`referee_down`;i.boxer.root.visible=a;let o=this.blobShadows[2];o!==void 0&&(o.visible=a);let s=n?.referee??null,c=this.replay!==null&&this.replay.plan.impact.kind===`referee_down`?this.replay:null;!this.refereePlaced&&s!==null&&(this.refereePlaced=!0,this.refereePosition.set(this.mapping.x(s.x),0,this.mapping.z(s.y)));let l=this.refereeReplayAt!==null||this.pendingRefereeEvents.some(e=>e.kind===`referee_down`);s?.alive===!0&&i.isDown&&this.replay===null&&n?.phase!==`referee_down`&&!l&&i.resetTransient(!1),s===null||s.alive||i.isDown||this.replay!==null||l||(this.refereePosition.set(this.mapping.x(s.x),0,this.mapping.z(s.y)),i.knockOut(),this.refereeFallUnseen=!0);let u=s!==null&&(n?.phase===`fight`&&s.alive||c!==null&&!c.impactFired)?s:null,d=s?.alive===!1&&(c===null||c.impactFired),f=n?.fighters.find(e=>e.is_downed)??(n?.phase===`knockdown`?n.fighters.find(e=>e.player_id===this.lastKnockdown?.knockdown.target_id):void 0)??null,p=n?.fighters.some(e=>e.clinch_ticks>0||e.clinch_startup_ticks>0)??!1,m=f===null&&i.breaking,h=f===null?void 0:this.graphs?.[n?.fighters.indexOf(f)??-1],g=h?.fallBody?.centre(this.bodyPoint)??null,_=f!==null&&!f.is_downed?h?.currentRoot??null:null,v=f===null?(this.tmpA.x+this.tmpB.x)/2:g?.x??_?.x??this.mapping.x(f.x),y=f===null?(this.tmpA.z+this.tmpB.z)/2:g?.z??_?.z??this.mapping.z(f.y),b=this.refereeAway.set(this.refereePosition.x-v,0,this.refereePosition.z-y);if(b.lengthSq()<.01&&b.set(0,0,-1),b.normalize(),m){let e=this.tmpB.z-this.tmpA.z,t=this.tmpA.x-this.tmpB.x,n=Math.hypot(e,t),r=e*b.x+t*b.z>=0?1:-1;n>.01&&b.set(e/n*r,0,t/n*r)}let{standoff:x,clearance:S}=Iq(f!==null,p,m),C=G.clamp(v+b.x*x,-2.4,2.4),w=G.clamp(y+b.z*x,-2.4,2.4),T=this.refereePosition.x,E=this.refereePosition.z,D=this.replay===null&&this.ceremony?.positions!==null?this.ceremony:null,O=!d&&D===null&&this.replay===null&&this.stoppageWinner>=0&&this.frameSeconds>=this.stoppageRaiseAt?this.stoppageWinner===0?this.tmpA:this.tmpB:null,k=O===null?null:this.stoppageSpot??=this.raiseSpot(O,this.stoppageWinner===0?this.tmpB:this.tmpA),A=k!==null&&k.x<0?-1:1;if(d)D!==null&&(D.refereeArrived=!0);else if(O!==null&&k!==null){let t=WG(this.refereePosition.x,this.refereePosition.z,{x:O.x+k.x,y:O.z+k.z},VG*e);this.refereePosition.x=t.x,this.refereePosition.z=t.y}else if(D!==null){let t=WG(this.refereePosition.x,this.refereePosition.z,{x:RG.x,y:RG.z},VG*e);this.refereePosition.x=t.x,this.refereePosition.z=t.y,D.refereeArrived=t.arrived}else if(u!==null){let t=c===null?1-Math.exp(-20*e):1;this.refereePosition.x+=(this.mapping.x(u.x)-this.refereePosition.x)*t,this.refereePosition.z+=(this.mapping.z(u.y)-this.refereePosition.z)*t}else{let t=1-Math.exp(-(m?8:1.6)*e),n=m?Math.min(1,jG*e/Math.max(1e-6,Math.hypot(C-this.refereePosition.x,w-this.refereePosition.z)*t)):1;this.refereePosition.x+=(C-this.refereePosition.x)*t*n,this.refereePosition.z+=(w-this.refereePosition.z)*t*n}let j=O===null?D===null?u!==null||d?0:S:D.refereeArrived?0:LG:fG*.85;for(let e of j>0?[this.tmpA,this.tmpB]:[]){let t=this.refereePosition.x-e.x,n=this.refereePosition.z-e.z,r=Math.hypot(t,n);r.001&&(this.refereePosition.x=e.x+t/r*j,this.refereePosition.z=e.z+n/r*j)}for(let e of D!==null||d?[]:this.graphs??[]){let t=e.fallBody;if(t!==null)for(let e of[0,1,2,3,4]){t.bodyPoint(e,this.bodyPoint);let n=PK(this.refereePosition.x,this.refereePosition.z,this.bodyPoint.x,this.bodyPoint.z,CG);this.refereePosition.x=n.x,this.refereePosition.z=n.z}}for(let e of d?[]:[0,1]){if(!this.effects.severedHeadPosition(e,this.closeUpTarget))continue;let t=PK(this.refereePosition.x,this.refereePosition.z,this.closeUpTarget.x,this.closeUpTarget.z,bG);this.refereePosition.x=t.x,this.refereePosition.z=t.z}if(c===null&&!d){let t=this.refereePosition.x-T,n=this.refereePosition.z-E,r=Math.hypot(t,n),i=eK*e;r>i&&(this.refereePosition.x=T+t/r*i,this.refereePosition.z=E+n/r*i)}e>0&&this.refereeVelocity.set((this.refereePosition.x-T)/e,0,(this.refereePosition.z-E)/e);let ee=O!==null&&k!==null&&Math.hypot(this.refereePosition.x-O.x-k.x,this.refereePosition.z-O.z-k.z)<=mG,M=D!==null&&!D.refereeArrived,te=O===null?D===null?u===null?Math.atan2(v-this.refereePosition.x,y-this.refereePosition.z):Math.atan2(u.facing_x,-u.facing_y):M?Math.atan2(RG.x-this.refereePosition.x,RG.z-this.refereePosition.z):0:ee?0:Math.atan2(O.x-this.refereePosition.x,O.z-this.refereePosition.z);if(O!==null){let e=this.graphs?.[this.stoppageWinner]?.boxer.rig.bones,t=n?.fighters[this.stoppageWinner]?.injuries??[],r=lK(t,`left`),a=!ee||e===void 0?null:r&&lK(t,`right`)?this.nearerGlove(e.gloveL,e.gloveR):(r?e.gloveL:e.gloveR).getWorldPosition(this.stoppageWrist);i.raise(A<0?a:null,A>0?a:null)}let ne=((te-this.refereeYaw+Math.PI)%(Math.PI*2)+Math.PI*2)%(Math.PI*2)-Math.PI;this.refereeYaw+=ne*(1-Math.exp(-(m?8:3)*e));let re=Lq(this.refereePosition,this.refereeYaw,this.refereeVelocity,this.mapping,s);i.setRefereeCount(f!==null,f?.get_up_count??0),i.aimBreak(this.tmpA,this.tmpB);let ie=this.settings();if(i.update(re.self,re.focus,e,t,ie.reducedMotion,ie.blood,r),this.refereeFallUnseen&&(this.refereeFallUnseen=!1,i.fallBody?.settle()),this.effects.gushing(2)){let e=this.refereeMouth();e!==null&&this.effects.anchorGush(2,e.position,e.axis)}this.poolUnderReferee(s?.alive===!1,d,e,ie.blood)}poolUnderReferee(e,t,n,r){if(!e&&this.replay===null&&(this.refereePoolAccumulator=0,this.refereePoolCount=0),!t||r===`off`||this.referee===null)return;this.refereePoolAccumulator+=n*5*pq;let i=this.referee.boxer.rig.bones.head.getWorldPosition(this.refereeHead);for(;this.refereePoolAccumulator>=1;){--this.refereePoolAccumulator;let e=this.refereePoolCount,t=Tq(e,fq,mq);if(t>=mq)return;this.refereePoolCount=e+1;let n=e*2.399963;this.effects.pool(i.x+Math.sin(n)*t*.25,i.z+Math.cos(n)*t*.25,t,e+14)}}updateTrails(e,t){let n=this.graphs;if(!(n===null||this.trails.length<4)){for(let[r,i]of n.entries())for(let[n,a]of[`gloveL`,`gloveR`].entries()){let o=this.trails[r*2+n],s=this.glows[r*2+n];if(!i.boxer.root.visible||!this.carnage.hasGlove(r,n===0?`left`:`right`)){o.reset(),s?.reset();continue}i.boxer.rig.bones[a].getWorldPosition(this.trailGlove);let c=i.powerHeat(n===0?`left`:`right`);o.update(this.trailGlove,e,this.camera.position,!t&&this.replay===null&&!i.isDown,c),s?.update(this.trailGlove,c,e,t,this.camera)}for(let t of this.impactFlashes)t.update(e,this.camera);this.powerShake*=.02**e}}presentPowerHit(e,t){let n=!t.detail.endsWith(`:body`)&&this.headCacheValid[e]===!0?this.headCache[e]:void 0;n===void 0?this.powerHitPoint.set(this.contactPoint.x,t.detail.endsWith(`:body`)?1.05:1.55,this.contactPoint.z):this.powerHitPoint.copy(n),this.impactFlashes[e]?.fire(this.powerHitPoint),this.powerShake=Math.min(rK,this.powerShake+nK)}updateCornermen(e,t,n,r){let i=this.cornermen;if(i===null)return;let a=UW(n,this.simulation.tick_rate);for(let[n,o]of i.entries()){let i=n===0?-1:1,s=a?AG:vG;this.cornermanPosition.set(i*s,0,-i*s);let c=n===0?3*Math.PI/4:-Math.PI/4;o.attend(a);let l=Lq(this.cornermanPosition,c,this.cornermanVelocity,this.mapping);o.update(l.self,l.focus,e,t,!1,`off`,r)}}updateCutmen(e,t,n,r){let i=this.cutmen,a=this.graphs;if(i===null||a===null)return;let o=n?.phase===`rest`,s=this.mapping.x(l);for(let[c,l]of i.entries()){let i=c===0?-1:1,u=o&&a[c].stoolVisible?1:0,d=this.cutmanProgress[c],f=d+Math.sign(u-d)*Math.min(Math.abs(u-d),e/MG);this.cutmanProgress[c]=f;let p=l.boxer.root.visible;if(l.boxer.root.visible=f>.005,!l.boxer.root.visible)continue;this.cutmanFrom.set(i*vG,0,-i*2.42),bD(c===0?0:1,s,_D,32,this.cutmanTo);let m=f*f*(3-2*f);this.cornermanPosition.copy(this.cutmanFrom).lerp(this.cutmanTo,m);let h=this.cutmanLast[c];p||h.copy(this.cornermanPosition),this.cornermanVelocity.copy(this.cornermanPosition).sub(h).divideScalar(Math.max(e,.001)),h.copy(this.cornermanPosition);let g=f>.02&&f=NG?_===null?Math.atan2(i,-i):Math.atan2(_.x-this.cutmanTo.x,_.z-this.cutmanTo.z):Math.atan2(-this.cutmanFrom.x,-this.cutmanFrom.z),y=hK(n?.fighters[c]);if(f>=NG&&_!==null){let e=a[c].boxer.root.rotation.y;this.cutmanFacing.set(Math.sin(e),0,Math.cos(e)),this.cutmanEye.copy(_).addScaledVector(this.cutmanFacing,.09),this.cutmanEye.x+=Math.cos(e)*y.side*y.lateral,this.cutmanEye.z-=Math.sin(e)*y.side*y.lateral,this.cutmanEye.y+=y.lift,l.treat(this.cutmanEye,this.cutmanFacing,y.side,y.prop)}else l.treat(null);let b=Lq(this.cornermanPosition,v,this.cornermanVelocity,this.mapping);l.update(b.self,b.focus,e,t,!1,`off`,r)}}drawHudOverlay(e){let t=VW(this.hudCanvas);if(t===null)return;let{context:n,viewport:r}=t;if(this.hudViewport.width=r.width,this.hudViewport.height=r.height,n.clearRect(0,0,r.width,r.height),e===null)return;let i=this.settings();if(this.viewerHitFlash>.01&&!i.reducedMotion){let e=n.createRadialGradient(r.width/2,r.height/2,r.width*.12,r.width/2,r.height/2,r.width*.7);e.addColorStop(0,`rgba(255,235,225,${(this.viewerHitFlash*.18).toFixed(3)})`),e.addColorStop(1,`rgba(140,0,10,${(this.viewerHitFlash*.55).toFixed(3)})`),n.fillStyle=e,n.fillRect(0,0,r.width,r.height)}let a=sq(Math.max(...e.fighters.map(e=>e.trauma.head+e.trauma.body)),i.blood);if(a>0){let e=n.createRadialGradient(r.width/2,r.height/2,r.width*.2,r.width/2,r.height/2,r.width*.72);e.addColorStop(0,`rgba(90,0,8,0)`),e.addColorStop(1,`rgba(75,0,8,${a.toFixed(3)})`),n.fillStyle=e,n.fillRect(0,0,r.width,r.height)}i.reducedMotion||this.effects.drawLens(n,r.width,r.height);let o=this.deaths[0]??this.deaths[1],s=this.replay===null?null:this.replay.plan.impact.kind===`referee_down`?`REFEREE DOWN`:o===null?`KNOCKOUT REPLAY`:Oe(o)===null?`DEATH REPLAY`:`FATALITY REPLAY`;Fr(n,r.width,r.height,e,this.players,this.viewerId,this.frameSeconds>=this.finalRevealAt?this.final:null,this.reconnectMs,this.simulation.tick_rate,this.roundStats,s,this.lagWarned?this.inputLatencyMs:null,this.frameSecondsthis.avatars.get(e),this.lastKnockdown?.knockdown.target_id??null,this.touchControls&&e.fighters.some(e=>e.player_id===this.viewerId),this.powerHeld?.()===!0,o,this.finishTargetId,!i.reducedMotion),this.drawCaption(n,r.width,r.height,e)}updateRocked(e,t,n){let r=e?.fighters.find(e=>e.player_id===this.viewerId),i=e===null||this.replay!==null||this.final!==null?0:_W(r,e.phase),a=this.rocked.update(n?0:i,t);return this.finishPass.uniforms.uRocked.value=n?0:a,r===void 0?null:i}shownAt(e){for(let t=this.history.length-1;t>=0;--t)if(this.history[t].tick<=e)return this.history[t];return null}drawCaption(e,t,n,r){let i=this.final!==null&&this.frameSeconds>=this.finalRevealAt?this.final:null;i!==null&&!this.resultAnnounced&&(this.resultAnnounced=!0,this.commentary.resultShown(this.frameSeconds));let a=this.commentary.current(this.frameSeconds),o=this.settings(),s=a===null||!o.commentary?``:a.line.text;if(s!==this.captionText&&(this.captionText=s,this.hudCanvas.dataset.caption=s),a===null||!o.commentary)return;let c=r.fighters.find(e=>e.player_id===this.viewerId),l=Vn(t,n),u=i===null?null:BK(i,t,n,r.fighters,this.players,this.roundStats,this.viewerId,this.deaths[0]??this.deaths[1])/l,d=this.frameSeconds0});p!==null&&(e.save(),e.scale(l,l),XD(e,a,p,o.reducedMotion),e.restore())}destroy(){if(!this.destroyed){if(this.destroyed=!0,cancelAnimationFrame(this.raf),this.raf=0,this.buffer.clear(),this.dedupe.reset(),this.pendingContacts.length=0,this.pendingGore.length=0,this.carnage.dispose(),this.effects.dispose(),this.avatars.dispose(),this.arena.dispose(),iF(this.ring),this.graphs!==null){for(let e of this.graphs)this.scene.remove(e.boxer.root),e.dispose();this.graphs=null}this.referee!==null&&(this.scene.remove(this.referee.boxer.root),this.referee.dispose(),this.referee=null);for(let e of this.trails)this.scene.remove(e.mesh),e.dispose();this.trails=[];for(let e of this.glows)this.scene.remove(e.mesh),e.dispose();this.glows=[];for(let e of this.impactFlashes)this.scene.remove(e.group),e.dispose();if(this.impactFlashes=[],this.glowMap?.dispose(),this.glowMap=null,this.cornermen!==null){for(let e of this.cornermen)this.scene.remove(e.boxer.root),e.dispose();this.cornermen=null}if(this.cutmen!==null){for(let e of this.cutmen)this.scene.remove(e.boxer.root),e.dispose();this.cutmen=null}for(let e of this.lights)this.scene.remove(e);this.keyLight?.shadow.map?.dispose(),this.keyLight?.shadow.dispose(),this.blobTexture.dispose();for(let e of this.blobShadows)this.scene.remove(e),e.geometry.dispose(),e.material.dispose();this.renderer.renderLists.dispose(),GW(this.composer),this.bloomPass.materialHighPassFilter.dispose(),hF(),this.renderer.dispose(),this.hudCanvas.remove()}}},zq=[`broadcast`,`close`,`fighter`],Bq=`hands.preferences.v1`,Vq={length:0,clear:()=>void 0,getItem:()=>null,key:()=>null,removeItem:()=>void 0,setItem:()=>void 0},Hq=()=>{try{return window.localStorage}catch{return Vq}},Uq=()=>({volume:.7,haptics:!0,reducedMotion:window.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches??!1,blood:`full`,commentary:!0,announcer:!0,camera:`broadcast`});function Wq(e=Hq()){let t=Uq();try{let n=JSON.parse(e.getItem(Bq)??`null`);if(typeof n!=`object`||!n||Array.isArray(n))return t;let r=n;return{volume:typeof r.volume==`number`&&Number.isFinite(r.volume)?Math.max(0,Math.min(1,r.volume)):t.volume,haptics:typeof r.haptics==`boolean`?r.haptics:t.haptics,reducedMotion:typeof r.reducedMotion==`boolean`?r.reducedMotion:t.reducedMotion,blood:r.blood===`reduced`||r.blood===`off`||r.blood===`full`?r.blood:t.blood,commentary:typeof r.commentary==`boolean`?r.commentary:t.commentary,announcer:typeof r.announcer==`boolean`?r.announcer:t.announcer,camera:zq.includes(r.camera)?r.camera:t.camera}}catch{return t}}function Gq(e,t=Hq()){try{t.setItem(Bq,JSON.stringify({volume:Math.max(0,Math.min(1,e.volume)),haptics:e.haptics,reducedMotion:e.reducedMotion,blood:e.blood,commentary:e.commentary,announcer:e.announcer,camera:e.camera}))}catch{}}var Kq=class{value;listeners=new Set;constructor(e=Hq()){this.storage=e,this.value=Wq(e)}storage;get current(){return this.value}update(e){this.value={...this.value,...e},Gq(this.value,this.storage);for(let e of this.listeners)e(this.value)}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}destroy(){this.listeners.clear()}},qq={stage:`bootstrapping`,player:null,playerId:null,role:null,players:{},playerOrder:[],simulation:null,snapshot:null,final:null,select:null,serverTick:0,nextSequence:0,reconnectMs:0,safeError:null},Jq=e=>Object.fromEntries(e.map(e=>[e.id,e]));function Yq(e,t){if(t.type===`bootstrap`)return{...e,stage:`authorizing`,simulation:t.simulation,safeError:null};if(t.type===`authorized`)return{...e,stage:`connecting`,player:t.player,safeError:null};if(t.type===`connecting`)return{...e,stage:`connecting`};if(t.type===`reconnect-tick`)return{...e,stage:`paused`,reconnectMs:Math.max(0,t.remainingMs)};if(t.type===`fatal`)return{...e,stage:`fatal`,safeError:t.code,reconnectMs:0};let n=t.message;switch(n.type){case`welcome`:return{...e,playerId:n.role===`fighter`?n.player_id:null,role:n.role,players:Jq(n.players),playerOrder:n.players.map(e=>e.id),serverTick:n.server_tick,nextSequence:n.role===`fighter`?n.next_sequence:0,safeError:null};case`ticket`:return e;case`waiting`:return{...e,stage:`waiting`,select:null};case`select`:return{...e,stage:`select`,select:n,players:Jq(n.players),playerOrder:n.players.map(e=>e.id)};case`ready`:return{...e,stage:e.snapshot?.phase??`countdown`,select:null,players:Jq(n.players),playerOrder:n.players.map(e=>e.id)};case`paused`:return{...e,stage:`paused`,reconnectMs:n.grace_ms};case`resumed`:return{...e,stage:e.snapshot?.phase??`countdown`,reconnectMs:0};case`snapshot`:return{...e,stage:n.payload.phase,snapshot:n.payload,serverTick:Math.max(e.serverTick,n.payload.tick)};case`final`:return{...e,stage:`complete`,final:n,reconnectMs:0};case`error`:return{...e,stage:`fatal`,safeError:n.code,reconnectMs:0}}}var Xq=new Set([`hit`,`counter_hit`,`block`,`perfect_block`,`guard_break`,`knockdown`,`parry`,`body_collapse`,`eye_shut`,`referee_hit`,`referee_down`]),Zq=11e3,Qq=1500,$q=4e3,eJ=3e3,tJ=6,nJ=5e3,rJ=[{level:`rookie`,label:`Rookie`,detail:`Slow hands, leaves openings`},{level:`contender`,label:`Contender`,detail:`Works the body, punishes mistakes`},{level:`champion`,label:`Champion`,detail:`Slips, counters, finishes`}],iJ=e=>Mt.includes(e),aJ=class{root;reloadPage;authorizer;state=qq;settings=new Kq;input=new pf;audio=new _i(()=>this.settings.current);haptics=new Rd(()=>this.settings.current);voice=new Zr(()=>this.settings.current);feedbackEvents=new Df;soundedPunches=[];renderer=null;network=null;session=null;abort=new AbortController;destroyed=!1;generation=0;reloadOnRetry=!1;reloading=!1;canvas;status;overlay;roleIndicator;controlsButton;controlsPanel;retry;rematchButton;hint;cpuPicker;cpuPrompt;cpuLevel=null;rematchOpponent=null;lastPhase=null;cpuRematchLevel=null;cpuRematch=null;cpuRematchTimer=null;diagnosticsTimer=null;finalReceivedAt=0;lastFinalMatchId=null;rematchAttempts=0;rematchTimer=null;rematchCountdownTimer=null;resultRevealTimer=null;resultWaitTimer=null;completeSince=null;summaryClock=new or;fightSummary;liveFightStatus;finalSummary;corner;stylePicker;constructor(e,t=()=>window.location.reload(),n=new _d){this.root=e,this.reloadPage=t,this.authorizer=n,e.innerHTML=`
HANDStwo-player boxing

`,this.canvas=e.querySelector(`canvas`),this.status=e.querySelector(`[data-status]`),this.overlay=e.querySelector(`[data-overlay]`),this.roleIndicator=e.querySelector(`[data-role]`),this.controlsButton=e.querySelector(`[data-controls]`),this.controlsPanel=e.querySelector(`[data-controls-panel]`),this.retry=e.querySelector(`[data-retry]`),this.rematchButton=e.querySelector(`[data-rematch]`),this.hint=e.querySelector(`[data-hint]`),this.cpuPicker=e.querySelector(`[data-cpu]`),this.cpuPrompt=e.querySelector(`[data-cpu-prompt]`),this.cpuPicker.addEventListener(`click`,this.onCpuPick),this.rematchButton.addEventListener(`click`,this.onRematch),this.fightSummary=e.querySelector(`[data-fight-summary]`),this.liveFightStatus=e.querySelector(`[data-fight-status]`),this.finalSummary=e.querySelector(`[data-final]`),this.retry.addEventListener(`click`,this.onRetry),this.bindPanels(),this.syncSettings(),this.input.attachTouch(e.querySelector(`.activity`)),this.corner=new kd(e.querySelector(`.activity`),e=>this.network?.sendCornerChoice(e)??!1),this.stylePicker=new Xt(e.querySelector(`.activity`),(e,t)=>this.network?.chooseStyle(e,t)??!1),this.input.setViewForward(()=>this.renderer?.viewForward()??null),window.addEventListener(`keydown`,this.onCameraKey)}onCameraKey=e=>{if(e.code!==`KeyK`||e.repeat||e.ctrlKey||e.metaKey||e.altKey)return;let t=e.target;if(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement)return;e.preventDefault();let n=zq[(zq.indexOf(this.settings.current.camera)+1)%zq.length];this.settings.update({camera:n}),this.root.querySelector(`[data-camera]`).value=n};start(){this.authorize()}resetForAuthorization(){this.reloadOnRetry=!1,this.network?.dispose(),this.network=null,this.session?.destroy(),this.session=null,this.renderer?.destroy(),this.renderer=null,this.voice.cancel(),this.audio.reset(),this.abort.abort(),this.abort=new AbortController,this.state=qq,this.feedbackEvents.reset(),this.input.setActive(!1),this.input.reset(),this.finalSummary.textContent=``,this.fightSummary.textContent=``,this.liveFightStatus.textContent=``,this.clearRematchTimers(),this.rematchButton.hidden=!0,this.cpuLevel=null,this.lastPhase=null}onCpuPick=e=>{let t=e.target?.closest(`[data-cpu-level]`)?.dataset.cpuLevel;iJ(t)&&this.state.stage===`waiting`&&this.state.role===`fighter`&&this.cpuLevel===null&&this.callCpu(t)};callCpu(e){this.network?.requestCpu(e)===!0&&(this.cpuLevel=e,this.renderState())}get cpuBout(){return Object.values(this.state.players).some(e=>e.cpu===!0)}onRematch=()=>{this.rematchButton.disabled||this.state.stage!==`complete`||(this.rematchAttempts=1,this.rematchOpponent=this.cpuBout||this.state.role!==`fighter`?null:Object.values(this.state.players).find(e=>e.id!==this.state.playerId)?.name??null,this.authorize())};clearRematchTimers(){this.rematchTimer!==null&&window.clearTimeout(this.rematchTimer),this.rematchCountdownTimer!==null&&window.clearInterval(this.rematchCountdownTimer),this.rematchTimer=null,this.rematchCountdownTimer=null,this.clearCpuRematch()}scheduleCpuRematch(e){this.clearCpuRematch(),this.cpuRematch={level:e,at:Date.now()+nJ},this.cpuRematchTimer=window.setInterval(()=>{let e=this.cpuRematch;e===null||this.state.stage!==`waiting`||this.state.role!==`fighter`||this.cpuLevel!==null?this.clearCpuRematch():Date.now()>=e.at&&(this.clearCpuRematch(),this.callCpu(e.level)),this.renderState()},250)}clearCpuRematch(){this.cpuRematchTimer!==null&&window.clearInterval(this.cpuRematchTimer),this.cpuRematchTimer=null,this.cpuRematch=null}awaitResultReveal(){this.resultRevealTimer!==null&&window.clearInterval(this.resultRevealTimer);let e=()=>{let e=this.renderer?.resultVisible??!0;this.overlay.hidden=this.state.stage===`complete`&&!e,(e||this.state.stage!==`complete`)&&this.resultRevealTimer!==null&&(window.clearInterval(this.resultRevealTimer),this.resultRevealTimer=null)};this.resultRevealTimer=window.setInterval(e,200),e()}startRematchCountdown(){this.clearRematchTimers();let e=this.state.role===`fighter`?`Rematch`:`Next bout`,t=()=>{let t=Math.ceil((this.finalReceivedAt+Zq-Date.now())/1e3);this.rematchButton.hidden=this.state.stage!==`complete`,this.rematchButton.disabled=t>0,this.setText(this.rematchButton,t>0?`${e} in ${t}s`:e),t<=0&&this.rematchCountdownTimer!==null&&(window.clearInterval(this.rematchCountdownTimer),this.rematchCountdownTimer=null)};t(),this.rematchCountdownTimer=window.setInterval(t,1e3)}scheduleRematchRetry(){this.rematchTimer===null&&(this.rematchAttempts>=tJ?this.fail(`rematch_unavailable`):(this.rematchAttempts+=1,this.setText(this.status,`The ring is still being cleared… trying again.`),this.rematchTimer=window.setTimeout(()=>{this.rematchTimer=null,this.authorize()},eJ)))}async authorize(){let e=++this.generation;this.resetForAuthorization(),this.dispatch({type:`connecting`}),this.setText(this.status,`Securing Discord Activity session…`),this.retry.hidden=!0;try{let t=await this.authorizer.authorize(this.abort.signal);if(this.destroyed||e!==this.generation){t.destroy();return}this.session=t,this.dispatch({type:`bootstrap`,simulation:t.bootstrap.simulation}),this.dispatch({type:`authorized`,player:t.player}),this.input.onAction(e=>{this.renderer?.predictAction?.(e),this.network?.notifyAction()}),this.input.onHeldChange(()=>this.network?.notifyHeld());let n=t.takeTicket();if(n===null)throw Error(`ticket_unavailable`);let r=new Rf(n,()=>this.input.frame(),{onMessage:e=>this.receive(e),onReconnect:e=>{this.dispatch({type:`reconnect-tick`,remainingMs:e}),this.renderer?.setReconnect(e),this.renderState()},onFatal:e=>this.fail(e),onFreshAuth:()=>{e===this.generation&&this.authorize()}});this.network=r,r.start(),this.setText(this.status,`Connecting to the ring…`)}catch(t){!this.abort.signal.aborted&&e===this.generation&&(this.reloadOnRetry=t instanceof vi&&t.reloadRequired,this.fail(wi(t)))}}ensureRenderer(){if(this.renderer!==null||this.session===null||this.destroyed)return;let e=new Rq(this.canvas,this.session.bootstrap.simulation,()=>this.settings.current,{localInput:()=>this.input.held(),inputSequenceOf:e=>this.network?.sequenceOf(e)??null,powerHeld:()=>this.input.powerHeld});e.onContact=(e,t)=>{this.audio.event(e,t),this.haptics.event(e,t)},e.onOwnPunch=(e,t,n)=>{this.audio.whoosh(e,t),this.soundedPunches.push(n),this.soundedPunches.length>8&&this.soundedPunches.shift()},e.onArcadeInjury=e=>this.audio.injury(e),e.onGore=e=>{this.audio.gore(e),this.haptics.gore(e),e.kind===`finish_him`?this.voice.shout(`Finish him!`):e.kind===`fatality`&&this.voice.shout(`Fatality.`)},e.onAnnouncement=e=>this.voice.speak(e),e.onCrowdCue=()=>this.audio.chant(),e.onRocked=(e,t)=>this.audio.rocked(e,t),this.renderer=e}receive(e){if(e.type===`error`){this.fail(e.code);return}e.type===`welcome`&&this.ensureRenderer(),(e.type===`welcome`||e.type===`resumed`)&&this.renderer?.resyncClock();let t=this.rematchAttempts>0;(e.type===`waiting`||e.type===`ready`)&&(this.rematchAttempts=0),e.type===`ready`&&(this.rematchOpponent=null),e.type===`ready`&&this.rememberStyle(e.players),e.type===`final`&&this.rematchAttempts>0&&e.match_id===this.lastFinalMatchId?this.scheduleRematchRetry():(this.dispatch({type:`message`,message:e}),e.type===`snapshot`&&this.receiveSnapshot(e.payload),e.type!==`select`&&e.type!==`ready`||e.players.some(e=>e.cpu===!0)||(this.cpuLevel=null),e.type===`waiting`&&(this.cpuLevel===null?t&&this.cpuRematchLevel!==null&&this.scheduleCpuRematch(this.cpuRematchLevel):this.callCpu(this.cpuLevel)),e.type===`final`&&(this.cpuRematchLevel=this.cpuBout?this.cpuLevel:null,this.rematchAttempts=0,this.lastFinalMatchId=e.match_id,this.finalReceivedAt=Date.now(),this.renderer?.setFinal(e),this.audio.result(e),this.startRematchCountdown(),this.awaitResultReveal()),this.renderer?.setPlayers(this.state.players,this.state.playerId,this.state.playerOrder),this.renderer?.setReconnect(this.state.reconnectMs),this.renderState())}get networkStats(){return{inputLatencyMs:this.network?.inputLatencyMs??null,resolutionScale:this.renderer?.resolutionScale??null,gpu:this.renderer?.memoryInfo??null}}receiveSnapshot(e){this.lastPhase===`countdown`&&e.phase!==`countdown`&&this.voice.finishLine(Qq),this.lastPhase=e.phase,this.renderer?.setInputLatency(this.network?.inputLatencyMs??null),this.renderer?.push(e);let t=e.fighters.find(e=>e.player_id===this.state.playerId);this.input.setKnockdown(t?.is_downed===!0),t!==void 0&&this.audio.snapshot(e.tick,t.stamina,t.maximum_stamina,t.trauma.head+t.trauma.body),this.audio.roundClock(e.phase,e.round_number,e.phase_ticks_remaining,this.state.simulation?.tick_rate??30),this.audio.tension(Fp(e));for(let t of this.feedbackEvents.accept(e.events)){if(Xq.has(t.kind)||t.kind===`punch_start`&&t.action_id!==null&&this.soundedPunches.includes(t.action_id))continue;let n=t.kind===`punch_start`?e.fighters.find(e=>e.player_id===t.actor_id&&e.action_id===t.action_id):void 0;this.audio.event(t,n?.action_power===`power`),this.haptics.event(t)}}rememberStyle(e){let t=e.find(e=>e.id===this.state.playerId)?.style;this.state.role===`fighter`&&t!==void 0&&Ut(t)}dispatch(e){this.state=Yq(this.state,e)}setText(e,t){e.textContent!==t&&(e.textContent=t)}renderState(){let e={bootstrapping:`Loading…`,authorizing:`Authorizing with Discord…`,connecting:`Connecting securely…`,waiting:this.state.role===`spectator`?`Waiting for the fighters…`:this.cpuLevel===null?this.cpuRematch===null?this.rematchOpponent===null?`Waiting for an opponent. Anyone in this channel can join with Play now.`:`Waiting for ${this.rematchOpponent} to take the rematch…`:`Rematch with the ${rJ.find(e=>e.level===this.cpuRematch?.level)?.label??`computer`} in ${Math.max(1,Math.ceil((this.cpuRematch.at-Date.now())/1e3))}s, unless someone joins first.`:`Calling in the computer…`,select:`Pick how your fighter boxes.`,countdown:`Bout countdown.`,fight:`Round ${this.state.snapshot?.round_number??1} in progress.`,knockdown:`Knockdown count ${this.state.snapshot?.fighters.find(e=>e.player_id===this.state.playerId)?.get_up_count??0}.`,foul_recovery:`Foul recovery in progress.`,referee_down:`The referee is down. The bout goes on without him.`,finish:this.state.snapshot!==null&&Er(this.state.snapshot.fighters)?.player_id===this.state.playerId?`You are out on your feet: one more punch kills you.`:`Finish him: one more punch kills.`,rest:`Between-round rest.`,paused:`Connection paused. ${Math.ceil(this.state.reconnectMs/1e3)} seconds remain.`,complete:this.cpuBout?`Bout complete. Scorecards are displayed. Bouts against the computer are unrated.`:`Bout complete. Scorecards and rating changes are displayed.`,fatal:jd(this.state.safeError??`safe_error`)},t=this.state.role===`spectator`;this.setText(this.status,t?`Spectating — ${e[this.state.stage]}`:e[this.state.stage]);let n=this.state.stage===`complete`&&this.state.final!==null;if(this.status.hidden=n||[`select`,`countdown`,`fight`,`knockdown`,`foul_recovery`,`referee_down`,`finish`,`rest`].includes(this.state.stage),this.overlay.toggleAttribute(`data-raised`,this.state.snapshot!==null),this.overlay.toggleAttribute(`data-result`,n),this.state.stage!==`complete`)this.overlay.hidden=!1,this.completeSince=null;else if(this.state.final===null){this.completeSince??=Date.now();let e=Date.now()-this.completeSince;this.overlay.hidden=e<$q,this.overlay.hidden&&this.resultWaitTimer===null&&(this.resultWaitTimer=window.setTimeout(()=>{this.resultWaitTimer=null,this.renderState()},$q-e+50))}this.roleIndicator.hidden=!t,this.controlsButton.hidden=t,t&&(this.controlsPanel.hidden=!0,this.controlsButton.setAttribute(`aria-expanded`,`false`));let r=this.state.snapshot?.fighters.find(e=>e.player_id===this.state.playerId),i=t?`Spectating. ${e[this.state.stage]}`:this.state.stage===`knockdown`&&r?.is_downed===!0?`Knockdown. Count ${r.get_up_count}. ${r.get_up_prompt===null?`Wait for your private rhythm instruction.`:`Press ${r.get_up_prompt===`get_up_left`?`left`:`right`} now.`}`:this.state.stage===`paused`?`Connection paused.`:e[this.state.stage];this.setText(this.liveFightStatus,i),this.corner.update(this.state.snapshot,this.state.playerId,this.state.role===`fighter`&&this.state.stage===`rest`),this.renderer?.setCornerPanelTop(this.corner.top()),this.stylePicker.update(this.state.stage===`select`?this.state.select:null,this.state.playerId,this.state.role),this.retry.hidden=this.state.stage!==`fatal`,this.setText(this.retry,this.reloadOnRetry?`Reload`:`Retry securely`),this.state.stage!==`complete`&&(this.rematchButton.hidden=!0),this.cpuPicker.hidden=t||this.state.stage!==`waiting`||this.cpuLevel!==null,this.setText(this.cpuPrompt,this.cpuRematch===null?this.rematchOpponent===null?`No one here yet? Fight the computer.`:`Or fight the computer instead:`:`Or start now:`);let a=!t&&(this.state.stage===`waiting`||this.state.stage===`countdown`);this.hint.hidden=!a,a&&this.setText(this.hint,Kd(Md(),window.innerWidth)),this.overlay.toggleAttribute(`data-touch-hint`,a&&this.state.stage===`countdown`&&Md());let o=!t&&[`countdown`,`fight`,`knockdown`,`foul_recovery`,`referee_down`,`finish`].includes(this.state.stage),s=!t&&this.state.snapshot!==null&&(this.state.stage===`rest`||this.state.stage===`paused`);if(this.input.setActive(o,o||s),this.network?.setActive(o),this.renderFightSummary(),this.state.final!==null){let e=this.state.final;this.setText(this.finalSummary,`${e.method.replaceAll(`_`,` `)}. ${e.winner_id===null?`Draw`:`${this.state.players[e.winner_id]?.name??`Winner`} wins`}. Scorecards: ${e.scorecards.map(e=>`${e.judge}: ${e.player_one.reduce((e,t)=>e+t,0)} to ${e.player_two.reduce((e,t)=>e+t,0)}`).join(`; `)}. ${this.cpuBout?`Unrated bout against the computer.`:`Ratings: ${Object.entries(e.ratings).map(([e,t])=>`${this.state.players[e]?.name??`fighter`} ${t.before} to ${t.after}`).join(`; `)}.`}`)}}renderFightSummary(){let e=this.state.snapshot;if(e===null)return;let t=this.state.simulation?.tick_rate??30,n=Math.floor(this.summaryClock.ticks(e)/t),r=`${Math.floor(n/60)}:${String(n%60).padStart(2,`0`)}`,i=e.fighters.map(e=>{let t=this.state.players[e.player_id],n=e.injuries.length===0?`no injuries`:`injuries: ${e.injuries.map(e=>we(e).toLowerCase()).join(`, `)}`;return`${t?.name??`Fighter`}, ${t?.cpu===!0?`computer opponent`:`ELO ${t?.rating??`unknown`}`}, stamina ${Math.round(e.stamina)} of ${Math.round(e.maximum_stamina)}, guard ${Math.round(e.guard)}, poise ${Math.round(e.poise)}, conditioning ${Math.round(e.conditioning)}, blood ${Math.round(e.blood_volume/ve*100)} percent, ${n}, ${e.warnings} warnings, ${e.knockdowns} knockdowns`}),a=e.fighters.find(e=>e.player_id===this.state.playerId),o=a?.is_downed===!0?a.get_up_prompt===null?`You are down. Count ${a.get_up_count}. Wait for your private rhythm instruction.`:`You are down. Count ${a.get_up_count}. Press ${a.get_up_prompt===`get_up_left`?`left`:`right`} now. Get-up progress ${a.get_up_meter} of ${a.get_up_required}.`:``;this.setText(this.fightSummary,`Round ${e.round_number}. ${e.phase.replace(`_`,` `)}. Clock ${r}. ${i.join(`. `)}. ${o}`.trim())}onRetry=()=>{this.reloadOnRetry?(this.reloading=!0,this.reloadPage()):this.authorize()};bindPanels(){let e=(e,t)=>{let n=this.root.querySelector(e),r=this.root.querySelector(t);n.addEventListener(`click`,()=>{r.hidden=!r.hidden,n.setAttribute(`aria-expanded`,String(!r.hidden))})};e(`[data-controls]`,`[data-controls-panel]`),e(`[data-settings]`,`[data-settings-panel]`);let t=this.root.querySelector(`[data-settings-panel]`);this.root.querySelector(`[data-settings]`).addEventListener(`click`,()=>{this.diagnosticsTimer!==null&&window.clearInterval(this.diagnosticsTimer),this.diagnosticsTimer=null,t.hidden||(this.refreshDiagnostics(),this.diagnosticsTimer=window.setInterval(()=>this.refreshDiagnostics(),1e3))});let n=this.root.querySelector(`[data-copy-diagnostics]`);n.addEventListener(`click`,()=>{let e=this.diagnosticsText(),t=()=>{this.setText(n,`Copied`),window.setTimeout(()=>this.setText(n,`Copy diagnostics`),1500)},r=()=>{let e=this.root.querySelector(`[data-diagnostics]`),t=window.getSelection();if(t===null)return;let r=document.createRange();r.selectNodeContents(e),t.removeAllRanges(),t.addRange(r),this.setText(n,`Selected. Copy manually`),window.setTimeout(()=>this.setText(n,`Copy diagnostics`),2500)},i=navigator.clipboard;i===void 0||typeof i.writeText!=`function`?r():i.writeText(e).then(t).catch(r)}),this.root.querySelector(`[data-volume]`).addEventListener(`input`,e=>{this.settings.update({volume:Number(e.target.value)}),this.audio.setVolume(),this.voice.settingsChanged()}),this.root.querySelector(`[data-haptics]`).addEventListener(`change`,e=>{this.settings.update({haptics:e.target.checked})}),this.root.querySelector(`[data-motion]`).addEventListener(`change`,e=>{let t=e.target.checked;this.settings.update({reducedMotion:t}),this.renderer?.setReducedMotion(t)}),this.root.querySelector(`[data-commentary]`).addEventListener(`change`,e=>{this.settings.update({commentary:e.target.checked})}),this.root.querySelector(`[data-announcer]`).addEventListener(`change`,e=>{let t=e.target.checked;this.settings.update({announcer:t}),t||this.voice.cancel()}),this.root.querySelector(`[data-blood]`).addEventListener(`change`,e=>{let t=e.target.value;this.settings.update({blood:t}),this.renderer?.setBloodLevel(t)}),this.root.querySelector(`[data-camera]`).addEventListener(`change`,e=>{let t=zq.find(t=>t===e.target.value);t!==void 0&&this.settings.update({camera:t})})}diagnosticsText(){let e=this.networkStats,t=this.renderer?.diagnostics,n=t===void 0||t.frameMs<=0?`-`:(1e3/t.frameMs).toFixed(0);return[`stage: ${this.state.stage} · role: ${this.state.role??`-`}`,`input latency: ${e.inputLatencyMs===null?`-`:`${Math.round(e.inputLatencyMs)} ms`}`,`frame: ${t===void 0?`-`:`${t.frameMs.toFixed(1)} ms (${n} fps)`} · render scale: ${t?.resolutionScale??`-`}`,`gpu objects: ${t===void 0?`-`:`${t.gpu.geometries} geometries, ${t.gpu.textures} textures, ${t.gpu.programs} programs`}`,`graphics: ${t?.graphics??`-`}`,`browser: ${navigator.userAgent}`,`pointer: ${Md()?`coarse`:`fine`} · viewport: ${window.innerWidth}x${window.innerHeight} @${window.devicePixelRatio}`,`last error: ${this.state.safeError??`none`}`,`match: ${this.state.final?.match_id??`-`}`].join(` +`)}refreshDiagnostics(){this.setText(this.root.querySelector(`[data-diagnostics]`),this.diagnosticsText())}syncSettings(){let e=this.settings.current;this.root.querySelector(`[data-volume]`).value=String(e.volume),this.root.querySelector(`[data-haptics]`).checked=e.haptics,this.root.querySelector(`[data-motion]`).checked=e.reducedMotion,this.root.querySelector(`[data-blood]`).value=e.blood,this.root.querySelector(`[data-commentary]`).checked=e.commentary,this.syncAnnouncerSetting(),this.voice.onVoicesChanged=()=>this.syncAnnouncerSetting(),this.root.querySelector(`[data-camera]`).value=e.camera}syncAnnouncerSetting(){let e=this.root.querySelector(`[data-announcer]`),t=this.voice.hasVoice;e.checked=this.settings.current.announcer&&t,e.disabled=!t;let n=this.voice.supported?t?null:`This device has no English voice of its own`:`This browser cannot speak`;n===null?e.parentElement.removeAttribute(`title`):e.parentElement.title=n}fail(e){e===`room_closed`&&this.rematchAttempts>0?this.scheduleRematchRetry():(e===`client_outdated`&&(this.reloadOnRetry=!0),this.dispatch({type:`fatal`,code:e}),this.rematchOpponent=null,this.voice.cancel(),this.network?.dispose(),this.network=null,this.session?.destroy(),this.session=null,this.renderer?.destroy(),this.renderer=null,this.input.setActive(!1),this.input.reset(),this.renderState())}destroy(){this.destroyed||(this.destroyed=!0,this.generation+=1,this.abort.abort(),this.network?.dispose(),this.session?.destroy(),this.reloading||this.authorizer.close(),this.renderer?.destroy(),window.removeEventListener(`keydown`,this.onCameraKey),this.input.destroy(),this.corner.destroy(),this.stylePicker.destroy(),this.audio.destroy(),this.voice.destroy(),this.settings.destroy(),this.retry.removeEventListener(`click`,this.onRetry),this.rematchButton.removeEventListener(`click`,this.onRematch),this.cpuPicker.removeEventListener(`click`,this.onCpuPick),this.clearRematchTimers(),this.diagnosticsTimer!==null&&window.clearInterval(this.diagnosticsTimer),this.resultRevealTimer!==null&&window.clearInterval(this.resultRevealTimer),this.resultWaitTimer!==null&&window.clearTimeout(this.resultWaitTimer),this.diagnosticsTimer=null,this.root.replaceChildren())}};(new URLSearchParams(window.location.search).get(`styles`)??``).split(`,`);var oJ={broadcast:{position:[0,1.88,7.15],lookAt:[0,1.12,0]},side:{position:[7.4,1.6,0],lookAt:[0,1.1,0]},top:{position:[.01,8.5,.01],lookAt:[0,0,0]},ringside:{position:[1.6,1.5,4.1],lookAt:[.2,1.25,0]}},sJ=[[`hips`,`spine`],[`spine`,`head`],[`chest`,`shoulderL`],[`shoulderL`,`elbowL`],[`elbowL`,`gloveL`],[`chest`,`shoulderR`],[`shoulderR`,`elbowR`],[`elbowR`,`gloveR`],[`hips`,`hipL`],[`hipL`,`kneeL`],[`kneeL`,`ankleL`],[`hips`,`hipR`],[`hipR`,`kneeR`],[`kneeR`,`ankleR`]],cJ=class{root;renderer=null;replay=null;raf=0;playing=!1;speed=1;virtualTick=0;carry=0;latencyMs=0;pendingQueue=[];destroyed=!1;overlays={skeleton:!1,hurtbox:!1,hitbox:!1};skeletonLines=[];hurtboxMeshes=[];hitboxMeshes=[];statusEl;metricsEl;canvas;constructor(e){this.root=e,e.innerHTML=`
HANDS LABloading replay…
@@ -5402,7 +5402,7 @@ void main() { -
`,this.canvas=e.querySelector(`canvas`),this.statusEl=e.querySelector(`[data-lab-status]`),this.metricsEl=e.querySelector(`[data-lab-metrics]`),this.bindControls()}async start(){let e=new URLSearchParams(window.location.search),t=e.get(`replay`)??`golden`,n=await fetch(`/replays/${t}.json`);if(n.ok||(n=await fetch(`/hands/replays/${t}.json`)),!n.ok)throw Error(`replay_load_failed:${n.status}`);this.replay=await n.json(),await mF(),this.renderer=new Lq(this.canvas,{tick_rate:this.replay.tick_rate,ring_half_width:500,ring_half_height:500},()=>({volume:0,haptics:!1,reducedMotion:!1,blood:`full`,commentary:!0,announcer:!1,camera:`broadcast`}),{manualClock:!0});let r=Object.fromEntries(this.replay.ticks[0].snapshot.payload.fighters.map(e=>[e.player_id,{id:e.player_id,name:e.player_id===`one`?`Azure Vector`:`Crimson Geometry`,avatar:null,rating:1500,connected:!0}]));this.renderer.setPlayers(r,`one`),this.buildOverlays();let i=e.get(`tick`);if(e.get(`metrics`)===`1`){await this.renderer.ready,this.exportMetrics(),this.setStatus(`metrics done`);return}if(i!==null){let t=Number(i);await this.renderer.ready,this.seek(t);let n=aJ[e.get(`camera`)??``]??aJ.broadcast;this.renderer.labSetCameraOverride(n.position,n.lookAt),this.overlays.skeleton=e.get(`skeleton`)===`1`,this.overlays.hurtbox=e.get(`hurtbox`)===`1`,this.overlays.hitbox=e.get(`hitbox`)===`1`,this.syncOverlayVisibility(),this.renderCurrentTick(),window.__labDebug={roots:this.renderer.labRigs.map(e=>e.position.toArray().map(e=>Number(e.toFixed(3)))),heads:this.renderer.labRigs.map(e=>{let t=e.getObjectByName(Qk.head??`head`);return t===void 0?null:t.getWorldPosition(new q).toArray().map(e=>Number(e.toFixed(3)))}),gloves:this.renderer.labRigs.map(e=>{let t=e.getObjectByName(Qk.gloveL??`gloveL`);return t===void 0?null:t.getWorldPosition(new q).toArray().map(e=>Number(e.toFixed(3)))}),material:(()=>{let e=null;return this.renderer.labRigs[0]?.traverse(t=>{if(e===null&&t instanceof Hv){let n=t.material;e={colorHex:n.color.getHexString(),hasMap:n.map!==null,mapImage:n.map?.image?.width??`none`,mapVersion:n.map?.version,clearcoat:n.clearcoat,opacity:n.opacity}}}),e})()},this.setStatus(`filmstrip tick ${t}`);return}this.playing=!0;let a=()=>{this.destroyed||(this.advance(),this.raf=requestAnimationFrame(a))};this.raf=requestAnimationFrame(a)}bindControls(){this.root.querySelector(`[data-lab='play']`).addEventListener(`click`,e=>{this.playing=!this.playing,e.target.textContent=this.playing?`Pause`:`Play`}),this.root.querySelector(`[data-lab='step']`).addEventListener(`click`,()=>{this.playing=!1,this.root.querySelector(`[data-lab='play']`).textContent=`Play`,this.virtualTick=Math.min(this.virtualTick+1,(this.replay?.ticks.length??1)-1),this.pushUpTo(this.virtualTick),this.renderCurrentTick()}),this.root.querySelector(`[data-lab='speed']`).addEventListener(`change`,e=>{this.speed=Number(e.target.value)}),this.root.querySelector(`[data-lab='camera']`).addEventListener(`change`,e=>{let t=aJ[e.target.value];this.renderer?.labSetCameraOverride(t.position,t.lookAt)});for(let e of[`skeleton`,`hurtbox`,`hitbox`])this.root.querySelector(`[data-lab='${e}']`).addEventListener(`change`,t=>{this.overlays[e]=t.target.checked,this.syncOverlayVisibility()});this.root.querySelector(`[data-lab='latency']`).addEventListener(`change`,e=>{this.latencyMs=Math.max(0,Math.min(500,Number(e.target.value)))}),this.root.querySelector(`[data-lab='metrics']`).addEventListener(`click`,()=>this.exportMetrics())}advance(){if(!this.playing||this.replay===null)return;let e=this.replay.ticks.length-1;if(!(this.virtualTick>=e)){for(this.carry+=this.speed;this.carry>=1&&this.virtualTick0?this.pendingQueue.push({at:performance.now()+this.latencyMs,tick:t}):this.renderer?.push(t.snapshot.payload))}drainLatencyQueue(){let e=performance.now();for(let t=this.pendingQueue.length-1;t>=0;--t){let n=this.pendingQueue[t];n.at<=e&&(this.renderer?.push(n.tick.snapshot.payload),this.pendingQueue.splice(t,1))}}seek(e,t=!0){if(this.replay===null||this.renderer===null)return;let n=Math.max(0,Math.min(e,this.replay.ticks.length-1));for(let e=0;e<=n;e+=1)this.renderer.push(this.replay.ticks[e].snapshot.payload),e>=n-15&&this.renderer.labEffects.update(1/30);this.virtualTick=n,this.renderOnSeek=t}renderOnSeek=!0;renderCurrentTick(e){if(this.replay===null||this.renderer===null)return;this.drainLatencyQueue(),this.renderer.labFrame(this.virtualTick/this.replay.tick_rate,e??this.renderOnSeek),this.renderer.labFrame((this.virtualTick+.5)/this.replay.tick_rate,e??this.renderOnSeek),this.updateOverlays();let t=this.replay.ticks[this.virtualTick]?.snapshot.payload.phase??``;this.setStatus(`tick ${this.virtualTick}/${this.replay.ticks.length-1} · ${t} · ${this.speed}×`)}buildOverlays(){let e=this.renderer;if(e===null)return;let t=new sy({color:8257448,depthTest:!1,transparent:!0,opacity:.9});for(let n of e.labRigs){let r=new iv;r.setAttribute(`position`,new U_(new Float32Array(oJ.length*6),3));let i=new yy(r,t);i.frustumCulled=!1,i.renderOrder=20,e.labScene.add(i),this.skeletonLines.push(i);let a=new Y(new Py(.13,.16,4,8),new yv({color:16735581,wireframe:!0,transparent:!0,opacity:.85,depthTest:!1}));a.renderOrder=21,a.position.y=.12,(n.getObjectByName(Qk.head??`head`)??n).add(a),this.hurtboxMeshes.push(a);let o=new Y(new Py(.21,.34,4,8),new yv({color:16758877,wireframe:!0,transparent:!0,opacity:.7,depthTest:!1}));o.renderOrder=21,o.position.y=.16,(n.getObjectByName(Qk.chest??`chest`)??n).add(o),this.hurtboxMeshes.push(o);for(let e of[`gloveL`,`gloveR`]){let t=new Y(new _b(.11,10,8),new yv({color:6141183,wireframe:!0,transparent:!0,opacity:.85,depthTest:!1}));t.renderOrder=22,(n.getObjectByName(Qk[e]??e)??n).add(t),this.hitboxMeshes.push(t)}}this.syncOverlayVisibility()}syncOverlayVisibility(){for(let e of this.skeletonLines)e.visible=this.overlays.skeleton;for(let e of this.hurtboxMeshes)e.visible=this.overlays.hurtbox;for(let e of this.hitboxMeshes)e.visible=this.overlays.hitbox}updateOverlays(){let e=this.renderer;if(e!==null)for(let[t,n]of e.labRigs.entries()){let e=this.skeletonLines[t];if(e===void 0||!e.visible)continue;let r=e.geometry.getAttribute(`position`),i=new q,a=new q;oJ.forEach(([e,t],o)=>{let s=n.getObjectByName(e),c=n.getObjectByName(t);s!==void 0&&c!==void 0&&(s.getWorldPosition(i),c.getWorldPosition(a),r.setXYZ(o*2,i.x,i.y,i.z),r.setXYZ(o*2+1,a.x,a.y,a.z))}),r.needsUpdate=!0}}jointWorld(e,t){let n=(this.renderer?.labRigs[e])?.getObjectByName(Qk[t]??t);return n==null?null:n.getWorldPosition(new q)}exportMetrics(){if(this.replay===null)return;let e={contactAlignment:[],maxRootStepMeters:0,footSlideMeters:0,phaseDriftTicks:0};for(let t of this.replay.ticks){let n=t.snapshot.payload.events.find(e=>[`hit`,`counter_hit`,`block`].includes(e.kind)),r=t.snapshot.payload.fighters[0].action_hand;if(n===void 0||r===null)continue;let i=Math.min(t.tick+1,this.replay.ticks.length-1);this.seek(i,!1),this.renderCurrentTick(!1);let a=this.jointWorld(0,r===`left`?`gloveL`:`gloveR`),o=this.jointWorld(1,`head`),c=this.jointWorld(1,`chest`);a!==null&&o!==null&&c!==null&&e.contactAlignment.push({tick:t.tick,kind:n.kind,gloveToHeadMeters:Number(Math.max(0,a.distanceTo(o)-s.head.radius).toFixed(4)),gloveToTorsoMeters:Number(Math.max(0,a.distanceTo(c)-s.torso.radius).toFixed(4))})}this.seek(0,!1);let t=null,n=null;for(let r of this.replay.ticks){this.seek(r.tick,!1),this.renderCurrentTick(!1);let i=this.renderer.labRigs[0].position.x;n!==null&&(e.maxRootStepMeters=Math.max(e.maxRootStepMeters,Math.abs(i-n))),n=i;let a=r.snapshot.payload.fighters[0],o=Math.hypot(a.velocity_x,a.velocity_y),s=this.replay.ticks.slice(Math.max(0,r.tick-30),r.tick+1).some(e=>e.snapshot.payload.fighters[0].is_downed);if(o===0&&!a.is_downed&&!s&&r.snapshot.payload.phase===`fight`){let n=[this.jointWorld(0,`ankleL`),this.jointWorld(0,`ankleR`)].filter(e=>e!==null);t!==null&&n.length===2&&(e.footSlideMeters=Math.max(e.footSlideMeters,Number(Math.max(n[0].distanceTo(t[0]),n[1].distanceTo(t[1])).toFixed(4)))),t=n}else t=null}this.metricsEl.textContent=` contacts: ${e.contactAlignment.map(e=>`${e.kind}@t${e.tick} glove-head ${e.gloveToHeadMeters}m`).join(` · `)} · max root step ${e.maxRootStepMeters.toFixed(3)}m · foot slide ${e.footSlideMeters}m`,window.__labDebug={roots:this.renderer.labRigs.map(e=>e.position.toArray().map(e=>Number(e.toFixed(3)))),graphsActive:this.renderer.graphs!==null,heads:this.renderer.labRigs.map(e=>{let t=e.getObjectByName(Qk.head??`head`);return t===void 0?null:t.getWorldPosition(new q).toArray().map(e=>Number(e.toFixed(3)))})};let r=new Blob([JSON.stringify(e,null,1)],{type:`application/json`}),i=document.createElement(`a`);i.href=URL.createObjectURL(r),i.download=`hands-lab-metrics.json`,i.click(),URL.revokeObjectURL(i.href)}setStatus(e){this.statusEl.textContent!==e&&(this.statusEl.textContent=e)}destroy(){this.destroyed||(this.destroyed=!0,cancelAnimationFrame(this.raf),this.renderer?.destroy(),this.root.replaceChildren())}};function cJ(e){let t=new sJ(e);return t.start().catch(t=>{e.querySelector(`[data-lab-status]`).textContent=`lab failed: ${String(t)}`}),()=>t.destroy()}var lJ={referee:{outfit:Pj,look:hj.referee},corner_blue:{outfit:Fj,look:hj.blueCorner},corner_red:{outfit:Ij,look:hj.redCorner},cutman:{outfit:Lj,look:hj.blueCutman}},uJ=()=>({player_id:`lab`,x:0,y:0,facing:1,facing_x:0,facing_y:-1e3,velocity_x:0,velocity_y:0,stance:`orthodox`,style:`balanced`,defense:`none`,stamina:1e3,maximum_stamina:1e3,conditioning:1e3,guard:700,guard_broken:!1,poise:600,trauma:{head:0,body:0,left_eye:0,right_eye:0,left_cut:0,right_cut:0,swelling:0,bleeding:0},knockdowns:0,warnings:0,deductions:0,stunned_ticks:0,is_downed:!1,action:null,action_hand:null,action_target:null,action_power:null,action_id:null,action_key:null,action_start_tick:0,action_startup_ticks:0,action_active_ticks:0,action_recovery_ticks:0,action_contact_tick:null,queued_actions:0,clinch_startup_ticks:0,clinch_ticks:0,is_foul_recovery_target:!1,taunt_ticks:0,corner_choice:null,get_up_prompt:null,get_up_meter:0,get_up_required:0,get_up_count:0,get_up_window_start_tick:0,get_up_window_end_tick:0,last_input_sequence:-1,injuries:[],blood_volume:1e3}),dJ=.45,fJ=.3,pJ={face:[.25,1.55,1],portrait:[.12,1.62,.62],eyes:[-.2,1.65,.44],floor:[1.62,.3,.18],hand:[.55,1.05,.75],front:[0,1.35,3.4],side:[3.4,1.3,.2],"three-quarter":[2.4,1.5,2.6],top:[.01,4.5,.6],back:[.2,1.4,-3.4],low:[1.8,.5,2.6],wide:[3.4,2.7,3.6]},mJ=class{root;renderer;scene=new u_;camera;graph=null;boxer=null;trails=[];trailGlove=new q;treatEye=new q(0,1.22,.78);treatFacing=new q(0,0,-1);treatTarget=new q;skeletonHelper=null;effects=null;shieldClock=1/0;shieldEvent=0;mouth=new q;headTurn=new rg;burstRim=new Float32Array;burstStump={position:new q,quaternion:new rg,across:new q,scratch:new q};raf=0;previous=performance.now();elapsed=0;params=new URLSearchParams(window.location.search);reactionFired=!1;carnage=null;injuries=[];inflictions=[];killed=!1;vomitClock=0;headAt=new q;statusEl;constructor(e){this.root=e,e.innerHTML=`
+
`,this.canvas=e.querySelector(`canvas`),this.statusEl=e.querySelector(`[data-lab-status]`),this.metricsEl=e.querySelector(`[data-lab-metrics]`),this.bindControls()}async start(){let e=new URLSearchParams(window.location.search),t=e.get(`replay`)??`golden`,n=await fetch(`/replays/${t}.json`);if(n.ok||(n=await fetch(`/hands/replays/${t}.json`)),!n.ok)throw Error(`replay_load_failed:${n.status}`);this.replay=await n.json(),await mF(),this.renderer=new Rq(this.canvas,{tick_rate:this.replay.tick_rate,ring_half_width:500,ring_half_height:500},()=>({volume:0,haptics:!1,reducedMotion:!1,blood:`full`,commentary:!0,announcer:!1,camera:`broadcast`}),{manualClock:!0});let r=Object.fromEntries(this.replay.ticks[0].snapshot.payload.fighters.map(e=>[e.player_id,{id:e.player_id,name:e.player_id===`one`?`Azure Vector`:`Crimson Geometry`,avatar:null,rating:1500,connected:!0}]));this.renderer.setPlayers(r,`one`),this.buildOverlays();let i=e.get(`tick`);if(e.get(`metrics`)===`1`){await this.renderer.ready,this.exportMetrics(),this.setStatus(`metrics done`);return}if(i!==null){let t=Number(i);await this.renderer.ready,this.seek(t);let n=oJ[e.get(`camera`)??``]??oJ.broadcast;this.renderer.labSetCameraOverride(n.position,n.lookAt),this.overlays.skeleton=e.get(`skeleton`)===`1`,this.overlays.hurtbox=e.get(`hurtbox`)===`1`,this.overlays.hitbox=e.get(`hitbox`)===`1`,this.syncOverlayVisibility(),this.renderCurrentTick(),window.__labDebug={roots:this.renderer.labRigs.map(e=>e.position.toArray().map(e=>Number(e.toFixed(3)))),heads:this.renderer.labRigs.map(e=>{let t=e.getObjectByName(Qk.head??`head`);return t===void 0?null:t.getWorldPosition(new q).toArray().map(e=>Number(e.toFixed(3)))}),gloves:this.renderer.labRigs.map(e=>{let t=e.getObjectByName(Qk.gloveL??`gloveL`);return t===void 0?null:t.getWorldPosition(new q).toArray().map(e=>Number(e.toFixed(3)))}),material:(()=>{let e=null;return this.renderer.labRigs[0]?.traverse(t=>{if(e===null&&t instanceof Hv){let n=t.material;e={colorHex:n.color.getHexString(),hasMap:n.map!==null,mapImage:n.map?.image?.width??`none`,mapVersion:n.map?.version,clearcoat:n.clearcoat,opacity:n.opacity}}}),e})()},this.setStatus(`filmstrip tick ${t}`);return}this.playing=!0;let a=()=>{this.destroyed||(this.advance(),this.raf=requestAnimationFrame(a))};this.raf=requestAnimationFrame(a)}bindControls(){this.root.querySelector(`[data-lab='play']`).addEventListener(`click`,e=>{this.playing=!this.playing,e.target.textContent=this.playing?`Pause`:`Play`}),this.root.querySelector(`[data-lab='step']`).addEventListener(`click`,()=>{this.playing=!1,this.root.querySelector(`[data-lab='play']`).textContent=`Play`,this.virtualTick=Math.min(this.virtualTick+1,(this.replay?.ticks.length??1)-1),this.pushUpTo(this.virtualTick),this.renderCurrentTick()}),this.root.querySelector(`[data-lab='speed']`).addEventListener(`change`,e=>{this.speed=Number(e.target.value)}),this.root.querySelector(`[data-lab='camera']`).addEventListener(`change`,e=>{let t=oJ[e.target.value];this.renderer?.labSetCameraOverride(t.position,t.lookAt)});for(let e of[`skeleton`,`hurtbox`,`hitbox`])this.root.querySelector(`[data-lab='${e}']`).addEventListener(`change`,t=>{this.overlays[e]=t.target.checked,this.syncOverlayVisibility()});this.root.querySelector(`[data-lab='latency']`).addEventListener(`change`,e=>{this.latencyMs=Math.max(0,Math.min(500,Number(e.target.value)))}),this.root.querySelector(`[data-lab='metrics']`).addEventListener(`click`,()=>this.exportMetrics())}advance(){if(!this.playing||this.replay===null)return;let e=this.replay.ticks.length-1;if(!(this.virtualTick>=e)){for(this.carry+=this.speed;this.carry>=1&&this.virtualTick0?this.pendingQueue.push({at:performance.now()+this.latencyMs,tick:t}):this.renderer?.push(t.snapshot.payload))}drainLatencyQueue(){let e=performance.now();for(let t=this.pendingQueue.length-1;t>=0;--t){let n=this.pendingQueue[t];n.at<=e&&(this.renderer?.push(n.tick.snapshot.payload),this.pendingQueue.splice(t,1))}}seek(e,t=!0){if(this.replay===null||this.renderer===null)return;let n=Math.max(0,Math.min(e,this.replay.ticks.length-1));for(let e=0;e<=n;e+=1)this.renderer.push(this.replay.ticks[e].snapshot.payload),e>=n-15&&this.renderer.labEffects.update(1/30);this.virtualTick=n,this.renderOnSeek=t}renderOnSeek=!0;renderCurrentTick(e){if(this.replay===null||this.renderer===null)return;this.drainLatencyQueue(),this.renderer.labFrame(this.virtualTick/this.replay.tick_rate,e??this.renderOnSeek),this.renderer.labFrame((this.virtualTick+.5)/this.replay.tick_rate,e??this.renderOnSeek),this.updateOverlays();let t=this.replay.ticks[this.virtualTick]?.snapshot.payload.phase??``;this.setStatus(`tick ${this.virtualTick}/${this.replay.ticks.length-1} · ${t} · ${this.speed}×`)}buildOverlays(){let e=this.renderer;if(e===null)return;let t=new sy({color:8257448,depthTest:!1,transparent:!0,opacity:.9});for(let n of e.labRigs){let r=new iv;r.setAttribute(`position`,new U_(new Float32Array(sJ.length*6),3));let i=new yy(r,t);i.frustumCulled=!1,i.renderOrder=20,e.labScene.add(i),this.skeletonLines.push(i);let a=new Y(new Py(.13,.16,4,8),new yv({color:16735581,wireframe:!0,transparent:!0,opacity:.85,depthTest:!1}));a.renderOrder=21,a.position.y=.12,(n.getObjectByName(Qk.head??`head`)??n).add(a),this.hurtboxMeshes.push(a);let o=new Y(new Py(.21,.34,4,8),new yv({color:16758877,wireframe:!0,transparent:!0,opacity:.7,depthTest:!1}));o.renderOrder=21,o.position.y=.16,(n.getObjectByName(Qk.chest??`chest`)??n).add(o),this.hurtboxMeshes.push(o);for(let e of[`gloveL`,`gloveR`]){let t=new Y(new _b(.11,10,8),new yv({color:6141183,wireframe:!0,transparent:!0,opacity:.85,depthTest:!1}));t.renderOrder=22,(n.getObjectByName(Qk[e]??e)??n).add(t),this.hitboxMeshes.push(t)}}this.syncOverlayVisibility()}syncOverlayVisibility(){for(let e of this.skeletonLines)e.visible=this.overlays.skeleton;for(let e of this.hurtboxMeshes)e.visible=this.overlays.hurtbox;for(let e of this.hitboxMeshes)e.visible=this.overlays.hitbox}updateOverlays(){let e=this.renderer;if(e!==null)for(let[t,n]of e.labRigs.entries()){let e=this.skeletonLines[t];if(e===void 0||!e.visible)continue;let r=e.geometry.getAttribute(`position`),i=new q,a=new q;sJ.forEach(([e,t],o)=>{let s=n.getObjectByName(e),c=n.getObjectByName(t);s!==void 0&&c!==void 0&&(s.getWorldPosition(i),c.getWorldPosition(a),r.setXYZ(o*2,i.x,i.y,i.z),r.setXYZ(o*2+1,a.x,a.y,a.z))}),r.needsUpdate=!0}}jointWorld(e,t){let n=(this.renderer?.labRigs[e])?.getObjectByName(Qk[t]??t);return n==null?null:n.getWorldPosition(new q)}exportMetrics(){if(this.replay===null)return;let e={contactAlignment:[],maxRootStepMeters:0,footSlideMeters:0,phaseDriftTicks:0};for(let t of this.replay.ticks){let n=t.snapshot.payload.events.find(e=>[`hit`,`counter_hit`,`block`].includes(e.kind)),r=t.snapshot.payload.fighters[0].action_hand;if(n===void 0||r===null)continue;let i=Math.min(t.tick+1,this.replay.ticks.length-1);this.seek(i,!1),this.renderCurrentTick(!1);let a=this.jointWorld(0,r===`left`?`gloveL`:`gloveR`),o=this.jointWorld(1,`head`),c=this.jointWorld(1,`chest`);a!==null&&o!==null&&c!==null&&e.contactAlignment.push({tick:t.tick,kind:n.kind,gloveToHeadMeters:Number(Math.max(0,a.distanceTo(o)-s.head.radius).toFixed(4)),gloveToTorsoMeters:Number(Math.max(0,a.distanceTo(c)-s.torso.radius).toFixed(4))})}this.seek(0,!1);let t=null,n=null;for(let r of this.replay.ticks){this.seek(r.tick,!1),this.renderCurrentTick(!1);let i=this.renderer.labRigs[0].position.x;n!==null&&(e.maxRootStepMeters=Math.max(e.maxRootStepMeters,Math.abs(i-n))),n=i;let a=r.snapshot.payload.fighters[0],o=Math.hypot(a.velocity_x,a.velocity_y),s=this.replay.ticks.slice(Math.max(0,r.tick-30),r.tick+1).some(e=>e.snapshot.payload.fighters[0].is_downed);if(o===0&&!a.is_downed&&!s&&r.snapshot.payload.phase===`fight`){let n=[this.jointWorld(0,`ankleL`),this.jointWorld(0,`ankleR`)].filter(e=>e!==null);t!==null&&n.length===2&&(e.footSlideMeters=Math.max(e.footSlideMeters,Number(Math.max(n[0].distanceTo(t[0]),n[1].distanceTo(t[1])).toFixed(4)))),t=n}else t=null}this.metricsEl.textContent=` contacts: ${e.contactAlignment.map(e=>`${e.kind}@t${e.tick} glove-head ${e.gloveToHeadMeters}m`).join(` · `)} · max root step ${e.maxRootStepMeters.toFixed(3)}m · foot slide ${e.footSlideMeters}m`,window.__labDebug={roots:this.renderer.labRigs.map(e=>e.position.toArray().map(e=>Number(e.toFixed(3)))),graphsActive:this.renderer.graphs!==null,heads:this.renderer.labRigs.map(e=>{let t=e.getObjectByName(Qk.head??`head`);return t===void 0?null:t.getWorldPosition(new q).toArray().map(e=>Number(e.toFixed(3)))})};let r=new Blob([JSON.stringify(e,null,1)],{type:`application/json`}),i=document.createElement(`a`);i.href=URL.createObjectURL(r),i.download=`hands-lab-metrics.json`,i.click(),URL.revokeObjectURL(i.href)}setStatus(e){this.statusEl.textContent!==e&&(this.statusEl.textContent=e)}destroy(){this.destroyed||(this.destroyed=!0,cancelAnimationFrame(this.raf),this.renderer?.destroy(),this.root.replaceChildren())}};function lJ(e){let t=new cJ(e);return t.start().catch(t=>{e.querySelector(`[data-lab-status]`).textContent=`lab failed: ${String(t)}`}),()=>t.destroy()}var uJ={referee:{outfit:Pj,look:hj.referee},corner_blue:{outfit:Fj,look:hj.blueCorner},corner_red:{outfit:Ij,look:hj.redCorner},cutman:{outfit:Lj,look:hj.blueCutman}},dJ=()=>({player_id:`lab`,x:0,y:0,facing:1,facing_x:0,facing_y:-1e3,velocity_x:0,velocity_y:0,stance:`orthodox`,style:`balanced`,defense:`none`,stamina:1e3,maximum_stamina:1e3,conditioning:1e3,guard:700,guard_broken:!1,poise:600,trauma:{head:0,body:0,left_eye:0,right_eye:0,left_cut:0,right_cut:0,swelling:0,bleeding:0},knockdowns:0,warnings:0,deductions:0,stunned_ticks:0,is_downed:!1,action:null,action_hand:null,action_target:null,action_power:null,action_id:null,action_key:null,action_start_tick:0,action_startup_ticks:0,action_active_ticks:0,action_recovery_ticks:0,action_contact_tick:null,queued_actions:0,clinch_startup_ticks:0,clinch_ticks:0,is_foul_recovery_target:!1,taunt_ticks:0,corner_choice:null,get_up_prompt:null,get_up_meter:0,get_up_required:0,get_up_count:0,get_up_window_start_tick:0,get_up_window_end_tick:0,last_input_sequence:-1,injuries:[],blood_volume:1e3}),fJ=.45,pJ=.3,mJ={face:[.25,1.55,1],portrait:[.12,1.62,.62],eyes:[-.2,1.65,.44],floor:[1.62,.3,.18],hand:[.55,1.05,.75],front:[0,1.35,3.4],side:[3.4,1.3,.2],"three-quarter":[2.4,1.5,2.6],top:[.01,4.5,.6],back:[.2,1.4,-3.4],low:[1.8,.5,2.6],wide:[3.4,2.7,3.6]},hJ=class{root;renderer;scene=new u_;camera;graph=null;boxer=null;trails=[];trailGlove=new q;treatEye=new q(0,1.22,.78);treatFacing=new q(0,0,-1);treatTarget=new q;skeletonHelper=null;effects=null;shieldClock=1/0;shieldEvent=0;mouth=new q;headTurn=new rg;burstRim=new Float32Array;burstStump={position:new q,quaternion:new rg,across:new q,scratch:new q};raf=0;previous=performance.now();elapsed=0;params=new URLSearchParams(window.location.search);reactionFired=!1;carnage=null;injuries=[];inflictions=[];killed=!1;vomitClock=0;headAt=new q;statusEl;constructor(e){this.root=e,e.innerHTML=`
HANDS POSE LABloading…
-
`,this.statusEl=e.querySelector(`[data-status]`);let t=e.querySelector(`[data-canvas]`);this.renderer=new AT({canvas:t,antialias:!0,preserveDrawingBuffer:!0}),this.renderer.setPixelRatio(Math.min(2,window.devicePixelRatio||1)),this.renderer.shadowMap.enabled=!0,this.renderer.toneMapping=4,this.camera=new Ox(38,1,.1,60);let n=pJ[this.params.get(`cam`)??`three-quarter`]??pJ[`three-quarter`];this.camera.position.set(...n),this.params.get(`cam`)===`hand`?this.camera.lookAt(.27,.84,.12):this.params.get(`cam`)===`portrait`?this.camera.lookAt(0,1.6,.05):this.params.get(`cam`)===`eyes`?this.camera.lookAt(.01,1.6,.06):this.params.get(`cam`)===`floor`?this.camera.lookAt(1.3,0,-.24):this.params.get(`cam`)===`wide`?this.camera.lookAt(0,.45,-.2):this.camera.lookAt(0,this.params.get(`cam`)===`face`?1.5:1,0),this.setupLighting()}setupLighting(){this.scene.background=new J(`#101318`),this.scene.add(new gx(`#8fa0c8`,`#1a1c22`,1.4));let e=new Fx(`#fff1dc`,2.6);e.position.set(2.5,5,3),e.castShadow=!0,e.shadow.mapSize.set(2048,2048),this.scene.add(e);let t=new Fx(`#9fb8ff`,1.2);t.position.set(-3,3,-3),this.scene.add(t);let n=new Y(new Fy(4,48),new Ab({color:`#3c4a7a`,roughness:.9}));n.rotation.x=-Math.PI/2,n.receiveShadow=!0,this.scene.add(n);let r=new uS(4,16,8952251,3358810);r.position.y=.002,this.scene.add(r)}synthesize(e){let t=this.params.get(`pose`)??`idle`,n=this.params.get(`stance`)===`southpaw`?`southpaw`:`orthodox`,r={...uJ(),stance:n},i=this.params.get(`trauma`);i===`light`&&(r.trauma={head:220,body:260,left_eye:190,right_eye:60,left_cut:40,right_cut:0,swelling:120,bleeding:60}),i===`heavy`&&(r.trauma={head:900,body:700,left_eye:720,right_eye:380,left_cut:520,right_cut:190,swelling:620,bleeding:520}),i===`cut`&&(r.trauma={head:420,body:120,left_eye:380,right_eye:120,left_cut:300,right_cut:0,swelling:260,bleeding:380});let a=i?.split(`,`).map(Number)??[];if(a.length===8&&a.every(Number.isFinite)){let[e,t,n,i,o,s,c,l]=a;r.trauma={head:e,body:t,left_eye:n,right_eye:i,left_cut:o,right_cut:s,swelling:c,bleeding:l}}let o={...uJ(),player_id:`other`,x:0,y:-150,facing_x:0,facing_y:1e3},s=Math.floor(e*30),c=/^(jab|straight|hook|uppercut)_(left|right)(_body)?(_power)?$/.exec(t);if(c!==null){let e=c[1],t=c[2],n=c[3]===`_body`?`body`:`head`,i=c[4]===`_power`?`power`:`normal`,a={jab:[4,2,7],straight:[6,2,10],hook:[7,3,12],uppercut:[8,2,13]}[e],o=a[0]+a[1]+a[2],l=Math.floor(s/(o+12))*(o+12)+6;s>=l&&s=dJ&&t<3.4,r.stunned_ticks=t=fJ&&(t===null||e{let i=Math.min(.05,(r-this.previous)/1e3);this.previous=r,t===null?(this.elapsed=e===null?this.elapsed+i:Number(e),this.step(e===null?i:1/60)):this.step(0),this.renderer.render(this.scene,this.camera),this.raf=requestAnimationFrame(n)};this.raf=requestAnimationFrame(n)}step(e){let t=this.graph;if(t===null)return;let n=this.renderer.domElement.clientWidth,r=this.renderer.domElement.clientHeight;n>0&&r>0&&(this.renderer.domElement.width!==n||this.renderer.domElement.height!==r)&&(this.renderer.setSize(n,r,!1),this.camera.aspect=n/r,this.camera.updateProjectionMatrix());let{fighter:i,opponent:a,sampledTick:o,head:s}=this.synthesize(this.elapsed),c=this.params.get(`pose`)??``;if(/^(hit|block)_/.test(c)){let n=this.elapsed%1.6;if(this.params.has(`freeze`)?!this.reactionFired&&this.elapsed>=.02:n=.27999999999999997){this.reactionFired=!0;let e=this.params.get(`hit`)??`straight`,n=e===`body`?`hook`:e;t.react(`hit`,e===`body`?`body`:`head`,1,n,this.params.get(`hand`)===`left`?`left`:`right`,Number(this.params.get(`amount`)??420))}this.params.get(`pose`)===`knockdown`&&this.params.get(`fall`)===`prone`&&this.elapsed%6=.02:this.elapsed%1.63)){this.shieldClock=0,this.shieldEvent+=1;let e=this.boxer.bone(`head`);e.getWorldQuaternion(this.headTurn),e.getWorldPosition(this.mouth).add(new q(0,.045,.12).applyQuaternion(this.headTurn)),this.effects.ejectMouthpiece(0,this.mouth,this.headTurn,1,this.shieldEvent,1920728,!0)}this.effects?.update(e);for(let[t,n]of[`gloveL`,`gloveR`].entries())this.carnage?.hasGlove(0,t===0?`left`:`right`)===!1?this.trails[t]?.reset():(this.boxer.rig.bones[n].getWorldPosition(this.trailGlove),this.trails[t]?.update(this.trailGlove,e,this.camera.position,e>0));window.__poseLab={head:this.boxer.bone(`head`).getWorldPosition(new q).toArray().map(e=>Number(e.toFixed(3))),gloveL:this.boxer.bone(`gloveL`).getWorldPosition(new q).toArray().map(e=>Number(e.toFixed(3))),gloveR:this.boxer.bone(`gloveR`).getWorldPosition(new q).toArray().map(e=>Number(e.toFixed(3))),ankleL:this.boxer.bone(`ankleL`).getWorldPosition(new q).toArray().map(e=>Number(e.toFixed(3))),ankleR:this.boxer.bone(`ankleR`).getWorldPosition(new q).toArray().map(e=>Number(e.toFixed(3))),kneeL:this.boxer.bone(`kneeL`).getWorldPosition(new q).toArray().map(e=>Number(e.toFixed(3))),kneeR:this.boxer.bone(`kneeR`).getWorldPosition(new q).toArray().map(e=>Number(e.toFixed(3))),metrics:this.boxer.rig.metrics,mouthpiece:this.effects!==null&&this.effects.mouthpiecePosition(0,this.mouth)?this.mouth.toArray().map(e=>Number(e.toFixed(3))):null}}get bloodSetting(){let e=this.params.get(`blood`);return e===`reduced`||e===`off`?e:`full`}startCarnage(){let e=e=>(this.params.get(e)??``).split(`,`).filter(e=>fe.includes(e));this.injuries.push(...e(`injuries`));for(let[t,n]of e(`inflict`).entries())this.inflictions.push({injury:n,at:1+t*.8,done:!1});(this.injuries.length>0||this.inflictions.length>0||[`fatality`,`dead`,`bloodvol`,`dazed`,`vomit`].some(e=>this.params.has(e)))&&this.graph!==null&&(this.effects??=new sW(this.scene),this.effects.setBloodLevel(this.bloodSetting),this.effects.setCamera(this.camera),this.carnage=new Yz(this.effects,XK),this.carnage.attach(0,this.graph))}stepCarnage(e){let t=this.carnage,n=this.graph;if(t===null||n===null||this.effects===null)return;for(let[e,n]of this.inflictions.entries())n.done||this.elapsed=1&&(i!==null||me.includes(r??``))&&(this.killed=!0,i===null?this.kill(t,r):t.die(0,i));let a=this.params.get(`dazed`)===`1`&&!this.killed;n.setDazed(a),this.params.get(`vomit`)===`1`&&(this.vomitClock+=e,this.vomitClock>=3&&(this.vomitClock=0,t.vomit(0,Math.round(this.elapsed*10))));let o=Number(this.params.get(`bloodvol`)??1e3),s=fe.filter(e=>this.injuries.includes(e));t.sync(0,{injuries:s,blood_volume:Number.isFinite(o)?o:1e3},{blood:this.bloodSetting,reducedMotion:!1},e,this.elapsed,a)}kill(e,t){let n=this.boxer,r=this.effects,i=n.bone(`head`);n.root.updateMatrixWorld(!0),i.getWorldQuaternion(this.headTurn),i.getWorldPosition(this.headAt).add(new q(0,.12,.02).applyQuaternion(this.headTurn)),t===`decapitation`||t===`spine_rip`?(r.decapitate(0,this.headAt,this.headTurn,1,31,11105359,YK(n,this.headAt,this.headTurn)),n.setDecapitated(!0)):t===`head_burst`&&(r.burstHead(0,this.headAt,1,31),n.setHeadBurst(!0)),e.fatality(0,t,31,1),e.die(0,`fatality:${t}`)}destroy(){cancelAnimationFrame(this.raf),this.carnage?.dispose(),this.effects?.dispose(),this.graph?.dispose(),this.renderer.dispose(),this.root.replaceChildren()}};function hJ(e){let t=new mJ(e);return t.start().catch(()=>void 0),()=>t.destroy()}var gJ=document.querySelector(`#app`);if(gJ===null)throw Error(`app_root_missing`);var _J,vJ=new URLSearchParams(window.location.search),yJ=window.location.pathname.endsWith(`/hands/lab`)||vJ.get(`lab`)===`1`;if(window.location.pathname.endsWith(`/hands/model-lab`)||vJ.get(`model-lab`)===`1`)_J=hJ(gJ);else if(yJ)_J=cJ(gJ);else{let e=new iJ(gJ);e.start(),_J=()=>e.destroy()}window.addEventListener(`pagehide`,_J,{once:!0}); \ No newline at end of file +`,this.statusEl=e.querySelector(`[data-status]`);let t=e.querySelector(`[data-canvas]`);this.renderer=new AT({canvas:t,antialias:!0,preserveDrawingBuffer:!0}),this.renderer.setPixelRatio(Math.min(2,window.devicePixelRatio||1)),this.renderer.shadowMap.enabled=!0,this.renderer.toneMapping=4,this.camera=new Ox(38,1,.1,60);let n=mJ[this.params.get(`cam`)??`three-quarter`]??mJ[`three-quarter`];this.camera.position.set(...n),this.params.get(`cam`)===`hand`?this.camera.lookAt(.27,.84,.12):this.params.get(`cam`)===`portrait`?this.camera.lookAt(0,1.6,.05):this.params.get(`cam`)===`eyes`?this.camera.lookAt(.01,1.6,.06):this.params.get(`cam`)===`floor`?this.camera.lookAt(1.3,0,-.24):this.params.get(`cam`)===`wide`?this.camera.lookAt(0,.45,-.2):this.camera.lookAt(0,this.params.get(`cam`)===`face`?1.5:1,0),this.setupLighting()}setupLighting(){this.scene.background=new J(`#101318`),this.scene.add(new gx(`#8fa0c8`,`#1a1c22`,1.4));let e=new Fx(`#fff1dc`,2.6);e.position.set(2.5,5,3),e.castShadow=!0,e.shadow.mapSize.set(2048,2048),this.scene.add(e);let t=new Fx(`#9fb8ff`,1.2);t.position.set(-3,3,-3),this.scene.add(t);let n=new Y(new Fy(4,48),new Ab({color:`#3c4a7a`,roughness:.9}));n.rotation.x=-Math.PI/2,n.receiveShadow=!0,this.scene.add(n);let r=new uS(4,16,8952251,3358810);r.position.y=.002,this.scene.add(r)}synthesize(e){let t=this.params.get(`pose`)??`idle`,n=this.params.get(`stance`)===`southpaw`?`southpaw`:`orthodox`,r={...dJ(),stance:n},i=this.params.get(`trauma`);i===`light`&&(r.trauma={head:220,body:260,left_eye:190,right_eye:60,left_cut:40,right_cut:0,swelling:120,bleeding:60}),i===`heavy`&&(r.trauma={head:900,body:700,left_eye:720,right_eye:380,left_cut:520,right_cut:190,swelling:620,bleeding:520}),i===`cut`&&(r.trauma={head:420,body:120,left_eye:380,right_eye:120,left_cut:300,right_cut:0,swelling:260,bleeding:380});let a=i?.split(`,`).map(Number)??[];if(a.length===8&&a.every(Number.isFinite)){let[e,t,n,i,o,s,c,l]=a;r.trauma={head:e,body:t,left_eye:n,right_eye:i,left_cut:o,right_cut:s,swelling:c,bleeding:l}}let o={...dJ(),player_id:`other`,x:0,y:-150,facing_x:0,facing_y:1e3},s=Math.floor(e*30),c=/^(jab|straight|hook|uppercut)_(left|right)(_body)?(_power)?$/.exec(t);if(c!==null){let e=c[1],t=c[2],n=c[3]===`_body`?`body`:`head`,i=c[4]===`_power`?`power`:`normal`,a={jab:[4,2,7],straight:[6,2,10],hook:[7,3,12],uppercut:[8,2,13]}[e],o=a[0]+a[1]+a[2],l=Math.floor(s/(o+12))*(o+12)+6;s>=l&&s=fJ&&t<3.4,r.stunned_ticks=t=pJ&&(t===null||e{let i=Math.min(.05,(r-this.previous)/1e3);this.previous=r,t===null?(this.elapsed=e===null?this.elapsed+i:Number(e),this.step(e===null?i:1/60)):this.step(0),this.renderer.render(this.scene,this.camera),this.raf=requestAnimationFrame(n)};this.raf=requestAnimationFrame(n)}step(e){let t=this.graph;if(t===null)return;let n=this.renderer.domElement.clientWidth,r=this.renderer.domElement.clientHeight;n>0&&r>0&&(this.renderer.domElement.width!==n||this.renderer.domElement.height!==r)&&(this.renderer.setSize(n,r,!1),this.camera.aspect=n/r,this.camera.updateProjectionMatrix());let{fighter:i,opponent:a,sampledTick:o,head:s}=this.synthesize(this.elapsed),c=this.params.get(`pose`)??``;if(/^(hit|block)_/.test(c)){let n=this.elapsed%1.6;if(this.params.has(`freeze`)?!this.reactionFired&&this.elapsed>=.02:n=.27999999999999997){this.reactionFired=!0;let e=this.params.get(`hit`)??`straight`,n=e===`body`?`hook`:e;t.react(`hit`,e===`body`?`body`:`head`,1,n,this.params.get(`hand`)===`left`?`left`:`right`,Number(this.params.get(`amount`)??420))}this.params.get(`pose`)===`knockdown`&&this.params.get(`fall`)===`prone`&&this.elapsed%6=.02:this.elapsed%1.63)){this.shieldClock=0,this.shieldEvent+=1;let e=this.boxer.bone(`head`);e.getWorldQuaternion(this.headTurn),e.getWorldPosition(this.mouth).add(new q(0,.045,.12).applyQuaternion(this.headTurn)),this.effects.ejectMouthpiece(0,this.mouth,this.headTurn,1,this.shieldEvent,1920728,!0)}this.effects?.update(e);for(let[t,n]of[`gloveL`,`gloveR`].entries())this.carnage?.hasGlove(0,t===0?`left`:`right`)===!1?this.trails[t]?.reset():(this.boxer.rig.bones[n].getWorldPosition(this.trailGlove),this.trails[t]?.update(this.trailGlove,e,this.camera.position,e>0));window.__poseLab={head:this.boxer.bone(`head`).getWorldPosition(new q).toArray().map(e=>Number(e.toFixed(3))),gloveL:this.boxer.bone(`gloveL`).getWorldPosition(new q).toArray().map(e=>Number(e.toFixed(3))),gloveR:this.boxer.bone(`gloveR`).getWorldPosition(new q).toArray().map(e=>Number(e.toFixed(3))),ankleL:this.boxer.bone(`ankleL`).getWorldPosition(new q).toArray().map(e=>Number(e.toFixed(3))),ankleR:this.boxer.bone(`ankleR`).getWorldPosition(new q).toArray().map(e=>Number(e.toFixed(3))),kneeL:this.boxer.bone(`kneeL`).getWorldPosition(new q).toArray().map(e=>Number(e.toFixed(3))),kneeR:this.boxer.bone(`kneeR`).getWorldPosition(new q).toArray().map(e=>Number(e.toFixed(3))),metrics:this.boxer.rig.metrics,mouthpiece:this.effects!==null&&this.effects.mouthpiecePosition(0,this.mouth)?this.mouth.toArray().map(e=>Number(e.toFixed(3))):null}}get bloodSetting(){let e=this.params.get(`blood`);return e===`reduced`||e===`off`?e:`full`}startCarnage(){let e=e=>(this.params.get(e)??``).split(`,`).filter(e=>fe.includes(e));this.injuries.push(...e(`injuries`));for(let[t,n]of e(`inflict`).entries())this.inflictions.push({injury:n,at:1+t*.8,done:!1});(this.injuries.length>0||this.inflictions.length>0||[`fatality`,`dead`,`bloodvol`,`dazed`,`vomit`].some(e=>this.params.has(e)))&&this.graph!==null&&(this.effects??=new sW(this.scene),this.effects.setBloodLevel(this.bloodSetting),this.effects.setCamera(this.camera),this.carnage=new Yz(this.effects,ZK),this.carnage.attach(0,this.graph))}stepCarnage(e){let t=this.carnage,n=this.graph;if(t===null||n===null||this.effects===null)return;for(let[e,n]of this.inflictions.entries())n.done||this.elapsed=1&&(i!==null||me.includes(r??``))&&(this.killed=!0,i===null?this.kill(t,r):t.die(0,i));let a=this.params.get(`dazed`)===`1`&&!this.killed;n.setDazed(a),this.params.get(`vomit`)===`1`&&(this.vomitClock+=e,this.vomitClock>=3&&(this.vomitClock=0,t.vomit(0,Math.round(this.elapsed*10))));let o=Number(this.params.get(`bloodvol`)??1e3),s=fe.filter(e=>this.injuries.includes(e));t.sync(0,{injuries:s,blood_volume:Number.isFinite(o)?o:1e3},{blood:this.bloodSetting,reducedMotion:!1},e,this.elapsed,a)}kill(e,t){let n=this.boxer,r=this.effects,i=n.bone(`head`);n.root.updateMatrixWorld(!0),i.getWorldQuaternion(this.headTurn),i.getWorldPosition(this.headAt).add(new q(0,.12,.02).applyQuaternion(this.headTurn)),t===`decapitation`||t===`spine_rip`?(r.decapitate(0,this.headAt,this.headTurn,1,31,11105359,XK(n,this.headAt,this.headTurn)),n.setDecapitated(!0)):t===`head_burst`&&(r.burstHead(0,this.headAt,1,31),n.setHeadBurst(!0)),e.fatality(0,t,31,1),e.die(0,`fatality:${t}`)}destroy(){cancelAnimationFrame(this.raf),this.carnage?.dispose(),this.effects?.dispose(),this.graph?.dispose(),this.renderer.dispose(),this.root.replaceChildren()}};function gJ(e){let t=new hJ(e);return t.start().catch(()=>void 0),()=>t.destroy()}var _J=document.querySelector(`#app`);if(_J===null)throw Error(`app_root_missing`);var vJ,yJ=new URLSearchParams(window.location.search),bJ=window.location.pathname.endsWith(`/hands/lab`)||yJ.get(`lab`)===`1`;if(window.location.pathname.endsWith(`/hands/model-lab`)||yJ.get(`model-lab`)===`1`)vJ=gJ(_J);else if(bJ)vJ=lJ(_J);else{let e=new aJ(_J);e.start(),vJ=()=>e.destroy()}window.addEventListener(`pagehide`,vJ,{once:!0}); \ No newline at end of file diff --git a/web/hands/src/render/renderer-gpu.test.ts b/web/hands/src/render/renderer-gpu.test.ts index 4323379a..217f7024 100644 --- a/web/hands/src/render/renderer-gpu.test.ts +++ b/web/hands/src/render/renderer-gpu.test.ts @@ -88,15 +88,30 @@ describe("quality tiers on the graphics card", () => { expect(gl.created.programs).toBe(programs); expect(key.castShadow).toBe(true); expect(key.shadow.intensity).toBe(0); - // The shadow map is no longer drawn, and its depth target is freed. - expect(key.shadow.map).toBeNull(); + // The shadow map is no longer drawn, and its depth target is freed. Every lit shader still samples a shadow + // map, so a tiny one, drawn once, stays in its place: with none the graphics card refuses to draw anything lit. expect(gl.alive(depth)).toBe(false); + const kept = key.shadow.map; + expect(kept?.width).toBe(16); + expect(gl.alive(glTexture(internals.renderer, kept?.depthTexture))).toBe(true); + expect(key.shadow.autoUpdate).toBe(false); + expect(key.shadow.needsUpdate).toBe(false); + fight.labFrame(time + 0.15); + expect(key.shadow.map).toBe(kept); setScale(0.7); fight.labFrame(time + 0.2); expect(gl.created.programs).toBe(programs); expect(key.shadow.intensity).toBe(1); expect(key.shadow.map).not.toBeNull(); expect(key.shadow.map?.width).toBe(1024); + // Down and up again, as a struggling client goes: a map is bound after every frame. + for (const [step, scale] of [0.55, 1, 0.55, 0.85].entries()) { + setScale(scale); + fight.labFrame(time + 0.3 + step / 10); + expect(key.shadow.map?.width).toBe(scale === 0.55 ? 16 : 2048); + expect(gl.alive(glTexture(internals.renderer, key.shadow.map?.depthTexture))).toBe(true); + } + expect(gl.created.programs).toBe(programs); }); }); diff --git a/web/hands/src/render/renderer.ts b/web/hands/src/render/renderer.ts index 4f4e37e6..5fa8504c 100644 --- a/web/hands/src/render/renderer.ts +++ b/web/hands/src/render/renderer.ts @@ -99,20 +99,27 @@ export function compileForComposer( const KEY_SHADOW_BIAS = -0.0004; /** Past the shadow camera's far plane, so every lit pixel skips the shadow lookups. */ const SKIPPED_SHADOW_BIAS = 10; +/** The side of the shadow map kept while the shadow is off. */ +const SKIPPED_SHADOW_SIZE = 16; /** * Sets the key light's shadow for a quality tier without touching castShadow, which is part of every * material's program key: flipping it would recompile every shader in one frame on the slowest - * devices. Turned off, the shadow stops being drawn, its depth target is freed, and it is hidden. + * devices. Turned off, the shadow stops being drawn and is hidden, and its depth target is swapped for a + * tiny one drawn once. It is never left without one: every lit shader still samples it, and with no map + * three binds a stand-in that is no comparison texture, which the graphics card refuses, so nothing lit is drawn. */ export function setKeyShadowTier(shadow: THREE.LightShadow, off: boolean, size: number): void { + const side = off ? SKIPPED_SHADOW_SIZE : size; shadow.autoUpdate = !off; shadow.intensity = off ? 0 : 1; shadow.bias = off ? SKIPPED_SHADOW_BIAS : KEY_SHADOW_BIAS; - if ((off && shadow.map !== null) || shadow.mapSize.x !== size) { - shadow.mapSize.set(size, size); + if (shadow.mapSize.x !== side) { + shadow.mapSize.set(side, side); shadow.map?.dispose(); shadow.map = null; + // The next frame draws the map at its new size, whether or not it goes on being drawn after that. + shadow.needsUpdate = true; } } From ed9dd56e315e28bd6e91982e81fa6baa7b2cff96 Mon Sep 17 00:00:00 2001 From: user1303836 Date: Tue, 17 Nov 2026 01:21:09 -0500 Subject: [PATCH 2/2] test(hands): pin the kept shadow map as a comparison texture --- web/hands/src/render/renderer-gpu.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/web/hands/src/render/renderer-gpu.test.ts b/web/hands/src/render/renderer-gpu.test.ts index 217f7024..ce7b640f 100644 --- a/web/hands/src/render/renderer-gpu.test.ts +++ b/web/hands/src/render/renderer-gpu.test.ts @@ -94,6 +94,8 @@ describe("quality tiers on the graphics card", () => { const kept = key.shadow.map; expect(kept?.width).toBe(16); expect(gl.alive(glTexture(internals.renderer, kept?.depthTexture))).toBe(true); + // The comparison is what the graphics card checks the shadow sampler's texture for. + expect(kept?.depthTexture?.compareFunction).toBe(THREE.LessEqualCompare); expect(key.shadow.autoUpdate).toBe(false); expect(key.shadow.needsUpdate).toBe(false); fight.labFrame(time + 0.15); @@ -104,7 +106,7 @@ describe("quality tiers on the graphics card", () => { expect(key.shadow.intensity).toBe(1); expect(key.shadow.map).not.toBeNull(); expect(key.shadow.map?.width).toBe(1024); - // Down and up again, as a struggling client goes: a map is bound after every frame. + // Down and up again, as a struggling client goes: a map with a live depth target is there after every frame. for (const [step, scale] of [0.55, 1, 0.55, 0.85].entries()) { setScale(scale); fight.labFrame(time + 0.3 + step / 10);