@sage-rsc/talking-head-react 1.6.2 → 1.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const X=require("react/jsx-runtime"),b=require("react"),Ke=require("three"),$e=require("three/addons/controls/OrbitControls.js"),Je=require("three/addons/loaders/GLTFLoader.js"),et=require("three/addons/loaders/DRACOLoader.js"),Ve=require("three/addons/loaders/FBXLoader.js"),tt=require("three/addons/environments/RoomEnvironment.js"),nt=require("three/addons/libs/stats.module.js");var De=typeof document<"u"?document.currentScript:null;function it(G){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(G){for(const e in G)if(e!=="default"){const n=Object.getOwnPropertyDescriptor(G,e);Object.defineProperty(t,e,n.get?n:{enumerable:!0,get:()=>G[e]})}}return t.default=G,Object.freeze(t)}const x=it(Ke);let m,me,ge;const T=[0,0,0,0],D=new x.Vector3,Me=new x.Vector3,ue=new x.Vector3,Fe=new x.Vector3;new x.Plane;new x.Ray;new x.Euler;const he=new x.Quaternion,Ge=new x.Quaternion,be=new x.Matrix4,ve=new x.Matrix4;new x.Vector3;const Ee=new x.Vector3(0,0,1),ot=new x.Vector3(1,0,0),st=new x.Vector3(0,1,0),at=new x.Vector3(0,0,1);class rt{constructor(t=null){this.opt=Object.assign({warmupMs:2e3,sensitivityFactor:1,movementFactor:1,isExcludes:!0,isPivots:!0,isLimits:!0,helperBoneColor1:16711680,helperBoneColor2:16238028,helperLinkColor1:16711680,helperLinkColor2:255,helperExcludesColor:11184895},t||{}),this.scene=null,this.armature=null,this.config=[],this.data=[],this.dict={},this.objectsUpdate=[],this.helpers={isActive:!1,isShowAll:!1,points:{bones:[],pivots:[],object:null},lines:{bones:[],object:null},excludes:{bones:[],deltaLocals:[],radii:[],objects:[]}},this.running=!1,this.timerMs=0}getOptionValue(t){return this.opt[t]}setOptionValue(t,e){this.opt[t]=e,this.helpers.isActive&&this.showHelpers()}getBoneNames(){return this.data.map(t=>t.name)}getValue(t,e){if(this.scene===null)throw new Error("Dynamic bones has not been setup yet.");if(!this.dict.hasOwnProperty(t))throw new Error("Dynamic bone '"+t+"' not found.");const n=this.dict[t];let i;if(e==="type")i=n.type;else if(e==="stiffness")i=n.k.every(s=>s===n.k[0])?n.k[0]:[...n.k];else if(e==="damping")i=n.c.every(s=>s===n.c[0])?n.c[0]:[...n.c];else if(e==="external")i=n.ext<1?n.ext:null;else if(e==="limits")i=n.limits?.map(s=>s===null?null:[...s]);else if(e==="deltaLocal")i=n.dl?[...n.dl]:null;else if(e==="excludes")i=n.excludes?[...n.excludes.map(s=>{const o={bone:s.bone.name.slice(),radius:s.radius};return s.deltaLocal&&(o.deltaLocal=[...s.deltaLocal]),o})]:null;else if(e==="deltaWorld")i=n.dw?[...n.dw]:null;else if(e==="pivot")i=n.pivot;else if(e==="helper")i=n.helper;else throw new Error("Unsupported property '"+e+"'.");return i}setValue(t,e,n){if(this.scene===null)throw new Error("Dynamic bones has not been setup yet.");if(!this.dict.hasOwnProperty(t))throw new Error("Dynamic bone '"+t+"' not found.");const i=this.dict[t];if(e==="type"){if(!n)throw new Error("Parameter 'type' not set.");if(typeof n!="string")throw new Error("Type must be a string.");switch(n){case"point":i.isPoint=!0,i.isX=!0,i.isY=!0,i.isZ=!0,i.isT=!1;break;case"link":i.isPoint=!1,i.isX=!0,i.isY=!1,i.isZ=!0,i.isT=!1;break;case"mix1":i.isPoint=!1,i.isX=!0,i.isY=!0,i.isZ=!0,i.isT=!1;break;case"mix2":i.isPoint=!1,i.isX=!0,i.isY=!1,i.isZ=!0,i.isT=!0;break;case"full":i.isPoint=!1,i.isX=!0,i.isY=!0,i.isZ=!0,i.isT=!0;break;default:throw new Error("Unknown type'"+n+"'.")}i.type=n.slice()}else if(e==="stiffness"){if(!n)throw new Error("Parameter 'stiffness' not set.");if(!Number.isNaN(n)&&n>=0)i.k=Array(4).fill(n);else if(Array.isArray(n)&&n.length===4&&n.every(s=>s>=0))i.k=[...n];else throw new Error("Stiffness must be a non-negative number or an array of four non-negative numbers.")}else if(e==="damping"){if(!n)throw new Error("Parameter 'damping' not set.");if(!Number.isNaN(n)&&n>=0)i.c=Array(4).fill(n);else if(Array.isArray(n)&&n.length===4&&n.every(s=>s>=0))i.c=[...n];else throw new Error("Damping must be a non-negative number or an array of four non-negative numbers.")}else if(e==="external")if(n==null)i.ext=1;else if(!Number.isNaN(n)&&n>=0&&n<=1)i.ext=n;else throw new Error("External (if set) must be a number between [0,1].");else if(e==="limits")if(n==null)i.limits=null;else{if(!Array.isArray(n)||n.length!==4)throw new Error("Limits (if set) must null, or an array of four arrays.");if(!n.every(s=>s===null||Array.isArray(s)&&s.length===2&&(s[0]===null||!Number.isNaN(s[0]))&&(s[1]===null||!Number.isNaN(s))))throw new Error("Limit values must be null or numbers.");i.limits=[n[0]?[...n[0]]:null,n[1]?[...n[1]]:null,n[2]?[...n[2]]:null,n[3]?[...n[3]]:null]}else if(e==="excludes"){if(n==null)i.excludes=null;else{if(!Array.isArray(n))throw new Error("Excludes (if set) must null, or an array.");i.excludes=[],n.forEach((s,o)=>{if(!s.bone)throw new Error("Bone not specified in #"+o+" exclude.");if(typeof s.bone!="string"||s.bone.length===0)throw new Error("Bone name must be a non-empty string in #"+o+" exclude.");const r=this.armature.getObjectByName(s.bone);if(!r)throw new Error("Bone '"+s.bone+"' not found in #"+o+" exclude.");if(Number.isNaN(s.radius)&&s.radius>=0)throw new Error("Radius must be a non-negative number in #"+o+" exclude.");const u={bone:r,radius:s.radius,radiusSq:s.radius*s.radius,deltaLocal:null};if(s.deltaLocal){if(!Array.isArray(s.deltaLocal)||s.deltaLocal.length!==3||s.deltaLocal.some(a=>Number.isNaN(a)))throw new Error("deltaLocal must be an array of three numbers in #"+o+" exclude.");u.deltaLocal=[...s.deltaLocal]}i.excludes.push(u)})}this.showHelpers()}else if(e==="helper"){if(n==null)i.helper=null;else{if(n!==!1&&n!==!0)throw new Error("Helper, if set, must be false or true.");i.helper=n}this.showHelpers()}else if(e==="pivot")if(n==null)i.pivot=null;else{if(n!==!1&&n!==!0)throw new Error("Pivot, if set, must be false or true.");if(n===!0&&i.type===0)throw new Error("Point type bone can't be a pivot.");i.pivot=n}else if(e==="deltaLocal")if(n==null)i.dl=null;else{if(!Array.isArray(n)||n.length!==3)throw new Error("deltaLocal, is set, must be an array of three numbers.");if(!n.every(s=>!Number.isNaN(s)))throw new Error("deltaLocal values must be numbers.");i.dl=[...n]}else if(e==="deltaWorld")if(n==null)i.dw=null;else{if(!Array.isArray(n)||n.length!==3)throw new Error("deltaWorld, is set, must be an array of three values.");if(!n.every(s=>!Number.isNaN(s)))throw new Error("deltaWorld values must be numbers.");i.dw=[...n]}else throw new Error("Unsupported property "+e)}getConfig(){return this.data.map(t=>{const e={bone:t.name.slice()};return["type","stiffness","damping","external","deltaLocal","deltaWorld","limits","excludes","pivot","helper"].forEach(n=>{m=this.getValue(t.name,n),m&&(e[n]=m)}),e})}sortBones(){if(this.scene===null)throw new Error("Dynamic bones has not been setup yet.");let t=0;const e=new WeakMap;this.armature.traverse(o=>{e.has(o)||(e.set(o,t),t++)}),this.data.sort((o,r)=>e.get(o.bone)-e.get(r.bone)),this.data.forEach(o=>{m=this.dict[o.boneParent.name],m&&(m.children||(m.children=[]),m.children.push(o))}),this.objectsUpdate=[];const n=new WeakSet,i=o=>o.parent?.isBone?[o,...i(o.parent)]:[o],s=o=>{i(o).forEach(u=>{n.has(u)||(this.objectsUpdate.push(u),n.add(u))})};this.data.forEach(o=>{s(o.bone),o.excludes&&o.excludes.forEach(r=>{s(r.bone)})}),this.objectsUpdate.sort((o,r)=>e.get(o)-e.get(r))}setup(t,e,n){this.dispose();const i=(s,o)=>{if(!s)throw this.dispose(),new Error(o)};i(t?.isScene,"First parameter must be Scene."),this.scene=t,i(e?.isObject3D,"Second parameter must be the armature Object3D."),this.armature=e,i(Array.isArray(n),"Third parameter must be an array of bone configs."),this.config=n,this.config.forEach((s,o)=>{const r="Config item #"+o+": ";i(s.bone,r+"Bone not specified.");const u=s.bone;i(typeof u=="string"&&u.length>0,r+"Bone name must be a non-empty string.");const a=this.armature.getObjectByName(u);i(a,r+"Bone '"+u+"' not found."),i(a.parent?.isBone,r+"Bone must have a parent bone."),i(this.data.every(l=>l.bone!==a),r+"Bone '"+u+"' already exists."),a.updateMatrixWorld(!0);const c={name:u,bone:a,boneParent:a.parent,vBasis:a.position.clone(),vWorld:a.parent.getWorldPosition(D).clone(),qBasis:a.parent.quaternion.clone(),l:a.position.length(),p:[0,0,0,0],v:[0,0,0,0],a:[0,0,0,0],ev:[0,0,0,0],ea:[0,0,0,0]};c.boneParent.matrixWorld.decompose(D,he,ue),D.copy(Ee).applyQuaternion(he).setY(0).normalize(),he.premultiply(Ge.setFromUnitVectors(Ee,D).invert()).normalize(),c.qWorldInverseYaw=he.clone().normalize(),this.data.push(c),this.dict[u]=c;try{this.setValue(u,"type",s.type),this.setValue(u,"stiffness",s.stiffness),this.setValue(u,"damping",s.damping),this.setValue(u,"external",s.external),this.setValue(u,"limits",s.limits),this.setValue(u,"excludes",s.excludes),this.setValue(u,"deltaLocal",s.deltaLocal),this.setValue(u,"deltaWorld",s.deltaWorld),this.setValue(u,"pivot",s.pivot),this.setValue(u,"helper",s.helper)}catch(l){i(!1,r+l)}}),this.sortBones(),this.start()}update(t){if(!this.running)return;let e,n,i,s,o;for(this.timerMs+=t,t>1e3&&(this.timerMs=0),t/=1e3,e=0,i=this.objectsUpdate.length;e<i;e++)o=this.objectsUpdate[e],o.updateMatrix(),o.parent===null?o.matrixWorld.copy(o.matrix):o.matrixWorld.multiplyMatrices(o.parent.matrixWorld,o.matrix),o.matrixWorldNeedsUpdate=!1;for(e=0,i=this.data.length;e<i;e++){if(o=this.data[e],D.copy(o.vWorld),be.copy(o.boneParent.matrixWorld),ve.copy(be).invert(),o.vWorld.setFromMatrixPosition(be),D.applyMatrix4(ve),D.length()>.5&&(console.info("Info: Unrealistic jump of "+D.length().toFixed(2)+" meters."),D.setLength(.5)),D.applyQuaternion(o.bone.quaternion),T[0]=D.x,T[1]=D.y,T[2]=-D.z,T[3]=D.length()/3,o.children)for(n=0,s=o.children.length;n<s;n++)m=o.children[n],T[0]-=m.v[0]*t/3,T[1]-=m.v[1]*t/3,T[2]+=m.v[2]*t/3,T[3]-=m.v[3]*t/3;if(m=this.opt.sensitivityFactor,T[0]*=o.ext*m,T[1]*=o.ext*m,T[2]*=o.ext*m,T[3]*=o.ext*m,o.isX&&(m=T[0]/t,o.ea[0]=(m-o.ev[0])/t,o.ev[0]=m,o.a[0]=-o.k[0]*o.p[0]-o.c[0]*o.v[0]-o.ea[0],o.p[0]+=o.v[0]*t+o.a[0]*t*t/2+T[0],m=o.v[0]+o.a[0]*t/2,m=-o.k[0]*o.p[0]-o.c[0]*m-o.ea[0],o.v[0]=o.v[0]+(m+o.a[0])*t/2),o.isY&&(m=T[1]/t,o.ea[1]=(m-o.ev[1])/t,o.ev[1]=m,o.a[1]=-o.k[1]*o.p[1]-o.c[1]*o.v[1]-o.ea[1],o.p[1]+=o.v[1]*t+o.a[1]*t*t/2+T[1],m=o.v[1]+o.a[1]*t/2,m=-o.k[1]*o.p[1]-o.c[1]*m-o.ea[1],o.v[1]=o.v[1]+(m+o.a[1])*t/2),o.isZ&&(m=T[2]/t,o.ea[2]=(m-o.ev[2])/t,o.ev[2]=m,o.a[2]=-o.k[2]*o.p[2]-o.c[2]*o.v[2]-o.ea[2],o.p[2]+=o.v[2]*t+o.a[2]*t*t/2+T[2],m=o.v[2]+o.a[2]*t/2,m=-o.k[2]*o.p[2]-o.c[2]*m-o.ea[2],o.v[2]=o.v[2]+(m+o.a[2])*t/2),o.isT&&(m=T[3]/t,o.ea[3]=(m-o.ev[3])/t,o.ev[3]=m,o.a[3]=-o.k[3]*o.p[3]-o.c[3]*o.v[3]-o.ea[3],o.p[3]+=o.v[3]*t+o.a[3]*t*t/2+T[3],m=o.v[3]+o.a[3]*t/2,m=-o.k[3]*o.p[3]-o.c[3]*m-o.ea[3],o.v[3]=o.v[3]+(m+o.a[3])*t/2),this.timerMs<this.opt.warmupMs&&(o.v[0]*=1e-4,o.p[0]*=1e-4,o.v[1]*=1e-4,o.p[1]*=1e-4,o.v[2]*=1e-4,o.p[2]*=1e-4,o.v[3]*=1e-4,o.p[3]*=1e-4),T[0]=o.p[0],T[1]=o.p[1],T[2]=o.p[2],T[3]=o.p[3],m=this.opt.movementFactor,T[0]*=m,T[1]*=m,T[2]*=m,T[3]*=m,o.dl&&(m=o.dl,T[0]+=m[0],T[1]+=m[1],T[2]+=m[2]),o.dw&&(m=o.dw,D.set(o.vBasis.x+T[0],o.vBasis.y+T[1],o.vBasis.z+T[2]),D.applyMatrix4(be),D.x+=m[0],D.y+=m[1],D.z+=m[2],D.applyMatrix4(ve),T[0]+=D.x-o.vBasis.x,T[1]+=D.y-o.vBasis.y,T[2]+=D.z-o.vBasis.z),o.limits&&this.opt.isLimits&&(m=o.limits,m[0]&&(m[0][0]!==null&&T[0]<m[0][0]&&(T[0]=m[0][0]),m[0][1]!==null&&T[0]>m[0][1]&&(T[0]=m[0][1])),m[1]&&(m[1][0]!==null&&T[1]<m[1][0]&&(T[1]=m[1][0]),m[1][1]!==null&&T[1]>m[1][1]&&(T[1]=m[1][1])),m[2]&&(m[2][0]!==null&&T[2]<m[2][0]&&(T[2]=m[2][0]),m[2][1]!==null&&T[2]>m[2][1]&&(T[2]=m[2][1])),m[3]&&(m[3][0]!==null&&T[3]<m[3][0]&&(T[3]=m[3][0]),m[3][1]!==null&&T[3]>m[3][1]&&(T[3]=m[3][1]))),o.isPoint)o.bone.position.set(o.vBasis.x+T[0],o.vBasis.y+T[1],o.vBasis.z-T[2]);else if(o.boneParent.quaternion.copy(o.qBasis),o.pivot&&this.opt.isPivots&&(o.boneParent.updateWorldMatrix(!1,!1),o.boneParent.matrixWorld.decompose(D,he,ue),D.copy(Ee).applyQuaternion(he).setY(0).normalize(),he.premultiply(Ge.setFromUnitVectors(Ee,D).invert()).normalize(),o.boneParent.quaternion.multiply(he.invert()),o.boneParent.quaternion.multiply(o.qWorldInverseYaw)),o.isZ&&(m=Math.atan(T[0]/o.l),he.setFromAxisAngle(at,-m),o.boneParent.quaternion.multiply(he)),o.isY&&(m=o.l/3,m=m*Math.tanh(T[1]/m),o.bone.position.setLength(o.l+m)),o.isX&&(m=Math.atan(T[2]/o.l),he.setFromAxisAngle(ot,-m),o.boneParent.quaternion.multiply(he)),o.isT&&(m=1.5*Math.tanh(T[3]*1.5),he.setFromAxisAngle(st,-m),o.boneParent.quaternion.multiply(he)),o.boneParent.updateWorldMatrix(!1,!0),o.excludes&&this.opt.isExcludes)for(n=0,s=o.excludes.length;n<s;n++)m=o.excludes[n],ue.set(0,0,0),m.deltaLocal&&(ue.x+=m.deltaLocal[0],ue.y+=m.deltaLocal[1],ue.z+=m.deltaLocal[2]),ue.applyMatrix4(m.bone.matrixWorld),ve.copy(o.boneParent.matrixWorld).invert(),ue.applyMatrix4(ve),D.copy(o.bone.position),!(D.distanceToSquared(ue)>=m.radiusSq)&&(ge=D.length(),me=ue.length(),!(me>m.radius+ge)&&(me<Math.abs(m.radius-ge)||(me=(me*me+ge*ge-m.radiusSq)/(2*me),ue.normalize(),Fe.copy(ue).multiplyScalar(me),me=Math.sqrt(ge*ge-me*me),D.subVectors(D,Fe).projectOnPlane(ue).normalize().multiplyScalar(me),Me.subVectors(o.vBasis,Fe).projectOnPlane(ue).normalize(),ge=Me.dot(D),ge<0&&(ge=Math.sqrt(me*me-ge*ge),Me.multiplyScalar(ge),D.add(Me)),D.add(Fe).normalize(),ue.copy(o.bone.position).normalize(),he.setFromUnitVectors(ue,D),o.boneParent.quaternion.premultiply(he),o.boneParent.updateWorldMatrix(!1,!0))))}this.helpers.isActive&&this.updateHelpers()}showHelpers(t){if(this.hideHelpers(),this.helpers.isShowAll=t===void 0?this.helpers.isShowAll:t===!0,m=this.helpers,this.data.forEach(e=>{(this.helpers.isShowAll||e.helper===!0)&&(m.points.bones.push(e.bone),m.points.pivots.push(e.pivot),e.type!==0&&m.lines.bones.push(e.bone),e.excludes&&e.excludes.forEach(n=>{let i=!1;for(let s=0;s<m.excludes.bones.length;s++)if(m.excludes.bones[s]===n.bone&&m.excludes.radii[s]===n.radius&&!(m.excludes.deltaLocals[s]===null&&n.deltaLocal!==null)&&!(m.excludes.deltaLocals[s]!==null&&n.deltaLocal===null)&&!(m.excludes.deltaLocals[s]!==null&&m.excludes.deltaLocals[s].some((o,r)=>o!==n.deltaLocal[r]))){i=!0;break}i||(m.excludes.bones.push(n.bone),m.excludes.radii.push(n.radius),m.excludes.deltaLocals.push(n.deltaLocal?[...n.deltaLocal]:null),m.excludes.objects.push(null))}))}),m=this.helpers.excludes,this.opt.isExcludes&&m.bones.length&&m.bones.forEach((e,n)=>{const i=new x.SphereGeometry(m.radii[n],6,6),s=new x.MeshBasicMaterial({depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0,wireframe:!0,color:this.opt.helperExcludesColor});m.objects[n]=new x.Mesh(i,s),m.objects[n].renderOrder=997,e.add(m.objects[n]),m.deltaLocals[n]&&m.objects[n].position.set(m.deltaLocals[n][0],m.deltaLocals[n][1],m.deltaLocals[n][2])}),m=this.helpers.points,m.bones.length){this.helpers.isActive=!0;const e=new x.BufferGeometry,n=m.bones.map(u=>[0,0,0]).flat();e.setAttribute("position",new x.Float32BufferAttribute(n,3));const i=new x.Color(this.opt.helperBoneColor1),s=new x.Color(this.opt.helperBoneColor2),o=m.pivots.map(u=>u&&this.opt.isPivots?[s.r,s.g,s.b]:[i.r,i.g,i.b]).flat();e.setAttribute("color",new x.Float32BufferAttribute(o,3));const r=new x.PointsMaterial({depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0,size:.2,vertexColors:!0});m.object=new x.Points(e,r),m.object.renderOrder=998,m.object.matrix=this.armature.matrixWorld,m.object.matrixAutoUpdate=!1,this.scene.add(m.object)}if(m=this.helpers.lines,m.bones.length){const e=new x.BufferGeometry,n=m.bones.map(u=>[0,0,0,0,0,0]).flat();e.setAttribute("position",new x.Float32BufferAttribute(n,3));const i=new x.Color(this.opt.helperLinkColor1),s=new x.Color(this.opt.helperLinkColor2),o=m.bones.map(u=>[i.r,i.g,i.b,s.r,s.g,s.b]).flat();e.setAttribute("color",new x.Float32BufferAttribute(o,3));const r=new x.LineBasicMaterial({vertexColors:!0,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0});m.object=new x.LineSegments(e,r),m.object.renderOrder=999,m.object.matrix=this.armature.matrixWorld,m.object.matrixAutoUpdate=!1,this.scene.add(m.object)}}updateHelpers(){if(m=this.helpers.points,m.bones.length){ve.copy(this.armature.matrixWorld).invert();const t=m.object.geometry.getAttribute("position");for(let e=0,n=m.bones.length;e<n;e++)be.multiplyMatrices(ve,m.bones[e].matrixWorld),D.setFromMatrixPosition(be),t.setXYZ(e,D.x,D.y,D.z);t.needsUpdate=!0,m.object.updateMatrixWorld()}if(m=this.helpers.lines,m.bones.length){ve.copy(this.armature.matrixWorld).invert();const t=m.object.geometry.getAttribute("position");for(let e=0,n=0,i=m.bones.length;e<i;e++,n+=2)be.multiplyMatrices(ve,m.bones[e].matrixWorld),D.setFromMatrixPosition(be),t.setXYZ(n,D.x,D.y,D.z),be.multiplyMatrices(ve,m.bones[e].parent.matrixWorld),D.setFromMatrixPosition(be),t.setXYZ(n+1,D.x,D.y,D.z);t.needsUpdate=!0,m.object.updateMatrixWorld()}}hideHelpers(){[this.helpers.points,this.helpers.lines].forEach(t=>{t.bones=[],t.object&&(this.scene.remove(t.object),t.object.geometry.dispose(),t.object.material.dispose(),t.object=null)}),m=this.helpers.excludes,m.objects.forEach((t,e)=>{t&&(m.bones[e].remove(t),t.geometry.dispose(),t.material.dispose())}),m.bones=[],m.deltaLocals=[],m.radii=[],m.objects=[],this.helpers.isActive=!1}start(){this.data.length&&(this.running=!0,this.timerMs=0,this.showHelpers())}stop(){this.running=!1,this.hideHelpers();for(let t=0,e=this.data.length;t<e;t++){const n=this.data[t];n.bone.position.copy(n.vBasis),n.boneParent.quaternion.copy(n.qBasis)}}dispose(){this.stop(),this.scene=null,this.armature=null,this.config=[],this.data=[],this.dict={},this.objectsUpdate=[],this.timerMs=0}}class lt{constructor(t){this.audioContext=t,this.analyzer=null,this.dataArray=null,this.bufferLength=0}async analyzeAudio(t,e){const n=t.sampleRate,i=t.duration,s=t.getChannelData(0),o=this.extractAudioFeatures(s,n);return this.generateTimingData(o,e,i)}extractAudioFeatures(t,e){const n={energy:[],spectralCentroid:[],zeroCrossingRate:[],mfcc:[],onsets:[],phonemeBoundaries:[]},i=1024,s=512,o=Math.floor((t.length-i)/s)+1;for(let r=0;r<o;r++){const u=r*s,a=Math.min(u+i,t.length),c=t.slice(u,a),l=this.calculateEnergy(c);n.energy.push(l);const d=this.calculateSpectralCentroid(c);n.spectralCentroid.push(d);const h=this.calculateZeroCrossingRate(c);n.zeroCrossingRate.push(h);const p=this.calculateMFCC(c);n.mfcc.push(p)}return n.onsets=this.detectOnsets(n.energy),n.phonemeBoundaries=this.detectPhonemeBoundaries(n),n}calculateEnergy(t){let e=0;for(let n=0;n<t.length;n++)e+=t[n]*t[n];return e/t.length}calculateSpectralCentroid(t){const e=this.fft(t);let n=0,i=0;for(let s=0;s<e.length/2;s++){const o=Math.sqrt(e[s*2]*e[s*2]+e[s*2+1]*e[s*2+1]);n+=s*o,i+=o}return i>0?n/i:0}calculateZeroCrossingRate(t){let e=0;for(let n=1;n<t.length;n++)t[n]>=0!=t[n-1]>=0&&e++;return e/(t.length-1)}calculateMFCC(t){const e=this.fft(t),n=[];for(let i=0;i<13;i++){let s=0;for(let o=0;o<e.length/2;o++){const r=Math.sqrt(e[o*2]*e[o*2]+e[o*2+1]*e[o*2+1]);s+=r*Math.cos(Math.PI*i*(o+.5)/(e.length/2))}n.push(s)}return n}fft(t){const e=t.length,n=new Float32Array(e*2);for(let i=0;i<e;i++)n[i*2]=t[i],n[i*2+1]=0;for(let i=1,s=0;i<e;i++){let o=e>>1;for(;s&o;)s^=o,o>>=1;if(s^=o,i<s){const r=n[i*2],u=n[i*2+1];n[i*2]=n[s*2],n[i*2+1]=n[s*2+1],n[s*2]=r,n[s*2+1]=u}}for(let i=2;i<=e;i<<=1){const s=-2*Math.PI/i,o=Math.cos(s),r=Math.sin(s);for(let u=0;u<e;u+=i){let a=1,c=0;for(let l=0;l<i/2;l++){const d=n[(u+l)*2],h=n[(u+l)*2+1],p=n[(u+l+i/2)*2]*a-n[(u+l+i/2)*2+1]*c,v=n[(u+l+i/2)*2]*c+n[(u+l+i/2)*2+1]*a;n[(u+l)*2]=d+p,n[(u+l)*2+1]=h+v,n[(u+l+i/2)*2]=d-p,n[(u+l+i/2)*2+1]=h-v;const y=a*o-c*r,w=a*r+c*o;a=y,c=w}}}return n}detectOnsets(t){const e=[];let s=-.1;for(let o=1;o<t.length;o++){const r=t[o]-t[o-1],u=o*.023;r>.1&&u-s>.1&&(e.push(u),s=u)}return e}detectPhonemeBoundaries(t){const e=[],{energy:n,spectralCentroid:i,zeroCrossingRate:s}=t;for(let o=1;o<n.length;o++){const r=o*.023,u=Math.abs(n[o]-n[o-1]),a=Math.abs(i[o]-i[o-1]),c=Math.abs(s[o]-s[o-1]);u+a*.1+c*.5>.2&&e.push(r)}return e}generateTimingData(t,e,n){const i=e.toLowerCase().split(/\s+/);t.phonemeBoundaries,t.onsets;const s=[];let o=0;for(let u=0;u<i.length;u++){const a=i[u],c=this.estimateWordDuration(a,n/i.length);s.push({word:a,startTime:o,endTime:o+c,duration:c}),o+=c}const r=this.generateVisemeTimings(t,e,n);return{words:s,visemes:r,duration:n,features:t}}estimateWordDuration(t,e){const n=Math.max(.5,Math.min(2,t.length/5)),i=this.getWordComplexity(t);return e*n*i}getWordComplexity(t){const e=(t.match(/[bcdfghjklmnpqrstvwxyz]{2,}/g)||[]).length,n=(t.match(/[aeiou]{2,}/g)||[]).length;return 1+e*.2+n*.1}generateVisemeTimings(t,e,n){const i=[],s=t.phonemeBoundaries;t.onsets;const o=this.textToVisemes(e);let r=0,u=0;for(let a=0;a<s.length&&r<o.length;a++){const c=s[a],l=o[r],d=t.energy[Math.floor(c/.023)]||0,h=this.calculateVisemeDuration(l,d);i.push({viseme:l,startTime:u,endTime:u+h,duration:h,intensity:Math.min(1,d*2)}),u+=h,r++}for(;r<o.length;){const a=o[r],c=this.calculateVisemeDuration(a,.5);i.push({viseme:a,startTime:u,endTime:u+c,duration:c,intensity:.6}),u+=c,r++}return i}textToVisemes(t){const e={a:"aa",e:"E",i:"I",o:"O",u:"U",ae:"aa",ai:"aa",au:"O",ea:"E",ee:"E",ei:"E",ie:"I",oa:"O",oo:"U",ou:"U",b:"PP",p:"PP",m:"PP",f:"FF",v:"FF",th:"SS",s:"SS",z:"SS",sh:"SS",ch:"SS",d:"DD",t:"DD",n:"nn",l:"nn",k:"kk",g:"kk",ng:"kk",r:"RR",w:"RR",y:"I",h:"kk"},n=[],i=t.toLowerCase().replace(/[^a-z\s]/g,"").split(/\s+/);for(const s of i){let o=0;for(;o<s.length;){let r=!1;for(let u=3;u>=2;u--){const a=s.substr(o,u);if(e[a]){n.push(e[a]),o+=u,r=!0;break}}if(!r){const u=s[o];e[u]&&n.push(e[u]),o++}}}return n}calculateVisemeDuration(t,e){const i={aa:.15,E:.12,I:.1,O:.14,U:.13,PP:.08,FF:.1,SS:.12,DD:.11,kk:.09,nn:.1,RR:.11}[t]||.1,s=.5+e*.5;return i*s}}class ct{constructor(){this.rules={A:["[A] =aa"," [ARE] =aa RR"," [AR]O=aa RR","[AR]#=E RR"," ^[AS]#=E SS","[A]WA=aa","[AW]=aa"," :[ANY]=E nn I","[A]^+#=E","#:[ALLY]=aa nn I"," [AL]#=aa nn","[AGAIN]=aa kk E nn","#:[AG]E=I kk","[A]^+:#=aa",":[A]^+ =E","[A]^%=E"," [ARR]=aa RR","[ARR]=aa RR"," :[AR] =aa RR","[AR] =E","[AR]=aa RR","[AIR]=E RR","[AI]=E","[AY]=E","[AU]=aa","#:[AL] =aa nn","#:[ALS] =aa nn SS","[ALK]=aa kk","[AL]^=aa nn"," :[ABLE]=E PP aa nn","[ABLE]=aa PP aa nn","[ANG]+=E nn kk","[A]=aa"],B:[" [BE]^#=PP I","[BEING]=PP I I nn"," [BOTH] =PP O TH"," [BUS]#=PP I SS","[BUIL]=PP I nn","[B]=PP"],C:[" [CH]^=kk","^E[CH]=kk","[CH]=CH"," S[CI]#=SS aa","[CI]A=SS","[CI]O=SS","[CI]EN=SS","[C]+=SS","[CK]=kk","[COM]%=kk aa PP","[C]=kk"],D:["#:[DED] =DD I DD",".E[D] =DD","#^:E[D] =DD"," [DE]^#=DD I"," [DO] =DD U"," [DOES]=DD aa SS"," [DOING]=DD U I nn"," [DOW]=DD aa","[DU]A=kk U","[D]=DD"],E:["#:[E] =","'^:[E] ="," :[E] =I","#[ED] =DD","#:[E]D =","[EV]ER=E FF","[E]^%=I","[ERI]#=I RR I","[ERI]=E RR I","#:[ER]#=E","[ER]#=E RR","[ER]=E"," [EVEN]=I FF E nn","#:[E]W=","@[EW]=U","[EW]=I U","[E]O=I","#:&[ES] =I SS","#:[E]S =","#:[ELY] =nn I","#:[EMENT]=PP E nn DD","[EFUL]=FF U nn","[EE]=I","[EARN]=E nn"," [EAR]^=E","[EAD]=E DD","#:[EA] =I aa","[EA]SU=E","[EA]=I","[EIGH]=E","[EI]=I"," [EYE]=aa","[EY]=I","[EU]=I U","[E]=E"],F:["[FUL]=FF U nn","[F]=FF"],G:["[GIV]=kk I FF"," [G]I^=kk","[GE]T=kk E","SU[GGES]=kk kk E SS","[GG]=kk"," B#[G]=kk","[G]+=kk","[GREAT]=kk RR E DD","#[GH]=","[G]=kk"],H:[" [HAV]=I aa FF"," [HERE]=I I RR"," [HOUR]=aa EE","[HOW]=I aa","[H]#=I","[H]="],I:[" [IN]=I nn"," [I] =aa","[IN]D=aa nn","[IER]=I E","#:R[IED] =I DD","[IED] =aa DD","[IEN]=I E nn","[IE]T=aa E"," :[I]%=aa","[I]%=I","[IE]=I","[I]^+:#=I","[IR]#=aa RR","[IZ]%=aa SS","[IS]%=aa SS","[I]D%=aa","+^[I]^+=I","[I]T%=aa","#^:[I]^+=I","[I]^+=aa","[IR]=E","[IGH]=aa","[ILD]=aa nn DD","[IGN] =aa nn","[IGN]^=aa nn","[IGN]%=aa nn","[IQUE]=I kk","[I]=I"],J:["[J]=kk"],K:[" [K]N=","[K]=kk"],L:["[LO]C#=nn O","L[L]=","#^:[L]%=aa nn","[LEAD]=nn I DD","[L]=nn"],M:["[MOV]=PP U FF","[M]=PP"],N:["E[NG]+=nn kk","[NG]R=nn kk","[NG]#=nn kk","[NGL]%=nn kk aa nn","[NG]=nn","[NK]=nn kk"," [NOW] =nn aa","[N]=nn"],O:["[OF] =aa FF","[OROUGH]=E O","#:[OR] =E","#:[ORS] =E SS","[OR]=aa RR"," [ONE]=FF aa nn","[OW]=O"," [OVER]=O FF E","[OV]=aa FF","[O]^%=O","[O]^EN=O","[O]^I#=O","[OL]D=O nn","[OUGHT]=aa DD","[OUGH]=aa FF"," [OU]=aa","H[OU]S#=aa","[OUS]=aa SS","[OUR]=aa RR","[OULD]=U DD","^[OU]^L=aa","[OUP]=U OO","[OU]=aa","[OY]=O","[OING]=O I nn","[OI]=O","[OOR]=aa RR","[OOK]=U kk","[OOD]=U DD","[OO]=U","[O]E=O","[O] =O","[OA]=O"," [ONLY]=O nn nn I"," [ONCE]=FF aa nn SS","[ON'T]=O nn DD","C[O]N=aa","[O]NG=aa"," ^:[O]N=aa","I[ON]=aa nn","#:[ON] =aa nn","#^[ON]=aa nn","[O]ST =O","[OF]^=aa FF","[OTHER]=aa TH E","[OSS] =aa SS","#^:[OM]=aa PP","[O]=aa"],P:["[PH]=FF","[PEOP]=PP I PP","[POW]=PP aa","[PUT] =PP U DD","[P]=PP"],Q:["[QUAR]=kk FF aa RR","[QU]=kk FF","[Q]=kk"],R:[" [RE]^#=RR I","[R]=RR"],S:["[SH]=SS","#[SION]=SS aa nn","[SOME]=SS aa PP","#[SUR]#=SS E","[SUR]#=SS E","#[SU]#=SS U","#[SSU]#=SS U","#[SED] =SS DD","#[S]#=SS","[SAID]=SS E DD","^[SION]=SS aa nn","[S]S=",".[S] =SS","#:.E[S] =SS","#^:##[S] =SS","#^:#[S] =SS","U[S] =SS"," :#[S] =SS"," [SCH]=SS kk","[S]C+=","#[SM]=SS PP","#[SN]'=SS aa nn","[S]=SS"],T:[" [THE] =TH aa","[TO] =DD U","[THAT] =TH aa DD"," [THIS] =TH I SS"," [THEY]=TH E"," [THERE]=TH E RR","[THER]=TH E","[THEIR]=TH E RR"," [THAN] =TH aa nn"," [THEM] =TH E PP","[THESE] =TH I SS"," [THEN]=TH E nn","[THROUGH]=TH RR U","[THOSE]=TH O SS","[THOUGH] =TH O"," [THUS]=TH aa SS","[TH]=TH","#:[TED] =DD I DD","S[TI]#N=CH","[TI]O=SS","[TI]A=SS","[TIEN]=SS aa nn","[TUR]#=CH E","[TU]A=CH U"," [TWO]=DD U","[T]=DD"],U:[" [UN]I=I U nn"," [UN]=aa nn"," [UPON]=aa PP aa nn","@[UR]#=U RR","[UR]#=I U RR","[UR]=E","[U]^ =aa","[U]^^=aa","[UY]=aa"," G[U]#=","G[U]%=","G[U]#=FF","#N[U]=I U","@[U]=I","[U]=I U"],V:["[VIEW]=FF I U","[V]=FF"],W:[" [WERE]=FF E","[WA]S=FF aa","[WA]T=FF aa","[WHERE]=FF E RR","[WHAT]=FF aa DD","[WHOL]=I O nn","[WHO]=I U","[WH]=FF","[WAR]=FF aa RR","[WOR]^=FF E","[WR]=RR","[W]=FF"],X:[" [X]=SS","[X]=kk SS"],Y:["[YOUNG]=I aa nn"," [YOU]=I U"," [YES]=I E SS"," [Y]=I","#^:[Y] =I","#^:[Y]I=I"," :[Y] =aa"," :[Y]#=aa"," :[Y]^+:#=I"," :[Y]^#=I","[Y]=I"],Z:["[Z]=SS"]};const t={"#":"[AEIOUY]+",".":"[BDVGJLMNRWZ]","%":"(?:ER|E|ES|ED|ING|ELY)","&":"(?:[SCGZXJ]|CH|SH)","@":"(?:[TSRDLZNJ]|TH|CH|SH)","^":"[BCDFGHJKLMNPQRSTVWXZ]","+":"[EIY]",":":"[BCDFGHJKLMNPQRSTVWXZ]*"," ":"\\b"};Object.keys(this.rules).forEach(e=>{this.rules[e]=this.rules[e].map(n=>{const i=n.indexOf("["),s=n.indexOf("]"),o=n.indexOf("="),r=n.substring(0,i),u=n.substring(i+1,s),a=n.substring(s+1,o),c=n.substring(o+1),l={regex:"",move:0,visemes:[]};let d="";d+=[...r].map(p=>t[p]||p).join("");const h=[...u];return h[0]=h[0].toLowerCase(),d+=h.join(""),l.move=h.length,d+=[...a].map(p=>t[p]||p).join(""),l.regex=new RegExp(d),c.length&&c.split(" ").forEach(p=>{l.visemes.push(p)}),l})}),this.visemeDurations={aa:.95,E:.9,I:.92,O:.96,U:.95,PP:1.08,SS:1.23,TH:1,DD:1.05,FF:1,kk:1.21,nn:.88,RR:.88,DD:1.05,sil:1},this.specialDurations={" ":1,",":3,"-":.5,"'":.5},this.digits=["oh","one","two","three","four","five","six","seven","eight","nine"],this.ones=["","one","two","three","four","five","six","seven","eight","nine"],this.tens=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"],this.teens=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],this.decades={20:"twenties",30:"thirties",40:"forties",50:"fifties",60:"sixties",70:"seventies",80:"eighties",90:"nineties"},this.ordinals={1:"first",2:"second",3:"third",4:"fourth",5:"fifth",6:"sixth",7:"seventh",8:"eighth",9:"ninth",10:"tenth",11:"eleventh",12:"twelfth",13:"thirteenth",14:"fourteenth",15:"fifteenth",16:"sixteenth",17:"seventeeth",18:"eighteenth",19:"nineteenth",20:"twentieth",30:"thirtieth",40:"fortieth",50:"fiftieth",60:"sixtieth",70:"seventieth",80:"eightieth",90:"ninetieth"},this.symbols={"%":"percent","€":"euros","&":"and","+":"plus",$:"dollars"},this.symbolsReg=/[%€&\+\$]/g}convert_digit_by_digit(t){t=String(t).split("");let e="";for(let n=0;n<t.length;n++)e+=this.digits[t[n]]+" ";return e=e.substring(0,e.length-1),e}convert_sets_of_two(t){let e=String(t).substring(0,2),n=String(t).substring(2,4),i=this.convert_tens(e);return i+=" "+this.convert_tens(n),i}convert_millions(t){return t>=1e6?this.convert_millions(Math.floor(t/1e6))+" million "+this.convert_thousands(t%1e6):this.convert_thousands(t)}convert_thousands(t){return t>=1e3?this.convert_hundreds(Math.floor(t/1e3))+" thousand "+this.convert_hundreds(t%1e3):this.convert_hundreds(t)}convert_hundreds(t){return t>99?this.ones[Math.floor(t/100)]+" hundred "+this.convert_tens(t%100):this.convert_tens(t)}convert_tens(t){return t<10?(Number(t)!=0&&t.toString().startsWith("0")?"oh ":"")+this.ones[Number(t)]:t>=10&&t<20?this.teens[t-10]:(this.tens[Math.floor(t/10)]+" "+this.ones[t%10]).trim()}convertNumberToWords(t,e=!1){const n=parseFloat(t);if(t=="0")return"zero";if(t<0)return" minus "+this.convertNumberToWords(Math.abs(t).toString(),e).trim();if(n&&!Number.isInteger(n)){const i=n.toString().split(".");return this.convertNumberToWords(i[0],e).trim()+" point "+this.convert_digit_by_digit(i[1]).trim()}else return t.toString().startsWith("0")?this.convert_digit_by_digit(t).trim():!e&&(t<1e3&&t>99&&t%100!==0||t>1e4&&t<1e6)?this.convert_digit_by_digit(t).trim():!e&&(t>1e3&&t<2e3||t>2009&&t<3e3)?t%100!=0?this.convert_sets_of_two(t).trim():this.convert_tens(t.toString().substring(0,2)).trim()+" hundred":this.convert_millions(t).trim()}convertDecade(t){const e=parseInt(t),n=!isNaN(e)&&t.length===2,i=!isNaN(e)&&t.length>2&&e>0&&e<=3e3,s=i&&e%1e3===0?Math.floor(e/1e3):null,o=i&&!s?Math.floor(e/100):null,r=n||i?Math.floor(e%100/10)*10:null;let u=[];return s?u.push(this.convertNumberToWords(s).trim(),"thousands"):(o&&u.push(this.convertNumberToWords(o).trim()),r?u.push(this.decades[r]||this.convertNumberToWords(r).trim()+"s"):o?u.push("hundreds"):u.push(t)),u.join(" ")}convertOrdinal(t){if(this.ordinals.hasOwnProperty(t))return this.ordinals[t];const e=Math.floor(t/100),n=Math.floor(t%100/10)*10,i=t%10;let s=[];return e&&(s.push(this.convertNumberToWords(e).trim()),n||i?s.push("hundred"):s.push("hundredth")),n&&(i?s.push(this.convertNumberToWords(n).trim()):s.push(this.ordinals[n])),i&&s.push(this.ordinals[i]),s.join(" ")}preProcessText(t){let e=t.replace('/[#_*":;]/g',"");return e=e.replace(this.symbolsReg,n=>" "+this.symbols[n]+" "),/\d/.test(e)&&(e=e.replace(/\b(\d{2,4})[''']?\s?[sS](?=\s|[.,!?;:]|$)/g,(n,i)=>{const s=this.convertDecade(i);return s===i?n:s}),e=e.replace(/\b(\d+)\s*(st|nd|rd|th)(?=\s|[.,!?;:]|$)/gi,(n,i)=>this.convertOrdinal(Number(i))),e=e.replace(/\b(\w*?)(\d+)([A-Za-z]+)\b/g,(n,i,s,o)=>{const r=this.convertNumberToWords(s);return`${i}${r} ${o}`}).replace(/\b([A-Za-z]+)(\d+)(\w*?)\b/g,(n,i,s,o)=>{const r=this.convertNumberToWords(s);return`${i} ${r}${o}`}),e=e.replace(/-?(?:\d{1,3}(?:,\d{3})+|\d+)(\.\d+)?/g,(n,i)=>{let s=n,o=!1;return/,/.test(s)&&(s=s.replace(/,/g,""),o=!0),i&&(o=!0),this.convertNumberToWords(s,o)})),e=e.replace(/(\D)\1\1+/g,"$1$1").replaceAll(" "," ").normalize("NFD").replace(/[\u0300-\u036f]/g,"").normalize("NFC").trim(),e}wordsToVisemes(t){let e={words:t.toUpperCase(),visemes:[],times:[],durations:[],i:0},n=0;const i=[...e.words];for(;e.i<i.length;){const s=i[e.i],o=this.rules[s];if(o)for(let r=0;r<o.length;r++){const u=o[r];if((e.words.substring(0,e.i)+s.toLowerCase()+e.words.substring(e.i+1)).match(u.regex)){u.visemes.forEach(l=>{if(e.visemes.length&&e.visemes[e.visemes.length-1]===l){const d=.7*(this.visemeDurations[l]||1);e.durations[e.durations.length-1]+=d,n+=d}else{const d=this.visemeDurations[l]||1;e.visemes.push(l),e.times.push(n),e.durations.push(d),n+=d}}),e.i+=u.move;break}}else e.i++,n+=this.specialDurations[s]||0}return e}}const ut=Object.freeze(Object.defineProperty({__proto__:null,LipsyncEn:ct},Symbol.toStringTag,{value:"Module"}));class ht{constructor(){this.rules={A:["[AH]=aa","[AU]=aa U","[AI]=aa I","[AE]=E","[A]H=aa","[A]U=aa U","[A]I=aa I"," [AN] =aa nn"," [AM] =aa PP","[ARR]=aa RR","[AR]=aa RR"," [ALS]=aa nn SS","[AL]=aa nn","[AUCH]=aa U kk","[ABER]=aa PP E RR","[A]=aa"],Ä:["[Ä]H=E","[ÄU]=O","[Ä]=E"],B:["[B]=PP"],C:["[CH]S=kk SS","[CH]=kk"," [CH]=kk","#[CH]=kk","[CK]=kk","[C]H=kk","[C]=kk"],D:[" [DAS] =DD aa SS"," [DEN] =DD E nn"," [DER] =DD E RR"," [DIE] =DD I"," [DU] =DD U"," [DURCH]=DD U RR kk","[D]=DD"],E:["[EI]=aa I","[EU]=O","[EH]=E"," [ER] =E RR"," [ES] =E SS"," [EIN] =aa I nn"," [EINE]=aa I nn aa","[ER]#=E","[ER]=E RR","[EN]#=aa nn","[E]=E"],F:["[F]=FF"],G:["[G]=kk"],H:[" [HAT] =I aa DD"," [HABEN]=I aa PP aa nn"," [HIER]=I I RR"," [HEUTE]=I O DD aa","[H]="],I:[" [ICH] =I kk"," [IHR] =I RR"," [IN] =I nn"," [IST] =I SS DD"," [IM] =I PP","[IE]=I","[IH]=I","[I]=I"],J:["[J]=I"],K:["[K]=kk"],L:["[L]=nn"],M:[" [MIT] =PP I DD"," [MAN] =PP aa nn"," [MEHR]=PP E RR"," [MICH]=PP I kk","[M]=PP"],N:[" [NICHT]=nn I kk DD"," [NUR] =nn U RR"," [NACH]=nn aa kk"," [NOCH]=nn aa kk","[NG]=nn kk","[N]=nn"],O:["[OO]=U","[OH]=O","[OU]=aa U"," [ODER]=O DD E RR"," [OHNE]=O nn aa","[Ö]=E","[O]=aa"],Ö:["[ÖH]=E","[Ö]=E"],P:["[PF]=FF FF","[PH]=FF","[P]=PP"],Q:["[QU]=kk FF","[Q]=kk"],R:["[R]=RR"],S:["[SCH]=SS","[SP]=SS PP","[ST]=SS DD","[SS]=SS","[S]=SS"],ß:["[ß]=SS"],T:["[TZ]=DD SS","[TH]=DD","[T]=DD"],U:[" [UND] =U nn DD"," [UM] =U PP"," [UNTER]=U nn DD E RR"," [UNS] =U nn SS","[UH]=U","[ÜH]=I U","[Ü]=I U","[U]=U"],Ü:["[ÜH]=I U","[Ü]=I U"],V:[" [VON] =FF aa nn"," [VOR] =FF aa RR"," [VIEL]=FF I nn","[V]=FF"],W:[" [WAS] =FF aa SS"," [WIR] =FF I RR"," [WIE] =FF I"," [WENN]=FF E nn"," [WILL]=FF I nn"," [WO] =FF aa"," [WIEDER]=FF I DD E RR","[W]=FF"],X:["[X]=kk SS"],Y:["[Y]=I"],Z:[" [ZU] =DD SS U"," [ZUM] =DD SS U PP"," [ZUR] =DD SS U RR"," [ZEIT]=DD SS aa I DD","[Z]=DD SS"]};const t={"#":"[AEIOUÄÖÜ]+",".":"[BDVGJLMNRWZ]","%":"(?:ER|E|ES|ED|ING|ELY|EN|TE|ST)","&":"(?:[SCGZXJ]|CH|SCH|TZ)","@":"(?:[TSRDLZNJ]|TH|CH|SCH)","^":"[BCDFGHJKLMNPQRSTVWXYZß]","+":"[EIY]",":":"[BCDFGHJKLMNPQRSTVWXYZß]*"," ":"\\b"};Object.keys(this.rules).forEach(e=>{this.rules[e]=this.rules[e].map(n=>{const i=n.indexOf("["),s=n.indexOf("]"),o=n.indexOf("="),r=n.substring(0,i),u=n.substring(i+1,s),a=n.substring(s+1,o),c=n.substring(o+1),l={regex:"",move:0,visemes:[]};let d="";d+=[...r].map(p=>t[p]||p).join("");const h=[...u];return h[0]=h[0].toLowerCase(),d+=h.join(""),l.move=h.length,d+=[...a].map(p=>t[p]||p).join(""),l.regex=new RegExp(d),c.length&&c.split(" ").forEach(p=>{l.visemes.push(p)}),l})}),this.visemeDurations={aa:1,E:.85,I:.9,O:1.05,U:1,PP:1.15,SS:1.2,TH:1,DD:1.1,FF:1.05,kk:1.25,nn:.85,RR:.9,sil:1},this.specialDurations={" ":1,",":3,"-":.5,"'":.5,".":4,"!":3,"?":3},this.digits=["null","eins","zwei","drei","vier","fünf","sechs","sieben","acht","neun"],this.ones=["","ein","zwei","drei","vier","fünf","sechs","sieben","acht","neun"],this.tens=["","","zwanzig","dreißig","vierzig","fünfzig","sechzig","siebzig","achtzig","neunzig"],this.teens=["zehn","elf","zwölf","dreizehn","vierzehn","fünfzehn","sechzehn","siebzehn","achtzehn","neunzehn"],this.symbols={"%":"prozent","€":"euro","&":"und","+":"plus",$:"dollar","=":"gleich","@":"at","#":"hashtag"},this.symbolsReg=/[%€&\+\$=@#]/g}convert_digit_by_digit(t){t=String(t).split("");let e="";for(let n=0;n<t.length;n++)e+=this.digits[t[n]]+" ";return e=e.substring(0,e.length-1),e}convert_millions(t){if(t>=1e6){const e=Math.floor(t/1e6),n=t%1e6;let i=this.convert_thousands(e);return i+=e===1?" million ":" millionen ",n>0&&(i+=this.convert_thousands(n)),i}else return this.convert_thousands(t)}convert_thousands(t){if(t>=1e3){const e=Math.floor(t/1e3),n=t%1e3;let i="";return e===1?i="eintausend":i=this.convert_hundreds(e)+"tausend",n>0&&(i+=this.convert_hundreds(n)),i}else return this.convert_hundreds(t)}convert_hundreds(t){if(t>99){const e=Math.floor(t/100),n=t%100;let i="";return e===1?i="einhundert":i=this.ones[e]+"hundert",n>0&&(i+=this.convert_tens(n)),i}else return this.convert_tens(t)}convert_tens(t){if(t<10)return this.ones[Number(t)]||"";if(t>=10&&t<20)return this.teens[t-10];{const e=Math.floor(t/10),n=t%10;return n===0?this.tens[e]:this.ones[n]+"und"+this.tens[e]}}convertNumberToWords(t){const e=String(t);return t=="0"?"null":e.startsWith("0")?this.convert_digit_by_digit(t):e.length===4&&(t<1e3||t>2100)?this.convert_digit_by_digit(t):this.convert_millions(Number(t))}preProcessText(t){return t.replace(/[#_*\":;]/g,"").replace(this.symbolsReg,e=>" "+this.symbols[e]+" ").replace(/(\d)\.(\d)/g,"$1 komma $2").replace(/(\d),(\d)/g,"$1 komma $2").replace(/\d+/g,this.convertNumberToWords.bind(this)).replace(/(\D)\1\1+/g,"$1$1").replace(/\s+/g," ").toLowerCase().trim()}wordsToVisemes(t){let e={words:t.toUpperCase(),visemes:[],times:[],durations:[],i:0},n=0;const i=[...e.words];for(;e.i<i.length;){const s=i[e.i],o=this.rules[s];if(o){let r=!1;for(let u=0;u<o.length;u++){const a=o[u];if((e.words.substring(0,e.i)+s.toLowerCase()+e.words.substring(e.i+1)).match(a.regex)){a.visemes.forEach(d=>{if(e.visemes.length&&e.visemes[e.visemes.length-1]===d){const h=.7*(this.visemeDurations[d]||1);e.durations[e.durations.length-1]+=h,n+=h}else{const h=this.visemeDurations[d]||1;e.visemes.push(d),e.times.push(n),e.durations.push(h),n+=h}}),e.i+=a.move,r=!0;break}}r||(e.i++,n+=this.specialDurations[s]||0)}else e.i++,n+=this.specialDurations[s]||0}return e}}const dt=Object.freeze(Object.defineProperty({__proto__:null,LipsyncDe:ht},Symbol.toStringTag,{value:"Module"}));class mt{constructor(){this.rules={A:["[AN]C=aa nn","[AN]G=aa nn","[AN]T=aa nn","[AN]D=aa nn","[AN] =aa nn","[AN]$=aa nn","[AM]P=aa nn","[AM]B=aa nn","[AM] =aa nn","[AM]$=aa nn","[AI]N=E nn","[AIM]=E nn","[AIN]=E nn","[AU]=O","[AUX]=O","[AUT]=O","[AI]=E","[AY]=E","[A]=aa"],À:["[À]=aa"],Â:["[Â]=aa"],B:[" [B] =PP","[BB]=PP","[B]=PP"],C:["[C]E=SS","[C]I=SS","[C]Y=SS","[C]È=SS","[C]É=SS","[C]Ê=SS","[CH]=SS","[C]A=kk","[C]O=kk","[C]U=kk","[C]L=kk","[C]R=kk","[CK]=kk","[C]=kk"],Ç:["[Ç]=SS"],D:["[D]=DD"],E:["[EN]C=aa nn","[EN]T=aa nn","[EN]D=aa nn","[EN] =aa nn","[EN]$=aa nn","[EM]P=aa nn","[EM]B=aa nn","[EM] =aa nn","[EM]$=aa nn","[EAU]=O","[EAU]X=O","[EU]=U","[EUX]=U","[EUR]=U RR","[EI]=E","[EIN]=E nn","[ER] =E","[ER]$=E","[EZ] =E","[EZ]$=E","[ED] =E","[ED]$=E"," [E] =","[E] =","[E]$=","[E]S =","[E]S$=","[E]NT =","[E]NT$=","[È]=E","[É]=E","[Ê]=E","[Ë]=E","[E]=E"],È:["[È]=E"],É:["[É]=E"],Ê:["[Ê]=E"],Ë:["[Ë]=E"],F:["[FF]=FF","[F]=FF","[PH]=FF"],G:["[G]E=SS","[G]I=SS","[G]Y=SS","[G]È=SS","[G]É=SS","[G]Ê=SS","[GN]=nn I","[GN]E=nn","[GN]A=nn aa","[GN]O=nn O","[GU]E=kk","[GU]I=kk","[GU]A=kk FF aa","[GU]O=kk FF O","[G]A=kk","[G]O=kk","[G]U=kk","[G]L=kk","[G]R=kk","[GG]=kk","[G]=kk"],H:["[H]="],I:["[IN]C=E nn","[IN]T=E nn","[IN]D=E nn","[IN] =E nn","[IN]$=E nn","[IM]P=E nn","[IM]B=E nn","[IM] =E nn","[IM]$=E nn","[IEN]=I E nn","[IER]=I E","[IEU]=I U","[IEZ]=I E","[ILL]E=I","[ILLE]=I","[ILL]=I","[Î]=I","[Ï]=I","[I]=I"],Î:["[Î]=I"],Ï:["[Ï]=I"],J:["[J]=SS"],K:["[K]=kk"],L:["[LL]E=","[LLE]=","[LL]A=I aa","[LL]O=I O","[LL]U=I U","[LL]I=I","[LL]=I","[L]=nn"],M:["[MM]=PP","[M]=PP"],N:["[NN]=nn","[N]=nn"],O:["[ON]C=O nn","[ON]T=O nn","[ON]D=O nn","[ON] =O nn","[ON]$=O nn","[OM]P=O nn","[OM]B=O nn","[OM] =O nn","[OM]$=O nn","[OI]N=FF E nn","[OI]G=FF aa","[OI]S=FF aa","[OI]T=FF aa","[OI]X=FF aa","[OI]=FF aa","[OU]=U","[OÙ]=U","[OÛ]=U","[OEU]=U","[OEUR]=U RR","[OUGH]=U FF","[OUGH]T=U","[Ô]=O","[O]=O"],Ô:["[Ô]=O"],Ù:["[Ù]=U"],Û:["[Û]=U"],P:["[PH]=FF","[PP]=PP","[P]=PP"],Q:["[QU]=kk","[Q]=kk"],R:["[RR]=RR","[R]=RR"],S:["#[S]#=SS"," [S]=SS","[SS]=SS","[S] =","[S]$=","[SC]E=SS","[SC]I=SS","[SC]Y=SS","[S]=SS"],T:["[TI]A=SS I aa","[TI]E=SS I E","[TI]O=SS I O","[TI]ON=SS I O nn","[TH]=DD","[TT]=DD","[T] =","[T]$=","[T]=DD"],U:["[UN]C=U nn","[UN]T=U nn","[UN]D=U nn","[UN] =U nn","[UN]$=U nn","[UM]=U nn","[UE]=I","[UEI]=I E","[UEIL]=I I","[UILL]=I","[Ù]=U","[Û]=U","[Ü]=I U","[U]=I U"],Ü:["[Ü]=I U"],V:["[V]=FF"],W:["[W]=FF"],X:["[X] =","[X]$=","#[X]#=kk SS"," [X]=kk SS","[X]=kk SS"],Y:["[Y]=I"," [Y]=I","[YE]=I E","[YA]=I aa","[YO]=I O","[YU]=I U"],Z:["[Z]=SS"]};const t={"#":"[AEIOUYÀÂÈÉÊËÎÏÔÙÛÜ]+",".":"[BDVGJLMNRWZ]","%":"(?:ER|E|ES|ÉS|ÈS|ÊS|ENT|MENT|TION|SION)","&":"(?:[SCGZXJ]|CH|SH|GN)","@":"(?:[TSRDLZNJ]|TH|CH|SH|GN)","^":"[BCDFGHJKLMNPQRSTVWXZÇ]+","+":"[EIYÈÉÊËÎÏ]",":":"[BCDFGHJKLMNPQRSTVWXZÇ]*"," ":"\\b",$:"$"};Object.keys(this.rules).forEach(e=>{this.rules[e]=this.rules[e].map(n=>{const i=n.indexOf("["),s=n.indexOf("]"),o=n.indexOf("="),r=n.substring(0,i),u=n.substring(i+1,s),a=n.substring(s+1,o),c=n.substring(o+1),l={regex:"",move:0,visemes:[]};let d="";d+=[...r].map(p=>t[p]||p).join("");const h=[...u];return h[0]=h[0].toLowerCase(),d+=h.join(""),l.move=h.length,d+=[...a].map(p=>t[p]||p).join(""),l.regex=new RegExp(d,"i"),c.length&&c.split(" ").forEach(p=>{p&&l.visemes.push(p)}),l})}),this.visemeDurations={aa:1,E:.95,I:.9,O:1.05,U:.95,PP:1.1,SS:1.25,TH:1,DD:1.05,FF:1,kk:1.2,nn:.88,RR:1.15,sil:1},this.specialDurations={" ":1,",":2.5,".":3.5,";":2.8,":":2.2,"!":3.2,"?":3.2,"-":.8,"'":.3,'"':.3,"(":1.5,")":1.5},this.digits=["zéro","un","deux","trois","quatre","cinq","six","sept","huit","neuf"],this.ones=["","un","deux","trois","quatre","cinq","six","sept","huit","neuf"],this.teens=["dix","onze","douze","treize","quatorze","quinze","seize","dix-sept","dix-huit","dix-neuf"],this.tens=["","dix","vingt","trente","quarante","cinquante","soixante","soixante-dix","quatre-vingts","quatre-vingt-dix"],this.symbols={"%":"pourcent","€":"euros","&":"et","+":"plus",$:"dollars","=":"égale","@":"arobase","#":"dièse","°":"degrés"},this.symbolsReg=/[%€&\+\$=@#°]/g}convert_digit_by_digit(t){t=String(t).split("");let e="";for(let n=0;n<t.length;n++)e+=this.digits[t[n]]+" ";return e=e.substring(0,e.length-1),e}convert_tens(t){if(t<10)return this.ones[t]||"";if(t>=10&&t<20)return this.teens[t-10];if(t>=70&&t<80){const e=t-60;return e===11?"soixante et onze":"soixante-"+this.teens[e-10]}else if(t>=90){const e=t-80;return e===11?"quatre-vingt-onze":"quatre-vingt-"+this.teens[e-10]}else{const e=Math.floor(t/10),n=t%10;return e===8&&n===0?"quatre-vingts":e===8?"quatre-vingt-"+this.ones[n]:(e===2||e===3||e===4||e===5||e===6)&&n===1?this.tens[e]+" et un":n===0?this.tens[e]:this.tens[e]+"-"+this.ones[n]}}convert_hundreds(t){if(t>=100){const e=Math.floor(t/100),n=t%100;let i="";return e===1?i="cent":(i=this.ones[e]+" cent",n===0&&(i+="s")),n>0&&(i+=" "+this.convert_tens(n)),i}else return this.convert_tens(t)}convert_thousands(t){if(t>=1e3){const e=Math.floor(t/1e3),n=t%1e3;let i="";return e===1?i="mille":i=this.convert_hundreds(e)+" mille",n>0&&(i+=" "+this.convert_hundreds(n)),i}else return this.convert_hundreds(t)}convert_millions(t){if(t>=1e6){const e=Math.floor(t/1e6),n=t%1e6;let i="";return e===1?i="un million":i=this.convert_hundreds(e)+" millions",n>0&&(i+=" "+this.convert_thousands(n)),i}else return this.convert_thousands(t)}convertNumberToWords(t){const e=String(t);return t==="0"||t===0?"zéro":e.startsWith("0")?this.convert_digit_by_digit(t):this.convert_millions(Number(t))}preProcessText(t){return t.replace(/[#_*\":;]/g,"").replace(this.symbolsReg,e=>" "+this.symbols[e]+" ").replace(/(\d)[,.](\d)/g,"$1 virgule $2").replace(/\d+/g,this.convertNumberToWords.bind(this)).replace(/(\D)\1\1+/g,"$1$1").replace(/\s+/g," ").replace(/'/g,"'").trim()}wordsToVisemes(t){let e={words:t.toUpperCase(),visemes:[],times:[],durations:[],i:0},n=0;const i=[...e.words];for(;e.i<i.length;){const s=i[e.i],o=this.rules[s];if(o){let r=!1;for(let u=0;u<o.length;u++){const a=o[u];if((e.words.substring(0,e.i)+s.toLowerCase()+e.words.substring(e.i+1)).match(a.regex)){a.visemes.forEach(d=>{if(e.visemes.length&&e.visemes[e.visemes.length-1]===d){const h=.7*(this.visemeDurations[d]||1);e.durations[e.durations.length-1]+=h,n+=h}else{const h=this.visemeDurations[d]||1;e.visemes.push(d),e.times.push(n),e.durations.push(h),n+=h}}),e.i+=a.move,r=!0;break}}r||(e.i++,n+=this.specialDurations[s]||0)}else e.i++,n+=this.specialDurations[s]||0}return e}}const pt=Object.freeze(Object.defineProperty({__proto__:null,LipsyncFr:mt},Symbol.toStringTag,{value:"Module"}));class gt{constructor(){this.visemes={a:"aa",e:"E",i:"I",o:"O",u:"U",y:"U",ä:"aa",ö:"O",å:"O",b:"PP",c:"SS",d:"DD",f:"FF",g:"kk",h:"kk",j:"I",k:"kk",l:"nn",m:"PP",n:"nn",p:"PP",q:"kk",r:"RR",s:"SS",t:"DD",v:"FF",w:"FF",x:"SS",z:"SS"},this.visemeDurations={aa:.95,E:.9,I:.92,O:.96,U:.95,PP:1.08,SS:1.23,DD:1.05,FF:1,kk:1.21,nn:.88,RR:.88,DD:1.05,sil:1},this.specialDurations={" ":1,",":3,"-":.5},this.numbers=["nolla","yksi","kaksi","kolme","neljä","viisi","kuusi","seitsemän","kahdeksan","yhdeksän","kymmenen","yksitoista","kaksitoista","kolmetoista","neljätoista","viisitoista","kuusitoista","seitsemäntoista","kahdeksantoista","yhdeksäntoista"],this.symbols={"%":"prosenttia","€":"euroa","&":"ja","+":"plus",$:"dollaria"},this.symbolsReg=/[%€&\+\$]/g}numberToFinnishWords(t){const e=[];let n=parseFloat(t);if(n===void 0)return t;let i=(s,o,r,u,a)=>{if(s<o)return s;const c=Math.floor(s/o);return e.push(r+(c===1?u:this.numberToFinnishWords(c.toString())+a)),s-c*o};if(n<0&&(e.push("miinus "),n=Math.abs(n)),n=i(n,1e9," ","miljardi"," miljardia"),n=i(n,1e6," ","miljoona"," miljoonaa"),n=i(n,1e3,"","tuhat","tuhatta"),n=i(n,100," ","sata","sataa"),n>20&&(n=i(n,10,"","","kymmentä")),n>=1){let s=Math.floor(n);e.push(this.numbers[s]),n-=s}if(n>=0&&Math.abs(parseFloat(t))<1&&e.push("nolla"),n>0){let s=t.split(".");if(s.length>1){e.push(" pilkku");let o=[...s[s.length-1]];for(let r=0;r<o.length;r++)e.push(" "+this.numbers[o[r]])}}return e.join("").trim()}preProcessText(t){return t.replace(/[#_*\'\":;]/g,"").replace(this.symbolsReg,e=>" "+this.symbols[e]+" ").replace(/(\d)\,(\d)/g,"$1 pilkku $2").replace(/\d+/g,this.numberToFinnishWords.bind(this)).replaceAll(" "," ").normalize("NFD").replace(/[\u0300-\u0307\u0309\u030b-\u036f]/g,"").normalize("NFC").trim()}wordsToVisemes(t){let e={words:t,visemes:[],times:[],durations:[]},n=0;const i=[...t];for(let s=0;s<i.length;s++){const o=this.visemes[i[s].toLowerCase()];if(o)if(e.visemes.length&&e.visemes[e.visemes.length-1]===o){const r=.7*(this.visemeDurations[o]||1);e.durations[e.durations.length-1]+=r,n+=r}else{const r=this.visemeDurations[o]||1;e.visemes.push(o),e.times.push(n),e.durations.push(r),n+=r}else n+=this.specialDurations[i[s]]||0}return e}}const ft=Object.freeze(Object.defineProperty({__proto__:null,LipsyncFi:gt},Symbol.toStringTag,{value:"Module"}));class yt{constructor(){this.visemes={a:"aa",ą:"O",e:"E",ę:"E",ė:"E",i:"I",į:"I",o:"O",u:"U",ū:"U",ų:"U",y:"I",b:"PP",c:"SS",č:"SS",d:"DD",f:"FF",g:"kk",h:"kk",j:"I",k:"kk",l:"nn",m:"PP",n:"nn",p:"PP",q:"kk",r:"RR",s:"SS",š:"CH",t:"DD",v:"FF",w:"FF",x:"SS",z:"SS",ž:"SS"},this.durations={a:.95,ą:1.5,e:.9,ę:1.5,ė:1.5,i:.92,į:1.5,o:.96,u:.95,ū:1.5,ų:1.5,y:1.5,b:1.08,c:1.23,d:1.05,f:1,g:1.21,h:1.21,j:.92,k:1.21,l:.88,m:1.08,n:.88,p:1.08,q:1.21,r:.88,s:1.23,š:1.23,t:1.05,v:1,w:1,x:1.23,z:1.23,ž:1.23},this.pauses={" ":1,",":3,"-":.5},this.numbers=["nulis","vienas","du","trys","keturi","penki","šeši","septyni","aštuoni","devyni","dešimt","vienuolika","dvylika","trylika","keturiolika","penkiolika","šešiolika","septyniolika","aštuoniolika","devyniolika"],this.tens=[this.numbers[0],this.numbers[10],"dvidešimt","trisdešimt","keturiasdešimt","penkiasdešimt","šešiasdešimt","septyniasdešimt","aštuoniasdešimt","devyniasdešimt"]}numberToLithuanianWords(t){const e=[];let n=parseFloat(t);if(n===void 0)return t;let i=(s,o,r,u,a)=>{if(s<o)return s;const c=Math.floor(s/o);return c===1?e.push(this.numbers[1]):e.push(this.numberToLithuanianWords(c.toString())),c%10===1?e.push(r):c%10===0||c%100>10&&c%100<20?e.push(a):e.push(u),s-c*o};n<0&&(e.push("minus"),n=Math.abs(n)),n=i(n,1e9,"milijardas","milijardai","milijardų"),n=i(n,1e6,"milijonas","milijonai","milijonų"),n=i(n,1e3,"tūkstantis","tūkstančiai","tūkstančių"),n=i(n,100,"šimtas","šimtai","šimtų");for(let s=this.tens.length-1;s>=1;s--)if(n>=10*s){e.push(this.tens[s]),n=n-10*s;break}if(n>=1){let s=Math.floor(n);e.push(this.numbers[s]),n-=s}if(n>=0&&Math.abs(parseFloat(t))<1&&e.push(this.numbers[0]),n>0){let s=t.split(".");if(s.length>1){e.push("kablelis");let o=[...s[s.length-1]];for(let r=0;r<o.length;r++)e.push(this.numbers[o[r]])}}return e.join(" ").trim()}preProcessText(t){return t.replace(`/[#_*'":;]/g`,"").replaceAll("0 %","0 procentų ").replaceAll("1 %","1 procentas ").replaceAll("%"," procentai ").replaceAll("0 €","0 eurų ").replaceAll("1 €","1 euras ").replaceAll("€"," eurai ").replaceAll("0 $","0 dolerių ").replaceAll("1 $","1 doleris ").replaceAll("$"," doleriai ").replaceAll("&"," ir ").replaceAll("+"," pliusas ").replace(/(\d)\,(\d)/g,"$1 kablelis $2").replace(/\d+/g,this.numberToLithuanianWords.bind(this)).replace(/(\D)\1\1+/g,"$1$1").replaceAll(" "," ").normalize("NFD").replace(/[\u0300-\u0303\u0305\u0306\u0308-\u0327\u0329-\u036f]/g,"").normalize("NFC").trim()}wordsToVisemes(t){let e={words:t,visemes:[],times:[],durations:[]},n=0;const i=[...t];for(let s=0;s<i.length;s++){const o=i[s].toLowerCase(),r=this.visemes[o];if(r)if(e.visemes.length&&e.visemes[e.visemes.length-1]===r){const u=.7*(this.durations[o]||1);e.durations[e.durations.length-1]+=u,n+=u}else{const u=this.durations[o]||1;e.visemes.push(r),e.times.push(n),e.durations.push(u),n+=u}else n+=this.pauses[i[s]]||0}return e}}const xt=Object.freeze(Object.defineProperty({__proto__:null,LipsyncLt:yt},Symbol.toStringTag,{value:"Module"})),bt=new URL("data:text/javascript;base64,Y2xhc3MgUGxheWJhY2tXb3JrbGV0IGV4dGVuZHMgQXVkaW9Xb3JrbGV0UHJvY2Vzc29yIHsKICBzdGF0aWMgRlNNID0gewogICAgSURMRTogMCwKICAgIFBMQVlJTkc6IDEsCiAgfTsKCiAgY29uc3RydWN0b3Iob3B0aW9ucykgewogICAgc3VwZXIoKTsKICAgIHRoaXMucG9ydC5vbm1lc3NhZ2UgPSB0aGlzLmhhbmRsZU1lc3NhZ2UuYmluZCh0aGlzKTsKCiAgICB0aGlzLl9zYW1wbGVSYXRlID0gb3B0aW9ucz8ucHJvY2Vzc29yT3B0aW9ucz8uc2FtcGxlUmF0ZSB8fCBzYW1wbGVSYXRlOwogICAgdGhpcy5fc2NhbGUgPSAxIC8gMzI3Njg7IC8vIFBDTTE2IC0+IGZsb2F0CgogICAgLy8gU2lsZW5jZSBkZXRlY3Rpb24gdGhyZXNob2xkICgxIHNlY29uZCkgYXMgYSBmYWxsYmFjayBzYWZldHkgbmV0CiAgICBjb25zdCBzaWxlbmNlRHVyYXRpb25TZWNvbmRzID0gMS4wOwogICAgdGhpcy5fc2lsZW5jZVRocmVzaG9sZEJsb2NrcyA9IE1hdGguY2VpbCgodGhpcy5fc2FtcGxlUmF0ZSAqIHNpbGVuY2VEdXJhdGlvblNlY29uZHMpIC8gMTI4KTsKCiAgICAvLyBNZXRyaWNzIGNvbmZpZ3VyYXRpb24gdmlhIG9wdGlvbnMKICAgIGNvbnN0IG1ldHJpY3NDZmcgPSBvcHRpb25zPy5wcm9jZXNzb3JPcHRpb25zPy5tZXRyaWNzIHx8IHt9OwogICAgdGhpcy5fbWV0cmljc0VuYWJsZWQgPSBtZXRyaWNzQ2ZnLmVuYWJsZWQgIT09IGZhbHNlOwogICAgY29uc3QgaW50ZXJ2YWxIeiA9ICh0eXBlb2YgbWV0cmljc0NmZy5pbnRlcnZhbEh6ID09PSAibnVtYmVyIiAmJiBtZXRyaWNzQ2ZnLmludGVydmFsSHogPiAwKQogICAgICA/IG1ldHJpY3NDZmcuaW50ZXJ2YWxIeiA6IDI7CiAgICAvLyBNZXRyaWNzIHN0YXRlIChsb3ctb3ZlcmhlYWQpCiAgICB0aGlzLl9mcmFtZXNQcm9jZXNzZWQgPSAwOwogICAgdGhpcy5fdW5kZXJydW5CbG9ja3MgPSAwOwogICAgdGhpcy5fbWF4UXVldWVTYW1wbGVzID0gMDsKICAgIHRoaXMuX2xhc3RNZXRyaWNzU2VudEF0RnJhbWUgPSAwOwogICAgLy8gQ29udmVydCB0byBmcmFtZXMgYmV0d2VlbiByZXBvcnRzCiAgICB0aGlzLl9tZXRyaWNzSW50ZXJ2YWxGcmFtZXMgPSBNYXRoLm1heCgxMjgsIE1hdGgucm91bmQodGhpcy5fc2FtcGxlUmF0ZSAvIGludGVydmFsSHopKTsKCiAgICB0aGlzLnJlc2V0KCk7CiAgfQoKICAvKioKICAgKiBSZXNldHMgdGhlIHdvcmtsZXQgdG8gaXRzIGluaXRpYWwgSURMRSBzdGF0ZS4KICAgKi8KICByZXNldCgpIHsKICAgIHRoaXMuX2J1ZmZlclF1ZXVlID0gW107CiAgICB0aGlzLl9jdXJyZW50Q2h1bmsgPSBudWxsOwogICAgdGhpcy5fY3VycmVudENodW5rT2Zmc2V0ID0gMDsKICAgIHRoaXMuX3N0YXRlID0gUGxheWJhY2tXb3JrbGV0LkZTTS5JRExFOwoKICAgIHRoaXMuX25vTW9yZURhdGFSZWNlaXZlZCA9IGZhbHNlOwogICAgdGhpcy5fc2lsZW5jZUZyYW1lc0NvdW50ID0gMDsKICAgIHRoaXMuX2hhc1NlbnRFbmRlZCA9IGZhbHNlOwogICAgLy8gUmVzZXQgbWF4IHF1ZXVlIHRyYWNrZXIgb25seSB3aGVuIGdvaW5nIGlkbGUKICAgIHRoaXMuX21heFF1ZXVlU2FtcGxlcyA9IDA7CiAgfQoKICBoYW5kbGVNZXNzYWdlKGV2ZW50KSB7CiAgICBjb25zdCB7IHR5cGUsIGRhdGEgfSA9IGV2ZW50LmRhdGE7CgogICAgLy8gSU5URVJSVVBUOiBUaGUgbWFpbiB0aHJlYWQgd2FudHMgdG8gc3RvcCBpbW1lZGlhdGVseS4KICAgIGlmICh0eXBlID09PSAic3RvcCIpIHsKICAgICAgdGhpcy5yZXNldCgpOwogICAgICAvLyBTZW5kIGZpbmFsIG1ldHJpY3Mgc2hvd2luZyBjbGVhcmVkIHN0YXRlCiAgICAgIGlmICh0aGlzLl9tZXRyaWNzRW5hYmxlZCkgewogICAgICAgIHRyeSB7CiAgICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UoewogICAgICAgICAgICB0eXBlOiAibWV0cmljcyIsCiAgICAgICAgICAgIGRhdGE6IHsKICAgICAgICAgICAgICBzdGF0ZTogUGxheWJhY2tXb3JrbGV0LkZTTS5JRExFLAogICAgICAgICAgICAgIHF1ZXVlZFNhbXBsZXM6IDAsCiAgICAgICAgICAgICAgcXVldWVkTXM6IDAsCiAgICAgICAgICAgICAgbWF4UXVldWVkTXM6IE1hdGgucm91bmQoKHRoaXMuX21heFF1ZXVlU2FtcGxlcyAvIHRoaXMuX3NhbXBsZVJhdGUpICogMTAwMCksCiAgICAgICAgICAgICAgdW5kZXJydW5CbG9ja3M6IHRoaXMuX3VuZGVycnVuQmxvY2tzLAogICAgICAgICAgICAgIGZyYW1lc1Byb2Nlc3NlZDogdGhpcy5fZnJhbWVzUHJvY2Vzc2VkCiAgICAgICAgICAgIH0KICAgICAgICAgIH0pOwogICAgICAgIH0gY2F0Y2ggKF8pIHsgfQogICAgICB9CiAgICAgIHJldHVybjsKICAgIH0KCiAgICAvLyBNYWluIHRocmVhZCBoYXMgc2lnbmFsZWQgdGhhdCBubyBtb3JlIGF1ZGlvIGNodW5rcyB3aWxsIGJlIHNlbnQgZm9yIHRoaXMgdXR0ZXJhbmNlLgogICAgaWYgKHR5cGUgPT09ICJuby1tb3JlLWRhdGEiKSB7CiAgICAgIHRoaXMuX25vTW9yZURhdGFSZWNlaXZlZCA9IHRydWU7CiAgICAgIHJldHVybjsKICAgIH0KCiAgICAvLyBVcGRhdGUgbWV0cmljcyBjb25maWd1cmF0aW9uIGF0IHJ1bnRpbWUKICAgIGlmICh0eXBlID09PSAiY29uZmlnLW1ldHJpY3MiICYmIGRhdGEgJiYgdHlwZW9mIGRhdGEgPT09ICJvYmplY3QiKSB7CiAgICAgIGlmICgiZW5hYmxlZCIgaW4gZGF0YSkgdGhpcy5fbWV0cmljc0VuYWJsZWQgPSAhIWRhdGEuZW5hYmxlZDsKICAgICAgaWYgKHR5cGVvZiBkYXRhLmludGVydmFsSHogPT09ICJudW1iZXIiICYmIGRhdGEuaW50ZXJ2YWxIeiA+IDApIHsKICAgICAgICBjb25zdCBpbnRlcnZhbEh6ID0gZGF0YS5pbnRlcnZhbEh6OwogICAgICAgIHRoaXMuX21ldHJpY3NJbnRlcnZhbEZyYW1lcyA9IE1hdGgubWF4KDEyOCwgTWF0aC5yb3VuZCh0aGlzLl9zYW1wbGVSYXRlIC8gaW50ZXJ2YWxIeikpOwogICAgICB9CiAgICAgIC8vIFJlc2V0IHBhY2luZyBzbyB0aGUgbmV4dCByZXBvcnQgYWxpZ25zIHdpdGggbmV3IGludGVydmFsCiAgICAgIHRoaXMuX2xhc3RNZXRyaWNzU2VudEF0RnJhbWUgPSB0aGlzLl9mcmFtZXNQcm9jZXNzZWQ7CiAgICAgIHJldHVybjsKICAgIH0KCiAgICAvLyBOZXcgYXVkaW8gZGF0YSBoYXMgYXJyaXZlZC4KICAgIGlmICh0eXBlID09PSAiYXVkaW9EYXRhIiAmJiBkYXRhIGluc3RhbmNlb2YgQXJyYXlCdWZmZXIpIHsKICAgICAgdGhpcy5fbm9Nb3JlRGF0YVJlY2VpdmVkID0gZmFsc2U7CiAgICAgIC8vIElmIHdlIHdlcmUgaWRsZSwgdGhpcyBuZXcgZGF0YSBraWNrcyBvZmYgdGhlIHBsYXliYWNrLgogICAgICBpZiAodGhpcy5fc3RhdGUgPT09IFBsYXliYWNrV29ya2xldC5GU00uSURMRSkgewogICAgICAgIHRoaXMuX3N0YXRlID0gUGxheWJhY2tXb3JrbGV0LkZTTS5QTEFZSU5HOwogICAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZSh7IHR5cGU6ICJwbGF5YmFjay1zdGFydGVkIiB9KTsKICAgICAgfQoKICAgICAgLy8gV2Ugb25seSBxdWV1ZSBkYXRhIGlmIHdlIGFyZSBpbiB0aGUgUExBWUlORyBzdGF0ZS4gVGhpcyBwcmV2ZW50cwogICAgICAvLyBkYXRhIGZyb20gYSBwcmV2aW91cywgaW50ZXJydXB0ZWQgc3RyZWFtIGZyb20gbGluZ2VyaW5nLgogICAgICBpZiAodGhpcy5fc3RhdGUgPT09IFBsYXliYWNrV29ya2xldC5GU00uUExBWUlORykgewogICAgICAgIC8vIFN0b3JlIGFzIEludDE2QXJyYXkgdmlldyB0byBhdm9pZCBjb25zdHJ1Y3RpbmcgaXQgaW4gcHJvY2VzcygpCiAgICAgICAgdGhpcy5fYnVmZmVyUXVldWUucHVzaChuZXcgSW50MTZBcnJheShkYXRhKSk7CiAgICAgICAgdGhpcy5fc2lsZW5jZUZyYW1lc0NvdW50ID0gMDsgLy8gUmVzZXQgc2lsZW5jZSBjb3VudGVyIG9uIG5ldyBkYXRhCiAgICAgIH0KICAgIH0KICB9CgogIHByb2Nlc3MoaW5wdXRzLCBvdXRwdXRzLCBwYXJhbWV0ZXJzKSB7CiAgICBjb25zdCBvdXRwdXRDaGFubmVsID0gb3V0cHV0c1swXT8uWzBdOwogICAgaWYgKCFvdXRwdXRDaGFubmVsKSB7CiAgICAgIHJldHVybiB0cnVlOyAvLyBLZWVwIGFsaXZlIGV2ZW4gaWYgb3V0cHV0IGlzIHRlbXBvcmFyaWx5IGRpc2Nvbm5lY3RlZAogICAgfQoKICAgIC8vIElmIHdlIGFyZSBub3QgcGxheWluZywganVzdCBvdXRwdXQgc2lsZW5jZSBhbmQgd2FpdC4KICAgIGlmICh0aGlzLl9zdGF0ZSAhPT0gUGxheWJhY2tXb3JrbGV0LkZTTS5QTEFZSU5HKSB7CiAgICAgIG91dHB1dENoYW5uZWwuZmlsbCgwKTsKICAgICAgcmV0dXJuIHRydWU7IC8vIEFsd2F5cyByZXR1cm4gdHJ1ZSB0byBrZWVwIHRoZSBwcm9jZXNzb3IgYWxpdmUKICAgIH0KCiAgICAvLyBDb3JlIFBMQVlJTkcgTG9naWMKICAgIGNvbnN0IGJsb2NrU2l6ZSA9IG91dHB1dENoYW5uZWwubGVuZ3RoOwogICAgbGV0IHNhbXBsZXNDb3BpZWQgPSAwOwoKICAgIHdoaWxlIChzYW1wbGVzQ29waWVkIDwgYmxvY2tTaXplKSB7CiAgICAgIGlmICghdGhpcy5fY3VycmVudENodW5rIHx8IHRoaXMuX2N1cnJlbnRDaHVua09mZnNldCA+PSB0aGlzLl9jdXJyZW50Q2h1bmsubGVuZ3RoKSB7CiAgICAgICAgaWYgKHRoaXMuX2J1ZmZlclF1ZXVlLmxlbmd0aCA+IDApIHsKICAgICAgICAgIHRoaXMuX2N1cnJlbnRDaHVuayA9IHRoaXMuX2J1ZmZlclF1ZXVlLnNoaWZ0KCk7CiAgICAgICAgICB0aGlzLl9jdXJyZW50Q2h1bmtPZmZzZXQgPSAwOwogICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAvLyBCdWZmZXIgaXMgZW1wdHkuIENoZWNrIGZvciBlbmQgY29uZGl0aW9ucy4KICAgICAgICAgIGNvbnN0IGlzVGltZWRPdXQgPSB0aGlzLl9zaWxlbmNlRnJhbWVzQ291bnQgPiB0aGlzLl9zaWxlbmNlVGhyZXNob2xkQmxvY2tzOwoKICAgICAgICAgIGlmICh0aGlzLl9ub01vcmVEYXRhUmVjZWl2ZWQgfHwgaXNUaW1lZE91dCkgewogICAgICAgICAgICAvLyBFTkQgT0YgUExBWUJBQ0s6IEVpdGhlciBleHBsaWNpdGx5IHNpZ25hbGVkIG9yIHRpbWVkIG91dC4KICAgICAgICAgICAgaWYgKCF0aGlzLl9oYXNTZW50RW5kZWQpIHsKICAgICAgICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UoeyB0eXBlOiAicGxheWJhY2stZW5kZWQiIH0pOwogICAgICAgICAgICAgIHRoaXMuX2hhc1NlbnRFbmRlZCA9IHRydWU7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgLy8gU2VuZCBmaW5hbCBtZXRyaWNzIHNob3dpbmcgY2xlYXJlZCBzdGF0ZQogICAgICAgICAgICBpZiAodGhpcy5fbWV0cmljc0VuYWJsZWQpIHsKICAgICAgICAgICAgICB0cnkgewogICAgICAgICAgICAgICAgdGhpcy5wb3J0LnBvc3RNZXNzYWdlKHsKICAgICAgICAgICAgICAgICAgdHlwZTogIm1ldHJpY3MiLAogICAgICAgICAgICAgICAgICBkYXRhOiB7CiAgICAgICAgICAgICAgICAgICAgc3RhdGU6IFBsYXliYWNrV29ya2xldC5GU00uSURMRSwKICAgICAgICAgICAgICAgICAgICBxdWV1ZWRTYW1wbGVzOiAwLAogICAgICAgICAgICAgICAgICAgIHF1ZXVlZE1zOiAwLAogICAgICAgICAgICAgICAgICAgIG1heFF1ZXVlZE1zOiBNYXRoLnJvdW5kKCh0aGlzLl9tYXhRdWV1ZVNhbXBsZXMgLyB0aGlzLl9zYW1wbGVSYXRlKSAqIDEwMDApLAogICAgICAgICAgICAgICAgICAgIHVuZGVycnVuQmxvY2tzOiB0aGlzLl91bmRlcnJ1bkJsb2NrcywKICAgICAgICAgICAgICAgICAgICBmcmFtZXNQcm9jZXNzZWQ6IHRoaXMuX2ZyYW1lc1Byb2Nlc3NlZAogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICB9KTsKICAgICAgICAgICAgICB9IGNhdGNoIChfKSB7IH0KICAgICAgICAgICAgfQogICAgICAgICAgICB0aGlzLnJlc2V0KCk7IC8vIFJlc2V0IHRvIElETEUgc3RhdGUgZm9yIHJldXNlCiAgICAgICAgICAgIGJyZWFrOyAvLyBFeGl0IHdoaWxlIGxvb3AKICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgIC8vIEJVRkZFUiBVTkRFUlJVTiAoTEFHKTogUGxheSBzaWxlbmNlIGFuZCB3YWl0IGZvciBtb3JlIGRhdGEuCiAgICAgICAgICAgIHRoaXMuX3NpbGVuY2VGcmFtZXNDb3VudCsrOwogICAgICAgICAgICBpZiAodGhpcy5fbWV0cmljc0VuYWJsZWQpIHRoaXMuX3VuZGVycnVuQmxvY2tzKys7CiAgICAgICAgICAgIGJyZWFrOyAvLyBFeGl0IHdoaWxlIGxvb3AKICAgICAgICAgIH0KICAgICAgICB9CiAgICAgIH0KCiAgICAgIC8vIElmIHdlIGhhdmUgYSBjaHVuayAoY291bGQgYmUgYSBuZXcgb25lIGZyb20gdGhlIGxvZ2ljIGFib3ZlKSwgcHJvY2VzcyBpdC4KICAgICAgaWYgKHRoaXMuX2N1cnJlbnRDaHVuaykgewogICAgICAgIGNvbnN0IHNhbXBsZXNUb0NvcHkgPSBNYXRoLm1pbigKICAgICAgICAgIGJsb2NrU2l6ZSAtIHNhbXBsZXNDb3BpZWQsCiAgICAgICAgICB0aGlzLl9jdXJyZW50Q2h1bmsubGVuZ3RoIC0gdGhpcy5fY3VycmVudENodW5rT2Zmc2V0CiAgICAgICAgKTsKICAgICAgICAvLyBEaXJlY3RseSB3cml0ZSB0byBvdXRwdXRDaGFubmVsIHRvIGF2b2lkIGV4dHJhIGNvcHkKICAgICAgICBjb25zdCBzcmMgPSB0aGlzLl9jdXJyZW50Q2h1bms7CiAgICAgICAgY29uc3QgYmFzZVNyYyA9IHRoaXMuX2N1cnJlbnRDaHVua09mZnNldDsKICAgICAgICBjb25zdCBiYXNlRHN0ID0gc2FtcGxlc0NvcGllZDsKICAgICAgICBjb25zdCBzY2FsZSA9IHRoaXMuX3NjYWxlOwogICAgICAgIGZvciAobGV0IGkgPSAwOyBpIDwgc2FtcGxlc1RvQ29weTsgaSsrKSB7CiAgICAgICAgICBvdXRwdXRDaGFubmVsW2Jhc2VEc3QgKyBpXSA9IHNyY1tiYXNlU3JjICsgaV0gKiBzY2FsZTsKICAgICAgICB9CgogICAgICAgIHRoaXMuX2N1cnJlbnRDaHVua09mZnNldCArPSBzYW1wbGVzVG9Db3B5OwogICAgICAgIHNhbXBsZXNDb3BpZWQgKz0gc2FtcGxlc1RvQ29weTsKICAgICAgfQogICAgfQoKICAgIC8vIFplcm8tZmlsbCB0aGUgcmVtYWluZGVyLCBpZiBhbnksIG9uY2UgcGVyIGJsb2NrCiAgICBpZiAoc2FtcGxlc0NvcGllZCA8IGJsb2NrU2l6ZSkgewogICAgICBvdXRwdXRDaGFubmVsLmZpbGwoMCwgc2FtcGxlc0NvcGllZCk7CiAgICB9CgogICAgLy8gVXBkYXRlIG1ldHJpY3MgKG9wdGlvbmFsKQogICAgaWYgKHRoaXMuX21ldHJpY3NFbmFibGVkKSB7CiAgICAgIHRoaXMuX2ZyYW1lc1Byb2Nlc3NlZCArPSBibG9ja1NpemU7CgogICAgICAvLyBUcmFjayBxdWV1ZSBkZXB0aCBpbiBzYW1wbGVzIChhcHByb3hpbWF0ZSkKICAgICAgbGV0IHF1ZXVlZFNhbXBsZXMgPSAwOwogICAgICBpZiAodGhpcy5fY3VycmVudENodW5rKSBxdWV1ZWRTYW1wbGVzICs9IE1hdGgubWF4KDAsIHRoaXMuX2N1cnJlbnRDaHVuay5sZW5ndGggLSB0aGlzLl9jdXJyZW50Q2h1bmtPZmZzZXQpOwogICAgICBmb3IgKGxldCBpID0gMDsgaSA8IHRoaXMuX2J1ZmZlclF1ZXVlLmxlbmd0aDsgaSsrKSBxdWV1ZWRTYW1wbGVzICs9IHRoaXMuX2J1ZmZlclF1ZXVlW2ldLmxlbmd0aDsKICAgICAgaWYgKHF1ZXVlZFNhbXBsZXMgPiB0aGlzLl9tYXhRdWV1ZVNhbXBsZXMpIHRoaXMuX21heFF1ZXVlU2FtcGxlcyA9IHF1ZXVlZFNhbXBsZXM7CgogICAgICAvLyBQZXJpb2RpY2FsbHkgc2VuZCBtZXRyaWNzIHRvIG1haW4gdGhyZWFkCiAgICAgIGlmICh0aGlzLl9mcmFtZXNQcm9jZXNzZWQgLSB0aGlzLl9sYXN0TWV0cmljc1NlbnRBdEZyYW1lID49IHRoaXMuX21ldHJpY3NJbnRlcnZhbEZyYW1lcykgewogICAgICAgIHRoaXMuX2xhc3RNZXRyaWNzU2VudEF0RnJhbWUgPSB0aGlzLl9mcmFtZXNQcm9jZXNzZWQ7CiAgICAgICAgdHJ5IHsKICAgICAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZSh7CiAgICAgICAgICAgIHR5cGU6ICJtZXRyaWNzIiwKICAgICAgICAgICAgZGF0YTogewogICAgICAgICAgICAgIHN0YXRlOiB0aGlzLl9zdGF0ZSwKICAgICAgICAgICAgICBxdWV1ZWRTYW1wbGVzLAogICAgICAgICAgICAgIHF1ZXVlZE1zOiBNYXRoLnJvdW5kKChxdWV1ZWRTYW1wbGVzIC8gdGhpcy5fc2FtcGxlUmF0ZSkgKiAxMDAwKSwKICAgICAgICAgICAgICBtYXhRdWV1ZWRNczogTWF0aC5yb3VuZCgodGhpcy5fbWF4UXVldWVTYW1wbGVzIC8gdGhpcy5fc2FtcGxlUmF0ZSkgKiAxMDAwKSwKICAgICAgICAgICAgICB1bmRlcnJ1bkJsb2NrczogdGhpcy5fdW5kZXJydW5CbG9ja3MsCiAgICAgICAgICAgICAgZnJhbWVzUHJvY2Vzc2VkOiB0aGlzLl9mcmFtZXNQcm9jZXNzZWQKICAgICAgICAgICAgfQogICAgICAgICAgfSk7CiAgICAgICAgfSBjYXRjaCAoXykgeyB9CiAgICAgICAgLy8gRG9uJ3QgcmVzZXQgbWF4IHRyYWNrZXIgLSBrZWVwIHNlc3Npb24gcGVhayB1bnRpbCBpZGxlCiAgICAgIH0KICAgIH0KCiAgICAvLyBBTFdBWVMgcmV0dXJuIHRydWUgdG8ga2VlcCB0aGUgcHJvY2Vzc29yIGFsaXZlIGZvciByZXVzZS4KICAgIHJldHVybiB0cnVlOwogIH0KfQoKcmVnaXN0ZXJQcm9jZXNzb3IoInBsYXliYWNrLXdvcmtsZXQiLCBQbGF5YmFja1dvcmtsZXQpOwo=",typeof document>"u"?require("url").pathToFileURL(__filename).href:De&&De.tagName.toUpperCase()==="SCRIPT"&&De.src||new URL("index.cjs",document.baseURI).href),Xe={en:ut,de:dt,fr:pt,fi:ft,lt:xt},ie=new x.Quaternion,K=new x.Euler,Ae=new x.Vector3,Le=new x.Vector3,Ze=new x.Box3;new x.Matrix4;new x.Matrix4;new x.Vector3;new x.Vector3(0,0,1);const vt=new x.Vector3(1,0,0);new x.Vector3(0,1,0);new x.Vector3(0,0,1);class Ne{constructor(t,e=null){this.nodeAvatar=t,this.opt={jwtGet:null,ttsEndpoint:"",ttsApikey:null,ttsTrimStart:0,ttsTrimEnd:400,ttsLang:"fi-FI",ttsVoice:"fi-FI-Standard-A",ttsRate:1,ttsPitch:0,ttsVolume:.3,mixerGainSpeech:1.2,mixerGainBackground:null,lipsyncLang:"fi",lipsyncModules:["fi","en","lt"],pcmSampleRate:22050,modelRoot:"Armature",modelPixelRatio:1,modelFPS:30,modelMovementFactor:1,cameraView:"full",dracoEnabled:!1,dracoDecoderPath:"https://www.gstatic.com/draco/v1/decoders/",cameraDistance:0,cameraX:0,cameraY:0,cameraRotateX:0,cameraRotateY:0,cameraRotateEnable:!0,cameraPanEnable:!1,cameraZoomEnable:!1,lightAmbientColor:16777215,lightAmbientIntensity:1.25,lightDirectColor:8947882,lightDirectIntensity:12,lightDirectPhi:1,lightDirectTheta:2,lightSpotIntensity:0,lightSpotColor:3377407,lightSpotPhi:.1,lightSpotTheta:4,lightSpotDispersion:1,avatarMood:"neutral",avatarMute:!1,avatarIdleEyeContact:.6,avatarIdleHeadMove:.5,avatarSpeakingEyeContact:.8,avatarSpeakingHeadMove:.5,avatarIgnoreCamera:!1,listeningSilenceThresholdLevel:40,listeningSilenceThresholdMs:2e3,listeningSilenceDurationMax:1e4,listeningActiveThresholdLevel:75,listeningActiveThresholdMs:300,listeningActiveDurationMax:24e4,update:null,avatarOnly:!1,avatarOnlyScene:null,avatarOnlyCamera:null,statsNode:null,statsStyle:null},Object.assign(this.opt,e||{}),this.opt.statsNode&&(this.stats=new nt,this.opt.statsStyle&&(this.stats.dom.style.cssText=this.opt.statsStyle),this.opt.statsNode.appendChild(this.stats.dom)),this.poseTemplates={side:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.003,y:-.017,z:.1},"Spine.rotation":{x:-.103,y:-.002,z:-.063},"Spine1.rotation":{x:.042,y:-.02,z:-.069},"Spine2.rotation":{x:.131,y:-.012,z:-.065},"Neck.rotation":{x:.027,y:.006,z:0},"Head.rotation":{x:.077,y:-.065,z:0},"LeftShoulder.rotation":{x:1.599,y:.084,z:-1.77},"LeftArm.rotation":{x:1.364,y:.052,z:-.044},"LeftForeArm.rotation":{x:.002,y:-.007,z:.331},"LeftHand.rotation":{x:.104,y:-.067,z:-.174},"LeftHandThumb1.rotation":{x:.231,y:.258,z:.355},"LeftHandThumb2.rotation":{x:-.106,y:-.339,z:-.454},"LeftHandThumb3.rotation":{x:-.02,y:-.142,z:-.004},"LeftHandIndex1.rotation":{x:.148,y:.032,z:-.069},"LeftHandIndex2.rotation":{x:.326,y:-.049,z:-.029},"LeftHandIndex3.rotation":{x:.247,y:-.053,z:-.073},"LeftHandMiddle1.rotation":{x:.238,y:-.057,z:-.089},"LeftHandMiddle2.rotation":{x:.469,y:-.036,z:-.081},"LeftHandMiddle3.rotation":{x:.206,y:-.015,z:-.017},"LeftHandRing1.rotation":{x:.187,y:-.118,z:-.157},"LeftHandRing2.rotation":{x:.579,y:.02,z:-.097},"LeftHandRing3.rotation":{x:.272,y:.021,z:-.063},"LeftHandPinky1.rotation":{x:.405,y:-.182,z:-.138},"LeftHandPinky2.rotation":{x:.613,y:.128,z:-.144},"LeftHandPinky3.rotation":{x:.268,y:.094,z:-.081},"RightShoulder.rotation":{x:1.541,y:.192,z:1.775},"RightArm.rotation":{x:1.273,y:-.352,z:-.067},"RightForeArm.rotation":{x:-.011,y:-.031,z:-.357},"RightHand.rotation":{x:-.008,y:.312,z:-.028},"RightHandThumb1.rotation":{x:.23,y:-.258,z:-.355},"RightHandThumb2.rotation":{x:-.107,y:.339,z:.454},"RightHandThumb3.rotation":{x:-.02,y:.142,z:.004},"RightHandIndex1.rotation":{x:.148,y:-.031,z:.069},"RightHandIndex2.rotation":{x:.326,y:.049,z:.029},"RightHandIndex3.rotation":{x:.247,y:.053,z:.073},"RightHandMiddle1.rotation":{x:.237,y:.057,z:.089},"RightHandMiddle2.rotation":{x:.469,y:.036,z:.081},"RightHandMiddle3.rotation":{x:.206,y:.015,z:.017},"RightHandRing1.rotation":{x:.204,y:.086,z:.135},"RightHandRing2.rotation":{x:.579,y:-.02,z:.098},"RightHandRing3.rotation":{x:.272,y:-.021,z:.063},"RightHandPinky1.rotation":{x:.404,y:.182,z:.137},"RightHandPinky2.rotation":{x:.613,y:-.128,z:.144},"RightHandPinky3.rotation":{x:.268,y:-.094,z:.081},"LeftUpLeg.rotation":{x:.096,y:.209,z:2.983},"LeftLeg.rotation":{x:-.053,y:.042,z:-.017},"LeftFoot.rotation":{x:1.091,y:.15,z:.026},"LeftToeBase.rotation":{x:.469,y:-.07,z:-.015},"RightUpLeg.rotation":{x:-.307,y:-.219,z:2.912},"RightLeg.rotation":{x:-.359,y:.164,z:.015},"RightFoot.rotation":{x:1.035,y:.11,z:.005},"RightToeBase.rotation":{x:.467,y:.07,z:.015}}},hip:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.036,y:.09,z:.135},"Spine.rotation":{x:.076,y:-.035,z:.01},"Spine1.rotation":{x:-.096,y:.013,z:-.094},"Spine2.rotation":{x:-.014,y:.002,z:-.097},"Neck.rotation":{x:.034,y:-.051,z:-.075},"Head.rotation":{x:.298,y:-.1,z:.154},"LeftShoulder.rotation":{x:1.694,y:.011,z:-1.68},"LeftArm.rotation":{x:1.343,y:.177,z:-.153},"LeftForeArm.rotation":{x:-.049,y:.134,z:.351},"LeftHand.rotation":{x:.057,y:-.189,z:-.026},"LeftHandThumb1.rotation":{x:.368,y:-.066,z:.438},"LeftHandThumb2.rotation":{x:-.156,y:.029,z:-.369},"LeftHandThumb3.rotation":{x:.034,y:-.009,z:.016},"LeftHandIndex1.rotation":{x:.157,y:-.002,z:-.171},"LeftHandIndex2.rotation":{x:.099,y:0,z:0},"LeftHandIndex3.rotation":{x:.1,y:0,z:0},"LeftHandMiddle1.rotation":{x:.222,y:-.019,z:-.16},"LeftHandMiddle2.rotation":{x:.142,y:0,z:0},"LeftHandMiddle3.rotation":{x:.141,y:0,z:0},"LeftHandRing1.rotation":{x:.333,y:-.039,z:-.174},"LeftHandRing2.rotation":{x:.214,y:0,z:0},"LeftHandRing3.rotation":{x:.213,y:0,z:0},"LeftHandPinky1.rotation":{x:.483,y:-.069,z:-.189},"LeftHandPinky2.rotation":{x:.312,y:0,z:0},"LeftHandPinky3.rotation":{x:.309,y:0,z:0},"RightShoulder.rotation":{x:1.597,y:.012,z:1.816},"RightArm.rotation":{x:.618,y:-1.274,z:-.266},"RightForeArm.rotation":{x:-.395,y:-.097,z:-1.342},"RightHand.rotation":{x:-.816,y:-.057,z:-.976},"RightHandThumb1.rotation":{x:.42,y:.23,z:-1.172},"RightHandThumb2.rotation":{x:-.027,y:.361,z:.122},"RightHandThumb3.rotation":{x:.076,y:.125,z:-.371},"RightHandIndex1.rotation":{x:-.158,y:-.045,z:.033},"RightHandIndex2.rotation":{x:.391,y:.051,z:.025},"RightHandIndex3.rotation":{x:.317,y:.058,z:.07},"RightHandMiddle1.rotation":{x:.486,y:.066,z:.014},"RightHandMiddle2.rotation":{x:.718,y:.055,z:.07},"RightHandMiddle3.rotation":{x:.453,y:.019,z:.013},"RightHandRing1.rotation":{x:.591,y:.241,z:.11},"RightHandRing2.rotation":{x:1.014,y:.023,z:.097},"RightHandRing3.rotation":{x:.708,y:.008,z:.066},"RightHandPinky1.rotation":{x:1.02,y:.305,z:.051},"RightHandPinky2.rotation":{x:1.187,y:-.028,z:.191},"RightHandPinky3.rotation":{x:.872,y:-.031,z:.121},"LeftUpLeg.rotation":{x:-.095,y:-.058,z:-3.338},"LeftLeg.rotation":{x:-.366,y:.287,z:-.021},"LeftFoot.rotation":{x:1.131,y:.21,z:.176},"LeftToeBase.rotation":{x:.739,y:-.068,z:-.001},"RightUpLeg.rotation":{x:-.502,y:.362,z:3.153},"RightLeg.rotation":{x:-1.002,y:.109,z:.008},"RightFoot.rotation":{x:.626,y:-.097,z:-.194},"RightToeBase.rotation":{x:1.33,y:.288,z:-.078}}},turn:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.07,y:-.604,z:-.004},"Spine.rotation":{x:-.007,y:.003,z:.071},"Spine1.rotation":{x:-.053,y:.024,z:-.06},"Spine2.rotation":{x:.074,y:.013,z:-.068},"Neck.rotation":{x:.03,y:.186,z:-.077},"Head.rotation":{x:.045,y:.243,z:-.086},"LeftShoulder.rotation":{x:1.717,y:-.085,z:-1.761},"LeftArm.rotation":{x:1.314,y:.07,z:-.057},"LeftForeArm.rotation":{x:-.151,y:.714,z:.302},"LeftHand.rotation":{x:-.069,y:.003,z:-.118},"LeftHandThumb1.rotation":{x:.23,y:.258,z:.354},"LeftHandThumb2.rotation":{x:-.107,y:-.338,z:-.455},"LeftHandThumb3.rotation":{x:-.015,y:-.142,z:.002},"LeftHandIndex1.rotation":{x:.145,y:.032,z:-.069},"LeftHandIndex2.rotation":{x:.323,y:-.049,z:-.028},"LeftHandIndex3.rotation":{x:.249,y:-.053,z:-.074},"LeftHandMiddle1.rotation":{x:.235,y:-.057,z:-.088},"LeftHandMiddle2.rotation":{x:.468,y:-.036,z:-.081},"LeftHandMiddle3.rotation":{x:.203,y:-.015,z:-.017},"LeftHandRing1.rotation":{x:.185,y:-.118,z:-.157},"LeftHandRing2.rotation":{x:.578,y:.02,z:-.097},"LeftHandRing3.rotation":{x:.27,y:.021,z:-.063},"LeftHandPinky1.rotation":{x:.404,y:-.182,z:-.138},"LeftHandPinky2.rotation":{x:.612,y:.128,z:-.144},"LeftHandPinky3.rotation":{x:.267,y:.094,z:-.081},"RightShoulder.rotation":{x:1.605,y:.17,z:1.625},"RightArm.rotation":{x:1.574,y:-.655,z:.388},"RightForeArm.rotation":{x:-.36,y:-.849,z:-.465},"RightHand.rotation":{x:.114,y:.416,z:-.069},"RightHandThumb1.rotation":{x:.486,y:.009,z:-.492},"RightHandThumb2.rotation":{x:-.073,y:-.01,z:.284},"RightHandThumb3.rotation":{x:-.054,y:-.006,z:.209},"RightHandIndex1.rotation":{x:.245,y:-.014,z:.052},"RightHandIndex2.rotation":{x:.155,y:0,z:0},"RightHandIndex3.rotation":{x:.153,y:0,z:0},"RightHandMiddle1.rotation":{x:.238,y:.004,z:.028},"RightHandMiddle2.rotation":{x:.15,y:0,z:0},"RightHandMiddle3.rotation":{x:.149,y:0,z:0},"RightHandRing1.rotation":{x:.267,y:.012,z:.007},"RightHandRing2.rotation":{x:.169,y:0,z:0},"RightHandRing3.rotation":{x:.167,y:0,z:0},"RightHandPinky1.rotation":{x:.304,y:.018,z:-.021},"RightHandPinky2.rotation":{x:.192,y:0,z:0},"RightHandPinky3.rotation":{x:.19,y:0,z:0},"LeftUpLeg.rotation":{x:-.001,y:-.058,z:-3.238},"LeftLeg.rotation":{x:-.29,y:.058,z:-.021},"LeftFoot.rotation":{x:1.288,y:.168,z:.183},"LeftToeBase.rotation":{x:.363,y:-.09,z:-.01},"RightUpLeg.rotation":{x:-.1,y:.36,z:3.062},"RightLeg.rotation":{x:-.67,y:-.304,z:.043},"RightFoot.rotation":{x:1.195,y:-.159,z:-.294},"RightToeBase.rotation":{x:.737,y:.164,z:-.002}}},bend:{bend:!0,standing:!0,props:{"Hips.position":{x:-.007,y:.943,z:-.001},"Hips.rotation":{x:1.488,y:-.633,z:1.435},"Spine.rotation":{x:-.126,y:.007,z:-.057},"Spine1.rotation":{x:-.134,y:.009,z:.01},"Spine2.rotation":{x:-.019,y:0,z:-.002},"Neck.rotation":{x:-.159,y:.572,z:-.108},"Head.rotation":{x:-.064,y:.716,z:-.257},"RightShoulder.rotation":{x:1.625,y:-.043,z:1.382},"RightArm.rotation":{x:.746,y:-.96,z:-1.009},"RightForeArm.rotation":{x:-.199,y:-.528,z:-.38},"RightHand.rotation":{x:-.261,y:-.043,z:-.027},"RightHandThumb1.rotation":{x:.172,y:-.138,z:-.445},"RightHandThumb2.rotation":{x:-.158,y:.327,z:.545},"RightHandThumb3.rotation":{x:-.062,y:.138,z:.152},"RightHandIndex1.rotation":{x:.328,y:-.005,z:.132},"RightHandIndex2.rotation":{x:.303,y:.049,z:.028},"RightHandIndex3.rotation":{x:.241,y:.046,z:.077},"RightHandMiddle1.rotation":{x:.309,y:.074,z:.089},"RightHandMiddle2.rotation":{x:.392,y:.036,z:.081},"RightHandMiddle3.rotation":{x:.199,y:.014,z:.019},"RightHandRing1.rotation":{x:.239,y:.143,z:.091},"RightHandRing2.rotation":{x:.275,y:-.02,z:.097},"RightHandRing3.rotation":{x:.248,y:-.023,z:.061},"RightHandPinky1.rotation":{x:.211,y:.154,z:.029},"RightHandPinky2.rotation":{x:.348,y:-.128,z:.144},"RightHandPinky3.rotation":{x:.21,y:-.091,z:.065},"LeftShoulder.rotation":{x:1.626,y:-.027,z:-1.367},"LeftArm.rotation":{x:1.048,y:.737,z:.712},"LeftForeArm.rotation":{x:-.508,y:.879,z:.625},"LeftHand.rotation":{x:.06,y:-.243,z:-.079},"LeftHandThumb1.rotation":{x:.187,y:-.072,z:.346},"LeftHandThumb2.rotation":{x:-.066,y:.008,z:-.256},"LeftHandThumb3.rotation":{x:-.085,y:.014,z:-.334},"LeftHandIndex1.rotation":{x:-.1,y:.016,z:-.058},"LeftHandIndex2.rotation":{x:.334,y:0,z:0},"LeftHandIndex3.rotation":{x:.281,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.056,y:0,z:0},"LeftHandMiddle2.rotation":{x:.258,y:0,z:0},"LeftHandMiddle3.rotation":{x:.26,y:0,z:0},"LeftHandRing1.rotation":{x:-.067,y:-.002,z:.008},"LeftHandRing2.rotation":{x:.259,y:0,z:0},"LeftHandRing3.rotation":{x:.276,y:0,z:0},"LeftHandPinky1.rotation":{x:-.128,y:-.007,z:.042},"LeftHandPinky2.rotation":{x:.227,y:0,z:0},"LeftHandPinky3.rotation":{x:.145,y:0,z:0},"RightUpLeg.rotation":{x:-1.507,y:.2,z:-3.043},"RightLeg.rotation":{x:-.689,y:-.124,z:.017},"RightFoot.rotation":{x:.909,y:.008,z:-.093},"RightToeBase.rotation":{x:.842,y:.075,z:-.008},"LeftUpLeg.rotation":{x:-1.449,y:-.2,z:3.018},"LeftLeg.rotation":{x:-.74,y:-.115,z:-.008},"LeftFoot.rotation":{x:1.048,y:-.058,z:.117},"LeftToeBase.rotation":{x:.807,y:-.067,z:.003}}},back:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.732,y:-1.463,z:-.637},"Spine.rotation":{x:-.171,y:.106,z:.157},"Spine1.rotation":{x:-.044,y:.138,z:-.059},"Spine2.rotation":{x:.082,y:.133,z:-.074},"Neck.rotation":{x:.39,y:.591,z:-.248},"Head.rotation":{x:-.001,y:.596,z:-.057},"LeftShoulder.rotation":{x:1.676,y:.007,z:-1.892},"LeftArm.rotation":{x:-5.566,y:1.188,z:-.173},"LeftForeArm.rotation":{x:-.673,y:-.105,z:1.702},"LeftHand.rotation":{x:-.469,y:-.739,z:.003},"LeftHandThumb1.rotation":{x:.876,y:.274,z:.793},"LeftHandThumb2.rotation":{x:.161,y:-.23,z:-.172},"LeftHandThumb3.rotation":{x:.078,y:.027,z:.156},"LeftHandIndex1.rotation":{x:-.085,y:-.002,z:.009},"LeftHandIndex2.rotation":{x:.176,y:0,z:-.002},"LeftHandIndex3.rotation":{x:-.036,y:.001,z:-.035},"LeftHandMiddle1.rotation":{x:.015,y:.144,z:-.076},"LeftHandMiddle2.rotation":{x:.378,y:-.007,z:-.077},"LeftHandMiddle3.rotation":{x:-.141,y:-.001,z:.031},"LeftHandRing1.rotation":{x:.039,y:.02,z:-.2},"LeftHandRing2.rotation":{x:.25,y:-.002,z:-.073},"LeftHandRing3.rotation":{x:.236,y:.006,z:-.075},"LeftHandPinky1.rotation":{x:.172,y:-.033,z:-.275},"LeftHandPinky2.rotation":{x:.216,y:.043,z:-.054},"LeftHandPinky3.rotation":{x:.325,y:.078,z:-.13},"RightShoulder.rotation":{x:2.015,y:-.168,z:1.706},"RightArm.rotation":{x:.203,y:-1.258,z:-.782},"RightForeArm.rotation":{x:-.658,y:-.133,z:-1.401},"RightHand.rotation":{x:-1.504,y:.375,z:-.005},"RightHandThumb1.rotation":{x:.413,y:-.158,z:-1.121},"RightHandThumb2.rotation":{x:-.142,y:-.008,z:.209},"RightHandThumb3.rotation":{x:-.091,y:.021,z:.142},"RightHandIndex1.rotation":{x:-.167,y:.014,z:-.072},"RightHandIndex2.rotation":{x:.474,y:.009,z:.051},"RightHandIndex3.rotation":{x:.115,y:.006,z:.047},"RightHandMiddle1.rotation":{x:.385,y:.019,z:.144},"RightHandMiddle2.rotation":{x:.559,y:.035,z:.101},"RightHandMiddle3.rotation":{x:.229,y:0,z:.027},"RightHandRing1.rotation":{x:.48,y:.026,z:.23},"RightHandRing2.rotation":{x:.772,y:.038,z:.109},"RightHandRing3.rotation":{x:.622,y:.039,z:.106},"RightHandPinky1.rotation":{x:.767,y:.288,z:.353},"RightHandPinky2.rotation":{x:.886,y:.049,z:.122},"RightHandPinky3.rotation":{x:.662,y:.044,z:.113},"LeftUpLeg.rotation":{x:-.206,y:-.268,z:-3.343},"LeftLeg.rotation":{x:-.333,y:.757,z:-.043},"LeftFoot.rotation":{x:1.049,y:.167,z:.287},"LeftToeBase.rotation":{x:.672,y:-.069,z:-.004},"RightUpLeg.rotation":{x:.055,y:-.226,z:3.037},"RightLeg.rotation":{x:-.559,y:.39,z:-.001},"RightFoot.rotation":{x:1.2,y:.133,z:.085},"RightToeBase.rotation":{x:.92,y:.093,z:-.013}}},straight:{standing:!0,props:{"Hips.position":{x:0,y:.989,z:.001},"Hips.rotation":{x:.047,y:.007,z:-.007},"Spine.rotation":{x:-.143,y:-.007,z:.005},"Spine1.rotation":{x:-.043,y:-.014,z:.012},"Spine2.rotation":{x:.072,y:-.013,z:.013},"Neck.rotation":{x:.048,y:-.003,z:.012},"Head.rotation":{x:.05,y:-.02,z:-.017},"LeftShoulder.rotation":{x:1.62,y:-.166,z:-1.605},"LeftArm.rotation":{x:1.275,y:.544,z:-.092},"LeftForeArm.rotation":{x:0,y:0,z:.302},"LeftHand.rotation":{x:-.225,y:-.154,z:.11},"LeftHandThumb1.rotation":{x:.435,y:-.044,z:.457},"LeftHandThumb2.rotation":{x:-.028,y:.002,z:-.246},"LeftHandThumb3.rotation":{x:-.236,y:-.025,z:.113},"LeftHandIndex1.rotation":{x:.218,y:.008,z:-.081},"LeftHandIndex2.rotation":{x:.165,y:-.001,z:-.017},"LeftHandIndex3.rotation":{x:.165,y:-.001,z:-.017},"LeftHandMiddle1.rotation":{x:.235,y:-.011,z:-.065},"LeftHandMiddle2.rotation":{x:.182,y:-.002,z:-.019},"LeftHandMiddle3.rotation":{x:.182,y:-.002,z:-.019},"LeftHandRing1.rotation":{x:.316,y:-.017,z:.008},"LeftHandRing2.rotation":{x:.253,y:-.003,z:-.026},"LeftHandRing3.rotation":{x:.255,y:-.003,z:-.026},"LeftHandPinky1.rotation":{x:.336,y:-.062,z:.088},"LeftHandPinky2.rotation":{x:.276,y:-.004,z:-.028},"LeftHandPinky3.rotation":{x:.276,y:-.004,z:-.028},"RightShoulder.rotation":{x:1.615,y:.064,z:1.53},"RightArm.rotation":{x:1.313,y:-.424,z:.131},"RightForeArm.rotation":{x:0,y:0,z:-.317},"RightHand.rotation":{x:-.158,y:-.639,z:-.196},"RightHandThumb1.rotation":{x:.44,y:.048,z:-.549},"RightHandThumb2.rotation":{x:-.056,y:-.008,z:.274},"RightHandThumb3.rotation":{x:-.258,y:.031,z:-.095},"RightHandIndex1.rotation":{x:.169,y:-.011,z:.105},"RightHandIndex2.rotation":{x:.134,y:.001,z:.011},"RightHandIndex3.rotation":{x:.134,y:.001,z:.011},"RightHandMiddle1.rotation":{x:.288,y:.014,z:.092},"RightHandMiddle2.rotation":{x:.248,y:.003,z:.02},"RightHandMiddle3.rotation":{x:.249,y:.003,z:.02},"RightHandRing1.rotation":{x:.369,y:.019,z:.006},"RightHandRing2.rotation":{x:.321,y:.004,z:.026},"RightHandRing3.rotation":{x:.323,y:.004,z:.026},"RightHandPinky1.rotation":{x:.468,y:.085,z:-.03},"RightHandPinky2.rotation":{x:.427,y:.007,z:.034},"RightHandPinky3.rotation":{x:.142,y:.001,z:.012},"LeftUpLeg.rotation":{x:-.077,y:-.058,z:3.126},"LeftLeg.rotation":{x:-.252,y:.001,z:-.018},"LeftFoot.rotation":{x:1.315,y:-.064,z:.315},"LeftToeBase.rotation":{x:.577,y:-.07,z:-.009},"RightUpLeg.rotation":{x:-.083,y:-.032,z:3.124},"RightLeg.rotation":{x:-.272,y:-.003,z:.021},"RightFoot.rotation":{x:1.342,y:.076,z:-.222},"RightToeBase.rotation":{x:.44,y:.069,z:.016}}},wide:{standing:!0,props:{"Hips.position":{x:0,y:1.017,z:.016},"Hips.rotation":{x:.064,y:-.048,z:.059},"Spine.rotation":{x:-.123,y:0,z:-.018},"Spine1.rotation":{x:.014,y:.003,z:-.006},"Spine2.rotation":{x:.04,y:.003,z:-.007},"Neck.rotation":{x:.101,y:.007,z:-.035},"Head.rotation":{x:-.091,y:-.049,z:.105},"RightShoulder.rotation":{x:1.831,y:.017,z:1.731},"RightArm.rotation":{x:-1.673,y:-1.102,z:-3.132},"RightForeArm.rotation":{x:.265,y:.23,z:-.824},"RightHand.rotation":{x:-.52,y:.345,z:-.061},"RightHandThumb1.rotation":{x:.291,y:.056,z:-.428},"RightHandThumb2.rotation":{x:.025,y:.005,z:.166},"RightHandThumb3.rotation":{x:-.089,y:.009,z:.068},"RightHandIndex1.rotation":{x:.392,y:-.015,z:.11},"RightHandIndex2.rotation":{x:.391,y:.001,z:.004},"RightHandIndex3.rotation":{x:.326,y:0,z:.003},"RightHandMiddle1.rotation":{x:.285,y:.068,z:.081},"RightHandMiddle2.rotation":{x:.519,y:.004,z:.011},"RightHandMiddle3.rotation":{x:.252,y:0,z:.001},"RightHandRing1.rotation":{x:.207,y:.133,z:.146},"RightHandRing2.rotation":{x:.597,y:.004,z:.004},"RightHandRing3.rotation":{x:.292,y:.002,z:.012},"RightHandPinky1.rotation":{x:.338,y:.182,z:.136},"RightHandPinky2.rotation":{x:.533,y:.002,z:.004},"RightHandPinky3.rotation":{x:.194,y:0,z:.002},"LeftShoulder.rotation":{x:1.83,y:-.063,z:-1.808},"LeftArm.rotation":{x:-1.907,y:1.228,z:-2.959},"LeftForeArm.rotation":{x:-.159,y:.268,z:.572},"LeftHand.rotation":{x:.069,y:-.498,z:-.025},"LeftHandThumb1.rotation":{x:.738,y:.123,z:.178},"LeftHandThumb2.rotation":{x:-.26,y:.028,z:-.477},"LeftHandThumb3.rotation":{x:-.448,y:.093,z:-.661},"LeftHandIndex1.rotation":{x:1.064,y:.005,z:-.13},"LeftHandIndex2.rotation":{x:1.55,y:-.143,z:-.136},"LeftHandIndex3.rotation":{x:.722,y:-.076,z:-.127},"LeftHandMiddle1.rotation":{x:1.095,y:-.091,z:.006},"LeftHandMiddle2.rotation":{x:1.493,y:-.174,z:-.151},"LeftHandMiddle3.rotation":{x:.651,y:-.031,z:-.087},"LeftHandRing1.rotation":{x:1.083,y:-.224,z:.072},"LeftHandRing2.rotation":{x:1.145,y:-.107,z:-.195},"LeftHandRing3.rotation":{x:1.208,y:-.134,z:-.158},"LeftHandPinky1.rotation":{x:.964,y:-.383,z:.128},"LeftHandPinky2.rotation":{x:1.457,y:-.146,z:-.159},"LeftHandPinky3.rotation":{x:1.019,y:-.102,z:-.141},"RightUpLeg.rotation":{x:-.221,y:-.233,z:2.87},"RightLeg.rotation":{x:-.339,y:-.043,z:-.041},"RightFoot.rotation":{x:1.081,y:.177,z:.114},"RightToeBase.rotation":{x:.775,y:0,z:0},"LeftUpLeg.rotation":{x:-.185,y:.184,z:3.131},"LeftLeg.rotation":{x:-.408,y:.129,z:.02},"LeftFoot.rotation":{x:1.167,y:-.002,z:-.007},"LeftToeBase.rotation":{x:.723,y:0,z:0}}},oneknee:{kneeling:!0,props:{"Hips.position":{x:-.005,y:.415,z:-.017},"Hips.rotation":{x:-.25,y:.04,z:-.238},"Spine.rotation":{x:.037,y:.043,z:.047},"Spine1.rotation":{x:.317,y:.103,z:.066},"Spine2.rotation":{x:.433,y:.109,z:.054},"Neck.rotation":{x:-.156,y:-.092,z:.059},"Head.rotation":{x:-.398,y:-.032,z:.018},"RightShoulder.rotation":{x:1.546,y:.119,z:1.528},"RightArm.rotation":{x:.896,y:-.247,z:-.512},"RightForeArm.rotation":{x:.007,y:0,z:-1.622},"RightHand.rotation":{x:1.139,y:-.853,z:.874},"RightHandThumb1.rotation":{x:.176,y:.107,z:-.311},"RightHandThumb2.rotation":{x:-.047,y:-.003,z:.12},"RightHandThumb3.rotation":{x:0,y:0,z:0},"RightHandIndex1.rotation":{x:.186,y:.005,z:.125},"RightHandIndex2.rotation":{x:.454,y:.005,z:.015},"RightHandIndex3.rotation":{x:0,y:0,z:0},"RightHandMiddle1.rotation":{x:.444,y:.035,z:.127},"RightHandMiddle2.rotation":{x:.403,y:-.006,z:-.04},"RightHandMiddle3.rotation":{x:0,y:0,z:0},"RightHandRing1.rotation":{x:.543,y:.074,z:.121},"RightHandRing2.rotation":{x:.48,y:-.018,z:-.063},"RightHandRing3.rotation":{x:0,y:0,z:0},"RightHandPinky1.rotation":{x:.464,y:.086,z:.113},"RightHandPinky2.rotation":{x:.667,y:-.06,z:-.128},"RightHandPinky3.rotation":{x:0,y:0,z:0},"LeftShoulder.rotation":{x:1.545,y:-.116,z:-1.529},"LeftArm.rotation":{x:.799,y:.631,z:.556},"LeftForeArm.rotation":{x:-.002,y:.007,z:.926},"LeftHand.rotation":{x:-.508,y:.439,z:.502},"LeftHandThumb1.rotation":{x:.651,y:-.035,z:.308},"LeftHandThumb2.rotation":{x:-.053,y:.008,z:-.11},"LeftHandThumb3.rotation":{x:0,y:0,z:0},"LeftHandIndex1.rotation":{x:.662,y:-.053,z:-.116},"LeftHandIndex2.rotation":{x:.309,y:-.004,z:-.02},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:.501,y:-.062,z:-.12},"LeftHandMiddle2.rotation":{x:.144,y:-.002,z:.016},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.397,y:-.029,z:-.143},"LeftHandRing2.rotation":{x:.328,y:.01,z:.059},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.194,y:.008,z:-.164},"LeftHandPinky2.rotation":{x:.38,y:.031,z:.128},"LeftHandPinky3.rotation":{x:0,y:0,z:0},"RightUpLeg.rotation":{x:-1.594,y:-.251,z:2.792},"RightLeg.rotation":{x:-2.301,y:-.073,z:.055},"RightFoot.rotation":{x:1.553,y:-.207,z:-.094},"RightToeBase.rotation":{x:.459,y:.069,z:.016},"LeftUpLeg.rotation":{x:-.788,y:-.236,z:-2.881},"LeftLeg.rotation":{x:-2.703,y:.012,z:-.047},"LeftFoot.rotation":{x:2.191,y:-.102,z:.019},"LeftToeBase.rotation":{x:1.215,y:-.027,z:.01}}},kneel:{kneeling:!0,lying:!0,props:{"Hips.position":{x:0,y:.532,z:-.002},"Hips.rotation":{x:.018,y:-.008,z:-.017},"Spine.rotation":{x:-.139,y:-.01,z:.002},"Spine1.rotation":{x:.002,y:-.002,z:.001},"Spine2.rotation":{x:.028,y:-.002,z:.001},"Neck.rotation":{x:-.007,y:0,z:-.002},"Head.rotation":{x:-.02,y:-.008,z:-.004},"LeftShoulder.rotation":{x:1.77,y:-.428,z:-1.588},"LeftArm.rotation":{x:.911,y:.343,z:.083},"LeftForeArm.rotation":{x:0,y:0,z:.347},"LeftHand.rotation":{x:.033,y:-.052,z:-.105},"LeftHandThumb1.rotation":{x:.508,y:-.22,z:.708},"LeftHandThumb2.rotation":{x:-.323,y:-.139,z:-.56},"LeftHandThumb3.rotation":{x:-.328,y:.16,z:-.301},"LeftHandIndex1.rotation":{x:.178,y:.248,z:.045},"LeftHandIndex2.rotation":{x:.236,y:-.002,z:-.019},"LeftHandIndex3.rotation":{x:-.062,y:0,z:.005},"LeftHandMiddle1.rotation":{x:.123,y:-.005,z:-.019},"LeftHandMiddle2.rotation":{x:.589,y:-.014,z:-.045},"LeftHandMiddle3.rotation":{x:.231,y:-.002,z:-.019},"LeftHandRing1.rotation":{x:.196,y:-.008,z:-.091},"LeftHandRing2.rotation":{x:.483,y:-.009,z:-.038},"LeftHandRing3.rotation":{x:.367,y:-.005,z:-.029},"LeftHandPinky1.rotation":{x:.191,y:-.269,z:-.246},"LeftHandPinky2.rotation":{x:.37,y:-.006,z:-.029},"LeftHandPinky3.rotation":{x:.368,y:-.005,z:-.029},"RightShoulder.rotation":{x:1.73,y:.434,z:1.715},"RightArm.rotation":{x:.841,y:-.508,z:-.155},"RightForeArm.rotation":{x:0,y:0,z:-.355},"RightHand.rotation":{x:.091,y:.137,z:.197},"RightHandThumb1.rotation":{x:.33,y:.051,z:-.753},"RightHandThumb2.rotation":{x:-.113,y:.075,z:.612},"RightHandThumb3.rotation":{x:-.271,y:-.166,z:.164},"RightHandIndex1.rotation":{x:.073,y:.001,z:-.093},"RightHandIndex2.rotation":{x:.338,y:.006,z:.034},"RightHandIndex3.rotation":{x:.131,y:.001,z:.013},"RightHandMiddle1.rotation":{x:.13,y:.005,z:-.017},"RightHandMiddle2.rotation":{x:.602,y:.018,z:.058},"RightHandMiddle3.rotation":{x:-.031,y:0,z:-.003},"RightHandRing1.rotation":{x:.351,y:.019,z:.045},"RightHandRing2.rotation":{x:.19,y:.002,z:.019},"RightHandRing3.rotation":{x:.21,y:.002,z:.021},"RightHandPinky1.rotation":{x:.256,y:.17,z:.118},"RightHandPinky2.rotation":{x:.451,y:.01,z:.045},"RightHandPinky3.rotation":{x:.346,y:.006,z:.035},"LeftUpLeg.rotation":{x:-.06,y:.1,z:-2.918},"LeftLeg.rotation":{x:-1.933,y:-.01,z:.011},"LeftFoot.rotation":{x:.774,y:-.162,z:-.144},"LeftToeBase.rotation":{x:1.188,y:0,z:0},"RightUpLeg.rotation":{x:-.099,y:-.057,z:2.922},"RightLeg.rotation":{x:-1.93,y:.172,z:-.02},"RightFoot.rotation":{x:.644,y:.251,z:.212},"RightToeBase.rotation":{x:.638,y:-.034,z:-.001}}},sitting:{sitting:!0,lying:!0,props:{"Hips.position":{x:0,y:.117,z:.005},"Hips.rotation":{x:-.411,y:-.049,z:.056},"Spine.rotation":{x:.45,y:-.039,z:-.116},"Spine1.rotation":{x:.092,y:-.076,z:.08},"Spine2.rotation":{x:.073,y:.035,z:.066},"Neck.rotation":{x:.051,y:.053,z:-.079},"Head.rotation":{x:-.169,y:.009,z:.034},"LeftShoulder.rotation":{x:1.756,y:-.037,z:-1.301},"LeftArm.rotation":{x:-.098,y:.016,z:1.006},"LeftForeArm.rotation":{x:-.089,y:.08,z:.837},"LeftHand.rotation":{x:.262,y:-.399,z:.3},"LeftHandThumb1.rotation":{x:.149,y:-.043,z:.452},"LeftHandThumb2.rotation":{x:.032,y:.006,z:-.162},"LeftHandThumb3.rotation":{x:-.086,y:-.005,z:-.069},"LeftHandIndex1.rotation":{x:.145,y:.032,z:-.069},"LeftHandIndex2.rotation":{x:.325,y:-.001,z:-.004},"LeftHandIndex3.rotation":{x:.253,y:0,z:-.003},"LeftHandMiddle1.rotation":{x:.186,y:-.051,z:-.091},"LeftHandMiddle2.rotation":{x:.42,y:-.003,z:-.011},"LeftHandMiddle3.rotation":{x:.153,y:.001,z:-.001},"LeftHandRing1.rotation":{x:.087,y:-.19,z:-.078},"LeftHandRing2.rotation":{x:.488,y:-.004,z:-.005},"LeftHandRing3.rotation":{x:.183,y:-.001,z:-.012},"LeftHandPinky1.rotation":{x:.205,y:-.262,z:.051},"LeftHandPinky2.rotation":{x:.407,y:-.002,z:-.004},"LeftHandPinky3.rotation":{x:.068,y:0,z:-.002},"RightShoulder.rotation":{x:1.619,y:-.139,z:1.179},"RightArm.rotation":{x:.17,y:-.037,z:-1.07},"RightForeArm.rotation":{x:-.044,y:-.056,z:-.665},"RightHand.rotation":{x:.278,y:.454,z:-.253},"RightHandThumb1.rotation":{x:.173,y:.089,z:-.584},"RightHandThumb2.rotation":{x:-.003,y:-.004,z:.299},"RightHandThumb3.rotation":{x:-.133,y:-.002,z:.235},"RightHandIndex1.rotation":{x:.393,y:-.023,z:.108},"RightHandIndex2.rotation":{x:.391,y:.001,z:.004},"RightHandIndex3.rotation":{x:.326,y:0,z:.003},"RightHandMiddle1.rotation":{x:.285,y:.062,z:.086},"RightHandMiddle2.rotation":{x:.519,y:.003,z:.011},"RightHandMiddle3.rotation":{x:.252,y:-.001,z:.001},"RightHandRing1.rotation":{x:.207,y:.122,z:.155},"RightHandRing2.rotation":{x:.597,y:.004,z:.005},"RightHandRing3.rotation":{x:.292,y:.001,z:.012},"RightHandPinky1.rotation":{x:.338,y:.171,z:.149},"RightHandPinky2.rotation":{x:.533,y:.002,z:.004},"RightHandPinky3.rotation":{x:.194,y:0,z:.002},"LeftUpLeg.rotation":{x:-1.957,y:.083,z:-2.886},"LeftLeg.rotation":{x:-1.46,y:.123,z:.005},"LeftFoot.rotation":{x:-.013,y:.016,z:.09},"LeftToeBase.rotation":{x:.744,y:0,z:0},"RightUpLeg.rotation":{x:-1.994,y:.125,z:2.905},"RightLeg.rotation":{x:-1.5,y:-.202,z:-.006},"RightFoot.rotation":{x:-.012,y:-.065,z:.081},"RightToeBase.rotation":{x:.758,y:0,z:0}}}},this.gestureTemplates={handup:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.815,y:[-.4,0,1,2],z:1.575},"LeftHand.rotation":{x:-.529,y:-.2,z:.022},"LeftHandThumb1.rotation":{x:.745,y:-.526,z:.604},"LeftHandThumb2.rotation":{x:-.107,y:-.01,z:-.142},"LeftHandThumb3.rotation":{x:0,y:.001,z:0},"LeftHandIndex1.rotation":{x:-.126,y:-.035,z:-.087},"LeftHandIndex2.rotation":{x:.255,y:.007,z:-.085},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.019,y:-.128,z:-.082},"LeftHandMiddle2.rotation":{x:.233,y:.019,z:-.074},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.005,y:-.241,z:-.122},"LeftHandRing2.rotation":{x:.261,y:.021,z:-.076},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.059,y:-.336,z:-.2},"LeftHandPinky2.rotation":{x:.153,y:.019,z:.001},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},index:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.815,y:[-.4,0,1,2],z:1.575},"LeftHand.rotation":{x:-.276,y:-.506,z:-.208},"LeftHandThumb1.rotation":{x:.579,y:.228,z:.363},"LeftHandThumb2.rotation":{x:-.027,y:-.04,z:-.662},"LeftHandThumb3.rotation":{x:0,y:.001,z:0},"LeftHandIndex1.rotation":{x:0,y:-.105,z:.225},"LeftHandIndex2.rotation":{x:.256,y:-.103,z:-.213},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:1.453,y:.07,z:.021},"LeftHandMiddle2.rotation":{x:1.599,y:.062,z:.07},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:1.528,y:-.073,z:.052},"LeftHandRing2.rotation":{x:1.386,y:.044,z:.053},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:1.65,y:-.204,z:.031},"LeftHandPinky2.rotation":{x:1.302,y:.071,z:.085},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},ok:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,1],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.415,y:[-.4,0,1,2],z:1.575},"LeftHand.rotation":{x:-.476,y:-.506,z:-.208},"LeftHandThumb1.rotation":{x:.703,y:.445,z:.899},"LeftHandThumb2.rotation":{x:-.312,y:-.04,z:-.938},"LeftHandThumb3.rotation":{x:-.37,y:.024,z:-.393},"LeftHandIndex1.rotation":{x:.8,y:-.086,z:-.091},"LeftHandIndex2.rotation":{x:1.123,y:-.046,z:-.074},"LeftHandIndex3.rotation":{x:.562,y:-.013,z:-.043},"LeftHandMiddle1.rotation":{x:-.019,y:-.128,z:-.082},"LeftHandMiddle2.rotation":{x:.233,y:.019,z:-.074},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.005,y:-.241,z:-.122},"LeftHandRing2.rotation":{x:.261,y:.021,z:-.076},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.059,y:-.336,z:-.2},"LeftHandPinky2.rotation":{x:.153,y:.019,z:.001},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},thumbup:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.415,y:.206,z:1.575},"LeftHand.rotation":{x:-.276,y:-.506,z:-.208},"LeftHandThumb1.rotation":{x:.208,y:-.189,z:.685},"LeftHandThumb2.rotation":{x:.129,y:-.285,z:-.163},"LeftHandThumb3.rotation":{x:-.047,y:.068,z:.401},"LeftHandIndex1.rotation":{x:1.412,y:-.102,z:-.152},"LeftHandIndex2.rotation":{x:1.903,y:-.16,z:-.114},"LeftHandIndex3.rotation":{x:.535,y:-.017,z:-.062},"LeftHandMiddle1.rotation":{x:1.424,y:-.103,z:-.12},"LeftHandMiddle2.rotation":{x:1.919,y:-.162,z:-.114},"LeftHandMiddle3.rotation":{x:.44,y:-.012,z:-.051},"LeftHandRing1.rotation":{x:1.619,y:-.127,z:-.053},"LeftHandRing2.rotation":{x:1.898,y:-.16,z:-.115},"LeftHandRing3.rotation":{x:.262,y:-.004,z:-.031},"LeftHandPinky1.rotation":{x:1.661,y:-.131,z:-.016},"LeftHandPinky2.rotation":{x:1.715,y:-.067,z:-.13},"LeftHandPinky3.rotation":{x:.627,y:-.023,z:-.071}},thumbdown:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-2.015,y:.406,z:1.575},"LeftHand.rotation":{x:-.176,y:-.206,z:-.208},"LeftHandThumb1.rotation":{x:.208,y:-.189,z:.685},"LeftHandThumb2.rotation":{x:.129,y:-.285,z:-.163},"LeftHandThumb3.rotation":{x:-.047,y:.068,z:.401},"LeftHandIndex1.rotation":{x:1.412,y:-.102,z:-.152},"LeftHandIndex2.rotation":{x:1.903,y:-.16,z:-.114},"LeftHandIndex3.rotation":{x:.535,y:-.017,z:-.062},"LeftHandMiddle1.rotation":{x:1.424,y:-.103,z:-.12},"LeftHandMiddle2.rotation":{x:1.919,y:-.162,z:-.114},"LeftHandMiddle3.rotation":{x:.44,y:-.012,z:-.051},"LeftHandRing1.rotation":{x:1.619,y:-.127,z:-.053},"LeftHandRing2.rotation":{x:1.898,y:-.16,z:-.115},"LeftHandRing3.rotation":{x:.262,y:-.004,z:-.031},"LeftHandPinky1.rotation":{x:1.661,y:-.131,z:-.016},"LeftHandPinky2.rotation":{x:1.715,y:-.067,z:-.13},"LeftHandPinky3.rotation":{x:.627,y:-.023,z:-.071}},side:{"LeftShoulder.rotation":{x:1.755,y:-.035,z:-1.63},"LeftArm.rotation":{x:1.263,y:-.955,z:1.024},"LeftForeArm.rotation":{x:0,y:0,z:.8},"LeftHand.rotation":{x:-.36,y:-1.353,z:-.184},"LeftHandThumb1.rotation":{x:.137,y:-.049,z:.863},"LeftHandThumb2.rotation":{x:-.293,y:.153,z:-.193},"LeftHandThumb3.rotation":{x:-.271,y:-.17,z:.18},"LeftHandIndex1.rotation":{x:-.018,y:.007,z:.28},"LeftHandIndex2.rotation":{x:.247,y:-.003,z:-.025},"LeftHandIndex3.rotation":{x:.13,y:-.001,z:-.013},"LeftHandMiddle1.rotation":{x:.333,y:-.015,z:.182},"LeftHandMiddle2.rotation":{x:.313,y:-.005,z:-.032},"LeftHandMiddle3.rotation":{x:.294,y:-.004,z:-.03},"LeftHandRing1.rotation":{x:.456,y:-.028,z:-.092},"LeftHandRing2.rotation":{x:.53,y:-.014,z:-.052},"LeftHandRing3.rotation":{x:.478,y:-.012,z:-.047},"LeftHandPinky1.rotation":{x:.647,y:-.049,z:-.184},"LeftHandPinky2.rotation":{x:.29,y:-.004,z:-.029},"LeftHandPinky3.rotation":{x:.501,y:-.013,z:-.049}},shrug:{"Neck.rotation":{x:[-.3,.3,1,2],y:[-.3,.3,1,2],z:[-.1,.1]},"Head.rotation":{x:[-.3,.3],y:[-.3,.3],z:[-.1,.1]},"RightShoulder.rotation":{x:1.732,y:-.058,z:1.407},"RightArm.rotation":{x:1.305,y:.46,z:.118},"RightForeArm.rotation":{x:[0,2],y:[-1,.2],z:-1.637},"RightHand.rotation":{x:-.048,y:.165,z:-.39},"RightHandThumb1.rotation":{x:1.467,y:.599,z:-1.315},"RightHandThumb2.rotation":{x:-.255,y:-.123,z:.119},"RightHandThumb3.rotation":{x:0,y:-.002,z:0},"RightHandIndex1.rotation":{x:-.293,y:-.066,z:-.112},"RightHandIndex2.rotation":{x:.181,y:.007,z:.069},"RightHandIndex3.rotation":{x:0,y:0,z:0},"RightHandMiddle1.rotation":{x:-.063,y:-.041,z:.032},"RightHandMiddle2.rotation":{x:.149,y:.005,z:.05},"RightHandMiddle3.rotation":{x:0,y:0,z:0},"RightHandRing1.rotation":{x:.152,y:-.03,z:.132},"RightHandRing2.rotation":{x:.194,y:.007,z:.058},"RightHandRing3.rotation":{x:0,y:0,z:0},"RightHandPinky1.rotation":{x:.306,y:-.015,z:.257},"RightHandPinky2.rotation":{x:.15,y:-.003,z:-.003},"RightHandPinky3.rotation":{x:0,y:0,z:0},"LeftShoulder.rotation":{x:1.713,y:.141,z:-1.433},"LeftArm.rotation":{x:1.136,y:-.422,z:-.416},"LeftForeArm.rotation":{x:1.42,y:.123,z:1.506},"LeftHand.rotation":{x:.073,y:-.138,z:.064},"LeftHandThumb1.rotation":{x:1.467,y:-.599,z:1.314},"LeftHandThumb2.rotation":{x:-.255,y:.123,z:-.119},"LeftHandThumb3.rotation":{x:0,y:.001,z:0},"LeftHandIndex1.rotation":{x:-.293,y:.066,z:.112},"LeftHandIndex2.rotation":{x:.181,y:-.007,z:-.069},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.062,y:.041,z:-.032},"LeftHandMiddle2.rotation":{x:.149,y:-.005,z:-.05},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.152,y:.03,z:-.132},"LeftHandRing2.rotation":{x:.194,y:-.007,z:-.058},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.306,y:.015,z:-.257},"LeftHandPinky2.rotation":{x:.15,y:.003,z:.003},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},namaste:{"RightShoulder.rotation":{x:1.758,y:.099,z:1.604},"RightArm.rotation":{x:.862,y:-.292,z:-.932},"RightForeArm.rotation":{x:.083,y:.066,z:-1.791},"RightHand.rotation":{x:-.52,y:-.001,z:-.176},"RightHandThumb1.rotation":{x:.227,y:.418,z:-.776},"RightHandThumb2.rotation":{x:-.011,y:-.003,z:.171},"RightHandThumb3.rotation":{x:-.041,y:-.001,z:-.013},"RightHandIndex1.rotation":{x:-.236,y:.003,z:-.028},"RightHandIndex2.rotation":{x:.004,y:0,z:.001},"RightHandIndex3.rotation":{x:.002,y:0,z:0},"RightHandMiddle1.rotation":{x:-.236,y:.003,z:-.028},"RightHandMiddle2.rotation":{x:.004,y:0,z:.001},"RightHandMiddle3.rotation":{x:.002,y:0,z:0},"RightHandRing1.rotation":{x:-.236,y:.003,z:-.028},"RightHandRing2.rotation":{x:.004,y:0,z:.001},"RightHandRing3.rotation":{x:.002,y:0,z:0},"RightHandPinky1.rotation":{x:-.236,y:.003,z:-.028},"RightHandPinky2.rotation":{x:.004,y:0,z:.001},"RightHandPinky3.rotation":{x:.002,y:0,z:0},"LeftShoulder.rotation":{x:1.711,y:-.002,z:-1.625},"LeftArm.rotation":{x:.683,y:.334,z:.977},"LeftForeArm.rotation":{x:.086,y:-.066,z:1.843},"LeftHand.rotation":{x:-.595,y:-.229,z:.096},"LeftHandThumb1.rotation":{x:.404,y:-.05,z:.537},"LeftHandThumb2.rotation":{x:-.02,y:.004,z:-.154},"LeftHandThumb3.rotation":{x:-.049,y:.002,z:-.019},"LeftHandIndex1.rotation":{x:-.113,y:-.001,z:.014},"LeftHandIndex2.rotation":{x:.003,y:0,z:0},"LeftHandIndex3.rotation":{x:.002,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.113,y:-.001,z:.014},"LeftHandMiddle2.rotation":{x:.004,y:0,z:0},"LeftHandMiddle3.rotation":{x:.002,y:0,z:0},"LeftHandRing1.rotation":{x:-.113,y:-.001,z:.014},"LeftHandRing2.rotation":{x:.003,y:0,z:0},"LeftHandRing3.rotation":{x:.002,y:0,z:0},"LeftHandPinky1.rotation":{x:-.122,y:-.001,z:-.057},"LeftHandPinky2.rotation":{x:.012,y:.001,z:.07},"LeftHandPinky3.rotation":{x:.002,y:0,z:0}}},this.poseDelta={props:{"Hips.quaternion":{x:0,y:0,z:0},"Spine.quaternion":{x:0,y:0,z:0},"Spine1.quaternion":{x:0,y:0,z:0},"Neck.quaternion":{x:0,y:0,z:0},"Head.quaternion":{x:0,y:0,z:0},"Spine1.scale":{x:0,y:0,z:0},"Neck.scale":{x:0,y:0,z:0},"LeftArm.scale":{x:0,y:0,z:0},"RightArm.scale":{x:0,y:0,z:0}}},["Left","Right"].forEach(r=>{["Leg","UpLeg","Arm","ForeArm","Hand"].forEach(u=>{this.poseDelta.props[r+u+".quaternion"]={x:0,y:0,z:0}}),["HandThumb","HandIndex","HandMiddle","HandRing","HandPinky"].forEach(u=>{this.poseDelta.props[r+u+"1.quaternion"]={x:0,y:0,z:0},this.poseDelta.props[r+u+"2.quaternion"]={x:0,y:0,z:0},this.poseDelta.props[r+u+"3.quaternion"]={x:0,y:0,z:0}})});const n=new Set;Object.values(this.poseTemplates).forEach(r=>{Object.keys(this.propsToThreeObjects(r.props)).forEach(u=>n.add(u))}),Object.keys(this.poseDelta.props).forEach(r=>{n.add(r)}),this.posePropNames=[...n],this.poseName="side",this.poseWeightOnLeft=!0,this.gesture=null,this.poseCurrentTemplate=this.poseTemplates[this.poseName],this.poseStraight=this.propsToThreeObjects(this.poseTemplates.straight.props),this.poseBase=this.poseFactory(this.poseCurrentTemplate),this.poseTarget=this.poseFactory(this.poseCurrentTemplate),this.poseAvatar=null,this.avatarHeight=1.7,this.animTemplateEyes={name:"eyes",idle:{alt:[{p:()=>this.avatar?.hasOwnProperty("avatarIdleEyeContact")?this.avatar.avatarIdleEyeContact:this.opt.avatarIdleEyeContact,delay:[200,5e3],dt:[200,[2e3,5e3],[3e3,1e4,1,2]],vs:{headMove:[this.avatar?.hasOwnProperty("avatarIdleHeadMove")?this.avatar.avatarIdleHeadMove:this.opt.avatarIdleHeadMove],eyesRotateY:[[-.6,.6]],eyesRotateX:[[-.2,.6]],eyeContact:[null,1]}},{delay:[200,5e3],dt:[200,[2e3,5e3,1,2]],vs:{headMove:[this.avatar?.hasOwnProperty("avatarIdleHeadMove")?this.avatar.avatarIdleHeadMove:this.opt.avatarIdleHeadMove],eyesRotateY:[[-.6,.6]],eyesRotateX:[[-.2,.6]]}}]},speaking:{alt:[{p:()=>this.avatar?.hasOwnProperty("avatarSpeakingEyeContact")?this.avatar.avatarSpeakingEyeContact:this.opt.avatarSpeakingEyeContact,delay:[200,5e3],dt:[0,[3e3,1e4,1,2],[2e3,5e3]],vs:{eyeContact:[1,null],headMove:[null,this.avatar?.hasOwnProperty("avatarSpeakingHeadMove")?this.avatar.avatarSpeakingHeadMove:this.opt.avatarSpeakingHeadMove,null],eyesRotateY:[null,[-.6,.6]],eyesRotateX:[null,[-.2,.6]]}},{delay:[200,5e3],dt:[200,[2e3,5e3,1,2]],vs:{headMove:[this.avatar?.hasOwnProperty("avatarSpeakingHeadMove")?this.avatar.avatarSpeakingHeadMove:this.opt.avatarSpeakingHeadMove,null],eyesRotateY:[[-.6,.6]],eyesRotateX:[[-.2,.6]]}}]}},this.animTemplateBlink={name:"blink",alt:[{p:.85,delay:[1e3,8e3,1,2],dt:[50,[100,300],100],vs:{eyeBlinkLeft:[1,1,0],eyeBlinkRight:[1,1,0]}},{delay:[1e3,4e3,1,2],dt:[50,[100,200],100,[10,400,0],50,[100,200],100],vs:{eyeBlinkLeft:[1,1,0,0,1,1,0],eyeBlinkRight:[1,1,0,0,1,1,0]}}]},this.animMoods={neutral:{baseline:{eyesLookDown:0},speech:{deltaRate:0,deltaPitch:0,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1200,500,1e3],vs:{chestInhale:[.5,.5,0]}},{name:"pose",alt:[{p:.5,delay:[5e3,3e4],vs:{pose:["side"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{p:.3,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{delay:[5e3,3e4],vs:{pose:["straight"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}}]},{name:"head",idle:{delay:[0,1e3],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.3,.3]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},happy:{baseline:{mouthSmile:.2,eyesLookDown:0},speech:{deltaRate:0,deltaPitch:.1,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1200,500,1e3],vs:{chestInhale:[.5,.5,0]}},{name:"pose",idle:{alt:[{p:.6,delay:[5e3,3e4],vs:{pose:["side"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{p:.2,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{p:.1,delay:[5e3,3e4],vs:{pose:["straight"]}},{delay:[5e3,1e4],vs:{pose:["wide"]}},{delay:[1e3,3e3],vs:{pose:["turn"]}}]},speaking:{alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{p:.4,delay:[5e3,3e4],vs:{pose:["straight"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{delay:[5e3,2e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}}]}},{name:"head",idle:{dt:[[1e3,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.3,.3]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthLeft:[[0,.3,2]],mouthSmile:[[0,.2,3]],mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},angry:{baseline:{eyesLookDown:.1,browDownLeft:.6,browDownRight:.6,jawForward:.3,mouthFrownLeft:.7,mouthFrownRight:.7,mouthRollLower:.2,mouthShrugLower:.3,handFistLeft:1,handFistRight:1},speech:{deltaRate:-.2,deltaPitch:.2,deltaVolume:0},anims:[{name:"breathing",delay:500,dt:[1e3,500,1e3],vs:{chestInhale:[.7,.7,0]}},{name:"pose",alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.4,delay:[5e3,3e4],vs:{pose:["straight"]}},{p:.2,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}}]},{name:"head",idle:{delay:[100,500],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.2,.2]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},sad:{baseline:{eyesLookDown:.2,browDownRight:.1,browInnerUp:.6,browOuterUpRight:.2,eyeSquintLeft:.7,eyeSquintRight:.7,mouthFrownLeft:.8,mouthFrownRight:.8,mouthLeft:.2,mouthPucker:.5,mouthRollLower:.2,mouthRollUpper:.2,mouthShrugLower:.2,mouthShrugUpper:.2,mouthStretchLeft:.4},speech:{deltaRate:-.2,deltaPitch:-.2,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1e3,500,1e3],vs:{chestInhale:[.3,.3,0]}},{name:"pose",alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.4,delay:[5e3,3e4],vs:{pose:["straight"]}},{delay:[5e3,2e4],vs:{pose:["side"]},full:{delay:[5e3,2e4],vs:{pose:["oneknee"]}}}]},{name:"head",idle:{delay:[100,500],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.2,.2]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},fear:{baseline:{browInnerUp:.7,eyeSquintLeft:.5,eyeSquintRight:.5,eyeWideLeft:.6,eyeWideRight:.6,mouthClose:.1,mouthFunnel:.3,mouthShrugLower:.5,mouthShrugUpper:.5},speech:{deltaRate:-.2,deltaPitch:0,deltaVolume:0},anims:[{name:"breathing",delay:500,dt:[1e3,500,1e3],vs:{chestInhale:[.7,.7,0]}},{name:"pose",alt:[{p:.8,delay:[5e3,3e4],vs:{pose:["side"]}},{delay:[5e3,3e4],vs:{pose:["straight"]}},{delay:[5e3,2e4],vs:{pose:["wide"]}},{delay:[5e3,2e4],vs:{pose:["side"]},full:{delay:[5e3,2e4],vs:{pose:["oneknee"]}}}]},{name:"head",idle:{delay:[100,500],dt:[[200,3e3]],vs:{bodyRotateX:[[-.06,.12]],bodyRotateY:[[-.7,.7]],bodyRotateZ:[[-.1,.1]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},disgust:{baseline:{browDownLeft:.7,browDownRight:.1,browInnerUp:.3,eyeSquintLeft:1,eyeSquintRight:1,eyeWideLeft:.5,eyeWideRight:.5,eyesRotateX:.05,mouthLeft:.4,mouthPressLeft:.3,mouthRollLower:.3,mouthShrugLower:.3,mouthShrugUpper:.8,mouthUpperUpLeft:.3,noseSneerLeft:1,noseSneerRight:.7},speech:{deltaRate:-.2,deltaPitch:0,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1e3,500,1e3],vs:{chestInhale:[.5,.5,0]}},{name:"pose",alt:[{delay:[5e3,2e4],vs:{pose:["side"]}}]},{name:"head",idle:{delay:[100,500],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.2,.2]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},love:{baseline:{browInnerUp:.4,browOuterUpLeft:.2,browOuterUpRight:.2,mouthSmile:.2,eyeBlinkLeft:.6,eyeBlinkRight:.6,eyeWideLeft:.7,eyeWideRight:.7,bodyRotateX:.1,mouthDimpleLeft:.1,mouthDimpleRight:.1,mouthPressLeft:.2,mouthShrugUpper:.2,mouthUpperUpLeft:.1,mouthUpperUpRight:.1},speech:{deltaRate:-.1,deltaPitch:-.7,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1500,500,1500],vs:{chestInhale:[.8,.8,0]}},{name:"pose",alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.2,delay:[5e3,3e4],vs:{pose:["straight"]}},{p:.2,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["side"]}}},{delay:[5e3,1e4],vs:{pose:["side"]},full:{delay:[5e3,1e4],vs:{pose:["kneel"]}}},{delay:[1e3,3e3],vs:{pose:["turn"]},M:{delay:[1e3,3e3],vs:{pose:["wide"]}}},{delay:[1e3,3e3],vs:{pose:["back"]},M:{delay:[1e3,3e3],vs:{pose:["wide"]}}},{delay:[5e3,2e4],vs:{pose:["side"]},M:{delay:[5e3,2e4],vs:{pose:["side"]}},full:{delay:[5e3,2e4],vs:{pose:["bend"]}}},{delay:[1e3,3e3],vs:{pose:["side"]},full:{delay:[5e3,1e4],vs:{pose:["oneknee"]}}}]},{name:"head",idle:{dt:[[1e3,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.3,.3]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.deepCopy(this.animTemplateBlink,r=>{r.alt[0].delay[0]=r.alt[1].delay[0]=2e3}),{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthLeft:[[0,.3,2]],mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[500,1e3],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[.3,.6,2]],browOuterUpLeft:[[.1,.3,2]],browOuterUpRight:[[.1,.3,2]]}}]},sleep:{baseline:{eyeBlinkLeft:1,eyeBlinkRight:1,eyesClosed:.6},speech:{deltaRate:0,deltaPitch:-.2,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1e3,500,1e3],vs:{chestInhale:[.6,.6,0]}},{name:"pose",alt:[{delay:[5e3,2e4],vs:{pose:["side"]}}]},{name:"head",delay:[1e3,5e3],dt:[[2e3,1e4]],vs:{bodyRotateX:[[0,.4]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.04,.04]]}},{name:"eyes",delay:10010,dt:[],vs:{}},{name:"blink",delay:10020,dt:[],vs:{}},{name:"mouth",delay:10030,dt:[],vs:{}},{name:"misc",delay:10040,dt:[],vs:{}}]}},this.moodName=this.opt.avatarMood||"neutral",this.mood=this.animMoods[this.moodName],this.mood||(this.moodName="neutral",this.mood=this.animMoods.neutral),this.animEmojis={"😐":{dt:[300,2e3],rescale:[0,1],vs:{pose:["straight"],browInnerUp:[.4],eyeWideLeft:[.7],eyeWideRight:[.7],mouthPressLeft:[.6],mouthPressRight:[.6],mouthRollLower:[.3],mouthStretchLeft:[1],mouthStretchRight:[1]}},"😶":{link:"😐"},"😏":{dt:[300,2e3],rescale:[0,1],vs:{eyeContact:[0],browDownRight:[.1],browInnerUp:[.7],browOuterUpRight:[.2],eyeLookInRight:[.7],eyeLookOutLeft:[.7],eyeSquintLeft:[1],eyeSquintRight:[.8],eyesRotateY:[.7],mouthLeft:[.4],mouthPucker:[.4],mouthShrugLower:[.3],mouthShrugUpper:[.2],mouthSmile:[.2],mouthSmileLeft:[.4],mouthSmileRight:[.2],mouthStretchLeft:[.5],mouthUpperUpLeft:[.6],noseSneerLeft:[.7]}},"🙂":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5]}},"🙃":{link:"🙂"},"😊":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.6],eyeSquintLeft:[1],eyeSquintRight:[1],mouthSmile:[.7],noseSneerLeft:[.7],noseSneerRight:[.7]}},"😇":{link:"😊"},"😀":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.6],jawOpen:[.1],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😃":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.6],eyeWideLeft:[.7],eyeWideRight:[.7],jawOpen:[.1],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😄":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],jawOpen:[.2],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😁":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],jawOpen:[.3],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthPressLeft:[.5],mouthPressRight:[.5],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😆":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.6],jawOpen:[.3],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthPressLeft:[.5],mouthPressRight:[.5],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😝":{dt:[300,100,1500,500,500],rescale:[0,0,1,0,0],vs:{browInnerUp:[.8],eyesClosed:[1],jawOpen:[.7],mouthFunnel:[.5],mouthSmile:[1],tongueOut:[0,1,1,0]}},"😋":{link:"😝"},"😛":{link:"😝"},"😛":{link:"😝"},"😜":{link:"😝"},"🤪":{link:"😝"},"😂":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.6],jawOpen:[.3],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthPressLeft:[.5],mouthPressRight:[.5],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"🤣":{link:"😂"},"😅":{link:"😂"},"😉":{dt:[500,200,500,500],rescale:[0,0,0,1],vs:{mouthSmile:[.5],mouthOpen:[.2],mouthSmileLeft:[0,.5,0],eyeBlinkLeft:[0,.7,0],eyeBlinkRight:[0,0,0],bodyRotateX:[.05,.05,.05,0],bodyRotateZ:[-.05,-.05,-.05,0],browDownLeft:[0,.7,0],cheekSquintLeft:[0,.7,0],eyeSquintLeft:[0,1,0],eyesClosed:[0]}},"😭":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[1],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.1],jawOpen:[0],mouthFrownLeft:[1],mouthFrownRight:[1],mouthOpen:[.5],mouthPucker:[.5],mouthUpperUpLeft:[.6],mouthUpperUpRight:[.6]}},"🥺":{dt:[1e3,1e3],rescale:[0,1],vs:{browDownLeft:[.2],browDownRight:[.2],browInnerUp:[1],eyeWideLeft:[.9],eyeWideRight:[.9],eyesClosed:[.1],mouthClose:[.2],mouthFrownLeft:[1],mouthFrownRight:[1],mouthPressLeft:[.4],mouthPressRight:[.4],mouthPucker:[1],mouthRollLower:[.6],mouthRollUpper:[.2],mouthUpperUpLeft:[.8],mouthUpperUpRight:[.8]}},"😞":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[.7],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.5],bodyRotateX:[.3],mouthClose:[.2],mouthFrownLeft:[1],mouthFrownRight:[1],mouthPucker:[1],mouthRollLower:[1],mouthShrugLower:[.2],mouthUpperUpLeft:[.8],mouthUpperUpRight:[.8]}},"😔":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[1],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.5],bodyRotateX:[.3],mouthClose:[.2],mouthFrownLeft:[1],mouthFrownRight:[1],mouthPressLeft:[.4],mouthPressRight:[.4],mouthPucker:[1],mouthRollLower:[.6],mouthRollUpper:[.2],mouthUpperUpLeft:[.8],mouthUpperUpRight:[.8]}},"😳":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[1],eyeWideLeft:[.5],eyeWideRight:[.5],eyesRotateY:[.05],eyesRotateX:[.05],mouthClose:[.2],mouthFunnel:[.5],mouthPucker:[.4],mouthRollLower:[.4],mouthRollUpper:[.4]}},"☹️":{dt:[500,1500],rescale:[0,1],vs:{mouthFrownLeft:[1],mouthFrownRight:[1],mouthPucker:[.1],mouthRollLower:[.8]}},"😚":{dt:[500,1e3,1e3],rescale:[0,1,0],vs:{browInnerUp:[.6],eyeBlinkLeft:[1],eyeBlinkRight:[1],eyeSquintLeft:[1],eyeSquintRight:[1],mouthPucker:[0,.5],noseSneerLeft:[0,.7],noseSneerRight:[0,.7],viseme_U:[0,1]}},"😘":{dt:[500,500,200,500],rescale:[0,0,0,1],vs:{browInnerUp:[.6],eyeBlinkLeft:[0,0,1,0],eyeBlinkRight:[0],eyesRotateY:[0],bodyRotateY:[0],bodyRotateX:[0,.05,.05,0],bodyRotateZ:[0,-.05,-.05,0],eyeSquintLeft:[1],eyeSquintRight:[1],mouthPucker:[0,.5,0],noseSneerLeft:[0,.7],noseSneerRight:[.7],viseme_U:[0,1]}},"🥰":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[.6],eyeSquintLeft:[1],eyeSquintRight:[1],mouthSmile:[.7],noseSneerLeft:[.7],noseSneerRight:[.7]}},"😍":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[.6],jawOpen:[.1],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"🤩":{link:"😍"},"😡":{dt:[1e3,1500],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],eyesLookUp:[.2],jawForward:[.3],mouthFrownLeft:[1],mouthFrownRight:[1],bodyRotateX:[.15]}},"😠":{dt:[1e3,1500],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],eyesLookUp:[.2],jawForward:[.3],mouthFrownLeft:[1],mouthFrownRight:[1],bodyRotateX:[.15]}},"🤬":{link:"😠"},"😒":{dt:[1e3,1e3],rescale:[0,1],vs:{eyeContact:[0],browDownRight:[.1],browInnerUp:[.7],browOuterUpRight:[.2],eyeLookInRight:[.7],eyeLookOutLeft:[.7],eyeSquintLeft:[1],eyeSquintRight:[.8],eyesRotateY:[.7],mouthFrownLeft:[1],mouthFrownRight:[1],mouthLeft:[.2],mouthPucker:[.5],mouthRollLower:[.2],mouthRollUpper:[.2],mouthShrugLower:[.2],mouthShrugUpper:[.2],mouthStretchLeft:[.5]}},"😱":{dt:[500,1500],rescale:[0,1],vs:{browInnerUp:[.8],eyeWideLeft:[.5],eyeWideRight:[.5],jawOpen:[.7],mouthFunnel:[.5]}},"😬":{dt:[500,1500],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],browInnerUp:[1],mouthDimpleLeft:[.5],mouthDimpleRight:[.5],mouthLowerDownLeft:[1],mouthLowerDownRight:[1],mouthPressLeft:[.4],mouthPressRight:[.4],mouthPucker:[.5],mouthSmile:[.1],mouthSmileLeft:[.2],mouthSmileRight:[.2],mouthStretchLeft:[1],mouthStretchRight:[1],mouthUpperUpLeft:[1],mouthUpperUpRight:[1]}},"🙄":{dt:[500,1500],rescale:[0,1],vs:{browInnerUp:[.8],eyeWideLeft:[1],eyeWideRight:[1],eyesRotateX:[-.8],bodyRotateX:[.15],mouthPucker:[.5],mouthRollLower:[.6],mouthRollUpper:[.5],mouthShrugLower:[0],mouthSmile:[0]}},"🤔":{dt:[500,1500],rescale:[0,1],vs:{browDownLeft:[1],browOuterUpRight:[1],eyeSquintLeft:[.6],mouthFrownLeft:[.7],mouthFrownRight:[.7],mouthLowerDownLeft:[.3],mouthPressRight:[.4],mouthPucker:[.1],mouthRight:[.5],mouthRollLower:[.5],mouthRollUpper:[.2],handRight:[{x:.1,y:.1,z:.1,d:1e3},{d:1e3}],handFistRight:[.1]}},"👀":{dt:[500,1500],rescale:[0,1],vs:{eyesRotateY:[-.8]}},"😴":{dt:[5e3,5e3],rescale:[0,1],vs:{eyeBlinkLeft:[1],eyeBlinkRight:[1],bodyRotateX:[.2],bodyRotateZ:[.1]}},"✋":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["handup",2,!0],null]}},"🤚":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["handup",2],null]}},"👋":{link:"✋"},"👍":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["thumbup",2],null]}},"👎":{dt:[300,2e3],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],eyesLookUp:[.2],jawForward:[.3],mouthFrownLeft:[1],mouthFrownRight:[1],bodyRotateX:[.15],gesture:[["thumbdown",2],null]}},"👌":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["ok",2],null]}},"🤷‍♂️":{dt:[1e3,1500],rescale:[0,1],vs:{gesture:[["shrug",2],null]}},"🤷‍♀️":{link:"🤷‍♂️"},"🤷":{link:"🤷‍♂️"},"🙏":{dt:[1500,300,1e3],rescale:[0,1,0],vs:{eyeBlinkLeft:[0,1],eyeBlinkRight:[0,1],bodyRotateX:[0],bodyRotateZ:[.1],gesture:[["namaste",2],null]}},yes:{dt:[[200,500],[200,500],[200,500],[200,500]],vs:{headMove:[0],headRotateX:[[.1,.2],.1,[.1,.2],0],headRotateZ:[[-.2,.2]]}},no:{dt:[[200,500],[200,500],[200,500],[200,500],[200,500]],vs:{headMove:[0],headRotateY:[[-.1,-.05],[.05,.1],[-.1,-.05],[.05,.1],0],headRotateZ:[[-.2,.2]]}}},this.mtAvatar={},this.mtCustoms=["handFistLeft","handFistRight","bodyRotateX","bodyRotateY","bodyRotateZ","headRotateX","headRotateY","headRotateZ","chestInhale"],this.mtEasingDefault=this.sigmoidFactory(5),this.mtAccDefault=.01,this.mtAccExceptions={eyeBlinkLeft:.1,eyeBlinkRight:.1,eyeLookOutLeft:.1,eyeLookInLeft:.1,eyeLookOutRight:.1,eyeLookInRight:.1},this.mtMaxVDefault=5,this.mtMaxVExceptions={bodyRotateX:1,bodyRotateY:1,bodyRotateZ:1},this.mtBaselineDefault=0,this.mtBaselineExceptions={bodyRotateX:null,bodyRotateY:null,bodyRotateZ:null,eyeLookOutLeft:null,eyeLookInLeft:null,eyeLookOutRight:null,eyeLookInRight:null,eyesLookDown:null,eyesLookUp:null},this.mtMinDefault=0,this.mtMinExceptions={bodyRotateX:-1,bodyRotateY:-1,bodyRotateZ:-1,headRotateX:-1,headRotateY:-1,headRotateZ:-1},this.mtMaxDefault=1,this.mtMaxExceptions={},this.mtLimits={eyeBlinkLeft:r=>Math.max(r,(this.mtAvatar.eyesLookDown.value+this.mtAvatar.browDownLeft.value)/2),eyeBlinkRight:r=>Math.max(r,(this.mtAvatar.eyesLookDown.value+this.mtAvatar.browDownRight.value)/2)},this.mtOnchange={eyesLookDown:()=>{this.mtAvatar.eyeBlinkLeft.needsUpdate=!0,this.mtAvatar.eyeBlinkRight.needsUpdate=!0},browDownLeft:()=>{this.mtAvatar.eyeBlinkLeft.needsUpdate=!0},browDownRight:()=>{this.mtAvatar.eyeBlinkRight.needsUpdate=!0}},this.mtRandomized=["mouthDimpleLeft","mouthDimpleRight","mouthLeft","mouthPressLeft","mouthPressRight","mouthStretchLeft","mouthStretchRight","mouthShrugLower","mouthShrugUpper","noseSneerLeft","noseSneerRight","mouthRollLower","mouthRollUpper","browDownLeft","browDownRight","browOuterUpLeft","browOuterUpRight","cheekPuff","cheekSquintLeft","cheekSquintRight"],this.mtExtras=[{key:"mouthOpen",mix:{jawOpen:.5}},{key:"mouthSmile",mix:{mouthSmileLeft:.8,mouthSmileRight:.8}},{key:"eyesClosed",mix:{eyeBlinkLeft:1,eyeBlinkRight:1}},{key:"eyesLookUp",mix:{eyeLookUpLeft:1,eyeLookUpRight:1}},{key:"eyesLookDown",mix:{eyeLookDownLeft:1,eyeLookDownRight:1}}],this.animQueue=[],this.animClips=[],this.animPoses=[],this.animFrameDur=1e3/this.opt.modelFPS,this.animClock=0,this.animSlowdownRate=1,this.animTimeLast=0,this.easing=this.sigmoidFactory(5),this.lipsync={},this.opt.lipsyncModules.forEach(r=>{this.lipsyncGetProcessor(r)}),this.visemeNames=["aa","E","I","O","U","PP","SS","TH","DD","FF","kk","nn","RR","CH","sil"],this.segmenter=new Intl.Segmenter("en",{granularity:"grapheme"}),this.initAudioGraph(),this.audioPlaylist=[],this.volumeFrequencyData=new Uint8Array(16),this.volumeMax=0,this.volumeHeadBase=0,this.volumeHeadTarget=0,this.volumeHeadCurrent=0,this.volumeHeadVelocity=.15,this.volumeHeadEasing=this.sigmoidFactory(3),this.isListening=!1,this.listeningAnalyzer=null,this.listeningActive=!1,this.listeningVolume=0,this.listeningSilenceThresholdLevel=this.opt.listeningSilenceThresholdLevel,this.listeningSilenceThresholdMs=this.opt.listeningSilenceThresholdMs,this.listeningSilenceDurationMax=this.opt.listeningSilenceDurationMax,this.listeningActiveThresholdLevel=this.opt.listeningActiveThresholdLevel,this.listeningActiveThresholdMs=this.opt.listeningActiveThresholdMs,this.listeningActiveDurationMax=this.opt.listeningActiveDurationMax,this.listeningTimer=0,this.listeningTimerTotal=0,this.dracoEnabled=this.opt.dracoEnabled,this.dracoDecoderPath=this.opt.dracoDecoderPath;const i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";this.b64Lookup=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let r=0;r<i.length;r++)this.b64Lookup[i.charCodeAt(r)]=r;if(this.stateName="idle",this.speechQueue=[],this.isSpeaking=!1,this.isListening=!1,this.opt.ttsEndpoint){let r=new Audio;if(r.canPlayType("audio/ogg"))this.ttsAudioEncoding="OGG-OPUS";else if(r.canPlayType("audio/mp3"))this.ttsAudioEncoding="MP3";else throw new Error("There was no support for either OGG or MP3 audio.")}if(this.isAvatarOnly=this.opt.avatarOnly,this.isAvatarOnly)this.scene=this.opt.avatarOnlyScene,this.camera=this.opt.avatarOnlyCamera;else{this.renderer=new x.WebGLRenderer({antialias:!0,alpha:!0}),this.renderer.setPixelRatio(this.opt.modelPixelRatio*window.devicePixelRatio),this.renderer.setSize(this.nodeAvatar.clientWidth,this.nodeAvatar.clientHeight),this.renderer.outputColorSpace=x.SRGBColorSpace,this.renderer.toneMapping=x.ACESFilmicToneMapping,this.renderer.shadowMap.enabled=!1,this.nodeAvatar.appendChild(this.renderer.domElement),this.camera=new x.PerspectiveCamera(10,this.nodeAvatar.clientWidth/this.nodeAvatar.clientHeight,.1,2e3),this.scene=new x.Scene,this.lightAmbient=new x.AmbientLight(new x.Color(this.opt.lightAmbientColor),this.opt.lightAmbientIntensity),this.lightDirect=new x.DirectionalLight(new x.Color(this.opt.lightDirectColor),this.opt.lightDirectIntensity),this.lightSpot=new x.SpotLight(new x.Color(this.opt.lightSpotColor),this.opt.lightSpotIntensity,0,this.opt.lightSpotDispersion),this.setLighting(this.opt);const r=new x.PMREMGenerator(this.renderer);r.compileEquirectangularShader(),this.scene.environment=r.fromScene(new tt.RoomEnvironment).texture,this.resizeobserver=new ResizeObserver(this.onResize.bind(this)),this.resizeobserver.observe(this.nodeAvatar),this.controls=new $e.OrbitControls(this.camera,this.renderer.domElement),this.controls.enableZoom=this.opt.cameraZoomEnable,this.controls.enableRotate=this.opt.cameraRotateEnable,this.controls.enablePan=this.opt.cameraPanEnable,this.controls.minDistance=2,this.controls.maxDistance=2e3,this.controls.autoRotateSpeed=0,this.controls.autoRotate=!1,this.controls.update(),this.cameraClock=null}this.ikMesh=new x.SkinnedMesh;const s={LeftShoulder:null,LeftArm:"LeftShoulder",LeftForeArm:"LeftArm",LeftHand:"LeftForeArm",LeftHandMiddle1:"LeftHand",RightShoulder:null,RightArm:"RightShoulder",RightForeArm:"RightArm",RightHand:"RightForeArm",RightHandMiddle1:"RightHand"},o=[];Object.entries(s).forEach((r,u)=>{const a=new x.Bone;a.name=r[0],r[1]?this.ikMesh.getObjectByName(r[1]).add(a):this.ikMesh.add(a),o.push(a)}),this.ikMesh.bind(new x.Skeleton(o)),this.dynamicbones=new rt,this.isStreaming=!1,this.streamWorkletNode=null,this.streamAudioStartTime=null,this.streamWaitForAudioChunks=!0,this.streamLipsyncLang=null,this.streamLipsyncType="visemes",this.streamLipsyncQueue=[]}initAudioGraph(t=null){if(this.audioCtx&&this.audioCtx.state!=="closed"&&this.audioCtx.close(),t?this.audioCtx=new AudioContext({sampleRate:t}):this.audioCtx=new AudioContext,this.audioSpeechSource=this.audioCtx.createBufferSource(),this.audioBackgroundSource=this.audioCtx.createBufferSource(),this.audioBackgroundGainNode=this.audioCtx.createGain(),this.audioSpeechGainNode=this.audioCtx.createGain(),this.audioStreamGainNode=this.audioCtx.createGain(),this.audioAnalyzerNode=this.audioCtx.createAnalyser(),this.audioAnalyzerNode.fftSize=256,this.audioAnalyzerNode.smoothingTimeConstant=.1,this.audioAnalyzerNode.minDecibels=-70,this.audioAnalyzerNode.maxDecibels=-10,this.audioAnalyzer=new lt(this.audioCtx),this.audioReverbNode=this.audioCtx.createConvolver(),this.audioBackgroundGainNode.connect(this.audioReverbNode),this.audioAnalyzerNode.connect(this.audioSpeechGainNode),this.audioSpeechGainNode.connect(this.audioReverbNode),this.audioStreamGainNode.connect(this.audioReverbNode),this.audioReverbNode.connect(this.audioCtx.destination),this.setReverb(this.currentReverb||null),this.setMixerGain(this.opt.mixerGainSpeech,this.opt.mixerGainBackground),this.workletLoaded=!1,this.streamWorkletNode){try{this.streamWorkletNode.port.postMessage({type:"stop"}),this.streamWorkletNode.disconnect(),this.isStreaming=!1}catch(e){console.error("Error disconnecting streamWorkletNode:",e)}this.streamWorkletNode=null}}valueFn(t){return typeof t=="function"?t():t}deepCopy(t,e=null){const n=JSON.parse(JSON.stringify(t));return e&&typeof e=="function"&&e(n),n}b64ToArrayBuffer(t){let e=3*t.length/4;t[t.length-1]==="="&&(e--,t[t.length-2]==="="&&e--);const n=new ArrayBuffer(e),i=new Uint8Array(n);let s,o=0,r,u,a,c;for(s=0;s<t.length;s+=4)r=this.b64Lookup[t.charCodeAt(s)],u=this.b64Lookup[t.charCodeAt(s+1)],a=this.b64Lookup[t.charCodeAt(s+2)],c=this.b64Lookup[t.charCodeAt(s+3)],i[o++]=r<<2|u>>4,i[o++]=(u&15)<<4|a>>2,i[o++]=(a&3)<<6|c&63;return n}concatArrayBuffers(t){if(t.length===1)return t[0];let e=0;for(let o=0;o<t.length;o++)e+=t[o].byteLength;let n=new ArrayBuffer(e),i=new Uint8Array(n),s=0;for(let o=0;o<t.length;o++)i.set(new Uint8Array(t[o]),s),s+=t[o].byteLength;return n}pcmToAudioBuffer(t){const e=new Int16Array(t),n=new Float32Array(e.length);for(let s=0;s<e.length;s++)n[s]=e[s]>=32768?-(65536-e[s])/32768:e[s]/32767;const i=this.audioCtx.createBuffer(1,n.length,this.opt.pcmSampleRate);return i.copyToChannel(n,0,0),i}propsToThreeObjects(t){const e={};for(let[n,i]of Object.entries(t)){const s=n.split(".");let o=Array.isArray(i.x)?this.gaussianRandom(...i.x):i.x,r=Array.isArray(i.y)?this.gaussianRandom(...i.y):i.y,u=Array.isArray(i.z)?this.gaussianRandom(...i.z):i.z;s[1]==="position"||s[1]==="scale"?e[n]=new x.Vector3(o,r,u):s[1]==="rotation"?(n=s[0]+".quaternion",e[n]=new x.Quaternion().setFromEuler(new x.Euler(o,r,u,"XYZ")).normalize()):s[1]==="quaternion"&&(e[n]=new x.Quaternion(o,r,u,i.w).normalize())}return e}clearThree(t){for(;t.children.length;)this.clearThree(t.children[0]),t.remove(t.children[0]);t.geometry&&t.geometry.dispose(),t.material&&(Object.keys(t.material).forEach(e=>{t.material[e]&&t.material[e]!==null&&typeof t.material[e].dispose=="function"&&t.material[e].dispose()}),t.material.dispose())}addMixedMorphTarget(t,e,n,i=!1){t.forEach(s=>{if(!i&&s.morphTargetDictionary.hasOwnProperty(e))return;const o=s.geometry;let r=null,u=null;for(const[a,c]of Object.entries(n))if(s.morphTargetDictionary.hasOwnProperty(a)){const l=s.morphTargetDictionary[a],d=o.morphAttributes.position[l],h=o.morphAttributes.normal?.[l];r||(r=new x.Float32BufferAttribute(d.count*3,3),h&&(u=new x.Float32BufferAttribute(d.count*3,3)));for(let p=0;p<d.count;p++){const v=r.getX(p)+d.getX(p)*c,y=r.getY(p)+d.getY(p)*c,w=r.getZ(p)+d.getZ(p)*c;r.setXYZ(p,v,y,w)}if(h)for(let p=0;p<d.count;p++){const v=u.getX(p)+h.getX(p)*c,y=u.getY(p)+h.getY(p)*c,w=u.getZ(p)+h.getZ(p)*c;u.setXYZ(p,v,y,w)}}if(r){o.morphAttributes.position.push(r),u&&o.morphAttributes.normal.push(u);const a=o.morphAttributes.position.length-1;s.morphTargetInfluences[a]=0,s.morphTargetDictionary[e]=a}})}async showAvatar(t,e=null){if(!t||!t.hasOwnProperty("url"))throw new Error("Invalid parameter. The avatar must have at least 'url' specified.");const n=new Je.GLTFLoader;if(this.dracoEnabled){const a=new et.DRACOLoader;a.setDecoderPath(this.dracoDecoderPath),n.setDRACOLoader(a)}let i=await n.loadAsync(t.url,e);const s=[this.opt.modelRoot];if(this.posePropNames.forEach(a=>s.push(a.split(".")[0])),s.forEach(a=>{if(!i.scene.getObjectByName(a))throw new Error("Avatar object "+a+" not found")}),this.stop(),this.avatar=t,this.bodyMovement=t.bodyMovement||"idle",this.movementIntensity=t.movementIntensity||.5,this.showFullAvatar=t.showFullAvatar||!1,this.fbxAnimationLoader=null,this.dynamicbones.dispose(),this.mixer=null,this.isAvatarOnly?this.armature&&this.clearThree(this.armature):this.armature&&this.clearThree(this.scene),this.armature=i.scene.getObjectByName(this.opt.modelRoot),this.armature.scale.setScalar(1),this.animations=i.animations,this.userData=i.userData,this.morphs=[],this.armature.traverse(a=>{a.morphTargetInfluences&&a.morphTargetInfluences.length&&a.morphTargetDictionary&&this.morphs.push(a),a.frustumCulled=!1}),this.morphs.length===0)throw new Error("Blend shapes not found");const o=new Set(this.mtCustoms);this.morphs.forEach(a=>{Object.keys(a.morphTargetDictionary).forEach(c=>o.add(c))}),this.mtExtras.forEach(a=>{o.has(a.key)||(this.addMixedMorphTarget(this.morphs,a.key,a.mix),o.add(a.key))});const r={};if(o.forEach(a=>{r[a]={fixed:null,realtime:null,system:null,systemd:null,newvalue:null,ref:null,min:this.mtMinExceptions.hasOwnProperty(a)?this.mtMinExceptions[a]:this.mtMinDefault,max:this.mtMaxExceptions.hasOwnProperty(a)?this.mtMaxExceptions[a]:this.mtMaxDefault,easing:this.mtEasingDefault,base:null,v:0,needsUpdate:!0,acc:(this.mtAccExceptions.hasOwnProperty(a)?this.mtAccExceptions[a]:this.mtAccDefault)/1e3,maxv:(this.mtMaxVExceptions.hasOwnProperty(a)?this.mtMaxVExceptions[a]:this.mtMaxVDefault)/1e3,limit:this.mtLimits.hasOwnProperty(a)?this.mtLimits[a]:null,onchange:this.mtOnchange.hasOwnProperty(a)?this.mtOnchange[a]:null,baseline:this.avatar.baseline?.hasOwnProperty(a)?this.avatar.baseline[a]:this.mtBaselineExceptions.hasOwnProperty(a)?this.mtBaselineExceptions[a]:this.mtBaselineDefault,ms:[],is:[]},r[a].value=r[a].baseline,r[a].applied=r[a].baseline;const c=this.mtAvatar[a];c&&["fixed","system","systemd","realtime","base","v","value","applied"].forEach(l=>{r[a][l]=c[l]}),this.morphs.forEach(l=>{const d=l.morphTargetDictionary[a];d!==void 0&&(r[a].ms.push(l.morphTargetInfluences),r[a].is.push(d),l.morphTargetInfluences[d]=r[a].applied)})}),this.mtAvatar=r,this.poseAvatar={props:{}},this.posePropNames.forEach(a=>{const c=a.split("."),l=this.armature.getObjectByName(c[0]);this.poseAvatar.props[a]=l[c[1]],this.poseBase.props.hasOwnProperty(a)?this.poseAvatar.props[a].copy(this.poseBase.props[a]):this.poseBase.props[a]=this.poseAvatar.props[a].clone(),this.poseDelta.props.hasOwnProperty(a)&&!this.poseTarget.props.hasOwnProperty(a)&&(this.poseTarget.props[a]=this.poseAvatar.props[a].clone()),this.poseTarget.props[a].t=this.animClock,this.poseTarget.props[a].d=2e3}),this.ikMesh.traverse(a=>{a.isBone&&a.position.copy(this.armature.getObjectByName(a.name).position)}),this.isAvatarOnly?this.scene&&this.scene.add(this.armature):(this.scene.add(i.scene),this.scene.add(this.lightAmbient),this.scene.add(this.lightDirect),this.scene.add(this.lightSpot),this.lightSpot.target=this.armature.getObjectByName("Head")),t.hasOwnProperty("modelDynamicBones"))try{this.dynamicbones.setup(this.scene,this.armature,t.modelDynamicBones)}catch(a){console.error("Dynamic bones setup failed: "+a)}this.objectLeftToeBase=this.armature.getObjectByName("LeftToeBase"),this.objectRightToeBase=this.armature.getObjectByName("RightToeBase"),this.objectLeftEye=this.armature.getObjectByName("LeftEye"),this.objectRightEye=this.armature.getObjectByName("RightEye"),this.objectLeftArm=this.armature.getObjectByName("LeftArm"),this.objectRightArm=this.armature.getObjectByName("RightArm"),this.objectHips=this.armature.getObjectByName("Hips"),this.objectHead=this.armature.getObjectByName("Head"),this.objectNeck=this.armature.getObjectByName("Neck");const u=new x.Vector3;this.objectLeftEye.getWorldPosition(u),this.avatarHeight=u.y+.2,this.viewName||this.setView(this.opt.cameraView),this.setMood(this.avatar.avatarMood||this.moodName||this.opt.avatarMood),this.avatar.body==="M"&&this.poseTemplates.wide&&(this.poseName="wide",this.setPoseFromTemplate(this.poseTemplates.wide,0),console.log("Set initial male-appropriate pose: wide")),this.initializeFBXAnimationLoader(),this.bodyMovement&&this.bodyMovement!=="idle"&&this.applyBodyMovementAnimation(),this.start()}getViewNames(){return["full","mid","upper","head"]}getView(){return this.viewName}setView(t,e=null){if(t=t||this.viewName,t!=="full"&&t!=="upper"&&t!=="head"&&t!=="mid")return;if(!this.armature){this.opt.cameraView=t;return}if(this.viewName=t||this.viewName,e=e||{},this.isAvatarOnly)return;const n=e.hasOwnProperty("cameraX")?e.cameraX:this.opt.cameraX,i=e.hasOwnProperty("cameraY")?e.cameraY:this.opt.cameraY,s=e.hasOwnProperty("cameraDistance")?e.cameraDistance:this.opt.cameraDistance,o=e.hasOwnProperty("cameraRotateX")?e.cameraRotateX:this.opt.cameraRotateX,r=e.hasOwnProperty("cameraRotateY")?e.cameraRotateY:this.opt.cameraRotateY,u=this.camera.fov*(Math.PI/180);let a=-n*Math.tan(u/2),c=(1-i)*Math.tan(u/2),l=s;switch(this.viewName){case"head":l+=2,c=c*l+4*this.avatarHeight/5;break;case"upper":l+=4.5,c=c*l+2*this.avatarHeight/3;break;case"mid":l+=8,c=c*l+this.avatarHeight/3;break;default:l+=12,c=c*l}a=a*l,this.controlsEnd=new x.Vector3(a,c,0),this.cameraEnd=new x.Vector3(a,c,l).applyEuler(new x.Euler(o,r,0)),this.cameraClock===null&&(this.controls.target.copy(this.controlsEnd),this.camera.position.copy(this.cameraEnd)),this.controlsStart=this.controls.target.clone(),this.cameraStart=this.camera.position.clone(),this.cameraClock=0}setLighting(t){this.isAvatarOnly||(t=t||{},t.hasOwnProperty("lightAmbientColor")&&this.lightAmbient.color.set(new x.Color(t.lightAmbientColor)),t.hasOwnProperty("lightAmbientIntensity")&&(this.lightAmbient.intensity=t.lightAmbientIntensity,this.lightAmbient.visible=t.lightAmbientIntensity!==0),t.hasOwnProperty("lightDirectColor")&&this.lightDirect.color.set(new x.Color(t.lightDirectColor)),t.hasOwnProperty("lightDirectIntensity")&&(this.lightDirect.intensity=t.lightDirectIntensity,this.lightDirect.visible=t.lightDirectIntensity!==0),t.hasOwnProperty("lightDirectPhi")&&t.hasOwnProperty("lightDirectTheta")&&this.lightDirect.position.setFromSphericalCoords(2,t.lightDirectPhi,t.lightDirectTheta),t.hasOwnProperty("lightSpotColor")&&this.lightSpot.color.set(new x.Color(t.lightSpotColor)),t.hasOwnProperty("lightSpotIntensity")&&(this.lightSpot.intensity=t.lightSpotIntensity,this.lightSpot.visible=t.lightSpotIntensity!==0),t.hasOwnProperty("lightSpotPhi")&&t.hasOwnProperty("lightSpotTheta")&&(this.lightSpot.position.setFromSphericalCoords(2,t.lightSpotPhi,t.lightSpotTheta),this.lightSpot.position.add(new x.Vector3(0,1.5,0))),t.hasOwnProperty("lightSpotDispersion")&&(this.lightSpot.angle=t.lightSpotDispersion))}render(){this.isRunning&&!this.isAvatarOnly&&this.renderer&&this.renderer.render(this.scene,this.camera)}onResize(){!this.isAvatarOnly&&this.renderer&&(this.camera.aspect=this.nodeAvatar.clientWidth/this.nodeAvatar.clientHeight,this.camera.updateProjectionMatrix(),this.renderer.setSize(this.nodeAvatar.clientWidth,this.nodeAvatar.clientHeight),this.controls.update(),this.render())}updatePoseBase(t){for(const[e,n]of Object.entries(this.poseTarget.props)){const i=this.poseAvatar.props[e];if(i){let s=(t-n.t)/n.d;s>1||!this.poseBase.props.hasOwnProperty(e)?i.copy(n):i.isQuaternion?i.copy(this.poseBase.props[e].slerp(n,this.easing(s))):i.isVector3&&i.copy(this.poseBase.props[e].lerp(n,this.easing(s)))}}}applyShoulderAdjustment(){}applyShoulderAdjustmentToBones(){}updatePoseDelta(){for(const[t,e]of Object.entries(this.poseDelta.props)){if(e.x===0&&e.y===0&&e.z===0)continue;K.set(e.x,e.y,e.z);const n=this.poseAvatar.props[t];n.isQuaternion?(ie.setFromEuler(K),n.multiply(ie)):n.isVector3&&n.add(K)}}updateMorphTargets(t){for(let[e,n]of Object.entries(this.mtAvatar)){if(!n.needsUpdate)continue;let i=null,s=null;if(n.fixed!==null){if(i=n.fixed,n.system=null,n.systemd=null,n.newvalue=null,n.ref&&n.ref.hasOwnProperty(e)&&delete n.ref[e],n.ref=null,n.base=null,n.value===i){n.needsUpdate=!1;continue}}else n.realtime!==null?(n.ref=null,n.base=null,s=n.realtime):n.system!==null?(i=n.system,n.newvalue=null,n.ref&&n.ref.hasOwnProperty(e)&&delete n.ref[e],n.ref=null,n.base=null,n.systemd!==null?n.systemd===0?(i=null,n.system=null,n.systemd=null):(n.systemd-=t,n.systemd<0&&(n.systemd=0),n.value===i&&(i=null)):n.value===i&&(i=null,n.system=null)):n.newvalue!==null?(n.ref=null,n.base=null,s=n.newvalue,n.newvalue=null):n.base!==null?(i=n.base,n.ref=null,n.value===i&&(i=null,n.base=null,n.needsUpdate=!1)):(n.ref=null,n.baseline!==null&&n.value!==n.baseline?(i=n.baseline,n.base=n.baseline):n.needsUpdate=!1);if(i!==null){let o=i-n.value;o>=0?o<.005?(s=i,n.v=0):(n.v<n.maxv&&(n.v+=n.acc*t),n.v>=0?s=n.value+o*(1-Math.exp(-n.v*t)):s=n.value+n.v*t*(1-Math.exp(n.v*t))):o>-.005?(s=i,n.v=0):(n.v>-n.maxv&&(n.v-=n.acc*t),n.v>=0?s=n.value+n.v*t*(1-Math.exp(-n.v*t)):s=n.value+o*(1-Math.exp(n.v*t)))}if(n.limit!==null){if(s!==null&&s!==n.value&&(n.value=s,n.onchange!==null&&n.onchange(s)),s=n.limit(n.value),s===n.applied)continue}else{if(s===null||s===n.value)continue;n.value=s,n.onchange!==null&&n.onchange(s)}switch(n.applied=s,n.applied<n.min&&(n.applied=n.min),n.applied>n.max&&(n.applied=n.max),e){case"headRotateX":this.poseDelta.props["Head.quaternion"].x=n.applied+this.mtAvatar.bodyRotateX.applied;break;case"headRotateY":this.poseDelta.props["Head.quaternion"].y=n.applied+this.mtAvatar.bodyRotateY.applied;break;case"headRotateZ":this.poseDelta.props["Head.quaternion"].z=n.applied+this.mtAvatar.bodyRotateZ.applied;break;case"bodyRotateX":this.poseDelta.props["Head.quaternion"].x=n.applied+this.mtAvatar.headRotateX.applied,this.poseDelta.props["Spine1.quaternion"].x=n.applied/2,this.poseDelta.props["Spine.quaternion"].x=n.applied/8,this.poseDelta.props["Hips.quaternion"].x=n.applied/24;break;case"bodyRotateY":this.poseDelta.props["Head.quaternion"].y=n.applied+this.mtAvatar.headRotateY.applied,this.poseDelta.props["Spine1.quaternion"].y=n.applied/2,this.poseDelta.props["Spine.quaternion"].y=n.applied/2,this.poseDelta.props["Hips.quaternion"].y=n.applied/4,this.poseDelta.props["LeftUpLeg.quaternion"].y=n.applied/2,this.poseDelta.props["RightUpLeg.quaternion"].y=n.applied/2,this.poseDelta.props["LeftLeg.quaternion"].y=n.applied/4,this.poseDelta.props["RightLeg.quaternion"].y=n.applied/4;break;case"bodyRotateZ":this.poseDelta.props["Head.quaternion"].z=n.applied+this.mtAvatar.headRotateZ.applied,this.poseDelta.props["Spine1.quaternion"].z=n.applied/12,this.poseDelta.props["Spine.quaternion"].z=n.applied/12,this.poseDelta.props["Hips.quaternion"].z=n.applied/24;break;case"handFistLeft":case"handFistRight":const o=e.substring(8);["HandThumb","HandIndex","HandMiddle","HandRing","HandPinky"].forEach((c,l)=>{l===0?(this.poseDelta.props[o+c+"1.quaternion"].x=0,this.poseDelta.props[o+c+"2.quaternion"].z=(o==="Left"?-1:1)*n.applied,this.poseDelta.props[o+c+"3.quaternion"].z=(o==="Left"?-1:1)*n.applied):(this.poseDelta.props[o+c+"1.quaternion"].x=n.applied,this.poseDelta.props[o+c+"2.quaternion"].x=1.5*n.applied,this.poseDelta.props[o+c+"3.quaternion"].x=1.5*n.applied)});break;case"chestInhale":const r=n.applied/20,u={x:r,y:r/2,z:3*r},a={x:1/(1+r)-1,y:1/(1+r/2)-1,z:1/(1+3*r)-1};this.poseDelta.props["Spine1.scale"]=u,this.poseDelta.props["Neck.scale"]=a,this.poseDelta.props["LeftArm.scale"]=a,this.poseDelta.props["RightArm.scale"]=a;break;default:for(let c=0,l=n.ms.length;c<l;c++)n.ms[c][n.is[c]]=n.applied}}}getPoseString(t,e=1e3){let n="{";return Object.entries(t).forEach((i,s)=>{const o=i[0].split(".");if(o[1]==="position"||o[1]==="rotation"||o[1]==="quaternion"){const r=o[1]==="quaternion"?o[0]+".rotation":i[0],u=i[1].isQuaternion?new x.Euler().setFromQuaternion(i[1]):i[1];n+=(s?", ":"")+"'"+r+"':{",n+="x:"+Math.round(u.x*e)/e,n+=", y:"+Math.round(u.y*e)/e,n+=", z:"+Math.round(u.z*e)/e,n+="}"}}),n+="}",n}getPoseTemplateProp(t){const e=t.split(".");let n=e[0]+"."+(e[1]==="rotation"?"quaternion":e[1]);if(this.gesture&&this.gesture.hasOwnProperty(n))return this.gesture[n].clone();{let i=e[0]+"."+(e[1]==="quaternion"?"rotation":e[1]);this.poseWeightOnLeft||(i.startsWith("Left")?(i="Right"+i.substring(4),n="Right"+n.substring(4)):i.startsWith("Right")&&(i="Left"+i.substring(5),n="Left"+n.substring(5)));let s;if(this.poseTarget.template.props.hasOwnProperty(n)){const o={};o[n]=this.poseTarget.template.props[n],s=this.propsToThreeObjects(o)[n]}else if(this.poseTarget.template.props.hasOwnProperty(i)){const o={};o[i]=this.poseTarget.template.props[i],s=this.propsToThreeObjects(o)[n]}return s&&!this.poseWeightOnLeft&&s.isQuaternion&&(s.x*=-1,s.w*=-1),s}}mirrorPose(t){const e={};for(let[n,i]of Object.entries(t))i.isQuaternion&&(n.startsWith("Left")?n="Right"+n.substring(4):n.startsWith("Right")&&(n="Left"+n.substring(5)),i.x*=-1,i.w*=-1),e[n]=i.clone(),e[n].t=i.t,e[n].d=i.d;return e}poseFactory(t,e=2e3){const n={template:t,props:this.propsToThreeObjects(t.props)};for(const[i,s]of Object.entries(n.props)){if(this.opt.modelMovementFactor<1&&t.standing&&(i==="Hips.quaternion"||i==="Spine.quaternion"||i==="Spine1.quaternion"||i==="Spine2.quaternion"||i==="Neck.quaternion"||i==="LeftUpLeg.quaternion"||i==="LeftLeg.quaternion"||i==="RightUpLeg.quaternion"||i==="RightLeg.quaternion")){const o=this.poseStraight[i],r=s.angleTo(o);s.rotateTowards(o,(1-this.opt.modelMovementFactor)*r)}s.t=this.animClock,s.d=e}return n}setPoseFromTemplate(t,e=2e3){const n=t&&this.poseTarget&&this.poseTarget.template&&(this.poseTarget.template.standing&&t.lying||this.poseTarget.template.lying&&t.standing),i=t&&t===this.poseCurrentTemplate,s=this.poseWeightOnLeft;let o=n?1e3:e;if(n?(this.poseCurrentTemplate=this.poseTemplates.oneknee,setTimeout(()=>{this.setPoseFromTemplate(t,e)},o)):this.poseCurrentTemplate=t||this.poseCurrentTemplate,this.poseTarget=this.poseFactory(this.poseCurrentTemplate,o),this.poseWeightOnLeft=!0,(!i&&!s||i&&s)&&(this.poseTarget.props=this.mirrorPose(this.poseTarget.props),this.poseWeightOnLeft=!this.poseWeightOnLeft),this.gesture)for(let[r,u]of Object.entries(this.gesture))this.poseTarget.props.hasOwnProperty(r)&&(this.poseTarget.props[r].copy(u),this.poseTarget.props[r].t=u.t,this.poseTarget.props[r].d=u.d);Object.keys(this.poseDelta.props).forEach(r=>{this.poseTarget.props.hasOwnProperty(r)||(this.poseTarget.props[r]=this.poseBase.props[r].clone(),this.poseTarget.props[r].t=this.animClock,this.poseTarget.props[r].d=o)})}getValue(t){return this.mtAvatar[t]?.value}setValue(t,e,n=null){this.mtAvatar.hasOwnProperty(t)&&Object.assign(this.mtAvatar[t],{system:e,systemd:n,needsUpdate:!0})}getMoodNames(){return Object.keys(this.animMoods)}getMood(){return this.opt.avatarMood}setMood(t){if(t=(t||"").trim().toLowerCase(),!this.animMoods.hasOwnProperty(t))throw new Error("Unknown mood.");this.moodName=t,this.mood=this.animMoods[this.moodName];for(let e of Object.keys(this.mtAvatar)){let n=this.mtBaselineExceptions.hasOwnProperty(e)?this.mtBaselineExceptions[e]:this.mtBaselineDefault;this.mood.baseline.hasOwnProperty(e)?n=this.mood.baseline[e]:this.avatar.baseline?.hasOwnProperty(e)&&(n=this.avatar.baseline[e]),this.setBaselineValue(e,n)}this.mood.anims.forEach(e=>{let n=this.animQueue.findIndex(i=>i.template.name===e.name);n!==-1&&this.animQueue.splice(n,1),this.animQueue.push(this.animFactory(e,-1))})}async initializeFBXAnimationLoader(){try{const{FBXAnimationLoader:t}=await Promise.resolve().then(()=>require("./fbxAnimationLoader-CNrfhJRz.cjs"));this.fbxAnimationLoader=new t(this.armature),console.log("FBX Animation Loader initialized")}catch(t){console.warn("FBX Animation Loader not available:",t),this.fbxAnimationLoader=null}}setBodyMovement(t){this.bodyMovement=t,this.avatar&&(this.avatar.bodyMovement=t),console.log("Body movement set to:",t),t==="idle"&&this.unlockAvatarPosition(),this.applyBodyMovementAnimation()}async applyBodyMovementAnimation(){if(!this.armature||!this.animQueue){console.log("Avatar not ready for body movement animations");return}console.log("Avatar is running:",this.isRunning),console.log("Animation queue exists:",!!this.animQueue);const t=this.animQueue.length;this.animQueue=this.animQueue.filter(i=>!i.template.name.startsWith("bodyMovement"));const e=this.animQueue.length;if(console.log(`Filtered animation queue: ${t} -> ${e} animations`),this.bodyMovement==="idle"){this.fbxAnimationLoader&&this.fbxAnimationLoader.stopCurrentAnimation();return}if(this.fbxAnimationLoader)try{await this.fbxAnimationLoader.playGestureAnimation(this.bodyMovement,this.movementIntensity),console.log("Applied FBX body movement animation:",this.bodyMovement);return}catch(i){console.warn("FBX animation failed, falling back to code animation:",i)}const n=this.createBodyMovementAnimation(this.bodyMovement);if(console.log("Created movement animation:",n),n)try{const i=this.animFactory(n,!0);i&&i.ts&&i.ts.length>0?(this.animQueue.push(i),console.log("Applied code-based body movement animation:",this.bodyMovement),console.log("Animation queue length:",this.animQueue.length),console.log("Animation object:",i)):(console.error("Invalid animation object created for:",this.bodyMovement),console.error("Animation object:",i))}catch(i){console.error("Error creating body movement animation:",i)}}lockAvatarPosition(){if(!this.armature){console.warn("Cannot lock position: armature not available");return}this.originalPosition||(this.originalPosition={x:this.armature.position.x,y:this.armature.position.y,z:this.armature.position.z},console.log("Original position stored:",this.originalPosition)),this.lockedPosition={x:this.armature.position.x,y:this.armature.position.y,z:this.armature.position.z},console.log("Avatar position locked at current position:",this.lockedPosition)}unlockAvatarPosition(){this.armature&&this.originalPosition?(this.armature.position.set(this.originalPosition.x,this.originalPosition.y,this.originalPosition.z),console.log("Avatar position restored to original:",this.originalPosition)):this.armature&&(this.armature.position.set(0,0,0),console.log("Avatar position reset to center (0,0,0)")),this.lockedPosition=null,this.originalPosition=null,console.log("Avatar position unlocked")}maintainLockedPosition(){this.lockedPosition&&this.armature&&this.armature.position.set(this.lockedPosition.x,this.lockedPosition.y,this.lockedPosition.z)}createBodyMovementAnimation(t){const e=this.movementIntensity||.5,n={walking:{name:"bodyMovement_walking",delay:[500,2e3],dt:[800,1200],vs:{bodyRotateY:[-.1*e,.1*e,0],bodyRotateZ:[-.05*e,.05*e,0],bodyRotateX:[-.02*e,.02*e,0]}},prancing:{name:"bodyMovement_prancing",delay:[300,1e3],dt:[400,800],vs:{bodyRotateY:[-.15*e,.15*e,0],bodyRotateZ:[-.08*e,.08*e,0],bodyRotateX:[-.05*e,.05*e,0]}},gesturing:{name:"bodyMovement_gesturing",delay:[400,1500],dt:[600,1e3],vs:{bodyRotateY:[-.08*e,.08*e,0],bodyRotateZ:[-.03*e,.03*e,0]}},dancing:{name:"bodyMovement_dancing",delay:[200,600],dt:[400,800],vs:{bodyRotateY:[-.25*e,.25*e,0],bodyRotateZ:[-.15*e,.15*e,0],bodyRotateX:[-.1*e,.1*e,0]}},dancing2:{name:"bodyMovement_dancing2",delay:[150,500],dt:[300,700],vs:{bodyRotateY:[-.3*e,.3*e,0],bodyRotateZ:[-.2*e,.2*e,0],bodyRotateX:[-.12*e,.12*e,0]}},dancing3:{name:"bodyMovement_dancing3",delay:[100,400],dt:[200,600],vs:{bodyRotateY:[-.35*e,.35*e,0],bodyRotateZ:[-.25*e,.25*e,0],bodyRotateX:[-.15*e,.15*e,0]}},excited:{name:"bodyMovement_excited",delay:[200,600],dt:[300,700],vs:{bodyRotateY:[-.12*e,.12*e,0],bodyRotateZ:[-.06*e,.06*e,0],bodyRotateX:[-.04*e,.04*e,0]}},happy:{name:"bodyMovement_happy",delay:[300,800],dt:[500,1e3],vs:{bodyRotateY:[-.08*e,.08*e,0],bodyRotateZ:[-.04*e,.04*e,0],bodyRotateX:[-.02*e,.02*e,0]}},surprised:{name:"bodyMovement_surprised",delay:[100,300],dt:[200,500],vs:{bodyRotateY:[-.05*e,.05*e,0],bodyRotateZ:[-.03*e,.03*e,0],bodyRotateX:[-.01*e,.01*e,0]}},thinking:{name:"bodyMovement_thinking",delay:[800,2e3],dt:[1e3,1500],vs:{bodyRotateY:[-.06*e,.06*e,0],bodyRotateZ:[-.03*e,.03*e,0],bodyRotateX:[-.02*e,.02*e,0]}},nodding:{name:"bodyMovement_nodding",delay:[400,800],dt:[300,600],vs:{bodyRotateX:[-.1*e,.1*e,0],bodyRotateY:[-.02*e,.02*e,0]}},shaking:{name:"bodyMovement_shaking",delay:[200,400],dt:[150,300],vs:{bodyRotateY:[-.15*e,.15*e,0],bodyRotateZ:[-.05*e,.05*e,0]}},celebration:{name:"bodyMovement_celebration",delay:[100,300],dt:[200,500],vs:{bodyRotateY:[-.2*e,.2*e,0],bodyRotateZ:[-.1*e,.1*e,0],bodyRotateX:[-.08*e,.08*e,0]}},energetic:{name:"bodyMovement_energetic",delay:[150,400],dt:[250,500],vs:{bodyRotateY:[-.18*e,.18*e,0],bodyRotateZ:[-.12*e,.12*e,0],bodyRotateX:[-.08*e,.08*e,0]}},swaying:{name:"bodyMovement_swaying",delay:[600,1200],dt:[800,1e3],vs:{bodyRotateY:[-.1*e,.1*e,0],bodyRotateZ:[-.05*e,.05*e,0]}},bouncing:{name:"bodyMovement_bouncing",delay:[300,600],dt:[400,700],vs:{bodyRotateY:[-.05*e,.05*e,0]}}};if(t==="dancing"){const i=["dancing","dancing2","dancing3"],s=i[Math.floor(Math.random()*i.length)];return n[s]||n.dancing}return n[t]||null}playRandomDance(){const t=["dancing","dancing2","dancing3"],e=t[Math.floor(Math.random()*t.length)];this.setBodyMovement(e)}playReaction(t){["happy","surprised","thinking","nodding","shaking","celebration","energetic","swaying","bouncing"].includes(t)?(this.setBodyMovement(t),["surprised","nodding","shaking","celebration"].includes(t)&&setTimeout(()=>{this.setBodyMovement("idle")},3e3)):console.warn("Invalid reaction type:",t)}playCelebration(){this.playReaction("celebration"),setTimeout(()=>{this.playRandomDance()},2e3)}setMovementIntensity(t){this.movementIntensity=Math.max(0,Math.min(1,t)),this.avatar&&(this.avatar.movementIntensity=this.movementIntensity),console.log("Movement intensity set to:",this.movementIntensity),this.fbxAnimationLoader&&this.fbxAnimationLoader.setIntensity(this.movementIntensity),this.applyBodyMovementAnimation()}setShowFullAvatar(t){this.showFullAvatar=t,this.avatar&&(this.avatar.showFullAvatar=t),console.log("Show full avatar set to:",t),t&&this.viewName!=="full"?(console.log("Changing camera view to full"),this.setView("full")):!t&&this.viewName!=="upper"?(console.log("Changing camera view to upper"),this.setView("upper")):console.log("Camera view already set to:",this.viewName)}getMorphTargetNames(){return["eyesRotateX","eyesRotateY",...Object.keys(this.mtAvatar)].sort()}getBaselineValue(t){if(t==="eyesRotateY"){const e=this.getBaselineValue("eyeLookOutLeft");if(e===void 0)return;const n=this.getBaselineValue("eyeLookInLeft");return n===void 0||this.getBaselineValue("eyeLookOutRight")===void 0||this.getBaselineValue("eyeLookInRight")===void 0?void 0:e-n}else if(t==="eyesRotateX"){const e=this.getBaselineValue("eyesLookDown");if(e===void 0)return;const n=this.getBaselineValue("eyesLookUp");return n===void 0?void 0:e-n}else return this.mtAvatar[t]?.baseline}setBaselineValue(t,e){t==="eyesRotateY"?(this.setBaselineValue("eyeLookOutLeft",e===null?null:e>0?e:0),this.setBaselineValue("eyeLookInLeft",e===null?null:e>0?0:-e),this.setBaselineValue("eyeLookOutRight",e===null?null:e>0?0:-e),this.setBaselineValue("eyeLookInRight",e===null?null:e>0?e:0)):t==="eyesRotateX"?(this.setBaselineValue("eyesLookDown",e===null?null:e>0?e:0),this.setBaselineValue("eyesLookUp",e===null?null:e>0?0:-e)):this.mtAvatar.hasOwnProperty(t)&&Object.assign(this.mtAvatar[t],{base:null,baseline:e,needsUpdate:!0})}getFixedValue(t){if(t==="eyesRotateY"){const e=this.getFixedValue("eyeLookOutLeft");if(e===null)return null;const n=this.getFixedValue("eyeLookInLeft");return n===null||this.getFixedValue("eyeLookOutRight")===null||this.getFixedValue("eyeLookInRight")===null?null:e-n}else if(t==="eyesRotateX"){const e=this.getFixedValue("eyesLookDown");if(e===null)return null;const n=this.getFixedValue("eyesLookUp");return n===null?null:e-n}else return this.mtAvatar[t]?.fixed}setFixedValue(t,e,n=null){t==="eyesRotateY"?(this.setFixedValue("eyeLookOutLeft",e===null?null:e>0?e:0,n),this.setFixedValue("eyeLookInLeft",e===null?null:e>0?0:-e,n),this.setFixedValue("eyeLookOutRight",e===null?null:e>0?0:-e,n),this.setFixedValue("eyeLookInRight",e===null?null:e>0?e:0,n)):t==="eyesRotateX"?(this.setFixedValue("eyesLookDown",e===null?null:e>0?e:0,n),this.setFixedValue("eyesLookUp",e===null?null:e>0?0:-e,n)):this.mtAvatar.hasOwnProperty(t)&&Object.assign(this.mtAvatar[t],{fixed:e,needsUpdate:!0})}animFactory(t,e=!1,n=1,i=1,s=!1){const o={template:t,ts:[0],vs:{}};let r=t;for(;;)if(r.hasOwnProperty(this.stateName))(this.stateName==="speaking"||this.stateName==="idle")&&console.log("Selected state:",this.stateName,"for avatar body:",this.avatar?.body),r=r[this.stateName];else if(r.hasOwnProperty(this.moodName))r=r[this.moodName];else if(r.hasOwnProperty(this.poseName))r=r[this.poseName];else if(r.hasOwnProperty(this.viewName))r=r[this.viewName];else if(this.avatar&&this.avatar.body&&r.hasOwnProperty(this.avatar.body))console.log("Applying gender-specific override:",this.avatar.body,"for state:",this.stateName,"keys:",Object.keys(r)),r=r[this.avatar.body];else if(r.hasOwnProperty("alt")){let a=r.alt[0];if(r.alt.length>1){const c=Math.random();let l=0;for(let d=0;d<r.alt.length;d++){let h=this.valueFn(r.alt[d].p);if(l+=h===void 0?(1-l)/(r.alt.length-1-d):h,c<l){a=r.alt[d];break}}}r=a,this.avatar&&this.avatar.body&&r.hasOwnProperty(this.avatar.body)&&console.log("Found gender override in selected alternative:",this.avatar.body,"keys:",Object.keys(r));continue}else break;let u=this.valueFn(r.delay)||0;if(Array.isArray(u)&&(u=this.gaussianRandom(...u)),r.hasOwnProperty("dt"))r.dt.forEach((a,c)=>{let l=this.valueFn(a);Array.isArray(l)&&(l=this.gaussianRandom(...l)),o.ts[c+1]=o.ts[c]+l});else{let a=Object.values(r.vs).reduce((c,l)=>l.length>c?l.length:c,0);o.ts=Array(a+1).fill(0)}s?o.ts=o.ts.map(a=>u+a*n):o.ts=o.ts.map(a=>this.animClock+u+a*n),r.vs&&r.vs.pose&&console.log("Pose being selected from vs.pose:",r.vs.pose,"for avatar body:",this.avatar?.body);for(let[a,c]of Object.entries(r.vs)){const l=this.getBaselineValue(a),d=c.map(h=>(h=this.valueFn(h),h===null?null:typeof h=="function"?h:typeof h=="string"||h instanceof String?a==="pose"&&this.avatar&&this.avatar.body==="M"&&(h==="hip"||h==="side")?(console.log("Intercepting pose",h,"in animation factory, overriding to wide for male avatar"),"wide"):h.slice():Array.isArray(h)?a==="gesture"?h.slice():(l===void 0?0:l)+i*this.gaussianRandom(...h):typeof h=="boolean"?h:h instanceof Object&&h.constructor===Object?Object.assign({},h):(l===void 0?0:l)+i*h));a==="eyesRotateY"?(o.vs.eyeLookOutLeft=[null,...d.map(h=>h>0?h:0)],o.vs.eyeLookInLeft=[null,...d.map(h=>h>0?0:-h)],o.vs.eyeLookOutRight=[null,...d.map(h=>h>0?0:-h)],o.vs.eyeLookInRight=[null,...d.map(h=>h>0?h:0)]):a==="eyesRotateX"?(o.vs.eyesLookDown=[null,...d.map(h=>h>0?h:0)],o.vs.eyesLookUp=[null,...d.map(h=>h>0?0:-h)]):o.vs[a]=[null,...d]}for(let a of Object.keys(o.vs))for(;o.vs[a].length<=o.ts.length;)o.vs[a].push(o.vs[a][o.vs[a].length-1]);return t.hasOwnProperty("mood")&&(o.mood=this.valueFn(t.mood).slice()),e&&(o.loop=e),o}valueAnimationSeq(t,e,n,i,s,o=null){t=this.valueFn(t),e=this.valueFn(e),s<n&&(s=n),s>i&&(s=i);let r=(e-t)/(i-n);return o&&(r*=o((s-n)/(i-n))),r*s+(t-r*n)}gaussianRandom(t,e,n=1,i=5){let s=0;for(let o=0;o<i;o++)s+=Math.random();return t+Math.pow(s/i,n)*(e-t)}sigmoidFactory(t){function e(i){return 1/(1+Math.exp(-t*i))-.5}var n=.5/e(1);return function(i){return n*e(2*Math.max(Math.min(i,1),0)-1)+.5}}convertRange(t,e,n){return(t-e[0])*(n[1]-n[0])/(e[1]-e[0])+n[0]}animate(t){if(!this.isRunning)return;let e;if(this.isAvatarOnly)e=t;else{if(requestAnimationFrame(this.animate.bind(this)),e=t-this.animTimeLast,e<this.animFrameDur)return;this.animTimeLast=t}e=e/this.animSlowdownRate,this.animClock+=e,this.maintainLockedPosition();let n,i,s,o,r=0;if(this.stats&&this.stats.begin(),this.isListening){for(this.listeningAnalyzer.getByteFrequencyData(this.volumeFrequencyData),n=2,s=10;n<s;n++)this.volumeFrequencyData[n]>r&&(r=this.volumeFrequencyData[n]);this.listeningVolume=(this.listeningVolume+r)/2,this.listeningActive?(this.listeningTimerTotal+=e,this.listeningVolume<this.listeningSilenceThresholdLevel?(this.listeningTimer+=e,this.listeningTimer>this.listeningSilenceThresholdMs&&(this.listeningOnchange&&this.listeningOnchange("stop",this.listeningTimer),this.listeningActive=!1,this.listeningTimer=0,this.listeningTimerTotal=0)):this.listeningTimer*=.5,this.listeningTimerTotal>this.listeningActiveDurationMax&&(this.listeningOnchange&&this.listeningOnchange("maxactive"),this.listeningTimerTotal=0)):(this.listeningTimerTotal+=e,this.listeningVolume>this.listeningActiveThresholdLevel?(this.listeningTimer+=e,this.listeningTimer>this.listeningActiveThresholdMs&&(this.listeningOnchange&&this.listeningOnchange("start"),this.listeningActive=!0,this.listeningTimer=0,this.listeningTimerTotal=0)):this.listeningTimer*=.5,this.listeningTimerTotal>this.listeningSilenceDurationMax&&(this.listeningOnchange&&this.listeningOnchange("maxsilence"),this.listeningTimerTotal=0))}if(this.isSpeaking)for(r=0,this.audioAnalyzerNode.getByteFrequencyData(this.volumeFrequencyData),n=2,s=10;n<s;n++)this.volumeFrequencyData[n]>r&&(r=this.volumeFrequencyData[n]);let u=null,a=null;const c=[];for(n=0,s=this.animQueue.length;n<s;n++){const l=this.animQueue[n];if(!(!l||!l.ts||!l.ts.length||this.animClock<l.ts[0])){for(i=l.ndx||0,o=l.ts.length;i<o&&!(this.animClock<l.ts[i]);i++)for(let[d,h]of Object.entries(l.vs))if(this.mtAvatar.hasOwnProperty(d)){if(h[i+1]===null)continue;const p=this.mtAvatar[d];if(h[i]===null&&(h[i]=p.value),i===o-1)p.newvalue=h[i];else{p.newvalue=h[i+1];const v=l.ts[i+1]-l.ts[i];let y=1;v>1e-4&&(y=(this.animClock-l.ts[i])/v),y<1&&(p.easing&&(y=p.easing(y)),p.newvalue=(1-y)*h[i]+y*p.newvalue),p.ref&&p.ref!==l.vs&&p.ref.hasOwnProperty(d)&&delete p.ref[d],p.ref=l.vs}if(r)switch(d){case"viseme_aa":case"viseme_E":case"viseme_I":case"viseme_O":case"viseme_U":p.newvalue*=1+r/255-.5}p.needsUpdate=!0}else d==="eyeContact"&&h[i]!==null&&u!==!1?u=!!h[i]:d==="headMove"&&h[i]!==null&&a!==!1?h[i]===0?a=!1:(Math.random()<h[i]&&(a=!0),h[i]=null):h[i]!==null&&(c.push({mt:d,val:h[i]}),h[i]=null);i===o?(l.hasOwnProperty("mood")&&this.setMood(l.mood),l.loop?(o=this.isSpeaking&&(l.template.name==="head"||l.template.name==="eyes")?4:1,this.animQueue[n]=this.animFactory(l.template,l.loop>0?l.loop-1:l.loop,1,1/o)):(this.animQueue.splice(n--,1),s--)):l.ndx=i-1}}for(let l=0,d=c.length;l<d;l++)switch(i=c[l].val,c[l].mt){case"speak":this.speakText(i);break;case"subtitles":this.onSubtitles&&typeof this.onSubtitles=="function"&&this.onSubtitles(i);break;case"pose":this.avatar&&this.avatar.body==="M"&&(i==="hip"||i==="side")&&this.poseTemplates.wide&&(i="wide",console.log("Overriding pose",i==="hip"?"hip":"side","to wide for male avatar")),this.poseName=i,console.log("Setting pose to:",this.poseName,"for avatar body:",this.avatar?.body,"state:",this.stateName),this.setPoseFromTemplate(this.poseTemplates[this.poseName]);break;case"gesture":this.playGesture(...i);break;case"function":i&&typeof i=="function"&&i();break;case"moveto":Object.entries(i.props).forEach(h=>{h[1]?this.poseTarget.props[h[0]].copy(h[1]):this.poseTarget.props[h[0]].copy(this.getPoseTemplateProp(h[0])),this.poseTarget.props[h[0]].t=this.animClock,this.poseTarget.props[h[0]].d=h[1]&&h[1].d?h[1].d:h.duration||2e3});break;case"handLeft":this.ikSolve({iterations:20,root:"LeftShoulder",effector:"LeftHandMiddle1",links:[{link:"LeftHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5},{link:"LeftForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-.5,maxz:3},{link:"LeftArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},i.x?new x.Vector3(i.x,i.y,i.z):null,!0,i.d);break;case"handRight":this.ikSolve({iterations:20,root:"RightShoulder",effector:"RightHandMiddle1",links:[{link:"RightHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5,maxAngle:.1},{link:"RightForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-3,maxz:.5,maxAngle:.2},{link:"RightArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},i.x?new x.Vector3(i.x,i.y,i.z):null,!0,i.d);break}if((u||a)&&(K.setFromQuaternion(this.poseAvatar.props["Head.quaternion"]),K.x=Math.max(-.9,Math.min(.9,2*K.x-.5)),K.y=Math.max(-.9,Math.min(.9,-2.5*K.y)),u?(Object.assign(this.mtAvatar.eyesLookDown,{system:K.x<0?-K.x:0,needsUpdate:!0}),Object.assign(this.mtAvatar.eyesLookUp,{system:K.x<0?0:K.x,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookInLeft,{system:K.y<0?-K.y:0,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookOutLeft,{system:K.y<0?0:K.y,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookInRight,{system:K.y<0?0:K.y,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookOutRight,{system:K.y<0?-K.y:0,needsUpdate:!0}),a&&(n=-this.mtAvatar.bodyRotateY.value,i=this.gaussianRandom(-.2,.2),this.animQueue.push(this.animFactory({name:"headmove",dt:[[1e3,2e3],[1e3,2e3,1,2],[1e3,2e3],[1e3,2e3,1,2]],vs:{headRotateY:[n,n,0],headRotateX:[i,i,0],headRotateZ:[-n/4,-n/4,0]}})))):(n=this.mtAvatar.eyeLookInLeft.value-this.mtAvatar.eyeLookOutLeft.value,i=this.gaussianRandom(-.2,.2),this.animQueue.push(this.animFactory({name:"headmove",dt:[[1e3,2e3],[1e3,2e3,1,2],[1e3,2e3],[1e3,2e3,1,2]],vs:{headRotateY:[null,n,n,0],headRotateX:[null,i,i,0],headRotateZ:[null,-n/4,-n/4,0],eyeLookInLeft:[null,0],eyeLookOutLeft:[null,0],eyeLookInRight:[null,0],eyeLookOutRight:[null,0],eyeContact:[0]}})))),e>2*this.animFrameDur&&(e=2*this.animFrameDur),(this.viewName!=="full"||this.isAvatarOnly)&&(n=this.mtRandomized[Math.floor(Math.random()*this.mtRandomized.length)],i=this.mtAvatar[n],i.needsUpdate||Object.assign(i,{base:(this.mood.baseline[n]||0)+(1+r/255)*Math.random()/5,needsUpdate:!0})),this.updatePoseBase(this.animClock),this.mixer&&this.mixer.update(e/1e3*this.mixer.timeScale),this.updatePoseDelta(),this.applyShoulderAdjustmentToBones(),(this.isSpeaking||this.isListening)&&u?r>this.volumeMax?(this.volumeHeadBase=.05,Math.random()>.6&&(this.volumeHeadTarget=-.05-Math.random()/15),this.volumeMax=r):(this.volumeMax*=.92,this.volumeHeadTarget=this.volumeHeadBase-.9*(this.volumeHeadBase-this.volumeHeadTarget)):(this.volumeHeadTarget=0,this.volumeMax=0),n=this.volumeHeadTarget-this.volumeHeadCurrent,i=Math.abs(n),i>1e-4&&(o=i*(this.volumeHeadEasing(Math.min(1,this.volumeHeadVelocity*e/1e3/i)/2+.5)-.5),this.volumeHeadCurrent+=Math.sign(n)*Math.min(i,o)),Math.abs(this.volumeHeadCurrent)>1e-4&&(ie.setFromAxisAngle(vt,this.volumeHeadCurrent),this.objectNeck.quaternion.multiply(ie)),Ze.setFromObject(this.armature),this.objectLeftToeBase.getWorldPosition(Ae),Ae.sub(this.armature.position),this.objectRightToeBase.getWorldPosition(Le),Le.sub(this.armature.position),this.objectHips.position.y-=Ze.min.y/2,this.objectHips.position.x-=(Ae.x+Le.x)/4,this.objectHips.position.z-=(Ae.z+Le.z)/2,this.dynamicbones.update(e),this.fbxAnimationLoader&&this.fbxAnimationLoader.update(),this.opt.update&&this.opt.update(e),this.updateMorphTargets(e),this.isAvatarOnly)this.stats&&this.stats.end();else{if(this.cameraClock!==null&&this.cameraClock<1e3){this.cameraClock+=e,this.cameraClock>1e3&&(this.cameraClock=1e3);let l=new x.Spherical().setFromVector3(this.cameraStart),d=new x.Spherical().setFromVector3(this.cameraEnd);l.phi+=this.easing(this.cameraClock/1e3)*(d.phi-l.phi),l.theta+=this.easing(this.cameraClock/1e3)*(d.theta-l.theta),l.radius+=this.easing(this.cameraClock/1e3)*(d.radius-l.radius),l.makeSafe(),this.camera.position.setFromSpherical(l),this.controlsStart.x!==this.controlsEnd.x?this.controls.target.copy(this.controlsStart.lerp(this.controlsEnd,this.easing(this.cameraClock/1e3))):(l.setFromVector3(this.controlsStart),d.setFromVector3(this.controlsEnd),l.phi+=this.easing(this.cameraClock/1e3)*(d.phi-l.phi),l.theta+=this.easing(this.cameraClock/1e3)*(d.theta-l.theta),l.radius+=this.easing(this.cameraClock/1e3)*(d.radius-l.radius),l.makeSafe(),this.controls.target.setFromSpherical(l)),this.controls.update()}this.controls.autoRotate&&this.controls.update(),this.stats&&this.stats.end(),this.render()}}resetLips(){this.visemeNames.forEach(t=>{this.morphs.forEach(e=>{const n=e.morphTargetDictionary["viseme_"+t];n!==void 0&&(e.morphTargetInfluences[n]=0)})})}lipsyncGetProcessor(t,e="./"){if(!this.lipsync.hasOwnProperty(t)){const n=t.toLowerCase(),i="Lipsync"+t.charAt(0).toUpperCase()+t.slice(1);try{const s=Xe[n];s&&s[i]?(this.lipsync[t]=new s[i],console.log(`Loaded lip-sync module for ${t}`)):console.warn(`Lip-sync module for ${t} not found. Available modules:`,Object.keys(Xe))}catch(s){console.warn(`Failed to load lip-sync module for ${t}:`,s)}}}lipsyncPreProcessText(t,e){return(this.lipsync[e]||Object.values(this.lipsync)[0]).preProcessText(t)}lipsyncWordsToVisemes(t,e){return(this.lipsync[e]||Object.values(this.lipsync)[0]).wordsToVisemes(t)}speakText(t,e=null,n=null,i=null){e=e||{};const s=/[!\.\?\n\p{Extended_Pictographic}]/ug,o=/[ ]/ug,r=/[\p{L}\p{N},\.\p{Quotation_Mark}!€\$\+\p{Dash_Punctuation}%&\?]/ug,u=/[\p{Extended_Pictographic}]/ug,a=e.lipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang;let c="",l="",d=0,h=[],p=[];const v=Array.from(this.segmenter.segment(t),y=>y.segment);for(let y=0;y<v.length;y++){const w=y===v.length-1,M=v[y].match(r);let g=v[y].match(s);const U=v[y].match(u),E=v[y].match(o);if(g&&!w&&!U&&v[y+1].match(s)&&(g=!1),n&&(c+=v[y]),M&&(!i||i.every(L=>y<L[0]||y>L[1]))&&(l+=v[y]),(E||g||w)&&(l.length&&(l=this.lipsyncPreProcessText(l,a),l.length&&h.push({mark:d,word:l})),c.length&&(p.push({mark:d,template:{name:"subtitles"},ts:[0],vs:{subtitles:[c]}}),c=""),l.length)){const L=this.lipsyncWordsToVisemes(l,a);if(L&&L.visemes&&L.visemes.length){const W=L.times[L.visemes.length-1]+L.durations[L.visemes.length-1];for(let k=0;k<L.visemes.length;k++)p.push({mark:d,template:{name:"viseme"},ts:[(L.times[k]-.6)/W,(L.times[k]+.5)/W,(L.times[k]+L.durations[k]+.5)/W],vs:{["viseme_"+L.visemes[k]]:[null,L.visemes[k]==="PP"||L.visemes[k]==="FF"?.9:.6,0]}})}l="",d++}if(g||w){if(h.length||w&&p.length){const L={anim:p};n&&(L.onSubtitles=n),h.length&&!e.avatarMute&&(L.text=h,e.avatarMood&&(L.mood=e.avatarMood),e.ttsLang&&(L.lang=e.ttsLang),e.ttsVoice&&(L.voice=e.ttsVoice),e.ttsRate&&(L.rate=e.ttsRate),e.ttsVoice&&(L.pitch=e.ttsPitch),e.ttsVolume&&(L.volume=e.ttsVolume)),this.speechQueue.push(L),h=[],l="",d=0,p=[]}if(U){let L=this.animEmojis[v[y]];L&&L.link&&(L=this.animEmojis[L.link]),L&&this.speechQueue.push({emoji:L})}this.speechQueue.push({break:100})}}this.speechQueue.push({break:1e3}),this.startSpeaking()}async speakEmoji(t){let e=this.animEmojis[t];e&&e.link&&(e=this.animEmojis[e.link]),e&&this.speechQueue.push({emoji:e}),this.startSpeaking()}async speakBreak(t){this.speechQueue.push({break:t}),this.startSpeaking()}async speakMarker(t){this.speechQueue.push({marker:t}),this.startSpeaking()}async playBackgroundAudio(t){let n=await(await fetch(t)).arrayBuffer();this.stopBackgroundAudio(),this.audioBackgroundSource=this.audioCtx.createBufferSource(),this.audioBackgroundSource.loop=!0,this.audioBackgroundSource.buffer=await this.audioCtx.decodeAudioData(n),this.audioBackgroundSource.playbackRate.value=1/this.animSlowdownRate,this.audioBackgroundSource.connect(this.audioBackgroundGainNode),this.audioBackgroundSource.start(0)}stopBackgroundAudio(){try{this.audioBackgroundSource.stop()}catch{}this.audioBackgroundSource.disconnect()}async setReverb(t=null){if(t){let n=await(await fetch(t)).arrayBuffer();this.audioReverbNode.buffer=await this.audioCtx.decodeAudioData(n)}else{const e=this.audioCtx.sampleRate,n=this.audioCtx.createBuffer(2,e,e);n.getChannelData(0)[0]=1,n.getChannelData(1)[0]=1,this.audioReverbNode.buffer=n}}setMixerGain(t,e=null,n=0){t!==null&&(this.audioSpeechGainNode.gain.cancelScheduledValues(this.audioCtx.currentTime),n?(this.audioSpeechGainNode.gain.setValueAtTime(Math.max(this.audioSpeechGainNode.gain.value,1e-4),this.audioCtx.currentTime),this.audioSpeechGainNode.gain.exponentialRampToValueAtTime(Math.max(t,1e-4),this.audioCtx.currentTime+n)):this.audioSpeechGainNode.gain.setValueAtTime(t,this.audioCtx.currentTime)),e!==null&&(this.audioBackgroundGainNode.gain.cancelScheduledValues(this.audioCtx.currentTime),n?(this.audioBackgroundGainNode.gain.setValueAtTime(Math.max(this.audioBackgroundGainNode.gain.value,1e-4),this.audioCtx.currentTime),this.audioBackgroundGainNode.gain.exponentialRampToValueAtTime(Math.max(e,1e-4),this.audioCtx.currentTime+n)):this.audioBackgroundGainNode.gain.setValueAtTime(e,this.audioCtx.currentTime))}speakAudio(t,e=null,n=null){e=e||{};const i=e.lipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang,s={};if(t.words){let o=[];for(let r=0;r<t.words.length;r++){const u=t.words[r],a=t.wtimes[r];let c=t.wdurations[r];if(u.length&&(n&&o.push({template:{name:"subtitles"},ts:[a],vs:{subtitles:[" "+u]}}),!t.visemes)){const l=this.lipsyncPreProcessText(u,i),d=this.lipsyncWordsToVisemes(l,i);if(d&&d.visemes&&d.visemes.length){const h=d.times[d.visemes.length-1]+d.durations[d.visemes.length-1],p=Math.min(c,Math.max(0,c-d.visemes.length*150));let v=.6+this.convertRange(p,[0,c],[0,.4]);if(c=Math.min(c,d.visemes.length*200),h>0)for(let y=0;y<d.visemes.length;y++){const w=a+d.times[y]/h*c,M=d.durations[y]/h*c;o.push({template:{name:"viseme"},ts:[w-Math.min(60,2*M/3),w+Math.min(25,M/2),w+M+Math.min(60,M/2)],vs:{["viseme_"+d.visemes[y]]:[null,d.visemes[y]==="PP"||d.visemes[y]==="FF"?.9:v,0]}})}}}}if(t.visemes)for(let r=0;r<t.visemes.length;r++){const u=t.visemes[r],a=t.vtimes[r],c=t.vdurations[r];o.push({template:{name:"viseme"},ts:[a-2*c/3,a+c/2,a+c+c/2],vs:{["viseme_"+u]:[null,u==="PP"||u==="FF"?.9:.6,0]}})}if(t.markers)for(let r=0;r<t.markers.length;r++){const u=t.markers[r],a=t.mtimes[r];o.push({template:{name:"markers"},ts:[a],vs:{function:[u]}})}o.length&&(s.anim=o)}if(t.audio&&(s.audio=t.audio),t.anim?.name){let o=this.animFactory(t.anim,!1,1,1,!0);s.anim?s.anim.push(o):s.anim=[o]}n&&(s.onSubtitles=n),e.isRaw&&(s.isRaw=!0),Object.keys(s).length&&(this.speechQueue.push(s),s.isRaw||this.speechQueue.push({break:300}),this.startSpeaking())}async playAudio(t=!1){if(!(!this.armature||this.isAudioPlaying&&!t))if(this.isAudioPlaying=!0,this.audioPlaylist.length){const e=this.audioPlaylist.shift();if(this.audioCtx.state==="suspended"||this.audioCtx.state==="interrupted"){const s=this.audioCtx.resume(),o=new Promise((r,u)=>setTimeout(()=>u("p2"),1e3));try{await Promise.race([s,o])}catch{console.log("Can't play audio. Web Audio API suspended. This is often due to calling some speak method before the first user action, which is typically prevented by the browser."),this.playAudio(!0);return}}let n;if(Array.isArray(e.audio)){let s=this.concatArrayBuffers(e.audio);n=this.pcmToAudioBuffer(s)}else n=e.audio;this.audioSpeechSource=this.audioCtx.createBufferSource(),this.audioSpeechSource.buffer=n,this.audioSpeechSource.playbackRate.value=1/this.animSlowdownRate,this.audioSpeechSource.connect(this.audioAnalyzerNode),this.audioSpeechSource.addEventListener("ended",()=>{this.audioSpeechSource.disconnect(),this.playAudio(!0)},{once:!0});let i=0;e.anim&&(e.isRaw||(i=Math.abs(Math.min(0,...e.anim.map(s=>Math.min(...s.ts))))),e.anim.forEach(s=>{for(let o=0;o<s.ts.length;o++)s.ts[o]=this.animClock+s.ts[o]+i;this.animQueue.push(s)})),this.audioSpeechSource.start(i/1e3)}else this.isAudioPlaying=!1,this.startSpeaking(!0)}async synthesizeWithBrowserTTS(t){return new Promise((e,n)=>{const i=t.text.map(g=>g.word).join(" "),s=new SpeechSynthesisUtterance(i),o=t.lang||this.avatar.ttsLang||this.opt.ttsLang||"en-US",r=(t.rate||this.avatar.ttsRate||this.opt.ttsRate||1)+this.mood.speech.deltaRate,u=(t.pitch||this.avatar.ttsPitch||this.opt.ttsPitch||1)+this.mood.speech.deltaPitch,a=(t.volume||this.avatar.ttsVolume||this.opt.ttsVolume||1)+this.mood.speech.deltaVolume;s.lang=o,s.rate=Math.max(.1,Math.min(10,r)),s.pitch=Math.max(0,Math.min(2,u)),s.volume=Math.max(0,Math.min(1,a));const c=speechSynthesis.getVoices(),l=t.voice||this.avatar.ttsVoice||this.opt.ttsVoice;if(l&&c.length>0){const g=c.find(U=>U.name.includes(l)||U.lang===o);g&&(s.voice=g)}const d=i.length*100/s.rate,h=this.audioCtx.createBuffer(1,this.audioCtx.sampleRate*(d/1e3),this.audioCtx.sampleRate),p=this.avatar.lipsyncLang||this.opt.lipsyncLang||"en",v=this.lipsyncPreProcessText(i,p),y=this.lipsyncWordsToVisemes(v,p);console.log("Browser TTS Lip-sync Debug:",{text:i,lipsyncLang:p,processedText:v,lipsyncData:y,hasVisemes:y&&y.visemes&&y.visemes.length>0,estimatedDuration:d});const w=[];if(y&&y.visemes&&y.visemes.length>0){const g=y.times[y.visemes.length-1]+y.durations[y.visemes.length-1];for(let U=0;U<y.visemes.length;U++){const E=y.visemes[U],L=y.times[U]/g,W=y.durations[U]/g,k=L*d,A=W*d;w.push({template:{name:"viseme"},ts:[k-Math.min(60,2*A/3),k+Math.min(25,A/2),k+A+Math.min(60,A/2)],vs:{["viseme_"+E]:[null,E==="PP"||E==="FF"?.9:.6,0]}})}}const M=[...t.anim,...w];this.audioPlaylist.push({anim:M,audio:h}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio(),s.onend=()=>{e()},s.onerror=g=>{console.error("Speech synthesis error:",g.error),n(g.error)},speechSynthesis.speak(s)})}async synthesizeWithElevenLabsTTS(t){const e=t.text.map(d=>d.word).join(" "),n=t.voice||this.avatar.ttsVoice||this.opt.ttsVoice||"21m00Tcm4TlvDq8ikWAM",i={text:e,model_id:"eleven_monolingual_v1",voice_settings:{stability:.5,similarity_boost:.5,style:0,use_speaker_boost:!0}},s=await fetch(`${this.opt.ttsEndpoint}/${n}`,{method:"POST",headers:{Accept:"audio/mpeg","Content-Type":"application/json","xi-api-key":this.opt.ttsApikey},body:JSON.stringify(i)});if(!s.ok)throw new Error(`ElevenLabs TTS error: ${s.status} ${s.statusText}`);const o=await s.arrayBuffer(),r=await this.audioCtx.decodeAudioData(o);console.log("Using text-based lip-sync for debugging...");const u=this.avatar.lipsyncLang||this.opt.lipsyncLang||"en";let a;try{console.log("Lip-sync modules available:",{hasLipsync:!!this.lipsync,lipsyncKeys:this.lipsync?Object.keys(this.lipsync):[],lipsyncLang:u});const d=this.lipsyncPreProcessText(e,u),h=this.lipsyncWordsToVisemes(d,u);if(console.log("Lip-sync data:",{processedText:d,lipsyncData:h,hasVisemes:h&&h.visemes&&h.visemes.length>0}),h&&h.visemes&&h.visemes.length>0)a={visemes:h.visemes.map((p,v)=>({viseme:p,startTime:v*r.duration/h.visemes.length,endTime:(v+1)*r.duration/h.visemes.length,duration:r.duration/h.visemes.length,intensity:.7})),words:[],duration:r.duration,features:{onsets:[],boundaries:[]}};else throw new Error("No visemes generated from text")}catch(d){console.error("Text-based lip-sync failed, using fallback:",d);const h=e.toLowerCase().split(/\s+/),p=[];for(const v of h)for(const y of v){let w="aa";"aeiou".includes(y)?w="aa":"bp".includes(y)?w="PP":"fv".includes(y)?w="FF":"st".includes(y)?w="SS":"dln".includes(y)?w="DD":"kg".includes(y)?w="kk":"rw".includes(y)&&(w="RR"),p.push(w)}a={visemes:p.map((v,y)=>({viseme:v,startTime:y*r.duration/p.length,endTime:(y+1)*r.duration/p.length,duration:r.duration/p.length,intensity:.6})),words:[],duration:r.duration,features:{onsets:[],boundaries:[]}}}console.log("ElevenLabs TTS Audio Analysis:",{text:e,audioDuration:r.duration,visemeCount:a.visemes?a.visemes.length:0,wordCount:a.words?a.words.length:0,features:{onsets:a.features&&a.features.onsets?a.features.onsets.length:0,boundaries:a.features&&a.features.phonemeBoundaries?a.features.phonemeBoundaries.length:0},visemes:a.visemes?a.visemes.slice(0,3):[]});const c=[];if(a.visemes&&a.visemes.length>0){console.log("ElevenLabs: Generating lip-sync animation from",a.visemes.length,"visemes");for(let d=0;d<a.visemes.length;d++){const h=a.visemes[d],p=h.startTime*1e3,v=h.duration*1e3,y=h.intensity;c.push({template:{name:"viseme"},ts:[p-Math.min(60,2*v/3),p+Math.min(25,v/2),p+v+Math.min(60,v/2)],vs:{["viseme_"+h.viseme]:[null,y,0]}})}console.log("ElevenLabs: Generated",c.length,"lip-sync animation frames")}else console.warn("ElevenLabs: No visemes available for lip-sync animation");const l=[...t.anim,...c];console.log("ElevenLabs: Combined animation frames:",l.length,"(original:",t.anim.length,"+ lipsync:",c.length,")"),this.audioPlaylist.push({anim:l,audio:r}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio()}async synthesizeWithDeepgramTTS(t){const e=t.text.map(d=>d.word).join(" "),n=t.voice||this.avatar.ttsVoice||this.opt.ttsVoice||"aura-2-thalia-en",i=`${this.opt.ttsEndpoint}?model=${n}`,s=await fetch(i,{method:"POST",headers:{Authorization:`Token ${this.opt.ttsApikey}`,"Content-Type":"text/plain",Accept:"audio/mpeg"},body:e});if(!s.ok)throw new Error(`Deepgram TTS error: ${s.status} ${s.statusText}`);const o=await s.arrayBuffer(),r=await this.audioCtx.decodeAudioData(o);console.log("Using text-based lip-sync for Deepgram...");const u=this.avatar.lipsyncLang||this.opt.lipsyncLang||"en";let a;try{console.log("Lip-sync modules available:",{hasLipsync:!!this.lipsync,lipsyncKeys:this.lipsync?Object.keys(this.lipsync):[],lipsyncLang:u});const d=this.lipsyncPreProcessText(e,u),h=this.lipsyncWordsToVisemes(d,u);if(console.log("Lip-sync data:",{processedText:d,lipsyncData:h,hasVisemes:h&&h.visemes&&h.visemes.length>0}),h&&h.visemes&&h.visemes.length>0)a={visemes:h.visemes.map((p,v)=>({viseme:p,startTime:v*r.duration/h.visemes.length,endTime:(v+1)*r.duration/h.visemes.length,duration:r.duration/h.visemes.length,intensity:.7})),words:[],duration:r.duration,features:{onsets:[],boundaries:[]}};else throw new Error("No visemes generated from text")}catch(d){console.error("Text-based lip-sync failed, using fallback:",d);const h=e.toLowerCase().split(/\s+/),p=[];for(const v of h)for(const y of v){let w="aa";"aeiou".includes(y)?w="aa":"bp".includes(y)?w="PP":"fv".includes(y)?w="FF":"st".includes(y)?w="SS":"dln".includes(y)?w="DD":"kg".includes(y)?w="kk":"rw".includes(y)&&(w="RR"),p.push(w)}a={visemes:p.map((v,y)=>({viseme:v,startTime:y*r.duration/p.length,endTime:(y+1)*r.duration/p.length,duration:r.duration/p.length,intensity:.6})),words:[],duration:r.duration,features:{onsets:[],boundaries:[]}}}console.log("Deepgram TTS Audio Analysis:",{text:e,audioDuration:r.duration,visemeCount:a.visemes?a.visemes.length:0,wordCount:a.words?a.words.length:0,features:{onsets:a.features&&a.features.onsets?a.features.onsets.length:0,boundaries:a.features&&a.features.phonemeBoundaries?a.features.phonemeBoundaries.length:0},visemes:a.visemes?a.visemes.slice(0,3):[]});const c=[];if(a.visemes&&a.visemes.length>0){console.log("Deepgram: Generating lip-sync animation from",a.visemes.length,"visemes");for(let d=0;d<a.visemes.length;d++){const h=a.visemes[d],p=h.startTime*1e3,v=h.duration*1e3,y=h.intensity;c.push({template:{name:"viseme"},ts:[p-Math.min(60,2*v/3),p+Math.min(25,v/2),p+v+Math.min(60,v/2)],vs:{["viseme_"+h.viseme]:[null,y,0]}})}console.log("Deepgram: Generated",c.length,"lip-sync animation frames")}else console.warn("Deepgram: No visemes available for lip-sync animation");const l=[...t.anim,...c];console.log("Deepgram: Combined animation frames:",l.length,"(original:",t.anim.length,"+ lipsync:",c.length,")"),this.audioPlaylist.push({anim:l,audio:r}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio()}async synthesizeWithAzureTTS(t){const e=t.text.map(l=>l.word).join(" "),i=`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const V=require("react/jsx-runtime"),R=require("react"),Je=require("three"),$e=require("three/addons/controls/OrbitControls.js"),et=require("three/addons/loaders/GLTFLoader.js"),tt=require("three/addons/loaders/DRACOLoader.js"),Ge=require("three/addons/loaders/FBXLoader.js"),nt=require("three/addons/environments/RoomEnvironment.js"),it=require("three/addons/libs/stats.module.js");var De=typeof document<"u"?document.currentScript:null;function ot(U){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(U){for(const e in U)if(e!=="default"){const n=Object.getOwnPropertyDescriptor(U,e);Object.defineProperty(t,e,n.get?n:{enumerable:!0,get:()=>U[e]})}}return t.default=U,Object.freeze(t)}const f=ot(Je);let m,ge,fe;const H=[0,0,0,0],B=new f.Vector3,Ee=new f.Vector3,ce=new f.Vector3,Fe=new f.Vector3;new f.Plane;new f.Ray;new f.Euler;const he=new f.Quaternion,Ze=new f.Quaternion,be=new f.Matrix4,Re=new f.Matrix4;new f.Vector3;const Pe=new f.Vector3(0,0,1),st=new f.Vector3(1,0,0),at=new f.Vector3(0,1,0),rt=new f.Vector3(0,0,1);class lt{constructor(t=null){this.opt=Object.assign({warmupMs:2e3,sensitivityFactor:1,movementFactor:1,isExcludes:!0,isPivots:!0,isLimits:!0,helperBoneColor1:16711680,helperBoneColor2:16238028,helperLinkColor1:16711680,helperLinkColor2:255,helperExcludesColor:11184895},t||{}),this.scene=null,this.armature=null,this.config=[],this.data=[],this.dict={},this.objectsUpdate=[],this.helpers={isActive:!1,isShowAll:!1,points:{bones:[],pivots:[],object:null},lines:{bones:[],object:null},excludes:{bones:[],deltaLocals:[],radii:[],objects:[]}},this.running=!1,this.timerMs=0}getOptionValue(t){return this.opt[t]}setOptionValue(t,e){this.opt[t]=e,this.helpers.isActive&&this.showHelpers()}getBoneNames(){return this.data.map(t=>t.name)}getValue(t,e){if(this.scene===null)throw new Error("Dynamic bones has not been setup yet.");if(!this.dict.hasOwnProperty(t))throw new Error("Dynamic bone '"+t+"' not found.");const n=this.dict[t];let o;if(e==="type")o=n.type;else if(e==="stiffness")o=n.k.every(s=>s===n.k[0])?n.k[0]:[...n.k];else if(e==="damping")o=n.c.every(s=>s===n.c[0])?n.c[0]:[...n.c];else if(e==="external")o=n.ext<1?n.ext:null;else if(e==="limits")o=n.limits?.map(s=>s===null?null:[...s]);else if(e==="deltaLocal")o=n.dl?[...n.dl]:null;else if(e==="excludes")o=n.excludes?[...n.excludes.map(s=>{const i={bone:s.bone.name.slice(),radius:s.radius};return s.deltaLocal&&(i.deltaLocal=[...s.deltaLocal]),i})]:null;else if(e==="deltaWorld")o=n.dw?[...n.dw]:null;else if(e==="pivot")o=n.pivot;else if(e==="helper")o=n.helper;else throw new Error("Unsupported property '"+e+"'.");return o}setValue(t,e,n){if(this.scene===null)throw new Error("Dynamic bones has not been setup yet.");if(!this.dict.hasOwnProperty(t))throw new Error("Dynamic bone '"+t+"' not found.");const o=this.dict[t];if(e==="type"){if(!n)throw new Error("Parameter 'type' not set.");if(typeof n!="string")throw new Error("Type must be a string.");switch(n){case"point":o.isPoint=!0,o.isX=!0,o.isY=!0,o.isZ=!0,o.isT=!1;break;case"link":o.isPoint=!1,o.isX=!0,o.isY=!1,o.isZ=!0,o.isT=!1;break;case"mix1":o.isPoint=!1,o.isX=!0,o.isY=!0,o.isZ=!0,o.isT=!1;break;case"mix2":o.isPoint=!1,o.isX=!0,o.isY=!1,o.isZ=!0,o.isT=!0;break;case"full":o.isPoint=!1,o.isX=!0,o.isY=!0,o.isZ=!0,o.isT=!0;break;default:throw new Error("Unknown type'"+n+"'.")}o.type=n.slice()}else if(e==="stiffness"){if(!n)throw new Error("Parameter 'stiffness' not set.");if(!Number.isNaN(n)&&n>=0)o.k=Array(4).fill(n);else if(Array.isArray(n)&&n.length===4&&n.every(s=>s>=0))o.k=[...n];else throw new Error("Stiffness must be a non-negative number or an array of four non-negative numbers.")}else if(e==="damping"){if(!n)throw new Error("Parameter 'damping' not set.");if(!Number.isNaN(n)&&n>=0)o.c=Array(4).fill(n);else if(Array.isArray(n)&&n.length===4&&n.every(s=>s>=0))o.c=[...n];else throw new Error("Damping must be a non-negative number or an array of four non-negative numbers.")}else if(e==="external")if(n==null)o.ext=1;else if(!Number.isNaN(n)&&n>=0&&n<=1)o.ext=n;else throw new Error("External (if set) must be a number between [0,1].");else if(e==="limits")if(n==null)o.limits=null;else{if(!Array.isArray(n)||n.length!==4)throw new Error("Limits (if set) must null, or an array of four arrays.");if(!n.every(s=>s===null||Array.isArray(s)&&s.length===2&&(s[0]===null||!Number.isNaN(s[0]))&&(s[1]===null||!Number.isNaN(s))))throw new Error("Limit values must be null or numbers.");o.limits=[n[0]?[...n[0]]:null,n[1]?[...n[1]]:null,n[2]?[...n[2]]:null,n[3]?[...n[3]]:null]}else if(e==="excludes"){if(n==null)o.excludes=null;else{if(!Array.isArray(n))throw new Error("Excludes (if set) must null, or an array.");o.excludes=[],n.forEach((s,i)=>{if(!s.bone)throw new Error("Bone not specified in #"+i+" exclude.");if(typeof s.bone!="string"||s.bone.length===0)throw new Error("Bone name must be a non-empty string in #"+i+" exclude.");const r=this.armature.getObjectByName(s.bone);if(!r)throw new Error("Bone '"+s.bone+"' not found in #"+i+" exclude.");if(Number.isNaN(s.radius)&&s.radius>=0)throw new Error("Radius must be a non-negative number in #"+i+" exclude.");const c={bone:r,radius:s.radius,radiusSq:s.radius*s.radius,deltaLocal:null};if(s.deltaLocal){if(!Array.isArray(s.deltaLocal)||s.deltaLocal.length!==3||s.deltaLocal.some(l=>Number.isNaN(l)))throw new Error("deltaLocal must be an array of three numbers in #"+i+" exclude.");c.deltaLocal=[...s.deltaLocal]}o.excludes.push(c)})}this.showHelpers()}else if(e==="helper"){if(n==null)o.helper=null;else{if(n!==!1&&n!==!0)throw new Error("Helper, if set, must be false or true.");o.helper=n}this.showHelpers()}else if(e==="pivot")if(n==null)o.pivot=null;else{if(n!==!1&&n!==!0)throw new Error("Pivot, if set, must be false or true.");if(n===!0&&o.type===0)throw new Error("Point type bone can't be a pivot.");o.pivot=n}else if(e==="deltaLocal")if(n==null)o.dl=null;else{if(!Array.isArray(n)||n.length!==3)throw new Error("deltaLocal, is set, must be an array of three numbers.");if(!n.every(s=>!Number.isNaN(s)))throw new Error("deltaLocal values must be numbers.");o.dl=[...n]}else if(e==="deltaWorld")if(n==null)o.dw=null;else{if(!Array.isArray(n)||n.length!==3)throw new Error("deltaWorld, is set, must be an array of three values.");if(!n.every(s=>!Number.isNaN(s)))throw new Error("deltaWorld values must be numbers.");o.dw=[...n]}else throw new Error("Unsupported property "+e)}getConfig(){return this.data.map(t=>{const e={bone:t.name.slice()};return["type","stiffness","damping","external","deltaLocal","deltaWorld","limits","excludes","pivot","helper"].forEach(n=>{m=this.getValue(t.name,n),m&&(e[n]=m)}),e})}sortBones(){if(this.scene===null)throw new Error("Dynamic bones has not been setup yet.");let t=0;const e=new WeakMap;this.armature.traverse(i=>{e.has(i)||(e.set(i,t),t++)}),this.data.sort((i,r)=>e.get(i.bone)-e.get(r.bone)),this.data.forEach(i=>{m=this.dict[i.boneParent.name],m&&(m.children||(m.children=[]),m.children.push(i))}),this.objectsUpdate=[];const n=new WeakSet,o=i=>i.parent?.isBone?[i,...o(i.parent)]:[i],s=i=>{o(i).forEach(c=>{n.has(c)||(this.objectsUpdate.push(c),n.add(c))})};this.data.forEach(i=>{s(i.bone),i.excludes&&i.excludes.forEach(r=>{s(r.bone)})}),this.objectsUpdate.sort((i,r)=>e.get(i)-e.get(r))}setup(t,e,n){this.dispose();const o=(s,i)=>{if(!s)throw this.dispose(),new Error(i)};o(t?.isScene,"First parameter must be Scene."),this.scene=t,o(e?.isObject3D,"Second parameter must be the armature Object3D."),this.armature=e,o(Array.isArray(n),"Third parameter must be an array of bone configs."),this.config=n,this.config.forEach((s,i)=>{const r="Config item #"+i+": ";o(s.bone,r+"Bone not specified.");const c=s.bone;o(typeof c=="string"&&c.length>0,r+"Bone name must be a non-empty string.");const l=this.armature.getObjectByName(c);o(l,r+"Bone '"+c+"' not found."),o(l.parent?.isBone,r+"Bone must have a parent bone."),o(this.data.every(a=>a.bone!==l),r+"Bone '"+c+"' already exists."),l.updateMatrixWorld(!0);const u={name:c,bone:l,boneParent:l.parent,vBasis:l.position.clone(),vWorld:l.parent.getWorldPosition(B).clone(),qBasis:l.parent.quaternion.clone(),l:l.position.length(),p:[0,0,0,0],v:[0,0,0,0],a:[0,0,0,0],ev:[0,0,0,0],ea:[0,0,0,0]};u.boneParent.matrixWorld.decompose(B,he,ce),B.copy(Pe).applyQuaternion(he).setY(0).normalize(),he.premultiply(Ze.setFromUnitVectors(Pe,B).invert()).normalize(),u.qWorldInverseYaw=he.clone().normalize(),this.data.push(u),this.dict[c]=u;try{this.setValue(c,"type",s.type),this.setValue(c,"stiffness",s.stiffness),this.setValue(c,"damping",s.damping),this.setValue(c,"external",s.external),this.setValue(c,"limits",s.limits),this.setValue(c,"excludes",s.excludes),this.setValue(c,"deltaLocal",s.deltaLocal),this.setValue(c,"deltaWorld",s.deltaWorld),this.setValue(c,"pivot",s.pivot),this.setValue(c,"helper",s.helper)}catch(a){o(!1,r+a)}}),this.sortBones(),this.start()}update(t){if(!this.running)return;let e,n,o,s,i;for(this.timerMs+=t,t>1e3&&(this.timerMs=0),t/=1e3,e=0,o=this.objectsUpdate.length;e<o;e++)i=this.objectsUpdate[e],i.updateMatrix(),i.parent===null?i.matrixWorld.copy(i.matrix):i.matrixWorld.multiplyMatrices(i.parent.matrixWorld,i.matrix),i.matrixWorldNeedsUpdate=!1;for(e=0,o=this.data.length;e<o;e++){if(i=this.data[e],B.copy(i.vWorld),be.copy(i.boneParent.matrixWorld),Re.copy(be).invert(),i.vWorld.setFromMatrixPosition(be),B.applyMatrix4(Re),B.length()>.5&&(console.info("Info: Unrealistic jump of "+B.length().toFixed(2)+" meters."),B.setLength(.5)),B.applyQuaternion(i.bone.quaternion),H[0]=B.x,H[1]=B.y,H[2]=-B.z,H[3]=B.length()/3,i.children)for(n=0,s=i.children.length;n<s;n++)m=i.children[n],H[0]-=m.v[0]*t/3,H[1]-=m.v[1]*t/3,H[2]+=m.v[2]*t/3,H[3]-=m.v[3]*t/3;if(m=this.opt.sensitivityFactor,H[0]*=i.ext*m,H[1]*=i.ext*m,H[2]*=i.ext*m,H[3]*=i.ext*m,i.isX&&(m=H[0]/t,i.ea[0]=(m-i.ev[0])/t,i.ev[0]=m,i.a[0]=-i.k[0]*i.p[0]-i.c[0]*i.v[0]-i.ea[0],i.p[0]+=i.v[0]*t+i.a[0]*t*t/2+H[0],m=i.v[0]+i.a[0]*t/2,m=-i.k[0]*i.p[0]-i.c[0]*m-i.ea[0],i.v[0]=i.v[0]+(m+i.a[0])*t/2),i.isY&&(m=H[1]/t,i.ea[1]=(m-i.ev[1])/t,i.ev[1]=m,i.a[1]=-i.k[1]*i.p[1]-i.c[1]*i.v[1]-i.ea[1],i.p[1]+=i.v[1]*t+i.a[1]*t*t/2+H[1],m=i.v[1]+i.a[1]*t/2,m=-i.k[1]*i.p[1]-i.c[1]*m-i.ea[1],i.v[1]=i.v[1]+(m+i.a[1])*t/2),i.isZ&&(m=H[2]/t,i.ea[2]=(m-i.ev[2])/t,i.ev[2]=m,i.a[2]=-i.k[2]*i.p[2]-i.c[2]*i.v[2]-i.ea[2],i.p[2]+=i.v[2]*t+i.a[2]*t*t/2+H[2],m=i.v[2]+i.a[2]*t/2,m=-i.k[2]*i.p[2]-i.c[2]*m-i.ea[2],i.v[2]=i.v[2]+(m+i.a[2])*t/2),i.isT&&(m=H[3]/t,i.ea[3]=(m-i.ev[3])/t,i.ev[3]=m,i.a[3]=-i.k[3]*i.p[3]-i.c[3]*i.v[3]-i.ea[3],i.p[3]+=i.v[3]*t+i.a[3]*t*t/2+H[3],m=i.v[3]+i.a[3]*t/2,m=-i.k[3]*i.p[3]-i.c[3]*m-i.ea[3],i.v[3]=i.v[3]+(m+i.a[3])*t/2),this.timerMs<this.opt.warmupMs&&(i.v[0]*=1e-4,i.p[0]*=1e-4,i.v[1]*=1e-4,i.p[1]*=1e-4,i.v[2]*=1e-4,i.p[2]*=1e-4,i.v[3]*=1e-4,i.p[3]*=1e-4),H[0]=i.p[0],H[1]=i.p[1],H[2]=i.p[2],H[3]=i.p[3],m=this.opt.movementFactor,H[0]*=m,H[1]*=m,H[2]*=m,H[3]*=m,i.dl&&(m=i.dl,H[0]+=m[0],H[1]+=m[1],H[2]+=m[2]),i.dw&&(m=i.dw,B.set(i.vBasis.x+H[0],i.vBasis.y+H[1],i.vBasis.z+H[2]),B.applyMatrix4(be),B.x+=m[0],B.y+=m[1],B.z+=m[2],B.applyMatrix4(Re),H[0]+=B.x-i.vBasis.x,H[1]+=B.y-i.vBasis.y,H[2]+=B.z-i.vBasis.z),i.limits&&this.opt.isLimits&&(m=i.limits,m[0]&&(m[0][0]!==null&&H[0]<m[0][0]&&(H[0]=m[0][0]),m[0][1]!==null&&H[0]>m[0][1]&&(H[0]=m[0][1])),m[1]&&(m[1][0]!==null&&H[1]<m[1][0]&&(H[1]=m[1][0]),m[1][1]!==null&&H[1]>m[1][1]&&(H[1]=m[1][1])),m[2]&&(m[2][0]!==null&&H[2]<m[2][0]&&(H[2]=m[2][0]),m[2][1]!==null&&H[2]>m[2][1]&&(H[2]=m[2][1])),m[3]&&(m[3][0]!==null&&H[3]<m[3][0]&&(H[3]=m[3][0]),m[3][1]!==null&&H[3]>m[3][1]&&(H[3]=m[3][1]))),i.isPoint)i.bone.position.set(i.vBasis.x+H[0],i.vBasis.y+H[1],i.vBasis.z-H[2]);else if(i.boneParent.quaternion.copy(i.qBasis),i.pivot&&this.opt.isPivots&&(i.boneParent.updateWorldMatrix(!1,!1),i.boneParent.matrixWorld.decompose(B,he,ce),B.copy(Pe).applyQuaternion(he).setY(0).normalize(),he.premultiply(Ze.setFromUnitVectors(Pe,B).invert()).normalize(),i.boneParent.quaternion.multiply(he.invert()),i.boneParent.quaternion.multiply(i.qWorldInverseYaw)),i.isZ&&(m=Math.atan(H[0]/i.l),he.setFromAxisAngle(rt,-m),i.boneParent.quaternion.multiply(he)),i.isY&&(m=i.l/3,m=m*Math.tanh(H[1]/m),i.bone.position.setLength(i.l+m)),i.isX&&(m=Math.atan(H[2]/i.l),he.setFromAxisAngle(st,-m),i.boneParent.quaternion.multiply(he)),i.isT&&(m=1.5*Math.tanh(H[3]*1.5),he.setFromAxisAngle(at,-m),i.boneParent.quaternion.multiply(he)),i.boneParent.updateWorldMatrix(!1,!0),i.excludes&&this.opt.isExcludes)for(n=0,s=i.excludes.length;n<s;n++)m=i.excludes[n],ce.set(0,0,0),m.deltaLocal&&(ce.x+=m.deltaLocal[0],ce.y+=m.deltaLocal[1],ce.z+=m.deltaLocal[2]),ce.applyMatrix4(m.bone.matrixWorld),Re.copy(i.boneParent.matrixWorld).invert(),ce.applyMatrix4(Re),B.copy(i.bone.position),!(B.distanceToSquared(ce)>=m.radiusSq)&&(fe=B.length(),ge=ce.length(),!(ge>m.radius+fe)&&(ge<Math.abs(m.radius-fe)||(ge=(ge*ge+fe*fe-m.radiusSq)/(2*ge),ce.normalize(),Fe.copy(ce).multiplyScalar(ge),ge=Math.sqrt(fe*fe-ge*ge),B.subVectors(B,Fe).projectOnPlane(ce).normalize().multiplyScalar(ge),Ee.subVectors(i.vBasis,Fe).projectOnPlane(ce).normalize(),fe=Ee.dot(B),fe<0&&(fe=Math.sqrt(ge*ge-fe*fe),Ee.multiplyScalar(fe),B.add(Ee)),B.add(Fe).normalize(),ce.copy(i.bone.position).normalize(),he.setFromUnitVectors(ce,B),i.boneParent.quaternion.premultiply(he),i.boneParent.updateWorldMatrix(!1,!0))))}this.helpers.isActive&&this.updateHelpers()}showHelpers(t){if(this.hideHelpers(),this.helpers.isShowAll=t===void 0?this.helpers.isShowAll:t===!0,m=this.helpers,this.data.forEach(e=>{(this.helpers.isShowAll||e.helper===!0)&&(m.points.bones.push(e.bone),m.points.pivots.push(e.pivot),e.type!==0&&m.lines.bones.push(e.bone),e.excludes&&e.excludes.forEach(n=>{let o=!1;for(let s=0;s<m.excludes.bones.length;s++)if(m.excludes.bones[s]===n.bone&&m.excludes.radii[s]===n.radius&&!(m.excludes.deltaLocals[s]===null&&n.deltaLocal!==null)&&!(m.excludes.deltaLocals[s]!==null&&n.deltaLocal===null)&&!(m.excludes.deltaLocals[s]!==null&&m.excludes.deltaLocals[s].some((i,r)=>i!==n.deltaLocal[r]))){o=!0;break}o||(m.excludes.bones.push(n.bone),m.excludes.radii.push(n.radius),m.excludes.deltaLocals.push(n.deltaLocal?[...n.deltaLocal]:null),m.excludes.objects.push(null))}))}),m=this.helpers.excludes,this.opt.isExcludes&&m.bones.length&&m.bones.forEach((e,n)=>{const o=new f.SphereGeometry(m.radii[n],6,6),s=new f.MeshBasicMaterial({depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0,wireframe:!0,color:this.opt.helperExcludesColor});m.objects[n]=new f.Mesh(o,s),m.objects[n].renderOrder=997,e.add(m.objects[n]),m.deltaLocals[n]&&m.objects[n].position.set(m.deltaLocals[n][0],m.deltaLocals[n][1],m.deltaLocals[n][2])}),m=this.helpers.points,m.bones.length){this.helpers.isActive=!0;const e=new f.BufferGeometry,n=m.bones.map(c=>[0,0,0]).flat();e.setAttribute("position",new f.Float32BufferAttribute(n,3));const o=new f.Color(this.opt.helperBoneColor1),s=new f.Color(this.opt.helperBoneColor2),i=m.pivots.map(c=>c&&this.opt.isPivots?[s.r,s.g,s.b]:[o.r,o.g,o.b]).flat();e.setAttribute("color",new f.Float32BufferAttribute(i,3));const r=new f.PointsMaterial({depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0,size:.2,vertexColors:!0});m.object=new f.Points(e,r),m.object.renderOrder=998,m.object.matrix=this.armature.matrixWorld,m.object.matrixAutoUpdate=!1,this.scene.add(m.object)}if(m=this.helpers.lines,m.bones.length){const e=new f.BufferGeometry,n=m.bones.map(c=>[0,0,0,0,0,0]).flat();e.setAttribute("position",new f.Float32BufferAttribute(n,3));const o=new f.Color(this.opt.helperLinkColor1),s=new f.Color(this.opt.helperLinkColor2),i=m.bones.map(c=>[o.r,o.g,o.b,s.r,s.g,s.b]).flat();e.setAttribute("color",new f.Float32BufferAttribute(i,3));const r=new f.LineBasicMaterial({vertexColors:!0,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0});m.object=new f.LineSegments(e,r),m.object.renderOrder=999,m.object.matrix=this.armature.matrixWorld,m.object.matrixAutoUpdate=!1,this.scene.add(m.object)}}updateHelpers(){if(m=this.helpers.points,m.bones.length){Re.copy(this.armature.matrixWorld).invert();const t=m.object.geometry.getAttribute("position");for(let e=0,n=m.bones.length;e<n;e++)be.multiplyMatrices(Re,m.bones[e].matrixWorld),B.setFromMatrixPosition(be),t.setXYZ(e,B.x,B.y,B.z);t.needsUpdate=!0,m.object.updateMatrixWorld()}if(m=this.helpers.lines,m.bones.length){Re.copy(this.armature.matrixWorld).invert();const t=m.object.geometry.getAttribute("position");for(let e=0,n=0,o=m.bones.length;e<o;e++,n+=2)be.multiplyMatrices(Re,m.bones[e].matrixWorld),B.setFromMatrixPosition(be),t.setXYZ(n,B.x,B.y,B.z),be.multiplyMatrices(Re,m.bones[e].parent.matrixWorld),B.setFromMatrixPosition(be),t.setXYZ(n+1,B.x,B.y,B.z);t.needsUpdate=!0,m.object.updateMatrixWorld()}}hideHelpers(){[this.helpers.points,this.helpers.lines].forEach(t=>{t.bones=[],t.object&&(this.scene.remove(t.object),t.object.geometry.dispose(),t.object.material.dispose(),t.object=null)}),m=this.helpers.excludes,m.objects.forEach((t,e)=>{t&&(m.bones[e].remove(t),t.geometry.dispose(),t.material.dispose())}),m.bones=[],m.deltaLocals=[],m.radii=[],m.objects=[],this.helpers.isActive=!1}start(){this.data.length&&(this.running=!0,this.timerMs=0,this.showHelpers())}stop(){this.running=!1,this.hideHelpers();for(let t=0,e=this.data.length;t<e;t++){const n=this.data[t];n.bone.position.copy(n.vBasis),n.boneParent.quaternion.copy(n.qBasis)}}dispose(){this.stop(),this.scene=null,this.armature=null,this.config=[],this.data=[],this.dict={},this.objectsUpdate=[],this.timerMs=0}}class ut{constructor(t){this.audioContext=t,this.analyzer=null,this.dataArray=null,this.bufferLength=0}async analyzeAudio(t,e){const n=t.sampleRate,o=t.duration,s=t.getChannelData(0),i=this.extractAudioFeatures(s,n);return this.generateTimingData(i,e,o)}extractAudioFeatures(t,e){const n={energy:[],spectralCentroid:[],zeroCrossingRate:[],mfcc:[],onsets:[],phonemeBoundaries:[]},o=1024,s=512,i=Math.floor((t.length-o)/s)+1;for(let r=0;r<i;r++){const c=r*s,l=Math.min(c+o,t.length),u=t.slice(c,l),a=this.calculateEnergy(u);n.energy.push(a);const d=this.calculateSpectralCentroid(u);n.spectralCentroid.push(d);const h=this.calculateZeroCrossingRate(u);n.zeroCrossingRate.push(h);const g=this.calculateMFCC(u);n.mfcc.push(g)}return n.onsets=this.detectOnsets(n.energy),n.phonemeBoundaries=this.detectPhonemeBoundaries(n),n}calculateEnergy(t){let e=0;for(let n=0;n<t.length;n++)e+=t[n]*t[n];return e/t.length}calculateSpectralCentroid(t){const e=this.fft(t);let n=0,o=0;for(let s=0;s<e.length/2;s++){const i=Math.sqrt(e[s*2]*e[s*2]+e[s*2+1]*e[s*2+1]);n+=s*i,o+=i}return o>0?n/o:0}calculateZeroCrossingRate(t){let e=0;for(let n=1;n<t.length;n++)t[n]>=0!=t[n-1]>=0&&e++;return e/(t.length-1)}calculateMFCC(t){const e=this.fft(t),n=[];for(let o=0;o<13;o++){let s=0;for(let i=0;i<e.length/2;i++){const r=Math.sqrt(e[i*2]*e[i*2]+e[i*2+1]*e[i*2+1]);s+=r*Math.cos(Math.PI*o*(i+.5)/(e.length/2))}n.push(s)}return n}fft(t){const e=t.length,n=new Float32Array(e*2);for(let o=0;o<e;o++)n[o*2]=t[o],n[o*2+1]=0;for(let o=1,s=0;o<e;o++){let i=e>>1;for(;s&i;)s^=i,i>>=1;if(s^=i,o<s){const r=n[o*2],c=n[o*2+1];n[o*2]=n[s*2],n[o*2+1]=n[s*2+1],n[s*2]=r,n[s*2+1]=c}}for(let o=2;o<=e;o<<=1){const s=-2*Math.PI/o,i=Math.cos(s),r=Math.sin(s);for(let c=0;c<e;c+=o){let l=1,u=0;for(let a=0;a<o/2;a++){const d=n[(c+a)*2],h=n[(c+a)*2+1],g=n[(c+a+o/2)*2]*l-n[(c+a+o/2)*2+1]*u,v=n[(c+a+o/2)*2]*u+n[(c+a+o/2)*2+1]*l;n[(c+a)*2]=d+g,n[(c+a)*2+1]=h+v,n[(c+a+o/2)*2]=d-g,n[(c+a+o/2)*2+1]=h-v;const b=l*i-u*r,S=l*r+u*i;l=b,u=S}}}return n}detectOnsets(t){const e=[];let s=-.1;for(let i=1;i<t.length;i++){const r=t[i]-t[i-1],c=i*.023;r>.1&&c-s>.1&&(e.push(c),s=c)}return e}detectPhonemeBoundaries(t){const e=[],{energy:n,spectralCentroid:o,zeroCrossingRate:s}=t;for(let i=1;i<n.length;i++){const r=i*.023,c=Math.abs(n[i]-n[i-1]),l=Math.abs(o[i]-o[i-1]),u=Math.abs(s[i]-s[i-1]);c+l*.1+u*.5>.2&&e.push(r)}return e}generateTimingData(t,e,n){const o=e.toLowerCase().split(/\s+/);t.phonemeBoundaries,t.onsets;const s=[];let i=0;for(let c=0;c<o.length;c++){const l=o[c],u=this.estimateWordDuration(l,n/o.length);s.push({word:l,startTime:i,endTime:i+u,duration:u}),i+=u}const r=this.generateVisemeTimings(t,e,n);return{words:s,visemes:r,duration:n,features:t}}estimateWordDuration(t,e){const n=Math.max(.5,Math.min(2,t.length/5)),o=this.getWordComplexity(t);return e*n*o}getWordComplexity(t){const e=(t.match(/[bcdfghjklmnpqrstvwxyz]{2,}/g)||[]).length,n=(t.match(/[aeiou]{2,}/g)||[]).length;return 1+e*.2+n*.1}generateVisemeTimings(t,e,n){const o=[],s=t.phonemeBoundaries;t.onsets;const i=this.textToVisemes(e);let r=0,c=0;for(let l=0;l<s.length&&r<i.length;l++){const u=s[l],a=i[r],d=t.energy[Math.floor(u/.023)]||0,h=this.calculateVisemeDuration(a,d);o.push({viseme:a,startTime:c,endTime:c+h,duration:h,intensity:Math.min(1,d*2)}),c+=h,r++}for(;r<i.length;){const l=i[r],u=this.calculateVisemeDuration(l,.5);o.push({viseme:l,startTime:c,endTime:c+u,duration:u,intensity:.6}),c+=u,r++}return o}textToVisemes(t){const e={a:"aa",e:"E",i:"I",o:"O",u:"U",ae:"aa",ai:"aa",au:"O",ea:"E",ee:"E",ei:"E",ie:"I",oa:"O",oo:"U",ou:"U",b:"PP",p:"PP",m:"PP",f:"FF",v:"FF",th:"SS",s:"SS",z:"SS",sh:"SS",ch:"SS",d:"DD",t:"DD",n:"nn",l:"nn",k:"kk",g:"kk",ng:"kk",r:"RR",w:"RR",y:"I",h:"kk"},n=[],o=t.toLowerCase().replace(/[^a-z\s]/g,"").split(/\s+/);for(const s of o){let i=0;for(;i<s.length;){let r=!1;for(let c=3;c>=2;c--){const l=s.substr(i,c);if(e[l]){n.push(e[l]),i+=c,r=!0;break}}if(!r){const c=s[i];e[c]&&n.push(e[c]),i++}}}return n}calculateVisemeDuration(t,e){const o={aa:.15,E:.12,I:.1,O:.14,U:.13,PP:.08,FF:.1,SS:.12,DD:.11,kk:.09,nn:.1,RR:.11}[t]||.1,s=.5+e*.5;return o*s}}class ct{constructor(){this.rules={A:["[A] =aa"," [ARE] =aa RR"," [AR]O=aa RR","[AR]#=E RR"," ^[AS]#=E SS","[A]WA=aa","[AW]=aa"," :[ANY]=E nn I","[A]^+#=E","#:[ALLY]=aa nn I"," [AL]#=aa nn","[AGAIN]=aa kk E nn","#:[AG]E=I kk","[A]^+:#=aa",":[A]^+ =E","[A]^%=E"," [ARR]=aa RR","[ARR]=aa RR"," :[AR] =aa RR","[AR] =E","[AR]=aa RR","[AIR]=E RR","[AI]=E","[AY]=E","[AU]=aa","#:[AL] =aa nn","#:[ALS] =aa nn SS","[ALK]=aa kk","[AL]^=aa nn"," :[ABLE]=E PP aa nn","[ABLE]=aa PP aa nn","[ANG]+=E nn kk","[A]=aa"],B:[" [BE]^#=PP I","[BEING]=PP I I nn"," [BOTH] =PP O TH"," [BUS]#=PP I SS","[BUIL]=PP I nn","[B]=PP"],C:[" [CH]^=kk","^E[CH]=kk","[CH]=CH"," S[CI]#=SS aa","[CI]A=SS","[CI]O=SS","[CI]EN=SS","[C]+=SS","[CK]=kk","[COM]%=kk aa PP","[C]=kk"],D:["#:[DED] =DD I DD",".E[D] =DD","#^:E[D] =DD"," [DE]^#=DD I"," [DO] =DD U"," [DOES]=DD aa SS"," [DOING]=DD U I nn"," [DOW]=DD aa","[DU]A=kk U","[D]=DD"],E:["#:[E] =","'^:[E] ="," :[E] =I","#[ED] =DD","#:[E]D =","[EV]ER=E FF","[E]^%=I","[ERI]#=I RR I","[ERI]=E RR I","#:[ER]#=E","[ER]#=E RR","[ER]=E"," [EVEN]=I FF E nn","#:[E]W=","@[EW]=U","[EW]=I U","[E]O=I","#:&[ES] =I SS","#:[E]S =","#:[ELY] =nn I","#:[EMENT]=PP E nn DD","[EFUL]=FF U nn","[EE]=I","[EARN]=E nn"," [EAR]^=E","[EAD]=E DD","#:[EA] =I aa","[EA]SU=E","[EA]=I","[EIGH]=E","[EI]=I"," [EYE]=aa","[EY]=I","[EU]=I U","[E]=E"],F:["[FUL]=FF U nn","[F]=FF"],G:["[GIV]=kk I FF"," [G]I^=kk","[GE]T=kk E","SU[GGES]=kk kk E SS","[GG]=kk"," B#[G]=kk","[G]+=kk","[GREAT]=kk RR E DD","#[GH]=","[G]=kk"],H:[" [HAV]=I aa FF"," [HERE]=I I RR"," [HOUR]=aa EE","[HOW]=I aa","[H]#=I","[H]="],I:[" [IN]=I nn"," [I] =aa","[IN]D=aa nn","[IER]=I E","#:R[IED] =I DD","[IED] =aa DD","[IEN]=I E nn","[IE]T=aa E"," :[I]%=aa","[I]%=I","[IE]=I","[I]^+:#=I","[IR]#=aa RR","[IZ]%=aa SS","[IS]%=aa SS","[I]D%=aa","+^[I]^+=I","[I]T%=aa","#^:[I]^+=I","[I]^+=aa","[IR]=E","[IGH]=aa","[ILD]=aa nn DD","[IGN] =aa nn","[IGN]^=aa nn","[IGN]%=aa nn","[IQUE]=I kk","[I]=I"],J:["[J]=kk"],K:[" [K]N=","[K]=kk"],L:["[LO]C#=nn O","L[L]=","#^:[L]%=aa nn","[LEAD]=nn I DD","[L]=nn"],M:["[MOV]=PP U FF","[M]=PP"],N:["E[NG]+=nn kk","[NG]R=nn kk","[NG]#=nn kk","[NGL]%=nn kk aa nn","[NG]=nn","[NK]=nn kk"," [NOW] =nn aa","[N]=nn"],O:["[OF] =aa FF","[OROUGH]=E O","#:[OR] =E","#:[ORS] =E SS","[OR]=aa RR"," [ONE]=FF aa nn","[OW]=O"," [OVER]=O FF E","[OV]=aa FF","[O]^%=O","[O]^EN=O","[O]^I#=O","[OL]D=O nn","[OUGHT]=aa DD","[OUGH]=aa FF"," [OU]=aa","H[OU]S#=aa","[OUS]=aa SS","[OUR]=aa RR","[OULD]=U DD","^[OU]^L=aa","[OUP]=U OO","[OU]=aa","[OY]=O","[OING]=O I nn","[OI]=O","[OOR]=aa RR","[OOK]=U kk","[OOD]=U DD","[OO]=U","[O]E=O","[O] =O","[OA]=O"," [ONLY]=O nn nn I"," [ONCE]=FF aa nn SS","[ON'T]=O nn DD","C[O]N=aa","[O]NG=aa"," ^:[O]N=aa","I[ON]=aa nn","#:[ON] =aa nn","#^[ON]=aa nn","[O]ST =O","[OF]^=aa FF","[OTHER]=aa TH E","[OSS] =aa SS","#^:[OM]=aa PP","[O]=aa"],P:["[PH]=FF","[PEOP]=PP I PP","[POW]=PP aa","[PUT] =PP U DD","[P]=PP"],Q:["[QUAR]=kk FF aa RR","[QU]=kk FF","[Q]=kk"],R:[" [RE]^#=RR I","[R]=RR"],S:["[SH]=SS","#[SION]=SS aa nn","[SOME]=SS aa PP","#[SUR]#=SS E","[SUR]#=SS E","#[SU]#=SS U","#[SSU]#=SS U","#[SED] =SS DD","#[S]#=SS","[SAID]=SS E DD","^[SION]=SS aa nn","[S]S=",".[S] =SS","#:.E[S] =SS","#^:##[S] =SS","#^:#[S] =SS","U[S] =SS"," :#[S] =SS"," [SCH]=SS kk","[S]C+=","#[SM]=SS PP","#[SN]'=SS aa nn","[S]=SS"],T:[" [THE] =TH aa","[TO] =DD U","[THAT] =TH aa DD"," [THIS] =TH I SS"," [THEY]=TH E"," [THERE]=TH E RR","[THER]=TH E","[THEIR]=TH E RR"," [THAN] =TH aa nn"," [THEM] =TH E PP","[THESE] =TH I SS"," [THEN]=TH E nn","[THROUGH]=TH RR U","[THOSE]=TH O SS","[THOUGH] =TH O"," [THUS]=TH aa SS","[TH]=TH","#:[TED] =DD I DD","S[TI]#N=CH","[TI]O=SS","[TI]A=SS","[TIEN]=SS aa nn","[TUR]#=CH E","[TU]A=CH U"," [TWO]=DD U","[T]=DD"],U:[" [UN]I=I U nn"," [UN]=aa nn"," [UPON]=aa PP aa nn","@[UR]#=U RR","[UR]#=I U RR","[UR]=E","[U]^ =aa","[U]^^=aa","[UY]=aa"," G[U]#=","G[U]%=","G[U]#=FF","#N[U]=I U","@[U]=I","[U]=I U"],V:["[VIEW]=FF I U","[V]=FF"],W:[" [WERE]=FF E","[WA]S=FF aa","[WA]T=FF aa","[WHERE]=FF E RR","[WHAT]=FF aa DD","[WHOL]=I O nn","[WHO]=I U","[WH]=FF","[WAR]=FF aa RR","[WOR]^=FF E","[WR]=RR","[W]=FF"],X:[" [X]=SS","[X]=kk SS"],Y:["[YOUNG]=I aa nn"," [YOU]=I U"," [YES]=I E SS"," [Y]=I","#^:[Y] =I","#^:[Y]I=I"," :[Y] =aa"," :[Y]#=aa"," :[Y]^+:#=I"," :[Y]^#=I","[Y]=I"],Z:["[Z]=SS"]};const t={"#":"[AEIOUY]+",".":"[BDVGJLMNRWZ]","%":"(?:ER|E|ES|ED|ING|ELY)","&":"(?:[SCGZXJ]|CH|SH)","@":"(?:[TSRDLZNJ]|TH|CH|SH)","^":"[BCDFGHJKLMNPQRSTVWXZ]","+":"[EIY]",":":"[BCDFGHJKLMNPQRSTVWXZ]*"," ":"\\b"};Object.keys(this.rules).forEach(e=>{this.rules[e]=this.rules[e].map(n=>{const o=n.indexOf("["),s=n.indexOf("]"),i=n.indexOf("="),r=n.substring(0,o),c=n.substring(o+1,s),l=n.substring(s+1,i),u=n.substring(i+1),a={regex:"",move:0,visemes:[]};let d="";d+=[...r].map(g=>t[g]||g).join("");const h=[...c];return h[0]=h[0].toLowerCase(),d+=h.join(""),a.move=h.length,d+=[...l].map(g=>t[g]||g).join(""),a.regex=new RegExp(d),u.length&&u.split(" ").forEach(g=>{a.visemes.push(g)}),a})}),this.visemeDurations={aa:.95,E:.9,I:.92,O:.96,U:.95,PP:1.08,SS:1.23,TH:1,DD:1.05,FF:1,kk:1.21,nn:.88,RR:.88,DD:1.05,sil:1},this.specialDurations={" ":1,",":3,"-":.5,"'":.5},this.digits=["oh","one","two","three","four","five","six","seven","eight","nine"],this.ones=["","one","two","three","four","five","six","seven","eight","nine"],this.tens=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"],this.teens=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],this.decades={20:"twenties",30:"thirties",40:"forties",50:"fifties",60:"sixties",70:"seventies",80:"eighties",90:"nineties"},this.ordinals={1:"first",2:"second",3:"third",4:"fourth",5:"fifth",6:"sixth",7:"seventh",8:"eighth",9:"ninth",10:"tenth",11:"eleventh",12:"twelfth",13:"thirteenth",14:"fourteenth",15:"fifteenth",16:"sixteenth",17:"seventeeth",18:"eighteenth",19:"nineteenth",20:"twentieth",30:"thirtieth",40:"fortieth",50:"fiftieth",60:"sixtieth",70:"seventieth",80:"eightieth",90:"ninetieth"},this.symbols={"%":"percent","€":"euros","&":"and","+":"plus",$:"dollars"},this.symbolsReg=/[%€&\+\$]/g}convert_digit_by_digit(t){t=String(t).split("");let e="";for(let n=0;n<t.length;n++)e+=this.digits[t[n]]+" ";return e=e.substring(0,e.length-1),e}convert_sets_of_two(t){let e=String(t).substring(0,2),n=String(t).substring(2,4),o=this.convert_tens(e);return o+=" "+this.convert_tens(n),o}convert_millions(t){return t>=1e6?this.convert_millions(Math.floor(t/1e6))+" million "+this.convert_thousands(t%1e6):this.convert_thousands(t)}convert_thousands(t){return t>=1e3?this.convert_hundreds(Math.floor(t/1e3))+" thousand "+this.convert_hundreds(t%1e3):this.convert_hundreds(t)}convert_hundreds(t){return t>99?this.ones[Math.floor(t/100)]+" hundred "+this.convert_tens(t%100):this.convert_tens(t)}convert_tens(t){return t<10?(Number(t)!=0&&t.toString().startsWith("0")?"oh ":"")+this.ones[Number(t)]:t>=10&&t<20?this.teens[t-10]:(this.tens[Math.floor(t/10)]+" "+this.ones[t%10]).trim()}convertNumberToWords(t,e=!1){const n=parseFloat(t);if(t=="0")return"zero";if(t<0)return" minus "+this.convertNumberToWords(Math.abs(t).toString(),e).trim();if(n&&!Number.isInteger(n)){const o=n.toString().split(".");return this.convertNumberToWords(o[0],e).trim()+" point "+this.convert_digit_by_digit(o[1]).trim()}else return t.toString().startsWith("0")?this.convert_digit_by_digit(t).trim():!e&&(t<1e3&&t>99&&t%100!==0||t>1e4&&t<1e6)?this.convert_digit_by_digit(t).trim():!e&&(t>1e3&&t<2e3||t>2009&&t<3e3)?t%100!=0?this.convert_sets_of_two(t).trim():this.convert_tens(t.toString().substring(0,2)).trim()+" hundred":this.convert_millions(t).trim()}convertDecade(t){const e=parseInt(t),n=!isNaN(e)&&t.length===2,o=!isNaN(e)&&t.length>2&&e>0&&e<=3e3,s=o&&e%1e3===0?Math.floor(e/1e3):null,i=o&&!s?Math.floor(e/100):null,r=n||o?Math.floor(e%100/10)*10:null;let c=[];return s?c.push(this.convertNumberToWords(s).trim(),"thousands"):(i&&c.push(this.convertNumberToWords(i).trim()),r?c.push(this.decades[r]||this.convertNumberToWords(r).trim()+"s"):i?c.push("hundreds"):c.push(t)),c.join(" ")}convertOrdinal(t){if(this.ordinals.hasOwnProperty(t))return this.ordinals[t];const e=Math.floor(t/100),n=Math.floor(t%100/10)*10,o=t%10;let s=[];return e&&(s.push(this.convertNumberToWords(e).trim()),n||o?s.push("hundred"):s.push("hundredth")),n&&(o?s.push(this.convertNumberToWords(n).trim()):s.push(this.ordinals[n])),o&&s.push(this.ordinals[o]),s.join(" ")}preProcessText(t){let e=t.replace('/[#_*":;]/g',"");return e=e.replace(this.symbolsReg,n=>" "+this.symbols[n]+" "),/\d/.test(e)&&(e=e.replace(/\b(\d{2,4})[''']?\s?[sS](?=\s|[.,!?;:]|$)/g,(n,o)=>{const s=this.convertDecade(o);return s===o?n:s}),e=e.replace(/\b(\d+)\s*(st|nd|rd|th)(?=\s|[.,!?;:]|$)/gi,(n,o)=>this.convertOrdinal(Number(o))),e=e.replace(/\b(\w*?)(\d+)([A-Za-z]+)\b/g,(n,o,s,i)=>{const r=this.convertNumberToWords(s);return`${o}${r} ${i}`}).replace(/\b([A-Za-z]+)(\d+)(\w*?)\b/g,(n,o,s,i)=>{const r=this.convertNumberToWords(s);return`${o} ${r}${i}`}),e=e.replace(/-?(?:\d{1,3}(?:,\d{3})+|\d+)(\.\d+)?/g,(n,o)=>{let s=n,i=!1;return/,/.test(s)&&(s=s.replace(/,/g,""),i=!0),o&&(i=!0),this.convertNumberToWords(s,i)})),e=e.replace(/(\D)\1\1+/g,"$1$1").replaceAll(" "," ").normalize("NFD").replace(/[\u0300-\u036f]/g,"").normalize("NFC").trim(),e}wordsToVisemes(t){let e={words:t.toUpperCase(),visemes:[],times:[],durations:[],i:0},n=0;const o=[...e.words];for(;e.i<o.length;){const s=o[e.i],i=this.rules[s];if(i)for(let r=0;r<i.length;r++){const c=i[r];if((e.words.substring(0,e.i)+s.toLowerCase()+e.words.substring(e.i+1)).match(c.regex)){c.visemes.forEach(a=>{if(e.visemes.length&&e.visemes[e.visemes.length-1]===a){const d=.7*(this.visemeDurations[a]||1);e.durations[e.durations.length-1]+=d,n+=d}else{const d=this.visemeDurations[a]||1;e.visemes.push(a),e.times.push(n),e.durations.push(d),n+=d}}),e.i+=c.move;break}}else e.i++,n+=this.specialDurations[s]||0}return e}}const ht=Object.freeze(Object.defineProperty({__proto__:null,LipsyncEn:ct},Symbol.toStringTag,{value:"Module"}));class dt{constructor(){this.rules={A:["[AH]=aa","[AU]=aa U","[AI]=aa I","[AE]=E","[A]H=aa","[A]U=aa U","[A]I=aa I"," [AN] =aa nn"," [AM] =aa PP","[ARR]=aa RR","[AR]=aa RR"," [ALS]=aa nn SS","[AL]=aa nn","[AUCH]=aa U kk","[ABER]=aa PP E RR","[A]=aa"],Ä:["[Ä]H=E","[ÄU]=O","[Ä]=E"],B:["[B]=PP"],C:["[CH]S=kk SS","[CH]=kk"," [CH]=kk","#[CH]=kk","[CK]=kk","[C]H=kk","[C]=kk"],D:[" [DAS] =DD aa SS"," [DEN] =DD E nn"," [DER] =DD E RR"," [DIE] =DD I"," [DU] =DD U"," [DURCH]=DD U RR kk","[D]=DD"],E:["[EI]=aa I","[EU]=O","[EH]=E"," [ER] =E RR"," [ES] =E SS"," [EIN] =aa I nn"," [EINE]=aa I nn aa","[ER]#=E","[ER]=E RR","[EN]#=aa nn","[E]=E"],F:["[F]=FF"],G:["[G]=kk"],H:[" [HAT] =I aa DD"," [HABEN]=I aa PP aa nn"," [HIER]=I I RR"," [HEUTE]=I O DD aa","[H]="],I:[" [ICH] =I kk"," [IHR] =I RR"," [IN] =I nn"," [IST] =I SS DD"," [IM] =I PP","[IE]=I","[IH]=I","[I]=I"],J:["[J]=I"],K:["[K]=kk"],L:["[L]=nn"],M:[" [MIT] =PP I DD"," [MAN] =PP aa nn"," [MEHR]=PP E RR"," [MICH]=PP I kk","[M]=PP"],N:[" [NICHT]=nn I kk DD"," [NUR] =nn U RR"," [NACH]=nn aa kk"," [NOCH]=nn aa kk","[NG]=nn kk","[N]=nn"],O:["[OO]=U","[OH]=O","[OU]=aa U"," [ODER]=O DD E RR"," [OHNE]=O nn aa","[Ö]=E","[O]=aa"],Ö:["[ÖH]=E","[Ö]=E"],P:["[PF]=FF FF","[PH]=FF","[P]=PP"],Q:["[QU]=kk FF","[Q]=kk"],R:["[R]=RR"],S:["[SCH]=SS","[SP]=SS PP","[ST]=SS DD","[SS]=SS","[S]=SS"],ß:["[ß]=SS"],T:["[TZ]=DD SS","[TH]=DD","[T]=DD"],U:[" [UND] =U nn DD"," [UM] =U PP"," [UNTER]=U nn DD E RR"," [UNS] =U nn SS","[UH]=U","[ÜH]=I U","[Ü]=I U","[U]=U"],Ü:["[ÜH]=I U","[Ü]=I U"],V:[" [VON] =FF aa nn"," [VOR] =FF aa RR"," [VIEL]=FF I nn","[V]=FF"],W:[" [WAS] =FF aa SS"," [WIR] =FF I RR"," [WIE] =FF I"," [WENN]=FF E nn"," [WILL]=FF I nn"," [WO] =FF aa"," [WIEDER]=FF I DD E RR","[W]=FF"],X:["[X]=kk SS"],Y:["[Y]=I"],Z:[" [ZU] =DD SS U"," [ZUM] =DD SS U PP"," [ZUR] =DD SS U RR"," [ZEIT]=DD SS aa I DD","[Z]=DD SS"]};const t={"#":"[AEIOUÄÖÜ]+",".":"[BDVGJLMNRWZ]","%":"(?:ER|E|ES|ED|ING|ELY|EN|TE|ST)","&":"(?:[SCGZXJ]|CH|SCH|TZ)","@":"(?:[TSRDLZNJ]|TH|CH|SCH)","^":"[BCDFGHJKLMNPQRSTVWXYZß]","+":"[EIY]",":":"[BCDFGHJKLMNPQRSTVWXYZß]*"," ":"\\b"};Object.keys(this.rules).forEach(e=>{this.rules[e]=this.rules[e].map(n=>{const o=n.indexOf("["),s=n.indexOf("]"),i=n.indexOf("="),r=n.substring(0,o),c=n.substring(o+1,s),l=n.substring(s+1,i),u=n.substring(i+1),a={regex:"",move:0,visemes:[]};let d="";d+=[...r].map(g=>t[g]||g).join("");const h=[...c];return h[0]=h[0].toLowerCase(),d+=h.join(""),a.move=h.length,d+=[...l].map(g=>t[g]||g).join(""),a.regex=new RegExp(d),u.length&&u.split(" ").forEach(g=>{a.visemes.push(g)}),a})}),this.visemeDurations={aa:1,E:.85,I:.9,O:1.05,U:1,PP:1.15,SS:1.2,TH:1,DD:1.1,FF:1.05,kk:1.25,nn:.85,RR:.9,sil:1},this.specialDurations={" ":1,",":3,"-":.5,"'":.5,".":4,"!":3,"?":3},this.digits=["null","eins","zwei","drei","vier","fünf","sechs","sieben","acht","neun"],this.ones=["","ein","zwei","drei","vier","fünf","sechs","sieben","acht","neun"],this.tens=["","","zwanzig","dreißig","vierzig","fünfzig","sechzig","siebzig","achtzig","neunzig"],this.teens=["zehn","elf","zwölf","dreizehn","vierzehn","fünfzehn","sechzehn","siebzehn","achtzehn","neunzehn"],this.symbols={"%":"prozent","€":"euro","&":"und","+":"plus",$:"dollar","=":"gleich","@":"at","#":"hashtag"},this.symbolsReg=/[%€&\+\$=@#]/g}convert_digit_by_digit(t){t=String(t).split("");let e="";for(let n=0;n<t.length;n++)e+=this.digits[t[n]]+" ";return e=e.substring(0,e.length-1),e}convert_millions(t){if(t>=1e6){const e=Math.floor(t/1e6),n=t%1e6;let o=this.convert_thousands(e);return o+=e===1?" million ":" millionen ",n>0&&(o+=this.convert_thousands(n)),o}else return this.convert_thousands(t)}convert_thousands(t){if(t>=1e3){const e=Math.floor(t/1e3),n=t%1e3;let o="";return e===1?o="eintausend":o=this.convert_hundreds(e)+"tausend",n>0&&(o+=this.convert_hundreds(n)),o}else return this.convert_hundreds(t)}convert_hundreds(t){if(t>99){const e=Math.floor(t/100),n=t%100;let o="";return e===1?o="einhundert":o=this.ones[e]+"hundert",n>0&&(o+=this.convert_tens(n)),o}else return this.convert_tens(t)}convert_tens(t){if(t<10)return this.ones[Number(t)]||"";if(t>=10&&t<20)return this.teens[t-10];{const e=Math.floor(t/10),n=t%10;return n===0?this.tens[e]:this.ones[n]+"und"+this.tens[e]}}convertNumberToWords(t){const e=String(t);return t=="0"?"null":e.startsWith("0")?this.convert_digit_by_digit(t):e.length===4&&(t<1e3||t>2100)?this.convert_digit_by_digit(t):this.convert_millions(Number(t))}preProcessText(t){return t.replace(/[#_*\":;]/g,"").replace(this.symbolsReg,e=>" "+this.symbols[e]+" ").replace(/(\d)\.(\d)/g,"$1 komma $2").replace(/(\d),(\d)/g,"$1 komma $2").replace(/\d+/g,this.convertNumberToWords.bind(this)).replace(/(\D)\1\1+/g,"$1$1").replace(/\s+/g," ").toLowerCase().trim()}wordsToVisemes(t){let e={words:t.toUpperCase(),visemes:[],times:[],durations:[],i:0},n=0;const o=[...e.words];for(;e.i<o.length;){const s=o[e.i],i=this.rules[s];if(i){let r=!1;for(let c=0;c<i.length;c++){const l=i[c];if((e.words.substring(0,e.i)+s.toLowerCase()+e.words.substring(e.i+1)).match(l.regex)){l.visemes.forEach(d=>{if(e.visemes.length&&e.visemes[e.visemes.length-1]===d){const h=.7*(this.visemeDurations[d]||1);e.durations[e.durations.length-1]+=h,n+=h}else{const h=this.visemeDurations[d]||1;e.visemes.push(d),e.times.push(n),e.durations.push(h),n+=h}}),e.i+=l.move,r=!0;break}}r||(e.i++,n+=this.specialDurations[s]||0)}else e.i++,n+=this.specialDurations[s]||0}return e}}const mt=Object.freeze(Object.defineProperty({__proto__:null,LipsyncDe:dt},Symbol.toStringTag,{value:"Module"}));class pt{constructor(){this.rules={A:["[AN]C=aa nn","[AN]G=aa nn","[AN]T=aa nn","[AN]D=aa nn","[AN] =aa nn","[AN]$=aa nn","[AM]P=aa nn","[AM]B=aa nn","[AM] =aa nn","[AM]$=aa nn","[AI]N=E nn","[AIM]=E nn","[AIN]=E nn","[AU]=O","[AUX]=O","[AUT]=O","[AI]=E","[AY]=E","[A]=aa"],À:["[À]=aa"],Â:["[Â]=aa"],B:[" [B] =PP","[BB]=PP","[B]=PP"],C:["[C]E=SS","[C]I=SS","[C]Y=SS","[C]È=SS","[C]É=SS","[C]Ê=SS","[CH]=SS","[C]A=kk","[C]O=kk","[C]U=kk","[C]L=kk","[C]R=kk","[CK]=kk","[C]=kk"],Ç:["[Ç]=SS"],D:["[D]=DD"],E:["[EN]C=aa nn","[EN]T=aa nn","[EN]D=aa nn","[EN] =aa nn","[EN]$=aa nn","[EM]P=aa nn","[EM]B=aa nn","[EM] =aa nn","[EM]$=aa nn","[EAU]=O","[EAU]X=O","[EU]=U","[EUX]=U","[EUR]=U RR","[EI]=E","[EIN]=E nn","[ER] =E","[ER]$=E","[EZ] =E","[EZ]$=E","[ED] =E","[ED]$=E"," [E] =","[E] =","[E]$=","[E]S =","[E]S$=","[E]NT =","[E]NT$=","[È]=E","[É]=E","[Ê]=E","[Ë]=E","[E]=E"],È:["[È]=E"],É:["[É]=E"],Ê:["[Ê]=E"],Ë:["[Ë]=E"],F:["[FF]=FF","[F]=FF","[PH]=FF"],G:["[G]E=SS","[G]I=SS","[G]Y=SS","[G]È=SS","[G]É=SS","[G]Ê=SS","[GN]=nn I","[GN]E=nn","[GN]A=nn aa","[GN]O=nn O","[GU]E=kk","[GU]I=kk","[GU]A=kk FF aa","[GU]O=kk FF O","[G]A=kk","[G]O=kk","[G]U=kk","[G]L=kk","[G]R=kk","[GG]=kk","[G]=kk"],H:["[H]="],I:["[IN]C=E nn","[IN]T=E nn","[IN]D=E nn","[IN] =E nn","[IN]$=E nn","[IM]P=E nn","[IM]B=E nn","[IM] =E nn","[IM]$=E nn","[IEN]=I E nn","[IER]=I E","[IEU]=I U","[IEZ]=I E","[ILL]E=I","[ILLE]=I","[ILL]=I","[Î]=I","[Ï]=I","[I]=I"],Î:["[Î]=I"],Ï:["[Ï]=I"],J:["[J]=SS"],K:["[K]=kk"],L:["[LL]E=","[LLE]=","[LL]A=I aa","[LL]O=I O","[LL]U=I U","[LL]I=I","[LL]=I","[L]=nn"],M:["[MM]=PP","[M]=PP"],N:["[NN]=nn","[N]=nn"],O:["[ON]C=O nn","[ON]T=O nn","[ON]D=O nn","[ON] =O nn","[ON]$=O nn","[OM]P=O nn","[OM]B=O nn","[OM] =O nn","[OM]$=O nn","[OI]N=FF E nn","[OI]G=FF aa","[OI]S=FF aa","[OI]T=FF aa","[OI]X=FF aa","[OI]=FF aa","[OU]=U","[OÙ]=U","[OÛ]=U","[OEU]=U","[OEUR]=U RR","[OUGH]=U FF","[OUGH]T=U","[Ô]=O","[O]=O"],Ô:["[Ô]=O"],Ù:["[Ù]=U"],Û:["[Û]=U"],P:["[PH]=FF","[PP]=PP","[P]=PP"],Q:["[QU]=kk","[Q]=kk"],R:["[RR]=RR","[R]=RR"],S:["#[S]#=SS"," [S]=SS","[SS]=SS","[S] =","[S]$=","[SC]E=SS","[SC]I=SS","[SC]Y=SS","[S]=SS"],T:["[TI]A=SS I aa","[TI]E=SS I E","[TI]O=SS I O","[TI]ON=SS I O nn","[TH]=DD","[TT]=DD","[T] =","[T]$=","[T]=DD"],U:["[UN]C=U nn","[UN]T=U nn","[UN]D=U nn","[UN] =U nn","[UN]$=U nn","[UM]=U nn","[UE]=I","[UEI]=I E","[UEIL]=I I","[UILL]=I","[Ù]=U","[Û]=U","[Ü]=I U","[U]=I U"],Ü:["[Ü]=I U"],V:["[V]=FF"],W:["[W]=FF"],X:["[X] =","[X]$=","#[X]#=kk SS"," [X]=kk SS","[X]=kk SS"],Y:["[Y]=I"," [Y]=I","[YE]=I E","[YA]=I aa","[YO]=I O","[YU]=I U"],Z:["[Z]=SS"]};const t={"#":"[AEIOUYÀÂÈÉÊËÎÏÔÙÛÜ]+",".":"[BDVGJLMNRWZ]","%":"(?:ER|E|ES|ÉS|ÈS|ÊS|ENT|MENT|TION|SION)","&":"(?:[SCGZXJ]|CH|SH|GN)","@":"(?:[TSRDLZNJ]|TH|CH|SH|GN)","^":"[BCDFGHJKLMNPQRSTVWXZÇ]+","+":"[EIYÈÉÊËÎÏ]",":":"[BCDFGHJKLMNPQRSTVWXZÇ]*"," ":"\\b",$:"$"};Object.keys(this.rules).forEach(e=>{this.rules[e]=this.rules[e].map(n=>{const o=n.indexOf("["),s=n.indexOf("]"),i=n.indexOf("="),r=n.substring(0,o),c=n.substring(o+1,s),l=n.substring(s+1,i),u=n.substring(i+1),a={regex:"",move:0,visemes:[]};let d="";d+=[...r].map(g=>t[g]||g).join("");const h=[...c];return h[0]=h[0].toLowerCase(),d+=h.join(""),a.move=h.length,d+=[...l].map(g=>t[g]||g).join(""),a.regex=new RegExp(d,"i"),u.length&&u.split(" ").forEach(g=>{g&&a.visemes.push(g)}),a})}),this.visemeDurations={aa:1,E:.95,I:.9,O:1.05,U:.95,PP:1.1,SS:1.25,TH:1,DD:1.05,FF:1,kk:1.2,nn:.88,RR:1.15,sil:1},this.specialDurations={" ":1,",":2.5,".":3.5,";":2.8,":":2.2,"!":3.2,"?":3.2,"-":.8,"'":.3,'"':.3,"(":1.5,")":1.5},this.digits=["zéro","un","deux","trois","quatre","cinq","six","sept","huit","neuf"],this.ones=["","un","deux","trois","quatre","cinq","six","sept","huit","neuf"],this.teens=["dix","onze","douze","treize","quatorze","quinze","seize","dix-sept","dix-huit","dix-neuf"],this.tens=["","dix","vingt","trente","quarante","cinquante","soixante","soixante-dix","quatre-vingts","quatre-vingt-dix"],this.symbols={"%":"pourcent","€":"euros","&":"et","+":"plus",$:"dollars","=":"égale","@":"arobase","#":"dièse","°":"degrés"},this.symbolsReg=/[%€&\+\$=@#°]/g}convert_digit_by_digit(t){t=String(t).split("");let e="";for(let n=0;n<t.length;n++)e+=this.digits[t[n]]+" ";return e=e.substring(0,e.length-1),e}convert_tens(t){if(t<10)return this.ones[t]||"";if(t>=10&&t<20)return this.teens[t-10];if(t>=70&&t<80){const e=t-60;return e===11?"soixante et onze":"soixante-"+this.teens[e-10]}else if(t>=90){const e=t-80;return e===11?"quatre-vingt-onze":"quatre-vingt-"+this.teens[e-10]}else{const e=Math.floor(t/10),n=t%10;return e===8&&n===0?"quatre-vingts":e===8?"quatre-vingt-"+this.ones[n]:(e===2||e===3||e===4||e===5||e===6)&&n===1?this.tens[e]+" et un":n===0?this.tens[e]:this.tens[e]+"-"+this.ones[n]}}convert_hundreds(t){if(t>=100){const e=Math.floor(t/100),n=t%100;let o="";return e===1?o="cent":(o=this.ones[e]+" cent",n===0&&(o+="s")),n>0&&(o+=" "+this.convert_tens(n)),o}else return this.convert_tens(t)}convert_thousands(t){if(t>=1e3){const e=Math.floor(t/1e3),n=t%1e3;let o="";return e===1?o="mille":o=this.convert_hundreds(e)+" mille",n>0&&(o+=" "+this.convert_hundreds(n)),o}else return this.convert_hundreds(t)}convert_millions(t){if(t>=1e6){const e=Math.floor(t/1e6),n=t%1e6;let o="";return e===1?o="un million":o=this.convert_hundreds(e)+" millions",n>0&&(o+=" "+this.convert_thousands(n)),o}else return this.convert_thousands(t)}convertNumberToWords(t){const e=String(t);return t==="0"||t===0?"zéro":e.startsWith("0")?this.convert_digit_by_digit(t):this.convert_millions(Number(t))}preProcessText(t){return t.replace(/[#_*\":;]/g,"").replace(this.symbolsReg,e=>" "+this.symbols[e]+" ").replace(/(\d)[,.](\d)/g,"$1 virgule $2").replace(/\d+/g,this.convertNumberToWords.bind(this)).replace(/(\D)\1\1+/g,"$1$1").replace(/\s+/g," ").replace(/'/g,"'").trim()}wordsToVisemes(t){let e={words:t.toUpperCase(),visemes:[],times:[],durations:[],i:0},n=0;const o=[...e.words];for(;e.i<o.length;){const s=o[e.i],i=this.rules[s];if(i){let r=!1;for(let c=0;c<i.length;c++){const l=i[c];if((e.words.substring(0,e.i)+s.toLowerCase()+e.words.substring(e.i+1)).match(l.regex)){l.visemes.forEach(d=>{if(e.visemes.length&&e.visemes[e.visemes.length-1]===d){const h=.7*(this.visemeDurations[d]||1);e.durations[e.durations.length-1]+=h,n+=h}else{const h=this.visemeDurations[d]||1;e.visemes.push(d),e.times.push(n),e.durations.push(h),n+=h}}),e.i+=l.move,r=!0;break}}r||(e.i++,n+=this.specialDurations[s]||0)}else e.i++,n+=this.specialDurations[s]||0}return e}}const gt=Object.freeze(Object.defineProperty({__proto__:null,LipsyncFr:pt},Symbol.toStringTag,{value:"Module"}));class yt{constructor(){this.visemes={a:"aa",e:"E",i:"I",o:"O",u:"U",y:"U",ä:"aa",ö:"O",å:"O",b:"PP",c:"SS",d:"DD",f:"FF",g:"kk",h:"kk",j:"I",k:"kk",l:"nn",m:"PP",n:"nn",p:"PP",q:"kk",r:"RR",s:"SS",t:"DD",v:"FF",w:"FF",x:"SS",z:"SS"},this.visemeDurations={aa:.95,E:.9,I:.92,O:.96,U:.95,PP:1.08,SS:1.23,DD:1.05,FF:1,kk:1.21,nn:.88,RR:.88,DD:1.05,sil:1},this.specialDurations={" ":1,",":3,"-":.5},this.numbers=["nolla","yksi","kaksi","kolme","neljä","viisi","kuusi","seitsemän","kahdeksan","yhdeksän","kymmenen","yksitoista","kaksitoista","kolmetoista","neljätoista","viisitoista","kuusitoista","seitsemäntoista","kahdeksantoista","yhdeksäntoista"],this.symbols={"%":"prosenttia","€":"euroa","&":"ja","+":"plus",$:"dollaria"},this.symbolsReg=/[%€&\+\$]/g}numberToFinnishWords(t){const e=[];let n=parseFloat(t);if(n===void 0)return t;let o=(s,i,r,c,l)=>{if(s<i)return s;const u=Math.floor(s/i);return e.push(r+(u===1?c:this.numberToFinnishWords(u.toString())+l)),s-u*i};if(n<0&&(e.push("miinus "),n=Math.abs(n)),n=o(n,1e9," ","miljardi"," miljardia"),n=o(n,1e6," ","miljoona"," miljoonaa"),n=o(n,1e3,"","tuhat","tuhatta"),n=o(n,100," ","sata","sataa"),n>20&&(n=o(n,10,"","","kymmentä")),n>=1){let s=Math.floor(n);e.push(this.numbers[s]),n-=s}if(n>=0&&Math.abs(parseFloat(t))<1&&e.push("nolla"),n>0){let s=t.split(".");if(s.length>1){e.push(" pilkku");let i=[...s[s.length-1]];for(let r=0;r<i.length;r++)e.push(" "+this.numbers[i[r]])}}return e.join("").trim()}preProcessText(t){return t.replace(/[#_*\'\":;]/g,"").replace(this.symbolsReg,e=>" "+this.symbols[e]+" ").replace(/(\d)\,(\d)/g,"$1 pilkku $2").replace(/\d+/g,this.numberToFinnishWords.bind(this)).replaceAll(" "," ").normalize("NFD").replace(/[\u0300-\u0307\u0309\u030b-\u036f]/g,"").normalize("NFC").trim()}wordsToVisemes(t){let e={words:t,visemes:[],times:[],durations:[]},n=0;const o=[...t];for(let s=0;s<o.length;s++){const i=this.visemes[o[s].toLowerCase()];if(i)if(e.visemes.length&&e.visemes[e.visemes.length-1]===i){const r=.7*(this.visemeDurations[i]||1);e.durations[e.durations.length-1]+=r,n+=r}else{const r=this.visemeDurations[i]||1;e.visemes.push(i),e.times.push(n),e.durations.push(r),n+=r}else n+=this.specialDurations[o[s]]||0}return e}}const ft=Object.freeze(Object.defineProperty({__proto__:null,LipsyncFi:yt},Symbol.toStringTag,{value:"Module"}));class xt{constructor(){this.visemes={a:"aa",ą:"O",e:"E",ę:"E",ė:"E",i:"I",į:"I",o:"O",u:"U",ū:"U",ų:"U",y:"I",b:"PP",c:"SS",č:"SS",d:"DD",f:"FF",g:"kk",h:"kk",j:"I",k:"kk",l:"nn",m:"PP",n:"nn",p:"PP",q:"kk",r:"RR",s:"SS",š:"CH",t:"DD",v:"FF",w:"FF",x:"SS",z:"SS",ž:"SS"},this.durations={a:.95,ą:1.5,e:.9,ę:1.5,ė:1.5,i:.92,į:1.5,o:.96,u:.95,ū:1.5,ų:1.5,y:1.5,b:1.08,c:1.23,d:1.05,f:1,g:1.21,h:1.21,j:.92,k:1.21,l:.88,m:1.08,n:.88,p:1.08,q:1.21,r:.88,s:1.23,š:1.23,t:1.05,v:1,w:1,x:1.23,z:1.23,ž:1.23},this.pauses={" ":1,",":3,"-":.5},this.numbers=["nulis","vienas","du","trys","keturi","penki","šeši","septyni","aštuoni","devyni","dešimt","vienuolika","dvylika","trylika","keturiolika","penkiolika","šešiolika","septyniolika","aštuoniolika","devyniolika"],this.tens=[this.numbers[0],this.numbers[10],"dvidešimt","trisdešimt","keturiasdešimt","penkiasdešimt","šešiasdešimt","septyniasdešimt","aštuoniasdešimt","devyniasdešimt"]}numberToLithuanianWords(t){const e=[];let n=parseFloat(t);if(n===void 0)return t;let o=(s,i,r,c,l)=>{if(s<i)return s;const u=Math.floor(s/i);return u===1?e.push(this.numbers[1]):e.push(this.numberToLithuanianWords(u.toString())),u%10===1?e.push(r):u%10===0||u%100>10&&u%100<20?e.push(l):e.push(c),s-u*i};n<0&&(e.push("minus"),n=Math.abs(n)),n=o(n,1e9,"milijardas","milijardai","milijardų"),n=o(n,1e6,"milijonas","milijonai","milijonų"),n=o(n,1e3,"tūkstantis","tūkstančiai","tūkstančių"),n=o(n,100,"šimtas","šimtai","šimtų");for(let s=this.tens.length-1;s>=1;s--)if(n>=10*s){e.push(this.tens[s]),n=n-10*s;break}if(n>=1){let s=Math.floor(n);e.push(this.numbers[s]),n-=s}if(n>=0&&Math.abs(parseFloat(t))<1&&e.push(this.numbers[0]),n>0){let s=t.split(".");if(s.length>1){e.push("kablelis");let i=[...s[s.length-1]];for(let r=0;r<i.length;r++)e.push(this.numbers[i[r]])}}return e.join(" ").trim()}preProcessText(t){return t.replace(`/[#_*'":;]/g`,"").replaceAll("0 %","0 procentų ").replaceAll("1 %","1 procentas ").replaceAll("%"," procentai ").replaceAll("0 €","0 eurų ").replaceAll("1 €","1 euras ").replaceAll("€"," eurai ").replaceAll("0 $","0 dolerių ").replaceAll("1 $","1 doleris ").replaceAll("$"," doleriai ").replaceAll("&"," ir ").replaceAll("+"," pliusas ").replace(/(\d)\,(\d)/g,"$1 kablelis $2").replace(/\d+/g,this.numberToLithuanianWords.bind(this)).replace(/(\D)\1\1+/g,"$1$1").replaceAll(" "," ").normalize("NFD").replace(/[\u0300-\u0303\u0305\u0306\u0308-\u0327\u0329-\u036f]/g,"").normalize("NFC").trim()}wordsToVisemes(t){let e={words:t,visemes:[],times:[],durations:[]},n=0;const o=[...t];for(let s=0;s<o.length;s++){const i=o[s].toLowerCase(),r=this.visemes[i];if(r)if(e.visemes.length&&e.visemes[e.visemes.length-1]===r){const c=.7*(this.durations[i]||1);e.durations[e.durations.length-1]+=c,n+=c}else{const c=this.durations[i]||1;e.visemes.push(r),e.times.push(n),e.durations.push(c),n+=c}else n+=this.pauses[o[s]]||0}return e}}const bt=Object.freeze(Object.defineProperty({__proto__:null,LipsyncLt:xt},Symbol.toStringTag,{value:"Module"})),Rt=new URL("data:text/javascript;base64,Y2xhc3MgUGxheWJhY2tXb3JrbGV0IGV4dGVuZHMgQXVkaW9Xb3JrbGV0UHJvY2Vzc29yIHsKICBzdGF0aWMgRlNNID0gewogICAgSURMRTogMCwKICAgIFBMQVlJTkc6IDEsCiAgfTsKCiAgY29uc3RydWN0b3Iob3B0aW9ucykgewogICAgc3VwZXIoKTsKICAgIHRoaXMucG9ydC5vbm1lc3NhZ2UgPSB0aGlzLmhhbmRsZU1lc3NhZ2UuYmluZCh0aGlzKTsKCiAgICB0aGlzLl9zYW1wbGVSYXRlID0gb3B0aW9ucz8ucHJvY2Vzc29yT3B0aW9ucz8uc2FtcGxlUmF0ZSB8fCBzYW1wbGVSYXRlOwogICAgdGhpcy5fc2NhbGUgPSAxIC8gMzI3Njg7IC8vIFBDTTE2IC0+IGZsb2F0CgogICAgLy8gU2lsZW5jZSBkZXRlY3Rpb24gdGhyZXNob2xkICgxIHNlY29uZCkgYXMgYSBmYWxsYmFjayBzYWZldHkgbmV0CiAgICBjb25zdCBzaWxlbmNlRHVyYXRpb25TZWNvbmRzID0gMS4wOwogICAgdGhpcy5fc2lsZW5jZVRocmVzaG9sZEJsb2NrcyA9IE1hdGguY2VpbCgodGhpcy5fc2FtcGxlUmF0ZSAqIHNpbGVuY2VEdXJhdGlvblNlY29uZHMpIC8gMTI4KTsKCiAgICAvLyBNZXRyaWNzIGNvbmZpZ3VyYXRpb24gdmlhIG9wdGlvbnMKICAgIGNvbnN0IG1ldHJpY3NDZmcgPSBvcHRpb25zPy5wcm9jZXNzb3JPcHRpb25zPy5tZXRyaWNzIHx8IHt9OwogICAgdGhpcy5fbWV0cmljc0VuYWJsZWQgPSBtZXRyaWNzQ2ZnLmVuYWJsZWQgIT09IGZhbHNlOwogICAgY29uc3QgaW50ZXJ2YWxIeiA9ICh0eXBlb2YgbWV0cmljc0NmZy5pbnRlcnZhbEh6ID09PSAibnVtYmVyIiAmJiBtZXRyaWNzQ2ZnLmludGVydmFsSHogPiAwKQogICAgICA/IG1ldHJpY3NDZmcuaW50ZXJ2YWxIeiA6IDI7CiAgICAvLyBNZXRyaWNzIHN0YXRlIChsb3ctb3ZlcmhlYWQpCiAgICB0aGlzLl9mcmFtZXNQcm9jZXNzZWQgPSAwOwogICAgdGhpcy5fdW5kZXJydW5CbG9ja3MgPSAwOwogICAgdGhpcy5fbWF4UXVldWVTYW1wbGVzID0gMDsKICAgIHRoaXMuX2xhc3RNZXRyaWNzU2VudEF0RnJhbWUgPSAwOwogICAgLy8gQ29udmVydCB0byBmcmFtZXMgYmV0d2VlbiByZXBvcnRzCiAgICB0aGlzLl9tZXRyaWNzSW50ZXJ2YWxGcmFtZXMgPSBNYXRoLm1heCgxMjgsIE1hdGgucm91bmQodGhpcy5fc2FtcGxlUmF0ZSAvIGludGVydmFsSHopKTsKCiAgICB0aGlzLnJlc2V0KCk7CiAgfQoKICAvKioKICAgKiBSZXNldHMgdGhlIHdvcmtsZXQgdG8gaXRzIGluaXRpYWwgSURMRSBzdGF0ZS4KICAgKi8KICByZXNldCgpIHsKICAgIHRoaXMuX2J1ZmZlclF1ZXVlID0gW107CiAgICB0aGlzLl9jdXJyZW50Q2h1bmsgPSBudWxsOwogICAgdGhpcy5fY3VycmVudENodW5rT2Zmc2V0ID0gMDsKICAgIHRoaXMuX3N0YXRlID0gUGxheWJhY2tXb3JrbGV0LkZTTS5JRExFOwoKICAgIHRoaXMuX25vTW9yZURhdGFSZWNlaXZlZCA9IGZhbHNlOwogICAgdGhpcy5fc2lsZW5jZUZyYW1lc0NvdW50ID0gMDsKICAgIHRoaXMuX2hhc1NlbnRFbmRlZCA9IGZhbHNlOwogICAgLy8gUmVzZXQgbWF4IHF1ZXVlIHRyYWNrZXIgb25seSB3aGVuIGdvaW5nIGlkbGUKICAgIHRoaXMuX21heFF1ZXVlU2FtcGxlcyA9IDA7CiAgfQoKICBoYW5kbGVNZXNzYWdlKGV2ZW50KSB7CiAgICBjb25zdCB7IHR5cGUsIGRhdGEgfSA9IGV2ZW50LmRhdGE7CgogICAgLy8gSU5URVJSVVBUOiBUaGUgbWFpbiB0aHJlYWQgd2FudHMgdG8gc3RvcCBpbW1lZGlhdGVseS4KICAgIGlmICh0eXBlID09PSAic3RvcCIpIHsKICAgICAgdGhpcy5yZXNldCgpOwogICAgICAvLyBTZW5kIGZpbmFsIG1ldHJpY3Mgc2hvd2luZyBjbGVhcmVkIHN0YXRlCiAgICAgIGlmICh0aGlzLl9tZXRyaWNzRW5hYmxlZCkgewogICAgICAgIHRyeSB7CiAgICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UoewogICAgICAgICAgICB0eXBlOiAibWV0cmljcyIsCiAgICAgICAgICAgIGRhdGE6IHsKICAgICAgICAgICAgICBzdGF0ZTogUGxheWJhY2tXb3JrbGV0LkZTTS5JRExFLAogICAgICAgICAgICAgIHF1ZXVlZFNhbXBsZXM6IDAsCiAgICAgICAgICAgICAgcXVldWVkTXM6IDAsCiAgICAgICAgICAgICAgbWF4UXVldWVkTXM6IE1hdGgucm91bmQoKHRoaXMuX21heFF1ZXVlU2FtcGxlcyAvIHRoaXMuX3NhbXBsZVJhdGUpICogMTAwMCksCiAgICAgICAgICAgICAgdW5kZXJydW5CbG9ja3M6IHRoaXMuX3VuZGVycnVuQmxvY2tzLAogICAgICAgICAgICAgIGZyYW1lc1Byb2Nlc3NlZDogdGhpcy5fZnJhbWVzUHJvY2Vzc2VkCiAgICAgICAgICAgIH0KICAgICAgICAgIH0pOwogICAgICAgIH0gY2F0Y2ggKF8pIHsgfQogICAgICB9CiAgICAgIHJldHVybjsKICAgIH0KCiAgICAvLyBNYWluIHRocmVhZCBoYXMgc2lnbmFsZWQgdGhhdCBubyBtb3JlIGF1ZGlvIGNodW5rcyB3aWxsIGJlIHNlbnQgZm9yIHRoaXMgdXR0ZXJhbmNlLgogICAgaWYgKHR5cGUgPT09ICJuby1tb3JlLWRhdGEiKSB7CiAgICAgIHRoaXMuX25vTW9yZURhdGFSZWNlaXZlZCA9IHRydWU7CiAgICAgIHJldHVybjsKICAgIH0KCiAgICAvLyBVcGRhdGUgbWV0cmljcyBjb25maWd1cmF0aW9uIGF0IHJ1bnRpbWUKICAgIGlmICh0eXBlID09PSAiY29uZmlnLW1ldHJpY3MiICYmIGRhdGEgJiYgdHlwZW9mIGRhdGEgPT09ICJvYmplY3QiKSB7CiAgICAgIGlmICgiZW5hYmxlZCIgaW4gZGF0YSkgdGhpcy5fbWV0cmljc0VuYWJsZWQgPSAhIWRhdGEuZW5hYmxlZDsKICAgICAgaWYgKHR5cGVvZiBkYXRhLmludGVydmFsSHogPT09ICJudW1iZXIiICYmIGRhdGEuaW50ZXJ2YWxIeiA+IDApIHsKICAgICAgICBjb25zdCBpbnRlcnZhbEh6ID0gZGF0YS5pbnRlcnZhbEh6OwogICAgICAgIHRoaXMuX21ldHJpY3NJbnRlcnZhbEZyYW1lcyA9IE1hdGgubWF4KDEyOCwgTWF0aC5yb3VuZCh0aGlzLl9zYW1wbGVSYXRlIC8gaW50ZXJ2YWxIeikpOwogICAgICB9CiAgICAgIC8vIFJlc2V0IHBhY2luZyBzbyB0aGUgbmV4dCByZXBvcnQgYWxpZ25zIHdpdGggbmV3IGludGVydmFsCiAgICAgIHRoaXMuX2xhc3RNZXRyaWNzU2VudEF0RnJhbWUgPSB0aGlzLl9mcmFtZXNQcm9jZXNzZWQ7CiAgICAgIHJldHVybjsKICAgIH0KCiAgICAvLyBOZXcgYXVkaW8gZGF0YSBoYXMgYXJyaXZlZC4KICAgIGlmICh0eXBlID09PSAiYXVkaW9EYXRhIiAmJiBkYXRhIGluc3RhbmNlb2YgQXJyYXlCdWZmZXIpIHsKICAgICAgdGhpcy5fbm9Nb3JlRGF0YVJlY2VpdmVkID0gZmFsc2U7CiAgICAgIC8vIElmIHdlIHdlcmUgaWRsZSwgdGhpcyBuZXcgZGF0YSBraWNrcyBvZmYgdGhlIHBsYXliYWNrLgogICAgICBpZiAodGhpcy5fc3RhdGUgPT09IFBsYXliYWNrV29ya2xldC5GU00uSURMRSkgewogICAgICAgIHRoaXMuX3N0YXRlID0gUGxheWJhY2tXb3JrbGV0LkZTTS5QTEFZSU5HOwogICAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZSh7IHR5cGU6ICJwbGF5YmFjay1zdGFydGVkIiB9KTsKICAgICAgfQoKICAgICAgLy8gV2Ugb25seSBxdWV1ZSBkYXRhIGlmIHdlIGFyZSBpbiB0aGUgUExBWUlORyBzdGF0ZS4gVGhpcyBwcmV2ZW50cwogICAgICAvLyBkYXRhIGZyb20gYSBwcmV2aW91cywgaW50ZXJydXB0ZWQgc3RyZWFtIGZyb20gbGluZ2VyaW5nLgogICAgICBpZiAodGhpcy5fc3RhdGUgPT09IFBsYXliYWNrV29ya2xldC5GU00uUExBWUlORykgewogICAgICAgIC8vIFN0b3JlIGFzIEludDE2QXJyYXkgdmlldyB0byBhdm9pZCBjb25zdHJ1Y3RpbmcgaXQgaW4gcHJvY2VzcygpCiAgICAgICAgdGhpcy5fYnVmZmVyUXVldWUucHVzaChuZXcgSW50MTZBcnJheShkYXRhKSk7CiAgICAgICAgdGhpcy5fc2lsZW5jZUZyYW1lc0NvdW50ID0gMDsgLy8gUmVzZXQgc2lsZW5jZSBjb3VudGVyIG9uIG5ldyBkYXRhCiAgICAgIH0KICAgIH0KICB9CgogIHByb2Nlc3MoaW5wdXRzLCBvdXRwdXRzLCBwYXJhbWV0ZXJzKSB7CiAgICBjb25zdCBvdXRwdXRDaGFubmVsID0gb3V0cHV0c1swXT8uWzBdOwogICAgaWYgKCFvdXRwdXRDaGFubmVsKSB7CiAgICAgIHJldHVybiB0cnVlOyAvLyBLZWVwIGFsaXZlIGV2ZW4gaWYgb3V0cHV0IGlzIHRlbXBvcmFyaWx5IGRpc2Nvbm5lY3RlZAogICAgfQoKICAgIC8vIElmIHdlIGFyZSBub3QgcGxheWluZywganVzdCBvdXRwdXQgc2lsZW5jZSBhbmQgd2FpdC4KICAgIGlmICh0aGlzLl9zdGF0ZSAhPT0gUGxheWJhY2tXb3JrbGV0LkZTTS5QTEFZSU5HKSB7CiAgICAgIG91dHB1dENoYW5uZWwuZmlsbCgwKTsKICAgICAgcmV0dXJuIHRydWU7IC8vIEFsd2F5cyByZXR1cm4gdHJ1ZSB0byBrZWVwIHRoZSBwcm9jZXNzb3IgYWxpdmUKICAgIH0KCiAgICAvLyBDb3JlIFBMQVlJTkcgTG9naWMKICAgIGNvbnN0IGJsb2NrU2l6ZSA9IG91dHB1dENoYW5uZWwubGVuZ3RoOwogICAgbGV0IHNhbXBsZXNDb3BpZWQgPSAwOwoKICAgIHdoaWxlIChzYW1wbGVzQ29waWVkIDwgYmxvY2tTaXplKSB7CiAgICAgIGlmICghdGhpcy5fY3VycmVudENodW5rIHx8IHRoaXMuX2N1cnJlbnRDaHVua09mZnNldCA+PSB0aGlzLl9jdXJyZW50Q2h1bmsubGVuZ3RoKSB7CiAgICAgICAgaWYgKHRoaXMuX2J1ZmZlclF1ZXVlLmxlbmd0aCA+IDApIHsKICAgICAgICAgIHRoaXMuX2N1cnJlbnRDaHVuayA9IHRoaXMuX2J1ZmZlclF1ZXVlLnNoaWZ0KCk7CiAgICAgICAgICB0aGlzLl9jdXJyZW50Q2h1bmtPZmZzZXQgPSAwOwogICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAvLyBCdWZmZXIgaXMgZW1wdHkuIENoZWNrIGZvciBlbmQgY29uZGl0aW9ucy4KICAgICAgICAgIGNvbnN0IGlzVGltZWRPdXQgPSB0aGlzLl9zaWxlbmNlRnJhbWVzQ291bnQgPiB0aGlzLl9zaWxlbmNlVGhyZXNob2xkQmxvY2tzOwoKICAgICAgICAgIGlmICh0aGlzLl9ub01vcmVEYXRhUmVjZWl2ZWQgfHwgaXNUaW1lZE91dCkgewogICAgICAgICAgICAvLyBFTkQgT0YgUExBWUJBQ0s6IEVpdGhlciBleHBsaWNpdGx5IHNpZ25hbGVkIG9yIHRpbWVkIG91dC4KICAgICAgICAgICAgaWYgKCF0aGlzLl9oYXNTZW50RW5kZWQpIHsKICAgICAgICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UoeyB0eXBlOiAicGxheWJhY2stZW5kZWQiIH0pOwogICAgICAgICAgICAgIHRoaXMuX2hhc1NlbnRFbmRlZCA9IHRydWU7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgLy8gU2VuZCBmaW5hbCBtZXRyaWNzIHNob3dpbmcgY2xlYXJlZCBzdGF0ZQogICAgICAgICAgICBpZiAodGhpcy5fbWV0cmljc0VuYWJsZWQpIHsKICAgICAgICAgICAgICB0cnkgewogICAgICAgICAgICAgICAgdGhpcy5wb3J0LnBvc3RNZXNzYWdlKHsKICAgICAgICAgICAgICAgICAgdHlwZTogIm1ldHJpY3MiLAogICAgICAgICAgICAgICAgICBkYXRhOiB7CiAgICAgICAgICAgICAgICAgICAgc3RhdGU6IFBsYXliYWNrV29ya2xldC5GU00uSURMRSwKICAgICAgICAgICAgICAgICAgICBxdWV1ZWRTYW1wbGVzOiAwLAogICAgICAgICAgICAgICAgICAgIHF1ZXVlZE1zOiAwLAogICAgICAgICAgICAgICAgICAgIG1heFF1ZXVlZE1zOiBNYXRoLnJvdW5kKCh0aGlzLl9tYXhRdWV1ZVNhbXBsZXMgLyB0aGlzLl9zYW1wbGVSYXRlKSAqIDEwMDApLAogICAgICAgICAgICAgICAgICAgIHVuZGVycnVuQmxvY2tzOiB0aGlzLl91bmRlcnJ1bkJsb2NrcywKICAgICAgICAgICAgICAgICAgICBmcmFtZXNQcm9jZXNzZWQ6IHRoaXMuX2ZyYW1lc1Byb2Nlc3NlZAogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICB9KTsKICAgICAgICAgICAgICB9IGNhdGNoIChfKSB7IH0KICAgICAgICAgICAgfQogICAgICAgICAgICB0aGlzLnJlc2V0KCk7IC8vIFJlc2V0IHRvIElETEUgc3RhdGUgZm9yIHJldXNlCiAgICAgICAgICAgIGJyZWFrOyAvLyBFeGl0IHdoaWxlIGxvb3AKICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgIC8vIEJVRkZFUiBVTkRFUlJVTiAoTEFHKTogUGxheSBzaWxlbmNlIGFuZCB3YWl0IGZvciBtb3JlIGRhdGEuCiAgICAgICAgICAgIHRoaXMuX3NpbGVuY2VGcmFtZXNDb3VudCsrOwogICAgICAgICAgICBpZiAodGhpcy5fbWV0cmljc0VuYWJsZWQpIHRoaXMuX3VuZGVycnVuQmxvY2tzKys7CiAgICAgICAgICAgIGJyZWFrOyAvLyBFeGl0IHdoaWxlIGxvb3AKICAgICAgICAgIH0KICAgICAgICB9CiAgICAgIH0KCiAgICAgIC8vIElmIHdlIGhhdmUgYSBjaHVuayAoY291bGQgYmUgYSBuZXcgb25lIGZyb20gdGhlIGxvZ2ljIGFib3ZlKSwgcHJvY2VzcyBpdC4KICAgICAgaWYgKHRoaXMuX2N1cnJlbnRDaHVuaykgewogICAgICAgIGNvbnN0IHNhbXBsZXNUb0NvcHkgPSBNYXRoLm1pbigKICAgICAgICAgIGJsb2NrU2l6ZSAtIHNhbXBsZXNDb3BpZWQsCiAgICAgICAgICB0aGlzLl9jdXJyZW50Q2h1bmsubGVuZ3RoIC0gdGhpcy5fY3VycmVudENodW5rT2Zmc2V0CiAgICAgICAgKTsKICAgICAgICAvLyBEaXJlY3RseSB3cml0ZSB0byBvdXRwdXRDaGFubmVsIHRvIGF2b2lkIGV4dHJhIGNvcHkKICAgICAgICBjb25zdCBzcmMgPSB0aGlzLl9jdXJyZW50Q2h1bms7CiAgICAgICAgY29uc3QgYmFzZVNyYyA9IHRoaXMuX2N1cnJlbnRDaHVua09mZnNldDsKICAgICAgICBjb25zdCBiYXNlRHN0ID0gc2FtcGxlc0NvcGllZDsKICAgICAgICBjb25zdCBzY2FsZSA9IHRoaXMuX3NjYWxlOwogICAgICAgIGZvciAobGV0IGkgPSAwOyBpIDwgc2FtcGxlc1RvQ29weTsgaSsrKSB7CiAgICAgICAgICBvdXRwdXRDaGFubmVsW2Jhc2VEc3QgKyBpXSA9IHNyY1tiYXNlU3JjICsgaV0gKiBzY2FsZTsKICAgICAgICB9CgogICAgICAgIHRoaXMuX2N1cnJlbnRDaHVua09mZnNldCArPSBzYW1wbGVzVG9Db3B5OwogICAgICAgIHNhbXBsZXNDb3BpZWQgKz0gc2FtcGxlc1RvQ29weTsKICAgICAgfQogICAgfQoKICAgIC8vIFplcm8tZmlsbCB0aGUgcmVtYWluZGVyLCBpZiBhbnksIG9uY2UgcGVyIGJsb2NrCiAgICBpZiAoc2FtcGxlc0NvcGllZCA8IGJsb2NrU2l6ZSkgewogICAgICBvdXRwdXRDaGFubmVsLmZpbGwoMCwgc2FtcGxlc0NvcGllZCk7CiAgICB9CgogICAgLy8gVXBkYXRlIG1ldHJpY3MgKG9wdGlvbmFsKQogICAgaWYgKHRoaXMuX21ldHJpY3NFbmFibGVkKSB7CiAgICAgIHRoaXMuX2ZyYW1lc1Byb2Nlc3NlZCArPSBibG9ja1NpemU7CgogICAgICAvLyBUcmFjayBxdWV1ZSBkZXB0aCBpbiBzYW1wbGVzIChhcHByb3hpbWF0ZSkKICAgICAgbGV0IHF1ZXVlZFNhbXBsZXMgPSAwOwogICAgICBpZiAodGhpcy5fY3VycmVudENodW5rKSBxdWV1ZWRTYW1wbGVzICs9IE1hdGgubWF4KDAsIHRoaXMuX2N1cnJlbnRDaHVuay5sZW5ndGggLSB0aGlzLl9jdXJyZW50Q2h1bmtPZmZzZXQpOwogICAgICBmb3IgKGxldCBpID0gMDsgaSA8IHRoaXMuX2J1ZmZlclF1ZXVlLmxlbmd0aDsgaSsrKSBxdWV1ZWRTYW1wbGVzICs9IHRoaXMuX2J1ZmZlclF1ZXVlW2ldLmxlbmd0aDsKICAgICAgaWYgKHF1ZXVlZFNhbXBsZXMgPiB0aGlzLl9tYXhRdWV1ZVNhbXBsZXMpIHRoaXMuX21heFF1ZXVlU2FtcGxlcyA9IHF1ZXVlZFNhbXBsZXM7CgogICAgICAvLyBQZXJpb2RpY2FsbHkgc2VuZCBtZXRyaWNzIHRvIG1haW4gdGhyZWFkCiAgICAgIGlmICh0aGlzLl9mcmFtZXNQcm9jZXNzZWQgLSB0aGlzLl9sYXN0TWV0cmljc1NlbnRBdEZyYW1lID49IHRoaXMuX21ldHJpY3NJbnRlcnZhbEZyYW1lcykgewogICAgICAgIHRoaXMuX2xhc3RNZXRyaWNzU2VudEF0RnJhbWUgPSB0aGlzLl9mcmFtZXNQcm9jZXNzZWQ7CiAgICAgICAgdHJ5IHsKICAgICAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZSh7CiAgICAgICAgICAgIHR5cGU6ICJtZXRyaWNzIiwKICAgICAgICAgICAgZGF0YTogewogICAgICAgICAgICAgIHN0YXRlOiB0aGlzLl9zdGF0ZSwKICAgICAgICAgICAgICBxdWV1ZWRTYW1wbGVzLAogICAgICAgICAgICAgIHF1ZXVlZE1zOiBNYXRoLnJvdW5kKChxdWV1ZWRTYW1wbGVzIC8gdGhpcy5fc2FtcGxlUmF0ZSkgKiAxMDAwKSwKICAgICAgICAgICAgICBtYXhRdWV1ZWRNczogTWF0aC5yb3VuZCgodGhpcy5fbWF4UXVldWVTYW1wbGVzIC8gdGhpcy5fc2FtcGxlUmF0ZSkgKiAxMDAwKSwKICAgICAgICAgICAgICB1bmRlcnJ1bkJsb2NrczogdGhpcy5fdW5kZXJydW5CbG9ja3MsCiAgICAgICAgICAgICAgZnJhbWVzUHJvY2Vzc2VkOiB0aGlzLl9mcmFtZXNQcm9jZXNzZWQKICAgICAgICAgICAgfQogICAgICAgICAgfSk7CiAgICAgICAgfSBjYXRjaCAoXykgeyB9CiAgICAgICAgLy8gRG9uJ3QgcmVzZXQgbWF4IHRyYWNrZXIgLSBrZWVwIHNlc3Npb24gcGVhayB1bnRpbCBpZGxlCiAgICAgIH0KICAgIH0KCiAgICAvLyBBTFdBWVMgcmV0dXJuIHRydWUgdG8ga2VlcCB0aGUgcHJvY2Vzc29yIGFsaXZlIGZvciByZXVzZS4KICAgIHJldHVybiB0cnVlOwogIH0KfQoKcmVnaXN0ZXJQcm9jZXNzb3IoInBsYXliYWNrLXdvcmtsZXQiLCBQbGF5YmFja1dvcmtsZXQpOwo=",typeof document>"u"?require("url").pathToFileURL(__filename).href:De&&De.tagName.toUpperCase()==="SCRIPT"&&De.src||new URL("index.cjs",document.baseURI).href),Xe={en:ht,de:mt,fr:gt,fi:ft,lt:bt},ie=new f.Quaternion,_=new f.Euler,Ie=new f.Vector3,Le=new f.Vector3,je=new f.Box3;new f.Matrix4;new f.Matrix4;new f.Vector3;new f.Vector3(0,0,1);const vt=new f.Vector3(1,0,0);new f.Vector3(0,1,0);new f.Vector3(0,0,1);class Ne{constructor(t,e=null){this.nodeAvatar=t,this.opt={jwtGet:null,ttsEndpoint:"",ttsApikey:null,ttsTrimStart:0,ttsTrimEnd:400,ttsLang:"fi-FI",ttsVoice:"fi-FI-Standard-A",ttsRate:1,ttsPitch:0,ttsVolume:.3,mixerGainSpeech:1.2,mixerGainBackground:null,lipsyncLang:"fi",lipsyncModules:["fi","en","lt"],pcmSampleRate:22050,modelRoot:"Armature",modelPixelRatio:1,modelFPS:30,modelMovementFactor:1,cameraView:"full",dracoEnabled:!1,dracoDecoderPath:"https://www.gstatic.com/draco/v1/decoders/",cameraDistance:0,cameraX:0,cameraY:0,cameraRotateX:0,cameraRotateY:0,cameraRotateEnable:!0,cameraPanEnable:!1,cameraZoomEnable:!1,lightAmbientColor:16777215,lightAmbientIntensity:1.25,lightDirectColor:8947882,lightDirectIntensity:12,lightDirectPhi:1,lightDirectTheta:2,lightSpotIntensity:0,lightSpotColor:3377407,lightSpotPhi:.1,lightSpotTheta:4,lightSpotDispersion:1,avatarMood:"neutral",avatarMute:!1,avatarIdleEyeContact:.6,avatarIdleHeadMove:.5,avatarSpeakingEyeContact:.8,avatarSpeakingHeadMove:.5,avatarIgnoreCamera:!1,listeningSilenceThresholdLevel:40,listeningSilenceThresholdMs:2e3,listeningSilenceDurationMax:1e4,listeningActiveThresholdLevel:75,listeningActiveThresholdMs:300,listeningActiveDurationMax:24e4,update:null,avatarOnly:!1,avatarOnlyScene:null,avatarOnlyCamera:null,statsNode:null,statsStyle:null},Object.assign(this.opt,e||{}),this.opt.statsNode&&(this.stats=new it,this.opt.statsStyle&&(this.stats.dom.style.cssText=this.opt.statsStyle),this.opt.statsNode.appendChild(this.stats.dom)),this.poseTemplates={side:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.003,y:-.017,z:.1},"Spine.rotation":{x:-.103,y:-.002,z:-.063},"Spine1.rotation":{x:.042,y:-.02,z:-.069},"Spine2.rotation":{x:.131,y:-.012,z:-.065},"Neck.rotation":{x:.027,y:.006,z:0},"Head.rotation":{x:.077,y:-.065,z:0},"LeftShoulder.rotation":{x:1.599,y:.084,z:-1.77},"LeftArm.rotation":{x:1.364,y:.052,z:-.044},"LeftForeArm.rotation":{x:.002,y:-.007,z:.331},"LeftHand.rotation":{x:.104,y:-.067,z:-.174},"LeftHandThumb1.rotation":{x:.231,y:.258,z:.355},"LeftHandThumb2.rotation":{x:-.106,y:-.339,z:-.454},"LeftHandThumb3.rotation":{x:-.02,y:-.142,z:-.004},"LeftHandIndex1.rotation":{x:.148,y:.032,z:-.069},"LeftHandIndex2.rotation":{x:.326,y:-.049,z:-.029},"LeftHandIndex3.rotation":{x:.247,y:-.053,z:-.073},"LeftHandMiddle1.rotation":{x:.238,y:-.057,z:-.089},"LeftHandMiddle2.rotation":{x:.469,y:-.036,z:-.081},"LeftHandMiddle3.rotation":{x:.206,y:-.015,z:-.017},"LeftHandRing1.rotation":{x:.187,y:-.118,z:-.157},"LeftHandRing2.rotation":{x:.579,y:.02,z:-.097},"LeftHandRing3.rotation":{x:.272,y:.021,z:-.063},"LeftHandPinky1.rotation":{x:.405,y:-.182,z:-.138},"LeftHandPinky2.rotation":{x:.613,y:.128,z:-.144},"LeftHandPinky3.rotation":{x:.268,y:.094,z:-.081},"RightShoulder.rotation":{x:1.541,y:.192,z:1.775},"RightArm.rotation":{x:1.273,y:-.352,z:-.067},"RightForeArm.rotation":{x:-.011,y:-.031,z:-.357},"RightHand.rotation":{x:-.008,y:.312,z:-.028},"RightHandThumb1.rotation":{x:.23,y:-.258,z:-.355},"RightHandThumb2.rotation":{x:-.107,y:.339,z:.454},"RightHandThumb3.rotation":{x:-.02,y:.142,z:.004},"RightHandIndex1.rotation":{x:.148,y:-.031,z:.069},"RightHandIndex2.rotation":{x:.326,y:.049,z:.029},"RightHandIndex3.rotation":{x:.247,y:.053,z:.073},"RightHandMiddle1.rotation":{x:.237,y:.057,z:.089},"RightHandMiddle2.rotation":{x:.469,y:.036,z:.081},"RightHandMiddle3.rotation":{x:.206,y:.015,z:.017},"RightHandRing1.rotation":{x:.204,y:.086,z:.135},"RightHandRing2.rotation":{x:.579,y:-.02,z:.098},"RightHandRing3.rotation":{x:.272,y:-.021,z:.063},"RightHandPinky1.rotation":{x:.404,y:.182,z:.137},"RightHandPinky2.rotation":{x:.613,y:-.128,z:.144},"RightHandPinky3.rotation":{x:.268,y:-.094,z:.081},"LeftUpLeg.rotation":{x:.096,y:.209,z:2.983},"LeftLeg.rotation":{x:-.053,y:.042,z:-.017},"LeftFoot.rotation":{x:1.091,y:.15,z:.026},"LeftToeBase.rotation":{x:.469,y:-.07,z:-.015},"RightUpLeg.rotation":{x:-.307,y:-.219,z:2.912},"RightLeg.rotation":{x:-.359,y:.164,z:.015},"RightFoot.rotation":{x:1.035,y:.11,z:.005},"RightToeBase.rotation":{x:.467,y:.07,z:.015}}},hip:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.036,y:.09,z:.135},"Spine.rotation":{x:.076,y:-.035,z:.01},"Spine1.rotation":{x:-.096,y:.013,z:-.094},"Spine2.rotation":{x:-.014,y:.002,z:-.097},"Neck.rotation":{x:.034,y:-.051,z:-.075},"Head.rotation":{x:.298,y:-.1,z:.154},"LeftShoulder.rotation":{x:1.694,y:.011,z:-1.68},"LeftArm.rotation":{x:1.343,y:.177,z:-.153},"LeftForeArm.rotation":{x:-.049,y:.134,z:.351},"LeftHand.rotation":{x:.057,y:-.189,z:-.026},"LeftHandThumb1.rotation":{x:.368,y:-.066,z:.438},"LeftHandThumb2.rotation":{x:-.156,y:.029,z:-.369},"LeftHandThumb3.rotation":{x:.034,y:-.009,z:.016},"LeftHandIndex1.rotation":{x:.157,y:-.002,z:-.171},"LeftHandIndex2.rotation":{x:.099,y:0,z:0},"LeftHandIndex3.rotation":{x:.1,y:0,z:0},"LeftHandMiddle1.rotation":{x:.222,y:-.019,z:-.16},"LeftHandMiddle2.rotation":{x:.142,y:0,z:0},"LeftHandMiddle3.rotation":{x:.141,y:0,z:0},"LeftHandRing1.rotation":{x:.333,y:-.039,z:-.174},"LeftHandRing2.rotation":{x:.214,y:0,z:0},"LeftHandRing3.rotation":{x:.213,y:0,z:0},"LeftHandPinky1.rotation":{x:.483,y:-.069,z:-.189},"LeftHandPinky2.rotation":{x:.312,y:0,z:0},"LeftHandPinky3.rotation":{x:.309,y:0,z:0},"RightShoulder.rotation":{x:1.597,y:.012,z:1.816},"RightArm.rotation":{x:.618,y:-1.274,z:-.266},"RightForeArm.rotation":{x:-.395,y:-.097,z:-1.342},"RightHand.rotation":{x:-.816,y:-.057,z:-.976},"RightHandThumb1.rotation":{x:.42,y:.23,z:-1.172},"RightHandThumb2.rotation":{x:-.027,y:.361,z:.122},"RightHandThumb3.rotation":{x:.076,y:.125,z:-.371},"RightHandIndex1.rotation":{x:-.158,y:-.045,z:.033},"RightHandIndex2.rotation":{x:.391,y:.051,z:.025},"RightHandIndex3.rotation":{x:.317,y:.058,z:.07},"RightHandMiddle1.rotation":{x:.486,y:.066,z:.014},"RightHandMiddle2.rotation":{x:.718,y:.055,z:.07},"RightHandMiddle3.rotation":{x:.453,y:.019,z:.013},"RightHandRing1.rotation":{x:.591,y:.241,z:.11},"RightHandRing2.rotation":{x:1.014,y:.023,z:.097},"RightHandRing3.rotation":{x:.708,y:.008,z:.066},"RightHandPinky1.rotation":{x:1.02,y:.305,z:.051},"RightHandPinky2.rotation":{x:1.187,y:-.028,z:.191},"RightHandPinky3.rotation":{x:.872,y:-.031,z:.121},"LeftUpLeg.rotation":{x:-.095,y:-.058,z:-3.338},"LeftLeg.rotation":{x:-.366,y:.287,z:-.021},"LeftFoot.rotation":{x:1.131,y:.21,z:.176},"LeftToeBase.rotation":{x:.739,y:-.068,z:-.001},"RightUpLeg.rotation":{x:-.502,y:.362,z:3.153},"RightLeg.rotation":{x:-1.002,y:.109,z:.008},"RightFoot.rotation":{x:.626,y:-.097,z:-.194},"RightToeBase.rotation":{x:1.33,y:.288,z:-.078}}},turn:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.07,y:-.604,z:-.004},"Spine.rotation":{x:-.007,y:.003,z:.071},"Spine1.rotation":{x:-.053,y:.024,z:-.06},"Spine2.rotation":{x:.074,y:.013,z:-.068},"Neck.rotation":{x:.03,y:.186,z:-.077},"Head.rotation":{x:.045,y:.243,z:-.086},"LeftShoulder.rotation":{x:1.717,y:-.085,z:-1.761},"LeftArm.rotation":{x:1.314,y:.07,z:-.057},"LeftForeArm.rotation":{x:-.151,y:.714,z:.302},"LeftHand.rotation":{x:-.069,y:.003,z:-.118},"LeftHandThumb1.rotation":{x:.23,y:.258,z:.354},"LeftHandThumb2.rotation":{x:-.107,y:-.338,z:-.455},"LeftHandThumb3.rotation":{x:-.015,y:-.142,z:.002},"LeftHandIndex1.rotation":{x:.145,y:.032,z:-.069},"LeftHandIndex2.rotation":{x:.323,y:-.049,z:-.028},"LeftHandIndex3.rotation":{x:.249,y:-.053,z:-.074},"LeftHandMiddle1.rotation":{x:.235,y:-.057,z:-.088},"LeftHandMiddle2.rotation":{x:.468,y:-.036,z:-.081},"LeftHandMiddle3.rotation":{x:.203,y:-.015,z:-.017},"LeftHandRing1.rotation":{x:.185,y:-.118,z:-.157},"LeftHandRing2.rotation":{x:.578,y:.02,z:-.097},"LeftHandRing3.rotation":{x:.27,y:.021,z:-.063},"LeftHandPinky1.rotation":{x:.404,y:-.182,z:-.138},"LeftHandPinky2.rotation":{x:.612,y:.128,z:-.144},"LeftHandPinky3.rotation":{x:.267,y:.094,z:-.081},"RightShoulder.rotation":{x:1.605,y:.17,z:1.625},"RightArm.rotation":{x:1.574,y:-.655,z:.388},"RightForeArm.rotation":{x:-.36,y:-.849,z:-.465},"RightHand.rotation":{x:.114,y:.416,z:-.069},"RightHandThumb1.rotation":{x:.486,y:.009,z:-.492},"RightHandThumb2.rotation":{x:-.073,y:-.01,z:.284},"RightHandThumb3.rotation":{x:-.054,y:-.006,z:.209},"RightHandIndex1.rotation":{x:.245,y:-.014,z:.052},"RightHandIndex2.rotation":{x:.155,y:0,z:0},"RightHandIndex3.rotation":{x:.153,y:0,z:0},"RightHandMiddle1.rotation":{x:.238,y:.004,z:.028},"RightHandMiddle2.rotation":{x:.15,y:0,z:0},"RightHandMiddle3.rotation":{x:.149,y:0,z:0},"RightHandRing1.rotation":{x:.267,y:.012,z:.007},"RightHandRing2.rotation":{x:.169,y:0,z:0},"RightHandRing3.rotation":{x:.167,y:0,z:0},"RightHandPinky1.rotation":{x:.304,y:.018,z:-.021},"RightHandPinky2.rotation":{x:.192,y:0,z:0},"RightHandPinky3.rotation":{x:.19,y:0,z:0},"LeftUpLeg.rotation":{x:-.001,y:-.058,z:-3.238},"LeftLeg.rotation":{x:-.29,y:.058,z:-.021},"LeftFoot.rotation":{x:1.288,y:.168,z:.183},"LeftToeBase.rotation":{x:.363,y:-.09,z:-.01},"RightUpLeg.rotation":{x:-.1,y:.36,z:3.062},"RightLeg.rotation":{x:-.67,y:-.304,z:.043},"RightFoot.rotation":{x:1.195,y:-.159,z:-.294},"RightToeBase.rotation":{x:.737,y:.164,z:-.002}}},bend:{bend:!0,standing:!0,props:{"Hips.position":{x:-.007,y:.943,z:-.001},"Hips.rotation":{x:1.488,y:-.633,z:1.435},"Spine.rotation":{x:-.126,y:.007,z:-.057},"Spine1.rotation":{x:-.134,y:.009,z:.01},"Spine2.rotation":{x:-.019,y:0,z:-.002},"Neck.rotation":{x:-.159,y:.572,z:-.108},"Head.rotation":{x:-.064,y:.716,z:-.257},"RightShoulder.rotation":{x:1.625,y:-.043,z:1.382},"RightArm.rotation":{x:.746,y:-.96,z:-1.009},"RightForeArm.rotation":{x:-.199,y:-.528,z:-.38},"RightHand.rotation":{x:-.261,y:-.043,z:-.027},"RightHandThumb1.rotation":{x:.172,y:-.138,z:-.445},"RightHandThumb2.rotation":{x:-.158,y:.327,z:.545},"RightHandThumb3.rotation":{x:-.062,y:.138,z:.152},"RightHandIndex1.rotation":{x:.328,y:-.005,z:.132},"RightHandIndex2.rotation":{x:.303,y:.049,z:.028},"RightHandIndex3.rotation":{x:.241,y:.046,z:.077},"RightHandMiddle1.rotation":{x:.309,y:.074,z:.089},"RightHandMiddle2.rotation":{x:.392,y:.036,z:.081},"RightHandMiddle3.rotation":{x:.199,y:.014,z:.019},"RightHandRing1.rotation":{x:.239,y:.143,z:.091},"RightHandRing2.rotation":{x:.275,y:-.02,z:.097},"RightHandRing3.rotation":{x:.248,y:-.023,z:.061},"RightHandPinky1.rotation":{x:.211,y:.154,z:.029},"RightHandPinky2.rotation":{x:.348,y:-.128,z:.144},"RightHandPinky3.rotation":{x:.21,y:-.091,z:.065},"LeftShoulder.rotation":{x:1.626,y:-.027,z:-1.367},"LeftArm.rotation":{x:1.048,y:.737,z:.712},"LeftForeArm.rotation":{x:-.508,y:.879,z:.625},"LeftHand.rotation":{x:.06,y:-.243,z:-.079},"LeftHandThumb1.rotation":{x:.187,y:-.072,z:.346},"LeftHandThumb2.rotation":{x:-.066,y:.008,z:-.256},"LeftHandThumb3.rotation":{x:-.085,y:.014,z:-.334},"LeftHandIndex1.rotation":{x:-.1,y:.016,z:-.058},"LeftHandIndex2.rotation":{x:.334,y:0,z:0},"LeftHandIndex3.rotation":{x:.281,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.056,y:0,z:0},"LeftHandMiddle2.rotation":{x:.258,y:0,z:0},"LeftHandMiddle3.rotation":{x:.26,y:0,z:0},"LeftHandRing1.rotation":{x:-.067,y:-.002,z:.008},"LeftHandRing2.rotation":{x:.259,y:0,z:0},"LeftHandRing3.rotation":{x:.276,y:0,z:0},"LeftHandPinky1.rotation":{x:-.128,y:-.007,z:.042},"LeftHandPinky2.rotation":{x:.227,y:0,z:0},"LeftHandPinky3.rotation":{x:.145,y:0,z:0},"RightUpLeg.rotation":{x:-1.507,y:.2,z:-3.043},"RightLeg.rotation":{x:-.689,y:-.124,z:.017},"RightFoot.rotation":{x:.909,y:.008,z:-.093},"RightToeBase.rotation":{x:.842,y:.075,z:-.008},"LeftUpLeg.rotation":{x:-1.449,y:-.2,z:3.018},"LeftLeg.rotation":{x:-.74,y:-.115,z:-.008},"LeftFoot.rotation":{x:1.048,y:-.058,z:.117},"LeftToeBase.rotation":{x:.807,y:-.067,z:.003}}},back:{standing:!0,props:{"Hips.position":{x:0,y:1,z:0},"Hips.rotation":{x:-.732,y:-1.463,z:-.637},"Spine.rotation":{x:-.171,y:.106,z:.157},"Spine1.rotation":{x:-.044,y:.138,z:-.059},"Spine2.rotation":{x:.082,y:.133,z:-.074},"Neck.rotation":{x:.39,y:.591,z:-.248},"Head.rotation":{x:-.001,y:.596,z:-.057},"LeftShoulder.rotation":{x:1.676,y:.007,z:-1.892},"LeftArm.rotation":{x:-5.566,y:1.188,z:-.173},"LeftForeArm.rotation":{x:-.673,y:-.105,z:1.702},"LeftHand.rotation":{x:-.469,y:-.739,z:.003},"LeftHandThumb1.rotation":{x:.876,y:.274,z:.793},"LeftHandThumb2.rotation":{x:.161,y:-.23,z:-.172},"LeftHandThumb3.rotation":{x:.078,y:.027,z:.156},"LeftHandIndex1.rotation":{x:-.085,y:-.002,z:.009},"LeftHandIndex2.rotation":{x:.176,y:0,z:-.002},"LeftHandIndex3.rotation":{x:-.036,y:.001,z:-.035},"LeftHandMiddle1.rotation":{x:.015,y:.144,z:-.076},"LeftHandMiddle2.rotation":{x:.378,y:-.007,z:-.077},"LeftHandMiddle3.rotation":{x:-.141,y:-.001,z:.031},"LeftHandRing1.rotation":{x:.039,y:.02,z:-.2},"LeftHandRing2.rotation":{x:.25,y:-.002,z:-.073},"LeftHandRing3.rotation":{x:.236,y:.006,z:-.075},"LeftHandPinky1.rotation":{x:.172,y:-.033,z:-.275},"LeftHandPinky2.rotation":{x:.216,y:.043,z:-.054},"LeftHandPinky3.rotation":{x:.325,y:.078,z:-.13},"RightShoulder.rotation":{x:2.015,y:-.168,z:1.706},"RightArm.rotation":{x:.203,y:-1.258,z:-.782},"RightForeArm.rotation":{x:-.658,y:-.133,z:-1.401},"RightHand.rotation":{x:-1.504,y:.375,z:-.005},"RightHandThumb1.rotation":{x:.413,y:-.158,z:-1.121},"RightHandThumb2.rotation":{x:-.142,y:-.008,z:.209},"RightHandThumb3.rotation":{x:-.091,y:.021,z:.142},"RightHandIndex1.rotation":{x:-.167,y:.014,z:-.072},"RightHandIndex2.rotation":{x:.474,y:.009,z:.051},"RightHandIndex3.rotation":{x:.115,y:.006,z:.047},"RightHandMiddle1.rotation":{x:.385,y:.019,z:.144},"RightHandMiddle2.rotation":{x:.559,y:.035,z:.101},"RightHandMiddle3.rotation":{x:.229,y:0,z:.027},"RightHandRing1.rotation":{x:.48,y:.026,z:.23},"RightHandRing2.rotation":{x:.772,y:.038,z:.109},"RightHandRing3.rotation":{x:.622,y:.039,z:.106},"RightHandPinky1.rotation":{x:.767,y:.288,z:.353},"RightHandPinky2.rotation":{x:.886,y:.049,z:.122},"RightHandPinky3.rotation":{x:.662,y:.044,z:.113},"LeftUpLeg.rotation":{x:-.206,y:-.268,z:-3.343},"LeftLeg.rotation":{x:-.333,y:.757,z:-.043},"LeftFoot.rotation":{x:1.049,y:.167,z:.287},"LeftToeBase.rotation":{x:.672,y:-.069,z:-.004},"RightUpLeg.rotation":{x:.055,y:-.226,z:3.037},"RightLeg.rotation":{x:-.559,y:.39,z:-.001},"RightFoot.rotation":{x:1.2,y:.133,z:.085},"RightToeBase.rotation":{x:.92,y:.093,z:-.013}}},straight:{standing:!0,props:{"Hips.position":{x:0,y:.989,z:.001},"Hips.rotation":{x:.047,y:.007,z:-.007},"Spine.rotation":{x:-.143,y:-.007,z:.005},"Spine1.rotation":{x:-.043,y:-.014,z:.012},"Spine2.rotation":{x:.072,y:-.013,z:.013},"Neck.rotation":{x:.048,y:-.003,z:.012},"Head.rotation":{x:.05,y:-.02,z:-.017},"LeftShoulder.rotation":{x:1.62,y:-.166,z:-1.605},"LeftArm.rotation":{x:1.275,y:.544,z:-.092},"LeftForeArm.rotation":{x:0,y:0,z:.302},"LeftHand.rotation":{x:-.225,y:-.154,z:.11},"LeftHandThumb1.rotation":{x:.435,y:-.044,z:.457},"LeftHandThumb2.rotation":{x:-.028,y:.002,z:-.246},"LeftHandThumb3.rotation":{x:-.236,y:-.025,z:.113},"LeftHandIndex1.rotation":{x:.218,y:.008,z:-.081},"LeftHandIndex2.rotation":{x:.165,y:-.001,z:-.017},"LeftHandIndex3.rotation":{x:.165,y:-.001,z:-.017},"LeftHandMiddle1.rotation":{x:.235,y:-.011,z:-.065},"LeftHandMiddle2.rotation":{x:.182,y:-.002,z:-.019},"LeftHandMiddle3.rotation":{x:.182,y:-.002,z:-.019},"LeftHandRing1.rotation":{x:.316,y:-.017,z:.008},"LeftHandRing2.rotation":{x:.253,y:-.003,z:-.026},"LeftHandRing3.rotation":{x:.255,y:-.003,z:-.026},"LeftHandPinky1.rotation":{x:.336,y:-.062,z:.088},"LeftHandPinky2.rotation":{x:.276,y:-.004,z:-.028},"LeftHandPinky3.rotation":{x:.276,y:-.004,z:-.028},"RightShoulder.rotation":{x:1.615,y:.064,z:1.53},"RightArm.rotation":{x:1.313,y:-.424,z:.131},"RightForeArm.rotation":{x:0,y:0,z:-.317},"RightHand.rotation":{x:-.158,y:-.639,z:-.196},"RightHandThumb1.rotation":{x:.44,y:.048,z:-.549},"RightHandThumb2.rotation":{x:-.056,y:-.008,z:.274},"RightHandThumb3.rotation":{x:-.258,y:.031,z:-.095},"RightHandIndex1.rotation":{x:.169,y:-.011,z:.105},"RightHandIndex2.rotation":{x:.134,y:.001,z:.011},"RightHandIndex3.rotation":{x:.134,y:.001,z:.011},"RightHandMiddle1.rotation":{x:.288,y:.014,z:.092},"RightHandMiddle2.rotation":{x:.248,y:.003,z:.02},"RightHandMiddle3.rotation":{x:.249,y:.003,z:.02},"RightHandRing1.rotation":{x:.369,y:.019,z:.006},"RightHandRing2.rotation":{x:.321,y:.004,z:.026},"RightHandRing3.rotation":{x:.323,y:.004,z:.026},"RightHandPinky1.rotation":{x:.468,y:.085,z:-.03},"RightHandPinky2.rotation":{x:.427,y:.007,z:.034},"RightHandPinky3.rotation":{x:.142,y:.001,z:.012},"LeftUpLeg.rotation":{x:-.077,y:-.058,z:3.126},"LeftLeg.rotation":{x:-.252,y:.001,z:-.018},"LeftFoot.rotation":{x:1.315,y:-.064,z:.315},"LeftToeBase.rotation":{x:.577,y:-.07,z:-.009},"RightUpLeg.rotation":{x:-.083,y:-.032,z:3.124},"RightLeg.rotation":{x:-.272,y:-.003,z:.021},"RightFoot.rotation":{x:1.342,y:.076,z:-.222},"RightToeBase.rotation":{x:.44,y:.069,z:.016}}},wide:{standing:!0,props:{"Hips.position":{x:0,y:1.017,z:.016},"Hips.rotation":{x:.064,y:-.048,z:.059},"Spine.rotation":{x:-.123,y:0,z:-.018},"Spine1.rotation":{x:.014,y:.003,z:-.006},"Spine2.rotation":{x:.04,y:.003,z:-.007},"Neck.rotation":{x:.101,y:.007,z:-.035},"Head.rotation":{x:-.091,y:-.049,z:.105},"RightShoulder.rotation":{x:1.831,y:.017,z:1.731},"RightArm.rotation":{x:-1.673,y:-1.102,z:-3.132},"RightForeArm.rotation":{x:.265,y:.23,z:-.824},"RightHand.rotation":{x:-.52,y:.345,z:-.061},"RightHandThumb1.rotation":{x:.291,y:.056,z:-.428},"RightHandThumb2.rotation":{x:.025,y:.005,z:.166},"RightHandThumb3.rotation":{x:-.089,y:.009,z:.068},"RightHandIndex1.rotation":{x:.392,y:-.015,z:.11},"RightHandIndex2.rotation":{x:.391,y:.001,z:.004},"RightHandIndex3.rotation":{x:.326,y:0,z:.003},"RightHandMiddle1.rotation":{x:.285,y:.068,z:.081},"RightHandMiddle2.rotation":{x:.519,y:.004,z:.011},"RightHandMiddle3.rotation":{x:.252,y:0,z:.001},"RightHandRing1.rotation":{x:.207,y:.133,z:.146},"RightHandRing2.rotation":{x:.597,y:.004,z:.004},"RightHandRing3.rotation":{x:.292,y:.002,z:.012},"RightHandPinky1.rotation":{x:.338,y:.182,z:.136},"RightHandPinky2.rotation":{x:.533,y:.002,z:.004},"RightHandPinky3.rotation":{x:.194,y:0,z:.002},"LeftShoulder.rotation":{x:1.83,y:-.063,z:-1.808},"LeftArm.rotation":{x:-1.907,y:1.228,z:-2.959},"LeftForeArm.rotation":{x:-.159,y:.268,z:.572},"LeftHand.rotation":{x:.069,y:-.498,z:-.025},"LeftHandThumb1.rotation":{x:.738,y:.123,z:.178},"LeftHandThumb2.rotation":{x:-.26,y:.028,z:-.477},"LeftHandThumb3.rotation":{x:-.448,y:.093,z:-.661},"LeftHandIndex1.rotation":{x:1.064,y:.005,z:-.13},"LeftHandIndex2.rotation":{x:1.55,y:-.143,z:-.136},"LeftHandIndex3.rotation":{x:.722,y:-.076,z:-.127},"LeftHandMiddle1.rotation":{x:1.095,y:-.091,z:.006},"LeftHandMiddle2.rotation":{x:1.493,y:-.174,z:-.151},"LeftHandMiddle3.rotation":{x:.651,y:-.031,z:-.087},"LeftHandRing1.rotation":{x:1.083,y:-.224,z:.072},"LeftHandRing2.rotation":{x:1.145,y:-.107,z:-.195},"LeftHandRing3.rotation":{x:1.208,y:-.134,z:-.158},"LeftHandPinky1.rotation":{x:.964,y:-.383,z:.128},"LeftHandPinky2.rotation":{x:1.457,y:-.146,z:-.159},"LeftHandPinky3.rotation":{x:1.019,y:-.102,z:-.141},"RightUpLeg.rotation":{x:-.221,y:-.233,z:2.87},"RightLeg.rotation":{x:-.339,y:-.043,z:-.041},"RightFoot.rotation":{x:1.081,y:.177,z:.114},"RightToeBase.rotation":{x:.775,y:0,z:0},"LeftUpLeg.rotation":{x:-.185,y:.184,z:3.131},"LeftLeg.rotation":{x:-.408,y:.129,z:.02},"LeftFoot.rotation":{x:1.167,y:-.002,z:-.007},"LeftToeBase.rotation":{x:.723,y:0,z:0}}},oneknee:{kneeling:!0,props:{"Hips.position":{x:-.005,y:.415,z:-.017},"Hips.rotation":{x:-.25,y:.04,z:-.238},"Spine.rotation":{x:.037,y:.043,z:.047},"Spine1.rotation":{x:.317,y:.103,z:.066},"Spine2.rotation":{x:.433,y:.109,z:.054},"Neck.rotation":{x:-.156,y:-.092,z:.059},"Head.rotation":{x:-.398,y:-.032,z:.018},"RightShoulder.rotation":{x:1.546,y:.119,z:1.528},"RightArm.rotation":{x:.896,y:-.247,z:-.512},"RightForeArm.rotation":{x:.007,y:0,z:-1.622},"RightHand.rotation":{x:1.139,y:-.853,z:.874},"RightHandThumb1.rotation":{x:.176,y:.107,z:-.311},"RightHandThumb2.rotation":{x:-.047,y:-.003,z:.12},"RightHandThumb3.rotation":{x:0,y:0,z:0},"RightHandIndex1.rotation":{x:.186,y:.005,z:.125},"RightHandIndex2.rotation":{x:.454,y:.005,z:.015},"RightHandIndex3.rotation":{x:0,y:0,z:0},"RightHandMiddle1.rotation":{x:.444,y:.035,z:.127},"RightHandMiddle2.rotation":{x:.403,y:-.006,z:-.04},"RightHandMiddle3.rotation":{x:0,y:0,z:0},"RightHandRing1.rotation":{x:.543,y:.074,z:.121},"RightHandRing2.rotation":{x:.48,y:-.018,z:-.063},"RightHandRing3.rotation":{x:0,y:0,z:0},"RightHandPinky1.rotation":{x:.464,y:.086,z:.113},"RightHandPinky2.rotation":{x:.667,y:-.06,z:-.128},"RightHandPinky3.rotation":{x:0,y:0,z:0},"LeftShoulder.rotation":{x:1.545,y:-.116,z:-1.529},"LeftArm.rotation":{x:.799,y:.631,z:.556},"LeftForeArm.rotation":{x:-.002,y:.007,z:.926},"LeftHand.rotation":{x:-.508,y:.439,z:.502},"LeftHandThumb1.rotation":{x:.651,y:-.035,z:.308},"LeftHandThumb2.rotation":{x:-.053,y:.008,z:-.11},"LeftHandThumb3.rotation":{x:0,y:0,z:0},"LeftHandIndex1.rotation":{x:.662,y:-.053,z:-.116},"LeftHandIndex2.rotation":{x:.309,y:-.004,z:-.02},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:.501,y:-.062,z:-.12},"LeftHandMiddle2.rotation":{x:.144,y:-.002,z:.016},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.397,y:-.029,z:-.143},"LeftHandRing2.rotation":{x:.328,y:.01,z:.059},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.194,y:.008,z:-.164},"LeftHandPinky2.rotation":{x:.38,y:.031,z:.128},"LeftHandPinky3.rotation":{x:0,y:0,z:0},"RightUpLeg.rotation":{x:-1.594,y:-.251,z:2.792},"RightLeg.rotation":{x:-2.301,y:-.073,z:.055},"RightFoot.rotation":{x:1.553,y:-.207,z:-.094},"RightToeBase.rotation":{x:.459,y:.069,z:.016},"LeftUpLeg.rotation":{x:-.788,y:-.236,z:-2.881},"LeftLeg.rotation":{x:-2.703,y:.012,z:-.047},"LeftFoot.rotation":{x:2.191,y:-.102,z:.019},"LeftToeBase.rotation":{x:1.215,y:-.027,z:.01}}},kneel:{kneeling:!0,lying:!0,props:{"Hips.position":{x:0,y:.532,z:-.002},"Hips.rotation":{x:.018,y:-.008,z:-.017},"Spine.rotation":{x:-.139,y:-.01,z:.002},"Spine1.rotation":{x:.002,y:-.002,z:.001},"Spine2.rotation":{x:.028,y:-.002,z:.001},"Neck.rotation":{x:-.007,y:0,z:-.002},"Head.rotation":{x:-.02,y:-.008,z:-.004},"LeftShoulder.rotation":{x:1.77,y:-.428,z:-1.588},"LeftArm.rotation":{x:.911,y:.343,z:.083},"LeftForeArm.rotation":{x:0,y:0,z:.347},"LeftHand.rotation":{x:.033,y:-.052,z:-.105},"LeftHandThumb1.rotation":{x:.508,y:-.22,z:.708},"LeftHandThumb2.rotation":{x:-.323,y:-.139,z:-.56},"LeftHandThumb3.rotation":{x:-.328,y:.16,z:-.301},"LeftHandIndex1.rotation":{x:.178,y:.248,z:.045},"LeftHandIndex2.rotation":{x:.236,y:-.002,z:-.019},"LeftHandIndex3.rotation":{x:-.062,y:0,z:.005},"LeftHandMiddle1.rotation":{x:.123,y:-.005,z:-.019},"LeftHandMiddle2.rotation":{x:.589,y:-.014,z:-.045},"LeftHandMiddle3.rotation":{x:.231,y:-.002,z:-.019},"LeftHandRing1.rotation":{x:.196,y:-.008,z:-.091},"LeftHandRing2.rotation":{x:.483,y:-.009,z:-.038},"LeftHandRing3.rotation":{x:.367,y:-.005,z:-.029},"LeftHandPinky1.rotation":{x:.191,y:-.269,z:-.246},"LeftHandPinky2.rotation":{x:.37,y:-.006,z:-.029},"LeftHandPinky3.rotation":{x:.368,y:-.005,z:-.029},"RightShoulder.rotation":{x:1.73,y:.434,z:1.715},"RightArm.rotation":{x:.841,y:-.508,z:-.155},"RightForeArm.rotation":{x:0,y:0,z:-.355},"RightHand.rotation":{x:.091,y:.137,z:.197},"RightHandThumb1.rotation":{x:.33,y:.051,z:-.753},"RightHandThumb2.rotation":{x:-.113,y:.075,z:.612},"RightHandThumb3.rotation":{x:-.271,y:-.166,z:.164},"RightHandIndex1.rotation":{x:.073,y:.001,z:-.093},"RightHandIndex2.rotation":{x:.338,y:.006,z:.034},"RightHandIndex3.rotation":{x:.131,y:.001,z:.013},"RightHandMiddle1.rotation":{x:.13,y:.005,z:-.017},"RightHandMiddle2.rotation":{x:.602,y:.018,z:.058},"RightHandMiddle3.rotation":{x:-.031,y:0,z:-.003},"RightHandRing1.rotation":{x:.351,y:.019,z:.045},"RightHandRing2.rotation":{x:.19,y:.002,z:.019},"RightHandRing3.rotation":{x:.21,y:.002,z:.021},"RightHandPinky1.rotation":{x:.256,y:.17,z:.118},"RightHandPinky2.rotation":{x:.451,y:.01,z:.045},"RightHandPinky3.rotation":{x:.346,y:.006,z:.035},"LeftUpLeg.rotation":{x:-.06,y:.1,z:-2.918},"LeftLeg.rotation":{x:-1.933,y:-.01,z:.011},"LeftFoot.rotation":{x:.774,y:-.162,z:-.144},"LeftToeBase.rotation":{x:1.188,y:0,z:0},"RightUpLeg.rotation":{x:-.099,y:-.057,z:2.922},"RightLeg.rotation":{x:-1.93,y:.172,z:-.02},"RightFoot.rotation":{x:.644,y:.251,z:.212},"RightToeBase.rotation":{x:.638,y:-.034,z:-.001}}},sitting:{sitting:!0,lying:!0,props:{"Hips.position":{x:0,y:.117,z:.005},"Hips.rotation":{x:-.411,y:-.049,z:.056},"Spine.rotation":{x:.45,y:-.039,z:-.116},"Spine1.rotation":{x:.092,y:-.076,z:.08},"Spine2.rotation":{x:.073,y:.035,z:.066},"Neck.rotation":{x:.051,y:.053,z:-.079},"Head.rotation":{x:-.169,y:.009,z:.034},"LeftShoulder.rotation":{x:1.756,y:-.037,z:-1.301},"LeftArm.rotation":{x:-.098,y:.016,z:1.006},"LeftForeArm.rotation":{x:-.089,y:.08,z:.837},"LeftHand.rotation":{x:.262,y:-.399,z:.3},"LeftHandThumb1.rotation":{x:.149,y:-.043,z:.452},"LeftHandThumb2.rotation":{x:.032,y:.006,z:-.162},"LeftHandThumb3.rotation":{x:-.086,y:-.005,z:-.069},"LeftHandIndex1.rotation":{x:.145,y:.032,z:-.069},"LeftHandIndex2.rotation":{x:.325,y:-.001,z:-.004},"LeftHandIndex3.rotation":{x:.253,y:0,z:-.003},"LeftHandMiddle1.rotation":{x:.186,y:-.051,z:-.091},"LeftHandMiddle2.rotation":{x:.42,y:-.003,z:-.011},"LeftHandMiddle3.rotation":{x:.153,y:.001,z:-.001},"LeftHandRing1.rotation":{x:.087,y:-.19,z:-.078},"LeftHandRing2.rotation":{x:.488,y:-.004,z:-.005},"LeftHandRing3.rotation":{x:.183,y:-.001,z:-.012},"LeftHandPinky1.rotation":{x:.205,y:-.262,z:.051},"LeftHandPinky2.rotation":{x:.407,y:-.002,z:-.004},"LeftHandPinky3.rotation":{x:.068,y:0,z:-.002},"RightShoulder.rotation":{x:1.619,y:-.139,z:1.179},"RightArm.rotation":{x:.17,y:-.037,z:-1.07},"RightForeArm.rotation":{x:-.044,y:-.056,z:-.665},"RightHand.rotation":{x:.278,y:.454,z:-.253},"RightHandThumb1.rotation":{x:.173,y:.089,z:-.584},"RightHandThumb2.rotation":{x:-.003,y:-.004,z:.299},"RightHandThumb3.rotation":{x:-.133,y:-.002,z:.235},"RightHandIndex1.rotation":{x:.393,y:-.023,z:.108},"RightHandIndex2.rotation":{x:.391,y:.001,z:.004},"RightHandIndex3.rotation":{x:.326,y:0,z:.003},"RightHandMiddle1.rotation":{x:.285,y:.062,z:.086},"RightHandMiddle2.rotation":{x:.519,y:.003,z:.011},"RightHandMiddle3.rotation":{x:.252,y:-.001,z:.001},"RightHandRing1.rotation":{x:.207,y:.122,z:.155},"RightHandRing2.rotation":{x:.597,y:.004,z:.005},"RightHandRing3.rotation":{x:.292,y:.001,z:.012},"RightHandPinky1.rotation":{x:.338,y:.171,z:.149},"RightHandPinky2.rotation":{x:.533,y:.002,z:.004},"RightHandPinky3.rotation":{x:.194,y:0,z:.002},"LeftUpLeg.rotation":{x:-1.957,y:.083,z:-2.886},"LeftLeg.rotation":{x:-1.46,y:.123,z:.005},"LeftFoot.rotation":{x:-.013,y:.016,z:.09},"LeftToeBase.rotation":{x:.744,y:0,z:0},"RightUpLeg.rotation":{x:-1.994,y:.125,z:2.905},"RightLeg.rotation":{x:-1.5,y:-.202,z:-.006},"RightFoot.rotation":{x:-.012,y:-.065,z:.081},"RightToeBase.rotation":{x:.758,y:0,z:0}}}},this.gestureTemplates={handup:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.815,y:[-.4,0,1,2],z:1.575},"LeftHand.rotation":{x:-.529,y:-.2,z:.022},"LeftHandThumb1.rotation":{x:.745,y:-.526,z:.604},"LeftHandThumb2.rotation":{x:-.107,y:-.01,z:-.142},"LeftHandThumb3.rotation":{x:0,y:.001,z:0},"LeftHandIndex1.rotation":{x:-.126,y:-.035,z:-.087},"LeftHandIndex2.rotation":{x:.255,y:.007,z:-.085},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.019,y:-.128,z:-.082},"LeftHandMiddle2.rotation":{x:.233,y:.019,z:-.074},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.005,y:-.241,z:-.122},"LeftHandRing2.rotation":{x:.261,y:.021,z:-.076},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.059,y:-.336,z:-.2},"LeftHandPinky2.rotation":{x:.153,y:.019,z:.001},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},index:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.815,y:[-.4,0,1,2],z:1.575},"LeftHand.rotation":{x:-.276,y:-.506,z:-.208},"LeftHandThumb1.rotation":{x:.579,y:.228,z:.363},"LeftHandThumb2.rotation":{x:-.027,y:-.04,z:-.662},"LeftHandThumb3.rotation":{x:0,y:.001,z:0},"LeftHandIndex1.rotation":{x:0,y:-.105,z:.225},"LeftHandIndex2.rotation":{x:.256,y:-.103,z:-.213},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:1.453,y:.07,z:.021},"LeftHandMiddle2.rotation":{x:1.599,y:.062,z:.07},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:1.528,y:-.073,z:.052},"LeftHandRing2.rotation":{x:1.386,y:.044,z:.053},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:1.65,y:-.204,z:.031},"LeftHandPinky2.rotation":{x:1.302,y:.071,z:.085},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},ok:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,1],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.415,y:[-.4,0,1,2],z:1.575},"LeftHand.rotation":{x:-.476,y:-.506,z:-.208},"LeftHandThumb1.rotation":{x:.703,y:.445,z:.899},"LeftHandThumb2.rotation":{x:-.312,y:-.04,z:-.938},"LeftHandThumb3.rotation":{x:-.37,y:.024,z:-.393},"LeftHandIndex1.rotation":{x:.8,y:-.086,z:-.091},"LeftHandIndex2.rotation":{x:1.123,y:-.046,z:-.074},"LeftHandIndex3.rotation":{x:.562,y:-.013,z:-.043},"LeftHandMiddle1.rotation":{x:-.019,y:-.128,z:-.082},"LeftHandMiddle2.rotation":{x:.233,y:.019,z:-.074},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.005,y:-.241,z:-.122},"LeftHandRing2.rotation":{x:.261,y:.021,z:-.076},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.059,y:-.336,z:-.2},"LeftHandPinky2.rotation":{x:.153,y:.019,z:.001},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},thumbup:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-.415,y:.206,z:1.575},"LeftHand.rotation":{x:-.276,y:-.506,z:-.208},"LeftHandThumb1.rotation":{x:.208,y:-.189,z:.685},"LeftHandThumb2.rotation":{x:.129,y:-.285,z:-.163},"LeftHandThumb3.rotation":{x:-.047,y:.068,z:.401},"LeftHandIndex1.rotation":{x:1.412,y:-.102,z:-.152},"LeftHandIndex2.rotation":{x:1.903,y:-.16,z:-.114},"LeftHandIndex3.rotation":{x:.535,y:-.017,z:-.062},"LeftHandMiddle1.rotation":{x:1.424,y:-.103,z:-.12},"LeftHandMiddle2.rotation":{x:1.919,y:-.162,z:-.114},"LeftHandMiddle3.rotation":{x:.44,y:-.012,z:-.051},"LeftHandRing1.rotation":{x:1.619,y:-.127,z:-.053},"LeftHandRing2.rotation":{x:1.898,y:-.16,z:-.115},"LeftHandRing3.rotation":{x:.262,y:-.004,z:-.031},"LeftHandPinky1.rotation":{x:1.661,y:-.131,z:-.016},"LeftHandPinky2.rotation":{x:1.715,y:-.067,z:-.13},"LeftHandPinky3.rotation":{x:.627,y:-.023,z:-.071}},thumbdown:{"LeftShoulder.rotation":{x:[1.5,2,1,2],y:[.2,.4,1,2],z:[-1.5,-1.3,1,2]},"LeftArm.rotation":{x:[1.5,1.7,1,2],y:[-.6,-.4,1,2],z:[1,1.2,1,2]},"LeftForeArm.rotation":{x:-2.015,y:.406,z:1.575},"LeftHand.rotation":{x:-.176,y:-.206,z:-.208},"LeftHandThumb1.rotation":{x:.208,y:-.189,z:.685},"LeftHandThumb2.rotation":{x:.129,y:-.285,z:-.163},"LeftHandThumb3.rotation":{x:-.047,y:.068,z:.401},"LeftHandIndex1.rotation":{x:1.412,y:-.102,z:-.152},"LeftHandIndex2.rotation":{x:1.903,y:-.16,z:-.114},"LeftHandIndex3.rotation":{x:.535,y:-.017,z:-.062},"LeftHandMiddle1.rotation":{x:1.424,y:-.103,z:-.12},"LeftHandMiddle2.rotation":{x:1.919,y:-.162,z:-.114},"LeftHandMiddle3.rotation":{x:.44,y:-.012,z:-.051},"LeftHandRing1.rotation":{x:1.619,y:-.127,z:-.053},"LeftHandRing2.rotation":{x:1.898,y:-.16,z:-.115},"LeftHandRing3.rotation":{x:.262,y:-.004,z:-.031},"LeftHandPinky1.rotation":{x:1.661,y:-.131,z:-.016},"LeftHandPinky2.rotation":{x:1.715,y:-.067,z:-.13},"LeftHandPinky3.rotation":{x:.627,y:-.023,z:-.071}},side:{"LeftShoulder.rotation":{x:1.755,y:-.035,z:-1.63},"LeftArm.rotation":{x:1.263,y:-.955,z:1.024},"LeftForeArm.rotation":{x:0,y:0,z:.8},"LeftHand.rotation":{x:-.36,y:-1.353,z:-.184},"LeftHandThumb1.rotation":{x:.137,y:-.049,z:.863},"LeftHandThumb2.rotation":{x:-.293,y:.153,z:-.193},"LeftHandThumb3.rotation":{x:-.271,y:-.17,z:.18},"LeftHandIndex1.rotation":{x:-.018,y:.007,z:.28},"LeftHandIndex2.rotation":{x:.247,y:-.003,z:-.025},"LeftHandIndex3.rotation":{x:.13,y:-.001,z:-.013},"LeftHandMiddle1.rotation":{x:.333,y:-.015,z:.182},"LeftHandMiddle2.rotation":{x:.313,y:-.005,z:-.032},"LeftHandMiddle3.rotation":{x:.294,y:-.004,z:-.03},"LeftHandRing1.rotation":{x:.456,y:-.028,z:-.092},"LeftHandRing2.rotation":{x:.53,y:-.014,z:-.052},"LeftHandRing3.rotation":{x:.478,y:-.012,z:-.047},"LeftHandPinky1.rotation":{x:.647,y:-.049,z:-.184},"LeftHandPinky2.rotation":{x:.29,y:-.004,z:-.029},"LeftHandPinky3.rotation":{x:.501,y:-.013,z:-.049}},shrug:{"Neck.rotation":{x:[-.3,.3,1,2],y:[-.3,.3,1,2],z:[-.1,.1]},"Head.rotation":{x:[-.3,.3],y:[-.3,.3],z:[-.1,.1]},"RightShoulder.rotation":{x:1.732,y:-.058,z:1.407},"RightArm.rotation":{x:1.305,y:.46,z:.118},"RightForeArm.rotation":{x:[0,2],y:[-1,.2],z:-1.637},"RightHand.rotation":{x:-.048,y:.165,z:-.39},"RightHandThumb1.rotation":{x:1.467,y:.599,z:-1.315},"RightHandThumb2.rotation":{x:-.255,y:-.123,z:.119},"RightHandThumb3.rotation":{x:0,y:-.002,z:0},"RightHandIndex1.rotation":{x:-.293,y:-.066,z:-.112},"RightHandIndex2.rotation":{x:.181,y:.007,z:.069},"RightHandIndex3.rotation":{x:0,y:0,z:0},"RightHandMiddle1.rotation":{x:-.063,y:-.041,z:.032},"RightHandMiddle2.rotation":{x:.149,y:.005,z:.05},"RightHandMiddle3.rotation":{x:0,y:0,z:0},"RightHandRing1.rotation":{x:.152,y:-.03,z:.132},"RightHandRing2.rotation":{x:.194,y:.007,z:.058},"RightHandRing3.rotation":{x:0,y:0,z:0},"RightHandPinky1.rotation":{x:.306,y:-.015,z:.257},"RightHandPinky2.rotation":{x:.15,y:-.003,z:-.003},"RightHandPinky3.rotation":{x:0,y:0,z:0},"LeftShoulder.rotation":{x:1.713,y:.141,z:-1.433},"LeftArm.rotation":{x:1.136,y:-.422,z:-.416},"LeftForeArm.rotation":{x:1.42,y:.123,z:1.506},"LeftHand.rotation":{x:.073,y:-.138,z:.064},"LeftHandThumb1.rotation":{x:1.467,y:-.599,z:1.314},"LeftHandThumb2.rotation":{x:-.255,y:.123,z:-.119},"LeftHandThumb3.rotation":{x:0,y:.001,z:0},"LeftHandIndex1.rotation":{x:-.293,y:.066,z:.112},"LeftHandIndex2.rotation":{x:.181,y:-.007,z:-.069},"LeftHandIndex3.rotation":{x:0,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.062,y:.041,z:-.032},"LeftHandMiddle2.rotation":{x:.149,y:-.005,z:-.05},"LeftHandMiddle3.rotation":{x:0,y:0,z:0},"LeftHandRing1.rotation":{x:.152,y:.03,z:-.132},"LeftHandRing2.rotation":{x:.194,y:-.007,z:-.058},"LeftHandRing3.rotation":{x:0,y:0,z:0},"LeftHandPinky1.rotation":{x:.306,y:.015,z:-.257},"LeftHandPinky2.rotation":{x:.15,y:.003,z:.003},"LeftHandPinky3.rotation":{x:0,y:0,z:0}},namaste:{"RightShoulder.rotation":{x:1.758,y:.099,z:1.604},"RightArm.rotation":{x:.862,y:-.292,z:-.932},"RightForeArm.rotation":{x:.083,y:.066,z:-1.791},"RightHand.rotation":{x:-.52,y:-.001,z:-.176},"RightHandThumb1.rotation":{x:.227,y:.418,z:-.776},"RightHandThumb2.rotation":{x:-.011,y:-.003,z:.171},"RightHandThumb3.rotation":{x:-.041,y:-.001,z:-.013},"RightHandIndex1.rotation":{x:-.236,y:.003,z:-.028},"RightHandIndex2.rotation":{x:.004,y:0,z:.001},"RightHandIndex3.rotation":{x:.002,y:0,z:0},"RightHandMiddle1.rotation":{x:-.236,y:.003,z:-.028},"RightHandMiddle2.rotation":{x:.004,y:0,z:.001},"RightHandMiddle3.rotation":{x:.002,y:0,z:0},"RightHandRing1.rotation":{x:-.236,y:.003,z:-.028},"RightHandRing2.rotation":{x:.004,y:0,z:.001},"RightHandRing3.rotation":{x:.002,y:0,z:0},"RightHandPinky1.rotation":{x:-.236,y:.003,z:-.028},"RightHandPinky2.rotation":{x:.004,y:0,z:.001},"RightHandPinky3.rotation":{x:.002,y:0,z:0},"LeftShoulder.rotation":{x:1.711,y:-.002,z:-1.625},"LeftArm.rotation":{x:.683,y:.334,z:.977},"LeftForeArm.rotation":{x:.086,y:-.066,z:1.843},"LeftHand.rotation":{x:-.595,y:-.229,z:.096},"LeftHandThumb1.rotation":{x:.404,y:-.05,z:.537},"LeftHandThumb2.rotation":{x:-.02,y:.004,z:-.154},"LeftHandThumb3.rotation":{x:-.049,y:.002,z:-.019},"LeftHandIndex1.rotation":{x:-.113,y:-.001,z:.014},"LeftHandIndex2.rotation":{x:.003,y:0,z:0},"LeftHandIndex3.rotation":{x:.002,y:0,z:0},"LeftHandMiddle1.rotation":{x:-.113,y:-.001,z:.014},"LeftHandMiddle2.rotation":{x:.004,y:0,z:0},"LeftHandMiddle3.rotation":{x:.002,y:0,z:0},"LeftHandRing1.rotation":{x:-.113,y:-.001,z:.014},"LeftHandRing2.rotation":{x:.003,y:0,z:0},"LeftHandRing3.rotation":{x:.002,y:0,z:0},"LeftHandPinky1.rotation":{x:-.122,y:-.001,z:-.057},"LeftHandPinky2.rotation":{x:.012,y:.001,z:.07},"LeftHandPinky3.rotation":{x:.002,y:0,z:0}}},this.poseDelta={props:{"Hips.quaternion":{x:0,y:0,z:0},"Spine.quaternion":{x:0,y:0,z:0},"Spine1.quaternion":{x:0,y:0,z:0},"Neck.quaternion":{x:0,y:0,z:0},"Head.quaternion":{x:0,y:0,z:0},"Spine1.scale":{x:0,y:0,z:0},"Neck.scale":{x:0,y:0,z:0},"LeftArm.scale":{x:0,y:0,z:0},"RightArm.scale":{x:0,y:0,z:0}}},["Left","Right"].forEach(r=>{["Leg","UpLeg","Arm","ForeArm","Hand"].forEach(c=>{this.poseDelta.props[r+c+".quaternion"]={x:0,y:0,z:0}}),["HandThumb","HandIndex","HandMiddle","HandRing","HandPinky"].forEach(c=>{this.poseDelta.props[r+c+"1.quaternion"]={x:0,y:0,z:0},this.poseDelta.props[r+c+"2.quaternion"]={x:0,y:0,z:0},this.poseDelta.props[r+c+"3.quaternion"]={x:0,y:0,z:0}})});const n=new Set;Object.values(this.poseTemplates).forEach(r=>{Object.keys(this.propsToThreeObjects(r.props)).forEach(c=>n.add(c))}),Object.keys(this.poseDelta.props).forEach(r=>{n.add(r)}),this.posePropNames=[...n],this.poseName="side",this.poseWeightOnLeft=!0,this.gesture=null,this.poseCurrentTemplate=this.poseTemplates[this.poseName],this.poseStraight=this.propsToThreeObjects(this.poseTemplates.straight.props),this.poseBase=this.poseFactory(this.poseCurrentTemplate),this.poseTarget=this.poseFactory(this.poseCurrentTemplate),this.poseAvatar=null,this.avatarHeight=1.7,this.animTemplateEyes={name:"eyes",idle:{alt:[{p:()=>this.avatar?.hasOwnProperty("avatarIdleEyeContact")?this.avatar.avatarIdleEyeContact:this.opt.avatarIdleEyeContact,delay:[200,5e3],dt:[200,[2e3,5e3],[3e3,1e4,1,2]],vs:{headMove:[this.avatar?.hasOwnProperty("avatarIdleHeadMove")?this.avatar.avatarIdleHeadMove:this.opt.avatarIdleHeadMove],eyesRotateY:[[-.6,.6]],eyesRotateX:[[-.2,.6]],eyeContact:[null,1]}},{delay:[200,5e3],dt:[200,[2e3,5e3,1,2]],vs:{headMove:[this.avatar?.hasOwnProperty("avatarIdleHeadMove")?this.avatar.avatarIdleHeadMove:this.opt.avatarIdleHeadMove],eyesRotateY:[[-.6,.6]],eyesRotateX:[[-.2,.6]]}}]},speaking:{alt:[{p:()=>this.avatar?.hasOwnProperty("avatarSpeakingEyeContact")?this.avatar.avatarSpeakingEyeContact:this.opt.avatarSpeakingEyeContact,delay:[200,5e3],dt:[0,[3e3,1e4,1,2],[2e3,5e3]],vs:{eyeContact:[1,null],headMove:[null,this.avatar?.hasOwnProperty("avatarSpeakingHeadMove")?this.avatar.avatarSpeakingHeadMove:this.opt.avatarSpeakingHeadMove,null],eyesRotateY:[null,[-.6,.6]],eyesRotateX:[null,[-.2,.6]]}},{delay:[200,5e3],dt:[200,[2e3,5e3,1,2]],vs:{headMove:[this.avatar?.hasOwnProperty("avatarSpeakingHeadMove")?this.avatar.avatarSpeakingHeadMove:this.opt.avatarSpeakingHeadMove,null],eyesRotateY:[[-.6,.6]],eyesRotateX:[[-.2,.6]]}}]}},this.animTemplateBlink={name:"blink",alt:[{p:.85,delay:[1e3,8e3,1,2],dt:[50,[100,300],100],vs:{eyeBlinkLeft:[1,1,0],eyeBlinkRight:[1,1,0]}},{delay:[1e3,4e3,1,2],dt:[50,[100,200],100,[10,400,0],50,[100,200],100],vs:{eyeBlinkLeft:[1,1,0,0,1,1,0],eyeBlinkRight:[1,1,0,0,1,1,0]}}]},this.animMoods={neutral:{baseline:{eyesLookDown:0},speech:{deltaRate:0,deltaPitch:0,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1200,500,1e3],vs:{chestInhale:[.5,.5,0]}},{name:"pose",alt:[{p:.5,delay:[5e3,3e4],vs:{pose:["side"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{p:.3,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{delay:[5e3,3e4],vs:{pose:["straight"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}}]},{name:"head",idle:{delay:[0,1e3],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.3,.3]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},happy:{baseline:{mouthSmile:.2,eyesLookDown:0},speech:{deltaRate:0,deltaPitch:.1,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1200,500,1e3],vs:{chestInhale:[.5,.5,0]}},{name:"pose",idle:{alt:[{p:.6,delay:[5e3,3e4],vs:{pose:["side"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{p:.2,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{p:.1,delay:[5e3,3e4],vs:{pose:["straight"]}},{delay:[5e3,1e4],vs:{pose:["wide"]}},{delay:[1e3,3e3],vs:{pose:["turn"]}}]},speaking:{alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{p:.4,delay:[5e3,3e4],vs:{pose:["straight"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{delay:[5e3,2e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}}]}},{name:"head",idle:{dt:[[1e3,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.3,.3]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthLeft:[[0,.3,2]],mouthSmile:[[0,.2,3]],mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},angry:{baseline:{eyesLookDown:.1,browDownLeft:.6,browDownRight:.6,jawForward:.3,mouthFrownLeft:.7,mouthFrownRight:.7,mouthRollLower:.2,mouthShrugLower:.3,handFistLeft:1,handFistRight:1},speech:{deltaRate:-.2,deltaPitch:.2,deltaVolume:0},anims:[{name:"breathing",delay:500,dt:[1e3,500,1e3],vs:{chestInhale:[.7,.7,0]}},{name:"pose",alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.4,delay:[5e3,3e4],vs:{pose:["straight"]}},{p:.2,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}}]},{name:"head",idle:{delay:[100,500],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.2,.2]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},sad:{baseline:{eyesLookDown:.2,browDownRight:.1,browInnerUp:.6,browOuterUpRight:.2,eyeSquintLeft:.7,eyeSquintRight:.7,mouthFrownLeft:.8,mouthFrownRight:.8,mouthLeft:.2,mouthPucker:.5,mouthRollLower:.2,mouthRollUpper:.2,mouthShrugLower:.2,mouthShrugUpper:.2,mouthStretchLeft:.4},speech:{deltaRate:-.2,deltaPitch:-.2,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1e3,500,1e3],vs:{chestInhale:[.3,.3,0]}},{name:"pose",alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.4,delay:[5e3,3e4],vs:{pose:["straight"]}},{delay:[5e3,2e4],vs:{pose:["side"]},full:{delay:[5e3,2e4],vs:{pose:["oneknee"]}}}]},{name:"head",idle:{delay:[100,500],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.2,.2]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},fear:{baseline:{browInnerUp:.7,eyeSquintLeft:.5,eyeSquintRight:.5,eyeWideLeft:.6,eyeWideRight:.6,mouthClose:.1,mouthFunnel:.3,mouthShrugLower:.5,mouthShrugUpper:.5},speech:{deltaRate:-.2,deltaPitch:0,deltaVolume:0},anims:[{name:"breathing",delay:500,dt:[1e3,500,1e3],vs:{chestInhale:[.7,.7,0]}},{name:"pose",alt:[{p:.8,delay:[5e3,3e4],vs:{pose:["side"]}},{delay:[5e3,3e4],vs:{pose:["straight"]}},{delay:[5e3,2e4],vs:{pose:["wide"]}},{delay:[5e3,2e4],vs:{pose:["side"]},full:{delay:[5e3,2e4],vs:{pose:["oneknee"]}}}]},{name:"head",idle:{delay:[100,500],dt:[[200,3e3]],vs:{bodyRotateX:[[-.06,.12]],bodyRotateY:[[-.7,.7]],bodyRotateZ:[[-.1,.1]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},disgust:{baseline:{browDownLeft:.7,browDownRight:.1,browInnerUp:.3,eyeSquintLeft:1,eyeSquintRight:1,eyeWideLeft:.5,eyeWideRight:.5,eyesRotateX:.05,mouthLeft:.4,mouthPressLeft:.3,mouthRollLower:.3,mouthShrugLower:.3,mouthShrugUpper:.8,mouthUpperUpLeft:.3,noseSneerLeft:1,noseSneerRight:.7},speech:{deltaRate:-.2,deltaPitch:0,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1e3,500,1e3],vs:{chestInhale:[.5,.5,0]}},{name:"pose",alt:[{delay:[5e3,2e4],vs:{pose:["side"]}}]},{name:"head",idle:{delay:[100,500],dt:[[200,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.2,.2]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.animTemplateBlink,{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[100,500],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[0,.3,2]],browOuterUpLeft:[[0,.3,2]],browOuterUpRight:[[0,.3,2]]}}]},love:{baseline:{browInnerUp:.4,browOuterUpLeft:.2,browOuterUpRight:.2,mouthSmile:.2,eyeBlinkLeft:.6,eyeBlinkRight:.6,eyeWideLeft:.7,eyeWideRight:.7,bodyRotateX:.1,mouthDimpleLeft:.1,mouthDimpleRight:.1,mouthPressLeft:.2,mouthShrugUpper:.2,mouthUpperUpLeft:.1,mouthUpperUpRight:.1},speech:{deltaRate:-.1,deltaPitch:-.7,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1500,500,1500],vs:{chestInhale:[.8,.8,0]}},{name:"pose",alt:[{p:.4,delay:[5e3,3e4],vs:{pose:["side"]}},{p:.2,delay:[5e3,3e4],vs:{pose:["straight"]}},{p:.2,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["side"]}}},{delay:[5e3,1e4],vs:{pose:["side"]},full:{delay:[5e3,1e4],vs:{pose:["kneel"]}}},{delay:[1e3,3e3],vs:{pose:["turn"]},M:{delay:[1e3,3e3],vs:{pose:["wide"]}}},{delay:[1e3,3e3],vs:{pose:["back"]},M:{delay:[1e3,3e3],vs:{pose:["wide"]}}},{delay:[5e3,2e4],vs:{pose:["side"]},M:{delay:[5e3,2e4],vs:{pose:["side"]}},full:{delay:[5e3,2e4],vs:{pose:["bend"]}}},{delay:[1e3,3e3],vs:{pose:["side"]},full:{delay:[5e3,1e4],vs:{pose:["oneknee"]}}}]},{name:"head",idle:{dt:[[1e3,5e3]],vs:{bodyRotateX:[[-.04,.1]],bodyRotateY:[[-.3,.3]],bodyRotateZ:[[-.08,.08]]}},speaking:{dt:[[0,1e3,0]],vs:{bodyRotateX:[[-.05,.15,1,2]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.1,.1]]}}},this.animTemplateEyes,this.deepCopy(this.animTemplateBlink,r=>{r.alt[0].delay[0]=r.alt[1].delay[0]=2e3}),{name:"mouth",delay:[1e3,5e3],dt:[[100,500],[100,5e3,2]],vs:{mouthLeft:[[0,.3,2]],mouthRollLower:[[0,.3,2]],mouthRollUpper:[[0,.3,2]],mouthStretchLeft:[[0,.3]],mouthStretchRight:[[0,.3]],mouthPucker:[[0,.3]]}},{name:"misc",delay:[100,5e3],dt:[[500,1e3],[1e3,5e3,2]],vs:{eyeSquintLeft:[[0,.3,2]],eyeSquintRight:[[0,.3,2]],browInnerUp:[[.3,.6,2]],browOuterUpLeft:[[.1,.3,2]],browOuterUpRight:[[.1,.3,2]]}}]},sleep:{baseline:{eyeBlinkLeft:1,eyeBlinkRight:1,eyesClosed:.6},speech:{deltaRate:0,deltaPitch:-.2,deltaVolume:0},anims:[{name:"breathing",delay:1500,dt:[1e3,500,1e3],vs:{chestInhale:[.6,.6,0]}},{name:"pose",alt:[{delay:[5e3,2e4],vs:{pose:["side"]}}]},{name:"head",delay:[1e3,5e3],dt:[[2e3,1e4]],vs:{bodyRotateX:[[0,.4]],bodyRotateY:[[-.1,.1]],bodyRotateZ:[[-.04,.04]]}},{name:"eyes",delay:10010,dt:[],vs:{}},{name:"blink",delay:10020,dt:[],vs:{}},{name:"mouth",delay:10030,dt:[],vs:{}},{name:"misc",delay:10040,dt:[],vs:{}}]}},this.moodName=this.opt.avatarMood||"neutral",this.mood=this.animMoods[this.moodName],this.mood||(this.moodName="neutral",this.mood=this.animMoods.neutral),this.animEmojis={"😐":{dt:[300,2e3],rescale:[0,1],vs:{pose:["straight"],browInnerUp:[.4],eyeWideLeft:[.7],eyeWideRight:[.7],mouthPressLeft:[.6],mouthPressRight:[.6],mouthRollLower:[.3],mouthStretchLeft:[1],mouthStretchRight:[1]}},"😶":{link:"😐"},"😏":{dt:[300,2e3],rescale:[0,1],vs:{eyeContact:[0],browDownRight:[.1],browInnerUp:[.7],browOuterUpRight:[.2],eyeLookInRight:[.7],eyeLookOutLeft:[.7],eyeSquintLeft:[1],eyeSquintRight:[.8],eyesRotateY:[.7],mouthLeft:[.4],mouthPucker:[.4],mouthShrugLower:[.3],mouthShrugUpper:[.2],mouthSmile:[.2],mouthSmileLeft:[.4],mouthSmileRight:[.2],mouthStretchLeft:[.5],mouthUpperUpLeft:[.6],noseSneerLeft:[.7]}},"🙂":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5]}},"🙃":{link:"🙂"},"😊":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.6],eyeSquintLeft:[1],eyeSquintRight:[1],mouthSmile:[.7],noseSneerLeft:[.7],noseSneerRight:[.7]}},"😇":{link:"😊"},"😀":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.6],jawOpen:[.1],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😃":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.6],eyeWideLeft:[.7],eyeWideRight:[.7],jawOpen:[.1],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😄":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],jawOpen:[.2],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😁":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],jawOpen:[.3],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthPressLeft:[.5],mouthPressRight:[.5],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😆":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.6],jawOpen:[.3],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthPressLeft:[.5],mouthPressRight:[.5],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"😝":{dt:[300,100,1500,500,500],rescale:[0,0,1,0,0],vs:{browInnerUp:[.8],eyesClosed:[1],jawOpen:[.7],mouthFunnel:[.5],mouthSmile:[1],tongueOut:[0,1,1,0]}},"😋":{link:"😝"},"😛":{link:"😝"},"😛":{link:"😝"},"😜":{link:"😝"},"🤪":{link:"😝"},"😂":{dt:[300,2e3],rescale:[0,1],vs:{browInnerUp:[.3],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.6],jawOpen:[.3],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthPressLeft:[.5],mouthPressRight:[.5],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"🤣":{link:"😂"},"😅":{link:"😂"},"😉":{dt:[500,200,500,500],rescale:[0,0,0,1],vs:{mouthSmile:[.5],mouthOpen:[.2],mouthSmileLeft:[0,.5,0],eyeBlinkLeft:[0,.7,0],eyeBlinkRight:[0,0,0],bodyRotateX:[.05,.05,.05,0],bodyRotateZ:[-.05,-.05,-.05,0],browDownLeft:[0,.7,0],cheekSquintLeft:[0,.7,0],eyeSquintLeft:[0,1,0],eyesClosed:[0]}},"😭":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[1],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.1],jawOpen:[0],mouthFrownLeft:[1],mouthFrownRight:[1],mouthOpen:[.5],mouthPucker:[.5],mouthUpperUpLeft:[.6],mouthUpperUpRight:[.6]}},"🥺":{dt:[1e3,1e3],rescale:[0,1],vs:{browDownLeft:[.2],browDownRight:[.2],browInnerUp:[1],eyeWideLeft:[.9],eyeWideRight:[.9],eyesClosed:[.1],mouthClose:[.2],mouthFrownLeft:[1],mouthFrownRight:[1],mouthPressLeft:[.4],mouthPressRight:[.4],mouthPucker:[1],mouthRollLower:[.6],mouthRollUpper:[.2],mouthUpperUpLeft:[.8],mouthUpperUpRight:[.8]}},"😞":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[.7],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.5],bodyRotateX:[.3],mouthClose:[.2],mouthFrownLeft:[1],mouthFrownRight:[1],mouthPucker:[1],mouthRollLower:[1],mouthShrugLower:[.2],mouthUpperUpLeft:[.8],mouthUpperUpRight:[.8]}},"😔":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[1],eyeSquintLeft:[1],eyeSquintRight:[1],eyesClosed:[.5],bodyRotateX:[.3],mouthClose:[.2],mouthFrownLeft:[1],mouthFrownRight:[1],mouthPressLeft:[.4],mouthPressRight:[.4],mouthPucker:[1],mouthRollLower:[.6],mouthRollUpper:[.2],mouthUpperUpLeft:[.8],mouthUpperUpRight:[.8]}},"😳":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[1],eyeWideLeft:[.5],eyeWideRight:[.5],eyesRotateY:[.05],eyesRotateX:[.05],mouthClose:[.2],mouthFunnel:[.5],mouthPucker:[.4],mouthRollLower:[.4],mouthRollUpper:[.4]}},"☹️":{dt:[500,1500],rescale:[0,1],vs:{mouthFrownLeft:[1],mouthFrownRight:[1],mouthPucker:[.1],mouthRollLower:[.8]}},"😚":{dt:[500,1e3,1e3],rescale:[0,1,0],vs:{browInnerUp:[.6],eyeBlinkLeft:[1],eyeBlinkRight:[1],eyeSquintLeft:[1],eyeSquintRight:[1],mouthPucker:[0,.5],noseSneerLeft:[0,.7],noseSneerRight:[0,.7],viseme_U:[0,1]}},"😘":{dt:[500,500,200,500],rescale:[0,0,0,1],vs:{browInnerUp:[.6],eyeBlinkLeft:[0,0,1,0],eyeBlinkRight:[0],eyesRotateY:[0],bodyRotateY:[0],bodyRotateX:[0,.05,.05,0],bodyRotateZ:[0,-.05,-.05,0],eyeSquintLeft:[1],eyeSquintRight:[1],mouthPucker:[0,.5,0],noseSneerLeft:[0,.7],noseSneerRight:[.7],viseme_U:[0,1]}},"🥰":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[.6],eyeSquintLeft:[1],eyeSquintRight:[1],mouthSmile:[.7],noseSneerLeft:[.7],noseSneerRight:[.7]}},"😍":{dt:[1e3,1e3],rescale:[0,1],vs:{browInnerUp:[.6],jawOpen:[.1],mouthDimpleLeft:[.2],mouthDimpleRight:[.2],mouthOpen:[.3],mouthPressLeft:[.3],mouthPressRight:[.3],mouthRollLower:[.4],mouthShrugUpper:[.4],mouthSmile:[.7],mouthUpperUpLeft:[.3],mouthUpperUpRight:[.3],noseSneerLeft:[.4],noseSneerRight:[.4]}},"🤩":{link:"😍"},"😡":{dt:[1e3,1500],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],eyesLookUp:[.2],jawForward:[.3],mouthFrownLeft:[1],mouthFrownRight:[1],bodyRotateX:[.15]}},"😠":{dt:[1e3,1500],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],eyesLookUp:[.2],jawForward:[.3],mouthFrownLeft:[1],mouthFrownRight:[1],bodyRotateX:[.15]}},"🤬":{link:"😠"},"😒":{dt:[1e3,1e3],rescale:[0,1],vs:{eyeContact:[0],browDownRight:[.1],browInnerUp:[.7],browOuterUpRight:[.2],eyeLookInRight:[.7],eyeLookOutLeft:[.7],eyeSquintLeft:[1],eyeSquintRight:[.8],eyesRotateY:[.7],mouthFrownLeft:[1],mouthFrownRight:[1],mouthLeft:[.2],mouthPucker:[.5],mouthRollLower:[.2],mouthRollUpper:[.2],mouthShrugLower:[.2],mouthShrugUpper:[.2],mouthStretchLeft:[.5]}},"😱":{dt:[500,1500],rescale:[0,1],vs:{browInnerUp:[.8],eyeWideLeft:[.5],eyeWideRight:[.5],jawOpen:[.7],mouthFunnel:[.5]}},"😬":{dt:[500,1500],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],browInnerUp:[1],mouthDimpleLeft:[.5],mouthDimpleRight:[.5],mouthLowerDownLeft:[1],mouthLowerDownRight:[1],mouthPressLeft:[.4],mouthPressRight:[.4],mouthPucker:[.5],mouthSmile:[.1],mouthSmileLeft:[.2],mouthSmileRight:[.2],mouthStretchLeft:[1],mouthStretchRight:[1],mouthUpperUpLeft:[1],mouthUpperUpRight:[1]}},"🙄":{dt:[500,1500],rescale:[0,1],vs:{browInnerUp:[.8],eyeWideLeft:[1],eyeWideRight:[1],eyesRotateX:[-.8],bodyRotateX:[.15],mouthPucker:[.5],mouthRollLower:[.6],mouthRollUpper:[.5],mouthShrugLower:[0],mouthSmile:[0]}},"🤔":{dt:[500,1500],rescale:[0,1],vs:{browDownLeft:[1],browOuterUpRight:[1],eyeSquintLeft:[.6],mouthFrownLeft:[.7],mouthFrownRight:[.7],mouthLowerDownLeft:[.3],mouthPressRight:[.4],mouthPucker:[.1],mouthRight:[.5],mouthRollLower:[.5],mouthRollUpper:[.2],handRight:[{x:.1,y:.1,z:.1,d:1e3},{d:1e3}],handFistRight:[.1]}},"👀":{dt:[500,1500],rescale:[0,1],vs:{eyesRotateY:[-.8]}},"😴":{dt:[5e3,5e3],rescale:[0,1],vs:{eyeBlinkLeft:[1],eyeBlinkRight:[1],bodyRotateX:[.2],bodyRotateZ:[.1]}},"✋":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["handup",2,!0],null]}},"🤚":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["handup",2],null]}},"👋":{link:"✋"},"👍":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["thumbup",2],null]}},"👎":{dt:[300,2e3],rescale:[0,1],vs:{browDownLeft:[1],browDownRight:[1],eyesLookUp:[.2],jawForward:[.3],mouthFrownLeft:[1],mouthFrownRight:[1],bodyRotateX:[.15],gesture:[["thumbdown",2],null]}},"👌":{dt:[300,2e3],rescale:[0,1],vs:{mouthSmile:[.5],gesture:[["ok",2],null]}},"🤷‍♂️":{dt:[1e3,1500],rescale:[0,1],vs:{gesture:[["shrug",2],null]}},"🤷‍♀️":{link:"🤷‍♂️"},"🤷":{link:"🤷‍♂️"},"🙏":{dt:[1500,300,1e3],rescale:[0,1,0],vs:{eyeBlinkLeft:[0,1],eyeBlinkRight:[0,1],bodyRotateX:[0],bodyRotateZ:[.1],gesture:[["namaste",2],null]}},yes:{dt:[[200,500],[200,500],[200,500],[200,500]],vs:{headMove:[0],headRotateX:[[.1,.2],.1,[.1,.2],0],headRotateZ:[[-.2,.2]]}},no:{dt:[[200,500],[200,500],[200,500],[200,500],[200,500]],vs:{headMove:[0],headRotateY:[[-.1,-.05],[.05,.1],[-.1,-.05],[.05,.1],0],headRotateZ:[[-.2,.2]]}}},this.mtAvatar={},this.mtCustoms=["handFistLeft","handFistRight","bodyRotateX","bodyRotateY","bodyRotateZ","headRotateX","headRotateY","headRotateZ","chestInhale"],this.mtEasingDefault=this.sigmoidFactory(5),this.mtAccDefault=.01,this.mtAccExceptions={eyeBlinkLeft:.1,eyeBlinkRight:.1,eyeLookOutLeft:.1,eyeLookInLeft:.1,eyeLookOutRight:.1,eyeLookInRight:.1},this.mtMaxVDefault=5,this.mtMaxVExceptions={bodyRotateX:1,bodyRotateY:1,bodyRotateZ:1},this.mtBaselineDefault=0,this.mtBaselineExceptions={bodyRotateX:null,bodyRotateY:null,bodyRotateZ:null,eyeLookOutLeft:null,eyeLookInLeft:null,eyeLookOutRight:null,eyeLookInRight:null,eyesLookDown:null,eyesLookUp:null},this.mtMinDefault=0,this.mtMinExceptions={bodyRotateX:-1,bodyRotateY:-1,bodyRotateZ:-1,headRotateX:-1,headRotateY:-1,headRotateZ:-1},this.mtMaxDefault=1,this.mtMaxExceptions={},this.mtLimits={eyeBlinkLeft:r=>Math.max(r,(this.mtAvatar.eyesLookDown.value+this.mtAvatar.browDownLeft.value)/2),eyeBlinkRight:r=>Math.max(r,(this.mtAvatar.eyesLookDown.value+this.mtAvatar.browDownRight.value)/2)},this.mtOnchange={eyesLookDown:()=>{this.mtAvatar.eyeBlinkLeft.needsUpdate=!0,this.mtAvatar.eyeBlinkRight.needsUpdate=!0},browDownLeft:()=>{this.mtAvatar.eyeBlinkLeft.needsUpdate=!0},browDownRight:()=>{this.mtAvatar.eyeBlinkRight.needsUpdate=!0}},this.mtRandomized=["mouthDimpleLeft","mouthDimpleRight","mouthLeft","mouthPressLeft","mouthPressRight","mouthStretchLeft","mouthStretchRight","mouthShrugLower","mouthShrugUpper","noseSneerLeft","noseSneerRight","mouthRollLower","mouthRollUpper","browDownLeft","browDownRight","browOuterUpLeft","browOuterUpRight","cheekPuff","cheekSquintLeft","cheekSquintRight"],this.mtExtras=[{key:"mouthOpen",mix:{jawOpen:.5}},{key:"mouthSmile",mix:{mouthSmileLeft:.8,mouthSmileRight:.8}},{key:"eyesClosed",mix:{eyeBlinkLeft:1,eyeBlinkRight:1}},{key:"eyesLookUp",mix:{eyeLookUpLeft:1,eyeLookUpRight:1}},{key:"eyesLookDown",mix:{eyeLookDownLeft:1,eyeLookDownRight:1}}],this.animQueue=[],this.animClips=[],this.animPoses=[],this.animFrameDur=1e3/this.opt.modelFPS,this.animClock=0,this.animSlowdownRate=1,this.animTimeLast=0,this.easing=this.sigmoidFactory(5),this.lipsync={},this.opt.lipsyncModules.forEach(r=>{this.lipsyncGetProcessor(r)}),this.visemeNames=["aa","E","I","O","U","PP","SS","TH","DD","FF","kk","nn","RR","CH","sil"],this.segmenter=new Intl.Segmenter("en",{granularity:"grapheme"}),this.initAudioGraph(),this.audioPlaylist=[],this.volumeFrequencyData=new Uint8Array(16),this.volumeMax=0,this.volumeHeadBase=0,this.volumeHeadTarget=0,this.volumeHeadCurrent=0,this.volumeHeadVelocity=.15,this.volumeHeadEasing=this.sigmoidFactory(3),this.isListening=!1,this.listeningAnalyzer=null,this.listeningActive=!1,this.listeningVolume=0,this.listeningSilenceThresholdLevel=this.opt.listeningSilenceThresholdLevel,this.listeningSilenceThresholdMs=this.opt.listeningSilenceThresholdMs,this.listeningSilenceDurationMax=this.opt.listeningSilenceDurationMax,this.listeningActiveThresholdLevel=this.opt.listeningActiveThresholdLevel,this.listeningActiveThresholdMs=this.opt.listeningActiveThresholdMs,this.listeningActiveDurationMax=this.opt.listeningActiveDurationMax,this.listeningTimer=0,this.listeningTimerTotal=0,this.dracoEnabled=this.opt.dracoEnabled,this.dracoDecoderPath=this.opt.dracoDecoderPath;const o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";this.b64Lookup=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let r=0;r<o.length;r++)this.b64Lookup[o.charCodeAt(r)]=r;if(this.stateName="idle",this.speechQueue=[],this.isSpeaking=!1,this.isListening=!1,this.opt.ttsEndpoint){let r=new Audio;if(r.canPlayType("audio/ogg"))this.ttsAudioEncoding="OGG-OPUS";else if(r.canPlayType("audio/mp3"))this.ttsAudioEncoding="MP3";else throw new Error("There was no support for either OGG or MP3 audio.")}if(this.isAvatarOnly=this.opt.avatarOnly,this.isAvatarOnly)this.scene=this.opt.avatarOnlyScene,this.camera=this.opt.avatarOnlyCamera;else{this.renderer=new f.WebGLRenderer({antialias:!0,alpha:!0}),this.renderer.setPixelRatio(this.opt.modelPixelRatio*window.devicePixelRatio),this.renderer.setSize(this.nodeAvatar.clientWidth,this.nodeAvatar.clientHeight),this.renderer.outputColorSpace=f.SRGBColorSpace,this.renderer.toneMapping=f.ACESFilmicToneMapping,this.renderer.shadowMap.enabled=!1,this.nodeAvatar.appendChild(this.renderer.domElement),this.camera=new f.PerspectiveCamera(10,this.nodeAvatar.clientWidth/this.nodeAvatar.clientHeight,.1,2e3),this.scene=new f.Scene,this.lightAmbient=new f.AmbientLight(new f.Color(this.opt.lightAmbientColor),this.opt.lightAmbientIntensity),this.lightDirect=new f.DirectionalLight(new f.Color(this.opt.lightDirectColor),this.opt.lightDirectIntensity),this.lightSpot=new f.SpotLight(new f.Color(this.opt.lightSpotColor),this.opt.lightSpotIntensity,0,this.opt.lightSpotDispersion),this.setLighting(this.opt);const r=new f.PMREMGenerator(this.renderer);r.compileEquirectangularShader(),this.scene.environment=r.fromScene(new nt.RoomEnvironment).texture,this.resizeobserver=new ResizeObserver(this.onResize.bind(this)),this.resizeobserver.observe(this.nodeAvatar),this.controls=new $e.OrbitControls(this.camera,this.renderer.domElement),this.controls.enableZoom=this.opt.cameraZoomEnable,this.controls.enableRotate=this.opt.cameraRotateEnable,this.controls.enablePan=this.opt.cameraPanEnable,this.controls.minDistance=2,this.controls.maxDistance=2e3,this.controls.autoRotateSpeed=0,this.controls.autoRotate=!1,this.controls.update(),this.cameraClock=null}this.ikMesh=new f.SkinnedMesh;const s={LeftShoulder:null,LeftArm:"LeftShoulder",LeftForeArm:"LeftArm",LeftHand:"LeftForeArm",LeftHandMiddle1:"LeftHand",RightShoulder:null,RightArm:"RightShoulder",RightForeArm:"RightArm",RightHand:"RightForeArm",RightHandMiddle1:"RightHand"},i=[];Object.entries(s).forEach((r,c)=>{const l=new f.Bone;l.name=r[0],r[1]?this.ikMesh.getObjectByName(r[1]).add(l):this.ikMesh.add(l),i.push(l)}),this.ikMesh.bind(new f.Skeleton(i)),this.dynamicbones=new lt,this.isStreaming=!1,this.streamWorkletNode=null,this.streamAudioStartTime=null,this.streamWaitForAudioChunks=!0,this.streamLipsyncLang=null,this.streamLipsyncType="visemes",this.streamLipsyncQueue=[]}initAudioGraph(t=null){if(this.audioCtx&&this.audioCtx.state!=="closed"&&this.audioCtx.close(),t?this.audioCtx=new AudioContext({sampleRate:t}):this.audioCtx=new AudioContext,this.audioSpeechSource=this.audioCtx.createBufferSource(),this.audioBackgroundSource=this.audioCtx.createBufferSource(),this.audioBackgroundGainNode=this.audioCtx.createGain(),this.audioSpeechGainNode=this.audioCtx.createGain(),this.audioStreamGainNode=this.audioCtx.createGain(),this.audioAnalyzerNode=this.audioCtx.createAnalyser(),this.audioAnalyzerNode.fftSize=256,this.audioAnalyzerNode.smoothingTimeConstant=.1,this.audioAnalyzerNode.minDecibels=-70,this.audioAnalyzerNode.maxDecibels=-10,this.audioAnalyzer=new ut(this.audioCtx),this.audioReverbNode=this.audioCtx.createConvolver(),this.audioBackgroundGainNode.connect(this.audioReverbNode),this.audioAnalyzerNode.connect(this.audioSpeechGainNode),this.audioSpeechGainNode.connect(this.audioReverbNode),this.audioStreamGainNode.connect(this.audioReverbNode),this.audioReverbNode.connect(this.audioCtx.destination),this.setReverb(this.currentReverb||null),this.setMixerGain(this.opt.mixerGainSpeech,this.opt.mixerGainBackground),this.workletLoaded=!1,this.streamWorkletNode){try{this.streamWorkletNode.port.postMessage({type:"stop"}),this.streamWorkletNode.disconnect(),this.isStreaming=!1}catch(e){console.error("Error disconnecting streamWorkletNode:",e)}this.streamWorkletNode=null}}valueFn(t){return typeof t=="function"?t():t}deepCopy(t,e=null){const n=JSON.parse(JSON.stringify(t));return e&&typeof e=="function"&&e(n),n}b64ToArrayBuffer(t){let e=3*t.length/4;t[t.length-1]==="="&&(e--,t[t.length-2]==="="&&e--);const n=new ArrayBuffer(e),o=new Uint8Array(n);let s,i=0,r,c,l,u;for(s=0;s<t.length;s+=4)r=this.b64Lookup[t.charCodeAt(s)],c=this.b64Lookup[t.charCodeAt(s+1)],l=this.b64Lookup[t.charCodeAt(s+2)],u=this.b64Lookup[t.charCodeAt(s+3)],o[i++]=r<<2|c>>4,o[i++]=(c&15)<<4|l>>2,o[i++]=(l&3)<<6|u&63;return n}concatArrayBuffers(t){if(t.length===1)return t[0];let e=0;for(let i=0;i<t.length;i++)e+=t[i].byteLength;let n=new ArrayBuffer(e),o=new Uint8Array(n),s=0;for(let i=0;i<t.length;i++)o.set(new Uint8Array(t[i]),s),s+=t[i].byteLength;return n}pcmToAudioBuffer(t){const e=new Int16Array(t),n=new Float32Array(e.length);for(let s=0;s<e.length;s++)n[s]=e[s]>=32768?-(65536-e[s])/32768:e[s]/32767;const o=this.audioCtx.createBuffer(1,n.length,this.opt.pcmSampleRate);return o.copyToChannel(n,0,0),o}propsToThreeObjects(t){const e={};for(let[n,o]of Object.entries(t)){const s=n.split(".");let i=Array.isArray(o.x)?this.gaussianRandom(...o.x):o.x,r=Array.isArray(o.y)?this.gaussianRandom(...o.y):o.y,c=Array.isArray(o.z)?this.gaussianRandom(...o.z):o.z;s[1]==="position"||s[1]==="scale"?e[n]=new f.Vector3(i,r,c):s[1]==="rotation"?(n=s[0]+".quaternion",e[n]=new f.Quaternion().setFromEuler(new f.Euler(i,r,c,"XYZ")).normalize()):s[1]==="quaternion"&&(e[n]=new f.Quaternion(i,r,c,o.w).normalize())}return e}clearThree(t){for(;t.children.length;)this.clearThree(t.children[0]),t.remove(t.children[0]);t.geometry&&t.geometry.dispose(),t.material&&(Object.keys(t.material).forEach(e=>{t.material[e]&&t.material[e]!==null&&typeof t.material[e].dispose=="function"&&t.material[e].dispose()}),t.material.dispose())}addMixedMorphTarget(t,e,n,o=!1){t.forEach(s=>{if(!o&&s.morphTargetDictionary.hasOwnProperty(e))return;const i=s.geometry;let r=null,c=null;for(const[l,u]of Object.entries(n))if(s.morphTargetDictionary.hasOwnProperty(l)){const a=s.morphTargetDictionary[l],d=i.morphAttributes.position[a],h=i.morphAttributes.normal?.[a];r||(r=new f.Float32BufferAttribute(d.count*3,3),h&&(c=new f.Float32BufferAttribute(d.count*3,3)));for(let g=0;g<d.count;g++){const v=r.getX(g)+d.getX(g)*u,b=r.getY(g)+d.getY(g)*u,S=r.getZ(g)+d.getZ(g)*u;r.setXYZ(g,v,b,S)}if(h)for(let g=0;g<d.count;g++){const v=c.getX(g)+h.getX(g)*u,b=c.getY(g)+h.getY(g)*u,S=c.getZ(g)+h.getZ(g)*u;c.setXYZ(g,v,b,S)}}if(r){i.morphAttributes.position.push(r),c&&i.morphAttributes.normal.push(c);const l=i.morphAttributes.position.length-1;s.morphTargetInfluences[l]=0,s.morphTargetDictionary[e]=l}})}async showAvatar(t,e=null){if(!t||!t.hasOwnProperty("url"))throw new Error("Invalid parameter. The avatar must have at least 'url' specified.");const n=new et.GLTFLoader;if(this.dracoEnabled){const l=new tt.DRACOLoader;l.setDecoderPath(this.dracoDecoderPath),n.setDRACOLoader(l)}let o=await n.loadAsync(t.url,e);const s=[this.opt.modelRoot];if(this.posePropNames.forEach(l=>s.push(l.split(".")[0])),s.forEach(l=>{if(!o.scene.getObjectByName(l))throw new Error("Avatar object "+l+" not found")}),this.stop(),this.avatar=t,this.bodyMovement=t.bodyMovement||"idle",this.movementIntensity=t.movementIntensity||.5,this.showFullAvatar=t.showFullAvatar||!1,this.fbxAnimationLoader=null,this.dynamicbones.dispose(),this.mixer=null,this.isAvatarOnly?this.armature&&this.clearThree(this.armature):this.armature&&this.clearThree(this.scene),this.armature=o.scene.getObjectByName(this.opt.modelRoot),this.armature.scale.setScalar(1),this.animations=o.animations,this.userData=o.userData,this.morphs=[],this.armature.traverse(l=>{l.morphTargetInfluences&&l.morphTargetInfluences.length&&l.morphTargetDictionary&&this.morphs.push(l),l.frustumCulled=!1}),this.morphs.length===0)throw new Error("Blend shapes not found");const i=new Set(this.mtCustoms);this.morphs.forEach(l=>{Object.keys(l.morphTargetDictionary).forEach(u=>i.add(u))}),this.mtExtras.forEach(l=>{i.has(l.key)||(this.addMixedMorphTarget(this.morphs,l.key,l.mix),i.add(l.key))});const r={};if(i.forEach(l=>{r[l]={fixed:null,realtime:null,system:null,systemd:null,newvalue:null,ref:null,min:this.mtMinExceptions.hasOwnProperty(l)?this.mtMinExceptions[l]:this.mtMinDefault,max:this.mtMaxExceptions.hasOwnProperty(l)?this.mtMaxExceptions[l]:this.mtMaxDefault,easing:this.mtEasingDefault,base:null,v:0,needsUpdate:!0,acc:(this.mtAccExceptions.hasOwnProperty(l)?this.mtAccExceptions[l]:this.mtAccDefault)/1e3,maxv:(this.mtMaxVExceptions.hasOwnProperty(l)?this.mtMaxVExceptions[l]:this.mtMaxVDefault)/1e3,limit:this.mtLimits.hasOwnProperty(l)?this.mtLimits[l]:null,onchange:this.mtOnchange.hasOwnProperty(l)?this.mtOnchange[l]:null,baseline:this.avatar.baseline?.hasOwnProperty(l)?this.avatar.baseline[l]:this.mtBaselineExceptions.hasOwnProperty(l)?this.mtBaselineExceptions[l]:this.mtBaselineDefault,ms:[],is:[]},r[l].value=r[l].baseline,r[l].applied=r[l].baseline;const u=this.mtAvatar[l];u&&["fixed","system","systemd","realtime","base","v","value","applied"].forEach(a=>{r[l][a]=u[a]}),this.morphs.forEach(a=>{const d=a.morphTargetDictionary[l];d!==void 0&&(r[l].ms.push(a.morphTargetInfluences),r[l].is.push(d),a.morphTargetInfluences[d]=r[l].applied)})}),this.mtAvatar=r,this.poseAvatar={props:{}},this.posePropNames.forEach(l=>{const u=l.split("."),a=this.armature.getObjectByName(u[0]);this.poseAvatar.props[l]=a[u[1]],this.poseBase.props.hasOwnProperty(l)?this.poseAvatar.props[l].copy(this.poseBase.props[l]):this.poseBase.props[l]=this.poseAvatar.props[l].clone(),this.poseDelta.props.hasOwnProperty(l)&&!this.poseTarget.props.hasOwnProperty(l)&&(this.poseTarget.props[l]=this.poseAvatar.props[l].clone()),this.poseTarget.props[l].t=this.animClock,this.poseTarget.props[l].d=2e3}),this.ikMesh.traverse(l=>{l.isBone&&l.position.copy(this.armature.getObjectByName(l.name).position)}),this.isAvatarOnly?this.scene&&this.scene.add(this.armature):(this.scene.add(o.scene),this.scene.add(this.lightAmbient),this.scene.add(this.lightDirect),this.scene.add(this.lightSpot),this.lightSpot.target=this.armature.getObjectByName("Head")),t.hasOwnProperty("modelDynamicBones"))try{this.dynamicbones.setup(this.scene,this.armature,t.modelDynamicBones)}catch(l){console.error("Dynamic bones setup failed: "+l)}this.objectLeftToeBase=this.armature.getObjectByName("LeftToeBase"),this.objectRightToeBase=this.armature.getObjectByName("RightToeBase"),this.objectLeftEye=this.armature.getObjectByName("LeftEye"),this.objectRightEye=this.armature.getObjectByName("RightEye"),this.objectLeftArm=this.armature.getObjectByName("LeftArm"),this.objectRightArm=this.armature.getObjectByName("RightArm"),this.objectHips=this.armature.getObjectByName("Hips"),this.objectHead=this.armature.getObjectByName("Head"),this.objectNeck=this.armature.getObjectByName("Neck");const c=new f.Vector3;this.objectLeftEye.getWorldPosition(c),this.avatarHeight=c.y+.2,this.viewName||this.setView(this.opt.cameraView),this.setMood(this.avatar.avatarMood||this.moodName||this.opt.avatarMood),this.avatar.body==="M"&&this.poseTemplates.wide&&(this.poseName="wide",this.setPoseFromTemplate(this.poseTemplates.wide,0)),this.initializeFBXAnimationLoader(),this.bodyMovement&&this.bodyMovement!=="idle"&&this.applyBodyMovementAnimation(),this.start()}getViewNames(){return["full","mid","upper","head"]}getView(){return this.viewName}setView(t,e=null){if(t=t||this.viewName,t!=="full"&&t!=="upper"&&t!=="head"&&t!=="mid")return;if(!this.armature){this.opt.cameraView=t;return}if(this.viewName=t||this.viewName,e=e||{},this.isAvatarOnly)return;const n=e.hasOwnProperty("cameraX")?e.cameraX:this.opt.cameraX,o=e.hasOwnProperty("cameraY")?e.cameraY:this.opt.cameraY,s=e.hasOwnProperty("cameraDistance")?e.cameraDistance:this.opt.cameraDistance,i=e.hasOwnProperty("cameraRotateX")?e.cameraRotateX:this.opt.cameraRotateX,r=e.hasOwnProperty("cameraRotateY")?e.cameraRotateY:this.opt.cameraRotateY,c=this.camera.fov*(Math.PI/180);let l=-n*Math.tan(c/2),u=(1-o)*Math.tan(c/2),a=s;switch(this.viewName){case"head":a+=2,u=u*a+4*this.avatarHeight/5;break;case"upper":a+=4.5,u=u*a+2*this.avatarHeight/3;break;case"mid":a+=8,u=u*a+this.avatarHeight/3;break;default:a+=12,u=u*a}l=l*a,this.controlsEnd=new f.Vector3(l,u,0),this.cameraEnd=new f.Vector3(l,u,a).applyEuler(new f.Euler(i,r,0)),this.cameraClock===null&&(this.controls.target.copy(this.controlsEnd),this.camera.position.copy(this.cameraEnd)),this.controlsStart=this.controls.target.clone(),this.cameraStart=this.camera.position.clone(),this.cameraClock=0}setLighting(t){this.isAvatarOnly||(t=t||{},t.hasOwnProperty("lightAmbientColor")&&this.lightAmbient.color.set(new f.Color(t.lightAmbientColor)),t.hasOwnProperty("lightAmbientIntensity")&&(this.lightAmbient.intensity=t.lightAmbientIntensity,this.lightAmbient.visible=t.lightAmbientIntensity!==0),t.hasOwnProperty("lightDirectColor")&&this.lightDirect.color.set(new f.Color(t.lightDirectColor)),t.hasOwnProperty("lightDirectIntensity")&&(this.lightDirect.intensity=t.lightDirectIntensity,this.lightDirect.visible=t.lightDirectIntensity!==0),t.hasOwnProperty("lightDirectPhi")&&t.hasOwnProperty("lightDirectTheta")&&this.lightDirect.position.setFromSphericalCoords(2,t.lightDirectPhi,t.lightDirectTheta),t.hasOwnProperty("lightSpotColor")&&this.lightSpot.color.set(new f.Color(t.lightSpotColor)),t.hasOwnProperty("lightSpotIntensity")&&(this.lightSpot.intensity=t.lightSpotIntensity,this.lightSpot.visible=t.lightSpotIntensity!==0),t.hasOwnProperty("lightSpotPhi")&&t.hasOwnProperty("lightSpotTheta")&&(this.lightSpot.position.setFromSphericalCoords(2,t.lightSpotPhi,t.lightSpotTheta),this.lightSpot.position.add(new f.Vector3(0,1.5,0))),t.hasOwnProperty("lightSpotDispersion")&&(this.lightSpot.angle=t.lightSpotDispersion))}render(){this.isRunning&&!this.isAvatarOnly&&this.renderer&&this.renderer.render(this.scene,this.camera)}onResize(){!this.isAvatarOnly&&this.renderer&&(this.camera.aspect=this.nodeAvatar.clientWidth/this.nodeAvatar.clientHeight,this.camera.updateProjectionMatrix(),this.renderer.setSize(this.nodeAvatar.clientWidth,this.nodeAvatar.clientHeight),this.controls.update(),this.render())}updatePoseBase(t){for(const[e,n]of Object.entries(this.poseTarget.props)){const o=this.poseAvatar.props[e];if(o){let s=(t-n.t)/n.d;s>1||!this.poseBase.props.hasOwnProperty(e)?o.copy(n):o.isQuaternion?o.copy(this.poseBase.props[e].slerp(n,this.easing(s))):o.isVector3&&o.copy(this.poseBase.props[e].lerp(n,this.easing(s)))}}}applyShoulderAdjustment(){}applyShoulderAdjustmentToBones(){}updatePoseDelta(){for(const[t,e]of Object.entries(this.poseDelta.props)){if(e.x===0&&e.y===0&&e.z===0)continue;_.set(e.x,e.y,e.z);const n=this.poseAvatar.props[t];n.isQuaternion?(ie.setFromEuler(_),n.multiply(ie)):n.isVector3&&n.add(_)}}updateMorphTargets(t){for(let[e,n]of Object.entries(this.mtAvatar)){if(!n.needsUpdate)continue;let o=null,s=null;if(n.fixed!==null){if(o=n.fixed,n.system=null,n.systemd=null,n.newvalue=null,n.ref&&n.ref.hasOwnProperty(e)&&delete n.ref[e],n.ref=null,n.base=null,n.value===o){n.needsUpdate=!1;continue}}else n.realtime!==null?(n.ref=null,n.base=null,s=n.realtime):n.system!==null?(o=n.system,n.newvalue=null,n.ref&&n.ref.hasOwnProperty(e)&&delete n.ref[e],n.ref=null,n.base=null,n.systemd!==null?n.systemd===0?(o=null,n.system=null,n.systemd=null):(n.systemd-=t,n.systemd<0&&(n.systemd=0),n.value===o&&(o=null)):n.value===o&&(o=null,n.system=null)):n.newvalue!==null?(n.ref=null,n.base=null,s=n.newvalue,n.newvalue=null):n.base!==null?(o=n.base,n.ref=null,n.value===o&&(o=null,n.base=null,n.needsUpdate=!1)):(n.ref=null,n.baseline!==null&&n.value!==n.baseline?(o=n.baseline,n.base=n.baseline):n.needsUpdate=!1);if(o!==null){let i=o-n.value;i>=0?i<.005?(s=o,n.v=0):(n.v<n.maxv&&(n.v+=n.acc*t),n.v>=0?s=n.value+i*(1-Math.exp(-n.v*t)):s=n.value+n.v*t*(1-Math.exp(n.v*t))):i>-.005?(s=o,n.v=0):(n.v>-n.maxv&&(n.v-=n.acc*t),n.v>=0?s=n.value+n.v*t*(1-Math.exp(-n.v*t)):s=n.value+i*(1-Math.exp(n.v*t)))}if(n.limit!==null){if(s!==null&&s!==n.value&&(n.value=s,n.onchange!==null&&n.onchange(s)),s=n.limit(n.value),s===n.applied)continue}else{if(s===null||s===n.value)continue;n.value=s,n.onchange!==null&&n.onchange(s)}switch(n.applied=s,n.applied<n.min&&(n.applied=n.min),n.applied>n.max&&(n.applied=n.max),e){case"headRotateX":this.poseDelta.props["Head.quaternion"].x=n.applied+this.mtAvatar.bodyRotateX.applied;break;case"headRotateY":this.poseDelta.props["Head.quaternion"].y=n.applied+this.mtAvatar.bodyRotateY.applied;break;case"headRotateZ":this.poseDelta.props["Head.quaternion"].z=n.applied+this.mtAvatar.bodyRotateZ.applied;break;case"bodyRotateX":this.poseDelta.props["Head.quaternion"].x=n.applied+this.mtAvatar.headRotateX.applied,this.poseDelta.props["Spine1.quaternion"].x=n.applied/2,this.poseDelta.props["Spine.quaternion"].x=n.applied/8,this.poseDelta.props["Hips.quaternion"].x=n.applied/24;break;case"bodyRotateY":this.poseDelta.props["Head.quaternion"].y=n.applied+this.mtAvatar.headRotateY.applied,this.poseDelta.props["Spine1.quaternion"].y=n.applied/2,this.poseDelta.props["Spine.quaternion"].y=n.applied/2,this.poseDelta.props["Hips.quaternion"].y=n.applied/4,this.poseDelta.props["LeftUpLeg.quaternion"].y=n.applied/2,this.poseDelta.props["RightUpLeg.quaternion"].y=n.applied/2,this.poseDelta.props["LeftLeg.quaternion"].y=n.applied/4,this.poseDelta.props["RightLeg.quaternion"].y=n.applied/4;break;case"bodyRotateZ":this.poseDelta.props["Head.quaternion"].z=n.applied+this.mtAvatar.headRotateZ.applied,this.poseDelta.props["Spine1.quaternion"].z=n.applied/12,this.poseDelta.props["Spine.quaternion"].z=n.applied/12,this.poseDelta.props["Hips.quaternion"].z=n.applied/24;break;case"handFistLeft":case"handFistRight":const i=e.substring(8);["HandThumb","HandIndex","HandMiddle","HandRing","HandPinky"].forEach((u,a)=>{a===0?(this.poseDelta.props[i+u+"1.quaternion"].x=0,this.poseDelta.props[i+u+"2.quaternion"].z=(i==="Left"?-1:1)*n.applied,this.poseDelta.props[i+u+"3.quaternion"].z=(i==="Left"?-1:1)*n.applied):(this.poseDelta.props[i+u+"1.quaternion"].x=n.applied,this.poseDelta.props[i+u+"2.quaternion"].x=1.5*n.applied,this.poseDelta.props[i+u+"3.quaternion"].x=1.5*n.applied)});break;case"chestInhale":const r=n.applied/20,c={x:r,y:r/2,z:3*r},l={x:1/(1+r)-1,y:1/(1+r/2)-1,z:1/(1+3*r)-1};this.poseDelta.props["Spine1.scale"]=c,this.poseDelta.props["Neck.scale"]=l,this.poseDelta.props["LeftArm.scale"]=l,this.poseDelta.props["RightArm.scale"]=l;break;default:for(let u=0,a=n.ms.length;u<a;u++)n.ms[u][n.is[u]]=n.applied}}}getPoseString(t,e=1e3){let n="{";return Object.entries(t).forEach((o,s)=>{const i=o[0].split(".");if(i[1]==="position"||i[1]==="rotation"||i[1]==="quaternion"){const r=i[1]==="quaternion"?i[0]+".rotation":o[0],c=o[1].isQuaternion?new f.Euler().setFromQuaternion(o[1]):o[1];n+=(s?", ":"")+"'"+r+"':{",n+="x:"+Math.round(c.x*e)/e,n+=", y:"+Math.round(c.y*e)/e,n+=", z:"+Math.round(c.z*e)/e,n+="}"}}),n+="}",n}getPoseTemplateProp(t){const e=t.split(".");let n=e[0]+"."+(e[1]==="rotation"?"quaternion":e[1]);if(this.gesture&&this.gesture.hasOwnProperty(n))return this.gesture[n].clone();{let o=e[0]+"."+(e[1]==="quaternion"?"rotation":e[1]);this.poseWeightOnLeft||(o.startsWith("Left")?(o="Right"+o.substring(4),n="Right"+n.substring(4)):o.startsWith("Right")&&(o="Left"+o.substring(5),n="Left"+n.substring(5)));let s;if(this.poseTarget.template.props.hasOwnProperty(n)){const i={};i[n]=this.poseTarget.template.props[n],s=this.propsToThreeObjects(i)[n]}else if(this.poseTarget.template.props.hasOwnProperty(o)){const i={};i[o]=this.poseTarget.template.props[o],s=this.propsToThreeObjects(i)[n]}return s&&!this.poseWeightOnLeft&&s.isQuaternion&&(s.x*=-1,s.w*=-1),s}}mirrorPose(t){const e={};for(let[n,o]of Object.entries(t))o.isQuaternion&&(n.startsWith("Left")?n="Right"+n.substring(4):n.startsWith("Right")&&(n="Left"+n.substring(5)),o.x*=-1,o.w*=-1),e[n]=o.clone(),e[n].t=o.t,e[n].d=o.d;return e}poseFactory(t,e=2e3){const n={template:t,props:this.propsToThreeObjects(t.props)};for(const[o,s]of Object.entries(n.props)){if(this.opt.modelMovementFactor<1&&t.standing&&(o==="Hips.quaternion"||o==="Spine.quaternion"||o==="Spine1.quaternion"||o==="Spine2.quaternion"||o==="Neck.quaternion"||o==="LeftUpLeg.quaternion"||o==="LeftLeg.quaternion"||o==="RightUpLeg.quaternion"||o==="RightLeg.quaternion")){const i=this.poseStraight[o],r=s.angleTo(i);s.rotateTowards(i,(1-this.opt.modelMovementFactor)*r)}s.t=this.animClock,s.d=e}return n}setPoseFromTemplate(t,e=2e3){const n=t&&this.poseTarget&&this.poseTarget.template&&(this.poseTarget.template.standing&&t.lying||this.poseTarget.template.lying&&t.standing),o=t&&t===this.poseCurrentTemplate,s=this.poseWeightOnLeft;let i=n?1e3:e;if(n?(this.poseCurrentTemplate=this.poseTemplates.oneknee,setTimeout(()=>{this.setPoseFromTemplate(t,e)},i)):this.poseCurrentTemplate=t||this.poseCurrentTemplate,this.poseTarget=this.poseFactory(this.poseCurrentTemplate,i),this.poseWeightOnLeft=!0,(!o&&!s||o&&s)&&(this.poseTarget.props=this.mirrorPose(this.poseTarget.props),this.poseWeightOnLeft=!this.poseWeightOnLeft),this.gesture)for(let[r,c]of Object.entries(this.gesture))this.poseTarget.props.hasOwnProperty(r)&&(this.poseTarget.props[r].copy(c),this.poseTarget.props[r].t=c.t,this.poseTarget.props[r].d=c.d);Object.keys(this.poseDelta.props).forEach(r=>{this.poseTarget.props.hasOwnProperty(r)||(this.poseTarget.props[r]=this.poseBase.props[r].clone(),this.poseTarget.props[r].t=this.animClock,this.poseTarget.props[r].d=i)})}getValue(t){return this.mtAvatar[t]?.value}setValue(t,e,n=null){this.mtAvatar.hasOwnProperty(t)&&Object.assign(this.mtAvatar[t],{system:e,systemd:n,needsUpdate:!0})}getMoodNames(){return Object.keys(this.animMoods)}getMood(){return this.opt.avatarMood}setMood(t){if(t=(t||"").trim().toLowerCase(),!this.animMoods.hasOwnProperty(t))throw new Error("Unknown mood.");this.moodName=t,this.mood=this.animMoods[this.moodName];for(let e of Object.keys(this.mtAvatar)){let n=this.mtBaselineExceptions.hasOwnProperty(e)?this.mtBaselineExceptions[e]:this.mtBaselineDefault;this.mood.baseline.hasOwnProperty(e)?n=this.mood.baseline[e]:this.avatar.baseline?.hasOwnProperty(e)&&(n=this.avatar.baseline[e]),this.setBaselineValue(e,n)}this.mood.anims.forEach(e=>{let n=this.animQueue.findIndex(o=>o.template.name===e.name);n!==-1&&this.animQueue.splice(n,1),this.animQueue.push(this.animFactory(e,-1))})}async initializeFBXAnimationLoader(){try{const{FBXAnimationLoader:t}=await Promise.resolve().then(()=>require("./fbxAnimationLoader-CNrfhJRz.cjs"));this.fbxAnimationLoader=new t(this.armature)}catch(t){console.warn("FBX Animation Loader not available:",t),this.fbxAnimationLoader=null}}setBodyMovement(t){this.bodyMovement=t,this.avatar&&(this.avatar.bodyMovement=t),t==="idle"&&this.unlockAvatarPosition(),this.applyBodyMovementAnimation()}async applyBodyMovementAnimation(){if(!this.armature||!this.animQueue)return;if(this.animQueue=this.animQueue.filter(e=>!e.template.name.startsWith("bodyMovement")),this.bodyMovement==="idle"){this.fbxAnimationLoader&&this.fbxAnimationLoader.stopCurrentAnimation();return}if(this.fbxAnimationLoader)try{await this.fbxAnimationLoader.playGestureAnimation(this.bodyMovement,this.movementIntensity);return}catch{}const t=this.createBodyMovementAnimation(this.bodyMovement);if(t)try{const e=this.animFactory(t,!0);e&&e.ts&&e.ts.length>0?this.animQueue.push(e):(console.error("Invalid animation object created for:",this.bodyMovement),console.error("Animation object:",e))}catch(e){console.error("Error creating body movement animation:",e)}}lockAvatarPosition(){if(!this.armature){console.warn("Cannot lock position: armature not available");return}this.originalPosition||(this.originalPosition={x:this.armature.position.x,y:this.armature.position.y,z:this.armature.position.z}),this.lockedPosition={x:this.armature.position.x,y:this.armature.position.y,z:this.armature.position.z}}unlockAvatarPosition(){this.armature&&this.originalPosition?this.armature.position.set(this.originalPosition.x,this.originalPosition.y,this.originalPosition.z):this.armature&&this.armature.position.set(0,0,0),this.lockedPosition=null,this.originalPosition=null}maintainLockedPosition(){this.lockedPosition&&this.armature&&this.armature.position.set(this.lockedPosition.x,this.lockedPosition.y,this.lockedPosition.z)}createBodyMovementAnimation(t){const e=this.movementIntensity||.5,n={walking:{name:"bodyMovement_walking",delay:[500,2e3],dt:[800,1200],vs:{bodyRotateY:[-.1*e,.1*e,0],bodyRotateZ:[-.05*e,.05*e,0],bodyRotateX:[-.02*e,.02*e,0]}},prancing:{name:"bodyMovement_prancing",delay:[300,1e3],dt:[400,800],vs:{bodyRotateY:[-.15*e,.15*e,0],bodyRotateZ:[-.08*e,.08*e,0],bodyRotateX:[-.05*e,.05*e,0]}},gesturing:{name:"bodyMovement_gesturing",delay:[400,1500],dt:[600,1e3],vs:{bodyRotateY:[-.08*e,.08*e,0],bodyRotateZ:[-.03*e,.03*e,0]}},dancing:{name:"bodyMovement_dancing",delay:[200,600],dt:[400,800],vs:{bodyRotateY:[-.25*e,.25*e,0],bodyRotateZ:[-.15*e,.15*e,0],bodyRotateX:[-.1*e,.1*e,0]}},dancing2:{name:"bodyMovement_dancing2",delay:[150,500],dt:[300,700],vs:{bodyRotateY:[-.3*e,.3*e,0],bodyRotateZ:[-.2*e,.2*e,0],bodyRotateX:[-.12*e,.12*e,0]}},dancing3:{name:"bodyMovement_dancing3",delay:[100,400],dt:[200,600],vs:{bodyRotateY:[-.35*e,.35*e,0],bodyRotateZ:[-.25*e,.25*e,0],bodyRotateX:[-.15*e,.15*e,0]}},excited:{name:"bodyMovement_excited",delay:[200,600],dt:[300,700],vs:{bodyRotateY:[-.12*e,.12*e,0],bodyRotateZ:[-.06*e,.06*e,0],bodyRotateX:[-.04*e,.04*e,0]}},happy:{name:"bodyMovement_happy",delay:[300,800],dt:[500,1e3],vs:{bodyRotateY:[-.08*e,.08*e,0],bodyRotateZ:[-.04*e,.04*e,0],bodyRotateX:[-.02*e,.02*e,0]}},surprised:{name:"bodyMovement_surprised",delay:[100,300],dt:[200,500],vs:{bodyRotateY:[-.05*e,.05*e,0],bodyRotateZ:[-.03*e,.03*e,0],bodyRotateX:[-.01*e,.01*e,0]}},thinking:{name:"bodyMovement_thinking",delay:[800,2e3],dt:[1e3,1500],vs:{bodyRotateY:[-.06*e,.06*e,0],bodyRotateZ:[-.03*e,.03*e,0],bodyRotateX:[-.02*e,.02*e,0]}},nodding:{name:"bodyMovement_nodding",delay:[400,800],dt:[300,600],vs:{bodyRotateX:[-.1*e,.1*e,0],bodyRotateY:[-.02*e,.02*e,0]}},shaking:{name:"bodyMovement_shaking",delay:[200,400],dt:[150,300],vs:{bodyRotateY:[-.15*e,.15*e,0],bodyRotateZ:[-.05*e,.05*e,0]}},celebration:{name:"bodyMovement_celebration",delay:[100,300],dt:[200,500],vs:{bodyRotateY:[-.2*e,.2*e,0],bodyRotateZ:[-.1*e,.1*e,0],bodyRotateX:[-.08*e,.08*e,0]}},energetic:{name:"bodyMovement_energetic",delay:[150,400],dt:[250,500],vs:{bodyRotateY:[-.18*e,.18*e,0],bodyRotateZ:[-.12*e,.12*e,0],bodyRotateX:[-.08*e,.08*e,0]}},swaying:{name:"bodyMovement_swaying",delay:[600,1200],dt:[800,1e3],vs:{bodyRotateY:[-.1*e,.1*e,0],bodyRotateZ:[-.05*e,.05*e,0]}},bouncing:{name:"bodyMovement_bouncing",delay:[300,600],dt:[400,700],vs:{bodyRotateY:[-.05*e,.05*e,0]}}};if(t==="dancing"){const o=["dancing","dancing2","dancing3"],s=o[Math.floor(Math.random()*o.length)];return n[s]||n.dancing}return n[t]||null}playRandomDance(){const t=["dancing","dancing2","dancing3"],e=t[Math.floor(Math.random()*t.length)];this.setBodyMovement(e)}playReaction(t){["happy","surprised","thinking","nodding","shaking","celebration","energetic","swaying","bouncing"].includes(t)?(this.setBodyMovement(t),["surprised","nodding","shaking","celebration"].includes(t)&&setTimeout(()=>{this.setBodyMovement("idle")},3e3)):console.warn("Invalid reaction type:",t)}playCelebration(){this.playReaction("celebration"),setTimeout(()=>{this.playRandomDance()},2e3)}setMovementIntensity(t){this.movementIntensity=Math.max(0,Math.min(1,t)),this.avatar&&(this.avatar.movementIntensity=this.movementIntensity),this.fbxAnimationLoader&&this.fbxAnimationLoader.setIntensity(this.movementIntensity),this.applyBodyMovementAnimation()}setShowFullAvatar(t){this.showFullAvatar=t,this.avatar&&(this.avatar.showFullAvatar=t),t&&this.viewName!=="full"?this.setView("full"):!t&&this.viewName!=="upper"&&this.setView("upper")}getMorphTargetNames(){return["eyesRotateX","eyesRotateY",...Object.keys(this.mtAvatar)].sort()}getBaselineValue(t){if(t==="eyesRotateY"){const e=this.getBaselineValue("eyeLookOutLeft");if(e===void 0)return;const n=this.getBaselineValue("eyeLookInLeft");return n===void 0||this.getBaselineValue("eyeLookOutRight")===void 0||this.getBaselineValue("eyeLookInRight")===void 0?void 0:e-n}else if(t==="eyesRotateX"){const e=this.getBaselineValue("eyesLookDown");if(e===void 0)return;const n=this.getBaselineValue("eyesLookUp");return n===void 0?void 0:e-n}else return this.mtAvatar[t]?.baseline}setBaselineValue(t,e){t==="eyesRotateY"?(this.setBaselineValue("eyeLookOutLeft",e===null?null:e>0?e:0),this.setBaselineValue("eyeLookInLeft",e===null?null:e>0?0:-e),this.setBaselineValue("eyeLookOutRight",e===null?null:e>0?0:-e),this.setBaselineValue("eyeLookInRight",e===null?null:e>0?e:0)):t==="eyesRotateX"?(this.setBaselineValue("eyesLookDown",e===null?null:e>0?e:0),this.setBaselineValue("eyesLookUp",e===null?null:e>0?0:-e)):this.mtAvatar.hasOwnProperty(t)&&Object.assign(this.mtAvatar[t],{base:null,baseline:e,needsUpdate:!0})}getFixedValue(t){if(t==="eyesRotateY"){const e=this.getFixedValue("eyeLookOutLeft");if(e===null)return null;const n=this.getFixedValue("eyeLookInLeft");return n===null||this.getFixedValue("eyeLookOutRight")===null||this.getFixedValue("eyeLookInRight")===null?null:e-n}else if(t==="eyesRotateX"){const e=this.getFixedValue("eyesLookDown");if(e===null)return null;const n=this.getFixedValue("eyesLookUp");return n===null?null:e-n}else return this.mtAvatar[t]?.fixed}setFixedValue(t,e,n=null){t==="eyesRotateY"?(this.setFixedValue("eyeLookOutLeft",e===null?null:e>0?e:0,n),this.setFixedValue("eyeLookInLeft",e===null?null:e>0?0:-e,n),this.setFixedValue("eyeLookOutRight",e===null?null:e>0?0:-e,n),this.setFixedValue("eyeLookInRight",e===null?null:e>0?e:0,n)):t==="eyesRotateX"?(this.setFixedValue("eyesLookDown",e===null?null:e>0?e:0,n),this.setFixedValue("eyesLookUp",e===null?null:e>0?0:-e,n)):this.mtAvatar.hasOwnProperty(t)&&Object.assign(this.mtAvatar[t],{fixed:e,needsUpdate:!0})}animFactory(t,e=!1,n=1,o=1,s=!1){const i={template:t,ts:[0],vs:{}};let r=t;for(;;)if(r.hasOwnProperty(this.stateName))this.stateName==="speaking"||this.stateName,r=r[this.stateName];else if(r.hasOwnProperty(this.moodName))r=r[this.moodName];else if(r.hasOwnProperty(this.poseName))r=r[this.poseName];else if(r.hasOwnProperty(this.viewName))r=r[this.viewName];else if(this.avatar&&this.avatar.body&&r.hasOwnProperty(this.avatar.body))r=r[this.avatar.body];else if(r.hasOwnProperty("alt")){let l=r.alt[0];if(r.alt.length>1){const u=Math.random();let a=0;for(let d=0;d<r.alt.length;d++){let h=this.valueFn(r.alt[d].p);if(a+=h===void 0?(1-a)/(r.alt.length-1-d):h,u<a){l=r.alt[d];break}}}r=l,this.avatar&&this.avatar.body&&r.hasOwnProperty(this.avatar.body);continue}else break;let c=this.valueFn(r.delay)||0;if(Array.isArray(c)&&(c=this.gaussianRandom(...c)),r.hasOwnProperty("dt"))r.dt.forEach((l,u)=>{let a=this.valueFn(l);Array.isArray(a)&&(a=this.gaussianRandom(...a)),i.ts[u+1]=i.ts[u]+a});else{let l=Object.values(r.vs).reduce((u,a)=>a.length>u?a.length:u,0);i.ts=Array(l+1).fill(0)}s?i.ts=i.ts.map(l=>c+l*n):i.ts=i.ts.map(l=>this.animClock+c+l*n),r.vs&&r.vs.pose;for(let[l,u]of Object.entries(r.vs)){const a=this.getBaselineValue(l),d=u.map(h=>(h=this.valueFn(h),h===null?null:typeof h=="function"?h:typeof h=="string"||h instanceof String?l==="pose"&&this.avatar&&this.avatar.body==="M"&&(h==="hip"||h==="side")?"wide":h.slice():Array.isArray(h)?l==="gesture"?h.slice():(a===void 0?0:a)+o*this.gaussianRandom(...h):typeof h=="boolean"?h:h instanceof Object&&h.constructor===Object?Object.assign({},h):(a===void 0?0:a)+o*h));l==="eyesRotateY"?(i.vs.eyeLookOutLeft=[null,...d.map(h=>h>0?h:0)],i.vs.eyeLookInLeft=[null,...d.map(h=>h>0?0:-h)],i.vs.eyeLookOutRight=[null,...d.map(h=>h>0?0:-h)],i.vs.eyeLookInRight=[null,...d.map(h=>h>0?h:0)]):l==="eyesRotateX"?(i.vs.eyesLookDown=[null,...d.map(h=>h>0?h:0)],i.vs.eyesLookUp=[null,...d.map(h=>h>0?0:-h)]):i.vs[l]=[null,...d]}for(let l of Object.keys(i.vs))for(;i.vs[l].length<=i.ts.length;)i.vs[l].push(i.vs[l][i.vs[l].length-1]);return t.hasOwnProperty("mood")&&(i.mood=this.valueFn(t.mood).slice()),e&&(i.loop=e),i}valueAnimationSeq(t,e,n,o,s,i=null){t=this.valueFn(t),e=this.valueFn(e),s<n&&(s=n),s>o&&(s=o);let r=(e-t)/(o-n);return i&&(r*=i((s-n)/(o-n))),r*s+(t-r*n)}gaussianRandom(t,e,n=1,o=5){let s=0;for(let i=0;i<o;i++)s+=Math.random();return t+Math.pow(s/o,n)*(e-t)}sigmoidFactory(t){function e(o){return 1/(1+Math.exp(-t*o))-.5}var n=.5/e(1);return function(o){return n*e(2*Math.max(Math.min(o,1),0)-1)+.5}}convertRange(t,e,n){return(t-e[0])*(n[1]-n[0])/(e[1]-e[0])+n[0]}animate(t){if(!this.isRunning)return;let e;if(this.isAvatarOnly)e=t;else{if(requestAnimationFrame(this.animate.bind(this)),e=t-this.animTimeLast,e<this.animFrameDur)return;this.animTimeLast=t}e=e/this.animSlowdownRate,this.animClock+=e,this.maintainLockedPosition();let n,o,s,i,r=0;if(this.stats&&this.stats.begin(),this.isListening){for(this.listeningAnalyzer.getByteFrequencyData(this.volumeFrequencyData),n=2,s=10;n<s;n++)this.volumeFrequencyData[n]>r&&(r=this.volumeFrequencyData[n]);this.listeningVolume=(this.listeningVolume+r)/2,this.listeningActive?(this.listeningTimerTotal+=e,this.listeningVolume<this.listeningSilenceThresholdLevel?(this.listeningTimer+=e,this.listeningTimer>this.listeningSilenceThresholdMs&&(this.listeningOnchange&&this.listeningOnchange("stop",this.listeningTimer),this.listeningActive=!1,this.listeningTimer=0,this.listeningTimerTotal=0)):this.listeningTimer*=.5,this.listeningTimerTotal>this.listeningActiveDurationMax&&(this.listeningOnchange&&this.listeningOnchange("maxactive"),this.listeningTimerTotal=0)):(this.listeningTimerTotal+=e,this.listeningVolume>this.listeningActiveThresholdLevel?(this.listeningTimer+=e,this.listeningTimer>this.listeningActiveThresholdMs&&(this.listeningOnchange&&this.listeningOnchange("start"),this.listeningActive=!0,this.listeningTimer=0,this.listeningTimerTotal=0)):this.listeningTimer*=.5,this.listeningTimerTotal>this.listeningSilenceDurationMax&&(this.listeningOnchange&&this.listeningOnchange("maxsilence"),this.listeningTimerTotal=0))}if(this.isSpeaking)for(r=0,this.audioAnalyzerNode.getByteFrequencyData(this.volumeFrequencyData),n=2,s=10;n<s;n++)this.volumeFrequencyData[n]>r&&(r=this.volumeFrequencyData[n]);let c=null,l=null;const u=[];for(n=0,s=this.animQueue.length;n<s;n++){const a=this.animQueue[n];if(!(!a||!a.ts||!a.ts.length||this.animClock<a.ts[0])){for(o=a.ndx||0,i=a.ts.length;o<i&&!(this.animClock<a.ts[o]);o++)for(let[d,h]of Object.entries(a.vs))if(this.mtAvatar.hasOwnProperty(d)){if(h[o+1]===null)continue;const g=this.mtAvatar[d];if(h[o]===null&&(h[o]=g.value),o===i-1)g.newvalue=h[o];else{g.newvalue=h[o+1];const v=a.ts[o+1]-a.ts[o];let b=1;v>1e-4&&(b=(this.animClock-a.ts[o])/v),b<1&&(g.easing&&(b=g.easing(b)),g.newvalue=(1-b)*h[o]+b*g.newvalue),g.ref&&g.ref!==a.vs&&g.ref.hasOwnProperty(d)&&delete g.ref[d],g.ref=a.vs}if(r)switch(d){case"viseme_aa":case"viseme_E":case"viseme_I":case"viseme_O":case"viseme_U":g.newvalue*=1+r/255-.5}g.needsUpdate=!0}else d==="eyeContact"&&h[o]!==null&&c!==!1?c=!!h[o]:d==="headMove"&&h[o]!==null&&l!==!1?h[o]===0?l=!1:(Math.random()<h[o]&&(l=!0),h[o]=null):h[o]!==null&&(u.push({mt:d,val:h[o]}),h[o]=null);o===i?(a.hasOwnProperty("mood")&&this.setMood(a.mood),a.loop?(i=this.isSpeaking&&(a.template.name==="head"||a.template.name==="eyes")?4:1,this.animQueue[n]=this.animFactory(a.template,a.loop>0?a.loop-1:a.loop,1,1/i)):(this.animQueue.splice(n--,1),s--)):a.ndx=o-1}}for(let a=0,d=u.length;a<d;a++)switch(o=u[a].val,u[a].mt){case"speak":this.speakText(o);break;case"subtitles":this.onSubtitles&&typeof this.onSubtitles=="function"&&this.onSubtitles(o);break;case"pose":this.avatar&&this.avatar.body==="M"&&(o==="hip"||o==="side")&&this.poseTemplates.wide&&(o="wide"),this.poseName=o,this.setPoseFromTemplate(this.poseTemplates[this.poseName]);break;case"gesture":this.playGesture(...o);break;case"function":o&&typeof o=="function"&&o();break;case"moveto":Object.entries(o.props).forEach(h=>{h[1]?this.poseTarget.props[h[0]].copy(h[1]):this.poseTarget.props[h[0]].copy(this.getPoseTemplateProp(h[0])),this.poseTarget.props[h[0]].t=this.animClock,this.poseTarget.props[h[0]].d=h[1]&&h[1].d?h[1].d:h.duration||2e3});break;case"handLeft":this.ikSolve({iterations:20,root:"LeftShoulder",effector:"LeftHandMiddle1",links:[{link:"LeftHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5},{link:"LeftForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-.5,maxz:3},{link:"LeftArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},o.x?new f.Vector3(o.x,o.y,o.z):null,!0,o.d);break;case"handRight":this.ikSolve({iterations:20,root:"RightShoulder",effector:"RightHandMiddle1",links:[{link:"RightHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5,maxAngle:.1},{link:"RightForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-3,maxz:.5,maxAngle:.2},{link:"RightArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},o.x?new f.Vector3(o.x,o.y,o.z):null,!0,o.d);break}if((c||l)&&(_.setFromQuaternion(this.poseAvatar.props["Head.quaternion"]),_.x=Math.max(-.9,Math.min(.9,2*_.x-.5)),_.y=Math.max(-.9,Math.min(.9,-2.5*_.y)),c?(Object.assign(this.mtAvatar.eyesLookDown,{system:_.x<0?-_.x:0,needsUpdate:!0}),Object.assign(this.mtAvatar.eyesLookUp,{system:_.x<0?0:_.x,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookInLeft,{system:_.y<0?-_.y:0,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookOutLeft,{system:_.y<0?0:_.y,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookInRight,{system:_.y<0?0:_.y,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookOutRight,{system:_.y<0?-_.y:0,needsUpdate:!0}),l&&(n=-this.mtAvatar.bodyRotateY.value,o=this.gaussianRandom(-.2,.2),this.animQueue.push(this.animFactory({name:"headmove",dt:[[1e3,2e3],[1e3,2e3,1,2],[1e3,2e3],[1e3,2e3,1,2]],vs:{headRotateY:[n,n,0],headRotateX:[o,o,0],headRotateZ:[-n/4,-n/4,0]}})))):(n=this.mtAvatar.eyeLookInLeft.value-this.mtAvatar.eyeLookOutLeft.value,o=this.gaussianRandom(-.2,.2),this.animQueue.push(this.animFactory({name:"headmove",dt:[[1e3,2e3],[1e3,2e3,1,2],[1e3,2e3],[1e3,2e3,1,2]],vs:{headRotateY:[null,n,n,0],headRotateX:[null,o,o,0],headRotateZ:[null,-n/4,-n/4,0],eyeLookInLeft:[null,0],eyeLookOutLeft:[null,0],eyeLookInRight:[null,0],eyeLookOutRight:[null,0],eyeContact:[0]}})))),e>2*this.animFrameDur&&(e=2*this.animFrameDur),(this.viewName!=="full"||this.isAvatarOnly)&&(n=this.mtRandomized[Math.floor(Math.random()*this.mtRandomized.length)],o=this.mtAvatar[n],o.needsUpdate||Object.assign(o,{base:(this.mood.baseline[n]||0)+(1+r/255)*Math.random()/5,needsUpdate:!0})),this.updatePoseBase(this.animClock),this.mixer&&this.mixer.update(e/1e3*this.mixer.timeScale),this.updatePoseDelta(),this.applyShoulderAdjustmentToBones(),(this.isSpeaking||this.isListening)&&c?r>this.volumeMax?(this.volumeHeadBase=.05,Math.random()>.6&&(this.volumeHeadTarget=-.05-Math.random()/15),this.volumeMax=r):(this.volumeMax*=.92,this.volumeHeadTarget=this.volumeHeadBase-.9*(this.volumeHeadBase-this.volumeHeadTarget)):(this.volumeHeadTarget=0,this.volumeMax=0),n=this.volumeHeadTarget-this.volumeHeadCurrent,o=Math.abs(n),o>1e-4&&(i=o*(this.volumeHeadEasing(Math.min(1,this.volumeHeadVelocity*e/1e3/o)/2+.5)-.5),this.volumeHeadCurrent+=Math.sign(n)*Math.min(o,i)),Math.abs(this.volumeHeadCurrent)>1e-4&&(ie.setFromAxisAngle(vt,this.volumeHeadCurrent),this.objectNeck.quaternion.multiply(ie)),je.setFromObject(this.armature),this.objectLeftToeBase.getWorldPosition(Ie),Ie.sub(this.armature.position),this.objectRightToeBase.getWorldPosition(Le),Le.sub(this.armature.position),this.objectHips.position.y-=je.min.y/2,this.objectHips.position.x-=(Ie.x+Le.x)/4,this.objectHips.position.z-=(Ie.z+Le.z)/2,this.dynamicbones.update(e),this.fbxAnimationLoader&&this.fbxAnimationLoader.update(),this.opt.update&&this.opt.update(e),this.updateMorphTargets(e),this.isAvatarOnly)this.stats&&this.stats.end();else{if(this.cameraClock!==null&&this.cameraClock<1e3){this.cameraClock+=e,this.cameraClock>1e3&&(this.cameraClock=1e3);let a=new f.Spherical().setFromVector3(this.cameraStart),d=new f.Spherical().setFromVector3(this.cameraEnd);a.phi+=this.easing(this.cameraClock/1e3)*(d.phi-a.phi),a.theta+=this.easing(this.cameraClock/1e3)*(d.theta-a.theta),a.radius+=this.easing(this.cameraClock/1e3)*(d.radius-a.radius),a.makeSafe(),this.camera.position.setFromSpherical(a),this.controlsStart.x!==this.controlsEnd.x?this.controls.target.copy(this.controlsStart.lerp(this.controlsEnd,this.easing(this.cameraClock/1e3))):(a.setFromVector3(this.controlsStart),d.setFromVector3(this.controlsEnd),a.phi+=this.easing(this.cameraClock/1e3)*(d.phi-a.phi),a.theta+=this.easing(this.cameraClock/1e3)*(d.theta-a.theta),a.radius+=this.easing(this.cameraClock/1e3)*(d.radius-a.radius),a.makeSafe(),this.controls.target.setFromSpherical(a)),this.controls.update()}this.controls.autoRotate&&this.controls.update(),this.stats&&this.stats.end(),this.render()}}resetLips(){this.visemeNames.forEach(t=>{this.morphs.forEach(e=>{const n=e.morphTargetDictionary["viseme_"+t];n!==void 0&&(e.morphTargetInfluences[n]=0)})})}lipsyncGetProcessor(t,e="./"){if(!this.lipsync.hasOwnProperty(t)){const n=t.toLowerCase(),o="Lipsync"+t.charAt(0).toUpperCase()+t.slice(1);try{const s=Xe[n];s&&s[o]?this.lipsync[t]=new s[o]:console.warn(`Lip-sync module for ${t} not found. Available modules:`,Object.keys(Xe))}catch(s){console.warn(`Failed to load lip-sync module for ${t}:`,s)}}}lipsyncPreProcessText(t,e){return(this.lipsync[e]||Object.values(this.lipsync)[0]).preProcessText(t)}lipsyncWordsToVisemes(t,e){return(this.lipsync[e]||Object.values(this.lipsync)[0]).wordsToVisemes(t)}speakText(t,e=null,n=null,o=null){e=e||{};const s=/[!\.\?\n\p{Extended_Pictographic}]/ug,i=/[ ]/ug,r=/[\p{L}\p{N},\.\p{Quotation_Mark}!€\$\+\p{Dash_Punctuation}%&\?]/ug,c=/[\p{Extended_Pictographic}]/ug,l=e.lipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang;let u="",a="",d=0,h=[],g=[];const v=Array.from(this.segmenter.segment(t),b=>b.segment);for(let b=0;b<v.length;b++){const S=b===v.length-1,M=v[b].match(r);let p=v[b].match(s);const O=v[b].match(c),P=v[b].match(i);if(p&&!S&&!O&&v[b+1].match(s)&&(p=!1),n&&(u+=v[b]),M&&(!o||o.every(y=>b<y[0]||b>y[1]))&&(a+=v[b]),(P||p||S)&&(a.length&&(a=this.lipsyncPreProcessText(a,l),a.length&&h.push({mark:d,word:a})),u.length&&(g.push({mark:d,template:{name:"subtitles"},ts:[0],vs:{subtitles:[u]}}),u=""),a.length)){const y=this.lipsyncWordsToVisemes(a,l);if(y&&y.visemes&&y.visemes.length){const F=y.times[y.visemes.length-1]+y.durations[y.visemes.length-1];for(let x=0;x<y.visemes.length;x++)g.push({mark:d,template:{name:"viseme"},ts:[(y.times[x]-.6)/F,(y.times[x]+.5)/F,(y.times[x]+y.durations[x]+.5)/F],vs:{["viseme_"+y.visemes[x]]:[null,y.visemes[x]==="PP"||y.visemes[x]==="FF"?.9:.6,0]}})}a="",d++}if(p||S){if(h.length||S&&g.length){const y={anim:g};n&&(y.onSubtitles=n),h.length&&!e.avatarMute&&(y.text=h,e.avatarMood&&(y.mood=e.avatarMood),e.ttsLang&&(y.lang=e.ttsLang),e.ttsVoice&&(y.voice=e.ttsVoice),e.ttsRate&&(y.rate=e.ttsRate),e.ttsVoice&&(y.pitch=e.ttsPitch),e.ttsVolume&&(y.volume=e.ttsVolume)),this.speechQueue.push(y),h=[],a="",d=0,g=[]}if(O){let y=this.animEmojis[v[b]];y&&y.link&&(y=this.animEmojis[y.link]),y&&this.speechQueue.push({emoji:y})}this.speechQueue.push({break:100})}}this.speechQueue.push({break:1e3}),this.startSpeaking()}async speakEmoji(t){let e=this.animEmojis[t];e&&e.link&&(e=this.animEmojis[e.link]),e&&this.speechQueue.push({emoji:e}),this.startSpeaking()}async speakBreak(t){this.speechQueue.push({break:t}),this.startSpeaking()}async speakMarker(t){this.speechQueue.push({marker:t}),this.startSpeaking()}async playBackgroundAudio(t){let n=await(await fetch(t)).arrayBuffer();this.stopBackgroundAudio(),this.audioBackgroundSource=this.audioCtx.createBufferSource(),this.audioBackgroundSource.loop=!0,this.audioBackgroundSource.buffer=await this.audioCtx.decodeAudioData(n),this.audioBackgroundSource.playbackRate.value=1/this.animSlowdownRate,this.audioBackgroundSource.connect(this.audioBackgroundGainNode),this.audioBackgroundSource.start(0)}stopBackgroundAudio(){try{this.audioBackgroundSource.stop()}catch{}this.audioBackgroundSource.disconnect()}async setReverb(t=null){if(t){let n=await(await fetch(t)).arrayBuffer();this.audioReverbNode.buffer=await this.audioCtx.decodeAudioData(n)}else{const e=this.audioCtx.sampleRate,n=this.audioCtx.createBuffer(2,e,e);n.getChannelData(0)[0]=1,n.getChannelData(1)[0]=1,this.audioReverbNode.buffer=n}}setMixerGain(t,e=null,n=0){t!==null&&(this.audioSpeechGainNode.gain.cancelScheduledValues(this.audioCtx.currentTime),n?(this.audioSpeechGainNode.gain.setValueAtTime(Math.max(this.audioSpeechGainNode.gain.value,1e-4),this.audioCtx.currentTime),this.audioSpeechGainNode.gain.exponentialRampToValueAtTime(Math.max(t,1e-4),this.audioCtx.currentTime+n)):this.audioSpeechGainNode.gain.setValueAtTime(t,this.audioCtx.currentTime)),e!==null&&(this.audioBackgroundGainNode.gain.cancelScheduledValues(this.audioCtx.currentTime),n?(this.audioBackgroundGainNode.gain.setValueAtTime(Math.max(this.audioBackgroundGainNode.gain.value,1e-4),this.audioCtx.currentTime),this.audioBackgroundGainNode.gain.exponentialRampToValueAtTime(Math.max(e,1e-4),this.audioCtx.currentTime+n)):this.audioBackgroundGainNode.gain.setValueAtTime(e,this.audioCtx.currentTime))}speakAudio(t,e=null,n=null){e=e||{};const o=e.lipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang,s={};if(t.words){let i=[];for(let r=0;r<t.words.length;r++){const c=t.words[r],l=t.wtimes[r];let u=t.wdurations[r];if(c.length&&(n&&i.push({template:{name:"subtitles"},ts:[l],vs:{subtitles:[" "+c]}}),!t.visemes)){const a=this.lipsyncPreProcessText(c,o),d=this.lipsyncWordsToVisemes(a,o);if(d&&d.visemes&&d.visemes.length){const h=d.times[d.visemes.length-1]+d.durations[d.visemes.length-1],g=Math.min(u,Math.max(0,u-d.visemes.length*150));let v=.6+this.convertRange(g,[0,u],[0,.4]);if(u=Math.min(u,d.visemes.length*200),h>0)for(let b=0;b<d.visemes.length;b++){const S=l+d.times[b]/h*u,M=d.durations[b]/h*u;i.push({template:{name:"viseme"},ts:[S-Math.min(60,2*M/3),S+Math.min(25,M/2),S+M+Math.min(60,M/2)],vs:{["viseme_"+d.visemes[b]]:[null,d.visemes[b]==="PP"||d.visemes[b]==="FF"?.9:v,0]}})}}}}if(t.visemes)for(let r=0;r<t.visemes.length;r++){const c=t.visemes[r],l=t.vtimes[r],u=t.vdurations[r];i.push({template:{name:"viseme"},ts:[l-2*u/3,l+u/2,l+u+u/2],vs:{["viseme_"+c]:[null,c==="PP"||c==="FF"?.9:.6,0]}})}if(t.markers)for(let r=0;r<t.markers.length;r++){const c=t.markers[r],l=t.mtimes[r];i.push({template:{name:"markers"},ts:[l],vs:{function:[c]}})}i.length&&(s.anim=i)}if(t.audio&&(s.audio=t.audio),t.anim?.name){let i=this.animFactory(t.anim,!1,1,1,!0);s.anim?s.anim.push(i):s.anim=[i]}n&&(s.onSubtitles=n),e.isRaw&&(s.isRaw=!0),Object.keys(s).length&&(this.speechQueue.push(s),s.isRaw||this.speechQueue.push({break:300}),this.startSpeaking())}async playAudio(t=!1){if(!(!this.armature||this.isAudioPlaying&&!t))if(this.isAudioPlaying=!0,this.audioPlaylist.length){const e=this.audioPlaylist.shift();if(this.audioCtx.state==="suspended"||this.audioCtx.state==="interrupted"){const s=this.audioCtx.resume(),i=new Promise((r,c)=>setTimeout(()=>c("p2"),1e3));try{await Promise.race([s,i])}catch{console.log("Can't play audio. Web Audio API suspended. This is often due to calling some speak method before the first user action, which is typically prevented by the browser."),this.playAudio(!0);return}}let n;if(Array.isArray(e.audio)){let s=this.concatArrayBuffers(e.audio);n=this.pcmToAudioBuffer(s)}else n=e.audio;this.audioSpeechSource=this.audioCtx.createBufferSource(),this.audioSpeechSource.buffer=n,this.audioSpeechSource.playbackRate.value=1/this.animSlowdownRate,this.audioSpeechSource.connect(this.audioAnalyzerNode),this.audioSpeechSource.addEventListener("ended",()=>{this.audioSpeechSource.disconnect(),this.playAudio(!0)},{once:!0});let o=0;e.anim&&(e.isRaw||(o=Math.abs(Math.min(0,...e.anim.map(s=>Math.min(...s.ts))))),e.anim.forEach(s=>{for(let i=0;i<s.ts.length;i++)s.ts[i]=this.animClock+s.ts[i]+o;this.animQueue.push(s)})),this.audioSpeechSource.start(o/1e3)}else this.isAudioPlaying=!1,this.startSpeaking(!0)}async synthesizeWithBrowserTTS(t){return new Promise((e,n)=>{const o=t.text.map(p=>p.word).join(" "),s=new SpeechSynthesisUtterance(o),i=t.lang||this.avatar.ttsLang||this.opt.ttsLang||"en-US",r=(t.rate||this.avatar.ttsRate||this.opt.ttsRate||1)+this.mood.speech.deltaRate,c=(t.pitch||this.avatar.ttsPitch||this.opt.ttsPitch||1)+this.mood.speech.deltaPitch,l=(t.volume||this.avatar.ttsVolume||this.opt.ttsVolume||1)+this.mood.speech.deltaVolume;s.lang=i,s.rate=Math.max(.1,Math.min(10,r)),s.pitch=Math.max(0,Math.min(2,c)),s.volume=Math.max(0,Math.min(1,l));const u=speechSynthesis.getVoices(),a=t.voice||this.avatar.ttsVoice||this.opt.ttsVoice;if(a&&u.length>0){const p=u.find(O=>O.name.includes(a)||O.lang===i);p&&(s.voice=p)}const d=o.length*100/s.rate,h=this.audioCtx.createBuffer(1,this.audioCtx.sampleRate*(d/1e3),this.audioCtx.sampleRate),g=this.avatar.lipsyncLang||this.opt.lipsyncLang||"en",v=this.lipsyncPreProcessText(o,g),b=this.lipsyncWordsToVisemes(v,g),S=[];if(b&&b.visemes&&b.visemes.length>0){const p=b.times[b.visemes.length-1]+b.durations[b.visemes.length-1];for(let O=0;O<b.visemes.length;O++){const P=b.visemes[O],y=b.times[O]/p,F=b.durations[O]/p,x=y*d,k=F*d;S.push({template:{name:"viseme"},ts:[x-Math.min(60,2*k/3),x+Math.min(25,k/2),x+k+Math.min(60,k/2)],vs:{["viseme_"+P]:[null,P==="PP"||P==="FF"?.9:.6,0]}})}}const M=[...t.anim,...S];this.audioPlaylist.push({anim:M,audio:h}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio(),s.onend=()=>{e()},s.onerror=p=>{console.error("Speech synthesis error:",p.error),n(p.error)},speechSynthesis.speak(s)})}async synthesizeWithElevenLabsTTS(t){const e=t.text.map(d=>d.word).join(" "),n=t.voice||this.avatar.ttsVoice||this.opt.ttsVoice||"21m00Tcm4TlvDq8ikWAM",o={text:e,model_id:"eleven_monolingual_v1",voice_settings:{stability:.5,similarity_boost:.5,style:0,use_speaker_boost:!0}},s=await fetch(`${this.opt.ttsEndpoint}/${n}`,{method:"POST",headers:{Accept:"audio/mpeg","Content-Type":"application/json","xi-api-key":this.opt.ttsApikey},body:JSON.stringify(o)});if(!s.ok)throw new Error(`ElevenLabs TTS error: ${s.status} ${s.statusText}`);const i=await s.arrayBuffer(),r=await this.audioCtx.decodeAudioData(i),c=this.avatar.lipsyncLang||this.opt.lipsyncLang||"en";let l;try{console.log("Lip-sync modules available:",{hasLipsync:!!this.lipsync,lipsyncKeys:this.lipsync?Object.keys(this.lipsync):[],lipsyncLang:c});const d=this.lipsyncPreProcessText(e,c),h=this.lipsyncWordsToVisemes(d,c);if(console.log("Lip-sync data:",{processedText:d,lipsyncData:h,hasVisemes:h&&h.visemes&&h.visemes.length>0}),h&&h.visemes&&h.visemes.length>0)l={visemes:h.visemes.map((g,v)=>({viseme:g,startTime:v*r.duration/h.visemes.length,endTime:(v+1)*r.duration/h.visemes.length,duration:r.duration/h.visemes.length,intensity:.7})),words:[],duration:r.duration,features:{onsets:[],boundaries:[]}};else throw new Error("No visemes generated from text")}catch(d){console.error("Text-based lip-sync failed, using fallback:",d);const h=e.toLowerCase().split(/\s+/),g=[];for(const v of h)for(const b of v){let S="aa";"aeiou".includes(b)?S="aa":"bp".includes(b)?S="PP":"fv".includes(b)?S="FF":"st".includes(b)?S="SS":"dln".includes(b)?S="DD":"kg".includes(b)?S="kk":"rw".includes(b)&&(S="RR"),g.push(S)}l={visemes:g.map((v,b)=>({viseme:v,startTime:b*r.duration/g.length,endTime:(b+1)*r.duration/g.length,duration:r.duration/g.length,intensity:.6})),words:[],duration:r.duration,features:{onsets:[],boundaries:[]}}}const u=[];if(l.visemes&&l.visemes.length>0)for(let d=0;d<l.visemes.length;d++){const h=l.visemes[d],g=h.startTime*1e3,v=h.duration*1e3,b=h.intensity;u.push({template:{name:"viseme"},ts:[g-Math.min(60,2*v/3),g+Math.min(25,v/2),g+v+Math.min(60,v/2)],vs:{["viseme_"+h.viseme]:[null,b,0]}})}else console.warn("ElevenLabs: No visemes available for lip-sync animation");const a=[...t.anim,...u];this.audioPlaylist.push({anim:a,audio:r}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio()}async synthesizeWithDeepgramTTS(t){const e=t.text.map(d=>d.word).join(" "),n=t.voice||this.avatar.ttsVoice||this.opt.ttsVoice||"aura-2-thalia-en",o=`${this.opt.ttsEndpoint}?model=${n}`,s=await fetch(o,{method:"POST",headers:{Authorization:`Token ${this.opt.ttsApikey}`,"Content-Type":"text/plain",Accept:"audio/mpeg"},body:e});if(!s.ok)throw new Error(`Deepgram TTS error: ${s.status} ${s.statusText}`);const i=await s.arrayBuffer(),r=await this.audioCtx.decodeAudioData(i),c=this.avatar.lipsyncLang||this.opt.lipsyncLang||"en";let l;try{console.log("Lip-sync modules available:",{hasLipsync:!!this.lipsync,lipsyncKeys:this.lipsync?Object.keys(this.lipsync):[],lipsyncLang:c});const d=this.lipsyncPreProcessText(e,c),h=this.lipsyncWordsToVisemes(d,c);if(console.log("Lip-sync data:",{processedText:d,lipsyncData:h,hasVisemes:h&&h.visemes&&h.visemes.length>0}),h&&h.visemes&&h.visemes.length>0)l={visemes:h.visemes.map((g,v)=>({viseme:g,startTime:v*r.duration/h.visemes.length,endTime:(v+1)*r.duration/h.visemes.length,duration:r.duration/h.visemes.length,intensity:.7})),words:[],duration:r.duration,features:{onsets:[],boundaries:[]}};else throw new Error("No visemes generated from text")}catch(d){console.error("Text-based lip-sync failed, using fallback:",d);const h=e.toLowerCase().split(/\s+/),g=[];for(const v of h)for(const b of v){let S="aa";"aeiou".includes(b)?S="aa":"bp".includes(b)?S="PP":"fv".includes(b)?S="FF":"st".includes(b)?S="SS":"dln".includes(b)?S="DD":"kg".includes(b)?S="kk":"rw".includes(b)&&(S="RR"),g.push(S)}l={visemes:g.map((v,b)=>({viseme:v,startTime:b*r.duration/g.length,endTime:(b+1)*r.duration/g.length,duration:r.duration/g.length,intensity:.6})),words:[],duration:r.duration,features:{onsets:[],boundaries:[]}}}const u=[];if(l.visemes&&l.visemes.length>0)for(let d=0;d<l.visemes.length;d++){const h=l.visemes[d],g=h.startTime*1e3,v=h.duration*1e3,b=h.intensity;u.push({template:{name:"viseme"},ts:[g-Math.min(60,2*v/3),g+Math.min(25,v/2),g+v+Math.min(60,v/2)],vs:{["viseme_"+h.viseme]:[null,b,0]}})}else console.warn("Deepgram: No visemes available for lip-sync animation");const a=[...t.anim,...u];this.audioPlaylist.push({anim:a,audio:r}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio()}async synthesizeWithAzureTTS(t){const e=t.text.map(a=>a.word).join(" "),o=`
2
2
  <speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="en-US">
3
3
  <voice name="${t.voice||this.avatar.ttsVoice||this.opt.ttsVoice||"en-US-AriaNeural"}">
4
4
  ${e}
5
5
  </voice>
6
6
  </speak>
7
- `,s=await fetch(this.opt.ttsEndpoint,{method:"POST",headers:{"Ocp-Apim-Subscription-Key":this.opt.ttsApikey,"Content-Type":"application/ssml+xml","X-Microsoft-OutputFormat":"audio-16khz-128kbitrate-mono-mp3"},body:i});if(!s.ok)throw new Error(`Azure TTS error: ${s.status} ${s.statusText}`);const o=await s.arrayBuffer(),r=await this.audioCtx.decodeAudioData(o);console.log("Analyzing audio for precise lip-sync...");const u=await this.audioAnalyzer.analyzeAudio(r,e);console.log("Azure TTS Audio Analysis:",{text:e,audioDuration:r.duration,visemeCount:u.visemes.length,wordCount:u.words.length,features:{onsets:u.features.onsets.length,boundaries:u.features.phonemeBoundaries.length}});const a=[];for(let l=0;l<u.visemes.length;l++){const d=u.visemes[l],h=d.startTime*1e3,p=d.duration*1e3,v=d.intensity;a.push({template:{name:"viseme"},ts:[h-Math.min(60,2*p/3),h+Math.min(25,p/2),h+p+Math.min(60,p/2)],vs:{["viseme_"+d.viseme]:[null,v,0]}})}const c=[...t.anim,...a];this.audioPlaylist.push({anim:c,audio:r}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio()}async synthesizeWithExternalTTS(t){let e="<speak>";t.text.forEach((o,r)=>{r>0&&(e+=" <mark name='"+o.mark+"'/>"),e+=o.word.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;").replace(new RegExp("^\\p{Dash_Punctuation}$","ug"),'<break time="750ms"/>')}),e+="</speak>";const n={method:"POST",headers:{"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify({input:{ssml:e},voice:{languageCode:t.lang||this.avatar.ttsLang||this.opt.ttsLang,name:t.voice||this.avatar.ttsVoice||this.opt.ttsVoice},audioConfig:{audioEncoding:this.ttsAudioEncoding,speakingRate:(t.rate||this.avatar.ttsRate||this.opt.ttsRate)+this.mood.speech.deltaRate,pitch:(t.pitch||this.avatar.ttsPitch||this.opt.ttsPitch)+this.mood.speech.deltaPitch,volumeGainDb:(t.volume||this.avatar.ttsVolume||this.opt.ttsVolume)+this.mood.speech.deltaVolume},enableTimePointing:[1]})};this.opt.jwtGet&&typeof this.opt.jwtGet=="function"&&(n.headers.Authorization="Bearer "+await this.opt.jwtGet());const i=await fetch(this.opt.ttsEndpoint+(this.opt.ttsApikey?"?key="+this.opt.ttsApikey:""),n),s=await i.json();if(i.status===200&&s&&s.audioContent){const o=this.b64ToArrayBuffer(s.audioContent),r=await this.audioCtx.decodeAudioData(o);this.speakWithHands();const u=[0];let a=0;t.text.forEach((d,h)=>{if(h>0){let p=u[u.length-1];s.timepoints[a]&&(p=s.timepoints[a].timeSeconds*1e3,s.timepoints[a].markName===""+d.mark&&a++),u.push(p)}});const c=[{mark:0,time:0}];u.forEach((d,h)=>{if(h>0){let p=d-u[h-1];c[h-1].duration=p,c.push({mark:h,time:d})}});let l=1e3*r.duration;l>this.opt.ttsTrimEnd&&(l=l-this.opt.ttsTrimEnd),c[c.length-1].duration=l-c[c.length-1].time,t.anim.forEach(d=>{const h=c[d.mark];if(h)for(let p=0;p<d.ts.length;p++)d.ts[p]=h.time+d.ts[p]*h.duration+this.opt.ttsTrimStart}),this.audioPlaylist.push({anim:t.anim,audio:r}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio()}else this.startSpeaking(!0)}async startSpeaking(t=!1){if(!(!this.armature||this.isSpeaking&&!t))if(this.stateName="speaking",this.isSpeaking=!0,this.speechQueue.length){let e=this.speechQueue.shift();if(e.emoji){this.lookAtCamera(500);let n=e.emoji.dt.reduce((i,s)=>i+s,0);this.animQueue.push(this.animFactory(e.emoji)),setTimeout(this.startSpeaking.bind(this),n,!0)}else if(e.break)setTimeout(this.startSpeaking.bind(this),e.break,!0);else if(e.audio)e.isRaw||(this.lookAtCamera(500),this.speakWithHands(),this.resetLips()),this.audioPlaylist.push({anim:e.anim,audio:e.audio,isRaw:e.isRaw}),this.onSubtitles=e.onSubtitles||null,e.mood&&this.setMood(e.mood),this.playAudio();else if(e.text){this.lookAtCamera(500);try{!this.opt.ttsEndpoint||this.opt.ttsEndpoint===""?await this.synthesizeWithBrowserTTS(e):this.opt.ttsService==="elevenlabs"?await this.synthesizeWithElevenLabsTTS(e):this.opt.ttsService==="deepgram"?await this.synthesizeWithDeepgramTTS(e):this.opt.ttsService==="azure"?await this.synthesizeWithAzureTTS(e):await this.synthesizeWithExternalTTS(e)}catch(n){console.error("Error:",n),this.startSpeaking(!0)}}else e.anim?(this.onSubtitles=e.onSubtitles||null,this.resetLips(),e.mood&&this.setMood(e.mood),e.anim.forEach((n,i)=>{for(let s=0;s<n.ts.length;s++)n.ts[s]=this.animClock+10*i;this.animQueue.push(n)}),setTimeout(this.startSpeaking.bind(this),10*e.anim.length,!0)):e.marker?(typeof e.marker=="function"&&e.marker(),this.startSpeaking(!0)):this.startSpeaking(!0)}else this.stateName="idle",this.isSpeaking=!1}pauseSpeaking(){try{this.audioSpeechSource.stop()}catch{}this.audioPlaylist.length=0,this.stateName="idle",this.isSpeaking=!1,this.isAudioPlaying=!1,this.animQueue=this.animQueue.filter(t=>t.template.name!=="viseme"&&t.template.name!=="subtitles"&&t.template.name!=="blendshapes"),this.armature&&(this.resetLips(),this.render())}stopSpeaking(){try{this.audioSpeechSource.stop()}catch{}this.audioPlaylist.length=0,this.speechQueue.length=0,this.animQueue=this.animQueue.filter(t=>t.template.name!=="viseme"&&t.template.name!=="subtitles"&&t.template.name!=="blendshapes"),this.stateName="idle",this.isSpeaking=!1,this.isAudioPlaying=!1,this.armature&&(this.resetLips(),this.render())}async streamStart(t={},e=null,n=null,i=null,s=null){if(this.stopSpeaking(),this.isStreaming=!0,t.waitForAudioChunks!==void 0&&(this.streamWaitForAudioChunks=t.waitForAudioChunks),this.streamWaitForAudioChunks||(this.streamAudioStartTime=this.animClock),this.streamLipsyncQueue=[],this.streamLipsyncType=t.lipsyncType||this.streamLipsyncType||"visemes",this.streamLipsyncLang=t.lipsyncLang||this.streamLipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang,this.onAudioStart=e,this.onAudioEnd=n,this.onMetrics=s,t.sampleRate!==void 0){const r=t.sampleRate;typeof r=="number"&&r>=8e3&&r<=96e3?r!==this.audioCtx.sampleRate&&this.initAudioGraph(r):console.warn("Invalid sampleRate provided. It must be a number between 8000 and 96000 Hz.")}if(t.gain!==void 0&&(this.audioStreamGainNode.gain.value=t.gain),!this.streamWorkletNode||!this.streamWorkletNode.port||this.streamWorkletNode.numberOfOutputs===0||this.streamWorkletNode.context!==this.audioCtx){if(this.streamWorkletNode)try{this.streamWorkletNode.disconnect(),this.streamWorkletNode=null}catch{}if(!this.workletLoaded)try{const r=this.audioCtx.audioWorklet.addModule(bt.href),u=new Promise((a,c)=>setTimeout(()=>c(new Error("Worklet loading timed out")),5e3));await Promise.race([r,u]),this.workletLoaded=!0}catch(r){throw console.error("Failed to load audio worklet:",r),new Error("Failed to initialize streaming speech")}this.streamWorkletNode=new AudioWorkletNode(this.audioCtx,"playback-worklet",{processorOptions:{sampleRate:this.audioCtx.sampleRate,metrics:t.metrics||{enabled:!1}}}),this.streamWorkletNode.connect(this.audioStreamGainNode),this.streamWorkletNode.connect(this.audioAnalyzerNode),this.streamWorkletNode.port.onmessage=r=>{if(r.data.type==="playback-started"&&(this.isSpeaking=!0,this.stateName="speaking",this.streamWaitForAudioChunks&&(this.streamAudioStartTime=this.animClock),this._processStreamLipsyncQueue(),this.speakWithHands(),this.onAudioStart))try{this.onAudioStart?.()}catch(u){console.error(u)}if(r.data.type==="playback-ended"&&(this._streamPause(),this.onAudioEnd))try{this.onAudioEnd()}catch{}if(this.onMetrics&&r.data.type==="metrics")try{this.onMetrics(r.data)}catch{}}}if(t.metrics)try{this.streamWorkletNode.port.postMessage({type:"config-metrics",data:t.metrics})}catch{}if(this.resetLips(),this.lookAtCamera(500),t.mood&&this.setMood(t.mood),this.onSubtitles=i||null,this.audioCtx.state==="suspended"||this.audioCtx.state==="interrupted"){const r=this.audioCtx.resume(),u=new Promise((a,c)=>setTimeout(()=>c("p2"),1e3));try{await Promise.race([r,u])}catch{console.warn("Can't play audio. Web Audio API suspended. This is often due to calling some speak method before the first user action, which is typically prevented by the browser.");return}}}streamNotifyEnd(){!this.isStreaming||!this.streamWorkletNode||this.streamWorkletNode.port.postMessage({type:"no-more-data"})}streamInterrupt(){if(!this.isStreaming)return;const t=this.isSpeaking;if(this.streamWorkletNode)try{this.streamWorkletNode.port.postMessage({type:"stop"})}catch{}if(this._streamPause(!0),t&&this.onAudioEnd)try{this.onAudioEnd()}catch{}}streamStop(){if(this.isStreaming){if(this.streamInterrupt(),this.streamWorkletNode){try{this.streamWorkletNode.disconnect()}catch{}this.streamWorkletNode=null}this.isStreaming=!1}}_streamPause(t=!1){this.isSpeaking=!1,this.stateName="idle",t&&(this.streamWaitForAudioChunks&&(this.streamAudioStartTime=null),this.streamLipsyncQueue=[],this.animQueue=this.animQueue.filter(e=>e.template.name!=="viseme"&&e.template.name!=="subtitles"&&e.template.name!=="blendshapes"),this.armature&&(this.resetLips(),this.render()))}_processStreamLipsyncQueue(){if(this.isStreaming)for(;this.streamLipsyncQueue.length>0;){const t=this.streamLipsyncQueue.shift();this._processLipsyncData(t,this.streamAudioStartTime)}}_processLipsyncData(t,e){if(this.isStreaming){if(t.visemes&&this.streamLipsyncType=="visemes")for(let n=0;n<t.visemes.length;n++){const i=t.visemes[n],s=e+t.vtimes[n],o=t.vdurations[n],r={template:{name:"viseme"},ts:[s-2*o/3,s+o/2,s+o+o/2],vs:{["viseme_"+i]:[null,i==="PP"||i==="FF"?.9:.6,0]}};this.animQueue.push(r)}if(t.words&&(this.onSubtitles||this.streamLipsyncType=="words"))for(let n=0;n<t.words.length;n++){const i=t.words[n],s=t.wtimes[n];let o=t.wdurations[n];if(i.length&&(this.onSubtitles&&this.animQueue.push({template:{name:"subtitles"},ts:[e+s],vs:{subtitles:[" "+i]}}),this.streamLipsyncType=="words")){const r=this.streamLipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang,u=this.lipsyncPreProcessText(i,r),a=this.lipsyncWordsToVisemes(u,r);if(a&&a.visemes&&a.visemes.length){const c=a.times[a.visemes.length-1]+a.durations[a.visemes.length-1],l=Math.min(o,Math.max(0,o-a.visemes.length*150));let d=.6+this.convertRange(l,[0,o],[0,.4]);if(o=Math.min(o,a.visemes.length*200),c>0)for(let h=0;h<a.visemes.length;h++){const p=e+s+a.times[h]/c*o,v=a.durations[h]/c*o;this.animQueue.push({template:{name:"viseme"},ts:[p-Math.min(60,2*v/3),p+Math.min(25,v/2),p+v+Math.min(60,v/2)],vs:{["viseme_"+a.visemes[h]]:[null,a.visemes[h]==="PP"||a.visemes[h]==="FF"?.9:d,0]}})}}}}if(t.anims&&this.streamLipsyncType=="blendshapes")for(let n=0;n<t.anims.length;n++){let i=t.anims[n];i.delay+=e;let s=this.animFactory(i,!1,1,1,!0);this.animQueue.push(s)}}}streamAudio(t){if(!(!this.isStreaming||!this.streamWorkletNode)){if(this.isSpeaking||(this.streamLipsyncQueue=[],this.streamAudioStartTime=null),this.isSpeaking=!0,this.stateName="speaking",t.audio!==void 0){const e={type:"audioData",data:null};if(t.audio instanceof ArrayBuffer)e.data=t.audio,this.streamWorkletNode.port.postMessage(e,[e.data]);else if(t.audio instanceof Int16Array||t.audio instanceof Uint8Array){const n=t.audio.buffer.slice(t.audio.byteOffset,t.audio.byteOffset+t.audio.byteLength);e.data=n,this.streamWorkletNode.port.postMessage(e,[e.data])}else if(t.audio instanceof Float32Array){const n=new Int16Array(t.audio.length);for(let i=0;i<t.audio.length;i++){let s=Math.max(-1,Math.min(1,t.audio[i]));n[i]=s<0?s*32768:s*32767}e.data=n.buffer,this.streamWorkletNode.port.postMessage(e,[e.data])}else console.error("r.audio is not a supported type. Must be ArrayBuffer, Int16Array, Uint8Array, or Float32Array:",t.audio)}if(t.visemes||t.anims||t.words){if(this.streamWaitForAudioChunks&&!this.streamAudioStartTime){this.streamLipsyncQueue.length>=200&&this.streamLipsyncQueue.shift(),this.streamLipsyncQueue.push(t);return}else!this.streamWaitForAudioChunks&&!this.streamAudioStartTime&&(this.streamAudioStartTime=this.animClock);this._processLipsyncData(t,this.streamAudioStartTime)}}}makeEyeContact(t){this.animQueue.push(this.animFactory({name:"eyecontact",dt:[0,t],vs:{eyeContact:[1]}}))}lookAhead(t){if(t){let e=(Math.random()-.5)/4,n=(Math.random()-.5)/4,i=this.animQueue.findIndex(o=>o.template.name==="lookat");i!==-1&&this.animQueue.splice(i,1);const s={name:"lookat",dt:[750,t],vs:{bodyRotateX:[e],bodyRotateY:[n],eyesRotateX:[-3*e+.1],eyesRotateY:[-5*n],browInnerUp:[[0,.7]],mouthLeft:[[0,.7]],mouthRight:[[0,.7]],eyeContact:[0],headMove:[0]}};this.animQueue.push(this.animFactory(s))}}lookAtCamera(t){let e;if(this.speakTo&&(e=new x.Vector3,this.speakTo.objectLeftEye?.isObject3D?(this.speakTo.armature.objectHead,this.speakTo.objectLeftEye.updateMatrixWorld(!0),this.speakTo.objectRightEye.updateMatrixWorld(!0),Ae.setFromMatrixPosition(this.speakTo.objectLeftEye.matrixWorld),Le.setFromMatrixPosition(this.speakTo.objectRightEye.matrixWorld),e.addVectors(Ae,Le).divideScalar(2)):this.speakTo.isObject3D?this.speakTo.getWorldPosition(e):this.speakTo.isVector3?e.set(this.speakTo):this.speakTo.x&&this.speakTo.y&&this.speakTo.z&&e.set(this.speakTo.x,this.speakTo.y,this.speakTo.z)),!e){if(this.avatar.hasOwnProperty("avatarIgnoreCamera")){if(this.avatar.avatarIgnoreCamera){this.lookAhead(t);return}}else if(this.opt.avatarIgnoreCamera){this.lookAhead(t);return}this.lookAt(null,null,t);return}this.objectLeftEye.updateMatrixWorld(!0),this.objectRightEye.updateMatrixWorld(!0),Ae.setFromMatrixPosition(this.objectLeftEye.matrixWorld),Le.setFromMatrixPosition(this.objectRightEye.matrixWorld),Ae.add(Le).divideScalar(2),ie.copy(this.armature.quaternion),ie.multiply(this.poseTarget.props["Hips.quaternion"]),ie.multiply(this.poseTarget.props["Spine.quaternion"]),ie.multiply(this.poseTarget.props["Spine1.quaternion"]),ie.multiply(this.poseTarget.props["Spine2.quaternion"]),ie.multiply(this.poseTarget.props["Neck.quaternion"]),ie.multiply(this.poseTarget.props["Head.quaternion"]);const n=new x.Vector3().subVectors(e,Ae).normalize(),i=Math.atan2(n.x,n.z),s=Math.asin(-n.y);K.set(s,i,0,"YXZ");const r=new x.Quaternion().setFromEuler(K),u=new x.Quaternion().copy(r).multiply(ie.clone().invert());K.setFromQuaternion(u,"YXZ");let a=K.x/(40/24)+.2,c=K.y/(9/4),l=Math.min(.6,Math.max(-.3,a)),d=Math.min(.8,Math.max(-.8,c)),h=(Math.random()-.5)/4,p=(Math.random()-.5)/4;if(t){let v=this.animQueue.findIndex(w=>w.template.name==="lookat");v!==-1&&this.animQueue.splice(v,1);const y={name:"lookat",dt:[750,t],vs:{bodyRotateX:[l+h],bodyRotateY:[d+p],eyesRotateX:[-3*h+.1],eyesRotateY:[-5*p],browInnerUp:[[0,.7]],mouthLeft:[[0,.7]],mouthRight:[[0,.7]],eyeContact:[0],headMove:[0]}};this.animQueue.push(this.animFactory(y))}}lookAt(t,e,n){if(!this.camera)return;const i=this.nodeAvatar.getBoundingClientRect();this.objectLeftEye.updateMatrixWorld(!0),this.objectRightEye.updateMatrixWorld(!0);const s=new x.Vector3().setFromMatrixPosition(this.objectLeftEye.matrixWorld),o=new x.Vector3().setFromMatrixPosition(this.objectRightEye.matrixWorld),r=new x.Vector3().addVectors(s,o).divideScalar(2);r.project(this.camera);let u=(r.x+1)/2*i.width+i.left,a=-(r.y-1)/2*i.height+i.top;t===null&&(t=u),e===null&&(e=a),ie.copy(this.armature.quaternion),ie.multiply(this.poseTarget.props["Hips.quaternion"]),ie.multiply(this.poseTarget.props["Spine.quaternion"]),ie.multiply(this.poseTarget.props["Spine1.quaternion"]),ie.multiply(this.poseTarget.props["Spine2.quaternion"]),ie.multiply(this.poseTarget.props["Neck.quaternion"]),ie.multiply(this.poseTarget.props["Head.quaternion"]),K.setFromQuaternion(ie);let c=K.x/(40/24),l=K.y/(9/4),d=Math.min(.4,Math.max(-.4,this.camera.rotation.x)),h=Math.min(.4,Math.max(-.4,this.camera.rotation.y)),p=Math.max(window.innerWidth-u,u),v=Math.max(window.innerHeight-a,a),y=this.convertRange(e,[a-v,a+v],[-.3,.6])-c+d,w=this.convertRange(t,[u-p,u+p],[-.8,.8])-l+h;y=Math.min(.6,Math.max(-.3,y)),w=Math.min(.8,Math.max(-.8,w));let M=(Math.random()-.5)/4,g=(Math.random()-.5)/4;if(n){let U=this.animQueue.findIndex(L=>L.template.name==="lookat");U!==-1&&this.animQueue.splice(U,1);const E={name:"lookat",dt:[750,n],vs:{bodyRotateX:[y+M],bodyRotateY:[w+g],eyesRotateX:[-3*M+.1],eyesRotateY:[-5*g],browInnerUp:[[0,.7]],mouthLeft:[[0,.7]],mouthRight:[[0,.7]],eyeContact:[0],headMove:[0]}};this.animQueue.push(this.animFactory(E))}}touchAt(t,e){if(!this.camera)return;const n=this.nodeAvatar.getBoundingClientRect(),i=new x.Vector2((t-n.left)/n.width*2-1,-((e-n.top)/n.height)*2+1),s=new x.Raycaster;s.setFromCamera(i,this.camera);const o=s.intersectObject(this.armature);if(o.length>0){const r=o[0].point,u=new x.Vector3,a=new x.Vector3;this.objectLeftArm.getWorldPosition(u),this.objectRightArm.getWorldPosition(a);const c=u.distanceToSquared(r),l=a.distanceToSquared(r);c<l?(this.ikSolve({iterations:20,root:"LeftShoulder",effector:"LeftHandMiddle1",links:[{link:"LeftHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5,maxAngle:.1},{link:"LeftForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-.5,maxz:3,maxAngle:.2},{link:"LeftArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},r,!1,1e3),this.setValue("handFistLeft",0)):(this.ikSolve({iterations:20,root:"RightShoulder",effector:"RightHandMiddle1",links:[{link:"RightHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5,maxAngle:.1},{link:"RightForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-3,maxz:.5,maxAngle:.2},{link:"RightArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},r,!1,1e3),this.setValue("handFistRight",0))}else["LeftArm","LeftForeArm","LeftHand","RightArm","RightForeArm","RightHand"].forEach(r=>{let u=r+".quaternion";this.poseTarget.props[u].copy(this.getPoseTemplateProp(u)),this.poseTarget.props[u].t=this.animClock,this.poseTarget.props[u].d=1e3});return o.length>0}speakWithHands(t=0,e=.5){if(this.mixer||this.gesture||!this.poseTarget.template.standing||this.poseTarget.template.bend||Math.random()>e)return;this.ikSolve({root:"LeftShoulder",effector:"LeftHandMiddle1",links:[{link:"LeftHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5},{link:"LeftForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-.5,maxz:3},{link:"LeftArm",minx:-1.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-1,maxz:3}]},new x.Vector3(this.gaussianRandom(0,.5),this.gaussianRandom(-.8,-.2),this.gaussianRandom(0,.5)),!0),this.ikSolve({root:"RightShoulder",effector:"RightHandMiddle1",links:[{link:"RightHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5},{link:"RightForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-3,maxz:.5},{link:"RightArm"}]},new x.Vector3(this.gaussianRandom(-.5,0),this.gaussianRandom(-.8,-.2),this.gaussianRandom(0,.5)),!0);const n=[],i=[];n.push(100+Math.round(Math.random()*500)),i.push({duration:1e3,props:{"LeftHand.quaternion":new x.Quaternion().setFromEuler(new x.Euler(0,-1-Math.random(),0)),"RightHand.quaternion":new x.Quaternion().setFromEuler(new x.Euler(0,1+Math.random(),0))}}),["LeftArm","LeftForeArm","RightArm","RightForeArm"].forEach(o=>{i[0].props[o+".quaternion"]=this.ikMesh.getObjectByName(o).quaternion.clone()}),n.push(1e3+Math.round(Math.random()*500)),i.push({duration:2e3,props:{}}),["LeftArm","LeftForeArm","RightArm","RightForeArm","LeftHand","RightHand"].forEach(o=>{i[1].props[o+".quaternion"]=null});const s=this.animFactory({name:"talkinghands",delay:t,dt:n,vs:{moveto:i}});this.animQueue.push(s)}getSlowdownRate(t){return this.animSlowdownRate}setSlowdownRate(t){this.animSlowdownRate=t,this.audioSpeechSource.playbackRate.value=1/this.animSlowdownRate,this.audioBackgroundSource.playbackRate.value=1/this.animSlowdownRate}getAutoRotateSpeed(t){return this.controls.autoRotateSpeed}setAutoRotateSpeed(t){this.controls.autoRotateSpeed=t,this.controls.autoRotate=t>0}start(){this.armature&&this.isRunning===!1&&(this.audioCtx.resume(),this.animTimeLast=performance.now(),this.isRunning=!0,this.isAvatarOnly||requestAnimationFrame(this.animate.bind(this)))}stop(){this.isRunning=!1,this.audioCtx.suspend()}startListening(t,e={},n=null){this.listeningAnalyzer=t,this.listeningAnalyzer.fftSize=256,this.listeningAnalyzer.smoothingTimeConstant=.1,this.listeningAnalyzer.minDecibels=-70,this.listeningAnalyzer.maxDecibels=-10,this.listeningOnchange=n&&typeof n=="function"?n:null,this.listeningSilenceThresholdLevel=e?.hasOwnProperty("listeningSilenceThresholdLevel")?e.listeningSilenceThresholdLevel:this.opt.listeningSilenceThresholdLevel,this.listeningSilenceThresholdMs=e?.hasOwnProperty("listeningSilenceThresholdMs")?e.listeningSilenceThresholdMs:this.opt.listeningSilenceThresholdMs,this.listeningSilenceDurationMax=e?.hasOwnProperty("listeningSilenceDurationMax")?e.listeningSilenceDurationMax:this.opt.listeningSilenceDurationMax,this.listeningActiveThresholdLevel=e?.hasOwnProperty("listeningActiveThresholdLevel")?e.listeningActiveThresholdLevel:this.opt.listeningActiveThresholdLevel,this.listeningActiveThresholdMs=e?.hasOwnProperty("listeningActiveThresholdMs")?e.listeningActiveThresholdMs:this.opt.listeningActiveThresholdMs,this.listeningActiveDurationMax=e?.hasOwnProperty("listeningActiveDurationMax")?e.listeningActiveDurationMax:this.opt.listeningActiveDurationMax,this.listeningActive=!1,this.listeningVolume=0,this.listeningTimer=0,this.listeningTimerTotal=0,this.isListening=!0}stopListening(){this.isListening=!1}async playAnimation(t,e=null,n=10,i=0,s=.01,o=!1,r=null){if(!this.armature)return;this.positionWasLocked=!o,o?console.log("Position locking disabled for FBX animation:",t):(this.lockAvatarPosition(),console.log("Position locked immediately before FBX animation:",t));let u=this.animClips.find(a=>a.url===t+"-"+i);if(u){let a=this.animQueue.find(h=>h.template.name==="pose");a&&(a.ts[0]=1/0),Object.entries(u.pose.props).forEach(h=>{this.poseBase.props[h[0]]=h[1].clone(),this.poseTarget.props[h[0]]=h[1].clone(),this.poseTarget.props[h[0]].t=0,this.poseTarget.props[h[0]].d=1e3}),this.mixer?console.log("Using existing mixer for FBX animation, preserving morph targets"):(this.mixer=new x.AnimationMixer(this.armature),console.log("Created new mixer for FBX animation")),this.animationFinishedCallback=r;const c=()=>{this.animationFinishedCallback&&(this.animationFinishedCallback(),this.animationFinishedCallback=null),this.stopAnimation()};this.mixer.addEventListener("finished",c,{once:!0});const l=Math.ceil(n/u.clip.duration),d=this.mixer.clipAction(u.clip);if(d.setLoop(x.LoopRepeat,l),d.clampWhenFinished=!0,this.currentFBXAction&&this.currentFBXAction.isRunning()){this.currentFBXAction.fadeOut(.3),setTimeout(()=>{this.currentFBXAction=d;try{d.fadeIn(.5).play(),console.log("FBX animation started successfully (with fade transition):",t)}catch(h){console.warn("FBX animation failed to start:",h),this.stopAnimation()}},300);return}this.currentFBXAction=d;try{d.fadeIn(.5).play(),console.log("FBX animation started successfully:",t)}catch(h){console.warn("FBX animation failed to start:",h),this.stopAnimation();return}if(d.getClip().tracks.length===0){console.warn("FBX animation has no valid tracks, stopping"),this.stopAnimation();return}}else{if(t.split(".").pop().toLowerCase()!=="fbx"){console.error(`Invalid file type for FBX animation: ${t}. Expected .fbx file.`);return}let c=!1;try{const h=await fetch(t,{method:"HEAD"});if(c=h.ok,!c){console.error(`FBX file not found at ${t}. Status: ${h.status}`),console.error("Please check:"),console.error("1. File path is correct (note: path is case-sensitive)"),console.error("2. File exists in your public folder"),console.error("3. File is accessible (not blocked by server)");return}}catch(h){console.warn(`Could not verify file existence for ${t}, attempting to load anyway:`,h)}const l=new Ve.FBXLoader;let d;try{d=await l.loadAsync(t,e)}catch(h){console.error(`Failed to load FBX animation from ${t}:`,h),console.error("Error details:",{message:h.message,url:t,suggestion:"Make sure the file is a valid FBX file and the path is correct"}),h.message&&h.message.includes("version number")&&(console.error("FBX Loader Error: Cannot find version number"),console.error("This error usually means:"),console.error("1. The file is not a valid FBX file (might be GLB, corrupted, or wrong format)"),console.error("2. The file might be corrupted"),console.error("3. The file path might be incorrect"),console.error("4. The server returned an HTML error page instead of the FBX file"),console.error("5. The file might not exist at that path"),console.error(""),console.error("Solution: Please verify:"),console.error(` - File exists at: ${t}`),console.error(" - File is a valid FBX binary file"),console.error(" - File path matches your public folder structure"),console.error(" - File is not corrupted"));try{const p=await fetch(t),v=p.headers.get("content-type"),y=await p.text();console.error("Response details:",{status:p.status,contentType:v,firstBytes:y.substring(0,100),isHTML:y.trim().startsWith("<!DOCTYPE")||y.trim().startsWith("<html")}),(y.trim().startsWith("<!DOCTYPE")||y.trim().startsWith("<html"))&&console.error("The server returned an HTML page instead of an FBX file. The file path is likely incorrect.")}catch(p){console.error("Could not fetch file for debugging:",p)}return}if(d&&d.animations&&d.animations[i]){let h=d.animations[i];const p=new Set;this.armature&&this.armature.traverse(A=>{(A.isBone||A.type==="Bone")&&p.add(A.name)});const v=new Map,y=A=>{if(p.has(A))return A;let H=A.replace(/^mixamorig/i,"").replace(/^CC_Base_/i,"").replace(/^RPM_/i,"");if(p.has(H))return H;const f=H.toLowerCase();if(f.includes("left")&&f.includes("arm")){if(f.includes("fore")||f.includes("lower")){if(p.has("LeftForeArm"))return"LeftForeArm";if(p.has("LeftForearm"))return"LeftForearm"}else if(!f.includes("fore")&&!f.includes("hand")&&p.has("LeftArm"))return"LeftArm"}if(f.includes("right")&&f.includes("arm")){if(f.includes("fore")||f.includes("lower")){if(p.has("RightForeArm"))return"RightForeArm";if(p.has("RightForearm"))return"RightForearm"}else if(!f.includes("fore")&&!f.includes("hand")&&p.has("RightArm"))return"RightArm"}if(f.includes("left")&&f.includes("hand")&&!f.includes("index")&&!f.includes("thumb")&&!f.includes("middle")&&!f.includes("ring")&&!f.includes("pinky")&&p.has("LeftHand"))return"LeftHand";if(f.includes("right")&&f.includes("hand")&&!f.includes("index")&&!f.includes("thumb")&&!f.includes("middle")&&!f.includes("ring")&&!f.includes("pinky")&&p.has("RightHand"))return"RightHand";if(f.includes("left")&&(f.includes("shoulder")||f.includes("clavicle"))&&p.has("LeftShoulder"))return"LeftShoulder";if(f.includes("right")&&(f.includes("shoulder")||f.includes("clavicle"))&&p.has("RightShoulder"))return"RightShoulder";const P={LeftArm:"LeftArm",leftArm:"LeftArm",LEFTARM:"LeftArm",RightArm:"RightArm",rightArm:"RightArm",RIGHTARM:"RightArm",LeftForeArm:"LeftForeArm",leftForeArm:"LeftForeArm",leftForearm:"LeftForeArm",LeftForearm:"LeftForeArm",RightForeArm:"RightForeArm",rightForeArm:"RightForeArm",rightForearm:"RightForeArm",RightForearm:"RightForeArm",LeftHand:"LeftHand",leftHand:"LeftHand",RightHand:"RightHand",rightHand:"RightHand",LeftShoulder:"LeftShoulder",leftShoulder:"LeftShoulder",RightShoulder:"RightShoulder",rightShoulder:"RightShoulder",Spine:"Spine1",spine:"Spine1",Spine1:"Spine1",Spine2:"Spine2",Head:"Head",head:"Head",Neck:"Neck",neck:"Neck",Hips:"Hips",hips:"Hips",Root:"Hips",root:"Hips"};if(P[H]){const N=P[H];if(p.has(N))return N}for(const N of p)if(N.toLowerCase()===f)return N;for(const N of p){const B=N.toLowerCase();if((f.includes("left")&&B.includes("left")||f.includes("right")&&B.includes("right"))&&(f.includes("arm")&&B.includes("arm")&&!B.includes("fore")||f.includes("forearm")&&B.includes("forearm")||f.includes("hand")&&B.includes("hand")&&!B.includes("index")&&!B.includes("thumb")||f.includes("shoulder")&&B.includes("shoulder")))return N}return null},w=new Set;h.tracks.forEach(A=>{const H=A.name.split(".");w.add(H[0])}),console.log("=== Ready Player Me Animation Bone Analysis ==="),console.log("FBX bone names:",Array.from(w).sort().join(", ")),console.log("Avatar skeleton bone names:",Array.from(p).sort().join(", "));const M=Array.from(w).filter(A=>A.toLowerCase().includes("arm")||A.toLowerCase().includes("hand")||A.toLowerCase().includes("shoulder")),g=Array.from(p).filter(A=>A.includes("Arm")||A.includes("Hand")||A.includes("Shoulder"));console.log("FBX arm/hand/shoulder bones:",M.sort().join(", ")),console.log("Avatar arm/hand/shoulder bones:",g.sort().join(", "));const U=[],E=new Set;let L=0;if(h.tracks.forEach(A=>{const f=A.name.replaceAll("mixamorig","").split("."),P=f[0],N=f[1],B=y(P);if(B&&(B==="LeftShoulder"||B==="RightShoulder")&&(N==="quaternion"||N==="rotation")){L++;return}if(B&&N){const Y=`${B}.${N}`,se=A.clone();se.name=Y,U.push(se),P!==B&&v.set(P,B)}else E.add(P),(P.toLowerCase().includes("arm")||P.toLowerCase().includes("hand")||P.toLowerCase().includes("shoulder"))&&console.warn(`⚠️ Arm bone "${P}" could not be mapped to avatar skeleton`)}),L>0&&console.log(`✓ Filtered out ${L} shoulder rotation track(s) to prevent high shoulders`),E.size>0&&console.warn(`⚠️ ${E.size} bone(s) could not be mapped:`,Array.from(E).sort().join(", ")),U.length>0){h=new x.AnimationClip(h.name,h.duration,U),console.log(`✓ Created animation with ${U.length} mapped tracks (from ${h.tracks.length} original tracks)`),v.size>0&&console.log(`✓ Mapped ${v.size} bone(s):`,Array.from(v.entries()).map(([H,f])=>`${H}→${f}`).join(", "));const A=Array.from(v.values()).filter(H=>H.includes("Arm")||H.includes("Hand")||H.includes("Shoulder"));A.length>0?console.log(`✓ Arm bones mapped: ${A.join(", ")}`):console.warn("⚠️ No arm bones were mapped! This may cause arm rigging issues.")}else console.error("❌ No tracks could be mapped! Animation may not work correctly.");const W={};h.tracks.forEach(A=>{A.name=A.name.replaceAll("mixamorig","");const H=A.name.split(".");if(H[1]==="position"){for(let f=0;f<A.values.length;f++)A.values[f]=A.values[f]*s;W[A.name]=new x.Vector3(A.values[0],A.values[1],A.values[2])}else H[1]==="quaternion"?W[A.name]=new x.Quaternion(A.values[0],A.values[1],A.values[2],A.values[3]):H[1]==="rotation"&&(W[H[0]+".quaternion"]=new x.Quaternion().setFromEuler(new x.Euler(A.values[0],A.values[1],A.values[2],"XYZ")).normalize())});const k={props:W};W["Hips.position"]&&(W["Hips.position"].y<.5?k.lying=!0:k.standing=!0),this.animClips.push({url:t+"-"+i,clip:h,pose:k}),this.playAnimation(t,e,n,i,s)}else{const h="Animation "+t+" (ndx="+i+") not found";console.error(h),d&&d.animations?console.error(`FBX file loaded but has ${d.animations.length} animation(s), requested index ${i}`):console.error(d?"FBX file loaded but contains no animations":"FBX file failed to load or is invalid")}}}stopAnimation(){if(this.currentFBXAction&&(this.currentFBXAction.stop(),this.currentFBXAction=null,console.log("FBX animation action stopped, mixer preserved for lip-sync")),this.mixer&&this.mixer._actions.length===0&&(this.mixer=null,console.log("Mixer destroyed as no actions remain")),this.positionWasLocked?(this.unlockAvatarPosition(),console.log("Position unlocked after FBX animation stopped")):console.log("Position was not locked, no unlock needed"),this.gesture)for(let[e,n]of Object.entries(this.gesture))n.t=this.animClock,n.d=1e3,this.poseTarget.props.hasOwnProperty(e)&&(this.poseTarget.props[e].copy(n),this.poseTarget.props[e].t=this.animClock,this.poseTarget.props[e].d=1e3);let t=this.animQueue.find(e=>e.template.name==="pose");t&&(t.ts[0]=this.animClock),this.setPoseFromTemplate(null)}async playPose(t,e=null,n=5,i=0,s=.01){if(!this.armature)return;let o=this.poseTemplates[t];if(!o){const r=this.animPoses.find(u=>u.url===t+"-"+i);r&&(o=r.pose)}if(o){this.poseName=t,this.mixer=null;let r=this.animQueue.find(u=>u.template.name==="pose");r&&(r.ts[0]=this.animClock+n*1e3+2e3),this.setPoseFromTemplate(o)}else{let u=await new Ve.FBXLoader().loadAsync(t,e);if(u&&u.animations&&u.animations[i]){let a=u.animations[i];const c={};a.tracks.forEach(d=>{d.name=d.name.replaceAll("mixamorig","");const h=d.name.split(".");h[1]==="position"?c[d.name]=new x.Vector3(d.values[0]*s,d.values[1]*s,d.values[2]*s):h[1]==="quaternion"?c[d.name]=new x.Quaternion(d.values[0],d.values[1],d.values[2],d.values[3]):h[1]==="rotation"&&(c[h[0]+".quaternion"]=new x.Quaternion().setFromEuler(new x.Euler(d.values[0],d.values[1],d.values[2],"XYZ")).normalize())});const l={props:c};c["Hips.position"]&&(c["Hips.position"].y<.5?l.lying=!0:l.standing=!0),this.animPoses.push({url:t+"-"+i,pose:l}),this.playPose(t,e,n,i,s)}else{const a="Pose "+t+" (ndx="+i+") not found";console.error(a)}}}stopPose(){this.stopAnimation()}playGesture(t,e=3,n=!1,i=1e3){if(!this.armature)return;let s=this.gestureTemplates[t];if(s){this.gestureTimeout&&(clearTimeout(this.gestureTimeout),this.gestureTimeout=null);let r=this.animQueue.findIndex(u=>u.template.name==="talkinghands");r!==-1&&(this.animQueue[r].ts=this.animQueue[r].ts.map(u=>0)),this.gesture=this.propsToThreeObjects(s),n&&(this.gesture=this.mirrorPose(this.gesture)),t==="namaste"&&this.avatar.body==="M"&&(this.gesture["RightArm.quaternion"].rotateTowards(new x.Quaternion(0,1,0,0),-.25),this.gesture["LeftArm.quaternion"].rotateTowards(new x.Quaternion(0,1,0,0),-.25));for(let[u,a]of Object.entries(this.gesture))a.t=this.animClock,a.d=i,this.poseTarget.props.hasOwnProperty(u)&&(this.poseTarget.props[u].copy(a),this.poseTarget.props[u].t=this.animClock,this.poseTarget.props[u].d=i);e&&Number.isFinite(e)&&(this.gestureTimeout=setTimeout(this.stopGesture.bind(this,i),1e3*e))}let o=this.animEmojis[t];if(o&&(o&&o.link&&(o=this.animEmojis[o.link]),o)){this.lookAtCamera(500);const r=this.animFactory(o);if(r.gesture=!0,e&&Number.isFinite(e)){const u=r.ts[0],c=r.ts[r.ts.length-1]-u;if(e*1e3-c>0){const d=[];for(let v=1;v<r.ts.length;v++)d.push(r.ts[v]-r.ts[v-1]);const h=o.template?.rescale||d.map(v=>v/c),p=e*1e3-c;r.ts=r.ts.map((v,y,w)=>y===0?u:w[y-1]+d[y-1]+h[y-1]*p)}else{const d=e*1e3/c;r.ts=r.ts.map(h=>u+d*(h-u))}}this.animQueue.push(r)}}stopGesture(t=1e3){if(this.gestureTimeout&&(clearTimeout(this.gestureTimeout),this.gestureTimeout=null),this.gesture){const n=Object.entries(this.gesture);this.gesture=null;for(const[i,s]of n)this.poseTarget.props.hasOwnProperty(i)&&(this.poseTarget.props[i].copy(this.getPoseTemplateProp(i)),this.poseTarget.props[i].t=this.animClock,this.poseTarget.props[i].d=t)}let e=this.animQueue.findIndex(n=>n.gesture);e!==-1&&this.animQueue.splice(e,1)}ikSolve(t,e=null,n=!1,i=null){const s=new x.Vector3,o=new x.Vector3,r=new x.Vector3,u=new x.Vector3,a=new x.Quaternion,c=new x.Vector3,l=new x.Vector3,d=new x.Vector3,h=this.ikMesh.getObjectByName(t.root);h.position.setFromMatrixPosition(this.armature.getObjectByName(t.root).matrixWorld),h.quaternion.setFromRotationMatrix(this.armature.getObjectByName(t.root).matrixWorld),e&&n&&e.applyQuaternion(this.armature.quaternion).add(h.position);const p=this.ikMesh.getObjectByName(t.effector),v=t.links;v.forEach(w=>{w.bone=this.ikMesh.getObjectByName(w.link),w.bone.quaternion.copy(this.getPoseTemplateProp(w.link+".quaternion"))}),h.updateMatrixWorld(!0);const y=t.iterations||10;if(e)for(let w=0;w<y;w++){let M=!1;for(let g=0,U=v.length;g<U;g++){const E=v[g].bone;E.matrixWorld.decompose(u,a,c),a.invert(),o.setFromMatrixPosition(p.matrixWorld),r.subVectors(o,u),r.applyQuaternion(a),r.normalize(),s.subVectors(e,u),s.applyQuaternion(a),s.normalize();let L=s.dot(r);L>1?L=1:L<-1&&(L=-1),L=Math.acos(L),!(L<1e-5)&&(v[g].minAngle!==void 0&&L<v[g].minAngle&&(L=v[g].minAngle),v[g].maxAngle!==void 0&&L>v[g].maxAngle&&(L=v[g].maxAngle),l.crossVectors(r,s),l.normalize(),ie.setFromAxisAngle(l,L),E.quaternion.multiply(ie),E.rotation.setFromVector3(d.setFromEuler(E.rotation).clamp(new x.Vector3(v[g].minx!==void 0?v[g].minx:-1/0,v[g].miny!==void 0?v[g].miny:-1/0,v[g].minz!==void 0?v[g].minz:-1/0),new x.Vector3(v[g].maxx!==void 0?v[g].maxx:1/0,v[g].maxy!==void 0?v[g].maxy:1/0,v[g].maxz!==void 0?v[g].maxz:1/0))),E.updateMatrixWorld(!0),M=!0)}if(!M)break}i&&v.forEach(w=>{this.poseTarget.props[w.link+".quaternion"].copy(w.bone.quaternion),this.poseTarget.props[w.link+".quaternion"].t=this.animClock,this.poseTarget.props[w.link+".quaternion"].d=i})}dispose(){this.isRunning=!1,this.stop(),this.stopSpeaking(),this.streamStop(),this.isAvatarOnly?this.armature&&(this.armature.parent&&this.armature.parent.remove(this.armature),this.clearThree(this.armature)):(this.clearThree(this.scene),this.resizeobserver.disconnect(),this.renderer&&(this.renderer.dispose(),this.renderer.domElement&&this.renderer.domElement.parentNode&&this.renderer.domElement.parentNode.removeChild(this.renderer.domElement),this.renderer=null)),this.clearThree(this.ikMesh),this.dynamicbones.dispose()}}const Se={apiKey:"sk_ace57ef3ef65a92b9d3bee2a00183b78ca790bc3e10964f2",endpoint:"https://api.elevenlabs.io/v1/text-to-speech",defaultVoice:"21m00Tcm4TlvDq8ikWAM",voices:{rachel:"21m00Tcm4TlvDq8ikWAM",drew:"29vD33N1CtxCmqQRPOHJ",bella:"EXAVITQu4vr4xnSDxMaL",antoni:"ErXwobaYiN019PkySvjV",elli:"MF3mGyEYCl7XYWbV9V6O",josh:"VR6AewLTigWG4xSOukaG"}},Pe={defaultVoice:"aura-2-thalia-en",voices:{thalia:"aura-2-thalia-en",asteria:"aura-2-asteria-en",orion:"aura-2-orion-en",stella:"aura-2-stella-en",athena:"aura-2-athena-en",hera:"aura-2-hera-en",zeus:"aura-2-zeus-en"}};function ze(){return{service:"elevenlabs",endpoint:Se.endpoint,apiKey:Se.apiKey,defaultVoice:Se.defaultVoice,voices:Se.voices}}function Rt(){const G=ze(),t=[];return Object.entries(G.voices).forEach(([e,n])=>{t.push({value:n,label:`${e.charAt(0).toUpperCase()+e.slice(1)} (${G.service})`})}),t}const Ue=b.forwardRef(({avatarUrl:G="/avatars/brunette.glb",avatarBody:t="F",mood:e="neutral",ttsLang:n="en",ttsService:i=null,ttsVoice:s=null,ttsApiKey:o=null,bodyMovement:r="idle",movementIntensity:u=.5,showFullAvatar:a=!0,cameraView:c="upper",onReady:l=()=>{},onLoading:d=()=>{},onError:h=()=>{},className:p="",style:v={},animations:y={}},w)=>{const M=b.useRef(null),g=b.useRef(null),U=b.useRef(a),E=b.useRef(null),L=b.useRef(null),W=b.useRef(!1),k=b.useRef({remainingText:null,originalText:null,options:null}),A=b.useRef([]),H=b.useRef(0),[f,P]=b.useState(!0),[N,B]=b.useState(null),[Y,se]=b.useState(!1),[re,fe]=b.useState(!1);b.useEffect(()=>{W.current=re},[re]),b.useEffect(()=>{U.current=a},[a]);const oe=ze(),Re=i||oe.service;let ee;Re==="browser"?ee={service:"browser",endpoint:"",apiKey:null,defaultVoice:"Google US English"}:Re==="elevenlabs"?ee={service:"elevenlabs",endpoint:"https://api.elevenlabs.io/v1/text-to-speech",apiKey:o||oe.apiKey,defaultVoice:s||oe.defaultVoice||Se.defaultVoice,voices:oe.voices||Se.voices}:Re==="deepgram"?ee={service:"deepgram",endpoint:"https://api.deepgram.com/v1/speak",apiKey:o||oe.apiKey,defaultVoice:s||oe.defaultVoice||Pe.defaultVoice,voices:oe.voices||Pe.voices}:ee={...oe,apiKey:o!==null?o:oe.apiKey};const R={url:G,body:t,avatarMood:e,ttsLang:Re==="browser"?"en-US":n,ttsVoice:s||ee.defaultVoice,lipsyncLang:"en",showFullAvatar:a,bodyMovement:r,movementIntensity:u},I={ttsEndpoint:ee.endpoint,ttsApikey:ee.apiKey,ttsService:Re,lipsyncModules:["en"],cameraView:c},F=b.useCallback(async()=>{if(!(!M.current||g.current))try{if(P(!0),B(null),g.current=new Ne(M.current,I),g.current.controls&&(g.current.controls.enableRotate=!1,g.current.controls.enableZoom=!1,g.current.controls.enablePan=!1,g.current.controls.enableDamping=!1),y&&Object.keys(y).length>0&&(g.current.customAnimations=y),await g.current.showAvatar(R,_=>{if(_.lengthComputable){const ne=Math.min(100,Math.round(_.loaded/_.total*100));d(ne)}}),await new Promise(_=>{const ne=()=>{g.current.lipsync&&Object.keys(g.current.lipsync).length>0?_():setTimeout(ne,100)};ne()}),g.current&&g.current.setShowFullAvatar)try{g.current.setShowFullAvatar(a)}catch(_){console.warn("Error setting full body mode on initialization:",_)}g.current&&g.current.controls&&(g.current.controls.enableRotate=!1,g.current.controls.enableZoom=!1,g.current.controls.enablePan=!1,g.current.controls.enableDamping=!1,g.current.controls.update()),P(!1),se(!0),l(g.current);const q=()=>{document.visibilityState==="visible"?g.current?.start():g.current?.stop()};return document.addEventListener("visibilitychange",q),()=>{document.removeEventListener("visibilitychange",q)}}catch(z){console.error("Error initializing TalkingHead:",z),B(z.message||"Failed to initialize avatar"),P(!1),h(z)}},[G,t,e,n,i,s,o,a,r,u,c]);b.useEffect(()=>(F(),()=>{g.current&&(g.current.stop(),g.current.dispose(),g.current=null)}),[F]),b.useEffect(()=>{if(!M.current||!g.current)return;const z=new ResizeObserver(_=>{for(const ne of _)g.current&&g.current.onResize&&g.current.onResize()});z.observe(M.current);const q=()=>{g.current&&g.current.onResize&&g.current.onResize()};return window.addEventListener("resize",q),()=>{z.disconnect(),window.removeEventListener("resize",q)}},[Y]);const V=b.useCallback(async()=>{if(g.current&&g.current.audioCtx)try{(g.current.audioCtx.state==="suspended"||g.current.audioCtx.state==="interrupted")&&(await g.current.audioCtx.resume(),console.log("Audio context resumed"))}catch(z){console.warn("Failed to resume audio context:",z)}},[]),Q=b.useCallback(async(z,q={})=>{if(g.current&&Y)try{L.current&&(clearInterval(L.current),L.current=null),E.current={text:z,options:q},k.current={remainingText:null,originalText:null,options:null};const _=/[!\.\?\n\p{Extended_Pictographic}]/ug,ne=z.split(_).map(J=>J.trim()).filter(J=>J.length>0);A.current=ne,H.current=0,fe(!1),W.current=!1,await V();const ye={...q,lipsyncLang:q.lipsyncLang||R.lipsyncLang||"en"};if(q.onSpeechEnd&&g.current){const J=g.current;let de=null,C=0;const S=1200;let O=!1;de=setInterval(()=>{if(C++,W.current)return;if(C>S){if(de&&(clearInterval(de),de=null,L.current=null),!O&&!W.current){O=!0;try{q.onSpeechEnd()}catch(Be){console.error("Error in onSpeechEnd callback (timeout):",Be)}}return}const Z=!J.speechQueue||J.speechQueue.length===0,j=!J.audioPlaylist||J.audioPlaylist.length===0;J&&J.isSpeaking===!1&&Z&&j&&J.isAudioPlaying===!1&&!O&&!W.current&&setTimeout(()=>{if(J&&!W.current&&J.isSpeaking===!1&&(!J.speechQueue||J.speechQueue.length===0)&&(!J.audioPlaylist||J.audioPlaylist.length===0)&&J.isAudioPlaying===!1&&!O&&!W.current){O=!0,de&&(clearInterval(de),de=null,L.current=null);try{q.onSpeechEnd()}catch(le){console.error("Error in onSpeechEnd callback:",le)}}},100)},100),L.current=de}g.current.lipsync&&Object.keys(g.current.lipsync).length>0?(g.current.setSlowdownRate&&g.current.setSlowdownRate(1.05),g.current.speakText(z,ye)):setTimeout(async()=>{await V(),g.current&&g.current.lipsync&&(g.current.setSlowdownRate&&g.current.setSlowdownRate(1.05),g.current.speakText(z,ye))},100)}catch(_){console.error("Error speaking text:",_),B(_.message||"Failed to speak text")}},[Y,V,R.lipsyncLang]),ae=b.useCallback(()=>{g.current&&(g.current.stopSpeaking(),g.current.setSlowdownRate&&g.current.setSlowdownRate(1),E.current=null,fe(!1))},[]),$=b.useCallback(()=>{if(g.current&&g.current.pauseSpeaking){const z=g.current;if(z.isSpeaking||z.audioPlaylist&&z.audioPlaylist.length>0||z.speechQueue&&z.speechQueue.length>0){L.current&&(clearInterval(L.current),L.current=null);let _="";if(E.current&&A.current.length>0){const ne=A.current.length,ye=z.speechQueue?z.speechQueue.filter(S=>S&&S.text&&Array.isArray(S.text)&&S.text.length>0).length:0,J=z.audioPlaylist&&z.audioPlaylist.length>0,de=ye+(J?1:0),C=ne-de;if(de>0&&C<ne&&(_=A.current.slice(C).join(". ").trim(),!_&&ye>0&&z.speechQueue)){const O=z.speechQueue.filter(Z=>Z&&Z.text&&Array.isArray(Z.text)&&Z.text.length>0).map(Z=>Z.text.map(j=>j.word||"").filter(j=>j.length>0).join(" ")).filter(Z=>Z.length>0).join(" ");O&&O.trim()&&(_=O.trim())}}E.current&&(k.current={remainingText:_||null,originalText:E.current.text,options:E.current.options}),z.speechQueue&&(z.speechQueue.length=0),g.current.pauseSpeaking(),W.current=!0,fe(!0)}}},[]),te=b.useCallback(async()=>{if(!g.current||!re)return;let z="",q={};if(k.current&&k.current.remainingText)z=k.current.remainingText,q=k.current.options||{},k.current={remainingText:null,originalText:null,options:null};else if(E.current&&E.current.text)z=E.current.text,q=E.current.options||{};else{console.warn("Resume called but no paused speech found"),fe(!1),W.current=!1;return}fe(!1),W.current=!1,await V();const _={...q,lipsyncLang:q.lipsyncLang||R.lipsyncLang||"en"};try{await Q(z,_)}catch(ne){console.error("Error resuming speech:",ne),fe(!1),W.current=!1}},[V,re,Q,R]),pe=b.useCallback(z=>{g.current&&g.current.setMood(z)},[]),ke=b.useCallback(z=>{g.current&&g.current.setSlowdownRate&&g.current.setSlowdownRate(z)},[]),Oe=b.useCallback((z,q=!1)=>{if(g.current&&g.current.playAnimation){if(y&&y[z]&&(z=y[z]),g.current.setShowFullAvatar)try{g.current.setShowFullAvatar(U.current)}catch(ne){console.warn("Error setting full body mode:",ne)}if(z.includes("."))try{g.current.playAnimation(z,null,10,0,.01,q)}catch(ne){console.warn(`Failed to play ${z}:`,ne);try{g.current.setBodyMovement("idle")}catch(ye){console.warn("Fallback animation also failed:",ye)}}else{const ne=[".fbx",".glb",".gltf"];let ye=!1;for(const J of ne)try{g.current.playAnimation(z+J,null,10,0,.01,q),ye=!0;break}catch{}if(!ye){console.warn("Animation not found:",z);try{g.current.setBodyMovement("idle")}catch(J){console.warn("Fallback animation also failed:",J)}}}}},[y]),He=b.useCallback(()=>{g.current&&g.current.onResize&&g.current.onResize()},[]);return b.useImperativeHandle(w,()=>({speakText:Q,stopSpeaking:ae,pauseSpeaking:$,resumeSpeaking:te,resumeAudioContext:V,setMood:pe,setTimingAdjustment:ke,playAnimation:Oe,isReady:Y,isPaused:re,talkingHead:g.current,handleResize:He,setBodyMovement:z=>{if(g.current&&g.current.setShowFullAvatar&&g.current.setBodyMovement)try{g.current.setShowFullAvatar(U.current),g.current.setBodyMovement(z)}catch(q){console.warn("Error setting body movement:",q)}},setMovementIntensity:z=>g.current?.setMovementIntensity(z),playRandomDance:()=>{if(g.current&&g.current.setShowFullAvatar&&g.current.playRandomDance)try{g.current.setShowFullAvatar(U.current),g.current.playRandomDance()}catch(z){console.warn("Error playing random dance:",z)}},playReaction:z=>{if(g.current&&g.current.setShowFullAvatar&&g.current.playReaction)try{g.current.setShowFullAvatar(U.current),g.current.playReaction(z)}catch(q){console.warn("Error playing reaction:",q)}},playCelebration:()=>{if(g.current&&g.current.setShowFullAvatar&&g.current.playCelebration)try{g.current.setShowFullAvatar(U.current),g.current.playCelebration()}catch(z){console.warn("Error playing celebration:",z)}},setShowFullAvatar:z=>{if(g.current&&g.current.setShowFullAvatar)try{U.current=z,g.current.setShowFullAvatar(z)}catch(q){console.warn("Error setting showFullAvatar:",q)}},lockAvatarPosition:()=>{if(g.current&&g.current.lockAvatarPosition)try{g.current.lockAvatarPosition()}catch(z){console.warn("Error locking avatar position:",z)}},unlockAvatarPosition:()=>{if(g.current&&g.current.unlockAvatarPosition)try{g.current.unlockAvatarPosition()}catch(z){console.warn("Error unlocking avatar position:",z)}}})),X.jsxs("div",{className:`talking-head-avatar ${p}`,style:{width:"100%",height:"100%",position:"relative",...v},children:[X.jsx("div",{ref:M,className:"talking-head-viewer",style:{width:"100%",height:"100%",minHeight:"400px"}}),f&&X.jsx("div",{className:"loading-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"white",fontSize:"18px",zIndex:10},children:"Loading avatar..."}),N&&X.jsx("div",{className:"error-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"#ff6b6b",fontSize:"16px",textAlign:"center",zIndex:10,padding:"20px",borderRadius:"8px"},children:N})]})});Ue.displayName="TalkingHeadAvatar";const Ye=b.forwardRef(({text:G="Hello! I'm a talking avatar. How are you today?",onLoading:t=()=>{},onError:e=()=>{},onReady:n=()=>{},className:i="",style:s={},avatarConfig:o={}},r)=>{const u=b.useRef(null),a=b.useRef(null),[c,l]=b.useState(!0),[d,h]=b.useState(null),[p,v]=b.useState(!1),y=ze(),w=o.ttsService||y.service,M=w==="browser"?{endpoint:"",apiKey:null,defaultVoice:"Google US English"}:{...y,apiKey:o.ttsApiKey!==void 0&&o.ttsApiKey!==null?o.ttsApiKey:y.apiKey,endpoint:w==="elevenlabs"&&o.ttsApiKey?"https://api.elevenlabs.io/v1/text-to-speech":y.endpoint},g={url:"/avatars/brunette.glb",body:"F",avatarMood:"neutral",ttsLang:w==="browser"?"en-US":"en",ttsVoice:o.ttsVoice||M.defaultVoice,lipsyncLang:"en",showFullAvatar:!0,bodyMovement:"idle",movementIntensity:.5,...o},U={ttsEndpoint:M.endpoint,ttsApikey:M.apiKey,ttsService:w,lipsyncModules:["en"],cameraView:"upper"},E=b.useCallback(async()=>{if(!(!u.current||a.current))try{if(l(!0),h(null),a.current=new Ne(u.current,U),await a.current.showAvatar(g,N=>{if(N.lengthComputable){const B=Math.min(100,Math.round(N.loaded/N.total*100));t(B)}}),a.current.morphs&&a.current.morphs.length>0){const N=a.current.morphs[0].morphTargetDictionary;console.log("Available morph targets:",Object.keys(N));const B=Object.keys(N).filter(Y=>Y.startsWith("viseme_"));console.log("Viseme morph targets found:",B),B.length===0&&(console.warn("No viseme morph targets found! Lip-sync will not work properly."),console.log("Expected viseme targets: viseme_aa, viseme_E, viseme_I, viseme_O, viseme_U, viseme_PP, viseme_SS, viseme_TH, viseme_DD, viseme_FF, viseme_kk, viseme_nn, viseme_RR, viseme_CH, viseme_sil"))}if(await new Promise(N=>{const B=()=>{a.current.lipsync&&Object.keys(a.current.lipsync).length>0?(console.log("Lip-sync modules loaded:",Object.keys(a.current.lipsync)),N()):(console.log("Waiting for lip-sync modules to load..."),setTimeout(B,100))};B()}),a.current&&a.current.setShowFullAvatar)try{a.current.setShowFullAvatar(!0),console.log("Avatar initialized in full body mode")}catch(N){console.warn("Error setting full body mode on initialization:",N)}l(!1),v(!0),n(a.current);const P=()=>{document.visibilityState==="visible"?a.current?.start():a.current?.stop()};return document.addEventListener("visibilitychange",P),()=>{document.removeEventListener("visibilitychange",P)}}catch(f){console.error("Error initializing TalkingHead:",f),h(f.message||"Failed to initialize avatar"),l(!1),e(f)}},[]);b.useEffect(()=>(E(),()=>{a.current&&(a.current.stop(),a.current.dispose(),a.current=null)}),[E]);const L=b.useCallback(f=>{if(a.current&&p)try{console.log("Speaking text:",f),console.log("Avatar config:",g),console.log("TalkingHead instance:",a.current),a.current.lipsync&&Object.keys(a.current.lipsync).length>0?(console.log("Lip-sync modules loaded:",Object.keys(a.current.lipsync)),a.current.setSlowdownRate&&(a.current.setSlowdownRate(1.05),console.log("Applied timing adjustment for better lip-sync")),a.current.speakText(f)):(console.warn("Lip-sync modules not ready, waiting..."),setTimeout(()=>{a.current&&a.current.lipsync?(console.log("Lip-sync now ready, speaking..."),a.current.setSlowdownRate&&(a.current.setSlowdownRate(1.05),console.log("Applied timing adjustment for better lip-sync")),a.current.speakText(f)):console.error("Lip-sync still not ready after waiting")},500))}catch(P){console.error("Error speaking text:",P),h(P.message||"Failed to speak text")}else console.warn("Avatar not ready for speaking. isReady:",p,"talkingHeadRef:",!!a.current)},[p,g]),W=b.useCallback(()=>{a.current&&(a.current.stopSpeaking(),a.current.setSlowdownRate&&(a.current.setSlowdownRate(1),console.log("Reset timing to normal")))},[]),k=b.useCallback(f=>{a.current&&a.current.setMood(f)},[]),A=b.useCallback(f=>{a.current&&a.current.setSlowdownRate&&(a.current.setSlowdownRate(f),console.log("Timing adjustment set to:",f))},[]),H=b.useCallback((f,P=!1)=>{if(a.current&&a.current.playAnimation){if(a.current.setShowFullAvatar)try{a.current.setShowFullAvatar(!0)}catch(B){console.warn("Error setting full body mode:",B)}if(f.includes("."))try{a.current.playAnimation(f,null,10,0,.01,P),console.log("Playing animation:",f)}catch(B){console.log(`Failed to play ${f}:`,B);try{a.current.setBodyMovement("idle"),console.log("Fallback to idle animation")}catch(Y){console.warn("Fallback animation also failed:",Y)}}else{const B=[".fbx",".glb",".gltf"];let Y=!1;for(const se of B)try{a.current.playAnimation(f+se,null,10,0,.01,P),console.log("Playing animation:",f+se),Y=!0;break}catch{console.log(`Failed to play ${f}${se}, trying next format...`)}if(!Y){console.warn("Animation system not available or animation not found:",f);try{a.current.setBodyMovement("idle"),console.log("Fallback to idle animation")}catch(se){console.warn("Fallback animation also failed:",se)}}}}else console.warn("Animation system not available or animation not found:",f)},[]);return b.useImperativeHandle(r,()=>({speakText:L,stopSpeaking:W,setMood:k,setTimingAdjustment:A,playAnimation:H,isReady:p,talkingHead:a.current,setBodyMovement:f=>{if(a.current&&a.current.setShowFullAvatar&&a.current.setBodyMovement)try{a.current.setShowFullAvatar(!0),a.current.setBodyMovement(f),console.log("Body movement set with full body mode:",f)}catch(P){console.warn("Error setting body movement:",P)}},setMovementIntensity:f=>a.current?.setMovementIntensity(f),playRandomDance:()=>{if(a.current&&a.current.setShowFullAvatar&&a.current.playRandomDance)try{a.current.setShowFullAvatar(!0),a.current.playRandomDance(),console.log("Random dance played with full body mode")}catch(f){console.warn("Error playing random dance:",f)}},playReaction:f=>{if(a.current&&a.current.setShowFullAvatar&&a.current.playReaction)try{a.current.setShowFullAvatar(!0),a.current.playReaction(f),console.log("Reaction played with full body mode:",f)}catch(P){console.warn("Error playing reaction:",P)}},playCelebration:()=>{if(a.current&&a.current.setShowFullAvatar&&a.current.playCelebration)try{a.current.setShowFullAvatar(!0),a.current.playCelebration(),console.log("Celebration played with full body mode")}catch(f){console.warn("Error playing celebration:",f)}},setShowFullAvatar:f=>{if(a.current&&a.current.setShowFullAvatar)try{a.current.setShowFullAvatar(f),console.log("Show full avatar set to:",f)}catch(P){console.warn("Error setting showFullAvatar:",P)}},lockAvatarPosition:()=>{if(a.current&&a.current.lockAvatarPosition)try{a.current.lockAvatarPosition()}catch(f){console.warn("Error locking avatar position:",f)}},unlockAvatarPosition:()=>{if(a.current&&a.current.unlockAvatarPosition)try{a.current.unlockAvatarPosition()}catch(f){console.warn("Error unlocking avatar position:",f)}}})),X.jsxs("div",{className:`talking-head-container ${i}`,style:s,children:[X.jsx("div",{ref:u,className:"talking-head-viewer",style:{width:"100%",height:"100%",minHeight:"400px"}}),c&&X.jsx("div",{className:"loading-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"white",fontSize:"18px",zIndex:10},children:"Loading avatar..."}),d&&X.jsx("div",{className:"error-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"#ff6b6b",fontSize:"16px",textAlign:"center",zIndex:10,padding:"20px",borderRadius:"8px"},children:d})]})});Ye.displayName="TalkingHeadComponent";async function Ce(G){try{console.log(`📥 Loading animation manifest from: ${G}`);const t=await fetch(G);if(!t.ok)throw new Error(`Failed to fetch manifest: ${t.status} ${t.statusText}`);const e=await t.json();console.log("📦 Raw manifest loaded:",e);const n=e.animations||{};return console.log("✅ Processed animations object:",n),n._genderSpecific&&console.log("👥 Gender-specific structure detected:",{male:Object.keys(n._genderSpecific.male||{}),female:Object.keys(n._genderSpecific.female||{}),shared:Object.keys(n._genderSpecific.shared||{})}),n}catch(t){return console.error("❌ Failed to load animation manifest:",t),{}}}async function At(G,t="F"){const e=[],n=G.replace(/\/$/,"");try{const s=[`${n}/.list.json`,`/api/directory?path=${encodeURIComponent(n)}`,`${n}/index.json`];for(const o of s)try{const r=await fetch(o);if(r.ok){const u=await r.json(),c=(Array.isArray(u)?u:u.files||[]).filter(l=>typeof l=="string"&&l.toLowerCase().endsWith(".fbx")).map(l=>l.startsWith("/")?l:`${n}/${l}`);if(c.length>0)return console.log(`✅ Auto-discovered ${c.length} animations from ${o}`),c}}catch{continue}}catch(s){console.warn(`⚠️ Could not use directory listing API for ${n}:`,s)}const i=[];t==="M"||t==="m"?i.push(`${n}/male`,`${n}/m`):i.push(`${n}/female`,`${n}/f`),i.push(`${n}/shared`);for(const s of i)try{const o=`${s}/.list.json`,r=await fetch(o);if(r.ok){const u=await r.json(),a=(Array.isArray(u)?u:u.files||[]).filter(c=>typeof c=="string"&&c.toLowerCase().endsWith(".fbx")).map(c=>c.startsWith("/")?c:`${s}/${c}`);a.length>0&&(console.log(`✅ Auto-discovered ${a.length} animations from ${s}`),e.push(...a))}}catch{continue}return e.length>0||(console.warn(`⚠️ Could not auto-discover animations from ${n}. Consider using a manifest.json file or a server-side directory listing API.`),console.info(`💡 Tip: Create a ${n}/.list.json file with an array of FBX filenames, or use animations: { manifest: "/animations/manifest.json" }`)),e}async function je(G,t="F"){const e={};for(const[n,i]of Object.entries(G))try{const s=await At(i,t);s.length>0?(e[n]=s,console.log(`✅ Auto-loaded ${s.length} animations for group "${n}"`)):console.warn(`⚠️ No animations found in ${i} for group "${n}"`)}catch(s){console.error(`❌ Failed to auto-load animations from ${i}:`,s)}return e}const Qe=b.forwardRef(({text:G=null,avatarUrl:t="/avatars/brunette.glb",avatarBody:e="F",mood:n="neutral",ttsLang:i="en",ttsService:s=null,ttsVoice:o=null,ttsApiKey:r=null,bodyMovement:u="idle",movementIntensity:a=.5,showFullAvatar:c=!1,cameraView:l="upper",onReady:d=()=>{},onLoading:h=()=>{},onError:p=()=>{},onSpeechEnd:v=()=>{},className:y="",style:w={},animations:M={},autoAnimationGroup:g=null,autoIdleGroup:U=null,autoSpeak:E=!1},L)=>{const W=b.useRef(null),k=b.useRef(null),A=b.useRef(c),H=b.useRef(null),f=b.useRef(null),P=b.useRef(!1),N=b.useRef({remainingText:null,originalText:null,options:null}),B=b.useRef([]),[Y,se]=b.useState(!0),[re,fe]=b.useState(null),[oe,Re]=b.useState(!1),[ee,R]=b.useState(!1),[I,F]=b.useState(M),V=b.useRef(null),Q=b.useRef(!1),ae=b.useRef(null);b.useEffect(()=>{P.current=ee},[ee]),b.useEffect(()=>{(async()=>{if(M.manifest&&M.auto)try{console.log("🔄 Loading animations from manifest (priority over auto-discovery):",M.manifest);const S=await Ce(M.manifest);F(S),console.log("✅ Animations loaded from manifest:",S),S._genderSpecific&&console.log("👥 Gender-specific animations detected:",{male:Object.keys(S._genderSpecific.male||{}),female:Object.keys(S._genderSpecific.female||{}),shared:Object.keys(S._genderSpecific.shared||{})});return}catch(S){console.warn("⚠️ Manifest failed, falling back to auto-discovery:",S)}if(M.manifest&&!M.auto)try{console.log("🔄 Loading animations from manifest:",M.manifest);const S=await Ce(M.manifest);F(S),console.log("✅ Animations loaded and set:",S),S._genderSpecific?console.log("👥 Gender-specific animations detected:",{male:Object.keys(S._genderSpecific.male||{}),female:Object.keys(S._genderSpecific.female||{}),shared:Object.keys(S._genderSpecific.shared||{})}):console.log("⚠️ No gender-specific animations found in manifest")}catch(S){console.error("❌ Failed to load animation manifest:",S),F(M)}else if(M.auto)try{console.log("🔄 Auto-discovering animations from folder:",M.auto);let S=null;if(M.manifest)try{S=await Ce(M.manifest),console.log("📦 Loaded manifest as fallback:",S)}catch(O){console.warn("⚠️ Could not load manifest fallback:",O)}if(typeof M.auto=="string"){const O=M.auto,Z={talking:`${O}/talking`,idle:`${O}/idle`},j=e==="M"?"male":"female";Z[`${j}_talking`]=`${O}/${j}/talking`,Z[`${j}_idle`]=`${O}/${j}/idle`,Z.shared_talking=`${O}/shared/talking`,Z.shared_idle=`${O}/shared/idle`;const xe=await je(Z,e);if(!Object.values(xe).some(ce=>Array.isArray(ce)&&ce.length>0)&&S){console.log("⚠️ No animations auto-discovered, using manifest fallback"),F(S);return}const le={_genderSpecific:{[j]:{},shared:{}}};Object.entries(xe).forEach(([ce,Ie])=>{if(ce.includes("_")){const[Te,..._e]=ce.split("_"),we=_e.join("_");Te==="shared"?(le._genderSpecific.shared[we]||(le._genderSpecific.shared[we]=[]),le._genderSpecific.shared[we].push(...Ie)):Te===j&&(le._genderSpecific[j][we]||(le._genderSpecific[j][we]=[]),le._genderSpecific[j][we].push(...Ie))}else le[ce]=Ie}),S&&(S._genderSpecific&&Object.keys(S._genderSpecific).forEach(ce=>{le._genderSpecific[ce]||(le._genderSpecific[ce]={}),Object.entries(S._genderSpecific[ce]).forEach(([Ie,Te])=>{le._genderSpecific[ce][Ie]||(le._genderSpecific[ce][Ie]=Te)})}),Object.entries(S).forEach(([ce,Ie])=>{ce!=="_genderSpecific"&&!le[ce]&&(le[ce]=Ie)})),F(le),console.log("✅ Auto-discovered animations:",le)}else if(typeof M.auto=="object"){const O=await je(M.auto,e);!Object.values(O).some(j=>Array.isArray(j)&&j.length>0)&&S?(console.log("⚠️ No animations auto-discovered, using manifest fallback"),F(S)):(F(O),console.log("✅ Auto-discovered animations from folders:",O))}}catch(S){if(console.error("❌ Failed to auto-discover animations:",S),M.manifest)try{const O=await Ce(M.manifest);F(O),console.log("✅ Using manifest fallback after auto-discovery error")}catch{F(M)}else F(M)}else console.log("📝 Using animations from props (no manifest or auto):",M),F(M)})()},[M,e]),b.useEffect(()=>{A.current=c},[c]);const $=ze(),te=s||$.service;let pe;te==="browser"?pe={service:"browser",endpoint:"",apiKey:null,defaultVoice:"Google US English"}:te==="elevenlabs"?pe={service:"elevenlabs",endpoint:"https://api.elevenlabs.io/v1/text-to-speech",apiKey:r||$.apiKey,defaultVoice:o||$.defaultVoice||Se.defaultVoice,voices:$.voices||Se.voices}:te==="deepgram"?pe={service:"deepgram",endpoint:"https://api.deepgram.com/v1/speak",apiKey:r||$.apiKey,defaultVoice:o||$.defaultVoice||Pe.defaultVoice,voices:$.voices||Pe.voices}:pe={...$,apiKey:r!==null?r:$.apiKey};const ke={url:t,body:e,avatarMood:n,ttsLang:te==="browser"?"en-US":i,ttsVoice:o||pe.defaultVoice,lipsyncLang:"en",showFullAvatar:c,bodyMovement:u,movementIntensity:a},Oe={ttsEndpoint:pe.endpoint,ttsApikey:pe.apiKey,ttsService:te,lipsyncModules:["en"],cameraView:l},He=b.useCallback(async()=>{if(!(!W.current||k.current))try{se(!0),fe(null),k.current=new Ne(W.current,Oe),console.log("Avatar config being passed:",{url:ke.url,body:ke.body,avatarMood:ke.avatarMood}),await k.current.showAvatar(ke,S=>{if(S.lengthComputable){const O=Math.min(100,Math.round(S.loaded/S.total*100));h(O)}}),k.current?.avatar&&console.log("Avatar body after initialization:",k.current.avatar.body),se(!1),Re(!0),d(k.current);const C=()=>{document.visibilityState==="visible"?k.current?.start():k.current?.stop()};return document.addEventListener("visibilitychange",C),()=>{document.removeEventListener("visibilitychange",C)}}catch(C){console.error("Error initializing TalkingHead:",C),fe(C.message||"Failed to initialize avatar"),se(!1),p(C)}},[]);b.useEffect(()=>(He(),()=>{k.current&&(k.current.stop(),k.current.dispose(),k.current=null)}),[He]);const z=b.useCallback(async()=>{if(k.current)try{const C=k.current.audioCtx||k.current.audioContext;C&&(C.state==="suspended"||C.state==="interrupted")&&(await C.resume(),console.log("Audio context resumed"))}catch(C){console.warn("Failed to resume audio context:",C)}},[]),q=b.useCallback(C=>{if(!I)return console.warn("No animations loaded"),null;let S=null;if(I._genderSpecific){const Z=(e?.toUpperCase()||"F")==="M"?"male":"female",j=I._genderSpecific[Z];j&&j[C]?(S=j[C],console.log(`Using ${Z} animations for "${C}":`,S)):I._genderSpecific.shared&&I._genderSpecific.shared[C]&&(S=I._genderSpecific.shared[C],console.log(`Using shared animations for "${C}":`,S))}if(!S&&I[C]&&(S=I[C],console.log(`Using root-level animations for "${C}":`,S)),!S){if(console.warn(`Animation group "${C}" not found. Available groups:`,Object.keys(I).filter(O=>O!=="_genderSpecific")),I._genderSpecific){const Z=(e?.toUpperCase()||"F")==="M"?"male":"female";console.warn(`Gender-specific groups (${Z}):`,Object.keys(I._genderSpecific[Z]||{}))}return null}if(Array.isArray(S)&&S.length>0){const O=Math.floor(Math.random()*S.length);return S[O]}return typeof S=="string"?S:(console.warn(`Animation group "${C}" is not a valid format (expected array or string):`,S),null)},[I,e]),_=b.useCallback((C,S=!1,O=null)=>{if(!k.current)return console.warn("TalkingHead not initialized yet"),null;const Z=q(C);if(Z)try{const j=()=>{Q.current&&ae.current===C?setTimeout(()=>{_(C,S,O)},100):O&&O()};return k.current.playAnimation(Z,null,10,0,.01,S,j),console.log(`✅ Playing random animation from "${C}" group:`,Z),Z}catch(j){return console.error(`❌ Failed to play random animation from "${C}" group:`,j),null}else console.warn(`⚠️ No animation found for group "${C}"`);return null},[q]),ne=b.useCallback(async(C,S={})=>{if(!k.current||!oe){console.warn("Avatar not ready for speaking");return}if(!C||C.trim()===""){console.warn("No text provided to speak");return}await z();const O=S.animationGroup||g;O&&!S.skipAnimation?(console.log(`🎬 Attempting to play animation from group: "${O}"`),console.log(`📊 Current avatarBody: "${e}", loadedAnimations:`,I),Q.current=!0,ae.current=O,_(O)):console.log(`⏭️ Skipping animation (group: ${O}, skipAnimation: ${S.skipAnimation})`),N.current={remainingText:null,originalText:null,options:null},B.current=[],H.current={text:C,options:S},f.current&&(clearInterval(f.current),f.current=null),R(!1),P.current=!1;const Z=C.split(/[.!?]+/).filter(xe=>xe.trim().length>0);B.current=Z;const j={lipsyncLang:S.lipsyncLang||"en",onSpeechEnd:()=>{f.current&&(clearInterval(f.current),f.current=null),Q.current=!1,ae.current=null,S.onSpeechEnd&&S.onSpeechEnd(),v()}};try{k.current.speakText(C,j)}catch(xe){console.error("Error speaking text:",xe),fe(xe.message||"Failed to speak text")}},[oe,v,z,g,_]);b.useEffect(()=>{if(!oe||!U||!k.current)return;V.current&&clearInterval(V.current);const C=()=>{k.current&&!P.current&&_(U)};return C(),V.current=setInterval(()=>{C()},12e3+Math.random()*3e3),()=>{V.current&&(clearInterval(V.current),V.current=null)}},[oe,U,_]),b.useEffect(()=>{oe&&G&&E&&k.current&&ne(G)},[oe,G,E,ne]);const ye=b.useCallback(()=>{if(k.current)try{const C=k.current.isSpeaking||!1,S=k.current.audioPlaylist||[],O=k.current.speechQueue||[];if(C||S.length>0||O.length>0){f.current&&(clearInterval(f.current),f.current=null);let Z="";O.length>0&&(Z=O.map(j=>j.text&&Array.isArray(j.text)?j.text.map(xe=>xe.word).join(" "):j.text||"").join(" ")),N.current={remainingText:Z||null,originalText:H.current?.text||null,options:H.current?.options||null},k.current.speechQueue.length=0,k.current.pauseSpeaking(),R(!0),P.current=!0}}catch(C){console.warn("Error pausing speech:",C)}},[]),J=b.useCallback(async()=>{if(!(!k.current||!ee))try{await z(),R(!1),P.current=!1;const C=N.current?.remainingText,S=N.current?.originalText||H.current?.text,O=N.current?.options||H.current?.options||{},Z=C||S;Z&&ne(Z,O)}catch(C){console.warn("Error resuming speech:",C),R(!1),P.current=!1}},[ee,ne,z]),de=b.useCallback(()=>{k.current&&(k.current.stopSpeaking(),f.current&&(clearInterval(f.current),f.current=null),Q.current=!1,ae.current=null,R(!1),P.current=!1)},[]);return b.useImperativeHandle(L,()=>({speakText:ne,pauseSpeaking:ye,resumeSpeaking:J,stopSpeaking:de,resumeAudioContext:z,isPaused:()=>ee,setMood:C=>k.current?.setMood(C),setBodyMovement:C=>{k.current&&k.current.setBodyMovement(C)},playAnimation:(C,S=!1)=>{k.current&&k.current.playAnimation&&k.current.playAnimation(C,null,10,0,.01,S)},playRandomAnimation:(C,S=!1)=>_(C,S),getRandomAnimation:C=>q(C),playReaction:C=>k.current?.playReaction(C),playCelebration:()=>k.current?.playCelebration(),setShowFullAvatar:C=>{k.current&&(A.current=C,k.current.setShowFullAvatar(C))},isReady:oe,talkingHead:k.current})),X.jsxs("div",{className:`simple-talking-avatar-container ${y}`,style:w,children:[X.jsx("div",{ref:W,className:"talking-head-viewer",style:{width:"100%",height:"100%",minHeight:"400px"}}),Y&&X.jsx("div",{className:"loading-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"white",fontSize:"18px",zIndex:10},children:"Loading avatar..."}),re&&X.jsx("div",{className:"error-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"#ff6b6b",fontSize:"16px",textAlign:"center",zIndex:10,padding:"20px",borderRadius:"8px"},children:re})]})});Qe.displayName="SimpleTalkingAvatar";const qe=b.forwardRef(({curriculumData:G=null,avatarConfig:t={},animations:e={},onLessonStart:n=()=>{},onLessonComplete:i=()=>{},onQuestionAnswer:s=()=>{},onCurriculumComplete:o=()=>{},onCustomAction:r=()=>{},autoStart:u=!1},a)=>{const c=b.useRef(null),l=b.useRef({currentModuleIndex:0,currentLessonIndex:0,currentQuestionIndex:0,isTeaching:!1,isQuestionMode:!1,lessonCompleted:!1,curriculumCompleted:!1,score:0,totalQuestions:0}),d=b.useRef({onLessonStart:n,onLessonComplete:i,onQuestionAnswer:s,onCurriculumComplete:o,onCustomAction:r}),h=b.useRef(null),p=b.useRef(null),v=b.useRef(null),y=b.useRef(null),w=b.useRef(null),M=b.useRef(null),g=b.useRef(null),U=b.useRef(G?.curriculum||{title:"Default Curriculum",description:"No curriculum data provided",language:"en",modules:[]}),E=b.useRef({avatarUrl:t.avatarUrl||"/avatars/brunette.glb",avatarBody:t.avatarBody||"F",mood:t.mood||"happy",ttsLang:t.ttsLang||"en",ttsService:t.ttsService||null,ttsVoice:t.ttsVoice||null,ttsApiKey:t.ttsApiKey||null,bodyMovement:t.bodyMovement||"gesturing",movementIntensity:t.movementIntensity||.7,showFullAvatar:t.showFullAvatar!==void 0?t.showFullAvatar:!1,animations:e,lipsyncLang:"en"});b.useEffect(()=>{d.current={onLessonStart:n,onLessonComplete:i,onQuestionAnswer:s,onCurriculumComplete:o,onCustomAction:r}},[n,i,s,o,r]),b.useEffect(()=>{U.current=G?.curriculum||{title:"Default Curriculum",description:"No curriculum data provided",language:"en",modules:[]},E.current={avatarUrl:t.avatarUrl||"/avatars/brunette.glb",avatarBody:t.avatarBody||"F",mood:t.mood||"happy",ttsLang:t.ttsLang||"en",ttsService:t.ttsService||null,ttsVoice:t.ttsVoice||null,ttsApiKey:t.ttsApiKey||null,bodyMovement:t.bodyMovement||"gesturing",movementIntensity:t.movementIntensity||.7,showFullAvatar:t.showFullAvatar!==void 0?t.showFullAvatar:!1,animations:e,lipsyncLang:"en"}},[G,t,e]);const L=b.useCallback(()=>(U.current||{modules:[]}).modules[l.current.currentModuleIndex]?.lessons[l.current.currentLessonIndex],[]),W=b.useCallback(()=>L()?.questions[l.current.currentQuestionIndex],[L]),k=b.useCallback((R,I)=>I.type==="multiple_choice"||I.type==="true_false"?R===I.answer:I.type==="code_test"&&typeof R=="object"&&R!==null?R.passed===!0:!1,[]),A=b.useCallback(()=>{l.current.lessonCompleted=!0,l.current.isQuestionMode=!1;const R=l.current.totalQuestions>0?Math.round(l.current.score/l.current.totalQuestions*100):100;let I="Congratulations! You've completed this lesson";if(l.current.totalQuestions>0?I+=` You got ${l.current.score} correct out of ${l.current.totalQuestions} question${l.current.totalQuestions===1?"":"s"}, achieving a score of ${R} percent. `:I+="! ",R>=80?I+="Excellent work! You have a great understanding of this topic.":R>=60?I+="Good job! You understand most of the concepts.":I+="Keep practicing! You're making progress.",d.current.onLessonComplete({moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,score:l.current.score,totalQuestions:l.current.totalQuestions,percentage:R}),d.current.onCustomAction({type:"lessonComplete",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,score:l.current.score,totalQuestions:l.current.totalQuestions,percentage:R}),c.current){if(c.current.setMood("happy"),e.lessonComplete)try{c.current.playAnimation(e.lessonComplete,!0)}catch{c.current.playCelebration()}const F=U.current||{modules:[]},V=F.modules[l.current.currentModuleIndex],Q=l.current.currentLessonIndex<(V?.lessons?.length||0)-1,ae=l.current.currentModuleIndex<(F.modules?.length||0)-1,$=Q||ae,te=E.current||{lipsyncLang:"en"};c.current.speakText(I,{lipsyncLang:te.lipsyncLang,onSpeechEnd:()=>{d.current.onCustomAction({type:"lessonCompleteFeedbackDone",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,score:l.current.score,totalQuestions:l.current.totalQuestions,percentage:R,hasNextLesson:$})}})}},[e.lessonComplete]),H=b.useCallback(()=>{l.current.curriculumCompleted=!0;const R=U.current||{modules:[]};if(d.current.onCurriculumComplete({modules:R.modules.length,totalLessons:R.modules.reduce((I,F)=>I+F.lessons.length,0)}),c.current){if(c.current.setMood("celebrating"),e.curriculumComplete)try{c.current.playAnimation(e.curriculumComplete,!0)}catch{c.current.playCelebration()}const I=E.current||{lipsyncLang:"en"};c.current.speakText("Amazing! You've completed the entire curriculum! You're now ready to move on to more advanced topics. Well done!",{lipsyncLang:I.lipsyncLang})}},[e.curriculumComplete]),f=b.useCallback(()=>{const R=L();l.current.isQuestionMode=!0,l.current.currentQuestionIndex=0,l.current.totalQuestions=R?.questions?.length||0,l.current.score=0;const I=W();I&&d.current.onCustomAction({type:"questionStart",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,questionIndex:l.current.currentQuestionIndex,totalQuestions:l.current.totalQuestions,question:I,score:l.current.score});const F=()=>{if(!c.current||!I)return;if(c.current.setMood("happy"),e.questionStart)try{c.current.playAnimation(e.questionStart,!0)}catch(Q){console.warn("Failed to play questionStart animation:",Q)}const V=E.current||{lipsyncLang:"en"};I.type==="code_test"?c.current.speakText(`Let's test your coding skills! Here's your first challenge: ${I.question}`,{lipsyncLang:V.lipsyncLang}):I.type==="multiple_choice"?c.current.speakText(`Now let me ask you some questions. Here's the first one: ${I.question}`,{lipsyncLang:V.lipsyncLang}):I.type==="true_false"?c.current.speakText(`Let's start with some true or false questions. First question: ${I.question}`,{lipsyncLang:V.lipsyncLang}):c.current.speakText(`Now let me ask you some questions. Here's the first one: ${I.question}`,{lipsyncLang:V.lipsyncLang})};if(c.current&&c.current.isReady&&I)F();else if(c.current&&c.current.isReady){const V=E.current||{lipsyncLang:"en"};c.current.speakText("Now let me ask you some questions to test your understanding.",{lipsyncLang:V.lipsyncLang})}else{const V=setInterval(()=>{c.current&&c.current.isReady&&(clearInterval(V),I&&F())},100);setTimeout(()=>{clearInterval(V)},5e3)}},[e.questionStart,L,W]),P=b.useCallback(()=>{const R=L();if(l.current.currentQuestionIndex<(R?.questions?.length||0)-1){c.current&&c.current.stopSpeaking&&c.current.stopSpeaking(),l.current.currentQuestionIndex+=1;const I=W();I&&d.current.onCustomAction({type:"nextQuestion",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,questionIndex:l.current.currentQuestionIndex,totalQuestions:l.current.totalQuestions,question:I,score:l.current.score});const F=()=>{if(!c.current||!I)return;if(c.current.setMood("happy"),c.current.setBodyMovement("idle"),e.nextQuestion)try{c.current.playAnimation(e.nextQuestion,!0)}catch(te){console.warn("Failed to play nextQuestion animation:",te)}const V=E.current||{lipsyncLang:"en"},ae=L()?.questions?.length||0,$=l.current.currentQuestionIndex>=ae-1;if(I.type==="code_test"){const te=$?`Great! Here's your final coding challenge: ${I.question}`:`Great! Now let's move on to your next coding challenge: ${I.question}`;c.current.speakText(te,{lipsyncLang:V.lipsyncLang})}else if(I.type==="multiple_choice"){const te=$?`Alright! Here's your final question: ${I.question}`:`Alright! Here's your next question: ${I.question}`;c.current.speakText(te,{lipsyncLang:V.lipsyncLang})}else if(I.type==="true_false"){const te=$?`Now let's try this final one: ${I.question}`:`Now let's try this one: ${I.question}`;c.current.speakText(te,{lipsyncLang:V.lipsyncLang})}else{const te=$?`Here's your final question: ${I.question}`:`Here's the next question: ${I.question}`;c.current.speakText(te,{lipsyncLang:V.lipsyncLang})}};if(c.current&&c.current.isReady&&I)F();else if(I){const V=setInterval(()=>{c.current&&c.current.isReady&&(clearInterval(V),F())},100);setTimeout(()=>{clearInterval(V)},5e3)}}else d.current.onCustomAction({type:"allQuestionsComplete",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,totalQuestions:l.current.totalQuestions,score:l.current.score})},[e.nextQuestion,L,W]),N=b.useCallback(()=>{const R=U.current||{modules:[]},I=R.modules[l.current.currentModuleIndex];if(l.current.currentLessonIndex<(I?.lessons?.length||0)-1){l.current.currentLessonIndex+=1,l.current.currentQuestionIndex=0,l.current.lessonCompleted=!1,l.current.isQuestionMode=!1,l.current.isTeaching=!1,l.current.score=0,l.current.totalQuestions=0;const V=R.modules[l.current.currentModuleIndex],Q=l.current.currentLessonIndex<(V?.lessons?.length||0)-1,ae=l.current.currentModuleIndex<(R.modules?.length||0)-1,$=Q||ae;d.current.onCustomAction({type:"lessonStart",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,hasNextLesson:$}),d.current.onLessonStart({moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,lesson:L()}),c.current&&(c.current.setMood("happy"),c.current.setBodyMovement("idle"))}else if(l.current.currentModuleIndex<(R.modules?.length||0)-1){l.current.currentModuleIndex+=1,l.current.currentLessonIndex=0,l.current.currentQuestionIndex=0,l.current.lessonCompleted=!1,l.current.isQuestionMode=!1,l.current.isTeaching=!1,l.current.score=0,l.current.totalQuestions=0;const Q=R.modules[l.current.currentModuleIndex],ae=l.current.currentLessonIndex<(Q?.lessons?.length||0)-1,$=l.current.currentModuleIndex<(R.modules?.length||0)-1,te=ae||$;d.current.onCustomAction({type:"lessonStart",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,hasNextLesson:te}),d.current.onLessonStart({moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,lesson:L()}),c.current&&(c.current.setMood("happy"),c.current.setBodyMovement("idle"))}else w.current&&w.current()},[]),B=b.useCallback(()=>{const R=L();let I=null;if(R?.avatar_script&&R?.body){const F=R.avatar_script.trim(),V=R.body.trim(),Q=F.match(/[.!?]$/)?" ":". ";I=`${F}${Q}${V}`}else I=R?.avatar_script||R?.body||null;if(c.current&&c.current.isReady&&I){l.current.isTeaching=!0,l.current.isQuestionMode=!1,l.current.score=0,l.current.totalQuestions=0,c.current.setMood("happy");let F=!1;if(e.teaching)try{c.current.playAnimation(e.teaching,!0),F=!0}catch(Q){console.warn("Failed to play teaching animation:",Q)}F||c.current.setBodyMovement("gesturing");const V=E.current||{lipsyncLang:"en"};d.current.onLessonStart({moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,lesson:R}),d.current.onCustomAction({type:"teachingStart",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,lesson:R}),c.current.speakText(I,{lipsyncLang:V.lipsyncLang,onSpeechEnd:()=>{l.current.isTeaching=!1,d.current.onCustomAction({type:"teachingComplete",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,lesson:R,hasQuestions:R.questions&&R.questions.length>0}),R?.code_example&&d.current.onCustomAction({type:"codeExampleReady",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,lesson:R,codeExample:R.code_example})}})}},[e.teaching,L]),Y=b.useCallback(R=>{const I=W(),F=k(R,I);if(F&&(l.current.score+=1),d.current.onQuestionAnswer({moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,questionIndex:l.current.currentQuestionIndex,answer:R,isCorrect:F,question:I}),c.current)if(F){if(c.current.setMood("happy"),e.correct)try{c.current.playReaction("happy")}catch{c.current.setBodyMovement("happy")}c.current.setBodyMovement("gesturing");const Q=L()?.questions?.length||0;l.current.currentQuestionIndex>=Q-1;const ae=l.current.currentQuestionIndex<Q-1;console.log("[CurriculumLearning] Answer feedback - questionIndex:",l.current.currentQuestionIndex,"totalQuestions:",Q,"hasNextQuestion:",ae);const $=I.type==="code_test"?`Great job! Your code passed all the tests! ${I.explanation||""}`:`Excellent! That's correct! ${I.explanation||""}`,te=E.current||{lipsyncLang:"en"};c.current.speakText($,{lipsyncLang:te.lipsyncLang,onSpeechEnd:()=>{d.current.onCustomAction({type:"answerFeedbackComplete",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,questionIndex:l.current.currentQuestionIndex,isCorrect:!0,hasNextQuestion:ae,score:l.current.score,totalQuestions:l.current.totalQuestions})}})}else{if(c.current.setMood("sad"),e.incorrect)try{c.current.playAnimation(e.incorrect,!0)}catch{c.current.setBodyMovement("idle")}c.current.setBodyMovement("gesturing");const Q=L()?.questions?.length||0,ae=l.current.currentQuestionIndex>=Q-1,$=l.current.currentQuestionIndex<Q-1;console.log("[CurriculumLearning] Answer feedback (incorrect) - questionIndex:",l.current.currentQuestionIndex,"totalQuestions:",Q,"hasNextQuestion:",$);const te=I.type==="code_test"?`Your code didn't pass all the tests. ${I.explanation||"Try again!"}`:`Not quite right, but don't worry! ${I.explanation||""}${ae?"":" Let's move on to the next question."}`,pe=E.current||{lipsyncLang:"en"};c.current.speakText(te,{lipsyncLang:pe.lipsyncLang,onSpeechEnd:()=>{d.current.onCustomAction({type:"answerFeedbackComplete",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,questionIndex:l.current.currentQuestionIndex,isCorrect:!1,hasNextQuestion:$,score:l.current.score,totalQuestions:l.current.totalQuestions})}})}else{const Q=L()?.questions?.length||0;d.current.onCustomAction({type:"answerFeedbackComplete",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,questionIndex:l.current.currentQuestionIndex,isCorrect:F,hasNextQuestion:l.current.currentQuestionIndex<Q-1,score:l.current.score,totalQuestions:l.current.totalQuestions,avatarNotReady:!0})}},[e.correct,e.incorrect,W,L,k]),se=b.useCallback(R=>{const I=W();if(!R||typeof R!="object"){console.error("Invalid code test result format. Expected object with {passed: boolean, ...}");return}if(I?.type!=="code_test"){console.warn("Current question is not a code test. Use handleAnswerSelect for other question types.");return}const F={passed:R.passed===!0,results:R.results||[],output:R.output||"",error:R.error||null,executionTime:R.executionTime||null,testCount:R.testCount||0,passedCount:R.passedCount||0,failedCount:R.failedCount||0};d.current.onCustomAction({type:"codeTestSubmitted",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,questionIndex:l.current.currentQuestionIndex,testResult:F,question:I}),g.current&&g.current(F)},[W,k]),re=b.useCallback(()=>{if(l.current.currentQuestionIndex>0){l.current.currentQuestionIndex-=1;const R=W();R&&d.current.onCustomAction({type:"questionStart",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,questionIndex:l.current.currentQuestionIndex,totalQuestions:l.current.totalQuestions,question:R,score:l.current.score});const I=()=>{if(!c.current||!R)return;c.current.setMood("happy"),c.current.setBodyMovement("idle");const F=E.current||{lipsyncLang:"en"};R.type==="code_test"?c.current.speakText(`Let's go back to this coding challenge: ${R.question}`,{lipsyncLang:F.lipsyncLang}):c.current.speakText(`Going back to: ${R.question}`,{lipsyncLang:F.lipsyncLang})};if(c.current&&c.current.isReady&&R)I();else if(R){const F=setInterval(()=>{c.current&&c.current.isReady&&(clearInterval(F),I())},100);setTimeout(()=>{clearInterval(F)},5e3)}}},[W]),fe=b.useCallback(()=>{const R=U.current||{modules:[]};if(R.modules[l.current.currentModuleIndex],l.current.currentLessonIndex>0)l.current.currentLessonIndex-=1,l.current.currentQuestionIndex=0,l.current.lessonCompleted=!1,l.current.isQuestionMode=!1,l.current.isTeaching=!1,l.current.score=0,l.current.totalQuestions=0,d.current.onCustomAction({type:"lessonStart",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex}),d.current.onLessonStart({moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,lesson:L()}),c.current&&(c.current.setMood("happy"),c.current.setBodyMovement("idle"));else if(l.current.currentModuleIndex>0){const V=R.modules[l.current.currentModuleIndex-1];l.current.currentModuleIndex-=1,l.current.currentLessonIndex=(V?.lessons?.length||1)-1,l.current.currentQuestionIndex=0,l.current.lessonCompleted=!1,l.current.isQuestionMode=!1,l.current.isTeaching=!1,l.current.score=0,l.current.totalQuestions=0,d.current.onCustomAction({type:"lessonStart",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex}),d.current.onLessonStart({moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,lesson:L()}),c.current&&(c.current.setMood("happy"),c.current.setBodyMovement("idle"))}},[L]),oe=b.useCallback(()=>{l.current.currentModuleIndex=0,l.current.currentLessonIndex=0,l.current.currentQuestionIndex=0,l.current.isTeaching=!1,l.current.isQuestionMode=!1,l.current.lessonCompleted=!1,l.current.curriculumCompleted=!1,l.current.score=0,l.current.totalQuestions=0},[]),Re=b.useCallback(R=>{console.log("Avatar is ready!",R);const I=L(),F=I?.avatar_script||I?.body;u&&F&&setTimeout(()=>{h.current&&h.current()},10)},[u,L]);b.useLayoutEffect(()=>{h.current=B,p.current=N,v.current=A,y.current=P,w.current=H,M.current=f,g.current=Y}),b.useImperativeHandle(a,()=>({startTeaching:B,startQuestions:f,handleAnswerSelect:Y,handleCodeTestResult:se,nextQuestion:P,previousQuestion:re,nextLesson:N,previousLesson:fe,completeLesson:A,completeCurriculum:H,resetCurriculum:oe,getState:()=>({...l.current}),getCurrentQuestion:()=>W(),getCurrentLesson:()=>L(),getAvatarRef:()=>c.current,speakText:async(R,I={})=>{await c.current?.resumeAudioContext?.();const F=E.current||{lipsyncLang:"en"};c.current?.speakText(R,{...I,lipsyncLang:I.lipsyncLang||F.lipsyncLang})},resumeAudioContext:async()=>{if(c.current?.resumeAudioContext)return await c.current.resumeAudioContext();const R=c.current?.talkingHead;if(R?.audioCtx){const I=R.audioCtx;if(I.state==="suspended"||I.state==="interrupted")try{await I.resume(),console.log("Audio context resumed via talkingHead")}catch(F){console.warn("Failed to resume audio context:",F)}}else console.warn("Audio context not available yet")},stopSpeaking:()=>c.current?.stopSpeaking(),pauseSpeaking:()=>c.current?.pauseSpeaking(),resumeSpeaking:async()=>await c.current?.resumeSpeaking(),isPaused:()=>c.current&&typeof c.current.isPaused<"u"?c.current.isPaused:!1,setMood:R=>c.current?.setMood(R),playAnimation:(R,I)=>c.current?.playAnimation(R,I),setBodyMovement:R=>c.current?.setBodyMovement(R),setMovementIntensity:R=>c.current?.setMovementIntensity(R),playRandomDance:()=>c.current?.playRandomDance(),playReaction:R=>c.current?.playReaction(R),playCelebration:()=>c.current?.playCelebration(),setShowFullAvatar:R=>c.current?.setShowFullAvatar(R),setTimingAdjustment:R=>c.current?.setTimingAdjustment(R),lockAvatarPosition:()=>c.current?.lockAvatarPosition(),unlockAvatarPosition:()=>c.current?.unlockAvatarPosition(),triggerCustomAction:(R,I)=>{d.current.onCustomAction({type:R,...I,state:{...l.current}})},handleResize:()=>c.current?.handleResize(),isAvatarReady:()=>c.current?.isReady||!1}),[B,f,Y,se,P,N,A,H,oe,W,L]);const ee=E.current||{avatarUrl:"/avatars/brunette.glb",avatarBody:"F",mood:"happy",ttsLang:"en",ttsService:null,ttsVoice:null,ttsApiKey:null,bodyMovement:"gesturing",movementIntensity:.7,showFullAvatar:!1,animations:e};return X.jsx("div",{style:{width:"100%",height:"100%"},children:X.jsx(Ue,{ref:c,avatarUrl:ee.avatarUrl,avatarBody:ee.avatarBody,mood:ee.mood,ttsLang:ee.ttsLang,ttsService:ee.ttsService,ttsVoice:ee.ttsVoice,ttsApiKey:ee.ttsApiKey,bodyMovement:ee.bodyMovement,movementIntensity:ee.movementIntensity,showFullAvatar:ee.showFullAvatar,cameraView:"upper",animations:ee.animations,onReady:Re,onLoading:()=>{},onError:R=>{console.error("Avatar error:",R)}})})});qe.displayName="CurriculumLearning";function It({manifestPath:G="/animations/manifest.json",avatarBody:t="F",onAnimationPlay:e=null,onAnimationsSelected:n=null,onDeleteAnimations:i=null,style:s={}}){const[o,r]=b.useState([]),[u,a]=b.useState(new Set),[c,l]=b.useState(!0),[d,h]=b.useState(null),[p,v]=b.useState("all"),[y,w]=b.useState("");b.useEffect(()=>{(async()=>{l(!0),h(null);try{const H=await Ce(G),f=[];if(H._genderSpecific){const N=(t?.toUpperCase()||"F")==="M"?"male":"female";H._genderSpecific[N]&&Object.entries(H._genderSpecific[N]).forEach(([B,Y])=>{(Array.isArray(Y)?Y:[Y]).forEach(re=>{f.push({path:re,group:B,gender:N,name:re.split("/").pop().replace(".fbx","")})})}),H._genderSpecific.shared&&Object.entries(H._genderSpecific.shared).forEach(([B,Y])=>{(Array.isArray(Y)?Y:[Y]).forEach(re=>{f.push({path:re,group:B,gender:"shared",name:re.split("/").pop().replace(".fbx","")})})})}Object.entries(H).forEach(([P,N])=>{P!=="_genderSpecific"&&(Array.isArray(N)?N:[N]).forEach(Y=>{typeof Y=="string"&&f.push({path:Y,group:P,gender:"root",name:Y.split("/").pop().replace(".fbx","")})})}),r(f),l(!1)}catch(H){console.error("Failed to load animations:",H),h(H.message),l(!1)}})()},[G,t]);const M=["all",...new Set(o.map(A=>A.group))],g=o.filter(A=>{const H=p==="all"||A.group===p,f=y===""||A.name.toLowerCase().includes(y.toLowerCase())||A.path.toLowerCase().includes(y.toLowerCase());return H&&f}),U=A=>{const H=new Set(u);H.has(A)?H.delete(A):H.add(A),a(H),n&&n(Array.from(H))},E=()=>{const A=new Set(u);g.forEach(H=>{A.add(H.path)}),a(A),n&&n(Array.from(A))},L=()=>{const A=new Set(u);g.forEach(H=>{A.delete(H.path)}),a(A),n&&n(Array.from(A))},W=()=>{const H=o.filter(f=>!u.has(f.path)).map(f=>f.path);if(H.length===0){alert("No animations to delete. Select animations to keep, then delete will remove the unselected ones.");return}window.confirm(`Are you sure you want to delete ${H.length} animation(s)?
7
+ `,s=await fetch(this.opt.ttsEndpoint,{method:"POST",headers:{"Ocp-Apim-Subscription-Key":this.opt.ttsApikey,"Content-Type":"application/ssml+xml","X-Microsoft-OutputFormat":"audio-16khz-128kbitrate-mono-mp3"},body:o});if(!s.ok)throw new Error(`Azure TTS error: ${s.status} ${s.statusText}`);const i=await s.arrayBuffer(),r=await this.audioCtx.decodeAudioData(i),c=await this.audioAnalyzer.analyzeAudio(r,e),l=[];for(let a=0;a<c.visemes.length;a++){const d=c.visemes[a],h=d.startTime*1e3,g=d.duration*1e3,v=d.intensity;l.push({template:{name:"viseme"},ts:[h-Math.min(60,2*g/3),h+Math.min(25,g/2),h+g+Math.min(60,g/2)],vs:{["viseme_"+d.viseme]:[null,v,0]}})}const u=[...t.anim,...l];this.audioPlaylist.push({anim:u,audio:r}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio()}async synthesizeWithExternalTTS(t){let e="<speak>";t.text.forEach((i,r)=>{r>0&&(e+=" <mark name='"+i.mark+"'/>"),e+=i.word.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;").replace(new RegExp("^\\p{Dash_Punctuation}$","ug"),'<break time="750ms"/>')}),e+="</speak>";const n={method:"POST",headers:{"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify({input:{ssml:e},voice:{languageCode:t.lang||this.avatar.ttsLang||this.opt.ttsLang,name:t.voice||this.avatar.ttsVoice||this.opt.ttsVoice},audioConfig:{audioEncoding:this.ttsAudioEncoding,speakingRate:(t.rate||this.avatar.ttsRate||this.opt.ttsRate)+this.mood.speech.deltaRate,pitch:(t.pitch||this.avatar.ttsPitch||this.opt.ttsPitch)+this.mood.speech.deltaPitch,volumeGainDb:(t.volume||this.avatar.ttsVolume||this.opt.ttsVolume)+this.mood.speech.deltaVolume},enableTimePointing:[1]})};this.opt.jwtGet&&typeof this.opt.jwtGet=="function"&&(n.headers.Authorization="Bearer "+await this.opt.jwtGet());const o=await fetch(this.opt.ttsEndpoint+(this.opt.ttsApikey?"?key="+this.opt.ttsApikey:""),n),s=await o.json();if(o.status===200&&s&&s.audioContent){const i=this.b64ToArrayBuffer(s.audioContent),r=await this.audioCtx.decodeAudioData(i);this.speakWithHands();const c=[0];let l=0;t.text.forEach((d,h)=>{if(h>0){let g=c[c.length-1];s.timepoints[l]&&(g=s.timepoints[l].timeSeconds*1e3,s.timepoints[l].markName===""+d.mark&&l++),c.push(g)}});const u=[{mark:0,time:0}];c.forEach((d,h)=>{if(h>0){let g=d-c[h-1];u[h-1].duration=g,u.push({mark:h,time:d})}});let a=1e3*r.duration;a>this.opt.ttsTrimEnd&&(a=a-this.opt.ttsTrimEnd),u[u.length-1].duration=a-u[u.length-1].time,t.anim.forEach(d=>{const h=u[d.mark];if(h)for(let g=0;g<d.ts.length;g++)d.ts[g]=h.time+d.ts[g]*h.duration+this.opt.ttsTrimStart}),this.audioPlaylist.push({anim:t.anim,audio:r}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio()}else this.startSpeaking(!0)}async startSpeaking(t=!1){if(!(!this.armature||this.isSpeaking&&!t))if(this.stateName="speaking",this.isSpeaking=!0,this.speechQueue.length){let e=this.speechQueue.shift();if(e.emoji){this.lookAtCamera(500);let n=e.emoji.dt.reduce((o,s)=>o+s,0);this.animQueue.push(this.animFactory(e.emoji)),setTimeout(this.startSpeaking.bind(this),n,!0)}else if(e.break)setTimeout(this.startSpeaking.bind(this),e.break,!0);else if(e.audio)e.isRaw||(this.lookAtCamera(500),this.speakWithHands(),this.resetLips()),this.audioPlaylist.push({anim:e.anim,audio:e.audio,isRaw:e.isRaw}),this.onSubtitles=e.onSubtitles||null,e.mood&&this.setMood(e.mood),this.playAudio();else if(e.text){this.lookAtCamera(500);try{!this.opt.ttsEndpoint||this.opt.ttsEndpoint===""?await this.synthesizeWithBrowserTTS(e):this.opt.ttsService==="elevenlabs"?await this.synthesizeWithElevenLabsTTS(e):this.opt.ttsService==="deepgram"?await this.synthesizeWithDeepgramTTS(e):this.opt.ttsService==="azure"?await this.synthesizeWithAzureTTS(e):await this.synthesizeWithExternalTTS(e)}catch(n){console.error("Error:",n),this.startSpeaking(!0)}}else e.anim?(this.onSubtitles=e.onSubtitles||null,this.resetLips(),e.mood&&this.setMood(e.mood),e.anim.forEach((n,o)=>{for(let s=0;s<n.ts.length;s++)n.ts[s]=this.animClock+10*o;this.animQueue.push(n)}),setTimeout(this.startSpeaking.bind(this),10*e.anim.length,!0)):e.marker?(typeof e.marker=="function"&&e.marker(),this.startSpeaking(!0)):this.startSpeaking(!0)}else this.stateName="idle",this.isSpeaking=!1}pauseSpeaking(){try{this.audioSpeechSource.stop()}catch{}this.audioPlaylist.length=0,this.stateName="idle",this.isSpeaking=!1,this.isAudioPlaying=!1,this.animQueue=this.animQueue.filter(t=>t.template.name!=="viseme"&&t.template.name!=="subtitles"&&t.template.name!=="blendshapes"),this.armature&&(this.resetLips(),this.render())}stopSpeaking(){try{this.audioSpeechSource.stop()}catch{}this.audioPlaylist.length=0,this.speechQueue.length=0,this.animQueue=this.animQueue.filter(t=>t.template.name!=="viseme"&&t.template.name!=="subtitles"&&t.template.name!=="blendshapes"),this.stateName="idle",this.isSpeaking=!1,this.isAudioPlaying=!1,this.armature&&(this.resetLips(),this.render())}async streamStart(t={},e=null,n=null,o=null,s=null){if(this.stopSpeaking(),this.isStreaming=!0,t.waitForAudioChunks!==void 0&&(this.streamWaitForAudioChunks=t.waitForAudioChunks),this.streamWaitForAudioChunks||(this.streamAudioStartTime=this.animClock),this.streamLipsyncQueue=[],this.streamLipsyncType=t.lipsyncType||this.streamLipsyncType||"visemes",this.streamLipsyncLang=t.lipsyncLang||this.streamLipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang,this.onAudioStart=e,this.onAudioEnd=n,this.onMetrics=s,t.sampleRate!==void 0){const r=t.sampleRate;typeof r=="number"&&r>=8e3&&r<=96e3?r!==this.audioCtx.sampleRate&&this.initAudioGraph(r):console.warn("Invalid sampleRate provided. It must be a number between 8000 and 96000 Hz.")}if(t.gain!==void 0&&(this.audioStreamGainNode.gain.value=t.gain),!this.streamWorkletNode||!this.streamWorkletNode.port||this.streamWorkletNode.numberOfOutputs===0||this.streamWorkletNode.context!==this.audioCtx){if(this.streamWorkletNode)try{this.streamWorkletNode.disconnect(),this.streamWorkletNode=null}catch{}if(!this.workletLoaded)try{const r=this.audioCtx.audioWorklet.addModule(Rt.href),c=new Promise((l,u)=>setTimeout(()=>u(new Error("Worklet loading timed out")),5e3));await Promise.race([r,c]),this.workletLoaded=!0}catch(r){throw console.error("Failed to load audio worklet:",r),new Error("Failed to initialize streaming speech")}this.streamWorkletNode=new AudioWorkletNode(this.audioCtx,"playback-worklet",{processorOptions:{sampleRate:this.audioCtx.sampleRate,metrics:t.metrics||{enabled:!1}}}),this.streamWorkletNode.connect(this.audioStreamGainNode),this.streamWorkletNode.connect(this.audioAnalyzerNode),this.streamWorkletNode.port.onmessage=r=>{if(r.data.type==="playback-started"&&(this.isSpeaking=!0,this.stateName="speaking",this.streamWaitForAudioChunks&&(this.streamAudioStartTime=this.animClock),this._processStreamLipsyncQueue(),this.speakWithHands(),this.onAudioStart))try{this.onAudioStart?.()}catch(c){console.error(c)}if(r.data.type==="playback-ended"&&(this._streamPause(),this.onAudioEnd))try{this.onAudioEnd()}catch{}if(this.onMetrics&&r.data.type==="metrics")try{this.onMetrics(r.data)}catch{}}}if(t.metrics)try{this.streamWorkletNode.port.postMessage({type:"config-metrics",data:t.metrics})}catch{}if(this.resetLips(),this.lookAtCamera(500),t.mood&&this.setMood(t.mood),this.onSubtitles=o||null,this.audioCtx.state==="suspended"||this.audioCtx.state==="interrupted"){const r=this.audioCtx.resume(),c=new Promise((l,u)=>setTimeout(()=>u("p2"),1e3));try{await Promise.race([r,c])}catch{console.warn("Can't play audio. Web Audio API suspended. This is often due to calling some speak method before the first user action, which is typically prevented by the browser.");return}}}streamNotifyEnd(){!this.isStreaming||!this.streamWorkletNode||this.streamWorkletNode.port.postMessage({type:"no-more-data"})}streamInterrupt(){if(!this.isStreaming)return;const t=this.isSpeaking;if(this.streamWorkletNode)try{this.streamWorkletNode.port.postMessage({type:"stop"})}catch{}if(this._streamPause(!0),t&&this.onAudioEnd)try{this.onAudioEnd()}catch{}}streamStop(){if(this.isStreaming){if(this.streamInterrupt(),this.streamWorkletNode){try{this.streamWorkletNode.disconnect()}catch{}this.streamWorkletNode=null}this.isStreaming=!1}}_streamPause(t=!1){this.isSpeaking=!1,this.stateName="idle",t&&(this.streamWaitForAudioChunks&&(this.streamAudioStartTime=null),this.streamLipsyncQueue=[],this.animQueue=this.animQueue.filter(e=>e.template.name!=="viseme"&&e.template.name!=="subtitles"&&e.template.name!=="blendshapes"),this.armature&&(this.resetLips(),this.render()))}_processStreamLipsyncQueue(){if(this.isStreaming)for(;this.streamLipsyncQueue.length>0;){const t=this.streamLipsyncQueue.shift();this._processLipsyncData(t,this.streamAudioStartTime)}}_processLipsyncData(t,e){if(this.isStreaming){if(t.visemes&&this.streamLipsyncType=="visemes")for(let n=0;n<t.visemes.length;n++){const o=t.visemes[n],s=e+t.vtimes[n],i=t.vdurations[n],r={template:{name:"viseme"},ts:[s-2*i/3,s+i/2,s+i+i/2],vs:{["viseme_"+o]:[null,o==="PP"||o==="FF"?.9:.6,0]}};this.animQueue.push(r)}if(t.words&&(this.onSubtitles||this.streamLipsyncType=="words"))for(let n=0;n<t.words.length;n++){const o=t.words[n],s=t.wtimes[n];let i=t.wdurations[n];if(o.length&&(this.onSubtitles&&this.animQueue.push({template:{name:"subtitles"},ts:[e+s],vs:{subtitles:[" "+o]}}),this.streamLipsyncType=="words")){const r=this.streamLipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang,c=this.lipsyncPreProcessText(o,r),l=this.lipsyncWordsToVisemes(c,r);if(l&&l.visemes&&l.visemes.length){const u=l.times[l.visemes.length-1]+l.durations[l.visemes.length-1],a=Math.min(i,Math.max(0,i-l.visemes.length*150));let d=.6+this.convertRange(a,[0,i],[0,.4]);if(i=Math.min(i,l.visemes.length*200),u>0)for(let h=0;h<l.visemes.length;h++){const g=e+s+l.times[h]/u*i,v=l.durations[h]/u*i;this.animQueue.push({template:{name:"viseme"},ts:[g-Math.min(60,2*v/3),g+Math.min(25,v/2),g+v+Math.min(60,v/2)],vs:{["viseme_"+l.visemes[h]]:[null,l.visemes[h]==="PP"||l.visemes[h]==="FF"?.9:d,0]}})}}}}if(t.anims&&this.streamLipsyncType=="blendshapes")for(let n=0;n<t.anims.length;n++){let o=t.anims[n];o.delay+=e;let s=this.animFactory(o,!1,1,1,!0);this.animQueue.push(s)}}}streamAudio(t){if(!(!this.isStreaming||!this.streamWorkletNode)){if(this.isSpeaking||(this.streamLipsyncQueue=[],this.streamAudioStartTime=null),this.isSpeaking=!0,this.stateName="speaking",t.audio!==void 0){const e={type:"audioData",data:null};if(t.audio instanceof ArrayBuffer)e.data=t.audio,this.streamWorkletNode.port.postMessage(e,[e.data]);else if(t.audio instanceof Int16Array||t.audio instanceof Uint8Array){const n=t.audio.buffer.slice(t.audio.byteOffset,t.audio.byteOffset+t.audio.byteLength);e.data=n,this.streamWorkletNode.port.postMessage(e,[e.data])}else if(t.audio instanceof Float32Array){const n=new Int16Array(t.audio.length);for(let o=0;o<t.audio.length;o++){let s=Math.max(-1,Math.min(1,t.audio[o]));n[o]=s<0?s*32768:s*32767}e.data=n.buffer,this.streamWorkletNode.port.postMessage(e,[e.data])}else console.error("r.audio is not a supported type. Must be ArrayBuffer, Int16Array, Uint8Array, or Float32Array:",t.audio)}if(t.visemes||t.anims||t.words){if(this.streamWaitForAudioChunks&&!this.streamAudioStartTime){this.streamLipsyncQueue.length>=200&&this.streamLipsyncQueue.shift(),this.streamLipsyncQueue.push(t);return}else!this.streamWaitForAudioChunks&&!this.streamAudioStartTime&&(this.streamAudioStartTime=this.animClock);this._processLipsyncData(t,this.streamAudioStartTime)}}}makeEyeContact(t){this.animQueue.push(this.animFactory({name:"eyecontact",dt:[0,t],vs:{eyeContact:[1]}}))}lookAhead(t){if(t){let e=(Math.random()-.5)/4,n=(Math.random()-.5)/4,o=this.animQueue.findIndex(i=>i.template.name==="lookat");o!==-1&&this.animQueue.splice(o,1);const s={name:"lookat",dt:[750,t],vs:{bodyRotateX:[e],bodyRotateY:[n],eyesRotateX:[-3*e+.1],eyesRotateY:[-5*n],browInnerUp:[[0,.7]],mouthLeft:[[0,.7]],mouthRight:[[0,.7]],eyeContact:[0],headMove:[0]}};this.animQueue.push(this.animFactory(s))}}lookAtCamera(t){let e;if(this.speakTo&&(e=new f.Vector3,this.speakTo.objectLeftEye?.isObject3D?(this.speakTo.armature.objectHead,this.speakTo.objectLeftEye.updateMatrixWorld(!0),this.speakTo.objectRightEye.updateMatrixWorld(!0),Ie.setFromMatrixPosition(this.speakTo.objectLeftEye.matrixWorld),Le.setFromMatrixPosition(this.speakTo.objectRightEye.matrixWorld),e.addVectors(Ie,Le).divideScalar(2)):this.speakTo.isObject3D?this.speakTo.getWorldPosition(e):this.speakTo.isVector3?e.set(this.speakTo):this.speakTo.x&&this.speakTo.y&&this.speakTo.z&&e.set(this.speakTo.x,this.speakTo.y,this.speakTo.z)),!e){if(this.avatar.hasOwnProperty("avatarIgnoreCamera")){if(this.avatar.avatarIgnoreCamera){this.lookAhead(t);return}}else if(this.opt.avatarIgnoreCamera){this.lookAhead(t);return}this.lookAt(null,null,t);return}this.objectLeftEye.updateMatrixWorld(!0),this.objectRightEye.updateMatrixWorld(!0),Ie.setFromMatrixPosition(this.objectLeftEye.matrixWorld),Le.setFromMatrixPosition(this.objectRightEye.matrixWorld),Ie.add(Le).divideScalar(2),ie.copy(this.armature.quaternion),ie.multiply(this.poseTarget.props["Hips.quaternion"]),ie.multiply(this.poseTarget.props["Spine.quaternion"]),ie.multiply(this.poseTarget.props["Spine1.quaternion"]),ie.multiply(this.poseTarget.props["Spine2.quaternion"]),ie.multiply(this.poseTarget.props["Neck.quaternion"]),ie.multiply(this.poseTarget.props["Head.quaternion"]);const n=new f.Vector3().subVectors(e,Ie).normalize(),o=Math.atan2(n.x,n.z),s=Math.asin(-n.y);_.set(s,o,0,"YXZ");const r=new f.Quaternion().setFromEuler(_),c=new f.Quaternion().copy(r).multiply(ie.clone().invert());_.setFromQuaternion(c,"YXZ");let l=_.x/(40/24)+.2,u=_.y/(9/4),a=Math.min(.6,Math.max(-.3,l)),d=Math.min(.8,Math.max(-.8,u)),h=(Math.random()-.5)/4,g=(Math.random()-.5)/4;if(t){let v=this.animQueue.findIndex(S=>S.template.name==="lookat");v!==-1&&this.animQueue.splice(v,1);const b={name:"lookat",dt:[750,t],vs:{bodyRotateX:[a+h],bodyRotateY:[d+g],eyesRotateX:[-3*h+.1],eyesRotateY:[-5*g],browInnerUp:[[0,.7]],mouthLeft:[[0,.7]],mouthRight:[[0,.7]],eyeContact:[0],headMove:[0]}};this.animQueue.push(this.animFactory(b))}}lookAt(t,e,n){if(!this.camera)return;const o=this.nodeAvatar.getBoundingClientRect();this.objectLeftEye.updateMatrixWorld(!0),this.objectRightEye.updateMatrixWorld(!0);const s=new f.Vector3().setFromMatrixPosition(this.objectLeftEye.matrixWorld),i=new f.Vector3().setFromMatrixPosition(this.objectRightEye.matrixWorld),r=new f.Vector3().addVectors(s,i).divideScalar(2);r.project(this.camera);let c=(r.x+1)/2*o.width+o.left,l=-(r.y-1)/2*o.height+o.top;t===null&&(t=c),e===null&&(e=l),ie.copy(this.armature.quaternion),ie.multiply(this.poseTarget.props["Hips.quaternion"]),ie.multiply(this.poseTarget.props["Spine.quaternion"]),ie.multiply(this.poseTarget.props["Spine1.quaternion"]),ie.multiply(this.poseTarget.props["Spine2.quaternion"]),ie.multiply(this.poseTarget.props["Neck.quaternion"]),ie.multiply(this.poseTarget.props["Head.quaternion"]),_.setFromQuaternion(ie);let u=_.x/(40/24),a=_.y/(9/4),d=Math.min(.4,Math.max(-.4,this.camera.rotation.x)),h=Math.min(.4,Math.max(-.4,this.camera.rotation.y)),g=Math.max(window.innerWidth-c,c),v=Math.max(window.innerHeight-l,l),b=this.convertRange(e,[l-v,l+v],[-.3,.6])-u+d,S=this.convertRange(t,[c-g,c+g],[-.8,.8])-a+h;b=Math.min(.6,Math.max(-.3,b)),S=Math.min(.8,Math.max(-.8,S));let M=(Math.random()-.5)/4,p=(Math.random()-.5)/4;if(n){let O=this.animQueue.findIndex(y=>y.template.name==="lookat");O!==-1&&this.animQueue.splice(O,1);const P={name:"lookat",dt:[750,n],vs:{bodyRotateX:[b+M],bodyRotateY:[S+p],eyesRotateX:[-3*M+.1],eyesRotateY:[-5*p],browInnerUp:[[0,.7]],mouthLeft:[[0,.7]],mouthRight:[[0,.7]],eyeContact:[0],headMove:[0]}};this.animQueue.push(this.animFactory(P))}}touchAt(t,e){if(!this.camera)return;const n=this.nodeAvatar.getBoundingClientRect(),o=new f.Vector2((t-n.left)/n.width*2-1,-((e-n.top)/n.height)*2+1),s=new f.Raycaster;s.setFromCamera(o,this.camera);const i=s.intersectObject(this.armature);if(i.length>0){const r=i[0].point,c=new f.Vector3,l=new f.Vector3;this.objectLeftArm.getWorldPosition(c),this.objectRightArm.getWorldPosition(l);const u=c.distanceToSquared(r),a=l.distanceToSquared(r);u<a?(this.ikSolve({iterations:20,root:"LeftShoulder",effector:"LeftHandMiddle1",links:[{link:"LeftHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5,maxAngle:.1},{link:"LeftForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-.5,maxz:3,maxAngle:.2},{link:"LeftArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},r,!1,1e3),this.setValue("handFistLeft",0)):(this.ikSolve({iterations:20,root:"RightShoulder",effector:"RightHandMiddle1",links:[{link:"RightHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5,maxAngle:.1},{link:"RightForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-3,maxz:.5,maxAngle:.2},{link:"RightArm",minx:-1.5,maxx:1.5,miny:0,maxy:0,minz:-1,maxz:3}]},r,!1,1e3),this.setValue("handFistRight",0))}else["LeftArm","LeftForeArm","LeftHand","RightArm","RightForeArm","RightHand"].forEach(r=>{let c=r+".quaternion";this.poseTarget.props[c].copy(this.getPoseTemplateProp(c)),this.poseTarget.props[c].t=this.animClock,this.poseTarget.props[c].d=1e3});return i.length>0}speakWithHands(t=0,e=.5){if(this.mixer||this.gesture||!this.poseTarget.template.standing||this.poseTarget.template.bend||Math.random()>e)return;this.ikSolve({root:"LeftShoulder",effector:"LeftHandMiddle1",links:[{link:"LeftHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5},{link:"LeftForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-.5,maxz:3},{link:"LeftArm",minx:-1.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-1,maxz:3}]},new f.Vector3(this.gaussianRandom(0,.5),this.gaussianRandom(-.8,-.2),this.gaussianRandom(0,.5)),!0),this.ikSolve({root:"RightShoulder",effector:"RightHandMiddle1",links:[{link:"RightHand",minx:-.5,maxx:.5,miny:-1,maxy:1,minz:-.5,maxz:.5},{link:"RightForeArm",minx:-.5,maxx:1.5,miny:-1.5,maxy:1.5,minz:-3,maxz:.5},{link:"RightArm"}]},new f.Vector3(this.gaussianRandom(-.5,0),this.gaussianRandom(-.8,-.2),this.gaussianRandom(0,.5)),!0);const n=[],o=[];n.push(100+Math.round(Math.random()*500)),o.push({duration:1e3,props:{"LeftHand.quaternion":new f.Quaternion().setFromEuler(new f.Euler(0,-1-Math.random(),0)),"RightHand.quaternion":new f.Quaternion().setFromEuler(new f.Euler(0,1+Math.random(),0))}}),["LeftArm","LeftForeArm","RightArm","RightForeArm"].forEach(i=>{o[0].props[i+".quaternion"]=this.ikMesh.getObjectByName(i).quaternion.clone()}),n.push(1e3+Math.round(Math.random()*500)),o.push({duration:2e3,props:{}}),["LeftArm","LeftForeArm","RightArm","RightForeArm","LeftHand","RightHand"].forEach(i=>{o[1].props[i+".quaternion"]=null});const s=this.animFactory({name:"talkinghands",delay:t,dt:n,vs:{moveto:o}});this.animQueue.push(s)}getSlowdownRate(t){return this.animSlowdownRate}setSlowdownRate(t){this.animSlowdownRate=t,this.audioSpeechSource.playbackRate.value=1/this.animSlowdownRate,this.audioBackgroundSource.playbackRate.value=1/this.animSlowdownRate}getAutoRotateSpeed(t){return this.controls.autoRotateSpeed}setAutoRotateSpeed(t){this.controls.autoRotateSpeed=t,this.controls.autoRotate=t>0}start(){this.armature&&this.isRunning===!1&&(this.audioCtx.resume(),this.animTimeLast=performance.now(),this.isRunning=!0,this.isAvatarOnly||requestAnimationFrame(this.animate.bind(this)))}stop(){this.isRunning=!1,this.audioCtx.suspend()}startListening(t,e={},n=null){this.listeningAnalyzer=t,this.listeningAnalyzer.fftSize=256,this.listeningAnalyzer.smoothingTimeConstant=.1,this.listeningAnalyzer.minDecibels=-70,this.listeningAnalyzer.maxDecibels=-10,this.listeningOnchange=n&&typeof n=="function"?n:null,this.listeningSilenceThresholdLevel=e?.hasOwnProperty("listeningSilenceThresholdLevel")?e.listeningSilenceThresholdLevel:this.opt.listeningSilenceThresholdLevel,this.listeningSilenceThresholdMs=e?.hasOwnProperty("listeningSilenceThresholdMs")?e.listeningSilenceThresholdMs:this.opt.listeningSilenceThresholdMs,this.listeningSilenceDurationMax=e?.hasOwnProperty("listeningSilenceDurationMax")?e.listeningSilenceDurationMax:this.opt.listeningSilenceDurationMax,this.listeningActiveThresholdLevel=e?.hasOwnProperty("listeningActiveThresholdLevel")?e.listeningActiveThresholdLevel:this.opt.listeningActiveThresholdLevel,this.listeningActiveThresholdMs=e?.hasOwnProperty("listeningActiveThresholdMs")?e.listeningActiveThresholdMs:this.opt.listeningActiveThresholdMs,this.listeningActiveDurationMax=e?.hasOwnProperty("listeningActiveDurationMax")?e.listeningActiveDurationMax:this.opt.listeningActiveDurationMax,this.listeningActive=!1,this.listeningVolume=0,this.listeningTimer=0,this.listeningTimerTotal=0,this.isListening=!0}stopListening(){this.isListening=!1}async playAnimation(t,e=null,n=10,o=0,s=.01,i=!1,r=null){if(!this.armature)return;this.positionWasLocked=!i,i||this.lockAvatarPosition();let c=this.animClips.find(l=>l.url===t+"-"+o);if(c){let l=this.animQueue.find(h=>h.template.name==="pose");l&&(l.ts[0]=1/0),Object.entries(c.pose.props).forEach(h=>{this.poseBase.props[h[0]]=h[1].clone(),this.poseTarget.props[h[0]]=h[1].clone(),this.poseTarget.props[h[0]].t=0,this.poseTarget.props[h[0]].d=1e3}),this.mixer||(this.mixer=new f.AnimationMixer(this.armature)),this.animationFinishedCallback=r;const u=()=>{this.animationFinishedCallback&&(this.animationFinishedCallback(),this.animationFinishedCallback=null),this.stopAnimation()};this.mixer.addEventListener("finished",u,{once:!0});const a=Math.ceil(n/c.clip.duration),d=this.mixer.clipAction(c.clip);if(d.setLoop(f.LoopRepeat,a),d.clampWhenFinished=!0,this.currentFBXAction&&this.currentFBXAction.isRunning()){this.currentFBXAction.fadeOut(.3),setTimeout(()=>{this.currentFBXAction=d;try{d.fadeIn(.5).play(),console.log("FBX animation started successfully (with fade transition):",t)}catch(h){console.warn("FBX animation failed to start:",h),this.stopAnimation()}},300);return}this.currentFBXAction=d;try{d.fadeIn(.5).play(),console.log("FBX animation started successfully:",t)}catch(h){console.warn("FBX animation failed to start:",h),this.stopAnimation();return}if(d.getClip().tracks.length===0){console.warn("FBX animation has no valid tracks, stopping"),this.stopAnimation();return}}else{if(t.split(".").pop().toLowerCase()!=="fbx"){console.error(`Invalid file type for FBX animation: ${t}. Expected .fbx file.`);return}let u=!1;try{const h=await fetch(t,{method:"HEAD"});if(u=h.ok,!u){console.error(`FBX file not found at ${t}. Status: ${h.status}`),console.error("Please check:"),console.error("1. File path is correct (note: path is case-sensitive)"),console.error("2. File exists in your public folder"),console.error("3. File is accessible (not blocked by server)");return}}catch(h){console.warn(`Could not verify file existence for ${t}, attempting to load anyway:`,h)}const a=new Ge.FBXLoader;let d;try{d=await a.loadAsync(t,e)}catch(h){console.error(`Failed to load FBX animation from ${t}:`,h),console.error("Error details:",{message:h.message,url:t,suggestion:"Make sure the file is a valid FBX file and the path is correct"}),h.message&&h.message.includes("version number")&&(console.error("FBX Loader Error: Cannot find version number"),console.error("This error usually means:"),console.error("1. The file is not a valid FBX file (might be GLB, corrupted, or wrong format)"),console.error("2. The file might be corrupted"),console.error("3. The file path might be incorrect"),console.error("4. The server returned an HTML error page instead of the FBX file"),console.error("5. The file might not exist at that path"),console.error(""),console.error("Solution: Please verify:"),console.error(` - File exists at: ${t}`),console.error(" - File is a valid FBX binary file"),console.error(" - File path matches your public folder structure"),console.error(" - File is not corrupted"));try{const g=await fetch(t),v=g.headers.get("content-type"),b=await g.text();console.error("Response details:",{status:g.status,contentType:v,firstBytes:b.substring(0,100),isHTML:b.trim().startsWith("<!DOCTYPE")||b.trim().startsWith("<html")}),(b.trim().startsWith("<!DOCTYPE")||b.trim().startsWith("<html"))&&console.error("The server returned an HTML page instead of an FBX file. The file path is likely incorrect.")}catch(g){console.error("Could not fetch file for debugging:",g)}return}if(d&&d.animations&&d.animations[o]){let h=d.animations[o];const g=new Set;this.armature&&this.armature.traverse(y=>{(y.isBone||y.type==="Bone")&&g.add(y.name)});const v=new Map,b=y=>{if(g.has(y))return y;let F=y.replace(/^mixamorig/i,"").replace(/^CC_Base_/i,"").replace(/^RPM_/i,"");if(g.has(F))return F;const x=F.toLowerCase();if(x.includes("left")&&x.includes("arm")){if(x.includes("fore")||x.includes("lower")){if(g.has("LeftForeArm"))return"LeftForeArm";if(g.has("LeftForearm"))return"LeftForearm"}else if(!x.includes("fore")&&!x.includes("hand")&&g.has("LeftArm"))return"LeftArm"}if(x.includes("right")&&x.includes("arm")){if(x.includes("fore")||x.includes("lower")){if(g.has("RightForeArm"))return"RightForeArm";if(g.has("RightForearm"))return"RightForearm"}else if(!x.includes("fore")&&!x.includes("hand")&&g.has("RightArm"))return"RightArm"}if(x.includes("left")&&x.includes("hand")&&!x.includes("index")&&!x.includes("thumb")&&!x.includes("middle")&&!x.includes("ring")&&!x.includes("pinky")&&g.has("LeftHand"))return"LeftHand";if(x.includes("right")&&x.includes("hand")&&!x.includes("index")&&!x.includes("thumb")&&!x.includes("middle")&&!x.includes("ring")&&!x.includes("pinky")&&g.has("RightHand"))return"RightHand";if(x.includes("left")&&(x.includes("shoulder")||x.includes("clavicle"))&&g.has("LeftShoulder"))return"LeftShoulder";if(x.includes("right")&&(x.includes("shoulder")||x.includes("clavicle"))&&g.has("RightShoulder"))return"RightShoulder";const k={LeftArm:"LeftArm",leftArm:"LeftArm",LEFTARM:"LeftArm",RightArm:"RightArm",rightArm:"RightArm",RIGHTARM:"RightArm",LeftForeArm:"LeftForeArm",leftForeArm:"LeftForeArm",leftForearm:"LeftForeArm",LeftForearm:"LeftForeArm",RightForeArm:"RightForeArm",rightForeArm:"RightForeArm",rightForearm:"RightForeArm",RightForearm:"RightForeArm",LeftHand:"LeftHand",leftHand:"LeftHand",RightHand:"RightHand",rightHand:"RightHand",LeftShoulder:"LeftShoulder",leftShoulder:"LeftShoulder",RightShoulder:"RightShoulder",rightShoulder:"RightShoulder",Spine:"Spine1",spine:"Spine1",Spine1:"Spine1",Spine2:"Spine2",Head:"Head",head:"Head",Neck:"Neck",neck:"Neck",Hips:"Hips",hips:"Hips",Root:"Hips",root:"Hips"};if(k[F]){const T=k[F];if(g.has(T))return T}for(const T of g)if(T.toLowerCase()===x)return T;for(const T of g){const A=T.toLowerCase();if((x.includes("left")&&A.includes("left")||x.includes("right")&&A.includes("right"))&&(x.includes("arm")&&A.includes("arm")&&!A.includes("fore")||x.includes("forearm")&&A.includes("forearm")||x.includes("hand")&&A.includes("hand")&&!A.includes("index")&&!A.includes("thumb")||x.includes("shoulder")&&A.includes("shoulder")))return T}return null},S=new Set;h.tracks.forEach(y=>{const F=y.name.split(".");S.add(F[0])}),Array.from(S).filter(y=>y.toLowerCase().includes("arm")||y.toLowerCase().includes("hand")||y.toLowerCase().includes("shoulder")),Array.from(g).filter(y=>y.includes("Arm")||y.includes("Hand")||y.includes("Shoulder"));const M=[],p=new Set;h.tracks.forEach(y=>{const x=y.name.replaceAll("mixamorig","").split("."),k=x[0],T=x[1],A=b(k);if(!(A&&(A==="LeftShoulder"||A==="RightShoulder")&&(T==="quaternion"||T==="rotation")))if(A&&T){const W=`${A}.${T}`,G=y.clone();G.name=W,M.push(G),k!==A&&v.set(k,A)}else p.add(k),(k.toLowerCase().includes("arm")||k.toLowerCase().includes("hand")||k.toLowerCase().includes("shoulder"))&&console.warn(`⚠️ Arm bone "${k}" could not be mapped to avatar skeleton`)}),M.length>0?h=new f.AnimationClip(h.name,h.duration,M):console.error("No tracks could be mapped! Animation may not work correctly.");const O={};h.tracks.forEach(y=>{y.name=y.name.replaceAll("mixamorig","");const F=y.name.split(".");if(F[1]==="position"){for(let x=0;x<y.values.length;x++)y.values[x]=y.values[x]*s;O[y.name]=new f.Vector3(y.values[0],y.values[1],y.values[2])}else F[1]==="quaternion"?O[y.name]=new f.Quaternion(y.values[0],y.values[1],y.values[2],y.values[3]):F[1]==="rotation"&&(O[F[0]+".quaternion"]=new f.Quaternion().setFromEuler(new f.Euler(y.values[0],y.values[1],y.values[2],"XYZ")).normalize())});const P={props:O};O["Hips.position"]&&(O["Hips.position"].y<.5?P.lying=!0:P.standing=!0),this.animClips.push({url:t+"-"+o,clip:h,pose:P}),this.playAnimation(t,e,n,o,s)}else{const h="Animation "+t+" (ndx="+o+") not found";console.error(h),d&&d.animations?console.error(`FBX file loaded but has ${d.animations.length} animation(s), requested index ${o}`):console.error(d?"FBX file loaded but contains no animations":"FBX file failed to load or is invalid")}}}stopAnimation(){if(this.currentFBXAction&&(this.currentFBXAction.stop(),this.currentFBXAction=null),this.mixer&&this.mixer._actions.length===0&&(this.mixer=null),this.positionWasLocked&&this.unlockAvatarPosition(),this.gesture)for(let[e,n]of Object.entries(this.gesture))n.t=this.animClock,n.d=1e3,this.poseTarget.props.hasOwnProperty(e)&&(this.poseTarget.props[e].copy(n),this.poseTarget.props[e].t=this.animClock,this.poseTarget.props[e].d=1e3);let t=this.animQueue.find(e=>e.template.name==="pose");t&&(t.ts[0]=this.animClock),this.setPoseFromTemplate(null)}async playPose(t,e=null,n=5,o=0,s=.01){if(!this.armature)return;let i=this.poseTemplates[t];if(!i){const r=this.animPoses.find(c=>c.url===t+"-"+o);r&&(i=r.pose)}if(i){this.poseName=t,this.mixer=null;let r=this.animQueue.find(c=>c.template.name==="pose");r&&(r.ts[0]=this.animClock+n*1e3+2e3),this.setPoseFromTemplate(i)}else{let c=await new Ge.FBXLoader().loadAsync(t,e);if(c&&c.animations&&c.animations[o]){let l=c.animations[o];const u={};l.tracks.forEach(d=>{d.name=d.name.replaceAll("mixamorig","");const h=d.name.split(".");h[1]==="position"?u[d.name]=new f.Vector3(d.values[0]*s,d.values[1]*s,d.values[2]*s):h[1]==="quaternion"?u[d.name]=new f.Quaternion(d.values[0],d.values[1],d.values[2],d.values[3]):h[1]==="rotation"&&(u[h[0]+".quaternion"]=new f.Quaternion().setFromEuler(new f.Euler(d.values[0],d.values[1],d.values[2],"XYZ")).normalize())});const a={props:u};u["Hips.position"]&&(u["Hips.position"].y<.5?a.lying=!0:a.standing=!0),this.animPoses.push({url:t+"-"+o,pose:a}),this.playPose(t,e,n,o,s)}else{const l="Pose "+t+" (ndx="+o+") not found";console.error(l)}}}stopPose(){this.stopAnimation()}playGesture(t,e=3,n=!1,o=1e3){if(!this.armature)return;let s=this.gestureTemplates[t];if(s){this.gestureTimeout&&(clearTimeout(this.gestureTimeout),this.gestureTimeout=null);let r=this.animQueue.findIndex(c=>c.template.name==="talkinghands");r!==-1&&(this.animQueue[r].ts=this.animQueue[r].ts.map(c=>0)),this.gesture=this.propsToThreeObjects(s),n&&(this.gesture=this.mirrorPose(this.gesture)),t==="namaste"&&this.avatar.body==="M"&&(this.gesture["RightArm.quaternion"].rotateTowards(new f.Quaternion(0,1,0,0),-.25),this.gesture["LeftArm.quaternion"].rotateTowards(new f.Quaternion(0,1,0,0),-.25));for(let[c,l]of Object.entries(this.gesture))l.t=this.animClock,l.d=o,this.poseTarget.props.hasOwnProperty(c)&&(this.poseTarget.props[c].copy(l),this.poseTarget.props[c].t=this.animClock,this.poseTarget.props[c].d=o);e&&Number.isFinite(e)&&(this.gestureTimeout=setTimeout(this.stopGesture.bind(this,o),1e3*e))}let i=this.animEmojis[t];if(i&&(i&&i.link&&(i=this.animEmojis[i.link]),i)){this.lookAtCamera(500);const r=this.animFactory(i);if(r.gesture=!0,e&&Number.isFinite(e)){const c=r.ts[0],u=r.ts[r.ts.length-1]-c;if(e*1e3-u>0){const d=[];for(let v=1;v<r.ts.length;v++)d.push(r.ts[v]-r.ts[v-1]);const h=i.template?.rescale||d.map(v=>v/u),g=e*1e3-u;r.ts=r.ts.map((v,b,S)=>b===0?c:S[b-1]+d[b-1]+h[b-1]*g)}else{const d=e*1e3/u;r.ts=r.ts.map(h=>c+d*(h-c))}}this.animQueue.push(r)}}stopGesture(t=1e3){if(this.gestureTimeout&&(clearTimeout(this.gestureTimeout),this.gestureTimeout=null),this.gesture){const n=Object.entries(this.gesture);this.gesture=null;for(const[o,s]of n)this.poseTarget.props.hasOwnProperty(o)&&(this.poseTarget.props[o].copy(this.getPoseTemplateProp(o)),this.poseTarget.props[o].t=this.animClock,this.poseTarget.props[o].d=t)}let e=this.animQueue.findIndex(n=>n.gesture);e!==-1&&this.animQueue.splice(e,1)}ikSolve(t,e=null,n=!1,o=null){const s=new f.Vector3,i=new f.Vector3,r=new f.Vector3,c=new f.Vector3,l=new f.Quaternion,u=new f.Vector3,a=new f.Vector3,d=new f.Vector3,h=this.ikMesh.getObjectByName(t.root);h.position.setFromMatrixPosition(this.armature.getObjectByName(t.root).matrixWorld),h.quaternion.setFromRotationMatrix(this.armature.getObjectByName(t.root).matrixWorld),e&&n&&e.applyQuaternion(this.armature.quaternion).add(h.position);const g=this.ikMesh.getObjectByName(t.effector),v=t.links;v.forEach(S=>{S.bone=this.ikMesh.getObjectByName(S.link),S.bone.quaternion.copy(this.getPoseTemplateProp(S.link+".quaternion"))}),h.updateMatrixWorld(!0);const b=t.iterations||10;if(e)for(let S=0;S<b;S++){let M=!1;for(let p=0,O=v.length;p<O;p++){const P=v[p].bone;P.matrixWorld.decompose(c,l,u),l.invert(),i.setFromMatrixPosition(g.matrixWorld),r.subVectors(i,c),r.applyQuaternion(l),r.normalize(),s.subVectors(e,c),s.applyQuaternion(l),s.normalize();let y=s.dot(r);y>1?y=1:y<-1&&(y=-1),y=Math.acos(y),!(y<1e-5)&&(v[p].minAngle!==void 0&&y<v[p].minAngle&&(y=v[p].minAngle),v[p].maxAngle!==void 0&&y>v[p].maxAngle&&(y=v[p].maxAngle),a.crossVectors(r,s),a.normalize(),ie.setFromAxisAngle(a,y),P.quaternion.multiply(ie),P.rotation.setFromVector3(d.setFromEuler(P.rotation).clamp(new f.Vector3(v[p].minx!==void 0?v[p].minx:-1/0,v[p].miny!==void 0?v[p].miny:-1/0,v[p].minz!==void 0?v[p].minz:-1/0),new f.Vector3(v[p].maxx!==void 0?v[p].maxx:1/0,v[p].maxy!==void 0?v[p].maxy:1/0,v[p].maxz!==void 0?v[p].maxz:1/0))),P.updateMatrixWorld(!0),M=!0)}if(!M)break}o&&v.forEach(S=>{this.poseTarget.props[S.link+".quaternion"].copy(S.bone.quaternion),this.poseTarget.props[S.link+".quaternion"].t=this.animClock,this.poseTarget.props[S.link+".quaternion"].d=o})}dispose(){this.isRunning=!1,this.stop(),this.stopSpeaking(),this.streamStop(),this.isAvatarOnly?this.armature&&(this.armature.parent&&this.armature.parent.remove(this.armature),this.clearThree(this.armature)):(this.clearThree(this.scene),this.resizeobserver.disconnect(),this.renderer&&(this.renderer.dispose(),this.renderer.domElement&&this.renderer.domElement.parentNode&&this.renderer.domElement.parentNode.removeChild(this.renderer.domElement),this.renderer=null)),this.clearThree(this.ikMesh),this.dynamicbones.dispose()}}const Se={apiKey:"sk_ace57ef3ef65a92b9d3bee2a00183b78ca790bc3e10964f2",endpoint:"https://api.elevenlabs.io/v1/text-to-speech",defaultVoice:"21m00Tcm4TlvDq8ikWAM",voices:{rachel:"21m00Tcm4TlvDq8ikWAM",drew:"29vD33N1CtxCmqQRPOHJ",bella:"EXAVITQu4vr4xnSDxMaL",antoni:"ErXwobaYiN019PkySvjV",elli:"MF3mGyEYCl7XYWbV9V6O",josh:"VR6AewLTigWG4xSOukaG"}},Oe={defaultVoice:"aura-2-thalia-en",voices:{thalia:"aura-2-thalia-en",asteria:"aura-2-asteria-en",orion:"aura-2-orion-en",stella:"aura-2-stella-en",athena:"aura-2-athena-en",hera:"aura-2-hera-en",zeus:"aura-2-zeus-en"}};function ze(){return{service:"elevenlabs",endpoint:Se.endpoint,apiKey:Se.apiKey,defaultVoice:Se.defaultVoice,voices:Se.voices}}function It(){const U=ze(),t=[];return Object.entries(U.voices).forEach(([e,n])=>{t.push({value:n,label:`${e.charAt(0).toUpperCase()+e.slice(1)} (${U.service})`})}),t}const Ue=R.forwardRef(({avatarUrl:U="/avatars/brunette.glb",avatarBody:t="F",mood:e="neutral",ttsLang:n="en",ttsService:o=null,ttsVoice:s=null,ttsApiKey:i=null,bodyMovement:r="idle",movementIntensity:c=.5,showFullAvatar:l=!0,cameraView:u="upper",onReady:a=()=>{},onLoading:d=()=>{},onError:h=()=>{},className:g="",style:v={},animations:b={}},S)=>{const M=R.useRef(null),p=R.useRef(null),O=R.useRef(l),P=R.useRef(null),y=R.useRef(null),F=R.useRef(!1),x=R.useRef({remainingText:null,originalText:null,options:null}),k=R.useRef([]),T=R.useRef(0),[A,W]=R.useState(!0),[G,j]=R.useState(null),[Y,re]=R.useState(!1),[ae,xe]=R.useState(!1);R.useEffect(()=>{F.current=ae},[ae]),R.useEffect(()=>{O.current=l},[l]);const oe=ze(),ve=o||oe.service;let $;ve==="browser"?$={service:"browser",endpoint:"",apiKey:null,defaultVoice:"Google US English"}:ve==="elevenlabs"?$={service:"elevenlabs",endpoint:"https://api.elevenlabs.io/v1/text-to-speech",apiKey:i||oe.apiKey,defaultVoice:s||oe.defaultVoice||Se.defaultVoice,voices:oe.voices||Se.voices}:ve==="deepgram"?$={service:"deepgram",endpoint:"https://api.deepgram.com/v1/speak",apiKey:i||oe.apiKey,defaultVoice:s||oe.defaultVoice||Oe.defaultVoice,voices:oe.voices||Oe.voices}:$={...oe,apiKey:i!==null?i:oe.apiKey};const I={url:U,body:t,avatarMood:e,ttsLang:ve==="browser"?"en-US":n,ttsVoice:s||$.defaultVoice,lipsyncLang:"en",showFullAvatar:l,bodyMovement:r,movementIntensity:c},L={ttsEndpoint:$.endpoint,ttsApikey:$.apiKey,ttsService:ve,lipsyncModules:["en"],cameraView:u},E=R.useCallback(async()=>{if(!(!M.current||p.current))try{if(W(!0),j(null),p.current=new Ne(M.current,L),p.current.controls&&(p.current.controls.enableRotate=!1,p.current.controls.enableZoom=!1,p.current.controls.enablePan=!1,p.current.controls.enableDamping=!1),b&&Object.keys(b).length>0&&(p.current.customAnimations=b),await p.current.showAvatar(I,te=>{if(te.lengthComputable){const ne=Math.min(100,Math.round(te.loaded/te.total*100));d(ne)}}),await new Promise(te=>{const ne=()=>{p.current.lipsync&&Object.keys(p.current.lipsync).length>0?te():setTimeout(ne,100)};ne()}),p.current&&p.current.setShowFullAvatar)try{p.current.setShowFullAvatar(l)}catch(te){console.warn("Error setting full body mode on initialization:",te)}p.current&&p.current.controls&&(p.current.controls.enableRotate=!1,p.current.controls.enableZoom=!1,p.current.controls.enablePan=!1,p.current.controls.enableDamping=!1,p.current.controls.update()),W(!1),re(!0),a(p.current);const X=()=>{document.visibilityState==="visible"?p.current?.start():p.current?.stop()};return document.addEventListener("visibilitychange",X),()=>{document.removeEventListener("visibilitychange",X)}}catch(w){console.error("Error initializing TalkingHead:",w),j(w.message||"Failed to initialize avatar"),W(!1),h(w)}},[U,t,e,n,o,s,i,l,r,c,u]);R.useEffect(()=>(E(),()=>{p.current&&(p.current.stop(),p.current.dispose(),p.current=null)}),[E]),R.useEffect(()=>{if(!M.current||!p.current)return;const w=new ResizeObserver(te=>{for(const ne of te)p.current&&p.current.onResize&&p.current.onResize()});w.observe(M.current);const X=()=>{p.current&&p.current.onResize&&p.current.onResize()};return window.addEventListener("resize",X),()=>{w.disconnect(),window.removeEventListener("resize",X)}},[Y]);const D=R.useCallback(async()=>{if(p.current&&p.current.audioCtx)try{(p.current.audioCtx.state==="suspended"||p.current.audioCtx.state==="interrupted")&&(await p.current.audioCtx.resume(),console.log("Audio context resumed"))}catch(w){console.warn("Failed to resume audio context:",w)}},[]),Z=R.useCallback(async(w,X={})=>{if(p.current&&Y)try{y.current&&(clearInterval(y.current),y.current=null),P.current={text:w,options:X},x.current={remainingText:null,originalText:null,options:null};const te=/[!\.\?\n\p{Extended_Pictographic}]/ug,ne=w.split(te).map(J=>J.trim()).filter(J=>J.length>0);k.current=ne,T.current=0,xe(!1),F.current=!1,await D();const le={...X,lipsyncLang:X.lipsyncLang||I.lipsyncLang||"en"};if(X.onSpeechEnd&&p.current){const J=p.current;let de=null,ke=0;const C=1200;let z=!1;de=setInterval(()=>{if(ke++,F.current)return;if(ke>C){if(de&&(clearInterval(de),de=null,y.current=null),!z&&!F.current){z=!0;try{X.onSpeechEnd()}catch(me){console.error("Error in onSpeechEnd callback (timeout):",me)}}return}const N=!J.speechQueue||J.speechQueue.length===0,Q=!J.audioPlaylist||J.audioPlaylist.length===0;J&&J.isSpeaking===!1&&N&&Q&&J.isAudioPlaying===!1&&!z&&!F.current&&setTimeout(()=>{if(J&&!F.current&&J.isSpeaking===!1&&(!J.speechQueue||J.speechQueue.length===0)&&(!J.audioPlaylist||J.audioPlaylist.length===0)&&J.isAudioPlaying===!1&&!z&&!F.current){z=!0,de&&(clearInterval(de),de=null,y.current=null);try{X.onSpeechEnd()}catch(Ve){console.error("Error in onSpeechEnd callback:",Ve)}}},100)},100),y.current=de}p.current.lipsync&&Object.keys(p.current.lipsync).length>0?(p.current.setSlowdownRate&&p.current.setSlowdownRate(1.05),p.current.speakText(w,le)):setTimeout(async()=>{await D(),p.current&&p.current.lipsync&&(p.current.setSlowdownRate&&p.current.setSlowdownRate(1.05),p.current.speakText(w,le))},100)}catch(te){console.error("Error speaking text:",te),j(te.message||"Failed to speak text")}},[Y,D,I.lipsyncLang]),se=R.useCallback(()=>{p.current&&(p.current.stopSpeaking(),p.current.setSlowdownRate&&p.current.setSlowdownRate(1),P.current=null,xe(!1))},[]),K=R.useCallback(()=>{if(p.current&&p.current.pauseSpeaking){const w=p.current;if(w.isSpeaking||w.audioPlaylist&&w.audioPlaylist.length>0||w.speechQueue&&w.speechQueue.length>0){y.current&&(clearInterval(y.current),y.current=null);let te="";if(P.current&&k.current.length>0){const ne=k.current.length,le=w.speechQueue?w.speechQueue.filter(C=>C&&C.text&&Array.isArray(C.text)&&C.text.length>0).length:0,J=w.audioPlaylist&&w.audioPlaylist.length>0,de=le+(J?1:0),ke=ne-de;if(de>0&&ke<ne&&(te=k.current.slice(ke).join(". ").trim(),!te&&le>0&&w.speechQueue)){const z=w.speechQueue.filter(N=>N&&N.text&&Array.isArray(N.text)&&N.text.length>0).map(N=>N.text.map(Q=>Q.word||"").filter(Q=>Q.length>0).join(" ")).filter(N=>N.length>0).join(" ");z&&z.trim()&&(te=z.trim())}}P.current&&(x.current={remainingText:te||null,originalText:P.current.text,options:P.current.options}),w.speechQueue&&(w.speechQueue.length=0),p.current.pauseSpeaking(),F.current=!0,xe(!0)}}},[]),ee=R.useCallback(async()=>{if(!p.current||!ae)return;let w="",X={};if(x.current&&x.current.remainingText)w=x.current.remainingText,X=x.current.options||{},x.current={remainingText:null,originalText:null,options:null};else if(P.current&&P.current.text)w=P.current.text,X=P.current.options||{};else{console.warn("Resume called but no paused speech found"),xe(!1),F.current=!1;return}xe(!1),F.current=!1,await D();const te={...X,lipsyncLang:X.lipsyncLang||I.lipsyncLang||"en"};try{await Z(w,te)}catch(ne){console.error("Error resuming speech:",ne),xe(!1),F.current=!1}},[D,ae,Z,I]),ye=R.useCallback(w=>{p.current&&p.current.setMood(w)},[]),He=R.useCallback(w=>{p.current&&p.current.setSlowdownRate&&p.current.setSlowdownRate(w)},[]),Be=R.useCallback((w,X=!1)=>{if(p.current&&p.current.playAnimation){if(b&&b[w]&&(w=b[w]),p.current.setShowFullAvatar)try{p.current.setShowFullAvatar(O.current)}catch(ne){console.warn("Error setting full body mode:",ne)}if(w.includes("."))try{p.current.playAnimation(w,null,10,0,.01,X)}catch(ne){console.warn(`Failed to play ${w}:`,ne);try{p.current.setBodyMovement("idle")}catch(le){console.warn("Fallback animation also failed:",le)}}else{const ne=[".fbx",".glb",".gltf"];let le=!1;for(const J of ne)try{p.current.playAnimation(w+J,null,10,0,.01,X),le=!0;break}catch{}if(!le){console.warn("Animation not found:",w);try{p.current.setBodyMovement("idle")}catch(J){console.warn("Fallback animation also failed:",J)}}}}},[b]),Te=R.useCallback(()=>{p.current&&p.current.onResize&&p.current.onResize()},[]);return R.useImperativeHandle(S,()=>({speakText:Z,stopSpeaking:se,pauseSpeaking:K,resumeSpeaking:ee,resumeAudioContext:D,setMood:ye,setTimingAdjustment:He,playAnimation:Be,isReady:Y,isPaused:ae,talkingHead:p.current,handleResize:Te,setBodyMovement:w=>{if(p.current&&p.current.setShowFullAvatar&&p.current.setBodyMovement)try{p.current.setShowFullAvatar(O.current),p.current.setBodyMovement(w)}catch(X){console.warn("Error setting body movement:",X)}},setMovementIntensity:w=>p.current?.setMovementIntensity(w),playRandomDance:()=>{if(p.current&&p.current.setShowFullAvatar&&p.current.playRandomDance)try{p.current.setShowFullAvatar(O.current),p.current.playRandomDance()}catch(w){console.warn("Error playing random dance:",w)}},playReaction:w=>{if(p.current&&p.current.setShowFullAvatar&&p.current.playReaction)try{p.current.setShowFullAvatar(O.current),p.current.playReaction(w)}catch(X){console.warn("Error playing reaction:",X)}},playCelebration:()=>{if(p.current&&p.current.setShowFullAvatar&&p.current.playCelebration)try{p.current.setShowFullAvatar(O.current),p.current.playCelebration()}catch(w){console.warn("Error playing celebration:",w)}},setShowFullAvatar:w=>{if(p.current&&p.current.setShowFullAvatar)try{O.current=w,p.current.setShowFullAvatar(w)}catch(X){console.warn("Error setting showFullAvatar:",X)}},lockAvatarPosition:()=>{if(p.current&&p.current.lockAvatarPosition)try{p.current.lockAvatarPosition()}catch(w){console.warn("Error locking avatar position:",w)}},unlockAvatarPosition:()=>{if(p.current&&p.current.unlockAvatarPosition)try{p.current.unlockAvatarPosition()}catch(w){console.warn("Error unlocking avatar position:",w)}}})),V.jsxs("div",{className:`talking-head-avatar ${g}`,style:{width:"100%",height:"100%",position:"relative",...v},children:[V.jsx("div",{ref:M,className:"talking-head-viewer",style:{width:"100%",height:"100%",minHeight:"400px"}}),A&&V.jsx("div",{className:"loading-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"white",fontSize:"18px",zIndex:10},children:"Loading avatar..."}),G&&V.jsx("div",{className:"error-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"#ff6b6b",fontSize:"16px",textAlign:"center",zIndex:10,padding:"20px",borderRadius:"8px"},children:G})]})});Ue.displayName="TalkingHeadAvatar";const Qe=R.forwardRef(({text:U="Hello! I'm a talking avatar. How are you today?",onLoading:t=()=>{},onError:e=()=>{},onReady:n=()=>{},className:o="",style:s={},avatarConfig:i={}},r)=>{const c=R.useRef(null),l=R.useRef(null),[u,a]=R.useState(!0),[d,h]=R.useState(null),[g,v]=R.useState(!1),b=ze(),S=i.ttsService||b.service,M=S==="browser"?{endpoint:"",apiKey:null,defaultVoice:"Google US English"}:{...b,apiKey:i.ttsApiKey!==void 0&&i.ttsApiKey!==null?i.ttsApiKey:b.apiKey,endpoint:S==="elevenlabs"&&i.ttsApiKey?"https://api.elevenlabs.io/v1/text-to-speech":b.endpoint},p={url:"/avatars/brunette.glb",body:"F",avatarMood:"neutral",ttsLang:S==="browser"?"en-US":"en",ttsVoice:i.ttsVoice||M.defaultVoice,lipsyncLang:"en",showFullAvatar:!0,bodyMovement:"idle",movementIntensity:.5,...i},O={ttsEndpoint:M.endpoint,ttsApikey:M.apiKey,ttsService:S,lipsyncModules:["en"],cameraView:"upper"},P=R.useCallback(async()=>{if(!(!c.current||l.current))try{if(a(!0),h(null),l.current=new Ne(c.current,O),await l.current.showAvatar(p,G=>{if(G.lengthComputable){const j=Math.min(100,Math.round(G.loaded/G.total*100));t(j)}}),l.current.morphs&&l.current.morphs.length>0){const G=l.current.morphs[0].morphTargetDictionary;console.log("Available morph targets:",Object.keys(G));const j=Object.keys(G).filter(Y=>Y.startsWith("viseme_"));console.log("Viseme morph targets found:",j),j.length===0&&(console.warn("No viseme morph targets found! Lip-sync will not work properly."),console.log("Expected viseme targets: viseme_aa, viseme_E, viseme_I, viseme_O, viseme_U, viseme_PP, viseme_SS, viseme_TH, viseme_DD, viseme_FF, viseme_kk, viseme_nn, viseme_RR, viseme_CH, viseme_sil"))}if(await new Promise(G=>{const j=()=>{l.current.lipsync&&Object.keys(l.current.lipsync).length>0?(console.log("Lip-sync modules loaded:",Object.keys(l.current.lipsync)),G()):(console.log("Waiting for lip-sync modules to load..."),setTimeout(j,100))};j()}),l.current&&l.current.setShowFullAvatar)try{l.current.setShowFullAvatar(!0),console.log("Avatar initialized in full body mode")}catch(G){console.warn("Error setting full body mode on initialization:",G)}a(!1),v(!0),n(l.current);const W=()=>{document.visibilityState==="visible"?l.current?.start():l.current?.stop()};return document.addEventListener("visibilitychange",W),()=>{document.removeEventListener("visibilitychange",W)}}catch(A){console.error("Error initializing TalkingHead:",A),h(A.message||"Failed to initialize avatar"),a(!1),e(A)}},[]);R.useEffect(()=>(P(),()=>{l.current&&(l.current.stop(),l.current.dispose(),l.current=null)}),[P]);const y=R.useCallback(A=>{if(l.current&&g)try{console.log("Speaking text:",A),console.log("Avatar config:",p),console.log("TalkingHead instance:",l.current),l.current.lipsync&&Object.keys(l.current.lipsync).length>0?(console.log("Lip-sync modules loaded:",Object.keys(l.current.lipsync)),l.current.setSlowdownRate&&(l.current.setSlowdownRate(1.05),console.log("Applied timing adjustment for better lip-sync")),l.current.speakText(A)):(console.warn("Lip-sync modules not ready, waiting..."),setTimeout(()=>{l.current&&l.current.lipsync?(console.log("Lip-sync now ready, speaking..."),l.current.setSlowdownRate&&(l.current.setSlowdownRate(1.05),console.log("Applied timing adjustment for better lip-sync")),l.current.speakText(A)):console.error("Lip-sync still not ready after waiting")},500))}catch(W){console.error("Error speaking text:",W),h(W.message||"Failed to speak text")}else console.warn("Avatar not ready for speaking. isReady:",g,"talkingHeadRef:",!!l.current)},[g,p]),F=R.useCallback(()=>{l.current&&(l.current.stopSpeaking(),l.current.setSlowdownRate&&(l.current.setSlowdownRate(1),console.log("Reset timing to normal")))},[]),x=R.useCallback(A=>{l.current&&l.current.setMood(A)},[]),k=R.useCallback(A=>{l.current&&l.current.setSlowdownRate&&(l.current.setSlowdownRate(A),console.log("Timing adjustment set to:",A))},[]),T=R.useCallback((A,W=!1)=>{if(l.current&&l.current.playAnimation){if(l.current.setShowFullAvatar)try{l.current.setShowFullAvatar(!0)}catch(j){console.warn("Error setting full body mode:",j)}if(A.includes("."))try{l.current.playAnimation(A,null,10,0,.01,W),console.log("Playing animation:",A)}catch(j){console.log(`Failed to play ${A}:`,j);try{l.current.setBodyMovement("idle"),console.log("Fallback to idle animation")}catch(Y){console.warn("Fallback animation also failed:",Y)}}else{const j=[".fbx",".glb",".gltf"];let Y=!1;for(const re of j)try{l.current.playAnimation(A+re,null,10,0,.01,W),console.log("Playing animation:",A+re),Y=!0;break}catch{console.log(`Failed to play ${A}${re}, trying next format...`)}if(!Y){console.warn("Animation system not available or animation not found:",A);try{l.current.setBodyMovement("idle"),console.log("Fallback to idle animation")}catch(re){console.warn("Fallback animation also failed:",re)}}}}else console.warn("Animation system not available or animation not found:",A)},[]);return R.useImperativeHandle(r,()=>({speakText:y,stopSpeaking:F,setMood:x,setTimingAdjustment:k,playAnimation:T,isReady:g,talkingHead:l.current,setBodyMovement:A=>{if(l.current&&l.current.setShowFullAvatar&&l.current.setBodyMovement)try{l.current.setShowFullAvatar(!0),l.current.setBodyMovement(A),console.log("Body movement set with full body mode:",A)}catch(W){console.warn("Error setting body movement:",W)}},setMovementIntensity:A=>l.current?.setMovementIntensity(A),playRandomDance:()=>{if(l.current&&l.current.setShowFullAvatar&&l.current.playRandomDance)try{l.current.setShowFullAvatar(!0),l.current.playRandomDance(),console.log("Random dance played with full body mode")}catch(A){console.warn("Error playing random dance:",A)}},playReaction:A=>{if(l.current&&l.current.setShowFullAvatar&&l.current.playReaction)try{l.current.setShowFullAvatar(!0),l.current.playReaction(A),console.log("Reaction played with full body mode:",A)}catch(W){console.warn("Error playing reaction:",W)}},playCelebration:()=>{if(l.current&&l.current.setShowFullAvatar&&l.current.playCelebration)try{l.current.setShowFullAvatar(!0),l.current.playCelebration(),console.log("Celebration played with full body mode")}catch(A){console.warn("Error playing celebration:",A)}},setShowFullAvatar:A=>{if(l.current&&l.current.setShowFullAvatar)try{l.current.setShowFullAvatar(A),console.log("Show full avatar set to:",A)}catch(W){console.warn("Error setting showFullAvatar:",W)}},lockAvatarPosition:()=>{if(l.current&&l.current.lockAvatarPosition)try{l.current.lockAvatarPosition()}catch(A){console.warn("Error locking avatar position:",A)}},unlockAvatarPosition:()=>{if(l.current&&l.current.unlockAvatarPosition)try{l.current.unlockAvatarPosition()}catch(A){console.warn("Error unlocking avatar position:",A)}}})),V.jsxs("div",{className:`talking-head-container ${o}`,style:s,children:[V.jsx("div",{ref:c,className:"talking-head-viewer",style:{width:"100%",height:"100%",minHeight:"400px"}}),u&&V.jsx("div",{className:"loading-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"white",fontSize:"18px",zIndex:10},children:"Loading avatar..."}),d&&V.jsx("div",{className:"error-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"#ff6b6b",fontSize:"16px",textAlign:"center",zIndex:10,padding:"20px",borderRadius:"8px"},children:d})]})});Qe.displayName="TalkingHeadComponent";async function Ce(U){try{const t=await fetch(U);if(!t.ok)throw new Error(`Failed to fetch manifest: ${t.status} ${t.statusText}`);return(await t.json()).animations||{}}catch(t){return console.error("Failed to load animation manifest:",t),{}}}async function At(U,t="F"){const e=[],n=U.replace(/\/$/,"");try{const s=[`${n}/.list.json`,`/api/directory?path=${encodeURIComponent(n)}`,`${n}/index.json`];for(const i of s)try{const r=await fetch(i);if(r.ok){const c=await r.json(),u=(Array.isArray(c)?c:c.files||[]).filter(a=>typeof a=="string"&&a.toLowerCase().endsWith(".fbx")).map(a=>a.startsWith("/")?a:`${n}/${a}`);if(u.length>0)return u}}catch{continue}}catch(s){console.warn(`⚠️ Could not use directory listing API for ${n}:`,s)}const o=[];t==="M"||t==="m"?o.push(`${n}/male`,`${n}/m`):o.push(`${n}/female`,`${n}/f`),o.push(`${n}/shared`);for(const s of o)try{const i=`${s}/.list.json`,r=await fetch(i);if(r.ok){const c=await r.json(),l=(Array.isArray(c)?c:c.files||[]).filter(u=>typeof u=="string"&&u.toLowerCase().endsWith(".fbx")).map(u=>u.startsWith("/")?u:`${s}/${u}`);l.length>0&&e.push(...l)}}catch{continue}return e.length>0,e}async function Ye(U,t="F"){const e={};for(const[n,o]of Object.entries(U))try{const s=await At(o,t);s.length>0&&(e[n]=s)}catch(s){console.error(`❌ Failed to auto-load animations from ${o}:`,s)}return e}const qe=R.forwardRef(({text:U=null,avatarUrl:t="/avatars/brunette.glb",avatarBody:e="F",mood:n="neutral",ttsLang:o="en",ttsService:s=null,ttsVoice:i=null,ttsApiKey:r=null,bodyMovement:c="idle",movementIntensity:l=.5,showFullAvatar:u=!1,cameraView:a="upper",onReady:d=()=>{},onLoading:h=()=>{},onError:g=()=>{},onSpeechEnd:v=()=>{},className:b="",style:S={},animations:M={},autoAnimationGroup:p=null,autoIdleGroup:O=null,autoSpeak:P=!1},y)=>{const F=R.useRef(null),x=R.useRef(null),k=R.useRef(u),T=R.useRef(null),A=R.useRef(null),W=R.useRef(!1),G=R.useRef({remainingText:null,originalText:null,options:null}),j=R.useRef([]),[Y,re]=R.useState(!0),[ae,xe]=R.useState(null),[oe,ve]=R.useState(!1),[$,I]=R.useState(!1),[L,E]=R.useState(M),D=R.useRef(null),Z=R.useRef(!1),se=R.useRef(null);R.useEffect(()=>{W.current=$},[$]),R.useEffect(()=>{(async()=>{if(M.manifest&&M.auto)try{const z=await Ce(M.manifest);E(z);return}catch{}if(M.manifest&&!M.auto)try{const z=await Ce(M.manifest);E(z)}catch(z){console.error("Failed to load animation manifest:",z),E(M)}else if(M.auto)try{let z=null;if(M.manifest)try{z=await Ce(M.manifest)}catch{}if(typeof M.auto=="string"){const N=M.auto,Q={talking:`${N}/talking`,idle:`${N}/idle`},q=e==="M"?"male":"female";Q[`${q}_talking`]=`${N}/${q}/talking`,Q[`${q}_idle`]=`${N}/${q}/idle`,Q.shared_talking=`${N}/shared/talking`,Q.shared_idle=`${N}/shared/idle`;const me=await Ye(Q,e);if(!Object.values(me).some(ue=>Array.isArray(ue)&&ue.length>0)&&z){E(z);return}const pe={_genderSpecific:{[q]:{},shared:{}}};Object.entries(me).forEach(([ue,Ae])=>{if(ue.includes("_")){const[Me,...Ke]=ue.split("_"),we=Ke.join("_");Me==="shared"?(pe._genderSpecific.shared[we]||(pe._genderSpecific.shared[we]=[]),pe._genderSpecific.shared[we].push(...Ae)):Me===q&&(pe._genderSpecific[q][we]||(pe._genderSpecific[q][we]=[]),pe._genderSpecific[q][we].push(...Ae))}else pe[ue]=Ae}),z&&(z._genderSpecific&&Object.keys(z._genderSpecific).forEach(ue=>{pe._genderSpecific[ue]||(pe._genderSpecific[ue]={}),Object.entries(z._genderSpecific[ue]).forEach(([Ae,Me])=>{pe._genderSpecific[ue][Ae]||(pe._genderSpecific[ue][Ae]=Me)})}),Object.entries(z).forEach(([ue,Ae])=>{ue!=="_genderSpecific"&&!pe[ue]&&(pe[ue]=Ae)})),E(pe)}else if(typeof M.auto=="object"){const N=await Ye(M.auto,e),Q=Object.values(N).some(q=>Array.isArray(q)&&q.length>0);E(!Q&&z?z:N)}}catch(z){if(console.error("Failed to auto-discover animations:",z),M.manifest)try{const N=await Ce(M.manifest);E(N)}catch{E(M)}else E(M)}else E(M)})()},[M,e]),R.useEffect(()=>{k.current=u},[u]);const K=ze(),ee=s||K.service;let ye;ee==="browser"?ye={service:"browser",endpoint:"",apiKey:null,defaultVoice:"Google US English"}:ee==="elevenlabs"?ye={service:"elevenlabs",endpoint:"https://api.elevenlabs.io/v1/text-to-speech",apiKey:r||K.apiKey,defaultVoice:i||K.defaultVoice||Se.defaultVoice,voices:K.voices||Se.voices}:ee==="deepgram"?ye={service:"deepgram",endpoint:"https://api.deepgram.com/v1/speak",apiKey:r||K.apiKey,defaultVoice:i||K.defaultVoice||Oe.defaultVoice,voices:K.voices||Oe.voices}:ye={...K,apiKey:r!==null?r:K.apiKey};const He={url:t,body:e,avatarMood:n,ttsLang:ee==="browser"?"en-US":o,ttsVoice:i||ye.defaultVoice,lipsyncLang:"en",showFullAvatar:u,bodyMovement:c,movementIntensity:l},Be={ttsEndpoint:ye.endpoint,ttsApikey:ye.apiKey,ttsService:ee,lipsyncModules:["en"],cameraView:a},Te=R.useCallback(async()=>{if(!(!F.current||x.current))try{re(!0),xe(null),x.current=new Ne(F.current,Be),await x.current.showAvatar(He,z=>{if(z.lengthComputable){const N=Math.min(100,Math.round(z.loaded/z.total*100));h(N)}}),re(!1),ve(!0),d(x.current);const C=()=>{document.visibilityState==="visible"?x.current?.start():x.current?.stop()};return document.addEventListener("visibilitychange",C),()=>{document.removeEventListener("visibilitychange",C)}}catch(C){console.error("Error initializing TalkingHead:",C),xe(C.message||"Failed to initialize avatar"),re(!1),g(C)}},[]);R.useEffect(()=>(Te(),()=>{x.current&&(x.current.stop(),x.current.dispose(),x.current=null)}),[Te]);const w=R.useCallback(async()=>{if(x.current)try{const C=x.current.audioCtx||x.current.audioContext;C&&(C.state==="suspended"||C.state==="interrupted")&&await C.resume()}catch(C){console.warn("Failed to resume audio context:",C)}},[]),X=R.useCallback(C=>{if(!L)return null;let z=null;if(L._genderSpecific){const Q=(e?.toUpperCase()||"F")==="M"?"male":"female",q=L._genderSpecific[Q];q&&q[C]?z=q[C]:L._genderSpecific.shared&&L._genderSpecific.shared[C]&&(z=L._genderSpecific.shared[C])}if(!z&&L[C]&&(z=L[C]),!z)return null;if(Array.isArray(z)&&z.length>0){const N=Math.floor(Math.random()*z.length);return z[N]}return typeof z=="string"?z:null},[L,e]),te=R.useCallback(C=>C?C.split("/").pop().replace(".fbx","").replace(/[-_]/g," "):"Unknown",[]),ne=R.useCallback((C,z=!1,N=null)=>{if(!x.current)return null;const Q=X(C);if(Q)try{const q=te(Q);console.log(`🎬 Playing animation: "${q}"`);const me=()=>{Z.current&&se.current===C?setTimeout(()=>{ne(C,z,N)},100):N&&N()};return x.current.playAnimation(Q,null,10,0,.01,z,me),Q}catch(q){return console.error("Failed to play animation:",q),null}return null},[X,te]),le=R.useCallback(async(C,z={})=>{if(!x.current||!oe||!C||C.trim()==="")return;await w();const N=z.animationGroup||p;N&&!z.skipAnimation&&(Z.current=!0,se.current=N,ne(N)),G.current={remainingText:null,originalText:null,options:null},j.current=[],T.current={text:C,options:z},A.current&&(clearInterval(A.current),A.current=null),I(!1),W.current=!1;const Q=C.split(/[.!?]+/).filter(me=>me.trim().length>0);j.current=Q;const q={lipsyncLang:z.lipsyncLang||"en",onSpeechEnd:()=>{A.current&&(clearInterval(A.current),A.current=null),Z.current=!1,se.current=null,z.onSpeechEnd&&z.onSpeechEnd(),v()}};try{x.current.speakText(C,q)}catch(me){console.error("Error speaking text:",me),xe(me.message||"Failed to speak text")}},[oe,v,w,p,ne]);R.useEffect(()=>{if(!oe||!O||!x.current)return;D.current&&clearInterval(D.current);const C=()=>{x.current&&!W.current&&ne(O)};return C(),D.current=setInterval(()=>{C()},12e3+Math.random()*3e3),()=>{D.current&&(clearInterval(D.current),D.current=null)}},[oe,O,ne]),R.useEffect(()=>{oe&&U&&P&&x.current&&le(U)},[oe,U,P,le]);const J=R.useCallback(()=>{if(x.current)try{const C=x.current.isSpeaking||!1,z=x.current.audioPlaylist||[],N=x.current.speechQueue||[];if(C||z.length>0||N.length>0){A.current&&(clearInterval(A.current),A.current=null);let Q="";N.length>0&&(Q=N.map(q=>q.text&&Array.isArray(q.text)?q.text.map(me=>me.word).join(" "):q.text||"").join(" ")),G.current={remainingText:Q||null,originalText:T.current?.text||null,options:T.current?.options||null},x.current.speechQueue.length=0,x.current.pauseSpeaking(),I(!0),W.current=!0}}catch(C){console.warn("Error pausing speech:",C)}},[]),de=R.useCallback(async()=>{if(!(!x.current||!$))try{await w(),I(!1),W.current=!1;const C=G.current?.remainingText,z=G.current?.originalText||T.current?.text,N=G.current?.options||T.current?.options||{},Q=C||z;Q&&le(Q,N)}catch(C){console.warn("Error resuming speech:",C),I(!1),W.current=!1}},[$,le,w]),ke=R.useCallback(()=>{x.current&&(x.current.stopSpeaking(),A.current&&(clearInterval(A.current),A.current=null),Z.current=!1,se.current=null,I(!1),W.current=!1)},[]);return R.useImperativeHandle(y,()=>({speakText:le,pauseSpeaking:J,resumeSpeaking:de,stopSpeaking:ke,resumeAudioContext:w,isPaused:()=>$,setMood:C=>x.current?.setMood(C),setBodyMovement:C=>{x.current&&x.current.setBodyMovement(C)},playAnimation:(C,z=!1)=>{x.current&&x.current.playAnimation&&x.current.playAnimation(C,null,10,0,.01,z)},playRandomAnimation:(C,z=!1)=>ne(C,z),getRandomAnimation:C=>X(C),playReaction:C=>x.current?.playReaction(C),playCelebration:()=>x.current?.playCelebration(),setShowFullAvatar:C=>{x.current&&(k.current=C,x.current.setShowFullAvatar(C))},isReady:oe,talkingHead:x.current})),V.jsxs("div",{className:`simple-talking-avatar-container ${b}`,style:S,children:[V.jsx("div",{ref:F,className:"talking-head-viewer",style:{width:"100%",height:"100%",minHeight:"400px"}}),Y&&V.jsx("div",{className:"loading-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"white",fontSize:"18px",zIndex:10},children:"Loading avatar..."}),ae&&V.jsx("div",{className:"error-overlay",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"#ff6b6b",fontSize:"16px",textAlign:"center",zIndex:10,padding:"20px",borderRadius:"8px"},children:ae})]})});qe.displayName="SimpleTalkingAvatar";const _e=R.forwardRef(({curriculumData:U=null,avatarConfig:t={},animations:e={},onLessonStart:n=()=>{},onLessonComplete:o=()=>{},onQuestionAnswer:s=()=>{},onCurriculumComplete:i=()=>{},onCustomAction:r=()=>{},autoStart:c=!1},l)=>{const u=R.useRef(null),a=R.useRef({currentModuleIndex:0,currentLessonIndex:0,currentQuestionIndex:0,isTeaching:!1,isQuestionMode:!1,lessonCompleted:!1,curriculumCompleted:!1,score:0,totalQuestions:0}),d=R.useRef({onLessonStart:n,onLessonComplete:o,onQuestionAnswer:s,onCurriculumComplete:i,onCustomAction:r}),h=R.useRef(null),g=R.useRef(null),v=R.useRef(null),b=R.useRef(null),S=R.useRef(null),M=R.useRef(null),p=R.useRef(null),O=R.useRef(U?.curriculum||{title:"Default Curriculum",description:"No curriculum data provided",language:"en",modules:[]}),P=R.useRef({avatarUrl:t.avatarUrl||"/avatars/brunette.glb",avatarBody:t.avatarBody||"F",mood:t.mood||"happy",ttsLang:t.ttsLang||"en",ttsService:t.ttsService||null,ttsVoice:t.ttsVoice||null,ttsApiKey:t.ttsApiKey||null,bodyMovement:t.bodyMovement||"gesturing",movementIntensity:t.movementIntensity||.7,showFullAvatar:t.showFullAvatar!==void 0?t.showFullAvatar:!1,animations:e,lipsyncLang:"en"});R.useEffect(()=>{d.current={onLessonStart:n,onLessonComplete:o,onQuestionAnswer:s,onCurriculumComplete:i,onCustomAction:r}},[n,o,s,i,r]),R.useEffect(()=>{O.current=U?.curriculum||{title:"Default Curriculum",description:"No curriculum data provided",language:"en",modules:[]},P.current={avatarUrl:t.avatarUrl||"/avatars/brunette.glb",avatarBody:t.avatarBody||"F",mood:t.mood||"happy",ttsLang:t.ttsLang||"en",ttsService:t.ttsService||null,ttsVoice:t.ttsVoice||null,ttsApiKey:t.ttsApiKey||null,bodyMovement:t.bodyMovement||"gesturing",movementIntensity:t.movementIntensity||.7,showFullAvatar:t.showFullAvatar!==void 0?t.showFullAvatar:!1,animations:e,lipsyncLang:"en"}},[U,t,e]);const y=R.useCallback(()=>(O.current||{modules:[]}).modules[a.current.currentModuleIndex]?.lessons[a.current.currentLessonIndex],[]),F=R.useCallback(()=>y()?.questions[a.current.currentQuestionIndex],[y]),x=R.useCallback((I,L)=>L.type==="multiple_choice"||L.type==="true_false"?I===L.answer:L.type==="code_test"&&typeof I=="object"&&I!==null?I.passed===!0:!1,[]),k=R.useCallback(()=>{a.current.lessonCompleted=!0,a.current.isQuestionMode=!1;const I=a.current.totalQuestions>0?Math.round(a.current.score/a.current.totalQuestions*100):100;let L="Congratulations! You've completed this lesson";if(a.current.totalQuestions>0?L+=` You got ${a.current.score} correct out of ${a.current.totalQuestions} question${a.current.totalQuestions===1?"":"s"}, achieving a score of ${I} percent. `:L+="! ",I>=80?L+="Excellent work! You have a great understanding of this topic.":I>=60?L+="Good job! You understand most of the concepts.":L+="Keep practicing! You're making progress.",d.current.onLessonComplete({moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,score:a.current.score,totalQuestions:a.current.totalQuestions,percentage:I}),d.current.onCustomAction({type:"lessonComplete",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,score:a.current.score,totalQuestions:a.current.totalQuestions,percentage:I}),u.current){if(u.current.setMood("happy"),e.lessonComplete)try{u.current.playAnimation(e.lessonComplete,!0)}catch{u.current.playCelebration()}const E=O.current||{modules:[]},D=E.modules[a.current.currentModuleIndex],Z=a.current.currentLessonIndex<(D?.lessons?.length||0)-1,se=a.current.currentModuleIndex<(E.modules?.length||0)-1,K=Z||se,ee=P.current||{lipsyncLang:"en"};u.current.speakText(L,{lipsyncLang:ee.lipsyncLang,onSpeechEnd:()=>{d.current.onCustomAction({type:"lessonCompleteFeedbackDone",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,score:a.current.score,totalQuestions:a.current.totalQuestions,percentage:I,hasNextLesson:K})}})}},[e.lessonComplete]),T=R.useCallback(()=>{a.current.curriculumCompleted=!0;const I=O.current||{modules:[]};if(d.current.onCurriculumComplete({modules:I.modules.length,totalLessons:I.modules.reduce((L,E)=>L+E.lessons.length,0)}),u.current){if(u.current.setMood("celebrating"),e.curriculumComplete)try{u.current.playAnimation(e.curriculumComplete,!0)}catch{u.current.playCelebration()}const L=P.current||{lipsyncLang:"en"};u.current.speakText("Amazing! You've completed the entire curriculum! You're now ready to move on to more advanced topics. Well done!",{lipsyncLang:L.lipsyncLang})}},[e.curriculumComplete]),A=R.useCallback(()=>{const I=y();a.current.isQuestionMode=!0,a.current.currentQuestionIndex=0,a.current.totalQuestions=I?.questions?.length||0,a.current.score=0;const L=F();L&&d.current.onCustomAction({type:"questionStart",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,totalQuestions:a.current.totalQuestions,question:L,score:a.current.score});const E=()=>{if(!u.current||!L)return;if(u.current.setMood("happy"),e.questionStart)try{u.current.playAnimation(e.questionStart,!0)}catch(Z){console.warn("Failed to play questionStart animation:",Z)}const D=P.current||{lipsyncLang:"en"};L.type==="code_test"?u.current.speakText(`Let's test your coding skills! Here's your first challenge: ${L.question}`,{lipsyncLang:D.lipsyncLang}):L.type==="multiple_choice"?u.current.speakText(`Now let me ask you some questions. Here's the first one: ${L.question}`,{lipsyncLang:D.lipsyncLang}):L.type==="true_false"?u.current.speakText(`Let's start with some true or false questions. First question: ${L.question}`,{lipsyncLang:D.lipsyncLang}):u.current.speakText(`Now let me ask you some questions. Here's the first one: ${L.question}`,{lipsyncLang:D.lipsyncLang})};if(u.current&&u.current.isReady&&L)E();else if(u.current&&u.current.isReady){const D=P.current||{lipsyncLang:"en"};u.current.speakText("Now let me ask you some questions to test your understanding.",{lipsyncLang:D.lipsyncLang})}else{const D=setInterval(()=>{u.current&&u.current.isReady&&(clearInterval(D),L&&E())},100);setTimeout(()=>{clearInterval(D)},5e3)}},[e.questionStart,y,F]),W=R.useCallback(()=>{const I=y();if(a.current.currentQuestionIndex<(I?.questions?.length||0)-1){u.current&&u.current.stopSpeaking&&u.current.stopSpeaking(),a.current.currentQuestionIndex+=1;const L=F();L&&d.current.onCustomAction({type:"nextQuestion",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,totalQuestions:a.current.totalQuestions,question:L,score:a.current.score});const E=()=>{if(!u.current||!L)return;if(u.current.setMood("happy"),u.current.setBodyMovement("idle"),e.nextQuestion)try{u.current.playAnimation(e.nextQuestion,!0)}catch(ee){console.warn("Failed to play nextQuestion animation:",ee)}const D=P.current||{lipsyncLang:"en"},se=y()?.questions?.length||0,K=a.current.currentQuestionIndex>=se-1;if(L.type==="code_test"){const ee=K?`Great! Here's your final coding challenge: ${L.question}`:`Great! Now let's move on to your next coding challenge: ${L.question}`;u.current.speakText(ee,{lipsyncLang:D.lipsyncLang})}else if(L.type==="multiple_choice"){const ee=K?`Alright! Here's your final question: ${L.question}`:`Alright! Here's your next question: ${L.question}`;u.current.speakText(ee,{lipsyncLang:D.lipsyncLang})}else if(L.type==="true_false"){const ee=K?`Now let's try this final one: ${L.question}`:`Now let's try this one: ${L.question}`;u.current.speakText(ee,{lipsyncLang:D.lipsyncLang})}else{const ee=K?`Here's your final question: ${L.question}`:`Here's the next question: ${L.question}`;u.current.speakText(ee,{lipsyncLang:D.lipsyncLang})}};if(u.current&&u.current.isReady&&L)E();else if(L){const D=setInterval(()=>{u.current&&u.current.isReady&&(clearInterval(D),E())},100);setTimeout(()=>{clearInterval(D)},5e3)}}else d.current.onCustomAction({type:"allQuestionsComplete",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,totalQuestions:a.current.totalQuestions,score:a.current.score})},[e.nextQuestion,y,F]),G=R.useCallback(()=>{const I=O.current||{modules:[]},L=I.modules[a.current.currentModuleIndex];if(a.current.currentLessonIndex<(L?.lessons?.length||0)-1){a.current.currentLessonIndex+=1,a.current.currentQuestionIndex=0,a.current.lessonCompleted=!1,a.current.isQuestionMode=!1,a.current.isTeaching=!1,a.current.score=0,a.current.totalQuestions=0;const D=I.modules[a.current.currentModuleIndex],Z=a.current.currentLessonIndex<(D?.lessons?.length||0)-1,se=a.current.currentModuleIndex<(I.modules?.length||0)-1,K=Z||se;d.current.onCustomAction({type:"lessonStart",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,hasNextLesson:K}),d.current.onLessonStart({moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:y()}),u.current&&(u.current.setMood("happy"),u.current.setBodyMovement("idle"))}else if(a.current.currentModuleIndex<(I.modules?.length||0)-1){a.current.currentModuleIndex+=1,a.current.currentLessonIndex=0,a.current.currentQuestionIndex=0,a.current.lessonCompleted=!1,a.current.isQuestionMode=!1,a.current.isTeaching=!1,a.current.score=0,a.current.totalQuestions=0;const Z=I.modules[a.current.currentModuleIndex],se=a.current.currentLessonIndex<(Z?.lessons?.length||0)-1,K=a.current.currentModuleIndex<(I.modules?.length||0)-1,ee=se||K;d.current.onCustomAction({type:"lessonStart",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,hasNextLesson:ee}),d.current.onLessonStart({moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:y()}),u.current&&(u.current.setMood("happy"),u.current.setBodyMovement("idle"))}else S.current&&S.current()},[]),j=R.useCallback(()=>{const I=y();let L=null;if(I?.avatar_script&&I?.body){const E=I.avatar_script.trim(),D=I.body.trim(),Z=E.match(/[.!?]$/)?" ":". ";L=`${E}${Z}${D}`}else L=I?.avatar_script||I?.body||null;if(u.current&&u.current.isReady&&L){a.current.isTeaching=!0,a.current.isQuestionMode=!1,a.current.score=0,a.current.totalQuestions=0,u.current.setMood("happy");let E=!1;if(e.teaching)try{u.current.playAnimation(e.teaching,!0),E=!0}catch(Z){console.warn("Failed to play teaching animation:",Z)}E||u.current.setBodyMovement("gesturing");const D=P.current||{lipsyncLang:"en"};d.current.onLessonStart({moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:I}),d.current.onCustomAction({type:"teachingStart",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:I}),u.current.speakText(L,{lipsyncLang:D.lipsyncLang,onSpeechEnd:()=>{a.current.isTeaching=!1,d.current.onCustomAction({type:"teachingComplete",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:I,hasQuestions:I.questions&&I.questions.length>0}),I?.code_example&&d.current.onCustomAction({type:"codeExampleReady",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:I,codeExample:I.code_example})}})}},[e.teaching,y]),Y=R.useCallback(I=>{const L=F(),E=x(I,L);if(E&&(a.current.score+=1),d.current.onQuestionAnswer({moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,answer:I,isCorrect:E,question:L}),u.current)if(E){if(u.current.setMood("happy"),e.correct)try{u.current.playReaction("happy")}catch{u.current.setBodyMovement("happy")}u.current.setBodyMovement("gesturing");const Z=y()?.questions?.length||0;a.current.currentQuestionIndex>=Z-1;const se=a.current.currentQuestionIndex<Z-1;console.log("[CurriculumLearning] Answer feedback - questionIndex:",a.current.currentQuestionIndex,"totalQuestions:",Z,"hasNextQuestion:",se);const K=L.type==="code_test"?`Great job! Your code passed all the tests! ${L.explanation||""}`:`Excellent! That's correct! ${L.explanation||""}`,ee=P.current||{lipsyncLang:"en"};u.current.speakText(K,{lipsyncLang:ee.lipsyncLang,onSpeechEnd:()=>{d.current.onCustomAction({type:"answerFeedbackComplete",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,isCorrect:!0,hasNextQuestion:se,score:a.current.score,totalQuestions:a.current.totalQuestions})}})}else{if(u.current.setMood("sad"),e.incorrect)try{u.current.playAnimation(e.incorrect,!0)}catch{u.current.setBodyMovement("idle")}u.current.setBodyMovement("gesturing");const Z=y()?.questions?.length||0,se=a.current.currentQuestionIndex>=Z-1,K=a.current.currentQuestionIndex<Z-1;console.log("[CurriculumLearning] Answer feedback (incorrect) - questionIndex:",a.current.currentQuestionIndex,"totalQuestions:",Z,"hasNextQuestion:",K);const ee=L.type==="code_test"?`Your code didn't pass all the tests. ${L.explanation||"Try again!"}`:`Not quite right, but don't worry! ${L.explanation||""}${se?"":" Let's move on to the next question."}`,ye=P.current||{lipsyncLang:"en"};u.current.speakText(ee,{lipsyncLang:ye.lipsyncLang,onSpeechEnd:()=>{d.current.onCustomAction({type:"answerFeedbackComplete",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,isCorrect:!1,hasNextQuestion:K,score:a.current.score,totalQuestions:a.current.totalQuestions})}})}else{const Z=y()?.questions?.length||0;d.current.onCustomAction({type:"answerFeedbackComplete",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,isCorrect:E,hasNextQuestion:a.current.currentQuestionIndex<Z-1,score:a.current.score,totalQuestions:a.current.totalQuestions,avatarNotReady:!0})}},[e.correct,e.incorrect,F,y,x]),re=R.useCallback(I=>{const L=F();if(!I||typeof I!="object"){console.error("Invalid code test result format. Expected object with {passed: boolean, ...}");return}if(L?.type!=="code_test"){console.warn("Current question is not a code test. Use handleAnswerSelect for other question types.");return}const E={passed:I.passed===!0,results:I.results||[],output:I.output||"",error:I.error||null,executionTime:I.executionTime||null,testCount:I.testCount||0,passedCount:I.passedCount||0,failedCount:I.failedCount||0};d.current.onCustomAction({type:"codeTestSubmitted",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,testResult:E,question:L}),p.current&&p.current(E)},[F,x]),ae=R.useCallback(()=>{if(a.current.currentQuestionIndex>0){a.current.currentQuestionIndex-=1;const I=F();I&&d.current.onCustomAction({type:"questionStart",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,questionIndex:a.current.currentQuestionIndex,totalQuestions:a.current.totalQuestions,question:I,score:a.current.score});const L=()=>{if(!u.current||!I)return;u.current.setMood("happy"),u.current.setBodyMovement("idle");const E=P.current||{lipsyncLang:"en"};I.type==="code_test"?u.current.speakText(`Let's go back to this coding challenge: ${I.question}`,{lipsyncLang:E.lipsyncLang}):u.current.speakText(`Going back to: ${I.question}`,{lipsyncLang:E.lipsyncLang})};if(u.current&&u.current.isReady&&I)L();else if(I){const E=setInterval(()=>{u.current&&u.current.isReady&&(clearInterval(E),L())},100);setTimeout(()=>{clearInterval(E)},5e3)}}},[F]),xe=R.useCallback(()=>{const I=O.current||{modules:[]};if(I.modules[a.current.currentModuleIndex],a.current.currentLessonIndex>0)a.current.currentLessonIndex-=1,a.current.currentQuestionIndex=0,a.current.lessonCompleted=!1,a.current.isQuestionMode=!1,a.current.isTeaching=!1,a.current.score=0,a.current.totalQuestions=0,d.current.onCustomAction({type:"lessonStart",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex}),d.current.onLessonStart({moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:y()}),u.current&&(u.current.setMood("happy"),u.current.setBodyMovement("idle"));else if(a.current.currentModuleIndex>0){const D=I.modules[a.current.currentModuleIndex-1];a.current.currentModuleIndex-=1,a.current.currentLessonIndex=(D?.lessons?.length||1)-1,a.current.currentQuestionIndex=0,a.current.lessonCompleted=!1,a.current.isQuestionMode=!1,a.current.isTeaching=!1,a.current.score=0,a.current.totalQuestions=0,d.current.onCustomAction({type:"lessonStart",moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex}),d.current.onLessonStart({moduleIndex:a.current.currentModuleIndex,lessonIndex:a.current.currentLessonIndex,lesson:y()}),u.current&&(u.current.setMood("happy"),u.current.setBodyMovement("idle"))}},[y]),oe=R.useCallback(()=>{a.current.currentModuleIndex=0,a.current.currentLessonIndex=0,a.current.currentQuestionIndex=0,a.current.isTeaching=!1,a.current.isQuestionMode=!1,a.current.lessonCompleted=!1,a.current.curriculumCompleted=!1,a.current.score=0,a.current.totalQuestions=0},[]),ve=R.useCallback(I=>{console.log("Avatar is ready!",I);const L=y(),E=L?.avatar_script||L?.body;c&&E&&setTimeout(()=>{h.current&&h.current()},10)},[c,y]);R.useLayoutEffect(()=>{h.current=j,g.current=G,v.current=k,b.current=W,S.current=T,M.current=A,p.current=Y}),R.useImperativeHandle(l,()=>({startTeaching:j,startQuestions:A,handleAnswerSelect:Y,handleCodeTestResult:re,nextQuestion:W,previousQuestion:ae,nextLesson:G,previousLesson:xe,completeLesson:k,completeCurriculum:T,resetCurriculum:oe,getState:()=>({...a.current}),getCurrentQuestion:()=>F(),getCurrentLesson:()=>y(),getAvatarRef:()=>u.current,speakText:async(I,L={})=>{await u.current?.resumeAudioContext?.();const E=P.current||{lipsyncLang:"en"};u.current?.speakText(I,{...L,lipsyncLang:L.lipsyncLang||E.lipsyncLang})},resumeAudioContext:async()=>{if(u.current?.resumeAudioContext)return await u.current.resumeAudioContext();const I=u.current?.talkingHead;if(I?.audioCtx){const L=I.audioCtx;if(L.state==="suspended"||L.state==="interrupted")try{await L.resume(),console.log("Audio context resumed via talkingHead")}catch(E){console.warn("Failed to resume audio context:",E)}}else console.warn("Audio context not available yet")},stopSpeaking:()=>u.current?.stopSpeaking(),pauseSpeaking:()=>u.current?.pauseSpeaking(),resumeSpeaking:async()=>await u.current?.resumeSpeaking(),isPaused:()=>u.current&&typeof u.current.isPaused<"u"?u.current.isPaused:!1,setMood:I=>u.current?.setMood(I),playAnimation:(I,L)=>u.current?.playAnimation(I,L),setBodyMovement:I=>u.current?.setBodyMovement(I),setMovementIntensity:I=>u.current?.setMovementIntensity(I),playRandomDance:()=>u.current?.playRandomDance(),playReaction:I=>u.current?.playReaction(I),playCelebration:()=>u.current?.playCelebration(),setShowFullAvatar:I=>u.current?.setShowFullAvatar(I),setTimingAdjustment:I=>u.current?.setTimingAdjustment(I),lockAvatarPosition:()=>u.current?.lockAvatarPosition(),unlockAvatarPosition:()=>u.current?.unlockAvatarPosition(),triggerCustomAction:(I,L)=>{d.current.onCustomAction({type:I,...L,state:{...a.current}})},handleResize:()=>u.current?.handleResize(),isAvatarReady:()=>u.current?.isReady||!1}),[j,A,Y,re,W,G,k,T,oe,F,y]);const $=P.current||{avatarUrl:"/avatars/brunette.glb",avatarBody:"F",mood:"happy",ttsLang:"en",ttsService:null,ttsVoice:null,ttsApiKey:null,bodyMovement:"gesturing",movementIntensity:.7,showFullAvatar:!1,animations:e};return V.jsx("div",{style:{width:"100%",height:"100%"},children:V.jsx(Ue,{ref:u,avatarUrl:$.avatarUrl,avatarBody:$.avatarBody,mood:$.mood,ttsLang:$.ttsLang,ttsService:$.ttsService,ttsVoice:$.ttsVoice,ttsApiKey:$.ttsApiKey,bodyMovement:$.bodyMovement,movementIntensity:$.movementIntensity,showFullAvatar:$.showFullAvatar,cameraView:"upper",animations:$.animations,onReady:ve,onLoading:()=>{},onError:I=>{console.error("Avatar error:",I)}})})});_e.displayName="CurriculumLearning";function Lt({manifestPath:U="/animations/manifest.json",avatarBody:t="F",onAnimationPlay:e=null,onAnimationsSelected:n=null,onDeleteAnimations:o=null,style:s={}}){const[i,r]=R.useState([]),[c,l]=R.useState(new Set),[u,a]=R.useState(!0),[d,h]=R.useState(null),[g,v]=R.useState("all"),[b,S]=R.useState("");R.useEffect(()=>{(async()=>{a(!0),h(null);try{const T=await Ce(U),A=[];if(T._genderSpecific){const G=(t?.toUpperCase()||"F")==="M"?"male":"female";T._genderSpecific[G]&&Object.entries(T._genderSpecific[G]).forEach(([j,Y])=>{(Array.isArray(Y)?Y:[Y]).forEach(ae=>{A.push({path:ae,group:j,gender:G,name:ae.split("/").pop().replace(".fbx","")})})}),T._genderSpecific.shared&&Object.entries(T._genderSpecific.shared).forEach(([j,Y])=>{(Array.isArray(Y)?Y:[Y]).forEach(ae=>{A.push({path:ae,group:j,gender:"shared",name:ae.split("/").pop().replace(".fbx","")})})})}Object.entries(T).forEach(([W,G])=>{W!=="_genderSpecific"&&(Array.isArray(G)?G:[G]).forEach(Y=>{typeof Y=="string"&&A.push({path:Y,group:W,gender:"root",name:Y.split("/").pop().replace(".fbx","")})})}),r(A),a(!1)}catch(T){console.error("Failed to load animations:",T),h(T.message),a(!1)}})()},[U,t]);const M=["all",...new Set(i.map(k=>k.group))],p=i.filter(k=>{const T=g==="all"||k.group===g,A=b===""||k.name.toLowerCase().includes(b.toLowerCase())||k.path.toLowerCase().includes(b.toLowerCase());return T&&A}),O=k=>{const T=new Set(c);T.has(k)?T.delete(k):T.add(k),l(T),n&&n(Array.from(T))},P=()=>{const k=new Set(c);p.forEach(T=>{k.add(T.path)}),l(k),n&&n(Array.from(k))},y=()=>{const k=new Set(c);p.forEach(T=>{k.delete(T.path)}),l(k),n&&n(Array.from(k))},F=()=>{const T=i.filter(A=>!c.has(A.path)).map(A=>A.path);if(T.length===0){alert("No animations to delete. Select animations to keep, then delete will remove the unselected ones.");return}window.confirm(`Are you sure you want to delete ${T.length} animation(s)?
8
8
 
9
9
  This will delete:
10
- ${H.slice(0,5).join(`
11
- `)}${H.length>5?`
12
- ...`:""}`)&&(i&&i(H),r(o.filter(f=>u.has(f.path))),a(new Set))},k=A=>{e&&e(A)};return c?X.jsx("div",{style:{padding:"20px",textAlign:"center",...s},children:X.jsx("p",{children:"Loading animations..."})}):d?X.jsx("div",{style:{padding:"20px",color:"red",...s},children:X.jsxs("p",{children:["Error loading animations: ",d]})}):X.jsxs("div",{style:{padding:"20px",backgroundColor:"#2a2a2a",borderRadius:"8px",color:"#fff",...s},children:[X.jsx("h2",{style:{marginTop:0},children:"Animation Selector"}),X.jsx("p",{style:{color:"#aaa",fontSize:"14px"},children:"Click buttons to play animations. Select animations to keep, then delete will remove the rest."}),X.jsxs("div",{style:{display:"flex",gap:"10px",marginBottom:"20px",flexWrap:"wrap",alignItems:"center"},children:[X.jsx("input",{type:"text",placeholder:"Search animations...",value:y,onChange:A=>w(A.target.value),style:{padding:"8px 12px",borderRadius:"6px",border:"1px solid #555",backgroundColor:"#333",color:"#fff",fontSize:"14px",flex:"1",minWidth:"200px"}}),X.jsx("select",{value:p,onChange:A=>v(A.target.value),style:{padding:"8px 12px",borderRadius:"6px",border:"1px solid #555",backgroundColor:"#333",color:"#fff",fontSize:"14px"},children:M.map(A=>X.jsx("option",{value:A,children:A==="all"?"All Groups":A},A))}),X.jsx("button",{onClick:E,style:{padding:"8px 16px",backgroundColor:"#4CAF50",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"14px"},children:"Select All Visible"}),X.jsx("button",{onClick:L,style:{padding:"8px 16px",backgroundColor:"#666",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"14px"},children:"Deselect All Visible"}),X.jsxs("button",{onClick:W,style:{padding:"8px 16px",backgroundColor:"#f44336",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"14px",fontWeight:"bold"},children:["Delete Unselected (",o.length-u.size,")"]})]}),X.jsxs("div",{style:{marginBottom:"15px",fontSize:"14px",color:"#aaa"},children:["Total: ",o.length," | Selected: ",u.size," | Showing: ",g.length]}),X.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(200px, 1fr))",gap:"10px",maxHeight:"500px",overflowY:"auto",padding:"10px",backgroundColor:"#1a1a1a",borderRadius:"6px"},children:g.map((A,H)=>{const f=u.has(A.path);return X.jsxs("div",{style:{border:`2px solid ${f?"#4CAF50":"#555"}`,borderRadius:"6px",padding:"10px",backgroundColor:f?"#2a4a2a":"#222",cursor:"pointer",transition:"all 0.2s"},onClick:()=>U(A.path),children:[X.jsxs("div",{style:{marginBottom:"8px"},children:[X.jsx("input",{type:"checkbox",checked:f,onChange:()=>U(A.path),onClick:P=>P.stopPropagation(),style:{marginRight:"8px",cursor:"pointer"}}),X.jsxs("span",{style:{fontSize:"12px",color:"#aaa"},children:[A.group," ",A.gender!=="root"&&`(${A.gender})`]})]}),X.jsx("div",{style:{fontSize:"13px",fontWeight:"bold",marginBottom:"8px",wordBreak:"break-word"},children:A.name}),X.jsx("button",{onClick:P=>{P.stopPropagation(),k(A.path)},style:{width:"100%",padding:"6px",backgroundColor:"#2196F3",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"12px"},children:"▶ Play"})]},`${A.path}-${H}`)})}),g.length===0&&X.jsx("div",{style:{padding:"40px",textAlign:"center",color:"#aaa"},children:"No animations found matching your filters."})]})}const We={dance:{name:"dance",type:"code-based",variations:["dancing","dancing2","dancing3"],loop:!0,duration:1e4,description:"Celebration dance animation with multiple variations"},happy:{name:"happy",type:"code-based",loop:!0,duration:5e3,description:"Happy, upbeat body movement"},surprised:{name:"surprised",type:"code-based",loop:!1,duration:3e3,description:"Surprised reaction with quick movements"},thinking:{name:"thinking",type:"code-based",loop:!0,duration:8e3,description:"Thoughtful, contemplative movement"},nodding:{name:"nodding",type:"code-based",loop:!1,duration:2e3,description:"Nodding agreement gesture"},shaking:{name:"shaking",type:"code-based",loop:!1,duration:2e3,description:"Shaking head disagreement gesture"},celebration:{name:"celebration",type:"code-based",loop:!1,duration:3e3,description:"Celebration animation for achievements"},energetic:{name:"energetic",type:"code-based",loop:!0,duration:6e3,description:"High-energy, enthusiastic movement"},swaying:{name:"swaying",type:"code-based",loop:!0,duration:8e3,description:"Gentle swaying motion"},bouncing:{name:"bouncing",type:"code-based",loop:!0,duration:4e3,description:"Bouncy, playful movement"},gesturing:{name:"gesturing",type:"code-based",loop:!0,duration:5e3,description:"Teaching gesture animation"},walking:{name:"walking",type:"code-based",loop:!0,duration:6e3,description:"Walking motion"},prancing:{name:"prancing",type:"code-based",loop:!0,duration:4e3,description:"Playful prancing movement"},excited:{name:"excited",type:"code-based",loop:!0,duration:5e3,description:"Excited, energetic movement"}},Lt=G=>We[G]||null,St=G=>We.hasOwnProperty(G);exports.AnimationSelector=It;exports.CurriculumLearning=qe;exports.SimpleTalkingAvatar=Qe;exports.TalkingHeadAvatar=Ue;exports.TalkingHeadComponent=Ye;exports.animations=We;exports.getActiveTTSConfig=ze;exports.getAnimation=Lt;exports.getVoiceOptions=Rt;exports.hasAnimation=St;
10
+ ${T.slice(0,5).join(`
11
+ `)}${T.length>5?`
12
+ ...`:""}`)&&(o&&o(T),r(i.filter(A=>c.has(A.path))),l(new Set))},x=k=>{e&&e(k)};return u?V.jsx("div",{style:{padding:"20px",textAlign:"center",...s},children:V.jsx("p",{children:"Loading animations..."})}):d?V.jsx("div",{style:{padding:"20px",color:"red",...s},children:V.jsxs("p",{children:["Error loading animations: ",d]})}):V.jsxs("div",{style:{padding:"20px",backgroundColor:"#2a2a2a",borderRadius:"8px",color:"#fff",...s},children:[V.jsx("h2",{style:{marginTop:0},children:"Animation Selector"}),V.jsx("p",{style:{color:"#aaa",fontSize:"14px"},children:"Click buttons to play animations. Select animations to keep, then delete will remove the rest."}),V.jsxs("div",{style:{display:"flex",gap:"10px",marginBottom:"20px",flexWrap:"wrap",alignItems:"center"},children:[V.jsx("input",{type:"text",placeholder:"Search animations...",value:b,onChange:k=>S(k.target.value),style:{padding:"8px 12px",borderRadius:"6px",border:"1px solid #555",backgroundColor:"#333",color:"#fff",fontSize:"14px",flex:"1",minWidth:"200px"}}),V.jsx("select",{value:g,onChange:k=>v(k.target.value),style:{padding:"8px 12px",borderRadius:"6px",border:"1px solid #555",backgroundColor:"#333",color:"#fff",fontSize:"14px"},children:M.map(k=>V.jsx("option",{value:k,children:k==="all"?"All Groups":k},k))}),V.jsx("button",{onClick:P,style:{padding:"8px 16px",backgroundColor:"#4CAF50",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"14px"},children:"Select All Visible"}),V.jsx("button",{onClick:y,style:{padding:"8px 16px",backgroundColor:"#666",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"14px"},children:"Deselect All Visible"}),V.jsxs("button",{onClick:F,style:{padding:"8px 16px",backgroundColor:"#f44336",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"14px",fontWeight:"bold"},children:["Delete Unselected (",i.length-c.size,")"]})]}),V.jsxs("div",{style:{marginBottom:"15px",fontSize:"14px",color:"#aaa"},children:["Total: ",i.length," | Selected: ",c.size," | Showing: ",p.length]}),V.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(200px, 1fr))",gap:"10px",maxHeight:"500px",overflowY:"auto",padding:"10px",backgroundColor:"#1a1a1a",borderRadius:"6px"},children:p.map((k,T)=>{const A=c.has(k.path);return V.jsxs("div",{style:{border:`2px solid ${A?"#4CAF50":"#555"}`,borderRadius:"6px",padding:"10px",backgroundColor:A?"#2a4a2a":"#222",cursor:"pointer",transition:"all 0.2s"},onClick:()=>O(k.path),children:[V.jsxs("div",{style:{marginBottom:"8px"},children:[V.jsx("input",{type:"checkbox",checked:A,onChange:()=>O(k.path),onClick:W=>W.stopPropagation(),style:{marginRight:"8px",cursor:"pointer"}}),V.jsxs("span",{style:{fontSize:"12px",color:"#aaa"},children:[k.group," ",k.gender!=="root"&&`(${k.gender})`]})]}),V.jsx("div",{style:{fontSize:"13px",fontWeight:"bold",marginBottom:"8px",wordBreak:"break-word"},children:k.name}),V.jsx("button",{onClick:W=>{W.stopPropagation(),x(k.path)},style:{width:"100%",padding:"6px",backgroundColor:"#2196F3",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"12px"},children:"▶ Play"})]},`${k.path}-${T}`)})}),p.length===0&&V.jsx("div",{style:{padding:"40px",textAlign:"center",color:"#aaa"},children:"No animations found matching your filters."})]})}const We={dance:{name:"dance",type:"code-based",variations:["dancing","dancing2","dancing3"],loop:!0,duration:1e4,description:"Celebration dance animation with multiple variations"},happy:{name:"happy",type:"code-based",loop:!0,duration:5e3,description:"Happy, upbeat body movement"},surprised:{name:"surprised",type:"code-based",loop:!1,duration:3e3,description:"Surprised reaction with quick movements"},thinking:{name:"thinking",type:"code-based",loop:!0,duration:8e3,description:"Thoughtful, contemplative movement"},nodding:{name:"nodding",type:"code-based",loop:!1,duration:2e3,description:"Nodding agreement gesture"},shaking:{name:"shaking",type:"code-based",loop:!1,duration:2e3,description:"Shaking head disagreement gesture"},celebration:{name:"celebration",type:"code-based",loop:!1,duration:3e3,description:"Celebration animation for achievements"},energetic:{name:"energetic",type:"code-based",loop:!0,duration:6e3,description:"High-energy, enthusiastic movement"},swaying:{name:"swaying",type:"code-based",loop:!0,duration:8e3,description:"Gentle swaying motion"},bouncing:{name:"bouncing",type:"code-based",loop:!0,duration:4e3,description:"Bouncy, playful movement"},gesturing:{name:"gesturing",type:"code-based",loop:!0,duration:5e3,description:"Teaching gesture animation"},walking:{name:"walking",type:"code-based",loop:!0,duration:6e3,description:"Walking motion"},prancing:{name:"prancing",type:"code-based",loop:!0,duration:4e3,description:"Playful prancing movement"},excited:{name:"excited",type:"code-based",loop:!0,duration:5e3,description:"Excited, energetic movement"}},St=U=>We[U]||null,kt=U=>We.hasOwnProperty(U);exports.AnimationSelector=Lt;exports.CurriculumLearning=_e;exports.SimpleTalkingAvatar=qe;exports.TalkingHeadAvatar=Ue;exports.TalkingHeadComponent=Qe;exports.animations=We;exports.getActiveTTSConfig=ze;exports.getAnimation=St;exports.getVoiceOptions=It;exports.hasAnimation=kt;