@sage-rsc/talking-head-react 1.0.52 → 1.0.54
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 +2 -2
- package/dist/index.js +1062 -992
- package/package.json +1 -1
- package/src/components/CurriculumLearning.jsx +152 -6
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const te=require("react/jsx-runtime"),A=require("react"),He=require("three"),Te=require("three/addons/controls/OrbitControls.js"),Me=require("three/addons/loaders/GLTFLoader.js"),Ee=require("three/addons/loaders/DRACOLoader.js"),be=require("three/addons/loaders/FBXLoader.js"),Fe=require("three/addons/environments/RoomEnvironment.js"),Pe=require("three/addons/libs/stats.module.js");var pe=typeof document<"u"?document.currentScript:null;function Be(M){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(M){for(const e in M)if(e!=="default"){const i=Object.getOwnPropertyDescriptor(M,e);Object.defineProperty(t,e,i.get?i:{enumerable:!0,get:()=>M[e]})}}return t.default=M,Object.freeze(t)}const f=Be(He);let m,j,_;const L=[0,0,0,0],w=new f.Vector3,he=new f.Vector3,Z=new f.Vector3,ue=new f.Vector3;new f.Plane;new f.Ray;new f.Euler;const X=new f.Quaternion,Re=new f.Quaternion,$=new f.Matrix4,ee=new f.Matrix4;new f.Vector3;const de=new f.Vector3(0,0,1),De=new f.Vector3(1,0,0),Oe=new f.Vector3(0,1,0),Ne=new f.Vector3(0,0,1);class Ue{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 i=this.dict[t];let n;if(e==="type")n=i.type;else if(e==="stiffness")n=i.k.every(s=>s===i.k[0])?i.k[0]:[...i.k];else if(e==="damping")n=i.c.every(s=>s===i.c[0])?i.c[0]:[...i.c];else if(e==="external")n=i.ext<1?i.ext:null;else if(e==="limits")n=i.limits?.map(s=>s===null?null:[...s]);else if(e==="deltaLocal")n=i.dl?[...i.dl]:null;else if(e==="excludes")n=i.excludes?[...i.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")n=i.dw?[...i.dw]:null;else if(e==="pivot")n=i.pivot;else if(e==="helper")n=i.helper;else throw new Error("Unsupported property '"+e+"'.");return n}setValue(t,e,i){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];if(e==="type"){if(!i)throw new Error("Parameter 'type' not set.");if(typeof i!="string")throw new Error("Type must be a string.");switch(i){case"point":n.isPoint=!0,n.isX=!0,n.isY=!0,n.isZ=!0,n.isT=!1;break;case"link":n.isPoint=!1,n.isX=!0,n.isY=!1,n.isZ=!0,n.isT=!1;break;case"mix1":n.isPoint=!1,n.isX=!0,n.isY=!0,n.isZ=!0,n.isT=!1;break;case"mix2":n.isPoint=!1,n.isX=!0,n.isY=!1,n.isZ=!0,n.isT=!0;break;case"full":n.isPoint=!1,n.isX=!0,n.isY=!0,n.isZ=!0,n.isT=!0;break;default:throw new Error("Unknown type'"+i+"'.")}n.type=i.slice()}else if(e==="stiffness"){if(!i)throw new Error("Parameter 'stiffness' not set.");if(!Number.isNaN(i)&&i>=0)n.k=Array(4).fill(i);else if(Array.isArray(i)&&i.length===4&&i.every(s=>s>=0))n.k=[...i];else throw new Error("Stiffness must be a non-negative number or an array of four non-negative numbers.")}else if(e==="damping"){if(!i)throw new Error("Parameter 'damping' not set.");if(!Number.isNaN(i)&&i>=0)n.c=Array(4).fill(i);else if(Array.isArray(i)&&i.length===4&&i.every(s=>s>=0))n.c=[...i];else throw new Error("Damping must be a non-negative number or an array of four non-negative numbers.")}else if(e==="external")if(i==null)n.ext=1;else if(!Number.isNaN(i)&&i>=0&&i<=1)n.ext=i;else throw new Error("External (if set) must be a number between [0,1].");else if(e==="limits")if(i==null)n.limits=null;else{if(!Array.isArray(i)||i.length!==4)throw new Error("Limits (if set) must null, or an array of four arrays.");if(!i.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.");n.limits=[i[0]?[...i[0]]:null,i[1]?[...i[1]]:null,i[2]?[...i[2]]:null,i[3]?[...i[3]]:null]}else if(e==="excludes"){if(i==null)n.excludes=null;else{if(!Array.isArray(i))throw new Error("Excludes (if set) must null, or an array.");n.excludes=[],i.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]}n.excludes.push(u)})}this.showHelpers()}else if(e==="helper"){if(i==null)n.helper=null;else{if(i!==!1&&i!==!0)throw new Error("Helper, if set, must be false or true.");n.helper=i}this.showHelpers()}else if(e==="pivot")if(i==null)n.pivot=null;else{if(i!==!1&&i!==!0)throw new Error("Pivot, if set, must be false or true.");if(i===!0&&n.type===0)throw new Error("Point type bone can't be a pivot.");n.pivot=i}else if(e==="deltaLocal")if(i==null)n.dl=null;else{if(!Array.isArray(i)||i.length!==3)throw new Error("deltaLocal, is set, must be an array of three numbers.");if(!i.every(s=>!Number.isNaN(s)))throw new Error("deltaLocal values must be numbers.");n.dl=[...i]}else if(e==="deltaWorld")if(i==null)n.dw=null;else{if(!Array.isArray(i)||i.length!==3)throw new Error("deltaWorld, is set, must be an array of three values.");if(!i.every(s=>!Number.isNaN(s)))throw new Error("deltaWorld values must be numbers.");n.dw=[...i]}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(i=>{m=this.getValue(t.name,i),m&&(e[i]=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 i=new WeakSet,n=o=>o.parent?.isBone?[o,...n(o.parent)]:[o],s=o=>{n(o).forEach(u=>{i.has(u)||(this.objectsUpdate.push(u),i.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,i){this.dispose();const n=(s,o)=>{if(!s)throw this.dispose(),new Error(o)};n(t?.isScene,"First parameter must be Scene."),this.scene=t,n(e?.isObject3D,"Second parameter must be the armature Object3D."),this.armature=e,n(Array.isArray(i),"Third parameter must be an array of bone configs."),this.config=i,this.config.forEach((s,o)=>{const r="Config item #"+o+": ";n(s.bone,r+"Bone not specified.");const u=s.bone;n(typeof u=="string"&&u.length>0,r+"Bone name must be a non-empty string.");const a=this.armature.getObjectByName(u);n(a,r+"Bone '"+u+"' not found."),n(a.parent?.isBone,r+"Bone must have a parent bone."),n(this.data.every(l=>l.bone!==a),r+"Bone '"+u+"' already exists."),a.updateMatrixWorld(!0);const h={name:u,bone:a,boneParent:a.parent,vBasis:a.position.clone(),vWorld:a.parent.getWorldPosition(w).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]};h.boneParent.matrixWorld.decompose(w,X,Z),w.copy(de).applyQuaternion(X).setY(0).normalize(),X.premultiply(Re.setFromUnitVectors(de,w).invert()).normalize(),h.qWorldInverseYaw=X.clone().normalize(),this.data.push(h),this.dict[u]=h;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){n(!1,r+l)}}),this.sortBones(),this.start()}update(t){if(!this.running)return;let e,i,n,s,o;for(this.timerMs+=t,t>1e3&&(this.timerMs=0),t/=1e3,e=0,n=this.objectsUpdate.length;e<n;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,n=this.data.length;e<n;e++){if(o=this.data[e],w.copy(o.vWorld),$.copy(o.boneParent.matrixWorld),ee.copy($).invert(),o.vWorld.setFromMatrixPosition($),w.applyMatrix4(ee),w.length()>.5&&(console.info("Info: Unrealistic jump of "+w.length().toFixed(2)+" meters."),w.setLength(.5)),w.applyQuaternion(o.bone.quaternion),L[0]=w.x,L[1]=w.y,L[2]=-w.z,L[3]=w.length()/3,o.children)for(i=0,s=o.children.length;i<s;i++)m=o.children[i],L[0]-=m.v[0]*t/3,L[1]-=m.v[1]*t/3,L[2]+=m.v[2]*t/3,L[3]-=m.v[3]*t/3;if(m=this.opt.sensitivityFactor,L[0]*=o.ext*m,L[1]*=o.ext*m,L[2]*=o.ext*m,L[3]*=o.ext*m,o.isX&&(m=L[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+L[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=L[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+L[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=L[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+L[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=L[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+L[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),L[0]=o.p[0],L[1]=o.p[1],L[2]=o.p[2],L[3]=o.p[3],m=this.opt.movementFactor,L[0]*=m,L[1]*=m,L[2]*=m,L[3]*=m,o.dl&&(m=o.dl,L[0]+=m[0],L[1]+=m[1],L[2]+=m[2]),o.dw&&(m=o.dw,w.set(o.vBasis.x+L[0],o.vBasis.y+L[1],o.vBasis.z+L[2]),w.applyMatrix4($),w.x+=m[0],w.y+=m[1],w.z+=m[2],w.applyMatrix4(ee),L[0]+=w.x-o.vBasis.x,L[1]+=w.y-o.vBasis.y,L[2]+=w.z-o.vBasis.z),o.limits&&this.opt.isLimits&&(m=o.limits,m[0]&&(m[0][0]!==null&&L[0]<m[0][0]&&(L[0]=m[0][0]),m[0][1]!==null&&L[0]>m[0][1]&&(L[0]=m[0][1])),m[1]&&(m[1][0]!==null&&L[1]<m[1][0]&&(L[1]=m[1][0]),m[1][1]!==null&&L[1]>m[1][1]&&(L[1]=m[1][1])),m[2]&&(m[2][0]!==null&&L[2]<m[2][0]&&(L[2]=m[2][0]),m[2][1]!==null&&L[2]>m[2][1]&&(L[2]=m[2][1])),m[3]&&(m[3][0]!==null&&L[3]<m[3][0]&&(L[3]=m[3][0]),m[3][1]!==null&&L[3]>m[3][1]&&(L[3]=m[3][1]))),o.isPoint)o.bone.position.set(o.vBasis.x+L[0],o.vBasis.y+L[1],o.vBasis.z-L[2]);else if(o.boneParent.quaternion.copy(o.qBasis),o.pivot&&this.opt.isPivots&&(o.boneParent.updateWorldMatrix(!1,!1),o.boneParent.matrixWorld.decompose(w,X,Z),w.copy(de).applyQuaternion(X).setY(0).normalize(),X.premultiply(Re.setFromUnitVectors(de,w).invert()).normalize(),o.boneParent.quaternion.multiply(X.invert()),o.boneParent.quaternion.multiply(o.qWorldInverseYaw)),o.isZ&&(m=Math.atan(L[0]/o.l),X.setFromAxisAngle(Ne,-m),o.boneParent.quaternion.multiply(X)),o.isY&&(m=o.l/3,m=m*Math.tanh(L[1]/m),o.bone.position.setLength(o.l+m)),o.isX&&(m=Math.atan(L[2]/o.l),X.setFromAxisAngle(De,-m),o.boneParent.quaternion.multiply(X)),o.isT&&(m=1.5*Math.tanh(L[3]*1.5),X.setFromAxisAngle(Oe,-m),o.boneParent.quaternion.multiply(X)),o.boneParent.updateWorldMatrix(!1,!0),o.excludes&&this.opt.isExcludes)for(i=0,s=o.excludes.length;i<s;i++)m=o.excludes[i],Z.set(0,0,0),m.deltaLocal&&(Z.x+=m.deltaLocal[0],Z.y+=m.deltaLocal[1],Z.z+=m.deltaLocal[2]),Z.applyMatrix4(m.bone.matrixWorld),ee.copy(o.boneParent.matrixWorld).invert(),Z.applyMatrix4(ee),w.copy(o.bone.position),!(w.distanceToSquared(Z)>=m.radiusSq)&&(_=w.length(),j=Z.length(),!(j>m.radius+_)&&(j<Math.abs(m.radius-_)||(j=(j*j+_*_-m.radiusSq)/(2*j),Z.normalize(),ue.copy(Z).multiplyScalar(j),j=Math.sqrt(_*_-j*j),w.subVectors(w,ue).projectOnPlane(Z).normalize().multiplyScalar(j),he.subVectors(o.vBasis,ue).projectOnPlane(Z).normalize(),_=he.dot(w),_<0&&(_=Math.sqrt(j*j-_*_),he.multiplyScalar(_),w.add(he)),w.add(ue).normalize(),Z.copy(o.bone.position).normalize(),X.setFromUnitVectors(Z,w),o.boneParent.quaternion.premultiply(X),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(i=>{let n=!1;for(let s=0;s<m.excludes.bones.length;s++)if(m.excludes.bones[s]===i.bone&&m.excludes.radii[s]===i.radius&&!(m.excludes.deltaLocals[s]===null&&i.deltaLocal!==null)&&!(m.excludes.deltaLocals[s]!==null&&i.deltaLocal===null)&&!(m.excludes.deltaLocals[s]!==null&&m.excludes.deltaLocals[s].some((o,r)=>o!==i.deltaLocal[r]))){n=!0;break}n||(m.excludes.bones.push(i.bone),m.excludes.radii.push(i.radius),m.excludes.deltaLocals.push(i.deltaLocal?[...i.deltaLocal]:null),m.excludes.objects.push(null))}))}),m=this.helpers.excludes,this.opt.isExcludes&&m.bones.length&&m.bones.forEach((e,i)=>{const n=new f.SphereGeometry(m.radii[i],6,6),s=new f.MeshBasicMaterial({depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0,wireframe:!0,color:this.opt.helperExcludesColor});m.objects[i]=new f.Mesh(n,s),m.objects[i].renderOrder=997,e.add(m.objects[i]),m.deltaLocals[i]&&m.objects[i].position.set(m.deltaLocals[i][0],m.deltaLocals[i][1],m.deltaLocals[i][2])}),m=this.helpers.points,m.bones.length){this.helpers.isActive=!0;const e=new f.BufferGeometry,i=m.bones.map(u=>[0,0,0]).flat();e.setAttribute("position",new f.Float32BufferAttribute(i,3));const n=new f.Color(this.opt.helperBoneColor1),s=new f.Color(this.opt.helperBoneColor2),o=m.pivots.map(u=>u&&this.opt.isPivots?[s.r,s.g,s.b]:[n.r,n.g,n.b]).flat();e.setAttribute("color",new f.Float32BufferAttribute(o,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,i=m.bones.map(u=>[0,0,0,0,0,0]).flat();e.setAttribute("position",new f.Float32BufferAttribute(i,3));const n=new f.Color(this.opt.helperLinkColor1),s=new f.Color(this.opt.helperLinkColor2),o=m.bones.map(u=>[n.r,n.g,n.b,s.r,s.g,s.b]).flat();e.setAttribute("color",new f.Float32BufferAttribute(o,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){ee.copy(this.armature.matrixWorld).invert();const t=m.object.geometry.getAttribute("position");for(let e=0,i=m.bones.length;e<i;e++)$.multiplyMatrices(ee,m.bones[e].matrixWorld),w.setFromMatrixPosition($),t.setXYZ(e,w.x,w.y,w.z);t.needsUpdate=!0,m.object.updateMatrixWorld()}if(m=this.helpers.lines,m.bones.length){ee.copy(this.armature.matrixWorld).invert();const t=m.object.geometry.getAttribute("position");for(let e=0,i=0,n=m.bones.length;e<n;e++,i+=2)$.multiplyMatrices(ee,m.bones[e].matrixWorld),w.setFromMatrixPosition($),t.setXYZ(i,w.x,w.y,w.z),$.multiplyMatrices(ee,m.bones[e].parent.matrixWorld),w.setFromMatrixPosition($),t.setXYZ(i+1,w.x,w.y,w.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 i=this.data[t];i.bone.position.copy(i.vBasis),i.boneParent.quaternion.copy(i.qBasis)}}dispose(){this.stop(),this.scene=null,this.armature=null,this.config=[],this.data=[],this.dict={},this.objectsUpdate=[],this.timerMs=0}}class We{constructor(t){this.audioContext=t,this.analyzer=null,this.dataArray=null,this.bufferLength=0}async analyzeAudio(t,e){const i=t.sampleRate,n=t.duration,s=t.getChannelData(0),o=this.extractAudioFeatures(s,i);return this.generateTimingData(o,e,n)}extractAudioFeatures(t,e){const i={energy:[],spectralCentroid:[],zeroCrossingRate:[],mfcc:[],onsets:[],phonemeBoundaries:[]},n=1024,s=512,o=Math.floor((t.length-n)/s)+1;for(let r=0;r<o;r++){const u=r*s,a=Math.min(u+n,t.length),h=t.slice(u,a),l=this.calculateEnergy(h);i.energy.push(l);const c=this.calculateSpectralCentroid(h);i.spectralCentroid.push(c);const d=this.calculateZeroCrossingRate(h);i.zeroCrossingRate.push(d);const g=this.calculateMFCC(h);i.mfcc.push(g)}return i.onsets=this.detectOnsets(i.energy),i.phonemeBoundaries=this.detectPhonemeBoundaries(i),i}calculateEnergy(t){let e=0;for(let i=0;i<t.length;i++)e+=t[i]*t[i];return e/t.length}calculateSpectralCentroid(t){const e=this.fft(t);let i=0,n=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]);i+=s*o,n+=o}return n>0?i/n:0}calculateZeroCrossingRate(t){let e=0;for(let i=1;i<t.length;i++)t[i]>=0!=t[i-1]>=0&&e++;return e/(t.length-1)}calculateMFCC(t){const e=this.fft(t),i=[];for(let n=0;n<13;n++){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*n*(o+.5)/(e.length/2))}i.push(s)}return i}fft(t){const e=t.length,i=new Float32Array(e*2);for(let n=0;n<e;n++)i[n*2]=t[n],i[n*2+1]=0;for(let n=1,s=0;n<e;n++){let o=e>>1;for(;s&o;)s^=o,o>>=1;if(s^=o,n<s){const r=i[n*2],u=i[n*2+1];i[n*2]=i[s*2],i[n*2+1]=i[s*2+1],i[s*2]=r,i[s*2+1]=u}}for(let n=2;n<=e;n<<=1){const s=-2*Math.PI/n,o=Math.cos(s),r=Math.sin(s);for(let u=0;u<e;u+=n){let a=1,h=0;for(let l=0;l<n/2;l++){const c=i[(u+l)*2],d=i[(u+l)*2+1],g=i[(u+l+n/2)*2]*a-i[(u+l+n/2)*2+1]*h,y=i[(u+l+n/2)*2]*h+i[(u+l+n/2)*2+1]*a;i[(u+l)*2]=c+g,i[(u+l)*2+1]=d+y,i[(u+l+n/2)*2]=c-g,i[(u+l+n/2)*2+1]=d-y;const x=a*o-h*r,I=a*r+h*o;a=x,h=I}}}return i}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:i,spectralCentroid:n,zeroCrossingRate:s}=t;for(let o=1;o<i.length;o++){const r=o*.023,u=Math.abs(i[o]-i[o-1]),a=Math.abs(n[o]-n[o-1]),h=Math.abs(s[o]-s[o-1]);u+a*.1+h*.5>.2&&e.push(r)}return e}generateTimingData(t,e,i){const n=e.toLowerCase().split(/\s+/);t.phonemeBoundaries,t.onsets;const s=[];let o=0;for(let u=0;u<n.length;u++){const a=n[u],h=this.estimateWordDuration(a,i/n.length);s.push({word:a,startTime:o,endTime:o+h,duration:h}),o+=h}const r=this.generateVisemeTimings(t,e,i);return{words:s,visemes:r,duration:i,features:t}}estimateWordDuration(t,e){const i=Math.max(.5,Math.min(2,t.length/5)),n=this.getWordComplexity(t);return e*i*n}getWordComplexity(t){const e=(t.match(/[bcdfghjklmnpqrstvwxyz]{2,}/g)||[]).length,i=(t.match(/[aeiou]{2,}/g)||[]).length;return 1+e*.2+i*.1}generateVisemeTimings(t,e,i){const n=[],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 h=s[a],l=o[r],c=t.energy[Math.floor(h/.023)]||0,d=this.calculateVisemeDuration(l,c);n.push({viseme:l,startTime:u,endTime:u+d,duration:d,intensity:Math.min(1,c*2)}),u+=d,r++}for(;r<o.length;){const a=o[r],h=this.calculateVisemeDuration(a,.5);n.push({viseme:a,startTime:u,endTime:u+h,duration:h,intensity:.6}),u+=h,r++}return n}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"},i=[],n=t.toLowerCase().replace(/[^a-z\s]/g,"").split(/\s+/);for(const s of n){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]){i.push(e[a]),o+=u,r=!0;break}}if(!r){const u=s[o];e[u]&&i.push(e[u]),o++}}}return i}calculateVisemeDuration(t,e){const n={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 n*s}}class Ve{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(i=>{const n=i.indexOf("["),s=i.indexOf("]"),o=i.indexOf("="),r=i.substring(0,n),u=i.substring(n+1,s),a=i.substring(s+1,o),h=i.substring(o+1),l={regex:"",move:0,visemes:[]};let c="";c+=[...r].map(g=>t[g]||g).join("");const d=[...u];return d[0]=d[0].toLowerCase(),c+=d.join(""),l.move=d.length,c+=[...a].map(g=>t[g]||g).join(""),l.regex=new RegExp(c),h.length&&h.split(" ").forEach(g=>{l.visemes.push(g)}),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 i=0;i<t.length;i++)e+=this.digits[t[i]]+" ";return e=e.substring(0,e.length-1),e}convert_sets_of_two(t){let e=String(t).substring(0,2),i=String(t).substring(2,4),n=this.convert_tens(e);return n+=" "+this.convert_tens(i),n}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 i=parseFloat(t);if(t=="0")return"zero";if(t<0)return" minus "+this.convertNumberToWords(Math.abs(t).toString(),e).trim();if(i&&!Number.isInteger(i)){const n=i.toString().split(".");return this.convertNumberToWords(n[0],e).trim()+" point "+this.convert_digit_by_digit(n[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),i=!isNaN(e)&&t.length===2,n=!isNaN(e)&&t.length>2&&e>0&&e<=3e3,s=n&&e%1e3===0?Math.floor(e/1e3):null,o=n&&!s?Math.floor(e/100):null,r=i||n?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),i=Math.floor(t%100/10)*10,n=t%10;let s=[];return e&&(s.push(this.convertNumberToWords(e).trim()),i||n?s.push("hundred"):s.push("hundredth")),i&&(n?s.push(this.convertNumberToWords(i).trim()):s.push(this.ordinals[i])),n&&s.push(this.ordinals[n]),s.join(" ")}preProcessText(t){let e=t.replace('/[#_*":;]/g',"");return e=e.replace(this.symbolsReg,i=>" "+this.symbols[i]+" "),/\d/.test(e)&&(e=e.replace(/\b(\d{2,4})[''']?\s?[sS](?=\s|[.,!?;:]|$)/g,(i,n)=>{const s=this.convertDecade(n);return s===n?i:s}),e=e.replace(/\b(\d+)\s*(st|nd|rd|th)(?=\s|[.,!?;:]|$)/gi,(i,n)=>this.convertOrdinal(Number(n))),e=e.replace(/\b(\w*?)(\d+)([A-Za-z]+)\b/g,(i,n,s,o)=>{const r=this.convertNumberToWords(s);return`${n}${r} ${o}`}).replace(/\b([A-Za-z]+)(\d+)(\w*?)\b/g,(i,n,s,o)=>{const r=this.convertNumberToWords(s);return`${n} ${r}${o}`}),e=e.replace(/-?(?:\d{1,3}(?:,\d{3})+|\d+)(\.\d+)?/g,(i,n)=>{let s=i,o=!1;return/,/.test(s)&&(s=s.replace(/,/g,""),o=!0),n&&(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},i=0;const n=[...e.words];for(;e.i<n.length;){const s=n[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 c=.7*(this.visemeDurations[l]||1);e.durations[e.durations.length-1]+=c,i+=c}else{const c=this.visemeDurations[l]||1;e.visemes.push(l),e.times.push(i),e.durations.push(c),i+=c}}),e.i+=u.move;break}}else e.i++,i+=this.specialDurations[s]||0}return e}}const Ge=Object.freeze(Object.defineProperty({__proto__:null,LipsyncEn:Ve},Symbol.toStringTag,{value:"Module"}));class Ze{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(i=>{const n=i.indexOf("["),s=i.indexOf("]"),o=i.indexOf("="),r=i.substring(0,n),u=i.substring(n+1,s),a=i.substring(s+1,o),h=i.substring(o+1),l={regex:"",move:0,visemes:[]};let c="";c+=[...r].map(g=>t[g]||g).join("");const d=[...u];return d[0]=d[0].toLowerCase(),c+=d.join(""),l.move=d.length,c+=[...a].map(g=>t[g]||g).join(""),l.regex=new RegExp(c),h.length&&h.split(" ").forEach(g=>{l.visemes.push(g)}),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 i=0;i<t.length;i++)e+=this.digits[t[i]]+" ";return e=e.substring(0,e.length-1),e}convert_millions(t){if(t>=1e6){const e=Math.floor(t/1e6),i=t%1e6;let n=this.convert_thousands(e);return n+=e===1?" million ":" millionen ",i>0&&(n+=this.convert_thousands(i)),n}else return this.convert_thousands(t)}convert_thousands(t){if(t>=1e3){const e=Math.floor(t/1e3),i=t%1e3;let n="";return e===1?n="eintausend":n=this.convert_hundreds(e)+"tausend",i>0&&(n+=this.convert_hundreds(i)),n}else return this.convert_hundreds(t)}convert_hundreds(t){if(t>99){const e=Math.floor(t/100),i=t%100;let n="";return e===1?n="einhundert":n=this.ones[e]+"hundert",i>0&&(n+=this.convert_tens(i)),n}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),i=t%10;return i===0?this.tens[e]:this.ones[i]+"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},i=0;const n=[...e.words];for(;e.i<n.length;){const s=n[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(c=>{if(e.visemes.length&&e.visemes[e.visemes.length-1]===c){const d=.7*(this.visemeDurations[c]||1);e.durations[e.durations.length-1]+=d,i+=d}else{const d=this.visemeDurations[c]||1;e.visemes.push(c),e.times.push(i),e.durations.push(d),i+=d}}),e.i+=a.move,r=!0;break}}r||(e.i++,i+=this.specialDurations[s]||0)}else e.i++,i+=this.specialDurations[s]||0}return e}}const Xe=Object.freeze(Object.defineProperty({__proto__:null,LipsyncDe:Ze},Symbol.toStringTag,{value:"Module"}));class Ye{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(i=>{const n=i.indexOf("["),s=i.indexOf("]"),o=i.indexOf("="),r=i.substring(0,n),u=i.substring(n+1,s),a=i.substring(s+1,o),h=i.substring(o+1),l={regex:"",move:0,visemes:[]};let c="";c+=[...r].map(g=>t[g]||g).join("");const d=[...u];return d[0]=d[0].toLowerCase(),c+=d.join(""),l.move=d.length,c+=[...a].map(g=>t[g]||g).join(""),l.regex=new RegExp(c,"i"),h.length&&h.split(" ").forEach(g=>{g&&l.visemes.push(g)}),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 i=0;i<t.length;i++)e+=this.digits[t[i]]+" ";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),i=t%10;return e===8&&i===0?"quatre-vingts":e===8?"quatre-vingt-"+this.ones[i]:(e===2||e===3||e===4||e===5||e===6)&&i===1?this.tens[e]+" et un":i===0?this.tens[e]:this.tens[e]+"-"+this.ones[i]}}convert_hundreds(t){if(t>=100){const e=Math.floor(t/100),i=t%100;let n="";return e===1?n="cent":(n=this.ones[e]+" cent",i===0&&(n+="s")),i>0&&(n+=" "+this.convert_tens(i)),n}else return this.convert_tens(t)}convert_thousands(t){if(t>=1e3){const e=Math.floor(t/1e3),i=t%1e3;let n="";return e===1?n="mille":n=this.convert_hundreds(e)+" mille",i>0&&(n+=" "+this.convert_hundreds(i)),n}else return this.convert_hundreds(t)}convert_millions(t){if(t>=1e6){const e=Math.floor(t/1e6),i=t%1e6;let n="";return e===1?n="un million":n=this.convert_hundreds(e)+" millions",i>0&&(n+=" "+this.convert_thousands(i)),n}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},i=0;const n=[...e.words];for(;e.i<n.length;){const s=n[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(c=>{if(e.visemes.length&&e.visemes[e.visemes.length-1]===c){const d=.7*(this.visemeDurations[c]||1);e.durations[e.durations.length-1]+=d,i+=d}else{const d=this.visemeDurations[c]||1;e.visemes.push(c),e.times.push(i),e.durations.push(d),i+=d}}),e.i+=a.move,r=!0;break}}r||(e.i++,i+=this.specialDurations[s]||0)}else e.i++,i+=this.specialDurations[s]||0}return e}}const je=Object.freeze(Object.defineProperty({__proto__:null,LipsyncFr:Ye},Symbol.toStringTag,{value:"Module"}));class Qe{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 i=parseFloat(t);if(i===void 0)return t;let n=(s,o,r,u,a)=>{if(s<o)return s;const h=Math.floor(s/o);return e.push(r+(h===1?u:this.numberToFinnishWords(h.toString())+a)),s-h*o};if(i<0&&(e.push("miinus "),i=Math.abs(i)),i=n(i,1e9," ","miljardi"," miljardia"),i=n(i,1e6," ","miljoona"," miljoonaa"),i=n(i,1e3,"","tuhat","tuhatta"),i=n(i,100," ","sata","sataa"),i>20&&(i=n(i,10,"","","kymmentä")),i>=1){let s=Math.floor(i);e.push(this.numbers[s]),i-=s}if(i>=0&&Math.abs(parseFloat(t))<1&&e.push("nolla"),i>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:[]},i=0;const n=[...t];for(let s=0;s<n.length;s++){const o=this.visemes[n[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,i+=r}else{const r=this.visemeDurations[o]||1;e.visemes.push(o),e.times.push(i),e.durations.push(r),i+=r}else i+=this.specialDurations[n[s]]||0}return e}}const qe=Object.freeze(Object.defineProperty({__proto__:null,LipsyncFi:Qe},Symbol.toStringTag,{value:"Module"}));class _e{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 i=parseFloat(t);if(i===void 0)return t;let n=(s,o,r,u,a)=>{if(s<o)return s;const h=Math.floor(s/o);return h===1?e.push(this.numbers[1]):e.push(this.numberToLithuanianWords(h.toString())),h%10===1?e.push(r):h%10===0||h%100>10&&h%100<20?e.push(a):e.push(u),s-h*o};i<0&&(e.push("minus"),i=Math.abs(i)),i=n(i,1e9,"milijardas","milijardai","milijardų"),i=n(i,1e6,"milijonas","milijonai","milijonų"),i=n(i,1e3,"tūkstantis","tūkstančiai","tūkstančių"),i=n(i,100,"šimtas","šimtai","šimtų");for(let s=this.tens.length-1;s>=1;s--)if(i>=10*s){e.push(this.tens[s]),i=i-10*s;break}if(i>=1){let s=Math.floor(i);e.push(this.numbers[s]),i-=s}if(i>=0&&Math.abs(parseFloat(t))<1&&e.push(this.numbers[0]),i>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:[]},i=0;const n=[...t];for(let s=0;s<n.length;s++){const o=n[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,i+=u}else{const u=this.durations[o]||1;e.visemes.push(r),e.times.push(i),e.durations.push(u),i+=u}else i+=this.pauses[n[s]]||0}return e}}const Ke=Object.freeze(Object.defineProperty({__proto__:null,LipsyncLt:_e},Symbol.toStringTag,{value:"Module"})),Je=new URL("data:text/javascript;base64,Y2xhc3MgUGxheWJhY2tXb3JrbGV0IGV4dGVuZHMgQXVkaW9Xb3JrbGV0UHJvY2Vzc29yIHsKICBzdGF0aWMgRlNNID0gewogICAgSURMRTogMCwKICAgIFBMQVlJTkc6IDEsCiAgfTsKCiAgY29uc3RydWN0b3Iob3B0aW9ucykgewogICAgc3VwZXIoKTsKICAgIHRoaXMucG9ydC5vbm1lc3NhZ2UgPSB0aGlzLmhhbmRsZU1lc3NhZ2UuYmluZCh0aGlzKTsKCiAgICB0aGlzLl9zYW1wbGVSYXRlID0gb3B0aW9ucz8ucHJvY2Vzc29yT3B0aW9ucz8uc2FtcGxlUmF0ZSB8fCBzYW1wbGVSYXRlOwogICAgdGhpcy5fc2NhbGUgPSAxIC8gMzI3Njg7IC8vIFBDTTE2IC0+IGZsb2F0CgogICAgLy8gU2lsZW5jZSBkZXRlY3Rpb24gdGhyZXNob2xkICgxIHNlY29uZCkgYXMgYSBmYWxsYmFjayBzYWZldHkgbmV0CiAgICBjb25zdCBzaWxlbmNlRHVyYXRpb25TZWNvbmRzID0gMS4wOwogICAgdGhpcy5fc2lsZW5jZVRocmVzaG9sZEJsb2NrcyA9IE1hdGguY2VpbCgodGhpcy5fc2FtcGxlUmF0ZSAqIHNpbGVuY2VEdXJhdGlvblNlY29uZHMpIC8gMTI4KTsKCiAgICAvLyBNZXRyaWNzIGNvbmZpZ3VyYXRpb24gdmlhIG9wdGlvbnMKICAgIGNvbnN0IG1ldHJpY3NDZmcgPSBvcHRpb25zPy5wcm9jZXNzb3JPcHRpb25zPy5tZXRyaWNzIHx8IHt9OwogICAgdGhpcy5fbWV0cmljc0VuYWJsZWQgPSBtZXRyaWNzQ2ZnLmVuYWJsZWQgIT09IGZhbHNlOwogICAgY29uc3QgaW50ZXJ2YWxIeiA9ICh0eXBlb2YgbWV0cmljc0NmZy5pbnRlcnZhbEh6ID09PSAibnVtYmVyIiAmJiBtZXRyaWNzQ2ZnLmludGVydmFsSHogPiAwKQogICAgICA/IG1ldHJpY3NDZmcuaW50ZXJ2YWxIeiA6IDI7CiAgICAvLyBNZXRyaWNzIHN0YXRlIChsb3ctb3ZlcmhlYWQpCiAgICB0aGlzLl9mcmFtZXNQcm9jZXNzZWQgPSAwOwogICAgdGhpcy5fdW5kZXJydW5CbG9ja3MgPSAwOwogICAgdGhpcy5fbWF4UXVldWVTYW1wbGVzID0gMDsKICAgIHRoaXMuX2xhc3RNZXRyaWNzU2VudEF0RnJhbWUgPSAwOwogICAgLy8gQ29udmVydCB0byBmcmFtZXMgYmV0d2VlbiByZXBvcnRzCiAgICB0aGlzLl9tZXRyaWNzSW50ZXJ2YWxGcmFtZXMgPSBNYXRoLm1heCgxMjgsIE1hdGgucm91bmQodGhpcy5fc2FtcGxlUmF0ZSAvIGludGVydmFsSHopKTsKCiAgICB0aGlzLnJlc2V0KCk7CiAgfQoKICAvKioKICAgKiBSZXNldHMgdGhlIHdvcmtsZXQgdG8gaXRzIGluaXRpYWwgSURMRSBzdGF0ZS4KICAgKi8KICByZXNldCgpIHsKICAgIHRoaXMuX2J1ZmZlclF1ZXVlID0gW107CiAgICB0aGlzLl9jdXJyZW50Q2h1bmsgPSBudWxsOwogICAgdGhpcy5fY3VycmVudENodW5rT2Zmc2V0ID0gMDsKICAgIHRoaXMuX3N0YXRlID0gUGxheWJhY2tXb3JrbGV0LkZTTS5JRExFOwoKICAgIHRoaXMuX25vTW9yZURhdGFSZWNlaXZlZCA9IGZhbHNlOwogICAgdGhpcy5fc2lsZW5jZUZyYW1lc0NvdW50ID0gMDsKICAgIHRoaXMuX2hhc1NlbnRFbmRlZCA9IGZhbHNlOwogICAgLy8gUmVzZXQgbWF4IHF1ZXVlIHRyYWNrZXIgb25seSB3aGVuIGdvaW5nIGlkbGUKICAgIHRoaXMuX21heFF1ZXVlU2FtcGxlcyA9IDA7CiAgfQoKICBoYW5kbGVNZXNzYWdlKGV2ZW50KSB7CiAgICBjb25zdCB7IHR5cGUsIGRhdGEgfSA9IGV2ZW50LmRhdGE7CgogICAgLy8gSU5URVJSVVBUOiBUaGUgbWFpbiB0aHJlYWQgd2FudHMgdG8gc3RvcCBpbW1lZGlhdGVseS4KICAgIGlmICh0eXBlID09PSAic3RvcCIpIHsKICAgICAgdGhpcy5yZXNldCgpOwogICAgICAvLyBTZW5kIGZpbmFsIG1ldHJpY3Mgc2hvd2luZyBjbGVhcmVkIHN0YXRlCiAgICAgIGlmICh0aGlzLl9tZXRyaWNzRW5hYmxlZCkgewogICAgICAgIHRyeSB7CiAgICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UoewogICAgICAgICAgICB0eXBlOiAibWV0cmljcyIsCiAgICAgICAgICAgIGRhdGE6IHsKICAgICAgICAgICAgICBzdGF0ZTogUGxheWJhY2tXb3JrbGV0LkZTTS5JRExFLAogICAgICAgICAgICAgIHF1ZXVlZFNhbXBsZXM6IDAsCiAgICAgICAgICAgICAgcXVldWVkTXM6IDAsCiAgICAgICAgICAgICAgbWF4UXVldWVkTXM6IE1hdGgucm91bmQoKHRoaXMuX21heFF1ZXVlU2FtcGxlcyAvIHRoaXMuX3NhbXBsZVJhdGUpICogMTAwMCksCiAgICAgICAgICAgICAgdW5kZXJydW5CbG9ja3M6IHRoaXMuX3VuZGVycnVuQmxvY2tzLAogICAgICAgICAgICAgIGZyYW1lc1Byb2Nlc3NlZDogdGhpcy5fZnJhbWVzUHJvY2Vzc2VkCiAgICAgICAgICAgIH0KICAgICAgICAgIH0pOwogICAgICAgIH0gY2F0Y2ggKF8pIHsgfQogICAgICB9CiAgICAgIHJldHVybjsKICAgIH0KCiAgICAvLyBNYWluIHRocmVhZCBoYXMgc2lnbmFsZWQgdGhhdCBubyBtb3JlIGF1ZGlvIGNodW5rcyB3aWxsIGJlIHNlbnQgZm9yIHRoaXMgdXR0ZXJhbmNlLgogICAgaWYgKHR5cGUgPT09ICJuby1tb3JlLWRhdGEiKSB7CiAgICAgIHRoaXMuX25vTW9yZURhdGFSZWNlaXZlZCA9IHRydWU7CiAgICAgIHJldHVybjsKICAgIH0KCiAgICAvLyBVcGRhdGUgbWV0cmljcyBjb25maWd1cmF0aW9uIGF0IHJ1bnRpbWUKICAgIGlmICh0eXBlID09PSAiY29uZmlnLW1ldHJpY3MiICYmIGRhdGEgJiYgdHlwZW9mIGRhdGEgPT09ICJvYmplY3QiKSB7CiAgICAgIGlmICgiZW5hYmxlZCIgaW4gZGF0YSkgdGhpcy5fbWV0cmljc0VuYWJsZWQgPSAhIWRhdGEuZW5hYmxlZDsKICAgICAgaWYgKHR5cGVvZiBkYXRhLmludGVydmFsSHogPT09ICJudW1iZXIiICYmIGRhdGEuaW50ZXJ2YWxIeiA+IDApIHsKICAgICAgICBjb25zdCBpbnRlcnZhbEh6ID0gZGF0YS5pbnRlcnZhbEh6OwogICAgICAgIHRoaXMuX21ldHJpY3NJbnRlcnZhbEZyYW1lcyA9IE1hdGgubWF4KDEyOCwgTWF0aC5yb3VuZCh0aGlzLl9zYW1wbGVSYXRlIC8gaW50ZXJ2YWxIeikpOwogICAgICB9CiAgICAgIC8vIFJlc2V0IHBhY2luZyBzbyB0aGUgbmV4dCByZXBvcnQgYWxpZ25zIHdpdGggbmV3IGludGVydmFsCiAgICAgIHRoaXMuX2xhc3RNZXRyaWNzU2VudEF0RnJhbWUgPSB0aGlzLl9mcmFtZXNQcm9jZXNzZWQ7CiAgICAgIHJldHVybjsKICAgIH0KCiAgICAvLyBOZXcgYXVkaW8gZGF0YSBoYXMgYXJyaXZlZC4KICAgIGlmICh0eXBlID09PSAiYXVkaW9EYXRhIiAmJiBkYXRhIGluc3RhbmNlb2YgQXJyYXlCdWZmZXIpIHsKICAgICAgdGhpcy5fbm9Nb3JlRGF0YVJlY2VpdmVkID0gZmFsc2U7CiAgICAgIC8vIElmIHdlIHdlcmUgaWRsZSwgdGhpcyBuZXcgZGF0YSBraWNrcyBvZmYgdGhlIHBsYXliYWNrLgogICAgICBpZiAodGhpcy5fc3RhdGUgPT09IFBsYXliYWNrV29ya2xldC5GU00uSURMRSkgewogICAgICAgIHRoaXMuX3N0YXRlID0gUGxheWJhY2tXb3JrbGV0LkZTTS5QTEFZSU5HOwogICAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZSh7IHR5cGU6ICJwbGF5YmFjay1zdGFydGVkIiB9KTsKICAgICAgfQoKICAgICAgLy8gV2Ugb25seSBxdWV1ZSBkYXRhIGlmIHdlIGFyZSBpbiB0aGUgUExBWUlORyBzdGF0ZS4gVGhpcyBwcmV2ZW50cwogICAgICAvLyBkYXRhIGZyb20gYSBwcmV2aW91cywgaW50ZXJydXB0ZWQgc3RyZWFtIGZyb20gbGluZ2VyaW5nLgogICAgICBpZiAodGhpcy5fc3RhdGUgPT09IFBsYXliYWNrV29ya2xldC5GU00uUExBWUlORykgewogICAgICAgIC8vIFN0b3JlIGFzIEludDE2QXJyYXkgdmlldyB0byBhdm9pZCBjb25zdHJ1Y3RpbmcgaXQgaW4gcHJvY2VzcygpCiAgICAgICAgdGhpcy5fYnVmZmVyUXVldWUucHVzaChuZXcgSW50MTZBcnJheShkYXRhKSk7CiAgICAgICAgdGhpcy5fc2lsZW5jZUZyYW1lc0NvdW50ID0gMDsgLy8gUmVzZXQgc2lsZW5jZSBjb3VudGVyIG9uIG5ldyBkYXRhCiAgICAgIH0KICAgIH0KICB9CgogIHByb2Nlc3MoaW5wdXRzLCBvdXRwdXRzLCBwYXJhbWV0ZXJzKSB7CiAgICBjb25zdCBvdXRwdXRDaGFubmVsID0gb3V0cHV0c1swXT8uWzBdOwogICAgaWYgKCFvdXRwdXRDaGFubmVsKSB7CiAgICAgIHJldHVybiB0cnVlOyAvLyBLZWVwIGFsaXZlIGV2ZW4gaWYgb3V0cHV0IGlzIHRlbXBvcmFyaWx5IGRpc2Nvbm5lY3RlZAogICAgfQoKICAgIC8vIElmIHdlIGFyZSBub3QgcGxheWluZywganVzdCBvdXRwdXQgc2lsZW5jZSBhbmQgd2FpdC4KICAgIGlmICh0aGlzLl9zdGF0ZSAhPT0gUGxheWJhY2tXb3JrbGV0LkZTTS5QTEFZSU5HKSB7CiAgICAgIG91dHB1dENoYW5uZWwuZmlsbCgwKTsKICAgICAgcmV0dXJuIHRydWU7IC8vIEFsd2F5cyByZXR1cm4gdHJ1ZSB0byBrZWVwIHRoZSBwcm9jZXNzb3IgYWxpdmUKICAgIH0KCiAgICAvLyBDb3JlIFBMQVlJTkcgTG9naWMKICAgIGNvbnN0IGJsb2NrU2l6ZSA9IG91dHB1dENoYW5uZWwubGVuZ3RoOwogICAgbGV0IHNhbXBsZXNDb3BpZWQgPSAwOwoKICAgIHdoaWxlIChzYW1wbGVzQ29waWVkIDwgYmxvY2tTaXplKSB7CiAgICAgIGlmICghdGhpcy5fY3VycmVudENodW5rIHx8IHRoaXMuX2N1cnJlbnRDaHVua09mZnNldCA+PSB0aGlzLl9jdXJyZW50Q2h1bmsubGVuZ3RoKSB7CiAgICAgICAgaWYgKHRoaXMuX2J1ZmZlclF1ZXVlLmxlbmd0aCA+IDApIHsKICAgICAgICAgIHRoaXMuX2N1cnJlbnRDaHVuayA9IHRoaXMuX2J1ZmZlclF1ZXVlLnNoaWZ0KCk7CiAgICAgICAgICB0aGlzLl9jdXJyZW50Q2h1bmtPZmZzZXQgPSAwOwogICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAvLyBCdWZmZXIgaXMgZW1wdHkuIENoZWNrIGZvciBlbmQgY29uZGl0aW9ucy4KICAgICAgICAgIGNvbnN0IGlzVGltZWRPdXQgPSB0aGlzLl9zaWxlbmNlRnJhbWVzQ291bnQgPiB0aGlzLl9zaWxlbmNlVGhyZXNob2xkQmxvY2tzOwoKICAgICAgICAgIGlmICh0aGlzLl9ub01vcmVEYXRhUmVjZWl2ZWQgfHwgaXNUaW1lZE91dCkgewogICAgICAgICAgICAvLyBFTkQgT0YgUExBWUJBQ0s6IEVpdGhlciBleHBsaWNpdGx5IHNpZ25hbGVkIG9yIHRpbWVkIG91dC4KICAgICAgICAgICAgaWYgKCF0aGlzLl9oYXNTZW50RW5kZWQpIHsKICAgICAgICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UoeyB0eXBlOiAicGxheWJhY2stZW5kZWQiIH0pOwogICAgICAgICAgICAgIHRoaXMuX2hhc1NlbnRFbmRlZCA9IHRydWU7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgLy8gU2VuZCBmaW5hbCBtZXRyaWNzIHNob3dpbmcgY2xlYXJlZCBzdGF0ZQogICAgICAgICAgICBpZiAodGhpcy5fbWV0cmljc0VuYWJsZWQpIHsKICAgICAgICAgICAgICB0cnkgewogICAgICAgICAgICAgICAgdGhpcy5wb3J0LnBvc3RNZXNzYWdlKHsKICAgICAgICAgICAgICAgICAgdHlwZTogIm1ldHJpY3MiLAogICAgICAgICAgICAgICAgICBkYXRhOiB7CiAgICAgICAgICAgICAgICAgICAgc3RhdGU6IFBsYXliYWNrV29ya2xldC5GU00uSURMRSwKICAgICAgICAgICAgICAgICAgICBxdWV1ZWRTYW1wbGVzOiAwLAogICAgICAgICAgICAgICAgICAgIHF1ZXVlZE1zOiAwLAogICAgICAgICAgICAgICAgICAgIG1heFF1ZXVlZE1zOiBNYXRoLnJvdW5kKCh0aGlzLl9tYXhRdWV1ZVNhbXBsZXMgLyB0aGlzLl9zYW1wbGVSYXRlKSAqIDEwMDApLAogICAgICAgICAgICAgICAgICAgIHVuZGVycnVuQmxvY2tzOiB0aGlzLl91bmRlcnJ1bkJsb2NrcywKICAgICAgICAgICAgICAgICAgICBmcmFtZXNQcm9jZXNzZWQ6IHRoaXMuX2ZyYW1lc1Byb2Nlc3NlZAogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICB9KTsKICAgICAgICAgICAgICB9IGNhdGNoIChfKSB7IH0KICAgICAgICAgICAgfQogICAgICAgICAgICB0aGlzLnJlc2V0KCk7IC8vIFJlc2V0IHRvIElETEUgc3RhdGUgZm9yIHJldXNlCiAgICAgICAgICAgIGJyZWFrOyAvLyBFeGl0IHdoaWxlIGxvb3AKICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgIC8vIEJVRkZFUiBVTkRFUlJVTiAoTEFHKTogUGxheSBzaWxlbmNlIGFuZCB3YWl0IGZvciBtb3JlIGRhdGEuCiAgICAgICAgICAgIHRoaXMuX3NpbGVuY2VGcmFtZXNDb3VudCsrOwogICAgICAgICAgICBpZiAodGhpcy5fbWV0cmljc0VuYWJsZWQpIHRoaXMuX3VuZGVycnVuQmxvY2tzKys7CiAgICAgICAgICAgIGJyZWFrOyAvLyBFeGl0IHdoaWxlIGxvb3AKICAgICAgICAgIH0KICAgICAgICB9CiAgICAgIH0KCiAgICAgIC8vIElmIHdlIGhhdmUgYSBjaHVuayAoY291bGQgYmUgYSBuZXcgb25lIGZyb20gdGhlIGxvZ2ljIGFib3ZlKSwgcHJvY2VzcyBpdC4KICAgICAgaWYgKHRoaXMuX2N1cnJlbnRDaHVuaykgewogICAgICAgIGNvbnN0IHNhbXBsZXNUb0NvcHkgPSBNYXRoLm1pbigKICAgICAgICAgIGJsb2NrU2l6ZSAtIHNhbXBsZXNDb3BpZWQsCiAgICAgICAgICB0aGlzLl9jdXJyZW50Q2h1bmsubGVuZ3RoIC0gdGhpcy5fY3VycmVudENodW5rT2Zmc2V0CiAgICAgICAgKTsKICAgICAgICAvLyBEaXJlY3RseSB3cml0ZSB0byBvdXRwdXRDaGFubmVsIHRvIGF2b2lkIGV4dHJhIGNvcHkKICAgICAgICBjb25zdCBzcmMgPSB0aGlzLl9jdXJyZW50Q2h1bms7CiAgICAgICAgY29uc3QgYmFzZVNyYyA9IHRoaXMuX2N1cnJlbnRDaHVua09mZnNldDsKICAgICAgICBjb25zdCBiYXNlRHN0ID0gc2FtcGxlc0NvcGllZDsKICAgICAgICBjb25zdCBzY2FsZSA9IHRoaXMuX3NjYWxlOwogICAgICAgIGZvciAobGV0IGkgPSAwOyBpIDwgc2FtcGxlc1RvQ29weTsgaSsrKSB7CiAgICAgICAgICBvdXRwdXRDaGFubmVsW2Jhc2VEc3QgKyBpXSA9IHNyY1tiYXNlU3JjICsgaV0gKiBzY2FsZTsKICAgICAgICB9CgogICAgICAgIHRoaXMuX2N1cnJlbnRDaHVua09mZnNldCArPSBzYW1wbGVzVG9Db3B5OwogICAgICAgIHNhbXBsZXNDb3BpZWQgKz0gc2FtcGxlc1RvQ29weTsKICAgICAgfQogICAgfQoKICAgIC8vIFplcm8tZmlsbCB0aGUgcmVtYWluZGVyLCBpZiBhbnksIG9uY2UgcGVyIGJsb2NrCiAgICBpZiAoc2FtcGxlc0NvcGllZCA8IGJsb2NrU2l6ZSkgewogICAgICBvdXRwdXRDaGFubmVsLmZpbGwoMCwgc2FtcGxlc0NvcGllZCk7CiAgICB9CgogICAgLy8gVXBkYXRlIG1ldHJpY3MgKG9wdGlvbmFsKQogICAgaWYgKHRoaXMuX21ldHJpY3NFbmFibGVkKSB7CiAgICAgIHRoaXMuX2ZyYW1lc1Byb2Nlc3NlZCArPSBibG9ja1NpemU7CgogICAgICAvLyBUcmFjayBxdWV1ZSBkZXB0aCBpbiBzYW1wbGVzIChhcHByb3hpbWF0ZSkKICAgICAgbGV0IHF1ZXVlZFNhbXBsZXMgPSAwOwogICAgICBpZiAodGhpcy5fY3VycmVudENodW5rKSBxdWV1ZWRTYW1wbGVzICs9IE1hdGgubWF4KDAsIHRoaXMuX2N1cnJlbnRDaHVuay5sZW5ndGggLSB0aGlzLl9jdXJyZW50Q2h1bmtPZmZzZXQpOwogICAgICBmb3IgKGxldCBpID0gMDsgaSA8IHRoaXMuX2J1ZmZlclF1ZXVlLmxlbmd0aDsgaSsrKSBxdWV1ZWRTYW1wbGVzICs9IHRoaXMuX2J1ZmZlclF1ZXVlW2ldLmxlbmd0aDsKICAgICAgaWYgKHF1ZXVlZFNhbXBsZXMgPiB0aGlzLl9tYXhRdWV1ZVNhbXBsZXMpIHRoaXMuX21heFF1ZXVlU2FtcGxlcyA9IHF1ZXVlZFNhbXBsZXM7CgogICAgICAvLyBQZXJpb2RpY2FsbHkgc2VuZCBtZXRyaWNzIHRvIG1haW4gdGhyZWFkCiAgICAgIGlmICh0aGlzLl9mcmFtZXNQcm9jZXNzZWQgLSB0aGlzLl9sYXN0TWV0cmljc1NlbnRBdEZyYW1lID49IHRoaXMuX21ldHJpY3NJbnRlcnZhbEZyYW1lcykgewogICAgICAgIHRoaXMuX2xhc3RNZXRyaWNzU2VudEF0RnJhbWUgPSB0aGlzLl9mcmFtZXNQcm9jZXNzZWQ7CiAgICAgICAgdHJ5IHsKICAgICAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZSh7CiAgICAgICAgICAgIHR5cGU6ICJtZXRyaWNzIiwKICAgICAgICAgICAgZGF0YTogewogICAgICAgICAgICAgIHN0YXRlOiB0aGlzLl9zdGF0ZSwKICAgICAgICAgICAgICBxdWV1ZWRTYW1wbGVzLAogICAgICAgICAgICAgIHF1ZXVlZE1zOiBNYXRoLnJvdW5kKChxdWV1ZWRTYW1wbGVzIC8gdGhpcy5fc2FtcGxlUmF0ZSkgKiAxMDAwKSwKICAgICAgICAgICAgICBtYXhRdWV1ZWRNczogTWF0aC5yb3VuZCgodGhpcy5fbWF4UXVldWVTYW1wbGVzIC8gdGhpcy5fc2FtcGxlUmF0ZSkgKiAxMDAwKSwKICAgICAgICAgICAgICB1bmRlcnJ1bkJsb2NrczogdGhpcy5fdW5kZXJydW5CbG9ja3MsCiAgICAgICAgICAgICAgZnJhbWVzUHJvY2Vzc2VkOiB0aGlzLl9mcmFtZXNQcm9jZXNzZWQKICAgICAgICAgICAgfQogICAgICAgICAgfSk7CiAgICAgICAgfSBjYXRjaCAoXykgeyB9CiAgICAgICAgLy8gRG9uJ3QgcmVzZXQgbWF4IHRyYWNrZXIgLSBrZWVwIHNlc3Npb24gcGVhayB1bnRpbCBpZGxlCiAgICAgIH0KICAgIH0KCiAgICAvLyBBTFdBWVMgcmV0dXJuIHRydWUgdG8ga2VlcCB0aGUgcHJvY2Vzc29yIGFsaXZlIGZvciByZXVzZS4KICAgIHJldHVybiB0cnVlOwogIH0KfQoKcmVnaXN0ZXJQcm9jZXNzb3IoInBsYXliYWNrLXdvcmtsZXQiLCBQbGF5YmFja1dvcmtsZXQpOwo=",typeof document>"u"?require("url").pathToFileURL(__filename).href:pe&&pe.tagName.toUpperCase()==="SCRIPT"&&pe.src||new URL("index.cjs",document.baseURI).href),ve={en:Ge,de:Xe,fr:je,fi:qe,lt:Ke},U=new f.Quaternion,F=new f.Euler,ie=new f.Vector3,oe=new f.Vector3,Ie=new f.Box3;new f.Matrix4;new f.Matrix4;new f.Vector3;new f.Vector3(0,0,1);const $e=new f.Vector3(1,0,0);new f.Vector3(0,1,0);new f.Vector3(0,0,1);class Le{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:0,mixerGainSpeech:null,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 Pe,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 i=new Set;Object.values(this.poseTemplates).forEach(r=>{Object.keys(this.propsToThreeObjects(r.props)).forEach(u=>i.add(u))}),Object.keys(this.poseDelta.props).forEach(r=>{i.add(r)}),this.posePropNames=[...i],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"]}},{p:.3,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{delay:[5e3,3e4],vs:{pose:["straight"]}}]},{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"]}},{p:.2,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["side"]}}},{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"]}},{p:.4,delay:[5e3,3e4],vs:{pose:["straight"]}},{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 n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";this.b64Lookup=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let r=0;r<n.length;r++)this.b64Lookup[n.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 Fe.RoomEnvironment).texture,this.resizeobserver=new ResizeObserver(this.onResize.bind(this)),this.resizeobserver.observe(this.nodeAvatar),this.controls=new Te.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"},o=[];Object.entries(s).forEach((r,u)=>{const a=new f.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 f.Skeleton(o)),this.dynamicbones=new Ue,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 We(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 i=JSON.parse(JSON.stringify(t));return e&&typeof e=="function"&&e(i),i}b64ToArrayBuffer(t){let e=3*t.length/4;t[t.length-1]==="="&&(e--,t[t.length-2]==="="&&e--);const i=new ArrayBuffer(e),n=new Uint8Array(i);let s,o=0,r,u,a,h;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)],h=this.b64Lookup[t.charCodeAt(s+3)],n[o++]=r<<2|u>>4,n[o++]=(u&15)<<4|a>>2,n[o++]=(a&3)<<6|h&63;return i}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 i=new ArrayBuffer(e),n=new Uint8Array(i),s=0;for(let o=0;o<t.length;o++)n.set(new Uint8Array(t[o]),s),s+=t[o].byteLength;return i}pcmToAudioBuffer(t){const e=new Int16Array(t),i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]>=32768?-(65536-e[s])/32768:e[s]/32767;const n=this.audioCtx.createBuffer(1,i.length,this.opt.pcmSampleRate);return n.copyToChannel(i,0,0),n}propsToThreeObjects(t){const e={};for(let[i,n]of Object.entries(t)){const s=i.split(".");let o=Array.isArray(n.x)?this.gaussianRandom(...n.x):n.x,r=Array.isArray(n.y)?this.gaussianRandom(...n.y):n.y,u=Array.isArray(n.z)?this.gaussianRandom(...n.z):n.z;s[1]==="position"||s[1]==="scale"?e[i]=new f.Vector3(o,r,u):s[1]==="rotation"?(i=s[0]+".quaternion",e[i]=new f.Quaternion().setFromEuler(new f.Euler(o,r,u,"XYZ")).normalize()):s[1]==="quaternion"&&(e[i]=new f.Quaternion(o,r,u,n.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,i,n=!1){t.forEach(s=>{if(!n&&s.morphTargetDictionary.hasOwnProperty(e))return;const o=s.geometry;let r=null,u=null;for(const[a,h]of Object.entries(i))if(s.morphTargetDictionary.hasOwnProperty(a)){const l=s.morphTargetDictionary[a],c=o.morphAttributes.position[l],d=o.morphAttributes.normal?.[l];r||(r=new f.Float32BufferAttribute(c.count*3,3),d&&(u=new f.Float32BufferAttribute(c.count*3,3)));for(let g=0;g<c.count;g++){const y=r.getX(g)+c.getX(g)*h,x=r.getY(g)+c.getY(g)*h,I=r.getZ(g)+c.getZ(g)*h;r.setXYZ(g,y,x,I)}if(d)for(let g=0;g<c.count;g++){const y=u.getX(g)+d.getX(g)*h,x=u.getY(g)+d.getY(g)*h,I=u.getZ(g)+d.getZ(g)*h;u.setXYZ(g,y,x,I)}}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 i=new Me.GLTFLoader;if(this.dracoEnabled){const a=new Ee.DRACOLoader;a.setDecoderPath(this.dracoDecoderPath),i.setDRACOLoader(a)}let n=await i.loadAsync(t.url,e);const s=[this.opt.modelRoot];if(this.posePropNames.forEach(a=>s.push(a.split(".")[0])),s.forEach(a=>{if(!n.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=n.scene.getObjectByName(this.opt.modelRoot),this.armature.scale.setScalar(1),this.animations=n.animations,this.userData=n.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(h=>o.add(h))}),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 h=this.mtAvatar[a];h&&["fixed","system","systemd","realtime","base","v","value","applied"].forEach(l=>{r[a][l]=h[l]}),this.morphs.forEach(l=>{const c=l.morphTargetDictionary[a];c!==void 0&&(r[a].ms.push(l.morphTargetInfluences),r[a].is.push(c),l.morphTargetInfluences[c]=r[a].applied)})}),this.mtAvatar=r,this.poseAvatar={props:{}},this.posePropNames.forEach(a=>{const h=a.split("."),l=this.armature.getObjectByName(h[0]);this.poseAvatar.props[a]=l[h[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(n.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 f.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.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 i=e.hasOwnProperty("cameraX")?e.cameraX:this.opt.cameraX,n=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=-i*Math.tan(u/2),h=(1-n)*Math.tan(u/2),l=s;switch(this.viewName){case"head":l+=2,h=h*l+4*this.avatarHeight/5;break;case"upper":l+=4.5,h=h*l+2*this.avatarHeight/3;break;case"mid":l+=8,h=h*l+this.avatarHeight/3;break;default:l+=12,h=h*l}a=a*l,this.controlsEnd=new f.Vector3(a,h,0),this.cameraEnd=new f.Vector3(a,h,l).applyEuler(new f.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 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,i]of Object.entries(this.poseTarget.props)){const n=this.poseAvatar.props[e];if(n){let s=(t-i.t)/i.d;s>1||!this.poseBase.props.hasOwnProperty(e)?n.copy(i):n.isQuaternion?n.copy(this.poseBase.props[e].slerp(i,this.easing(s))):n.isVector3&&n.copy(this.poseBase.props[e].lerp(i,this.easing(s)))}}}updatePoseDelta(){for(const[t,e]of Object.entries(this.poseDelta.props)){if(e.x===0&&e.y===0&&e.z===0)continue;F.set(e.x,e.y,e.z);const i=this.poseAvatar.props[t];i.isQuaternion?(U.setFromEuler(F),i.multiply(U)):i.isVector3&&i.add(F)}}updateMorphTargets(t){for(let[e,i]of Object.entries(this.mtAvatar)){if(!i.needsUpdate)continue;let n=null,s=null;if(i.fixed!==null){if(n=i.fixed,i.system=null,i.systemd=null,i.newvalue=null,i.ref&&i.ref.hasOwnProperty(e)&&delete i.ref[e],i.ref=null,i.base=null,i.value===n){i.needsUpdate=!1;continue}}else i.realtime!==null?(i.ref=null,i.base=null,s=i.realtime):i.system!==null?(n=i.system,i.newvalue=null,i.ref&&i.ref.hasOwnProperty(e)&&delete i.ref[e],i.ref=null,i.base=null,i.systemd!==null?i.systemd===0?(n=null,i.system=null,i.systemd=null):(i.systemd-=t,i.systemd<0&&(i.systemd=0),i.value===n&&(n=null)):i.value===n&&(n=null,i.system=null)):i.newvalue!==null?(i.ref=null,i.base=null,s=i.newvalue,i.newvalue=null):i.base!==null?(n=i.base,i.ref=null,i.value===n&&(n=null,i.base=null,i.needsUpdate=!1)):(i.ref=null,i.baseline!==null&&i.value!==i.baseline?(n=i.baseline,i.base=i.baseline):i.needsUpdate=!1);if(n!==null){let o=n-i.value;o>=0?o<.005?(s=n,i.v=0):(i.v<i.maxv&&(i.v+=i.acc*t),i.v>=0?s=i.value+o*(1-Math.exp(-i.v*t)):s=i.value+i.v*t*(1-Math.exp(i.v*t))):o>-.005?(s=n,i.v=0):(i.v>-i.maxv&&(i.v-=i.acc*t),i.v>=0?s=i.value+i.v*t*(1-Math.exp(-i.v*t)):s=i.value+o*(1-Math.exp(i.v*t)))}if(i.limit!==null){if(s!==null&&s!==i.value&&(i.value=s,i.onchange!==null&&i.onchange(s)),s=i.limit(i.value),s===i.applied)continue}else{if(s===null||s===i.value)continue;i.value=s,i.onchange!==null&&i.onchange(s)}switch(i.applied=s,i.applied<i.min&&(i.applied=i.min),i.applied>i.max&&(i.applied=i.max),e){case"headRotateX":this.poseDelta.props["Head.quaternion"].x=i.applied+this.mtAvatar.bodyRotateX.applied;break;case"headRotateY":this.poseDelta.props["Head.quaternion"].y=i.applied+this.mtAvatar.bodyRotateY.applied;break;case"headRotateZ":this.poseDelta.props["Head.quaternion"].z=i.applied+this.mtAvatar.bodyRotateZ.applied;break;case"bodyRotateX":this.poseDelta.props["Head.quaternion"].x=i.applied+this.mtAvatar.headRotateX.applied,this.poseDelta.props["Spine1.quaternion"].x=i.applied/2,this.poseDelta.props["Spine.quaternion"].x=i.applied/8,this.poseDelta.props["Hips.quaternion"].x=i.applied/24;break;case"bodyRotateY":this.poseDelta.props["Head.quaternion"].y=i.applied+this.mtAvatar.headRotateY.applied,this.poseDelta.props["Spine1.quaternion"].y=i.applied/2,this.poseDelta.props["Spine.quaternion"].y=i.applied/2,this.poseDelta.props["Hips.quaternion"].y=i.applied/4,this.poseDelta.props["LeftUpLeg.quaternion"].y=i.applied/2,this.poseDelta.props["RightUpLeg.quaternion"].y=i.applied/2,this.poseDelta.props["LeftLeg.quaternion"].y=i.applied/4,this.poseDelta.props["RightLeg.quaternion"].y=i.applied/4;break;case"bodyRotateZ":this.poseDelta.props["Head.quaternion"].z=i.applied+this.mtAvatar.headRotateZ.applied,this.poseDelta.props["Spine1.quaternion"].z=i.applied/12,this.poseDelta.props["Spine.quaternion"].z=i.applied/12,this.poseDelta.props["Hips.quaternion"].z=i.applied/24;break;case"handFistLeft":case"handFistRight":const o=e.substring(8);["HandThumb","HandIndex","HandMiddle","HandRing","HandPinky"].forEach((h,l)=>{l===0?(this.poseDelta.props[o+h+"1.quaternion"].x=0,this.poseDelta.props[o+h+"2.quaternion"].z=(o==="Left"?-1:1)*i.applied,this.poseDelta.props[o+h+"3.quaternion"].z=(o==="Left"?-1:1)*i.applied):(this.poseDelta.props[o+h+"1.quaternion"].x=i.applied,this.poseDelta.props[o+h+"2.quaternion"].x=1.5*i.applied,this.poseDelta.props[o+h+"3.quaternion"].x=1.5*i.applied)});break;case"chestInhale":const r=i.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 h=0,l=i.ms.length;h<l;h++)i.ms[h][i.is[h]]=i.applied}}}getPoseString(t,e=1e3){let i="{";return Object.entries(t).forEach((n,s)=>{const o=n[0].split(".");if(o[1]==="position"||o[1]==="rotation"||o[1]==="quaternion"){const r=o[1]==="quaternion"?o[0]+".rotation":n[0],u=n[1].isQuaternion?new f.Euler().setFromQuaternion(n[1]):n[1];i+=(s?", ":"")+"'"+r+"':{",i+="x:"+Math.round(u.x*e)/e,i+=", y:"+Math.round(u.y*e)/e,i+=", z:"+Math.round(u.z*e)/e,i+="}"}}),i+="}",i}getPoseTemplateProp(t){const e=t.split(".");let i=e[0]+"."+(e[1]==="rotation"?"quaternion":e[1]);if(this.gesture&&this.gesture.hasOwnProperty(i))return this.gesture[i].clone();{let n=e[0]+"."+(e[1]==="quaternion"?"rotation":e[1]);this.poseWeightOnLeft||(n.startsWith("Left")?(n="Right"+n.substring(4),i="Right"+i.substring(4)):n.startsWith("Right")&&(n="Left"+n.substring(5),i="Left"+i.substring(5)));let s;if(this.poseTarget.template.props.hasOwnProperty(i)){const o={};o[i]=this.poseTarget.template.props[i],s=this.propsToThreeObjects(o)[i]}else if(this.poseTarget.template.props.hasOwnProperty(n)){const o={};o[n]=this.poseTarget.template.props[n],s=this.propsToThreeObjects(o)[i]}return s&&!this.poseWeightOnLeft&&s.isQuaternion&&(s.x*=-1,s.w*=-1),s}}mirrorPose(t){const e={};for(let[i,n]of Object.entries(t))n.isQuaternion&&(i.startsWith("Left")?i="Right"+i.substring(4):i.startsWith("Right")&&(i="Left"+i.substring(5)),n.x*=-1,n.w*=-1),e[i]=n.clone(),e[i].t=n.t,e[i].d=n.d;return e}poseFactory(t,e=2e3){const i={template:t,props:this.propsToThreeObjects(t.props)};for(const[n,s]of Object.entries(i.props)){if(this.opt.modelMovementFactor<1&&t.standing&&(n==="Hips.quaternion"||n==="Spine.quaternion"||n==="Spine1.quaternion"||n==="Spine2.quaternion"||n==="Neck.quaternion"||n==="LeftUpLeg.quaternion"||n==="LeftLeg.quaternion"||n==="RightUpLeg.quaternion"||n==="RightLeg.quaternion")){const o=this.poseStraight[n],r=s.angleTo(o);s.rotateTowards(o,(1-this.opt.modelMovementFactor)*r)}s.t=this.animClock,s.d=e}return i}setPoseFromTemplate(t,e=2e3){const i=t&&this.poseTarget&&this.poseTarget.template&&(this.poseTarget.template.standing&&t.lying||this.poseTarget.template.lying&&t.standing),n=t&&t===this.poseCurrentTemplate,s=this.poseWeightOnLeft;let o=i?1e3:e;if(i?(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,(!n&&!s||n&&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,i=null){this.mtAvatar.hasOwnProperty(t)&&Object.assign(this.mtAvatar[t],{system:e,systemd:i,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 i=this.mtBaselineExceptions.hasOwnProperty(e)?this.mtBaselineExceptions[e]:this.mtBaselineDefault;this.mood.baseline.hasOwnProperty(e)?i=this.mood.baseline[e]:this.avatar.baseline?.hasOwnProperty(e)&&(i=this.avatar.baseline[e]),this.setBaselineValue(e,i)}this.mood.anims.forEach(e=>{let i=this.animQueue.findIndex(n=>n.template.name===e.name);i!==-1&&this.animQueue.splice(i,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(n=>!n.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(n){console.warn("FBX animation failed, falling back to code animation:",n)}const i=this.createBodyMovementAnimation(this.bodyMovement);if(console.log("Created movement animation:",i),i)try{const n=this.animFactory(i,!0);n&&n.ts&&n.ts.length>0?(this.animQueue.push(n),console.log("Applied code-based body movement animation:",this.bodyMovement),console.log("Animation queue length:",this.animQueue.length),console.log("Animation object:",n)):(console.error("Invalid animation object created for:",this.bodyMovement),console.error("Animation object:",n))}catch(n){console.error("Error creating body movement animation:",n)}}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));const t=2;this.lockedPosition={x:0,y:t,z:0},this.armature.position.set(this.lockedPosition.x,this.lockedPosition.y,this.lockedPosition.z),console.log("BEFORE: Avatar position was:",this.armature.position.x,this.armature.position.y,this.armature.position.z),console.log("AFTER: Avatar position moved up and locked at:",this.lockedPosition),console.log("Current view:",this.viewName)}unlockAvatarPosition(){this.armature&&(this.armature.position.set(0,0,0),console.log("Avatar position reset to center (0,0,0)")),this.lockedPosition=null,console.log("Avatar position unlocked")}maintainLockedPosition(){if(this.lockedPosition&&this.armature){const t=this.armature.position.y,e=this.lockedPosition.y-2,i=this.lockedPosition.y+.1;t<e?this.armature.position.set(this.lockedPosition.x,e,this.lockedPosition.z):t>i&&this.armature.position.set(this.lockedPosition.x,i,this.lockedPosition.z),this.armature.position.x=this.lockedPosition.x,this.armature.position.z=this.lockedPosition.z}}createBodyMovementAnimation(t){const e=this.movementIntensity||.5,i={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 n=["dancing","dancing2","dancing3"],s=n[Math.floor(Math.random()*n.length)];return i[s]||i.dancing}return i[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 i=this.getBaselineValue("eyeLookInLeft");return i===void 0||this.getBaselineValue("eyeLookOutRight")===void 0||this.getBaselineValue("eyeLookInRight")===void 0?void 0:e-i}else if(t==="eyesRotateX"){const e=this.getBaselineValue("eyesLookDown");if(e===void 0)return;const i=this.getBaselineValue("eyesLookUp");return i===void 0?void 0:e-i}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 i=this.getFixedValue("eyeLookInLeft");return i===null||this.getFixedValue("eyeLookOutRight")===null||this.getFixedValue("eyeLookInRight")===null?null:e-i}else if(t==="eyesRotateX"){const e=this.getFixedValue("eyesLookDown");if(e===null)return null;const i=this.getFixedValue("eyesLookUp");return i===null?null:e-i}else return this.mtAvatar[t]?.fixed}setFixedValue(t,e,i=null){t==="eyesRotateY"?(this.setFixedValue("eyeLookOutLeft",e===null?null:e>0?e:0,i),this.setFixedValue("eyeLookInLeft",e===null?null:e>0?0:-e,i),this.setFixedValue("eyeLookOutRight",e===null?null:e>0?0:-e,i),this.setFixedValue("eyeLookInRight",e===null?null:e>0?e:0,i)):t==="eyesRotateX"?(this.setFixedValue("eyesLookDown",e===null?null:e>0?e:0,i),this.setFixedValue("eyesLookUp",e===null?null:e>0?0:-e,i)):this.mtAvatar.hasOwnProperty(t)&&Object.assign(this.mtAvatar[t],{fixed:e,needsUpdate:!0})}animFactory(t,e=!1,i=1,n=1,s=!1){const o={template:t,ts:[0],vs:{}};let r=t;for(;;)if(r.hasOwnProperty(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.body&&r.hasOwnProperty(this.avatar.body))r=r[this.avatar.body];else if(r.hasOwnProperty("alt")){let a=r.alt[0];if(r.alt.length>1){const h=Math.random();let l=0;for(let c=0;c<r.alt.length;c++){let d=this.valueFn(r.alt[c].p);if(l+=d===void 0?(1-l)/(r.alt.length-1-c):d,h<l){a=r.alt[c];break}}}r=a}else break;let u=this.valueFn(r.delay)||0;if(Array.isArray(u)&&(u=this.gaussianRandom(...u)),r.hasOwnProperty("dt"))r.dt.forEach((a,h)=>{let l=this.valueFn(a);Array.isArray(l)&&(l=this.gaussianRandom(...l)),o.ts[h+1]=o.ts[h]+l});else{let a=Object.values(r.vs).reduce((h,l)=>l.length>h?l.length:h,0);o.ts=Array(a+1).fill(0)}s?o.ts=o.ts.map(a=>u+a*i):o.ts=o.ts.map(a=>this.animClock+u+a*i);for(let[a,h]of Object.entries(r.vs)){const l=this.getBaselineValue(a),c=h.map(d=>(d=this.valueFn(d),d===null?null:typeof d=="function"?d:typeof d=="string"||d instanceof String?d.slice():Array.isArray(d)?a==="gesture"?d.slice():(l===void 0?0:l)+n*this.gaussianRandom(...d):typeof d=="boolean"?d:d instanceof Object&&d.constructor===Object?Object.assign({},d):(l===void 0?0:l)+n*d));a==="eyesRotateY"?(o.vs.eyeLookOutLeft=[null,...c.map(d=>d>0?d:0)],o.vs.eyeLookInLeft=[null,...c.map(d=>d>0?0:-d)],o.vs.eyeLookOutRight=[null,...c.map(d=>d>0?0:-d)],o.vs.eyeLookInRight=[null,...c.map(d=>d>0?d:0)]):a==="eyesRotateX"?(o.vs.eyesLookDown=[null,...c.map(d=>d>0?d:0)],o.vs.eyesLookUp=[null,...c.map(d=>d>0?0:-d)]):o.vs[a]=[null,...c]}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,i,n,s,o=null){t=this.valueFn(t),e=this.valueFn(e),s<i&&(s=i),s>n&&(s=n);let r=(e-t)/(n-i);return o&&(r*=o((s-i)/(n-i))),r*s+(t-r*i)}gaussianRandom(t,e,i=1,n=5){let s=0;for(let o=0;o<n;o++)s+=Math.random();return t+Math.pow(s/n,i)*(e-t)}sigmoidFactory(t){function e(n){return 1/(1+Math.exp(-t*n))-.5}var i=.5/e(1);return function(n){return i*e(2*Math.max(Math.min(n,1),0)-1)+.5}}convertRange(t,e,i){return(t-e[0])*(i[1]-i[0])/(e[1]-e[0])+i[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 i,n,s,o,r=0;if(this.stats&&this.stats.begin(),this.isListening){for(this.listeningAnalyzer.getByteFrequencyData(this.volumeFrequencyData),i=2,s=10;i<s;i++)this.volumeFrequencyData[i]>r&&(r=this.volumeFrequencyData[i]);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),i=2,s=10;i<s;i++)this.volumeFrequencyData[i]>r&&(r=this.volumeFrequencyData[i]);let u=null,a=null;const h=[];for(i=0,s=this.animQueue.length;i<s;i++){const l=this.animQueue[i];if(!(!l||!l.ts||!l.ts.length||this.animClock<l.ts[0])){for(n=l.ndx||0,o=l.ts.length;n<o&&!(this.animClock<l.ts[n]);n++)for(let[c,d]of Object.entries(l.vs))if(this.mtAvatar.hasOwnProperty(c)){if(d[n+1]===null)continue;const g=this.mtAvatar[c];if(d[n]===null&&(d[n]=g.value),n===o-1)g.newvalue=d[n];else{g.newvalue=d[n+1];const y=l.ts[n+1]-l.ts[n];let x=1;y>1e-4&&(x=(this.animClock-l.ts[n])/y),x<1&&(g.easing&&(x=g.easing(x)),g.newvalue=(1-x)*d[n]+x*g.newvalue),g.ref&&g.ref!==l.vs&&g.ref.hasOwnProperty(c)&&delete g.ref[c],g.ref=l.vs}if(r)switch(c){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 c==="eyeContact"&&d[n]!==null&&u!==!1?u=!!d[n]:c==="headMove"&&d[n]!==null&&a!==!1?d[n]===0?a=!1:(Math.random()<d[n]&&(a=!0),d[n]=null):d[n]!==null&&(h.push({mt:c,val:d[n]}),d[n]=null);n===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[i]=this.animFactory(l.template,l.loop>0?l.loop-1:l.loop,1,1/o)):(this.animQueue.splice(i--,1),s--)):l.ndx=n-1}}for(let l=0,c=h.length;l<c;l++)switch(n=h[l].val,h[l].mt){case"speak":this.speakText(n);break;case"subtitles":this.onSubtitles&&typeof this.onSubtitles=="function"&&this.onSubtitles(n);break;case"pose":this.poseName=n,this.setPoseFromTemplate(this.poseTemplates[this.poseName]);break;case"gesture":this.playGesture(...n);break;case"function":n&&typeof n=="function"&&n();break;case"moveto":Object.entries(n.props).forEach(d=>{d[1]?this.poseTarget.props[d[0]].copy(d[1]):this.poseTarget.props[d[0]].copy(this.getPoseTemplateProp(d[0])),this.poseTarget.props[d[0]].t=this.animClock,this.poseTarget.props[d[0]].d=d[1]&&d[1].d?d[1].d:d.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}]},n.x?new f.Vector3(n.x,n.y,n.z):null,!0,n.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}]},n.x?new f.Vector3(n.x,n.y,n.z):null,!0,n.d);break}if((u||a)&&(F.setFromQuaternion(this.poseAvatar.props["Head.quaternion"]),F.x=Math.max(-.9,Math.min(.9,2*F.x-.5)),F.y=Math.max(-.9,Math.min(.9,-2.5*F.y)),u?(Object.assign(this.mtAvatar.eyesLookDown,{system:F.x<0?-F.x:0,needsUpdate:!0}),Object.assign(this.mtAvatar.eyesLookUp,{system:F.x<0?0:F.x,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookInLeft,{system:F.y<0?-F.y:0,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookOutLeft,{system:F.y<0?0:F.y,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookInRight,{system:F.y<0?0:F.y,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookOutRight,{system:F.y<0?-F.y:0,needsUpdate:!0}),a&&(i=-this.mtAvatar.bodyRotateY.value,n=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:[i,i,0],headRotateX:[n,n,0],headRotateZ:[-i/4,-i/4,0]}})))):(i=this.mtAvatar.eyeLookInLeft.value-this.mtAvatar.eyeLookOutLeft.value,n=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,i,i,0],headRotateX:[null,n,n,0],headRotateZ:[null,-i/4,-i/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)&&(i=this.mtRandomized[Math.floor(Math.random()*this.mtRandomized.length)],n=this.mtAvatar[i],n.needsUpdate||Object.assign(n,{base:(this.mood.baseline[i]||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.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),i=this.volumeHeadTarget-this.volumeHeadCurrent,n=Math.abs(i),n>1e-4&&(o=n*(this.volumeHeadEasing(Math.min(1,this.volumeHeadVelocity*e/1e3/n)/2+.5)-.5),this.volumeHeadCurrent+=Math.sign(i)*Math.min(n,o)),Math.abs(this.volumeHeadCurrent)>1e-4&&(U.setFromAxisAngle($e,this.volumeHeadCurrent),this.objectNeck.quaternion.multiply(U)),Ie.setFromObject(this.armature),this.objectLeftToeBase.getWorldPosition(ie),ie.sub(this.armature.position),this.objectRightToeBase.getWorldPosition(oe),oe.sub(this.armature.position),this.objectHips.position.y-=Ie.min.y/2,this.objectHips.position.x-=(ie.x+oe.x)/4,this.objectHips.position.z-=(ie.z+oe.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 f.Spherical().setFromVector3(this.cameraStart),c=new f.Spherical().setFromVector3(this.cameraEnd);l.phi+=this.easing(this.cameraClock/1e3)*(c.phi-l.phi),l.theta+=this.easing(this.cameraClock/1e3)*(c.theta-l.theta),l.radius+=this.easing(this.cameraClock/1e3)*(c.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),c.setFromVector3(this.controlsEnd),l.phi+=this.easing(this.cameraClock/1e3)*(c.phi-l.phi),l.theta+=this.easing(this.cameraClock/1e3)*(c.theta-l.theta),l.radius+=this.easing(this.cameraClock/1e3)*(c.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 i=e.morphTargetDictionary["viseme_"+t];i!==void 0&&(e.morphTargetInfluences[i]=0)})})}lipsyncGetProcessor(t,e="./"){if(!this.lipsync.hasOwnProperty(t)){const i=t.toLowerCase(),n="Lipsync"+t.charAt(0).toUpperCase()+t.slice(1);try{const s=ve[i];s&&s[n]?(this.lipsync[t]=new s[n],console.log(`Loaded lip-sync module for ${t}`)):console.warn(`Lip-sync module for ${t} not found. Available modules:`,Object.keys(ve))}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,i=null,n=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 h="",l="",c=0,d=[],g=[];const y=Array.from(this.segmenter.segment(t),x=>x.segment);for(let x=0;x<y.length;x++){const I=x===y.length-1,P=y[x].match(r);let p=y[x].match(s);const z=y[x].match(u),H=y[x].match(o);if(p&&!I&&!z&&y[x+1].match(s)&&(p=!1),i&&(h+=y[x]),P&&(!n||n.every(R=>x<R[0]||x>R[1]))&&(l+=y[x]),(H||p||I)&&(l.length&&(l=this.lipsyncPreProcessText(l,a),l.length&&d.push({mark:c,word:l})),h.length&&(g.push({mark:c,template:{name:"subtitles"},ts:[0],vs:{subtitles:[h]}}),h=""),l.length)){const R=this.lipsyncWordsToVisemes(l,a);if(R&&R.visemes&&R.visemes.length){const W=R.times[R.visemes.length-1]+R.durations[R.visemes.length-1];for(let O=0;O<R.visemes.length;O++)g.push({mark:c,template:{name:"viseme"},ts:[(R.times[O]-.6)/W,(R.times[O]+.5)/W,(R.times[O]+R.durations[O]+.5)/W],vs:{["viseme_"+R.visemes[O]]:[null,R.visemes[O]==="PP"||R.visemes[O]==="FF"?.9:.6,0]}})}l="",c++}if(p||I){if(d.length||I&&g.length){const R={anim:g};i&&(R.onSubtitles=i),d.length&&!e.avatarMute&&(R.text=d,e.avatarMood&&(R.mood=e.avatarMood),e.ttsLang&&(R.lang=e.ttsLang),e.ttsVoice&&(R.voice=e.ttsVoice),e.ttsRate&&(R.rate=e.ttsRate),e.ttsVoice&&(R.pitch=e.ttsPitch),e.ttsVolume&&(R.volume=e.ttsVolume)),this.speechQueue.push(R),d=[],l="",c=0,g=[]}if(z){let R=this.animEmojis[y[x]];R&&R.link&&(R=this.animEmojis[R.link]),R&&this.speechQueue.push({emoji:R})}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 i=await(await fetch(t)).arrayBuffer();this.stopBackgroundAudio(),this.audioBackgroundSource=this.audioCtx.createBufferSource(),this.audioBackgroundSource.loop=!0,this.audioBackgroundSource.buffer=await this.audioCtx.decodeAudioData(i),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 i=await(await fetch(t)).arrayBuffer();this.audioReverbNode.buffer=await this.audioCtx.decodeAudioData(i)}else{const e=this.audioCtx.sampleRate,i=this.audioCtx.createBuffer(2,e,e);i.getChannelData(0)[0]=1,i.getChannelData(1)[0]=1,this.audioReverbNode.buffer=i}}setMixerGain(t,e=null,i=0){t!==null&&(this.audioSpeechGainNode.gain.cancelScheduledValues(this.audioCtx.currentTime),i?(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+i)):this.audioSpeechGainNode.gain.setValueAtTime(t,this.audioCtx.currentTime)),e!==null&&(this.audioBackgroundGainNode.gain.cancelScheduledValues(this.audioCtx.currentTime),i?(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+i)):this.audioBackgroundGainNode.gain.setValueAtTime(e,this.audioCtx.currentTime))}speakAudio(t,e=null,i=null){e=e||{};const n=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 h=t.wdurations[r];if(u.length&&(i&&o.push({template:{name:"subtitles"},ts:[a],vs:{subtitles:[" "+u]}}),!t.visemes)){const l=this.lipsyncPreProcessText(u,n),c=this.lipsyncWordsToVisemes(l,n);if(c&&c.visemes&&c.visemes.length){const d=c.times[c.visemes.length-1]+c.durations[c.visemes.length-1],g=Math.min(h,Math.max(0,h-c.visemes.length*150));let y=.6+this.convertRange(g,[0,h],[0,.4]);if(h=Math.min(h,c.visemes.length*200),d>0)for(let x=0;x<c.visemes.length;x++){const I=a+c.times[x]/d*h,P=c.durations[x]/d*h;o.push({template:{name:"viseme"},ts:[I-Math.min(60,2*P/3),I+Math.min(25,P/2),I+P+Math.min(60,P/2)],vs:{["viseme_"+c.visemes[x]]:[null,c.visemes[x]==="PP"||c.visemes[x]==="FF"?.9:y,0]}})}}}}if(t.visemes)for(let r=0;r<t.visemes.length;r++){const u=t.visemes[r],a=t.vtimes[r],h=t.vdurations[r];o.push({template:{name:"viseme"},ts:[a-2*h/3,a+h/2,a+h+h/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]}i&&(s.onSubtitles=i),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 i;if(Array.isArray(e.audio)){let s=this.concatArrayBuffers(e.audio);i=this.pcmToAudioBuffer(s)}else i=e.audio;this.audioSpeechSource=this.audioCtx.createBufferSource(),this.audioSpeechSource.buffer=i,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 n=0;e.anim&&(e.isRaw||(n=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]+n;this.animQueue.push(s)})),this.audioSpeechSource.start(n/1e3)}else this.isAudioPlaying=!1,this.startSpeaking(!0)}async synthesizeWithBrowserTTS(t){return new Promise((e,i)=>{const n=t.text.map(p=>p.word).join(" "),s=new SpeechSynthesisUtterance(n),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 h=speechSynthesis.getVoices(),l=t.voice||this.avatar.ttsVoice||this.opt.ttsVoice;if(l&&h.length>0){const p=h.find(z=>z.name.includes(l)||z.lang===o);p&&(s.voice=p)}const c=n.length*100/s.rate,d=this.audioCtx.createBuffer(1,this.audioCtx.sampleRate*(c/1e3),this.audioCtx.sampleRate),g=this.avatar.lipsyncLang||this.opt.lipsyncLang||"en",y=this.lipsyncPreProcessText(n,g),x=this.lipsyncWordsToVisemes(y,g);console.log("Browser TTS Lip-sync Debug:",{text:n,lipsyncLang:g,processedText:y,lipsyncData:x,hasVisemes:x&&x.visemes&&x.visemes.length>0,estimatedDuration:c});const I=[];if(x&&x.visemes&&x.visemes.length>0){const p=x.times[x.visemes.length-1]+x.durations[x.visemes.length-1];for(let z=0;z<x.visemes.length;z++){const H=x.visemes[z],R=x.times[z]/p,W=x.durations[z]/p,O=R*c,Y=W*c;I.push({template:{name:"viseme"},ts:[O-Math.min(60,2*Y/3),O+Math.min(25,Y/2),O+Y+Math.min(60,Y/2)],vs:{["viseme_"+H]:[null,H==="PP"||H==="FF"?.9:.6,0]}})}}const P=[...t.anim,...I];this.audioPlaylist.push({anim:P,audio:d}),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),i(p.error)},speechSynthesis.speak(s)})}async synthesizeWithElevenLabsTTS(t){const e=t.text.map(c=>c.word).join(" "),i=t.voice||this.avatar.ttsVoice||this.opt.ttsVoice||"21m00Tcm4TlvDq8ikWAM",n={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}/${i}`,{method:"POST",headers:{Accept:"audio/mpeg","Content-Type":"application/json","xi-api-key":this.opt.ttsApikey},body:JSON.stringify(n)});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 c=this.lipsyncPreProcessText(e,u),d=this.lipsyncWordsToVisemes(c,u);if(console.log("Lip-sync data:",{processedText:c,lipsyncData:d,hasVisemes:d&&d.visemes&&d.visemes.length>0}),d&&d.visemes&&d.visemes.length>0)a={visemes:d.visemes.map((g,y)=>({viseme:g,startTime:y*r.duration/d.visemes.length,endTime:(y+1)*r.duration/d.visemes.length,duration:r.duration/d.visemes.length,intensity:.7})),words:[],duration:r.duration,features:{onsets:[],boundaries:[]}};else throw new Error("No visemes generated from text")}catch(c){console.error("Text-based lip-sync failed, using fallback:",c);const d=e.toLowerCase().split(/\s+/),g=[];for(const y of d)for(const x of y){let I="aa";"aeiou".includes(x)?I="aa":"bp".includes(x)?I="PP":"fv".includes(x)?I="FF":"st".includes(x)?I="SS":"dln".includes(x)?I="DD":"kg".includes(x)?I="kk":"rw".includes(x)&&(I="RR"),g.push(I)}a={visemes:g.map((y,x)=>({viseme:y,startTime:x*r.duration/g.length,endTime:(x+1)*r.duration/g.length,duration:r.duration/g.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 h=[];if(a.visemes&&a.visemes.length>0){console.log("ElevenLabs: Generating lip-sync animation from",a.visemes.length,"visemes");for(let c=0;c<a.visemes.length;c++){const d=a.visemes[c],g=d.startTime*1e3,y=d.duration*1e3,x=d.intensity;h.push({template:{name:"viseme"},ts:[g-Math.min(60,2*y/3),g+Math.min(25,y/2),g+y+Math.min(60,y/2)],vs:{["viseme_"+d.viseme]:[null,x,0]}})}console.log("ElevenLabs: Generated",h.length,"lip-sync animation frames")}else console.warn("ElevenLabs: No visemes available for lip-sync animation");const l=[...t.anim,...h];console.log("ElevenLabs: Combined animation frames:",l.length,"(original:",t.anim.length,"+ lipsync:",h.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(c=>c.word).join(" "),i=t.voice||this.avatar.ttsVoice||this.opt.ttsVoice||"aura-2-thalia-en",n=`${this.opt.ttsEndpoint}?model=${i}`,s=await fetch(n,{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 c=this.lipsyncPreProcessText(e,u),d=this.lipsyncWordsToVisemes(c,u);if(console.log("Lip-sync data:",{processedText:c,lipsyncData:d,hasVisemes:d&&d.visemes&&d.visemes.length>0}),d&&d.visemes&&d.visemes.length>0)a={visemes:d.visemes.map((g,y)=>({viseme:g,startTime:y*r.duration/d.visemes.length,endTime:(y+1)*r.duration/d.visemes.length,duration:r.duration/d.visemes.length,intensity:.7})),words:[],duration:r.duration,features:{onsets:[],boundaries:[]}};else throw new Error("No visemes generated from text")}catch(c){console.error("Text-based lip-sync failed, using fallback:",c);const d=e.toLowerCase().split(/\s+/),g=[];for(const y of d)for(const x of y){let I="aa";"aeiou".includes(x)?I="aa":"bp".includes(x)?I="PP":"fv".includes(x)?I="FF":"st".includes(x)?I="SS":"dln".includes(x)?I="DD":"kg".includes(x)?I="kk":"rw".includes(x)&&(I="RR"),g.push(I)}a={visemes:g.map((y,x)=>({viseme:y,startTime:x*r.duration/g.length,endTime:(x+1)*r.duration/g.length,duration:r.duration/g.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 h=[];if(a.visemes&&a.visemes.length>0){console.log("Deepgram: Generating lip-sync animation from",a.visemes.length,"visemes");for(let c=0;c<a.visemes.length;c++){const d=a.visemes[c],g=d.startTime*1e3,y=d.duration*1e3,x=d.intensity;h.push({template:{name:"viseme"},ts:[g-Math.min(60,2*y/3),g+Math.min(25,y/2),g+y+Math.min(60,y/2)],vs:{["viseme_"+d.viseme]:[null,x,0]}})}console.log("Deepgram: Generated",h.length,"lip-sync animation frames")}else console.warn("Deepgram: No visemes available for lip-sync animation");const l=[...t.anim,...h];console.log("Deepgram: Combined animation frames:",l.length,"(original:",t.anim.length,"+ lipsync:",h.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(" "),n=`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ee=require("react/jsx-runtime"),A=require("react"),He=require("three"),Te=require("three/addons/controls/OrbitControls.js"),Me=require("three/addons/loaders/GLTFLoader.js"),Ee=require("three/addons/loaders/DRACOLoader.js"),be=require("three/addons/loaders/FBXLoader.js"),Fe=require("three/addons/environments/RoomEnvironment.js"),Pe=require("three/addons/libs/stats.module.js");var ge=typeof document<"u"?document.currentScript:null;function Be(E){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(E){for(const e in E)if(e!=="default"){const i=Object.getOwnPropertyDescriptor(E,e);Object.defineProperty(t,e,i.get?i:{enumerable:!0,get:()=>E[e]})}}return t.default=E,Object.freeze(t)}const f=Be(He);let m,Y,Q;const k=[0,0,0,0],C=new f.Vector3,le=new f.Vector3,G=new f.Vector3,he=new f.Vector3;new f.Plane;new f.Ray;new f.Euler;const Z=new f.Quaternion,Re=new f.Quaternion,J=new f.Matrix4,$=new f.Matrix4;new f.Vector3;const ue=new f.Vector3(0,0,1),De=new f.Vector3(1,0,0),Oe=new f.Vector3(0,1,0),Ne=new f.Vector3(0,0,1);class Ue{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 i=this.dict[t];let n;if(e==="type")n=i.type;else if(e==="stiffness")n=i.k.every(s=>s===i.k[0])?i.k[0]:[...i.k];else if(e==="damping")n=i.c.every(s=>s===i.c[0])?i.c[0]:[...i.c];else if(e==="external")n=i.ext<1?i.ext:null;else if(e==="limits")n=i.limits?.map(s=>s===null?null:[...s]);else if(e==="deltaLocal")n=i.dl?[...i.dl]:null;else if(e==="excludes")n=i.excludes?[...i.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")n=i.dw?[...i.dw]:null;else if(e==="pivot")n=i.pivot;else if(e==="helper")n=i.helper;else throw new Error("Unsupported property '"+e+"'.");return n}setValue(t,e,i){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];if(e==="type"){if(!i)throw new Error("Parameter 'type' not set.");if(typeof i!="string")throw new Error("Type must be a string.");switch(i){case"point":n.isPoint=!0,n.isX=!0,n.isY=!0,n.isZ=!0,n.isT=!1;break;case"link":n.isPoint=!1,n.isX=!0,n.isY=!1,n.isZ=!0,n.isT=!1;break;case"mix1":n.isPoint=!1,n.isX=!0,n.isY=!0,n.isZ=!0,n.isT=!1;break;case"mix2":n.isPoint=!1,n.isX=!0,n.isY=!1,n.isZ=!0,n.isT=!0;break;case"full":n.isPoint=!1,n.isX=!0,n.isY=!0,n.isZ=!0,n.isT=!0;break;default:throw new Error("Unknown type'"+i+"'.")}n.type=i.slice()}else if(e==="stiffness"){if(!i)throw new Error("Parameter 'stiffness' not set.");if(!Number.isNaN(i)&&i>=0)n.k=Array(4).fill(i);else if(Array.isArray(i)&&i.length===4&&i.every(s=>s>=0))n.k=[...i];else throw new Error("Stiffness must be a non-negative number or an array of four non-negative numbers.")}else if(e==="damping"){if(!i)throw new Error("Parameter 'damping' not set.");if(!Number.isNaN(i)&&i>=0)n.c=Array(4).fill(i);else if(Array.isArray(i)&&i.length===4&&i.every(s=>s>=0))n.c=[...i];else throw new Error("Damping must be a non-negative number or an array of four non-negative numbers.")}else if(e==="external")if(i==null)n.ext=1;else if(!Number.isNaN(i)&&i>=0&&i<=1)n.ext=i;else throw new Error("External (if set) must be a number between [0,1].");else if(e==="limits")if(i==null)n.limits=null;else{if(!Array.isArray(i)||i.length!==4)throw new Error("Limits (if set) must null, or an array of four arrays.");if(!i.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.");n.limits=[i[0]?[...i[0]]:null,i[1]?[...i[1]]:null,i[2]?[...i[2]]:null,i[3]?[...i[3]]:null]}else if(e==="excludes"){if(i==null)n.excludes=null;else{if(!Array.isArray(i))throw new Error("Excludes (if set) must null, or an array.");n.excludes=[],i.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 l=this.armature.getObjectByName(s.bone);if(!l)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:l,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]}n.excludes.push(u)})}this.showHelpers()}else if(e==="helper"){if(i==null)n.helper=null;else{if(i!==!1&&i!==!0)throw new Error("Helper, if set, must be false or true.");n.helper=i}this.showHelpers()}else if(e==="pivot")if(i==null)n.pivot=null;else{if(i!==!1&&i!==!0)throw new Error("Pivot, if set, must be false or true.");if(i===!0&&n.type===0)throw new Error("Point type bone can't be a pivot.");n.pivot=i}else if(e==="deltaLocal")if(i==null)n.dl=null;else{if(!Array.isArray(i)||i.length!==3)throw new Error("deltaLocal, is set, must be an array of three numbers.");if(!i.every(s=>!Number.isNaN(s)))throw new Error("deltaLocal values must be numbers.");n.dl=[...i]}else if(e==="deltaWorld")if(i==null)n.dw=null;else{if(!Array.isArray(i)||i.length!==3)throw new Error("deltaWorld, is set, must be an array of three values.");if(!i.every(s=>!Number.isNaN(s)))throw new Error("deltaWorld values must be numbers.");n.dw=[...i]}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(i=>{m=this.getValue(t.name,i),m&&(e[i]=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,l)=>e.get(o.bone)-e.get(l.bone)),this.data.forEach(o=>{m=this.dict[o.boneParent.name],m&&(m.children||(m.children=[]),m.children.push(o))}),this.objectsUpdate=[];const i=new WeakSet,n=o=>o.parent?.isBone?[o,...n(o.parent)]:[o],s=o=>{n(o).forEach(u=>{i.has(u)||(this.objectsUpdate.push(u),i.add(u))})};this.data.forEach(o=>{s(o.bone),o.excludes&&o.excludes.forEach(l=>{s(l.bone)})}),this.objectsUpdate.sort((o,l)=>e.get(o)-e.get(l))}setup(t,e,i){this.dispose();const n=(s,o)=>{if(!s)throw this.dispose(),new Error(o)};n(t?.isScene,"First parameter must be Scene."),this.scene=t,n(e?.isObject3D,"Second parameter must be the armature Object3D."),this.armature=e,n(Array.isArray(i),"Third parameter must be an array of bone configs."),this.config=i,this.config.forEach((s,o)=>{const l="Config item #"+o+": ";n(s.bone,l+"Bone not specified.");const u=s.bone;n(typeof u=="string"&&u.length>0,l+"Bone name must be a non-empty string.");const a=this.armature.getObjectByName(u);n(a,l+"Bone '"+u+"' not found."),n(a.parent?.isBone,l+"Bone must have a parent bone."),n(this.data.every(r=>r.bone!==a),l+"Bone '"+u+"' already exists."),a.updateMatrixWorld(!0);const h={name:u,bone:a,boneParent:a.parent,vBasis:a.position.clone(),vWorld:a.parent.getWorldPosition(C).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]};h.boneParent.matrixWorld.decompose(C,Z,G),C.copy(ue).applyQuaternion(Z).setY(0).normalize(),Z.premultiply(Re.setFromUnitVectors(ue,C).invert()).normalize(),h.qWorldInverseYaw=Z.clone().normalize(),this.data.push(h),this.dict[u]=h;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(r){n(!1,l+r)}}),this.sortBones(),this.start()}update(t){if(!this.running)return;let e,i,n,s,o;for(this.timerMs+=t,t>1e3&&(this.timerMs=0),t/=1e3,e=0,n=this.objectsUpdate.length;e<n;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,n=this.data.length;e<n;e++){if(o=this.data[e],C.copy(o.vWorld),J.copy(o.boneParent.matrixWorld),$.copy(J).invert(),o.vWorld.setFromMatrixPosition(J),C.applyMatrix4($),C.length()>.5&&(console.info("Info: Unrealistic jump of "+C.length().toFixed(2)+" meters."),C.setLength(.5)),C.applyQuaternion(o.bone.quaternion),k[0]=C.x,k[1]=C.y,k[2]=-C.z,k[3]=C.length()/3,o.children)for(i=0,s=o.children.length;i<s;i++)m=o.children[i],k[0]-=m.v[0]*t/3,k[1]-=m.v[1]*t/3,k[2]+=m.v[2]*t/3,k[3]-=m.v[3]*t/3;if(m=this.opt.sensitivityFactor,k[0]*=o.ext*m,k[1]*=o.ext*m,k[2]*=o.ext*m,k[3]*=o.ext*m,o.isX&&(m=k[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+k[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=k[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+k[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=k[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+k[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=k[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+k[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),k[0]=o.p[0],k[1]=o.p[1],k[2]=o.p[2],k[3]=o.p[3],m=this.opt.movementFactor,k[0]*=m,k[1]*=m,k[2]*=m,k[3]*=m,o.dl&&(m=o.dl,k[0]+=m[0],k[1]+=m[1],k[2]+=m[2]),o.dw&&(m=o.dw,C.set(o.vBasis.x+k[0],o.vBasis.y+k[1],o.vBasis.z+k[2]),C.applyMatrix4(J),C.x+=m[0],C.y+=m[1],C.z+=m[2],C.applyMatrix4($),k[0]+=C.x-o.vBasis.x,k[1]+=C.y-o.vBasis.y,k[2]+=C.z-o.vBasis.z),o.limits&&this.opt.isLimits&&(m=o.limits,m[0]&&(m[0][0]!==null&&k[0]<m[0][0]&&(k[0]=m[0][0]),m[0][1]!==null&&k[0]>m[0][1]&&(k[0]=m[0][1])),m[1]&&(m[1][0]!==null&&k[1]<m[1][0]&&(k[1]=m[1][0]),m[1][1]!==null&&k[1]>m[1][1]&&(k[1]=m[1][1])),m[2]&&(m[2][0]!==null&&k[2]<m[2][0]&&(k[2]=m[2][0]),m[2][1]!==null&&k[2]>m[2][1]&&(k[2]=m[2][1])),m[3]&&(m[3][0]!==null&&k[3]<m[3][0]&&(k[3]=m[3][0]),m[3][1]!==null&&k[3]>m[3][1]&&(k[3]=m[3][1]))),o.isPoint)o.bone.position.set(o.vBasis.x+k[0],o.vBasis.y+k[1],o.vBasis.z-k[2]);else if(o.boneParent.quaternion.copy(o.qBasis),o.pivot&&this.opt.isPivots&&(o.boneParent.updateWorldMatrix(!1,!1),o.boneParent.matrixWorld.decompose(C,Z,G),C.copy(ue).applyQuaternion(Z).setY(0).normalize(),Z.premultiply(Re.setFromUnitVectors(ue,C).invert()).normalize(),o.boneParent.quaternion.multiply(Z.invert()),o.boneParent.quaternion.multiply(o.qWorldInverseYaw)),o.isZ&&(m=Math.atan(k[0]/o.l),Z.setFromAxisAngle(Ne,-m),o.boneParent.quaternion.multiply(Z)),o.isY&&(m=o.l/3,m=m*Math.tanh(k[1]/m),o.bone.position.setLength(o.l+m)),o.isX&&(m=Math.atan(k[2]/o.l),Z.setFromAxisAngle(De,-m),o.boneParent.quaternion.multiply(Z)),o.isT&&(m=1.5*Math.tanh(k[3]*1.5),Z.setFromAxisAngle(Oe,-m),o.boneParent.quaternion.multiply(Z)),o.boneParent.updateWorldMatrix(!1,!0),o.excludes&&this.opt.isExcludes)for(i=0,s=o.excludes.length;i<s;i++)m=o.excludes[i],G.set(0,0,0),m.deltaLocal&&(G.x+=m.deltaLocal[0],G.y+=m.deltaLocal[1],G.z+=m.deltaLocal[2]),G.applyMatrix4(m.bone.matrixWorld),$.copy(o.boneParent.matrixWorld).invert(),G.applyMatrix4($),C.copy(o.bone.position),!(C.distanceToSquared(G)>=m.radiusSq)&&(Q=C.length(),Y=G.length(),!(Y>m.radius+Q)&&(Y<Math.abs(m.radius-Q)||(Y=(Y*Y+Q*Q-m.radiusSq)/(2*Y),G.normalize(),he.copy(G).multiplyScalar(Y),Y=Math.sqrt(Q*Q-Y*Y),C.subVectors(C,he).projectOnPlane(G).normalize().multiplyScalar(Y),le.subVectors(o.vBasis,he).projectOnPlane(G).normalize(),Q=le.dot(C),Q<0&&(Q=Math.sqrt(Y*Y-Q*Q),le.multiplyScalar(Q),C.add(le)),C.add(he).normalize(),G.copy(o.bone.position).normalize(),Z.setFromUnitVectors(G,C),o.boneParent.quaternion.premultiply(Z),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(i=>{let n=!1;for(let s=0;s<m.excludes.bones.length;s++)if(m.excludes.bones[s]===i.bone&&m.excludes.radii[s]===i.radius&&!(m.excludes.deltaLocals[s]===null&&i.deltaLocal!==null)&&!(m.excludes.deltaLocals[s]!==null&&i.deltaLocal===null)&&!(m.excludes.deltaLocals[s]!==null&&m.excludes.deltaLocals[s].some((o,l)=>o!==i.deltaLocal[l]))){n=!0;break}n||(m.excludes.bones.push(i.bone),m.excludes.radii.push(i.radius),m.excludes.deltaLocals.push(i.deltaLocal?[...i.deltaLocal]:null),m.excludes.objects.push(null))}))}),m=this.helpers.excludes,this.opt.isExcludes&&m.bones.length&&m.bones.forEach((e,i)=>{const n=new f.SphereGeometry(m.radii[i],6,6),s=new f.MeshBasicMaterial({depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0,wireframe:!0,color:this.opt.helperExcludesColor});m.objects[i]=new f.Mesh(n,s),m.objects[i].renderOrder=997,e.add(m.objects[i]),m.deltaLocals[i]&&m.objects[i].position.set(m.deltaLocals[i][0],m.deltaLocals[i][1],m.deltaLocals[i][2])}),m=this.helpers.points,m.bones.length){this.helpers.isActive=!0;const e=new f.BufferGeometry,i=m.bones.map(u=>[0,0,0]).flat();e.setAttribute("position",new f.Float32BufferAttribute(i,3));const n=new f.Color(this.opt.helperBoneColor1),s=new f.Color(this.opt.helperBoneColor2),o=m.pivots.map(u=>u&&this.opt.isPivots?[s.r,s.g,s.b]:[n.r,n.g,n.b]).flat();e.setAttribute("color",new f.Float32BufferAttribute(o,3));const l=new f.PointsMaterial({depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0,size:.2,vertexColors:!0});m.object=new f.Points(e,l),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,i=m.bones.map(u=>[0,0,0,0,0,0]).flat();e.setAttribute("position",new f.Float32BufferAttribute(i,3));const n=new f.Color(this.opt.helperLinkColor1),s=new f.Color(this.opt.helperLinkColor2),o=m.bones.map(u=>[n.r,n.g,n.b,s.r,s.g,s.b]).flat();e.setAttribute("color",new f.Float32BufferAttribute(o,3));const l=new f.LineBasicMaterial({vertexColors:!0,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0});m.object=new f.LineSegments(e,l),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){$.copy(this.armature.matrixWorld).invert();const t=m.object.geometry.getAttribute("position");for(let e=0,i=m.bones.length;e<i;e++)J.multiplyMatrices($,m.bones[e].matrixWorld),C.setFromMatrixPosition(J),t.setXYZ(e,C.x,C.y,C.z);t.needsUpdate=!0,m.object.updateMatrixWorld()}if(m=this.helpers.lines,m.bones.length){$.copy(this.armature.matrixWorld).invert();const t=m.object.geometry.getAttribute("position");for(let e=0,i=0,n=m.bones.length;e<n;e++,i+=2)J.multiplyMatrices($,m.bones[e].matrixWorld),C.setFromMatrixPosition(J),t.setXYZ(i,C.x,C.y,C.z),J.multiplyMatrices($,m.bones[e].parent.matrixWorld),C.setFromMatrixPosition(J),t.setXYZ(i+1,C.x,C.y,C.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 i=this.data[t];i.bone.position.copy(i.vBasis),i.boneParent.quaternion.copy(i.qBasis)}}dispose(){this.stop(),this.scene=null,this.armature=null,this.config=[],this.data=[],this.dict={},this.objectsUpdate=[],this.timerMs=0}}class We{constructor(t){this.audioContext=t,this.analyzer=null,this.dataArray=null,this.bufferLength=0}async analyzeAudio(t,e){const i=t.sampleRate,n=t.duration,s=t.getChannelData(0),o=this.extractAudioFeatures(s,i);return this.generateTimingData(o,e,n)}extractAudioFeatures(t,e){const i={energy:[],spectralCentroid:[],zeroCrossingRate:[],mfcc:[],onsets:[],phonemeBoundaries:[]},n=1024,s=512,o=Math.floor((t.length-n)/s)+1;for(let l=0;l<o;l++){const u=l*s,a=Math.min(u+n,t.length),h=t.slice(u,a),r=this.calculateEnergy(h);i.energy.push(r);const d=this.calculateSpectralCentroid(h);i.spectralCentroid.push(d);const c=this.calculateZeroCrossingRate(h);i.zeroCrossingRate.push(c);const g=this.calculateMFCC(h);i.mfcc.push(g)}return i.onsets=this.detectOnsets(i.energy),i.phonemeBoundaries=this.detectPhonemeBoundaries(i),i}calculateEnergy(t){let e=0;for(let i=0;i<t.length;i++)e+=t[i]*t[i];return e/t.length}calculateSpectralCentroid(t){const e=this.fft(t);let i=0,n=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]);i+=s*o,n+=o}return n>0?i/n:0}calculateZeroCrossingRate(t){let e=0;for(let i=1;i<t.length;i++)t[i]>=0!=t[i-1]>=0&&e++;return e/(t.length-1)}calculateMFCC(t){const e=this.fft(t),i=[];for(let n=0;n<13;n++){let s=0;for(let o=0;o<e.length/2;o++){const l=Math.sqrt(e[o*2]*e[o*2]+e[o*2+1]*e[o*2+1]);s+=l*Math.cos(Math.PI*n*(o+.5)/(e.length/2))}i.push(s)}return i}fft(t){const e=t.length,i=new Float32Array(e*2);for(let n=0;n<e;n++)i[n*2]=t[n],i[n*2+1]=0;for(let n=1,s=0;n<e;n++){let o=e>>1;for(;s&o;)s^=o,o>>=1;if(s^=o,n<s){const l=i[n*2],u=i[n*2+1];i[n*2]=i[s*2],i[n*2+1]=i[s*2+1],i[s*2]=l,i[s*2+1]=u}}for(let n=2;n<=e;n<<=1){const s=-2*Math.PI/n,o=Math.cos(s),l=Math.sin(s);for(let u=0;u<e;u+=n){let a=1,h=0;for(let r=0;r<n/2;r++){const d=i[(u+r)*2],c=i[(u+r)*2+1],g=i[(u+r+n/2)*2]*a-i[(u+r+n/2)*2+1]*h,y=i[(u+r+n/2)*2]*h+i[(u+r+n/2)*2+1]*a;i[(u+r)*2]=d+g,i[(u+r)*2+1]=c+y,i[(u+r+n/2)*2]=d-g,i[(u+r+n/2)*2+1]=c-y;const x=a*o-h*l,L=a*l+h*o;a=x,h=L}}}return i}detectOnsets(t){const e=[];let s=-.1;for(let o=1;o<t.length;o++){const l=t[o]-t[o-1],u=o*.023;l>.1&&u-s>.1&&(e.push(u),s=u)}return e}detectPhonemeBoundaries(t){const e=[],{energy:i,spectralCentroid:n,zeroCrossingRate:s}=t;for(let o=1;o<i.length;o++){const l=o*.023,u=Math.abs(i[o]-i[o-1]),a=Math.abs(n[o]-n[o-1]),h=Math.abs(s[o]-s[o-1]);u+a*.1+h*.5>.2&&e.push(l)}return e}generateTimingData(t,e,i){const n=e.toLowerCase().split(/\s+/);t.phonemeBoundaries,t.onsets;const s=[];let o=0;for(let u=0;u<n.length;u++){const a=n[u],h=this.estimateWordDuration(a,i/n.length);s.push({word:a,startTime:o,endTime:o+h,duration:h}),o+=h}const l=this.generateVisemeTimings(t,e,i);return{words:s,visemes:l,duration:i,features:t}}estimateWordDuration(t,e){const i=Math.max(.5,Math.min(2,t.length/5)),n=this.getWordComplexity(t);return e*i*n}getWordComplexity(t){const e=(t.match(/[bcdfghjklmnpqrstvwxyz]{2,}/g)||[]).length,i=(t.match(/[aeiou]{2,}/g)||[]).length;return 1+e*.2+i*.1}generateVisemeTimings(t,e,i){const n=[],s=t.phonemeBoundaries;t.onsets;const o=this.textToVisemes(e);let l=0,u=0;for(let a=0;a<s.length&&l<o.length;a++){const h=s[a],r=o[l],d=t.energy[Math.floor(h/.023)]||0,c=this.calculateVisemeDuration(r,d);n.push({viseme:r,startTime:u,endTime:u+c,duration:c,intensity:Math.min(1,d*2)}),u+=c,l++}for(;l<o.length;){const a=o[l],h=this.calculateVisemeDuration(a,.5);n.push({viseme:a,startTime:u,endTime:u+h,duration:h,intensity:.6}),u+=h,l++}return n}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"},i=[],n=t.toLowerCase().replace(/[^a-z\s]/g,"").split(/\s+/);for(const s of n){let o=0;for(;o<s.length;){let l=!1;for(let u=3;u>=2;u--){const a=s.substr(o,u);if(e[a]){i.push(e[a]),o+=u,l=!0;break}}if(!l){const u=s[o];e[u]&&i.push(e[u]),o++}}}return i}calculateVisemeDuration(t,e){const n={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 n*s}}class Ve{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(i=>{const n=i.indexOf("["),s=i.indexOf("]"),o=i.indexOf("="),l=i.substring(0,n),u=i.substring(n+1,s),a=i.substring(s+1,o),h=i.substring(o+1),r={regex:"",move:0,visemes:[]};let d="";d+=[...l].map(g=>t[g]||g).join("");const c=[...u];return c[0]=c[0].toLowerCase(),d+=c.join(""),r.move=c.length,d+=[...a].map(g=>t[g]||g).join(""),r.regex=new RegExp(d),h.length&&h.split(" ").forEach(g=>{r.visemes.push(g)}),r})}),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 i=0;i<t.length;i++)e+=this.digits[t[i]]+" ";return e=e.substring(0,e.length-1),e}convert_sets_of_two(t){let e=String(t).substring(0,2),i=String(t).substring(2,4),n=this.convert_tens(e);return n+=" "+this.convert_tens(i),n}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 i=parseFloat(t);if(t=="0")return"zero";if(t<0)return" minus "+this.convertNumberToWords(Math.abs(t).toString(),e).trim();if(i&&!Number.isInteger(i)){const n=i.toString().split(".");return this.convertNumberToWords(n[0],e).trim()+" point "+this.convert_digit_by_digit(n[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),i=!isNaN(e)&&t.length===2,n=!isNaN(e)&&t.length>2&&e>0&&e<=3e3,s=n&&e%1e3===0?Math.floor(e/1e3):null,o=n&&!s?Math.floor(e/100):null,l=i||n?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()),l?u.push(this.decades[l]||this.convertNumberToWords(l).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),i=Math.floor(t%100/10)*10,n=t%10;let s=[];return e&&(s.push(this.convertNumberToWords(e).trim()),i||n?s.push("hundred"):s.push("hundredth")),i&&(n?s.push(this.convertNumberToWords(i).trim()):s.push(this.ordinals[i])),n&&s.push(this.ordinals[n]),s.join(" ")}preProcessText(t){let e=t.replace('/[#_*":;]/g',"");return e=e.replace(this.symbolsReg,i=>" "+this.symbols[i]+" "),/\d/.test(e)&&(e=e.replace(/\b(\d{2,4})[''']?\s?[sS](?=\s|[.,!?;:]|$)/g,(i,n)=>{const s=this.convertDecade(n);return s===n?i:s}),e=e.replace(/\b(\d+)\s*(st|nd|rd|th)(?=\s|[.,!?;:]|$)/gi,(i,n)=>this.convertOrdinal(Number(n))),e=e.replace(/\b(\w*?)(\d+)([A-Za-z]+)\b/g,(i,n,s,o)=>{const l=this.convertNumberToWords(s);return`${n}${l} ${o}`}).replace(/\b([A-Za-z]+)(\d+)(\w*?)\b/g,(i,n,s,o)=>{const l=this.convertNumberToWords(s);return`${n} ${l}${o}`}),e=e.replace(/-?(?:\d{1,3}(?:,\d{3})+|\d+)(\.\d+)?/g,(i,n)=>{let s=i,o=!1;return/,/.test(s)&&(s=s.replace(/,/g,""),o=!0),n&&(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},i=0;const n=[...e.words];for(;e.i<n.length;){const s=n[e.i],o=this.rules[s];if(o)for(let l=0;l<o.length;l++){const u=o[l];if((e.words.substring(0,e.i)+s.toLowerCase()+e.words.substring(e.i+1)).match(u.regex)){u.visemes.forEach(r=>{if(e.visemes.length&&e.visemes[e.visemes.length-1]===r){const d=.7*(this.visemeDurations[r]||1);e.durations[e.durations.length-1]+=d,i+=d}else{const d=this.visemeDurations[r]||1;e.visemes.push(r),e.times.push(i),e.durations.push(d),i+=d}}),e.i+=u.move;break}}else e.i++,i+=this.specialDurations[s]||0}return e}}const Ge=Object.freeze(Object.defineProperty({__proto__:null,LipsyncEn:Ve},Symbol.toStringTag,{value:"Module"}));class Ze{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(i=>{const n=i.indexOf("["),s=i.indexOf("]"),o=i.indexOf("="),l=i.substring(0,n),u=i.substring(n+1,s),a=i.substring(s+1,o),h=i.substring(o+1),r={regex:"",move:0,visemes:[]};let d="";d+=[...l].map(g=>t[g]||g).join("");const c=[...u];return c[0]=c[0].toLowerCase(),d+=c.join(""),r.move=c.length,d+=[...a].map(g=>t[g]||g).join(""),r.regex=new RegExp(d),h.length&&h.split(" ").forEach(g=>{r.visemes.push(g)}),r})}),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 i=0;i<t.length;i++)e+=this.digits[t[i]]+" ";return e=e.substring(0,e.length-1),e}convert_millions(t){if(t>=1e6){const e=Math.floor(t/1e6),i=t%1e6;let n=this.convert_thousands(e);return n+=e===1?" million ":" millionen ",i>0&&(n+=this.convert_thousands(i)),n}else return this.convert_thousands(t)}convert_thousands(t){if(t>=1e3){const e=Math.floor(t/1e3),i=t%1e3;let n="";return e===1?n="eintausend":n=this.convert_hundreds(e)+"tausend",i>0&&(n+=this.convert_hundreds(i)),n}else return this.convert_hundreds(t)}convert_hundreds(t){if(t>99){const e=Math.floor(t/100),i=t%100;let n="";return e===1?n="einhundert":n=this.ones[e]+"hundert",i>0&&(n+=this.convert_tens(i)),n}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),i=t%10;return i===0?this.tens[e]:this.ones[i]+"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},i=0;const n=[...e.words];for(;e.i<n.length;){const s=n[e.i],o=this.rules[s];if(o){let l=!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 c=.7*(this.visemeDurations[d]||1);e.durations[e.durations.length-1]+=c,i+=c}else{const c=this.visemeDurations[d]||1;e.visemes.push(d),e.times.push(i),e.durations.push(c),i+=c}}),e.i+=a.move,l=!0;break}}l||(e.i++,i+=this.specialDurations[s]||0)}else e.i++,i+=this.specialDurations[s]||0}return e}}const Xe=Object.freeze(Object.defineProperty({__proto__:null,LipsyncDe:Ze},Symbol.toStringTag,{value:"Module"}));class Ye{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(i=>{const n=i.indexOf("["),s=i.indexOf("]"),o=i.indexOf("="),l=i.substring(0,n),u=i.substring(n+1,s),a=i.substring(s+1,o),h=i.substring(o+1),r={regex:"",move:0,visemes:[]};let d="";d+=[...l].map(g=>t[g]||g).join("");const c=[...u];return c[0]=c[0].toLowerCase(),d+=c.join(""),r.move=c.length,d+=[...a].map(g=>t[g]||g).join(""),r.regex=new RegExp(d,"i"),h.length&&h.split(" ").forEach(g=>{g&&r.visemes.push(g)}),r})}),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 i=0;i<t.length;i++)e+=this.digits[t[i]]+" ";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),i=t%10;return e===8&&i===0?"quatre-vingts":e===8?"quatre-vingt-"+this.ones[i]:(e===2||e===3||e===4||e===5||e===6)&&i===1?this.tens[e]+" et un":i===0?this.tens[e]:this.tens[e]+"-"+this.ones[i]}}convert_hundreds(t){if(t>=100){const e=Math.floor(t/100),i=t%100;let n="";return e===1?n="cent":(n=this.ones[e]+" cent",i===0&&(n+="s")),i>0&&(n+=" "+this.convert_tens(i)),n}else return this.convert_tens(t)}convert_thousands(t){if(t>=1e3){const e=Math.floor(t/1e3),i=t%1e3;let n="";return e===1?n="mille":n=this.convert_hundreds(e)+" mille",i>0&&(n+=" "+this.convert_hundreds(i)),n}else return this.convert_hundreds(t)}convert_millions(t){if(t>=1e6){const e=Math.floor(t/1e6),i=t%1e6;let n="";return e===1?n="un million":n=this.convert_hundreds(e)+" millions",i>0&&(n+=" "+this.convert_thousands(i)),n}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},i=0;const n=[...e.words];for(;e.i<n.length;){const s=n[e.i],o=this.rules[s];if(o){let l=!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 c=.7*(this.visemeDurations[d]||1);e.durations[e.durations.length-1]+=c,i+=c}else{const c=this.visemeDurations[d]||1;e.visemes.push(d),e.times.push(i),e.durations.push(c),i+=c}}),e.i+=a.move,l=!0;break}}l||(e.i++,i+=this.specialDurations[s]||0)}else e.i++,i+=this.specialDurations[s]||0}return e}}const je=Object.freeze(Object.defineProperty({__proto__:null,LipsyncFr:Ye},Symbol.toStringTag,{value:"Module"}));class Qe{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 i=parseFloat(t);if(i===void 0)return t;let n=(s,o,l,u,a)=>{if(s<o)return s;const h=Math.floor(s/o);return e.push(l+(h===1?u:this.numberToFinnishWords(h.toString())+a)),s-h*o};if(i<0&&(e.push("miinus "),i=Math.abs(i)),i=n(i,1e9," ","miljardi"," miljardia"),i=n(i,1e6," ","miljoona"," miljoonaa"),i=n(i,1e3,"","tuhat","tuhatta"),i=n(i,100," ","sata","sataa"),i>20&&(i=n(i,10,"","","kymmentä")),i>=1){let s=Math.floor(i);e.push(this.numbers[s]),i-=s}if(i>=0&&Math.abs(parseFloat(t))<1&&e.push("nolla"),i>0){let s=t.split(".");if(s.length>1){e.push(" pilkku");let o=[...s[s.length-1]];for(let l=0;l<o.length;l++)e.push(" "+this.numbers[o[l]])}}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:[]},i=0;const n=[...t];for(let s=0;s<n.length;s++){const o=this.visemes[n[s].toLowerCase()];if(o)if(e.visemes.length&&e.visemes[e.visemes.length-1]===o){const l=.7*(this.visemeDurations[o]||1);e.durations[e.durations.length-1]+=l,i+=l}else{const l=this.visemeDurations[o]||1;e.visemes.push(o),e.times.push(i),e.durations.push(l),i+=l}else i+=this.specialDurations[n[s]]||0}return e}}const qe=Object.freeze(Object.defineProperty({__proto__:null,LipsyncFi:Qe},Symbol.toStringTag,{value:"Module"}));class _e{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 i=parseFloat(t);if(i===void 0)return t;let n=(s,o,l,u,a)=>{if(s<o)return s;const h=Math.floor(s/o);return h===1?e.push(this.numbers[1]):e.push(this.numberToLithuanianWords(h.toString())),h%10===1?e.push(l):h%10===0||h%100>10&&h%100<20?e.push(a):e.push(u),s-h*o};i<0&&(e.push("minus"),i=Math.abs(i)),i=n(i,1e9,"milijardas","milijardai","milijardų"),i=n(i,1e6,"milijonas","milijonai","milijonų"),i=n(i,1e3,"tūkstantis","tūkstančiai","tūkstančių"),i=n(i,100,"šimtas","šimtai","šimtų");for(let s=this.tens.length-1;s>=1;s--)if(i>=10*s){e.push(this.tens[s]),i=i-10*s;break}if(i>=1){let s=Math.floor(i);e.push(this.numbers[s]),i-=s}if(i>=0&&Math.abs(parseFloat(t))<1&&e.push(this.numbers[0]),i>0){let s=t.split(".");if(s.length>1){e.push("kablelis");let o=[...s[s.length-1]];for(let l=0;l<o.length;l++)e.push(this.numbers[o[l]])}}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:[]},i=0;const n=[...t];for(let s=0;s<n.length;s++){const o=n[s].toLowerCase(),l=this.visemes[o];if(l)if(e.visemes.length&&e.visemes[e.visemes.length-1]===l){const u=.7*(this.durations[o]||1);e.durations[e.durations.length-1]+=u,i+=u}else{const u=this.durations[o]||1;e.visemes.push(l),e.times.push(i),e.durations.push(u),i+=u}else i+=this.pauses[n[s]]||0}return e}}const Ke=Object.freeze(Object.defineProperty({__proto__:null,LipsyncLt:_e},Symbol.toStringTag,{value:"Module"})),Je=new URL("data:text/javascript;base64,Y2xhc3MgUGxheWJhY2tXb3JrbGV0IGV4dGVuZHMgQXVkaW9Xb3JrbGV0UHJvY2Vzc29yIHsKICBzdGF0aWMgRlNNID0gewogICAgSURMRTogMCwKICAgIFBMQVlJTkc6IDEsCiAgfTsKCiAgY29uc3RydWN0b3Iob3B0aW9ucykgewogICAgc3VwZXIoKTsKICAgIHRoaXMucG9ydC5vbm1lc3NhZ2UgPSB0aGlzLmhhbmRsZU1lc3NhZ2UuYmluZCh0aGlzKTsKCiAgICB0aGlzLl9zYW1wbGVSYXRlID0gb3B0aW9ucz8ucHJvY2Vzc29yT3B0aW9ucz8uc2FtcGxlUmF0ZSB8fCBzYW1wbGVSYXRlOwogICAgdGhpcy5fc2NhbGUgPSAxIC8gMzI3Njg7IC8vIFBDTTE2IC0+IGZsb2F0CgogICAgLy8gU2lsZW5jZSBkZXRlY3Rpb24gdGhyZXNob2xkICgxIHNlY29uZCkgYXMgYSBmYWxsYmFjayBzYWZldHkgbmV0CiAgICBjb25zdCBzaWxlbmNlRHVyYXRpb25TZWNvbmRzID0gMS4wOwogICAgdGhpcy5fc2lsZW5jZVRocmVzaG9sZEJsb2NrcyA9IE1hdGguY2VpbCgodGhpcy5fc2FtcGxlUmF0ZSAqIHNpbGVuY2VEdXJhdGlvblNlY29uZHMpIC8gMTI4KTsKCiAgICAvLyBNZXRyaWNzIGNvbmZpZ3VyYXRpb24gdmlhIG9wdGlvbnMKICAgIGNvbnN0IG1ldHJpY3NDZmcgPSBvcHRpb25zPy5wcm9jZXNzb3JPcHRpb25zPy5tZXRyaWNzIHx8IHt9OwogICAgdGhpcy5fbWV0cmljc0VuYWJsZWQgPSBtZXRyaWNzQ2ZnLmVuYWJsZWQgIT09IGZhbHNlOwogICAgY29uc3QgaW50ZXJ2YWxIeiA9ICh0eXBlb2YgbWV0cmljc0NmZy5pbnRlcnZhbEh6ID09PSAibnVtYmVyIiAmJiBtZXRyaWNzQ2ZnLmludGVydmFsSHogPiAwKQogICAgICA/IG1ldHJpY3NDZmcuaW50ZXJ2YWxIeiA6IDI7CiAgICAvLyBNZXRyaWNzIHN0YXRlIChsb3ctb3ZlcmhlYWQpCiAgICB0aGlzLl9mcmFtZXNQcm9jZXNzZWQgPSAwOwogICAgdGhpcy5fdW5kZXJydW5CbG9ja3MgPSAwOwogICAgdGhpcy5fbWF4UXVldWVTYW1wbGVzID0gMDsKICAgIHRoaXMuX2xhc3RNZXRyaWNzU2VudEF0RnJhbWUgPSAwOwogICAgLy8gQ29udmVydCB0byBmcmFtZXMgYmV0d2VlbiByZXBvcnRzCiAgICB0aGlzLl9tZXRyaWNzSW50ZXJ2YWxGcmFtZXMgPSBNYXRoLm1heCgxMjgsIE1hdGgucm91bmQodGhpcy5fc2FtcGxlUmF0ZSAvIGludGVydmFsSHopKTsKCiAgICB0aGlzLnJlc2V0KCk7CiAgfQoKICAvKioKICAgKiBSZXNldHMgdGhlIHdvcmtsZXQgdG8gaXRzIGluaXRpYWwgSURMRSBzdGF0ZS4KICAgKi8KICByZXNldCgpIHsKICAgIHRoaXMuX2J1ZmZlclF1ZXVlID0gW107CiAgICB0aGlzLl9jdXJyZW50Q2h1bmsgPSBudWxsOwogICAgdGhpcy5fY3VycmVudENodW5rT2Zmc2V0ID0gMDsKICAgIHRoaXMuX3N0YXRlID0gUGxheWJhY2tXb3JrbGV0LkZTTS5JRExFOwoKICAgIHRoaXMuX25vTW9yZURhdGFSZWNlaXZlZCA9IGZhbHNlOwogICAgdGhpcy5fc2lsZW5jZUZyYW1lc0NvdW50ID0gMDsKICAgIHRoaXMuX2hhc1NlbnRFbmRlZCA9IGZhbHNlOwogICAgLy8gUmVzZXQgbWF4IHF1ZXVlIHRyYWNrZXIgb25seSB3aGVuIGdvaW5nIGlkbGUKICAgIHRoaXMuX21heFF1ZXVlU2FtcGxlcyA9IDA7CiAgfQoKICBoYW5kbGVNZXNzYWdlKGV2ZW50KSB7CiAgICBjb25zdCB7IHR5cGUsIGRhdGEgfSA9IGV2ZW50LmRhdGE7CgogICAgLy8gSU5URVJSVVBUOiBUaGUgbWFpbiB0aHJlYWQgd2FudHMgdG8gc3RvcCBpbW1lZGlhdGVseS4KICAgIGlmICh0eXBlID09PSAic3RvcCIpIHsKICAgICAgdGhpcy5yZXNldCgpOwogICAgICAvLyBTZW5kIGZpbmFsIG1ldHJpY3Mgc2hvd2luZyBjbGVhcmVkIHN0YXRlCiAgICAgIGlmICh0aGlzLl9tZXRyaWNzRW5hYmxlZCkgewogICAgICAgIHRyeSB7CiAgICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UoewogICAgICAgICAgICB0eXBlOiAibWV0cmljcyIsCiAgICAgICAgICAgIGRhdGE6IHsKICAgICAgICAgICAgICBzdGF0ZTogUGxheWJhY2tXb3JrbGV0LkZTTS5JRExFLAogICAgICAgICAgICAgIHF1ZXVlZFNhbXBsZXM6IDAsCiAgICAgICAgICAgICAgcXVldWVkTXM6IDAsCiAgICAgICAgICAgICAgbWF4UXVldWVkTXM6IE1hdGgucm91bmQoKHRoaXMuX21heFF1ZXVlU2FtcGxlcyAvIHRoaXMuX3NhbXBsZVJhdGUpICogMTAwMCksCiAgICAgICAgICAgICAgdW5kZXJydW5CbG9ja3M6IHRoaXMuX3VuZGVycnVuQmxvY2tzLAogICAgICAgICAgICAgIGZyYW1lc1Byb2Nlc3NlZDogdGhpcy5fZnJhbWVzUHJvY2Vzc2VkCiAgICAgICAgICAgIH0KICAgICAgICAgIH0pOwogICAgICAgIH0gY2F0Y2ggKF8pIHsgfQogICAgICB9CiAgICAgIHJldHVybjsKICAgIH0KCiAgICAvLyBNYWluIHRocmVhZCBoYXMgc2lnbmFsZWQgdGhhdCBubyBtb3JlIGF1ZGlvIGNodW5rcyB3aWxsIGJlIHNlbnQgZm9yIHRoaXMgdXR0ZXJhbmNlLgogICAgaWYgKHR5cGUgPT09ICJuby1tb3JlLWRhdGEiKSB7CiAgICAgIHRoaXMuX25vTW9yZURhdGFSZWNlaXZlZCA9IHRydWU7CiAgICAgIHJldHVybjsKICAgIH0KCiAgICAvLyBVcGRhdGUgbWV0cmljcyBjb25maWd1cmF0aW9uIGF0IHJ1bnRpbWUKICAgIGlmICh0eXBlID09PSAiY29uZmlnLW1ldHJpY3MiICYmIGRhdGEgJiYgdHlwZW9mIGRhdGEgPT09ICJvYmplY3QiKSB7CiAgICAgIGlmICgiZW5hYmxlZCIgaW4gZGF0YSkgdGhpcy5fbWV0cmljc0VuYWJsZWQgPSAhIWRhdGEuZW5hYmxlZDsKICAgICAgaWYgKHR5cGVvZiBkYXRhLmludGVydmFsSHogPT09ICJudW1iZXIiICYmIGRhdGEuaW50ZXJ2YWxIeiA+IDApIHsKICAgICAgICBjb25zdCBpbnRlcnZhbEh6ID0gZGF0YS5pbnRlcnZhbEh6OwogICAgICAgIHRoaXMuX21ldHJpY3NJbnRlcnZhbEZyYW1lcyA9IE1hdGgubWF4KDEyOCwgTWF0aC5yb3VuZCh0aGlzLl9zYW1wbGVSYXRlIC8gaW50ZXJ2YWxIeikpOwogICAgICB9CiAgICAgIC8vIFJlc2V0IHBhY2luZyBzbyB0aGUgbmV4dCByZXBvcnQgYWxpZ25zIHdpdGggbmV3IGludGVydmFsCiAgICAgIHRoaXMuX2xhc3RNZXRyaWNzU2VudEF0RnJhbWUgPSB0aGlzLl9mcmFtZXNQcm9jZXNzZWQ7CiAgICAgIHJldHVybjsKICAgIH0KCiAgICAvLyBOZXcgYXVkaW8gZGF0YSBoYXMgYXJyaXZlZC4KICAgIGlmICh0eXBlID09PSAiYXVkaW9EYXRhIiAmJiBkYXRhIGluc3RhbmNlb2YgQXJyYXlCdWZmZXIpIHsKICAgICAgdGhpcy5fbm9Nb3JlRGF0YVJlY2VpdmVkID0gZmFsc2U7CiAgICAgIC8vIElmIHdlIHdlcmUgaWRsZSwgdGhpcyBuZXcgZGF0YSBraWNrcyBvZmYgdGhlIHBsYXliYWNrLgogICAgICBpZiAodGhpcy5fc3RhdGUgPT09IFBsYXliYWNrV29ya2xldC5GU00uSURMRSkgewogICAgICAgIHRoaXMuX3N0YXRlID0gUGxheWJhY2tXb3JrbGV0LkZTTS5QTEFZSU5HOwogICAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZSh7IHR5cGU6ICJwbGF5YmFjay1zdGFydGVkIiB9KTsKICAgICAgfQoKICAgICAgLy8gV2Ugb25seSBxdWV1ZSBkYXRhIGlmIHdlIGFyZSBpbiB0aGUgUExBWUlORyBzdGF0ZS4gVGhpcyBwcmV2ZW50cwogICAgICAvLyBkYXRhIGZyb20gYSBwcmV2aW91cywgaW50ZXJydXB0ZWQgc3RyZWFtIGZyb20gbGluZ2VyaW5nLgogICAgICBpZiAodGhpcy5fc3RhdGUgPT09IFBsYXliYWNrV29ya2xldC5GU00uUExBWUlORykgewogICAgICAgIC8vIFN0b3JlIGFzIEludDE2QXJyYXkgdmlldyB0byBhdm9pZCBjb25zdHJ1Y3RpbmcgaXQgaW4gcHJvY2VzcygpCiAgICAgICAgdGhpcy5fYnVmZmVyUXVldWUucHVzaChuZXcgSW50MTZBcnJheShkYXRhKSk7CiAgICAgICAgdGhpcy5fc2lsZW5jZUZyYW1lc0NvdW50ID0gMDsgLy8gUmVzZXQgc2lsZW5jZSBjb3VudGVyIG9uIG5ldyBkYXRhCiAgICAgIH0KICAgIH0KICB9CgogIHByb2Nlc3MoaW5wdXRzLCBvdXRwdXRzLCBwYXJhbWV0ZXJzKSB7CiAgICBjb25zdCBvdXRwdXRDaGFubmVsID0gb3V0cHV0c1swXT8uWzBdOwogICAgaWYgKCFvdXRwdXRDaGFubmVsKSB7CiAgICAgIHJldHVybiB0cnVlOyAvLyBLZWVwIGFsaXZlIGV2ZW4gaWYgb3V0cHV0IGlzIHRlbXBvcmFyaWx5IGRpc2Nvbm5lY3RlZAogICAgfQoKICAgIC8vIElmIHdlIGFyZSBub3QgcGxheWluZywganVzdCBvdXRwdXQgc2lsZW5jZSBhbmQgd2FpdC4KICAgIGlmICh0aGlzLl9zdGF0ZSAhPT0gUGxheWJhY2tXb3JrbGV0LkZTTS5QTEFZSU5HKSB7CiAgICAgIG91dHB1dENoYW5uZWwuZmlsbCgwKTsKICAgICAgcmV0dXJuIHRydWU7IC8vIEFsd2F5cyByZXR1cm4gdHJ1ZSB0byBrZWVwIHRoZSBwcm9jZXNzb3IgYWxpdmUKICAgIH0KCiAgICAvLyBDb3JlIFBMQVlJTkcgTG9naWMKICAgIGNvbnN0IGJsb2NrU2l6ZSA9IG91dHB1dENoYW5uZWwubGVuZ3RoOwogICAgbGV0IHNhbXBsZXNDb3BpZWQgPSAwOwoKICAgIHdoaWxlIChzYW1wbGVzQ29waWVkIDwgYmxvY2tTaXplKSB7CiAgICAgIGlmICghdGhpcy5fY3VycmVudENodW5rIHx8IHRoaXMuX2N1cnJlbnRDaHVua09mZnNldCA+PSB0aGlzLl9jdXJyZW50Q2h1bmsubGVuZ3RoKSB7CiAgICAgICAgaWYgKHRoaXMuX2J1ZmZlclF1ZXVlLmxlbmd0aCA+IDApIHsKICAgICAgICAgIHRoaXMuX2N1cnJlbnRDaHVuayA9IHRoaXMuX2J1ZmZlclF1ZXVlLnNoaWZ0KCk7CiAgICAgICAgICB0aGlzLl9jdXJyZW50Q2h1bmtPZmZzZXQgPSAwOwogICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAvLyBCdWZmZXIgaXMgZW1wdHkuIENoZWNrIGZvciBlbmQgY29uZGl0aW9ucy4KICAgICAgICAgIGNvbnN0IGlzVGltZWRPdXQgPSB0aGlzLl9zaWxlbmNlRnJhbWVzQ291bnQgPiB0aGlzLl9zaWxlbmNlVGhyZXNob2xkQmxvY2tzOwoKICAgICAgICAgIGlmICh0aGlzLl9ub01vcmVEYXRhUmVjZWl2ZWQgfHwgaXNUaW1lZE91dCkgewogICAgICAgICAgICAvLyBFTkQgT0YgUExBWUJBQ0s6IEVpdGhlciBleHBsaWNpdGx5IHNpZ25hbGVkIG9yIHRpbWVkIG91dC4KICAgICAgICAgICAgaWYgKCF0aGlzLl9oYXNTZW50RW5kZWQpIHsKICAgICAgICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UoeyB0eXBlOiAicGxheWJhY2stZW5kZWQiIH0pOwogICAgICAgICAgICAgIHRoaXMuX2hhc1NlbnRFbmRlZCA9IHRydWU7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgLy8gU2VuZCBmaW5hbCBtZXRyaWNzIHNob3dpbmcgY2xlYXJlZCBzdGF0ZQogICAgICAgICAgICBpZiAodGhpcy5fbWV0cmljc0VuYWJsZWQpIHsKICAgICAgICAgICAgICB0cnkgewogICAgICAgICAgICAgICAgdGhpcy5wb3J0LnBvc3RNZXNzYWdlKHsKICAgICAgICAgICAgICAgICAgdHlwZTogIm1ldHJpY3MiLAogICAgICAgICAgICAgICAgICBkYXRhOiB7CiAgICAgICAgICAgICAgICAgICAgc3RhdGU6IFBsYXliYWNrV29ya2xldC5GU00uSURMRSwKICAgICAgICAgICAgICAgICAgICBxdWV1ZWRTYW1wbGVzOiAwLAogICAgICAgICAgICAgICAgICAgIHF1ZXVlZE1zOiAwLAogICAgICAgICAgICAgICAgICAgIG1heFF1ZXVlZE1zOiBNYXRoLnJvdW5kKCh0aGlzLl9tYXhRdWV1ZVNhbXBsZXMgLyB0aGlzLl9zYW1wbGVSYXRlKSAqIDEwMDApLAogICAgICAgICAgICAgICAgICAgIHVuZGVycnVuQmxvY2tzOiB0aGlzLl91bmRlcnJ1bkJsb2NrcywKICAgICAgICAgICAgICAgICAgICBmcmFtZXNQcm9jZXNzZWQ6IHRoaXMuX2ZyYW1lc1Byb2Nlc3NlZAogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICB9KTsKICAgICAgICAgICAgICB9IGNhdGNoIChfKSB7IH0KICAgICAgICAgICAgfQogICAgICAgICAgICB0aGlzLnJlc2V0KCk7IC8vIFJlc2V0IHRvIElETEUgc3RhdGUgZm9yIHJldXNlCiAgICAgICAgICAgIGJyZWFrOyAvLyBFeGl0IHdoaWxlIGxvb3AKICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgIC8vIEJVRkZFUiBVTkRFUlJVTiAoTEFHKTogUGxheSBzaWxlbmNlIGFuZCB3YWl0IGZvciBtb3JlIGRhdGEuCiAgICAgICAgICAgIHRoaXMuX3NpbGVuY2VGcmFtZXNDb3VudCsrOwogICAgICAgICAgICBpZiAodGhpcy5fbWV0cmljc0VuYWJsZWQpIHRoaXMuX3VuZGVycnVuQmxvY2tzKys7CiAgICAgICAgICAgIGJyZWFrOyAvLyBFeGl0IHdoaWxlIGxvb3AKICAgICAgICAgIH0KICAgICAgICB9CiAgICAgIH0KCiAgICAgIC8vIElmIHdlIGhhdmUgYSBjaHVuayAoY291bGQgYmUgYSBuZXcgb25lIGZyb20gdGhlIGxvZ2ljIGFib3ZlKSwgcHJvY2VzcyBpdC4KICAgICAgaWYgKHRoaXMuX2N1cnJlbnRDaHVuaykgewogICAgICAgIGNvbnN0IHNhbXBsZXNUb0NvcHkgPSBNYXRoLm1pbigKICAgICAgICAgIGJsb2NrU2l6ZSAtIHNhbXBsZXNDb3BpZWQsCiAgICAgICAgICB0aGlzLl9jdXJyZW50Q2h1bmsubGVuZ3RoIC0gdGhpcy5fY3VycmVudENodW5rT2Zmc2V0CiAgICAgICAgKTsKICAgICAgICAvLyBEaXJlY3RseSB3cml0ZSB0byBvdXRwdXRDaGFubmVsIHRvIGF2b2lkIGV4dHJhIGNvcHkKICAgICAgICBjb25zdCBzcmMgPSB0aGlzLl9jdXJyZW50Q2h1bms7CiAgICAgICAgY29uc3QgYmFzZVNyYyA9IHRoaXMuX2N1cnJlbnRDaHVua09mZnNldDsKICAgICAgICBjb25zdCBiYXNlRHN0ID0gc2FtcGxlc0NvcGllZDsKICAgICAgICBjb25zdCBzY2FsZSA9IHRoaXMuX3NjYWxlOwogICAgICAgIGZvciAobGV0IGkgPSAwOyBpIDwgc2FtcGxlc1RvQ29weTsgaSsrKSB7CiAgICAgICAgICBvdXRwdXRDaGFubmVsW2Jhc2VEc3QgKyBpXSA9IHNyY1tiYXNlU3JjICsgaV0gKiBzY2FsZTsKICAgICAgICB9CgogICAgICAgIHRoaXMuX2N1cnJlbnRDaHVua09mZnNldCArPSBzYW1wbGVzVG9Db3B5OwogICAgICAgIHNhbXBsZXNDb3BpZWQgKz0gc2FtcGxlc1RvQ29weTsKICAgICAgfQogICAgfQoKICAgIC8vIFplcm8tZmlsbCB0aGUgcmVtYWluZGVyLCBpZiBhbnksIG9uY2UgcGVyIGJsb2NrCiAgICBpZiAoc2FtcGxlc0NvcGllZCA8IGJsb2NrU2l6ZSkgewogICAgICBvdXRwdXRDaGFubmVsLmZpbGwoMCwgc2FtcGxlc0NvcGllZCk7CiAgICB9CgogICAgLy8gVXBkYXRlIG1ldHJpY3MgKG9wdGlvbmFsKQogICAgaWYgKHRoaXMuX21ldHJpY3NFbmFibGVkKSB7CiAgICAgIHRoaXMuX2ZyYW1lc1Byb2Nlc3NlZCArPSBibG9ja1NpemU7CgogICAgICAvLyBUcmFjayBxdWV1ZSBkZXB0aCBpbiBzYW1wbGVzIChhcHByb3hpbWF0ZSkKICAgICAgbGV0IHF1ZXVlZFNhbXBsZXMgPSAwOwogICAgICBpZiAodGhpcy5fY3VycmVudENodW5rKSBxdWV1ZWRTYW1wbGVzICs9IE1hdGgubWF4KDAsIHRoaXMuX2N1cnJlbnRDaHVuay5sZW5ndGggLSB0aGlzLl9jdXJyZW50Q2h1bmtPZmZzZXQpOwogICAgICBmb3IgKGxldCBpID0gMDsgaSA8IHRoaXMuX2J1ZmZlclF1ZXVlLmxlbmd0aDsgaSsrKSBxdWV1ZWRTYW1wbGVzICs9IHRoaXMuX2J1ZmZlclF1ZXVlW2ldLmxlbmd0aDsKICAgICAgaWYgKHF1ZXVlZFNhbXBsZXMgPiB0aGlzLl9tYXhRdWV1ZVNhbXBsZXMpIHRoaXMuX21heFF1ZXVlU2FtcGxlcyA9IHF1ZXVlZFNhbXBsZXM7CgogICAgICAvLyBQZXJpb2RpY2FsbHkgc2VuZCBtZXRyaWNzIHRvIG1haW4gdGhyZWFkCiAgICAgIGlmICh0aGlzLl9mcmFtZXNQcm9jZXNzZWQgLSB0aGlzLl9sYXN0TWV0cmljc1NlbnRBdEZyYW1lID49IHRoaXMuX21ldHJpY3NJbnRlcnZhbEZyYW1lcykgewogICAgICAgIHRoaXMuX2xhc3RNZXRyaWNzU2VudEF0RnJhbWUgPSB0aGlzLl9mcmFtZXNQcm9jZXNzZWQ7CiAgICAgICAgdHJ5IHsKICAgICAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZSh7CiAgICAgICAgICAgIHR5cGU6ICJtZXRyaWNzIiwKICAgICAgICAgICAgZGF0YTogewogICAgICAgICAgICAgIHN0YXRlOiB0aGlzLl9zdGF0ZSwKICAgICAgICAgICAgICBxdWV1ZWRTYW1wbGVzLAogICAgICAgICAgICAgIHF1ZXVlZE1zOiBNYXRoLnJvdW5kKChxdWV1ZWRTYW1wbGVzIC8gdGhpcy5fc2FtcGxlUmF0ZSkgKiAxMDAwKSwKICAgICAgICAgICAgICBtYXhRdWV1ZWRNczogTWF0aC5yb3VuZCgodGhpcy5fbWF4UXVldWVTYW1wbGVzIC8gdGhpcy5fc2FtcGxlUmF0ZSkgKiAxMDAwKSwKICAgICAgICAgICAgICB1bmRlcnJ1bkJsb2NrczogdGhpcy5fdW5kZXJydW5CbG9ja3MsCiAgICAgICAgICAgICAgZnJhbWVzUHJvY2Vzc2VkOiB0aGlzLl9mcmFtZXNQcm9jZXNzZWQKICAgICAgICAgICAgfQogICAgICAgICAgfSk7CiAgICAgICAgfSBjYXRjaCAoXykgeyB9CiAgICAgICAgLy8gRG9uJ3QgcmVzZXQgbWF4IHRyYWNrZXIgLSBrZWVwIHNlc3Npb24gcGVhayB1bnRpbCBpZGxlCiAgICAgIH0KICAgIH0KCiAgICAvLyBBTFdBWVMgcmV0dXJuIHRydWUgdG8ga2VlcCB0aGUgcHJvY2Vzc29yIGFsaXZlIGZvciByZXVzZS4KICAgIHJldHVybiB0cnVlOwogIH0KfQoKcmVnaXN0ZXJQcm9jZXNzb3IoInBsYXliYWNrLXdvcmtsZXQiLCBQbGF5YmFja1dvcmtsZXQpOwo=",typeof document>"u"?require("url").pathToFileURL(__filename).href:ge&&ge.tagName.toUpperCase()==="SCRIPT"&&ge.src||new URL("index.cjs",document.baseURI).href),ve={en:Ge,de:Xe,fr:je,fi:qe,lt:Ke},U=new f.Quaternion,F=new f.Euler,te=new f.Vector3,ie=new f.Vector3,Ie=new f.Box3;new f.Matrix4;new f.Matrix4;new f.Vector3;new f.Vector3(0,0,1);const $e=new f.Vector3(1,0,0);new f.Vector3(0,1,0);new f.Vector3(0,0,1);class Ae{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:0,mixerGainSpeech:null,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 Pe,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(l=>{["Leg","UpLeg","Arm","ForeArm","Hand"].forEach(u=>{this.poseDelta.props[l+u+".quaternion"]={x:0,y:0,z:0}}),["HandThumb","HandIndex","HandMiddle","HandRing","HandPinky"].forEach(u=>{this.poseDelta.props[l+u+"1.quaternion"]={x:0,y:0,z:0},this.poseDelta.props[l+u+"2.quaternion"]={x:0,y:0,z:0},this.poseDelta.props[l+u+"3.quaternion"]={x:0,y:0,z:0}})});const i=new Set;Object.values(this.poseTemplates).forEach(l=>{Object.keys(this.propsToThreeObjects(l.props)).forEach(u=>i.add(u))}),Object.keys(this.poseDelta.props).forEach(l=>{i.add(l)}),this.posePropNames=[...i],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"]}},{p:.3,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["wide"]}}},{delay:[5e3,3e4],vs:{pose:["straight"]}}]},{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"]}},{p:.2,delay:[5e3,3e4],vs:{pose:["hip"]},M:{delay:[5e3,3e4],vs:{pose:["side"]}}},{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"]}},{p:.4,delay:[5e3,3e4],vs:{pose:["straight"]}},{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,l=>{l.alt[0].delay[0]=l.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:l=>Math.max(l,(this.mtAvatar.eyesLookDown.value+this.mtAvatar.browDownLeft.value)/2),eyeBlinkRight:l=>Math.max(l,(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(l=>{this.lipsyncGetProcessor(l)}),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 n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";this.b64Lookup=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let l=0;l<n.length;l++)this.b64Lookup[n.charCodeAt(l)]=l;if(this.stateName="idle",this.speechQueue=[],this.isSpeaking=!1,this.isListening=!1,this.opt.ttsEndpoint){let l=new Audio;if(l.canPlayType("audio/ogg"))this.ttsAudioEncoding="OGG-OPUS";else if(l.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 l=new f.PMREMGenerator(this.renderer);l.compileEquirectangularShader(),this.scene.environment=l.fromScene(new Fe.RoomEnvironment).texture,this.resizeobserver=new ResizeObserver(this.onResize.bind(this)),this.resizeobserver.observe(this.nodeAvatar),this.controls=new Te.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"},o=[];Object.entries(s).forEach((l,u)=>{const a=new f.Bone;a.name=l[0],l[1]?this.ikMesh.getObjectByName(l[1]).add(a):this.ikMesh.add(a),o.push(a)}),this.ikMesh.bind(new f.Skeleton(o)),this.dynamicbones=new Ue,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 We(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 i=JSON.parse(JSON.stringify(t));return e&&typeof e=="function"&&e(i),i}b64ToArrayBuffer(t){let e=3*t.length/4;t[t.length-1]==="="&&(e--,t[t.length-2]==="="&&e--);const i=new ArrayBuffer(e),n=new Uint8Array(i);let s,o=0,l,u,a,h;for(s=0;s<t.length;s+=4)l=this.b64Lookup[t.charCodeAt(s)],u=this.b64Lookup[t.charCodeAt(s+1)],a=this.b64Lookup[t.charCodeAt(s+2)],h=this.b64Lookup[t.charCodeAt(s+3)],n[o++]=l<<2|u>>4,n[o++]=(u&15)<<4|a>>2,n[o++]=(a&3)<<6|h&63;return i}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 i=new ArrayBuffer(e),n=new Uint8Array(i),s=0;for(let o=0;o<t.length;o++)n.set(new Uint8Array(t[o]),s),s+=t[o].byteLength;return i}pcmToAudioBuffer(t){const e=new Int16Array(t),i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]>=32768?-(65536-e[s])/32768:e[s]/32767;const n=this.audioCtx.createBuffer(1,i.length,this.opt.pcmSampleRate);return n.copyToChannel(i,0,0),n}propsToThreeObjects(t){const e={};for(let[i,n]of Object.entries(t)){const s=i.split(".");let o=Array.isArray(n.x)?this.gaussianRandom(...n.x):n.x,l=Array.isArray(n.y)?this.gaussianRandom(...n.y):n.y,u=Array.isArray(n.z)?this.gaussianRandom(...n.z):n.z;s[1]==="position"||s[1]==="scale"?e[i]=new f.Vector3(o,l,u):s[1]==="rotation"?(i=s[0]+".quaternion",e[i]=new f.Quaternion().setFromEuler(new f.Euler(o,l,u,"XYZ")).normalize()):s[1]==="quaternion"&&(e[i]=new f.Quaternion(o,l,u,n.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,i,n=!1){t.forEach(s=>{if(!n&&s.morphTargetDictionary.hasOwnProperty(e))return;const o=s.geometry;let l=null,u=null;for(const[a,h]of Object.entries(i))if(s.morphTargetDictionary.hasOwnProperty(a)){const r=s.morphTargetDictionary[a],d=o.morphAttributes.position[r],c=o.morphAttributes.normal?.[r];l||(l=new f.Float32BufferAttribute(d.count*3,3),c&&(u=new f.Float32BufferAttribute(d.count*3,3)));for(let g=0;g<d.count;g++){const y=l.getX(g)+d.getX(g)*h,x=l.getY(g)+d.getY(g)*h,L=l.getZ(g)+d.getZ(g)*h;l.setXYZ(g,y,x,L)}if(c)for(let g=0;g<d.count;g++){const y=u.getX(g)+c.getX(g)*h,x=u.getY(g)+c.getY(g)*h,L=u.getZ(g)+c.getZ(g)*h;u.setXYZ(g,y,x,L)}}if(l){o.morphAttributes.position.push(l),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 i=new Me.GLTFLoader;if(this.dracoEnabled){const a=new Ee.DRACOLoader;a.setDecoderPath(this.dracoDecoderPath),i.setDRACOLoader(a)}let n=await i.loadAsync(t.url,e);const s=[this.opt.modelRoot];if(this.posePropNames.forEach(a=>s.push(a.split(".")[0])),s.forEach(a=>{if(!n.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=n.scene.getObjectByName(this.opt.modelRoot),this.armature.scale.setScalar(1),this.animations=n.animations,this.userData=n.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(h=>o.add(h))}),this.mtExtras.forEach(a=>{o.has(a.key)||(this.addMixedMorphTarget(this.morphs,a.key,a.mix),o.add(a.key))});const l={};if(o.forEach(a=>{l[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:[]},l[a].value=l[a].baseline,l[a].applied=l[a].baseline;const h=this.mtAvatar[a];h&&["fixed","system","systemd","realtime","base","v","value","applied"].forEach(r=>{l[a][r]=h[r]}),this.morphs.forEach(r=>{const d=r.morphTargetDictionary[a];d!==void 0&&(l[a].ms.push(r.morphTargetInfluences),l[a].is.push(d),r.morphTargetInfluences[d]=l[a].applied)})}),this.mtAvatar=l,this.poseAvatar={props:{}},this.posePropNames.forEach(a=>{const h=a.split("."),r=this.armature.getObjectByName(h[0]);this.poseAvatar.props[a]=r[h[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(n.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 f.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.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 i=e.hasOwnProperty("cameraX")?e.cameraX:this.opt.cameraX,n=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,l=e.hasOwnProperty("cameraRotateY")?e.cameraRotateY:this.opt.cameraRotateY,u=this.camera.fov*(Math.PI/180);let a=-i*Math.tan(u/2),h=(1-n)*Math.tan(u/2),r=s;switch(this.viewName){case"head":r+=2,h=h*r+4*this.avatarHeight/5;break;case"upper":r+=4.5,h=h*r+2*this.avatarHeight/3;break;case"mid":r+=8,h=h*r+this.avatarHeight/3;break;default:r+=12,h=h*r}a=a*r,this.controlsEnd=new f.Vector3(a,h,0),this.cameraEnd=new f.Vector3(a,h,r).applyEuler(new f.Euler(o,l,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,i]of Object.entries(this.poseTarget.props)){const n=this.poseAvatar.props[e];if(n){let s=(t-i.t)/i.d;s>1||!this.poseBase.props.hasOwnProperty(e)?n.copy(i):n.isQuaternion?n.copy(this.poseBase.props[e].slerp(i,this.easing(s))):n.isVector3&&n.copy(this.poseBase.props[e].lerp(i,this.easing(s)))}}}updatePoseDelta(){for(const[t,e]of Object.entries(this.poseDelta.props)){if(e.x===0&&e.y===0&&e.z===0)continue;F.set(e.x,e.y,e.z);const i=this.poseAvatar.props[t];i.isQuaternion?(U.setFromEuler(F),i.multiply(U)):i.isVector3&&i.add(F)}}updateMorphTargets(t){for(let[e,i]of Object.entries(this.mtAvatar)){if(!i.needsUpdate)continue;let n=null,s=null;if(i.fixed!==null){if(n=i.fixed,i.system=null,i.systemd=null,i.newvalue=null,i.ref&&i.ref.hasOwnProperty(e)&&delete i.ref[e],i.ref=null,i.base=null,i.value===n){i.needsUpdate=!1;continue}}else i.realtime!==null?(i.ref=null,i.base=null,s=i.realtime):i.system!==null?(n=i.system,i.newvalue=null,i.ref&&i.ref.hasOwnProperty(e)&&delete i.ref[e],i.ref=null,i.base=null,i.systemd!==null?i.systemd===0?(n=null,i.system=null,i.systemd=null):(i.systemd-=t,i.systemd<0&&(i.systemd=0),i.value===n&&(n=null)):i.value===n&&(n=null,i.system=null)):i.newvalue!==null?(i.ref=null,i.base=null,s=i.newvalue,i.newvalue=null):i.base!==null?(n=i.base,i.ref=null,i.value===n&&(n=null,i.base=null,i.needsUpdate=!1)):(i.ref=null,i.baseline!==null&&i.value!==i.baseline?(n=i.baseline,i.base=i.baseline):i.needsUpdate=!1);if(n!==null){let o=n-i.value;o>=0?o<.005?(s=n,i.v=0):(i.v<i.maxv&&(i.v+=i.acc*t),i.v>=0?s=i.value+o*(1-Math.exp(-i.v*t)):s=i.value+i.v*t*(1-Math.exp(i.v*t))):o>-.005?(s=n,i.v=0):(i.v>-i.maxv&&(i.v-=i.acc*t),i.v>=0?s=i.value+i.v*t*(1-Math.exp(-i.v*t)):s=i.value+o*(1-Math.exp(i.v*t)))}if(i.limit!==null){if(s!==null&&s!==i.value&&(i.value=s,i.onchange!==null&&i.onchange(s)),s=i.limit(i.value),s===i.applied)continue}else{if(s===null||s===i.value)continue;i.value=s,i.onchange!==null&&i.onchange(s)}switch(i.applied=s,i.applied<i.min&&(i.applied=i.min),i.applied>i.max&&(i.applied=i.max),e){case"headRotateX":this.poseDelta.props["Head.quaternion"].x=i.applied+this.mtAvatar.bodyRotateX.applied;break;case"headRotateY":this.poseDelta.props["Head.quaternion"].y=i.applied+this.mtAvatar.bodyRotateY.applied;break;case"headRotateZ":this.poseDelta.props["Head.quaternion"].z=i.applied+this.mtAvatar.bodyRotateZ.applied;break;case"bodyRotateX":this.poseDelta.props["Head.quaternion"].x=i.applied+this.mtAvatar.headRotateX.applied,this.poseDelta.props["Spine1.quaternion"].x=i.applied/2,this.poseDelta.props["Spine.quaternion"].x=i.applied/8,this.poseDelta.props["Hips.quaternion"].x=i.applied/24;break;case"bodyRotateY":this.poseDelta.props["Head.quaternion"].y=i.applied+this.mtAvatar.headRotateY.applied,this.poseDelta.props["Spine1.quaternion"].y=i.applied/2,this.poseDelta.props["Spine.quaternion"].y=i.applied/2,this.poseDelta.props["Hips.quaternion"].y=i.applied/4,this.poseDelta.props["LeftUpLeg.quaternion"].y=i.applied/2,this.poseDelta.props["RightUpLeg.quaternion"].y=i.applied/2,this.poseDelta.props["LeftLeg.quaternion"].y=i.applied/4,this.poseDelta.props["RightLeg.quaternion"].y=i.applied/4;break;case"bodyRotateZ":this.poseDelta.props["Head.quaternion"].z=i.applied+this.mtAvatar.headRotateZ.applied,this.poseDelta.props["Spine1.quaternion"].z=i.applied/12,this.poseDelta.props["Spine.quaternion"].z=i.applied/12,this.poseDelta.props["Hips.quaternion"].z=i.applied/24;break;case"handFistLeft":case"handFistRight":const o=e.substring(8);["HandThumb","HandIndex","HandMiddle","HandRing","HandPinky"].forEach((h,r)=>{r===0?(this.poseDelta.props[o+h+"1.quaternion"].x=0,this.poseDelta.props[o+h+"2.quaternion"].z=(o==="Left"?-1:1)*i.applied,this.poseDelta.props[o+h+"3.quaternion"].z=(o==="Left"?-1:1)*i.applied):(this.poseDelta.props[o+h+"1.quaternion"].x=i.applied,this.poseDelta.props[o+h+"2.quaternion"].x=1.5*i.applied,this.poseDelta.props[o+h+"3.quaternion"].x=1.5*i.applied)});break;case"chestInhale":const l=i.applied/20,u={x:l,y:l/2,z:3*l},a={x:1/(1+l)-1,y:1/(1+l/2)-1,z:1/(1+3*l)-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 h=0,r=i.ms.length;h<r;h++)i.ms[h][i.is[h]]=i.applied}}}getPoseString(t,e=1e3){let i="{";return Object.entries(t).forEach((n,s)=>{const o=n[0].split(".");if(o[1]==="position"||o[1]==="rotation"||o[1]==="quaternion"){const l=o[1]==="quaternion"?o[0]+".rotation":n[0],u=n[1].isQuaternion?new f.Euler().setFromQuaternion(n[1]):n[1];i+=(s?", ":"")+"'"+l+"':{",i+="x:"+Math.round(u.x*e)/e,i+=", y:"+Math.round(u.y*e)/e,i+=", z:"+Math.round(u.z*e)/e,i+="}"}}),i+="}",i}getPoseTemplateProp(t){const e=t.split(".");let i=e[0]+"."+(e[1]==="rotation"?"quaternion":e[1]);if(this.gesture&&this.gesture.hasOwnProperty(i))return this.gesture[i].clone();{let n=e[0]+"."+(e[1]==="quaternion"?"rotation":e[1]);this.poseWeightOnLeft||(n.startsWith("Left")?(n="Right"+n.substring(4),i="Right"+i.substring(4)):n.startsWith("Right")&&(n="Left"+n.substring(5),i="Left"+i.substring(5)));let s;if(this.poseTarget.template.props.hasOwnProperty(i)){const o={};o[i]=this.poseTarget.template.props[i],s=this.propsToThreeObjects(o)[i]}else if(this.poseTarget.template.props.hasOwnProperty(n)){const o={};o[n]=this.poseTarget.template.props[n],s=this.propsToThreeObjects(o)[i]}return s&&!this.poseWeightOnLeft&&s.isQuaternion&&(s.x*=-1,s.w*=-1),s}}mirrorPose(t){const e={};for(let[i,n]of Object.entries(t))n.isQuaternion&&(i.startsWith("Left")?i="Right"+i.substring(4):i.startsWith("Right")&&(i="Left"+i.substring(5)),n.x*=-1,n.w*=-1),e[i]=n.clone(),e[i].t=n.t,e[i].d=n.d;return e}poseFactory(t,e=2e3){const i={template:t,props:this.propsToThreeObjects(t.props)};for(const[n,s]of Object.entries(i.props)){if(this.opt.modelMovementFactor<1&&t.standing&&(n==="Hips.quaternion"||n==="Spine.quaternion"||n==="Spine1.quaternion"||n==="Spine2.quaternion"||n==="Neck.quaternion"||n==="LeftUpLeg.quaternion"||n==="LeftLeg.quaternion"||n==="RightUpLeg.quaternion"||n==="RightLeg.quaternion")){const o=this.poseStraight[n],l=s.angleTo(o);s.rotateTowards(o,(1-this.opt.modelMovementFactor)*l)}s.t=this.animClock,s.d=e}return i}setPoseFromTemplate(t,e=2e3){const i=t&&this.poseTarget&&this.poseTarget.template&&(this.poseTarget.template.standing&&t.lying||this.poseTarget.template.lying&&t.standing),n=t&&t===this.poseCurrentTemplate,s=this.poseWeightOnLeft;let o=i?1e3:e;if(i?(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,(!n&&!s||n&&s)&&(this.poseTarget.props=this.mirrorPose(this.poseTarget.props),this.poseWeightOnLeft=!this.poseWeightOnLeft),this.gesture)for(let[l,u]of Object.entries(this.gesture))this.poseTarget.props.hasOwnProperty(l)&&(this.poseTarget.props[l].copy(u),this.poseTarget.props[l].t=u.t,this.poseTarget.props[l].d=u.d);Object.keys(this.poseDelta.props).forEach(l=>{this.poseTarget.props.hasOwnProperty(l)||(this.poseTarget.props[l]=this.poseBase.props[l].clone(),this.poseTarget.props[l].t=this.animClock,this.poseTarget.props[l].d=o)})}getValue(t){return this.mtAvatar[t]?.value}setValue(t,e,i=null){this.mtAvatar.hasOwnProperty(t)&&Object.assign(this.mtAvatar[t],{system:e,systemd:i,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 i=this.mtBaselineExceptions.hasOwnProperty(e)?this.mtBaselineExceptions[e]:this.mtBaselineDefault;this.mood.baseline.hasOwnProperty(e)?i=this.mood.baseline[e]:this.avatar.baseline?.hasOwnProperty(e)&&(i=this.avatar.baseline[e]),this.setBaselineValue(e,i)}this.mood.anims.forEach(e=>{let i=this.animQueue.findIndex(n=>n.template.name===e.name);i!==-1&&this.animQueue.splice(i,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(n=>!n.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(n){console.warn("FBX animation failed, falling back to code animation:",n)}const i=this.createBodyMovementAnimation(this.bodyMovement);if(console.log("Created movement animation:",i),i)try{const n=this.animFactory(i,!0);n&&n.ts&&n.ts.length>0?(this.animQueue.push(n),console.log("Applied code-based body movement animation:",this.bodyMovement),console.log("Animation queue length:",this.animQueue.length),console.log("Animation object:",n)):(console.error("Invalid animation object created for:",this.bodyMovement),console.error("Animation object:",n))}catch(n){console.error("Error creating body movement animation:",n)}}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));const t=2;this.lockedPosition={x:0,y:t,z:0},this.armature.position.set(this.lockedPosition.x,this.lockedPosition.y,this.lockedPosition.z),console.log("BEFORE: Avatar position was:",this.armature.position.x,this.armature.position.y,this.armature.position.z),console.log("AFTER: Avatar position moved up and locked at:",this.lockedPosition),console.log("Current view:",this.viewName)}unlockAvatarPosition(){this.armature&&(this.armature.position.set(0,0,0),console.log("Avatar position reset to center (0,0,0)")),this.lockedPosition=null,console.log("Avatar position unlocked")}maintainLockedPosition(){if(this.lockedPosition&&this.armature){const t=this.armature.position.y,e=this.lockedPosition.y-2,i=this.lockedPosition.y+.1;t<e?this.armature.position.set(this.lockedPosition.x,e,this.lockedPosition.z):t>i&&this.armature.position.set(this.lockedPosition.x,i,this.lockedPosition.z),this.armature.position.x=this.lockedPosition.x,this.armature.position.z=this.lockedPosition.z}}createBodyMovementAnimation(t){const e=this.movementIntensity||.5,i={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 n=["dancing","dancing2","dancing3"],s=n[Math.floor(Math.random()*n.length)];return i[s]||i.dancing}return i[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 i=this.getBaselineValue("eyeLookInLeft");return i===void 0||this.getBaselineValue("eyeLookOutRight")===void 0||this.getBaselineValue("eyeLookInRight")===void 0?void 0:e-i}else if(t==="eyesRotateX"){const e=this.getBaselineValue("eyesLookDown");if(e===void 0)return;const i=this.getBaselineValue("eyesLookUp");return i===void 0?void 0:e-i}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 i=this.getFixedValue("eyeLookInLeft");return i===null||this.getFixedValue("eyeLookOutRight")===null||this.getFixedValue("eyeLookInRight")===null?null:e-i}else if(t==="eyesRotateX"){const e=this.getFixedValue("eyesLookDown");if(e===null)return null;const i=this.getFixedValue("eyesLookUp");return i===null?null:e-i}else return this.mtAvatar[t]?.fixed}setFixedValue(t,e,i=null){t==="eyesRotateY"?(this.setFixedValue("eyeLookOutLeft",e===null?null:e>0?e:0,i),this.setFixedValue("eyeLookInLeft",e===null?null:e>0?0:-e,i),this.setFixedValue("eyeLookOutRight",e===null?null:e>0?0:-e,i),this.setFixedValue("eyeLookInRight",e===null?null:e>0?e:0,i)):t==="eyesRotateX"?(this.setFixedValue("eyesLookDown",e===null?null:e>0?e:0,i),this.setFixedValue("eyesLookUp",e===null?null:e>0?0:-e,i)):this.mtAvatar.hasOwnProperty(t)&&Object.assign(this.mtAvatar[t],{fixed:e,needsUpdate:!0})}animFactory(t,e=!1,i=1,n=1,s=!1){const o={template:t,ts:[0],vs:{}};let l=t;for(;;)if(l.hasOwnProperty(this.stateName))l=l[this.stateName];else if(l.hasOwnProperty(this.moodName))l=l[this.moodName];else if(l.hasOwnProperty(this.poseName))l=l[this.poseName];else if(l.hasOwnProperty(this.viewName))l=l[this.viewName];else if(this.avatar.body&&l.hasOwnProperty(this.avatar.body))l=l[this.avatar.body];else if(l.hasOwnProperty("alt")){let a=l.alt[0];if(l.alt.length>1){const h=Math.random();let r=0;for(let d=0;d<l.alt.length;d++){let c=this.valueFn(l.alt[d].p);if(r+=c===void 0?(1-r)/(l.alt.length-1-d):c,h<r){a=l.alt[d];break}}}l=a}else break;let u=this.valueFn(l.delay)||0;if(Array.isArray(u)&&(u=this.gaussianRandom(...u)),l.hasOwnProperty("dt"))l.dt.forEach((a,h)=>{let r=this.valueFn(a);Array.isArray(r)&&(r=this.gaussianRandom(...r)),o.ts[h+1]=o.ts[h]+r});else{let a=Object.values(l.vs).reduce((h,r)=>r.length>h?r.length:h,0);o.ts=Array(a+1).fill(0)}s?o.ts=o.ts.map(a=>u+a*i):o.ts=o.ts.map(a=>this.animClock+u+a*i);for(let[a,h]of Object.entries(l.vs)){const r=this.getBaselineValue(a),d=h.map(c=>(c=this.valueFn(c),c===null?null:typeof c=="function"?c:typeof c=="string"||c instanceof String?c.slice():Array.isArray(c)?a==="gesture"?c.slice():(r===void 0?0:r)+n*this.gaussianRandom(...c):typeof c=="boolean"?c:c instanceof Object&&c.constructor===Object?Object.assign({},c):(r===void 0?0:r)+n*c));a==="eyesRotateY"?(o.vs.eyeLookOutLeft=[null,...d.map(c=>c>0?c:0)],o.vs.eyeLookInLeft=[null,...d.map(c=>c>0?0:-c)],o.vs.eyeLookOutRight=[null,...d.map(c=>c>0?0:-c)],o.vs.eyeLookInRight=[null,...d.map(c=>c>0?c:0)]):a==="eyesRotateX"?(o.vs.eyesLookDown=[null,...d.map(c=>c>0?c:0)],o.vs.eyesLookUp=[null,...d.map(c=>c>0?0:-c)]):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,i,n,s,o=null){t=this.valueFn(t),e=this.valueFn(e),s<i&&(s=i),s>n&&(s=n);let l=(e-t)/(n-i);return o&&(l*=o((s-i)/(n-i))),l*s+(t-l*i)}gaussianRandom(t,e,i=1,n=5){let s=0;for(let o=0;o<n;o++)s+=Math.random();return t+Math.pow(s/n,i)*(e-t)}sigmoidFactory(t){function e(n){return 1/(1+Math.exp(-t*n))-.5}var i=.5/e(1);return function(n){return i*e(2*Math.max(Math.min(n,1),0)-1)+.5}}convertRange(t,e,i){return(t-e[0])*(i[1]-i[0])/(e[1]-e[0])+i[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 i,n,s,o,l=0;if(this.stats&&this.stats.begin(),this.isListening){for(this.listeningAnalyzer.getByteFrequencyData(this.volumeFrequencyData),i=2,s=10;i<s;i++)this.volumeFrequencyData[i]>l&&(l=this.volumeFrequencyData[i]);this.listeningVolume=(this.listeningVolume+l)/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(l=0,this.audioAnalyzerNode.getByteFrequencyData(this.volumeFrequencyData),i=2,s=10;i<s;i++)this.volumeFrequencyData[i]>l&&(l=this.volumeFrequencyData[i]);let u=null,a=null;const h=[];for(i=0,s=this.animQueue.length;i<s;i++){const r=this.animQueue[i];if(!(!r||!r.ts||!r.ts.length||this.animClock<r.ts[0])){for(n=r.ndx||0,o=r.ts.length;n<o&&!(this.animClock<r.ts[n]);n++)for(let[d,c]of Object.entries(r.vs))if(this.mtAvatar.hasOwnProperty(d)){if(c[n+1]===null)continue;const g=this.mtAvatar[d];if(c[n]===null&&(c[n]=g.value),n===o-1)g.newvalue=c[n];else{g.newvalue=c[n+1];const y=r.ts[n+1]-r.ts[n];let x=1;y>1e-4&&(x=(this.animClock-r.ts[n])/y),x<1&&(g.easing&&(x=g.easing(x)),g.newvalue=(1-x)*c[n]+x*g.newvalue),g.ref&&g.ref!==r.vs&&g.ref.hasOwnProperty(d)&&delete g.ref[d],g.ref=r.vs}if(l)switch(d){case"viseme_aa":case"viseme_E":case"viseme_I":case"viseme_O":case"viseme_U":g.newvalue*=1+l/255-.5}g.needsUpdate=!0}else d==="eyeContact"&&c[n]!==null&&u!==!1?u=!!c[n]:d==="headMove"&&c[n]!==null&&a!==!1?c[n]===0?a=!1:(Math.random()<c[n]&&(a=!0),c[n]=null):c[n]!==null&&(h.push({mt:d,val:c[n]}),c[n]=null);n===o?(r.hasOwnProperty("mood")&&this.setMood(r.mood),r.loop?(o=this.isSpeaking&&(r.template.name==="head"||r.template.name==="eyes")?4:1,this.animQueue[i]=this.animFactory(r.template,r.loop>0?r.loop-1:r.loop,1,1/o)):(this.animQueue.splice(i--,1),s--)):r.ndx=n-1}}for(let r=0,d=h.length;r<d;r++)switch(n=h[r].val,h[r].mt){case"speak":this.speakText(n);break;case"subtitles":this.onSubtitles&&typeof this.onSubtitles=="function"&&this.onSubtitles(n);break;case"pose":this.poseName=n,this.setPoseFromTemplate(this.poseTemplates[this.poseName]);break;case"gesture":this.playGesture(...n);break;case"function":n&&typeof n=="function"&&n();break;case"moveto":Object.entries(n.props).forEach(c=>{c[1]?this.poseTarget.props[c[0]].copy(c[1]):this.poseTarget.props[c[0]].copy(this.getPoseTemplateProp(c[0])),this.poseTarget.props[c[0]].t=this.animClock,this.poseTarget.props[c[0]].d=c[1]&&c[1].d?c[1].d:c.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}]},n.x?new f.Vector3(n.x,n.y,n.z):null,!0,n.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}]},n.x?new f.Vector3(n.x,n.y,n.z):null,!0,n.d);break}if((u||a)&&(F.setFromQuaternion(this.poseAvatar.props["Head.quaternion"]),F.x=Math.max(-.9,Math.min(.9,2*F.x-.5)),F.y=Math.max(-.9,Math.min(.9,-2.5*F.y)),u?(Object.assign(this.mtAvatar.eyesLookDown,{system:F.x<0?-F.x:0,needsUpdate:!0}),Object.assign(this.mtAvatar.eyesLookUp,{system:F.x<0?0:F.x,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookInLeft,{system:F.y<0?-F.y:0,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookOutLeft,{system:F.y<0?0:F.y,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookInRight,{system:F.y<0?0:F.y,needsUpdate:!0}),Object.assign(this.mtAvatar.eyeLookOutRight,{system:F.y<0?-F.y:0,needsUpdate:!0}),a&&(i=-this.mtAvatar.bodyRotateY.value,n=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:[i,i,0],headRotateX:[n,n,0],headRotateZ:[-i/4,-i/4,0]}})))):(i=this.mtAvatar.eyeLookInLeft.value-this.mtAvatar.eyeLookOutLeft.value,n=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,i,i,0],headRotateX:[null,n,n,0],headRotateZ:[null,-i/4,-i/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)&&(i=this.mtRandomized[Math.floor(Math.random()*this.mtRandomized.length)],n=this.mtAvatar[i],n.needsUpdate||Object.assign(n,{base:(this.mood.baseline[i]||0)+(1+l/255)*Math.random()/5,needsUpdate:!0})),this.updatePoseBase(this.animClock),this.mixer&&this.mixer.update(e/1e3*this.mixer.timeScale),this.updatePoseDelta(),(this.isSpeaking||this.isListening)&&u?l>this.volumeMax?(this.volumeHeadBase=.05,Math.random()>.6&&(this.volumeHeadTarget=-.05-Math.random()/15),this.volumeMax=l):(this.volumeMax*=.92,this.volumeHeadTarget=this.volumeHeadBase-.9*(this.volumeHeadBase-this.volumeHeadTarget)):(this.volumeHeadTarget=0,this.volumeMax=0),i=this.volumeHeadTarget-this.volumeHeadCurrent,n=Math.abs(i),n>1e-4&&(o=n*(this.volumeHeadEasing(Math.min(1,this.volumeHeadVelocity*e/1e3/n)/2+.5)-.5),this.volumeHeadCurrent+=Math.sign(i)*Math.min(n,o)),Math.abs(this.volumeHeadCurrent)>1e-4&&(U.setFromAxisAngle($e,this.volumeHeadCurrent),this.objectNeck.quaternion.multiply(U)),Ie.setFromObject(this.armature),this.objectLeftToeBase.getWorldPosition(te),te.sub(this.armature.position),this.objectRightToeBase.getWorldPosition(ie),ie.sub(this.armature.position),this.objectHips.position.y-=Ie.min.y/2,this.objectHips.position.x-=(te.x+ie.x)/4,this.objectHips.position.z-=(te.z+ie.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 r=new f.Spherical().setFromVector3(this.cameraStart),d=new f.Spherical().setFromVector3(this.cameraEnd);r.phi+=this.easing(this.cameraClock/1e3)*(d.phi-r.phi),r.theta+=this.easing(this.cameraClock/1e3)*(d.theta-r.theta),r.radius+=this.easing(this.cameraClock/1e3)*(d.radius-r.radius),r.makeSafe(),this.camera.position.setFromSpherical(r),this.controlsStart.x!==this.controlsEnd.x?this.controls.target.copy(this.controlsStart.lerp(this.controlsEnd,this.easing(this.cameraClock/1e3))):(r.setFromVector3(this.controlsStart),d.setFromVector3(this.controlsEnd),r.phi+=this.easing(this.cameraClock/1e3)*(d.phi-r.phi),r.theta+=this.easing(this.cameraClock/1e3)*(d.theta-r.theta),r.radius+=this.easing(this.cameraClock/1e3)*(d.radius-r.radius),r.makeSafe(),this.controls.target.setFromSpherical(r)),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 i=e.morphTargetDictionary["viseme_"+t];i!==void 0&&(e.morphTargetInfluences[i]=0)})})}lipsyncGetProcessor(t,e="./"){if(!this.lipsync.hasOwnProperty(t)){const i=t.toLowerCase(),n="Lipsync"+t.charAt(0).toUpperCase()+t.slice(1);try{const s=ve[i];s&&s[n]?(this.lipsync[t]=new s[n],console.log(`Loaded lip-sync module for ${t}`)):console.warn(`Lip-sync module for ${t} not found. Available modules:`,Object.keys(ve))}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,i=null,n=null){e=e||{};const s=/[!\.\?\n\p{Extended_Pictographic}]/ug,o=/[ ]/ug,l=/[\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 h="",r="",d=0,c=[],g=[];const y=Array.from(this.segmenter.segment(t),x=>x.segment);for(let x=0;x<y.length;x++){const L=x===y.length-1,P=y[x].match(l);let p=y[x].match(s);const T=y[x].match(u),M=y[x].match(o);if(p&&!L&&!T&&y[x+1].match(s)&&(p=!1),i&&(h+=y[x]),P&&(!n||n.every(I=>x<I[0]||x>I[1]))&&(r+=y[x]),(M||p||L)&&(r.length&&(r=this.lipsyncPreProcessText(r,a),r.length&&c.push({mark:d,word:r})),h.length&&(g.push({mark:d,template:{name:"subtitles"},ts:[0],vs:{subtitles:[h]}}),h=""),r.length)){const I=this.lipsyncWordsToVisemes(r,a);if(I&&I.visemes&&I.visemes.length){const D=I.times[I.visemes.length-1]+I.durations[I.visemes.length-1];for(let O=0;O<I.visemes.length;O++)g.push({mark:d,template:{name:"viseme"},ts:[(I.times[O]-.6)/D,(I.times[O]+.5)/D,(I.times[O]+I.durations[O]+.5)/D],vs:{["viseme_"+I.visemes[O]]:[null,I.visemes[O]==="PP"||I.visemes[O]==="FF"?.9:.6,0]}})}r="",d++}if(p||L){if(c.length||L&&g.length){const I={anim:g};i&&(I.onSubtitles=i),c.length&&!e.avatarMute&&(I.text=c,e.avatarMood&&(I.mood=e.avatarMood),e.ttsLang&&(I.lang=e.ttsLang),e.ttsVoice&&(I.voice=e.ttsVoice),e.ttsRate&&(I.rate=e.ttsRate),e.ttsVoice&&(I.pitch=e.ttsPitch),e.ttsVolume&&(I.volume=e.ttsVolume)),this.speechQueue.push(I),c=[],r="",d=0,g=[]}if(T){let I=this.animEmojis[y[x]];I&&I.link&&(I=this.animEmojis[I.link]),I&&this.speechQueue.push({emoji:I})}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 i=await(await fetch(t)).arrayBuffer();this.stopBackgroundAudio(),this.audioBackgroundSource=this.audioCtx.createBufferSource(),this.audioBackgroundSource.loop=!0,this.audioBackgroundSource.buffer=await this.audioCtx.decodeAudioData(i),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 i=await(await fetch(t)).arrayBuffer();this.audioReverbNode.buffer=await this.audioCtx.decodeAudioData(i)}else{const e=this.audioCtx.sampleRate,i=this.audioCtx.createBuffer(2,e,e);i.getChannelData(0)[0]=1,i.getChannelData(1)[0]=1,this.audioReverbNode.buffer=i}}setMixerGain(t,e=null,i=0){t!==null&&(this.audioSpeechGainNode.gain.cancelScheduledValues(this.audioCtx.currentTime),i?(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+i)):this.audioSpeechGainNode.gain.setValueAtTime(t,this.audioCtx.currentTime)),e!==null&&(this.audioBackgroundGainNode.gain.cancelScheduledValues(this.audioCtx.currentTime),i?(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+i)):this.audioBackgroundGainNode.gain.setValueAtTime(e,this.audioCtx.currentTime))}speakAudio(t,e=null,i=null){e=e||{};const n=e.lipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang,s={};if(t.words){let o=[];for(let l=0;l<t.words.length;l++){const u=t.words[l],a=t.wtimes[l];let h=t.wdurations[l];if(u.length&&(i&&o.push({template:{name:"subtitles"},ts:[a],vs:{subtitles:[" "+u]}}),!t.visemes)){const r=this.lipsyncPreProcessText(u,n),d=this.lipsyncWordsToVisemes(r,n);if(d&&d.visemes&&d.visemes.length){const c=d.times[d.visemes.length-1]+d.durations[d.visemes.length-1],g=Math.min(h,Math.max(0,h-d.visemes.length*150));let y=.6+this.convertRange(g,[0,h],[0,.4]);if(h=Math.min(h,d.visemes.length*200),c>0)for(let x=0;x<d.visemes.length;x++){const L=a+d.times[x]/c*h,P=d.durations[x]/c*h;o.push({template:{name:"viseme"},ts:[L-Math.min(60,2*P/3),L+Math.min(25,P/2),L+P+Math.min(60,P/2)],vs:{["viseme_"+d.visemes[x]]:[null,d.visemes[x]==="PP"||d.visemes[x]==="FF"?.9:y,0]}})}}}}if(t.visemes)for(let l=0;l<t.visemes.length;l++){const u=t.visemes[l],a=t.vtimes[l],h=t.vdurations[l];o.push({template:{name:"viseme"},ts:[a-2*h/3,a+h/2,a+h+h/2],vs:{["viseme_"+u]:[null,u==="PP"||u==="FF"?.9:.6,0]}})}if(t.markers)for(let l=0;l<t.markers.length;l++){const u=t.markers[l],a=t.mtimes[l];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]}i&&(s.onSubtitles=i),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((l,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 i;if(Array.isArray(e.audio)){let s=this.concatArrayBuffers(e.audio);i=this.pcmToAudioBuffer(s)}else i=e.audio;this.audioSpeechSource=this.audioCtx.createBufferSource(),this.audioSpeechSource.buffer=i,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 n=0;e.anim&&(e.isRaw||(n=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]+n;this.animQueue.push(s)})),this.audioSpeechSource.start(n/1e3)}else this.isAudioPlaying=!1,this.startSpeaking(!0)}async synthesizeWithBrowserTTS(t){return new Promise((e,i)=>{const n=t.text.map(p=>p.word).join(" "),s=new SpeechSynthesisUtterance(n),o=t.lang||this.avatar.ttsLang||this.opt.ttsLang||"en-US",l=(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,l)),s.pitch=Math.max(0,Math.min(2,u)),s.volume=Math.max(0,Math.min(1,a));const h=speechSynthesis.getVoices(),r=t.voice||this.avatar.ttsVoice||this.opt.ttsVoice;if(r&&h.length>0){const p=h.find(T=>T.name.includes(r)||T.lang===o);p&&(s.voice=p)}const d=n.length*100/s.rate,c=this.audioCtx.createBuffer(1,this.audioCtx.sampleRate*(d/1e3),this.audioCtx.sampleRate),g=this.avatar.lipsyncLang||this.opt.lipsyncLang||"en",y=this.lipsyncPreProcessText(n,g),x=this.lipsyncWordsToVisemes(y,g);console.log("Browser TTS Lip-sync Debug:",{text:n,lipsyncLang:g,processedText:y,lipsyncData:x,hasVisemes:x&&x.visemes&&x.visemes.length>0,estimatedDuration:d});const L=[];if(x&&x.visemes&&x.visemes.length>0){const p=x.times[x.visemes.length-1]+x.durations[x.visemes.length-1];for(let T=0;T<x.visemes.length;T++){const M=x.visemes[T],I=x.times[T]/p,D=x.durations[T]/p,O=I*d,X=D*d;L.push({template:{name:"viseme"},ts:[O-Math.min(60,2*X/3),O+Math.min(25,X/2),O+X+Math.min(60,X/2)],vs:{["viseme_"+M]:[null,M==="PP"||M==="FF"?.9:.6,0]}})}}const P=[...t.anim,...L];this.audioPlaylist.push({anim:P,audio:c}),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),i(p.error)},speechSynthesis.speak(s)})}async synthesizeWithElevenLabsTTS(t){const e=t.text.map(d=>d.word).join(" "),i=t.voice||this.avatar.ttsVoice||this.opt.ttsVoice||"21m00Tcm4TlvDq8ikWAM",n={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}/${i}`,{method:"POST",headers:{Accept:"audio/mpeg","Content-Type":"application/json","xi-api-key":this.opt.ttsApikey},body:JSON.stringify(n)});if(!s.ok)throw new Error(`ElevenLabs TTS error: ${s.status} ${s.statusText}`);const o=await s.arrayBuffer(),l=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),c=this.lipsyncWordsToVisemes(d,u);if(console.log("Lip-sync data:",{processedText:d,lipsyncData:c,hasVisemes:c&&c.visemes&&c.visemes.length>0}),c&&c.visemes&&c.visemes.length>0)a={visemes:c.visemes.map((g,y)=>({viseme:g,startTime:y*l.duration/c.visemes.length,endTime:(y+1)*l.duration/c.visemes.length,duration:l.duration/c.visemes.length,intensity:.7})),words:[],duration:l.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 c=e.toLowerCase().split(/\s+/),g=[];for(const y of c)for(const x of y){let L="aa";"aeiou".includes(x)?L="aa":"bp".includes(x)?L="PP":"fv".includes(x)?L="FF":"st".includes(x)?L="SS":"dln".includes(x)?L="DD":"kg".includes(x)?L="kk":"rw".includes(x)&&(L="RR"),g.push(L)}a={visemes:g.map((y,x)=>({viseme:y,startTime:x*l.duration/g.length,endTime:(x+1)*l.duration/g.length,duration:l.duration/g.length,intensity:.6})),words:[],duration:l.duration,features:{onsets:[],boundaries:[]}}}console.log("ElevenLabs TTS Audio Analysis:",{text:e,audioDuration:l.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 h=[];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 c=a.visemes[d],g=c.startTime*1e3,y=c.duration*1e3,x=c.intensity;h.push({template:{name:"viseme"},ts:[g-Math.min(60,2*y/3),g+Math.min(25,y/2),g+y+Math.min(60,y/2)],vs:{["viseme_"+c.viseme]:[null,x,0]}})}console.log("ElevenLabs: Generated",h.length,"lip-sync animation frames")}else console.warn("ElevenLabs: No visemes available for lip-sync animation");const r=[...t.anim,...h];console.log("ElevenLabs: Combined animation frames:",r.length,"(original:",t.anim.length,"+ lipsync:",h.length,")"),this.audioPlaylist.push({anim:r,audio:l}),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(" "),i=t.voice||this.avatar.ttsVoice||this.opt.ttsVoice||"aura-2-thalia-en",n=`${this.opt.ttsEndpoint}?model=${i}`,s=await fetch(n,{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(),l=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),c=this.lipsyncWordsToVisemes(d,u);if(console.log("Lip-sync data:",{processedText:d,lipsyncData:c,hasVisemes:c&&c.visemes&&c.visemes.length>0}),c&&c.visemes&&c.visemes.length>0)a={visemes:c.visemes.map((g,y)=>({viseme:g,startTime:y*l.duration/c.visemes.length,endTime:(y+1)*l.duration/c.visemes.length,duration:l.duration/c.visemes.length,intensity:.7})),words:[],duration:l.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 c=e.toLowerCase().split(/\s+/),g=[];for(const y of c)for(const x of y){let L="aa";"aeiou".includes(x)?L="aa":"bp".includes(x)?L="PP":"fv".includes(x)?L="FF":"st".includes(x)?L="SS":"dln".includes(x)?L="DD":"kg".includes(x)?L="kk":"rw".includes(x)&&(L="RR"),g.push(L)}a={visemes:g.map((y,x)=>({viseme:y,startTime:x*l.duration/g.length,endTime:(x+1)*l.duration/g.length,duration:l.duration/g.length,intensity:.6})),words:[],duration:l.duration,features:{onsets:[],boundaries:[]}}}console.log("Deepgram TTS Audio Analysis:",{text:e,audioDuration:l.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 h=[];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 c=a.visemes[d],g=c.startTime*1e3,y=c.duration*1e3,x=c.intensity;h.push({template:{name:"viseme"},ts:[g-Math.min(60,2*y/3),g+Math.min(25,y/2),g+y+Math.min(60,y/2)],vs:{["viseme_"+c.viseme]:[null,x,0]}})}console.log("Deepgram: Generated",h.length,"lip-sync animation frames")}else console.warn("Deepgram: No visemes available for lip-sync animation");const r=[...t.anim,...h];console.log("Deepgram: Combined animation frames:",r.length,"(original:",t.anim.length,"+ lipsync:",h.length,")"),this.audioPlaylist.push({anim:r,audio:l}),this.onSubtitles=t.onSubtitles||null,this.resetLips(),t.mood&&this.setMood(t.mood),this.playAudio()}async synthesizeWithAzureTTS(t){const e=t.text.map(r=>r.word).join(" "),n=`
|
|
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:n});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 c=u.visemes[l],d=c.startTime*1e3,g=c.duration*1e3,y=c.intensity;a.push({template:{name:"viseme"},ts:[d-Math.min(60,2*g/3),d+Math.min(25,g/2),d+g+Math.min(60,g/2)],vs:{["viseme_"+c.viseme]:[null,y,0]}})}const h=[...t.anim,...a];this.audioPlaylist.push({anim:h,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("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'").replace(new RegExp("^\\p{Dash_Punctuation}$","ug"),'<break time="750ms"/>')}),e+="</speak>";const i={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"&&(i.headers.Authorization="Bearer "+await this.opt.jwtGet());const n=await fetch(this.opt.ttsEndpoint+(this.opt.ttsApikey?"?key="+this.opt.ttsApikey:""),i),s=await n.json();if(n.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((c,d)=>{if(d>0){let g=u[u.length-1];s.timepoints[a]&&(g=s.timepoints[a].timeSeconds*1e3,s.timepoints[a].markName===""+c.mark&&a++),u.push(g)}});const h=[{mark:0,time:0}];u.forEach((c,d)=>{if(d>0){let g=c-u[d-1];h[d-1].duration=g,h.push({mark:d,time:c})}});let l=1e3*r.duration;l>this.opt.ttsTrimEnd&&(l=l-this.opt.ttsTrimEnd),h[h.length-1].duration=l-h[h.length-1].time,t.anim.forEach(c=>{const d=h[c.mark];if(d)for(let g=0;g<c.ts.length;g++)c.ts[g]=d.time+c.ts[g]*d.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 i=e.emoji.dt.reduce((n,s)=>n+s,0);this.animQueue.push(this.animFactory(e.emoji)),setTimeout(this.startSpeaking.bind(this),i,!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(i){console.error("Error:",i),this.startSpeaking(!0)}}else e.anim?(this.onSubtitles=e.onSubtitles||null,this.resetLips(),e.mood&&this.setMood(e.mood),e.anim.forEach((i,n)=>{for(let s=0;s<i.ts.length;s++)i.ts[s]=this.animClock+10*n;this.animQueue.push(i)}),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,i=null,n=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=i,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(Je.href),u=new Promise((a,h)=>setTimeout(()=>h(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=n||null,this.audioCtx.state==="suspended"||this.audioCtx.state==="interrupted"){const r=this.audioCtx.resume(),u=new Promise((a,h)=>setTimeout(()=>h("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 i=0;i<t.visemes.length;i++){const n=t.visemes[i],s=e+t.vtimes[i],o=t.vdurations[i],r={template:{name:"viseme"},ts:[s-2*o/3,s+o/2,s+o+o/2],vs:{["viseme_"+n]:[null,n==="PP"||n==="FF"?.9:.6,0]}};this.animQueue.push(r)}if(t.words&&(this.onSubtitles||this.streamLipsyncType=="words"))for(let i=0;i<t.words.length;i++){const n=t.words[i],s=t.wtimes[i];let o=t.wdurations[i];if(n.length&&(this.onSubtitles&&this.animQueue.push({template:{name:"subtitles"},ts:[e+s],vs:{subtitles:[" "+n]}}),this.streamLipsyncType=="words")){const r=this.streamLipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang,u=this.lipsyncPreProcessText(n,r),a=this.lipsyncWordsToVisemes(u,r);if(a&&a.visemes&&a.visemes.length){const h=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 c=.6+this.convertRange(l,[0,o],[0,.4]);if(o=Math.min(o,a.visemes.length*200),h>0)for(let d=0;d<a.visemes.length;d++){const g=e+s+a.times[d]/h*o,y=a.durations[d]/h*o;this.animQueue.push({template:{name:"viseme"},ts:[g-Math.min(60,2*y/3),g+Math.min(25,y/2),g+y+Math.min(60,y/2)],vs:{["viseme_"+a.visemes[d]]:[null,a.visemes[d]==="PP"||a.visemes[d]==="FF"?.9:c,0]}})}}}}if(t.anims&&this.streamLipsyncType=="blendshapes")for(let i=0;i<t.anims.length;i++){let n=t.anims[i];n.delay+=e;let s=this.animFactory(n,!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 i=t.audio.buffer.slice(t.audio.byteOffset,t.audio.byteOffset+t.audio.byteLength);e.data=i,this.streamWorkletNode.port.postMessage(e,[e.data])}else if(t.audio instanceof Float32Array){const i=new Int16Array(t.audio.length);for(let n=0;n<t.audio.length;n++){let s=Math.max(-1,Math.min(1,t.audio[n]));i[n]=s<0?s*32768:s*32767}e.data=i.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,i=(Math.random()-.5)/4,n=this.animQueue.findIndex(o=>o.template.name==="lookat");n!==-1&&this.animQueue.splice(n,1);const s={name:"lookat",dt:[750,t],vs:{bodyRotateX:[e],bodyRotateY:[i],eyesRotateX:[-3*e+.1],eyesRotateY:[-5*i],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),oe.setFromMatrixPosition(this.speakTo.objectRightEye.matrixWorld),e.addVectors(ie,oe).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),oe.setFromMatrixPosition(this.objectRightEye.matrixWorld),ie.add(oe).divideScalar(2),U.copy(this.armature.quaternion),U.multiply(this.poseTarget.props["Hips.quaternion"]),U.multiply(this.poseTarget.props["Spine.quaternion"]),U.multiply(this.poseTarget.props["Spine1.quaternion"]),U.multiply(this.poseTarget.props["Spine2.quaternion"]),U.multiply(this.poseTarget.props["Neck.quaternion"]),U.multiply(this.poseTarget.props["Head.quaternion"]);const i=new f.Vector3().subVectors(e,ie).normalize(),n=Math.atan2(i.x,i.z),s=Math.asin(-i.y);F.set(s,n,0,"YXZ");const r=new f.Quaternion().setFromEuler(F),u=new f.Quaternion().copy(r).multiply(U.clone().invert());F.setFromQuaternion(u,"YXZ");let a=F.x/(40/24)+.2,h=F.y/(9/4),l=Math.min(.6,Math.max(-.3,a)),c=Math.min(.8,Math.max(-.8,h)),d=(Math.random()-.5)/4,g=(Math.random()-.5)/4;if(t){let y=this.animQueue.findIndex(I=>I.template.name==="lookat");y!==-1&&this.animQueue.splice(y,1);const x={name:"lookat",dt:[750,t],vs:{bodyRotateX:[l+d],bodyRotateY:[c+g],eyesRotateX:[-3*d+.1],eyesRotateY:[-5*g],browInnerUp:[[0,.7]],mouthLeft:[[0,.7]],mouthRight:[[0,.7]],eyeContact:[0],headMove:[0]}};this.animQueue.push(this.animFactory(x))}}lookAt(t,e,i){if(!this.camera)return;const n=this.nodeAvatar.getBoundingClientRect();this.objectLeftEye.updateMatrixWorld(!0),this.objectRightEye.updateMatrixWorld(!0);const s=new f.Vector3().setFromMatrixPosition(this.objectLeftEye.matrixWorld),o=new f.Vector3().setFromMatrixPosition(this.objectRightEye.matrixWorld),r=new f.Vector3().addVectors(s,o).divideScalar(2);r.project(this.camera);let u=(r.x+1)/2*n.width+n.left,a=-(r.y-1)/2*n.height+n.top;t===null&&(t=u),e===null&&(e=a),U.copy(this.armature.quaternion),U.multiply(this.poseTarget.props["Hips.quaternion"]),U.multiply(this.poseTarget.props["Spine.quaternion"]),U.multiply(this.poseTarget.props["Spine1.quaternion"]),U.multiply(this.poseTarget.props["Spine2.quaternion"]),U.multiply(this.poseTarget.props["Neck.quaternion"]),U.multiply(this.poseTarget.props["Head.quaternion"]),F.setFromQuaternion(U);let h=F.x/(40/24),l=F.y/(9/4),c=Math.min(.4,Math.max(-.4,this.camera.rotation.x)),d=Math.min(.4,Math.max(-.4,this.camera.rotation.y)),g=Math.max(window.innerWidth-u,u),y=Math.max(window.innerHeight-a,a),x=this.convertRange(e,[a-y,a+y],[-.3,.6])-h+c,I=this.convertRange(t,[u-g,u+g],[-.8,.8])-l+d;x=Math.min(.6,Math.max(-.3,x)),I=Math.min(.8,Math.max(-.8,I));let P=(Math.random()-.5)/4,p=(Math.random()-.5)/4;if(i){let z=this.animQueue.findIndex(R=>R.template.name==="lookat");z!==-1&&this.animQueue.splice(z,1);const H={name:"lookat",dt:[750,i],vs:{bodyRotateX:[x+P],bodyRotateY:[I+p],eyesRotateX:[-3*P+.1],eyesRotateY:[-5*p],browInnerUp:[[0,.7]],mouthLeft:[[0,.7]],mouthRight:[[0,.7]],eyeContact:[0],headMove:[0]}};this.animQueue.push(this.animFactory(H))}}touchAt(t,e){if(!this.camera)return;const i=this.nodeAvatar.getBoundingClientRect(),n=new f.Vector2((t-i.left)/i.width*2-1,-((e-i.top)/i.height)*2+1),s=new f.Raycaster;s.setFromCamera(n,this.camera);const o=s.intersectObject(this.armature);if(o.length>0){const r=o[0].point,u=new f.Vector3,a=new f.Vector3;this.objectLeftArm.getWorldPosition(u),this.objectRightArm.getWorldPosition(a);const h=u.distanceToSquared(r),l=a.distanceToSquared(r);h<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 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 i=[],n=[];i.push(100+Math.round(Math.random()*500)),n.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(o=>{n[0].props[o+".quaternion"]=this.ikMesh.getObjectByName(o).quaternion.clone()}),i.push(1e3+Math.round(Math.random()*500)),n.push({duration:2e3,props:{}}),["LeftArm","LeftForeArm","RightArm","RightForeArm","LeftHand","RightHand"].forEach(o=>{n[1].props[o+".quaternion"]=null});const s=this.animFactory({name:"talkinghands",delay:t,dt:i,vs:{moveto:n}});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={},i=null){this.listeningAnalyzer=t,this.listeningAnalyzer.fftSize=256,this.listeningAnalyzer.smoothingTimeConstant=.1,this.listeningAnalyzer.minDecibels=-70,this.listeningAnalyzer.maxDecibels=-10,this.listeningOnchange=i&&typeof i=="function"?i: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,i=10,n=0,s=.01,o=!1){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 r=this.animClips.find(u=>u.url===t+"-"+n);if(r){let u=this.animQueue.find(l=>l.template.name==="pose");u&&(u.ts[0]=1/0),Object.entries(r.pose.props).forEach(l=>{this.poseBase.props[l[0]]=l[1].clone(),this.poseTarget.props[l[0]]=l[1].clone(),this.poseTarget.props[l[0]].t=0,this.poseTarget.props[l[0]].d=1e3}),this.mixer?console.log("Using existing mixer for FBX animation, preserving morph targets"):(this.mixer=new f.AnimationMixer(this.armature),console.log("Created new mixer for FBX animation")),this.mixer.addEventListener("finished",this.stopAnimation.bind(this),{once:!0});const a=Math.ceil(i/r.clip.duration),h=this.mixer.clipAction(r.clip);h.setLoop(f.LoopRepeat,a),h.clampWhenFinished=!0,this.currentFBXAction=h;try{h.fadeIn(.5).play(),console.log("FBX animation started successfully:",t)}catch(l){console.warn("FBX animation failed to start:",l),this.stopAnimation();return}if(h.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 a=!1;try{const c=await fetch(t,{method:"HEAD"});if(a=c.ok,!a){console.error(`FBX file not found at ${t}. Status: ${c.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(c){console.warn(`Could not verify file existence for ${t}, attempting to load anyway:`,c)}const h=new be.FBXLoader;let l;try{l=await h.loadAsync(t,e)}catch(c){console.error(`Failed to load FBX animation from ${t}:`,c),console.error("Error details:",{message:c.message,url:t,suggestion:"Make sure the file is a valid FBX file and the path is correct"}),c.message&&c.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 d=await fetch(t),g=d.headers.get("content-type"),y=await d.text();console.error("Response details:",{status:d.status,contentType:g,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(d){console.error("Could not fetch file for debugging:",d)}return}if(l&&l.animations&&l.animations[n]){let c=l.animations[n];const d={};c.tracks.forEach(y=>{y.name=y.name.replaceAll("mixamorig","");const x=y.name.split(".");if(x[1]==="position"){for(let I=0;I<y.values.length;I++)y.values[I]=y.values[I]*s;d[y.name]=new f.Vector3(y.values[0],y.values[1],y.values[2])}else x[1]==="quaternion"?d[y.name]=new f.Quaternion(y.values[0],y.values[1],y.values[2],y.values[3]):x[1]==="rotation"&&(d[x[0]+".quaternion"]=new f.Quaternion().setFromEuler(new f.Euler(y.values[0],y.values[1],y.values[2],"XYZ")).normalize())});const g={props:d};d["Hips.position"]&&(d["Hips.position"].y<.5?g.lying=!0:g.standing=!0),this.animClips.push({url:t+"-"+n,clip:c,pose:g}),this.playAnimation(t,e,i,n,s)}else{const c="Animation "+t+" (ndx="+n+") not found";console.error(c),l&&l.animations?console.error(`FBX file loaded but has ${l.animations.length} animation(s), requested index ${n}`):console.error(l?"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,i]of Object.entries(this.gesture))i.t=this.animClock,i.d=1e3,this.poseTarget.props.hasOwnProperty(e)&&(this.poseTarget.props[e].copy(i),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,i=5,n=0,s=.01){if(!this.armature)return;let o=this.poseTemplates[t];if(!o){const r=this.animPoses.find(u=>u.url===t+"-"+n);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+i*1e3+2e3),this.setPoseFromTemplate(o)}else{let u=await new be.FBXLoader().loadAsync(t,e);if(u&&u.animations&&u.animations[n]){let a=u.animations[n];const h={};a.tracks.forEach(c=>{c.name=c.name.replaceAll("mixamorig","");const d=c.name.split(".");d[1]==="position"?h[c.name]=new f.Vector3(c.values[0]*s,c.values[1]*s,c.values[2]*s):d[1]==="quaternion"?h[c.name]=new f.Quaternion(c.values[0],c.values[1],c.values[2],c.values[3]):d[1]==="rotation"&&(h[d[0]+".quaternion"]=new f.Quaternion().setFromEuler(new f.Euler(c.values[0],c.values[1],c.values[2],"XYZ")).normalize())});const l={props:h};h["Hips.position"]&&(h["Hips.position"].y<.5?l.lying=!0:l.standing=!0),this.animPoses.push({url:t+"-"+n,pose:l}),this.playPose(t,e,i,n,s)}else{const a="Pose "+t+" (ndx="+n+") not found";console.error(a)}}}stopPose(){this.stopAnimation()}playGesture(t,e=3,i=!1,n=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),i&&(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[u,a]of Object.entries(this.gesture))a.t=this.animClock,a.d=n,this.poseTarget.props.hasOwnProperty(u)&&(this.poseTarget.props[u].copy(a),this.poseTarget.props[u].t=this.animClock,this.poseTarget.props[u].d=n);e&&Number.isFinite(e)&&(this.gestureTimeout=setTimeout(this.stopGesture.bind(this,n),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],h=r.ts[r.ts.length-1]-u;if(e*1e3-h>0){const c=[];for(let y=1;y<r.ts.length;y++)c.push(r.ts[y]-r.ts[y-1]);const d=o.template?.rescale||c.map(y=>y/h),g=e*1e3-h;r.ts=r.ts.map((y,x,I)=>x===0?u:I[x-1]+c[x-1]+d[x-1]*g)}else{const c=e*1e3/h;r.ts=r.ts.map(d=>u+c*(d-u))}}this.animQueue.push(r)}}stopGesture(t=1e3){if(this.gestureTimeout&&(clearTimeout(this.gestureTimeout),this.gestureTimeout=null),this.gesture){const i=Object.entries(this.gesture);this.gesture=null;for(const[n,s]of i)this.poseTarget.props.hasOwnProperty(n)&&(this.poseTarget.props[n].copy(this.getPoseTemplateProp(n)),this.poseTarget.props[n].t=this.animClock,this.poseTarget.props[n].d=t)}let e=this.animQueue.findIndex(i=>i.gesture);e!==-1&&this.animQueue.splice(e,1)}ikSolve(t,e=null,i=!1,n=null){const s=new f.Vector3,o=new f.Vector3,r=new f.Vector3,u=new f.Vector3,a=new f.Quaternion,h=new f.Vector3,l=new f.Vector3,c=new f.Vector3,d=this.ikMesh.getObjectByName(t.root);d.position.setFromMatrixPosition(this.armature.getObjectByName(t.root).matrixWorld),d.quaternion.setFromRotationMatrix(this.armature.getObjectByName(t.root).matrixWorld),e&&i&&e.applyQuaternion(this.armature.quaternion).add(d.position);const g=this.ikMesh.getObjectByName(t.effector),y=t.links;y.forEach(I=>{I.bone=this.ikMesh.getObjectByName(I.link),I.bone.quaternion.copy(this.getPoseTemplateProp(I.link+".quaternion"))}),d.updateMatrixWorld(!0);const x=t.iterations||10;if(e)for(let I=0;I<x;I++){let P=!1;for(let p=0,z=y.length;p<z;p++){const H=y[p].bone;H.matrixWorld.decompose(u,a,h),a.invert(),o.setFromMatrixPosition(g.matrixWorld),r.subVectors(o,u),r.applyQuaternion(a),r.normalize(),s.subVectors(e,u),s.applyQuaternion(a),s.normalize();let R=s.dot(r);R>1?R=1:R<-1&&(R=-1),R=Math.acos(R),!(R<1e-5)&&(y[p].minAngle!==void 0&&R<y[p].minAngle&&(R=y[p].minAngle),y[p].maxAngle!==void 0&&R>y[p].maxAngle&&(R=y[p].maxAngle),l.crossVectors(r,s),l.normalize(),U.setFromAxisAngle(l,R),H.quaternion.multiply(U),H.rotation.setFromVector3(c.setFromEuler(H.rotation).clamp(new f.Vector3(y[p].minx!==void 0?y[p].minx:-1/0,y[p].miny!==void 0?y[p].miny:-1/0,y[p].minz!==void 0?y[p].minz:-1/0),new f.Vector3(y[p].maxx!==void 0?y[p].maxx:1/0,y[p].maxy!==void 0?y[p].maxy:1/0,y[p].maxz!==void 0?y[p].maxz:1/0))),H.updateMatrixWorld(!0),P=!0)}if(!P)break}n&&y.forEach(I=>{this.poseTarget.props[I.link+".quaternion"].copy(I.bone.quaternion),this.poseTarget.props[I.link+".quaternion"].t=this.animClock,this.poseTarget.props[I.link+".quaternion"].d=n})}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 re={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"}},Ae={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 ce(){return{service:"elevenlabs",endpoint:re.endpoint,apiKey:re.apiKey,defaultVoice:re.defaultVoice,voices:re.voices}}function et(){const M=ce(),t=[];return Object.entries(M.voices).forEach(([e,i])=>{t.push({value:i,label:`${e.charAt(0).toUpperCase()+e.slice(1)} (${M.service})`})}),t}const ge=A.forwardRef(({avatarUrl:M="/avatars/brunette.glb",avatarBody:t="F",mood:e="neutral",ttsLang:i="en",ttsService:n=null,ttsVoice:s=null,ttsApiKey:o=null,bodyMovement:r="idle",movementIntensity:u=.5,showFullAvatar:a=!0,cameraView:h="upper",onReady:l=()=>{},onLoading:c=()=>{},onError:d=()=>{},className:g="",style:y={},animations:x={}},I)=>{const P=A.useRef(null),p=A.useRef(null),z=A.useRef(a),[H,R]=A.useState(!0),[W,O]=A.useState(null),[Y,se]=A.useState(!1);A.useEffect(()=>{z.current=a},[a]);const S=ce(),B=n||S.service;let N;B==="browser"?N={service:"browser",endpoint:"",apiKey:null,defaultVoice:"Google US English"}:B==="elevenlabs"?N={service:"elevenlabs",endpoint:"https://api.elevenlabs.io/v1/text-to-speech",apiKey:o||S.apiKey,defaultVoice:s||S.defaultVoice||re.defaultVoice,voices:S.voices||re.voices}:B==="deepgram"?N={service:"deepgram",endpoint:"https://api.deepgram.com/v1/speak",apiKey:o||S.apiKey,defaultVoice:s||S.defaultVoice||Ae.defaultVoice,voices:S.voices||Ae.voices}:N={...S,apiKey:o!==null?o:S.apiKey};const V={url:M,body:t,avatarMood:e,ttsLang:B==="browser"?"en-US":i,ttsVoice:s||N.defaultVoice,lipsyncLang:"en",showFullAvatar:a,bodyMovement:r,movementIntensity:u},K={ttsEndpoint:N.endpoint,ttsApikey:N.apiKey,ttsService:B,lipsyncModules:["en"],cameraView:h},J=A.useCallback(async()=>{if(!(!P.current||p.current))try{if(R(!0),O(null),p.current=new Le(P.current,K),p.current.controls&&(p.current.controls.enableRotate=!1,p.current.controls.enableZoom=!1,p.current.controls.enablePan=!1,p.current.controls.enableDamping=!1),x&&Object.keys(x).length>0&&(p.current.customAnimations=x),await p.current.showAvatar(V,G=>{if(G.lengthComputable){const E=Math.min(100,Math.round(G.loaded/G.total*100));c(E)}}),await new Promise(G=>{const E=()=>{p.current.lipsync&&Object.keys(p.current.lipsync).length>0?G():setTimeout(E,100)};E()}),p.current&&p.current.setShowFullAvatar)try{p.current.setShowFullAvatar(a)}catch(G){console.warn("Error setting full body mode on initialization:",G)}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()),R(!1),se(!0),l(p.current);const D=()=>{document.visibilityState==="visible"?p.current?.start():p.current?.stop()};return document.addEventListener("visibilitychange",D),()=>{document.removeEventListener("visibilitychange",D)}}catch(k){console.error("Error initializing TalkingHead:",k),O(k.message||"Failed to initialize avatar"),R(!1),d(k)}},[M,t,e,i,n,s,o,a,r,u,h]);A.useEffect(()=>(J(),()=>{p.current&&(p.current.stop(),p.current.dispose(),p.current=null)}),[J]),A.useEffect(()=>{if(!P.current||!p.current)return;const k=new ResizeObserver(G=>{for(const E of G)p.current&&p.current.onResize&&p.current.onResize()});k.observe(P.current);const D=()=>{p.current&&p.current.onResize&&p.current.onResize()};return window.addEventListener("resize",D),()=>{k.disconnect(),window.removeEventListener("resize",D)}},[Y]);const ne=A.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(k){console.warn("Failed to resume audio context:",k)}},[]),me=A.useCallback(async(k,D={})=>{if(p.current&&Y)try{await ne();const G={...D,lipsyncLang:D.lipsyncLang||V.lipsyncLang||"en"};if(D.onSpeechEnd&&p.current){const E=p.current;let q=null,ae=0;const fe=1200;let le=!1;q=setInterval(()=>{if(ae++,ae>fe){if(q&&(clearInterval(q),q=null),!le){le=!0;try{D.onSpeechEnd()}catch(xe){console.error("Error in onSpeechEnd callback (timeout):",xe)}}return}const we=!E.speechQueue||E.speechQueue.length===0,Ce=!E.audioPlaylist||E.audioPlaylist.length===0;E&&E.isSpeaking===!1&&we&&Ce&&E.isAudioPlaying===!1&&!le&&setTimeout(()=>{if(E&&E.isSpeaking===!1&&(!E.speechQueue||E.speechQueue.length===0)&&(!E.audioPlaylist||E.audioPlaylist.length===0)&&E.isAudioPlaying===!1&&!le){le=!0,q&&(clearInterval(q),q=null);try{D.onSpeechEnd()}catch(ze){console.error("Error in onSpeechEnd callback:",ze)}}},100)},100)}p.current.lipsync&&Object.keys(p.current.lipsync).length>0?(p.current.setSlowdownRate&&p.current.setSlowdownRate(1.05),p.current.speakText(k,G)):setTimeout(async()=>{await ne(),p.current&&p.current.lipsync&&(p.current.setSlowdownRate&&p.current.setSlowdownRate(1.05),p.current.speakText(k,G))},100)}catch(G){console.error("Error speaking text:",G),O(G.message||"Failed to speak text")}},[Y,ne,V.lipsyncLang]),Q=A.useCallback(()=>{p.current&&(p.current.stopSpeaking(),p.current.setSlowdownRate&&p.current.setSlowdownRate(1))},[]),v=A.useCallback(k=>{p.current&&p.current.setMood(k)},[]),b=A.useCallback(k=>{p.current&&p.current.setSlowdownRate&&p.current.setSlowdownRate(k)},[]),C=A.useCallback((k,D=!1)=>{if(p.current&&p.current.playAnimation){if(x&&x[k]&&(k=x[k]),p.current.setShowFullAvatar)try{p.current.setShowFullAvatar(z.current)}catch(E){console.warn("Error setting full body mode:",E)}if(k.includes("."))try{p.current.playAnimation(k,null,10,0,.01,D)}catch(E){console.warn(`Failed to play ${k}:`,E);try{p.current.setBodyMovement("idle")}catch(q){console.warn("Fallback animation also failed:",q)}}else{const E=[".fbx",".glb",".gltf"];let q=!1;for(const ae of E)try{p.current.playAnimation(k+ae,null,10,0,.01,D),q=!0;break}catch{}if(!q){console.warn("Animation not found:",k);try{p.current.setBodyMovement("idle")}catch(ae){console.warn("Fallback animation also failed:",ae)}}}}},[x]),T=A.useCallback(()=>{p.current&&p.current.onResize&&p.current.onResize()},[]);return A.useImperativeHandle(I,()=>({speakText:me,stopSpeaking:Q,resumeAudioContext:ne,setMood:v,setTimingAdjustment:b,playAnimation:C,isReady:Y,talkingHead:p.current,handleResize:T,setBodyMovement:k=>{if(p.current&&p.current.setShowFullAvatar&&p.current.setBodyMovement)try{p.current.setShowFullAvatar(z.current),p.current.setBodyMovement(k)}catch(D){console.warn("Error setting body movement:",D)}},setMovementIntensity:k=>p.current?.setMovementIntensity(k),playRandomDance:()=>{if(p.current&&p.current.setShowFullAvatar&&p.current.playRandomDance)try{p.current.setShowFullAvatar(z.current),p.current.playRandomDance()}catch(k){console.warn("Error playing random dance:",k)}},playReaction:k=>{if(p.current&&p.current.setShowFullAvatar&&p.current.playReaction)try{p.current.setShowFullAvatar(z.current),p.current.playReaction(k)}catch(D){console.warn("Error playing reaction:",D)}},playCelebration:()=>{if(p.current&&p.current.setShowFullAvatar&&p.current.playCelebration)try{p.current.setShowFullAvatar(z.current),p.current.playCelebration()}catch(k){console.warn("Error playing celebration:",k)}},setShowFullAvatar:k=>{if(p.current&&p.current.setShowFullAvatar)try{z.current=k,p.current.setShowFullAvatar(k)}catch(D){console.warn("Error setting showFullAvatar:",D)}},lockAvatarPosition:()=>{if(p.current&&p.current.lockAvatarPosition)try{p.current.lockAvatarPosition()}catch(k){console.warn("Error locking avatar position:",k)}},unlockAvatarPosition:()=>{if(p.current&&p.current.unlockAvatarPosition)try{p.current.unlockAvatarPosition()}catch(k){console.warn("Error unlocking avatar position:",k)}}})),te.jsxs("div",{className:`talking-head-avatar ${g}`,style:{width:"100%",height:"100%",position:"relative",...y},children:[te.jsx("div",{ref:P,className:"talking-head-viewer",style:{width:"100%",height:"100%",minHeight:"400px"}}),H&&te.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..."}),W&&te.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:W})]})});ge.displayName="TalkingHeadAvatar";const ke=A.forwardRef(({text:M="Hello! I'm a talking avatar. How are you today?",onLoading:t=()=>{},onError:e=()=>{},onReady:i=()=>{},className:n="",style:s={},avatarConfig:o={}},r)=>{const u=A.useRef(null),a=A.useRef(null),[h,l]=A.useState(!0),[c,d]=A.useState(null),[g,y]=A.useState(!1),x=ce(),I=o.ttsService||x.service,P=I==="browser"?{endpoint:"",apiKey:null,defaultVoice:"Google US English"}:{...x,apiKey:o.ttsApiKey!==void 0&&o.ttsApiKey!==null?o.ttsApiKey:x.apiKey,endpoint:I==="elevenlabs"&&o.ttsApiKey?"https://api.elevenlabs.io/v1/text-to-speech":x.endpoint},p={url:"/avatars/brunette.glb",body:"F",avatarMood:"neutral",ttsLang:I==="browser"?"en-US":"en",ttsVoice:o.ttsVoice||P.defaultVoice,lipsyncLang:"en",showFullAvatar:!0,bodyMovement:"idle",movementIntensity:.5,...o},z={ttsEndpoint:P.endpoint,ttsApikey:P.apiKey,ttsService:I,lipsyncModules:["en"],cameraView:"upper"},H=A.useCallback(async()=>{if(!(!u.current||a.current))try{if(l(!0),d(null),a.current=new Le(u.current,z),await a.current.showAvatar(p,N=>{if(N.lengthComputable){const V=Math.min(100,Math.round(N.loaded/N.total*100));t(V)}}),a.current.morphs&&a.current.morphs.length>0){const N=a.current.morphs[0].morphTargetDictionary;console.log("Available morph targets:",Object.keys(N));const V=Object.keys(N).filter(K=>K.startsWith("viseme_"));console.log("Viseme morph targets found:",V),V.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 V=()=>{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(V,100))};V()}),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),y(!0),i(a.current);const B=()=>{document.visibilityState==="visible"?a.current?.start():a.current?.stop()};return document.addEventListener("visibilitychange",B),()=>{document.removeEventListener("visibilitychange",B)}}catch(S){console.error("Error initializing TalkingHead:",S),d(S.message||"Failed to initialize avatar"),l(!1),e(S)}},[]);A.useEffect(()=>(H(),()=>{a.current&&(a.current.stop(),a.current.dispose(),a.current=null)}),[H]);const R=A.useCallback(S=>{if(a.current&&g)try{console.log("Speaking text:",S),console.log("Avatar config:",p),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(S)):(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(S)):console.error("Lip-sync still not ready after waiting")},500))}catch(B){console.error("Error speaking text:",B),d(B.message||"Failed to speak text")}else console.warn("Avatar not ready for speaking. isReady:",g,"talkingHeadRef:",!!a.current)},[g,p]),W=A.useCallback(()=>{a.current&&(a.current.stopSpeaking(),a.current.setSlowdownRate&&(a.current.setSlowdownRate(1),console.log("Reset timing to normal")))},[]),O=A.useCallback(S=>{a.current&&a.current.setMood(S)},[]),Y=A.useCallback(S=>{a.current&&a.current.setSlowdownRate&&(a.current.setSlowdownRate(S),console.log("Timing adjustment set to:",S))},[]),se=A.useCallback((S,B=!1)=>{if(a.current&&a.current.playAnimation){if(a.current.setShowFullAvatar)try{a.current.setShowFullAvatar(!0)}catch(V){console.warn("Error setting full body mode:",V)}if(S.includes("."))try{a.current.playAnimation(S,null,10,0,.01,B),console.log("Playing animation:",S)}catch(V){console.log(`Failed to play ${S}:`,V);try{a.current.setBodyMovement("idle"),console.log("Fallback to idle animation")}catch(K){console.warn("Fallback animation also failed:",K)}}else{const V=[".fbx",".glb",".gltf"];let K=!1;for(const J of V)try{a.current.playAnimation(S+J,null,10,0,.01,B),console.log("Playing animation:",S+J),K=!0;break}catch{console.log(`Failed to play ${S}${J}, trying next format...`)}if(!K){console.warn("Animation system not available or animation not found:",S);try{a.current.setBodyMovement("idle"),console.log("Fallback to idle animation")}catch(J){console.warn("Fallback animation also failed:",J)}}}}else console.warn("Animation system not available or animation not found:",S)},[]);return A.useImperativeHandle(r,()=>({speakText:R,stopSpeaking:W,setMood:O,setTimingAdjustment:Y,playAnimation:se,isReady:g,talkingHead:a.current,setBodyMovement:S=>{if(a.current&&a.current.setShowFullAvatar&&a.current.setBodyMovement)try{a.current.setShowFullAvatar(!0),a.current.setBodyMovement(S),console.log("Body movement set with full body mode:",S)}catch(B){console.warn("Error setting body movement:",B)}},setMovementIntensity:S=>a.current?.setMovementIntensity(S),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(S){console.warn("Error playing random dance:",S)}},playReaction:S=>{if(a.current&&a.current.setShowFullAvatar&&a.current.playReaction)try{a.current.setShowFullAvatar(!0),a.current.playReaction(S),console.log("Reaction played with full body mode:",S)}catch(B){console.warn("Error playing reaction:",B)}},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(S){console.warn("Error playing celebration:",S)}},setShowFullAvatar:S=>{if(a.current&&a.current.setShowFullAvatar)try{a.current.setShowFullAvatar(S),console.log("Show full avatar set to:",S)}catch(B){console.warn("Error setting showFullAvatar:",B)}},lockAvatarPosition:()=>{if(a.current&&a.current.lockAvatarPosition)try{a.current.lockAvatarPosition()}catch(S){console.warn("Error locking avatar position:",S)}},unlockAvatarPosition:()=>{if(a.current&&a.current.unlockAvatarPosition)try{a.current.unlockAvatarPosition()}catch(S){console.warn("Error unlocking avatar position:",S)}}})),te.jsxs("div",{className:`talking-head-container ${n}`,style:s,children:[te.jsx("div",{ref:u,className:"talking-head-viewer",style:{width:"100%",height:"100%",minHeight:"400px"}}),h&&te.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..."}),c&&te.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:c})]})});ke.displayName="TalkingHeadComponent";const Se=A.forwardRef(({curriculumData:M=null,avatarConfig:t={},animations:e={},onLessonStart:i=()=>{},onLessonComplete:n=()=>{},onQuestionAnswer:s=()=>{},onCurriculumComplete:o=()=>{},onCustomAction:r=()=>{},autoStart:u=!1},a)=>{const h=A.useRef(null),l=A.useRef({currentModuleIndex:0,currentLessonIndex:0,currentQuestionIndex:0,isTeaching:!1,isQuestionMode:!1,lessonCompleted:!1,curriculumCompleted:!1,score:0,totalQuestions:0}),c=A.useRef({onLessonStart:i,onLessonComplete:n,onQuestionAnswer:s,onCurriculumComplete:o,onCustomAction:r}),d=A.useRef(null),g=A.useRef(null),y=A.useRef(null),x=A.useRef(null),I=A.useRef(null),P=A.useRef(null),p=A.useRef(null),z=A.useRef(M?.curriculum||{title:"Default Curriculum",description:"No curriculum data provided",language:"en",modules:[]}),H=A.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"});A.useEffect(()=>{c.current={onLessonStart:i,onLessonComplete:n,onQuestionAnswer:s,onCurriculumComplete:o,onCustomAction:r}},[i,n,s,o,r]),A.useEffect(()=>{z.current=M?.curriculum||{title:"Default Curriculum",description:"No curriculum data provided",language:"en",modules:[]},H.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"}},[M,t,e]);const R=A.useCallback(()=>(z.current||{modules:[]}).modules[l.current.currentModuleIndex]?.lessons[l.current.currentLessonIndex],[]),W=A.useCallback(()=>R()?.questions[l.current.currentQuestionIndex],[R]),O=A.useCallback((v,b)=>b.type==="multiple_choice"||b.type==="true_false"?v===b.answer:b.type==="code_test"&&typeof v=="object"&&v!==null?v.passed===!0:!1,[]),Y=A.useCallback(()=>{l.current.lessonCompleted=!0,l.current.isQuestionMode=!1;const v=l.current.totalQuestions>0?Math.round(l.current.score/l.current.totalQuestions*100):100;let b="Congratulations! You've completed this lesson";if(l.current.totalQuestions>0?b+=` with a score of ${l.current.score} out of ${l.current.totalQuestions} (${v}%). `:b+="! ",v>=80?b+="Excellent work! You have a great understanding of this topic.":v>=60?b+="Good job! You understand most of the concepts.":b+="Keep practicing! You're making progress.",c.current.onLessonComplete({moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,score:l.current.score,totalQuestions:l.current.totalQuestions,percentage:v}),c.current.onCustomAction({type:"lessonComplete",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,score:l.current.score,totalQuestions:l.current.totalQuestions,percentage:v}),h.current){if(h.current.setMood("happy"),e.lessonComplete)try{h.current.playAnimation(e.lessonComplete,!0)}catch{h.current.playCelebration()}const C=z.current||{modules:[]},T=C.modules[l.current.currentModuleIndex],k=l.current.currentLessonIndex<(T?.lessons?.length||0)-1,D=l.current.currentModuleIndex<(C.modules?.length||0)-1,G=k||D,E=H.current||{lipsyncLang:"en"};h.current.speakText(b,{lipsyncLang:E.lipsyncLang,onSpeechEnd:()=>{c.current.onCustomAction({type:"lessonCompleteFeedbackDone",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,score:l.current.score,totalQuestions:l.current.totalQuestions,percentage:v,hasNextLesson:G})}})}},[e.lessonComplete]),se=A.useCallback(()=>{l.current.curriculumCompleted=!0;const v=z.current||{modules:[]};if(c.current.onCurriculumComplete({modules:v.modules.length,totalLessons:v.modules.reduce((b,C)=>b+C.lessons.length,0)}),h.current){if(h.current.setMood("celebrating"),e.curriculumComplete)try{h.current.playAnimation(e.curriculumComplete,!0)}catch{h.current.playCelebration()}const b=H.current||{lipsyncLang:"en"};h.current.speakText("Amazing! You've completed the entire curriculum! You're now ready to move on to more advanced topics. Well done!",{lipsyncLang:b.lipsyncLang})}},[e.curriculumComplete]),S=A.useCallback(()=>{const v=R();l.current.isQuestionMode=!0,l.current.currentQuestionIndex=0,l.current.totalQuestions=v?.questions?.length||0;const b=W();b&&c.current.onCustomAction({type:"questionStart",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,questionIndex:l.current.currentQuestionIndex,totalQuestions:l.current.totalQuestions,question:b});const C=()=>{if(!h.current||!b)return;if(h.current.setMood("curious"),e.questionStart)try{h.current.playAnimation(e.questionStart,!0)}catch(k){console.warn("Failed to play questionStart animation:",k)}const T=H.current||{lipsyncLang:"en"};b.type==="code_test"?h.current.speakText(`Let's test your coding skills! Here's your first challenge: ${b.question}`,{lipsyncLang:T.lipsyncLang}):b.type==="multiple_choice"?h.current.speakText(`Now let me ask you some questions. Here's the first one: ${b.question}`,{lipsyncLang:T.lipsyncLang}):b.type==="true_false"?h.current.speakText(`Let's start with some true or false questions. First question: ${b.question}`,{lipsyncLang:T.lipsyncLang}):h.current.speakText(`Now let me ask you some questions. Here's the first one: ${b.question}`,{lipsyncLang:T.lipsyncLang})};if(h.current&&h.current.isReady&&b)C();else if(h.current&&h.current.isReady){const T=H.current||{lipsyncLang:"en"};h.current.speakText("Now let me ask you some questions to test your understanding.",{lipsyncLang:T.lipsyncLang})}else{const T=setInterval(()=>{h.current&&h.current.isReady&&(clearInterval(T),b&&C())},100);setTimeout(()=>{clearInterval(T)},5e3)}},[e.questionStart,R,W]),B=A.useCallback(()=>{const v=R();if(l.current.currentQuestionIndex<(v?.questions?.length||0)-1){l.current.currentQuestionIndex+=1;const b=W();b&&c.current.onCustomAction({type:"nextQuestion",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,questionIndex:l.current.currentQuestionIndex,totalQuestions:l.current.totalQuestions,question:b});const C=()=>{if(!h.current||!b)return;if(h.current.setMood("happy"),h.current.setBodyMovement("idle"),e.nextQuestion)try{h.current.playAnimation(e.nextQuestion,!0)}catch(k){console.warn("Failed to play nextQuestion animation:",k)}const T=H.current||{lipsyncLang:"en"};b.type==="code_test"?h.current.speakText(`Great! Now let's move on to your next coding challenge: ${b.question}`,{lipsyncLang:T.lipsyncLang}):b.type==="multiple_choice"?h.current.speakText(`Alright! Here's your next question: ${b.question}`,{lipsyncLang:T.lipsyncLang}):b.type==="true_false"?h.current.speakText(`Now let's try this one: ${b.question}`,{lipsyncLang:T.lipsyncLang}):h.current.speakText(`Here's the next question: ${b.question}`,{lipsyncLang:T.lipsyncLang})};if(h.current&&h.current.isReady&&b)C();else if(b){const T=setInterval(()=>{h.current&&h.current.isReady&&(clearInterval(T),C())},100);setTimeout(()=>{clearInterval(T)},5e3)}}else c.current.onCustomAction({type:"allQuestionsComplete",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,totalQuestions:l.current.totalQuestions,score:l.current.score})},[e.nextQuestion,R,W]),N=A.useCallback(()=>{const v=z.current||{modules:[]},b=v.modules[l.current.currentModuleIndex];l.current.currentLessonIndex<(b?.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,c.current.onCustomAction({type:"lessonStart",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex}),c.current.onLessonStart({moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,lesson:R()}),h.current&&(h.current.setMood("happy"),h.current.setBodyMovement("idle"))):l.current.currentModuleIndex<(v.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,c.current.onCustomAction({type:"lessonStart",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex}),c.current.onLessonStart({moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,lesson:R()}),h.current&&(h.current.setMood("happy"),h.current.setBodyMovement("idle"))):I.current&&I.current()},[]),V=A.useCallback(()=>{const v=R();let b=null;if(v?.avatar_script&&v?.body){const C=v.avatar_script.trim(),T=v.body.trim(),k=C.match(/[.!?]$/)?" ":". ";b=`${C}${k}${T}`}else b=v?.avatar_script||v?.body||null;if(h.current&&h.current.isReady&&b){l.current.isTeaching=!0,l.current.isQuestionMode=!1,h.current.setMood("happy");let C=!1;if(e.teaching)try{h.current.playAnimation(e.teaching,!0),C=!0}catch(k){console.warn("Failed to play teaching animation:",k)}C||h.current.setBodyMovement("gesturing");const T=H.current||{lipsyncLang:"en"};c.current.onLessonStart({moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,lesson:v}),c.current.onCustomAction({type:"teachingStart",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,lesson:v}),h.current.speakText(b,{lipsyncLang:T.lipsyncLang,onSpeechEnd:()=>{l.current.isTeaching=!1,c.current.onCustomAction({type:"teachingComplete",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,lesson:v,hasQuestions:v.questions&&v.questions.length>0})}})}},[e.teaching,R]),K=A.useCallback(v=>{const b=W(),C=O(v,b);if(C&&(l.current.score+=1),c.current.onQuestionAnswer({moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,questionIndex:l.current.currentQuestionIndex,answer:v,isCorrect:C,question:b}),h.current)if(C){if(h.current.setMood("happy"),e.correct)try{h.current.playReaction("happy")}catch{h.current.setBodyMovement("happy")}h.current.setBodyMovement("gesturing");const T=b.type==="code_test"?`Great job! Your code passed all the tests! ${b.explanation||""}`:`Excellent! That's correct! ${b.explanation||""}`,k=H.current||{lipsyncLang:"en"};h.current.speakText(T,{lipsyncLang:k.lipsyncLang,onSpeechEnd:()=>{c.current.onCustomAction({type:"answerFeedbackComplete",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,questionIndex:l.current.currentQuestionIndex,isCorrect:!0,hasNextQuestion:l.current.currentQuestionIndex<(R()?.questions?.length||0)-1})}})}else{if(h.current.setMood("sad"),e.incorrect)try{h.current.playAnimation(e.incorrect,!0)}catch{h.current.setBodyMovement("idle")}h.current.setBodyMovement("gesturing");const T=b.type==="code_test"?`Your code didn't pass all the tests. ${b.explanation||"Try again!"}`:`Not quite right, but don't worry! ${b.explanation||""} Let's move on to the next question.`,k=H.current||{lipsyncLang:"en"};h.current.speakText(T,{lipsyncLang:k.lipsyncLang,onSpeechEnd:()=>{c.current.onCustomAction({type:"answerFeedbackComplete",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,questionIndex:l.current.currentQuestionIndex,isCorrect:!1,hasNextQuestion:l.current.currentQuestionIndex<(R()?.questions?.length||0)-1})}})}else c.current.onCustomAction({type:"answerFeedbackComplete",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,questionIndex:l.current.currentQuestionIndex,isCorrect:C,hasNextQuestion:l.current.currentQuestionIndex<(R()?.questions?.length||0)-1,avatarNotReady:!0})},[e.correct,e.incorrect,W,R,O]),J=A.useCallback(v=>{const b=W();if(!v||typeof v!="object"){console.error("Invalid code test result format. Expected object with {passed: boolean, ...}");return}if(b?.type!=="code_test"){console.warn("Current question is not a code test. Use handleAnswerSelect for other question types.");return}const C={passed:v.passed===!0,results:v.results||[],output:v.output||"",error:v.error||null,executionTime:v.executionTime||null,testCount:v.testCount||0,passedCount:v.passedCount||0,failedCount:v.failedCount||0};c.current.onCustomAction({type:"codeTestSubmitted",moduleIndex:l.current.currentModuleIndex,lessonIndex:l.current.currentLessonIndex,questionIndex:l.current.currentQuestionIndex,testResult:C,question:b}),p.current&&p.current(C)},[W,O]),ne=A.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},[]),me=A.useCallback(v=>{console.log("Avatar is ready!",v);const b=R(),C=b?.avatar_script||b?.body;u&&C&&setTimeout(()=>{d.current&&d.current()},10)},[u,R]);A.useLayoutEffect(()=>{d.current=V,g.current=N,y.current=Y,x.current=B,I.current=se,P.current=S,p.current=K}),A.useImperativeHandle(a,()=>({startTeaching:V,startQuestions:S,handleAnswerSelect:K,handleCodeTestResult:J,nextQuestion:B,nextLesson:N,completeLesson:Y,completeCurriculum:se,resetCurriculum:ne,getState:()=>({...l.current}),getCurrentQuestion:()=>W(),getCurrentLesson:()=>R(),getAvatarRef:()=>h.current,speakText:async(v,b={})=>{await h.current?.resumeAudioContext?.();const C=H.current||{lipsyncLang:"en"};h.current?.speakText(v,{...b,lipsyncLang:b.lipsyncLang||C.lipsyncLang})},resumeAudioContext:async()=>{if(h.current?.resumeAudioContext)return await h.current.resumeAudioContext();const v=h.current?.talkingHead;if(v?.audioCtx){const b=v.audioCtx;if(b.state==="suspended"||b.state==="interrupted")try{await b.resume(),console.log("Audio context resumed via talkingHead")}catch(C){console.warn("Failed to resume audio context:",C)}}else console.warn("Audio context not available yet")},stopSpeaking:()=>h.current?.stopSpeaking(),setMood:v=>h.current?.setMood(v),playAnimation:(v,b)=>h.current?.playAnimation(v,b),setBodyMovement:v=>h.current?.setBodyMovement(v),setMovementIntensity:v=>h.current?.setMovementIntensity(v),playRandomDance:()=>h.current?.playRandomDance(),playReaction:v=>h.current?.playReaction(v),playCelebration:()=>h.current?.playCelebration(),setShowFullAvatar:v=>h.current?.setShowFullAvatar(v),setTimingAdjustment:v=>h.current?.setTimingAdjustment(v),lockAvatarPosition:()=>h.current?.lockAvatarPosition(),unlockAvatarPosition:()=>h.current?.unlockAvatarPosition(),triggerCustomAction:(v,b)=>{c.current.onCustomAction({type:v,...b,state:{...l.current}})},handleResize:()=>h.current?.handleResize(),isAvatarReady:()=>h.current?.isReady||!1}),[V,S,K,J,B,N,Y,se,ne,W,R]);const Q=H.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 te.jsx("div",{style:{width:"100%",height:"100%"},children:te.jsx(ge,{ref:h,avatarUrl:Q.avatarUrl,avatarBody:Q.avatarBody,mood:Q.mood,ttsLang:Q.ttsLang,ttsService:Q.ttsService,ttsVoice:Q.ttsVoice,ttsApiKey:Q.ttsApiKey,bodyMovement:Q.bodyMovement,movementIntensity:Q.movementIntensity,showFullAvatar:Q.showFullAvatar,cameraView:"upper",animations:Q.animations,onReady:me,onLoading:()=>{},onError:v=>{console.error("Avatar error:",v)}})})});Se.displayName="CurriculumLearning";const ye={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"}},tt=M=>ye[M]||null,it=M=>ye.hasOwnProperty(M);exports.CurriculumLearning=Se;exports.TalkingHeadAvatar=ge;exports.TalkingHeadComponent=ke;exports.animations=ye;exports.getActiveTTSConfig=ce;exports.getAnimation=tt;exports.getVoiceOptions=et;exports.hasAnimation=it;
|
|
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:n});if(!s.ok)throw new Error(`Azure TTS error: ${s.status} ${s.statusText}`);const o=await s.arrayBuffer(),l=await this.audioCtx.decodeAudioData(o);console.log("Analyzing audio for precise lip-sync...");const u=await this.audioAnalyzer.analyzeAudio(l,e);console.log("Azure TTS Audio Analysis:",{text:e,audioDuration:l.duration,visemeCount:u.visemes.length,wordCount:u.words.length,features:{onsets:u.features.onsets.length,boundaries:u.features.phonemeBoundaries.length}});const a=[];for(let r=0;r<u.visemes.length;r++){const d=u.visemes[r],c=d.startTime*1e3,g=d.duration*1e3,y=d.intensity;a.push({template:{name:"viseme"},ts:[c-Math.min(60,2*g/3),c+Math.min(25,g/2),c+g+Math.min(60,g/2)],vs:{["viseme_"+d.viseme]:[null,y,0]}})}const h=[...t.anim,...a];this.audioPlaylist.push({anim:h,audio:l}),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,l)=>{l>0&&(e+=" <mark name='"+o.mark+"'/>"),e+=o.word.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'").replace(new RegExp("^\\p{Dash_Punctuation}$","ug"),'<break time="750ms"/>')}),e+="</speak>";const i={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"&&(i.headers.Authorization="Bearer "+await this.opt.jwtGet());const n=await fetch(this.opt.ttsEndpoint+(this.opt.ttsApikey?"?key="+this.opt.ttsApikey:""),i),s=await n.json();if(n.status===200&&s&&s.audioContent){const o=this.b64ToArrayBuffer(s.audioContent),l=await this.audioCtx.decodeAudioData(o);this.speakWithHands();const u=[0];let a=0;t.text.forEach((d,c)=>{if(c>0){let g=u[u.length-1];s.timepoints[a]&&(g=s.timepoints[a].timeSeconds*1e3,s.timepoints[a].markName===""+d.mark&&a++),u.push(g)}});const h=[{mark:0,time:0}];u.forEach((d,c)=>{if(c>0){let g=d-u[c-1];h[c-1].duration=g,h.push({mark:c,time:d})}});let r=1e3*l.duration;r>this.opt.ttsTrimEnd&&(r=r-this.opt.ttsTrimEnd),h[h.length-1].duration=r-h[h.length-1].time,t.anim.forEach(d=>{const c=h[d.mark];if(c)for(let g=0;g<d.ts.length;g++)d.ts[g]=c.time+d.ts[g]*c.duration+this.opt.ttsTrimStart}),this.audioPlaylist.push({anim:t.anim,audio:l}),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 i=e.emoji.dt.reduce((n,s)=>n+s,0);this.animQueue.push(this.animFactory(e.emoji)),setTimeout(this.startSpeaking.bind(this),i,!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(i){console.error("Error:",i),this.startSpeaking(!0)}}else e.anim?(this.onSubtitles=e.onSubtitles||null,this.resetLips(),e.mood&&this.setMood(e.mood),e.anim.forEach((i,n)=>{for(let s=0;s<i.ts.length;s++)i.ts[s]=this.animClock+10*n;this.animQueue.push(i)}),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,i=null,n=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=i,this.onMetrics=s,t.sampleRate!==void 0){const l=t.sampleRate;typeof l=="number"&&l>=8e3&&l<=96e3?l!==this.audioCtx.sampleRate&&this.initAudioGraph(l):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 l=this.audioCtx.audioWorklet.addModule(Je.href),u=new Promise((a,h)=>setTimeout(()=>h(new Error("Worklet loading timed out")),5e3));await Promise.race([l,u]),this.workletLoaded=!0}catch(l){throw console.error("Failed to load audio worklet:",l),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=l=>{if(l.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(l.data.type==="playback-ended"&&(this._streamPause(),this.onAudioEnd))try{this.onAudioEnd()}catch{}if(this.onMetrics&&l.data.type==="metrics")try{this.onMetrics(l.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=n||null,this.audioCtx.state==="suspended"||this.audioCtx.state==="interrupted"){const l=this.audioCtx.resume(),u=new Promise((a,h)=>setTimeout(()=>h("p2"),1e3));try{await Promise.race([l,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 i=0;i<t.visemes.length;i++){const n=t.visemes[i],s=e+t.vtimes[i],o=t.vdurations[i],l={template:{name:"viseme"},ts:[s-2*o/3,s+o/2,s+o+o/2],vs:{["viseme_"+n]:[null,n==="PP"||n==="FF"?.9:.6,0]}};this.animQueue.push(l)}if(t.words&&(this.onSubtitles||this.streamLipsyncType=="words"))for(let i=0;i<t.words.length;i++){const n=t.words[i],s=t.wtimes[i];let o=t.wdurations[i];if(n.length&&(this.onSubtitles&&this.animQueue.push({template:{name:"subtitles"},ts:[e+s],vs:{subtitles:[" "+n]}}),this.streamLipsyncType=="words")){const l=this.streamLipsyncLang||this.avatar.lipsyncLang||this.opt.lipsyncLang,u=this.lipsyncPreProcessText(n,l),a=this.lipsyncWordsToVisemes(u,l);if(a&&a.visemes&&a.visemes.length){const h=a.times[a.visemes.length-1]+a.durations[a.visemes.length-1],r=Math.min(o,Math.max(0,o-a.visemes.length*150));let d=.6+this.convertRange(r,[0,o],[0,.4]);if(o=Math.min(o,a.visemes.length*200),h>0)for(let c=0;c<a.visemes.length;c++){const g=e+s+a.times[c]/h*o,y=a.durations[c]/h*o;this.animQueue.push({template:{name:"viseme"},ts:[g-Math.min(60,2*y/3),g+Math.min(25,y/2),g+y+Math.min(60,y/2)],vs:{["viseme_"+a.visemes[c]]:[null,a.visemes[c]==="PP"||a.visemes[c]==="FF"?.9:d,0]}})}}}}if(t.anims&&this.streamLipsyncType=="blendshapes")for(let i=0;i<t.anims.length;i++){let n=t.anims[i];n.delay+=e;let s=this.animFactory(n,!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 i=t.audio.buffer.slice(t.audio.byteOffset,t.audio.byteOffset+t.audio.byteLength);e.data=i,this.streamWorkletNode.port.postMessage(e,[e.data])}else if(t.audio instanceof Float32Array){const i=new Int16Array(t.audio.length);for(let n=0;n<t.audio.length;n++){let s=Math.max(-1,Math.min(1,t.audio[n]));i[n]=s<0?s*32768:s*32767}e.data=i.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,i=(Math.random()-.5)/4,n=this.animQueue.findIndex(o=>o.template.name==="lookat");n!==-1&&this.animQueue.splice(n,1);const s={name:"lookat",dt:[750,t],vs:{bodyRotateX:[e],bodyRotateY:[i],eyesRotateX:[-3*e+.1],eyesRotateY:[-5*i],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),te.setFromMatrixPosition(this.speakTo.objectLeftEye.matrixWorld),ie.setFromMatrixPosition(this.speakTo.objectRightEye.matrixWorld),e.addVectors(te,ie).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),te.setFromMatrixPosition(this.objectLeftEye.matrixWorld),ie.setFromMatrixPosition(this.objectRightEye.matrixWorld),te.add(ie).divideScalar(2),U.copy(this.armature.quaternion),U.multiply(this.poseTarget.props["Hips.quaternion"]),U.multiply(this.poseTarget.props["Spine.quaternion"]),U.multiply(this.poseTarget.props["Spine1.quaternion"]),U.multiply(this.poseTarget.props["Spine2.quaternion"]),U.multiply(this.poseTarget.props["Neck.quaternion"]),U.multiply(this.poseTarget.props["Head.quaternion"]);const i=new f.Vector3().subVectors(e,te).normalize(),n=Math.atan2(i.x,i.z),s=Math.asin(-i.y);F.set(s,n,0,"YXZ");const l=new f.Quaternion().setFromEuler(F),u=new f.Quaternion().copy(l).multiply(U.clone().invert());F.setFromQuaternion(u,"YXZ");let a=F.x/(40/24)+.2,h=F.y/(9/4),r=Math.min(.6,Math.max(-.3,a)),d=Math.min(.8,Math.max(-.8,h)),c=(Math.random()-.5)/4,g=(Math.random()-.5)/4;if(t){let y=this.animQueue.findIndex(L=>L.template.name==="lookat");y!==-1&&this.animQueue.splice(y,1);const x={name:"lookat",dt:[750,t],vs:{bodyRotateX:[r+c],bodyRotateY:[d+g],eyesRotateX:[-3*c+.1],eyesRotateY:[-5*g],browInnerUp:[[0,.7]],mouthLeft:[[0,.7]],mouthRight:[[0,.7]],eyeContact:[0],headMove:[0]}};this.animQueue.push(this.animFactory(x))}}lookAt(t,e,i){if(!this.camera)return;const n=this.nodeAvatar.getBoundingClientRect();this.objectLeftEye.updateMatrixWorld(!0),this.objectRightEye.updateMatrixWorld(!0);const s=new f.Vector3().setFromMatrixPosition(this.objectLeftEye.matrixWorld),o=new f.Vector3().setFromMatrixPosition(this.objectRightEye.matrixWorld),l=new f.Vector3().addVectors(s,o).divideScalar(2);l.project(this.camera);let u=(l.x+1)/2*n.width+n.left,a=-(l.y-1)/2*n.height+n.top;t===null&&(t=u),e===null&&(e=a),U.copy(this.armature.quaternion),U.multiply(this.poseTarget.props["Hips.quaternion"]),U.multiply(this.poseTarget.props["Spine.quaternion"]),U.multiply(this.poseTarget.props["Spine1.quaternion"]),U.multiply(this.poseTarget.props["Spine2.quaternion"]),U.multiply(this.poseTarget.props["Neck.quaternion"]),U.multiply(this.poseTarget.props["Head.quaternion"]),F.setFromQuaternion(U);let h=F.x/(40/24),r=F.y/(9/4),d=Math.min(.4,Math.max(-.4,this.camera.rotation.x)),c=Math.min(.4,Math.max(-.4,this.camera.rotation.y)),g=Math.max(window.innerWidth-u,u),y=Math.max(window.innerHeight-a,a),x=this.convertRange(e,[a-y,a+y],[-.3,.6])-h+d,L=this.convertRange(t,[u-g,u+g],[-.8,.8])-r+c;x=Math.min(.6,Math.max(-.3,x)),L=Math.min(.8,Math.max(-.8,L));let P=(Math.random()-.5)/4,p=(Math.random()-.5)/4;if(i){let T=this.animQueue.findIndex(I=>I.template.name==="lookat");T!==-1&&this.animQueue.splice(T,1);const M={name:"lookat",dt:[750,i],vs:{bodyRotateX:[x+P],bodyRotateY:[L+p],eyesRotateX:[-3*P+.1],eyesRotateY:[-5*p],browInnerUp:[[0,.7]],mouthLeft:[[0,.7]],mouthRight:[[0,.7]],eyeContact:[0],headMove:[0]}};this.animQueue.push(this.animFactory(M))}}touchAt(t,e){if(!this.camera)return;const i=this.nodeAvatar.getBoundingClientRect(),n=new f.Vector2((t-i.left)/i.width*2-1,-((e-i.top)/i.height)*2+1),s=new f.Raycaster;s.setFromCamera(n,this.camera);const o=s.intersectObject(this.armature);if(o.length>0){const l=o[0].point,u=new f.Vector3,a=new f.Vector3;this.objectLeftArm.getWorldPosition(u),this.objectRightArm.getWorldPosition(a);const h=u.distanceToSquared(l),r=a.distanceToSquared(l);h<r?(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}]},l,!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}]},l,!1,1e3),this.setValue("handFistRight",0))}else["LeftArm","LeftForeArm","LeftHand","RightArm","RightForeArm","RightHand"].forEach(l=>{let u=l+".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 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 i=[],n=[];i.push(100+Math.round(Math.random()*500)),n.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(o=>{n[0].props[o+".quaternion"]=this.ikMesh.getObjectByName(o).quaternion.clone()}),i.push(1e3+Math.round(Math.random()*500)),n.push({duration:2e3,props:{}}),["LeftArm","LeftForeArm","RightArm","RightForeArm","LeftHand","RightHand"].forEach(o=>{n[1].props[o+".quaternion"]=null});const s=this.animFactory({name:"talkinghands",delay:t,dt:i,vs:{moveto:n}});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={},i=null){this.listeningAnalyzer=t,this.listeningAnalyzer.fftSize=256,this.listeningAnalyzer.smoothingTimeConstant=.1,this.listeningAnalyzer.minDecibels=-70,this.listeningAnalyzer.maxDecibels=-10,this.listeningOnchange=i&&typeof i=="function"?i: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,i=10,n=0,s=.01,o=!1){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 l=this.animClips.find(u=>u.url===t+"-"+n);if(l){let u=this.animQueue.find(r=>r.template.name==="pose");u&&(u.ts[0]=1/0),Object.entries(l.pose.props).forEach(r=>{this.poseBase.props[r[0]]=r[1].clone(),this.poseTarget.props[r[0]]=r[1].clone(),this.poseTarget.props[r[0]].t=0,this.poseTarget.props[r[0]].d=1e3}),this.mixer?console.log("Using existing mixer for FBX animation, preserving morph targets"):(this.mixer=new f.AnimationMixer(this.armature),console.log("Created new mixer for FBX animation")),this.mixer.addEventListener("finished",this.stopAnimation.bind(this),{once:!0});const a=Math.ceil(i/l.clip.duration),h=this.mixer.clipAction(l.clip);h.setLoop(f.LoopRepeat,a),h.clampWhenFinished=!0,this.currentFBXAction=h;try{h.fadeIn(.5).play(),console.log("FBX animation started successfully:",t)}catch(r){console.warn("FBX animation failed to start:",r),this.stopAnimation();return}if(h.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 a=!1;try{const d=await fetch(t,{method:"HEAD"});if(a=d.ok,!a){console.error(`FBX file not found at ${t}. Status: ${d.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(d){console.warn(`Could not verify file existence for ${t}, attempting to load anyway:`,d)}const h=new be.FBXLoader;let r;try{r=await h.loadAsync(t,e)}catch(d){console.error(`Failed to load FBX animation from ${t}:`,d),console.error("Error details:",{message:d.message,url:t,suggestion:"Make sure the file is a valid FBX file and the path is correct"}),d.message&&d.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 c=await fetch(t),g=c.headers.get("content-type"),y=await c.text();console.error("Response details:",{status:c.status,contentType:g,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(c){console.error("Could not fetch file for debugging:",c)}return}if(r&&r.animations&&r.animations[n]){let d=r.animations[n];const c={};d.tracks.forEach(y=>{y.name=y.name.replaceAll("mixamorig","");const x=y.name.split(".");if(x[1]==="position"){for(let L=0;L<y.values.length;L++)y.values[L]=y.values[L]*s;c[y.name]=new f.Vector3(y.values[0],y.values[1],y.values[2])}else x[1]==="quaternion"?c[y.name]=new f.Quaternion(y.values[0],y.values[1],y.values[2],y.values[3]):x[1]==="rotation"&&(c[x[0]+".quaternion"]=new f.Quaternion().setFromEuler(new f.Euler(y.values[0],y.values[1],y.values[2],"XYZ")).normalize())});const g={props:c};c["Hips.position"]&&(c["Hips.position"].y<.5?g.lying=!0:g.standing=!0),this.animClips.push({url:t+"-"+n,clip:d,pose:g}),this.playAnimation(t,e,i,n,s)}else{const d="Animation "+t+" (ndx="+n+") not found";console.error(d),r&&r.animations?console.error(`FBX file loaded but has ${r.animations.length} animation(s), requested index ${n}`):console.error(r?"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,i]of Object.entries(this.gesture))i.t=this.animClock,i.d=1e3,this.poseTarget.props.hasOwnProperty(e)&&(this.poseTarget.props[e].copy(i),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,i=5,n=0,s=.01){if(!this.armature)return;let o=this.poseTemplates[t];if(!o){const l=this.animPoses.find(u=>u.url===t+"-"+n);l&&(o=l.pose)}if(o){this.poseName=t,this.mixer=null;let l=this.animQueue.find(u=>u.template.name==="pose");l&&(l.ts[0]=this.animClock+i*1e3+2e3),this.setPoseFromTemplate(o)}else{let u=await new be.FBXLoader().loadAsync(t,e);if(u&&u.animations&&u.animations[n]){let a=u.animations[n];const h={};a.tracks.forEach(d=>{d.name=d.name.replaceAll("mixamorig","");const c=d.name.split(".");c[1]==="position"?h[d.name]=new f.Vector3(d.values[0]*s,d.values[1]*s,d.values[2]*s):c[1]==="quaternion"?h[d.name]=new f.Quaternion(d.values[0],d.values[1],d.values[2],d.values[3]):c[1]==="rotation"&&(h[c[0]+".quaternion"]=new f.Quaternion().setFromEuler(new f.Euler(d.values[0],d.values[1],d.values[2],"XYZ")).normalize())});const r={props:h};h["Hips.position"]&&(h["Hips.position"].y<.5?r.lying=!0:r.standing=!0),this.animPoses.push({url:t+"-"+n,pose:r}),this.playPose(t,e,i,n,s)}else{const a="Pose "+t+" (ndx="+n+") not found";console.error(a)}}}stopPose(){this.stopAnimation()}playGesture(t,e=3,i=!1,n=1e3){if(!this.armature)return;let s=this.gestureTemplates[t];if(s){this.gestureTimeout&&(clearTimeout(this.gestureTimeout),this.gestureTimeout=null);let l=this.animQueue.findIndex(u=>u.template.name==="talkinghands");l!==-1&&(this.animQueue[l].ts=this.animQueue[l].ts.map(u=>0)),this.gesture=this.propsToThreeObjects(s),i&&(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[u,a]of Object.entries(this.gesture))a.t=this.animClock,a.d=n,this.poseTarget.props.hasOwnProperty(u)&&(this.poseTarget.props[u].copy(a),this.poseTarget.props[u].t=this.animClock,this.poseTarget.props[u].d=n);e&&Number.isFinite(e)&&(this.gestureTimeout=setTimeout(this.stopGesture.bind(this,n),1e3*e))}let o=this.animEmojis[t];if(o&&(o&&o.link&&(o=this.animEmojis[o.link]),o)){this.lookAtCamera(500);const l=this.animFactory(o);if(l.gesture=!0,e&&Number.isFinite(e)){const u=l.ts[0],h=l.ts[l.ts.length-1]-u;if(e*1e3-h>0){const d=[];for(let y=1;y<l.ts.length;y++)d.push(l.ts[y]-l.ts[y-1]);const c=o.template?.rescale||d.map(y=>y/h),g=e*1e3-h;l.ts=l.ts.map((y,x,L)=>x===0?u:L[x-1]+d[x-1]+c[x-1]*g)}else{const d=e*1e3/h;l.ts=l.ts.map(c=>u+d*(c-u))}}this.animQueue.push(l)}}stopGesture(t=1e3){if(this.gestureTimeout&&(clearTimeout(this.gestureTimeout),this.gestureTimeout=null),this.gesture){const i=Object.entries(this.gesture);this.gesture=null;for(const[n,s]of i)this.poseTarget.props.hasOwnProperty(n)&&(this.poseTarget.props[n].copy(this.getPoseTemplateProp(n)),this.poseTarget.props[n].t=this.animClock,this.poseTarget.props[n].d=t)}let e=this.animQueue.findIndex(i=>i.gesture);e!==-1&&this.animQueue.splice(e,1)}ikSolve(t,e=null,i=!1,n=null){const s=new f.Vector3,o=new f.Vector3,l=new f.Vector3,u=new f.Vector3,a=new f.Quaternion,h=new f.Vector3,r=new f.Vector3,d=new f.Vector3,c=this.ikMesh.getObjectByName(t.root);c.position.setFromMatrixPosition(this.armature.getObjectByName(t.root).matrixWorld),c.quaternion.setFromRotationMatrix(this.armature.getObjectByName(t.root).matrixWorld),e&&i&&e.applyQuaternion(this.armature.quaternion).add(c.position);const g=this.ikMesh.getObjectByName(t.effector),y=t.links;y.forEach(L=>{L.bone=this.ikMesh.getObjectByName(L.link),L.bone.quaternion.copy(this.getPoseTemplateProp(L.link+".quaternion"))}),c.updateMatrixWorld(!0);const x=t.iterations||10;if(e)for(let L=0;L<x;L++){let P=!1;for(let p=0,T=y.length;p<T;p++){const M=y[p].bone;M.matrixWorld.decompose(u,a,h),a.invert(),o.setFromMatrixPosition(g.matrixWorld),l.subVectors(o,u),l.applyQuaternion(a),l.normalize(),s.subVectors(e,u),s.applyQuaternion(a),s.normalize();let I=s.dot(l);I>1?I=1:I<-1&&(I=-1),I=Math.acos(I),!(I<1e-5)&&(y[p].minAngle!==void 0&&I<y[p].minAngle&&(I=y[p].minAngle),y[p].maxAngle!==void 0&&I>y[p].maxAngle&&(I=y[p].maxAngle),r.crossVectors(l,s),r.normalize(),U.setFromAxisAngle(r,I),M.quaternion.multiply(U),M.rotation.setFromVector3(d.setFromEuler(M.rotation).clamp(new f.Vector3(y[p].minx!==void 0?y[p].minx:-1/0,y[p].miny!==void 0?y[p].miny:-1/0,y[p].minz!==void 0?y[p].minz:-1/0),new f.Vector3(y[p].maxx!==void 0?y[p].maxx:1/0,y[p].maxy!==void 0?y[p].maxy:1/0,y[p].maxz!==void 0?y[p].maxz:1/0))),M.updateMatrixWorld(!0),P=!0)}if(!P)break}n&&y.forEach(L=>{this.poseTarget.props[L.link+".quaternion"].copy(L.bone.quaternion),this.poseTarget.props[L.link+".quaternion"].t=this.animClock,this.poseTarget.props[L.link+".quaternion"].d=n})}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"}},Le={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 de(){return{service:"elevenlabs",endpoint:se.endpoint,apiKey:se.apiKey,defaultVoice:se.defaultVoice,voices:se.voices}}function et(){const E=de(),t=[];return Object.entries(E.voices).forEach(([e,i])=>{t.push({value:i,label:`${e.charAt(0).toUpperCase()+e.slice(1)} (${E.service})`})}),t}const ye=A.forwardRef(({avatarUrl:E="/avatars/brunette.glb",avatarBody:t="F",mood:e="neutral",ttsLang:i="en",ttsService:n=null,ttsVoice:s=null,ttsApiKey:o=null,bodyMovement:l="idle",movementIntensity:u=.5,showFullAvatar:a=!0,cameraView:h="upper",onReady:r=()=>{},onLoading:d=()=>{},onError:c=()=>{},className:g="",style:y={},animations:x={}},L)=>{const P=A.useRef(null),p=A.useRef(null),T=A.useRef(a),[M,I]=A.useState(!0),[D,O]=A.useState(null),[X,ne]=A.useState(!1);A.useEffect(()=>{T.current=a},[a]);const S=de(),B=n||S.service;let N;B==="browser"?N={service:"browser",endpoint:"",apiKey:null,defaultVoice:"Google US English"}:B==="elevenlabs"?N={service:"elevenlabs",endpoint:"https://api.elevenlabs.io/v1/text-to-speech",apiKey:o||S.apiKey,defaultVoice:s||S.defaultVoice||se.defaultVoice,voices:S.voices||se.voices}:B==="deepgram"?N={service:"deepgram",endpoint:"https://api.deepgram.com/v1/speak",apiKey:o||S.apiKey,defaultVoice:s||S.defaultVoice||Le.defaultVoice,voices:S.voices||Le.voices}:N={...S,apiKey:o!==null?o:S.apiKey};const W={url:E,body:t,avatarMood:e,ttsLang:B==="browser"?"en-US":i,ttsVoice:s||N.defaultVoice,lipsyncLang:"en",showFullAvatar:a,bodyMovement:l,movementIntensity:u},q={ttsEndpoint:N.endpoint,ttsApikey:N.apiKey,ttsService:B,lipsyncModules:["en"],cameraView:h},_=A.useCallback(async()=>{if(!(!P.current||p.current))try{if(I(!0),O(null),p.current=new Ae(P.current,q),p.current.controls&&(p.current.controls.enableRotate=!1,p.current.controls.enableZoom=!1,p.current.controls.enablePan=!1,p.current.controls.enableDamping=!1),x&&Object.keys(x).length>0&&(p.current.customAnimations=x),await p.current.showAvatar(W,z=>{if(z.lengthComputable){const H=Math.min(100,Math.round(z.loaded/z.total*100));d(H)}}),await new Promise(z=>{const H=()=>{p.current.lipsync&&Object.keys(p.current.lipsync).length>0?z():setTimeout(H,100)};H()}),p.current&&p.current.setShowFullAvatar)try{p.current.setShowFullAvatar(a)}catch(z){console.warn("Error setting full body mode on initialization:",z)}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()),I(!1),ne(!0),r(p.current);const w=()=>{document.visibilityState==="visible"?p.current?.start():p.current?.stop()};return document.addEventListener("visibilitychange",w),()=>{document.removeEventListener("visibilitychange",w)}}catch(R){console.error("Error initializing TalkingHead:",R),O(R.message||"Failed to initialize avatar"),I(!1),c(R)}},[E,t,e,i,n,s,o,a,l,u,h]);A.useEffect(()=>(_(),()=>{p.current&&(p.current.stop(),p.current.dispose(),p.current=null)}),[_]),A.useEffect(()=>{if(!P.current||!p.current)return;const R=new ResizeObserver(z=>{for(const H of z)p.current&&p.current.onResize&&p.current.onResize()});R.observe(P.current);const w=()=>{p.current&&p.current.onResize&&p.current.onResize()};return window.addEventListener("resize",w),()=>{R.disconnect(),window.removeEventListener("resize",w)}},[X]);const oe=A.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(R){console.warn("Failed to resume audio context:",R)}},[]),ce=A.useCallback(async(R,w={})=>{if(p.current&&X)try{await oe();const z={...w,lipsyncLang:w.lipsyncLang||W.lipsyncLang||"en"};if(w.onSpeechEnd&&p.current){const H=p.current;let V=null,K=0;const pe=1200;let ae=!1;V=setInterval(()=>{if(K++,K>pe){if(V&&(clearInterval(V),V=null),!ae){ae=!0;try{w.onSpeechEnd()}catch(xe){console.error("Error in onSpeechEnd callback (timeout):",xe)}}return}const we=!H.speechQueue||H.speechQueue.length===0,Ce=!H.audioPlaylist||H.audioPlaylist.length===0;H&&H.isSpeaking===!1&&we&&Ce&&H.isAudioPlaying===!1&&!ae&&setTimeout(()=>{if(H&&H.isSpeaking===!1&&(!H.speechQueue||H.speechQueue.length===0)&&(!H.audioPlaylist||H.audioPlaylist.length===0)&&H.isAudioPlaying===!1&&!ae){ae=!0,V&&(clearInterval(V),V=null);try{w.onSpeechEnd()}catch(ze){console.error("Error in onSpeechEnd callback:",ze)}}},100)},100)}p.current.lipsync&&Object.keys(p.current.lipsync).length>0?(p.current.setSlowdownRate&&p.current.setSlowdownRate(1.05),p.current.speakText(R,z)):setTimeout(async()=>{await oe(),p.current&&p.current.lipsync&&(p.current.setSlowdownRate&&p.current.setSlowdownRate(1.05),p.current.speakText(R,z))},100)}catch(z){console.error("Error speaking text:",z),O(z.message||"Failed to speak text")}},[X,oe,W.lipsyncLang]),re=A.useCallback(()=>{p.current&&(p.current.stopSpeaking(),p.current.setSlowdownRate&&p.current.setSlowdownRate(1))},[]),me=A.useCallback(R=>{p.current&&p.current.setMood(R)},[]),j=A.useCallback(R=>{p.current&&p.current.setSlowdownRate&&p.current.setSlowdownRate(R)},[]),b=A.useCallback((R,w=!1)=>{if(p.current&&p.current.playAnimation){if(x&&x[R]&&(R=x[R]),p.current.setShowFullAvatar)try{p.current.setShowFullAvatar(T.current)}catch(H){console.warn("Error setting full body mode:",H)}if(R.includes("."))try{p.current.playAnimation(R,null,10,0,.01,w)}catch(H){console.warn(`Failed to play ${R}:`,H);try{p.current.setBodyMovement("idle")}catch(V){console.warn("Fallback animation also failed:",V)}}else{const H=[".fbx",".glb",".gltf"];let V=!1;for(const K of H)try{p.current.playAnimation(R+K,null,10,0,.01,w),V=!0;break}catch{}if(!V){console.warn("Animation not found:",R);try{p.current.setBodyMovement("idle")}catch(K){console.warn("Fallback animation also failed:",K)}}}}},[x]),v=A.useCallback(()=>{p.current&&p.current.onResize&&p.current.onResize()},[]);return A.useImperativeHandle(L,()=>({speakText:ce,stopSpeaking:re,resumeAudioContext:oe,setMood:me,setTimingAdjustment:j,playAnimation:b,isReady:X,talkingHead:p.current,handleResize:v,setBodyMovement:R=>{if(p.current&&p.current.setShowFullAvatar&&p.current.setBodyMovement)try{p.current.setShowFullAvatar(T.current),p.current.setBodyMovement(R)}catch(w){console.warn("Error setting body movement:",w)}},setMovementIntensity:R=>p.current?.setMovementIntensity(R),playRandomDance:()=>{if(p.current&&p.current.setShowFullAvatar&&p.current.playRandomDance)try{p.current.setShowFullAvatar(T.current),p.current.playRandomDance()}catch(R){console.warn("Error playing random dance:",R)}},playReaction:R=>{if(p.current&&p.current.setShowFullAvatar&&p.current.playReaction)try{p.current.setShowFullAvatar(T.current),p.current.playReaction(R)}catch(w){console.warn("Error playing reaction:",w)}},playCelebration:()=>{if(p.current&&p.current.setShowFullAvatar&&p.current.playCelebration)try{p.current.setShowFullAvatar(T.current),p.current.playCelebration()}catch(R){console.warn("Error playing celebration:",R)}},setShowFullAvatar:R=>{if(p.current&&p.current.setShowFullAvatar)try{T.current=R,p.current.setShowFullAvatar(R)}catch(w){console.warn("Error setting showFullAvatar:",w)}},lockAvatarPosition:()=>{if(p.current&&p.current.lockAvatarPosition)try{p.current.lockAvatarPosition()}catch(R){console.warn("Error locking avatar position:",R)}},unlockAvatarPosition:()=>{if(p.current&&p.current.unlockAvatarPosition)try{p.current.unlockAvatarPosition()}catch(R){console.warn("Error unlocking avatar position:",R)}}})),ee.jsxs("div",{className:`talking-head-avatar ${g}`,style:{width:"100%",height:"100%",position:"relative",...y},children:[ee.jsx("div",{ref:P,className:"talking-head-viewer",style:{width:"100%",height:"100%",minHeight:"400px"}}),M&&ee.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&&ee.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="TalkingHeadAvatar";const ke=A.forwardRef(({text:E="Hello! I'm a talking avatar. How are you today?",onLoading:t=()=>{},onError:e=()=>{},onReady:i=()=>{},className:n="",style:s={},avatarConfig:o={}},l)=>{const u=A.useRef(null),a=A.useRef(null),[h,r]=A.useState(!0),[d,c]=A.useState(null),[g,y]=A.useState(!1),x=de(),L=o.ttsService||x.service,P=L==="browser"?{endpoint:"",apiKey:null,defaultVoice:"Google US English"}:{...x,apiKey:o.ttsApiKey!==void 0&&o.ttsApiKey!==null?o.ttsApiKey:x.apiKey,endpoint:L==="elevenlabs"&&o.ttsApiKey?"https://api.elevenlabs.io/v1/text-to-speech":x.endpoint},p={url:"/avatars/brunette.glb",body:"F",avatarMood:"neutral",ttsLang:L==="browser"?"en-US":"en",ttsVoice:o.ttsVoice||P.defaultVoice,lipsyncLang:"en",showFullAvatar:!0,bodyMovement:"idle",movementIntensity:.5,...o},T={ttsEndpoint:P.endpoint,ttsApikey:P.apiKey,ttsService:L,lipsyncModules:["en"],cameraView:"upper"},M=A.useCallback(async()=>{if(!(!u.current||a.current))try{if(r(!0),c(null),a.current=new Ae(u.current,T),await a.current.showAvatar(p,N=>{if(N.lengthComputable){const W=Math.min(100,Math.round(N.loaded/N.total*100));t(W)}}),a.current.morphs&&a.current.morphs.length>0){const N=a.current.morphs[0].morphTargetDictionary;console.log("Available morph targets:",Object.keys(N));const W=Object.keys(N).filter(q=>q.startsWith("viseme_"));console.log("Viseme morph targets found:",W),W.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 W=()=>{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(W,100))};W()}),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)}r(!1),y(!0),i(a.current);const B=()=>{document.visibilityState==="visible"?a.current?.start():a.current?.stop()};return document.addEventListener("visibilitychange",B),()=>{document.removeEventListener("visibilitychange",B)}}catch(S){console.error("Error initializing TalkingHead:",S),c(S.message||"Failed to initialize avatar"),r(!1),e(S)}},[]);A.useEffect(()=>(M(),()=>{a.current&&(a.current.stop(),a.current.dispose(),a.current=null)}),[M]);const I=A.useCallback(S=>{if(a.current&&g)try{console.log("Speaking text:",S),console.log("Avatar config:",p),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(S)):(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(S)):console.error("Lip-sync still not ready after waiting")},500))}catch(B){console.error("Error speaking text:",B),c(B.message||"Failed to speak text")}else console.warn("Avatar not ready for speaking. isReady:",g,"talkingHeadRef:",!!a.current)},[g,p]),D=A.useCallback(()=>{a.current&&(a.current.stopSpeaking(),a.current.setSlowdownRate&&(a.current.setSlowdownRate(1),console.log("Reset timing to normal")))},[]),O=A.useCallback(S=>{a.current&&a.current.setMood(S)},[]),X=A.useCallback(S=>{a.current&&a.current.setSlowdownRate&&(a.current.setSlowdownRate(S),console.log("Timing adjustment set to:",S))},[]),ne=A.useCallback((S,B=!1)=>{if(a.current&&a.current.playAnimation){if(a.current.setShowFullAvatar)try{a.current.setShowFullAvatar(!0)}catch(W){console.warn("Error setting full body mode:",W)}if(S.includes("."))try{a.current.playAnimation(S,null,10,0,.01,B),console.log("Playing animation:",S)}catch(W){console.log(`Failed to play ${S}:`,W);try{a.current.setBodyMovement("idle"),console.log("Fallback to idle animation")}catch(q){console.warn("Fallback animation also failed:",q)}}else{const W=[".fbx",".glb",".gltf"];let q=!1;for(const _ of W)try{a.current.playAnimation(S+_,null,10,0,.01,B),console.log("Playing animation:",S+_),q=!0;break}catch{console.log(`Failed to play ${S}${_}, trying next format...`)}if(!q){console.warn("Animation system not available or animation not found:",S);try{a.current.setBodyMovement("idle"),console.log("Fallback to idle animation")}catch(_){console.warn("Fallback animation also failed:",_)}}}}else console.warn("Animation system not available or animation not found:",S)},[]);return A.useImperativeHandle(l,()=>({speakText:I,stopSpeaking:D,setMood:O,setTimingAdjustment:X,playAnimation:ne,isReady:g,talkingHead:a.current,setBodyMovement:S=>{if(a.current&&a.current.setShowFullAvatar&&a.current.setBodyMovement)try{a.current.setShowFullAvatar(!0),a.current.setBodyMovement(S),console.log("Body movement set with full body mode:",S)}catch(B){console.warn("Error setting body movement:",B)}},setMovementIntensity:S=>a.current?.setMovementIntensity(S),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(S){console.warn("Error playing random dance:",S)}},playReaction:S=>{if(a.current&&a.current.setShowFullAvatar&&a.current.playReaction)try{a.current.setShowFullAvatar(!0),a.current.playReaction(S),console.log("Reaction played with full body mode:",S)}catch(B){console.warn("Error playing reaction:",B)}},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(S){console.warn("Error playing celebration:",S)}},setShowFullAvatar:S=>{if(a.current&&a.current.setShowFullAvatar)try{a.current.setShowFullAvatar(S),console.log("Show full avatar set to:",S)}catch(B){console.warn("Error setting showFullAvatar:",B)}},lockAvatarPosition:()=>{if(a.current&&a.current.lockAvatarPosition)try{a.current.lockAvatarPosition()}catch(S){console.warn("Error locking avatar position:",S)}},unlockAvatarPosition:()=>{if(a.current&&a.current.unlockAvatarPosition)try{a.current.unlockAvatarPosition()}catch(S){console.warn("Error unlocking avatar position:",S)}}})),ee.jsxs("div",{className:`talking-head-container ${n}`,style:s,children:[ee.jsx("div",{ref:u,className:"talking-head-viewer",style:{width:"100%",height:"100%",minHeight:"400px"}}),h&&ee.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&&ee.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})]})});ke.displayName="TalkingHeadComponent";const Se=A.forwardRef(({curriculumData:E=null,avatarConfig:t={},animations:e={},onLessonStart:i=()=>{},onLessonComplete:n=()=>{},onQuestionAnswer:s=()=>{},onCurriculumComplete:o=()=>{},onCustomAction:l=()=>{},autoStart:u=!1},a)=>{const h=A.useRef(null),r=A.useRef({currentModuleIndex:0,currentLessonIndex:0,currentQuestionIndex:0,isTeaching:!1,isQuestionMode:!1,lessonCompleted:!1,curriculumCompleted:!1,score:0,totalQuestions:0}),d=A.useRef({onLessonStart:i,onLessonComplete:n,onQuestionAnswer:s,onCurriculumComplete:o,onCustomAction:l}),c=A.useRef(null),g=A.useRef(null),y=A.useRef(null),x=A.useRef(null),L=A.useRef(null),P=A.useRef(null),p=A.useRef(null),T=A.useRef(E?.curriculum||{title:"Default Curriculum",description:"No curriculum data provided",language:"en",modules:[]}),M=A.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"});A.useEffect(()=>{d.current={onLessonStart:i,onLessonComplete:n,onQuestionAnswer:s,onCurriculumComplete:o,onCustomAction:l}},[i,n,s,o,l]),A.useEffect(()=>{T.current=E?.curriculum||{title:"Default Curriculum",description:"No curriculum data provided",language:"en",modules:[]},M.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"}},[E,t,e]);const I=A.useCallback(()=>(T.current||{modules:[]}).modules[r.current.currentModuleIndex]?.lessons[r.current.currentLessonIndex],[]),D=A.useCallback(()=>I()?.questions[r.current.currentQuestionIndex],[I]),O=A.useCallback((b,v)=>v.type==="multiple_choice"||v.type==="true_false"?b===v.answer:v.type==="code_test"&&typeof b=="object"&&b!==null?b.passed===!0:!1,[]),X=A.useCallback(()=>{r.current.lessonCompleted=!0,r.current.isQuestionMode=!1;const b=r.current.totalQuestions>0?Math.round(r.current.score/r.current.totalQuestions*100):100;let v="Congratulations! You've completed this lesson";if(r.current.totalQuestions>0?v+=` with a score of ${r.current.score} out of ${r.current.totalQuestions} (${b}%). `:v+="! ",b>=80?v+="Excellent work! You have a great understanding of this topic.":b>=60?v+="Good job! You understand most of the concepts.":v+="Keep practicing! You're making progress.",d.current.onLessonComplete({moduleIndex:r.current.currentModuleIndex,lessonIndex:r.current.currentLessonIndex,score:r.current.score,totalQuestions:r.current.totalQuestions,percentage:b}),d.current.onCustomAction({type:"lessonComplete",moduleIndex:r.current.currentModuleIndex,lessonIndex:r.current.currentLessonIndex,score:r.current.score,totalQuestions:r.current.totalQuestions,percentage:b}),h.current){if(h.current.setMood("happy"),e.lessonComplete)try{h.current.playAnimation(e.lessonComplete,!0)}catch{h.current.playCelebration()}const R=T.current||{modules:[]},w=R.modules[r.current.currentModuleIndex],z=r.current.currentLessonIndex<(w?.lessons?.length||0)-1,H=r.current.currentModuleIndex<(R.modules?.length||0)-1,V=z||H,K=M.current||{lipsyncLang:"en"};h.current.speakText(v,{lipsyncLang:K.lipsyncLang,onSpeechEnd:()=>{d.current.onCustomAction({type:"lessonCompleteFeedbackDone",moduleIndex:r.current.currentModuleIndex,lessonIndex:r.current.currentLessonIndex,score:r.current.score,totalQuestions:r.current.totalQuestions,percentage:b,hasNextLesson:V})}})}},[e.lessonComplete]),ne=A.useCallback(()=>{r.current.curriculumCompleted=!0;const b=T.current||{modules:[]};if(d.current.onCurriculumComplete({modules:b.modules.length,totalLessons:b.modules.reduce((v,R)=>v+R.lessons.length,0)}),h.current){if(h.current.setMood("celebrating"),e.curriculumComplete)try{h.current.playAnimation(e.curriculumComplete,!0)}catch{h.current.playCelebration()}const v=M.current||{lipsyncLang:"en"};h.current.speakText("Amazing! You've completed the entire curriculum! You're now ready to move on to more advanced topics. Well done!",{lipsyncLang:v.lipsyncLang})}},[e.curriculumComplete]),S=A.useCallback(()=>{const b=I();r.current.isQuestionMode=!0,r.current.currentQuestionIndex=0,r.current.totalQuestions=b?.questions?.length||0;const v=D();v&&d.current.onCustomAction({type:"questionStart",moduleIndex:r.current.currentModuleIndex,lessonIndex:r.current.currentLessonIndex,questionIndex:r.current.currentQuestionIndex,totalQuestions:r.current.totalQuestions,question:v});const R=()=>{if(!h.current||!v)return;if(h.current.setMood("happy"),e.questionStart)try{h.current.playAnimation(e.questionStart,!0)}catch(z){console.warn("Failed to play questionStart animation:",z)}const w=M.current||{lipsyncLang:"en"};v.type==="code_test"?h.current.speakText(`Let's test your coding skills! Here's your first challenge: ${v.question}`,{lipsyncLang:w.lipsyncLang}):v.type==="multiple_choice"?h.current.speakText(`Now let me ask you some questions. Here's the first one: ${v.question}`,{lipsyncLang:w.lipsyncLang}):v.type==="true_false"?h.current.speakText(`Let's start with some true or false questions. First question: ${v.question}`,{lipsyncLang:w.lipsyncLang}):h.current.speakText(`Now let me ask you some questions. Here's the first one: ${v.question}`,{lipsyncLang:w.lipsyncLang})};if(h.current&&h.current.isReady&&v)R();else if(h.current&&h.current.isReady){const w=M.current||{lipsyncLang:"en"};h.current.speakText("Now let me ask you some questions to test your understanding.",{lipsyncLang:w.lipsyncLang})}else{const w=setInterval(()=>{h.current&&h.current.isReady&&(clearInterval(w),v&&R())},100);setTimeout(()=>{clearInterval(w)},5e3)}},[e.questionStart,I,D]),B=A.useCallback(()=>{const b=I();if(r.current.currentQuestionIndex<(b?.questions?.length||0)-1){r.current.currentQuestionIndex+=1;const v=D();v&&d.current.onCustomAction({type:"nextQuestion",moduleIndex:r.current.currentModuleIndex,lessonIndex:r.current.currentLessonIndex,questionIndex:r.current.currentQuestionIndex,totalQuestions:r.current.totalQuestions,question:v});const R=()=>{if(!h.current||!v)return;if(h.current.setMood("happy"),h.current.setBodyMovement("idle"),e.nextQuestion)try{h.current.playAnimation(e.nextQuestion,!0)}catch(z){console.warn("Failed to play nextQuestion animation:",z)}const w=M.current||{lipsyncLang:"en"};v.type==="code_test"?h.current.speakText(`Great! Now let's move on to your next coding challenge: ${v.question}`,{lipsyncLang:w.lipsyncLang}):v.type==="multiple_choice"?h.current.speakText(`Alright! Here's your next question: ${v.question}`,{lipsyncLang:w.lipsyncLang}):v.type==="true_false"?h.current.speakText(`Now let's try this one: ${v.question}`,{lipsyncLang:w.lipsyncLang}):h.current.speakText(`Here's the next question: ${v.question}`,{lipsyncLang:w.lipsyncLang})};if(h.current&&h.current.isReady&&v)R();else if(v){const w=setInterval(()=>{h.current&&h.current.isReady&&(clearInterval(w),R())},100);setTimeout(()=>{clearInterval(w)},5e3)}}else d.current.onCustomAction({type:"allQuestionsComplete",moduleIndex:r.current.currentModuleIndex,lessonIndex:r.current.currentLessonIndex,totalQuestions:r.current.totalQuestions,score:r.current.score})},[e.nextQuestion,I,D]),N=A.useCallback(()=>{const b=T.current||{modules:[]},v=b.modules[r.current.currentModuleIndex];if(r.current.currentLessonIndex<(v?.lessons?.length||0)-1){r.current.currentLessonIndex+=1,r.current.currentQuestionIndex=0,r.current.lessonCompleted=!1,r.current.isQuestionMode=!1,r.current.isTeaching=!1,r.current.score=0,r.current.totalQuestions=0;const w=b.modules[r.current.currentModuleIndex],z=r.current.currentLessonIndex<(w?.lessons?.length||0)-1,H=r.current.currentModuleIndex<(b.modules?.length||0)-1,V=z||H;d.current.onCustomAction({type:"lessonStart",moduleIndex:r.current.currentModuleIndex,lessonIndex:r.current.currentLessonIndex,hasNextLesson:V}),d.current.onLessonStart({moduleIndex:r.current.currentModuleIndex,lessonIndex:r.current.currentLessonIndex,lesson:I()}),h.current&&(h.current.setMood("happy"),h.current.setBodyMovement("idle"))}else if(r.current.currentModuleIndex<(b.modules?.length||0)-1){r.current.currentModuleIndex+=1,r.current.currentLessonIndex=0,r.current.currentQuestionIndex=0,r.current.lessonCompleted=!1,r.current.isQuestionMode=!1,r.current.isTeaching=!1,r.current.score=0,r.current.totalQuestions=0;const z=b.modules[r.current.currentModuleIndex],H=r.current.currentLessonIndex<(z?.lessons?.length||0)-1,V=r.current.currentModuleIndex<(b.modules?.length||0)-1,K=H||V;d.current.onCustomAction({type:"lessonStart",moduleIndex:r.current.currentModuleIndex,lessonIndex:r.current.currentLessonIndex,hasNextLesson:K}),d.current.onLessonStart({moduleIndex:r.current.currentModuleIndex,lessonIndex:r.current.currentLessonIndex,lesson:I()}),h.current&&(h.current.setMood("happy"),h.current.setBodyMovement("idle"))}else L.current&&L.current()},[]),W=A.useCallback(()=>{const b=I();let v=null;if(b?.avatar_script&&b?.body){const R=b.avatar_script.trim(),w=b.body.trim(),z=R.match(/[.!?]$/)?" ":". ";v=`${R}${z}${w}`}else v=b?.avatar_script||b?.body||null;if(h.current&&h.current.isReady&&v){r.current.isTeaching=!0,r.current.isQuestionMode=!1,h.current.setMood("happy");let R=!1;if(e.teaching)try{h.current.playAnimation(e.teaching,!0),R=!0}catch(z){console.warn("Failed to play teaching animation:",z)}R||h.current.setBodyMovement("gesturing");const w=M.current||{lipsyncLang:"en"};d.current.onLessonStart({moduleIndex:r.current.currentModuleIndex,lessonIndex:r.current.currentLessonIndex,lesson:b}),d.current.onCustomAction({type:"teachingStart",moduleIndex:r.current.currentModuleIndex,lessonIndex:r.current.currentLessonIndex,lesson:b}),h.current.speakText(v,{lipsyncLang:w.lipsyncLang,onSpeechEnd:()=>{r.current.isTeaching=!1,d.current.onCustomAction({type:"teachingComplete",moduleIndex:r.current.currentModuleIndex,lessonIndex:r.current.currentLessonIndex,lesson:b,hasQuestions:b.questions&&b.questions.length>0})}})}},[e.teaching,I]),q=A.useCallback(b=>{const v=D(),R=O(b,v);if(R&&(r.current.score+=1),d.current.onQuestionAnswer({moduleIndex:r.current.currentModuleIndex,lessonIndex:r.current.currentLessonIndex,questionIndex:r.current.currentQuestionIndex,answer:b,isCorrect:R,question:v}),h.current)if(R){if(h.current.setMood("happy"),e.correct)try{h.current.playReaction("happy")}catch{h.current.setBodyMovement("happy")}h.current.setBodyMovement("gesturing");const w=v.type==="code_test"?`Great job! Your code passed all the tests! ${v.explanation||""}`:`Excellent! That's correct! ${v.explanation||""}`,z=M.current||{lipsyncLang:"en"};h.current.speakText(w,{lipsyncLang:z.lipsyncLang,onSpeechEnd:()=>{d.current.onCustomAction({type:"answerFeedbackComplete",moduleIndex:r.current.currentModuleIndex,lessonIndex:r.current.currentLessonIndex,questionIndex:r.current.currentQuestionIndex,isCorrect:!0,hasNextQuestion:r.current.currentQuestionIndex<(I()?.questions?.length||0)-1})}})}else{if(h.current.setMood("sad"),e.incorrect)try{h.current.playAnimation(e.incorrect,!0)}catch{h.current.setBodyMovement("idle")}h.current.setBodyMovement("gesturing");const w=v.type==="code_test"?`Your code didn't pass all the tests. ${v.explanation||"Try again!"}`:`Not quite right, but don't worry! ${v.explanation||""} Let's move on to the next question.`,z=M.current||{lipsyncLang:"en"};h.current.speakText(w,{lipsyncLang:z.lipsyncLang,onSpeechEnd:()=>{d.current.onCustomAction({type:"answerFeedbackComplete",moduleIndex:r.current.currentModuleIndex,lessonIndex:r.current.currentLessonIndex,questionIndex:r.current.currentQuestionIndex,isCorrect:!1,hasNextQuestion:r.current.currentQuestionIndex<(I()?.questions?.length||0)-1})}})}else d.current.onCustomAction({type:"answerFeedbackComplete",moduleIndex:r.current.currentModuleIndex,lessonIndex:r.current.currentLessonIndex,questionIndex:r.current.currentQuestionIndex,isCorrect:R,hasNextQuestion:r.current.currentQuestionIndex<(I()?.questions?.length||0)-1,avatarNotReady:!0})},[e.correct,e.incorrect,D,I,O]),_=A.useCallback(b=>{const v=D();if(!b||typeof b!="object"){console.error("Invalid code test result format. Expected object with {passed: boolean, ...}");return}if(v?.type!=="code_test"){console.warn("Current question is not a code test. Use handleAnswerSelect for other question types.");return}const R={passed:b.passed===!0,results:b.results||[],output:b.output||"",error:b.error||null,executionTime:b.executionTime||null,testCount:b.testCount||0,passedCount:b.passedCount||0,failedCount:b.failedCount||0};d.current.onCustomAction({type:"codeTestSubmitted",moduleIndex:r.current.currentModuleIndex,lessonIndex:r.current.currentLessonIndex,questionIndex:r.current.currentQuestionIndex,testResult:R,question:v}),p.current&&p.current(R)},[D,O]),oe=A.useCallback(()=>{if(r.current.currentQuestionIndex>0){r.current.currentQuestionIndex-=1;const b=D();b&&d.current.onCustomAction({type:"questionStart",moduleIndex:r.current.currentModuleIndex,lessonIndex:r.current.currentLessonIndex,questionIndex:r.current.currentQuestionIndex,totalQuestions:r.current.totalQuestions,question:b});const v=()=>{if(!h.current||!b)return;h.current.setMood("happy"),h.current.setBodyMovement("idle");const R=M.current||{lipsyncLang:"en"};b.type==="code_test"?h.current.speakText(`Let's go back to this coding challenge: ${b.question}`,{lipsyncLang:R.lipsyncLang}):h.current.speakText(`Going back to: ${b.question}`,{lipsyncLang:R.lipsyncLang})};if(h.current&&h.current.isReady&&b)v();else if(b){const R=setInterval(()=>{h.current&&h.current.isReady&&(clearInterval(R),v())},100);setTimeout(()=>{clearInterval(R)},5e3)}}},[D]),ce=A.useCallback(()=>{const b=T.current||{modules:[]};if(b.modules[r.current.currentModuleIndex],r.current.currentLessonIndex>0)r.current.currentLessonIndex-=1,r.current.currentQuestionIndex=0,r.current.lessonCompleted=!1,r.current.isQuestionMode=!1,r.current.isTeaching=!1,r.current.score=0,r.current.totalQuestions=0,d.current.onCustomAction({type:"lessonStart",moduleIndex:r.current.currentModuleIndex,lessonIndex:r.current.currentLessonIndex}),d.current.onLessonStart({moduleIndex:r.current.currentModuleIndex,lessonIndex:r.current.currentLessonIndex,lesson:I()}),h.current&&(h.current.setMood("happy"),h.current.setBodyMovement("idle"));else if(r.current.currentModuleIndex>0){const w=b.modules[r.current.currentModuleIndex-1];r.current.currentModuleIndex-=1,r.current.currentLessonIndex=(w?.lessons?.length||1)-1,r.current.currentQuestionIndex=0,r.current.lessonCompleted=!1,r.current.isQuestionMode=!1,r.current.isTeaching=!1,r.current.score=0,r.current.totalQuestions=0,d.current.onCustomAction({type:"lessonStart",moduleIndex:r.current.currentModuleIndex,lessonIndex:r.current.currentLessonIndex}),d.current.onLessonStart({moduleIndex:r.current.currentModuleIndex,lessonIndex:r.current.currentLessonIndex,lesson:I()}),h.current&&(h.current.setMood("happy"),h.current.setBodyMovement("idle"))}},[I]),re=A.useCallback(()=>{r.current.currentModuleIndex=0,r.current.currentLessonIndex=0,r.current.currentQuestionIndex=0,r.current.isTeaching=!1,r.current.isQuestionMode=!1,r.current.lessonCompleted=!1,r.current.curriculumCompleted=!1,r.current.score=0,r.current.totalQuestions=0},[]),me=A.useCallback(b=>{console.log("Avatar is ready!",b);const v=I(),R=v?.avatar_script||v?.body;u&&R&&setTimeout(()=>{c.current&&c.current()},10)},[u,I]);A.useLayoutEffect(()=>{c.current=W,g.current=N,y.current=X,x.current=B,L.current=ne,P.current=S,p.current=q}),A.useImperativeHandle(a,()=>({startTeaching:W,startQuestions:S,handleAnswerSelect:q,handleCodeTestResult:_,nextQuestion:B,previousQuestion:oe,nextLesson:N,previousLesson:ce,completeLesson:X,completeCurriculum:ne,resetCurriculum:re,getState:()=>({...r.current}),getCurrentQuestion:()=>D(),getCurrentLesson:()=>I(),getAvatarRef:()=>h.current,speakText:async(b,v={})=>{await h.current?.resumeAudioContext?.();const R=M.current||{lipsyncLang:"en"};h.current?.speakText(b,{...v,lipsyncLang:v.lipsyncLang||R.lipsyncLang})},resumeAudioContext:async()=>{if(h.current?.resumeAudioContext)return await h.current.resumeAudioContext();const b=h.current?.talkingHead;if(b?.audioCtx){const v=b.audioCtx;if(v.state==="suspended"||v.state==="interrupted")try{await v.resume(),console.log("Audio context resumed via talkingHead")}catch(R){console.warn("Failed to resume audio context:",R)}}else console.warn("Audio context not available yet")},stopSpeaking:()=>h.current?.stopSpeaking(),setMood:b=>h.current?.setMood(b),playAnimation:(b,v)=>h.current?.playAnimation(b,v),setBodyMovement:b=>h.current?.setBodyMovement(b),setMovementIntensity:b=>h.current?.setMovementIntensity(b),playRandomDance:()=>h.current?.playRandomDance(),playReaction:b=>h.current?.playReaction(b),playCelebration:()=>h.current?.playCelebration(),setShowFullAvatar:b=>h.current?.setShowFullAvatar(b),setTimingAdjustment:b=>h.current?.setTimingAdjustment(b),lockAvatarPosition:()=>h.current?.lockAvatarPosition(),unlockAvatarPosition:()=>h.current?.unlockAvatarPosition(),triggerCustomAction:(b,v)=>{d.current.onCustomAction({type:b,...v,state:{...r.current}})},handleResize:()=>h.current?.handleResize(),isAvatarReady:()=>h.current?.isReady||!1}),[W,S,q,_,B,N,X,ne,re,D,I]);const j=M.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 ee.jsx("div",{style:{width:"100%",height:"100%"},children:ee.jsx(ye,{ref:h,avatarUrl:j.avatarUrl,avatarBody:j.avatarBody,mood:j.mood,ttsLang:j.ttsLang,ttsService:j.ttsService,ttsVoice:j.ttsVoice,ttsApiKey:j.ttsApiKey,bodyMovement:j.bodyMovement,movementIntensity:j.movementIntensity,showFullAvatar:j.showFullAvatar,cameraView:"upper",animations:j.animations,onReady:me,onLoading:()=>{},onError:b=>{console.error("Avatar error:",b)}})})});Se.displayName="CurriculumLearning";const fe={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"}},tt=E=>fe[E]||null,it=E=>fe.hasOwnProperty(E);exports.CurriculumLearning=Se;exports.TalkingHeadAvatar=ye;exports.TalkingHeadComponent=ke;exports.animations=fe;exports.getActiveTTSConfig=de;exports.getAnimation=tt;exports.getVoiceOptions=et;exports.hasAnimation=it;
|