/* Savanna Chase (c) 2026 CyberMax. All rights reserved. Includes three.js r170 (c) 2010-2024 three.js authors, MIT licence. */ var p0=Object.defineProperty;var Vp=(r,e)=>{for(var t in e)p0(r,t,{get:e[t],enumerable:!0})};var zr={};Vp(zr,{ABILITY:()=>to,ACT:()=>Rc,BIOMES:()=>_n,BIOME_IDS:()=>no,BRIGHT:()=>qs,CHAPTERS:()=>io,CHUNK:()=>Ye,DT:()=>rt,EV:()=>so,FACTS:()=>co,FREE_BIOMES:()=>Qa,FREE_PREDATORS:()=>f0,FREE_PREY:()=>kc,HALF_W:()=>$e,LIVE_TICKS:()=>Pc,MAX_TICKS:()=>eo,OBJECTIVES:()=>rf,PREDATORS:()=>Lc,PRED_HOME:()=>Uc,PREY:()=>Ic,PREY_HOME:()=>Nc,SPECIES:()=>Te,TICK:()=>yn,TODS:()=>Kp,VERSION:()=>Cc,WEATHER:()=>Dc,applyInput:()=>Mn,boardRun:()=>D0,burrowNear:()=>Fc,byId:()=>Ne,challengeOpts:()=>Xc,chunkAt:()=>Bt,dailyOpts:()=>Xs,dailySeed:()=>$p,dayNumber:()=>ro,dcos:()=>Yt,decodeChallenge:()=>qc,decodeInputs:()=>li,detectR:()=>tf,dsin:()=>kt,encodeChallenge:()=>jc,encodeInputs:()=>oi,hash3:()=>qn,heightAt:()=>et,inCover:()=>Qp,inWater:()=>Or,isNight:()=>Oc,liveOpts:()=>Wc,liveScores:()=>lo,newRun:()=>ai,replay:()=>Vc,rng:()=>xn,roomMode:()=>ao,roomOpts:()=>oo,scentDir:()=>Hc,stars:()=>Gc,stateCode:()=>Ys,step:()=>Xn,verifyRoom:()=>N0,verifyRun:()=>U0});var Cc=1,yn=30,rt=.03333333333333333,eo=30*60*10,$e=34,Pc=30*120,Ye=48,ln=3.141592653589793,js=2*ln,yt=(r,e,t)=>rt?t:r;function kt(r){r-=js*Math.floor(r/js+.5),r>ln/2?r=ln-r:r<-ln/2&&(r=-ln-r);let e=r*r;return r*(1-e/6*(1-e/20*(1-e/42*(1-e/72*(1-e/110)))))}var Yt=r=>kt(r+ln/2),wc=2147483647;function xn(r){let e=Math.floor(Math.abs(r))%(wc-1)+1,t=()=>(e=e*48271%wc,(e-1)/(wc-1));return t.state=()=>e,t}function qn(r,e,t){let n=Math.imul(r|0,374761393)^Math.imul(e|0,668265263)^Math.imul(t|0,1274126177);return n=Math.imul(n^n>>>13,1103515245),((n^n>>>16)>>>0)/4294967296}var Ja=r=>r*r*(3-2*r);function Za(r,e,t){let n=Math.floor(e),i=Math.floor(t),s=Ja(e-n),a=Ja(t-i),o=qn(n,i,r),l=qn(n+1,i,r),c=qn(n,i+1,r),h=qn(n+1,i+1,r);return o+(l-o)*s+(c-o)*a+(o-l-c+h)*s*a}var Te={deer:{side:"prey",name:"Red Deer",r:.5,cruise:8.5,top:15.2,accel:9,turn:2.8,drain:.12,regen:.1,jump:2,jt:19,ab:"leap",herd:5,agile:.4,h:1.2,cd:3},zebra:{side:"prey",name:"Zebra",r:.6,cruise:8,top:14.4,accel:8,turn:2.4,drain:.09,regen:.1,jump:1.3,jt:16,ab:"kick",herd:8,agile:.25,h:1.35,cd:5},wildebeest:{side:"prey",name:"Wildebeest",r:.6,cruise:9,top:15.6,accel:9,turn:2.6,drain:.1,regen:.11,jump:1.4,jt:16,ab:"stampede",herd:10,agile:.35,h:1.3,cd:10},rabbit:{side:"prey",name:"Rabbit",r:.25,cruise:7,top:13,accel:13,turn:4.6,drain:.12,regen:.13,jump:.9,jt:12,ab:"burrow",herd:0,agile:.6,h:.35,cd:2},horse:{side:"prey",name:"Wild Horse",r:.6,cruise:9,top:15.8,accel:8,turn:2.3,drain:.075,regen:.14,jump:1.5,jt:17,ab:"surge",herd:6,agile:.25,h:1.5,cd:25},lion:{side:"pred",name:"Lioness",r:.6,cruise:6,top:15.8,accel:11,turn:2.6,drain:.2,regen:.06,jump:1.6,jt:16,ab:"stalk",reach:3.2,h:1.1,cd:1},leopard:{side:"pred",name:"Leopard",r:.45,cruise:6,top:16.6,accel:16,turn:2.9,drain:.28,regen:.06,jump:2,jt:15,ab:"burst",reach:3,h:.75,cd:8},wolf:{side:"pred",name:"Grey Wolf",r:.45,cruise:8,top:13.4,accel:9,turn:2.8,drain:.045,regen:.06,jump:1.6,jt:15,ab:"command",reach:2.6,h:.85,cd:.4},bear:{side:"pred",name:"Brown Bear",r:.85,cruise:5,top:14.5,accel:8,turn:1.7,drain:.22,regen:.05,jump:1,jt:14,ab:"charge",reach:3,h:1.3,cd:6},eagle:{side:"pred",name:"Bald Eagle",r:.5,cruise:13,top:19,accel:8,turn:2.2,drain:.1,regen:.08,jump:0,jt:0,ab:"dive",reach:1.8,h:.6,cd:3,fly:24},croc:{side:"pred",name:"Crocodile",r:.6,cruise:2.5,top:9,accel:14,turn:1.5,drain:.4,regen:.1,jump:0,jt:0,ab:"lunge",reach:3.4,h:.5,cd:3}},Ic=["deer","zebra","wildebeest","horse","rabbit"],Lc=["lion","leopard","wolf","bear","eagle"],kc=["deer","zebra","wildebeest"],f0=["lion"],to={stampede:"Stampede",leap:"Leap",kick:"Kick",burrow:"Burrow",surge:"Second wind",stalk:"Stalk",burst:"Burst",command:"Pack call",charge:"Charge",dive:"Dive",lunge:"Lunge"},_n={savanna:{name:"Savanna",pack:null,amp:2,freq:.012,grass:1.6,trees:.35,tree:"acacia",rocks:.5,logs:.15,bush:.6,river:.14,burrow:.6,mud:0,drift:0,cliff:0,enc:{lion:4,leopard:2.5},croc:!0,herd:["zebra","wildebeest"],hunt:{lion:["zebra","wildebeest"],leopard:["wildebeest"],wolf:["zebra"],bear:["zebra"],eagle:["rabbit"]}},forest:{name:"Forest",pack:"wild",amp:3.2,freq:.016,grass:.9,trees:2.6,tree:"pine",rocks:.7,logs:.9,bush:.8,river:.09,burrow:.4,mud:.2,drift:0,cliff:0,enc:{wolf:4,bear:3,eagle:.6},croc:!1,herd:["deer","horse"],hunt:{lion:["deer"],leopard:["deer"],wolf:["deer","horse"],bear:["deer"],eagle:["rabbit"]}},snow:{name:"Snow",pack:"snow",amp:3.6,freq:.014,grass:.2,trees:1.3,tree:"snowpine",rocks:.8,logs:.4,bush:.2,river:.05,burrow:.5,mud:0,drift:1.4,cliff:0,enc:{wolf:5,eagle:1.4,bear:.8},croc:!1,herd:["deer","horse"],hunt:{lion:["deer"],leopard:["deer"],wolf:["deer","horse"],bear:["deer"],eagle:["rabbit"]}},canyon:{name:"Canyon",pack:"canyon",amp:4.2,freq:.02,grass:.3,trees:.25,tree:"juniper",rocks:1.8,logs:.1,bush:.7,river:.06,burrow:.5,mud:0,drift:0,cliff:1.1,enc:{eagle:2.2,wolf:3,bear:1},croc:!1,herd:["horse"],hunt:{lion:["horse"],leopard:["horse"],wolf:["horse"],bear:["horse"],eagle:["rabbit"]}},wetlands:{name:"Wetlands",pack:"wetlands",amp:1,freq:.01,grass:2,trees:.7,tree:"willow",rocks:.2,logs:.6,bush:.4,river:.42,burrow:.3,mud:1.5,drift:0,cliff:0,enc:{lion:3,leopard:1},croc:!0,herd:["zebra","wildebeest"],hunt:{lion:["zebra","wildebeest"],leopard:["wildebeest"],wolf:["horse"],bear:["horse"],eagle:["rabbit"]}}},no=Object.keys(_n),Qa=["savanna","forest"],Kp=[.27,.42,.58,.74,.9],qs=[.42,.5,.56],Dc={savanna:["clear","clear","dust","rain"],forest:["clear","fog","rain","clear"],snow:["clear","snow","fog","snow"],canyon:["clear","dust","clear","rain"],wetlands:["clear","rain","fog","clear"]},Uc={lion:"savanna",leopard:"savanna",wolf:"forest",bear:"forest",eagle:"canyon"},Nc={zebra:"savanna",wildebeest:"savanna",deer:"forest",horse:"wetlands",rabbit:"snow"},io={savanna:{name:"The Long Grass",levels:[{name:"First Light",sp:"wildebeest",goal:{t:"reach",n:400},tod:.3,w:"clear",line:"Reach the acacia line. Stay with the herd.",enc:{leopard:1}},{name:"Tall Grass",sp:"zebra",goal:{t:"herd",n:600,k:4},tod:.45,w:"clear",line:"Lions hide in tall grass. Keep 4 zebras alive.",enc:{lion:1}},{name:"The Crossing",sp:"wildebeest",goal:{t:"reach",n:700},tod:.62,w:"dust",line:"Cross the river. Watch the ripples.",river:1},{name:"Lone Runner",sp:"zebra",goal:{t:"lone",n:250},tod:.72,w:"clear",line:"Break away from the herd for 250 m."},{name:"Night Hunt",side:"pred",sp:"lion",goal:{t:"hunt",n:2},tod:.9,w:"clear",line:"Be the lioness. Stalk in the grass, then charge."}]},forest:{name:"Pines and Shadows",levels:[{name:"Morning Mist",sp:"deer",goal:{t:"reach",n:450},tod:.3,w:"fog",line:"Leap the fallen logs."},{name:"The Pack",sp:"deer",goal:{t:"survive",n:50},tod:.5,w:"clear",line:"Wolves flank. Zig-zag when they close in.",enc:{wolf:1}},{name:"Bear Country",sp:"horse",goal:{t:"reach",n:800},tod:.6,w:"rain",line:"Bears charge from the trees. Save your second wind.",enc:{bear:1}},{name:"Herd Leader",sp:"horse",goal:{t:"herd",n:900,k:3},tod:.7,w:"clear",line:"Bring 3 of your herd through."},{name:"Lead the Pack",side:"pred",sp:"wolf",goal:{t:"hunt",n:2},tod:.8,w:"clear",line:"Lead your pack. Call a flank, then close in."}]},snow:{name:"White Silence",levels:[{name:"Fresh Snow",sp:"rabbit",goal:{t:"reach",n:350},tod:.35,w:"snow",line:"Dive into burrows to lose the hunter."},{name:"Shadow Above",sp:"rabbit",goal:{t:"survive",n:45},tod:.5,w:"clear",line:"When the shadow tightens, dodge.",enc:{eagle:1}},{name:"Drift Line",sp:"deer",goal:{t:"reach",n:700},tod:.62,w:"snow",line:"Drifts slow you down. Wolves do not mind.",enc:{wolf:1}},{name:"Blizzard",sp:"horse",goal:{t:"herd",n:800,k:3},tod:.74,w:"snow",line:"Keep the herd together in the storm."},{name:"Winter Pack",side:"pred",sp:"wolf",goal:{t:"hunt",n:3},tod:.86,w:"clear",line:"Test the herd. Find the tired one."}]},canyon:{name:"Red Walls",levels:[{name:"Dry Wash",sp:"horse",goal:{t:"reach",n:500},tod:.32,w:"clear",line:"Find the gaps between the rock walls."},{name:"Talons",sp:"rabbit",goal:{t:"survive",n:45},tod:.5,w:"clear",line:"Eagles strike from above. Dodge the dive.",enc:{eagle:1}},{name:"Mesa Run",sp:"horse",goal:{t:"reach",n:800},tod:.64,w:"dust",line:"Wolves work the canyon floor.",enc:{wolf:1}},{name:"High Road",sp:"horse",goal:{t:"lone",n:300},tod:.7,w:"clear",line:"Go alone for 300 m."},{name:"Stoop",side:"pred",sp:"eagle",goal:{t:"hunt",n:2},tod:.55,w:"clear",line:"Be the eagle. Dive when the shadow is on them."}]},wetlands:{name:"Delta Floods",levels:[{name:"Reed Beds",sp:"horse",goal:{t:"reach",n:500},tod:.3,w:"fog",line:"Mud slows you. Keep to the dry ground."},{name:"Still Water",sp:"zebra",goal:{t:"reach",n:700},tod:.5,w:"clear",line:"Crocodiles wait at the crossings.",river:1},{name:"Swimming Lions",sp:"wildebeest",goal:{t:"herd",n:800,k:4},tod:.7,w:"rain",line:"These lions swim. Stay in the herd.",enc:{lion:1}},{name:"Flood Run",sp:"zebra",goal:{t:"survive",n:60},tod:.78,w:"rain",line:"One minute. Every crossing."},{name:"Delta Pride",side:"pred",sp:"lion",goal:{t:"hunt",n:3},tod:.88,w:"clear",line:"Hunt across the water."}]}};function ro(r){return Math.floor(Date.UTC(+r.slice(0,4),+r.slice(5,7)-1,+r.slice(8,10))/864e5)}function $p(r){return(r*7919+6151)%2147483646+1}function Xs(r){let e=$p(r),t=xn(e),n=Qa[Math.floor(t()*Qa.length)],i=_n[n].herd.filter(l=>kc.includes(l)),s=i[Math.floor(t()*i.length)],a=qs[Math.floor(t()*qs.length)],o=Dc[n][Math.floor(t()*4)];return{mode:"daily",daily:r,seed:e,biome:n,sp:s,side:"prey",tod:a,weather:o}}function et(r,e,t){let n=r.B,i=r.seed%1e5,a=(Za(i,e*n.freq,t*n.freq)*.62+Za(i+7,e*n.freq*2.3,t*n.freq*2.3)*.28+Za(i+13,e*.11,t*.11)*.1-.5)*2*n.amp,o=e<0?-e:e;if(o>$e-6){let c=o-($e-6),h=c<14?Ja(c/14):1;a+=r.biome==="canyon"?h*6+Math.min(c,40)*Math.min(c,40)*.012:h*1.8+Za(i+29,e*.006,t*.006)*Math.min(1,c/70)*n.amp*7}let l=Bt(r,Math.floor(t/Ye));if(l.river){let c=Zp(l.river,t);c>0&&(a=Math.min(a,.2)-c)}for(let c of l.ledges)e>c.x0&&ec.z0&&t0?Ja(t<1?t:1)*1.6:0}function Or(r,e,t){let n=Bt(r,Math.floor(t/Ye));return!!(n.river&&Zp(n.river,t)>.18)}function Bt(r,e){let t=r.chunks.get(e);if(t)return t;if(r.chunks.size>64)for(let d of r.chunks.keys())d{let p=n[d]*(d==="trees"||d==="rocks"?4:2.5);return Math.floor(p)+(i()(i()*2-1)*($e-3),c=()=>s+i()*Ye,h=r.opts.river&&e===6;if(!a&&(h||e>3&&i()-$e+2&&t.ledges.push({x0:-$e-8,x1:d-p/2,z0:m,z1:m+f,h:x}),d+p/2<$e-2&&t.ledges.push({x0:d+p/2,x1:$e+8,z0:m,z1:m+f,h:x})}}if(t.spots=[],!a){let d=xn(Math.floor(qn(e,r.seed%1000003,177)*2147483e3)+1),p=(f,g,v)=>!t.obs.some(b=>(b.x-f)*(b.x-f)+(b.z-g)*(b.z-g)<(b.r+v+1)*(b.r+v+1))&&!(t.river&&Math.abs(g-t.river.z){p(g,v,b)&&t.spots.push({k:f,x:g,z:v,r:b,used:0})};if(d()<.8&&m("graze",(d()*2-1)*15,s+4+d()*38,3.4),d()<.65){let f=(d()*2-1)*12,g=s+d()*30;for(let v=0;v<3;v++)m("shoot",f+(d()-.5)*3,g+v*5,1.5)}d()<.34&&m("water",(d()*2-1)*16,s+10+d()*28,4.6);let x=t.obs.find(f=>f.k==="tree"&&Math.abs(f.x)<22);x&&d()<.7&&t.spots.push({k:"shade",x:x.x,z:x.z-2.6,r:3.6,used:0})}let u=o("burrow")+(r.sp0==="rabbit"?3:0);if(!a)for(let d=u;d--;)t.burrows.push({x:l(),z:c()});if(t.river&&(t.obs=t.obs.filter(d=>Math.abs(d.z-t.river.z)>t.river.w/2+2),t.burrows=t.burrows.filter(d=>Math.abs(d.z-t.river.z)>t.river.w/2+2),n.croc&&r.opts.enc!==!1)){let d=1+(i()<.5?1:0);for(let p=0;p!(p.x>d.x0-2&&p.xd.z0-2&&p.z{let n=Jp(r,e,t);return!!(n&&(n.k==="grass"||n.k==="fern"||n.k==="reed"))};function m0(r,e){if(Or(r,e.x,e.z))return"water";let t=Jp(r,e.x,e.z);return t?t.k:r.biome==="snow"?"snow":r.biome==="canyon"?"rock":r.biome==="forest"?"litter":r.biome==="wetlands"?"mud":"dirt"}var g0={water:.45,mud:.72,drift:.66,grass:.94,reed:.88,fern:.95};function jn(r,e,t,n,i,s={}){let a=Te[e],o={id:r.nextId++,sp:e,side:a.side,x:t,z:n,y:0,a:i,spd:a.cruise*.6,lat:0,stam:1,winded:!1,air:0,airT:0,jumpH:0,stun:0,dodge:0,dodgeCd:0,abCd:0,abT:0,alive:!0,gone:0,st:"run",t:0,tgt:0,lunge:0,hidden:0,ctl:-1,role:"",lone:0,...s};return o.y=et(r,t,n),r.agents.push(o),o}var Ne=(r,e)=>r.agents.find(t=>t.id===e),at=(r,e)=>(r.x-e.x)*(r.x-e.x)+(r.z-e.z)*(r.z-e.z);function ai(r,e={}){let t=e.level?io[e.level.biome].levels[e.level.i]:null,n=(t?e.level.biome:e.biome)||"savanna",i=t&&t.side||e.side||"prey",s=t&&t.sp||e.sp||(i==="pred"?"lion":"zebra"),a=xn(r),o={v:1,seed:r,opts:{...e,river:e.river||t&&t.river},mode:e.mode||(t?"level":"endless"),lvl:t,biome:n,B:_n[n],side:i,sp0:s,rand:a,chunks:new Map,tick:0,agents:[],nextId:1,events:[],pin:[],humans:[],over:!1,result:"",score:0,grazed:0,drinks:0,shoots:0,rests:0,boost:0,boostT:0,obj:null,objN:0,objs:0,dist:0,lone:0,close:0,combo:0,comboT:0,hunts:0,misses:0,encNext:45,encN:0,huntT:0,nextHunt:0,tod:e.tod??(t?t.tod:qs[Math.floor(a()*qs.length)]),weather:e.weather||(t?t.w:(a(),"clear")),cmd:0,stotOk:0,giveups:0,eaten:0,best:0,slow:0,goal:t?t.goal:null,won:!1};o.light=()=>o.tod<.22||o.tod>.8?o.tod:Math.min(Math.max(o.tod,.68),o.tod+o.tick/(30*1500));let l=e.players||[{side:i,sp:s}];l.forEach((h,u)=>{let d=jn(o,h.sp,(u-(l.length-1)/2)*3.2,4-u*1.5,0,{ctl:u});o.humans.push(d.id),o.pin.push(8)}),o.me=o.humans[0];let c=Ne(o,o.me);if(i==="prey")ef(o,s,c.z,Te[s].herd);else if(o.nextHunt=30*1,s==="wolf")for(let h=0;h<3;h++)jn(o,"wolf",c.x+(h-1)*4,c.z-3-h,0,{pack:1,role:["L","C","R"][h]});if(e.ghost){let h=e.ghost,u=jn(o,h.sp,c.x+(h.side==="pred",0),h.side==="pred"?c.z-40:c.z+2,0,{ghost:1,ctl:99});o.ghost={id:u.id,inputs:h.inputs||[],i:0,cur:8}}return o}function ef(r,e,t,n,i=0){let s=r.rand,a=[],o=Ne(r,r.humans[0]);for(let l=0;l(yt(Math.round(r*4),-4,4)+4)*2+(e?1:0);function oi(r){let e=0,t="";for(let[n,i]of r)i<0||i>21||n12e4||!/^([0-9a-z]{1,4}[A-V])*$/.test(r))return null;let e=[],t=0;for(let n of r.matchAll(/([0-9a-z]{1,4})([A-V])/g))t+=parseInt(n[1],36),e.push([t,n[2].charCodeAt(0)-65]);return e}function Mn(r,e,t){let n=e==="ghost"?r.ghost&&r.ghost.id:r.humans[e],i=n&&Ne(r,n);if(i){if(t<18){e==="ghost"?r.ghost.cur=t:r.pin[e]=t;return}i.ev=(i.ev||0)|1<({steer:(Math.floor(r/2)-4)/4,sprint:!!(r&1)});function Xn(r){if(r.over)return r;if(r.events.length=0,r.tick++,r.ghost){let i=r.ghost;for(;i.ii.alive&&i.ctl>=0)||e,n=r.B;if(r.side==="prey"&&r.opts.enc!==!1&&t.alive){for(;Bt(r,Math.floor((t.z+60)/Ye)).crocs.length&&!1;);if(b0(r,t),t.z>=r.encNext){let i=r.agents.filter(a=>a.side==="pred"&&a.alive&&!a.ghost&&a.sp!=="croc"&&a.st!=="tired").length,s=t.z<600?1:t.z<1500?2:3;if(i=r.nextHunt&&y0(r,e);for(let i of r.agents){if(!i.alive){i.gone>0&&i.gone--;continue}let s;i.ghost?s=Wp(r.ghost.cur):i.ctl>=0?s=Wp(r.pin[i.ctl]):s=i.side==="prey"?T0(r,i):A0(r,i),_0(r,i,s)}for(let i of r.agents)i.alive&&i.side==="pred"&&C0(r,i);r.agents=r.agents.filter(i=>i.alive||i.gone>0||i.ctl>=0||i.ghost);for(let i of r.agents)i.alive&&i.ctl<0&&!i.ghost&&i.z=Pc&&si(r,"time")}return r.tick>=eo&&si(r,"time"),r}function b0(r,e){let t=Math.floor((e.z+70)/Ye),n=Bt(r,t);if(n.crocs.length&&!n.crocsOut){n.crocsOut=1;for(let i of n.crocs)jn(r,"croc",i.x,i.z,ln*(i.x>0?1.5:.5),{st:"lurk",home:n.river.z,rw:n.river.w})}}function v0(r,e){let t=0;for(let i in e)t+=e[i];let n=r()*t;for(let i in e)if(n-=e[i],n<=0)return i;return Object.keys(e)[0]}function x0(r,e){let t=r.rand,n={...r.lvl&&r.lvl.enc||r.B.enc},i=Oc(r);i&&n.lion&&(n.lion*=2),i&&n.eagle&&(n.eagle=0),e.sp==="rabbit"?n.eagle!==void 0&&(n.eagle=(n.eagle||0)+1.5):n.eagle&&(n.eagle*=.4),!r.B.enc.eagle&&!(r.lvl&&r.lvl.enc&&r.lvl.enc.eagle)&&delete n.eagle;let s=v0(t,n),a=t()<.5?-1:1;if(s==="lion"){let o=e.z>900&&t()<.5?2:1;for(let l=0;le.z+24&&(o=c.x,l=c.z);for(let h=0;h<6&&jp(r,o,l)<22;h++)l+=10;jn(r,"leopard",o,l,ln,{st:"stalk"})}else if(s==="wolf"){let o=3+(e.z>800?1:0);for(let l=0;l0?-ln/2:ln/2,{st:"wait"}):s==="eagle"&&jn(r,"eagle",e.x+a*10,e.z-30,0,{st:"soar",t:0,y:0});r.events.push({t:"spawn",k:s})}function jp(r,e,t){let n=1e9;for(let i of r.agents)i.alive&&i.side==="prey"&&(n=Math.min(n,Math.sqrt((i.x-e)*(i.x-e)+(i.z-t)*(i.z-t))));return n}function qp(r,e,t){let n=null,i=1e9;for(let s=Math.floor((t-20)/Ye);s<=Math.floor((t+20)/Ye);s++)for(let a of Bt(r,s).patches){if(a.k!=="grass"&&a.k!=="reed"&&a.k!=="fern")continue;let o=(a.x-e)*(a.x-e)+(a.z-t)*(a.z-t);o{let e=r.light();return e<.22||e>.8};function y0(r,e){r.nextHunt=0;let t=r.rand,n=r.B.hunt[e.sp]||r.B.herd,i=n[Math.floor(t()*n.length)],s=i==="rabbit"?3:Math.max(3,Te[i].herd-2);ef(r,i,e.z,s,(r.hunts||r.misses?38:50)+t()*14),r.huntT=r.tick,r.events.push({t:"hunt",sp:i})}function _0(r,e,t){let n=Te[e.sp],i=e.ev||0;if(e.ev=0,e.t++,e.hidden>0){e.hidden--,e.hidden||(e.x=e.hx,e.z=e.hz,e.spd=n.cruise,r.events.push({t:"pop",id:e.id})),e.y=et(r,e.x,e.z)-(e.hidden?.6:0);return}e.abCd>0&&(e.abCd-=rt),e.abT>0&&(e.abT-=rt),e.dodgeCd>0&&(e.dodgeCd-=rt),e.stun>0&&(e.stun-=rt),i&8&&e.abCd<=0&&e.stun<=0&&S0(r,e);let s=n.fly&&e.st!=="perch",a=m0(r,e),o=g0[a]||1;e.sp==="croc"&&a==="water"&&(o=1.6),e.sp==="rabbit"&&(a==="drift"||a==="snow")&&(o=Math.max(o,.9)),e.sp==="wolf"&&a==="drift"&&(o=Math.max(o,.85)),s&&(o=1),e.stam<.04?e.winded=!0:e.stam>.3&&(e.winded=!1);let l=e.ab==="stalk"&&e.abT>0,c=t.sprint&&!e.winded&&!l,h=(c?n.top:n.cruise)*o;if(l&&(h=3.2),e.burst>0&&(e.burst-=rt,h=n.top*1.08),e.stun>0&&(h*=.35),e.lunge>0&&(h=n.top*1.4),(e.st==="tired"||e.st==="rest")&&(h=Math.min(h,n.cruise*.55)),e.st==="graze"&&(h=1.2),e.eatT>0&&(h=Math.min(h,e.eatK==="rest"?.5:1.3)),e.side==="pred"&&e.ctl<0&&e.cap&&(h=Math.min(h,e.cap)),e.side==="prey"&&e.ctl<0&&r.side==="pred"&&r.opts.gentle!==!1&&(h*=.7+.3*yt((r.tick-30*15)/(30*30),0,1)),!s){let M=et(r,e.x+kt(e.a)*1.5,e.z+Yt(e.a)*1.5)-et(r,e.x,e.z);h*=yt(1-M*.22,.6,1.1)}let u=n.accel*(h>e.spd?e.burst>0||e.lunge>0?2.2:1:1.6);e.spd+=yt(h-e.spd,-u*rt,u*rt);let d=c&&e.spd>n.cruise*1.05||e.lunge>0||e.burst>0,p=e.ctl>=0&&r.side==="pred"&&r.opts.gentle!==!1&&r.tick<30*40?.55:1;d?e.stam-=n.drain*rt*(e.sp==="leopard"&&e.spd>15?1.3:1)*p:e.stam+=n.regen*rt*(a==="water"?.4:1)*(e.spd=0||e.ghost){let M=yt(t.steer,-1,1)*1.15;if(!e.ghost&&!s&&e.spd>2&&!e.air){let R=Bc(r,e,5+e.spd*.35);R&&R.jump&&n.jump?(Ac(e,n.jump*.8,n.jt),r.events.push({t:"jump",id:e.id})):R&&R.steer&&(M=yt(e.a+R.steer*.7,-1.4,1.4))}let _=m*1.9*rt;e.a+=yt(M-e.a,-_,_)}else e.a+=yt(t.steer,-1,1)*m*rt;e.side==="prey"||e.ctl>=0||e.ghost?e.a=yt(e.a,-1.4,1.4):e.a>ln?e.a-=js:e.a<-ln&&(e.a+=js),(i&2||i&4)&&e.dodgeCd<=0&&e.stun<=0&&!e.air&&(e.dodge=.28,e.lat=(i&2?-1:1)*8.5,e.dodgeCd=e.sp==="rabbit"?.42:.75,e.stam=Math.max(0,e.stam-.03),e.lastDodge=r.tick,r.events.push({t:"dodge",id:e.id})),i&1&&!e.air&&n.jump&&e.stun<=0&&(Ac(e,n.jump,n.jt),e.stam=Math.max(0,e.stam-.025),r.events.push({t:"jump",id:e.id})),e.dodge>0&&(e.dodge-=rt,e.dodge<=0&&(e.lat=0));let x=kt(e.a),f=Yt(e.a),g=e.x,v=e.z;e.x+=(x*e.spd+f*e.lat)*rt,e.z+=(f*e.spd-x*e.lat)*rt,e.knock&&(e.x+=e.knock.x*rt,e.z+=e.knock.z*rt,e.knock.x*=.9,e.knock.z*=.9,Math.abs(e.knock.x)+Math.abs(e.knock.z)<.2&&(e.knock=null)),e.x<-$e&&(e.x+=(-$e-e.x)*.25,e.spd*=.97,e.ctl>=0&&e.a<-.3&&(e.a+=.05)),e.x>$e&&(e.x-=(e.x-$e)*.25,e.spd*=.97,e.ctl>=0&&e.a>.3&&(e.a-=.05));let b=0;if(e.air>0){e.air--;let M=1-e.air/e.airT;b=e.jumpH*4*M*(1-M),e.air||r.events.push({t:"land",id:e.id})}s||M0(r,e,b,g,v);let y=et(r,e.x,e.z);if(s){let M=e.st==="dive"||e.st==="strike"?y+.8:y+(e.alt??n.fly);e.y+=yt(M-e.y,-(e.st==="dive"?34:10)*rt,8*rt)}else e.y=y+b-(a==="water"&&e.sp!=="croc"?.5:0)-(e.sp==="croc"&&e.st==="lurk"?.55:0);e.hop=b,e.surf=a}function Ac(r,e,t){r.air=r.airT=t,r.jumpH=e}function M0(r,e,t,n,i){let s=Te[e.sp];for(let a=Math.floor((e.z-4)/Ye);a<=Math.floor((e.z+4)/Ye);a++){let o=Bt(r,a);for(let l of o.obs){let c=e.x-l.x,h=e.z-l.z,u=l.r+s.r;if(l.k==="log"){if(Math.abs(h)>.5+s.r||Math.abs(c)>l.r+s.r||t>l.h*.8||l.soft)continue;Tc(r,e,n,i,0,Math.sign(h)||-1,.7);continue}if(c*c+h*h>u*u||t>l.h*.85)continue;if(l.soft){e.spd*=.985;continue}let d=Math.sqrt(c*c+h*h)||1;Tc(r,e,n,i,c/d,h/d,l.k==="tree"?.55:.7)}for(let l of o.ledges)if(e.sp!=="eagle"&&e.x>l.x0-s.r&&e.xl.z0-s.r&&e.zl.h)continue;let c=Math.min(e.x-(l.x0-s.r),l.x1+s.r-e.x)4&&(e.stun=.45,e.spd*=a,r.events.push({t:"stumble",id:e.id}),e.ctl>=0&&(r.combo=0)),s<=0&&i&&(e.a+=i*.08)}function S0(r,e){let t=Te[e.sp],n=t.ab;switch(e.ab=n,n){case"stampede":{e.abT=1.2,e.abCd=t.cd,e.stam=Math.max(0,e.stam-.05),r.events.push({t:"stampede",id:e.id});for(let i of r.agents)i.alive&&i.herd&&i.side==="prey"&&at(i,e)<18*18&&(i.st="flee",i.alarm=30*6,i.surge=30*3);for(let i of r.agents)if(i.alive&&i.side==="pred"&&i.tgt===e.id&&i.st!=="tired"){let s=0;for(let a of r.agents)a.alive&&a.herd&&at(a,e)<9*9&&s++;if(s>=2&&r.rand()<.6){let a=ri(r,i,30,e.id);a&&(i.tgt=a,i.lunge=0,r.events.push({t:"confused",id:i.id}),e.ctl>=0&&(r.stotOk++,r.score+=100))}}break}case"leap":Ac(e,t.jump*1.75,Math.round(t.jt*1.35)),e.spd+=2.5,e.abCd=t.cd,e.stam=Math.max(0,e.stam-.05),r.events.push({t:"leap",id:e.id});break;case"kick":{e.abCd=1.2,e.abT=.4,r.events.push({t:"kick",id:e.id});for(let i of r.agents)if(i.alive&&i.side==="pred"&&!Te[i.sp].fly){let s=i.x-e.x,a=i.z-e.z,o=Math.sqrt(s*s+a*a);o<4.2&&s*kt(e.a)+a*Yt(e.a)<.5&&(i.stun=1.6,i.lunge=0,i.knock={x:s/o*9,z:a/o*9},e.abCd=t.cd,r.events.push({t:"kickHit",id:i.id}),e.ctl>=0&&(r.score+=80,nf(r,e,i,"kick")))}break}case"burrow":{let i=zc(r,e,3.4);if(!i){e.abCd=.3,r.events.push({t:"noBurrow",id:e.id});break}e.hidden=Math.round(30*2.2),e.abCd=t.cd,e.x=i.x,e.z=i.z,e.hx=yt(i.x+(r.rand()*2-1)*8,-$e+2,$e-2),e.hz=i.z+14+r.rand()*8,r.events.push({t:"burrow",id:e.id});for(let s of r.agents)s.alive&&s.tgt===e.id&&(s.tgt=0,s.lunge=0,s.st!=="lurk"&&(s.st="search"));e.ctl>=0&&(r.score+=40);break}case"surge":e.stam=Math.min(1,e.stam+.55),e.abCd=t.cd,e.winded=!1,r.events.push({t:"surge",id:e.id});break;case"stalk":{let i=e.abT>0;e.abT=i?0:30,e.abCd=.3,r.events.push({t:"stalk",id:e.id,on:!i}),i&&(e.burst=1.4,r.events.push({t:"roar",id:e.id}));break}case"burst":e.burst=1.1,e.abCd=t.cd,e.stam=Math.max(0,e.stam-.1),r.events.push({t:"burst",id:e.id});break;case"charge":e.burst=1.6,e.charge=1.6,e.abCd=t.cd,r.events.push({t:"roar",id:e.id}),w0(r,e,22);break;case"command":r.cmd=(r.cmd+1)%3,e.abCd=t.cd,r.events.push({t:"cmd",id:e.id,cmd:r.cmd});break;case"dive":e.st!=="dive"&&(e.st="dive",e.t=0,e.abCd=t.cd,r.events.push({t:"screech",id:e.id}));break;default:break}}function zc(r,e,t){for(let n=Math.floor((e.z-t)/Ye);n<=Math.floor((e.z+t)/Ye);n++)for(let i of Bt(r,n).burrows)if((i.x-e.x)*(i.x-e.x)+(i.z-e.z)*(i.z-e.z)=0?1:-1:yt(c*n,-1,1)}function Bc(r,e,t=6){let n=kt(e.a),i=Yt(e.a),s=Te[e.sp],a=e.x+n*t*.6,o=e.z+i*t*.6;for(let l=Math.floor((o-4)/Ye);l<=Math.floor((o+4)/Ye);l++){let c=Bt(r,l);for(let h of c.obs){if(h.soft)continue;let u=h.x-a,d=h.z-o;if(h.k==="log"){if(Math.abs(d)<2.5&&Math.abs(u).8};continue}let p=h.r+s.r+1.4;if(u*u+d*d0?-1:1}}for(let h of c.ledges)if(a>h.x0-3&&ah.z0-6&&oe.x?1:-1,hard:1}}return null}function T0(r,e){let t=Te[e.sp],n=r.rand,i={steer:0,sprint:!1},s=null,a=1e9;for(let x of r.agents){if(!x.alive||x.side!=="pred"||x.st==="tired"||x.hidden)continue;let f=at(x,e),g=tf(r,x,e);f0&&e.alarm--,e.st==="graze")return i.steer=kt(e.t*.05+(e.wob||0))*.5,i;let o=0,l=0,c=0,h=0,u=0;for(let x of r.agents){if(x===e||!x.alive||x.side!=="prey"||x.hidden)continue;let f=at(x,e);f<30*30&&(o+=x.x,l+=x.z,c++,x.ctl>=0&&(o+=x.x*2,l+=x.z*2,c+=2)),f<3.2*3.2&&(h+=e.x-x.x,u+=e.z-x.z)}let d=e.x+h*2,p=e.z+20;if(c&&(d=d+(o/c-e.x)*.6,p=Math.max(p,l/c+14)),s){let x=Math.sqrt(a);d=e.x+(e.x-s.x)/x*14+h*2,p=e.z+Math.max(8,(e.z-s.z)/x*14+8),i.sprint=!0,x<7&&e.dodgeCd<=0&&n()0)e.surge--,i.sprint=!0;else if(r.side==="prey"){let x=Ne(r,r.humans[0]);i.sprint=!!(x&&x.alive&&x.spd>t.cruise*1.1&&e.zx.z+14&&(i.sprint=!1)}d=yt(d,-$e+4,$e-4),i.steer=vn(e,d,p,2.4);let m=Bc(r,e,7);return m&&(m.jump&&!e.air?e.ev=(e.ev||0)|1:m.steer&&(i.steer=m.steer)),e.stam<.15&&(i.sprint=!1),i}function E0(r,e){for(let t of r.agents)t.alive&&t.side==="prey"&&t.st==="graze"&&at(t,e)<26*26&&(t.st="flee")}function tf(r,e,t){let n=34;return e.ab==="stalk"&&e.abT>0?n=11:(e.st==="hide"||e.st==="stalk"||e.st==="wait")&&(n=13),Qp(r,e.x,e.z)&&(n*=.6),Oc(r)&&(n*=.75),(r.weather==="fog"||r.weather==="snow")&&(n*=.75),t&&t.ctl>=0&&t.side==="prey"&&r.agents.filter(i=>i!==t&&i.alive&&i.herd&&at(i,t)<100).length>=2&&(n*=.85),(e.lunge>0||e.spd>Te[e.sp].cruise*1.3)&&(n=Math.max(n,26)),n}function ri(r,e,t=70,n=0){let i=0,s=-1e9;for(let a of r.agents){if(!a.alive||a.side!=="prey"||a.hidden||a.id===n||e.sp==="eagle"&&!(a.sp==="rabbit"||a.ctl>=0))continue;let o=Math.sqrt(at(e,a));if(o>t)continue;let l=0;for(let h of r.agents)h!==a&&h.alive&&h.side==="prey"&&!h.hidden&&at(h,a)<10*10&&l++;let c=-o-l*5+(1-a.stam)*14+(a.ctl>=0?6:0);a.sp==="zebra"&&l>=2&&(c-=8),c>s&&(s=c,i=a.id)}return i}function A0(r,e){let t=Te[e.sp],n=r.rand,i={steer:0,sprint:!1},s=e.tgt?Ne(r,e.tgt):null;if(s&&(!s.alive||s.hidden)&&(e.tgt=0,s=null),e.pack)return R0(r,e,i);if(e.st==="tired"||e.st==="rest")return i.steer=vn(e,e.x+(e.x>0?20:-20),e.z+5),i;if(s&&s.sp==="zebra"){let o=0;for(let l of r.agents)l!==s&&l.alive&&l.sp==="zebra"&&at(l,s)<7*7&&o++;if(o>=2&&n()<.012){let l=ri(r,e,30);l&&l!==e.tgt&&(e.tgt=l,r.events.push({t:"confused",id:e.id}))}}switch(e.sp){case"lion":{if(e.st==="hide")return e.tgt=ri(r,e,26),s=e.tgt?Ne(r,e.tgt):null,s&&at(e,s)<21*21&&(e.st="charge",e.t=0,e.burst=1.2,r.events.push({t:"roar",id:e.id})),i.steer=0,e.cap=.01,i;if(e.cap=0,s||(e.tgt=ri(r,e,40),s=Ne(r,e.tgt)),!s)return Ii(r,e),i;i.sprint=!0,i.steer=vn(e,s.x+kt(s.a)*2,s.z+Yt(s.a)*2,3),(e.stam<.08||at(e,s)>45*45)&&Ii(r,e,s);break}case"leopard":{if(e.st==="stalk")return e.tgt=ri(r,e,50),s=e.tgt?Ne(r,e.tgt):null,s&&(i.steer=vn(e,s.x,s.z),(at(e,s)<17*17||e.t>30*6)&&(e.st="chase",e.burst=1.2,r.events.push({t:"burst",id:e.id}))),e.cap=3.5,i;if(e.cap=0,!s)return Ii(r,e),i;let o=Math.min(1,Math.sqrt(at(e,s))/16);i.sprint=!0,i.steer=vn(e,s.x+kt(s.a)*s.spd*o,s.z+Yt(s.a)*s.spd*o,3.4),(e.stam<.08||at(e,s)>40*40)&&Ii(r,e,s);break}case"wolf":{if(!s&&(e.tgt=ri(r,e,80),s=Ne(r,e.tgt),!s))return Ii(r,e),i;let o=kt(s.a),l=Yt(s.a),c=s.x,h=s.z,u=Math.sqrt(at(e,s));if(e.role==="L"||e.role==="R"){let d=e.role==="L"?-1:1;!(e.z>s.z-2)&&u>7?(c=s.x+l*d*9+o*6,h=s.z-o*d*9+l*6):(c=s.x+o*3,h=s.z+l*3)}else c=s.x+o*1.5,h=s.z+l*1.5;i.sprint=u<50,i.steer=vn(e,yt(c,-$e,$e),h,3),(e.stam<.06||u>70)&&Ii(r,e,s);break}case"bear":{if(e.st==="wait")return e.tgt=ri(r,e,40),s=e.tgt?Ne(r,e.tgt):null,s&&at(e,s)<28*28&&(e.st="charge",e.burst=1.4,r.events.push({t:"roar",id:e.id})),e.cap=.01,i;if(e.cap=0,!s)return Ii(r,e),i;i.sprint=!0,i.steer=vn(e,s.x+kt(s.a)*4,s.z+Yt(s.a)*4,2.2),(e.stam<.08||e.z30*20&&(e.alive=!1),i):(e.st==="soar"||e.st==="leave"?(e.alt=24,i.sprint=e.z30*3.5&&Math.abs(e.z-s.z)<6&&(e.st="dive",e.t=0,e.dx=s.x,e.dz=s.z,r.events.push({t:"screech",id:e.id})),e.passes>1&&(e.st="leave",e.alt=45)):e.st==="dive"?(i.sprint=!0,i.steer=vn(e,s.x+kt(s.a)*3,s.z+Yt(s.a)*3,3),e.alt=0,e.t>30*1.25&&!e.lunge&&!e.gentle&&(e.lunge=4,e.ltgt=s.id)):e.st==="strike"&&(e.alt=24,e.t>30*2&&(e.st="soar",e.t=0,e.passes=(e.passes||0)+1)),i);case"croc":{e.cap=.01;let o=null,l=1e9;for(let c of r.agents)if(c.alive&&c.side==="prey"&&!c.hidden&&c.surf==="water"){let h=at(e,c);h30*3&&(e.st="lurk")),e.st==="miss"&&(e.cap=1,e.t>30*2&&(e.st="lurk")),i}default:break}if(s&&!e.lunge&&e.stun<=0){let o=s.x-e.x,l=s.z-e.z,c=Math.sqrt(o*o+l*l);!e.gentle&&c.55&&(e.lunge=8,e.ltgt=s.id,r.events.push({t:"pounce",id:e.id}))}let a=Bc(r,e,7);return a&&(a.jump&&!e.air?e.ev=(e.ev||0)|1:a.steer&&(a.hard||Math.abs(i.steer)<.6)&&(i.steer=a.steer)),i}function R0(r,e,t){let n=Ne(r,r.humans[0]);if(!n)return t;let i=e.tgt?Ne(r,e.tgt):null;if((!i||!i.alive)&&(e.tgt=ri(r,n,70),i=e.tgt?Ne(r,e.tgt):null),!i)return t.steer=vn(e,n.x+(e.role==="L"?-5:e.role==="R"?5:0),n.z-2),t.sprint=at(e,n)>8*8,t;let s=kt(i.a),a=Yt(i.a),o,l,c=r.cmd;if(c===1||c===2){let p=c===1?-1:1,m=e.z>i.z;o=m?i.x:i.x+a*p*8+s*7,l=m?i.z:i.z-s*p*8+a*7}else{let p=i.x-n.x,m=i.z-n.z,x=Math.sqrt(p*p+m*m)||1;o=i.x+p/x*6+(e.role==="L"?-3:e.role==="R"?3:0),l=i.z+m/x*6,e.z>i.z+2&&(o=i.x,l=i.z)}t.sprint=!0,t.steer=vn(e,yt(o,-$e,$e),l,3);let h=i.x-e.x,u=i.z-e.z,d=Math.sqrt(h*h+u*u);return!e.gentle&&!e.lunge&&e.stun<=0&&d.5&&r.rand()<.35&&(e.lunge=8,e.ltgt=i.id,r.events.push({t:"pounce",id:e.id})),e.stam<.15&&(t.sprint=!1),t}function Ii(r,e,t){e.st="tired",e.tgt=0,e.lunge=0,r.events.push({t:"giveup",id:e.id,sp:e.sp}),r.side==="prey"&&t&&t.ctl>=0&&(r.giveups++,r.score+=60)}function C0(r,e){let t=Te[e.sp];if(e.ctl>=0||e.ghost){if(!e.lunge&&e.air&&e.air===e.airT-1&&r.side==="pred"||e.ghost&&!e.lunge&&e.air&&e.air===e.airT-1){let u=null,d=1e9;for(let p of r.agents)if(p.alive&&p.side==="prey"&&!p.hidden){let m=at(e,p);m=0&&e.burst>0&&e.charge){for(let u of r.agents)if(u.alive&&u.side==="prey"&&!u.hidden&&at(e,u)<2.2*2.2){e.lunge=2,e.ltgt=u.id;break}}if(!e.lunge&&e.ctl>=0&&r.side==="pred"&&r.tick>30*3&&e.spd>t.cruise*.9&&!e.air){for(let u of r.agents)if(u.alive&&u.side==="prey"&&!u.hidden&&at(e,u)<(1.4+t.r+Te[u.sp].r)**2){e.lunge=2,e.ltgt=u.id;break}}}if(!e.lunge)return;e.lunge--;let n=Ne(r,e.ltgt);if(n&&n.alive&&n.ctl<0&&!n.ghost&&e.lunge===6&&n.side==="prey"){let u=Math.abs(kt(e.a-n.a))>.6;r.rand()0)return;if(!n||!n.alive||n.hidden){Xp(r,e,n,9);return}let i=kt(e.a),s=Yt(e.a),a=e.x+i*1.1,o=e.z+s*1.1,l=Math.sqrt((n.x-a)*(n.x-a)+(n.z-o)*(n.z-o)),c=n.lastDodge&&r.tick-n.lastDodge<11,h=1.55+Te[n.sp].r+(e.sp==="bear"?.5:0)+(e.sp==="eagle"?.6:0);if(e.sp==="eagle"&&n.sp!=="rabbit"&&l=0&&(r.combo=0);return}l=0&&n<3.4&&nf(r,t,e,"dodge"),r.side==="pred"&&e.ctl>=0&&(r.combo=0)}function nf(r,e,t,n){r.close++,r.combo++,r.comboT=30*6;let i=50*Math.min(5,r.combo);r.score+=i,e.ctl>=0&&(e.pts=(e.pts||0)+i),r.events.push({t:"close",id:e.id,by:t.id,why:n,pts:i,combo:r.combo})}function P0(r,e,t){if(t.alive=!1,t.gone=30*2,t.caughtBy=e.id,t.stun=0,e.lunge=0,e.stun=1.2,e.tgt=0,e.st=e.ctl>=0||e.pack?e.st:"tired",r.events.push({t:"catch",id:t.id,by:e.id,sp:e.sp,prey:t.sp,me:t.ctl>=0,mine:e.ctl>=0||!!e.pack}),t.ctl>=0&&t.ctl!==99&&(t.out=r.tick),t.ctl===0&&r.mode!=="live"?si(r,"caught",e.sp):t.ctl>=0&&t.ctl!==99?r.agents.some(n=>n.alive&&n.ctl>=0&&n.side==="prey")||si(r,"caught",e.sp):t.herd&&r.side==="prey"&&r.eaten++,r.mode==="live"&&r.side==="prey"&&e.ctl>=0&&(e.pts=(e.pts||0)+(t.ctl>=0?500:200)),r.side==="pred"&&(e.ctl>=0||e.pack)&&t.side==="prey"){r.hunts++;let n=Math.max(0,40-(r.tick-r.huntT)/30),i=300+Math.round(n*10)+(t.sp==="zebra"||t.sp==="horse"||t.sp==="wildebeest"?100:0);r.score+=i,e.ctl>=0&&(e.pts=(e.pts||0)+i);for(let a of r.agents)a.alive&&a.side==="prey"&&a.ctl<0&&(a.alive=!1,a.gone=30);r.nextHunt=r.tick+30*2;let s=Ne(r,r.humans[0]);s&&(s.stam=Math.min(1,s.stam+.4))}}var Rc={graze:{secs:1.1,stam:.3,pts:25},water:{secs:1.4,stam:.4,pts:40},shade:{secs:1.6,stam:.5,pts:15}};function Yp(r,e,t){return r.agents.some(n=>n.alive&&n.side==="pred"&&n.ctl<0&&(n.tgt===e.id||n.lunge>0)&&at(n,e)0){let i=Rc[e.eatK],s=1/(i.secs*30);if(e.stam=Math.min(1,e.stam+i.stam*s),e.side==="prey"&&Yp(r,e,30)){e.eatT=0,r.events.push({t:"startle",id:e.id});return}if(--e.eatT===0){let a=e.eatK==="water"&&e.side==="pred"?20:i.pts;r.score+=a,e.pts=(e.pts||0)+a,e.eatK==="graze"?r.grazed++:e.eatK==="water"?r.drinks++:r.rests++,r.events.push({t:e.eatK==="graze"?"grazed":e.eatK==="water"?"drank":"rested",id:e.id,pts:a})}return}if(r.boostT>0&&--r.boostT===0&&(r.boost=0),e.air>0||e.stun>0||e.lunge>0)return;let t=Te[e.sp],n=e.spds.r*s.r)continue;if(s.k==="shoot"&&e.side==="prey"){s.used=r.tick,r.shoots++,r.boost++,r.boostT=30*20,r.score+=10,r.events.push({t:"shoot",id:e.id,n:r.boost});continue}if(!(!(n&&(s.k==="water"||s.k==="graze"&&e.side==="prey"||s.k==="shade"&&e.side==="pred"))||e.side==="prey"&&Yp(r,e,30)||t.fly)){s.used=r.tick,e.eatK=s.k,e.eatT=Math.round(Rc[s.k].secs*30),r.events.push({t:s.k==="graze"?"graze":s.k==="water"?"drink":"rest",id:e.id});return}}}function Hc(r,e){let t=null,n=1e18;for(let i of r.agents)if(i.alive&&i.side==="prey"&&i.ctl<0){let s=at(i,e);sn.alive&&n.side==="prey"&&n.ctl<0&&at(n,e)<30*30)?1:0}function L0(r,e){if(r.goal||r.mode==="live"||!e||!e.alive)return;let t=rf[r.side].filter(s=>s.k!=="herd"||Te[e.sp].herd);if(!r.obj){if(r.tick<30*6)return;let s=t[r.objN%t.length];r.obj={...s,base:s.k==="scent"?0:Ec(r,e,s.k)},r.events.push({t:"obj",next:r.obj.txt});return}let n=r.obj,i=Math.min(n.n,Math.floor(Ec(r,e,n.k)-n.base));if(n.have=i,i>=n.n){r.objs++,r.objN++,r.score+=100,e.pts=(e.pts||0)+100;let s=t[r.objN%t.length];r.obj={...s,base:s.k==="scent"?0:Ec(r,e,s.k),have:0},r.events.push({t:"obj",done:n.txt,next:r.obj.txt,pts:100})}}function k0(r,e){if(r.comboT>0&&--r.comboT===0&&(r.combo=0),!e||!e.alive)return;if(r.side==="prey"){let n=e.z-r.dist;if(n>0){let i=1e9;for(let a of r.agents)a!==e&&a.alive&&a.side==="prey"&&a.herd&&(i=Math.min(i,at(a,e)));let s=i>18*18;r.lone+=s?n:0,r.score+=n*(s&&Te[e.sp].herd?2:1)*(r.boostT>0?1+Math.min(.5,r.boost*.1):1),r.dist=e.z,e.lone=s}}else if(r.dist=Math.max(r.dist,e.z),!r.nextHunt&&r.tick-r.huntT>30*45){r.misses++,r.events.push({t:"escaped"});for(let n of r.agents)n.alive&&n.side==="prey"&&n.ctl<0&&(n.alive=!1,n.gone=30);r.nextHunt=r.tick+30*2,r.misses>=3&&!r.goal&&si(r,"escaped")}else!r.nextHunt&&!r.agents.some(n=>n.alive&&n.side==="prey"&&n.ctl<0&&n.z>e.z-40&&n.z=3&&!r.goal&&si(r,"escaped"));let t=r.goal;if(t&&!r.over){let n=r.agents.filter(i=>i.alive&&i.herd&&i.side==="prey"&&i.ctl<0).length;t.t==="reach"&&r.dist>=t.n||t.t==="survive"&&r.tick>=t.n*30||t.t==="lone"&&r.lone>=t.n||t.t==="hunt"&&r.hunts>=t.n?Ws(r):t.t==="herd"&&(n=t.n&&Ws(r)),t.t==="hunt"&&r.misses>=3&&si(r,"escaped")}}function Ws(r){r.won=!0,si(r,"won")}function si(r,e,t=""){r.over||(r.over=!0,r.result=e,r.by=t,r.events.push({t:"end",why:e}),r.score=Math.floor(r.score))}function Gc(r){return r.won?1+(r.close>=2||r.hunts>(r.goal.n||0)-1&&r.misses===0?1:0)+(r.eaten===0&&r.misses===0?1:0):0}function Vc(r,e,t,n=eo){let i=ai(r,t),s=0;for(;!i.over&&i.tickkc.includes(i));return{mode:"live",biome:t,sp:n[Math.floor(e()*n.length)],side:"prey",tod:Kp[1],weather:"clear"}}var ao=r=>r>>>1&1?"hunt":"race";function oo(r,e){let t=Wc(r),n=ao(r),i=Array.from({length:e},(s,a)=>n==="hunt"&&a===0?{side:"pred",sp:t.biome==="forest"?"wolf":"lion"}:{side:"prey",sp:t.sp});return{...t,players:i,enc:n==="race",side:"prey"}}function lo(r){return r.humans.map(e=>{let t=Ne(r,e);return t?Math.floor((t.zmax||0)+(t.pts||0)):0})}function N0(r,e,{maxTicks:t=Pc}={}){let n=e.map(li);if(!n.length||n.length>6||n.some(a=>!a))return null;let i=ai(r,oo(r,n.length)),s=n.map(()=>0);for(;!i.over&&i.tick(typeof btoa=="function"?btoa(unescape(encodeURIComponent(r))):Buffer.from(r,"utf8").toString("base64")).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),z0=r=>{for(r=r.replace(/-/g,"+").replace(/_/g,"/");r.length%4;)r+="=";return typeof atob=="function"?decodeURIComponent(escape(atob(r))):Buffer.from(r,"base64").toString("utf8")};function jc(r){return O0(JSON.stringify({v:1,s:r.seed,b:r.biome,d:r.side,p:r.sp,o:r.tod,w:r.weather,i:r.taps,n:String(r.name||"").slice(0,10),sc:r.score|0}))}function qc(r){try{if(typeof r!="string"||r.length>16e4)return null;let e=JSON.parse(z0(r));return!e||e.v!==1||!_n[e.b]||!Te[e.p]||!["prey","pred"].includes(e.d)||!li(e.i)?null:{seed:e.s|0,biome:e.b,side:e.d,sp:e.p,tod:+e.o||.42,weather:Dc[e.b].includes(e.w)?e.w:"clear",taps:e.i,name:String(e.n||"").replace(/[^A-Za-z0-9 ]/g,""),score:e.sc|0}}catch{return null}}function Xc(r,e){let t=r.side==="prey"?"pred":"prey",n=e||(t==="pred"?r.biome==="savanna"||r.biome==="wetlands"?"lion":"wolf":_n[r.biome].herd[0]);return{mode:"challenge",biome:r.biome,side:t,sp:n,tod:r.tod,weather:r.weather,enc:!1,ghost:{side:r.side,sp:r.sp,inputs:li(r.taps)}}}var co={deer:["Red deer live in herds of hinds (females) and young for most of the year; stags, which grow and shed antlers every year, join them in the autumn rut.","Red deer can run at about 50 km/h and clear tall obstacles in a bound."],zebra:["Every zebra has its own stripe pattern, like a fingerprint.","Zebras defend themselves with powerful kicks, and lions are wary of them.","Research suggests zebra stripes help keep biting flies away."],wildebeest:["More than a million wildebeest migrate in a yearly loop through the Serengeti and the Maasai Mara.","Wildebeest calves can stand within minutes of birth and run with the herd soon after."],rabbit:["European rabbits live in warrens: burrow systems with many entrances.","Rabbits escape by zig-zagging, which makes them hard to catch for predators that are faster on a straight line."],horse:['Horses can doze standing up: a "stay apparatus" in their legs locks the joints.',"Wild horses live in the Camargue wetlands of southern France."],lion:["Lionesses do most of a pride's hunting, often working together.","Lions stalk close using cover before they charge: they can only keep their top speed for a short distance.","Lions hunt mostly at night."],leopard:["Leopards hunt by stalking close and pouncing, not by long chases.","Leopards are strong climbers and often haul their prey up into trees, away from lions and hyenas."],wolf:["Grey wolves hunt in packs and are endurance hunters: they can trot for hours and test a herd to find a weak animal."],bear:["Brown bears can run at about 50 km/h over short distances."],eagle:["Bald eagles eat mostly fish but also catch rabbits and other small mammals.","A bald eagle's wings can span more than 2 metres."],croc:["Nile crocodiles ambush animals at river crossings and can stay underwater for many minutes."]};var Ih="170";var Sm=2;var td=0,Pl=1,Qn=2,Il=0;var wm=2;var mr=100,F0=101,B0=102;var H0=200,G0=201,V0=202,W0=203,Lh=204,kh=205,j0=206,q0=207,X0=208,Y0=209,K0=210,$0=211,Z0=212,J0=213,Q0=214,eb=0,tb=1,nb=2,ib=3,rb=4,sb=5,ab=6,ob=7;var Tm=1,Em=2,Am=3,Ll=4;var Rm=6,Cm=7,sf="attached",lb="detached",Pm=300,os=301,ls=302,ua=303,Dh=304,kl=306,Fn=1e3,gr=1001,da=1002,Ht=1003,nd=1004;var es=1005;var jt=1006,aa=1007;var gi=1008;var Vi=1009,Im=1010,Lm=1011,pa=1012,id=1013,br=1014,On=1015,Jt=1016,rd=1017,sd=1018,cs=1020,km=35902,Dm=1021,Um=1022,zn=1023,Nm=1024,Om=1025,fa=1026,hs=1027,ad=1028,od=1029,zm=1030,ld=1031;var cd=1033,Wo=33776,jo=33777,qo=33778,Xo=33779,Uh=35840,Nh=35841,Oh=35842,zh=35843,Fh=36196,Bh=37492,Hh=37496,Gh=37808,Vh=37809,Wh=37810,jh=37811,qh=37812,Xh=37813,Yh=37814,Kh=37815,$h=37816,Zh=37817,Jh=37818,Qh=37819,eu=37820,tu=37821,Yo=36492,nu=36494,iu=36495,Fm=36283,ru=36284,su=36285,au=36286,Bm=2200;var us=2300,ds=2301,Yc=2302,ts=2400,ns=2401,Ko=2402,cb=2500,hb=2501,Hm=0,Dl=1,Da=2;var Gm=3201;var Qr="",ot="srgb",qt="srgb-linear",Ul="linear",tt="srgb";var Fr=7680;var ub=512,db=513,pb=514,fb=515,mb=516,gb=517,bb=518,vb=519,ou=35044;var af="300 es",ps=2e3,$o=2001,vi=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){if(this._listeners===void 0)return!1;let n=this._listeners;return n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){if(this._listeners===void 0)return;let n=this._listeners[e];if(n!==void 0){let i=n.indexOf(t);i!==-1&&n.splice(i,1)}}dispatchEvent(e){if(this._listeners===void 0)return;let t=this._listeners[e.type];if(t!==void 0){e.target=this;let n=t.slice(0);for(let i=0,s=n.length;i>8&255]+Vt[r>>16&255]+Vt[r>>24&255]+"-"+Vt[255&e]+Vt[e>>8&255]+"-"+Vt[e>>16&15|64]+Vt[e>>24&255]+"-"+Vt[63&t|128]+Vt[t>>8&255]+"-"+Vt[t>>16&255]+Vt[t>>24&255]+Vt[255&n]+Vt[n>>8&255]+Vt[n>>16&255]+Vt[n>>24&255]).toLowerCase()}function Et(r,e,t){return Math.max(e,Math.min(t,r))}function lu(r,e){return(r%e+e)%e}function oa(r,e,t){return(1-t)*r+t*e}function Nn(r,e){switch(e.constructor){case Float32Array:return r;case Uint32Array:return r/4294967295;case Uint16Array:return r/65535;case Uint8Array:return r/255;case Int32Array:return Math.max(r/2147483647,-1);case Int16Array:return Math.max(r/32767,-1);case Int8Array:return Math.max(r/127,-1);default:throw new Error("Invalid component type.")}}function st(r,e){switch(e.constructor){case Float32Array:return r;case Uint32Array:return Math.round(4294967295*r);case Uint16Array:return Math.round(65535*r);case Uint8Array:return Math.round(255*r);case Int32Array:return Math.round(2147483647*r);case Int16Array:return Math.round(32767*r);case Int8Array:return Math.round(127*r);default:throw new Error("Invalid component type.")}}var It={DEG2RAD:rs,RAD2DEG:fs,generateUUID:wn,clamp:Et,euclideanModulo:lu,mapLinear:function(r,e,t,n,i){return n+(r-e)*(i-n)/(t-e)},inverseLerp:function(r,e,t){return r!==e?(t-r)/(e-r):0},lerp:oa,damp:function(r,e,t,n){return oa(r,e,1-Math.exp(-t*n))},pingpong:function(r,e=1){return e-Math.abs(lu(r,2*e)-e)},smoothstep:function(r,e,t){return r<=e?0:r>=t?1:(r=(r-e)/(t-e))*r*(3-2*r)},smootherstep:function(r,e,t){return r<=e?0:r>=t?1:(r=(r-e)/(t-e))*r*r*(r*(6*r-15)+10)},randInt:function(r,e){return r+Math.floor(Math.random()*(e-r+1))},randFloat:function(r,e){return r+Math.random()*(e-r)},randFloatSpread:function(r){return r*(.5-Math.random())},seededRandom:function(r){r!==void 0&&(of=r);let e=of+=1831565813;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296},degToRad:function(r){return r*rs},radToDeg:function(r){return r*fs},isPowerOfTwo:function(r){return!(r&r-1)&&r!==0},ceilPowerOfTwo:function(r){return Math.pow(2,Math.ceil(Math.log(r)/Math.LN2))},floorPowerOfTwo:function(r){return Math.pow(2,Math.floor(Math.log(r)/Math.LN2))},setQuaternionFromProperEuler:function(r,e,t,n,i){let s=Math.cos,a=Math.sin,o=s(t/2),l=a(t/2),c=s((e+n)/2),h=a((e+n)/2),u=s((e-n)/2),d=a((e-n)/2),p=s((n-e)/2),m=a((n-e)/2);switch(i){case"XYX":r.set(o*h,l*u,l*d,o*c);break;case"YZY":r.set(l*d,o*h,l*u,o*c);break;case"ZXZ":r.set(l*u,l*d,o*h,o*c);break;case"XZX":r.set(o*h,l*m,l*p,o*c);break;case"YXY":r.set(l*p,o*h,l*m,o*c);break;case"ZYZ":r.set(l*m,l*p,o*h,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}},normalize:st,denormalize:Nn},Z=class r{constructor(e=0,t=0){r.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,n=this.y,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6],this.y=i[1]*t+i[4]*n+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(e,Math.min(t,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(Et(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){let n=Math.cos(t),i=Math.sin(t),s=this.x-e.x,a=this.y-e.y;return this.x=s*n-a*i+e.x,this.y=s*i+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},Le=class r{constructor(e,t,n,i,s,a,o,l,c){r.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,i,s,a,o,l,c)}set(e,t,n,i,s,a,o,l,c){let h=this.elements;return h[0]=e,h[1]=i,h[2]=o,h[3]=t,h[4]=s,h[5]=l,h[6]=n,h[7]=a,h[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,i=t.elements,s=this.elements,a=n[0],o=n[3],l=n[6],c=n[1],h=n[4],u=n[7],d=n[2],p=n[5],m=n[8],x=i[0],f=i[3],g=i[6],v=i[1],b=i[4],y=i[7],M=i[2],_=i[5],R=i[8];return s[0]=a*x+o*v+l*M,s[3]=a*f+o*b+l*_,s[6]=a*g+o*y+l*R,s[1]=c*x+h*v+u*M,s[4]=c*f+h*b+u*_,s[7]=c*g+h*y+u*R,s[2]=d*x+p*v+m*M,s[5]=d*f+p*b+m*_,s[8]=d*g+p*y+m*R,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8];return t*a*h-t*o*c-n*s*h+n*o*l+i*s*c-i*a*l}invert(){let e=this.elements,t=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8],u=h*a-o*c,d=o*l-h*s,p=c*s-a*l,m=t*u+n*d+i*p;if(m===0)return this.set(0,0,0,0,0,0,0,0,0);let x=1/m;return e[0]=u*x,e[1]=(i*c-h*n)*x,e[2]=(o*n-i*a)*x,e[3]=d*x,e[4]=(h*t-i*l)*x,e[5]=(i*s-o*t)*x,e[6]=p*x,e[7]=(n*l-c*t)*x,e[8]=(a*t-n*s)*x,this}transpose(){let e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,i,s,a,o){let l=Math.cos(s),c=Math.sin(s);return this.set(n*l,n*c,-n*(l*a+c*o)+a+e,-i*c,i*l,-i*(-c*a+l*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(Kc.makeScale(e,t)),this}rotate(e){return this.premultiply(Kc.makeRotation(-e)),this}translate(e,t){return this.premultiply(Kc.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,n=e.elements;for(let i=0;i<9;i++)if(t[i]!==n[i])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}},Kc=new Le;function Vm(r){for(let e=r.length-1;e>=0;--e)if(r[e]>=65535)return!0;return!1}function ma(r){return document.createElementNS("http://www.w3.org/1999/xhtml",r)}function xb(){let r=ma("canvas");return r.style.display="block",r}var lf={};function sa(r){r in lf||(lf[r]=!0,console.warn(r))}var Oe={enabled:!0,workingColorSpace:qt,spaces:{},convert:function(r,e,t){return this.enabled!==!1&&e!==t&&e&&t&&(this.spaces[e].transfer===tt&&(r.r=bi(r.r),r.g=bi(r.g),r.b=bi(r.b)),this.spaces[e].primaries!==this.spaces[t].primaries&&(r.applyMatrix3(this.spaces[e].toXYZ),r.applyMatrix3(this.spaces[t].fromXYZ)),this.spaces[t].transfer===tt&&(r.r=ss(r.r),r.g=ss(r.g),r.b=ss(r.b))),r},fromWorkingColorSpace:function(r,e){return this.convert(r,this.workingColorSpace,e)},toWorkingColorSpace:function(r,e){return this.convert(r,e,this.workingColorSpace)},getPrimaries:function(r){return this.spaces[r].primaries},getTransfer:function(r){return r===Qr?Ul:this.spaces[r].transfer},getLuminanceCoefficients:function(r,e=this.workingColorSpace){return r.fromArray(this.spaces[e].luminanceCoefficients)},define:function(r){Object.assign(this.spaces,r)},_getMatrix:function(r,e,t){return r.copy(this.spaces[e].toXYZ).multiply(this.spaces[t].fromXYZ)},_getDrawingBufferColorSpace:function(r){return this.spaces[r].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(r=this.workingColorSpace){return this.spaces[r].workingColorSpaceConfig.unpackColorSpace}};function bi(r){return r<.04045?.0773993808*r:Math.pow(.9478672986*r+.0521327014,2.4)}function ss(r){return r<.0031308?12.92*r:1.055*Math.pow(r,.41666)-.055}var cf=[.64,.33,.3,.6,.15,.06],hf=[.2126,.7152,.0722],uf=[.3127,.329],df=new Le().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),pf=new Le().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715),Br;Oe.define({[qt]:{primaries:cf,whitePoint:uf,transfer:Ul,toXYZ:df,fromXYZ:pf,luminanceCoefficients:hf,workingColorSpaceConfig:{unpackColorSpace:ot},outputColorSpaceConfig:{drawingBufferColorSpace:ot}},[ot]:{primaries:cf,whitePoint:uf,transfer:tt,toXYZ:df,fromXYZ:pf,luminanceCoefficients:hf,outputColorSpaceConfig:{drawingBufferColorSpace:ot}}});var cu=class{static getDataURL(e){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let t;if(e instanceof HTMLCanvasElement)t=e;else{Br===void 0&&(Br=ma("canvas")),Br.width=e.width,Br.height=e.height;let n=Br.getContext("2d");e instanceof ImageData?n.putImageData(e,0,0):n.drawImage(e,0,0,e.width,e.height),t=Br}return t.width>2048||t.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),t.toDataURL("image/jpeg",.6)):t.toDataURL("image/png")}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){let t=ma("canvas");t.width=e.width,t.height=e.height;let n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);let i=n.getImageData(0,0,e.width,e.height),s=i.data;for(let a=0;a0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==Pm)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Fn:e.x=e.x-Math.floor(e.x);break;case gr:e.x=e.x<0?0:1;break;case da:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case Fn:e.y=e.y-Math.floor(e.y);break;case gr:e.y=e.y<0?0:1;break;case da:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};Ut.DEFAULT_IMAGE=null,Ut.DEFAULT_MAPPING=Pm,Ut.DEFAULT_ANISOTROPY=1;var Ze=class r{constructor(e=0,t=0,n=0,i=1){r.prototype.isVector4=!0,this.x=e,this.y=t,this.z=n,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,i){return this.x=e,this.y=t,this.z=n,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,n=this.y,i=this.z,s=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*i+a[12]*s,this.y=a[1]*t+a[5]*n+a[9]*i+a[13]*s,this.z=a[2]*t+a[6]*n+a[10]*i+a[14]*s,this.w=a[3]*t+a[7]*n+a[11]*i+a[15]*s,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,i,s,l=e.elements,c=l[0],h=l[4],u=l[8],d=l[1],p=l[5],m=l[9],x=l[2],f=l[6],g=l[10];if(Math.abs(h-d)<.01&&Math.abs(u-x)<.01&&Math.abs(m-f)<.01){if(Math.abs(h+d)<.1&&Math.abs(u+x)<.1&&Math.abs(m+f)<.1&&Math.abs(c+p+g-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;let b=(c+1)/2,y=(p+1)/2,M=(g+1)/2,_=(h+d)/4,R=(u+x)/4,C=(m+f)/4;return b>y&&b>M?b<.01?(n=0,i=.707106781,s=.707106781):(n=Math.sqrt(b),i=_/n,s=R/n):y>M?y<.01?(n=.707106781,i=0,s=.707106781):(i=Math.sqrt(y),n=_/i,s=C/i):M<.01?(n=.707106781,i=.707106781,s=0):(s=Math.sqrt(M),n=R/s,i=C/s),this.set(n,i,s,t),this}let v=Math.sqrt((f-m)*(f-m)+(u-x)*(u-x)+(d-h)*(d-h));return Math.abs(v)<.001&&(v=1),this.x=(f-m)/v,this.y=(u-x)/v,this.z=(d-h)/v,this.w=Math.acos((c+p+g-1)/2),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this.w=Math.max(e.w,Math.min(t.w,this.w)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this.w=Math.max(e,Math.min(t,this.w)),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(e,Math.min(t,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}},hu=class extends vi{constructor(e=1,t=1,n={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=1,this.scissor=new Ze(0,0,e,t),this.scissorTest=!1,this.viewport=new Ze(0,0,e,t);let i={width:e,height:t,depth:1};n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:jt,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1},n);let s=new Ut(i,n.mapping,n.wrapS,n.wrapT,n.magFilter,n.minFilter,n.format,n.type,n.anisotropy,n.colorSpace);s.flipY=!1,s.generateMipmaps=n.generateMipmaps,s.internalFormat=n.internalFormat,this.textures=[];let a=n.count;for(let o=0;o=0?1:-1,b=1-g*g;if(b>Number.EPSILON){let M=Math.sqrt(b),_=Math.atan2(M,g*v);f=Math.sin(f*_)/M,o=Math.sin(o*_)/M}let y=o*v;if(l=l*f+d*y,c=c*f+p*y,h=h*f+m*y,u=u*f+x*y,f===1-o){let M=1/Math.sqrt(l*l+c*c+h*h+u*u);l*=M,c*=M,h*=M,u*=M}}e[t]=l,e[t+1]=c,e[t+2]=h,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,i,s,a){let o=n[i],l=n[i+1],c=n[i+2],h=n[i+3],u=s[a],d=s[a+1],p=s[a+2],m=s[a+3];return e[t]=o*m+h*u+l*p-c*d,e[t+1]=l*m+h*d+c*u-o*p,e[t+2]=c*m+h*p+o*d-l*u,e[t+3]=h*m-o*u-l*d-c*p,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,i){return this._x=e,this._y=t,this._z=n,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let n=e._x,i=e._y,s=e._z,a=e._order,o=Math.cos,l=Math.sin,c=o(n/2),h=o(i/2),u=o(s/2),d=l(n/2),p=l(i/2),m=l(s/2);switch(a){case"XYZ":this._x=d*h*u+c*p*m,this._y=c*p*u-d*h*m,this._z=c*h*m+d*p*u,this._w=c*h*u-d*p*m;break;case"YXZ":this._x=d*h*u+c*p*m,this._y=c*p*u-d*h*m,this._z=c*h*m-d*p*u,this._w=c*h*u+d*p*m;break;case"ZXY":this._x=d*h*u-c*p*m,this._y=c*p*u+d*h*m,this._z=c*h*m+d*p*u,this._w=c*h*u-d*p*m;break;case"ZYX":this._x=d*h*u-c*p*m,this._y=c*p*u+d*h*m,this._z=c*h*m-d*p*u,this._w=c*h*u+d*p*m;break;case"YZX":this._x=d*h*u+c*p*m,this._y=c*p*u+d*h*m,this._z=c*h*m-d*p*u,this._w=c*h*u-d*p*m;break;case"XZY":this._x=d*h*u-c*p*m,this._y=c*p*u-d*h*m,this._z=c*h*m+d*p*u,this._w=c*h*u+d*p*m;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,i=Math.sin(n);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],i=t[4],s=t[8],a=t[1],o=t[5],l=t[9],c=t[2],h=t[6],u=t[10],d=n+o+u;if(d>0){let p=.5/Math.sqrt(d+1);this._w=.25/p,this._x=(h-l)*p,this._y=(s-c)*p,this._z=(a-i)*p}else if(n>o&&n>u){let p=2*Math.sqrt(1+n-o-u);this._w=(h-l)/p,this._x=.25*p,this._y=(i+a)/p,this._z=(s+c)/p}else if(o>u){let p=2*Math.sqrt(1+o-n-u);this._w=(s-c)/p,this._x=(i+a)/p,this._y=.25*p,this._z=(l+h)/p}else{let p=2*Math.sqrt(1+u-n-o);this._w=(a-i)/p,this._x=(s+c)/p,this._y=(l+h)/p,this._z=.25*p}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return nMath.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Et(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let i=Math.min(1,t/n);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,i=e._y,s=e._z,a=e._w,o=t._x,l=t._y,c=t._z,h=t._w;return this._x=n*h+a*o+i*c-s*l,this._y=i*h+a*l+s*o-n*c,this._z=s*h+a*c+n*l-i*o,this._w=a*h-n*o-i*l-s*c,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);let n=this._x,i=this._y,s=this._z,a=this._w,o=a*e._w+n*e._x+i*e._y+s*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=a,this._x=n,this._y=i,this._z=s,this;let l=1-o*o;if(l<=Number.EPSILON){let p=1-t;return this._w=p*a+t*this._w,this._x=p*n+t*this._x,this._y=p*i+t*this._y,this._z=p*s+t*this._z,this.normalize(),this}let c=Math.sqrt(l),h=Math.atan2(c,o),u=Math.sin((1-t)*h)/c,d=Math.sin(t*h)/c;return this._w=a*u+this._w*d,this._x=n*u+this._x*d,this._y=i*u+this._y*d,this._z=s*u+this._z*d,this._onChangeCallback(),this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),i=Math.sqrt(1-n),s=Math.sqrt(n);return this.set(i*Math.sin(e),i*Math.cos(e),s*Math.sin(t),s*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},S=class r{constructor(e=0,t=0,n=0){r.prototype.isVector3=!0,this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(ff.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(ff.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,i=this.z,s=e.elements;return this.x=s[0]*t+s[3]*n+s[6]*i,this.y=s[1]*t+s[4]*n+s[7]*i,this.z=s[2]*t+s[5]*n+s[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,i=this.z,s=e.elements,a=1/(s[3]*t+s[7]*n+s[11]*i+s[15]);return this.x=(s[0]*t+s[4]*n+s[8]*i+s[12])*a,this.y=(s[1]*t+s[5]*n+s[9]*i+s[13])*a,this.z=(s[2]*t+s[6]*n+s[10]*i+s[14])*a,this}applyQuaternion(e){let t=this.x,n=this.y,i=this.z,s=e.x,a=e.y,o=e.z,l=e.w,c=2*(a*i-o*n),h=2*(o*t-s*i),u=2*(s*n-a*t);return this.x=t+l*c+a*u-o*h,this.y=n+l*h+o*c-s*u,this.z=i+l*u+s*h-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,i=this.z,s=e.elements;return this.x=s[0]*t+s[4]*n+s[8]*i,this.y=s[1]*t+s[5]*n+s[9]*i,this.z=s[2]*t+s[6]*n+s[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(e,Math.min(t,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let n=e.x,i=e.y,s=e.z,a=t.x,o=t.y,l=t.z;return this.x=i*l-s*o,this.y=s*a-n*l,this.z=n*o-i*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return Zc.copy(this).projectOnVector(e),this.sub(Zc)}reflect(e){return this.sub(Zc.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(Et(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,i=this.z-e.z;return t*t+n*n+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){let i=Math.sin(t)*e;return this.x=i*Math.sin(n),this.y=Math.cos(t)*e,this.z=i*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,4*t)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,3*t)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=2*Math.random()-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}},Zc=new S,ff=new _t,Gt=class{constructor(e=new S(1/0,1/0,1/0),t=new S(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,kn),kn.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Ks),uo.subVectors(this.max,Ks),Hr.subVectors(e.a,Ks),Gr.subVectors(e.b,Ks),Vr.subVectors(e.c,Ks),Li.subVectors(Gr,Hr),ki.subVectors(Vr,Gr),lr.subVectors(Hr,Vr);let t=[0,-Li.z,Li.y,0,-ki.z,ki.y,0,-lr.z,lr.y,Li.z,0,-Li.x,ki.z,0,-ki.x,lr.z,0,-lr.x,-Li.y,Li.x,0,-ki.y,ki.x,0,-lr.y,lr.x,0];return!!Jc(t,Hr,Gr,Vr,uo)&&(t=[1,0,0,0,1,0,0,0,1],!!Jc(t,Hr,Gr,Vr,uo)&&(po.crossVectors(Li,ki),t=[po.x,po.y,po.z],Jc(t,Hr,Gr,Vr,uo)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,kn).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(kn).length()),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()||(ci[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),ci[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),ci[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),ci[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),ci[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),ci[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),ci[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),ci[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(ci)),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}},ci=[new S,new S,new S,new S,new S,new S,new S,new S],kn=new S,ho=new Gt,Hr=new S,Gr=new S,Vr=new S,Li=new S,ki=new S,lr=new S,Ks=new S,uo=new S,po=new S,cr=new S;function Jc(r,e,t,n,i){for(let s=0,a=r.length-3;s<=a;s+=3){cr.fromArray(r,s);let o=i.x*Math.abs(cr.x)+i.y*Math.abs(cr.y)+i.z*Math.abs(cr.z),l=e.dot(cr),c=t.dot(cr),h=n.dot(cr);if(Math.max(-Math.max(l,c,h),Math.min(l,c,h))>o)return!1}return!0}var Mb=new Gt,$s=new S,Qc=new S,nn=class{constructor(e=new S,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){let n=this.center;t!==void 0?n.copy(t):Mb.setFromPoints(e).getCenter(n);let i=0;for(let s=0,a=e.length;sthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;$s.subVectors(e,this.center);let t=$s.lengthSq();if(t>this.radius*this.radius){let n=Math.sqrt(t),i=.5*(n-this.radius);this.center.addScaledVector($s,i/n),this.radius+=i}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(Qc.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint($s.copy(e.center).add(Qc)),this.expandByPoint($s.copy(e.center).sub(Qc))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}},hi=new S,eh=new S,fo=new S,Di=new S,th=new S,mo=new S,nh=new S,ms=class{constructor(e=new S,t=new S(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,hi)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=hi.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(hi.copy(this.origin).addScaledVector(this.direction,t),hi.distanceToSquared(e))}distanceSqToSegment(e,t,n,i){eh.copy(e).add(t).multiplyScalar(.5),fo.copy(t).sub(e).normalize(),Di.copy(this.origin).sub(eh);let s=.5*e.distanceTo(t),a=-this.direction.dot(fo),o=Di.dot(this.direction),l=-Di.dot(fo),c=Di.lengthSq(),h=Math.abs(1-a*a),u,d,p,m;if(h>0)if(u=a*l-o,d=a*o-l,m=s*h,u>=0)if(d>=-m)if(d<=m){let x=1/h;u*=x,d*=x,p=u*(u+a*d+2*o)+d*(a*u+d+2*l)+c}else d=s,u=Math.max(0,-(a*d+o)),p=-u*u+d*(d+2*l)+c;else d=-s,u=Math.max(0,-(a*d+o)),p=-u*u+d*(d+2*l)+c;else d<=-m?(u=Math.max(0,-(-a*s+o)),d=u>0?-s:Math.min(Math.max(-s,-l),s),p=-u*u+d*(d+2*l)+c):d<=m?(u=0,d=Math.min(Math.max(-s,-l),s),p=d*(d+2*l)+c):(u=Math.max(0,-(a*s+o)),d=u>0?s:Math.min(Math.max(-s,-l),s),p=-u*u+d*(d+2*l)+c);else d=a>0?-s:s,u=Math.max(0,-(a*d+o)),p=-u*u+d*(d+2*l)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,u),i&&i.copy(eh).addScaledVector(fo,d),p}intersectSphere(e,t){hi.subVectors(e.center,this.origin);let n=hi.dot(this.direction),i=hi.dot(hi)-n*n,s=e.radius*e.radius;if(i>s)return null;let a=Math.sqrt(s-i),o=n-a,l=n+a;return l<0?null:o<0?this.at(l,t):this.at(o,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0?!0:e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,i,s,a,o,l,c=1/this.direction.x,h=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(n=(e.min.x-d.x)*c,i=(e.max.x-d.x)*c):(n=(e.max.x-d.x)*c,i=(e.min.x-d.x)*c),h>=0?(s=(e.min.y-d.y)*h,a=(e.max.y-d.y)*h):(s=(e.max.y-d.y)*h,a=(e.min.y-d.y)*h),n>a||s>i?null:((s>n||isNaN(n))&&(n=s),(a=0?(o=(e.min.z-d.z)*u,l=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,l=(e.min.z-d.z)*u),n>l||o>i?null:((o>n||n!=n)&&(n=o),(l=0?n:i,t)))}intersectsBox(e){return this.intersectBox(e,hi)!==null}intersectTriangle(e,t,n,i,s){th.subVectors(t,e),mo.subVectors(n,e),nh.crossVectors(th,mo);let a,o=this.direction.dot(nh);if(o>0){if(i)return null;a=1}else{if(!(o<0))return null;a=-1,o=-o}Di.subVectors(this.origin,e);let l=a*this.direction.dot(mo.crossVectors(Di,mo));if(l<0)return null;let c=a*this.direction.dot(th.cross(Di));if(c<0||l+c>o)return null;let h=-a*Di.dot(nh);return h<0?null:this.at(h/o,s)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},Ee=class r{constructor(e,t,n,i,s,a,o,l,c,h,u,d,p,m,x,f){r.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,i,s,a,o,l,c,h,u,d,p,m,x,f)}set(e,t,n,i,s,a,o,l,c,h,u,d,p,m,x,f){let g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=i,g[1]=s,g[5]=a,g[9]=o,g[13]=l,g[2]=c,g[6]=h,g[10]=u,g[14]=d,g[3]=p,g[7]=m,g[11]=x,g[15]=f,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new r().fromArray(this.elements)}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){let t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){let t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){let t=this.elements,n=e.elements,i=1/Wr.setFromMatrixColumn(e,0).length(),s=1/Wr.setFromMatrixColumn(e,1).length(),a=1/Wr.setFromMatrixColumn(e,2).length();return t[0]=n[0]*i,t[1]=n[1]*i,t[2]=n[2]*i,t[3]=0,t[4]=n[4]*s,t[5]=n[5]*s,t[6]=n[6]*s,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){let t=this.elements,n=e.x,i=e.y,s=e.z,a=Math.cos(n),o=Math.sin(n),l=Math.cos(i),c=Math.sin(i),h=Math.cos(s),u=Math.sin(s);if(e.order==="XYZ"){let d=a*h,p=a*u,m=o*h,x=o*u;t[0]=l*h,t[4]=-l*u,t[8]=c,t[1]=p+m*c,t[5]=d-x*c,t[9]=-o*l,t[2]=x-d*c,t[6]=m+p*c,t[10]=a*l}else if(e.order==="YXZ"){let d=l*h,p=l*u,m=c*h,x=c*u;t[0]=d+x*o,t[4]=m*o-p,t[8]=a*c,t[1]=a*u,t[5]=a*h,t[9]=-o,t[2]=p*o-m,t[6]=x+d*o,t[10]=a*l}else if(e.order==="ZXY"){let d=l*h,p=l*u,m=c*h,x=c*u;t[0]=d-x*o,t[4]=-a*u,t[8]=m+p*o,t[1]=p+m*o,t[5]=a*h,t[9]=x-d*o,t[2]=-a*c,t[6]=o,t[10]=a*l}else if(e.order==="ZYX"){let d=a*h,p=a*u,m=o*h,x=o*u;t[0]=l*h,t[4]=m*c-p,t[8]=d*c+x,t[1]=l*u,t[5]=x*c+d,t[9]=p*c-m,t[2]=-c,t[6]=o*l,t[10]=a*l}else if(e.order==="YZX"){let d=a*l,p=a*c,m=o*l,x=o*c;t[0]=l*h,t[4]=x-d*u,t[8]=m*u+p,t[1]=u,t[5]=a*h,t[9]=-o*h,t[2]=-c*h,t[6]=p*u+m,t[10]=d-x*u}else if(e.order==="XZY"){let d=a*l,p=a*c,m=o*l,x=o*c;t[0]=l*h,t[4]=-u,t[8]=c*h,t[1]=d*u+x,t[5]=a*h,t[9]=p*u-m,t[2]=m*u-p,t[6]=o*h,t[10]=x*u+d}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Sb,e,wb)}lookAt(e,t,n){let i=this.elements;return cn.subVectors(e,t),cn.lengthSq()===0&&(cn.z=1),cn.normalize(),Ui.crossVectors(n,cn),Ui.lengthSq()===0&&(Math.abs(n.z)===1?cn.x+=1e-4:cn.z+=1e-4,cn.normalize(),Ui.crossVectors(n,cn)),Ui.normalize(),go.crossVectors(cn,Ui),i[0]=Ui.x,i[4]=go.x,i[8]=cn.x,i[1]=Ui.y,i[5]=go.y,i[9]=cn.y,i[2]=Ui.z,i[6]=go.z,i[10]=cn.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,i=t.elements,s=this.elements,a=n[0],o=n[4],l=n[8],c=n[12],h=n[1],u=n[5],d=n[9],p=n[13],m=n[2],x=n[6],f=n[10],g=n[14],v=n[3],b=n[7],y=n[11],M=n[15],_=i[0],R=i[4],C=i[8],I=i[12],O=i[1],z=i[5],F=i[9],W=i[13],j=i[2],Y=i[6],K=i[10],re=i[14],ie=i[3],ge=i[7],ye=i[11],ne=i[15];return s[0]=a*_+o*O+l*j+c*ie,s[4]=a*R+o*z+l*Y+c*ge,s[8]=a*C+o*F+l*K+c*ye,s[12]=a*I+o*W+l*re+c*ne,s[1]=h*_+u*O+d*j+p*ie,s[5]=h*R+u*z+d*Y+p*ge,s[9]=h*C+u*F+d*K+p*ye,s[13]=h*I+u*W+d*re+p*ne,s[2]=m*_+x*O+f*j+g*ie,s[6]=m*R+x*z+f*Y+g*ge,s[10]=m*C+x*F+f*K+g*ye,s[14]=m*I+x*W+f*re+g*ne,s[3]=v*_+b*O+y*j+M*ie,s[7]=v*R+b*z+y*Y+M*ge,s[11]=v*C+b*F+y*K+M*ye,s[15]=v*I+b*W+y*re+M*ne,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[4],i=e[8],s=e[12],a=e[1],o=e[5],l=e[9],c=e[13],h=e[2],u=e[6],d=e[10],p=e[14];return e[3]*(+s*l*u-i*c*u-s*o*d+n*c*d+i*o*p-n*l*p)+e[7]*(+t*l*p-t*c*d+s*a*d-i*a*p+i*c*h-s*l*h)+e[11]*(+t*c*u-t*o*p-s*a*u+n*a*p+s*o*h-n*c*h)+e[15]*(-i*o*h-t*l*u+t*o*d+i*a*u-n*a*d+n*l*h)}transpose(){let e=this.elements,t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){let i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=n),this}invert(){let e=this.elements,t=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8],u=e[9],d=e[10],p=e[11],m=e[12],x=e[13],f=e[14],g=e[15],v=u*f*c-x*d*c+x*l*p-o*f*p-u*l*g+o*d*g,b=m*d*c-h*f*c-m*l*p+a*f*p+h*l*g-a*d*g,y=h*x*c-m*u*c+m*o*p-a*x*p-h*o*g+a*u*g,M=m*u*l-h*x*l-m*o*d+a*x*d+h*o*f-a*u*f,_=t*v+n*b+i*y+s*M;if(_===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let R=1/_;return e[0]=v*R,e[1]=(x*d*s-u*f*s-x*i*p+n*f*p+u*i*g-n*d*g)*R,e[2]=(o*f*s-x*l*s+x*i*c-n*f*c-o*i*g+n*l*g)*R,e[3]=(u*l*s-o*d*s-u*i*c+n*d*c+o*i*p-n*l*p)*R,e[4]=b*R,e[5]=(h*f*s-m*d*s+m*i*p-t*f*p-h*i*g+t*d*g)*R,e[6]=(m*l*s-a*f*s-m*i*c+t*f*c+a*i*g-t*l*g)*R,e[7]=(a*d*s-h*l*s+h*i*c-t*d*c-a*i*p+t*l*p)*R,e[8]=y*R,e[9]=(m*u*s-h*x*s-m*n*p+t*x*p+h*n*g-t*u*g)*R,e[10]=(a*x*s-m*o*s+m*n*c-t*x*c-a*n*g+t*o*g)*R,e[11]=(h*o*s-a*u*s-h*n*c+t*u*c+a*n*p-t*o*p)*R,e[12]=M*R,e[13]=(h*x*i-m*u*i+m*n*d-t*x*d-h*n*f+t*u*f)*R,e[14]=(m*o*i-a*x*i-m*n*l+t*x*l+a*n*f-t*o*f)*R,e[15]=(a*u*i-h*o*i+h*n*l-t*u*l-a*n*d+t*o*d)*R,this}scale(e){let t=this.elements,n=e.x,i=e.y,s=e.z;return t[0]*=n,t[4]*=i,t[8]*=s,t[1]*=n,t[5]*=i,t[9]*=s,t[2]*=n,t[6]*=i,t[10]*=s,t[3]*=n,t[7]*=i,t[11]*=s,this}getMaxScaleOnAxis(){let e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,i))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){let t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){let n=Math.cos(t),i=Math.sin(t),s=1-n,a=e.x,o=e.y,l=e.z,c=s*a,h=s*o;return this.set(c*a+n,c*o-i*l,c*l+i*o,0,c*o+i*l,h*o+n,h*l-i*a,0,c*l-i*o,h*l+i*a,s*l*l+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,i,s,a){return this.set(1,n,s,0,e,1,a,0,t,i,1,0,0,0,0,1),this}compose(e,t,n){let i=this.elements,s=t._x,a=t._y,o=t._z,l=t._w,c=s+s,h=a+a,u=o+o,d=s*c,p=s*h,m=s*u,x=a*h,f=a*u,g=o*u,v=l*c,b=l*h,y=l*u,M=n.x,_=n.y,R=n.z;return i[0]=(1-(x+g))*M,i[1]=(p+y)*M,i[2]=(m-b)*M,i[3]=0,i[4]=(p-y)*_,i[5]=(1-(d+g))*_,i[6]=(f+v)*_,i[7]=0,i[8]=(m+b)*R,i[9]=(f-v)*R,i[10]=(1-(d+x))*R,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,n){let i=this.elements,s=Wr.set(i[0],i[1],i[2]).length(),a=Wr.set(i[4],i[5],i[6]).length(),o=Wr.set(i[8],i[9],i[10]).length();this.determinant()<0&&(s=-s),e.x=i[12],e.y=i[13],e.z=i[14],Dn.copy(this);let l=1/s,c=1/a,h=1/o;return Dn.elements[0]*=l,Dn.elements[1]*=l,Dn.elements[2]*=l,Dn.elements[4]*=c,Dn.elements[5]*=c,Dn.elements[6]*=c,Dn.elements[8]*=h,Dn.elements[9]*=h,Dn.elements[10]*=h,t.setFromRotationMatrix(Dn),n.x=s,n.y=a,n.z=o,this}makePerspective(e,t,n,i,s,a,o=2e3){let l=this.elements,c=2*s/(t-e),h=2*s/(n-i),u=(t+e)/(t-e),d=(n+i)/(n-i),p,m;if(o===ps)p=-(a+s)/(a-s),m=-2*a*s/(a-s);else{if(o!==$o)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);p=-a/(a-s),m=-a*s/(a-s)}return l[0]=c,l[4]=0,l[8]=u,l[12]=0,l[1]=0,l[5]=h,l[9]=d,l[13]=0,l[2]=0,l[6]=0,l[10]=p,l[14]=m,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,n,i,s,a,o=2e3){let l=this.elements,c=1/(t-e),h=1/(n-i),u=1/(a-s),d=(t+e)*c,p=(n+i)*h,m,x;if(o===ps)m=(a+s)*u,x=-2*u;else{if(o!==$o)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);m=s*u,x=-1*u}return l[0]=2*c,l[4]=0,l[8]=0,l[12]=-d,l[1]=0,l[5]=2*h,l[9]=0,l[13]=-p,l[2]=0,l[6]=0,l[10]=x,l[14]=-m,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){let t=this.elements,n=e.elements;for(let i=0;i<16;i++)if(t[i]!==n[i])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}},Wr=new S,Dn=new Ee,Sb=new S(0,0,0),wb=new S(1,1,1),Ui=new S,go=new S,cn=new S,mf=new Ee,gf=new _t,Kn=class r{constructor(e=0,t=0,n=0,i=r.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,i=this._order){return this._x=e,this._y=t,this._z=n,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){let i=e.elements,s=i[0],a=i[4],o=i[8],l=i[1],c=i[5],h=i[9],u=i[2],d=i[6],p=i[10];switch(t){case"XYZ":this._y=Math.asin(Et(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-h,p),this._z=Math.atan2(-a,s)):(this._x=Math.atan2(d,c),this._z=0);break;case"YXZ":this._x=Math.asin(-Et(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(o,p),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-u,s),this._z=0);break;case"ZXY":this._x=Math.asin(Et(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,p),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(l,s));break;case"ZYX":this._y=Math.asin(-Et(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,p),this._z=Math.atan2(l,s)):(this._x=0,this._z=Math.atan2(-a,c));break;case"YZX":this._z=Math.asin(Et(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-h,c),this._y=Math.atan2(-u,s)):(this._x=0,this._y=Math.atan2(o,p));break;case"XZY":this._z=Math.asin(-Et(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(o,s)):(this._x=Math.atan2(-h,p),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return mf.makeRotationFromQuaternion(e),this.setFromRotationMatrix(mf,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return gf.setFromEuler(this),this.setFromQuaternion(gf,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}};Kn.DEFAULT_ORDER="XYZ";var Qo=class{constructor(){this.mask=1}set(e){this.mask=1<>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let n=0;n0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.visibility=this._visibility,i.active=this._active,i.bounds=this._bounds.map(o=>({boxInitialized:o.boxInitialized,boxMin:o.box.min.toArray(),boxMax:o.box.max.toArray(),sphereInitialized:o.sphereInitialized,sphereRadius:o.sphere.radius,sphereCenter:o.sphere.center.toArray()})),i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(e),this._colorsTexture!==null&&(i.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),this.boundingBox!==null&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.boundingBox.max.toArray()})),this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=s(e.geometries,this.geometry);let o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){let l=o.shapes;if(Array.isArray(l))for(let c=0,h=l.length;c0){i.children=[];for(let o=0;o0){i.animations=[];for(let o=0;o0&&(n.geometries=o),l.length>0&&(n.materials=l),c.length>0&&(n.textures=c),h.length>0&&(n.images=h),u.length>0&&(n.shapes=u),d.length>0&&(n.skeletons=d),p.length>0&&(n.animations=p),m.length>0&&(n.nodes=m)}return n.object=i,n;function a(o){let l=[];for(let c in o){let h=o[c];delete h.metadata,l.push(h)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let n=0;n0?i.multiplyScalar(1/Math.sqrt(s)):i.set(0,0,0)}static getBarycoord(e,t,n,i,s){Un.subVectors(i,t),di.subVectors(n,t),rh.subVectors(e,t);let a=Un.dot(Un),o=Un.dot(di),l=Un.dot(rh),c=di.dot(di),h=di.dot(rh),u=a*c-o*o;if(u===0)return s.set(0,0,0),null;let d=1/u,p=(c*l-o*h)*d,m=(a*h-o*l)*d;return s.set(1-p-m,m,p)}static containsPoint(e,t,n,i){return this.getBarycoord(e,t,n,i,pi)!==null&&pi.x>=0&&pi.y>=0&&pi.x+pi.y<=1}static getInterpolation(e,t,n,i,s,a,o,l){return this.getBarycoord(e,t,n,i,pi)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(s,pi.x),l.addScaledVector(a,pi.y),l.addScaledVector(o,pi.z),l)}static getInterpolatedAttribute(e,t,n,i,s,a){return lh.setScalar(0),ch.setScalar(0),hh.setScalar(0),lh.fromBufferAttribute(e,t),ch.fromBufferAttribute(e,n),hh.fromBufferAttribute(e,i),a.setScalar(0),a.addScaledVector(lh,s.x),a.addScaledVector(ch,s.y),a.addScaledVector(hh,s.z),a}static isFrontFacing(e,t,n,i){return Un.subVectors(n,t),di.subVectors(e,t),Un.cross(di).dot(i)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,i){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,n,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,i),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Un.subVectors(this.c,this.b),di.subVectors(this.a,this.b),.5*Un.cross(di).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return r.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return r.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,i,s){return r.getInterpolation(e,this.a,this.b,this.c,t,n,i,s)}containsPoint(e){return r.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return r.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,i=this.b,s=this.c,a,o;Xr.subVectors(i,n),Yr.subVectors(s,n),sh.subVectors(e,n);let l=Xr.dot(sh),c=Yr.dot(sh);if(l<=0&&c<=0)return t.copy(n);ah.subVectors(e,i);let h=Xr.dot(ah),u=Yr.dot(ah);if(h>=0&&u<=h)return t.copy(i);let d=l*u-h*c;if(d<=0&&l>=0&&h<=0)return a=l/(l-h),t.copy(n).addScaledVector(Xr,a);oh.subVectors(e,s);let p=Xr.dot(oh),m=Yr.dot(oh);if(m>=0&&p<=m)return t.copy(s);let x=p*c-l*m;if(x<=0&&c>=0&&m<=0)return o=c/(c-m),t.copy(n).addScaledVector(Yr,o);let f=h*m-p*u;if(f<=0&&u-h>=0&&p-m>=0)return Mf.subVectors(s,i),o=(u-h)/(u-h+(p-m)),t.copy(i).addScaledVector(Mf,o);let g=1/(f+x+d);return a=x*g,o=d*g,t.copy(n).addScaledVector(Xr,a).addScaledVector(Yr,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},Wm={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Ni={h:0,s:0,l:0},vo={h:0,s:0,l:0};function uh(r,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?r+6*(e-r)*t:t<.5?e:t<2/3?r+6*(e-r)*(2/3-t):r}var oe=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){let i=e;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=ot){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,Oe.toWorkingColorSpace(this,t),this}setRGB(e,t,n,i=Oe.workingColorSpace){return this.r=e,this.g=t,this.b=n,Oe.toWorkingColorSpace(this,i),this}setHSL(e,t,n,i=Oe.workingColorSpace){if(e=lu(e,1),t=Et(t,0,1),n=Et(n,0,1),t===0)this.r=this.g=this.b=n;else{let s=n<=.5?n*(1+t):n+t-n*t,a=2*n-s;this.r=uh(a,s,e+1/3),this.g=uh(a,s,e),this.b=uh(a,s,e-1/3)}return Oe.toWorkingColorSpace(this,i),this}setStyle(e,t=ot){function n(s){s!==void 0&&parseFloat(s)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let s,a=i[1],o=i[2];switch(a){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,t);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,t);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){let s=i[1],a=s.length;if(a===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(a===6)return this.setHex(parseInt(s,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=ot){let n=Wm[e.toLowerCase()];return n!==void 0?this.setHex(n,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=bi(e.r),this.g=bi(e.g),this.b=bi(e.b),this}copyLinearToSRGB(e){return this.r=ss(e.r),this.g=ss(e.g),this.b=ss(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=ot){return Oe.fromWorkingColorSpace(Wt.copy(this),e),65536*Math.round(Et(255*Wt.r,0,255))+256*Math.round(Et(255*Wt.g,0,255))+Math.round(Et(255*Wt.b,0,255))}getHexString(e=ot){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Oe.workingColorSpace){Oe.fromWorkingColorSpace(Wt.copy(this),t);let n=Wt.r,i=Wt.g,s=Wt.b,a=Math.max(n,i,s),o=Math.min(n,i,s),l,c,h=(o+a)/2;if(o===a)l=0,c=0;else{let u=a-o;switch(c=h<=.5?u/(a+o):u/(2-a-o),a){case n:l=(i-s)/u+(i0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let n=e[t];if(n===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}let i=this[t];i!==void 0?i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[t]=n:console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`)}}toJSON(e){let t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});let n={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};function i(s){let a=[];for(let o in s){let l=s[o];delete l.metadata,a.push(l)}return a}if(n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==1&&(n.blending=this.blending),this.side!==0&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==Lh&&(n.blendSrc=this.blendSrc),this.blendDst!==kh&&(n.blendDst=this.blendDst),this.blendEquation!==mr&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==3&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==519&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Fr&&(n.stencilFail=this.stencilFail),this.stencilZFail!==Fr&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==Fr&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData),t){let s=i(e.textures),a=i(e.images);s.length>0&&(n.textures=s),a.length>0&&(n.images=a)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,n=null;if(t!==null){let i=t.length;n=new Array(i);for(let s=0;s!==i;++s)n[s]=t[s].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}onBuild(){console.warn("Material: onBuild() has been removed.")}},Nt=class extends un{static get type(){return"MeshBasicMaterial"}constructor(e){super(),this.isMeshBasicMaterial=!0,this.color=new oe(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Kn,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},Vy=Pb();function Pb(){let r=new ArrayBuffer(4),e=new Float32Array(r),t=new Uint32Array(r),n=new Uint32Array(512),i=new Uint32Array(512);for(let l=0;l<256;++l){let c=l-127;c<-27?(n[l]=0,n[256|l]=32768,i[l]=24,i[256|l]=24):c<-14?(n[l]=1024>>-c-14,n[256|l]=1024>>-c-14|32768,i[l]=-c-1,i[256|l]=-c-1):c<=15?(n[l]=c+15<<10,n[256|l]=c+15<<10|32768,i[l]=13,i[256|l]=13):c<128?(n[l]=31744,n[256|l]=64512,i[l]=24,i[256|l]=24):(n[l]=31744,n[256|l]=64512,i[l]=13,i[256|l]=13)}let s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let l=1;l<1024;++l){let c=l<<13,h=0;for(;!(8388608&c);)c<<=1,h-=8388608;c&=-8388609,h+=947912704,s[l]=c|h}for(let l=1024;l<2048;++l)s[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)a[l]=l<<23;a[31]=1199570944,a[32]=2147483648;for(let l=33;l<63;++l)a[l]=2147483648+(l-32<<23);a[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(o[l]=1024);return{floatView:e,uint32View:t,baseTable:n,shiftTable:i,mantissaTable:s,exponentTable:a,offsetTable:o}}var St=new S,xo=new Z,Qe=class{constructor(e,t,n=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=ou,this.updateRanges=[],this.gpuType=On,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let i=0,s=this.itemSize;it.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Gt);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new S(-1/0,-1/0,-1/0),new S(1/0,1/0,1/0));if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,i=t.length;n0&&(e.userData=this.userData),this.parameters!==void 0){let l=this.parameters;for(let c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let l in n){let c=n[l];e.data.attributes[l]=c.toJSON(e.data)}let i={},s=!1;for(let l in this.morphAttributes){let c=this.morphAttributes[l],h=[];for(let u=0,d=c.length;u0&&(i[l]=h,s=!0)}s&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere={center:o.center.toArray(),radius:o.radius}),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone(t));let i=e.attributes;for(let c in i){let h=i[c];this.setAttribute(c,h.clone(t))}let s=e.morphAttributes;for(let c in s){let h=[],u=s[c];for(let d=0,p=u.length;d0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let i=0,s=n.length;i(e.far-e.near)**2))return;Sf.copy(s).invert(),hr.copy(e.ray).applyMatrix4(Sf),n.boundingBox!==null&&hr.intersectsBox(n.boundingBox)===!1||this._computeIntersections(e,t,hr)}}_computeIntersections(e,t,n){let i,s=this.geometry,a=this.material,o=s.index,l=s.attributes.position,c=s.attributes.uv,h=s.attributes.uv1,u=s.attributes.normal,d=s.groups,p=s.drawRange;if(o!==null)if(Array.isArray(a))for(let m=0,x=d.length;mp.far?null:{distance:y,point:To.clone(),object:u}}(r,e,t,n,_o,Mo,So,Tf);if(h){let u=new S;zi.getBarycoord(Tf,_o,Mo,So,u),i&&(h.uv=zi.getInterpolatedAttribute(i,o,l,c,u,new Z)),s&&(h.uv1=zi.getInterpolatedAttribute(s,o,l,c,u,new Z)),a&&(h.normal=zi.getInterpolatedAttribute(a,o,l,c,u,new S),h.normal.dot(n.direction)>0&&h.normal.multiplyScalar(-1));let d={a:o,b:l,c,normal:new S,materialIndex:0};zi.getNormal(_o,Mo,So,d.normal),h.face=d,h.barycoord=u}return h}var Wi=class r extends qe{constructor(e=1,t=1,n=1,i=1,s=1,a=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:i,heightSegments:s,depthSegments:a};let o=this;i=Math.floor(i),s=Math.floor(s),a=Math.floor(a);let l=[],c=[],h=[],u=[],d=0,p=0;function m(x,f,g,v,b,y,M,_,R,C,I){let O=y/R,z=M/C,F=y/2,W=M/2,j=_/2,Y=R+1,K=C+1,re=0,ie=0,ge=new S;for(let ye=0;ye0?1:-1,h.push(ge.x,ge.y,ge.z),u.push(ae/R),u.push(1-ye/C),re+=1}}for(let ye=0;ye0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let n={};for(let i in this.extensions)this.extensions[i]===!0&&(n[i]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}},ga=class extends nt{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Ee,this.projectionMatrix=new Ee,this.projectionMatrixInverse=new Ee,this.coordinateSystem=ps}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}},Oi=new S,Ef=new Z,Af=new Z,At=class extends ga{constructor(e=50,t=1,n=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){let t=.5*this.getFilmHeight()/e;this.fov=2*fs*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(.5*rs*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*fs*Math.atan(Math.tan(.5*rs*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){Oi.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Oi.x,Oi.y).multiplyScalar(-e/Oi.z),Oi.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Oi.x,Oi.y).multiplyScalar(-e/Oi.z)}getViewSize(e,t){return this.getViewBounds(e,Ef,Af),t.subVectors(Af,Ef)}setViewOffset(e,t,n,i,s,a){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=i,this.view.width=s,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(.5*rs*this.fov)/this.zoom,n=2*t,i=this.aspect*n,s=-.5*i,a=this.view;if(this.view!==null&&this.view.enabled){let l=a.fullWidth,c=a.fullHeight;s+=a.offsetX*i/l,t-=a.offsetY*n/c,i*=a.width/l,n*=a.height/c}let o=this.filmOffset;o!==0&&(s+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+i,t,t-n,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}},$r=-90,du=class extends nt{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let i=new At($r,1,e,t);i.layers=this.layers,this.add(i);let s=new At($r,1,e,t);s.layers=this.layers,this.add(s);let a=new At($r,1,e,t);a.layers=this.layers,this.add(a);let o=new At($r,1,e,t);o.layers=this.layers,this.add(o);let l=new At($r,1,e,t);l.layers=this.layers,this.add(l);let c=new At($r,1,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,i,s,a,o,l]=t;for(let c of t)this.remove(c);if(e===ps)n.up.set(0,1,0),n.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else{if(e!==$o)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);n.up.set(0,-1,0),n.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1)}for(let c of t)this.add(c),c.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[s,a,o,l,c,h]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),p=e.getActiveMipmapLevel(),m=e.xr.enabled;e.xr.enabled=!1;let x=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,i),e.render(t,s),e.setRenderTarget(n,1,i),e.render(t,a),e.setRenderTarget(n,2,i),e.render(t,o),e.setRenderTarget(n,3,i),e.render(t,l),e.setRenderTarget(n,4,i),e.render(t,c),n.texture.generateMipmaps=x,e.setRenderTarget(n,5,i),e.render(t,h),e.setRenderTarget(u,d,p),e.xr.enabled=m,n.texture.needsPMREMUpdate=!0}},nl=class extends Ut{constructor(e,t,n,i,s,a,o,l,c,h){super(e=e!==void 0?e:[],t=t!==void 0?t:os,n,i,s,a,o,l,c,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},pu=class extends Rt{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;let n={width:e,height:e,depth:1},i=[n,n,n,n,n,n];this.texture=new nl(i,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=t.generateMipmaps!==void 0&&t.generateMipmaps,this.texture.minFilter=t.minFilter!==void 0?t.minFilter:jt}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;let n={uniforms:{tEquirect:{value:null}},vertexShader:` varying vec3 vWorldDirection; vec3 transformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); } void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include } `,fragmentShader:` uniform sampler2D tEquirect; varying vec3 vWorldDirection; #include void main() { vec3 direction = normalize( vWorldDirection ); vec2 sampleUV = equirectUv( direction ); gl_FragColor = texture2D( tEquirect, sampleUV ); } `},i=new Wi(5,5,5),s=new ft({name:"CubemapFromEquirect",uniforms:gs(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});s.uniforms.tEquirect.value=t;let a=new Je(i,s),o=t.minFilter;return t.minFilter===gi&&(t.minFilter=jt),new du(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t,n,i){let s=e.getRenderTarget();for(let a=0;a<6;a++)e.setRenderTarget(this,a),e.clear(t,n,i);e.setRenderTarget(s)}},fh=new S,Lb=new S,kb=new Le,mi=class{constructor(e=new S(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,i){return this.normal.set(e,t,n),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){let i=fh.subVectors(n,t).cross(Lb.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){let e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){let n=e.delta(fh),i=this.normal.dot(n);if(i===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;let s=-(e.start.dot(this.normal)+this.constant)/i;return s<0||s>1?null:t.copy(e.start).addScaledVector(n,s)}intersectsLine(e){let t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let n=t||kb.getNormalMatrix(e),i=this.coplanarPoint(fh).applyMatrix4(e),s=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(s),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}},ur=new nn,Ao=new S,bs=class{constructor(e=new mi,t=new mi,n=new mi,i=new mi,s=new mi,a=new mi){this.planes=[e,t,n,i,s,a]}set(e,t,n,i,s,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(i),o[4].copy(s),o[5].copy(a),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=2e3){let n=this.planes,i=e.elements,s=i[0],a=i[1],o=i[2],l=i[3],c=i[4],h=i[5],u=i[6],d=i[7],p=i[8],m=i[9],x=i[10],f=i[11],g=i[12],v=i[13],b=i[14],y=i[15];if(n[0].setComponents(l-s,d-c,f-p,y-g).normalize(),n[1].setComponents(l+s,d+c,f+p,y+g).normalize(),n[2].setComponents(l+a,d+h,f+m,y+v).normalize(),n[3].setComponents(l-a,d-h,f-m,y-v).normalize(),n[4].setComponents(l-o,d-u,f-x,y-b).normalize(),t===ps)n[5].setComponents(l+o,d+u,f+x,y+b).normalize();else{if(t!==$o)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);n[5].setComponents(o,u,x,b).normalize()}return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),ur.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),ur.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(ur)}intersectsSprite(e){return ur.center.set(0,0,0),ur.radius=.7071067811865476,ur.applyMatrix4(e.matrixWorld),this.intersectsSphere(ur)}intersectsSphere(e){let t=this.planes,n=e.center,i=-e.radius;for(let s=0;s<6;s++)if(t[s].distanceToPoint(n)0?e.max.x:e.min.x,Ao.y=i.normal.y>0?e.max.y:e.min.y,Ao.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Ao)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}};function qm(){let r=null,e=!1,t=null,n=null;function i(s,a){t(s,a),n=r.requestAnimationFrame(i)}return{start:function(){e!==!0&&t!==null&&(n=r.requestAnimationFrame(i),e=!0)},stop:function(){r.cancelAnimationFrame(n),e=!1},setAnimationLoop:function(s){t=s},setContext:function(s){r=s}}}function Db(r){let e=new WeakMap;return{get:function(t){return t.isInterleavedBufferAttribute&&(t=t.data),e.get(t)},remove:function(t){t.isInterleavedBufferAttribute&&(t=t.data);let n=e.get(t);n&&(r.deleteBuffer(n.buffer),e.delete(t))},update:function(t,n){if(t.isInterleavedBufferAttribute&&(t=t.data),t.isGLBufferAttribute){let s=e.get(t);return void((!s||s.versionu.start-d.start);let h=0;for(let u=1;u 0 vec4 plane; #ifdef ALPHA_TO_COVERAGE float distanceToPlane, distanceGradient; float clipOpacity = 1.0; #pragma unroll_loop_start for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; distanceGradient = fwidth( distanceToPlane ) / 2.0; clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); if ( clipOpacity == 0.0 ) discard; } #pragma unroll_loop_end #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES float unionClipOpacity = 1.0; #pragma unroll_loop_start for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; distanceGradient = fwidth( distanceToPlane ) / 2.0; unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); } #pragma unroll_loop_end clipOpacity *= 1.0 - unionClipOpacity; #endif diffuseColor.a *= clipOpacity; if ( diffuseColor.a == 0.0 ) discard; #else #pragma unroll_loop_start for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; } #pragma unroll_loop_end #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES bool clipped = true; #pragma unroll_loop_start for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; } #pragma unroll_loop_end if ( clipped ) discard; #endif #endif #endif`,clipping_planes_pars_fragment:`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; #endif`,clipping_planes_pars_vertex:`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; #endif`,clipping_planes_vertex:`#if NUM_CLIPPING_PLANES > 0 vClipPosition = - mvPosition.xyz; #endif`,color_fragment:`#if defined( USE_COLOR_ALPHA ) diffuseColor *= vColor; #elif defined( USE_COLOR ) diffuseColor.rgb *= vColor; #endif`,color_pars_fragment:`#if defined( USE_COLOR_ALPHA ) varying vec4 vColor; #elif defined( USE_COLOR ) varying vec3 vColor; #endif`,color_pars_vertex:`#if defined( USE_COLOR_ALPHA ) varying vec4 vColor; #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) varying vec3 vColor; #endif`,color_vertex:`#if defined( USE_COLOR_ALPHA ) vColor = vec4( 1.0 ); #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) vColor = vec3( 1.0 ); #endif #ifdef USE_COLOR vColor *= color; #endif #ifdef USE_INSTANCING_COLOR vColor.xyz *= instanceColor.xyz; #endif #ifdef USE_BATCHING_COLOR vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); vColor.xyz *= batchingColor.xyz; #endif`,common:`#define PI 3.141592653589793 #define PI2 6.283185307179586 #define PI_HALF 1.5707963267948966 #define RECIPROCAL_PI 0.3183098861837907 #define RECIPROCAL_PI2 0.15915494309189535 #define EPSILON 1e-6 #ifndef saturate #define saturate( a ) clamp( a, 0.0, 1.0 ) #endif #define whiteComplement( a ) ( 1.0 - saturate( a ) ) float pow2( const in float x ) { return x*x; } vec3 pow2( const in vec3 x ) { return x*x; } float pow3( const in float x ) { return x*x*x; } float pow4( const in float x ) { float x2 = x*x; return x2*x2; } float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } highp float rand( const in vec2 uv ) { const highp float a = 12.9898, b = 78.233, c = 43758.5453; highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); return fract( sin( sn ) * c ); } #ifdef HIGH_PRECISION float precisionSafeLength( vec3 v ) { return length( v ); } #else float precisionSafeLength( vec3 v ) { float maxComponent = max3( abs( v ) ); return length( v / maxComponent ) * maxComponent; } #endif struct IncidentLight { vec3 color; vec3 direction; bool visible; }; struct ReflectedLight { vec3 directDiffuse; vec3 directSpecular; vec3 indirectDiffuse; vec3 indirectSpecular; }; #ifdef USE_ALPHAHASH varying vec3 vPosition; #endif vec3 transformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); } vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); } mat3 transposeMat3( const in mat3 m ) { mat3 tmp; tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); return tmp; } bool isPerspectiveMatrix( mat4 m ) { return m[ 2 ][ 3 ] == - 1.0; } vec2 equirectUv( in vec3 dir ) { float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; return vec2( u, v ); } vec3 BRDF_Lambert( const in vec3 diffuseColor ) { return RECIPROCAL_PI * diffuseColor; } vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); } float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); } // validated`,cube_uv_reflection_fragment:`#ifdef ENVMAP_TYPE_CUBE_UV #define cubeUV_minMipLevel 4.0 #define cubeUV_minTileSize 16.0 float getFace( vec3 direction ) { vec3 absDirection = abs( direction ); float face = - 1.0; if ( absDirection.x > absDirection.z ) { if ( absDirection.x > absDirection.y ) face = direction.x > 0.0 ? 0.0 : 3.0; else face = direction.y > 0.0 ? 1.0 : 4.0; } else { if ( absDirection.z > absDirection.y ) face = direction.z > 0.0 ? 2.0 : 5.0; else face = direction.y > 0.0 ? 1.0 : 4.0; } return face; } vec2 getUV( vec3 direction, float face ) { vec2 uv; if ( face == 0.0 ) { uv = vec2( direction.z, direction.y ) / abs( direction.x ); } else if ( face == 1.0 ) { uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); } else if ( face == 2.0 ) { uv = vec2( - direction.x, direction.y ) / abs( direction.z ); } else if ( face == 3.0 ) { uv = vec2( - direction.z, direction.y ) / abs( direction.x ); } else if ( face == 4.0 ) { uv = vec2( - direction.x, direction.z ) / abs( direction.y ); } else { uv = vec2( direction.x, direction.y ) / abs( direction.z ); } return 0.5 * ( uv + 1.0 ); } vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { float face = getFace( direction ); float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); mipInt = max( mipInt, cubeUV_minMipLevel ); float faceSize = exp2( mipInt ); highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; if ( face > 2.0 ) { uv.y += faceSize; face -= 3.0; } uv.x += face * faceSize; uv.x += filterInt * 3.0 * cubeUV_minTileSize; uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); uv.x *= CUBEUV_TEXEL_WIDTH; uv.y *= CUBEUV_TEXEL_HEIGHT; #ifdef texture2DGradEXT return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; #else return texture2D( envMap, uv ).rgb; #endif } #define cubeUV_r0 1.0 #define cubeUV_m0 - 2.0 #define cubeUV_r1 0.8 #define cubeUV_m1 - 1.0 #define cubeUV_r4 0.4 #define cubeUV_m4 2.0 #define cubeUV_r5 0.305 #define cubeUV_m5 3.0 #define cubeUV_r6 0.21 #define cubeUV_m6 4.0 float roughnessToMip( float roughness ) { float mip = 0.0; if ( roughness >= cubeUV_r1 ) { mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; } else if ( roughness >= cubeUV_r4 ) { mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; } else if ( roughness >= cubeUV_r5 ) { mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; } else if ( roughness >= cubeUV_r6 ) { mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; } else { mip = - 2.0 * log2( 1.16 * roughness ); } return mip; } vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); float mipF = fract( mip ); float mipInt = floor( mip ); vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); if ( mipF == 0.0 ) { return vec4( color0, 1.0 ); } else { vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); return vec4( mix( color0, color1, mipF ), 1.0 ); } } #endif`,defaultnormal_vertex:`vec3 transformedNormal = objectNormal; #ifdef USE_TANGENT vec3 transformedTangent = objectTangent; #endif #ifdef USE_BATCHING mat3 bm = mat3( batchingMatrix ); transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); transformedNormal = bm * transformedNormal; #ifdef USE_TANGENT transformedTangent = bm * transformedTangent; #endif #endif #ifdef USE_INSTANCING mat3 im = mat3( instanceMatrix ); transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); transformedNormal = im * transformedNormal; #ifdef USE_TANGENT transformedTangent = im * transformedTangent; #endif #endif transformedNormal = normalMatrix * transformedNormal; #ifdef FLIP_SIDED transformedNormal = - transformedNormal; #endif #ifdef USE_TANGENT transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; #ifdef FLIP_SIDED transformedTangent = - transformedTangent; #endif #endif`,displacementmap_pars_vertex:`#ifdef USE_DISPLACEMENTMAP uniform sampler2D displacementMap; uniform float displacementScale; uniform float displacementBias; #endif`,displacementmap_vertex:`#ifdef USE_DISPLACEMENTMAP transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); #endif`,emissivemap_fragment:`#ifdef USE_EMISSIVEMAP vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE emissiveColor = sRGBTransferEOTF( emissiveColor ); #endif totalEmissiveRadiance *= emissiveColor.rgb; #endif`,emissivemap_pars_fragment:`#ifdef USE_EMISSIVEMAP uniform sampler2D emissiveMap; #endif`,colorspace_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",colorspace_pars_fragment:`vec4 LinearTransferOETF( in vec4 value ) { return value; } vec4 sRGBTransferEOTF( in vec4 value ) { return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); } vec4 sRGBTransferOETF( in vec4 value ) { return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); }`,envmap_fragment:`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vec3 cameraToFrag; if ( isOrthographic ) { cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); } else { cameraToFrag = normalize( vWorldPosition - cameraPosition ); } vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); #ifdef ENVMAP_MODE_REFLECTION vec3 reflectVec = reflect( cameraToFrag, worldNormal ); #else vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); #endif #else vec3 reflectVec = vReflect; #endif #ifdef ENVMAP_TYPE_CUBE vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); #else vec4 envColor = vec4( 0.0 ); #endif #ifdef ENVMAP_BLENDING_MULTIPLY outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); #elif defined( ENVMAP_BLENDING_MIX ) outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); #elif defined( ENVMAP_BLENDING_ADD ) outgoingLight += envColor.xyz * specularStrength * reflectivity; #endif #endif`,envmap_common_pars_fragment:`#ifdef USE_ENVMAP uniform float envMapIntensity; uniform float flipEnvMap; uniform mat3 envMapRotation; #ifdef ENVMAP_TYPE_CUBE uniform samplerCube envMap; #else uniform sampler2D envMap; #endif #endif`,envmap_pars_fragment:`#ifdef USE_ENVMAP uniform float reflectivity; #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS #endif #ifdef ENV_WORLDPOS varying vec3 vWorldPosition; uniform float refractionRatio; #else varying vec3 vReflect; #endif #endif`,envmap_pars_vertex:`#ifdef USE_ENVMAP #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS #endif #ifdef ENV_WORLDPOS varying vec3 vWorldPosition; #else varying vec3 vReflect; uniform float refractionRatio; #endif #endif`,envmap_physical_pars_fragment:`#ifdef USE_ENVMAP vec3 getIBLIrradiance( const in vec3 normal ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); return PI * envMapColor.rgb * envMapIntensity; #else return vec3( 0.0 ); #endif } vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 reflectVec = reflect( - viewDir, normal ); reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); return envMapColor.rgb * envMapIntensity; #else return vec3( 0.0 ); #endif } #ifdef USE_ANISOTROPY vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 bentNormal = cross( bitangent, viewDir ); bentNormal = normalize( cross( bentNormal, bitangent ) ); bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); return getIBLRadiance( viewDir, bentNormal, roughness ); #else return vec3( 0.0 ); #endif } #endif #endif`,envmap_vertex:`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vWorldPosition = worldPosition.xyz; #else vec3 cameraToVertex; if ( isOrthographic ) { cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); } else { cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); } vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); #ifdef ENVMAP_MODE_REFLECTION vReflect = reflect( cameraToVertex, worldNormal ); #else vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); #endif #endif #endif`,fog_vertex:`#ifdef USE_FOG vFogDepth = - mvPosition.z; #endif`,fog_pars_vertex:`#ifdef USE_FOG varying float vFogDepth; #endif`,fog_fragment:`#ifdef USE_FOG #ifdef FOG_EXP2 float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); #else float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); #endif gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); #endif`,fog_pars_fragment:`#ifdef USE_FOG uniform vec3 fogColor; varying float vFogDepth; #ifdef FOG_EXP2 uniform float fogDensity; #else uniform float fogNear; uniform float fogFar; #endif #endif`,gradientmap_pars_fragment:`#ifdef USE_GRADIENTMAP uniform sampler2D gradientMap; #endif vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { float dotNL = dot( normal, lightDirection ); vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); #ifdef USE_GRADIENTMAP return vec3( texture2D( gradientMap, coord ).r ); #else vec2 fw = fwidth( coord ) * 0.5; return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); #endif }`,lightmap_pars_fragment:`#ifdef USE_LIGHTMAP uniform sampler2D lightMap; uniform float lightMapIntensity; #endif`,lights_lambert_fragment:`LambertMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularStrength = specularStrength;`,lights_lambert_pars_fragment:`varying vec3 vViewPosition; struct LambertMaterial { vec3 diffuseColor; float specularStrength; }; void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Lambert #define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,lights_pars_begin:`uniform bool receiveShadow; uniform vec3 ambientLightColor; #if defined( USE_LIGHT_PROBES ) uniform vec3 lightProbe[ 9 ]; #endif vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { float x = normal.x, y = normal.y, z = normal.z; vec3 result = shCoefficients[ 0 ] * 0.886227; result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); return result; } vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); return irradiance; } vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { vec3 irradiance = ambientLightColor; return irradiance; } float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); if ( cutoffDistance > 0.0 ) { distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); } return distanceFalloff; } float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { return smoothstep( coneCosine, penumbraCosine, angleCosine ); } #if NUM_DIR_LIGHTS > 0 struct DirectionalLight { vec3 direction; vec3 color; }; uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { light.color = directionalLight.color; light.direction = directionalLight.direction; light.visible = true; } #endif #if NUM_POINT_LIGHTS > 0 struct PointLight { vec3 position; vec3 color; float distance; float decay; }; uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { vec3 lVector = pointLight.position - geometryPosition; light.direction = normalize( lVector ); float lightDistance = length( lVector ); light.color = pointLight.color; light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); light.visible = ( light.color != vec3( 0.0 ) ); } #endif #if NUM_SPOT_LIGHTS > 0 struct SpotLight { vec3 position; vec3 direction; vec3 color; float distance; float decay; float coneCos; float penumbraCos; }; uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { vec3 lVector = spotLight.position - geometryPosition; light.direction = normalize( lVector ); float angleCos = dot( light.direction, spotLight.direction ); float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); if ( spotAttenuation > 0.0 ) { float lightDistance = length( lVector ); light.color = spotLight.color * spotAttenuation; light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); light.visible = ( light.color != vec3( 0.0 ) ); } else { light.color = vec3( 0.0 ); light.visible = false; } } #endif #if NUM_RECT_AREA_LIGHTS > 0 struct RectAreaLight { vec3 color; vec3 position; vec3 halfWidth; vec3 halfHeight; }; uniform sampler2D ltc_1; uniform sampler2D ltc_2; uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; #endif #if NUM_HEMI_LIGHTS > 0 struct HemisphereLight { vec3 direction; vec3 skyColor; vec3 groundColor; }; uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { float dotNL = dot( normal, hemiLight.direction ); float hemiDiffuseWeight = 0.5 * dotNL + 0.5; vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); return irradiance; } #endif`,lights_toon_fragment:`ToonMaterial material; material.diffuseColor = diffuseColor.rgb;`,lights_toon_pars_fragment:`varying vec3 vViewPosition; struct ToonMaterial { vec3 diffuseColor; }; void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Toon #define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,lights_phong_fragment:`BlinnPhongMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularColor = specular; material.specularShininess = shininess; material.specularStrength = specularStrength;`,lights_phong_pars_fragment:`varying vec3 vViewPosition; struct BlinnPhongMaterial { vec3 diffuseColor; vec3 specularColor; float specularShininess; float specularStrength; }; void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; } void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_BlinnPhong #define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,lights_physical_fragment:`PhysicalMaterial material; material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; material.roughness = min( material.roughness, 1.0 ); #ifdef IOR material.ior = ior; #ifdef USE_SPECULAR float specularIntensityFactor = specularIntensity; vec3 specularColorFactor = specularColor; #ifdef USE_SPECULAR_COLORMAP specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; #endif #ifdef USE_SPECULAR_INTENSITYMAP specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; #endif material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); #else float specularIntensityFactor = 1.0; vec3 specularColorFactor = vec3( 1.0 ); material.specularF90 = 1.0; #endif material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); #else material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); material.specularF90 = 1.0; #endif #ifdef USE_CLEARCOAT material.clearcoat = clearcoat; material.clearcoatRoughness = clearcoatRoughness; material.clearcoatF0 = vec3( 0.04 ); material.clearcoatF90 = 1.0; #ifdef USE_CLEARCOATMAP material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; #endif material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); material.clearcoatRoughness += geometryRoughness; material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); #endif #ifdef USE_DISPERSION material.dispersion = dispersion; #endif #ifdef USE_IRIDESCENCE material.iridescence = iridescence; material.iridescenceIOR = iridescenceIOR; #ifdef USE_IRIDESCENCEMAP material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; #else material.iridescenceThickness = iridescenceThicknessMaximum; #endif #endif #ifdef USE_SHEEN material.sheenColor = sheenColor; #ifdef USE_SHEEN_COLORMAP material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; #endif material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); #ifdef USE_SHEEN_ROUGHNESSMAP material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; #endif #endif #ifdef USE_ANISOTROPY #ifdef USE_ANISOTROPYMAP mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; #else vec2 anisotropyV = anisotropyVector; #endif material.anisotropy = length( anisotropyV ); if( material.anisotropy == 0.0 ) { anisotropyV = vec2( 1.0, 0.0 ); } else { anisotropyV /= material.anisotropy; material.anisotropy = saturate( material.anisotropy ); } material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; #endif`,lights_physical_pars_fragment:`struct PhysicalMaterial { vec3 diffuseColor; float roughness; vec3 specularColor; float specularF90; float dispersion; #ifdef USE_CLEARCOAT float clearcoat; float clearcoatRoughness; vec3 clearcoatF0; float clearcoatF90; #endif #ifdef USE_IRIDESCENCE float iridescence; float iridescenceIOR; float iridescenceThickness; vec3 iridescenceFresnel; vec3 iridescenceF0; #endif #ifdef USE_SHEEN vec3 sheenColor; float sheenRoughness; #endif #ifdef IOR float ior; #endif #ifdef USE_TRANSMISSION float transmission; float transmissionAlpha; float thickness; float attenuationDistance; vec3 attenuationColor; #endif #ifdef USE_ANISOTROPY float anisotropy; float alphaT; vec3 anisotropyT; vec3 anisotropyB; #endif }; vec3 clearcoatSpecularDirect = vec3( 0.0 ); vec3 clearcoatSpecularIndirect = vec3( 0.0 ); vec3 sheenSpecularDirect = vec3( 0.0 ); vec3 sheenSpecularIndirect = vec3(0.0 ); vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); float x2 = x * x; float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); } float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { float a2 = pow2( alpha ); float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); return 0.5 / max( gv + gl, EPSILON ); } float D_GGX( const in float alpha, const in float dotNH ) { float a2 = pow2( alpha ); float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; return RECIPROCAL_PI * a2 / pow2( denom ); } #ifdef USE_ANISOTROPY float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); float v = 0.5 / ( gv + gl ); return saturate(v); } float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { float a2 = alphaT * alphaB; highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); highp float v2 = dot( v, v ); float w2 = a2 / v2; return RECIPROCAL_PI * a2 * pow2 ( w2 ); } #endif #ifdef USE_CLEARCOAT vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { vec3 f0 = material.clearcoatF0; float f90 = material.clearcoatF90; float roughness = material.clearcoatRoughness; float alpha = pow2( roughness ); vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float dotVH = saturate( dot( viewDir, halfDir ) ); vec3 F = F_Schlick( f0, f90, dotVH ); float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); float D = D_GGX( alpha, dotNH ); return F * ( V * D ); } #endif vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { vec3 f0 = material.specularColor; float f90 = material.specularF90; float roughness = material.roughness; float alpha = pow2( roughness ); vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float dotVH = saturate( dot( viewDir, halfDir ) ); vec3 F = F_Schlick( f0, f90, dotVH ); #ifdef USE_IRIDESCENCE F = mix( F, material.iridescenceFresnel, material.iridescence ); #endif #ifdef USE_ANISOTROPY float dotTL = dot( material.anisotropyT, lightDir ); float dotTV = dot( material.anisotropyT, viewDir ); float dotTH = dot( material.anisotropyT, halfDir ); float dotBL = dot( material.anisotropyB, lightDir ); float dotBV = dot( material.anisotropyB, viewDir ); float dotBH = dot( material.anisotropyB, halfDir ); float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); #else float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); float D = D_GGX( alpha, dotNH ); #endif return F * ( V * D ); } vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { const float LUT_SIZE = 64.0; const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; const float LUT_BIAS = 0.5 / LUT_SIZE; float dotNV = saturate( dot( N, V ) ); vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); uv = uv * LUT_SCALE + LUT_BIAS; return uv; } float LTC_ClippedSphereFormFactor( const in vec3 f ) { float l = length( f ); return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); } vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { float x = dot( v1, v2 ); float y = abs( x ); float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; float b = 3.4175940 + ( 4.1616724 + y ) * y; float v = a / b; float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; return cross( v1, v2 ) * theta_sintheta; } vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; vec3 lightNormal = cross( v1, v2 ); if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); vec3 T1, T2; T1 = normalize( V - N * dot( V, N ) ); T2 = - cross( N, T1 ); mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); vec3 coords[ 4 ]; coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); coords[ 0 ] = normalize( coords[ 0 ] ); coords[ 1 ] = normalize( coords[ 1 ] ); coords[ 2 ] = normalize( coords[ 2 ] ); coords[ 3 ] = normalize( coords[ 3 ] ); vec3 vectorFormFactor = vec3( 0.0 ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); return vec3( result ); } #if defined( USE_SHEEN ) float D_Charlie( float roughness, float dotNH ) { float alpha = pow2( roughness ); float invAlpha = 1.0 / alpha; float cos2h = dotNH * dotNH; float sin2h = max( 1.0 - cos2h, 0.0078125 ); return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); } float V_Neubelt( float dotNV, float dotNL ) { return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); } vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float D = D_Charlie( sheenRoughness, dotNH ); float V = V_Neubelt( dotNV, dotNL ); return sheenColor * ( D * V ); } #endif float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { float dotNV = saturate( dot( normal, viewDir ) ); float r2 = roughness * roughness; float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); return saturate( DG * RECIPROCAL_PI ); } vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { float dotNV = saturate( dot( normal, viewDir ) ); const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); vec4 r = roughness * c0 + c1; float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; return fab; } vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { vec2 fab = DFGApprox( normal, viewDir, roughness ); return specularColor * fab.x + specularF90 * fab.y; } #ifdef USE_IRIDESCENCE void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { #else void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { #endif vec2 fab = DFGApprox( normal, viewDir, roughness ); #ifdef USE_IRIDESCENCE vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); #else vec3 Fr = specularColor; #endif vec3 FssEss = Fr * fab.x + specularF90 * fab.y; float Ess = fab.x + fab.y; float Ems = 1.0 - Ess; vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); singleScatter += FssEss; multiScatter += Fms * Ems; } #if NUM_RECT_AREA_LIGHTS > 0 void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { vec3 normal = geometryNormal; vec3 viewDir = geometryViewDir; vec3 position = geometryPosition; vec3 lightPos = rectAreaLight.position; vec3 halfWidth = rectAreaLight.halfWidth; vec3 halfHeight = rectAreaLight.halfHeight; vec3 lightColor = rectAreaLight.color; float roughness = material.roughness; vec3 rectCoords[ 4 ]; rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; vec2 uv = LTC_Uv( normal, viewDir, roughness ); vec4 t1 = texture2D( ltc_1, uv ); vec4 t2 = texture2D( ltc_2, uv ); mat3 mInv = mat3( vec3( t1.x, 0, t1.y ), vec3( 0, 1, 0 ), vec3( t1.z, 0, t1.w ) ); vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); } #endif void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; #ifdef USE_CLEARCOAT float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); vec3 ccIrradiance = dotNLcc * directLight.color; clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); #endif #ifdef USE_SHEEN sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); #endif reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material ); reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { #ifdef USE_CLEARCOAT clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); #endif #ifdef USE_SHEEN sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); #endif vec3 singleScattering = vec3( 0.0 ); vec3 multiScattering = vec3( 0.0 ); vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; #ifdef USE_IRIDESCENCE computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); #else computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); #endif vec3 totalScattering = singleScattering + multiScattering; vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); reflectedLight.indirectSpecular += radiance * singleScattering; reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; } #define RE_Direct RE_Direct_Physical #define RE_Direct_RectArea RE_Direct_RectArea_Physical #define RE_IndirectDiffuse RE_IndirectDiffuse_Physical #define RE_IndirectSpecular RE_IndirectSpecular_Physical float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); }`,lights_fragment_begin:` vec3 geometryPosition = - vViewPosition; vec3 geometryNormal = normal; vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); vec3 geometryClearcoatNormal = vec3( 0.0 ); #ifdef USE_CLEARCOAT geometryClearcoatNormal = clearcoatNormal; #endif #ifdef USE_IRIDESCENCE float dotNVi = saturate( dot( normal, geometryViewDir ) ); if ( material.iridescenceThickness == 0.0 ) { material.iridescence = 0.0; } else { material.iridescence = saturate( material.iridescence ); } if ( material.iridescence > 0.0 ) { material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); } #endif IncidentLight directLight; #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) PointLight pointLight; #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 PointLightShadow pointLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { pointLight = pointLights[ i ]; getPointLightInfo( pointLight, geometryPosition, directLight ); #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) pointLightShadow = pointLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) SpotLight spotLight; vec4 spotColor; vec3 spotLightCoord; bool inSpotLightMap; #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 SpotLightShadow spotLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { spotLight = spotLights[ i ]; getSpotLightInfo( spotLight, geometryPosition, directLight ); #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS #else #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) #endif #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; #endif #undef SPOT_LIGHT_MAP_INDEX #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) spotLightShadow = spotLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) DirectionalLight directionalLight; #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 DirectionalLightShadow directionalLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { directionalLight = directionalLights[ i ]; getDirectionalLightInfo( directionalLight, directLight ); #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) directionalLightShadow = directionalLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) RectAreaLight rectAreaLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { rectAreaLight = rectAreaLights[ i ]; RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if defined( RE_IndirectDiffuse ) vec3 iblIrradiance = vec3( 0.0 ); vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); #if defined( USE_LIGHT_PROBES ) irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); #endif #if ( NUM_HEMI_LIGHTS > 0 ) #pragma unroll_loop_start for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); } #pragma unroll_loop_end #endif #endif #if defined( RE_IndirectSpecular ) vec3 radiance = vec3( 0.0 ); vec3 clearcoatRadiance = vec3( 0.0 ); #endif`,lights_fragment_maps:`#if defined( RE_IndirectDiffuse ) #ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; irradiance += lightMapIrradiance; #endif #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) iblIrradiance += getIBLIrradiance( geometryNormal ); #endif #endif #if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) #ifdef USE_ANISOTROPY radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); #else radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); #endif #ifdef USE_CLEARCOAT clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); #endif #endif`,lights_fragment_end:`#if defined( RE_IndirectDiffuse ) RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); #endif #if defined( RE_IndirectSpecular ) RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); #endif`,logdepthbuf_fragment:`#if defined( USE_LOGDEPTHBUF ) gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; #endif`,logdepthbuf_pars_fragment:`#if defined( USE_LOGDEPTHBUF ) uniform float logDepthBufFC; varying float vFragDepth; varying float vIsPerspective; #endif`,logdepthbuf_pars_vertex:`#ifdef USE_LOGDEPTHBUF varying float vFragDepth; varying float vIsPerspective; #endif`,logdepthbuf_vertex:`#ifdef USE_LOGDEPTHBUF vFragDepth = 1.0 + gl_Position.w; vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); #endif`,map_fragment:`#ifdef USE_MAP vec4 sampledDiffuseColor = texture2D( map, vMapUv ); #ifdef DECODE_VIDEO_TEXTURE sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); #endif diffuseColor *= sampledDiffuseColor; #endif`,map_pars_fragment:`#ifdef USE_MAP uniform sampler2D map; #endif`,map_particle_fragment:`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) #if defined( USE_POINTS_UV ) vec2 uv = vUv; #else vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; #endif #endif #ifdef USE_MAP diffuseColor *= texture2D( map, uv ); #endif #ifdef USE_ALPHAMAP diffuseColor.a *= texture2D( alphaMap, uv ).g; #endif`,map_particle_pars_fragment:`#if defined( USE_POINTS_UV ) varying vec2 vUv; #else #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) uniform mat3 uvTransform; #endif #endif #ifdef USE_MAP uniform sampler2D map; #endif #ifdef USE_ALPHAMAP uniform sampler2D alphaMap; #endif`,metalnessmap_fragment:`float metalnessFactor = metalness; #ifdef USE_METALNESSMAP vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); metalnessFactor *= texelMetalness.b; #endif`,metalnessmap_pars_fragment:`#ifdef USE_METALNESSMAP uniform sampler2D metalnessMap; #endif`,morphinstance_vertex:`#ifdef USE_INSTANCING_MORPH float morphTargetInfluences[ MORPHTARGETS_COUNT ]; float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; } #endif`,morphcolor_vertex:`#if defined( USE_MORPHCOLORS ) vColor *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { #if defined( USE_COLOR_ALPHA ) if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; #elif defined( USE_COLOR ) if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; #endif } #endif`,morphnormal_vertex:`#ifdef USE_MORPHNORMALS objectNormal *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; } #endif`,morphtarget_pars_vertex:`#ifdef USE_MORPHTARGETS #ifndef USE_INSTANCING_MORPH uniform float morphTargetBaseInfluence; uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; #endif uniform sampler2DArray morphTargetsTexture; uniform ivec2 morphTargetsTextureSize; vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; int y = texelIndex / morphTargetsTextureSize.x; int x = texelIndex - y * morphTargetsTextureSize.x; ivec3 morphUV = ivec3( x, y, morphTargetIndex ); return texelFetch( morphTargetsTexture, morphUV, 0 ); } #endif`,morphtarget_vertex:`#ifdef USE_MORPHTARGETS transformed *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; } #endif`,normal_fragment_begin:`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; #ifdef FLAT_SHADED vec3 fdx = dFdx( vViewPosition ); vec3 fdy = dFdy( vViewPosition ); vec3 normal = normalize( cross( fdx, fdy ) ); #else vec3 normal = normalize( vNormal ); #ifdef DOUBLE_SIDED normal *= faceDirection; #endif #endif #if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) #ifdef USE_TANGENT mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); #else mat3 tbn = getTangentFrame( - vViewPosition, normal, #if defined( USE_NORMALMAP ) vNormalMapUv #elif defined( USE_CLEARCOAT_NORMALMAP ) vClearcoatNormalMapUv #else vUv #endif ); #endif #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) tbn[0] *= faceDirection; tbn[1] *= faceDirection; #endif #endif #ifdef USE_CLEARCOAT_NORMALMAP #ifdef USE_TANGENT mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); #else mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); #endif #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) tbn2[0] *= faceDirection; tbn2[1] *= faceDirection; #endif #endif vec3 nonPerturbedNormal = normal;`,normal_fragment_maps:`#ifdef USE_NORMALMAP_OBJECTSPACE normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; #ifdef FLIP_SIDED normal = - normal; #endif #ifdef DOUBLE_SIDED normal = normal * faceDirection; #endif normal = normalize( normalMatrix * normal ); #elif defined( USE_NORMALMAP_TANGENTSPACE ) vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; mapN.xy *= normalScale; normal = normalize( tbn * mapN ); #elif defined( USE_BUMPMAP ) normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); #endif`,normal_pars_fragment:`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif #endif`,normal_pars_vertex:`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif #endif`,normal_vertex:`#ifndef FLAT_SHADED vNormal = normalize( transformedNormal ); #ifdef USE_TANGENT vTangent = normalize( transformedTangent ); vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); #endif #endif`,normalmap_pars_fragment:`#ifdef USE_NORMALMAP uniform sampler2D normalMap; uniform vec2 normalScale; #endif #ifdef USE_NORMALMAP_OBJECTSPACE uniform mat3 normalMatrix; #endif #if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { vec3 q0 = dFdx( eye_pos.xyz ); vec3 q1 = dFdy( eye_pos.xyz ); vec2 st0 = dFdx( uv.st ); vec2 st1 = dFdy( uv.st ); vec3 N = surf_norm; vec3 q1perp = cross( q1, N ); vec3 q0perp = cross( N, q0 ); vec3 T = q1perp * st0.x + q0perp * st1.x; vec3 B = q1perp * st0.y + q0perp * st1.y; float det = max( dot( T, T ), dot( B, B ) ); float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); return mat3( T * scale, B * scale, N ); } #endif`,clearcoat_normal_fragment_begin:`#ifdef USE_CLEARCOAT vec3 clearcoatNormal = nonPerturbedNormal; #endif`,clearcoat_normal_fragment_maps:`#ifdef USE_CLEARCOAT_NORMALMAP vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; clearcoatMapN.xy *= clearcoatNormalScale; clearcoatNormal = normalize( tbn2 * clearcoatMapN ); #endif`,clearcoat_pars_fragment:`#ifdef USE_CLEARCOATMAP uniform sampler2D clearcoatMap; #endif #ifdef USE_CLEARCOAT_NORMALMAP uniform sampler2D clearcoatNormalMap; uniform vec2 clearcoatNormalScale; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP uniform sampler2D clearcoatRoughnessMap; #endif`,iridescence_pars_fragment:`#ifdef USE_IRIDESCENCEMAP uniform sampler2D iridescenceMap; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform sampler2D iridescenceThicknessMap; #endif`,opaque_fragment:`#ifdef OPAQUE diffuseColor.a = 1.0; #endif #ifdef USE_TRANSMISSION diffuseColor.a *= material.transmissionAlpha; #endif gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,packing:`vec3 packNormalToRGB( const in vec3 normal ) { return normalize( normal ) * 0.5 + 0.5; } vec3 unpackRGBToNormal( const in vec3 rgb ) { return 2.0 * rgb.xyz - 1.0; } const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; const float Inv255 = 1. / 255.; const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); vec4 packDepthToRGBA( const in float v ) { if( v <= 0.0 ) return vec4( 0., 0., 0., 0. ); if( v >= 1.0 ) return vec4( 1., 1., 1., 1. ); float vuf; float af = modf( v * PackFactors.a, vuf ); float bf = modf( vuf * ShiftRight8, vuf ); float gf = modf( vuf * ShiftRight8, vuf ); return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); } vec3 packDepthToRGB( const in float v ) { if( v <= 0.0 ) return vec3( 0., 0., 0. ); if( v >= 1.0 ) return vec3( 1., 1., 1. ); float vuf; float bf = modf( v * PackFactors.b, vuf ); float gf = modf( vuf * ShiftRight8, vuf ); return vec3( vuf * Inv255, gf * PackUpscale, bf ); } vec2 packDepthToRG( const in float v ) { if( v <= 0.0 ) return vec2( 0., 0. ); if( v >= 1.0 ) return vec2( 1., 1. ); float vuf; float gf = modf( v * 256., vuf ); return vec2( vuf * Inv255, gf ); } float unpackRGBAToDepth( const in vec4 v ) { return dot( v, UnpackFactors4 ); } float unpackRGBToDepth( const in vec3 v ) { return dot( v, UnpackFactors3 ); } float unpackRGToDepth( const in vec2 v ) { return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; } vec4 pack2HalfToRGBA( const in vec2 v ) { vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); } vec2 unpackRGBATo2Half( const in vec4 v ) { return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); } float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { return ( viewZ + near ) / ( near - far ); } float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { return depth * ( near - far ) - near; } float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); } float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { return ( near * far ) / ( ( far - near ) * depth - far ); }`,premultiplied_alpha_fragment:`#ifdef PREMULTIPLIED_ALPHA gl_FragColor.rgb *= gl_FragColor.a; #endif`,project_vertex:`vec4 mvPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING mvPosition = batchingMatrix * mvPosition; #endif #ifdef USE_INSTANCING mvPosition = instanceMatrix * mvPosition; #endif mvPosition = modelViewMatrix * mvPosition; gl_Position = projectionMatrix * mvPosition;`,dithering_fragment:`#ifdef DITHERING gl_FragColor.rgb = dithering( gl_FragColor.rgb ); #endif`,dithering_pars_fragment:`#ifdef DITHERING vec3 dithering( vec3 color ) { float grid_position = rand( gl_FragCoord.xy ); vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); return color + dither_shift_RGB; } #endif`,roughnessmap_fragment:`float roughnessFactor = roughness; #ifdef USE_ROUGHNESSMAP vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); roughnessFactor *= texelRoughness.g; #endif`,roughnessmap_pars_fragment:`#ifdef USE_ROUGHNESSMAP uniform sampler2D roughnessMap; #endif`,shadowmap_pars_fragment:`#if NUM_SPOT_LIGHT_COORDS > 0 varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif #if NUM_SPOT_LIGHT_MAPS > 0 uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; #endif #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; struct DirectionalLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; struct SpotLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; #endif #if NUM_POINT_LIGHT_SHADOWS > 0 uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; struct PointLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; float shadowCameraNear; float shadowCameraFar; }; uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; #endif float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) ); } vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { return unpackRGBATo2Half( texture2D( shadow, uv ) ); } float VSMShadow (sampler2D shadow, vec2 uv, float compare ){ float occlusion = 1.0; vec2 distribution = texture2DDistribution( shadow, uv ); float hard_shadow = step( compare , distribution.x ); if (hard_shadow != 1.0 ) { float distance = compare - distribution.x ; float variance = max( 0.00000, distribution.y * distribution.y ); float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); } return occlusion; } float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { float shadow = 1.0; shadowCoord.xyz /= shadowCoord.w; shadowCoord.z += shadowBias; bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; bool frustumTest = inFrustum && shadowCoord.z <= 1.0; if ( frustumTest ) { #if defined( SHADOWMAP_TYPE_PCF ) vec2 texelSize = vec2( 1.0 ) / shadowMapSize; float dx0 = - texelSize.x * shadowRadius; float dy0 = - texelSize.y * shadowRadius; float dx1 = + texelSize.x * shadowRadius; float dy1 = + texelSize.y * shadowRadius; float dx2 = dx0 / 2.0; float dy2 = dy0 / 2.0; float dx3 = dx1 / 2.0; float dy3 = dy1 / 2.0; shadow = ( texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) ) * ( 1.0 / 17.0 ); #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) vec2 texelSize = vec2( 1.0 ) / shadowMapSize; float dx = texelSize.x; float dy = texelSize.y; vec2 uv = shadowCoord.xy; vec2 f = fract( uv * shadowMapSize + 0.5 ); uv -= f * texelSize; shadow = ( texture2DCompare( shadowMap, uv, shadowCoord.z ) + texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), f.x ) + mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), f.x ) + mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), f.y ) + mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), f.y ) + mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), f.x ), mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), f.x ), f.y ) ) * ( 1.0 / 9.0 ); #elif defined( SHADOWMAP_TYPE_VSM ) shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); #else shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); #endif } return mix( 1.0, shadow, shadowIntensity ); } vec2 cubeToUV( vec3 v, float texelSizeY ) { vec3 absV = abs( v ); float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); absV *= scaleToCube; v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); vec2 planar = v.xy; float almostATexel = 1.5 * texelSizeY; float almostOne = 1.0 - almostATexel; if ( absV.z >= almostOne ) { if ( v.z > 0.0 ) planar.x = 4.0 - v.x; } else if ( absV.x >= almostOne ) { float signX = sign( v.x ); planar.x = v.z * signX + 2.0 * signX; } else if ( absV.y >= almostOne ) { float signY = sign( v.y ); planar.x = v.x + 2.0 * signY + 2.0; planar.y = v.z * signY - 2.0; } return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); } float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { float shadow = 1.0; vec3 lightToPosition = shadowCoord.xyz; float lightToPositionLength = length( lightToPosition ); if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) { float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; vec3 bd3D = normalize( lightToPosition ); vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; shadow = ( texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) ) * ( 1.0 / 9.0 ); #else shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); #endif } return mix( 1.0, shadow, shadowIntensity ); } #endif`,shadowmap_pars_vertex:`#if NUM_SPOT_LIGHT_COORDS > 0 uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; struct DirectionalLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 struct SpotLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; #endif #if NUM_POINT_LIGHT_SHADOWS > 0 uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; struct PointLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; float shadowCameraNear; float shadowCameraFar; }; uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; #endif #endif`,shadowmap_vertex:`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); vec4 shadowWorldPosition; #endif #if defined( USE_SHADOWMAP ) #if NUM_DIR_LIGHT_SHADOWS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif #if NUM_POINT_LIGHT_SHADOWS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif #endif #if NUM_SPOT_LIGHT_COORDS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { shadowWorldPosition = worldPosition; #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; #endif vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif`,shadowmask_pars_fragment:`float getShadowMask() { float shadow = 1.0; #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 DirectionalLightShadow directionalLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { directionalLight = directionalLightShadows[ i ]; shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; } #pragma unroll_loop_end #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 SpotLightShadow spotLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { spotLight = spotLightShadows[ i ]; shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; } #pragma unroll_loop_end #endif #if NUM_POINT_LIGHT_SHADOWS > 0 PointLightShadow pointLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { pointLight = pointLightShadows[ i ]; shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; } #pragma unroll_loop_end #endif #endif return shadow; }`,skinbase_vertex:`#ifdef USE_SKINNING mat4 boneMatX = getBoneMatrix( skinIndex.x ); mat4 boneMatY = getBoneMatrix( skinIndex.y ); mat4 boneMatZ = getBoneMatrix( skinIndex.z ); mat4 boneMatW = getBoneMatrix( skinIndex.w ); #endif`,skinning_pars_vertex:`#ifdef USE_SKINNING uniform mat4 bindMatrix; uniform mat4 bindMatrixInverse; uniform highp sampler2D boneTexture; mat4 getBoneMatrix( const in float i ) { int size = textureSize( boneTexture, 0 ).x; int j = int( i ) * 4; int x = j % size; int y = j / size; vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); return mat4( v1, v2, v3, v4 ); } #endif`,skinning_vertex:`#ifdef USE_SKINNING vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); vec4 skinned = vec4( 0.0 ); skinned += boneMatX * skinVertex * skinWeight.x; skinned += boneMatY * skinVertex * skinWeight.y; skinned += boneMatZ * skinVertex * skinWeight.z; skinned += boneMatW * skinVertex * skinWeight.w; transformed = ( bindMatrixInverse * skinned ).xyz; #endif`,skinnormal_vertex:`#ifdef USE_SKINNING mat4 skinMatrix = mat4( 0.0 ); skinMatrix += skinWeight.x * boneMatX; skinMatrix += skinWeight.y * boneMatY; skinMatrix += skinWeight.z * boneMatZ; skinMatrix += skinWeight.w * boneMatW; skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; #ifdef USE_TANGENT objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; #endif #endif`,specularmap_fragment:`float specularStrength; #ifdef USE_SPECULARMAP vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); specularStrength = texelSpecular.r; #else specularStrength = 1.0; #endif`,specularmap_pars_fragment:`#ifdef USE_SPECULARMAP uniform sampler2D specularMap; #endif`,tonemapping_fragment:`#if defined( TONE_MAPPING ) gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); #endif`,tonemapping_pars_fragment:`#ifndef saturate #define saturate( a ) clamp( a, 0.0, 1.0 ) #endif uniform float toneMappingExposure; vec3 LinearToneMapping( vec3 color ) { return saturate( toneMappingExposure * color ); } vec3 ReinhardToneMapping( vec3 color ) { color *= toneMappingExposure; return saturate( color / ( vec3( 1.0 ) + color ) ); } vec3 CineonToneMapping( vec3 color ) { color *= toneMappingExposure; color = max( vec3( 0.0 ), color - 0.004 ); return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); } vec3 RRTAndODTFit( vec3 v ) { vec3 a = v * ( v + 0.0245786 ) - 0.000090537; vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; return a / b; } vec3 ACESFilmicToneMapping( vec3 color ) { const mat3 ACESInputMat = mat3( vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), vec3( 0.04823, 0.01566, 0.83777 ) ); const mat3 ACESOutputMat = mat3( vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), vec3( -0.07367, -0.00605, 1.07602 ) ); color *= toneMappingExposure / 0.6; color = ACESInputMat * color; color = RRTAndODTFit( color ); color = ACESOutputMat * color; return saturate( color ); } const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) ); const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) ); vec3 agxDefaultContrastApprox( vec3 x ) { vec3 x2 = x * x; vec3 x4 = x2 * x2; return + 15.5 * x4 * x2 - 40.14 * x4 * x + 31.96 * x4 - 6.868 * x2 * x + 0.4298 * x2 + 0.1191 * x - 0.00232; } vec3 AgXToneMapping( vec3 color ) { const mat3 AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) ); const mat3 AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) ); const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; color *= toneMappingExposure; color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; color = AgXInsetMatrix * color; color = max( color, 1e-10 ); color = log2( color ); color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); color = clamp( color, 0.0, 1.0 ); color = agxDefaultContrastApprox( color ); color = AgXOutsetMatrix * color; color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); color = LINEAR_REC2020_TO_LINEAR_SRGB * color; color = clamp( color, 0.0, 1.0 ); return color; } vec3 NeutralToneMapping( vec3 color ) { const float StartCompression = 0.8 - 0.04; const float Desaturation = 0.15; color *= toneMappingExposure; float x = min( color.r, min( color.g, color.b ) ); float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; color -= offset; float peak = max( color.r, max( color.g, color.b ) ); if ( peak < StartCompression ) return color; float d = 1. - StartCompression; float newPeak = 1. - d * d / ( peak + d - StartCompression ); color *= newPeak / peak; float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); return mix( color, vec3( newPeak ), g ); } vec3 CustomToneMapping( vec3 color ) { return color; }`,transmission_fragment:`#ifdef USE_TRANSMISSION material.transmission = transmission; material.transmissionAlpha = 1.0; material.thickness = thickness; material.attenuationDistance = attenuationDistance; material.attenuationColor = attenuationColor; #ifdef USE_TRANSMISSIONMAP material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; #endif #ifdef USE_THICKNESSMAP material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; #endif vec3 pos = vWorldPosition; vec3 v = normalize( cameraPosition - pos ); vec3 n = inverseTransformDirection( normal, viewMatrix ); vec4 transmitted = getIBLVolumeRefraction( n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, material.attenuationColor, material.attenuationDistance ); material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); #endif`,transmission_pars_fragment:`#ifdef USE_TRANSMISSION uniform float transmission; uniform float thickness; uniform float attenuationDistance; uniform vec3 attenuationColor; #ifdef USE_TRANSMISSIONMAP uniform sampler2D transmissionMap; #endif #ifdef USE_THICKNESSMAP uniform sampler2D thicknessMap; #endif uniform vec2 transmissionSamplerSize; uniform sampler2D transmissionSamplerMap; uniform mat4 modelMatrix; uniform mat4 projectionMatrix; varying vec3 vWorldPosition; float w0( float a ) { return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); } float w1( float a ) { return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); } float w2( float a ){ return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); } float w3( float a ) { return ( 1.0 / 6.0 ) * ( a * a * a ); } float g0( float a ) { return w0( a ) + w1( a ); } float g1( float a ) { return w2( a ) + w3( a ); } float h0( float a ) { return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); } float h1( float a ) { return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); } vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { uv = uv * texelSize.zw + 0.5; vec2 iuv = floor( uv ); vec2 fuv = fract( uv ); float g0x = g0( fuv.x ); float g1x = g1( fuv.x ); float h0x = h0( fuv.x ); float h1x = h1( fuv.x ); float h0y = h0( fuv.y ); float h1y = h1( fuv.y ); vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); } vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); vec2 fLodSizeInv = 1.0 / fLodSize; vec2 cLodSizeInv = 1.0 / cLodSize; vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); return mix( fSample, cSample, fract( lod ) ); } vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); vec3 modelScale; modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); return normalize( refractionVector ) * thickness * modelScale; } float applyIorToRoughness( const in float roughness, const in float ior ) { return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); } vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); } vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { if ( isinf( attenuationDistance ) ) { return vec3( 1.0 ); } else { vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; } } vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, const in vec3 attenuationColor, const in float attenuationDistance ) { vec4 transmittedLight; vec3 transmittance; #ifdef USE_DISPERSION float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); for ( int i = 0; i < 3; i ++ ) { vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); vec3 refractedRayExit = position + transmissionRay; vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); vec2 refractionCoords = ndcPos.xy / ndcPos.w; refractionCoords += 1.0; refractionCoords /= 2.0; vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); transmittedLight[ i ] = transmissionSample[ i ]; transmittedLight.a += transmissionSample.a; transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; } transmittedLight.a /= 3.0; #else vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); vec3 refractedRayExit = position + transmissionRay; vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); vec2 refractionCoords = ndcPos.xy / ndcPos.w; refractionCoords += 1.0; refractionCoords /= 2.0; transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); #endif vec3 attenuatedColor = transmittance * transmittedLight.rgb; vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); } #endif`,uv_pars_fragment:`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP varying vec2 vMapUv; #endif #ifdef USE_ALPHAMAP varying vec2 vAlphaMapUv; #endif #ifdef USE_LIGHTMAP varying vec2 vLightMapUv; #endif #ifdef USE_AOMAP varying vec2 vAoMapUv; #endif #ifdef USE_BUMPMAP varying vec2 vBumpMapUv; #endif #ifdef USE_NORMALMAP varying vec2 vNormalMapUv; #endif #ifdef USE_EMISSIVEMAP varying vec2 vEmissiveMapUv; #endif #ifdef USE_METALNESSMAP varying vec2 vMetalnessMapUv; #endif #ifdef USE_ROUGHNESSMAP varying vec2 vRoughnessMapUv; #endif #ifdef USE_ANISOTROPYMAP varying vec2 vAnisotropyMapUv; #endif #ifdef USE_CLEARCOATMAP varying vec2 vClearcoatMapUv; #endif #ifdef USE_CLEARCOAT_NORMALMAP varying vec2 vClearcoatNormalMapUv; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP varying vec2 vClearcoatRoughnessMapUv; #endif #ifdef USE_IRIDESCENCEMAP varying vec2 vIridescenceMapUv; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP varying vec2 vIridescenceThicknessMapUv; #endif #ifdef USE_SHEEN_COLORMAP varying vec2 vSheenColorMapUv; #endif #ifdef USE_SHEEN_ROUGHNESSMAP varying vec2 vSheenRoughnessMapUv; #endif #ifdef USE_SPECULARMAP varying vec2 vSpecularMapUv; #endif #ifdef USE_SPECULAR_COLORMAP varying vec2 vSpecularColorMapUv; #endif #ifdef USE_SPECULAR_INTENSITYMAP varying vec2 vSpecularIntensityMapUv; #endif #ifdef USE_TRANSMISSIONMAP uniform mat3 transmissionMapTransform; varying vec2 vTransmissionMapUv; #endif #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; #endif`,uv_pars_vertex:`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP uniform mat3 mapTransform; varying vec2 vMapUv; #endif #ifdef USE_ALPHAMAP uniform mat3 alphaMapTransform; varying vec2 vAlphaMapUv; #endif #ifdef USE_LIGHTMAP uniform mat3 lightMapTransform; varying vec2 vLightMapUv; #endif #ifdef USE_AOMAP uniform mat3 aoMapTransform; varying vec2 vAoMapUv; #endif #ifdef USE_BUMPMAP uniform mat3 bumpMapTransform; varying vec2 vBumpMapUv; #endif #ifdef USE_NORMALMAP uniform mat3 normalMapTransform; varying vec2 vNormalMapUv; #endif #ifdef USE_DISPLACEMENTMAP uniform mat3 displacementMapTransform; varying vec2 vDisplacementMapUv; #endif #ifdef USE_EMISSIVEMAP uniform mat3 emissiveMapTransform; varying vec2 vEmissiveMapUv; #endif #ifdef USE_METALNESSMAP uniform mat3 metalnessMapTransform; varying vec2 vMetalnessMapUv; #endif #ifdef USE_ROUGHNESSMAP uniform mat3 roughnessMapTransform; varying vec2 vRoughnessMapUv; #endif #ifdef USE_ANISOTROPYMAP uniform mat3 anisotropyMapTransform; varying vec2 vAnisotropyMapUv; #endif #ifdef USE_CLEARCOATMAP uniform mat3 clearcoatMapTransform; varying vec2 vClearcoatMapUv; #endif #ifdef USE_CLEARCOAT_NORMALMAP uniform mat3 clearcoatNormalMapTransform; varying vec2 vClearcoatNormalMapUv; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP uniform mat3 clearcoatRoughnessMapTransform; varying vec2 vClearcoatRoughnessMapUv; #endif #ifdef USE_SHEEN_COLORMAP uniform mat3 sheenColorMapTransform; varying vec2 vSheenColorMapUv; #endif #ifdef USE_SHEEN_ROUGHNESSMAP uniform mat3 sheenRoughnessMapTransform; varying vec2 vSheenRoughnessMapUv; #endif #ifdef USE_IRIDESCENCEMAP uniform mat3 iridescenceMapTransform; varying vec2 vIridescenceMapUv; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform mat3 iridescenceThicknessMapTransform; varying vec2 vIridescenceThicknessMapUv; #endif #ifdef USE_SPECULARMAP uniform mat3 specularMapTransform; varying vec2 vSpecularMapUv; #endif #ifdef USE_SPECULAR_COLORMAP uniform mat3 specularColorMapTransform; varying vec2 vSpecularColorMapUv; #endif #ifdef USE_SPECULAR_INTENSITYMAP uniform mat3 specularIntensityMapTransform; varying vec2 vSpecularIntensityMapUv; #endif #ifdef USE_TRANSMISSIONMAP uniform mat3 transmissionMapTransform; varying vec2 vTransmissionMapUv; #endif #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; #endif`,uv_vertex:`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) vUv = vec3( uv, 1 ).xy; #endif #ifdef USE_MAP vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; #endif #ifdef USE_ALPHAMAP vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; #endif #ifdef USE_LIGHTMAP vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; #endif #ifdef USE_AOMAP vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; #endif #ifdef USE_BUMPMAP vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; #endif #ifdef USE_NORMALMAP vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; #endif #ifdef USE_DISPLACEMENTMAP vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; #endif #ifdef USE_EMISSIVEMAP vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; #endif #ifdef USE_METALNESSMAP vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_ROUGHNESSMAP vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_ANISOTROPYMAP vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOATMAP vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOAT_NORMALMAP vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_IRIDESCENCEMAP vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_SHEEN_COLORMAP vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; #endif #ifdef USE_SHEEN_ROUGHNESSMAP vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULARMAP vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULAR_COLORMAP vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULAR_INTENSITYMAP vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; #endif #ifdef USE_TRANSMISSIONMAP vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; #endif #ifdef USE_THICKNESSMAP vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; #endif`,worldpos_vertex:`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 vec4 worldPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING worldPosition = batchingMatrix * worldPosition; #endif #ifdef USE_INSTANCING worldPosition = instanceMatrix * worldPosition; #endif worldPosition = modelMatrix * worldPosition; #endif`,background_vert:`varying vec2 vUv; uniform mat3 uvTransform; void main() { vUv = ( uvTransform * vec3( uv, 1 ) ).xy; gl_Position = vec4( position.xy, 1.0, 1.0 ); }`,background_frag:`uniform sampler2D t2D; uniform float backgroundIntensity; varying vec2 vUv; void main() { vec4 texColor = texture2D( t2D, vUv ); #ifdef DECODE_VIDEO_TEXTURE texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); #endif texColor.rgb *= backgroundIntensity; gl_FragColor = texColor; #include #include }`,backgroundCube_vert:`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; }`,backgroundCube_frag:`#ifdef ENVMAP_TYPE_CUBE uniform samplerCube envMap; #elif defined( ENVMAP_TYPE_CUBE_UV ) uniform sampler2D envMap; #endif uniform float flipEnvMap; uniform float backgroundBlurriness; uniform float backgroundIntensity; uniform mat3 backgroundRotation; varying vec3 vWorldDirection; #include void main() { #ifdef ENVMAP_TYPE_CUBE vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); #elif defined( ENVMAP_TYPE_CUBE_UV ) vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); #else vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); #endif texColor.rgb *= backgroundIntensity; gl_FragColor = texColor; #include #include }`,cube_vert:`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; }`,cube_frag:`uniform samplerCube tCube; uniform float tFlip; uniform float opacity; varying vec3 vWorldDirection; void main() { vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); gl_FragColor = texColor; gl_FragColor.a *= opacity; #include #include }`,depth_vert:`#include #include #include #include #include #include #include #include varying vec2 vHighPrecisionZW; void main() { #include #include #include #include #ifdef USE_DISPLACEMENTMAP #include #include #include #endif #include #include #include #include #include #include #include vHighPrecisionZW = gl_Position.zw; }`,depth_frag:`#if DEPTH_PACKING == 3200 uniform float opacity; #endif #include #include #include #include #include #include #include #include #include varying vec2 vHighPrecisionZW; void main() { vec4 diffuseColor = vec4( 1.0 ); #include #if DEPTH_PACKING == 3200 diffuseColor.a = opacity; #endif #include #include #include #include #include float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5; #if DEPTH_PACKING == 3200 gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); #elif DEPTH_PACKING == 3201 gl_FragColor = packDepthToRGBA( fragCoordZ ); #elif DEPTH_PACKING == 3202 gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); #elif DEPTH_PACKING == 3203 gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); #endif }`,distanceRGBA_vert:`#define DISTANCE varying vec3 vWorldPosition; #include #include #include #include #include #include #include void main() { #include #include #include #include #ifdef USE_DISPLACEMENTMAP #include #include #include #endif #include #include #include #include #include #include #include vWorldPosition = worldPosition.xyz; }`,distanceRGBA_frag:`#define DISTANCE uniform vec3 referencePosition; uniform float nearDistance; uniform float farDistance; varying vec3 vWorldPosition; #include #include #include #include #include #include #include #include void main () { vec4 diffuseColor = vec4( 1.0 ); #include #include #include #include #include float dist = length( vWorldPosition - referencePosition ); dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); dist = saturate( dist ); gl_FragColor = packDepthToRGBA( dist ); }`,equirect_vert:`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include }`,equirect_frag:`uniform sampler2D tEquirect; varying vec3 vWorldDirection; #include void main() { vec3 direction = normalize( vWorldDirection ); vec2 sampleUV = equirectUv( direction ); gl_FragColor = texture2D( tEquirect, sampleUV ); #include #include }`,linedashed_vert:`uniform float scale; attribute float lineDistance; varying float vLineDistance; #include #include #include #include #include #include #include void main() { vLineDistance = scale * lineDistance; #include #include #include #include #include #include #include #include #include #include }`,linedashed_frag:`uniform vec3 diffuse; uniform float opacity; uniform float dashSize; uniform float totalSize; varying float vLineDistance; #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include if ( mod( vLineDistance, totalSize ) > dashSize ) { discard; } vec3 outgoingLight = vec3( 0.0 ); #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include #include }`,meshbasic_vert:`#include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) #include #include #include #include #include #endif #include #include #include #include #include #include #include #include #include }`,meshbasic_frag:`uniform vec3 diffuse; uniform float opacity; #ifndef FLAT_SHADED varying vec3 vNormal; #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include #include #include #include #include #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); #ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; #else reflectedLight.indirectDiffuse += vec3( 1.0 ); #endif #include reflectedLight.indirectDiffuse *= diffuseColor.rgb; vec3 outgoingLight = reflectedLight.indirectDiffuse; #include #include #include #include #include #include #include }`,meshlambert_vert:`#define LAMBERT varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #include }`,meshlambert_frag:`#define LAMBERT uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; #include #include #include #include #include #include #include }`,meshmatcap_vert:`#define MATCAP varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; }`,meshmatcap_frag:`#define MATCAP uniform vec3 diffuse; uniform float opacity; uniform sampler2D matcap; varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include #include #include #include #include #include #include vec3 viewDir = normalize( vViewPosition ); vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); vec3 y = cross( viewDir, x ); vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; #ifdef USE_MATCAP vec4 matcapColor = texture2D( matcap, uv ); #else vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); #endif vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; #include #include #include #include #include #include }`,meshnormal_vert:`#define NORMAL #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; #endif #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) vViewPosition = - mvPosition.xyz; #endif }`,meshnormal_frag:`#define NORMAL uniform float opacity; #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; #endif #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); #include #include #include #include gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); #ifdef OPAQUE gl_FragColor.a = 1.0; #endif }`,meshphong_vert:`#define PHONG varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #include }`,meshphong_frag:`#define PHONG uniform vec3 diffuse; uniform vec3 emissive; uniform vec3 specular; uniform float shininess; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; #include #include #include #include #include #include #include }`,meshphysical_vert:`#define STANDARD varying vec3 vViewPosition; #ifdef USE_TRANSMISSION varying vec3 vWorldPosition; #endif #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #ifdef USE_TRANSMISSION vWorldPosition = worldPosition.xyz; #endif }`,meshphysical_frag:`#define STANDARD #ifdef PHYSICAL #define IOR #define USE_SPECULAR #endif uniform vec3 diffuse; uniform vec3 emissive; uniform float roughness; uniform float metalness; uniform float opacity; #ifdef IOR uniform float ior; #endif #ifdef USE_SPECULAR uniform float specularIntensity; uniform vec3 specularColor; #ifdef USE_SPECULAR_COLORMAP uniform sampler2D specularColorMap; #endif #ifdef USE_SPECULAR_INTENSITYMAP uniform sampler2D specularIntensityMap; #endif #endif #ifdef USE_CLEARCOAT uniform float clearcoat; uniform float clearcoatRoughness; #endif #ifdef USE_DISPERSION uniform float dispersion; #endif #ifdef USE_IRIDESCENCE uniform float iridescence; uniform float iridescenceIOR; uniform float iridescenceThicknessMinimum; uniform float iridescenceThicknessMaximum; #endif #ifdef USE_SHEEN uniform vec3 sheenColor; uniform float sheenRoughness; #ifdef USE_SHEEN_COLORMAP uniform sampler2D sheenColorMap; #endif #ifdef USE_SHEEN_ROUGHNESSMAP uniform sampler2D sheenRoughnessMap; #endif #endif #ifdef USE_ANISOTROPY uniform vec2 anisotropyVector; #ifdef USE_ANISOTROPYMAP uniform sampler2D anisotropyMap; #endif #endif varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; #include vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; #ifdef USE_SHEEN float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; #endif #ifdef USE_CLEARCOAT float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; #endif #include #include #include #include #include #include }`,meshtoon_vert:`#define TOON varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include }`,meshtoon_frag:`#define TOON uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; #include #include #include #include #include #include }`,points_vert:`uniform float size; uniform float scale; #include #include #include #include #include #include #ifdef USE_POINTS_UV varying vec2 vUv; uniform mat3 uvTransform; #endif void main() { #ifdef USE_POINTS_UV vUv = ( uvTransform * vec3( uv, 1 ) ).xy; #endif #include #include #include #include #include #include gl_PointSize = size; #ifdef USE_SIZEATTENUATION bool isPerspective = isPerspectiveMatrix( projectionMatrix ); if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); #endif #include #include #include #include }`,points_frag:`uniform vec3 diffuse; uniform float opacity; #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include vec3 outgoingLight = vec3( 0.0 ); #include #include #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include #include }`,shadow_vert:`#include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include }`,shadow_frag:`uniform vec3 color; uniform float opacity; #include #include #include #include #include #include #include #include void main() { #include gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); #include #include #include }`,sprite_vert:`uniform float rotation; uniform vec2 center; #include #include #include #include #include void main() { #include vec4 mvPosition = modelViewMatrix[ 3 ]; vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); #ifndef USE_SIZEATTENUATION bool isPerspective = isPerspectiveMatrix( projectionMatrix ); if ( isPerspective ) scale *= - mvPosition.z; #endif vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; vec2 rotatedPosition; rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; mvPosition.xy += rotatedPosition; gl_Position = projectionMatrix * mvPosition; #include #include #include }`,sprite_frag:`uniform vec3 diffuse; uniform float opacity; #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include vec3 outgoingLight = vec3( 0.0 ); #include #include #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include }`},ce={common:{diffuse:{value:new oe(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Le},alphaMap:{value:null},alphaMapTransform:{value:new Le},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Le}},envmap:{envMap:{value:null},envMapRotation:{value:new Le},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Le}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Le}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Le},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Le},normalScale:{value:new Z(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Le},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Le}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Le}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Le}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new oe(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new oe(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Le},alphaTest:{value:0},uvTransform:{value:new Le}},sprite:{diffuse:{value:new oe(16777215)},opacity:{value:1},center:{value:new Z(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Le},alphaMap:{value:null},alphaMapTransform:{value:new Le},alphaTest:{value:0}}},Yn={basic:{uniforms:$t([ce.common,ce.specularmap,ce.envmap,ce.aomap,ce.lightmap,ce.fog]),vertexShader:De.meshbasic_vert,fragmentShader:De.meshbasic_frag},lambert:{uniforms:$t([ce.common,ce.specularmap,ce.envmap,ce.aomap,ce.lightmap,ce.emissivemap,ce.bumpmap,ce.normalmap,ce.displacementmap,ce.fog,ce.lights,{emissive:{value:new oe(0)}}]),vertexShader:De.meshlambert_vert,fragmentShader:De.meshlambert_frag},phong:{uniforms:$t([ce.common,ce.specularmap,ce.envmap,ce.aomap,ce.lightmap,ce.emissivemap,ce.bumpmap,ce.normalmap,ce.displacementmap,ce.fog,ce.lights,{emissive:{value:new oe(0)},specular:{value:new oe(1118481)},shininess:{value:30}}]),vertexShader:De.meshphong_vert,fragmentShader:De.meshphong_frag},standard:{uniforms:$t([ce.common,ce.envmap,ce.aomap,ce.lightmap,ce.emissivemap,ce.bumpmap,ce.normalmap,ce.displacementmap,ce.roughnessmap,ce.metalnessmap,ce.fog,ce.lights,{emissive:{value:new oe(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:De.meshphysical_vert,fragmentShader:De.meshphysical_frag},toon:{uniforms:$t([ce.common,ce.aomap,ce.lightmap,ce.emissivemap,ce.bumpmap,ce.normalmap,ce.displacementmap,ce.gradientmap,ce.fog,ce.lights,{emissive:{value:new oe(0)}}]),vertexShader:De.meshtoon_vert,fragmentShader:De.meshtoon_frag},matcap:{uniforms:$t([ce.common,ce.bumpmap,ce.normalmap,ce.displacementmap,ce.fog,{matcap:{value:null}}]),vertexShader:De.meshmatcap_vert,fragmentShader:De.meshmatcap_frag},points:{uniforms:$t([ce.points,ce.fog]),vertexShader:De.points_vert,fragmentShader:De.points_frag},dashed:{uniforms:$t([ce.common,ce.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:De.linedashed_vert,fragmentShader:De.linedashed_frag},depth:{uniforms:$t([ce.common,ce.displacementmap]),vertexShader:De.depth_vert,fragmentShader:De.depth_frag},normal:{uniforms:$t([ce.common,ce.bumpmap,ce.normalmap,ce.displacementmap,{opacity:{value:1}}]),vertexShader:De.meshnormal_vert,fragmentShader:De.meshnormal_frag},sprite:{uniforms:$t([ce.sprite,ce.fog]),vertexShader:De.sprite_vert,fragmentShader:De.sprite_frag},background:{uniforms:{uvTransform:{value:new Le},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:De.background_vert,fragmentShader:De.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Le}},vertexShader:De.backgroundCube_vert,fragmentShader:De.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:De.cube_vert,fragmentShader:De.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:De.equirect_vert,fragmentShader:De.equirect_frag},distanceRGBA:{uniforms:$t([ce.common,ce.displacementmap,{referencePosition:{value:new S},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:De.distanceRGBA_vert,fragmentShader:De.distanceRGBA_frag},shadow:{uniforms:$t([ce.lights,ce.fog,{color:{value:new oe(0)},opacity:{value:1}}]),vertexShader:De.shadow_vert,fragmentShader:De.shadow_frag}};Yn.physical={uniforms:$t([Yn.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Le},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Le},clearcoatNormalScale:{value:new Z(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Le},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Le},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Le},sheen:{value:0},sheenColor:{value:new oe(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Le},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Le},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Le},transmissionSamplerSize:{value:new Z},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Le},attenuationDistance:{value:0},attenuationColor:{value:new oe(0)},specularColor:{value:new oe(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Le},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Le},anisotropyVector:{value:new Z},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Le}}]),vertexShader:De.meshphysical_vert,fragmentShader:De.meshphysical_frag};var Ro={r:0,b:0,g:0},dr=new Kn,Ub=new Ee;function Nb(r,e,t,n,i,s,a){let o=new oe(0),l,c,h=s===!0?0:1,u=null,d=0,p=null;function m(f){let g=f.isScene===!0?f.background:null;return g&&g.isTexture&&(g=(f.backgroundBlurriness>0?t:e).get(g)),g}function x(f,g){f.getRGB(Ro,jm(r)),n.buffers.color.setClear(Ro.r,Ro.g,Ro.b,g,a)}return{getClearColor:function(){return o},setClearColor:function(f,g=1){o.set(f),h=g,x(o,h)},getClearAlpha:function(){return h},setClearAlpha:function(f){h=f,x(o,h)},render:function(f){let g=!1,v=m(f);v===null?x(o,h):v&&v.isColor&&(x(v,1),g=!0);let b=r.xr.getEnvironmentBlendMode();b==="additive"?n.buffers.color.setClear(0,0,0,1,a):b==="alpha-blend"&&n.buffers.color.setClear(0,0,0,0,a),(r.autoClear||g)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),r.clear(r.autoClearColor,r.autoClearDepth,r.autoClearStencil))},addToRenderList:function(f,g){let v=m(g);v&&(v.isCubeTexture||v.mapping===kl)?(c===void 0&&(c=new Je(new Wi(1,1,1),new ft({name:"BackgroundCubeMaterial",uniforms:gs(Yn.backgroundCube.uniforms),vertexShader:Yn.backgroundCube.vertexShader,fragmentShader:Yn.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(b,y,M){this.matrixWorld.copyPosition(M.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(c)),dr.copy(g.backgroundRotation),dr.x*=-1,dr.y*=-1,dr.z*=-1,v.isCubeTexture&&v.isRenderTargetTexture===!1&&(dr.y*=-1,dr.z*=-1),c.material.uniforms.envMap.value=v,c.material.uniforms.flipEnvMap.value=v.isCubeTexture&&v.isRenderTargetTexture===!1?-1:1,c.material.uniforms.backgroundBlurriness.value=g.backgroundBlurriness,c.material.uniforms.backgroundIntensity.value=g.backgroundIntensity,c.material.uniforms.backgroundRotation.value.setFromMatrix4(Ub.makeRotationFromEuler(dr)),c.material.toneMapped=Oe.getTransfer(v.colorSpace)!==tt,u===v&&d===v.version&&p===r.toneMapping||(c.material.needsUpdate=!0,u=v,d=v.version,p=r.toneMapping),c.layers.enableAll(),f.unshift(c,c.geometry,c.material,0,0,null)):v&&v.isTexture&&(l===void 0&&(l=new Je(new xi(2,2),new ft({name:"BackgroundMaterial",uniforms:gs(Yn.background.uniforms),vertexShader:Yn.background.vertexShader,fragmentShader:Yn.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(l)),l.material.uniforms.t2D.value=v,l.material.uniforms.backgroundIntensity.value=g.backgroundIntensity,l.material.toneMapped=Oe.getTransfer(v.colorSpace)!==tt,v.matrixAutoUpdate===!0&&v.updateMatrix(),l.material.uniforms.uvTransform.value.copy(v.matrix),u===v&&d===v.version&&p===r.toneMapping||(l.material.needsUpdate=!0,u=v,d=v.version,p=r.toneMapping),l.layers.enableAll(),f.unshift(l,l.geometry,l.material,0,0,null))}}}function Ob(r,e){let t=r.getParameter(r.MAX_VERTEX_ATTRIBS),n={},i=c(null),s=i,a=!1;function o(g){return r.bindVertexArray(g)}function l(g){return r.deleteVertexArray(g)}function c(g){let v=[],b=[],y=[];for(let M=0;M=0){let re=F[K],ie=W[K];if(ie===void 0&&(K==="instanceMatrix"&&C.instanceMatrix&&(ie=C.instanceMatrix),K==="instanceColor"&&C.instanceColor&&(ie=C.instanceColor)),re===void 0||re.attribute!==ie||ie&&re.data!==ie.data)return!0;j++}return s.attributesNum!==j||s.index!==z}(g,y,b,M),_&&function(C,I,O,z){let F={},W=I.attributes,j=0,Y=O.getAttributes();for(let K in Y)if(Y[K].location>=0){let re=W[K];re===void 0&&(K==="instanceMatrix"&&C.instanceMatrix&&(re=C.instanceMatrix),K==="instanceColor"&&C.instanceColor&&(re=C.instanceColor));let ie={};ie.attribute=re,re&&re.data&&(ie.data=re.data),F[K]=ie,j++}s.attributes=F,s.attributesNum=j,s.index=z}(g,y,b,M),M!==null&&e.update(M,r.ELEMENT_ARRAY_BUFFER),(_||a)&&(a=!1,function(C,I,O,z){h();let F=z.attributes,W=O.getAttributes(),j=I.defaultAttributeValues;for(let Y in W){let K=W[Y];if(K.location>=0){let re=F[Y];if(re===void 0&&(Y==="instanceMatrix"&&C.instanceMatrix&&(re=C.instanceMatrix),Y==="instanceColor"&&C.instanceColor&&(re=C.instanceColor)),re!==void 0){let ie=re.normalized,ge=re.itemSize,ye=e.get(re);if(ye===void 0)continue;let ne=ye.buffer,ae=ye.type,me=ye.bytesPerElement,be=ae===r.INT||ae===r.UNSIGNED_INT||re.gpuType===id;if(re.isInterleavedBufferAttribute){let ue=re.data,A=ue.stride,E=re.offset;if(ue.isInstancedInterleavedBuffer){for(let N=0;N0&&r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.HIGH_FLOAT).precision>0)return"highp";d="mediump"}return d==="mediump"&&r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.MEDIUM_FLOAT).precision>0&&r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let a=t.precision!==void 0?t.precision:"highp",o=s(a);o!==a&&(console.warn("THREE.WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);let l=t.logarithmicDepthBuffer===!0,c=t.reverseDepthBuffer===!0&&e.has("EXT_clip_control"),h=r.getParameter(r.MAX_TEXTURE_IMAGE_UNITS),u=r.getParameter(r.MAX_VERTEX_TEXTURE_IMAGE_UNITS);return{isWebGL2:!0,getMaxAnisotropy:function(){if(i!==void 0)return i;if(e.has("EXT_texture_filter_anisotropic")===!0){let d=e.get("EXT_texture_filter_anisotropic");i=r.getParameter(d.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i},getMaxPrecision:s,textureFormatReadable:function(d){return d===zn||n.convert(d)===r.getParameter(r.IMPLEMENTATION_COLOR_READ_FORMAT)},textureTypeReadable:function(d){let p=d===Jt&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(d!==Vi&&n.convert(d)!==r.getParameter(r.IMPLEMENTATION_COLOR_READ_TYPE)&&d!==On&&!p)},precision:a,logarithmicDepthBuffer:l,reverseDepthBuffer:c,maxTextures:h,maxVertexTextures:u,maxTextureSize:r.getParameter(r.MAX_TEXTURE_SIZE),maxCubemapSize:r.getParameter(r.MAX_CUBE_MAP_TEXTURE_SIZE),maxAttributes:r.getParameter(r.MAX_VERTEX_ATTRIBS),maxVertexUniforms:r.getParameter(r.MAX_VERTEX_UNIFORM_VECTORS),maxVaryings:r.getParameter(r.MAX_VARYING_VECTORS),maxFragmentUniforms:r.getParameter(r.MAX_FRAGMENT_UNIFORM_VECTORS),vertexTextures:u>0,maxSamples:r.getParameter(r.MAX_SAMPLES)}}function Bb(r){let e=this,t=null,n=0,i=!1,s=!1,a=new mi,o=new Le,l={value:null,needsUpdate:!1};function c(h,u,d,p){let m=h!==null?h.length:0,x=null;if(m!==0){if(x=l.value,p!==!0||x===null){let f=d+4*m,g=u.matrixWorldInverse;o.getNormalMatrix(g),(x===null||x.length0),e.numPlanes=n,e.numIntersection=0}();else{let g=s?0:n,v=4*g,b=f.clippingState||null;l.value=b,b=c(p,u,v,d);for(let y=0;y!==v;++y)b[y]=t[y];f.clippingState=b,this.numIntersection=m?this.numPlanes:0,this.numPlanes+=g}}}function Hb(r){let e=new WeakMap;function t(i,s){return s===ua?i.mapping=os:s===Dh&&(i.mapping=ls),i}function n(i){let s=i.target;s.removeEventListener("dispose",n);let a=e.get(s);a!==void 0&&(e.delete(s),a.dispose())}return{get:function(i){if(i&&i.isTexture){let s=i.mapping;if(s===ua||s===Dh){if(e.has(i))return t(e.get(i).texture,i.mapping);{let a=i.image;if(a&&a.height>0){let o=new pu(a.height);return o.fromEquirectangularTexture(r,i),e.set(i,o),i.addEventListener("dispose",n),t(o.texture,i.mapping)}return null}}}return i},dispose:function(){e=new WeakMap}}}var ji=class extends ga{constructor(e=-1,t=1,n=1,i=-1,s=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=i,this.near=s,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,i,s,a){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=i,this.view.width=s,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,i=(this.top+this.bottom)/2,s=n-e,a=n+e,o=i+t,l=i-t;if(this.view!==null&&this.view.enabled){let c=(this.right-this.left)/this.view.fullWidth/this.zoom,h=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=c*this.view.offsetX,a=s+c*this.view.width,o-=h*this.view.offsetY,l=o-h*this.view.height}this.projectionMatrix.makeOrthographic(s,a,o,l,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}},Rf=[.125,.215,.35,.446,.526,.582],Qs=20,mh=new ji,Cf=new oe,gh=null,bh=0,vh=0,xh=!1,fr=(1+Math.sqrt(5))/2,Zr=1/fr,Pf=[new S(-fr,Zr,0),new S(fr,Zr,0),new S(-Zr,0,fr),new S(Zr,0,fr),new S(0,fr,-Zr),new S(0,fr,Zr),new S(-1,1,-1),new S(1,1,-1),new S(-1,1,1),new S(1,1,1)],vs=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,n=.1,i=100){gh=this._renderer.getRenderTarget(),bh=this._renderer.getActiveCubeFace(),vh=this._renderer.getActiveMipmapLevel(),xh=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(256);let s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,n,i,s),t>0&&this._blur(s,0,0,t),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=kf(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Lf(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;ea-4?m=Rf[d-a+4-1]:d===0&&(m=0),c.push(m);let x=1/(p-2),f=-x,g=1+x,v=[f,f,g,f,g,g,f,f,g,g,f,g],b=6,y=6,M=3,_=2,R=1,C=new Float32Array(M*y*b),I=new Float32Array(_*y*b),O=new Float32Array(R*y*b);for(let F=0;F2?0:-1,Y=[W,j,0,W+2/3,j,0,W+2/3,j+1,0,W,j,0,W+2/3,j+1,0,W,j+1,0];C.set(Y,M*y*F),I.set(v,_*y*F);let K=[F,F,F,F,F,F];O.set(K,R*y*F)}let z=new qe;z.setAttribute("position",new Qe(C,M)),z.setAttribute("uv",new Qe(I,_)),z.setAttribute("faceIndex",new Qe(O,R)),o.push(z),h>4&&h--}return{lodPlanes:o,sizeLods:l,sigmas:c}}(s)),this._blurMaterial=function(a,o,l){let c=new Float32Array(Qs),h=new S(0,1,0);return new ft({name:"SphericalGaussianBlur",defines:{n:Qs,CUBEUV_TEXEL_WIDTH:1/o,CUBEUV_TEXEL_HEIGHT:1/l,CUBEUV_MAX_MIP:`${a}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:c},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:h}},vertexShader:hd(),fragmentShader:` precision mediump float; precision mediump int; varying vec3 vOutputDirection; uniform sampler2D envMap; uniform int samples; uniform float weights[ n ]; uniform bool latitudinal; uniform float dTheta; uniform float mipInt; uniform vec3 poleAxis; #define ENVMAP_TYPE_CUBE_UV #include vec3 getSample( float theta, vec3 axis ) { float cosTheta = cos( theta ); // Rodrigues' axis-angle rotation vec3 sampleDirection = vOutputDirection * cosTheta + cross( axis, vOutputDirection ) * sin( theta ) + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); return bilinearCubeUV( envMap, sampleDirection, mipInt ); } void main() { vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); if ( all( equal( axis, vec3( 0.0 ) ) ) ) { axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); } axis = normalize( axis ); gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); for ( int i = 1; i < n; i++ ) { if ( i >= samples ) { break; } float theta = dTheta * float( i ); gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); } } `,blending:0,depthTest:!1,depthWrite:!1})}(s,e,t)}return i}_compileMaterial(e){let t=new Je(this._lodPlanes[0],e);this._renderer.compile(t,mh)}_sceneToCubeUV(e,t,n,i){let s=new At(90,1,t,n),a=[1,-1,1,1,1,1],o=[1,1,1,-1,-1,-1],l=this._renderer,c=l.autoClear,h=l.toneMapping;l.getClearColor(Cf),l.toneMapping=0,l.autoClear=!1;let u=new Nt({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1}),d=new Je(new Wi,u),p=!1,m=e.background;m?m.isColor&&(u.color.copy(m),e.background=null,p=!0):(u.color.copy(Cf),p=!0);for(let x=0;x<6;x++){let f=x%3;f===0?(s.up.set(0,a[x],0),s.lookAt(o[x],0,0)):f===1?(s.up.set(0,0,a[x]),s.lookAt(0,o[x],0)):(s.up.set(0,a[x],0),s.lookAt(0,0,o[x]));let g=this._cubeSize;Co(i,f*g,x>2?g:0,g,g),l.setRenderTarget(i),p&&l.render(d,s),l.render(e,s)}d.geometry.dispose(),d.material.dispose(),l.toneMapping=h,l.autoClear=c,e.background=m}_textureToCubeUV(e,t){let n=this._renderer,i=e.mapping===os||e.mapping===ls;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=kf()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Lf());let s=i?this._cubemapMaterial:this._equirectMaterial,a=new Je(this._lodPlanes[0],s);s.uniforms.envMap.value=e;let o=this._cubeSize;Co(t,0,0,3*o,2*o),n.setRenderTarget(t),n.render(a,mh)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;let i=this._lodPlanes.length;for(let s=1;sQs&&console.warn(`sigmaRadians, ${s}, is too large and will clip, as it requested ${x} samples when the maximum is set to 20`);let f=[],g=0;for(let y=0;yv-4?i-v+4:0),4*(this._cubeSize-b),3*b,2*b),l.setRenderTarget(t),l.render(h,mh)}};function If(r,e,t){let n=new Rt(r,e,t);return n.texture.mapping=kl,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function Co(r,e,t,n,i){r.viewport.set(e,t,n,i),r.scissor.set(e,t,n,i)}function Lf(){return new ft({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:hd(),fragmentShader:` precision mediump float; precision mediump int; varying vec3 vOutputDirection; uniform sampler2D envMap; #include void main() { vec3 outputDirection = normalize( vOutputDirection ); vec2 uv = equirectUv( outputDirection ); gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); } `,blending:0,depthTest:!1,depthWrite:!1})}function kf(){return new ft({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:hd(),fragmentShader:` precision mediump float; precision mediump int; uniform float flipEnvMap; varying vec3 vOutputDirection; uniform samplerCube envMap; void main() { gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); } `,blending:0,depthTest:!1,depthWrite:!1})}function hd(){return` precision mediump float; precision mediump int; attribute float faceIndex; varying vec3 vOutputDirection; // RH coordinate system; PMREM face-indexing convention vec3 getDirection( vec2 uv, float face ) { uv = 2.0 * uv - 1.0; vec3 direction = vec3( uv, 1.0 ); if ( face == 0.0 ) { direction = direction.zyx; // ( 1, v, u ) pos x } else if ( face == 1.0 ) { direction = direction.xzy; direction.xz *= -1.0; // ( -u, 1, -v ) pos y } else if ( face == 2.0 ) { direction.x *= -1.0; // ( -u, v, 1 ) pos z } else if ( face == 3.0 ) { direction = direction.zyx; direction.xz *= -1.0; // ( -1, v, -u ) neg x } else if ( face == 4.0 ) { direction = direction.xzy; direction.xy *= -1.0; // ( -u, -1, v ) neg y } else if ( face == 5.0 ) { direction.z *= -1.0; // ( u, v, -1 ) neg z } return direction; } void main() { vOutputDirection = getDirection( uv, faceIndex ); gl_Position = vec4( position, 1.0 ); } `}function Gb(r){let e=new WeakMap,t=null;function n(i){let s=i.target;s.removeEventListener("dispose",n);let a=e.get(s);a!==void 0&&(e.delete(s),a.dispose())}return{get:function(i){if(i&&i.isTexture){let s=i.mapping,a=s===ua||s===Dh,o=s===os||s===ls;if(a||o){let l=e.get(i),c=l!==void 0?l.texture.pmremVersion:0;if(i.isRenderTargetTexture&&i.pmremVersion!==c)return t===null&&(t=new vs(r)),l=a?t.fromEquirectangular(i,l):t.fromCubemap(i,l),l.texture.pmremVersion=i.pmremVersion,e.set(i,l),l.texture;if(l!==void 0)return l.texture;{let h=i.image;return a&&h&&h.height>0||o&&h&&function(u){let d=0,p=6;for(let m=0;me.maxTextureSize&&(y=Math.ceil(b/e.maxTextureSize),b=e.maxTextureSize);let M=new Float32Array(b*y*4*h),_=new Jo(M,b,y,h);_.type=On,_.needsUpdate=!0;let R=4*v;for(let I=0;I0)return r;let i=e*t,s=Uf[i];if(s===void 0&&(s=new Float32Array(i),Uf[i]=s),e!==0){n.toArray(s,0);for(let a=1,o=0;a!==e;++a)o+=t,r[a].toArray(s,o)}return s}function Ct(r,e){if(r.length!==e.length)return!1;for(let t=0,n=r.length;t":" "} ${m}: ${c[p]}`)}return h.join(` `)}(r.getShaderSource(e),a)}return i}function Uv(r,e){let t=function(n){Oe._getMatrix(Gf,Oe.workingColorSpace,n);let i=`mat3( ${Gf.elements.map(s=>s.toFixed(4))} )`;switch(Oe.getTransfer(n)){case Ul:return[i,"LinearTransferOETF"];case tt:return[i,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",n),[i,"LinearTransferOETF"]}}(e);return[`vec4 ${r}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(` `)}function Nv(r,e){let t;switch(e){case 1:t="Linear";break;case 2:t="Reinhard";break;case 3:t="Cineon";break;case 4:t="ACESFilmic";break;case 6:t="AgX";break;case 7:t="Neutral";break;case 5:t="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),t="Linear"}return"vec3 "+r+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}var Po=new S;function Ov(){return Oe.getLuminanceCoefficients(Po),["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${Po.x.toFixed(4)}, ${Po.y.toFixed(4)}, ${Po.z.toFixed(4)} );`," return dot( weights, rgb );","}"].join(` `)}function ea(r){return r!==""}function Wf(r,e){let t=e.numSpotLightShadows+e.numSpotLightMaps-e.numSpotLightShadowsWithMaps;return r.replace(/NUM_DIR_LIGHTS/g,e.numDirLights).replace(/NUM_SPOT_LIGHTS/g,e.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,e.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,t).replace(/NUM_RECT_AREA_LIGHTS/g,e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,e.numPointLights).replace(/NUM_HEMI_LIGHTS/g,e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,e.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,e.numPointLightShadows)}function jf(r,e){return r.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}var zv=/^[ \t]*#include +<([\w\d./]+)>/gm;function bu(r){return r.replace(zv,Bv)}var Fv=new Map;function Bv(r,e){let t=De[e];if(t===void 0){let n=Fv.get(e);if(n===void 0)throw new Error("Can not resolve #include <"+e+">");t=De[n],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,n)}return bu(t)}var Hv=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function qf(r){return r.replace(Hv,Gv)}function Gv(r,e,t,n){let i="";for(let s=parseInt(e);s0&&(f+=` `),g=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m].filter(ea).join(` `),g.length>0&&(g+=` `)):(f=[Xf(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+h:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",t.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` `].filter(ea).join(` `),g=[Xf(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+c:"",t.envMap?"#define "+h:"",t.envMap?"#define "+u:"",d?"#define CUBEUV_TEXEL_WIDTH "+d.texelWidth:"",d?"#define CUBEUV_TEXEL_HEIGHT "+d.texelHeight:"",d?"#define CUBEUV_MAX_MIP "+d.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor||t.batchingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",t.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==0?"#define TONE_MAPPING":"",t.toneMapping!==0?De.tonemapping_pars_fragment:"",t.toneMapping!==0?Nv("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",De.colorspace_pars_fragment,Uv("linearToOutputTexel",t.outputColorSpace),Ov(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` `].filter(ea).join(` `)),a=bu(a),a=Wf(a,t),a=jf(a,t),o=bu(o),o=Wf(o,t),o=jf(o,t),a=qf(a),o=qf(o),t.isRawShaderMaterial!==!0&&(v=`#version 300 es `,f=[p,"#define attribute in","#define varying out","#define texture2D texture"].join(` `)+` `+f,g=["#define varying in",t.glslVersion===af?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===af?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` `)+` `+g);let b=v+f+a,y=v+g+o,M=Hf(i,i.VERTEX_SHADER,b),_=Hf(i,i.FRAGMENT_SHADER,y);function R(z){if(r.debug.checkShaderErrors){let F=i.getProgramInfoLog(x).trim(),W=i.getShaderInfoLog(M).trim(),j=i.getShaderInfoLog(_).trim(),Y=!0,K=!0;if(i.getProgramParameter(x,i.LINK_STATUS)===!1)if(Y=!1,typeof r.debug.onShaderError=="function")r.debug.onShaderError(i,x,M,_);else{let re=Vf(i,M,"vertex"),ie=Vf(i,_,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(x,i.VALIDATE_STATUS)+` Material Name: `+z.name+` Material Type: `+z.type+` Program Info Log: `+F+` `+re+` `+ie)}else F!==""?console.warn("THREE.WebGLProgram: Program Info Log:",F):W!==""&&j!==""||(K=!1);K&&(z.diagnostics={runnable:Y,programLog:F,vertexShader:{log:W,prefix:f},fragmentShader:{log:j,prefix:g}})}i.deleteShader(M),i.deleteShader(_),C=new as(i,x),I=function(F,W){let j={},Y=F.getProgramParameter(W,F.ACTIVE_ATTRIBUTES);for(let K=0;K0,H=f.clearcoat>0,ee=f.dispersion>0,B=f.iridescence>0,J=f.sheen>0,$=f.transmission>0,te=k&&!!f.anisotropyMap,pe=H&&!!f.clearcoatMap,de=H&&!!f.clearcoatNormalMap,Me=H&&!!f.clearcoatRoughnessMap,Ce=B&&!!f.iridescenceMap,Xe=B&&!!f.iridescenceThicknessMap,ze=J&&!!f.sheenColorMap,Se=J&&!!f.sheenRoughnessMap,Ke=!!f.specularMap,ht=!!f.specularColorMap,bt=!!f.specularIntensityMap,ve=$&&!!f.transmissionMap,Ge=$&&!!f.thicknessMap,lt=!!f.gradientMap,Ur=!!f.alphaMap,Ya=f.alphaTest>0,Cn=!!f.alphaHash,Vn=!!f.extensions,rr=0;f.toneMapped&&(ie!==null&&ie.isXRRenderTarget!==!0||(rr=r.toneMapping));let G={shaderID:O,shaderType:f.type,shaderName:f.name,vertexShader:W,fragmentShader:j,defines:f.defines,customVertexShaderID:Y,customFragmentShaderID:K,isRawShaderMaterial:f.isRawShaderMaterial===!0,glslVersion:f.glslVersion,precision:p,batching:ne,batchingColor:ne&&y._colorsTexture!==null,instancing:ye,instancingColor:ye&&y.instanceColor!==null,instancingMorph:ye&&y.morphTexture!==null,supportsVertexTextures:d,outputColorSpace:ie===null?r.outputColorSpace:ie.isXRRenderTarget===!0?ie.texture.colorSpace:qt,alphaToCoverage:!!f.alphaToCoverage,map:ae,matcap:me,envMap:be,envMapMode:be&&C.mapping,envMapCubeUVHeight:I,aoMap:ue,lightMap:A,bumpMap:E,normalMap:N,displacementMap:d&&U,emissiveMap:P,normalMapObjectSpace:N&&f.normalMapType===1,normalMapTangentSpace:N&&f.normalMapType===0,metalnessMap:D,roughnessMap:w,anisotropy:k,anisotropyMap:te,clearcoat:H,clearcoatMap:pe,clearcoatNormalMap:de,clearcoatRoughnessMap:Me,dispersion:ee,iridescence:B,iridescenceMap:Ce,iridescenceThicknessMap:Xe,sheen:J,sheenColorMap:ze,sheenRoughnessMap:Se,specularMap:Ke,specularColorMap:ht,specularIntensityMap:bt,transmission:$,transmissionMap:ve,thicknessMap:Ge,gradientMap:lt,opaque:f.transparent===!1&&f.blending===1&&f.alphaToCoverage===!1,alphaMap:Ur,alphaTest:Ya,alphaHash:Cn,combine:f.combine,mapUv:ae&&x(f.map.channel),aoMapUv:ue&&x(f.aoMap.channel),lightMapUv:A&&x(f.lightMap.channel),bumpMapUv:E&&x(f.bumpMap.channel),normalMapUv:N&&x(f.normalMap.channel),displacementMapUv:U&&x(f.displacementMap.channel),emissiveMapUv:P&&x(f.emissiveMap.channel),metalnessMapUv:D&&x(f.metalnessMap.channel),roughnessMapUv:w&&x(f.roughnessMap.channel),anisotropyMapUv:te&&x(f.anisotropyMap.channel),clearcoatMapUv:pe&&x(f.clearcoatMap.channel),clearcoatNormalMapUv:de&&x(f.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Me&&x(f.clearcoatRoughnessMap.channel),iridescenceMapUv:Ce&&x(f.iridescenceMap.channel),iridescenceThicknessMapUv:Xe&&x(f.iridescenceThicknessMap.channel),sheenColorMapUv:ze&&x(f.sheenColorMap.channel),sheenRoughnessMapUv:Se&&x(f.sheenRoughnessMap.channel),specularMapUv:Ke&&x(f.specularMap.channel),specularColorMapUv:ht&&x(f.specularColorMap.channel),specularIntensityMapUv:bt&&x(f.specularIntensityMap.channel),transmissionMapUv:ve&&x(f.transmissionMap.channel),thicknessMapUv:Ge&&x(f.thicknessMap.channel),alphaMapUv:Ur&&x(f.alphaMap.channel),vertexTangents:!!_.attributes.tangent&&(N||k),vertexColors:f.vertexColors,vertexAlphas:f.vertexColors===!0&&!!_.attributes.color&&_.attributes.color.itemSize===4,pointsUvs:y.isPoints===!0&&!!_.attributes.uv&&(ae||Ur),fog:!!M,useFog:f.fog===!0,fogExp2:!!M&&M.isFogExp2,flatShading:f.flatShading===!0,sizeAttenuation:f.sizeAttenuation===!0,logarithmicDepthBuffer:u,reverseDepthBuffer:ge,skinning:y.isSkinnedMesh===!0,morphTargets:_.morphAttributes.position!==void 0,morphNormals:_.morphAttributes.normal!==void 0,morphColors:_.morphAttributes.color!==void 0,morphTargetsCount:F,morphTextureStride:re,numDirLights:g.directional.length,numPointLights:g.point.length,numSpotLights:g.spot.length,numSpotLightMaps:g.spotLightMap.length,numRectAreaLights:g.rectArea.length,numHemiLights:g.hemi.length,numDirLightShadows:g.directionalShadowMap.length,numPointLightShadows:g.pointShadowMap.length,numSpotLightShadows:g.spotShadowMap.length,numSpotLightShadowsWithMaps:g.numSpotLightShadowsWithMaps,numLightProbes:g.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:f.dithering,shadowMapEnabled:r.shadowMap.enabled&&v.length>0,shadowMapType:r.shadowMap.type,toneMapping:rr,decodeVideoTexture:ae&&f.map.isVideoTexture===!0&&Oe.getTransfer(f.map.colorSpace)===tt,decodeVideoTextureEmissive:P&&f.emissiveMap.isVideoTexture===!0&&Oe.getTransfer(f.emissiveMap.colorSpace)===tt,premultipliedAlpha:f.premultipliedAlpha,doubleSided:f.side===2,flipSided:f.side===1,useDepthPacking:f.depthPacking>=0,depthPacking:f.depthPacking||0,index0AttributeName:f.index0AttributeName,extensionClipCullDistance:Vn&&f.extensions.clipCullDistance===!0&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(Vn&&f.extensions.multiDraw===!0||ne)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:f.customProgramCacheKey()};return G.vertexUv1s=c.has(1),G.vertexUv2s=c.has(2),G.vertexUv3s=c.has(3),c.clear(),G},getProgramCacheKey:function(f){let g=[];if(f.shaderID?g.push(f.shaderID):(g.push(f.customVertexShaderID),g.push(f.customFragmentShaderID)),f.defines!==void 0)for(let v in f.defines)g.push(v),g.push(f.defines[v]);return f.isRawShaderMaterial===!1&&(function(v,b){v.push(b.precision),v.push(b.outputColorSpace),v.push(b.envMapMode),v.push(b.envMapCubeUVHeight),v.push(b.mapUv),v.push(b.alphaMapUv),v.push(b.lightMapUv),v.push(b.aoMapUv),v.push(b.bumpMapUv),v.push(b.normalMapUv),v.push(b.displacementMapUv),v.push(b.emissiveMapUv),v.push(b.metalnessMapUv),v.push(b.roughnessMapUv),v.push(b.anisotropyMapUv),v.push(b.clearcoatMapUv),v.push(b.clearcoatNormalMapUv),v.push(b.clearcoatRoughnessMapUv),v.push(b.iridescenceMapUv),v.push(b.iridescenceThicknessMapUv),v.push(b.sheenColorMapUv),v.push(b.sheenRoughnessMapUv),v.push(b.specularMapUv),v.push(b.specularColorMapUv),v.push(b.specularIntensityMapUv),v.push(b.transmissionMapUv),v.push(b.thicknessMapUv),v.push(b.combine),v.push(b.fogExp2),v.push(b.sizeAttenuation),v.push(b.morphTargetsCount),v.push(b.morphAttributeCount),v.push(b.numDirLights),v.push(b.numPointLights),v.push(b.numSpotLights),v.push(b.numSpotLightMaps),v.push(b.numHemiLights),v.push(b.numRectAreaLights),v.push(b.numDirLightShadows),v.push(b.numPointLightShadows),v.push(b.numSpotLightShadows),v.push(b.numSpotLightShadowsWithMaps),v.push(b.numLightProbes),v.push(b.shadowMapType),v.push(b.toneMapping),v.push(b.numClippingPlanes),v.push(b.numClipIntersection),v.push(b.depthPacking)}(g,f),function(v,b){o.disableAll(),b.supportsVertexTextures&&o.enable(0),b.instancing&&o.enable(1),b.instancingColor&&o.enable(2),b.instancingMorph&&o.enable(3),b.matcap&&o.enable(4),b.envMap&&o.enable(5),b.normalMapObjectSpace&&o.enable(6),b.normalMapTangentSpace&&o.enable(7),b.clearcoat&&o.enable(8),b.iridescence&&o.enable(9),b.alphaTest&&o.enable(10),b.vertexColors&&o.enable(11),b.vertexAlphas&&o.enable(12),b.vertexUv1s&&o.enable(13),b.vertexUv2s&&o.enable(14),b.vertexUv3s&&o.enable(15),b.vertexTangents&&o.enable(16),b.anisotropy&&o.enable(17),b.alphaHash&&o.enable(18),b.batching&&o.enable(19),b.dispersion&&o.enable(20),b.batchingColor&&o.enable(21),v.push(o.mask),o.disableAll(),b.fog&&o.enable(0),b.useFog&&o.enable(1),b.flatShading&&o.enable(2),b.logarithmicDepthBuffer&&o.enable(3),b.reverseDepthBuffer&&o.enable(4),b.skinning&&o.enable(5),b.morphTargets&&o.enable(6),b.morphNormals&&o.enable(7),b.morphColors&&o.enable(8),b.premultipliedAlpha&&o.enable(9),b.shadowMapEnabled&&o.enable(10),b.doubleSided&&o.enable(11),b.flipSided&&o.enable(12),b.useDepthPacking&&o.enable(13),b.dithering&&o.enable(14),b.transmission&&o.enable(15),b.sheen&&o.enable(16),b.opaque&&o.enable(17),b.pointsUvs&&o.enable(18),b.decodeVideoTexture&&o.enable(19),b.decodeVideoTextureEmissive&&o.enable(20),b.alphaToCoverage&&o.enable(21),v.push(o.mask)}(g,f),g.push(r.outputColorSpace)),g.push(f.customProgramCacheKey),g.join()},getUniforms:function(f){let g=m[f.type],v;if(g){let b=Yn[g];v=ei.clone(b.uniforms)}else v=f.uniforms;return v},acquireProgram:function(f,g){let v;for(let b=0,y=h.length;b0?n.push(d):l.transparent===!0?i.push(d):t.push(d)},unshift:function(a,o,l,c,h,u){let d=s(a,o,l,c,h,u);l.transmission>0?n.unshift(d):l.transparent===!0?i.unshift(d):t.unshift(d)},finish:function(){for(let a=e,o=r.length;a1&&t.sort(a||Xv),n.length>1&&n.sort(o||Yf),i.length>1&&i.sort(o||Yf)}}}function Yv(){let r=new WeakMap;return{get:function(e,t){let n=r.get(e),i;return n===void 0?(i=new Kf,r.set(e,[i])):t>=n.length?(i=new Kf,n.push(i)):i=n[t],i},dispose:function(){r=new WeakMap}}}function Kv(){let r={};return{get:function(e){if(r[e.id]!==void 0)return r[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new S,color:new oe};break;case"SpotLight":t={position:new S,direction:new S,color:new oe,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new S,color:new oe,distance:0,decay:0};break;case"HemisphereLight":t={direction:new S,skyColor:new oe,groundColor:new oe};break;case"RectAreaLight":t={color:new oe,position:new S,halfWidth:new S,halfHeight:new S}}return r[e.id]=t,t}}}var $v=0;function Zv(r,e){return(e.castShadow?2:0)-(r.castShadow?2:0)+(e.map?1:0)-(r.map?1:0)}function Jv(r){let e=new Kv,t=function(){let o={};return{get:function(l){if(o[l.id]!==void 0)return o[l.id];let c;switch(l.type){case"DirectionalLight":case"SpotLight":c={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Z};break;case"PointLight":c={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Z,shadowCameraNear:1,shadowCameraFar:1e3}}return o[l.id]=c,c}}}(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let o=0;o<9;o++)n.probe.push(new S);let i=new S,s=new Ee,a=new Ee;return{setup:function(o){let l=0,c=0,h=0;for(let R=0;R<9;R++)n.probe[R].set(0,0,0);let u=0,d=0,p=0,m=0,x=0,f=0,g=0,v=0,b=0,y=0,M=0;o.sort(Zv);for(let R=0,C=o.length;R0&&(r.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=ce.LTC_FLOAT_1,n.rectAreaLTC2=ce.LTC_FLOAT_2):(n.rectAreaLTC1=ce.LTC_HALF_1,n.rectAreaLTC2=ce.LTC_HALF_2)),n.ambient[0]=l,n.ambient[1]=c,n.ambient[2]=h;let _=n.hash;_.directionalLength===u&&_.pointLength===d&&_.spotLength===p&&_.rectAreaLength===m&&_.hemiLength===x&&_.numDirectionalShadows===f&&_.numPointShadows===g&&_.numSpotShadows===v&&_.numSpotMaps===b&&_.numLightProbes===M||(n.directional.length=u,n.spot.length=p,n.rectArea.length=m,n.point.length=d,n.hemi.length=x,n.directionalShadow.length=f,n.directionalShadowMap.length=f,n.pointShadow.length=g,n.pointShadowMap.length=g,n.spotShadow.length=v,n.spotShadowMap.length=v,n.directionalShadowMatrix.length=f,n.pointShadowMatrix.length=g,n.spotLightMatrix.length=v+b-y,n.spotLightMap.length=b,n.numSpotLightShadowsWithMaps=y,n.numLightProbes=M,_.directionalLength=u,_.pointLength=d,_.spotLength=p,_.rectAreaLength=m,_.hemiLength=x,_.numDirectionalShadows=f,_.numPointShadows=g,_.numSpotShadows=v,_.numSpotMaps=b,_.numLightProbes=M,n.version=$v++)},setupView:function(o,l){let c=0,h=0,u=0,d=0,p=0,m=l.matrixWorldInverse;for(let x=0,f=o.length;x=i.length?(s=new $f(r),i.push(s)):s=i[n],s},dispose:function(){e=new WeakMap}}}var ba=class extends un{static get type(){return"MeshDepthMaterial"}constructor(e){super(),this.isMeshDepthMaterial=!0,this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},yu=class extends un{static get type(){return"MeshDistanceMaterial"}constructor(e){super(),this.isMeshDistanceMaterial=!0,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}};function ex(r,e,t){let n=new bs,i=new Z,s=new Z,a=new Ze,o=new ba({depthPacking:3201}),l=new yu,c={},h=t.maxTextureSize,u={[td]:1,[Pl]:0,[Qn]:2},d=new ft({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Z},radius:{value:4}},vertexShader:`void main() { gl_Position = vec4( position, 1.0 ); }`,fragmentShader:`uniform sampler2D shadow_pass; uniform vec2 resolution; uniform float radius; #include void main() { const float samples = float( VSM_SAMPLES ); float mean = 0.0; float squared_mean = 0.0; float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); float uvStart = samples <= 1.0 ? 0.0 : - 1.0; for ( float i = 0.0; i < samples; i ++ ) { float uvOffset = uvStart + i * uvStride; #ifdef HORIZONTAL_PASS vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); mean += distribution.x; squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; #else float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); mean += depth; squared_mean += depth * depth; #endif } mean = mean / samples; squared_mean = squared_mean / samples; float std_dev = sqrt( squared_mean - mean * mean ); gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); }`}),p=d.clone();p.defines.HORIZONTAL_PASS=1;let m=new qe;m.setAttribute("position",new Qe(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let x=new Je(m,d),f=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let g=this.type;function v(_,R){let C=e.update(x);d.defines.VSM_SAMPLES!==_.blurSamples&&(d.defines.VSM_SAMPLES=_.blurSamples,p.defines.VSM_SAMPLES=_.blurSamples,d.needsUpdate=!0,p.needsUpdate=!0),_.mapPass===null&&(_.mapPass=new Rt(i.x,i.y)),d.uniforms.shadow_pass.value=_.map.texture,d.uniforms.resolution.value=_.mapSize,d.uniforms.radius.value=_.radius,r.setRenderTarget(_.mapPass),r.clear(),r.renderBufferDirect(R,null,C,d,x,null),p.uniforms.shadow_pass.value=_.mapPass.texture,p.uniforms.resolution.value=_.mapSize,p.uniforms.radius.value=_.radius,r.setRenderTarget(_.map),r.clear(),r.renderBufferDirect(R,null,C,p,x,null)}function b(_,R,C,I){let O=null,z=C.isPointLight===!0?_.customDistanceMaterial:_.customDepthMaterial;if(z!==void 0)O=z;else if(O=C.isPointLight===!0?l:o,r.localClippingEnabled&&R.clipShadows===!0&&Array.isArray(R.clippingPlanes)&&R.clippingPlanes.length!==0||R.displacementMap&&R.displacementScale!==0||R.alphaMap&&R.alphaTest>0||R.map&&R.alphaTest>0){let F=O.uuid,W=R.uuid,j=c[F];j===void 0&&(j={},c[F]=j);let Y=j[W];Y===void 0&&(Y=O.clone(),j[W]=Y,R.addEventListener("dispose",M)),O=Y}return O.visible=R.visible,O.wireframe=R.wireframe,O.side=I===3?R.shadowSide!==null?R.shadowSide:R.side:R.shadowSide!==null?R.shadowSide:u[R.side],O.alphaMap=R.alphaMap,O.alphaTest=R.alphaTest,O.map=R.map,O.clipShadows=R.clipShadows,O.clippingPlanes=R.clippingPlanes,O.clipIntersection=R.clipIntersection,O.displacementMap=R.displacementMap,O.displacementScale=R.displacementScale,O.displacementBias=R.displacementBias,O.wireframeLinewidth=R.wireframeLinewidth,O.linewidth=R.linewidth,C.isPointLight===!0&&O.isMeshDistanceMaterial===!0&&(r.properties.get(O).light=C),O}function y(_,R,C,I,O){if(_.visible===!1)return;if(_.layers.test(R.layers)&&(_.isMesh||_.isLine||_.isPoints)&&(_.castShadow||_.receiveShadow&&O===3)&&(!_.frustumCulled||n.intersectsObject(_))){_.modelViewMatrix.multiplyMatrices(C.matrixWorldInverse,_.matrixWorld);let F=e.update(_),W=_.material;if(Array.isArray(W)){let j=F.groups;for(let Y=0,K=j.length;Yh||i.y>h)&&(i.x>h&&(s.x=Math.floor(h/ge.x),i.x=s.x*ge.x,ie.mapSize.x=s.x),i.y>h&&(s.y=Math.floor(h/ge.y),i.y=s.y*ge.y,ie.mapSize.y=s.y)),ie.map===null||W===!0||j===!0){let ne=this.type!==3?{minFilter:Ht,magFilter:Ht}:{};ie.map!==null&&ie.map.dispose(),ie.map=new Rt(i.x,i.y,ne),ie.map.texture.name=re.name+".shadowMap",ie.camera.updateProjectionMatrix()}r.setRenderTarget(ie.map),r.clear();let ye=ie.getViewportCount();for(let ne=0;ne=1):Y.indexOf("OpenGL ES")!==-1&&(j=parseFloat(/^OpenGL ES (\d)/.exec(Y)[1]),W=j>=2);let K=null,re={},ie=r.getParameter(r.SCISSOR_BOX),ge=r.getParameter(r.VIEWPORT),ye=new Ze().fromArray(ie),ne=new Ze().fromArray(ge);function ae(w,k,H,ee){let B=new Uint8Array(4),J=r.createTexture();r.bindTexture(w,J),r.texParameteri(w,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(w,r.TEXTURE_MAG_FILTER,r.NEAREST);for(let $=0;$N||P.height>N)&&(U=N/Math.max(P.width,P.height)),U<1){if(typeof HTMLImageElement<"u"&&A instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&A instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&A instanceof ImageBitmap||typeof VideoFrame<"u"&&A instanceof VideoFrame){let D=Math.floor(U*P.width),w=Math.floor(U*P.height);u===void 0&&(u=m(D,w));let k=E?m(D,w):u;return k.width=D,k.height=w,k.getContext("2d").drawImage(A,0,0,D,w),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+P.width+"x"+P.height+") to ("+D+"x"+w+")."),k}return"data"in A&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+P.width+"x"+P.height+")."),A}return A}function f(A){return A.generateMipmaps}function g(A){r.generateMipmap(A)}function v(A){return A.isWebGLCubeRenderTarget?r.TEXTURE_CUBE_MAP:A.isWebGL3DRenderTarget?r.TEXTURE_3D:A.isWebGLArrayRenderTarget||A.isCompressedArrayTexture?r.TEXTURE_2D_ARRAY:r.TEXTURE_2D}function b(A,E,N,U,P=!1){if(A!==null){if(r[A]!==void 0)return r[A];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+A+"'")}let D=E;if(E===r.RED&&(N===r.FLOAT&&(D=r.R32F),N===r.HALF_FLOAT&&(D=r.R16F),N===r.UNSIGNED_BYTE&&(D=r.R8)),E===r.RED_INTEGER&&(N===r.UNSIGNED_BYTE&&(D=r.R8UI),N===r.UNSIGNED_SHORT&&(D=r.R16UI),N===r.UNSIGNED_INT&&(D=r.R32UI),N===r.BYTE&&(D=r.R8I),N===r.SHORT&&(D=r.R16I),N===r.INT&&(D=r.R32I)),E===r.RG&&(N===r.FLOAT&&(D=r.RG32F),N===r.HALF_FLOAT&&(D=r.RG16F),N===r.UNSIGNED_BYTE&&(D=r.RG8)),E===r.RG_INTEGER&&(N===r.UNSIGNED_BYTE&&(D=r.RG8UI),N===r.UNSIGNED_SHORT&&(D=r.RG16UI),N===r.UNSIGNED_INT&&(D=r.RG32UI),N===r.BYTE&&(D=r.RG8I),N===r.SHORT&&(D=r.RG16I),N===r.INT&&(D=r.RG32I)),E===r.RGB_INTEGER&&(N===r.UNSIGNED_BYTE&&(D=r.RGB8UI),N===r.UNSIGNED_SHORT&&(D=r.RGB16UI),N===r.UNSIGNED_INT&&(D=r.RGB32UI),N===r.BYTE&&(D=r.RGB8I),N===r.SHORT&&(D=r.RGB16I),N===r.INT&&(D=r.RGB32I)),E===r.RGBA_INTEGER&&(N===r.UNSIGNED_BYTE&&(D=r.RGBA8UI),N===r.UNSIGNED_SHORT&&(D=r.RGBA16UI),N===r.UNSIGNED_INT&&(D=r.RGBA32UI),N===r.BYTE&&(D=r.RGBA8I),N===r.SHORT&&(D=r.RGBA16I),N===r.INT&&(D=r.RGBA32I)),E===r.RGB&&N===r.UNSIGNED_INT_5_9_9_9_REV&&(D=r.RGB9_E5),E===r.RGBA){let w=P?Ul:Oe.getTransfer(U);N===r.FLOAT&&(D=r.RGBA32F),N===r.HALF_FLOAT&&(D=r.RGBA16F),N===r.UNSIGNED_BYTE&&(D=w===tt?r.SRGB8_ALPHA8:r.RGBA8),N===r.UNSIGNED_SHORT_4_4_4_4&&(D=r.RGBA4),N===r.UNSIGNED_SHORT_5_5_5_1&&(D=r.RGB5_A1)}return D!==r.R16F&&D!==r.R32F&&D!==r.RG16F&&D!==r.RG32F&&D!==r.RGBA16F&&D!==r.RGBA32F||e.get("EXT_color_buffer_float"),D}function y(A,E){let N;return A?E===null||E===br||E===cs?N=r.DEPTH24_STENCIL8:E===On?N=r.DEPTH32F_STENCIL8:E===pa&&(N=r.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):E===null||E===br||E===cs?N=r.DEPTH_COMPONENT24:E===On?N=r.DEPTH_COMPONENT32F:E===pa&&(N=r.DEPTH_COMPONENT16),N}function M(A,E){return f(A)===!0||A.isFramebufferTexture&&A.minFilter!==Ht&&A.minFilter!==jt?Math.log2(Math.max(E.width,E.height))+1:A.mipmaps!==void 0&&A.mipmaps.length>0?A.mipmaps.length:A.isCompressedTexture&&Array.isArray(A.image)?E.mipmaps.length:1}function _(A){let E=A.target;E.removeEventListener("dispose",_),function(N){let U=n.get(N);if(U.__webglInit===void 0)return;let P=N.source,D=d.get(P);if(D){let w=D[U.__cacheKey];w.usedTimes--,w.usedTimes===0&&C(N),Object.keys(D).length===0&&d.delete(P)}n.remove(N)}(E),E.isVideoTexture&&h.delete(E)}function R(A){let E=A.target;E.removeEventListener("dispose",R),function(N){let U=n.get(N);if(N.depthTexture&&(N.depthTexture.dispose(),n.remove(N.depthTexture)),N.isWebGLCubeRenderTarget)for(let D=0;D<6;D++){if(Array.isArray(U.__webglFramebuffer[D]))for(let w=0;w0&&N.__version!==A.version){let U=A.image;if(U===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else{if(U.complete!==!1)return void K(N,A,E);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete")}}t.bindTexture(r.TEXTURE_2D,N.__webglTexture,r.TEXTURE0+E)}let z={[Fn]:r.REPEAT,[gr]:r.CLAMP_TO_EDGE,[da]:r.MIRRORED_REPEAT},F={[Ht]:r.NEAREST,[nd]:r.NEAREST_MIPMAP_NEAREST,[es]:r.NEAREST_MIPMAP_LINEAR,[jt]:r.LINEAR,[aa]:r.LINEAR_MIPMAP_NEAREST,[gi]:r.LINEAR_MIPMAP_LINEAR},W={[ub]:r.NEVER,[vb]:r.ALWAYS,[db]:r.LESS,[fb]:r.LEQUAL,[pb]:r.EQUAL,[bb]:r.GEQUAL,[mb]:r.GREATER,[gb]:r.NOTEQUAL};function j(A,E){if(E.type!==On||e.has("OES_texture_float_linear")!==!1||E.magFilter!==jt&&E.magFilter!==aa&&E.magFilter!==es&&E.magFilter!==gi&&E.minFilter!==jt&&E.minFilter!==aa&&E.minFilter!==es&&E.minFilter!==gi||console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),r.texParameteri(A,r.TEXTURE_WRAP_S,z[E.wrapS]),r.texParameteri(A,r.TEXTURE_WRAP_T,z[E.wrapT]),A!==r.TEXTURE_3D&&A!==r.TEXTURE_2D_ARRAY||r.texParameteri(A,r.TEXTURE_WRAP_R,z[E.wrapR]),r.texParameteri(A,r.TEXTURE_MAG_FILTER,F[E.magFilter]),r.texParameteri(A,r.TEXTURE_MIN_FILTER,F[E.minFilter]),E.compareFunction&&(r.texParameteri(A,r.TEXTURE_COMPARE_MODE,r.COMPARE_REF_TO_TEXTURE),r.texParameteri(A,r.TEXTURE_COMPARE_FUNC,W[E.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(E.magFilter===Ht||E.minFilter!==es&&E.minFilter!==gi||E.type===On&&e.has("OES_texture_float_linear")===!1)return;if(E.anisotropy>1||n.get(E).__currentAnisotropy){let N=e.get("EXT_texture_filter_anisotropic");r.texParameterf(A,N.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(E.anisotropy,i.getMaxAnisotropy())),n.get(E).__currentAnisotropy=E.anisotropy}}}function Y(A,E){let N=!1;A.__webglInit===void 0&&(A.__webglInit=!0,E.addEventListener("dispose",_));let U=E.source,P=d.get(U);P===void 0&&(P={},d.set(U,P));let D=function(w){let k=[];return k.push(w.wrapS),k.push(w.wrapT),k.push(w.wrapR||0),k.push(w.magFilter),k.push(w.minFilter),k.push(w.anisotropy),k.push(w.internalFormat),k.push(w.format),k.push(w.type),k.push(w.generateMipmaps),k.push(w.premultiplyAlpha),k.push(w.flipY),k.push(w.unpackAlignment),k.push(w.colorSpace),k.join()}(E);if(D!==A.__cacheKey){P[D]===void 0&&(P[D]={texture:r.createTexture(),usedTimes:0},a.memory.textures++,N=!0),P[D].usedTimes++;let w=P[A.__cacheKey];w!==void 0&&(P[A.__cacheKey].usedTimes--,w.usedTimes===0&&C(E)),A.__cacheKey=D,A.__webglTexture=P[D].texture}return N}function K(A,E,N){let U=r.TEXTURE_2D;(E.isDataArrayTexture||E.isCompressedArrayTexture)&&(U=r.TEXTURE_2D_ARRAY),E.isData3DTexture&&(U=r.TEXTURE_3D);let P=Y(A,E),D=E.source;t.bindTexture(U,A.__webglTexture,r.TEXTURE0+N);let w=n.get(D);if(D.version!==w.__version||P===!0){t.activeTexture(r.TEXTURE0+N);let k=Oe.getPrimaries(Oe.workingColorSpace),H=E.colorSpace===Qr?null:Oe.getPrimaries(E.colorSpace),ee=E.colorSpace===Qr||k===H?r.NONE:r.BROWSER_DEFAULT_WEBGL;r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,E.flipY),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,E.premultiplyAlpha),r.pixelStorei(r.UNPACK_ALIGNMENT,E.unpackAlignment),r.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,ee);let B=x(E.image,!1,i.maxTextureSize);B=be(E,B);let J=s.convert(E.format,E.colorSpace),$=s.convert(E.type),te,pe=b(E.internalFormat,J,$,E.colorSpace,E.isVideoTexture);j(U,E);let de=E.mipmaps,Me=E.isVideoTexture!==!0,Ce=w.__version===void 0||P===!0,Xe=D.dataReady,ze=M(E,B);if(E.isDepthTexture)pe=y(E.format===hs,E.type),Ce&&(Me?t.texStorage2D(r.TEXTURE_2D,1,pe,B.width,B.height):t.texImage2D(r.TEXTURE_2D,0,pe,B.width,B.height,0,J,$,null));else if(E.isDataTexture)if(de.length>0){Me&&Ce&&t.texStorage2D(r.TEXTURE_2D,ze,pe,de[0].width,de[0].height);for(let Se=0,Ke=de.length;Se0){let ht=Zf(te.width,te.height,E.format,E.type);for(let bt of E.layerUpdates){let ve=te.data.subarray(bt*ht/te.data.BYTES_PER_ELEMENT,(bt+1)*ht/te.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(r.TEXTURE_2D_ARRAY,Se,0,0,bt,te.width,te.height,1,J,ve)}E.clearLayerUpdates()}else t.compressedTexSubImage3D(r.TEXTURE_2D_ARRAY,Se,0,0,0,te.width,te.height,B.depth,J,te.data)}else t.compressedTexImage3D(r.TEXTURE_2D_ARRAY,Se,pe,te.width,te.height,B.depth,0,te.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else Me?Xe&&t.texSubImage3D(r.TEXTURE_2D_ARRAY,Se,0,0,0,te.width,te.height,B.depth,J,$,te.data):t.texImage3D(r.TEXTURE_2D_ARRAY,Se,pe,te.width,te.height,B.depth,0,J,$,te.data)}else{Me&&Ce&&t.texStorage2D(r.TEXTURE_2D,ze,pe,de[0].width,de[0].height);for(let Se=0,Ke=de.length;Se0){let Se=Zf(B.width,B.height,E.format,E.type);for(let Ke of E.layerUpdates){let ht=B.data.subarray(Ke*Se/B.data.BYTES_PER_ELEMENT,(Ke+1)*Se/B.data.BYTES_PER_ELEMENT);t.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,Ke,B.width,B.height,1,J,$,ht)}E.clearLayerUpdates()}else t.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,0,B.width,B.height,B.depth,J,$,B.data)}else t.texImage3D(r.TEXTURE_2D_ARRAY,0,pe,B.width,B.height,B.depth,0,J,$,B.data);else if(E.isData3DTexture)Me?(Ce&&t.texStorage3D(r.TEXTURE_3D,ze,pe,B.width,B.height,B.depth),Xe&&t.texSubImage3D(r.TEXTURE_3D,0,0,0,0,B.width,B.height,B.depth,J,$,B.data)):t.texImage3D(r.TEXTURE_3D,0,pe,B.width,B.height,B.depth,0,J,$,B.data);else if(E.isFramebufferTexture){if(Ce)if(Me)t.texStorage2D(r.TEXTURE_2D,ze,pe,B.width,B.height);else{let Se=B.width,Ke=B.height;for(let ht=0;ht>=1,Ke>>=1}}else if(de.length>0){if(Me&&Ce){let Se=ue(de[0]);t.texStorage2D(r.TEXTURE_2D,ze,pe,Se.width,Se.height)}for(let Se=0,Ke=de.length;Se>D),$=Math.max(1,E.height>>D);P===r.TEXTURE_3D||P===r.TEXTURE_2D_ARRAY?t.texImage3D(P,D,H,J,$,E.depth,0,w,k,null):t.texImage2D(P,D,H,J,$,0,w,k,null)}t.bindFramebuffer(r.FRAMEBUFFER,A),me(E)?o.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER,U,P,B.__webglTexture,0,ae(E)):(P===r.TEXTURE_2D||P>=r.TEXTURE_CUBE_MAP_POSITIVE_X&&P<=r.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&r.framebufferTexture2D(r.FRAMEBUFFER,U,P,B.__webglTexture,D),t.bindFramebuffer(r.FRAMEBUFFER,null)}function ie(A,E,N){if(r.bindRenderbuffer(r.RENDERBUFFER,A),E.depthBuffer){let U=E.depthTexture,P=U&&U.isDepthTexture?U.type:null,D=y(E.stencilBuffer,P),w=E.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,k=ae(E);me(E)?o.renderbufferStorageMultisampleEXT(r.RENDERBUFFER,k,D,E.width,E.height):N?r.renderbufferStorageMultisample(r.RENDERBUFFER,k,D,E.width,E.height):r.renderbufferStorage(r.RENDERBUFFER,D,E.width,E.height),r.framebufferRenderbuffer(r.FRAMEBUFFER,w,r.RENDERBUFFER,A)}else{let U=E.textures;for(let P=0;P{delete E.__boundDepthTexture,delete E.__depthDisposeCallback,U.removeEventListener("dispose",P)};U.addEventListener("dispose",P),E.__depthDisposeCallback=P}E.__boundDepthTexture=U}if(A.depthTexture&&!E.__autoAllocateDepthBuffer){if(N)throw new Error("target.depthTexture not supported in Cube render targets");(function(U,P){if(P&&P.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(t.bindFramebuffer(r.FRAMEBUFFER,U),!P.depthTexture||!P.depthTexture.isDepthTexture)throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");let D=n.get(P.depthTexture);D.__renderTarget=P,D.__webglTexture&&P.depthTexture.image.width===P.width&&P.depthTexture.image.height===P.height||(P.depthTexture.image.width=P.width,P.depthTexture.image.height=P.height,P.depthTexture.needsUpdate=!0),O(P.depthTexture,0);let w=D.__webglTexture,k=ae(P);if(P.depthTexture.format===fa)me(P)?o.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.TEXTURE_2D,w,0,k):r.framebufferTexture2D(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.TEXTURE_2D,w,0);else{if(P.depthTexture.format!==hs)throw new Error("Unknown depthTexture format");me(P)?o.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.TEXTURE_2D,w,0,k):r.framebufferTexture2D(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.TEXTURE_2D,w,0)}})(E.__webglFramebuffer,A)}else if(N){E.__webglDepthbuffer=[];for(let U=0;U<6;U++)if(t.bindFramebuffer(r.FRAMEBUFFER,E.__webglFramebuffer[U]),E.__webglDepthbuffer[U]===void 0)E.__webglDepthbuffer[U]=r.createRenderbuffer(),ie(E.__webglDepthbuffer[U],A,!1);else{let P=A.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,D=E.__webglDepthbuffer[U];r.bindRenderbuffer(r.RENDERBUFFER,D),r.framebufferRenderbuffer(r.FRAMEBUFFER,P,r.RENDERBUFFER,D)}}else if(t.bindFramebuffer(r.FRAMEBUFFER,E.__webglFramebuffer),E.__webglDepthbuffer===void 0)E.__webglDepthbuffer=r.createRenderbuffer(),ie(E.__webglDepthbuffer,A,!1);else{let U=A.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,P=E.__webglDepthbuffer;r.bindRenderbuffer(r.RENDERBUFFER,P),r.framebufferRenderbuffer(r.FRAMEBUFFER,U,r.RENDERBUFFER,P)}t.bindFramebuffer(r.FRAMEBUFFER,null)}let ye=[],ne=[];function ae(A){return Math.min(i.maxSamples,A.samples)}function me(A){let E=n.get(A);return A.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&E.__useRenderToTexture!==!1}function be(A,E){let N=A.colorSpace,U=A.format,P=A.type;return A.isCompressedTexture===!0||A.isVideoTexture===!0||N!==qt&&N!==Qr&&(Oe.getTransfer(N)===tt?U===zn&&P===Vi||console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",N)),E}function ue(A){return typeof HTMLImageElement<"u"&&A instanceof HTMLImageElement?(c.width=A.naturalWidth||A.width,c.height=A.naturalHeight||A.height):typeof VideoFrame<"u"&&A instanceof VideoFrame?(c.width=A.displayWidth,c.height=A.displayHeight):(c.width=A.width,c.height=A.height),c}this.allocateTextureUnit=function(){let A=I;return A>=i.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+A+" texture units while this GPU supports only "+i.maxTextures),I+=1,A},this.resetTextureUnits=function(){I=0},this.setTexture2D=O,this.setTexture2DArray=function(A,E){let N=n.get(A);A.version>0&&N.__version!==A.version?K(N,A,E):t.bindTexture(r.TEXTURE_2D_ARRAY,N.__webglTexture,r.TEXTURE0+E)},this.setTexture3D=function(A,E){let N=n.get(A);A.version>0&&N.__version!==A.version?K(N,A,E):t.bindTexture(r.TEXTURE_3D,N.__webglTexture,r.TEXTURE0+E)},this.setTextureCube=function(A,E){let N=n.get(A);A.version>0&&N.__version!==A.version?function(U,P,D){if(P.image.length!==6)return;let w=Y(U,P),k=P.source;t.bindTexture(r.TEXTURE_CUBE_MAP,U.__webglTexture,r.TEXTURE0+D);let H=n.get(k);if(k.version!==H.__version||w===!0){t.activeTexture(r.TEXTURE0+D);let ee=Oe.getPrimaries(Oe.workingColorSpace),B=P.colorSpace===Qr?null:Oe.getPrimaries(P.colorSpace),J=P.colorSpace===Qr||ee===B?r.NONE:r.BROWSER_DEFAULT_WEBGL;r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,P.flipY),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,P.premultiplyAlpha),r.pixelStorei(r.UNPACK_ALIGNMENT,P.unpackAlignment),r.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,J);let $=P.isCompressedTexture||P.image[0].isCompressedTexture,te=P.image[0]&&P.image[0].isDataTexture,pe=[];for(let ve=0;ve<6;ve++)pe[ve]=$||te?te?P.image[ve].image:P.image[ve]:x(P.image[ve],!0,i.maxCubemapSize),pe[ve]=be(P,pe[ve]);let de=pe[0],Me=s.convert(P.format,P.colorSpace),Ce=s.convert(P.type),Xe=b(P.internalFormat,Me,Ce,P.colorSpace),ze=P.isVideoTexture!==!0,Se=H.__version===void 0||w===!0,Ke=k.dataReady,ht,bt=M(P,de);if(j(r.TEXTURE_CUBE_MAP,P),$){ze&&Se&&t.texStorage2D(r.TEXTURE_CUBE_MAP,bt,Xe,de.width,de.height);for(let ve=0;ve<6;ve++){ht=pe[ve].mipmaps;for(let Ge=0;Ge0&&bt++;let ve=ue(pe[0]);t.texStorage2D(r.TEXTURE_CUBE_MAP,bt,Xe,ve.width,ve.height)}for(let ve=0;ve<6;ve++)if(te){ze?Ke&&t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+ve,0,0,0,pe[ve].width,pe[ve].height,Me,Ce,pe[ve].data):t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+ve,0,Xe,pe[ve].width,pe[ve].height,0,Me,Ce,pe[ve].data);for(let Ge=0;Ge1;if(w||(U.__webglTexture===void 0&&(U.__webglTexture=r.createTexture()),U.__version=E.version,a.memory.textures++),D){N.__webglFramebuffer=[];for(let k=0;k<6;k++)if(E.mipmaps&&E.mipmaps.length>0){N.__webglFramebuffer[k]=[];for(let H=0;H0){N.__webglFramebuffer=[];for(let k=0;k0&&me(A)===!1){N.__webglMultisampledFramebuffer=r.createFramebuffer(),N.__webglColorRenderbuffer=[],t.bindFramebuffer(r.FRAMEBUFFER,N.__webglMultisampledFramebuffer);for(let k=0;k0)for(let H=0;H0)for(let H=0;H0){if(me(A)===!1){let E=A.textures,N=A.width,U=A.height,P=r.COLOR_BUFFER_BIT,D=A.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,w=n.get(A),k=E.length>1;if(k)for(let H=0;Hp+m?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&d<=p-m&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(s=t.getPose(e.gripSpace,n),s!==null&&(l.matrix.fromArray(s.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,s.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(s.linearVelocity)):l.hasLinearVelocity=!1,s.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(s.angularVelocity)):l.hasAngularVelocity=!1));o!==null&&(i=t.getPose(e.targetRaySpace,n),i===null&&s!==null&&(i=s),i!==null&&(o.matrix.fromArray(i.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,i.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(i.linearVelocity)):o.hasLinearVelocity=!1,i.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(i.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(sx)))}return o!==null&&(o.visible=i!==null),l!==null&&(l.visible=s!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new Zt;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},Mu=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t,n){if(this.texture===null){let i=new Ut;e.properties.get(i).__webglTexture=t.texture,t.depthNear==n.depthNear&&t.depthFar==n.depthFar||(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=i}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,n=new ft({vertexShader:` void main() { gl_Position = vec4( position, 1.0 ); }`,fragmentShader:` uniform sampler2DArray depthColor; uniform float depthWidth; uniform float depthHeight; void main() { vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); if ( coord.x >= 1.0 ) { gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; } else { gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; } }`,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Je(new xi(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},Su=class extends vi{constructor(e,t){super();let n=this,i=null,s=1,a=null,o="local-floor",l=1,c=null,h=null,u=null,d=null,p=null,m=null,x=new Mu,f=t.getContextAttributes(),g=null,v=null,b=[],y=[],M=new Z,_=null,R=new At;R.viewport=new Ze;let C=new At;C.viewport=new Ze;let I=[R,C],O=new _u,z=null,F=null;function W(ne){let ae=y.indexOf(ne.inputSource);if(ae===-1)return;let me=b[ae];me!==void 0&&(me.update(ne.inputSource,ne.frame,c||a),me.dispatchEvent({type:ne.type,data:ne.inputSource}))}function j(){i.removeEventListener("select",W),i.removeEventListener("selectstart",W),i.removeEventListener("selectend",W),i.removeEventListener("squeeze",W),i.removeEventListener("squeezestart",W),i.removeEventListener("squeezeend",W),i.removeEventListener("end",j),i.removeEventListener("inputsourceschange",Y);for(let ne=0;ne=0&&(y[be]=null,b[be].disconnect(me))}for(let ae=0;ae=y.length){y.push(me),be=A;break}if(y[A]===null){y[A]=me,be=A;break}}if(be===-1)break}let ue=b[be];ue&&ue.connect(me)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(ne){let ae=b[ne];return ae===void 0&&(ae=new la,b[ne]=ae),ae.getTargetRaySpace()},this.getControllerGrip=function(ne){let ae=b[ne];return ae===void 0&&(ae=new la,b[ne]=ae),ae.getGripSpace()},this.getHand=function(ne){let ae=b[ne];return ae===void 0&&(ae=new la,b[ne]=ae),ae.getHandSpace()},this.setFramebufferScaleFactor=function(ne){s=ne,n.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(ne){o=ne,n.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return c||a},this.setReferenceSpace=function(ne){c=ne},this.getBaseLayer=function(){return d!==null?d:p},this.getBinding=function(){return u},this.getFrame=function(){return m},this.getSession=function(){return i},this.setSession=async function(ne){if(i=ne,i!==null){if(g=e.getRenderTarget(),i.addEventListener("select",W),i.addEventListener("selectstart",W),i.addEventListener("selectend",W),i.addEventListener("squeeze",W),i.addEventListener("squeezestart",W),i.addEventListener("squeezeend",W),i.addEventListener("end",j),i.addEventListener("inputsourceschange",Y),f.xrCompatible!==!0&&await t.makeXRCompatible(),_=e.getPixelRatio(),e.getSize(M),i.renderState.layers===void 0){let ae={antialias:f.antialias,alpha:!0,depth:f.depth,stencil:f.stencil,framebufferScaleFactor:s};p=new XRWebGLLayer(i,t,ae),i.updateRenderState({baseLayer:p}),e.setPixelRatio(1),e.setSize(p.framebufferWidth,p.framebufferHeight,!1),v=new Rt(p.framebufferWidth,p.framebufferHeight,{format:zn,type:Vi,colorSpace:e.outputColorSpace,stencilBuffer:f.stencil})}else{let ae=null,me=null,be=null;f.depth&&(be=f.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,ae=f.stencil?hs:fa,me=f.stencil?cs:br);let ue={colorFormat:t.RGBA8,depthFormat:be,scaleFactor:s};u=new XRWebGLBinding(i,t),d=u.createProjectionLayer(ue),i.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),v=new Rt(d.textureWidth,d.textureHeight,{format:zn,type:Vi,depthTexture:new il(d.textureWidth,d.textureHeight,me,void 0,void 0,void 0,void 0,void 0,void 0,ae),stencilBuffer:f.stencil,colorSpace:e.outputColorSpace,samples:f.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1})}v.isXRRenderTarget=!0,this.setFoveation(l),c=null,a=await i.requestReferenceSpace(o),ye.setContext(i),ye.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(i!==null)return i.environmentBlendMode},this.getDepthTexture=function(){return x.getDepthTexture()};let K=new S,re=new S;function ie(ne,ae){ae===null?ne.matrixWorld.copy(ne.matrix):ne.matrixWorld.multiplyMatrices(ae.matrixWorld,ne.matrix),ne.matrixWorldInverse.copy(ne.matrixWorld).invert()}this.updateCamera=function(ne){if(i===null)return;let ae=ne.near,me=ne.far;x.texture!==null&&(x.depthNear>0&&(ae=x.depthNear),x.depthFar>0&&(me=x.depthFar)),O.near=C.near=R.near=ae,O.far=C.far=R.far=me,z===O.near&&F===O.far||(i.updateRenderState({depthNear:O.near,depthFar:O.far}),z=O.near,F=O.far),R.layers.mask=2|ne.layers.mask,C.layers.mask=4|ne.layers.mask,O.layers.mask=R.layers.mask|C.layers.mask;let be=ne.parent,ue=O.cameras;ie(O,be);for(let A=0;A0&&(i.alphaTest.value=s.alphaTest);let a=e.get(s),o=a.envMap,l=a.envMapRotation;o&&(i.envMap.value=o,pr.copy(l),pr.x*=-1,pr.y*=-1,pr.z*=-1,o.isCubeTexture&&o.isRenderTargetTexture===!1&&(pr.y*=-1,pr.z*=-1),i.envMapRotation.value.setFromMatrix4(ax.makeRotationFromEuler(pr)),i.flipEnvMap.value=o.isCubeTexture&&o.isRenderTargetTexture===!1?-1:1,i.reflectivity.value=s.reflectivity,i.ior.value=s.ior,i.refractionRatio.value=s.refractionRatio),s.lightMap&&(i.lightMap.value=s.lightMap,i.lightMapIntensity.value=s.lightMapIntensity,t(s.lightMap,i.lightMapTransform)),s.aoMap&&(i.aoMap.value=s.aoMap,i.aoMapIntensity.value=s.aoMapIntensity,t(s.aoMap,i.aoMapTransform))}return{refreshFogUniforms:function(i,s){s.color.getRGB(i.fogColor.value,jm(r)),s.isFog?(i.fogNear.value=s.near,i.fogFar.value=s.far):s.isFogExp2&&(i.fogDensity.value=s.density)},refreshMaterialUniforms:function(i,s,a,o,l){s.isMeshBasicMaterial||s.isMeshLambertMaterial?n(i,s):s.isMeshToonMaterial?(n(i,s),function(c,h){h.gradientMap&&(c.gradientMap.value=h.gradientMap)}(i,s)):s.isMeshPhongMaterial?(n(i,s),function(c,h){c.specular.value.copy(h.specular),c.shininess.value=Math.max(h.shininess,1e-4)}(i,s)):s.isMeshStandardMaterial?(n(i,s),function(c,h){c.metalness.value=h.metalness,h.metalnessMap&&(c.metalnessMap.value=h.metalnessMap,t(h.metalnessMap,c.metalnessMapTransform)),c.roughness.value=h.roughness,h.roughnessMap&&(c.roughnessMap.value=h.roughnessMap,t(h.roughnessMap,c.roughnessMapTransform)),h.envMap&&(c.envMapIntensity.value=h.envMapIntensity)}(i,s),s.isMeshPhysicalMaterial&&function(c,h,u){c.ior.value=h.ior,h.sheen>0&&(c.sheenColor.value.copy(h.sheenColor).multiplyScalar(h.sheen),c.sheenRoughness.value=h.sheenRoughness,h.sheenColorMap&&(c.sheenColorMap.value=h.sheenColorMap,t(h.sheenColorMap,c.sheenColorMapTransform)),h.sheenRoughnessMap&&(c.sheenRoughnessMap.value=h.sheenRoughnessMap,t(h.sheenRoughnessMap,c.sheenRoughnessMapTransform))),h.clearcoat>0&&(c.clearcoat.value=h.clearcoat,c.clearcoatRoughness.value=h.clearcoatRoughness,h.clearcoatMap&&(c.clearcoatMap.value=h.clearcoatMap,t(h.clearcoatMap,c.clearcoatMapTransform)),h.clearcoatRoughnessMap&&(c.clearcoatRoughnessMap.value=h.clearcoatRoughnessMap,t(h.clearcoatRoughnessMap,c.clearcoatRoughnessMapTransform)),h.clearcoatNormalMap&&(c.clearcoatNormalMap.value=h.clearcoatNormalMap,t(h.clearcoatNormalMap,c.clearcoatNormalMapTransform),c.clearcoatNormalScale.value.copy(h.clearcoatNormalScale),h.side===1&&c.clearcoatNormalScale.value.negate())),h.dispersion>0&&(c.dispersion.value=h.dispersion),h.iridescence>0&&(c.iridescence.value=h.iridescence,c.iridescenceIOR.value=h.iridescenceIOR,c.iridescenceThicknessMinimum.value=h.iridescenceThicknessRange[0],c.iridescenceThicknessMaximum.value=h.iridescenceThicknessRange[1],h.iridescenceMap&&(c.iridescenceMap.value=h.iridescenceMap,t(h.iridescenceMap,c.iridescenceMapTransform)),h.iridescenceThicknessMap&&(c.iridescenceThicknessMap.value=h.iridescenceThicknessMap,t(h.iridescenceThicknessMap,c.iridescenceThicknessMapTransform))),h.transmission>0&&(c.transmission.value=h.transmission,c.transmissionSamplerMap.value=u.texture,c.transmissionSamplerSize.value.set(u.width,u.height),h.transmissionMap&&(c.transmissionMap.value=h.transmissionMap,t(h.transmissionMap,c.transmissionMapTransform)),c.thickness.value=h.thickness,h.thicknessMap&&(c.thicknessMap.value=h.thicknessMap,t(h.thicknessMap,c.thicknessMapTransform)),c.attenuationDistance.value=h.attenuationDistance,c.attenuationColor.value.copy(h.attenuationColor)),h.anisotropy>0&&(c.anisotropyVector.value.set(h.anisotropy*Math.cos(h.anisotropyRotation),h.anisotropy*Math.sin(h.anisotropyRotation)),h.anisotropyMap&&(c.anisotropyMap.value=h.anisotropyMap,t(h.anisotropyMap,c.anisotropyMapTransform))),c.specularIntensity.value=h.specularIntensity,c.specularColor.value.copy(h.specularColor),h.specularColorMap&&(c.specularColorMap.value=h.specularColorMap,t(h.specularColorMap,c.specularColorMapTransform)),h.specularIntensityMap&&(c.specularIntensityMap.value=h.specularIntensityMap,t(h.specularIntensityMap,c.specularIntensityMapTransform))}(i,s,l)):s.isMeshMatcapMaterial?(n(i,s),function(c,h){h.matcap&&(c.matcap.value=h.matcap)}(i,s)):s.isMeshDepthMaterial?n(i,s):s.isMeshDistanceMaterial?(n(i,s),function(c,h){let u=e.get(h).light;c.referencePosition.value.setFromMatrixPosition(u.matrixWorld),c.nearDistance.value=u.shadow.camera.near,c.farDistance.value=u.shadow.camera.far}(i,s)):s.isMeshNormalMaterial?n(i,s):s.isLineBasicMaterial?(function(c,h){c.diffuse.value.copy(h.color),c.opacity.value=h.opacity,h.map&&(c.map.value=h.map,t(h.map,c.mapTransform))}(i,s),s.isLineDashedMaterial&&function(c,h){c.dashSize.value=h.dashSize,c.totalSize.value=h.dashSize+h.gapSize,c.scale.value=h.scale}(i,s)):s.isPointsMaterial?function(c,h,u,d){c.diffuse.value.copy(h.color),c.opacity.value=h.opacity,c.size.value=h.size*u,c.scale.value=.5*d,h.map&&(c.map.value=h.map,t(h.map,c.uvTransform)),h.alphaMap&&(c.alphaMap.value=h.alphaMap,t(h.alphaMap,c.alphaMapTransform)),h.alphaTest>0&&(c.alphaTest.value=h.alphaTest)}(i,s,a,o):s.isSpriteMaterial?function(c,h){c.diffuse.value.copy(h.color),c.opacity.value=h.opacity,c.rotation.value=h.rotation,h.map&&(c.map.value=h.map,t(h.map,c.mapTransform)),h.alphaMap&&(c.alphaMap.value=h.alphaMap,t(h.alphaMap,c.alphaMapTransform)),h.alphaTest>0&&(c.alphaTest.value=h.alphaTest)}(i,s):s.isShadowMaterial?(i.color.value.copy(s.color),i.opacity.value=s.opacity):s.isShaderMaterial&&(s.uniformsNeedUpdate=!1)}}}function lx(r,e,t,n){let i={},s={},a=[],o=r.getParameter(r.MAX_UNIFORM_BUFFER_BINDINGS);function l(u,d,p,m){let x=u.value,f=d+"_"+p;if(m[f]===void 0)return m[f]=typeof x=="number"||typeof x=="boolean"?x:x.clone(),!0;{let g=m[f];if(typeof x=="number"||typeof x=="boolean"){if(g!==x)return m[f]=x,!0}else if(g.equals(x)===!1)return g.copy(x),!0}return!1}function c(u){let d={boundary:0,storage:0};return typeof u=="number"||typeof u=="boolean"?(d.boundary=4,d.storage=4):u.isVector2?(d.boundary=8,d.storage=8):u.isVector3||u.isColor?(d.boundary=16,d.storage=12):u.isVector4?(d.boundary=16,d.storage=16):u.isMatrix3?(d.boundary=48,d.storage=48):u.isMatrix4?(d.boundary=64,d.storage=64):u.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",u),d}function h(u){let d=u.target;d.removeEventListener("dispose",h);let p=a.indexOf(d.__bindingPointIndex);a.splice(p,1),r.deleteBuffer(i[d.id]),delete i[d.id],delete s[d.id]}return{bind:function(u,d){let p=d.program;n.uniformBlockBinding(u,p)},update:function(u,d){let p=i[u.id];p===void 0&&(function(f){let g=f.uniforms,v=0,b=16;for(let M=0,_=g.length;M<_;M++){let R=Array.isArray(g[M])?g[M]:[g[M]];for(let C=0,I=R.length;C0&&(v+=b-y),f.__size=v,f.__cache={}}(u),p=function(f){let g=function(){for(let M=0;M0),_c=!!Ft.morphAttributes.position,Ci=!!Ft.morphAttributes.normal,h0=!!Ft.morphAttributes.color,Fp=0;Ue.toneMapped&&(C!==null&&C.isXRRenderTarget!==!0||(Fp=y.toneMapping));let Bp=Ft.morphAttributes.position||Ft.morphAttributes.normal||Ft.morphAttributes.color,u0=Bp!==void 0?Bp.length:0,Ve=$.get(Ue),d0=g.state.lights;if(ue===!0&&(A===!0||je!==O)){let bn=je===O&&Ue.id===I;bt.setState(Ue,je,bn)}let In=!1;Ue.version===Ve.__version?Ve.needsLights&&Ve.lightsStateVersion!==d0.state.version||Ve.outputColorSpace!==Gs||Pe.isBatchedMesh&&Ve.batching===!1?In=!0:Pe.isBatchedMesh||Ve.batching!==!0?Pe.isBatchedMesh&&Ve.batchingColor===!0&&Pe.colorTexture===null||Pe.isBatchedMesh&&Ve.batchingColor===!1&&Pe.colorTexture!==null||Pe.isInstancedMesh&&Ve.instancing===!1?In=!0:Pe.isInstancedMesh||Ve.instancing!==!0?Pe.isSkinnedMesh&&Ve.skinning===!1?In=!0:Pe.isSkinnedMesh||Ve.skinning!==!0?Pe.isInstancedMesh&&Ve.instancingColor===!0&&Pe.instanceColor===null||Pe.isInstancedMesh&&Ve.instancingColor===!1&&Pe.instanceColor!==null||Pe.isInstancedMesh&&Ve.instancingMorph===!0&&Pe.morphTexture===null||Pe.isInstancedMesh&&Ve.instancingMorph===!1&&Pe.morphTexture!==null||Ve.envMap!==Nr||Ue.fog===!0&&Ve.fog!==Pn?In=!0:Ve.numClippingPlanes===void 0||Ve.numClippingPlanes===bt.numPlanes&&Ve.numIntersection===bt.numIntersection?(Ve.vertexAlphas!==xc||Ve.vertexTangents!==yc||Ve.morphTargets!==_c||Ve.morphNormals!==Ci||Ve.morphColors!==h0||Ve.toneMapping!==Fp||Ve.morphTargetsCount!==u0)&&(In=!0):In=!0:In=!0:In=!0:In=!0:(In=!0,Ve.__version=Ue.version);let ar=Ve.currentProgram;In===!0&&(ar=$a(Ue,Xt,Pe));let Hp=!1,Vs=!1,Mc=!1,Mt=ar.getUniforms(),Pi=Ve.uniforms;if(B.useProgram(ar.program)&&(Hp=!0,Vs=!0,Mc=!0),Ue.id!==I&&(I=Ue.id,Vs=!0),Hp||O!==je){B.buffers.depth.getReversed()?(E.copy(je.projectionMatrix),function(or){let mt=or.elements;mt[2]=.5*mt[2]+.5*mt[3],mt[6]=.5*mt[6]+.5*mt[7],mt[10]=.5*mt[10]+.5*mt[11],mt[14]=.5*mt[14]+.5*mt[15]}(E),function(or){let mt=or.elements;mt[11]===-1?(mt[10]=-mt[10]-1,mt[14]=-mt[14]):(mt[10]=-mt[10],mt[14]=1-mt[14])}(E),Mt.setValue(G,"projectionMatrix",E)):Mt.setValue(G,"projectionMatrix",je.projectionMatrix),Mt.setValue(G,"viewMatrix",je.matrixWorldInverse);let bn=Mt.map.cameraPosition;bn!==void 0&&bn.setValue(G,U.setFromMatrixPosition(je.matrixWorld)),ee.logarithmicDepthBuffer&&Mt.setValue(G,"logDepthBufFC",2/(Math.log(je.far+1)/Math.LN2)),(Ue.isMeshPhongMaterial||Ue.isMeshToonMaterial||Ue.isMeshLambertMaterial||Ue.isMeshBasicMaterial||Ue.isMeshStandardMaterial||Ue.isShaderMaterial)&&Mt.setValue(G,"isOrthographic",je.isOrthographicCamera===!0),O!==je&&(O=je,Vs=!0,Mc=!0)}if(Pe.isSkinnedMesh){Mt.setOptional(G,Pe,"bindMatrix"),Mt.setOptional(G,Pe,"bindMatrixInverse");let bn=Pe.skeleton;bn&&(bn.boneTexture===null&&bn.computeBoneTexture(),Mt.setValue(G,"boneTexture",bn.boneTexture,te))}Pe.isBatchedMesh&&(Mt.setOptional(G,Pe,"batchingTexture"),Mt.setValue(G,"batchingTexture",Pe._matricesTexture,te),Mt.setOptional(G,Pe,"batchingIdTexture"),Mt.setValue(G,"batchingIdTexture",Pe._indirectTexture,te),Mt.setOptional(G,Pe,"batchingColorTexture"),Pe._colorsTexture!==null&&Mt.setValue(G,"batchingColorTexture",Pe._colorsTexture,te));let Sc=Ft.morphAttributes;Sc.position===void 0&&Sc.normal===void 0&&Sc.color===void 0||lt.update(Pe,Ft,ar),(Vs||Ve.receiveShadow!==Pe.receiveShadow)&&(Ve.receiveShadow=Pe.receiveShadow,Mt.setValue(G,"receiveShadow",Pe.receiveShadow)),Ue.isMeshGouraudMaterial&&Ue.envMap!==null&&(Pi.envMap.value=Nr,Pi.flipEnvMap.value=Nr.isCubeTexture&&Nr.isRenderTargetTexture===!1?-1:1),Ue.isMeshStandardMaterial&&Ue.envMap===null&&Xt.environment!==null&&(Pi.envMapIntensity.value=Xt.environmentIntensity),Vs&&(Mt.setValue(G,"toneMappingExposure",y.toneMappingExposure),Ve.needsLights&&(Ln=Mc,(Wn=Pi).ambientLightColor.needsUpdate=Ln,Wn.lightProbe.needsUpdate=Ln,Wn.directionalLights.needsUpdate=Ln,Wn.directionalLightShadows.needsUpdate=Ln,Wn.pointLights.needsUpdate=Ln,Wn.pointLightShadows.needsUpdate=Ln,Wn.spotLights.needsUpdate=Ln,Wn.spotLightShadows.needsUpdate=Ln,Wn.rectAreaLights.needsUpdate=Ln,Wn.hemisphereLights.needsUpdate=Ln),Pn&&Ue.fog===!0&&Se.refreshFogUniforms(Pi,Pn),Se.refreshMaterialUniforms(Pi,Ue,ie,re,g.state.transmissionRenderTarget[je.id]),as.upload(G,Op(Ve),Pi,te));var Wn,Ln;if(Ue.isShaderMaterial&&Ue.uniformsNeedUpdate===!0&&(as.upload(G,Op(Ve),Pi,te),Ue.uniformsNeedUpdate=!1),Ue.isSpriteMaterial&&Mt.setValue(G,"center",Pe.center),Mt.setValue(G,"modelViewMatrix",Pe.modelViewMatrix),Mt.setValue(G,"normalMatrix",Pe.normalMatrix),Mt.setValue(G,"modelMatrix",Pe.matrixWorld),Ue.isShaderMaterial||Ue.isRawShaderMaterial){let bn=Ue.uniformsGroups;for(let or=0,mt=bn.length;or{function se(){Q.forEach(function(fe){$.get(fe).currentProgram.isReady()&&Q.delete(fe)}),Q.size!==0?setTimeout(se,10):q(T)}H.get("KHR_parallel_shader_compile")!==null?se():setTimeout(se,10)})};let gc=null;function Lp(){sr.stop()}function kp(){sr.start()}let sr=new qm;function bc(T,V,X,Q){if(T.visible===!1)return;if(T.layers.test(V.layers)){if(T.isGroup)X=T.renderOrder;else if(T.isLOD)T.autoUpdate===!0&&T.update(V);else if(T.isLight)g.pushLight(T),T.castShadow&&g.pushShadow(T);else if(T.isSprite){if(!T.frustumCulled||be.intersectsSprite(T)){Q&&P.setFromMatrixPosition(T.matrixWorld).applyMatrix4(N);let se=Xe.update(T),fe=T.material;fe.visible&&f.push(T,se,fe,X,P.z,null)}}else if((T.isMesh||T.isLine||T.isPoints)&&(!T.frustumCulled||be.intersectsObject(T))){let se=Xe.update(T),fe=T.material;if(Q&&(T.boundingSphere!==void 0?(T.boundingSphere===null&&T.computeBoundingSphere(),P.copy(T.boundingSphere.center)):(se.boundingSphere===null&&se.computeBoundingSphere(),P.copy(se.boundingSphere.center)),P.applyMatrix4(T.matrixWorld).applyMatrix4(N)),Array.isArray(fe)){let _e=se.groups;for(let Ae=0,Ie=_e.length;Ae0&&Ka(q,V,X),se.length>0&&Ka(se,V,X),fe.length>0&&Ka(fe,V,X),B.buffers.depth.setTest(!0),B.buffers.depth.setMask(!0),B.buffers.color.setMask(!0),B.setPolygonOffset(!1)}function Up(T,V,X,Q){if((X.isScene===!0?X.overrideMaterial:null)!==null)return;g.state.transmissionRenderTarget[Q.id]===void 0&&(g.state.transmissionRenderTarget[Q.id]=new Rt(1,1,{generateMipmaps:!0,type:H.has("EXT_color_buffer_half_float")||H.has("EXT_color_buffer_float")?Jt:Vi,minFilter:gi,samples:4,stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Oe.workingColorSpace}));let q=g.state.transmissionRenderTarget[Q.id],se=Q.viewport||z;q.setSize(se.z,se.w);let fe=y.getRenderTarget();y.setRenderTarget(q),y.getClearColor(j),Y=y.getClearAlpha(),Y<1&&y.setClearColor(16777215,.5),y.clear(),w&&Ge.render(X);let _e=y.toneMapping;y.toneMapping=0;let Ae=Q.viewport;if(Q.viewport!==void 0&&(Q.viewport=void 0),g.setupLightsView(Q),ue===!0&&bt.setGlobalState(y.clippingPlanes,Q),Ka(T,X,Q),te.updateMultisampleRenderTarget(q),te.updateRenderTargetMipmap(q),H.has("WEBGL_multisampled_render_to_texture")===!1){let Ie=!1;for(let ke=0,Re=V.length;ke0)for(let fe=0,_e=se.length;fe<_e;fe++)Up(Q,q,T,se[fe]);w&&Ge.render(T);for(let fe=0,_e=se.length;fe<_e;fe++){let Ae=se[fe];Dp(f,T,Ae,Ae.viewport)}}else q.length>0&&Up(Q,q,T,V),w&&Ge.render(T),Dp(f,T,V);C!==null&&(te.updateMultisampleRenderTarget(C),te.updateRenderTargetMipmap(C)),T.isScene===!0&&T.onAfterRender(y,T,V),Vn.resetDefaultState(),I=-1,O=null,b.pop(),b.length>0?(g=b[b.length-1],ue===!0&&bt.setGlobalState(y.clippingPlanes,g.state.camera)):g=null,v.pop(),f=v.length>0?v[v.length-1]:null},this.getActiveCubeFace=function(){return _},this.getActiveMipmapLevel=function(){return R},this.getRenderTarget=function(){return C},this.setRenderTargetTextures=function(T,V,X){$.get(T.texture).__webglTexture=V,$.get(T.depthTexture).__webglTexture=X;let Q=$.get(T);Q.__hasExternalTextures=!0,Q.__autoAllocateDepthBuffer=X===void 0,Q.__autoAllocateDepthBuffer||H.has("WEBGL_multisampled_render_to_texture")===!0&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),Q.__useRenderToTexture=!1)},this.setRenderTargetFramebuffer=function(T,V){let X=$.get(T);X.__webglFramebuffer=V,X.__useDefaultFramebuffer=V===void 0},this.setRenderTarget=function(T,V=0,X=0){C=T,_=V,R=X;let Q=!0,q=null,se=!1,fe=!1;if(T){let _e=$.get(T);if(_e.__useDefaultFramebuffer!==void 0)B.bindFramebuffer(G.FRAMEBUFFER,null),Q=!1;else if(_e.__webglFramebuffer===void 0)te.setupRenderTarget(T);else if(_e.__hasExternalTextures)te.rebindTextures(T,$.get(T.texture).__webglTexture,$.get(T.depthTexture).__webglTexture);else if(T.depthBuffer){let ke=T.depthTexture;if(_e.__boundDepthTexture!==ke){if(ke!==null&&$.has(ke)&&(T.width!==ke.image.width||T.height!==ke.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");te.setupDepthRenderbuffer(T)}}let Ae=T.texture;(Ae.isData3DTexture||Ae.isDataArrayTexture||Ae.isCompressedArrayTexture)&&(fe=!0);let Ie=$.get(T).__webglFramebuffer;T.isWebGLCubeRenderTarget?(q=Array.isArray(Ie[V])?Ie[V][X]:Ie[V],se=!0):q=T.samples>0&&te.useMultisampledRTT(T)===!1?$.get(T).__webglMultisampledFramebuffer:Array.isArray(Ie)?Ie[X]:Ie,z.copy(T.viewport),F.copy(T.scissor),W=T.scissorTest}else z.copy(ne).multiplyScalar(ie).floor(),F.copy(ae).multiplyScalar(ie).floor(),W=me;if(B.bindFramebuffer(G.FRAMEBUFFER,q)&&Q&&B.drawBuffers(T,q),B.viewport(z),B.scissor(F),B.setScissorTest(W),se){let _e=$.get(T.texture);G.framebufferTexture2D(G.FRAMEBUFFER,G.COLOR_ATTACHMENT0,G.TEXTURE_CUBE_MAP_POSITIVE_X+V,_e.__webglTexture,X)}else if(fe){let _e=$.get(T.texture),Ae=V||0;G.framebufferTextureLayer(G.FRAMEBUFFER,G.COLOR_ATTACHMENT0,_e.__webglTexture,X||0,Ae)}I=-1},this.readRenderTargetPixels=function(T,V,X,Q,q,se,fe){if(!T||!T.isWebGLRenderTarget)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let _e=$.get(T).__webglFramebuffer;if(T.isWebGLCubeRenderTarget&&fe!==void 0&&(_e=_e[fe]),_e){B.bindFramebuffer(G.FRAMEBUFFER,_e);try{let Ae=T.texture,Ie=Ae.format,ke=Ae.type;if(!ee.textureFormatReadable(Ie))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!ee.textureTypeReadable(ke))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");V>=0&&V<=T.width-Q&&X>=0&&X<=T.height-q&&G.readPixels(V,X,Q,q,Cn.convert(Ie),Cn.convert(ke),se)}finally{let Ae=C!==null?$.get(C).__webglFramebuffer:null;B.bindFramebuffer(G.FRAMEBUFFER,Ae)}}},this.readRenderTargetPixelsAsync=async function(T,V,X,Q,q,se,fe){if(!T||!T.isWebGLRenderTarget)throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let _e=$.get(T).__webglFramebuffer;if(T.isWebGLCubeRenderTarget&&fe!==void 0&&(_e=_e[fe]),_e){let Ae=T.texture,Ie=Ae.format,ke=Ae.type;if(!ee.textureFormatReadable(Ie))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!ee.textureTypeReadable(ke))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");if(V>=0&&V<=T.width-Q&&X>=0&&X<=T.height-q){B.bindFramebuffer(G.FRAMEBUFFER,_e);let Re=G.createBuffer();G.bindBuffer(G.PIXEL_PACK_BUFFER,Re),G.bufferData(G.PIXEL_PACK_BUFFER,se.byteLength,G.STREAM_READ),G.readPixels(V,X,Q,q,Cn.convert(Ie),Cn.convert(ke),0);let Fe=C!==null?$.get(C).__webglFramebuffer:null;B.bindFramebuffer(G.FRAMEBUFFER,Fe);let xt=G.fenceSync(G.SYNC_GPU_COMMANDS_COMPLETE,0);return G.flush(),await function(ut,Tt,pt){return new Promise(function(je,Xt){setTimeout(function Ft(){switch(ut.clientWaitSync(Tt,ut.SYNC_FLUSH_COMMANDS_BIT,0)){case ut.WAIT_FAILED:Xt();break;case ut.TIMEOUT_EXPIRED:setTimeout(Ft,pt);break;default:je()}},pt)})}(G,xt,4),G.bindBuffer(G.PIXEL_PACK_BUFFER,Re),G.getBufferSubData(G.PIXEL_PACK_BUFFER,0,se),G.deleteBuffer(Re),G.deleteSync(xt),se}throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(T,V=null,X=0){T.isTexture!==!0&&(sa("WebGLRenderer: copyFramebufferToTexture function signature has changed."),V=arguments[0]||null,T=arguments[1]);let Q=Math.pow(2,-X),q=Math.floor(T.image.width*Q),se=Math.floor(T.image.height*Q),fe=V!==null?V.x:0,_e=V!==null?V.y:0;te.setTexture2D(T,0),G.copyTexSubImage2D(G.TEXTURE_2D,X,0,0,fe,_e,q,se),B.unbindTexture()},this.copyTextureToTexture=function(T,V,X=null,Q=null,q=0){let se,fe,_e,Ae,Ie,ke,Re,Fe,xt;T.isTexture!==!0&&(sa("WebGLRenderer: copyTextureToTexture function signature has changed."),Q=arguments[0]||null,T=arguments[1],V=arguments[2],q=arguments[3]||0,X=null);let ut=T.isCompressedTexture?T.mipmaps[q]:T.image;X!==null?(se=X.max.x-X.min.x,fe=X.max.y-X.min.y,_e=X.isBox3?X.max.z-X.min.z:1,Ae=X.min.x,Ie=X.min.y,ke=X.isBox3?X.min.z:0):(se=ut.width,fe=ut.height,_e=ut.depth||1,Ae=0,Ie=0,ke=0),Q!==null?(Re=Q.x,Fe=Q.y,xt=Q.z):(Re=0,Fe=0,xt=0);let Tt=Cn.convert(V.format),pt=Cn.convert(V.type),je;V.isData3DTexture?(te.setTexture3D(V,0),je=G.TEXTURE_3D):V.isDataArrayTexture||V.isCompressedArrayTexture?(te.setTexture2DArray(V,0),je=G.TEXTURE_2D_ARRAY):(te.setTexture2D(V,0),je=G.TEXTURE_2D),G.pixelStorei(G.UNPACK_FLIP_Y_WEBGL,V.flipY),G.pixelStorei(G.UNPACK_PREMULTIPLY_ALPHA_WEBGL,V.premultiplyAlpha),G.pixelStorei(G.UNPACK_ALIGNMENT,V.unpackAlignment);let Xt=G.getParameter(G.UNPACK_ROW_LENGTH),Ft=G.getParameter(G.UNPACK_IMAGE_HEIGHT),Ue=G.getParameter(G.UNPACK_SKIP_PIXELS),Pe=G.getParameter(G.UNPACK_SKIP_ROWS),Pn=G.getParameter(G.UNPACK_SKIP_IMAGES);G.pixelStorei(G.UNPACK_ROW_LENGTH,ut.width),G.pixelStorei(G.UNPACK_IMAGE_HEIGHT,ut.height),G.pixelStorei(G.UNPACK_SKIP_PIXELS,Ae),G.pixelStorei(G.UNPACK_SKIP_ROWS,Ie),G.pixelStorei(G.UNPACK_SKIP_IMAGES,ke);let vc=T.isDataArrayTexture||T.isData3DTexture,Gs=V.isDataArrayTexture||V.isData3DTexture;if(T.isRenderTargetTexture||T.isDepthTexture){let Nr=$.get(T),xc=$.get(V),yc=$.get(Nr.__renderTarget),_c=$.get(xc.__renderTarget);B.bindFramebuffer(G.READ_FRAMEBUFFER,yc.__webglFramebuffer),B.bindFramebuffer(G.DRAW_FRAMEBUFFER,_c.__webglFramebuffer);for(let Ci=0;Ci<_e;Ci++)vc&&G.framebufferTextureLayer(G.READ_FRAMEBUFFER,G.COLOR_ATTACHMENT0,$.get(T).__webglTexture,q,ke+Ci),T.isDepthTexture?(Gs&&G.framebufferTextureLayer(G.DRAW_FRAMEBUFFER,G.COLOR_ATTACHMENT0,$.get(V).__webglTexture,q,xt+Ci),G.blitFramebuffer(Ae,Ie,se,fe,Re,Fe,se,fe,G.DEPTH_BUFFER_BIT,G.NEAREST)):Gs?G.copyTexSubImage3D(je,q,Re,Fe,xt+Ci,Ae,Ie,se,fe):G.copyTexSubImage2D(je,q,Re,Fe,xt+Ci,Ae,Ie,se,fe);B.bindFramebuffer(G.READ_FRAMEBUFFER,null),B.bindFramebuffer(G.DRAW_FRAMEBUFFER,null)}else Gs?T.isDataTexture||T.isData3DTexture?G.texSubImage3D(je,q,Re,Fe,xt,se,fe,_e,Tt,pt,ut.data):V.isCompressedArrayTexture?G.compressedTexSubImage3D(je,q,Re,Fe,xt,se,fe,_e,Tt,ut.data):G.texSubImage3D(je,q,Re,Fe,xt,se,fe,_e,Tt,pt,ut):T.isDataTexture?G.texSubImage2D(G.TEXTURE_2D,q,Re,Fe,se,fe,Tt,pt,ut.data):T.isCompressedTexture?G.compressedTexSubImage2D(G.TEXTURE_2D,q,Re,Fe,ut.width,ut.height,Tt,ut.data):G.texSubImage2D(G.TEXTURE_2D,q,Re,Fe,se,fe,Tt,pt,ut);G.pixelStorei(G.UNPACK_ROW_LENGTH,Xt),G.pixelStorei(G.UNPACK_IMAGE_HEIGHT,Ft),G.pixelStorei(G.UNPACK_SKIP_PIXELS,Ue),G.pixelStorei(G.UNPACK_SKIP_ROWS,Pe),G.pixelStorei(G.UNPACK_SKIP_IMAGES,Pn),q===0&&V.generateMipmaps&&G.generateMipmap(je),B.unbindTexture()},this.copyTextureToTexture3D=function(T,V,X=null,Q=null,q=0){return T.isTexture!==!0&&(sa("WebGLRenderer: copyTextureToTexture3D function signature has changed."),X=arguments[0]||null,Q=arguments[1]||null,T=arguments[2],V=arguments[3],q=arguments[4]||0),sa('WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.'),this.copyTextureToTexture(T,V,X,Q,q)},this.initRenderTarget=function(T){$.get(T).__webglFramebuffer===void 0&&te.setupRenderTarget(T)},this.initTexture=function(T){T.isCubeTexture?te.setTextureCube(T,0):T.isData3DTexture?te.setTexture3D(T,0):T.isDataArrayTexture||T.isCompressedArrayTexture?te.setTexture2DArray(T,0):te.setTexture2D(T,0),B.unbindTexture()},this.resetState=function(){_=0,R=0,C=null,B.reset(),Vn.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return ps}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorspace=Oe._getDrawingBufferColorSpace(e),t.unpackColorSpace=Oe._getUnpackColorSpace()}},sl=class r{constructor(e,t=25e-5){this.isFogExp2=!0,this.name="",this.color=new oe(e),this.density=t}clone(){return new r(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}};var al=class extends nt{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new Kn,this.environmentIntensity=1,this.environmentRotation=new Kn,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){let t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}},va=class{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=ou,this.updateRanges=[],this.version=0,this.uuid=wn()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,n){e*=this.stride,n*=t.stride;for(let i=0,s=this.stride;i=s.length&&s.push({start:-1,count:-1,z:-1,index:-1});let o=s[this.index];a.push(o),this.index++,o.start=e,o.count=t,o.z=n,o.index=i}reset(){this.list.length=0,this.index=0}},r_=new Ee,s_=new oe(1,1,1),a_=new bs,o_=new Gt,l_=new nn,c_=new S,h_=new S,u_=new S,d_=new wu,p_=new Je;var _a=class extends un{static get type(){return"LineBasicMaterial"}constructor(e){super(),this.isLineBasicMaterial=!0,this.color=new oe(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}},hl=new S,ul=new S,am=new Ee,ia=new ms,ko=new nn,Sh=new S,om=new S,xs=class extends nt{constructor(e=new qe,t=new _a){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[0];for(let i=1,s=t.count;i0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let i=0,s=n.length;in)return;Sh.applyMatrix4(r.matrixWorld);let o=e.ray.origin.distanceTo(Sh);return oe.far?void 0:{distance:o,point:om.clone().applyMatrix4(r.matrixWorld),index:i,face:null,faceIndex:null,barycoord:null,object:r}}var lm=new S,cm=new S,dl=class extends xs{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[];for(let i=0,s=t.count;i0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let i=0,s=n.length;ii.far)return;s.push({distance:c,distanceToRay:Math.sqrt(o),point:l,index:e,face:null,faceIndex:null,barycoord:null,object:a})}}var Ma=class extends Ut{constructor(e,t,n,i,s,a,o,l,c){super(e,t,n,i,s,a,o,l,c),this.isCanvasTexture=!0,this.needsUpdate=!0}},En=class{constructor(){this.type="Curve",this.arcLengthDivisions=200}getPoint(){return console.warn("THREE.Curve: .getPoint() not implemented."),null}getPointAt(e,t){let n=this.getUtoTmapping(e);return this.getPoint(n,t)}getPoints(e=5){let t=[];for(let n=0;n<=e;n++)t.push(this.getPoint(n/e));return t}getSpacedPoints(e=5){let t=[];for(let n=0;n<=e;n++)t.push(this.getPointAt(n/e));return t}getLength(){let e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;let t=[],n,i=this.getPoint(0),s=0;t.push(0);for(let a=1;a<=e;a++)n=this.getPoint(a/e),s+=n.distanceTo(i),t.push(s),i=n;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t){let n=this.getLengths(),i=0,s=n.length,a;a=t||e*n[s-1];let o,l=0,c=s-1;for(;l<=c;)if(i=Math.floor(l+(c-l)/2),o=n[i]-a,o<0)l=i+1;else{if(!(o>0)){c=i;break}c=i-1}if(i=c,n[i]===a)return i/(s-1);let h=n[i];return(i+(a-h)/(n[i+1]-h))/(s-1)}getTangent(e,t){let i=e-1e-4,s=e+1e-4;i<0&&(i=0),s>1&&(s=1);let a=this.getPoint(i),o=this.getPoint(s),l=t||(a.isVector2?new Z:new S);return l.copy(o).sub(a).normalize(),l}getTangentAt(e,t){let n=this.getUtoTmapping(e);return this.getTangent(n,t)}computeFrenetFrames(e,t){let n=new S,i=[],s=[],a=[],o=new S,l=new Ee;for(let p=0;p<=e;p++){let m=p/e;i[p]=this.getTangentAt(m,new S)}s[0]=new S,a[0]=new S;let c=Number.MAX_VALUE,h=Math.abs(i[0].x),u=Math.abs(i[0].y),d=Math.abs(i[0].z);h<=c&&(c=h,n.set(1,0,0)),u<=c&&(c=u,n.set(0,1,0)),d<=c&&n.set(0,0,1),o.crossVectors(i[0],n).normalize(),s[0].crossVectors(i[0],o),a[0].crossVectors(i[0],s[0]);for(let p=1;p<=e;p++){if(s[p]=s[p-1].clone(),a[p]=a[p-1].clone(),o.crossVectors(i[p-1],i[p]),o.length()>Number.EPSILON){o.normalize();let m=Math.acos(Et(i[p-1].dot(i[p]),-1,1));s[p].applyMatrix4(l.makeRotationAxis(o,m))}a[p].crossVectors(i[p],s[p])}if(t===!0){let p=Math.acos(Et(s[0].dot(s[e]),-1,1));p/=e,i[0].dot(o.crossVectors(s[0],s[e]))>0&&(p=-p);for(let m=1;m<=e;m++)s[m].applyMatrix4(l.makeRotationAxis(i[m],p*m)),a[m].crossVectors(i[m],s[m])}return{tangents:i,normals:s,binormals:a}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){let e={metadata:{version:4.6,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}},Sa=class extends En{constructor(e=0,t=0,n=1,i=1,s=0,a=2*Math.PI,o=!1,l=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=n,this.yRadius=i,this.aStartAngle=s,this.aEndAngle=a,this.aClockwise=o,this.aRotation=l}getPoint(e,t=new Z){let n=t,i=2*Math.PI,s=this.aEndAngle-this.aStartAngle,a=Math.abs(s)i;)s-=i;s0?0:(Math.floor(Math.abs(c)/s)+1)*s:h===0&&c===s-1&&(c=s-2,h=1),this.closed||c>0?o=i[(c-1)%s]:(Oo.subVectors(i[0],i[1]).add(i[0]),o=Oo);let u=i[c%s],d=i[(c+1)%s];if(this.closed||c+2i.length-2?i.length-1:a+1],u=i[a>i.length-3?i.length-1:a+2];return n.set(dm(o,l.x,c.x,h.x,u.x),dm(o,l.y,c.y,h.y,u.y)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t=n){let a=i[s]-n,o=this.curves[s],l=o.getLength(),c=l===0?0:1-a/l;return o.getPointAt(c,t)}s++}return null}getLength(){let e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;let e=[],t=0;for(let n=0,i=this.curves.length;n1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,n=e.curves.length;t0){let u=c.getPoint(0);u.equals(this.currentPoint)||this.lineTo(u.x,u.y)}this.curves.push(c);let h=c.getPoint(1);return this.currentPoint.copy(h),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){let e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}},yl=class r extends qe{constructor(e=[new Z(0,-.5),new Z(.5,0),new Z(0,.5)],t=12,n=0,i=2*Math.PI){super(),this.type="LatheGeometry",this.parameters={points:e,segments:t,phiStart:n,phiLength:i},t=Math.floor(t),i=Et(i,0,2*Math.PI);let s=[],a=[],o=[],l=[],c=[],h=1/t,u=new S,d=new Z,p=new S,m=new S,x=new S,f=0,g=0;for(let v=0;v<=e.length-1;v++)switch(v){case 0:f=e[v+1].x-e[v].x,g=e[v+1].y-e[v].y,p.x=1*g,p.y=-f,p.z=0*g,x.copy(p),p.normalize(),l.push(p.x,p.y,p.z);break;case e.length-1:l.push(x.x,x.y,x.z);break;default:f=e[v+1].x-e[v].x,g=e[v+1].y-e[v].y,p.x=1*g,p.y=-f,p.z=0*g,m.copy(p),p.x+=x.x,p.y+=x.y,p.z+=x.z,p.normalize(),l.push(p.x,p.y,p.z),x.copy(m)}for(let v=0;v<=t;v++){let b=n+v*h*i,y=Math.sin(b),M=Math.cos(b);for(let _=0;_<=e.length-1;_++){u.x=e[_].x*y,u.y=e[_].y,u.z=e[_].x*M,a.push(u.x,u.y,u.z),d.x=v/t,d.y=_/(e.length-1),o.push(d.x,d.y);let R=l[3*_+0]*y,C=l[3*_+1],I=l[3*_+0]*M;c.push(R,C,I)}}for(let v=0;v0||C!==0)&&(h.push(I,O,F),M+=3),(t>0||C!==s-1)&&(h.push(O,z,F),M+=3)}c.addGroup(g,M,0),g+=M})(),a===!1&&(e>0&&v(!0),t>0&&v(!1)),this.setIndex(h),this.setAttribute("position",new we(u,3)),this.setAttribute("normal",new we(d,3)),this.setAttribute("uv",new we(p,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new r(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}},Ta=class r extends $n{constructor(e=1,t=1,n=32,i=1,s=!1,a=0,o=2*Math.PI){super(0,e,t,n,i,s,a,o),this.type="ConeGeometry",this.parameters={radius:e,height:t,radialSegments:n,heightSegments:i,openEnded:s,thetaStart:a,thetaLength:o}}static fromJSON(e){return new r(e.radius,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}},Mr=class r extends qe{constructor(e=[],t=[],n=1,i=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:e,indices:t,radius:n,detail:i};let s=[],a=[];function o(d,p,m,x){let f=x+1,g=[];for(let v=0;v<=f;v++){g[v]=[];let b=d.clone().lerp(m,v/f),y=p.clone().lerp(m,v/f),M=f-v;for(let _=0;_<=M;_++)g[v][_]=_===0&&v===f?b:b.clone().lerp(y,_/M)}for(let v=0;v.9&&b<.1&&(x<.2&&(a[m+0]+=1),f<.2&&(a[m+2]+=1),g<.2&&(a[m+4]+=1))}}()}(),this.setAttribute("position",new we(s,3)),this.setAttribute("normal",new we(s.slice(),3)),this.setAttribute("uv",new we(a,2)),i===0?this.computeVertexNormals():this.normalizeNormals()}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new r(e.vertices,e.indices,e.radius,e.details)}},Ea=class r extends Mr{constructor(e=1,t=0){let n=(1+Math.sqrt(5))/2,i=1/n;super([-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-i,-n,0,-i,n,0,i,-n,0,i,n,-i,-n,0,-i,n,0,i,-n,0,i,n,0,-n,0,-i,n,0,-i,-n,0,i,n,0,i],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],e,t),this.type="DodecahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new r(e.radius,e.detail)}},zo=new S,Fo=new S,Ah=new S,Bo=new zi,Lu=class extends qe{constructor(e=null,t=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:e,thresholdAngle:t},e!==null){let i=Math.pow(10,4),s=Math.cos(rs*t),a=e.getIndex(),o=e.getAttribute("position"),l=a?a.count:o.count,c=[0,0,0],h=["a","b","c"],u=new Array(3),d={},p=[];for(let m=0;m80*t){o=c=r[0],l=h=r[1];for(let m=t;mc&&(c=u),d>h&&(h=d);p=Math.max(c-o,h-l),p=p!==0?32767/p:0}return Aa(s,a,t,o,l,p,0),a};function pm(r,e,t,n,i){let s,a;if(i===function(o,l,c,h){let u=0;for(let d=l,p=c-h;d0)for(s=e;s=e;s-=n)a=fm(s,r[s],r[s+1],a);return a&&Ol(a,a.next)&&(Ca(a),a=a.next),a}function Sr(r,e){if(!r)return r;e||(e=r);let t,n=r;do if(t=!1,n.steiner||!Ol(n,n.next)&&vt(n.prev,n,n.next)!==0)n=n.next;else{if(Ca(n),n=e=n.prev,n===n.next)break;t=!0}while(t||n!==e);return e}function Aa(r,e,t,n,i,s,a){if(!r)return;!a&&s&&function(h,u,d,p){let m=h;do m.z===0&&(m.z=ku(m.x,m.y,u,d,p)),m.prevZ=m.prev,m.nextZ=m.next,m=m.next;while(m!==h);m.prevZ.nextZ=null,m.prevZ=null,function(x){let f,g,v,b,y,M,_,R,C=1;do{for(g=x,x=null,y=null,M=0;g;){for(M++,v=g,_=0,f=0;f0||R>0&&v;)_!==0&&(R===0||!v||g.z<=v.z)?(b=g,g=g.nextZ,_--):(b=v,v=v.nextZ,R--),y?y.nextZ=b:x=b,b.prevZ=y,y=b;g=v}y.nextZ=null,C*=2}while(M>1)}(m)}(r,n,i,s);let o,l,c=r;for(;r.prev!==r.next;)if(o=r.prev,l=r.next,s?fx(r,n,i,s):px(r))e.push(o.i/t|0),e.push(r.i/t|0),e.push(l.i/t|0),Ca(r),r=l.next,c=l.next;else if((r=l)===c){a?a===1?Aa(r=mx(Sr(r),e,t),e,t,n,i,s,2):a===2&&gx(r,e,t,n,i,s):Aa(Sr(r),e,t,n,i,s,1);break}}function px(r){let e=r.prev,t=r,n=r.next;if(vt(e,t,n)>=0)return!1;let i=e.x,s=t.x,a=n.x,o=e.y,l=t.y,c=n.y,h=is?i>a?i:a:s>a?s:a,p=o>l?o>c?o:c:l>c?l:c,m=n.next;for(;m!==e;){if(m.x>=h&&m.x<=d&&m.y>=u&&m.y<=p&&is(i,o,s,l,a,c,m.x,m.y)&&vt(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function fx(r,e,t,n){let i=r.prev,s=r,a=r.next;if(vt(i,s,a)>=0)return!1;let o=i.x,l=s.x,c=a.x,h=i.y,u=s.y,d=a.y,p=ol?o>c?o:c:l>c?l:c,f=h>u?h>d?h:d:u>d?u:d,g=ku(p,m,e,t,n),v=ku(x,f,e,t,n),b=r.prevZ,y=r.nextZ;for(;b&&b.z>=g&&y&&y.z<=v;){if(b.x>=p&&b.x<=x&&b.y>=m&&b.y<=f&&b!==i&&b!==a&&is(o,h,l,u,c,d,b.x,b.y)&&vt(b.prev,b,b.next)>=0||(b=b.prevZ,y.x>=p&&y.x<=x&&y.y>=m&&y.y<=f&&y!==i&&y!==a&&is(o,h,l,u,c,d,y.x,y.y)&&vt(y.prev,y,y.next)>=0))return!1;y=y.nextZ}for(;b&&b.z>=g;){if(b.x>=p&&b.x<=x&&b.y>=m&&b.y<=f&&b!==i&&b!==a&&is(o,h,l,u,c,d,b.x,b.y)&&vt(b.prev,b,b.next)>=0)return!1;b=b.prevZ}for(;y&&y.z<=v;){if(y.x>=p&&y.x<=x&&y.y>=m&&y.y<=f&&y!==i&&y!==a&&is(o,h,l,u,c,d,y.x,y.y)&&vt(y.prev,y,y.next)>=0)return!1;y=y.nextZ}return!0}function mx(r,e,t){let n=r;do{let i=n.prev,s=n.next.next;!Ol(i,s)&&Zm(i,n,n.next,s)&&Ra(i,s)&&Ra(s,i)&&(e.push(i.i/t|0),e.push(n.i/t|0),e.push(s.i/t|0),Ca(n),Ca(n.next),n=r=s),n=n.next}while(n!==r);return Sr(n)}function gx(r,e,t,n,i,s){let a=r;do{let o=a.next.next;for(;o!==a.prev;){if(a.i!==o.i&&_x(a,o)){let l=Jm(a,o);return a=Sr(a,a.next),l=Sr(l,l.next),Aa(a,e,t,n,i,s,0),void Aa(l,e,t,n,i,s,0)}o=o.next}a=a.next}while(a!==r)}function bx(r,e){return r.x-e.x}function vx(r,e){let t=function(i,s){let a,o=s,l=-1/0,c=i.x,h=i.y;do{if(h<=o.y&&h>=o.next.y&&o.next.y!==o.y){let f=o.x+(h-o.y)*(o.next.x-o.x)/(o.next.y-o.y);if(f<=c&&f>l&&(l=f,a=o.x=o.x&&o.x>=d&&c!==o.x&&is(ha.x||o.x===a.x&&xx(a,o)))&&(a=o,x=m)),o=o.next;while(o!==u);return a}(r,e);if(!t)return e;let n=Jm(t,r);return Sr(n,n.next),Sr(t,t.next)}function xx(r,e){return vt(r.prev,r,e.prev)<0&&vt(e.next,r,r.next)<0}function ku(r,e,t,n,i){return(r=1431655765&((r=858993459&((r=252645135&((r=16711935&((r=(r-t)*i|0)|r<<8))|r<<4))|r<<2))|r<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function yx(r){let e=r,t=r;do(e.x=(r-a)*(s-o)&&(r-a)*(n-o)>=(t-a)*(e-o)&&(t-a)*(s-o)>=(i-a)*(n-o)}function _x(r,e){return r.next.i!==e.i&&r.prev.i!==e.i&&!function(t,n){let i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==n.i&&i.next.i!==n.i&&Zm(i,i.next,t,n))return!0;i=i.next}while(i!==t);return!1}(r,e)&&(Ra(r,e)&&Ra(e,r)&&function(t,n){let i=t,s=!1,a=(t.x+n.x)/2,o=(t.y+n.y)/2;do i.y>o!=i.next.y>o&&i.next.y!==i.y&&a<(i.next.x-i.x)*(o-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next;while(i!==t);return s}(r,e)&&(vt(r.prev,r,e.prev)||vt(r,e.prev,e))||Ol(r,e)&&vt(r.prev,r,r.next)>0&&vt(e.prev,e,e.next)>0)}function vt(r,e,t){return(e.y-r.y)*(t.x-e.x)-(e.x-r.x)*(t.y-e.y)}function Ol(r,e){return r.x===e.x&&r.y===e.y}function Zm(r,e,t,n){let i=Go(vt(r,e,t)),s=Go(vt(r,e,n)),a=Go(vt(t,n,r)),o=Go(vt(t,n,e));return i!==s&&a!==o||!(i!==0||!Ho(r,t,e))||!(s!==0||!Ho(r,n,e))||!(a!==0||!Ho(t,r,n))||!(o!==0||!Ho(t,e,n))}function Ho(r,e,t){return e.x<=Math.max(r.x,t.x)&&e.x>=Math.min(r.x,t.x)&&e.y<=Math.max(r.y,t.y)&&e.y>=Math.min(r.y,t.y)}function Go(r){return r>0?1:r<0?-1:0}function Ra(r,e){return vt(r.prev,r,r.next)<0?vt(r,e,r.next)>=0&&vt(r,r.prev,e)>=0:vt(r,e,r.prev)<0||vt(r,r.next,e)<0}function Jm(r,e){let t=new Du(r.i,r.x,r.y),n=new Du(e.i,e.x,e.y),i=r.next,s=e.prev;return r.next=e,e.prev=r,t.next=i,i.prev=t,n.next=t,t.prev=n,s.next=n,n.prev=s,n}function fm(r,e,t,n){let i=new Du(r,e,t);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Ca(r){r.next.prev=r.prev,r.prev.next=r.next,r.prevZ&&(r.prevZ.nextZ=r.nextZ),r.nextZ&&(r.nextZ.prevZ=r.prevZ)}function Du(r,e,t){this.i=r,this.x=e,this.y=t,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}var Gi=class r{static area(e){let t=e.length,n=0;for(let i=t-1,s=0;s2&&r[e-1].equals(r[0])&&r.pop()}function gm(r,e){for(let t=0;tNumber.EPSILON){let de=Math.sqrt(te),Me=Math.sqrt(J*J+$*$),Ce=P.x-B/de,Xe=P.y+ee/de,ze=((D.x-$/Me-Ce)*$-(D.y+J/Me-Xe)*J)/(ee*$-B*J);w=Ce+ee*ze-U.x,k=Xe+B*ze-U.y;let Se=w*w+k*k;if(Se<=2)return new Z(w,k);H=Math.sqrt(Se/2)}else{let de=!1;ee>Number.EPSILON?J>Number.EPSILON&&(de=!0):ee<-Number.EPSILON?J<-Number.EPSILON&&(de=!0):Math.sign(B)===Math.sign($)&&(de=!0),de?(w=-B,k=ee,H=Math.sqrt(te)):(w=ee,k=B,H=Math.sqrt(te/2))}return new Z(w/H,k/H)}let ie=[];for(let U=0,P=W.length,D=P-1,w=U+1;U=0;U--){let P=U/f,D=p*Math.cos(P*Math.PI/2),w=m*Math.sin(P*Math.PI/2)+x;for(let k=0,H=W.length;k=0;){let w=D,k=D-1;k<0&&(k=U.length-1);for(let H=0,ee=h+2*f;H0)&&p.push(b,y,_),(g!==n-1||l0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}};function Vo(r,e,t){return!r||!t&&r.constructor===e?r:typeof e.BYTES_PER_ELEMENT=="number"?new e(r):Array.prototype.slice.call(r)}function Sx(r){return ArrayBuffer.isView(r)&&!(r instanceof DataView)}function wx(r){let e=r.length,t=new Array(e);for(let n=0;n!==e;++n)t[n]=n;return t.sort(function(n,i){return r[n]-r[i]}),t}function vm(r,e,t){let n=r.length,i=new r.constructor(n);for(let s=0,a=0;a!==n;++s){let o=t[s]*e;for(let l=0;l!==e;++l)i[a++]=r[o+l]}return i}function Qm(r,e,t,n){let i=1,s=r[0];for(;s!==void 0&&s[n]===void 0;)s=r[i++];if(s===void 0)return;let a=s[n];if(a!==void 0)if(Array.isArray(a))do a=s[n],a!==void 0&&(e.push(s.time),t.push.apply(t,a)),s=r[i++];while(s!==void 0);else if(a.toArray!==void 0)do a=s[n],a!==void 0&&(e.push(s.time),a.toArray(t,t.length)),s=r[i++];while(s!==void 0);else do a=s[n],a!==void 0&&(e.push(s.time),t.push(a)),s=r[i++];while(s!==void 0)}var Xi=class{constructor(e,t,n,i){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=i!==void 0?i:new t.constructor(n),this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,i=t[n],s=t[n-1];e:{t:{let a;n:{i:if(!(e=s)break e;{let o=t[1];e=s)break t}a=n,n=0}}for(;n>>1;et;)--a;if(++a,s!==0||a!==i){s>=a&&(a=Math.max(a,1),s=a-1);let o=this.getValueSize();this.times=n.slice(s,a),this.values=this.values.slice(s*o,a*o)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!=0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);let n=this.times,i=this.values,s=n.length;s===0&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let a=null;for(let o=0;o!==s;o++){let l=n[o];if(typeof l=="number"&&isNaN(l)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,o,l),e=!1;break}if(a!==null&&a>l){console.error("THREE.KeyframeTrack: Out of order keys.",this,o,l,a),e=!1;break}a=l}if(i!==void 0&&Sx(i))for(let o=0,l=i.length;o!==l;++o){let c=i[o];if(isNaN(c)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,o,c),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),i=this.getInterpolation()===Yc,s=e.length-1,a=1;for(let o=1;o0){e[a]=e[s];for(let o=s*n,l=a*n,c=0;c!==n;++c)t[l+c]=t[o+c];++a}return a!==e.length?(this.times=e.slice(0,a),this.values=t.slice(0,a*n)):(this.times=e,this.values=t),this}clone(){let e=this.times.slice(),t=this.values.slice(),n=new this.constructor(this.name,e,t);return n.createInterpolant=this.createInterpolant,n}};Tn.prototype.TimeBufferType=Float32Array,Tn.prototype.ValueBufferType=Float32Array,Tn.prototype.DefaultInterpolation=ds;var Fi=class extends Tn{constructor(e,t,n){super(e,t,n)}};Fi.prototype.ValueTypeName="bool",Fi.prototype.ValueBufferType=Array,Fi.prototype.DefaultInterpolation=us,Fi.prototype.InterpolantFactoryMethodLinear=void 0,Fi.prototype.InterpolantFactoryMethodSmooth=void 0;var wl=class extends Tn{};wl.prototype.ValueTypeName="color";var yi=class extends Tn{};yi.prototype.ValueTypeName="number";var qu=class extends Xi{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){let s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=(n-t)/(i-t),c=e*o;for(let h=c+o;c!==h;c+=4)_t.slerpFlat(s,0,a,c-o,a,c,l);return s}},Zn=class extends Tn{InterpolantFactoryMethodLinear(e){return new qu(this.times,this.values,this.getValueSize(),e)}};Zn.prototype.ValueTypeName="quaternion",Zn.prototype.InterpolantFactoryMethodSmooth=void 0;var Bi=class extends Tn{constructor(e,t,n){super(e,t,n)}};Bi.prototype.ValueTypeName="string",Bi.prototype.ValueBufferType=Array,Bi.prototype.DefaultInterpolation=us,Bi.prototype.InterpolantFactoryMethodLinear=void 0,Bi.prototype.InterpolantFactoryMethodSmooth=void 0;var Jn=class extends Tn{};Jn.prototype.ValueTypeName="vector";var wr=class{constructor(e="",t=-1,n=[],i=2500){this.name=e,this.tracks=n,this.duration=t,this.blendMode=i,this.uuid=wn(),this.duration<0&&this.resetDuration()}static parse(e){let t=[],n=e.tracks,i=1/(e.fps||1);for(let a=0,o=n.length;a!==o;++a)t.push(Tx(n[a]).scale(i));let s=new this(e.name,e.duration,t,e.blendMode);return s.uuid=e.uuid,s}static toJSON(e){let t=[],n=e.tracks,i={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode};for(let s=0,a=n.length;s!==a;++s)t.push(Tn.toJSON(n[s]));return i}static CreateFromMorphTargetSequence(e,t,n,i){let s=t.length,a=[];for(let o=0;o1){let u=h[1],d=i[u];d||(i[u]=d=[]),d.push(c)}}let a=[];for(let o in i)a.push(this.CreateFromMorphTargetSequence(o,i[o],t,n));return a}static parseAnimation(e,t){if(!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;let n=function(h,u,d,p,m){if(d.length!==0){let x=[],f=[];Qm(d,x,f,p),x.length!==0&&m.push(new h(u,x,f))}},i=[],s=e.name||"default",a=e.fps||30,o=e.blendMode,l=e.length||-1,c=e.hierarchy||[];for(let h=0;h{t&&t(s),this.manager.itemEnd(e)},0),s;if(fi[e]!==void 0)return void fi[e].push({onLoad:t,onProgress:n,onError:i});fi[e]=[],fi[e].push({onLoad:t,onProgress:n,onError:i});let a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),o=this.mimeType,l=this.responseType;fetch(a).then(c=>{if(c.status===200||c.status===0){if(c.status===0&&console.warn("THREE.FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||c.body===void 0||c.body.getReader===void 0)return c;let h=fi[e],u=c.body.getReader(),d=c.headers.get("X-File-Size")||c.headers.get("Content-Length"),p=d?parseInt(d):0,m=p!==0,x=0,f=new ReadableStream({start(g){(function v(){u.read().then(({done:b,value:y})=>{if(b)g.close();else{x+=y.byteLength;let M=new ProgressEvent("progress",{lengthComputable:m,loaded:x,total:p});for(let _=0,R=h.length;_{g.error(b)})})()}});return new Response(f)}throw new Yu(`fetch for "${c.url}" responded with ${c.status}: ${c.statusText}`,c)}).then(c=>{switch(l){case"arraybuffer":return c.arrayBuffer();case"blob":return c.blob();case"document":return c.text().then(h=>new DOMParser().parseFromString(h,o));case"json":return c.json();default:if(o===void 0)return c.text();{let h=/charset="?([^;"\s]*)"?/i.exec(o),u=h&&h[1]?h[1].toLowerCase():void 0,d=new TextDecoder(u);return c.arrayBuffer().then(p=>d.decode(p))}}}).then(c=>{Hi.add(e,c);let h=fi[e];delete fi[e];for(let u=0,d=h.length;u{let h=fi[e];if(h===void 0)throw this.manager.itemError(e),c;delete fi[e];for(let u=0,d=h.length;u{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}};var Ku=class extends _i{constructor(e){super(e)}load(e,t,n,i){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let s=this,a=Hi.get(e);if(a!==void 0)return s.manager.itemStart(e),setTimeout(function(){t&&t(a),s.manager.itemEnd(e)},0),a;let o=ma("img");function l(){h(),Hi.add(e,this),t&&t(this),s.manager.itemEnd(e)}function c(u){h(),i&&i(u),s.manager.itemError(e),s.manager.itemEnd(e)}function h(){o.removeEventListener("load",l,!1),o.removeEventListener("error",c,!1)}return o.addEventListener("load",l,!1),o.addEventListener("error",c,!1),e.slice(0,5)!=="data:"&&this.crossOrigin!==void 0&&(o.crossOrigin=this.crossOrigin),s.manager.itemStart(e),o.src=e,o}};var Yi=class extends _i{constructor(e){super(e)}load(e,t,n,i){let s=new Ut,a=new Ku(this.manager);return a.setCrossOrigin(this.crossOrigin),a.setPath(this.path),a.load(e,function(o){s.image=o,s.needsUpdate=!0,t!==void 0&&t(s)},n,i),s}},ys=class extends nt{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new oe(e),this.intensity=t}dispose(){}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){let t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,this.groundColor!==void 0&&(t.object.groundColor=this.groundColor.getHex()),this.distance!==void 0&&(t.object.distance=this.distance),this.angle!==void 0&&(t.object.angle=this.angle),this.decay!==void 0&&(t.object.decay=this.decay),this.penumbra!==void 0&&(t.object.penumbra=this.penumbra),this.shadow!==void 0&&(t.object.shadow=this.shadow.toJSON()),this.target!==void 0&&(t.object.target=this.target.uuid),t}},Tl=class extends ys{constructor(e,t,n){super(e,n),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(nt.DEFAULT_UP),this.updateMatrix(),this.groundColor=new oe(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}},Rh=new Ee,xm=new S,ym=new S,La=class{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Z(512,512),this.map=null,this.mapPass=null,this.matrix=new Ee,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new bs,this._frameExtents=new Z(1,1),this._viewportCount=1,this._viewports=[new Ze(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){let t=this.camera,n=this.matrix;xm.setFromMatrixPosition(e.matrixWorld),t.position.copy(xm),ym.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(ym),t.updateMatrixWorld(),Rh.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Rh),n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(Rh)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.mapSize.copy(e.mapSize),this}clone(){return new this.constructor().copy(this)}toJSON(){let e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),this.mapSize.x===512&&this.mapSize.y===512||(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}},$u=class extends La{constructor(){super(new At(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1}updateMatrices(e){let t=this.camera,n=2*fs*e.angle*this.focus,i=this.mapSize.width/this.mapSize.height,s=e.distance||t.far;n===t.fov&&i===t.aspect&&s===t.far||(t.fov=n,t.aspect=i,t.far=s,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}},El=class extends ys{constructor(e,t,n=0,i=Math.PI/3,s=0,a=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(nt.DEFAULT_UP),this.updateMatrix(),this.target=new nt,this.distance=n,this.angle=i,this.penumbra=s,this.decay=a,this.map=null,this.shadow=new $u}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}},_m=new Ee,ra=new S,Ch=new S,Zu=class extends La{constructor(){super(new At(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new Z(4,2),this._viewportCount=6,this._viewports=[new Ze(2,1,1,1),new Ze(0,1,1,1),new Ze(3,1,1,1),new Ze(1,1,1,1),new Ze(3,0,1,1),new Ze(1,0,1,1)],this._cubeDirections=[new S(1,0,0),new S(-1,0,0),new S(0,0,1),new S(0,0,-1),new S(0,1,0),new S(0,-1,0)],this._cubeUps=[new S(0,1,0),new S(0,1,0),new S(0,1,0),new S(0,1,0),new S(0,0,1),new S(0,0,-1)]}updateMatrices(e,t=0){let n=this.camera,i=this.matrix,s=e.distance||n.far;s!==n.far&&(n.far=s,n.updateProjectionMatrix()),ra.setFromMatrixPosition(e.matrixWorld),n.position.copy(ra),Ch.copy(n.position),Ch.add(this._cubeDirections[t]),n.up.copy(this._cubeUps[t]),n.lookAt(Ch),n.updateMatrixWorld(),i.makeTranslation(-ra.x,-ra.y,-ra.z),_m.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),this._frustum.setFromProjectionMatrix(_m)}},Al=class extends ys{constructor(e,t,n=0,i=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=n,this.decay=i,this.shadow=new Zu}get power(){return 4*this.intensity*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}},Ju=class extends La{constructor(){super(new ji(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}},_s=class extends ys{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(nt.DEFAULT_UP),this.updateMatrix(),this.target=new nt,this.shadow=new Ju}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}};var Ki=class{static decodeText(e){if(console.warn("THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead."),typeof TextDecoder<"u")return new TextDecoder().decode(e);let t="";for(let n=0,i=e.length;n"u"&&console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&console.warn("THREE.ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"}}setOptions(e){return this.options=e,this}load(e,t,n,i){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let s=this,a=Hi.get(e);if(a!==void 0)return s.manager.itemStart(e),a.then?void a.then(c=>{t&&t(c),s.manager.itemEnd(e)}).catch(c=>{i&&i(c)}):(setTimeout(function(){t&&t(a),s.manager.itemEnd(e)},0),a);let o={};o.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",o.headers=this.requestHeader;let l=fetch(e,o).then(function(c){return c.blob()}).then(function(c){return createImageBitmap(c,Object.assign(s.options,{colorSpaceConversion:"none"}))}).then(function(c){return Hi.add(e,c),t&&t(c),s.manager.itemEnd(e),c}).catch(function(c){i&&i(c),Hi.remove(e),s.manager.itemError(e),s.manager.itemEnd(e)});Hi.add(e,l),s.manager.itemStart(e)}};var m_=new Ee,g_=new Ee,b_=new Ee;var Cl=class{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=Mm(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){let t=Mm();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}};function Mm(){return performance.now()}var v_=new S,x_=new _t,y_=new S,__=new S;var M_=new S,S_=new _t,w_=new S,T_=new S;var Qu=class{constructor(e,t,n){let i,s,a;switch(this.binding=e,this.valueSize=n,t){case"quaternion":i=this._slerp,s=this._slerpAdditive,a=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(6*n),this._workIndex=5;break;case"string":case"bool":i=this._select,s=this._select,a=this._setAdditiveIdentityOther,this.buffer=new Array(5*n);break;default:i=this._lerp,s=this._lerpAdditive,a=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(5*n)}this._mixBufferRegion=i,this._mixBufferRegionAdditive=s,this._setIdentity=a,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(e,t){let n=this.buffer,i=this.valueSize,s=e*i+i,a=this.cumulativeWeight;if(a===0){for(let o=0;o!==i;++o)n[s+o]=n[o];a=t}else{a+=t;let o=t/a;this._mixBufferRegion(n,s,0,o,i)}this.cumulativeWeight=a}accumulateAdditive(e){let t=this.buffer,n=this.valueSize,i=n*this._addIndex;this.cumulativeWeightAdditive===0&&this._setIdentity(),this._mixBufferRegionAdditive(t,i,0,e,n),this.cumulativeWeightAdditive+=e}apply(e){let t=this.valueSize,n=this.buffer,i=e*t+t,s=this.cumulativeWeight,a=this.cumulativeWeightAdditive,o=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,s<1){let l=t*this._origIndex;this._mixBufferRegion(n,i,l,1-s,t)}a>0&&this._mixBufferRegionAdditive(n,i,this._addIndex*t,1,t);for(let l=t,c=t+t;l!==c;++l)if(n[l]!==n[l+t]){o.setValue(n,i);break}}saveOriginalState(){let e=this.binding,t=this.buffer,n=this.valueSize,i=n*this._origIndex;e.getValue(t,i);for(let s=n,a=i;s!==a;++s)t[s]=t[i+s%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){let e=3*this.valueSize;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){let e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let n=e;n=.5)for(let a=0;a!==s;++a)e[t+a]=e[n+a]}_slerp(e,t,n,i){_t.slerpFlat(e,t,e,t,e,n,i)}_slerpAdditive(e,t,n,i,s){let a=this._workIndex*s;_t.multiplyQuaternionsFlat(e,a,e,t,e,n),_t.slerpFlat(e,t,e,t,e,a,i)}_lerp(e,t,n,i,s){let a=1-i;for(let o=0;o!==s;++o){let l=t+o;e[l]=e[l]*a+e[n+o]*i}}_lerpAdditive(e,t,n,i,s){for(let a=0;a!==s;++a){let o=t+a;e[o]=e[o]+e[n+a]*i}}},dd="\\[\\]\\.:\\/",Ax=new RegExp("["+dd+"]","g"),Ph="[^"+dd+"]",Rx="[^"+dd.replace("\\.","")+"]",Cx=new RegExp("^"+/((?:WC+[\/:])*)/.source.replace("WC",Ph)+/(WCOD+)?/.source.replace("WCOD",Rx)+/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",Ph)+/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",Ph)+"$"),Px=["material","materials","bones","map"],ct=class r{constructor(e,t,n){this.path=t,this.parsedPath=n||r.parseTrackName(t),this.node=r.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,n){return e&&e.isAnimationObjectGroup?new r.Composite(e,t,n):new r(e,t,n)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(Ax,"")}static parseTrackName(e){let t=Cx.exec(e);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},i=n.nodeName&&n.nodeName.lastIndexOf(".");if(i!==void 0&&i!==-1){let s=n.nodeName.substring(i+1);Px.indexOf(s)!==-1&&(n.nodeName=n.nodeName.substring(0,i),n.objectName=s)}if(n.propertyName===null||n.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return n}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(s){for(let a=0;a0){let l=this._interpolants,c=this._propertyBindings;if(this.blendMode===hb)for(let h=0,u=l.length;h!==u;++h)l[h].evaluate(a),c[h].accumulateAdditive(o);else for(let h=0,u=l.length;h!==u;++h)l[h].evaluate(a),c[h].accumulate(i,o)}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;let n=this._weightInterpolant;if(n!==null){let i=n.evaluate(e)[0];t*=i,e>n.parameterPositions[1]&&(this.stopFading(),i===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;let n=this._timeScaleInterpolant;n!==null&&(t*=n.evaluate(e)[0],e>n.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t))}return this._effectiveTimeScale=t,t}_updateTime(e){let t=this._clip.duration,n=this.loop,i=this.time+e,s=this._loopCount,a=n===2202;if(e===0)return s===-1||!a||1&~s?i:t-i;if(n===2200){s===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(i>=t)i=t;else{if(!(i<0)){this.time=i;break e}i=0}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(s===-1&&(e>=0?(s=0,this._setEndings(!0,this.repetitions===0,a)):this._setEndings(this.repetitions===0,!0,a)),i>=t||i<0){let o=Math.floor(i/t);i-=t*o,s+=Math.abs(o);let l=this.repetitions-s;if(l<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,i=e>0?t:0,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(l===1){let c=e<0;this._setEndings(c,!c,a)}else this._setEndings(!1,!1,a);this._loopCount=s,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}else this.time=i;if(a&&!(1&~s))return t-i}return i}_setEndings(e,t,n){let i=this._interpolantSettings;n?(i.endingStart=ns,i.endingEnd=ns):(i.endingStart=e?this.zeroSlopeAtStart?ns:ts:Ko,i.endingEnd=t?this.zeroSlopeAtEnd?ns:ts:Ko)}_scheduleFading(e,t,n){let i=this._mixer,s=i.time,a=this._weightInterpolant;a===null&&(a=i._lendControlInterpolant(),this._weightInterpolant=a);let o=a.parameterPositions,l=a.sampleValues;return o[0]=s,l[0]=t,o[1]=s+e,l[1]=n,this}},Ix=new Float32Array(1),ka=class extends vi{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){let n=e._localRoot||this._root,i=e._clip.tracks,s=i.length,a=e._propertyBindings,o=e._interpolants,l=n.uuid,c=this._bindingsByRootAndName,h=c[l];h===void 0&&(h={},c[l]=h);for(let u=0;u!==s;++u){let d=i[u],p=d.name,m=h[p];if(m!==void 0)++m.referenceCount,a[u]=m;else{if(m=a[u],m!==void 0){m._cacheIndex===null&&(++m.referenceCount,this._addInactiveBinding(m,l,p));continue}let x=t&&t._propertyBindings[u].binding.parsedPath;m=new Qu(ct.create(n,p,x),d.ValueTypeName,d.getValueSize()),++m.referenceCount,this._addInactiveBinding(m,l,p),a[u]=m}o[u].resultBuffer=m.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){let n=(e._localRoot||this._root).uuid,i=e._clip.uuid,s=this._actionsByClip[i];this._bindAction(e,s&&s.knownActions[0]),this._addInactiveAction(e,i,n)}let t=e._propertyBindings;for(let n=0,i=t.length;n!==i;++n){let s=t[n];s.useCount++==0&&(this._lendBinding(s),s.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){let t=e._propertyBindings;for(let n=0,i=t.length;n!==i;++n){let s=t[n];--s.useCount==0&&(s.restoreOriginalState(),this._takeBackBinding(s))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;let e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){let t=e._cacheIndex;return t!==null&&t=0;--t)e[t].stop();return this}update(e){e*=this.timeScale;let t=this._actions,n=this._nActiveActions,i=this.time+=e,s=Math.sign(e),a=this._accuIndex^=1;for(let c=0;c!==n;++c)t[c]._update(i,e,s,a);let o=this._bindings,l=this._nActiveBindings;for(let c=0;c!==l;++c)o[c].apply(a);return this}setTime(e){this.time=0;for(let t=0;t=2.0 are supported."));return}let c=new Vd(s,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let h=0;h=0&&o[u]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+u+'".')}}c.setExtensions(a),c.setPlugins(o),c.parse(n,i)}parseAsync(e,t){let n=this;return new Promise(function(i,s){n.parse(e,t,i,s)})}};function Lx(){let r={};return{get:function(e){return r[e]},add:function(e,t){r[e]=t},remove:function(e){delete r[e]},removeAll:function(){r={}}}}var Be={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"},vd=class{constructor(e){this.parser=e,this.name=Be.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let n=0,i=t.length;n=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,s.source,a)}},Ld=class{constructor(e){this.parser=e,this.name=Be.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(e){let t=this.name,n=this.parser,i=n.json,s=i.textures[e];if(!s.extensions||!s.extensions[t])return null;let a=s.extensions[t],o=i.images[a.source],l=n.textureLoader;if(o.uri){let c=n.options.manager.getHandler(o.uri);c!==null&&(l=c)}return this.detectSupport().then(function(c){if(c)return n.loadTextureImage(e,a.source,l);if(i.extensionsRequired&&i.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return n.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){let t=new Image;t.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}},kd=class{constructor(e){this.parser=e,this.name=Be.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(e){let t=this.name,n=this.parser,i=n.json,s=i.textures[e];if(!s.extensions||!s.extensions[t])return null;let a=s.extensions[t],o=i.images[a.source],l=n.textureLoader;if(o.uri){let c=n.options.manager.getHandler(o.uri);c!==null&&(l=c)}return this.detectSupport().then(function(c){if(c)return n.loadTextureImage(e,a.source,l);if(i.extensionsRequired&&i.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported.");return n.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){let t=new Image;t.src="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}},Dd=class{constructor(e){this.name=Be.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){let t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){let i=n.extensions[this.name],s=this.parser.getDependency("buffer",i.buffer),a=this.parser.options.meshoptDecoder;if(!a||!a.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return s.then(function(o){let l=i.byteOffset||0,c=i.byteLength||0,h=i.count,u=i.byteStride,d=new Uint8Array(o,l,c);return a.decodeGltfBufferAsync?a.decodeGltfBufferAsync(h,u,d,i.mode,i.filter).then(function(p){return p.buffer}):a.ready.then(function(){let p=new ArrayBuffer(h*u);return a.decodeGltfBuffer(new Uint8Array(p),h,u,d,i.mode,i.filter),p})})}else return null}},Ud=class{constructor(e){this.name=Be.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){let t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;let i=t.meshes[n.mesh];for(let c of i.primitives)if(c.mode!==An.TRIANGLES&&c.mode!==An.TRIANGLE_STRIP&&c.mode!==An.TRIANGLE_FAN&&c.mode!==void 0)return null;let a=n.extensions[this.name].attributes,o=[],l={};for(let c in a)o.push(this.parser.getDependency("accessor",a[c]).then(h=>(l[c]=h,l[c])));return o.length<1?null:(o.push(this.parser.createNodeMesh(e)),Promise.all(o).then(c=>{let h=c.pop(),u=h.isGroup?h.children:[h],d=c[0].count,p=[];for(let m of u){let x=new Ee,f=new S,g=new _t,v=new S(1,1,1),b=new rn(m.geometry,m.material,d);for(let y=0;y0||r.search(/^data\:image\/jpeg/)===0?"image/jpeg":r.search(/\.webp($|\?)/i)>0||r.search(/^data\:image\/webp/)===0?"image/webp":r.search(/\.ktx2($|\?)/i)>0||r.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}var Bx=new Ee,Vd=class{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new Lx,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,i=-1,s=!1,a=-1;if(typeof navigator<"u"){let o=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(o)===!0;let l=o.match(/Version\/(\d+)/);i=n&&l?parseInt(l[1],10):-1,s=o.indexOf("Firefox")>-1,a=s?o.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&i<17||s&&a<98?this.textureLoader=new Yi(this.options.manager):this.textureLoader=new Rl(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Ia(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){let n=this,i=this.json,s=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(a){return a._markDefs&&a._markDefs()}),Promise.all(this._invokeAll(function(a){return a.beforeRoot&&a.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(a){let o={scene:a[0][i.scene||0],scenes:a[0],animations:a[1],cameras:a[2],asset:i.asset,parser:n,userData:{}};return Tr(s,o,i),Mi(o,i),Promise.all(n._invokeAll(function(l){return l.afterRoot&&l.afterRoot(o)})).then(function(){for(let l of o.scenes)l.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let i=0,s=t.length;i{let l=this.associations.get(a);l!=null&&this.associations.set(o,l);for(let[c,h]of a.children.entries())s(h,o.children[c])};return s(n,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let n=0;n=2&&f.setY(I,_[R*l+1]),l>=3&&f.setZ(I,_[R*l+2]),l>=4&&f.setW(I,_[R*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}f.normalized=m}return f})}loadTexture(e){let t=this.json,n=this.options,s=t.textures[e].source,a=t.images[s],o=this.textureLoader;if(a.uri){let l=n.manager.getHandler(a.uri);l!==null&&(o=l)}return this.loadTextureImage(e,s,o)}loadTextureImage(e,t,n){let i=this,s=this.json,a=s.textures[e],o=s.images[t],l=(o.uri||o.bufferView)+":"+a.sampler;if(this.textureCache[l])return this.textureCache[l];let c=this.loadImageSource(t,n).then(function(h){h.flipY=!1,h.name=a.name||o.name||"",h.name===""&&typeof o.uri=="string"&&o.uri.startsWith("data:image/")===!1&&(h.name=o.uri);let d=(s.samplers||{})[a.sampler]||{};return h.magFilter=tg[d.magFilter]||jt,h.minFilter=tg[d.minFilter]||gi,h.wrapS=ng[d.wrapS]||Fn,h.wrapT=ng[d.wrapT]||Fn,h.generateMipmaps=!h.isCompressedTexture&&h.minFilter!==Ht&&h.minFilter!==jt,i.associations.set(h,{textures:e}),h}).catch(function(){return null});return this.textureCache[l]=c,c}loadImageSource(e,t){let n=this,i=this.json,s=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(u=>u.clone());let a=i.images[e],o=self.URL||self.webkitURL,l=a.uri||"",c=!1;if(a.bufferView!==void 0)l=n.getDependency("bufferView",a.bufferView).then(function(u){c=!0;let d=new Blob([u],{type:a.mimeType});return l=o.createObjectURL(d),l});else if(a.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");let h=Promise.resolve(l).then(function(u){return new Promise(function(d,p){let m=d;t.isImageBitmapLoader===!0&&(m=function(x){let f=new Ut(x);f.needsUpdate=!0,d(f)}),t.load(Ki.resolveURL(u,s.path),m,void 0,p)})}).then(function(u){return c===!0&&o.revokeObjectURL(l),Mi(u,a),u.userData.mimeType=a.mimeType||Fx(a.uri),u}).catch(function(u){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),u});return this.sourceCache[e]=h,h}assignTexture(e,t,n,i){let s=this;return this.getDependency("texture",n.index).then(function(a){if(!a)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(a=a.clone(),a.channel=n.texCoord),s.extensions[Be.KHR_TEXTURE_TRANSFORM]){let o=n.extensions!==void 0?n.extensions[Be.KHR_TEXTURE_TRANSFORM]:void 0;if(o){let l=s.associations.get(a);a=s.extensions[Be.KHR_TEXTURE_TRANSFORM].extendTexture(a,o),s.associations.set(a,l)}}return i!==void 0&&(a.colorSpace=i),e[t]=a,a})}assignFinalMaterial(e){let t=e.geometry,n=e.material,i=t.attributes.tangent===void 0,s=t.attributes.color!==void 0,a=t.attributes.normal===void 0;if(e.isPoints){let o="PointsMaterial:"+n.uuid,l=this.cache.get(o);l||(l=new xr,un.prototype.copy.call(l,n),l.color.copy(n.color),l.map=n.map,l.sizeAttenuation=!1,this.cache.add(o,l)),n=l}else if(e.isLine){let o="LineBasicMaterial:"+n.uuid,l=this.cache.get(o);l||(l=new _a,un.prototype.copy.call(l,n),l.color.copy(n.color),l.map=n.map,this.cache.add(o,l)),n=l}if(i||s||a){let o="ClonedMaterial:"+n.uuid+":";i&&(o+="derivative-tangents:"),s&&(o+="vertex-colors:"),a&&(o+="flat-shading:");let l=this.cache.get(o);l||(l=n.clone(),s&&(l.vertexColors=!0),a&&(l.flatShading=!0),i&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(o,l),this.associations.set(l,this.associations.get(n))),n=l}e.material=n}getMaterialType(){return Ot}loadMaterial(e){let t=this,n=this.json,i=this.extensions,s=n.materials[e],a,o={},l=s.extensions||{},c=[];if(l[Be.KHR_MATERIALS_UNLIT]){let u=i[Be.KHR_MATERIALS_UNLIT];a=u.getMaterialType(),c.push(u.extendParams(o,s,t))}else{let u=s.pbrMetallicRoughness||{};if(o.color=new oe(1,1,1),o.opacity=1,Array.isArray(u.baseColorFactor)){let d=u.baseColorFactor;o.color.setRGB(d[0],d[1],d[2],qt),o.opacity=d[3]}u.baseColorTexture!==void 0&&c.push(t.assignTexture(o,"map",u.baseColorTexture,ot)),o.metalness=u.metallicFactor!==void 0?u.metallicFactor:1,o.roughness=u.roughnessFactor!==void 0?u.roughnessFactor:1,u.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,"metalnessMap",u.metallicRoughnessTexture)),c.push(t.assignTexture(o,"roughnessMap",u.metallicRoughnessTexture))),a=this._invokeOne(function(d){return d.getMaterialType&&d.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(d){return d.extendMaterialParams&&d.extendMaterialParams(e,o)})))}s.doubleSided===!0&&(o.side=Qn);let h=s.alphaMode||gd.OPAQUE;if(h===gd.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,h===gd.MASK&&(o.alphaTest=s.alphaCutoff!==void 0?s.alphaCutoff:.5)),s.normalTexture!==void 0&&a!==Nt&&(c.push(t.assignTexture(o,"normalMap",s.normalTexture)),o.normalScale=new Z(1,1),s.normalTexture.scale!==void 0)){let u=s.normalTexture.scale;o.normalScale.set(u,u)}if(s.occlusionTexture!==void 0&&a!==Nt&&(c.push(t.assignTexture(o,"aoMap",s.occlusionTexture)),s.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=s.occlusionTexture.strength)),s.emissiveFactor!==void 0&&a!==Nt){let u=s.emissiveFactor;o.emissive=new oe().setRGB(u[0],u[1],u[2],qt)}return s.emissiveTexture!==void 0&&a!==Nt&&c.push(t.assignTexture(o,"emissiveMap",s.emissiveTexture,ot)),Promise.all(c).then(function(){let u=new a(o);return s.name&&(u.name=s.name),Mi(u,s),t.associations.set(u,{materials:e}),s.extensions&&Tr(i,u,s),u})}createUniqueName(e){let t=ct.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){let t=this,n=this.extensions,i=this.primitiveCache;function s(o){return n[Be.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(l){return ig(l,o,t)})}let a=[];for(let o=0,l=e.length;o0&&Ox(g,s),g.name=t.createUniqueName(s.name||"mesh_"+e),Mi(g,s),f.extensions&&Tr(i,g,f),t.assignFinalMaterial(g),u.push(g)}for(let p=0,m=u.length;p1?h=new Zt:c.length===1?h=c[0]:h=new nt,h!==c[0])for(let u=0,d=c.length;u{let u=new Map;for(let[d,p]of i.associations)(d instanceof un||d instanceof Ut)&&u.set(d,p);return h.traverse(d=>{let p=i.associations.get(d);p!=null&&u.set(d,p)}),u};return i.associations=c(s),s})}_createAnimationTracks(e,t,n,i,s){let a=[],o=e.name?e.name:e.uuid,l=[];$i[s.path]===$i.weights?e.traverse(function(d){d.morphTargetInfluences&&l.push(d.name?d.name:d.uuid)}):l.push(o);let c;switch($i[s.path]){case $i.weights:c=yi;break;case $i.rotation:c=Zn;break;case $i.position:case $i.scale:c=Jn;break;default:switch(n.itemSize){case 1:c=yi;break;case 2:case 3:default:c=Jn;break}break}let h=i.interpolation!==void 0?Dx[i.interpolation]:ds,u=this._getArrayFromAccessor(n);for(let d=0,p=l.length;d96?y-97:y>64?y-39:y+4}for(var M=0,b=0;b0?x(g,v,b,h[y],c[M]):a.then(function(){var _=new Uint8Array(g*v);return l(s.exports[h[y]],_,g,v,b,s.exports[c[M]]),_})}}}();var Rn="./art/",Gx={savanna:{ground:["Ground079S","Grass004","Rock030"],tint:[.9,.78,.6],altTint:[1.55,1.08,.42],altBase:.62,grass:[.5,.55,.24],grass2:[.84,.74,.42],gh:.75,fog:14207402,backdrop:0,props:{rock:["boulder2","rock"],bush:["rooibos","shrub2"]}},forest:{ground:["ScatteredLeaves009","Ground037","Rock063"],tint:[.85,.85,.8],altTint:[.9,1,.85],altBase:.35,grass:[.24,.36,.14],grass2:[.34,.46,.2],gh:.55,fog:12767960,backdrop:1,props:{rock:["mossrock","rock"],bush:["shrub2"]}},snow:{ground:["Snow006","Ground110","Rock030"],tint:[1,1,1.03],altTint:[1,1,1],altBase:.08,grass:[.55,.5,.4],grass2:[.66,.6,.48],gh:.4,fog:13949924,backdrop:2,props:{rock:["rock","boulder2"],bush:["shrub2"]}},canyon:{ground:["Ground111","Ground079S","Rock061"],tint:[1.1,.8,.62],altTint:[1.15,.85,.65],altBase:.3,grass:[.6,.52,.32],grass2:[.7,.6,.38],gh:.45,fog:14729376,backdrop:3,props:{rock:["boulder2","rock"],bush:["rooibos"]}},wetlands:{ground:["Ground048","Grass004","Ground037"],tint:[.9,.92,.85],altTint:[1,1.05,.8],altBase:.55,grass:[.34,.45,.18],grass2:[.5,.56,.26],gh:1.1,fog:13424852,backdrop:1,props:{rock:["mossrock"],bush:["shrub2","rooibos"]}}},sg=(r,e)=>e==="rain"||e==="snow"||e==="fog"?"overcast":r<.3||r>.72?"dusk":e==="dust"?"clear":"cloudy",Vx=new Yi,Wd=new Map,jd=new Set,ag=r=>{let e,t=new Promise(i=>{e=i});jd.add(t);let n=()=>{jd.delete(t),e()};return[n,r(n)]},og=(r=5e3)=>Promise.race([Promise.all([...jd]),new Promise(e=>setTimeout(e,r))]);function Si(r,e=!0,t=!0){if(Wd.has(r))return Wd.get(r);let[,n]=ag(i=>Vx.load(r,i,void 0,i));return e&&(n.colorSpace=ot),t&&(n.wrapS=n.wrapT=Fn),n.anisotropy=4,Wd.set(r,n),n}var Bl=class{constructor(e,t,n){this.scene=e,this.renderer=t,this.tier=n,this.chunks=new Map,this.time=0,this.root=new Zt,e.add(this.root),this.u={uTime:{value:0},uWind:{value:1},uDay:{value:1}},this.props=null,this.propsReady=this.loadProps(),this.makeSky(),this.makeLights(),this.makeWeather(),this.makeParticles()}setRun(e){this.run=e;for(let n of this.chunks.values())this.disposeChunk(n);this.chunks.clear();let t=this.L=Gx[e.biome];this.makeTerrainMaterial(t),this.makeGrassMaterial(t),this.makeTreeKit(e.B.tree),this.setBackdrop(t.backdrop),this.weather=e.weather,this.setSky(sg(e.tod,e.weather))}makeLights(){let e=this.sun=new _s(16773340,3);e.castShadow=this.tier>0;let t=this.tier>1?2048:1024;e.shadow.mapSize.set(t,t);let n=e.shadow.camera;n.left=-34,n.right=34,n.top=34,n.bottom=-34,n.near=1,n.far=220,e.shadow.bias=-4e-4,e.shadow.normalBias=.04,e.shadow.radius=3,this.scene.add(e,e.target),this.hemi=new Tl(13624063,6048308,.55),this.scene.add(this.hemi)}makeSky(){this.skyU={tA:{value:null},tB:{value:null},mixAB:{value:0},night:{value:0},sunDir:{value:new S(0,1,0)},sunCol:{value:new oe(1,.9,.7)},fogCol:{value:new oe},haze:{value:.3}};let e=new ft({uniforms:this.skyU,depthWrite:!1,side:Pl,fog:!1,vertexShader:"varying vec3 vDir; void main(){ vDir = normalize(position); vec4 p = projectionMatrix * modelViewMatrix * vec4(position, 1.0); gl_Position = p.xyww; }",fragmentShader:`uniform sampler2D tA, tB; uniform float mixAB, night, haze; uniform vec3 sunDir, sunCol, fogCol; varying vec3 vDir; float h(vec3 p){ return fract(sin(dot(p, vec3(12.9898, 78.233, 37.719))) * 43758.5453); } void main(){ vec3 d = normalize(vDir); vec2 uv = vec2(atan(d.z, d.x) / 6.2831853 + 0.5, asin(clamp(d.y, -1.0, 1.0)) / 3.14159265 + 0.5); vec3 c = mix(texture2D(tA, uv).rgb, texture2D(tB, uv).rgb, mixAB); float s = max(dot(d, sunDir), 0.0); c += sunCol * (pow(s, 900.0) * 6.0 + pow(s, 12.0) * 0.25) * (1.0 - night); // night: dim, blue, stars vec3 nightSky = vec3(0.012, 0.02, 0.045) + vec3(0.03, 0.04, 0.08) * (1.0 - abs(d.y)); vec3 g = floor(d * 380.0); float st = step(0.9965, h(g)) * smoothstep(0.0, 0.25, d.y) * (0.5 + 0.5 * h(g + 1.0)); c = mix(c, nightSky + st, night); c = mix(c, fogCol, haze * (1.0 - smoothstep(0.0, 0.32, d.y))); gl_FragColor = vec4(c, 1.0); #include #include }`});this.sky=new Je(new qi(900,40,20),e),this.sky.frustumCulled=!1,this.sky.renderOrder=-10,this.scene.add(this.sky),this.skyTex={},this.pmrem=new vs(this.renderer)}skyTexture(e){if(!this.skyTex[e]){let[,t]=ag(n=>new Yi().load(Rn+`sky/${e}.webp`,i=>{e===this.skyName&&this.bakeEnv(i),n()},void 0,n));t.colorSpace=ot,t.mapping=ua,t.generateMipmaps=!1,t.minFilter=jt,t.wrapS=Fn,this.skyTex[e]=t}return this.skyTex[e]}setSky(e){this.skyName=e;let t=this.skyTexture(e);this.skyU.tA.value=t,this.skyU.tB.value=t,this.skyU.mixAB.value=0,t.image&&this.bakeEnv(t)}bakeEnv(e){if(this.tier===0&&this.scene.environment)return;let t=this.pmrem.fromEquirectangular(e);this.envRT&&this.envRT.dispose(),this.envRT=t,this.scene.environment=t.texture}setBackdrop(e){if(!this.backdrop){let t=new Yi().load(Rn+"backdrops.webp",void 0,void 0,()=>{this.backdrop.visible=!1});t.colorSpace=ot,t.wrapS=Fn,t.generateMipmaps=!1,t.minFilter=jt,this.bdU={map:{value:t},row:{value:0},fogCol:{value:new oe},haze:{value:.45}};let n=new ft({uniforms:this.bdU,transparent:!0,depthWrite:!1,side:Pl,fog:!1,vertexShader:"varying vec2 vUv; void main(){ vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }",fragmentShader:`uniform sampler2D map; uniform float row, haze; uniform vec3 fogCol; varying vec2 vUv; void main(){ vec2 uv = vec2(vUv.x * 2.0, clamp((4.0 - row + vUv.y) / 5.0, (4.0 - row) / 5.0 + 0.002, (5.0 - row) / 5.0 - 0.002)); vec4 c = texture2D(map, uv); float a = c.a * smoothstep(0.0, 0.18, vUv.y); if (a < 0.02) discard; gl_FragColor = vec4(mix(c.rgb, fogCol, haze), a); // the band's foot fades into the haze: never a hard line #include #include }`});this.backdrop=new Je(new $n(760,760,190,64,1,!0),n),this.backdrop.renderOrder=-9,this.backdrop.frustumCulled=!1,this.scene.add(this.backdrop)}this.bdU.row.value=e}setTime(e,t){let n=It.smoothstep(e,.2,.3)*(1-It.smoothstep(e,.74,.84)),i=1-n,s=(e-.25)*Math.PI*2,a=new S(Math.cos(s)*.8,Math.max(.06,Math.sin(s)),.45).normalize(),o=1-It.smoothstep(a.y,.05,.45),l=new oe(1,.95,.86).lerp(new oe(1,.6,.32),o),c=new oe(.45,.55,.85),h=this.weather,u=h==="rain"||h==="snow"||h==="fog";this.sun.color.copy(l).lerp(c,i),this.sun.intensity=(u?1.9:3.2)*n+.5*i;let d=i>.5?new S(-.4,.75,-.5).normalize():a;this.sun.position.copy(t).addScaledVector(d,90),this.sun.target.position.copy(t),this.hemi.intensity=(u?1.05:.85)*n+.32*i,this.hemi.color.set(13624063).lerp(new oe(2767462),i),this.renderer.toneMappingExposure=(u?1.3:1.12)*(.66+.34*n)+.28*i,this.scene.environment&&(this.scene.environmentIntensity=.5+.8*n),this.skyU.sunDir.value.copy(a),this.skyU.sunCol.value.copy(l),this.skyU.night.value=i;let p=new oe(this.L?this.L.fog:13421772);u?p.lerp(new oe(13226972),.6):h!=="dust"&&p.lerp(new oe(11848674),.5*n*(1-o)),p.lerp(new oe(725542),i*.92).lerp(new oe(1,.62,.4),o*n*.35),this.scene.fog.color.copy(p),this.scene.fog.density=h==="fog"?.0095:h==="snow"?.0075:h==="rain"?.006:h==="dust"?.0065:.0036,this.skyU.fogCol.value.copy(p),this.skyU.haze.value=h==="fog"||h==="snow"?.6:.2,this.bdU&&(this.bdU.fogCol.value.copy(p),this.bdU.haze.value=(h==="fog"||h==="snow"?.75:.3)+i*.35),this.night=i,this.dayLight=n,this.low=o,this.u.uDay.value=n;let m=sg(e,h);m!==this.skyName&&!this.skyBlend&&(this.skyBlend={to:m,k:0},this.skyU.tB.value=this.skyTexture(m))}makeTerrainMaterial(e){let[t,n,i]=e.ground,s=new Ot({map:Si(Rn+`ground/${t}.webp`),normalMap:Si(Rn+`ground/${t}-n.webp`,!1),roughness:1,metalness:0,vertexColors:!0}),a={tB:{value:Si(Rn+`ground/${n}.webp`)},tR:{value:Si(Rn+`ground/${i}.webp`)},nB:{value:Si(Rn+`ground/${n}-n.webp`,!1)},nR:{value:Si(Rn+`ground/${i}-n.webp`,!1)},tint:{value:new S(...e.tint)},tintB:{value:new S(...e.altTint||[1,1,1])},wetCol:{value:new oe(.32,.27,.2)},snowy:{value:this.run.biome==="snow"?1:0}};s.onBeforeCompile=o=>{Object.assign(o.uniforms,a),o.vertexShader=`varying vec3 vWP; `+o.vertexShader.replace("#include ",`#include vWP = (modelMatrix * vec4(transformed, 1.0)).xyz;`),o.fragmentShader=`uniform sampler2D tB, tR, nB, nR; uniform vec3 tint, tintB, wetCol; uniform float snowy; varying vec3 vWP; float th(vec2 p){ return fract(sin(dot(p, vec2(41.3, 289.1))) * 43758.5); } float tn(vec2 p){ vec2 i = floor(p), f = fract(p); f = f*f*(3.0-2.0*f); return mix(mix(th(i), th(i+vec2(1,0)), f.x), mix(th(i+vec2(0,1)), th(i+vec2(1,1)), f.x), f.y); } vec4 tri(sampler2D t, vec2 uv){ // two scales blended to hide tiling return mix(texture2D(t, uv), texture2D(t, uv * 0.37 + 0.13), 0.35); } `+o.fragmentShader.replace("#include ",` vec2 wuv = vWP.xz * 0.22; float macro = tn(vWP.xz * 0.025) * 0.6 + tn(vWP.xz * 0.11) * 0.4; vec3 wts = vColor.rgb; // r = alt, g = rock, b = wet float wAlt = clamp(wts.r + (macro - 0.5) * 0.5, 0.0, 1.0); vec4 cA = tri(map, wuv), cB = tri(tB, wuv * 1.1), cR = tri(tR, wuv * 0.6); vec3 col = mix(cA.rgb, cB.rgb * tintB, smoothstep(0.35, 0.65, wAlt)); col = mix(col, cR.rgb, smoothstep(0.3, 0.7, wts.g)); col = mix(col, col * wetCol * 2.2, wts.b * 0.8); col *= tint * (0.86 + 0.28 * macro); diffuseColor.rgb = col;`).replace("#include ","").replace("#include ",` vec3 nA = tri(normalMap, wuv).xyz, nB2 = tri(nB, wuv * 1.1).xyz, nR2 = tri(nR, wuv * 0.6).xyz; vec3 nn = mix(nA, nB2, smoothstep(0.35, 0.65, wAlt)); nn = mix(nn, nR2, smoothstep(0.3, 0.7, wts.g)); vec3 mapN = nn * 2.0 - 1.0; mapN.xy *= 0.9; mat3 tbn2 = getTangentFrame(-vViewPosition, normal, wuv); normal = normalize(tbn2 * mapN);`).replace("#include ","float roughnessFactor = mix(0.95, 0.35, wts.b) * mix(1.0, 0.8, snowy);")},this.terrainMat&&this.terrainMat.dispose(),this.terrainMat=s,this.waterMat=this.waterMat||this.makeWater()}makeWater(){let e=new Ot({color:2373178,roughness:.06,metalness:0,transparent:!0,opacity:.88,envMapIntensity:1.2});return e.onBeforeCompile=t=>{t.uniforms.uTime=this.u.uTime,t.vertexShader=`varying vec3 vWP2; `+t.vertexShader.replace("#include ",`#include vWP2 = (modelMatrix * vec4(transformed, 1.0)).xyz;`),t.fragmentShader=`uniform float uTime; varying vec3 vWP2; `+t.fragmentShader.replace("#include ",` { vec2 p = vWP2.xz; float t = uTime; vec2 g = vec2(cos(p.x * 0.9 + t * 1.3) * 0.5 + cos(p.x * 2.3 - p.y * 1.7 + t * 2.1) * 0.3, sin(p.y * 1.1 - t * 1.6) * 0.5 + sin(p.y * 2.9 + p.x * 1.3 + t * 2.4) * 0.3); normal = normalize(normal + vec3(g.x, 0.0, g.y) * 0.12); }`)},e}buildChunk(e){let t=this.run,n=Bt(t,e),i=e*Ye,s=i+Ye,a=new Zt;a.name=`chunk${e}`;let o=[];for(let b=-300;b<-60;b+=30)o.push(b);for(let b=-60;b<-40;b+=4)o.push(b);let l=this.tier>1?1.25:this.tier>0?1.6:2.4;for(let b=-40;b<=40+1e-6;b+=l)o.push(b);for(let b=44;b<=60;b+=4)o.push(b);for(let b=90;b<=300;b+=30)o.push(b);let c=[];for(let b=i;b<=s+1e-6;b+=l*1.15)c.push(Math.min(b,s));c[c.length-1]et(t,b,y);for(let b=0;b40?.25:0),z=It.smoothstep(I,1.1,2.2),F=0;for(let W of n.patches){let j=Math.hypot(W.x-M,W.z-_)/W.r;if(j<1.2){let Y=1-It.smoothstep(j,.6,1.2);W.k==="mud"?F=Math.max(F,Y):O=Math.max(O,Y)}}if(n.river){let W=Math.abs(_-n.river.z)-n.river.w/2;W<4&&(F=Math.max(F,1-It.smoothstep(W,-1,4)))}for(let W of n.ledges)M>W.x0-1&&MW.z0-1&&_40&&(z=Math.max(z,It.smoothstep(Math.abs(M),60,140)*.6)),p[C]=O,p[C+1]=z,p[C+2]=F}let x=[];for(let b=0;b0,a.add(g),n.river){let b=new Je(new xi(600,n.river.w+2,1,1),this.waterMat);b.rotation.x=-Math.PI/2,b.position.set(0,-.12,n.river.z),b.receiveShadow=this.tier>0,a.add(b)}for(let b of n.ledges)a.add(this.ledgeMesh(b));this.addGrass(a,n,i),this.addObstacles(a,n),this.addBurrows(a,n);let v=this.addSpots(a,n);return this.root.add(a),{ci:e,g:a,spots:v}}ledgeMesh(e){let t=e.x1-e.x0,n=e.z1-e.z0,i=new Wi(t,e.h+3,n,Math.max(2,Math.round(t/2)),6,Math.max(2,Math.round(n/1.5))),s=i.attributes.position;for(let o=0;o0?u*.6:0),h+u*.7+(c>0,0))}if(i.computeVertexNormals(),!this.ledgeMat){let o=this.L.ground[2];this.ledgeMat=new Ot({map:Si(Rn+`ground/${o}.webp`),normalMap:Si(Rn+`ground/${o}-n.webp`,!1),roughness:.95,color:new oe(...this.L.tint)}),this.ledgeMat.onBeforeCompile=l=>{l.vertexShader=l.vertexShader.replace("#include ",`#include vec3 wp0 = (modelMatrix * vec4(position, 1.0)).xyz; vec3 an = abs(normal); vec2 tuv = an.y > 0.6 ? wp0.xz : (an.x > an.z ? wp0.zy : wp0.xy); tuv *= 0.18; #ifdef USE_MAP vMapUv = tuv; #endif #ifdef USE_NORMALMAP vNormalMapUv = tuv; #endif`)}}let a=new Je(i,this.ledgeMat);return a.position.set((e.x0+e.x1)/2,e.h/2-1.2+et(this.run,(e.x0+e.x1)/2,e.z0-2)*.2,(e.z0+e.z1)/2),a.castShadow=a.receiveShadow=this.tier>0,a}makeGrassMaterial(e){let t=[],n=[];for(let h=0;h<8;h++){let u=h/8*Math.PI*2+h*.7,d=.03+h%3*.05,p=.5+h*37%10/16,m=.024,x=.1+h%4*.07,f=Math.cos(u)*d,g=Math.sin(u)*d,v=Math.cos(u+1.57)*m,b=Math.sin(u+1.57)*m;for(let y=0;y<3;y++){let M=y/3,_=(y+1)/3,R=1-M*.9,C=1-_*.9,I=(z,F,W)=>[f+Math.cos(u)*x*z*z+v*F*W,p*z,g+Math.sin(u)*x*z*z+b*F*W],O=[I(M,R,-1),I(M,R,1),I(_,C,1),I(_,C,-1)];for(let z of[0,1,2,0,2,3])t.push(...O[z]),n.push(O[z][1]/p)}}let a=new qe;a.setAttribute("position",new we(t,3)),a.setAttribute("tip",new we(n,1)),a.computeVertexNormals();let o=a.attributes.normal;for(let h=0;h{Object.assign(h.uniforms,c,this.u),h.vertexShader=`attribute float tip; uniform float uTime, uWind; varying float vTip; varying float vVar; `+h.vertexShader.replace("#include ",`#include vTip = tip; vec4 ip = instanceMatrix * vec4(0.0, 0.0, 0.0, 1.0); vVar = fract(sin(dot(ip.xz, vec2(12.9898, 78.233))) * 43758.5453); // a slow wave rolls across the field (gusts), with a quicker flutter on top float wave = sin(uTime * 0.9 - dot(ip.xz, vec2(0.07, 0.045))) * 0.5 + 0.5; float sw = (sin(uTime * 1.7 + ip.x * 0.35 + ip.z * 0.21) * 0.35 + sin(uTime * 3.1 + ip.z * 0.9) * 0.15) + wave * wave * 0.9; transformed.x += sw * tip * tip * 0.18 * uWind; transformed.z += cos(uTime * 1.3 + ip.x * 0.4) * tip * tip * 0.08 * uWind;`),h.fragmentShader=`uniform vec3 c0, c1; uniform float uDay; varying float vTip; varying float vVar; `+h.fragmentShader.replace("#include ",` float v2 = fract(vVar * 7.31); vec3 col = mix(c0, c1, vVar) * (0.86 + 0.28 * v2); // clump-to-clump tone col = mix(col, col * vec3(0.86, 1.06, 0.82), smoothstep(0.55, 0.95, fract(vVar * 3.7)) * 0.45); // some greener clumps col = mix(col, col * 1.12 + vec3(0.02, 0.02, 0.0), smoothstep(0.65, 1.0, vTip) * 0.6); // dry, sunlit tips diffuseColor.rgb = mix(col * 0.66, col, smoothstep(0.0, 0.7, vTip)); // softly shaded roots (contact AO)`),h.fragmentShader=h.fragmentShader.replace("#include ",`#include totalEmissiveRadiance += diffuseColor.rgb * smoothstep(0.5, 1.0, vTip) * 0.09 * uDay; // light through the blade tips`)},this.grassMat&&this.grassMat.dispose(),this.grassMat=l}addGrass(e,t,n){let i=this.run,s=this.L,a=Math.abs(t.ci-Math.floor((this.focusZ||0)/Ye))<=3,o=[1300,3600,8e3][this.tier]*(i.B.grass+.3)/1.6*(a?1:.35),l=[],c=new nt,h=xn(t.ci*7919+13),u=0,d=Math.round(o),p=new rn(this.grassGeo,this.grassMat,d+600),m=(f,g,v)=>{if(!Or(i,f,g)){for(let b of t.ledges)if(f>b.x0&&fb.z0&&g1,e.add(p);let x={savanna:[15911244,16117728,15238970],forest:[15987178,10848984,15913562],canyon:[15911244,14711370],wetlands:[11833056,15987178,15913562]}[i.biome];if(x&&a){if(!this.flowerGeo){let y=[],M=new xi(.018,.28);M.translate(0,.14,0),y.push(M);for(let _=0;_<2;_++){let R=new _r(.075,7);R.rotateX(-Math.PI/2+.25+_*.3),R.rotateY(_*2.1),R.translate(0,.29,0),y.push(R)}this.flowerGeo=Hl(y);{let _=this.flowerGeo.attributes.position.count,R=new Float32Array(_);R.fill(1,6),this.flowerGeo.setAttribute("head",new Qe(R,1))}this.flowerMat=new Ot({roughness:.75,side:Qn}),this.flowerMat.onBeforeCompile=_=>{_.vertexShader=`attribute float head; varying float vHead; `+_.vertexShader.replace("#include ",`#include vHead = head;`),_.fragmentShader=`varying float vHead; `+_.fragmentShader.replace("#include ",`#include diffuseColor.rgb = mix(vec3(0.2, 0.3, 0.1), diffuseColor.rgb, vHead);`)}}let f=[40,120,260][this.tier],g=new rn(this.flowerGeo,this.flowerMat,f),v=new oe,b=0;for(let y=0;y{Object.assign(o.uniforms,this.u),o.vertexShader=`uniform float uTime, uWind; `+o.vertexShader.replace("#include ",`#include vec4 ip = instanceMatrix * vec4(0.0, 0.0, 0.0, 1.0); transformed.x += sin(uTime * 1.1 + ip.x * 0.3 + position.y) * 0.06 * uWind * position.y * 0.15;`),o.fragmentShader=o.fragmentShader.replace("#include ",`diffuseColor.a *= smoothstep(2.5, 7.0, length(vViewPosition)); #include `),o.fragmentShader=o.fragmentShader.replace("#include ",`#include normal = normalize(vNormal);`)};let{trunk:s,crown:a}=Wx(e);this.treeKit={kind:e,bark:n,leaf:i,trunk:s,crown:a}}leafTexture(e){let t=document.createElement("canvas");t.width=t.height=256;let n=t.getContext("2d"),i={acacia:["#4f6b2a","#6d8a3a","#3b5420"],pine:["#1f3a22","#2d4f2c","#16301b"],snowpine:["#e9eef2","#2a4630","#d5dde3"],juniper:["#4d5e3a","#66784a","#39462a"],willow:["#6f8a3c","#8aa34d","#55702d"]}[e]||["#4f6b2a","#6d8a3a","#3b5420"],s=xn(77),a=e==="pine"||e==="snowpine"||e==="juniper";if(e==="acacia"){for(let c=0;c<70;c++){let h=128+(s()-.5)*200,u=128+(s()-.5)*200;if((h-128)**2+(u-128)**2>104*104)continue;let d=14+s()*16;n.globalAlpha=.9,n.fillStyle=["#3a5220","#4a6427"][Math.floor(s()*2)],n.beginPath(),n.ellipse(h,u,d,d*.7,s()*3,0,6.28),n.fill();for(let p=0;p<110;p++){let m=s()*6.28,x=Math.sqrt(s())*d*1.25;n.fillStyle=["#3e5622","#566f2c","#6e8836","#2f441a","#7d9640"][Math.floor(s()*5)],n.globalAlpha=.95,n.fillRect(h+Math.cos(m)*x,u+Math.sin(m)*x*.75,2.5+s()*2.5,1.8+s()*1.5)}}n.globalAlpha=1;let l=new Ma(t);return l.colorSpace=ot,l.anisotropy=4,l}if(a)for(let l=0;l<46;l++){let c=128+(s()-.5)*170,h=128+(s()-.5)*170,u=18+s()*22;if((c-128)**2+(h-128)**2>92*92)continue;let d=n.createRadialGradient(c,h,0,c,h,u);d.addColorStop(0,i[1]),d.addColorStop(.7,i[0]),d.addColorStop(1,"rgba(0,0,0,0)"),n.fillStyle=d,n.beginPath(),n.arc(c,h,u,0,6.28),n.fill()}for(let l=0;l<(a?700:520);l++){let c=128+(s()-.5)*210,h=128+(s()-.5)*210;(c-128)**2+(h-128)**2>108*108||(n.fillStyle=i[Math.floor(s()*3)],n.save(),n.translate(c,h),n.rotate(s()*6.28),a?(n.globalAlpha=.85,n.fillRect(-.75,-10,1.5,20),n.globalAlpha=1):(n.beginPath(),n.ellipse(0,0,5+s()*4,2.5+s()*2,0,0,6.28),n.fill()),n.restore())}let o=new Ma(t);return o.colorSpace=ot,o.anisotropy=4,o}async loadProps(){let e=new ws;e.setMeshoptDecoder(Fl);try{let t=await e.loadAsync(Rn+"props.glb");this.props={};let n=[];for(let i of t.scene.children){let s=i.children.filter(c=>{let h=0;return c.traverse(u=>{u.isMesh&&h++}),h>0}),a=c=>{let h=new Gt().setFromObject(c),u=h.getSize(new S);return Math.max(u.x,u.z)},o=Math.max(0,...s.map(a)),l=s.filter(c=>a(c)>o*.4);l.length>1?(this.props[i.name]={variants:l.length},l.forEach((c,h)=>n.push([`${i.name}#${h}`,c]))):n.push([i.name,i])}for(let[i,s]of n){let a=[];s.updateMatrixWorld(!0),s.traverse(u=>{u.isMesh&&a.push(u)});let o=new Gt().setFromObject(s),l=o.getSize(new S),c=o.getCenter(new S),h=a.map(u=>{let d=u.geometry.clone();d.applyMatrix4(u.matrixWorld),d.translate(-c.x,-o.min.y,-c.z);let p=u.material;return p.roughness=Math.max(.6,p.roughness??1),p.map&&(p.map.anisotropy=4),{geo:d,mat:p}});this.props[i]={parts:h,size:l}}}catch{this.props=null}for(let t of this.chunks.values())t.g.removeFromParent();this.chunks.clear()}addObstacles(e,t){let n={},i=(a,o,l,c=0,h=0)=>{let u=this.props&&this.props[a]&&this.props[a].variants;u&&(a=`${a}#${Math.floor((o.v||0)*7.31%1*u)}`),(n[a]=n[a]||[]).push({o,scale:l,rotY:c,tilt:h})};for(let a of t.obs){let o=a.v;a.k==="tree"?i("tree",a,.8+o*.6,o*6.28):a.k==="rock"?i(this.pick(this.L.props.rock,o),a,a.r,o*6.28):a.k==="bush"?i(this.pick(this.L.props.bush,o),a,a.r,o*6.28):a.k==="log"&&i("log",a,a.r,Math.PI/2+(o-.5)*.25)}{let a=xn(t.ci*104729+77),o=Math.round((this.run.B.trees*5+1)*(this.tier?1:.5));for(let l=0;l{let x=et(this.run,p.o.x,p.o.z);if(s.rotation.set(0,p.rotY,0),c){let f=a==="log"?p.o.r*2/Math.max(c.x,c.z):p.scale*2/Math.max(c.x,c.z);s.scale.setScalar(f),/^(rock|boulder2|mossrock)/.test(a)&&(s.scale.y=f*(.8+p.o.v*.4));let g=Math.max(c.x,c.z)/2*f*.75;for(let v=0;v<8;v++)x=Math.min(x,et(this.run,p.o.x+Math.cos(v*.785)*g,p.o.z+Math.sin(v*.785)*g))}else s.scale.setScalar(p.scale);s.position.set(p.o.x,x-.08,p.o.z),s.updateMatrix(),d.setMatrixAt(m,s.matrix)}),d.castShadow=this.tier>0,d.receiveShadow=this.tier>1,e.add(d)}}}addFallback(e,t,n){let i=t==="log"?new $n(.35,.4,1,8).rotateZ(Math.PI/2):new Ea(1,1),s=new rn(i,new Ot({color:t==="log"?5916210:7828588,roughness:1}),n.length),a=new nt;n.forEach((o,l)=>{a.position.set(o.o.x,et(this.run,o.o.x,o.o.z),o.o.z),a.rotation.set(0,o.rotY,0),a.scale.set(t==="log"?o.o.r*2:o.scale,t==="log"?1:o.scale*.8,t==="log"?1:o.scale),a.updateMatrix(),s.setMatrixAt(l,a.matrix)}),e.add(s)}pick(e,t){return e[Math.floor(t*e.length)%e.length]}addSpots(e,t){let n=this.run,i=[];if(!t.spots||!t.spots.length)return i;if(!this.spotKit){let l=new Ot({color:8833354,roughness:.8,side:Qn});l.onBeforeCompile=u=>{Object.assign(u.uniforms,this.u),u.vertexShader=`attribute float tip; uniform float uTime, uWind; `+u.vertexShader.replace("#include ",`#include vec4 ip = instanceMatrix * vec4(0.0, 0.0, 0.0, 1.0); transformed.x += sin(uTime * 1.8 + ip.x * 0.5 + ip.z * 0.3) * tip * tip * 0.12 * uWind;`)};let c=Hl([0,1,2].map(u=>{let d=new Ta(.035,.42,4,1);return d.translate(0,.21,0),d.rotateZ((u-1)*.35),d.rotateY(u*2.1),d})),h=new Ot({color:10288986,emissive:5816352,emissiveIntensity:.9,roughness:.5});this.spotKit={lush:l,sprout:c,glow:h,pool:new _r(1,28)}}let s=this.spotKit,a=new nt,o=xn(t.ci*4421+7);for(let l of t.spots){let c=et(n,l.x,l.z);if(l.k==="graze"){let h=[60,110,160][this.tier],u=new rn(this.grassGeo,s.lush,h);for(let d=0;d1,e.add(u)}else if(l.k==="water"){let h=new Je(s.pool,this.waterMat);h.rotation.x=-Math.PI/2,h.scale.setScalar(l.r),h.position.set(l.x,c+.06,l.z),e.add(h);let u=[30,50,70][this.tier],d=new rn(this.grassGeo,this.grassMat,u);for(let p=0;p{t.isMesh&&t.geometry!==this.grassGeo&&t.geometry!==this.flowerGeo&&!(this.spotKit&&(t.geometry===this.spotKit.sprout||t.geometry===this.spotKit.pool))&&t.geometry!==this.burrowGeo&&t.geometry!==this.holeGeo&&(!this.treeKit||t.geometry!==this.treeKit.trunk&&t.geometry!==this.treeKit.crown)&&!(t.isInstancedMesh&&this.props)&&t.geometry.dispose(),t.isInstancedMesh&&t.dispose()})}makeWeather(){let e=[500,1400,2600][this.tier],t=new qe,n=new Float32Array(e*3);for(let i=0;iMath.abs(u-o)-Math.abs(d-o)))!this.chunks.has(h)&&(c++<1||h<=o+1)&&this.chunks.set(h,this.buildChunk(h));for(let h of this.chunks.values())for(let u of h.spots||[])u.visible=!u.userData.spot.used,u.visible&&(u.rotation.y=this.time*1.5,u.scale.setScalar(1+Math.sin(this.time*4+u.position.x)*.12))}this.sky.position.copy(t.position),this.backdrop&&this.backdrop.position.set(t.position.x,t.position.y+20,t.position.z),this.skyBlend&&(this.skyBlend.k=Math.min(1,this.skyBlend.k+e/4),this.skyU.mixAB.value=this.skyBlend.k,this.skyBlend.k>=1&&(this.skyU.tA.value=this.skyU.tB.value,this.skyU.mixAB.value=0,this.skyName=this.skyBlend.to,this.skyU.tA.value.image&&this.bakeEnv(this.skyU.tA.value),this.skyBlend=null));let i=this.weather,s=this.wx;if(s.visible=i==="rain"||i==="snow"||i==="dust"||this.night>.6&&this.run&&this.run.biome!=="snow",s.visible){let o=!(i==="rain"||i==="snow"||i==="dust");s.material.color.set(i==="snow"?16777215:i==="dust"?13612170:o?16773792:11452368),s.material.size=i==="snow"?.12:i==="rain"?.05:i==="dust"?.06:.1,s.material.opacity=o?.9:.65;let l=s.geometry.attributes.position,c=i==="rain"?22:i==="snow"?1.6:o?0:.4,h=i==="dust"?6:.6;for(let u=0;u35&&(p-=70),l.setX(u,p),l.setY(u,d)}l.needsUpdate=!0,s.position.set(t.position.x,t.position.y-(o?12:8),t.position.z)}for(let o=0;onew xi(a,o),s=(a,o,l,c,h,u,d,p=.6)=>{let m=i(c,h);m.rotateX(d),m.rotateY(u),m.translate(a,o,l);let x=m.attributes.normal,f=m.attributes.position;for(let g=0;g{let m=new S().subVectors(u,h),x=m.length(),f=new $n(p,d,x,6,1);f.translate(0,x/2,0),f.applyQuaternion(new _t().setFromUnitVectors(new S(0,1,0),m.normalize())),f.translate(h.x,h.y,h.z),t.push(f)},o=(e()-.5)*.5,l=new S(o,1.7+e()*.8,(e()-.5)*.3);a(new S(0,-.2,0),l,.3,.22);let c=3+Math.floor(e()*3);for(let h=0;hPromise.all([...new Set(r.map(e=>Zi[e].file))].map(jl)),qx=` { float rimF = pow(1.0 - clamp(dot(normalize(normal), normalize(vViewPosition)), 0.0, 1.0), 2.6); outgoingLight += uRim * rimF * (0.35 + 0.65 * totalDiffuse); }`;function hg(r,e){let t=r.clone();t.roughness=Math.max(.78,t.roughness??.9),t.metalness=0,t.envMapIntensity=1.15,t.normalMap&&(t.normalScale=new Z(.9,.9));let n=new oe(...e.tint||[1,1,1]);return e.coat==="lion"&&t.color.setRGB(1,1,1),t.color.multiply(n),t.userData.uRim={value:new oe(.55,.52,.48)},t.userData.uSat={value:e.sat??1},t.onBeforeCompile=i=>{i.uniforms.uRim=t.userData.uRim,i.uniforms.uSat=t.userData.uSat,i.fragmentShader=`uniform vec3 uRim; uniform float uSat; `+i.fragmentShader.replace("#include ",`#include { float lum = dot(diffuseColor.rgb, vec3(0.299, 0.587, 0.114)); diffuseColor.rgb = mix(vec3(lum), diffuseColor.rgb, uSat); }`).replace("#include ",` { float upF = dot(normal, normalize((viewMatrix * vec4(0.0, 1.0, 0.0, 0.0)).xyz)); diffuseColor.rgb *= 0.74 + 0.26 * smoothstep(-0.75, 0.45, upF); } // soft occlusion under the belly and neck #include `).replace("#include ",qx+` #include `),e.coat&&Xx(i,e)},t.customProgramCacheKey=()=>`fur-${e.coat||""}-${e.shadow?1:0}-${e.gold?1:0}`,t}function Xx(r,e){r.vertexShader=`attribute vec3 vbody; varying vec3 vBody; `+r.vertexShader.replace("#include ",`#include vBody = vbody;`);let t=` float vh(vec3 p) { return fract(sin(dot(p, vec3(127.1, 311.7, 74.7))) * 43758.5453); } float vn(vec3 p) { vec3 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f); return mix(mix(mix(vh(i), vh(i + vec3(1,0,0)), f.x), mix(vh(i + vec3(0,1,0)), vh(i + vec3(1,1,0)), f.x), f.y), mix(mix(vh(i + vec3(0,0,1)), vh(i + vec3(1,0,1)), f.x), mix(vh(i + vec3(0,1,1)), vh(i + vec3(1,1,1)), f.x), f.y), f.z); }`,n="";e.coat==="zebra"?n=` float f = vBody.x, h = vBody.y, s = vBody.z; float warp = vn(vBody * 9.0) * 0.06; float legs = (1.0 - smoothstep(0.30, 0.42, h)); // legs: horizontal rings float rump = (1.0 - smoothstep(-0.42, -0.25, f)) * (1.0 - legs); // rump: chevrons bend backwards float neck = smoothstep(0.18, 0.32, f) * (1.0 - legs); float u = mix(f * 78.0 + h * 9.0, f * 60.0 - h * 48.0, rump); u = mix(u, h * 95.0, legs); u = mix(u, f * 62.0 + h * 34.0, neck); float st = (1.0 - smoothstep(-0.08, 0.08, sin(u + warp * 40.0))); float belly = (1.0 - smoothstep(0.30, 0.36, h)) * (1.0 - smoothstep(0.04, 0.12, abs(s))) * (1.0 - legs) * smoothstep(-0.3, -0.2, f) * (1.0 - smoothstep(0.2, 0.3, f)); st *= 1.0 - belly; float muzzle = smoothstep(0.43, 0.48, f) * (1.0 - smoothstep(0.55, 0.7, h)); vec3 white = ${e.gold?"vec3(0.86, 0.74, 0.5)":"vec3(0.9, 0.88, 0.84)"}, black = ${e.gold?"vec3(0.62, 0.45, 0.25)":"vec3(0.045, 0.04, 0.04)"}; ${e.shadow?"black = mix(black, vec3(0.42, 0.36, 0.3), 0.55 * (1.0 - legs));":""} vec3 col = mix(white, black, max(st, muzzle * 0.85)); col *= 0.9 + 0.2 * vn(vBody * 60.0); diffuseColor.rgb = pow(col, vec3(2.2));`:e.coat==="deer"?n=` float f = vBody.x, h = vBody.y, s = vBody.z; vec3 coat = vec3(0.36, 0.21, 0.12); float belly = (1.0 - smoothstep(0.38, 0.47, h)) * (1.0 - smoothstep(0.36, 0.46, f)) * smoothstep(-0.42, -0.32, f); float rump = (1.0 - smoothstep(-0.44, -0.36, f)) * smoothstep(0.42, 0.52, h) * (1.0 - smoothstep(0.74, 0.86, h)); float neck = smoothstep(0.24, 0.34, f) * smoothstep(0.5, 0.6, h) * (1.0 - smoothstep(0.78, 0.88, h)); float legs = (1.0 - smoothstep(0.22, 0.36, h)); float head = smoothstep(0.4, 0.47, f) * smoothstep(0.62, 0.7, h); float antler = smoothstep(0.86, 0.9, h); vec3 col = coat; col = mix(col, vec3(0.55, 0.42, 0.29), belly * 0.85); col = mix(col, vec3(0.72, 0.6, 0.44), rump); col = mix(col, vec3(0.24, 0.15, 0.09), neck * 0.8); col = mix(col, vec3(0.3, 0.22, 0.15), legs * 0.7); col = mix(col, vec3(0.4, 0.3, 0.22), head * 0.6); col = mix(col, vec3(0.08, 0.06, 0.05), (1.0 - smoothstep(0.02, 0.045, h))); col = mix(col, vec3(0.5, 0.42, 0.32) * (0.75 + 0.5 * smoothstep(0.9, 1.0, h)), antler); col *= 0.86 + 0.28 * vn(vBody * vec3(90.0, 140.0, 90.0)) * (1.0 - antler); diffuseColor.rgb = pow(col, vec3(2.2)) * diffuseColor.rgb; // colours above are written in sRGB`:e.coat==="lion"&&(n=` // body coordinates measured on this model: f = -0.75 (tail tip) .. +0.30 (nose), h = 0 (paws) .. 1.06 (ears) float f = vBody.x, h = vBody.y, s = vBody.z; vec3 col = vec3(0.74, 0.55, 0.33); // tawny float torso = smoothstep(-0.5, -0.42, f) * (1.0 - smoothstep(-0.02, 0.04, f)); float back = smoothstep(0.82, 0.98, h) * (1.0 - smoothstep(0.0, 0.05, f)) * smoothstep(-0.62, -0.55, f); float belly = torso * (1.0 - smoothstep(0.5, 0.6, h)) * smoothstep(0.3, 0.4, h); float head = smoothstep(0.0, 0.06, f) * smoothstep(0.5, 0.58, h); float muzzle = smoothstep(0.2, 0.25, f) * (1.0 - smoothstep(0.82, 0.9, h)); float chin = smoothstep(0.06, 0.1, f) * (1.0 - smoothstep(0.66, 0.72, h)) * smoothstep(0.5, 0.55, h); float ears = smoothstep(0.98, 1.02, h) * smoothstep(0.02, 0.06, f) * (1.0 - smoothstep(0.2, 0.24, f)); float tuft = 1.0 - smoothstep(-0.73, -0.7, f); // the dark tip of the tail float paws = 1.0 - smoothstep(0.03, 0.1, h); col = mix(col, vec3(0.63, 0.45, 0.27), back * 0.75); col = mix(col, vec3(0.86, 0.75, 0.58), belly * 0.7); col = mix(col, vec3(0.72, 0.54, 0.34), head * 0.5); col = mix(col, vec3(0.9, 0.82, 0.68), max(muzzle, chin) * 0.8); col = mix(col, vec3(0.22, 0.15, 0.1), ears * 0.75); col = mix(col, vec3(0.16, 0.11, 0.08), tuft); col = mix(col, vec3(0.66, 0.5, 0.33), paws * 0.5); col *= 0.88 + 0.24 * vn(vBody * vec3(80.0, 120.0, 80.0)); diffuseColor.rgb = pow(col, vec3(2.2)) * diffuseColor.rgb; // colours above are written in sRGB`),r.fragmentShader=`varying vec3 vBody; `+t+` `+r.fragmentShader.replace("#include ",`#include {${n} }`)}var ug={walk:[0,.25,.5,.75],trot:[0,.5],canter:[0,.3,.45],gallop:[0,.12,.4,.52],bound:[0,.09,.48,.58],hop:[0,.05,.5,.55]},Vl=class{constructor(e,t,n=null){let i=Zi[e];this.sp=e,this.M=i,this.root=new Zt,this.body=lg(t.scene),this.body.scale.setScalar(i.scale),this.root.add(this.body);let s=(Wl[e]||[]).find(u=>u.id===n)||{},a=i.tint?i.tint.map((u,d)=>u*(s.tint||[1,1,1])[d]):s.tint,o={coat:i.coat,tint:a,sat:s.sat,shadow:s.shadow,gold:s.gold};this.mats=[],this.body.traverse(u=>{if(!u.isMesh)return;let d=u.geometry.attributes;if(d.__body&&!d.vbody&&u.geometry.setAttribute("vbody",d.__body),i.hide&&i.hide.includes(u.name)){u.visible=!1;return}u.castShadow=!0,u.receiveShadow=!1,u.frustumCulled=!1,u.material=Array.isArray(u.material)?u.material.map(p=>hg(p,o)):hg(u.material,o),this.mats.push(...[].concat(u.material))}),this.mixer=new ka(this.body),this.act={};for(let u of t.animations){let d=this.mixer.clipAction(u);d.play(),d.weight=0,this.act[u.name]=d}this.main=this.act.run||this.act.fly||this.act.walk||Object.values(this.act)[0],this.main&&(this.main.weight=1),this.lean=0,this.pitch=0,this.roll=0,this.fade=1,this.down=0,this.t=Math.random()*10,this.oneShot=null,this.spd=0,this.phase=Math.random(),this.turnS=0,this.land=0,this.wasAir=!1,this.loco=(i.bands||[]).map(([u])=>u).filter(u=>this.act[u]&&u!=="idle");for(let u of this.loco)this.act[u].timeScale=0;let l=[];this.body.traverse(u=>{u.isBone&&l.push(u)});let c=u=>{let d=0;for(let p=u;p.parent;p=p.parent)d++;return d},h=/(nub|end|tip|ear|jaw|eye|beard|mouth|mane|tongue|tough|saddle|clav|arm|leg|thigh|tail|pelvis|hip)/i;this.head=l.filter(u=>/(head|skull)/i.test(u.name)&&!h.test(u.name)).sort((u,d)=>c(u)-c(d))[0]||null,this.spine=[];for(let u=this.head&&this.head.parent;u&&u.isBone&&!/(root|pelvis|hip|armature)/i.test(u.name);u=u.parent)this.spine.unshift(u);this.spine.length&&!this.spine[0].parent?.isBone&&this.spine.shift(),this.bones=l,this.bind=new Map(l.map(u=>[u,u.quaternion.clone()])),this.tracked=new Set;for(let u of t.animations)for(let d of u.tracks)/\.quaternion$/.test(d.name)&&this.tracked.add(d.name.split(".")[0])}setRim(e){for(let t of this.mats)t.userData.uRim.value.copy(e)}update(e,{speed:t=0,turn:n=0,slope:i=0,side:s=0,vy:a=0,air:o=!1,crouch:l=0,eat:c=0},h=!1){this.eat=(this.eat||0)+((c?1:0)-(this.eat||0))*(1-Math.exp(-e*5));let u=this.act,d=this.M;this.spd+=(t-this.spd)*(1-Math.exp(-e*7));let p=this.spd,m=d.bands||[],x={};for(let C=0;C0&&!o&&p>.6&&!u.fly){let C=null,I=0;for(let z of this.loco)(x[z]||0)>I&&(I=x[z],C=z);let O=C==="run"?d.gait||"gallop":C;for(let z of ug[O]||ug.walk)((z-v)%1+1)%10&&(this.down=Math.min(1,this.down+e*2.2),this.body.rotation.z=this.down*1.45,this.body.position.y=-.15*this.down)}layers(e){let t=this.spine.length;if(!t&&!this.head)return;let n=this.lay||(this.lay=new Map),i=this.head?[...this.spine,this.head]:this.spine;for(let d of i){let p=n.get(d);p&&d.quaternion.equals(p.set)&&d.quaternion.copy(p.base)}this.body.updateMatrixWorld(!0);let s=It.clamp(this.turnS*.05,-.1,.1)*Math.min(1,.4+e*.08),a=new S(0,1,0),o=new S(1,0,0).applyQuaternion(this.root.quaternion),l=new _t,c=new _t,h=(d,p,m)=>{let x=d.quaternion.clone();d.getWorldQuaternion(c);let f=p.clone().applyQuaternion(c.invert()).normalize();d.quaternion.multiply(l.setFromAxisAngle(f,m)),d.updateMatrixWorld(!0),n.set(d,{base:x,set:d.quaternion.clone()})};for(let d of this.spine)h(d,a,s/t);this.head&&h(this.head,o,It.clamp(-this.pitch*.6,-.2,.2));let u=this.spine.slice(-3);if(this.eat>.01&&u.length&&this.head){if(this.eatSign==null){let d=this.head.getWorldPosition(new S).y,p=u[0],m=p.quaternion.clone();p.getWorldQuaternion(c),p.quaternion.multiply(l.setFromAxisAngle(o.clone().applyQuaternion(c.invert()).normalize(),.3)),p.updateMatrixWorld(!0),this.eatSign=this.head.getWorldPosition(new S).y=1;this.body.traverse(t=>{t.isMesh&&(t.castShadow=e>.5)})}}dispose(){this.mixer.stopAllAction(),this.root.removeFromParent();for(let e of this.mats)e.dispose()}};var ql={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`,fragmentShader:` uniform float opacity; uniform sampler2D tDiffuse; varying vec2 vUv; void main() { vec4 texel = texture2D( tDiffuse, vUv ); gl_FragColor = opacity * texel; }`};var Qt=class{constructor(){this.isPass=!0,this.enabled=!0,this.needsSwap=!0,this.clear=!1,this.renderToScreen=!1}setSize(){}render(){console.error("THREE.Pass: .render() must be implemented in derived pass.")}dispose(){}},Yx=new ji(-1,1,1,-1,0,1),Yd=class extends qe{constructor(){super(),this.setAttribute("position",new we([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new we([0,2,0,0,2,0],2))}},Kx=new Yd,ti=class{constructor(e){this._mesh=new Je(Kx,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,Yx)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}};var Er=class extends Qt{constructor(e,t){super(),this.textureID=t!==void 0?t:"tDiffuse",e instanceof ft?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=ei.clone(e.uniforms),this.material=new ft({name:e.name!==void 0?e.name:"unspecified",defines:Object.assign({},e.defines),uniforms:this.uniforms,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader})),this.fsQuad=new ti(this.material)}render(e,t,n){this.uniforms[this.textureID]&&(this.uniforms[this.textureID].value=n.texture),this.fsQuad.material=this.material,this.renderToScreen?(e.setRenderTarget(null),this.fsQuad.render(e)):(e.setRenderTarget(t),this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),this.fsQuad.render(e))}dispose(){this.material.dispose(),this.fsQuad.dispose()}};var Na=class extends Qt{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,n){let i=e.getContext(),s=e.state;s.buffers.color.setMask(!1),s.buffers.depth.setMask(!1),s.buffers.color.setLocked(!0),s.buffers.depth.setLocked(!0);let a,o;this.inverse?(a=0,o=1):(a=1,o=0),s.buffers.stencil.setTest(!0),s.buffers.stencil.setOp(i.REPLACE,i.REPLACE,i.REPLACE),s.buffers.stencil.setFunc(i.ALWAYS,a,4294967295),s.buffers.stencil.setClear(o),s.buffers.stencil.setLocked(!0),e.setRenderTarget(n),this.clear&&e.clear(),e.render(this.scene,this.camera),e.setRenderTarget(t),this.clear&&e.clear(),e.render(this.scene,this.camera),s.buffers.color.setLocked(!1),s.buffers.depth.setLocked(!1),s.buffers.color.setMask(!0),s.buffers.depth.setMask(!0),s.buffers.stencil.setLocked(!1),s.buffers.stencil.setFunc(i.EQUAL,1,4294967295),s.buffers.stencil.setOp(i.KEEP,i.KEEP,i.KEEP),s.buffers.stencil.setLocked(!0)}},Xl=class extends Qt{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}};var Yl=class{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),t===void 0){let n=e.getSize(new Z);this._width=n.width,this._height=n.height,t=new Rt(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:Jt}),t.texture.name="EffectComposer.rt1"}else this._width=t.width,this._height=t.height;this.renderTarget1=t,this.renderTarget2=t.clone(),this.renderTarget2.texture.name="EffectComposer.rt2",this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2,this.renderToScreen=!0,this.passes=[],this.copyPass=new Er(ql),this.copyPass.material.blending=Il,this.clock=new Cl}swapBuffers(){let e=this.readBuffer;this.readBuffer=this.writeBuffer,this.writeBuffer=e}addPass(e){this.passes.push(e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}insertPass(e,t){this.passes.splice(t,0,e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}removePass(e){let t=this.passes.indexOf(e);t!==-1&&this.passes.splice(t,1)}isLastEnabledPass(e){for(let t=e+1;t varying vec2 vUv; uniform sampler2D colorTexture; uniform vec2 invSize; uniform vec2 direction; uniform float gaussianCoefficients[KERNEL_RADIUS]; void main() { float weightSum = gaussianCoefficients[0]; vec3 diffuseSum = texture2D( colorTexture, vUv ).rgb * weightSum; for( int i = 1; i < KERNEL_RADIUS; i ++ ) { float x = float(i); float w = gaussianCoefficients[i]; vec2 uvOffset = direction * invSize * x; vec3 sample1 = texture2D( colorTexture, vUv + uvOffset ).rgb; vec3 sample2 = texture2D( colorTexture, vUv - uvOffset ).rgb; diffuseSum += (sample1 + sample2) * w; weightSum += 2.0 * w; } gl_FragColor = vec4(diffuseSum/weightSum, 1.0); }`})}getCompositeMaterial(e){return new ft({defines:{NUM_MIPS:e},uniforms:{blurTexture1:{value:null},blurTexture2:{value:null},blurTexture3:{value:null},blurTexture4:{value:null},blurTexture5:{value:null},bloomStrength:{value:1},bloomFactors:{value:null},bloomTintColors:{value:null},bloomRadius:{value:0}},vertexShader:`varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`,fragmentShader:`varying vec2 vUv; uniform sampler2D blurTexture1; uniform sampler2D blurTexture2; uniform sampler2D blurTexture3; uniform sampler2D blurTexture4; uniform sampler2D blurTexture5; uniform float bloomStrength; uniform float bloomRadius; uniform float bloomFactors[NUM_MIPS]; uniform vec3 bloomTintColors[NUM_MIPS]; float lerpBloomFactor(const in float factor) { float mirrorFactor = 1.2 - factor; return mix(factor, mirrorFactor, bloomRadius); } void main() { gl_FragColor = bloomStrength * ( lerpBloomFactor(bloomFactors[0]) * vec4(bloomTintColors[0], 1.0) * texture2D(blurTexture1, vUv) + lerpBloomFactor(bloomFactors[1]) * vec4(bloomTintColors[1], 1.0) * texture2D(blurTexture2, vUv) + lerpBloomFactor(bloomFactors[2]) * vec4(bloomTintColors[2], 1.0) * texture2D(blurTexture3, vUv) + lerpBloomFactor(bloomFactors[3]) * vec4(bloomTintColors[3], 1.0) * texture2D(blurTexture4, vUv) + lerpBloomFactor(bloomFactors[4]) * vec4(bloomTintColors[4], 1.0) * texture2D(blurTexture5, vUv) ); }`})}};Ts.BlurDirectionX=new Z(1,0);Ts.BlurDirectionY=new Z(0,1);var fg={name:"BokehShader",defines:{DEPTH_PACKING:1,PERSPECTIVE_CAMERA:1},uniforms:{tColor:{value:null},tDepth:{value:null},focus:{value:1},aspect:{value:1},aperture:{value:.025},maxblur:{value:.01},nearClip:{value:1},farClip:{value:1e3}},vertexShader:` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`,fragmentShader:` #include varying vec2 vUv; uniform sampler2D tColor; uniform sampler2D tDepth; uniform float maxblur; // max blur amount uniform float aperture; // aperture - bigger values for shallower depth of field uniform float nearClip; uniform float farClip; uniform float focus; uniform float aspect; #include float getDepth( const in vec2 screenPosition ) { #if DEPTH_PACKING == 1 return unpackRGBAToDepth( texture2D( tDepth, screenPosition ) ); #else return texture2D( tDepth, screenPosition ).x; #endif } float getViewZ( const in float depth ) { #if PERSPECTIVE_CAMERA == 1 return perspectiveDepthToViewZ( depth, nearClip, farClip ); #else return orthographicDepthToViewZ( depth, nearClip, farClip ); #endif } void main() { vec2 aspectcorrect = vec2( 1.0, aspect ); float viewZ = getViewZ( getDepth( vUv ) ); float factor = ( focus + viewZ ); // viewZ is <= 0, so this is a difference equation vec2 dofblur = vec2 ( clamp( factor * aperture, -maxblur, maxblur ) ); vec2 dofblur9 = dofblur * 0.9; vec2 dofblur7 = dofblur * 0.7; vec2 dofblur4 = dofblur * 0.4; vec4 col = vec4( 0.0 ); col += texture2D( tColor, vUv.xy ); col += texture2D( tColor, vUv.xy + ( vec2( 0.0, 0.4 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( 0.15, 0.37 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( 0.29, 0.29 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( -0.37, 0.15 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( 0.40, 0.0 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( 0.37, -0.15 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( 0.29, -0.29 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( -0.15, -0.37 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( 0.0, -0.4 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( -0.15, 0.37 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( -0.29, 0.29 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( 0.37, 0.15 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( -0.4, 0.0 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( -0.37, -0.15 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( -0.29, -0.29 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( 0.15, -0.37 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( 0.15, 0.37 ) * aspectcorrect ) * dofblur9 ); col += texture2D( tColor, vUv.xy + ( vec2( -0.37, 0.15 ) * aspectcorrect ) * dofblur9 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.37, -0.15 ) * aspectcorrect ) * dofblur9 ); col += texture2D( tColor, vUv.xy + ( vec2( -0.15, -0.37 ) * aspectcorrect ) * dofblur9 ); col += texture2D( tColor, vUv.xy + ( vec2( -0.15, 0.37 ) * aspectcorrect ) * dofblur9 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.37, 0.15 ) * aspectcorrect ) * dofblur9 ); col += texture2D( tColor, vUv.xy + ( vec2( -0.37, -0.15 ) * aspectcorrect ) * dofblur9 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.15, -0.37 ) * aspectcorrect ) * dofblur9 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.29, 0.29 ) * aspectcorrect ) * dofblur7 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.40, 0.0 ) * aspectcorrect ) * dofblur7 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.29, -0.29 ) * aspectcorrect ) * dofblur7 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.0, -0.4 ) * aspectcorrect ) * dofblur7 ); col += texture2D( tColor, vUv.xy + ( vec2( -0.29, 0.29 ) * aspectcorrect ) * dofblur7 ); col += texture2D( tColor, vUv.xy + ( vec2( -0.4, 0.0 ) * aspectcorrect ) * dofblur7 ); col += texture2D( tColor, vUv.xy + ( vec2( -0.29, -0.29 ) * aspectcorrect ) * dofblur7 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.0, 0.4 ) * aspectcorrect ) * dofblur7 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.29, 0.29 ) * aspectcorrect ) * dofblur4 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.4, 0.0 ) * aspectcorrect ) * dofblur4 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.29, -0.29 ) * aspectcorrect ) * dofblur4 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.0, -0.4 ) * aspectcorrect ) * dofblur4 ); col += texture2D( tColor, vUv.xy + ( vec2( -0.29, 0.29 ) * aspectcorrect ) * dofblur4 ); col += texture2D( tColor, vUv.xy + ( vec2( -0.4, 0.0 ) * aspectcorrect ) * dofblur4 ); col += texture2D( tColor, vUv.xy + ( vec2( -0.29, -0.29 ) * aspectcorrect ) * dofblur4 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.0, 0.4 ) * aspectcorrect ) * dofblur4 ); gl_FragColor = col / 41.0; gl_FragColor.a = 1.0; }`};var $l=class extends Qt{constructor(e,t,n){super(),this.scene=e,this.camera=t;let i=n.focus!==void 0?n.focus:1,s=n.aperture!==void 0?n.aperture:.025,a=n.maxblur!==void 0?n.maxblur:1;this.renderTargetDepth=new Rt(1,1,{minFilter:Ht,magFilter:Ht,type:Jt}),this.renderTargetDepth.texture.name="BokehPass.depth",this.materialDepth=new ba,this.materialDepth.depthPacking=Gm,this.materialDepth.blending=Il;let o=fg,l=ei.clone(o.uniforms);l.tDepth.value=this.renderTargetDepth.texture,l.focus.value=i,l.aspect.value=t.aspect,l.aperture.value=s,l.maxblur.value=a,l.nearClip.value=t.near,l.farClip.value=t.far,this.materialBokeh=new ft({defines:Object.assign({},o.defines),uniforms:l,vertexShader:o.vertexShader,fragmentShader:o.fragmentShader}),this.uniforms=l,this.fsQuad=new ti(this.materialBokeh),this._oldClearColor=new oe}render(e,t,n){this.scene.overrideMaterial=this.materialDepth,e.getClearColor(this._oldClearColor);let i=e.getClearAlpha(),s=e.autoClear;e.autoClear=!1,e.setClearColor(16777215),e.setClearAlpha(1),e.setRenderTarget(this.renderTargetDepth),e.clear(),e.render(this.scene,this.camera),this.uniforms.tColor.value=n.texture,this.uniforms.nearClip.value=this.camera.near,this.uniforms.farClip.value=this.camera.far,this.renderToScreen?(e.setRenderTarget(null),this.fsQuad.render(e)):(e.setRenderTarget(t),e.clear(),this.fsQuad.render(e)),this.scene.overrideMaterial=null,e.setClearColor(this._oldClearColor),e.setClearAlpha(i),e.autoClear=s}setSize(e,t){this.materialBokeh.uniforms.aspect.value=e/t,this.renderTargetDepth.setSize(e,t)}dispose(){this.renderTargetDepth.dispose(),this.materialDepth.dispose(),this.materialBokeh.dispose(),this.fsQuad.dispose()}};var mg={name:"OutputShader",uniforms:{tDiffuse:{value:null},toneMappingExposure:{value:1}},vertexShader:` precision highp float; uniform mat4 modelViewMatrix; uniform mat4 projectionMatrix; attribute vec3 position; attribute vec2 uv; varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`,fragmentShader:` precision highp float; uniform sampler2D tDiffuse; #include #include varying vec2 vUv; void main() { gl_FragColor = texture2D( tDiffuse, vUv ); // tone mapping #ifdef LINEAR_TONE_MAPPING gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb ); #elif defined( REINHARD_TONE_MAPPING ) gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb ); #elif defined( CINEON_TONE_MAPPING ) gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb ); #elif defined( ACES_FILMIC_TONE_MAPPING ) gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb ); #elif defined( AGX_TONE_MAPPING ) gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb ); #elif defined( NEUTRAL_TONE_MAPPING ) gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb ); #endif // color space #ifdef SRGB_TRANSFER gl_FragColor = sRGBTransferOETF( gl_FragColor ); #endif }`};var Zl=class extends Qt{constructor(){super();let e=mg;this.uniforms=ei.clone(e.uniforms),this.material=new Ml({name:e.name,uniforms:this.uniforms,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader}),this.fsQuad=new ti(this.material),this._outputColorSpace=null,this._toneMapping=null}render(e,t,n){this.uniforms.tDiffuse.value=n.texture,this.uniforms.toneMappingExposure.value=e.toneMappingExposure,(this._outputColorSpace!==e.outputColorSpace||this._toneMapping!==e.toneMapping)&&(this._outputColorSpace=e.outputColorSpace,this._toneMapping=e.toneMapping,this.material.defines={},Oe.getTransfer(this._outputColorSpace)===tt&&(this.material.defines.SRGB_TRANSFER=""),this._toneMapping===Tm?this.material.defines.LINEAR_TONE_MAPPING="":this._toneMapping===Em?this.material.defines.REINHARD_TONE_MAPPING="":this._toneMapping===Am?this.material.defines.CINEON_TONE_MAPPING="":this._toneMapping===Ll?this.material.defines.ACES_FILMIC_TONE_MAPPING="":this._toneMapping===Rm?this.material.defines.AGX_TONE_MAPPING="":this._toneMapping===Cm&&(this.material.defines.NEUTRAL_TONE_MAPPING=""),this.material.needsUpdate=!0),this.renderToScreen===!0?(e.setRenderTarget(null),this.fsQuad.render(e)):(e.setRenderTarget(t),this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),this.fsQuad.render(e))}dispose(){this.material.dispose(),this.fsQuad.dispose()}};var $x={uniforms:{tDiffuse:{value:null},lift:{value:new S},gain:{value:new S(1,1,1)},sat:{value:1.05},contrast:{value:1.05},vig:{value:.16}},vertexShader:"varying vec2 vUv; void main(){ vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }",fragmentShader:`uniform sampler2D tDiffuse; uniform vec3 lift, gain; uniform float sat, contrast, vig; varying vec2 vUv; void main(){ vec4 c = texture2D(tDiffuse, vUv); vec3 x = c.rgb; float l = dot(x, vec3(0.2126, 0.7152, 0.0722)); x = mix(vec3(l), x, sat); x = (x - 0.5) * contrast + 0.5; x = x * gain + lift * (1.0 - x); vec2 d = vUv - 0.5; x *= 1.0 - vig * dot(d, d) * 1.6; gl_FragColor = vec4(clamp(x, 0.0, 1.0), c.a); }`},Zx={uniforms:{tDiffuse:{value:null},amount:{value:0}},vertexShader:"varying vec2 vUv; void main(){ vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }",fragmentShader:`uniform sampler2D tDiffuse; uniform float amount; varying vec2 vUv; void main(){ vec2 d = vUv - vec2(0.5, 0.55); float k = amount * smoothstep(0.15, 0.7, length(d)); vec4 c = vec4(0.0); for (int i = 0; i < 8; i++) c += texture2D(tDiffuse, vUv - d * k * float(i) / 8.0); gl_FragColor = c / 8.0; }`},Jl=class{constructor(e,{tier:t=1,cap:n=!1}={}){this.canvas=e,this.cap=n;let i=this.r=new rl({canvas:e,antialias:!0,powerPreference:"high-performance",preserveDrawingBuffer:n});i.outputColorSpace=ot,i.toneMapping=Ll,i.toneMappingExposure=1,i.shadowMap.enabled=!0,i.shadowMap.type=Sm,this.scene=new al,this.scene.fog=new sl(14207402,.0045),this.cam=new At(58,1,.15,1400),this.anim=new Map,this.gltf={},this.camState={yaw:0,pos:new S(0,4,-8),look:new S,shake:0,fov:58,orbit:0},this.slow=0,this.flash=0,this.blobs=null,this.setTier(t),this.world=new Bl(this.scene,i,this.tier),this.resize(),addEventListener("resize",()=>this.resize())}setTier(e){if(this.tier=e,this.r.setPixelRatio(Math.min(devicePixelRatio||1,[1.3,1.6,2][e])),this.r.shadowMap.enabled=e>0,this.world&&(this.world.tier=e,this.world.sun.castShadow=e>0,e>0)){let t=e>1?2048:1024;this.world.sun.shadow.mapSize.x!==t&&(this.world.sun.shadow.mapSize.set(t,t),this.world.sun.shadow.map&&(this.world.sun.shadow.map.dispose(),this.world.sun.shadow.map=null))}this.makeComposer(),this.resize()}makeComposer(){if(this.composer&&this.composer.dispose?.(),this.composer=null,this.tier===0)return;let e=this.r.getDrawingBufferSize(new Z),t=this.composer=new Yl(this.r,new Rt(e.x,e.y,{type:Jt,samples:4}));t.addPass(new Kl(this.scene,this.cam)),this.tier>1?(this.bloom=new Ts(new Z(256,256),.28,.55,.88),t.addPass(this.bloom)):this.bloom=null,this.bokeh=new $l(this.scene,this.cam,{focus:8,aperture:0,maxblur:.008}),this.bokeh.enabled=!1,t.addPass(this.bokeh),this.tier>1?(this.blur=new Er(Zx),t.addPass(this.blur)):this.blur=null,t.addPass(new Zl),this.grade=new Er($x),t.addPass(this.grade)}updateGrade(){if(!this.grade)return;let e=this.world,t=e.dayLight??1,n=e.night??0,i=e.low??0,s=e.weather==="fog"||e.weather==="rain"||e.weather==="snow"?1:0,a=this.grade.uniforms,o=i*t;a.gain.value.set(1+.05*o-.07*n,1-.005*o-.03*n,1-.08*o+.06*n),a.lift.value.set(.022+.018*o,.022+.008*o+.004*n,.024+.012*n+.006*s),a.sat.value=1.05+.05*o-.22*n-.08*s,a.contrast.value=1.05+.03*o-.04*s}resize(){let e=this.canvas.clientWidth||innerWidth,t=this.canvas.clientHeight||innerHeight;this.r.setSize(e,t,!1),this.composer&&this.composer.setSize(e,t),this.cam.aspect=e/t,this.cam.updateProjectionMatrix(),this.portrait=t>e}async prepare(e){let t=new Set([e.sp0,...e.B.herd,...Object.keys(e.B.enc),...e.lvl&&e.lvl.enc?Object.keys(e.lvl.enc):[]]);if(e.B.croc&&t.add("croc"),e.side==="pred")for(let i of Object.values(e.B.hunt).flat())t.add(i);e.ghost&&t.add(Ne(e,e.ghost.id).sp);for(let i of e.agents)t.add(i.sp);let n=[...t].filter(i=>Zi[i]);await dg(n);for(let i of n)this.gltf[Zi[i].file]=await jl(Zi[i].file)}setRun(e,t={}){for(let n of this.anim.values())n.dispose();this.anim.clear(),this.run=e,this.looks=t,this.world.setRun(e),this.camState.init=!1,this.slow=0}animalFor(e){let t=this.anim.get(e.id);if(t)return t;let n=Zi[e.sp]&&Zi[e.sp].file,i=this.gltf[n];return i?(t=new Vl(e.sp,i,e.ctl===0?this.looks[e.sp]:e.pack&&this.looks[e.sp]||null),t.agent=e.id,t.lastX=e.x,t.lastZ=e.z,t.lastA=e.a,t.lastY=e.y,e.ghost&&t.setOpacity(.45),this.scene.add(t.root),this.anim.set(e.id,t),t):(jl(n).then(s=>{this.gltf[n]=s}),null)}frame(e,t,n=[],i={}){let s=this.run;if(!s)return;let a=Ne(s,s.me)||s.agents[0];for(let d of n)this.onEvent(d);let o=e*(this.slow>0?.3:1);this.slow>0&&(this.slow-=e);let l=new Set;(!this.steps||this.steps.length>40)&&(this.steps=[]),this.herdSteps=0;for(let d of this.extra&&this.extra.length?s.agents.concat(this.extra):s.agents){if(!d.alive&&!(d.gone>0))continue;let p=this.animalFor(d);if(!p)continue;l.add(d.id);let m=d.px??d.x,x=d.pz??d.z,f=d.py??d.y,g=d.pa??d.a,v=m+(d.x-m)*t,b=x+(d.z-x)*t,y=f+(d.y-f)*t,M=d.a-g;M>Math.PI&&(M-=Math.PI*2),M<-Math.PI&&(M+=Math.PI*2);let _=g+M*t;p.root.position.set(v,y,b),p.root.rotation.y=_,p.root.visible=!(d.hidden>0);let R=d.spd*(d.alive?1:0),C=M/rt,I=1.2,O=Math.sin(_),z=Math.cos(_),F=(et(s,v+O*I,b+z*I)-et(s,v-O*I,b-z*I))/(2*I),W=.5,j=(et(s,v+z*W,b-O*W)-et(s,v-z*W,b+O*W))/(2*W),Y=this.tier===0&&Math.hypot(d.x-a.x,d.z-a.z)>40&&this.frameNo&1;if(p.update(o,{speed:R,turn:C,slope:F,side:j,vy:(d.y-(d.py??d.y))/rt,air:d.air>0,crouch:d.ab==="stalk"&&d.abT>0||d.st==="hide"||d.st==="stalk"||d.st==="wait"?1:0,eat:d.eatT>0&&d.eatK!=="shade"||d.st==="graze"&&d.side==="prey"?1:0},Y),d.alive||(p.knockDown(),p.setOpacity(Math.max(0,d.gone/(30*2)))),p.steps&&d.alive&&!d.ghost){let K=v-a.x,re=b-a.z,ie=Math.hypot(K,re);if(d.id===a.id||ie<18&&(this.herdSteps=(this.herdSteps||0)+p.steps)<=3){let ge=Math.cos(a.a)*K-Math.sin(a.a)*re;for(let ye=0;ye6&&!Te[d.sp].fly&&Math.random()=0?.55:.25)*(this.tier?1:.5)){let K=d.surf==="water"?"water":d.surf==="snow"||d.surf==="drift"?"snow":d.surf==="mud"?"mud":"dust";this.world.puff(v-Math.sin(_)*.8,et(s,v,b),b-Math.cos(_)*.8,K,K==="water"?3:2,d.ctl===0?i.trail:"dust")}}for(let[d,p]of this.anim)l.has(d)||(p.dispose(),this.anim.delete(d));this.ring||(this.ring=new Je(new Pa(.85,1.1,40),new Nt({color:16762967,transparent:!0,opacity:.7,depthWrite:!1})),this.ring.rotation.x=-Math.PI/2,this.ring.renderOrder=2,this.scene.add(this.ring));let c=i.target!=null&&this.anim.get(i.target);if(this.ring.visible=!!c,c){let d=c.root.position;this.ring.position.set(d.x,et(s,d.x,d.z)+.06,d.z);let p=1+.08*Math.sin(performance.now()/180);this.ring.scale.setScalar(p*(Te[c.sp].h||1))}this.frameNo=(this.frameNo||0)+1;let h=this.anim.get(a.id),u=h?h.root.position:new S(a.x,a.y,a.z);if(this.updateCamera(e,a,u,i),this.ambient(o,a,u),this.world.setTime(s.light(),u),this.world.update(o,this.cam,u.z),this.bokeh){let d=this.slow>0&&this.tier>0;this.bokeh.enabled=d,d&&(this.bokeh.uniforms.focus.value=this.cam.position.distanceTo(u),this.bokeh.uniforms.aperture.value=25e-5*Math.min(1,this.slow*2))}this.blur&&(this.blur.uniforms.amount.value+=((a.alive&&a.spd>Te[a.sp].top*.86?.03*Math.min(1,(a.spd-Te[a.sp].top*.86)/(Te[a.sp].top*.1)):0)-this.blur.uniforms.amount.value)*Math.min(1,e*3)),this.updateGrade(),!this.noDraw&&(this.composer?this.composer.render():this.r.render(this.scene,this.cam))}ambient(e,t,n){let i=this.run;if(!this.amb){let c=new rn(new qi(.11,8,6),new Nt({color:16765562,transparent:!0,opacity:.55,depthWrite:!1}),10);c.frustumCulled=!1,c.renderOrder=2,this.scene.add(c);let h=new qe;h.setAttribute("position",new we([0,0,.1,-.32,.06,-.05,0,0,-.12,0,0,.1,.32,.06,-.05,0,0,-.12],3));let u=new rn(h,new Nt({color:2828066,side:Qn}),12);u.frustumCulled=!1,this.scene.add(u),this.amb={dot:c,birds:u,flock:[],next:6,t:0}}let s=this.amb,a=new nt;s.t+=e;let o=i.side==="pred"&&t.alive?Hc(i,t):null;if(s.dot.visible=o!=null,o!=null){let c=Math.sin(o),h=Math.cos(o);for(let u=0;u<10;u++){let d=5+u*3.2+s.t*2.2%3.2,p=n.x+c*d+Math.sin(u*1.7+s.t)*.4,m=n.z+h*d;a.position.set(p,et(i,p,m)+.5+Math.sin(s.t*2+u)*.12,m),a.scale.setScalar(1-u*.06),a.updateMatrix(),s.dot.setMatrixAt(u,a.matrix)}s.dot.instanceMatrix.needsUpdate=!0}if(s.next-=e,s.next<=0&&this.tier>=0){s.next=9+Math.random()*8;let c=t.a,h=16+Math.random()*10,u=(Math.random()-.5)*16,d=n.x+Math.sin(c)*h+Math.cos(c)*u,p=n.z+Math.cos(c)*h-Math.sin(c)*u,m=et(i,d,p);s.flock=Array.from({length:8+Math.floor(Math.random()*5)},()=>({x:d+(Math.random()-.5)*3,y:m+.2,z:p+(Math.random()-.5)*3,vx:(Math.random()-.5)*3+Math.cos(c)*(u>0?2:-2),vy:2.5+Math.random()*2,vz:Math.cos(c)*4+(Math.random()-.5)*2,ph:Math.random()*6,life:0}))}let l=0;for(let c of s.flock){if(c.life+=e,c.life>6)continue;c.x+=c.vx*e,c.y+=c.vy*e,c.z+=c.vz*e,c.vy*=.995,a.position.set(c.x,c.y,c.z),a.rotation.set(0,Math.atan2(c.vx,c.vz),0);let h=Math.sin(s.t*22+c.ph);a.scale.set(1,1+h*.9,1),a.updateMatrix(),s.birds.setMatrixAt(l++,a.matrix)}s.birds.count=l,s.birds.instanceMatrix.needsUpdate=!0,s.birds.visible=l>0}updateCamera(e,t,n,i){let s=this.camState,a=this.cam,o=Te[t.sp].fly,l=Te[t.sp].h,c=(this.portrait?4.6:6)*(.75+l*.35)+(o?3:0)+Math.min(this.portrait?1.2:3,t.spd*(this.portrait?.06:.12)),h=(this.portrait?2:2.6)*(.7+l*.35)+(o?2:0),u=this.anim.get(t.id),d=u?u.root.rotation.y:t.a,p=d;s.orbit&&(p+=s.orbit);let m=1-Math.exp(-e*3.2);s.init||(s.yaw=p,s.init=!0,s.pos.set(n.x-Math.sin(p)*c,n.y+h,n.z-Math.cos(p)*c));let x=p-s.yaw;x>Math.PI&&(x-=Math.PI*2),x<-Math.PI&&(x+=Math.PI*2),s.yaw+=x*m*.9;let f=new S(n.x-Math.sin(s.yaw)*c,n.y+h,n.z-Math.cos(s.yaw)*c),g=et(this.run,f.x,f.z)+1.2;f.yM.x0-1.5&&CM.z0-1.5&&I25?s.pos.copy(f):s.pos.lerp(f,1-Math.exp(-e*6));let v=4+Math.min(4,t.spd*.25);if(s.lookS||(s.lookS=new S(n.x+Math.sin(d)*v,n.y+l*.8,n.z+Math.cos(d)*v)),s.lookS.lerp(new S(n.x+Math.sin(d)*v,n.y+l*.8,n.z+Math.cos(d)*v),1-Math.exp(-e*8)),s.look.copy(s.lookS),a.position.copy(s.pos),s.shake>0){s.shake-=e;let y=s.shake*.25*(i.motion??1);a.position.x+=(Math.random()-.5)*y,a.position.y+=(Math.random()-.5)*y}a.lookAt(s.look);let b=(this.portrait?58:56)+Math.min(this.portrait?6:16,Math.max(0,t.spd-8)*(this.portrait?.6:1.6))*(i.motion??1)-(this.slow>0?6:0);s.fov+=(b-s.fov)*m,a.fov=s.fov,a.updateProjectionMatrix()}onEvent(e){let t=this.run,n=e.id&&Ne(t,e.id);switch(e.t){case"close":this.slow=.75,this.camState.shake=.25;break;case"catch":{let i=this.anim.get(e.id);i&&i.knockDown();let s=this.anim.get(e.by);s&&s.play("roar"),e.me&&(this.slow=1.1,this.camState.shake=.4);break}case"pounce":{let i=this.anim.get(e.id);i&&i.play("jump");break}case"roar":{let i=this.anim.get(e.id);i&&i.play("roar");break}case"kickHit":this.camState.shake=.2;break;case"stumble":n&&n.ctl===0&&(this.camState.shake=.3);break;case"burrow":case"pop":n&&this.world.puff(n.x,n.y,n.z,"dust",6);break;case"snap":case"ripple":n&&this.world.puff(n.x,n.y+.3,n.z,"water",e.t==="snap"?14:5);break;case"land":n&&n.ctl>=0&&this.world.puff(n.x,n.y,n.z,n.surf==="water"?"water":"dust",5);break;default:break}}snapshot(e=1080,t=1080){let n=document.createElement("canvas");n.width=e,n.height=t;let i=n.getContext("2d"),s=this.r.domElement,a=Math.max(e/s.width,t/s.height);return i.drawImage(s,(e-s.width*a)/2,(t-s.height*a)/2,s.width*a,s.height*a),n}};var xe=null,wi,za,Cs,Ji,Rs,tc,Es={music:.55,sfx:.85},$d=!1,Zd=[],gg={savanna:[57,60,64,67],forest:[55,58,62,65],snow:[52,55,59,62],canyon:[50,53,57,60],wetlands:[53,57,60,64]},ec=r=>440*Math.pow(2,(r-69)/12),Jd=r=>(...e)=>{try{if(xe)return r(...e)}catch(t){Zd.push(String(t).slice(0,120))}return null},Cr={},bg={steps:[0,.5,1,1.5,2,2.5].map(r=>[r,.45]),growls:[[0,3.6],[3.66,2.6],[6.34,2.2]]};function Fa(){if(xe){xe.state==="suspended"&&xe.resume();return}try{xe=new(window.AudioContext||window.webkitAudioContext)}catch{xe=null;return}let r=xe.createBiquadFilter();r.type="highshelf",r.frequency.value=5e3,r.gain.value=-8;let e=xe.createBiquadFilter();e.type="lowpass",e.frequency.value=11e3,e.Q.value=.5;let t=xe.createDynamicsCompressor();t.threshold.value=-20,t.ratio.value=2.5,t.knee.value=12,t.attack.value=.02,t.release.value=.3;let n=xe.createDynamicsCompressor();n.threshold.value=-4,n.ratio.value=20,n.knee.value=2,n.attack.value=.003,n.release.value=.15,wi=xe.createGain(),wi.gain.value=$d?0:.85,wi.connect(r),r.connect(e),e.connect(t),t.connect(n),n.connect(xe.destination),za=xe.createGain(),Cs=xe.createGain(),Ji=xe.createGain(),za.connect(wi),Cs.connect(wi),Ji.connect(wi),Rs=xe.createConvolver(),Rs.buffer=Jx(2.4,2.2);let i=xe.createGain();i.gain.value=.22,Rs.connect(i),i.connect(wi),nc(Es),tc=xe.createBuffer(1,xe.sampleRate*2,xe.sampleRate);let s=tc.getChannelData(0),a=0,o=0,l=0;for(let c=0;cxe.decodeAudioData(t,n,i)),(r==="wind"||r==="birds")&&ty(r)}catch{}}function nc(r){Es={...Es,...r},xe&&(za.gain.value=Es.music*.42,Cs.gain.value=Es.sfx*.9,Ji.gain.value=Es.sfx*.7)}function ic(r){$d=!!r,wi&&wi.gain.setTargetAtTime($d?0:.85,xe.currentTime,.05)}function Qd(r,e,t,n=0){let i=xe.createStereoPanner?xe.createStereoPanner():null;if(i){if(i.pan.value=Math.max(-1,Math.min(1,t||0)),r.connect(i),i.connect(e),n){let s=xe.createGain();s.gain.value=n,i.connect(s),s.connect(Rs)}}else r.connect(e)}function zt(r,{type:e="bandpass",f:t=800,q:n=1,gain:i=.3,attack:s=.005,dest:a=Cs,f2:o=null,pan:l=0,when:c=0,wet:h=0}={}){let u=xe.currentTime+c,d=xe.createBufferSource();d.buffer=tc,d.playbackRate.value=.85+Math.random()*.3;let p=xe.createBiquadFilter();p.type=e,p.frequency.setValueAtTime(t,u),p.Q.value=n,o&&p.frequency.exponentialRampToValueAtTime(o,u+r);let m=xe.createGain();m.gain.setValueAtTime(1e-4,u),m.gain.linearRampToValueAtTime(i,u+s),m.gain.exponentialRampToValueAtTime(1e-4,u+r),d.connect(p),p.connect(m),Qd(m,a,l,h),d.start(u,Math.random()),d.stop(u+r+.05)}function gt(r,e,{type:t="sine",gain:n=.2,attack:i=.01,f2:s=null,dest:a=Cs,lp:o=0,when:l=0,pan:c=0,wet:h=0}={}){let u=xe.currentTime+l,d=xe.createOscillator();d.type=t,d.frequency.setValueAtTime(r,u),s&&d.frequency.exponentialRampToValueAtTime(s,u+e);let p=xe.createGain();p.gain.setValueAtTime(1e-4,u),p.gain.linearRampToValueAtTime(n,u+i),p.gain.exponentialRampToValueAtTime(1e-4,u+e);let m=d;if(o){let x=xe.createBiquadFilter();x.type="lowpass",x.frequency.value=o,d.connect(x),m=x}m.connect(p),Qd(p,a,c,h),d.start(u),d.stop(u+e+.05)}function ep(r,e,{rate:t=1,lp:n=4e3,gain:i=.5,pan:s=0,when:a=0,dest:o=Cs,wet:l=0,attack:c=.004}={}){let h=Cr[r];if(!h)return!1;let[u,d]=bg[r][e%bg[r].length],p=xe.currentTime+a,m=xe.createBufferSource();m.buffer=h,m.playbackRate.value=t;let x=xe.createBiquadFilter();x.type="lowpass",x.frequency.value=n,x.Q.value=.4;let f=xe.createGain(),g=d/t;return f.gain.setValueAtTime(1e-4,p),f.gain.linearRampToValueAtTime(i,p+c),f.gain.setTargetAtTime(1e-4,p+g*.7,g*.12),m.connect(x),x.connect(f),Qd(f,o,s,l),m.start(p,u,d),!0}var Oa,wg,Tg,Eg,Ag,Rg,As,sn={biome:"savanna",night:0,weather:"clear",water:0},vg=0,Kd=0,xg=0,yg=0;function Ql(r,e,t){let n=xe.createBufferSource();n.buffer=tc,n.loop=!0;let i=xe.createBiquadFilter();i.type=r,i.frequency.value=e,i.Q.value=t;let s=xe.createGain();return s.gain.value=0,n.connect(i),i.connect(s),s.connect(Ji),n.start(),[s,i]}function ey(){[Tg,wg]=Ql("lowpass",380,.5),[Eg]=Ql("bandpass",3200,.6),[Ag]=Ql("bandpass",900,.5),[Rg]=Ql("highpass",2400,.4),Oa=xe.createGain(),Oa.gain.value=0,Oa.connect(Ji),As=xe.createGain(),As.gain.value=0,As.connect(Ji);let r=xe.createGain();r.gain.value=.25,As.connect(r),r.connect(Rs)}function ty(r){let e=xe.createBufferSource();e.buffer=Cr[r],e.loop=!0;let t=xe.createBiquadFilter();t.type="lowpass",t.frequency.value=r==="wind"?2200:7e3,e.connect(t),t.connect(r==="wind"?Oa:As),e.start(0,Math.random()*Cr[r].duration)}var Cg=Jd(r=>{sn={...sn,...r}}),Ti,Rr,Ar=0,_g=0,Mg=0,Sg=0;function ny(){Ti=xe.createGain(),Ti.gain.value=0,Rr=xe.createBiquadFilter(),Rr.type="lowpass",Rr.frequency.value=1200,Rr.Q.value=.3,Rr.connect(Ti),Ti.connect(za);let r=xe.createGain();r.gain.value=.6,Ti.connect(r),r.connect(Rs),Ti.oscs=[];for(let e=0;e<4;e++)for(let[t,n,i]of[["sine",-4,.06],["triangle",5,.03]]){let s=xe.createOscillator();s.type=t,s.detune.value=n;let a=xe.createOscillator();a.frequency.value=.07+e*.023;let o=xe.createGain();o.gain.value=3,a.connect(o),o.connect(s.detune),a.start();let l=xe.createGain();l.gain.value=i,s.connect(l),l.connect(Rr),s.start(),Ti.oscs.push(s)}Pg(0)}function Pg(r){let e=gg[sn.biome]||gg.savanna,t=[[0,0,0,0],[-2,0,-1,0],[-4,-3,-4,-2],[-2,-1,0,0]][r%4];Ti.oscs.forEach((n,i)=>n.frequency.setTargetAtTime(ec(e[i>>1]+t[i>>1]-12),xe.currentTime,1.6))}var Ig=Jd(r=>{let e=xe.currentTime,t=Math.min(.1,r.dt||.016),n=r.speed||0;sn.biome=r.biome||sn.biome,(vg-=t)<0&&(vg=2+Math.random()*5,Kd=Math.random());let i=r.weather,a=(i==="snow"||i==="dust"?.42:i==="rain"?.3:.18)*(.7+Kd*.5)+Math.min(.14,n*.008);Oa.gain.setTargetAtTime(Cr.wind?a:0,e,.8),Tg.gain.setTargetAtTime(Cr.wind?a*.25:a*.6,e,.8),wg.frequency.setTargetAtTime(260+n*28+Kd*120,e,.6),Eg.gain.setTargetAtTime(r.playing&&!r.flying&&["grass","reed","fern"].includes(r.surface)?Math.min(.05,n*.003):0,e,.25),Ag.gain.setTargetAtTime(r.nearWater?.12:0,e,.6),Rg.gain.setTargetAtTime(i==="rain"?.06:0,e,.8);let o=!r.night||r.night<.5;if(As.gain.setTargetAtTime(o&&i!=="rain"&&i!=="snow"?sn.biome==="snow"?.18:.42:0,e,2.5),!Cr.birds&&o&&i!=="rain"&&(xg-=t)<0&&(xg=2.5+Math.random()*5,ry()),r.night>.6&&(yg-=t)<0){yg=.5+Math.random()*.8;let l=Math.random()-.5;for(let c=0;c<3;c++)gt(3400+Math.random()*200,.05,{gain:.005,when:c*.06,pan:l,attack:.01,dest:Ji,lp:4500,wet:.4})}if(Ar+=((r.threat||0)-Ar)*Math.min(1,t*1.2),Ti.gain.setTargetAtTime(r.playing?.3:.22,e,1.5),Rr.frequency.setTargetAtTime(900+Ar*900,e,.8),(Sg-=t)<0&&(Sg=6-Ar*2,Mg++,Pg(Mg)),r.playing&&Ar>.2&&(_g-=t)<0&&(_g=.75-Ar*.25,gt(55,.5,{gain:.1*Ar,f2:48,attack:.03,dest:za,lp:200})),sn.fallT=Math.max(0,(sn.fallT||0)-t*16),r.playing)for(let l of r.steps||[])l.far&&sn.fallT>3||(sn.fallT++,Lg(r.surface,l));if(r.playing&&r.breath!==!1){let l=1-(r.stamina??1),c=Math.min(1,n/Math.max(1,(r.top||14)*.6));sn.breathT=(sn.breathT??1)-t*(c>.3&&r.stride?r.stride:.45+l*.8),sn.breathT<0&&(sn.breathT=1,iy((.012+c*.02+l*.035)*.6,r.big||1))}});function Lg(r,e){let t=Math.max(.15,e.k??.5),n=e.far||0,i=(1-n*.8)*(.5+.5*t),s=e.big||1,a=e.pan||0,o={snow:.6,drift:.6,mud:.7,water:.5,grass:.8,reed:.8,fern:.8,litter:.85}[r]??1,l=(e.hoof?.62:.5)/Math.sqrt(s)*(.94+Math.random()*.12),c=ep("steps",Math.floor(Math.random()*6),{rate:l,lp:e.hoof?800:500,gain:(n?.1:.2)*i*o,pan:a,attack:.003});gt((e.hoof?80:62)/Math.sqrt(s),.12,{gain:(c?.07:.1)*i,f2:42,attack:.003,lp:200,pan:a}),r==="water"?zt(.22,{f:1100,q:.6,gain:.07*i,attack:.01,pan:a}):r==="snow"||r==="drift"?zt(.12,{f:1800,q:1.4,gain:.03*i,attack:.004,pan:a}):r==="litter"&&zt(.09,{f:2600,q:1.2,gain:.02*i,attack:.003,pan:a})}function iy(r,e){let t=520/Math.sqrt(e);zt(.28,{f:t,q:1.6,gain:r,attack:.05,f2:t*.8}),zt(.22,{f:t*2.1,q:2.2,gain:r*.35,attack:.05}),zt(.18,{f:t*1.4,q:1.5,gain:r*.3,attack:.08,when:.3})}function ry(){let r=2300+Math.random()*1200,e=2+Math.floor(Math.random()*3),t=Math.random()*1.6-.8;for(let n=0;n{let t=e.pan||0,i=1-(e.far??0)*.7;switch(r.t){case"roar":sy(i*(e.sp==="bear"?1:.9),t,e.sp==="bear"?.85:1,e.sp==="lion"?0:1);break;case"spawn":r.k==="wolf"&&ay(i);break;case"screech":gt(1700,.6,{type:"sine",gain:.012*i,f2:1250,attack:.08,lp:2200,pan:t,wet:.5});break;case"snap":zt(.45,{type:"lowpass",f:700,q:.6,gain:.12*i,attack:.01,pan:t}),gt(70,.3,{gain:.12*i,f2:40,pan:t,lp:200});break;case"ripple":zt(.6,{f:600,q:.8,gain:.04*i,attack:.15,pan:t});break;case"close":zt(.45,{type:"bandpass",f:380,f2:1600,q:1.2,gain:.07,attack:.04}),oy();break;case"jump":case"leap":zt(.25,{type:"lowpass",f:900,gain:.04,attack:.03});break;case"land":gt(62,.2,{gain:.12,f2:40,lp:200}),ep("steps",2,{rate:.45,lp:900,gain:.5});break;case"dodge":zt(.2,{type:"lowpass",f:1200,f2:600,gain:.05,attack:.02});break;case"kick":case"kickHit":gt(80,.2,{gain:.18,f2:45,attack:.003,lp:250}),zt(.1,{type:"lowpass",f:800,gain:.06});break;case"stumble":gt(58,.25,{gain:.16,f2:40,lp:200}),zt(.25,{type:"lowpass",f:600,gain:.07});break;case"burrow":case"pop":zt(.3,{type:"lowpass",f:600,gain:.06,attack:.03});break;case"stampede":for(let s=0;s<14;s++)Lg("dirt",{k:.8,hoof:!0,big:1.4,pan:Math.random()-.5,far:.2+Math.random()*.3,_:s});break;case"surge":case"burst":zt(.6,{type:"lowpass",f:500,f2:1200,gain:.05,attack:.1});break;case"catch":e.me?(gt(196,1.4,{type:"sine",gain:.06,f2:147,attack:.05,wet:.5}),gt(147,1.6,{type:"sine",gain:.05,when:.2,f2:110,wet:.5})):zt(.5,{type:"lowpass",f:400,gain:.05*i,attack:.03,pan:t});break;case"win":[0,4,7,12].forEach((s,a)=>gt(ec(64+s),.9,{type:"sine",gain:.05,when:a*.14,attack:.03,wet:.5}));break;case"alarm":gt(900+Math.random()*200,.14,{gain:.008*i,f2:700,pan:t,lp:1500});break;case"cmd":gt(392,.4,{type:"sine",gain:.035,f2:440+(r.cmd||0)*40,attack:.04,wet:.3});break;case"click":gt(660,.05,{gain:.02,lp:2e3});break;case"graze":case"drink":case"rest":e.me!==!1&&!e.far&&zt(.5,{type:"lowpass",f:500,gain:.025,attack:.08});break;case"shoot":gt(ec(76+Math.min(5,r.n||0)),.18,{type:"sine",gain:.025,attack:.01,wet:.4});break;case"obj":r.done&&[0,4,7].forEach((s,a)=>gt(ec(69+s),.5,{type:"sine",gain:.03,when:a*.1,wet:.5}));break;case"warn":gt(196,.32,{type:"sine",gain:.05,attack:.03,lp:900}),gt(147,.45,{type:"sine",gain:.045,attack:.04,when:.18,lp:700});break;default:break}});function sy(r,e,t=1,n=0){ep("growls",n,{rate:.8*t,lp:600,gain:.3*r,pan:e,attack:.12,wet:.35})||(zt(1,{type:"lowpass",f:240,q:1.2,gain:.18*r,attack:.15,pan:e}),gt(58,.9,{type:"triangle",gain:.05*r,lp:220,attack:.15,pan:e}))}function ay(r){gt(380,1.9,{type:"sine",gain:.018*r,f2:560,attack:.5,pan:Math.random()-.5,lp:1200,wet:.7}),gt(560,1.5,{type:"sine",gain:.012*r,f2:430,attack:.3,when:1.5,lp:1200,wet:.7})}function oy(){for(let r=0;r<3;r++)gt(52,.16,{gain:.12,f2:40,when:r*.6,lp:150}),gt(48,.14,{gain:.08,f2:38,when:r*.6+.2,lp:150})}var cp={};Vp(cp,{API:()=>Is,DELAY:()=>Ps,GAME:()=>rc,Ghost:()=>Ha,Lockstep:()=>Ga,MAX_PLAYERS:()=>kg,board:()=>rp,challengeLink:()=>tp,challengeResult:()=>ip,joinRoom:()=>lp,liveFlag:()=>ap,post:()=>sp,readChallenge:()=>np,roomMode:()=>cy,roomOpts:()=>op});var Is="https://toys.cybermaxtools.com",rc="veldbolt",Ps=4,kg=6;function tp(r,e,t,n=""){let i=Ne(e,e.me),s=jc({seed:e.seed,biome:e.biome,side:e.side,sp:i.sp,tod:e.tod,weather:e.weather,taps:oi(t),name:n,score:e.score}),a=new URL(r);return a.search="",a.hash="",a.searchParams.set("ch",s),a.toString()}function np(r){let e=new URLSearchParams(r);return e.get("ch")?qc(e.get("ch")):null}function ip(r,e){if(r.side==="pred"){let i=r.hunts>0||r.agents.some(s=>s.ghost&&!s.alive);return{won:i,line:i?`You caught ${e.name||"their"} run.`:`${e.name||"They"} got away.`}}let t=r.ghost&&r.tick>(r.ghost.inputs.length?r.ghost.inputs[r.ghost.inputs.length-1][0]:0)+30*3,n=r.result!=="caught"||t;return{won:n,line:n?`You outran ${e.name||"their"} hunter.`:`${e.name||"Their"} hunter caught you.`}}var Ha=class{constructor(e,t){this.run=ai(e.seed,e),this.inputs=t,this.i=0}stepTo(e){let t=this.run;for(;!t.over&&t.ticknew URLSearchParams(location.search).get("live")==="1",cy=ao,op=oo,Ga=class{constructor(e,t){this.n=e,this.me=t,this.q=Array.from({length:e},()=>[]),this.done=new Array(e).fill(-1),this.sentTo=-1,this.pending=[]}local(e,t,n){let i=e+Ps;this.q[this.me].push([i,t]),n({t:"in",k:i,c:t})}heartbeat(e,t){let n=e+Ps;n-this.sentTo>=Ps-1&&(this.sentTo=n,this.done[this.me]=n,t({t:"in",k:n,c:-1}))}remote(e,t,n){e<0||e>=this.n||(n>=0&&this.q[e].push([t,n]),this.done[e]=Math.max(this.done[e],t))}ready(e){for(let t=0;t{try{i&&i.readyState===1&&i.send(JSON.stringify(l))}catch{}},close:()=>{try{i&&i.close()}catch{}}};try{i=new WebSocket(`${Is.replace(/^http/,"ws")}/api/room?g=${rc}&code=${r}&p=${t}&nick=${encodeURIComponent(e)}`)}catch{return n.status("Live rooms are not open yet."),o}return i.onerror=()=>n.status("Live rooms are not open yet."),i.onclose=()=>n.status("Room closed."),i.onmessage=l=>{let c;try{c=JSON.parse(l.data)}catch{return}if(c.t==="room")s=c.players||[],a=s.findIndex(h=>h.p===t),n.roster(s,c.host,a);else if(c.t==="start")n.start(c.seed>>>0,c.in??3e3,Math.min(kg,s.length),a);else if(c.t==="in"){let h=s.findIndex(u=>u.p===c.p);n.input(h,c.k|0,c.c|0)}else c.t==="result"&&n.result(c.rows||[])},o}var Dg="cmx-ft";var Ls=(r,e)=>String(r||"").toLowerCase().replace(/^www\./,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+/,"").slice(0,e).replace(/-+$/,""),hy=r=>r.replace(/(^|-)(test|e2e|check|probe|audit|lane\d*|internal)(?=-|$)/g,"$1x");function uy(r,e){let t=new URLSearchParams(r.search||""),n=t.get("utm_source"),i=t.get("utm_campaign"),s=t.get("s"),a;if(n)a=Ls(n,14)+(i?`-${Ls(String(i).replace(/^\d{4}-\d{2}-\d{2}-(\d+-)?/,""),18)}`:"");else if(s)a=`s-${Ls(s,24)}`;else{let c="";try{c=e?new URL(e).hostname.toLowerCase():""}catch{c="other"}a=c?/(^|\.)cybermaxtools\.com$|cybermax-tools/.test(c)?`site-${Ls(c.split(".")[0],12)}`:`r-${Ls(c,24)}`:"direct"}let o=String(r.pathname||"/").toLowerCase().split("/").filter(c=>c&&!/^index\.html?$/.test(c)),l=Ls(o.slice(-2).join("-"),18)||"home";return hy(`ft-${a||"direct"}-at-${l}`).slice(0,48).replace(/-+$/,"")}function Ug(){try{let r=JSON.parse(localStorage.getItem(Dg)||"null");if(r&&r.t&&Date.now()-r.at<90*864e5)return r.t;let e=uy(location,document.referrer);return localStorage.setItem(Dg,JSON.stringify({t:e,at:Date.now()})),e}catch{return""}}function dy(r,e){if(!e)return r;try{let t=new URL(r);if(t.hostname==="data.cybermaxtools.com"&&t.pathname.startsWith("/buy/")){let n=(t.searchParams.get("s")||"unknown").toLowerCase().replace(/[^a-z0-9-]/g,"");return n.includes("--ft-")?r:(t.searchParams.set("s",`${n}--${e}`.slice(0,80).replace(/-+$/,"")),t.toString())}if(t.hostname==="buy.stripe.com"){let n=t.searchParams.get("client_reference_id")||"data_unknown";return n.includes("--ft-")?r:(t.searchParams.set("client_reference_id",`${n}--${e}`.slice(0,200)),t.toString())}}catch{}return r}typeof document<"u"&&typeof location<"u"&&!window.__cmxFt&&(window.__cmxFt=1,Ug(),document.addEventListener("click",r=>{let e=r.target&&r.target.closest&&r.target.closest('a[href*="data.cybermaxtools.com/buy/"],a[href*="buy.stripe.com/"]');if(e){let t=Ug();t&&(e.href=dy(e.href,t))}},!0));var Ng="https://data.cybermaxtools.com",hp=/^cs_(live|test)_[A-Za-z0-9]{10,200}$/,py="https://cybermaxtools.com/terms#payments",pn=r=>String(r).replace(/[&<>"]/g,e=>({"&":"&","<":"<",">":">",'"':"""})[e]),Ei={get(r){try{return localStorage.getItem(r)}catch{return null}},set(r,e){try{e==null?localStorage.removeItem(r):localStorage.setItem(r,e)}catch{}}},up=()=>typeof document<"u"&&(!!document.querySelector('meta[name="cmx-portal"]')||!!(window.CMXPortal&&window.CMXPortal.portal));function Og(r){let e=r.fetch||((...f)=>fetch(...f)),t=`${r.game}:iap-pending`,n=()=>{let f=Ei.get("cmx-device");if(!f||!/^[A-Za-z0-9_-]{8,64}$/.test(f)){let g=crypto.getRandomValues(new Uint8Array(12));f=btoa(String.fromCharCode(...g)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),Ei.set("cmx-device",f)}return f},i=(f,g="shop")=>`${Ng}/buy/st-${r.game}-shop-${f}?s=game-${r.game}-${g}`,s=()=>r.offers.filter(f=>f.coins&&!f.looks),a=f=>s().find(g=>g.coins>=f)||s()[s().length-1],o=!1;async function l(f,g=!1){if(f=String(f||"").trim(),g&&r.preRedeem&&f&&!o){o=!0;let v;try{v=await r.preRedeem(f)}finally{o=!1}if(v==="ok"||v==="pass")return v}if(!hp.test(f))return r.toast("Paste the order code from your receipt page (it starts with cs_live_).",3500),"bad";if(r.has(f))return Ei.set(t,null),r.toast("That order is already added on this device.",3e3),"dup";if(o)return"busy";o=!0;try{let v,b;try{v=await e(`${Ng}/unlock/${r.game}-shop/redeem`,{method:"POST",headers:{"content-type":"text/plain"},body:JSON.stringify({code:f,device:n()})}),b=await v.json()}catch{b=null}if(b&&b.ok){r.credit({coins:b.coins||0,looks:b.looks||[],all:!!b.all,ref:b.ref},f),Ei.set(t,null);let y=r.offers.find(M=>M.ref===b.ref);return r.toast(`${y?y.name:"Your order"} added${b.coins?`: +${b.coins.toLocaleString("en-US")} coins`:""}. Thank you!`,4e3),r.count("pro",`shop-${b.ref}`),"ok"}return b&&b.error==="already_redeemed"?(Ei.set(t,null),b.looks&&b.looks.length||b.all?(r.credit({coins:0,looks:b.looks||[],all:!!b.all,ref:b.ref},f),r.toast("Looks restored. The coins of an order are added once, and these already were.",4500),"restored"):(r.toast(b.message||"Those coins were already added (each order adds its coins once).",4e3),"used")):b&&v&&(v.status===400||v.status===402||v.status===404)?(v.status!==402&&Ei.set(t,null),r.toast(b.message||"That code is not a paid order from this shop.",4e3),"refused"):(Ei.set(t,f),r.toast(b&&b.message||"Could not reach the shop check. Your order is safe; we will try again next time you open the game.",4500),"later")}finally{o=!1}}function c(){if(up())return;let f=new URLSearchParams(location.search),g=/[#&]cmx-pro=([^&]+)/.exec(location.hash||"");if(f.get("unlock")==="shop"&&g){let b=decodeURIComponent(g[1]);f.delete("unlock"),history.replaceState(null,"",location.pathname+(f.toString()?`?${f}`:"")),hp.test(b)&&(Ei.set(t,b),l(b));return}let v=Ei.get(t);v&&hp.test(v)&&l(v)}let h=f=>(r.catalog||[]).find(g=>g.offer===f)||{},u=f=>``,d=f=>Math.round(parseFloat(String(f).replace(/[^0-9.]/g,""))*100)||0;function p(f,g,v="",b=""){let y=g?`${pn(f.price)}${f.per?`${pn(f.per)}`:""}`:"";return{cents:f.cents||0,html:`
${u(f)}
${pn(f.name)}What you get: ${pn(f.what)}${b}
${y}
`}}function m(f="shop",g=""){let b=[...r.offers.map(y=>{let M=h(`st-${r.game}-shop-${y.ref}`);return{cents:M.cents||d(y.price),html:`
${u(M)}
${pn(y.name)}What you get: ${pn(y.what)}
${pn(y.price)}
`}}),...r.rows?r.rows(f,p):[]].sort((y,M)=>y.cents-M.cents);return`${g?`

${g}

`:""}${r.extra?r.extra(f):""}
${b.map(y=>y.html).join("")}

${pn(r.fair||"Looks only: coins and packs never change speed, score or the daily board.")} One-time payments unless marked /month or /year, by secure Stripe checkout; your coins are added when you come back here. Coins live in this browser like the rest of your progress. 14-day promise: if it doesn't work as described, we fix it or refund you (terms). Prices in USD, + tax where applicable.

`+(r.foot?`

${r.foot}

`:"")+'
Already paid?
'}function x(f){for(let v of f.querySelectorAll("a.shop-buy"))v.addEventListener("click",()=>r.count("cta",v.dataset.ref?`shop-buy-${v.dataset.ref}`:`buy-${String(v.dataset.offer).replace(/^st-/,"")}`.slice(0,40)));for(let v of f.querySelectorAll("a.cplus-buy"))v.addEventListener("click",()=>r.count("cta","campaign-buy"));let g=f.querySelector(".shop-code form");g&&g.addEventListener("submit",v=>{v.preventDefault(),l(g.querySelector("input").value,!0)})}return{capture:c,redeem:l,html:m,bind:x,buyUrl:i,packFor:a,device:n,portal:up,row:p}}(()=>{if(typeof document>"u"||window.__cmxBd)return;window.__cmxBd=1;let r=null;try{r=JSON.parse(sessionStorage.getItem("cmx-bd")||"null")}catch{}!r&&!up()&&fetch("https://cybermaxtools.com/store/buy-direct.json").then(e=>e.json()).then(e=>{r=e;try{sessionStorage.setItem("cmx-bd",JSON.stringify(e))}catch{}}).catch(()=>{}),document.addEventListener("click",e=>{let t=e.target&&e.target.closest&&e.target.closest('a[href*="data.cybermaxtools.com/buy/"]');if(!(!t||!r||!r.offers))try{let n=new URL(t.href),i=/^\/buy\/([a-z0-9-]+)\/?$/.exec(n.pathname),s=i&&r.offers[i[1]];if(!s)return;let a=String(n.searchParams.get("s")||"unknown").toLowerCase().replace(/[^a-z0-9-]/g,"").slice(0,80)||"unknown";t.href=s.split(r.ph).join(a),navigator.webdriver||navigator.sendBeacon(n.href+(n.search?"&":"?")+"b=1")}catch{}},!0)})();var zg="https://data.cybermaxtools.com",en={snow:{app:"veldbolt-snow",name:"Snow Pack",price:"$1.99",what:"The Snow biome, its 5-run chapter and the rabbit."},canyon:{app:"veldbolt-canyon",name:"Canyon Pack",price:"$1.99",what:"The Canyon biome with its rock walls and its 5-run chapter."},wetlands:{app:"veldbolt-wetlands",name:"Wetlands Pack",price:"$2.99",what:"The Wetlands biome, river crossings, its 5-run chapter and the wild horse."},wild:{app:"veldbolt-wild",name:"Wild Pass",price:"$4.99",what:"Everything: every biome and chapter, every animal and the full Predator mode (leopard, wolf pack, bear, eagle)."},looks:{app:"veldbolt-looks",name:"Coat & Trail Pack",price:"$0.99",what:"Every coat colour (real colour morphs) and every trail. Looks only."}},Fg=(r,e)=>`${zg}/buy/st-${en[r].app}-unlock?s=game-veldbolt-${e}`,dp="vb-own",Va="cmx-pro:fun-pass",fy=/^(cs_(live|test)_[A-Za-z0-9]{10,200}|[A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8})$/i,my=/^cmxk1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,gy=3*864e5,by="u0FDxbu0d9B9Sz5-yLT6AuL5IagyTlFcbBgEDqZxWtk",pp=r=>{try{return JSON.parse(localStorage.getItem(r)||"null")}catch{return null}},Wa=(r,e)=>{try{e==null?localStorage.removeItem(r):localStorage.setItem(r,JSON.stringify(e))}catch{}},sc=r=>{for(r=r.replace(/-/g,"+").replace(/_/g,"/");r.length%4;)r+="=";return Uint8Array.from(atob(r),e=>e.charCodeAt(0))};function Bg(r){let e=r.fetch||((...d)=>fetch(...d)),t=()=>pp(dp)||{},n=()=>{let d=pp(Va);return!!(d&&d.code)},i=d=>{let p=t()[d];return!!(p&&p.code&&!p.pend)},s=d=>n()||i("arcade")||i("wild")&&d!=="looks"||i(d),a=()=>{try{r.onChange()}catch{}};async function o(d,p){try{let x=await(await e(`${zg}/unlock/${p}?json=1&session_id=${encodeURIComponent(d)}`)).json();return x&&typeof x.pro=="boolean"?x.pro:null}catch{return null}}async function l(d,p){let[m,x,f]=d.split("."),g;try{g=JSON.parse(new TextDecoder().decode(sc(x)))}catch{return!1}if(!g||g.a!==p)return!1;try{let v=await crypto.subtle.importKey("raw",sc(by),{name:"Ed25519"},!1,["verify"]);if(await crypto.subtle.verify({name:"Ed25519"},v,sc(f),new TextEncoder().encode(`${m}.${x}`))&&(!g.x||g.x*1e3>Date.now()))return!0}catch{}return g.c?o(g.c,p):!1}function c(d,p,m){let x=t();x[d]={code:p,...m?{key:m}:{},at:new Date().toISOString()},Wa(dp,x),r.count("pro",`veldbolt-${d}`),r.toast(`${d==="arcade"?"CyberMax Arcade":en[d].name} is on. Thank you!`,4e3),a()}async function h(d,p="",{key:m="",quiet:x=!1}={}){let f=String(d||"").trim();if(my.test(f))return h("",p,{key:f,quiet:x});if(!f&&!m)return"bad";if(m){let b="";try{b=JSON.parse(new TextDecoder().decode(sc(m.split(".")[1]))).a}catch{}let y=Object.keys(en).find(M=>en[M].app===b);if(y&&await l(m,b)===!0)return c(y,f||m,m),"ok"}if(!fy.test(f))return"bad";let g=p?[p]:["wild","wetlands","snow","canyon","looks"],v=!1;for(let b of g){let y=await o(f,en[b].app);if(y===!0)return c(b,f),"ok";y===null&&(v=!0)}if(await o(f,"arcade")===!0)return c("arcade",f),"ok";if(await o(f,"fun-pass")===!0)return Wa(Va,{code:f,at:new Date().toISOString(),checked:Date.now()}),r.toast("Fun Pass is on: everything in Savanna Chase is open.",4e3),a(),"pass";if(v){if(p){let b=t();b[p]={code:f,pend:!0},Wa(dp,b)}return x||r.toast("Could not reach the order check. Your order is safe: we will try again next time.",4500),"later"}return x||r.toast("That code is not a Savanna Chase order.",3500),"no"}async function u(){if(r.portal())return null;let d=new URLSearchParams(location.search),p=location.hash||"",m=/[#&]cmx-pro=([^&]+)/.exec(p),x=/[#&]cmx-key=([^&]+)/.exec(p),f=d.get("unlock");if(f&&en[f]&&m)return d.delete("unlock"),history.replaceState(null,"",location.pathname+(d.toString()?`?${d}`:"")),h(decodeURIComponent(m[1]),f,{key:x?decodeURIComponent(x[1]):""});for(let[v,b]of Object.entries(t()))b&&b.pend&&await h(b.code,v);let g=pp(Va);if(g&&g.code&&Date.now()-(g.checked||0)>gy){let v=/^cmxk1\./.test(g.code)?!0:await o(g.code,"fun-pass");v===!1?(Wa(Va,null),a()):v&&Wa(Va,{...g,checked:Date.now()})}return null}return{has:s,ownsPack:i,pass:n,redeem:h,capture:u}}var ac=[{offer:"st-veldbolt-wild-unlock",kind:"full",name:"Wild Pass",what:"Everything: every biome and chapter, every animal and the full Predator mode (leopard, wolf pack, bear, eagle). One payment.",cents:499,price:"$4.99",per:"",icon:"\u{1F30D}",sw:["#FFB547","#2E8B57"],store:"https://cybermaxtools.com/store/savanna-chase-wild-pass/",img:"https://cybermaxtools.com/store/img/veldbolt-wild-pass-0.webp"},{offer:"st-veldbolt-looks-unlock",kind:"looks",name:"Coat & Trail Pack",what:"Every coat colour (real colour morphs) and every trail. Looks only.",cents:99,price:"$0.99",per:"",icon:"\u{1F3A8}",sw:["#F2C14E","#8C5A2B"],store:"https://cybermaxtools.com/store/savanna-chase-coat-trail-pack/",img:"https://cybermaxtools.com/store/img/veldbolt-coat-trail-pack-0.webp"},{offer:"st-veldbolt-snow-unlock",kind:"content",name:"Snow Pack",what:"The Snow biome, its 5-run chapter and the rabbit.",cents:199,price:"$1.99",per:"",icon:"\u2744\uFE0F",sw:["#DCE8F2","#5C7A99"],store:"https://cybermaxtools.com/store/savanna-chase-snow-pack/",img:"https://cybermaxtools.com/store/img/veldbolt-snow-pack-0.webp"},{offer:"st-veldbolt-canyon-unlock",kind:"content",name:"Canyon Pack",what:"The Canyon biome with its rock walls and its 5-run chapter.",cents:199,price:"$1.99",per:"",icon:"\u{1F3DC}\uFE0F",sw:["#F0A060","#8A3A1A"],store:"https://cybermaxtools.com/store/savanna-chase-canyon-pack/",img:"https://cybermaxtools.com/store/img/veldbolt-canyon-pack-0.webp"},{offer:"st-veldbolt-wetlands-unlock",kind:"content",name:"Wetlands Pack",what:"The Wetlands biome, river crossings with crocodiles, its 5-run chapter and the wild horse.",cents:299,price:"$2.99",per:"",icon:"\u{1F33F}",sw:["#9CC48A","#2F5D4A"],store:"https://cybermaxtools.com/store/savanna-chase-wetlands-pack/",img:"https://cybermaxtools.com/store/img/veldbolt-wetlands-pack-0.webp"},{offer:"st-fun-pass-monthly",kind:"pass",name:"Fun Pass",what:"In Savanna Chase: every biome, chapter and animal, the full Predator mode and every coat and trail. Plus every paid level, mode and theme in every CyberMax game. Cancel any time.",cents:299,price:"$2.99",per:"/month",icon:"\u2728",sw:["#FFB547","#FF6A3D"],store:"https://cybermaxtools.com/store/fun-pass/",img:"https://cybermaxtools.com/store/img/fun-pass-icon.webp",alt:[{offer:"st-fun-pass-yearly",label:"$19/year"},{offer:"st-fun-pass-unlock",label:"$29.99 for life"}]},{offer:"st-arcade-lifetime-lifetime",kind:"arcade",name:"Arcade Lifetime",what:"In Savanna Chase: the Wild Pass, all three biome packs and the Coat & Trail Pack for good. Plus the Fun Pass for life and every pack in every CyberMax game.",cents:3999,price:"$39.99",per:"",icon:"\u{1F579}\uFE0F",sw:["#5CF2FF","#B26BFF"],store:"https://cybermaxtools.com/store/arcade-lifetime/",img:"https://cybermaxtools.com/store/img/arcade-lifetime-icon.webp"}];var qg="veldbolt",Xg="https://cybermaxtools.com/games/savanna-chase/",Us=new URLSearchParams(location.search),tr=Us.has("cap"),vp=/^(localhost|127\.|0\.0\.0\.0|\[::1\])/.test(location.hostname)&&!Us.has("api"),he=r=>document.getElementById(r),kr=r=>String(r).replace(/[&<>"]/g,e=>({"&":"&","<":"<",">":">",'"':"""})[e]),an=r=>Math.round(r).toLocaleString("en-US"),Hn=new Date().toISOString().slice(0,10),fc=ro(Hn),xp=fc-20757,tn={get(r,e){try{let t=localStorage.getItem("vb-"+r);return t==null?e:JSON.parse(t)}catch{return e}},set(r,e){try{localStorage.setItem("vb-"+r,JSON.stringify(e))}catch{}}},vy=matchMedia("(prefers-reduced-motion: reduce)").matches,le={opt:tn.get("opt",{motion:!vy}),vol:tn.get("vol",{music:.55,sfx:.85}),mute:tn.get("mute",!1),stars:tn.get("stars",{}),best:tn.get("best",{}),daily:tn.get("daily",null),name:tn.get("name",""),tut:tn.get("tut",0),look:tn.get("look",{}),trail:tn.get("trail","dust"),pick:tn.get("pick",{side:"prey",prey:"zebra",pred:"lion",biome:"savanna"}),runs:tn.get("runs",0),upsold:0},fn=()=>{for(let r of["opt","vol","mute","stars","best","daily","name","tut","look","trail","pick","runs"])tn.set(r,le[r])};function nr(r,e=""){if(!(vp||tr))try{fetch(`${Is}/e?t=${qg}&a=${r}&c=${encodeURIComponent(e)}`,{mode:"no-cors",keepalive:!0})}catch{}}var Os=()=>!!document.querySelector('meta[name="cmx-portal"]')||!!(window.CMXPortal&&window.CMXPortal.portal),Dr=null,Ns={savanna:null,forest:null,snow:"snow",canyon:"canyon",wetlands:"wetlands"},ja={savanna:null,forest:"wild",snow:"snow",canyon:"canyon",wetlands:"wetlands"},hc={deer:null,zebra:null,wildebeest:null,horse:"wetlands",rabbit:"snow",lion:null,leopard:"wild",wolf:"wild",bear:"wild",eagle:"wild"},gn=r=>!r||!!(Dr&&Dr.has(r)),Yg=r=>gn(hc[r])||hc[r]!=="wild"&&gn("wild"),yp=()=>Object.values(le.stars).reduce((r,e)=>r+e.reduce((t,n)=>t+(n||0),0),0),Kg=(r,e)=>e.free||e.star&&yp()>=e.star||gn("looks"),Lr={deer:"\u{1F98C}",zebra:"\u{1F993}",wildebeest:"\u{1F403}",horse:"\u{1F40E}",rabbit:"\u{1F407}",lion:"\u{1F981}",leopard:"\u{1F406}",wolf:"\u{1F43A}",bear:"\u{1F43B}",eagle:"\u{1F985}",croc:"\u{1F40A}"},uc={savanna:"\u{1F33E}",forest:"\u{1F332}",snow:"\u2744\uFE0F",canyon:"\u{1F3DC}\uFE0F",wetlands:"\u{1F33F}"};function xy(){if(Us.has("q"))return Math.max(0,Math.min(2,+Us.get("q")));if(tr||Us.has("hq"))return 2;let r=matchMedia("(pointer: coarse)").matches,e=navigator.hardwareConcurrency||4,t=navigator.deviceMemory||4;return r?e>=8&&t>=6?1:0:e>=4?2:1}var _p=he("c"),dt;try{dt=new Jl(_p,{tier:xy(),cap:tr})}catch(r){throw he("nogl").hidden=!1,r}ic(le.mute);nc(le.vol);var L=null,He="menu",ii=[],ni=0,bp=performance.now(),cc=0,zs=null,Bn=np(location.search),on=null,mn=null,Qi=null,yy=[],oc=0,fp=0,Hg=0,ks=0,Ds=0,dc=0,Gg=0,$g=!1,it=window.__veldbolt={get state(){return He},get run(){return L},inputs:()=>ii,errors:[],restartMs:[],fps:0,get tier(){return dt.tier},forceFps:null,R:dt,S:zr,N:cp,version:1,audioErrors:Zd,events:[]};addEventListener("error",r=>it.errors.push(String(r.message||r)));addEventListener("unhandledrejection",r=>it.errors.push(String(r.reason)));function _y(r,e){return e==="pred"?Uc[r]:Nc[r]}async function ir(r,e=Math.random()*2147483e3|1){let t=performance.now();if(r.mode!=="live"&&(mn=null),Qi={...r,seed:e},L=ai(e,Qi),ii=[],ni=0,cc=0,yy=[],zs=null,r.mode==="daily"&&le.daily&&le.daily.d===Hn&&le.daily.taps&&!r.noGhost){let i=li(le.daily.taps);i&&(zs=new Ha(Qi,i))}await dt.prepare(L),dt.setRun(L,le.look),await og(tr?6e4:5e3),dt.extra=[],He="play",it.events.length=0,dt.camState.orbit=0,document.documentElement.classList.add("playing");for(let i of["menu","over","pick","chapters","board","shop","pause","chal","livep"])he(i).hidden=!0;he("hud").hidden=!1,t0(!0),Fa(),Cg({biome:L.biome}),it.restartMs.push(Math.round(performance.now()-t)),le.runs++,fn(),nr("play",`${L.mode}-${L.side}-${L.sp0}-${L.biome}`),Ds=le.tut>=3?9:0,dc=0;let n=L.lvl;return n?wt(n.line,3.5):L.mode==="challenge"?wt(L.side==="pred"?"Hunt down their recorded escape.":"Escape their recorded hunter.",3):le.tut<3&&n0(),L}var Zg=()=>{let r=le.pick,e=r.side,t=e==="pred"?r.pred:r.prey,n=gn(Ns[r.biome])?r.biome:"savanna";return ir({mode:"endless",side:e,sp:t,biome:n})},Mp=()=>{let r=Xs(fc);return ir(r,r.seed)},Jg=(r,e)=>ir({mode:"level",level:{biome:r,i:e}});function Qg(r){let e=Xc(Bn,r);return ir(e,Bn.seed)}it.press=r=>mc(r);it.start=ir;it.startDaily=Mp;it.startLevel=Jg;it.startPick=Zg;var We={steer:0,sprint:!1,keys:new Set,drag:null,hold:null,mouse:null,code:Ys(0,!1),pounceT:0},mp=matchMedia("(pointer: coarse)").matches;function mc(r){if(!(!L||L.over||He!=="play")){if(mn){ii.push([L.tick+1+Ps,r]),mn.local(L.tick+1,r,on.send);return}ii.push([L.tick+1,r]),Mn(L,0,r)}}function My(){let r=We.drag?We.steer:0;return!We.drag&&We.mouse!=null&&!We.keys.size&&(r=We.mouse),(We.keys.has("a")||We.keys.has("arrowleft"))&&(r-=1),(We.keys.has("d")||We.keys.has("arrowright"))&&(r+=1),Math.max(-1,Math.min(1,-r))}function Sy(r){if(it.target=null,!L||L.side!=="pred"||on)return r;let e=Ne(L,L.me);if(!e||!e.alive)return r;let t=null,n=1e9;for(let f of L.agents)if(f.alive&&f.side==="prey"&&!f.hidden&&!f.ghost||f.ghost&&f.alive&&L.mode==="challenge"){let g=f.x-e.x,v=f.z-e.z,b=Math.hypot(g,v);if(b>70||v<-4)continue;let y=Math.abs(Math.atan2(g,v)-e.a),M=b*(1+y*.8);M.15,d=Math.abs(h-r)<.6,p=u?d?r+(h-r)*.6:r:h,m=(Te[e.sp].reach||3)+2.5,x=(i*Math.sin(e.a)+s*Math.cos(e.a))/(a||1);return a.75&&!e.air&&!e.lunge&&performance.now()>We.pounceT&&(We.pounceT=performance.now()+700,mc(so.jump)),p}function Ri(){let r=We.sprint||We.keys.has("w")||We.keys.has("shift")||We.keys.has("arrowup"),e=Ys(Sy(My()),r);e!==We.code&&(We.code=e,mc(e))}var er=r=>{He==="play"&&(mc(so[r]),r==="ability"&&Ty(he("ab")))};function wy(){if(!L||He!=="play")return;let r=Ne(L,L.me);if(!r)return;if(L.side==="pred"){er("jump");return}let e=null,t=1e9;for(let n of L.agents)if(n.alive&&n.side==="pred"){let i=Math.hypot(n.x-r.x,n.z-r.z);ir.x?"dodgeL":"dodgeR")}var Ty=r=>{r.classList.remove("tap"),r.offsetWidth,r.classList.add("tap")},qa=he("game");qa.addEventListener("pointerdown",r=>{if(Fa(),!(He!=="play"||r.target.closest("button, .sheet, a, #chip"))){try{qa.setPointerCapture?.(r.pointerId)}catch{}We.drag={id:r.pointerId,x:r.clientX,y:r.clientY,t:performance.now(),lx:r.clientX,moved:0}}});qa.addEventListener("pointermove",r=>{if(r.pointerType==="mouse"&&!We.drag){let n=(r.clientX-innerWidth/2)/(innerWidth*.3);We.mouse=Math.abs(n)<.06?0:Math.max(-1,Math.min(1,n)),Ri();return}let e=We.drag;if(!e||e.id!==r.pointerId)return;e.moved=Math.max(e.moved,Math.abs(r.clientX-e.x)+Math.abs(r.clientY-e.y)),We.steer=Math.max(-1,Math.min(1,(r.clientX-e.x)/Math.max(40,innerWidth*.2)));let t=performance.now()-e.t;!e.flicked&&t<220&&Math.abs(r.clientX-e.x)>Math.max(46,innerWidth*.08)&&(e.flicked=!0,er(r.clientX>e.x?"dodgeR":"dodgeL")),Ri()});var e0=r=>{let e=We.drag;!e||e.id!==r.pointerId||(e.moved<12&&performance.now()-e.t<260&&r.type==="pointerup"&&wy(),We.drag=null,We.steer=0,Ri())};qa.addEventListener("pointerup",e0);qa.addEventListener("pointercancel",e0);var Fs=he("go");Fs.addEventListener("pointerdown",r=>{r.stopPropagation(),Fa(),We.hold=performance.now(),We.sprint=!0,Ri(),Fs.classList.add("on")});var Sp=()=>{We.hold!=null&&(We.hold=null,We.sprint=!1,Ri(),Fs.classList.remove("on"))};Fs.addEventListener("pointerup",Sp);Fs.addEventListener("pointercancel",Sp);Fs.addEventListener("pointerleave",Sp);he("ab").addEventListener("pointerdown",r=>{r.stopPropagation(),er("ability")});he("chip").addEventListener("click",()=>{He==="play"&&Xa(!0)});addEventListener("keydown",r=>{let e=r.key.toLowerCase();He==="play"?["a","d","w","shift","arrowleft","arrowright","arrowup"].includes(e)?(We.keys.add(e),Ri(),r.preventDefault()):e===" "?(er("jump"),r.preventDefault()):e==="q"?er("dodgeL"):e==="e"?er("dodgeR"):e==="f"?er("ability"):(e==="p"||e==="escape")&&Xa(!0):He==="over"&&(e===" "||e==="enter")&&wp(),e==="m"&&(le.mute=!le.mute,ic(le.mute),fn())});addEventListener("keyup",r=>{let e=r.key.toLowerCase();We.keys.delete(e)&&Ri()});addEventListener("blur",()=>{We.keys.clear(),We.drag=null,We.sprint=!1,Ri()});document.addEventListener("visibilitychange",()=>{document.hidden&&He==="play"&&!on&&Xa(!0)});var gp=0;function Ey(){let r=he("warn");if(!L||He!=="play"||L.side!=="prey"){r.hidden=!0;return}let e=Ne(L,L.me),t=null,n=1e9;for(let m of L.agents)if(m.alive&&m.side==="pred"&&m.tgt===e.id&&m.st!=="tired"){let x=Math.hypot(m.x-e.x,m.z-e.z);x45){r.hidden=!0,gp=0;return}gp!==t.id&&(gp=t.id,Ba({t:"warn"}));let i=new S(t.x,t.y+1,t.z).project(dt.cam),s=i.z>1,a=i.x,o=-i.y;s&&(a=-a,o=1);let l=!s&&Math.abs(a)<.9&&Math.abs(o)<.85;if(r.hidden=l,l)return;let c=Math.atan2(o,a),h=.86,u=Math.cos(c),d=Math.sin(c),p=Math.min(h/Math.abs(u||1e-6),h/Math.abs(d||1e-6));r.style.transform=`translate(${(.5+u*p*.5)*innerWidth}px, ${(.5+d*p*.5)*innerHeight}px) rotate(${c}rad)`,r.style.opacity=String(Math.min(1,.45+(45-n)/45))}function t0(r){if(!L)return;let e=Ne(L,L.me);if(!e)return;he("go").style.setProperty("--s",e.stam.toFixed(3)),he("go").classList.toggle("tired",e.winded);let t=Te[e.sp].ab,n=Te[e.sp].cd||1,i=Math.max(0,e.abCd)/n,s=he("ab");s.style.setProperty("--c",(1-i).toFixed(3));let a=t==="burrow"?Fc(L,e):!0;s.classList.toggle("ready",i<=0&&a);let o=t==="command"?["Drive","Flank \u25C0","Flank \u25B6"][L.cmd]:t==="stalk"&&e.abT>0?"Stalking":to[t];(r||s.dataset.l!==o)&&(s.dataset.l=o,he("ab-l").textContent=o);let l,c=L.goal;L.side==="pred"?l=c?`\u{1F3AF} ${L.hunts}/${c.n}`:`\u{1F3AF} ${L.hunts} \xB7 ${an(L.score)}`:c&&c.t==="survive"?l=`\u23F1 ${Math.max(0,c.n-Math.floor(L.tick/30))}s`:c&&(c.t==="reach"||c.t==="herd")?l=`${Math.floor(L.dist)} / ${c.n} m`:c&&c.t==="lone"?l=`Lone ${Math.floor(L.lone)} / ${c.n} m`:l=`${an(L.score)}${e.lone&&Te[e.sp].herd?" \xD72":""}`,L.combo>1&&(l+=` \xB7 \u{1F525}${L.combo}`),L.obj&&!c&&(l+=` \xB7 ${L.obj.icon} ${L.obj.have||0}/${L.obj.k==="herd"?L.obj.n+" m":L.obj.n}`),L.boostT>0&&L.side==="prey"&&!c&&(l+=` \xD7${(1+Math.min(.5,L.boost*.1)).toFixed(1)}`),he("chip").textContent!==l&&(he("chip").textContent=l)}function wt(r,e=2.6){let t=he("line");t.textContent=r,t.classList.add("on"),clearTimeout(wt.t),wt.t=setTimeout(()=>t.classList.remove("on"),e*1e3)}var Ay=()=>[mp?"Drag to steer \xB7 Hold \u26A1 to sprint":"Mouse or A / D to steer \xB7 Hold W to sprint",L&&L.side==="pred"?mp?"Get close: the pounce is automatic. Tap to pounce early.":"Get close: the pounce is automatic. Click to pounce early.":mp?"Tap to dodge a pounce":"Click or Q / E to dodge"];function n0(){let r=Ay();Ds{t.hidden=!0},e)}function i0(r){tr||requestAnimationFrame(i0);let e=Math.min(.1,(r-bp)/1e3);bp=r,r0(e)}function r0(r){if(He==="play"&&L&&!L.over&&Ri(),He==="play"||He==="end"||He==="menu"||He==="replay"){if(He==="play"||He==="end"||He==="replay"){let e=dt.slow>0?.35:1;ni+=r*e;let t=0,n=[];for(;ni>=rt&&t<6&&L&&!(L.over&&He==="play"&&cc>1.4);){if(mn&&!mn.ready(L.tick+1)){mn.heartbeat(L.tick,on.send);break}mn&&(mn.apply(L,L.tick+1),mn.heartbeat(L.tick,on.send)),He==="replay"&&Dy();for(let i of L.agents)i.px=i.x,i.pz=i.z,i.py=i.y,i.pa=i.a;Xn(L),ni-=rt,t++,n.push(...L.events)}if(zs&&L){let i=zs.stepTo(L.tick);i&&(dt.extra=[Object.assign(Object.create(i),{id:"ghost",ghost:1,ctl:-2})])}L&&He!=="menu"&&s0(n),L&&L.over&&He==="play"&&(cc+=r,cc>1.6&&a0()),dt.frame(r,Math.min(1,ni/rt),n,{trail:le.trail,motion:le.opt.motion?1:.25,target:it.target}),Ey(),He==="play"&&t0(),dc>0&&(dc-=r)<=0&&Ds<9&&n0()}else Ry(r);Cy(r),Py(r)}}function s0(r){let e=L&&Ne(L,L.me);for(let t of r){it.events.push(t.t);let n=t.id?Ne(L,t.id):null,i=n&&e?Math.min(1,Math.hypot(n.x-e.x,n.z-e.z)/60):0,s=n&&e?Math.max(-1,Math.min(1,(e.x-n.x)/25)):0;Ba(t,{far:i,pan:s,sp:n&&n.sp,me:t.me}),He==="play"&&(t.t==="close"?wt(t.combo>1?`Close call \xD7${t.combo} +${t.pts}`:`Close call +${t.pts}`,1.4):t.t==="giveup"&&n&&L.side==="prey"&&(!n.tgt||!0)&&i<.7?wt(`The ${Te[t.sp].name.toLowerCase()} gave up`,1.6):t.t==="confused"?wt("Lost in the herd",1.4):t.t==="spawn"&&L.side==="prey"&&le.runs<6?wt({lion:"Lioness in the grass ahead",leopard:"Leopard stalking close",wolf:"Wolf pack behind you",bear:"Bear in the trees",eagle:"Eagle overhead: watch the shadow"}[t.k]||"",2.2):t.t==="hunt"?wt(`New herd ahead: ${Te[t.sp].name.toLowerCase()}`,2):t.t==="escaped"&&L.side==="pred"?wt("They got away",1.6):t.t==="catch"&&t.mine&&!t.me&&L.side==="pred"?wt(`Caught: ${Te[t.prey].name.toLowerCase()}`,1.6):t.t==="noBurrow"?wt("No burrow here: find a mound",1.4):t.t==="cmd"?wt(["Pack: drive it to me","Pack: flank left","Pack: flank right"][t.cmd],1.4):t.t==="obj"?wt(t.done?`\u2713 ${t.done} +${t.pts} \xB7 Next: ${t.next}`:t.next,t.done?3:2.6):t.id===L.me&&t.t==="grazed"?wt(`Grazed +${t.pts} \xB7 stamina up`,1.3):t.id===L.me&&t.t==="drank"?wt(`Drank +${t.pts} \xB7 stamina up`,1.3):t.id===L.me&&t.t==="rested"?wt(`Rested +${t.pts} \xB7 stamina up`,1.3):t.id===L.me&&t.t==="shoot"?wt(`Fresh shoot \xB7 score \xD7${(1+Math.min(.5,t.n*.1)).toFixed(1)}`,1.2):t.id===L.me&&t.t==="startle"&&wt("Startled: run!",1.2))}}var Vg=0;function Ry(r){if(Vg+=r,!!L&&$g){for(ni+=r;ni>=rt;){for(let e of L.agents)e.px=e.x,e.pz=e.z,e.py=e.y,e.pa=e.a;if(Xn(L),ni-=rt,L.over||L.tick>30*50){Tp();break}}dt.camState.orbit=1.9+Math.sin(Vg*.05)*.4,dt.frame(r,ni/rt,L.events,{motion:.25})}}function Cy(r){if(!L)return;let e=Ne(L,L.me);if(!e)return;let t=0;for(let i of L.agents)i.alive&&i.side==="pred"&&i.tgt===e.id&&i.st!=="tired"&&(t=Math.max(t,1-Math.hypot(i.x-e.x,i.z-e.z)/45));L.side==="pred"&&(t=L.agents.some(i=>i.alive&&i.side==="prey"&&i.st==="flee")?.6:.1);let n=Bt(L,Math.floor(e.z/Ye));Ig({dt:r,speed:e.spd,top:Te[e.sp].top,stamina:e.stam,surface:e.surf,threat:t,playing:He==="play",night:dt.world.night||0,biome:L.biome,weather:L.weather,nearWater:!!(n.river&&Math.abs(n.river.z-e.z)<30),side:L.side,flying:!!Te[e.sp].fly,big:Te[e.sp].h,steps:dt.steps||[],stride:(dt.anim.get(e.id)||{}).stride||0}),dt.steps=[]}function Py(r){let e=it.forceFps||(r>0?1/r:60);if(oc+=r,fp++,oc>=1&&(it.fps=Math.round(fp/oc),oc=0,fp=0),He!=="play"||tr&&it.forceFps==null){ks=0;return}ks=e<45?ks+r:Math.max(0,ks-r*.5),ks>2&&dt.tier>0&&(dt.setTier(dt.tier-1),ks=0,Hg++,it.tierDrops=Hg)}function a0(){He="over",document.documentElement.classList.remove("playing"),he("hud").hidden=!0;let r=Ne(L,L.me),e=r.sp,t=L.result==="caught",n=L.won,i,s="";if(L.mode==="challenge"){let p=ip(L,Bn);i=p.won?"You win the challenge!":"Challenge lost",s=p.line}else L.goal?i=n?"Chapter run cleared!":L.result==="herd"?"The herd broke up":L.result==="escaped"?"The herd got away":`Caught by a ${Te[L.by]?Te[L.by].name.toLowerCase():"hunter"}`:L.side==="pred"?i=L.hunts?`${L.hunts} hunt${L.hunts>1?"s":""}`:"The herds got away":i=t?`Caught by a ${Te[L.by]?Te[L.by].name.toLowerCase():"hunter"}`:"You escaped!";if(n&&Ba({t:"win"}),L.mode==="level"&&n){let p=L.opts.level,m=Gc(L),x=le.stars[p.biome]||[];x[p.i]=Math.max(x[p.i]||0,m),le.stars[p.biome]=x}let a=`${L.mode}-${L.side}-${e}`,o=le.best[a]||0,l=L.score>o;if(l&&L.mode!=="challenge"&&(le.best[a]=L.score),L.mode==="daily"){let p=oi(ii);(!le.daily||le.daily.d!==Hn||L.score>(le.daily.score||0))&&(le.daily={d:Hn,score:L.score,dist:Math.floor(L.dist),close:L.close,taps:p,sp:e})}le.lastRun={opts:Qi,taps:oi(ii),score:L.score},fn(),nr("over",`${L.mode}-${L.side}-${L.result}`),he("o-h").textContent=i,he("o-sub").textContent=s,he("o-sub").hidden=!s,he("o-n").textContent=an(L.score),he("o-best").textContent=l&&o?"New best!":o?`Best ${an(Math.max(o,L.score))}`:"";let c=co[L.side==="pred"?e:t&&L.by?L.by:e]||co[e]||[],h=c[(L.seed>>>3)%Math.max(1,c.length)]||"";he("o-fact").innerHTML=h?`${Lr[L.side==="pred"?e:t&&L.by?L.by:e]||"\u{1F30D}"} Did you know? ${kr(h)}`:"";let u=L.agents.filter(p=>p.herd&&p.alive&&p.side==="prey"&&p.ctl<0).length;he("o-det").innerHTML=[L.side==="prey"?`
  • Distance ${an(L.dist)} m
  • `:`
  • Hunts ${L.hunts} \xB7 got away ${L.misses}
  • `,`
  • Close calls ${L.close}
  • `,L.side==="prey"&&Te[e].herd?`
  • Herd still with you ${u} \xB7 lone run ${an(L.lone)} m
  • `:"",L.giveups?`
  • Hunters that gave up ${L.giveups}
  • `:"",`
  • ${_n[L.biome].name} \xB7 ${L.weather} \xB7 ${Math.floor(L.tick/30)} s
  • `].join(""),he("o-daily").hidden=L.mode!=="daily",he("o-chal").hidden=L.mode==="challenge"||!!on||L.mode==="level",he("o-clip").hidden=!window.MediaRecorder||!_p.captureStream||Os();let d=he("o-up");d.hidden=!0,!Os()&&!le.upsold&&!gn("wild")&&le.runs>=2&&(le.upsold=1,d.hidden=!1,d.innerHTML=L.side==="pred"?`Hunt as a wolf pack, leopard, bear or eagle \xB7 Wild Pass ${en.wild.price}`:`New biomes and animals: Snow, Canyon, Wetlands or everything ${en.wild.price}`),he("over").hidden=!1,L.mode==="daily"&&Ny(),on&&mn&&on.send({t:"end",s:lo(L)[Math.max(0,L.humans.indexOf(L.me))],taps:oi(ii)})}function wp(){if(!Qi)return;let r={...Qi};delete r.seed,Qi.mode==="daily"?Mp():Qi.mode==="challenge"?Qg():ir(r)}function Xa(r){r&&He==="play"?(He="paused",he("pause").hidden=!1):!r&&He==="paused"&&(He="play",he("pause").hidden=!0,bp=performance.now())}function lc(){He="menu",document.documentElement.classList.remove("playing");for(let r of["over","pause","hud","pick","chapters","board","shop","chal","livep"])he(r).hidden=!0;he("menu").hidden=!1,c0(),Tp()}async function Tp(){$g=!0;let r=le.pick;L=ai(4242+fc%7,{mode:"demo",side:"prey",sp:r.prey,biome:"savanna",enc:!1,tod:.5,weather:"clear"}),Mn(L,0,Ys(0,!1)),await dt.prepare(L),dt.setRun(L,le.look),dt.extra=[]}function o0(){let r=Ne(L,L.me),e=r?r.sp:L.sp0,t=Math.min(10,Math.max(1,Math.round(L.tick/30/10))),n=Array.from({length:t},(a,o)=>o===t-1&&L.result==="caught"?"\u{1F7E5}":o>=t-2&&L.close>2?"\u{1F7E8}":"\u{1F7E9}").join(""),i=L.mode==="daily"?`Savanna Chase Daily #${xp} ${Lr[e]}${uc[L.biome]}`:`Savanna Chase ${Lr[e]}${uc[L.biome]}`,s=L.side==="pred"?`\u{1F3AF} ${L.hunts} hunts \xB7 \u26A1${L.close} close calls`:`\u{1F3C3} ${an(L.dist)} m \xB7 \u26A1${L.close} close calls${L.result==="caught"&&L.by?` \xB7 ${Lr[L.by]||""} caught`:" \xB7 escaped"}`;return`${i} ${s} ${n} ${an(L.score)}`}async function Iy(){let r=o0(),e=`${Xg}?s=share-${L.mode}`;nr("cta","share");try{let t=await new Promise(i=>Ly().toBlob(i,"image/png")),n=new File([t],"veldbolt.png",{type:"image/png"});if(navigator.canShare?.({files:[n]})){await navigator.share({files:[n],text:r,url:e});return}if(navigator.share){await navigator.share({text:r,url:e});return}}catch{}try{await navigator.clipboard.writeText(`${r} ${e}`),Gn("Copied. Paste it anywhere.")}catch{Gn(r,5e3)}}function Ly(){let r=document.createElement("canvas");r.width=1080,r.height=1350;let e=r.getContext("2d"),t=dt.snapshot(1080,1350);e.drawImage(t,0,0);let n=e.createLinearGradient(0,700,0,1350);return n.addColorStop(0,"rgba(10,10,12,0)"),n.addColorStop(1,"rgba(10,10,12,.85)"),e.fillStyle=n,e.fillRect(0,0,1080,1350),e.fillStyle="#f3ecdc",e.font='800 64px "Barlow Condensed", Impact, sans-serif',e.fillText(he("o-h").textContent,60,1060),e.fillStyle="#ffb547",e.font='800 150px "Barlow Condensed", Impact, sans-serif',e.fillText(he("o-n").textContent,60,1210),e.fillStyle="#f3ecdc",e.font="600 34px system-ui, sans-serif",e.fillText(o0().split(` `)[1],60,1280),e.font='800 40px "Barlow Condensed", Impact, sans-serif',e.fillStyle="#ffb547",e.fillText("SAVANNA CHASE",60,90),e.fillStyle="#f3ecdc",e.font="600 26px system-ui",e.fillText("cybermaxtools.com/games/savanna-chase",60,130),r}async function ky(){let r=tp(Xg,L,ii,le.name||"");nr("cta",`challenge-${L.side}`);let e=Ne(L,L.me),t=L.side==="pred"?`My ${Te[e.sp].name.toLowerCase()} is hunting. Can you escape it? \u{1F3C3}`:`My ${Te[e.sp].name.toLowerCase()} ran ${an(L.dist)} m. Can you hunt it down? \u{1F981}`;try{if(navigator.share){await navigator.share({text:t,url:r});return}}catch{return}try{await navigator.clipboard.writeText(`${t} ${r}`),Gn("Challenge link copied.")}catch{Gn(r,6e3)}}var Pr=null,l0=null;function Dy(){let r=l0;for(;r.iMediaRecorder.isTypeSupported(p))||"";Pr=new MediaRecorder(a,l?{mimeType:l,videoBitsPerSecond:5e6}:void 0),Pr.ondataavailable=p=>{p.data.size&&o.push(p.data)};let c=new Promise(p=>{Pr.onstop=p});Pr.start(),await new Promise(p=>{let m=setInterval(()=>{(L.over||L.tick>=n+30)&&(clearInterval(m),p())},100)}),await new Promise(p=>setTimeout(p,900)),Pr.stop(),await c,Pr=null;let u=new Blob(o,{type:"video/webm"}),d=document.createElement("a");d.href=URL.createObjectURL(u),d.download=`veldbolt-${Hn}.webm`,document.body.appendChild(d),d.click(),d.remove(),it.clipBytes=u.size,nr("cta","clip"),He="over",he("over").hidden=!1}async function Ny(){let r=he("o-board");if(r.innerHTML=`Checking today's board\u2026`,vp&&!Us.has("api")&&!window.__vbBoard){r.innerHTML="";return}let e=le.name||"",t=async n=>{let i=await(window.__vbBoard?window.__vbBoard.post(Hn,n,oi(ii)):sp(Hn,n,oi(ii)));it.lastPost=i,r.innerHTML=i&&!i.error?`Posted: ${an(i.score??L.score)}${i.rank?` \xB7 #${i.rank} today`:""}`:`${kr(i&&i.message||"Board offline. Your run is saved here.")}`};if(e)return t(e);r.innerHTML='
    ',he("o-name").addEventListener("submit",n=>{n.preventDefault();let i=n.target.querySelector("input").value.toUpperCase().replace(/[^A-Z0-9]/g,"").slice(0,3);i&&(le.name=i,fn(),t(i))})}async function Oy(){Bs("board"),he("b-day").textContent=`Daily Chase #${xp} \xB7 ${Hn}`;let r=window.__vbBoard?await window.__vbBoard.get(Hn):await rp(Hn),e=r&&(r.top||r.rows)||[];he("b-list").innerHTML=e.length?e.map(t=>`
  • ${kr(t.name)} ${an(t.score)}
  • `).join(""):'
  • No runs yet today. Be the first.
  • '}function Bs(r){for(let e of["menu","pick","chapters","board","shop","pause","over","chal","livep"])he(e).hidden=e!==r}function c0(){let r=Xs(fc);he("m-daily").innerHTML=`${Lr[r.sp]} Daily Chase #${xp}${le.daily&&le.daily.d===Hn?` \xB7 best ${an(le.daily.score)}`:""}`,he("m-shop").hidden=Os()}function Ir(r){le.pick.side=r,fn(),Bs("pick"),he("pk-h").textContent=r==="pred"?"Hunt as":"Run as";let e=r==="pred"?Lc:Ic,t=r==="pred"?le.pick.pred:le.pick.prey;he("pk-animals").innerHTML=e.map(s=>{let a=Yg(s),o=hc[s];return``}).join(""),he("pk-biomes").innerHTML=no.map(s=>{let a=gn(Ns[s]);return``}).join("");let n=t,i=Wl[n]||[];he("pk-looks").innerHTML=i.length>1?i.map(s=>{let a=Kg(n,s);return``}).join(""):"",he("pk-trails").innerHTML=r==="prey"?Xd.map(s=>{let a=s.free||s.star&&yp()>=s.star||gn("looks");return``}).join(""):""}function Wg(r="savanna"){Bs("chapters"),he("ch-tabs").innerHTML=no.map(i=>``).join("");let e=io[r],t=gn(ja[r]),n=le.stars[r]||[];he("ch-name").textContent=e.name,he("ch-list").innerHTML=e.levels.map((i,s)=>{let a=t&&(s===0||n[s-1]>0);return``}).join("")+(t?"":`

    \u{1F512} ${r==="forest"?"The Forest chapter comes with the Wild Pass.":`Comes with the ${en[ja[r]].name} or the Wild Pass.`} See it in the shop

    `)}var pc=null;function zy(r,e){let t=[];for(let n of["looks","snow","canyon","wetlands","wild"]){let i=en[n],s=ac.find(a=>a.offer===`st-${i.app}-unlock`)||{offer:`st-${i.app}-unlock`,name:i.name,what:i.what,price:i.price,cents:Math.round(parseFloat(i.price.slice(1))*100),icon:{looks:"\u{1F3A8}",snow:"\u2744\uFE0F",canyon:"\u{1F3DC}\uFE0F",wetlands:"\u{1F33F}",wild:"\u{1F30D}"}[n],sw:n==="wild"?["#FFB547","#2E8B57"]:["#7FB3D5","#2C3E50"]};gn(n)&&(n!=="looks"||Dr.has("looks"))?t.push(e({...s,name:`${i.name} is on`,what:i.what},"","on")):t.push(e(s,Fg(n,r),n==="wild"?"best":""))}for(let n of["st-fun-pass-monthly","st-arcade-lifetime-lifetime"]){let i=ac.find(s=>s.offer===n);i&&t.push(e(i,`https://data.cybermaxtools.com/buy/${n}?s=game-veldbolt-${r}`,"xall"))}return t}function Ai(r="menu",e=""){Os()||(Bs("shop"),he("s-body").innerHTML=pc.html(r,e?`${en[e].name}: ${en[e].what}`:""),pc.bind(he("s-body")),nr("cta",`shop-open-${r}`))}document.addEventListener("click",r=>{let e=r.target.closest("[data-act],[data-sp],[data-b],[data-look],[data-trail],[data-lv],[data-tab],[data-shop],[data-back]");if(e){if(Fa(),Ba({t:"click"}),e.dataset.shop){r.preventDefault(),Ai("lock",e.dataset.shop);return}if(e.dataset.back!=null){He==="over"?(he("over").hidden=!1,e.closest(".ov").hidden=!0):lc();return}if(e.dataset.sp){let t=e.dataset.sp;if(!Yg(t)){Ai("pick",hc[t]);return}le.pick[le.pick.side==="pred"?"pred":"prey"]=t,le.pick.biome=_y(t,le.pick.side),gn(Ns[le.pick.biome])||(le.pick.biome="savanna"),fn(),Ir(le.pick.side);return}if(e.dataset.b){if(!gn(Ns[e.dataset.b])){Ai("pick",Ns[e.dataset.b]);return}le.pick.biome=e.dataset.b,fn(),Ir(le.pick.side);return}if(e.dataset.look){let t=le.pick.side==="pred"?le.pick.pred:le.pick.prey,n=Wl[t].find(i=>i.id===e.dataset.look);if(!Kg(t,n)){n.star?Gn(`Earn ${n.star} campaign stars to unlock it.`):Ai("looks","looks");return}le.look[t]=n.id,fn(),Ir(le.pick.side);return}if(e.dataset.trail){let t=Xd.find(n=>n.id===e.dataset.trail);if(!(t.free||t.star&&yp()>=t.star||gn("looks"))){t.star?Gn(`Earn ${t.star} campaign stars to unlock it.`):Ai("looks","looks");return}le.trail=t.id,fn(),Ir(le.pick.side);return}if(e.dataset.tab){Wg(e.dataset.tab);return}if(e.dataset.lv){if(e.classList.contains("lock")){let i=e.dataset.lv.split(":")[0];gn(ja[i])?Gn("Clear the run before it first."):Ai("chapters",ja[i]);return}let[t,n]=e.dataset.lv.split(":");Jg(t,+n);return}switch(e.dataset.act){case"prey":Ir("prey");break;case"pred":Ir("pred");break;case"go":Zg();break;case"daily":Mp();break;case"chapters":Wg();break;case"board":Oy();break;case"shop":Ai("menu");break;case"again":wp();break;case"menu":lc();break;case"share":Iy();break;case"challenge":ky();break;case"clip":Uy();break;case"details":he("o-more").hidden=!he("o-more").hidden,e.setAttribute("aria-expanded",String(!he("o-more").hidden));break;case"pause":Xa(!0);break;case"resume":He==="paused"?Xa(!1):he("pause").hidden=!0;break;case"quit":lc();break;case"mute":le.mute=!le.mute,ic(le.mute),fn(),e.textContent=`Sound: ${le.mute?"off":"on"}`;break;case"motion":le.opt.motion=!le.opt.motion,fn(),e.textContent=`Camera motion: ${le.opt.motion?"full":"calm"}`;break;case"accept":he("chal").hidden=!0,Qg();break;case"decline":Bn=null,history.replaceState(null,"",location.pathname),lc();break;case"live":Hy();break;case"live-new":jg(Fy());break;case"live-join":jg(String(he("lv-code").value||"").toUpperCase());break;case"live-go":on&&on.send({t:"go"});break;default:break}}});for(let r of document.querySelectorAll("[data-vol]"))r.value=Math.round(le.vol[r.dataset.vol]*100),r.addEventListener("input",()=>{le.vol[r.dataset.vol]=r.value/100,nc(le.vol),fn()});var Fy=()=>Array.from({length:6},()=>"ABCDEFGHJKLMNPQRSTUVWXYZ23456789"[Math.floor(Math.random()*32)]).join("");function By(){let r=tn.get("tag","");return/^[a-z0-9]{8,16}$/.test(r)||(r=Math.random().toString(36).slice(2,12),tn.set("tag",r)),r}function Hy(){Bs("livep"),he("lv-status").textContent="Live rooms (beta): 2 to 6 players, the same chase on every screen."}function jg(r){if(!/^[A-HJ-NP-Z2-9]{6}$/.test(r)){Gn("A room code is 6 letters.");return}on&&on.close(),on=lp(r,le.name||"Runner",By(),{status:e=>{he("lv-status").textContent=e},roster:(e,t,n)=>{he("lv-status").textContent=`Room ${r} \xB7 ${e.length} player${e.length>1?"s":""}${n===0?" \xB7 you host":""}`,he("lv-go").hidden=n!==0||e.length<2},start:(e,t,n,i)=>setTimeout(async()=>{let s=op(e,n);mn=new Ga(n,i),await ir(s,e),L.me=L.humans[i]},t),input:(e,t,n)=>{mn&&mn.remote(e,t,n)},result:e=>Gn(e.map((t,n)=>`${n+1}. ${t.nick} ${an(t.s)}`).join(" "),6e3)}),it.live=on}Dr=Bg({toast:Gn,count:(r,e)=>nr(r,e),onChange:()=>{he("pick").hidden||Ir(le.pick.side),he("shop").hidden||Ai("menu")},portal:Os});pc=Og({game:qg,name:"Savanna Chase",offers:[],catalog:ac,rows:zy,has:()=>!1,credit(){},toast:Gn,count:(r,e)=>nr(r,e),fair:"Packs add biomes, chapters, animals and looks. Nothing sold changes the Daily Chase, its board or anyone's score there.",preRedeem:r=>Dr.redeem(r,"",{quiet:!0})});it.U=Dr;it.shop=pc;it.openShop=Ai;it.again=wp;it.finish=()=>a0();Dr.capture();Os()&&document.documentElement.classList.add("cmx-noshop");ap()&&(he("m-live").hidden=!1);if(Bn){Bs("chal");let r=Bn.side==="prey"?"hunt":"escape";he("ch-text").textContent=`${Bn.name||"A friend"}'s ${Te[Bn.sp].name.toLowerCase()} ${Bn.side==="prey"?`ran ${an(Bn.score)} points`:"is on the hunt"} in the ${_n[Bn.biome].name.toLowerCase()}. Can you ${r} it?`}else he("menu").hidden=!1;c0();Tp();"serviceWorker"in navigator&&!vp&&!tr&&navigator.serviceWorker.register("sw.js").catch(()=>{});tr?it.tick=(r=1/30)=>r0(r):requestAnimationFrame(i0);it.advance=r=>{for(let e=0;e{it.forceFps=60,dt.setTier(2),await ir({mode:"endless",side:"prey",sp:"zebra",biome:"savanna",tod:.5,weather:"clear",enc:!1},2026),it.advance(160),await new Promise(r=>setTimeout(r,2500))};it.ready=!0;