import{a as U,G as ee,c as te,S as oe,L as V,b as Y,d as ne,C as $,m as re,M as se,D as ie,e as ae,f as ce,A as le,V as Z}from"./avatar-BEKAZIeX.js";import{b as q}from"./contract-Qrs4QEiv.js";import"./schemas-DQxGDFXJ.js";function _(i,s){if(s)return new URL(i.file,s.endsWith("/")?s:s+"/").href;if(!i.url)throw new Error("Character asset URL is missing.");return i.url}function fe(i,s,y,h){const k=new ee,l=te(s.scene);k.add(l),l.updateMatrixWorld(!0);const W=s.scene.userData.jointOrder;if(!Array.isArray(W)||W.length>q.joints)throw new Error("Invalid character rig.");const j=W.map(a=>{const b=l.getObjectByName(a);if(!b)throw new Error(`Missing character joint: ${a}`);return b}),D=j.map(a=>a.matrixWorld.clone().invert()),S=new oe(j,D),O=[];let d=null,x;try{let a=function(){v==null||v.stop(),v=void 0,G=null},b=function(r,t=0,o=!1){const e=u.get(r);if(!e)return;a();const n=e.getClip().duration;t>=n&&!o||(v=e,G=r,N=o?1/0:n-Math.max(0,t),M.setEffectiveWeight(0),e.reset().setLoop(o?V:Y,o?1/0:1).setEffectiveWeight(1).play(),e.time=Math.max(t,0)%n)};for(const[r,t]of y.entries()){let o=0;if(t.scene.traverse(e=>{var X;const n=e;if(!n.isSkinnedMesh)return;if(o++,n.skeleton.bones.length!==j.length||n.skeleton.bones.some((c,f)=>c.name!==W[f]||n.skeleton.boneInverses[f].elements.some((E,L)=>Math.abs(E-D[f].elements[L])>.001)))throw new Error(`Incompatible character part: ${i.parts[r].name}`);const p=n.geometry.clone();ne(p),O.push(p);const g=p.getAttribute("_tint"),w=p.getAttribute("color"),T=new $(i.recipe.colors.skin),H=new $(i.recipe.colors.hair),J=new $(i.recipe.colors.cloth),K=((X=i.recipe.partColorModes)==null?void 0:X[i.parts[r].slot])??i.recipe.colorMode??"custom";for(let c=0;c<w.count;c++){const f=(g==null?void 0:g.getX(c))??0;if(K==="custom"&&(f===1||f===2||f===3)){const E=f===1?T:f===2?H:J,L=Math.min(1.6,Math.max(.3,(w.getX(c)+w.getY(c)+w.getZ(c))/(f===1?.8:.18)));w.setXYZ(c,E.r*L,E.g*L,E.b*L)}}for(const c of Object.keys(p.attributes))["position","normal","color","skinIndex","skinWeight"].includes(c)||p.deleteAttribute(c)}),o!==1)throw new Error("Each modular part must contain one skinned mesh.")}if(d=re(O),!d||d.index.count/3>q.triangles)throw new Error("Character geometry exceeds the profile.");x=new se({vertexColors:!0,roughness:.85,side:ie});const C=new ae(d,x);C.name="ModularCharacter",C.frustumCulled=!1,C.castShadow=!0,l.add(C),C.bind(S,new ce);const A=new le(l),u=new Map;for(const r of h.animations)u.set(r.name,A.clipAction(r));let B="idle",M=u.get("idle").play(),m,F=0,v,G=null,N=0,I=!1,P=0;const z=["L","R"].flatMap(r=>{const t=l.getObjectByName(`Foot${r}`),o=l.getObjectByName(`LowerLeg${r}`);return t&&o&&t.parent!==o?[{foot:t,leg:o,anchor:o.worldToLocal(t.getWorldPosition(new Z))}]:[]}),R=new Z;return{root:k,budget:{profile:"pocket-humanoid-v2",triangles:d.index.count/3,drawCalls:null,materials:1,texturePixels:0,textureBytes:0,skinningTextureBytes:0,joints:j.length,influences:4,coveredTriangles:0,pass:"Unmeasured"},update(r,t){if(I)return;const o=Math.min(.1,Math.max(0,r));let e=typeof t=="boolean"?t?"walk":"idle":t;(e==="wave"||e==="dance")&&(e="idle"),u.has(e)||(e="idle"),e!==B&&(a(),m==null||m.stop(),m=M,F=.16,m.fadeOut(.16),M=u.get(e).reset().setEffectiveWeight(1).fadeIn(.16).play(),B=e,["jump","land","fall"].includes(e)?(M.setLoop(Y,1),M.clampWhenFinished=!0):M.setLoop(V,1/0)),m&&(F-=o)<=0&&(m.stop(),m=void 0),v&&(N-=o)<=0&&a(),v||M.setEffectiveWeight(1),A.update(o),l.updateMatrixWorld(!0);for(const n of z)R.copy(n.anchor),n.leg.localToWorld(R),n.foot.parent.worldToLocal(R),n.foot.position.copy(R),n.foot.updateMatrixWorld(!0)},wave(){b("wave")},emote:b,async playClip(r,t,o=!1){const e=++P,n=await U(_(r));try{if(I||e!==P)return;const p=n.value.animations.find(g=>g.name===t);if(!p)throw new Error("Animation clip is missing.");a();for(const[g,w]of u)h.animations.some(T=>T.name===g)||(w.stop(),A.uncacheAction(w.getClip(),l),u.delete(g));u.set(t,A.clipAction(p)),b(t,0,o)}finally{n.release()}},diagnostics(){return{activeActions:[...u.values()].filter(r=>r.isRunning()).length,locomotion:B,emote:G}},dispose(){I||(I=!0,P++,A.stopAllAction(),A.uncacheRoot(l),d.dispose(),x.dispose(),S.dispose(),k.removeFromParent())}}}catch(a){throw d==null||d.dispose(),x==null||x.dispose(),S.dispose(),a}finally{O.forEach(a=>a.dispose())}}let Q=Promise.resolve();function me(i){const s=Q.then(()=>de(i));return Q=s.catch(()=>{}),s}async function de(i){const s=i.character;if(!s)throw new Error("Missing modular character recipe.");const y=[];try{for(const h of[s.rig,...s.parts.map(k=>k.asset),s.defaultAnimations])y.push(await U(_(h)));return fe(s,y[0].value,y.slice(1,-1).map(h=>h.value),y.at(-1).value)}finally{y.forEach(h=>h.release())}}export{_ as characterAssetUrl,fe as composeCharacter,me as loadCharacterAvatar};
